igraph/0000755000175100001440000000000013567553110011550 5ustar hornikusersigraph/NAMESPACE0000644000175100001440000005172413430773521012777 0ustar hornikusers# Generated by roxygen2: do not edit by hand S3method("$",igraph) S3method("$",igraph.es) S3method("$",igraph.vs) S3method("$<-",igraph) S3method("$<-",igraph.es) S3method("$<-",igraph.vs) S3method("*",igraph) S3method("+",igraph) S3method("-",igraph) S3method("[",communities) S3method("[",igraph) S3method("[",igraph.es) S3method("[",igraph.vs) S3method("[<-",igraph) S3method("[<-",igraph.es) S3method("[<-",igraph.vs) S3method("[[",communities) S3method("[[",igraph) S3method("[[",igraph.es) S3method("[[",igraph.vs) S3method("[[<-",igraph.es) S3method("[[<-",igraph.vs) S3method(as.dendrogram,communities) S3method(as.hclust,communities) S3method(as.igraph,igraphHRG) S3method(as_ids,igraph.es) S3method(as_ids,igraph.vs) S3method(as_phylo,communities) S3method(c,igraph.es) S3method(c,igraph.vs) S3method(cohesion,cohesiveBlocks) S3method(cohesion,igraph) S3method(compare,communities) S3method(compare,default) S3method(compare,membership) S3method(difference,igraph) S3method(difference,igraph.es) S3method(difference,igraph.vs) S3method(graph_id,igraph) S3method(graph_id,igraph.es) S3method(graph_id,igraph.vs) S3method(groups,communities) S3method(groups,default) S3method(intersection,igraph) S3method(intersection,igraph.es) S3method(intersection,igraph.vs) S3method(length,cohesiveBlocks) S3method(length,communities) S3method(median,sir) S3method(modularity,communities) S3method(modularity,igraph) S3method(plot,cohesiveBlocks) S3method(plot,communities) S3method(plot,igraph) S3method(plot,sir) S3method(plot_dendrogram,communities) S3method(plot_dendrogram,igraphHRG) S3method(print,cohesiveBlocks) S3method(print,communities) S3method(print,igraph) S3method(print,igraph.es) S3method(print,igraph.vs) S3method(print,igraphHRG) S3method(print,igraphHRGConsensus) S3method(print,igraph_layout_modifier) S3method(print,igraph_layout_spec) S3method(print,membership) S3method(quantile,sir) S3method(rep,igraph) S3method(rev,igraph.es) S3method(rev,igraph.vs) S3method(rglplot,igraph) S3method(scg,Matrix) S3method(scg,igraph) S3method(scg,matrix) S3method(summary,cohesiveBlocks) S3method(summary,igraph) S3method(time_bins,sir) S3method(union,default) S3method(union,igraph) S3method(union,igraph.es) S3method(union,igraph.vs) S3method(unique,igraph.es) S3method(unique,igraph.vs) export("%--%") export("%->%") export("%<-%") export("%>%") export("%c%") export("%du%") export("%m%") export("%s%") export("%u%") export("E<-") export("V<-") export("edge.attributes<-") export("edge_attr<-") export("graph.attributes<-") export("graph_attr<-") export("vertex.attributes<-") export("vertex_attr<-") export(.igraph.progress) export(.igraph.status) export(E) export(V) export(add.edges) export(add.vertex.shape) export(add.vertices) export(add_edges) export(add_layout_) export(add_shape) export(add_vertices) export(adhesion) export(adjacent.triangles) export(adjacent_vertices) export(aging.ba.game) export(aging.barabasi.game) export(aging.prefatt.game) export(algorithm) export(all_shortest_paths) export(all_simple_paths) export(alpha.centrality) export(alpha_centrality) export(any_multiple) export(are.connected) export(are_adjacent) export(arpack) export(arpack_defaults) export(articulation.points) export(articulation_points) export(as.directed) export(as.igraph) export(as.undirected) export(asPhylo) export(as_adj) export(as_adj_edge_list) export(as_adj_list) export(as_adjacency_matrix) export(as_bipartite) export(as_data_frame) export(as_edgelist) export(as_graphnel) export(as_ids) export(as_incidence_matrix) export(as_long_data_frame) export(as_membership) export(as_phylo) export(as_star) export(as_tree) export(assortativity) export(assortativity.degree) export(assortativity.nominal) export(assortativity_degree) export(assortativity_nominal) export(asym_pref) export(asymmetric.preference.game) export(atlas) export(authority.score) export(authority_score) export(autocurve.edges) export(automorphisms) export(average.path.length) export(ba.game) export(barabasi.game) export(betweenness) export(betweenness.estimate) export(bfs) export(bibcoupling) export(biconnected.components) export(biconnected_components) export(bipartite) export(bipartite.mapping) export(bipartite.projection) export(bipartite.projection.size) export(bipartite.random.game) export(bipartite_graph) export(bipartite_mapping) export(bipartite_projection) export(bipartite_projection_size) export(blockGraphs) export(blocks) export(bonpow) export(callaway.traits.game) export(canonical.permutation) export(canonical_permutation) export(categorical_pal) export(centr_betw) export(centr_betw_tmax) export(centr_clo) export(centr_clo_tmax) export(centr_degree) export(centr_degree_tmax) export(centr_eigen) export(centr_eigen_tmax) export(centralization.betweenness) export(centralization.betweenness.tmax) export(centralization.closeness) export(centralization.closeness.tmax) export(centralization.degree) export(centralization.degree.tmax) export(centralization.evcent) export(centralization.evcent.tmax) export(centralize) export(centralize.scores) export(chordal_ring) export(cit_cit_types) export(cit_types) export(cited.type.game) export(citing.cited.type.game) export(clique.number) export(clique_num) export(cliques) export(closeness) export(closeness.estimate) export(cluster.distribution) export(cluster_edge_betweenness) export(cluster_fast_greedy) export(cluster_infomap) export(cluster_label_prop) export(cluster_leading_eigen) export(cluster_louvain) export(cluster_optimal) export(cluster_spinglass) export(cluster_walktrap) export(clusters) export(cocitation) export(code.length) export(code_len) export(cohesion) export(cohesive.blocks) export(cohesive_blocks) export(communities) export(compare) export(complementer) export(component_distribution) export(component_wise) export(components) export(compose) export(connect) export(connect.neighborhood) export(consensus_tree) export(console) export(constraint) export(contract) export(contract.vertices) export(convex.hull) export(convex_hull) export(coreness) export(count.multiple) export(count_components) export(count_isomorphisms) export(count_max_cliques) export(count_motifs) export(count_multiple) export(count_subgraph_isomorphisms) export(count_triangles) export(create.communities) export(crossing) export(curve_multiple) export(cut_at) export(cutat) export(de_bruijn_graph) export(decompose) export(decompose.graph) export(degree) export(degree.distribution) export(degree.sequence.game) export(degree_distribution) export(degseq) export(delete.edges) export(delete.vertices) export(delete_edge_attr) export(delete_edges) export(delete_graph_attr) export(delete_vertex_attr) export(delete_vertices) export(dendPlot) export(dfs) export(diameter) export(difference) export(dim_select) export(directed_graph) export(disjoint_union) export(distance_table) export(distances) export(diverging_pal) export(diversity) export(dominator.tree) export(dominator_tree) export(dot_product) export(drl_defaults) export(dyad.census) export(dyad_census) export(each_edge) export(eccentricity) export(ecount) export(edge) export(edge.attributes) export(edge.betweenness) export(edge.betweenness.community) export(edge.betweenness.estimate) export(edge.connectivity) export(edge.disjoint.paths) export(edge_attr) export(edge_attr_names) export(edge_betweenness) export(edge_connectivity) export(edge_density) export(edge_disjoint_paths) export(edges) export(ego) export(ego_size) export(eigen_centrality) export(embed_adjacency_matrix) export(embed_laplacian_matrix) export(empty_graph) export(ends) export(erdos.renyi.game) export(establishment.game) export(estimate_betweenness) export(estimate_closeness) export(estimate_edge_betweenness) export(evcent) export(exportPajek) export(export_pajek) export(farthest.nodes) export(farthest_vertices) export(fastgreedy.community) export(fit_hrg) export(fit_power_law) export(forest.fire.game) export(from_adjacency) export(from_data_frame) export(from_edgelist) export(from_incidence_matrix) export(from_literal) export(full_bipartite_graph) export(full_citation_graph) export(full_graph) export(get.adjacency) export(get.adjedgelist) export(get.adjlist) export(get.all.shortest.paths) export(get.data.frame) export(get.diameter) export(get.edge) export(get.edge.attribute) export(get.edge.ids) export(get.edgelist) export(get.edges) export(get.graph.attribute) export(get.incidence) export(get.shortest.paths) export(get.stochastic) export(get.vertex.attribute) export(getIgraphOpt) export(get_diameter) export(girth) export(gnm) export(gnp) export(gorder) export(graph) export(graph.adhesion) export(graph.adjacency) export(graph.adjlist) export(graph.atlas) export(graph.attributes) export(graph.automorphisms) export(graph.bfs) export(graph.bipartite) export(graph.cohesion) export(graph.complementer) export(graph.compose) export(graph.coreness) export(graph.count.isomorphisms.vf2) export(graph.count.subisomorphisms.vf2) export(graph.data.frame) export(graph.de.bruijn) export(graph.density) export(graph.dfs) export(graph.difference) export(graph.disjoint.union) export(graph.diversity) export(graph.edgelist) export(graph.eigen) export(graph.empty) export(graph.extended.chordal.ring) export(graph.famous) export(graph.formula) export(graph.full) export(graph.full.bipartite) export(graph.full.citation) export(graph.get.isomorphisms.vf2) export(graph.get.subisomorphisms.vf2) export(graph.graphdb) export(graph.incidence) export(graph.intersection) export(graph.isoclass) export(graph.isoclass.subgraph) export(graph.isocreate) export(graph.isomorphic) export(graph.isomorphic.34) export(graph.isomorphic.bliss) export(graph.isomorphic.vf2) export(graph.kautz) export(graph.knn) export(graph.laplacian) export(graph.lattice) export(graph.lcf) export(graph.maxflow) export(graph.mincut) export(graph.motifs) export(graph.motifs.est) export(graph.motifs.no) export(graph.neighborhood) export(graph.ring) export(graph.star) export(graph.strength) export(graph.subisomorphic.lad) export(graph.subisomorphic.vf2) export(graph.tree) export(graph.union) export(graph_) export(graph_attr) export(graph_attr_names) export(graph_from_adj_list) export(graph_from_adjacency_matrix) export(graph_from_atlas) export(graph_from_data_frame) export(graph_from_edgelist) export(graph_from_graphdb) export(graph_from_graphnel) export(graph_from_incidence_matrix) export(graph_from_isomorphism_class) export(graph_from_lcf) export(graph_from_literal) export(graph_id) export(graph_version) export(graphlet_basis) export(graphlet_proj) export(graphlets) export(graphlets.candidate.basis) export(graphlets.project) export(graphs_from_cohesive_blocks) export(grg) export(grg.game) export(groups) export(growing) export(growing.random.game) export(gsize) export(has.multiple) export(head_of) export(head_print) export(hierarchical_sbm) export(hierarchy) export(hrg) export(hrg.consensus) export(hrg.create) export(hrg.dendrogram) export(hrg.fit) export(hrg.game) export(hrg.predict) export(hrg_tree) export(hub.score) export(hub_score) export(identical_graphs) export(igraph.arpack.default) export(igraph.console) export(igraph.drl.coarsen) export(igraph.drl.coarsest) export(igraph.drl.default) export(igraph.drl.final) export(igraph.drl.refine) export(igraph.eigen.default) export(igraph.from.graphNEL) export(igraph.options) export(igraph.sample) export(igraph.shape.noclip) export(igraph.shape.noplot) export(igraph.to.graphNEL) export(igraph.version) export(igraph_demo) export(igraph_opt) export(igraph_options) export(igraph_test) export(igraph_version) export(igraphdemo) export(igraphtest) export(in_circle) export(incident) export(incident_edges) export(indent_print) export(independence.number) export(independent.vertex.sets) export(induced.subgraph) export(induced_subgraph) export(infomap.community) export(interconnected.islands.game) export(intersection) export(is.bipartite) export(is.chordal) export(is.connected) export(is.dag) export(is.degree.sequence) export(is.directed) export(is.graphical.degree.sequence) export(is.hierarchical) export(is.igraph) export(is.loop) export(is.matching) export(is.maximal.matching) export(is.minimal.separator) export(is.multiple) export(is.mutual) export(is.named) export(is.separator) export(is.simple) export(is.weighted) export(is_bipartite) export(is_chordal) export(is_connected) export(is_dag) export(is_degseq) export(is_directed) export(is_graphical) export(is_hierarchical) export(is_igraph) export(is_isomorphic_to) export(is_matching) export(is_max_matching) export(is_min_separator) export(is_named) export(is_printer_callback) export(is_separator) export(is_simple) export(is_subgraph_isomorphic_to) export(is_weighted) export(isomorphic) export(isomorphism_class) export(isomorphisms) export(ivs) export(ivs_size) export(k.regular.game) export(kautz_graph) export(keeping_degseq) export(knn) export(label.propagation.community) export(laplacian_matrix) export(largest.cliques) export(largest.independent.vertex.sets) export(largest_cliques) export(largest_ivs) export(last_cit) export(lastcit.game) export(lattice) export(layout.auto) export(layout.bipartite) export(layout.circle) export(layout.davidson.harel) export(layout.drl) export(layout.fruchterman.reingold) export(layout.fruchterman.reingold.grid) export(layout.gem) export(layout.graphopt) export(layout.grid) export(layout.grid.3d) export(layout.kamada.kawai) export(layout.lgl) export(layout.mds) export(layout.merge) export(layout.norm) export(layout.random) export(layout.reingold.tilford) export(layout.sphere) export(layout.spring) export(layout.star) export(layout.sugiyama) export(layout.svd) export(layout_) export(layout_as_bipartite) export(layout_as_star) export(layout_as_tree) export(layout_components) export(layout_in_circle) export(layout_nicely) export(layout_on_grid) export(layout_on_sphere) export(layout_randomly) export(layout_with_dh) export(layout_with_drl) export(layout_with_fr) export(layout_with_gem) export(layout_with_graphopt) export(layout_with_kk) export(layout_with_lgl) export(layout_with_mds) export(layout_with_sugiyama) export(leading.eigenvector.community) export(line.graph) export(line_graph) export(list.edge.attributes) export(list.graph.attributes) export(list.vertex.attributes) export(local_scan) export(make_) export(make_bipartite_graph) export(make_chordal_ring) export(make_clusters) export(make_de_bruijn_graph) export(make_directed_graph) export(make_ego_graph) export(make_empty_graph) export(make_full_bipartite_graph) export(make_full_citation_graph) export(make_full_graph) export(make_graph) export(make_kautz_graph) export(make_lattice) export(make_line_graph) export(make_ring) export(make_star) export(make_tree) export(make_undirected_graph) export(match_vertices) export(max_bipartite_match) export(max_cardinality) export(max_cliques) export(max_cohesion) export(max_flow) export(maxcohesion) export(maximal.cliques) export(maximal.cliques.count) export(maximal.independent.vertex.sets) export(maximal_ivs) export(maximum.bipartite.matching) export(maximum.cardinality.search) export(mean_distance) export(membership) export(merge_coords) export(merges) export(min_cut) export(min_separators) export(min_st_separators) export(minimal.st.separators) export(minimum.size.separators) export(minimum.spanning.tree) export(mod.matrix) export(modularity) export(modularity_matrix) export(motifs) export(mst) export(multilevel.community) export(neighborhood) export(neighborhood.size) export(neighbors) export(nexus.get) export(nexus.info) export(nexus.list) export(nexus.search) export(nexus_get) export(nexus_info) export(nexus_list) export(nexus_search) export(nicely) export(no.clusters) export(norm_coords) export(normalize) export(on_grid) export(on_sphere) export(optimal.community) export(pa) export(pa_age) export(page.rank) export(page.rank.old) export(page_rank) export(page_rank_old) export(parent) export(path) export(path.length.hist) export(permute) export(permute.vertices) export(piecewise.layout) export(plot.igraph) export(plotHierarchy) export(plot_dendrogram) export(plot_hierarchy) export(power.law.fit) export(power_centrality) export(predict_edges) export(pref) export(preference.game) export(print.igraph) export(print_all) export(printer_callback) export(r_pal) export(radius) export(random.graph.game) export(random_walk) export(randomly) export(read.graph) export(read_graph) export(reciprocity) export(remove.edge.attribute) export(remove.graph.attribute) export(remove.vertex.attribute) export(rewire) export(rglplot) export(ring) export(running.mean) export(running_mean) export(sample_) export(sample_asym_pref) export(sample_bipartite) export(sample_cit_cit_types) export(sample_cit_types) export(sample_correlated_gnp) export(sample_correlated_gnp_pair) export(sample_degseq) export(sample_dirichlet) export(sample_dot_product) export(sample_fitness) export(sample_fitness_pl) export(sample_forestfire) export(sample_gnm) export(sample_gnp) export(sample_grg) export(sample_growing) export(sample_hierarchical_sbm) export(sample_hrg) export(sample_islands) export(sample_k_regular) export(sample_last_cit) export(sample_motifs) export(sample_pa) export(sample_pa_age) export(sample_pref) export(sample_sbm) export(sample_seq) export(sample_smallworld) export(sample_sphere_surface) export(sample_sphere_volume) export(sample_traits) export(sample_traits_callaway) export(sbm) export(sbm.game) export(scan_stat) export(scg) export(scgGrouping) export(scgNormEps) export(scgSemiProjectors) export(scg_eps) export(scg_group) export(scg_semi_proj) export(sequential_pal) export(set.edge.attribute) export(set.graph.attribute) export(set.vertex.attribute) export(set_edge_attr) export(set_graph_attr) export(set_vertex_attr) export(shape_noclip) export(shape_noplot) export(shapes) export(shortest.paths) export(shortest_paths) export(show_trace) export(showtrace) export(similarity) export(similarity.dice) export(similarity.invlogweighted) export(similarity.jaccard) export(simplified) export(simplify) export(sir) export(sizes) export(smallworld) export(spectrum) export(spinglass.community) export(split_join_distance) export(srand) export(stCuts) export(stMincuts) export(st_cuts) export(st_min_cuts) export(star) export(static.fitness.game) export(static.power.law.game) export(stochastic_matrix) export(strength) export(subcomponent) export(subgraph) export(subgraph.centrality) export(subgraph.edges) export(subgraph_centrality) export(subgraph_isomorphic) export(subgraph_isomorphisms) export(tail_of) export(time_bins) export(tk_canvas) export(tk_center) export(tk_close) export(tk_coords) export(tk_fit) export(tk_off) export(tk_postscript) export(tk_reshape) export(tk_rotate) export(tk_set_coords) export(tkigraph) export(tkplot) export(tkplot.canvas) export(tkplot.center) export(tkplot.close) export(tkplot.export.postscript) export(tkplot.fit.to.screen) export(tkplot.getcoords) export(tkplot.off) export(tkplot.reshape) export(tkplot.rotate) export(tkplot.setcoords) export(topo_sort) export(topological.sort) export(traits) export(traits_callaway) export(transitivity) export(tree) export(triad.census) export(triad_census) export(triangles) export(undirected_graph) export(unfold.tree) export(unfold_tree) export(union) export(upgrade_graph) export(vcount) export(vertex) export(vertex.attributes) export(vertex.connectivity) export(vertex.disjoint.paths) export(vertex.shapes) export(vertex_attr) export(vertex_attr_names) export(vertex_connectivity) export(vertex_disjoint_paths) export(vertices) export(walktrap.community) export(watts.strogatz.game) export(which_loop) export(which_multiple) export(which_mutual) export(with_dh) export(with_drl) export(with_edge_) export(with_fr) export(with_gem) export(with_graph_) export(with_graphopt) export(with_igraph_opt) export(with_kk) export(with_lgl) export(with_mds) export(with_sugiyama) export(with_vertex_) export(without_attr) export(without_loops) export(without_multiples) export(write.graph) export(write_graph) import(methods) importFrom(grDevices,as.raster) importFrom(grDevices,col2rgb) importFrom(grDevices,dev.new) importFrom(grDevices,palette) importFrom(grDevices,rainbow) importFrom(graphics,barplot) importFrom(graphics,hist) importFrom(graphics,layout) importFrom(graphics,layout.show) importFrom(graphics,legend) importFrom(graphics,lines) importFrom(graphics,par) importFrom(graphics,plot) importFrom(graphics,polygon) importFrom(graphics,rasterImage) importFrom(graphics,segments) importFrom(graphics,symbols) importFrom(graphics,text) importFrom(graphics,xspline) importFrom(graphics,xyinch) importFrom(magrittr,"%>%") importFrom(pkgconfig,get_config) importFrom(pkgconfig,set_config) importFrom(pkgconfig,set_config_in) importFrom(stats,IQR) importFrom(stats,as.dendrogram) importFrom(stats,as.hclust) importFrom(stats,ave) importFrom(stats,coef) importFrom(stats,median) importFrom(stats,na.omit) importFrom(stats,quantile) importFrom(stats,rect.hclust) importFrom(stats,reorder) importFrom(stats,runif) importFrom(stats,sd) importFrom(stats,vcov) importFrom(utils,URLencode) importFrom(utils,browseURL) importFrom(utils,capture.output) importFrom(utils,edit) importFrom(utils,head) importFrom(utils,packageDescription) importFrom(utils,packageName) importFrom(utils,read.table) importFrom(utils,setTxtProgressBar) importFrom(utils,tail) importFrom(utils,txtProgressBar) importFrom(utils,write.table) useDynLib(igraph, .registration = TRUE, .fixes = "C_") igraph/demo/0000755000175100001440000000000013177712334012476 5ustar hornikusersigraph/demo/cohesive.R0000644000175100001440000000166313177712334014434 0ustar hornikusers pause <- function() {} ### The Zachary Karate club network karate <- make_graph("Zachary") summary(karate) pause() ### Create a layout that is used from now on karate$layout <- layout_nicely(karate) plot(karate) pause() ### Run cohesive blocking on it cbKarate <- cohesive_blocks(karate) cbKarate pause() ### Plot the results and all the groups plot(cbKarate, karate) pause() ### This is a bit messy, plot them step-by-step ### See the hierarchy tree first hierarchy(cbKarate) plot_hierarchy(cbKarate) ## Plot the first level, blocks 1 & 2 plot(cbKarate, karate, mark.groups=blocks(cbKarate)[1:2+1], col="cyan") pause() ### The second group is simple, plot its more cohesive subgroup plot(cbKarate, karate, mark.groups=blocks(cbKarate)[c(2,5)+1], col="cyan") pause() ### The first group has more subgroups, plot them sub1 <- blocks(cbKarate)[parent(cbKarate)==1] sub1 plot(cbKarate, karate, mark.groups=sub1) pause() igraph/demo/smallworld.R0000644000175100001440000000721313177712334015004 0ustar hornikusers pause <- function() {} ### Create a star-like graph t1 <- graph_from_literal(A-B:C:D:E) t1 pause() ### Define its plotting properties t1$layout <- layout_in_circle V(t1)$color <- "white" V(t1)[name=="A"]$color <- "orange" V(t1)$size <- 40 V(t1)$label.cex <- 3 V(t1)$label <- V(t1)$name E(t1)$color <- "black" E(t1)$width <- 3 pause() ### Plot 't1' and A's transitivity tr <- transitivity(t1, type="local")[1] plot(t1, main=paste("Transitivity of 'A':", tr)) pause() ### Add an edge and recalculate transitivity t2 <- add_edges(t1, V(t1)[name %in% c("C","D")], color="red", width=3) tr <- transitivity(t2, type="local")[1] plot(t2, main=paste("Transitivity of 'A':", round(tr,4))) pause() ### Add two more edges newe <- match(c("B", "C", "B", "E"), V(t2)$name)-1 t3 <- add_edges(t2, newe, color="red", width=3) tr <- transitivity(t3, type="local")[1] plot(t3, main=paste("Transitivity of 'A':", round(tr,4))) pause() ### A one dimensional, circular lattice ring <- make_ring(50) ring$layout <- layout_in_circle V(ring)$size <- 3 plot(ring, vertex.label=NA, main="Ring graph") pause() ### Watts-Strogatz model ws1 <- sample_smallworld(1, 50, 3, p=0) ws1$layout <- layout_in_circle V(ws1)$size <- 3 E(ws1)$curved <- 1 plot(ws1, vertex.label=NA, main="regular graph") pause() ### Zoom in to this part axis(1) axis(2) abline(h=c(0.8, 1.1)) abline(v=c(-0.2,0.2)) pause() ### Zoom in to this part plot(ws1, vertex.label=NA, xlim=c(-0.2, 0.2), ylim=c(0.8,1.1)) pause() ### Transitivity of the ring graph transitivity(ws1) pause() ### Path lengths, regular graph mean_distance(ws1) pause() ### Function to test regular graph with given size try.ring.pl <- function(n) { g <- sample_smallworld(1, n, 3, p=0) mean_distance(g) } try.ring.pl(10) try.ring.pl(100) pause() ### Test a number of regular graphs ring.size <- seq(100, 1000, by=100) ring.pl <- sapply(ring.size, try.ring.pl) plot(ring.size, ring.pl, type="b") pause() ### Path lengths, random graph rg <- sample_gnm(50, 50 * 3) rg$layout <- layout_in_circle V(rg)$size <- 3 plot(rg, vertex.label=NA, main="Random graph") mean_distance(rg) pause() ### Path length of random graphs try.random.pl <- function(n) { g <- sample_gnm(n, n*3) mean_distance(g) } try.random.pl(100) pause() ### Plot network size vs. average path length random.pl <- sapply(ring.size, try.random.pl) plot(ring.size, random.pl, type="b") pause() ### Plot again, logarithmic 'x' axis plot(ring.size, random.pl, type="b", log="x") pause() ### Transitivity, random graph, by definition ecount(rg) / (vcount(rg)*(vcount(rg)-1)/2) transitivity(rg, type="localaverage") pause() ### Rewiring ws2 <- sample_smallworld(1, 50, 3, p=0.1) ws2$layout <- layout_in_circle V(ws2)$size <- 3 plot(ws2, vertex.label=NA) mean_distance(ws2) pause() ### Path lengths in randomized lattices try.rr.pl <- function(n, p) { g <- sample_smallworld(1, n, 3, p=p) mean_distance(g) } rr.pl.0.1 <- sapply(ring.size, try.rr.pl, p=0.1) plot(ring.size, rr.pl.0.1, type="b") pause() ### Logarithmic 'x' axis plot(ring.size, rr.pl.0.1, type="b", log="x") pause() ### Create the graph in the Watts-Strogatz paper ws.paper <- function(p, n=1000) { g <- sample_smallworld(1, n, 10, p=p) tr <- transitivity(g, type="localaverage") pl <- mean_distance(g) c(tr, pl) } pause() ### Do the simulation for a number of 'p' values rewire.prob <- ((1:10)^4)/(10^4) ws.result <- sapply(rewire.prob, ws.paper) dim(ws.result) pause() ### Plot it plot(rewire.prob, ws.result[1,]/ws.result[1,1], log="x", pch=22, xlab="p", ylab="") points(rewire.prob, ws.result[2,]/ws.result[2,1], pch=20) legend("bottomleft", c(expression(C(p)/C(0)), expression(L(p)/L(0))), pch=c(22, 20)) igraph/demo/centrality.R0000644000175100001440000001070413177712334015001 0ustar hornikusers pause <- function() {} ### Traditional approaches: degree, closeness, betweenness g <- graph_from_literal(Andre----Beverly:Diane:Fernando:Carol, Beverly--Andre:Diane:Garth:Ed, Carol----Andre:Diane:Fernando, Diane----Andre:Carol:Fernando:Garth:Ed:Beverly, Ed-------Beverly:Diane:Garth, Fernando-Carol:Andre:Diane:Garth:Heather, Garth----Ed:Beverly:Diane:Fernando:Heather, Heather--Fernando:Garth:Ike, Ike------Heather:Jane, Jane-----Ike ) pause() ### Hand-drawn coordinates coords <- c(5,5,119,256,119,256,120,340,478, 622,116,330,231,116,5,330,451,231,231,231) coords <- matrix(coords, nc=2) pause() ### Labels the same as names V(g)$label <- V(g)$name g$layout <- coords # $ pause() ### Take a look at it plotG <- function(g) { plot(g, asp=FALSE, vertex.label.color="blue", vertex.label.cex=1.5, vertex.label.font=2, vertex.size=25, vertex.color="white", vertex.frame.color="white", edge.color="black") } plotG(g) pause() ### Add degree centrality to labels V(g)$label <- paste(sep="\n", V(g)$name, degree(g)) pause() ### And plot again plotG(g) pause() ### Betweenness V(g)$label <- paste(sep="\n", V(g)$name, round(betweenness(g), 2)) plotG(g) pause() ### Closeness V(g)$label <- paste(sep="\n", V(g)$name, round(closeness(g), 2)) plotG(g) pause() ### Eigenvector centrality V(g)$label <- paste(sep="\n", V(g)$name, round(eigen_centrality(g)$vector, 2)) plotG(g) pause() ### PageRank V(g)$label <- paste(sep="\n", V(g)$name, round(page_rank(g)$vector, 2)) plotG(g) pause() ### Correlation between centrality measures karate <- make_graph("Zachary") cent <- list(`Degree`=degree(g), `Closeness`=closeness(g), `Betweenness`=betweenness(g), `Eigenvector`=eigen_centrality(g)$vector, `PageRank`=page_rank(g)$vector) pause() ### Pairs plot pairs(cent, lower.panel=function(x,y) { usr <- par("usr") text(mean(usr[1:2]), mean(usr[3:4]), round(cor(x,y), 3), cex=2, col="blue") } ) pause() ## ### A real network, US supreme court citations ## ## You will need internet connection for this to work ## vertices <- read.csv("http://jhfowler.ucsd.edu/data/judicial.csv") ## edges <- read.table("http://jhfowler.ucsd.edu/data/allcites.txt") ## jg <- graph.data.frame(edges, vertices=vertices, dir=TRUE) ## pause() ## ### Basic data ## summary(jg) ## pause() ## ### Is it a simple graph? ## is_simple(jg) ## pause() ## ### Is it connected? ## is_connected(jg) ## pause() ## ### How many components? ## count_components(jg) ## pause() ## ### How big are these? ## table(components(jg)$csize) ## pause() ## ### In-degree distribution ## plot(degree_distribution(jg, mode="in"), log="xy") ## pause() ## ### Out-degree distribution ## plot(degree_distribution(jg, mode="out"), log="xy") ## pause() ## ### Largest in- and out-degree, total degree ## c(max(degree(jg, mode="in")), ## max(degree(jg, mode="out")), ## max(degree(jg, mode="all"))) ## pause() ## ### Density ## density(jg) ## pause() ## ### Transitivity ## transitivity(jg) ## pause() ## ### Transitivity of a random graph of the same size ## g <- sample_gnm(vcount(jg), ecount(jg)) ## transitivity(g) ## pause() ## ### Transitivity of a random graph with the same degree distribution ## g <- sample_degseq(degree(jg, mode="out"), degree(jg, mode="in"), ## method="simple") ## transitivity(g) ## pause() ## ### Authority and Hub scores ## AS <- authority_score(jg)$vector ## HS <- hub_score(jg)$vector ## pause() ## ### Time evolution of authority scores ## AS <- authority_score(jg)$vector ## center <- which.max(AS) ## startyear <- V(jg)[center]$year ## pause() ## ### Function to go back in time ## auth.year <- function(y) { ## print(y) ## keep <- which(V(jg)$year <= y) ## g2 <- subgraph(jg, keep) ## as <- abs(authority_score(g2, scale=FALSE)$vector) ## w <- match(V(jg)[center]$usid, V(g2)$usid) ## as[w] ## } ## pause() ## ### Go back in time for the top authority, do a plot ## AS2 <- sapply(startyear:2005, auth.year) ## plot(startyear:2005, AS2, type="b", xlab="year", ylab="authority score") ## pause() ## ### Check another case ## center <- "22US1" ## startyear <- V(jg)[center]$year ## pause() ## ### Calculate past authority scores & plot them ## AS3 <- sapply(startyear:2005, auth.year) ## plot(startyear:2005, AS3, type="b", xlab="year", ylab="authority score") igraph/demo/hrg.R0000644000175100001440000000351413177712334013404 0ustar hornikusers pause <- function() {} ### Download the Zachary Karate Club network from Nexus karate <- nexus.get("karate") karate pause() ### Optimalize modularity optcom <- cluster_optimal(karate) V(karate)$comm <- membership(optcom) plot(optcom, karate) pause() ### Fit a HRG model to the network hrg <- fit_hrg(karate) hrg pause() ### The fitted model, more details print(hrg, level=5) pause() ### Plot the full hierarchy, as an igraph graph ihrg <- as.igraph(hrg) ihrg$layout <- layout.reingold.tilford plot(ihrg, vertex.size=10, edge.arrow.size=0.2) pause() ### Customize the plot a bit, show probabilities and communities vn <- sub("Actor ", "", V(ihrg)$name) colbar <- rainbow(length(optcom)) vc <- ifelse(is.na(V(ihrg)$prob), colbar[V(karate)$comm], "darkblue") V(ihrg)$label <- ifelse(is.na(V(ihrg)$prob), vn, round(V(ihrg)$prob, 2)) par(mar=c(0,0,3,0)) plot(ihrg, vertex.size=10, edge.arrow.size=0.2, vertex.shape="none", vertex.label.color=vc, main="Hierarchical network model of the Karate Club") pause() ### Plot it as a dendrogram, looks better if the 'ape' package is installed plot_dendrogram(hrg) pause() ### Make a very hierarchical graph g1 <- make_full_graph(5) g2 <- make_ring(5) g <- g1 + g2 g <- g + edge(1, vcount(g1)+1) plot(g) pause() ### Fit HRG ghrg <- fit_hrg(g) plot_dendrogram(ghrg) pause() ### Create a consensus dendrogram from multiple samples, takes longer... hcons <- consensus_tree(g) hcons$consensus pause() ### Predict missing edges pred <- predict_edges(g) pred pause() ### Add some the top 5 predicted edges to the graph, colored red E(g)$color <- "grey" lay <- layout_nicely(g) g2 <- add_edges(g, t(pred$edges[1:5,]), color="red") plot(g2, layout=lay) pause() ### Add four more predicted edges, colored orange g3 <- add_edges(g2, t(pred$edges[6:9,]), color="orange") plot(g3, layout=lay) igraph/demo/crashR.R0000644000175100001440000001113113177712334014040 0ustar hornikusers pause <- function() {} ### R objects, (real) numbers a <- 3 a b <- 4 b a+b pause() ### Case sensitive A <- 16 a A pause() ### Vector objects a <- c(1,2,3,4,5,6,7,8,9,10) a b <- 1:100 b a[1] b[1:5] a[1] <- 10 a a[1:4] <- 2 a pause() ### Vector arithmetic a * 2 + 1 pause() ### Functions ls() length(a) mean(a) sd(a) sd c pause() ### Getting help # ?sd # ??"standard deviation" # RSiteSearch("network betweenness") pause() ### Classes class(2) class(1:10) class(sd) pause() ### Character vectors char.vec <- c("this", "is", "a", "vector", "of", "characters") char_vec <- char.vec char.vec[1] pause() ### Index vectors age <- c(45, 36, 65, 21, 52, 19) age[1] age[1:5] age[c(2,5,6)] b[ seq(1,100,by=2) ] pause() ### Named vectors names(age) <- c("Alice", "Bob", "Cecil", "David", "Eve", "Fiona") age age["Bob"] age[c("Eve", "David", "David")] pause() ### Indexing with logical vectors age[c(FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)] names(age)[ age>40 ] age > 40 pause() ### Matrices M <- matrix(1:20, 10, 2) M M2 <- matrix(1:20, 10, 2, byrow=TRUE) ## Named argument! M2 M[1,1] M[1,] M[,1] M[1:5,2] pause() ### Generic functions sd(a) sd(M) class(a) class(M) pause() ### Lists l <- list(1:10, "Hello!", diag(5)) l l[[1]] l[2:3] l l2 <- list(A=1:10, H="Hello!", M=diag(5)) l2 l2$A l2$M pause() ### Factors countries <- c("SUI", "USA", "GBR", "GER", "SUI", "SUI", "GBR", "GER", "FRA", "GER") countries fcountries <- factor(countries) fcountries levels(fcountries) pause() ### Data frames survey <- data.frame(row.names=c("Alice", "Bob", "Cecil", "David", "Eve"), Sex=c("F","M","F","F","F"), Age=c(45,36,65,21,52), Country=c("SUI", "USA", "SUI", "GBR", "USA"), Married=c(TRUE, FALSE, FALSE, TRUE, TRUE), Salary=c(70, 65, 200, 45, 100)) survey survey$Sex plot(survey$Age, survey$Salary) AS.model <- lm(Salary ~ Age, data=survey) AS.model summary(AS.model) abline(AS.model) tapply(survey$Salary, survey$Country, mean) pause() ### Packages # install.packages("igraph") # library(help="igraph") library(igraph) sessionInfo() pause() ### Graphs ## Create a small graph, A->B, A->C, B->C, C->E, D ## A=1, B=2, C=3, D=4, E=5 g <- graph( c(1,2, 1,3, 2,3, 3,5), n=5 ) pause() ### Print a graph to the screen g pause() ### Create an undirected graph as well ## A--B, A--C, B--C, C--E, D g2 <- graph( c(1,2, 1,3, 2,3, 3,5), n=5, dir=FALSE ) g2 pause() ### Is this object an igraph graph? is_igraph(g) is_igraph(1:10) pause() ### Summary, number of vertices, edges summary(g) vcount(g) ecount(g) pause() ### Is the graph directed? is_directed(g) is_directed(g2) pause() ### Convert from directed to undirected as.undirected(g) pause() ### And back as.directed(as.undirected(g)) pause() ### Multiple edges g <- graph( c(1,2,1,2, 1,3, 2,3, 4,5), n=5 ) g is_simple(g) which_multiple(g) pause() ### Remove multiple edges g <- simplify(g) is_simple(g) pause() ### Loop edges g <- graph( c(1,1,1,2, 1,3, 2,3, 4,5), n=5 ) g is_simple(g) which_loop(g) pause() ### Remove loop edges g <- simplify(g) is_simple(g) pause() ### Naming vertices g <- make_ring(10) V(g)$name <- letters[1:10] V(g)$name g print(g, v=T) pause() ### Create undirected example graph g2 <- graph_from_literal(Alice-Bob:Cecil:Daniel, Cecil:Daniel-Eugene:Gordon ) print(g2, v=T) pause() ### Remove Alice g3 <- delete_vertices(g2, match("Alice", V(g2)$name)) pause() ### Add three new vertices g4 <- add_vertices(g3, 3) print(g4, v=T) igraph_options(print.vertex.attributes=TRUE, plot.layout=layout_with_fr) g4 plot(g4) pause() ### Add three new vertices, with names this time g4 <- add_vertices(g3, 3, attr=list(name=c("Helen", "Ike", "Jane"))) g4 pause() ### Add some edges as well g4 <- add_edges(g4, match(c("Helen", "Jane", "Ike", "Jane"), V(g4)$name )) g4 pause() ### Edge sequences, first create a directed example graph g2 <- graph_from_literal(Alice -+ Bob:Cecil:Daniel, Cecil:Daniel +-+ Eugene:Gordon ) print(g2, v=T) plot(g2, layout=layout_with_kk, vertex.label=V(g2)$name) pause() ### Sequence of all edges E(g2) pause() ### Edge from a vertex to another E(g2, P=c(1,2)) pause() ### Delete this edge g3 <- delete_edges(g2, E(g2, P=c(1,2))) g3 pause() ### Get the id of the edge as.vector(E(g2, P=c(1,2))) pause() ### All adjacent edges of a vertex E(g2)[ adj(3) ] pause() ### Or multiple vertices E(g2)[ adj(c(3,1)) ] pause() ### Outgoing edges E(g2)[ from(3) ] pause() ### Incoming edges E(g2)[ to(3) ] pause() ### Edges along a path E(g2, path=c(1,4,5)) igraph/demo/00Index0000644000175100001440000000037513177712334013635 0ustar hornikuserscrashR A crash-course into R centrality Classic and other vertex centrality indices community Community structure detection smallworld Small-world networks cohesive Cohesive blocking, the Moody & White method hrg Hierarchical random graphs igraph/demo/community.R0000644000175100001440000001223313177712334014646 0ustar hornikusers pause <- function() {} ### A modular graph has dense subgraphs mod <- make_full_graph(10) %du% make_full_graph(10) %du% make_full_graph(10) perfect <- c(rep(1,10), rep(2,10), rep(3,10)) perfect pause() ### Plot it with community (=component) colors plot(mod, vertex.color=perfect, layout=layout_with_fr) pause() ### Modularity of the perfect division modularity(mod, perfect) pause() ### Modularity of the trivial partition, quite bad modularity(mod, rep(1, 30)) pause() ### Modularity of a good partition with two communities modularity(mod, c(rep(1, 10), rep(2,20))) pause() ### A real little network, Zachary's karate club data karate <- make_graph("Zachary") karate$layout <- layout_with_kk(karate, niter=1000) pause() ### Greedy algorithm fc <- cluster_fast_greedy(karate) memb <- membership(fc) plot(karate, vertex.color=memb) pause() ### Greedy algorithm, easier plotting plot(fc, karate) pause() ### Spinglass algorithm, create a hierarchical network pref.mat <- matrix(0, 16, 16) pref.mat[1:4,1:4] <- pref.mat[5:8,5:8] <- pref.mat[9:12,9:12] <- pref.mat[13:16,13:16] <- 7.5/127 pref.mat[ pref.mat==0 ] <- 5/(3*128) diag(pref.mat) <- diag(pref.mat) + 10/31 pause() ### Create the network with the given vertex preferences G <- sample_pref(128*4, types=16, pref.matrix=pref.mat) pause() ### Run spinglass community detection with two gamma parameters sc1 <- cluster_spinglass(G, spins=4, gamma=1.0) sc2.2 <- cluster_spinglass(G, spins=16, gamma=2.2) pause() ### Plot the adjacency matrix, use the Matrix package if available if (require(Matrix)) { myimage <- function(...) image(Matrix(...)) } else { myimage <- image } A <- as_adj(G) myimage(A) pause() ### Ordering according to (big) communities ord1 <- order(membership(sc1)) myimage(A[ord1,ord1]) pause() ### Ordering according to (small) communities ord2.2 <- order(membership(sc2.2)) myimage(A[ord2.2,ord2.2]) pause() ### Consensus ordering ord <- order(membership(sc1), membership(sc2.2)) myimage(A[ord,ord]) pause() ### Comparision of algorithms communities <- list() pause() ### cluster_edge_betweenness ebc <- cluster_edge_betweenness(karate) communities$`Edge betweenness` <- ebc pause() ### cluster_fast_greedy fc <- cluster_fast_greedy(karate) communities$`Fast greedy` <- fc pause() ### cluster_leading_eigen lec <- cluster_leading_eigen(karate) communities$`Leading eigenvector` <- lec pause() ### cluster_spinglass sc <- cluster_spinglass(karate, spins=10) communities$`Spinglass` <- sc pause() ### cluster_walktrap wt <- cluster_walktrap(karate) communities$`Walktrap` <- wt pause() ### cluster_label_prop labprop <- cluster_label_prop(karate) communities$`Label propagation` <- labprop pause() ### Plot everything layout(rbind(1:3, 4:6)) coords <- layout_with_kk(karate) lapply(seq_along(communities), function(x) { m <- modularity(communities[[x]]) par(mar=c(1,1,3,1)) plot(communities[[x]], karate, layout=coords, main=paste(names(communities)[x], "\n", "Modularity:", round(m, 3))) }) pause() ### Function to calculate clique communities clique.community <- function(graph, k) { clq <- cliques(graph, min=k, max=k) edges <- c() for (i in seq(along=clq)) { for (j in seq(along=clq)) { if ( length(unique(c(clq[[i]], clq[[j]]))) == k+1 ) { edges <- c(edges, c(i,j)) } } } clq.graph <- simplify(graph(edges)) V(clq.graph)$name <- seq(length=vcount(clq.graph)) comps <- decompose(clq.graph) lapply(comps, function(x) { unique(unlist(clq[ V(x)$name ])) }) } pause() ### Apply it to a graph, this is the example graph from ## the original publication g <- graph_from_literal(A-B:F:C:E:D, B-A:D:C:E:F:G, C-A:B:F:E:D, D-A:B:C:F:E, E-D:A:C:B:F:V:W:U, F-H:B:A:C:D:E, G-B:J:K:L:H, H-F:G:I:J:K:L, I-J:L:H, J-I:G:H:L, K-G:H:L:M, L-H:G:I:J:K:M, M-K:L:Q:R:S:P:O:N, N-M:Q:R:P:S:O, O-N:M:P, P-Q:M:N:O:S, Q-M:N:P:V:U:W:R, R-M:N:V:W:Q, S-N:P:M:U:W:T, T-S:V:W:U, U-E:V:Q:S:W:T, V-E:U:W:T:R:Q, W-U:E:V:Q:R:S:T) pause() ### Hand-made layout to make it look like the original in the paper lay <- c(387.0763, 306.6947, 354.0305, 421.0153, 483.5344, 512.1145, 148.6107, 392.4351, 524.6183, 541.5878, 240.6031, 20, 65.54962, 228.0992, 61.9771, 152.1832, 334.3817, 371.8931, 421.9084, 265.6107, 106.6336, 57.51145, 605, 20, 124.8780, 273.6585, 160.2439, 241.9512, 132.1951, 123.6585, 343.1707, 465.1220, 317.561, 216.3415, 226.0976, 343.1707, 306.5854, 123.6585, 360.2439, 444.3902, 532.1951, 720, 571.2195, 639.5122, 505.3659, 644.3902) lay <- matrix(lay, nc=2) lay[,2] <- max(lay[,2])-lay[,2] pause() ### Take a look at it layout(1) plot(g, layout=lay, vertex.label=V(g)$name) pause() ### Calculate communities res <- clique.community(g, k=4) pause() ### Paint them to different colors colbar <- rainbow( length(res)+1 ) for (i in seq(along=res)) { V(g)[ res[[i]] ]$color <- colbar[i+1] } pause() ### Paint the vertices in multiple communities to red V(g)[ unlist(res)[ duplicated(unlist(res)) ] ]$color <- "red" pause() ### Plot with the new colors plot(g, layout=lay, vertex.label=V(g)$name) igraph/man/0000755000175100001440000000000013430770476012330 5ustar hornikusersigraph/man/cluster_walktrap.Rd0000644000175100001440000000461313430770475016210 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_walktrap} \alias{cluster_walktrap} \alias{walktrap.community} \title{Community strucure via short random walks} \usage{ cluster_walktrap(graph, weights = E(graph)$weight, steps = 4, merges = TRUE, modularity = TRUE, membership = TRUE) } \arguments{ \item{graph}{The input graph, edge directions are ignored in directed graphs.} \item{weights}{The edge weights. Larger edge weights increase the probability that an edge is selected by the random walker. In other words, larger edge weights correspond to stronger connections.} \item{steps}{The length of the random walks to perform.} \item{merges}{Logical scalar, whether to include the merge matrix in the result.} \item{modularity}{Logical scalar, whether to include the vector of the modularity scores in the result. If the \code{membership} argument is true, then it will be always calculated.} \item{membership}{Logical scalar, whether to calculate the membership vector for the split corresponding to the highest modularity value.} } \value{ \code{cluster_walktrap} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ This function tries to find densely connected subgraphs, also called communities in a graph via random walks. The idea is that short random walks tend to stay in the same community. } \details{ This function is the implementation of the Walktrap community finding algorithm, see Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, http://arxiv.org/abs/physics/0512106 } \examples{ g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) cluster_walktrap(g) } \references{ Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, http://arxiv.org/abs/physics/0512106 } \seealso{ See \code{\link{communities}} on getting the actual membership vector, merge matrix, modularity score, etc. \code{\link{modularity}} and \code{\link{cluster_fast_greedy}}, \code{\link{cluster_spinglass}}, \code{\link{cluster_leading_eigen}}, \code{\link{cluster_edge_betweenness}} for other community detection methods. } \author{ Pascal Pons (\url{http://psl.pons.free.fr/}) and Gabor Csardi \email{csardi.gabor@gmail.com} for the R and igraph interface } \keyword{graphs} igraph/man/edge_connectivity.Rd0000644000175100001440000000602013430770475016316 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{edge_connectivity} \alias{edge_connectivity} \alias{edge.connectivity} \alias{edge_disjoint_paths} \alias{graph.adhesion} \alias{adhesion} \alias{edge.disjoint.paths} \title{Edge connectivity.} \usage{ edge_connectivity(graph, source = NULL, target = NULL, checks = TRUE) } \arguments{ \item{graph}{The input graph.} \item{source}{The id of the source vertex, for \code{edge_connectivity} it can be \code{NULL}, see details below.} \item{target}{The id of the target vertex, for \code{edge_connectivity} it can be \code{NULL}, see details below.} \item{checks}{Logical constant. Whether to check that the graph is connected and also the degree of the vertices. If the graph is not (strongly) connected then the connectivity is obviously zero. Otherwise if the minimum degree is one then the edge connectivity is also one. It is a good idea to perform these checks, as they can be done quickly compared to the connectivity calculation itself. They were suggested by Peter McMahan, thanks Peter.} } \value{ A scalar real value. } \description{ The edge connectivity of a graph or two vertices, this is recently also called group adhesion. } \details{ The edge connectivity of a pair of vertices (\code{source} and \code{target}) is the minimum number of edges needed to remove to eliminate all (directed) paths from \code{source} to \code{target}. \code{edge_connectivity} calculates this quantity if both the \code{source} and \code{target} arguments are given (and not \code{NULL}). The edge connectivity of a graph is the minimum of the edge connectivity of every (ordered) pair of vertices in the graph. \code{edge_connectivity} calculates this quantity if neither the \code{source} nor the \code{target} arguments are given (ie. they are both \code{NULL}). A set of edge disjoint paths between two vertices is a set of paths between them containing no common edges. The maximum number of edge disjoint paths between two vertices is the same as their edge connectivity. The adhesion of a graph is the minimum number of edges needed to remove to obtain a graph which is not strongly connected. This is the same as the edge connectivity of the graph. The three functions documented on this page calculate similar properties, more precisely the most general is \code{edge_connectivity}, the others are included only for having more descriptive function names. } \examples{ g <- barabasi.game(100, m=1) g2 <- barabasi.game(100, m=5) edge_connectivity(g, 100, 1) edge_connectivity(g2, 100, 1) edge_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5/50) g <- as.directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) adhesion(g) } \references{ Douglas R. White and Frank Harary: The cohesiveness of blocks in social networks: node connectivity and conditional density, TODO: citation } \seealso{ \code{\link{max_flow}}, \code{\link{vertex_connectivity}}, \code{\link{vertex_disjoint_paths}}, \code{\link{cohesion}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/igraph-es-indexing.Rd0000644000175100001440000001144713430770475016307 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-es-indexing} \alias{igraph-es-indexing} \alias{[.igraph.es} \alias{\%--\%} \alias{\%<-\%} \alias{\%->\%} \title{Indexing edge sequences} \usage{ \method{[}{igraph.es}(x, ...) } \arguments{ \item{x}{An edge sequence} \item{...}{Indices, see details below.} } \value{ Another edge sequence, referring to the same graph. } \description{ Edge sequences can be indexed very much like a plain numeric R vector, with some extras. } \section{Multiple indices}{ When using multiple indices within the bracket, all of them are evaluated independently, and then the results are concatenated using the \code{c()} function. E.g. \code{E(g)[1, 2, .inc(1)]} is equivalent to \code{c(E(g)[1], E(g)[2], E(g)[.inc(1)])}. } \section{Index types}{ Edge sequences can be indexed with positive numeric vectors, negative numeric vectors, logical vectors, character vectors: \itemize{ \item When indexed with positive numeric vectors, the edges at the given positions in the sequence are selected. This is the same as indexing a regular R atomic vector with positive numeric vectors. \item When indexed with negative numeric vectors, the edges at the given positions in the sequence are omitted. Again, this is the same as indexing a regular R atomic vector. \item When indexed with a logical vector, the lengths of the edge sequence and the index must match, and the edges for which the index is \code{TRUE} are selected. \item Named graphs can be indexed with character vectors, to select edges with the given names. Note that a graph may have edge names and vertex names, and both can be used to select edges. Edge names are simply used as names of the numeric edge id vector. Vertex names effectively only work in graphs without multiple edges, and must be separated with a \code{|} bar character to select an edges that incident to the two given vertices. See examples below. } } \section{Edge attributes}{ When indexing edge sequences, edge attributes can be refered to simply by using their names. E.g. if a graph has a \code{weight} edge attribute, then \code{E(G)[weight > 1]} selects all edges with a larger than one weight. See more examples below. } \section{Special functions}{ There are some special igraph functions that can be used only in expressions indexing edge sequences: \describe{ \item{\code{.inc}}{takes a vertex sequence, and selects all edges that have at least one incident vertex in the vertex sequence.} \item{\code{.from}}{similar to \code{.inc()}, but only the tails of the edges are considered.} \item{\code{.to}}{is similar to \code{.inc()}, but only the heads of the edges are considered.} \item{\code{\%--\%}}{a special operator that can be used to select all edges between two sets of vertices. It ignores the edge directions in directed graphs.} \item{\code{\%->\%}}{similar to \code{\%--\%}, but edges \emph{from} the left hand side argument, pointing \emph{to} the right hand side argument, are selected, in directed graphs.} \item{\code{\%<-\%}}{similar to \code{\%--\%}, but edges \emph{to} the left hand side argument, pointing \emph{from} the right hand side argument, are selected, in directed graphs.} } Note that multiple special functions can be used together, or with regular indices, and then their results are concatenated. See more examples below. } \examples{ # special operators for indexing based on graph structure g <- sample_pa(100, power = 0.3) E(g) [ 1:3 \%--\% 2:6 ] E(g) [ 1:5 \%->\% 1:6 ] E(g) [ 1:3 \%<-\% 2:6 ] # the edges along the diameter g <- sample_pa(100, directed = FALSE) d <- get_diameter(g) E(g, path = d) # select edges based on attributes g <- sample_gnp(20, 3/20) \%>\% set_edge_attr("weight", value = rnorm(gsize(.))) E(g)[[ weight < 0 ]] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} \concept{vertex and edge sequences} igraph/man/add_vertices.Rd0000644000175100001440000000246013430770475015254 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{add_vertices} \alias{add_vertices} \alias{add.vertices} \title{Add vertices to a graph} \usage{ add_vertices(graph, nv, ..., attr = list()) } \arguments{ \item{graph}{The input graph.} \item{nv}{The number of vertices to add.} \item{...}{Additional arguments, they must be named, and they will be added as vertex attributes, for the newly added vertices. See also details below.} \item{attr}{A named list, its elements will be added as vertex attributes, for the newly added vertices. See also details below.} } \value{ The graph, with the vertices (and attributes) added. } \description{ If attributes are supplied, and they are not present in the graph, their values for the original vertices of the graph are set to \code{NA}. } \examples{ g <- make_empty_graph() \%>\% add_vertices(3, color = "red") \%>\% add_vertices(2, color = "green") \%>\% add_edges(c(1,2, 2,3, 3,4, 4,5)) g V(g)[[]] plot(g) } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/biconnected_components.Rd0000644000175100001440000000353013430770475017341 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/components.R \name{biconnected_components} \alias{biconnected_components} \alias{biconnected.components} \title{Biconnected components} \usage{ biconnected_components(graph) } \arguments{ \item{graph}{The input graph. It is treated as an undirected graph, even if it is directed.} } \value{ A named list with three components: \item{no}{Numeric scalar, an integer giving the number of biconnected components in the graph.} \item{tree_edges}{The components themselves, a list of numeric vectors. Each vector is a set of edge ids giving the edges in a biconnected component. These edges define a spanning tree of the component.} \item{component_edges}{A list of numeric vectors. It gives all edges in the components.} \item{components}{A list of numeric vectors, the vertices of the components.} \item{articulation_points}{The articulation points of the graph. See \code{\link{articulation_points}}.} } \description{ Finding the biconnected components of a graph } \details{ A graph is biconnected if the removal of any single vertex (and its adjacent edges) does not disconnect it. A biconnected component of a graph is a maximal biconnected subgraph of it. The biconnected components of a graph can be given by the partition of its edges: every edge is a member of exactly one biconnected component. Note that this is not true for vertices: the same vertex can be part of many biconnected components. } \examples{ g <- disjoint_union( make_full_graph(5), make_full_graph(5) ) clu <- components(g)$membership g <- add_edges(g, c(which(clu==1), which(clu==2))) bc <- biconnected_components(g) } \seealso{ \code{\link{articulation_points}}, \code{\link{components}}, \code{\link{is_connected}}, \code{\link{vertex_connectivity}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/plus-.igraph.Rd0000644000175100001440000001137313430770475015134 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{+.igraph} \alias{+.igraph} \title{Add vertices, edges or another graph to a graph} \usage{ \method{+}{igraph}(e1, e2) } \arguments{ \item{e1}{First argument, probably an igraph graph, but see details below.} \item{e2}{Second argument, see details below.} } \description{ Add vertices, edges or another graph to a graph } \details{ The plus operator can be used to add vertices or edges to graph. The actual operation that is performed depends on the type of the right hand side argument. \itemize{ \item If is is another igraph graph object and they are both named graphs, then the union of the two graphs are calculated, see \code{\link{union}}. \item If it is another igraph graph object, but either of the two are not named, then the disjoint union of the two graphs is calculated, see \code{\link{disjoint_union}}. \item If it is a numeric scalar, then the specified number of vertices are added to the graph. \item If it is a character scalar or vector, then it is interpreted as the names of the vertices to add to the graph. \item If it is an object created with the \code{\link{vertex}} or \code{\link{vertices}} function, then new vertices are added to the graph. This form is appropriate when one wants to add some vertex attributes as well. The operands of the \code{vertices} function specifies the number of vertices to add and their attributes as well. The unnamed arguments of \code{vertices} are concatenated and used as the \sQuote{\code{name}} vertex attribute (i.e. vertex names), the named arguments will be added as additional vertex attributes. Examples: \preformatted{ g <- g + vertex(shape="circle", color= "red") g <- g + vertex("foo", color="blue") g <- g + vertex("bar", "foobar") g <- g + vertices("bar2", "foobar2", color=1:2, shape="rectangle")} \code{vertex} is just an alias to \code{vertices}, and it is provided for readability. The user should use it if a single vertex is added to the graph. \item If it is an object created with the \code{\link{edge}} or \code{\link{edges}} function, then new edges will be added to the graph. The new edges and possibly their attributes can be specified as the arguments of the \code{edges} function. The unnamed arguments of \code{edges} are concatenated and used as vertex ids of the end points of the new edges. The named arguments will be added as edge attributes. Examples: \preformatted{ g <- make_empty_graph() + vertices(letters[1:10]) + vertices("foo", "bar", "bar2", "foobar2") g <- g + edge("a", "b") g <- g + edges("foo", "bar", "bar2", "foobar2") g <- g + edges(c("bar", "foo", "foobar2", "bar2"), color="red", weight=1:2)} See more examples below. \code{edge} is just an alias to \code{edges} and it is provided for readability. The user should use it if a single edge is added to the graph. \item If it is an object created with the \code{\link{path}} function, then new edges that form a path are added. The edges and possibly their attributes are specified as the arguments to the \code{path} function. The non-named arguments are concatenated and interpreted as the vertex ids along the path. The remaining arguments are added as edge attributes. Examples: \preformatted{ g <- make_empty_graph() + vertices(letters[1:10]) g <- g + path("a", "b", "c", "d") g <- g + path("e", "f", "g", weight=1:2, color="red") g <- g + path(c("f", "c", "j", "d"), width=1:3, color="green")} } It is important to note that, although the plus operator is commutative, i.e. is possible to write \preformatted{ graph <- "foo" + make_empty_graph()} it is not associative, e.g. \preformatted{ graph <- "foo" + "bar" + make_empty_graph()} results a syntax error, unless parentheses are used: \preformatted{ graph <- "foo" + ( "bar" + make_empty_graph() )} For clarity, we suggest to always put the graph object on the left hand side of the operator: \preformatted{ graph <- make_empty_graph() + "foo" + "bar"} } \examples{ # 10 vertices named a,b,c,... and no edges g <- make_empty_graph() + vertices(letters[1:10]) # Add edges to make it a ring g <- g + path(letters[1:10], letters[1], color = "grey") # Add some extra random edges g <- g + edges(sample(V(g), 10, replace = TRUE), color = "red") g$layout <- layout_in_circle plot(g) } \seealso{ Other functions for manipulating graph structure: \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/head_print.Rd0000644000175100001440000000175013430770475014736 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/printr.R \name{head_print} \alias{head_print} \title{Print the only the head of an R object} \usage{ head_print(x, max_lines = 20, header = "", footer = "", omitted_footer = "", ...) } \arguments{ \item{x}{The object to print, or a callback function. See \code{\link{printer_callback}} for details.} \item{max_lines}{Maximum number of lines to print, \emph{not} including the header and the footer.} \item{header}{The header, if a function, then it will be called, otherwise printed using \code{cat}.} \item{footer}{The footer, if a function, then it will be called, otherwise printed using \code{cat}.} \item{omitted_footer}{Footer that is only printed if anything is omitted from the printout. If a function, then it will be called, otherwise printed using \code{cat}.} \item{...}{Extra arguments to pass to \code{print()}.} } \value{ \code{x}, invisibly. } \description{ Print the only the head of an R object } igraph/man/girth.Rd0000644000175100001440000000313713430770476013740 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{girth} \alias{girth} \title{Girth of a graph} \usage{ girth(graph, circle = TRUE) } \arguments{ \item{graph}{The input graph. It may be directed, but the algorithm searches for undirected circles anyway.} \item{circle}{Logical scalar, whether to return the shortest circle itself.} } \value{ A named list with two components: \item{girth}{Integer constant, the girth of the graph, or 0 if the graph is acyclic.} \item{circle}{Numeric vector with the vertex ids in the shortest circle.} } \description{ The girth of a graph is the length of the shortest circle in it. } \details{ The current implementation works for undirected graphs only, directed graphs are treated as undirected graphs. Loop edges and multiple edges are ignored. If the graph is a forest (ie. acyclic), then zero is returned. This implementation is based on Alon Itai and Michael Rodeh: Finding a minimum circuit in a graph \emph{Proceedings of the ninth annual ACM symposium on Theory of computing}, 1-10, 1977. The first implementation of this function was done by Keith Briggs, thanks Keith. } \examples{ # No circle in a tree g <- make_tree(1000, 3) girth(g) # The worst case running time is for a ring g <- make_ring(100) girth(g) # What about a random graph? g <- sample_gnp(1000, 1/1000) girth(g) } \references{ Alon Itai and Michael Rodeh: Finding a minimum circuit in a graph \emph{Proceedings of the ninth annual ACM symposium on Theory of computing}, 1-10, 1977 } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/without_loops.Rd0000644000175100001440000000116413430770475015537 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{without_loops} \alias{without_loops} \title{Constructor modifier to drop loop edges} \usage{ without_loops() } \description{ Constructor modifier to drop loop edges } \examples{ # An artificial example make_(full_graph(5, loops = TRUE)) make_(full_graph(5, loops = TRUE), without_loops()) } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_edge_}}, \code{\link{with_graph_}}, \code{\link{with_vertex_}}, \code{\link{without_attr}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/plot.common.Rd0000644000175100001440000005320213424602743015060 0ustar hornikusers\name{Drawing graphs} \alias{igraph.plotting} \concept{Visualization} \title{Drawing graphs} \description{The common bits of the three plotting functions \code{plot.igraph}, \code{tkplot} and \code{rglplot} are discussed in this manual page} \details{ There are currently three different functions in the igraph package which can draw graph in various ways: \code{plot.igraph} does simple non-interactive 2D plotting to R devices. Actually it is an implementation of the \code{\link[graphics]{plot}} generic function, so you can write \code{plot(graph)} instead of \code{plot.igraph(graph)}. As it used the standard R devices it supports every output format for which R has an output device. The list is quite impressing: PostScript, PDF files, XFig files, SVG files, JPG, PNG and of course you can plot to the screen as well using the default devices, or the good-looking anti-aliased Cairo device. See \code{\link{plot.igraph}} for some more information. \code{\link{tkplot}} does interactive 2D plotting using the \code{tcltk} package. It can only handle graphs of moderate size, a thousend vertices is probably already too many. Some parameters of the plotted graph can be changed interactively after issuing the \code{tkplot} command: the position, color and size of the vertices and the color and width of the edges. See \code{\link{tkplot}} for details. \code{\link{rglplot}} is an experimental function to draw graphs in 3D using OpenGL. See \code{\link{rglplot}} for some more information. Please also check the examples below. } \section{How to specify graphical parameters}{ There are three ways to give values to the parameters described below, in section 'Parameters'. We give these three ways here in the order of their precedence. The first method is to supply named arguments to the plotting commands: \code{\link{plot.igraph}}, \code{\link{tkplot}} or \code{\link{rglplot}}. Parameters for vertices start with prefix \sQuote{\code{vertex.}}, parameters for edges have prefix \sQuote{\code{edge.}}, and global parameters have no prefix. Eg. the color of the vertices can be given via argument \code{vertex.color}, whereas \code{edge.color} sets the color of the edges. \code{layout} gives the layout of the graphs. The second way is to assign vertex, edge and graph attributes to the graph. These attributes have no prefix, ie. the color of the vertices is taken from the \code{color} vertex attribute and the color of the edges from the \code{color} edge attribute. The layout of the graph is given by the \code{layout} graph attribute. (Always assuming that the corresponding command argument is not present.) Setting vertex and edge attributes are handy if you want to assign a given \sQuote{look} to a graph, attributes are saved with the graph is you save it with \code{\link[base]{save}} or in GraphML format with \code{\link{write_graph}}, so the graph will have the same look after loading it again. If a parameter is not given in the command line, and the corresponding vertex/edge/graph attribute is also missing then the general igraph parameters handled by \code{\link{igraph_options}} are also checked. Vertex parameters have prefix \sQuote{\code{vertex.}}, edge parameters are prefixed with \sQuote{\code{edge.}}, general parameters like \code{layout} are prefixed with \sQuote{\code{plot}}. These parameters are useful if you want all or most of your graphs to have the same look, vertex size, vertex color, etc. Then you don't need to set these at every plotting, and you also don't need to assign vertex/edge attributes to every graph. If the value of a parameter is not specified by any of the three ways described here, its default valued is used, as given in the source code. Different parameters can have different type, eg. vertex colors can be given as a character vector with color names, or as an integer vector with the color numbers from the current palette. Different types are valid for different parameters, this is discussed in detail in the next section. It is however always true that the parameter can always be a function object in which it will be called with the graph as its single argument to get the \dQuote{proper} value of the parameter. (If the function returns another function object that will \emph{not} be called again\dots) } \section{The list of parameters}{ Vertex parameters first, note that the \sQuote{\code{vertex.}} prefix needs to be added if they are used as an argument or when setting via \code{\link{igraph_options}}. The value of the parameter may be scalar valid for every vertex or a vector with a separate value for each vertex. (Shorter vectors are recycled.) \describe{ \item{size}{The size of the vertex, a numeric scalar or vector, in the latter case each vertex sizes may differ. This vertex sizes are scaled in order have about the same size of vertices for a given value for all three plotting commands. It does not need to be an integer number. The default value is 15. This is big enough to place short labels on vertices.} \item{size2}{The \dQuote{other} size of the vertex, for some vertex shapes. For the various rectangle shapes this gives the height of the vertices, whereas \code{size} gives the width. It is ignored by shapes for which the size can be specified with a single number. The default is 15. } \item{color}{The fill color of the vertex. If it is numeric then the current palette is used, see \code{\link[grDevices]{palette}}. If it is a character vector then it may either contain integer values, named colors or RGB specified colors with three or four bytes. All strings starting with \sQuote{\code{#}} are assumed to be RGB color specifications. It is possible to mix named color and RGB colors. Note that \code{\link{tkplot}} ignores the fourth byte (alpha channel) in the RGB color specification. For \code{plot.igraph} and integer values, the default igraph palette is used (see the \sQuote{palette} parameter below. Note that this is different from the R palette. If you don't want (some) vertices to have any color, supply \code{NA} as the color name. The default value is \dQuote{\code{SkyBlue2}}. } \item{frame.color}{The color of the frame of the vertices, the same formats are allowed as for the fill color. If you don't want vertices to have a frame, supply \code{NA} as the color name. By default it is \dQuote{black}. } \item{shape}{The shape of the vertex, currently \dQuote{\code{circle}}, \dQuote{\code{square}}, \dQuote{\code{csquare}}, \dQuote{\code{rectangle}}, \dQuote{\code{crectangle}}, \dQuote{\code{vrectangle}}, \dQuote{\code{pie}} (see \link{vertex.shape.pie}), \sQuote{\code{sphere}}, and \dQuote{\code{none}} are supported, and only by the \code{\link{plot.igraph}} command. \dQuote{\code{none}} does not draw the vertices at all, although vertex label are plotted (if given). See \code{\link{shapes}} for details about vertex shapes and \code{\link{vertex.shape.pie}} for using pie charts as vertices. The \dQuote{\code{sphere}} vertex shape plots vertices as 3D ray-traced spheres, in the given color and size. This produces a raster image and it is only supported with some graphics devices. On some devices raster transparency is not supported and the spheres do not have a transparent background. See \code{\link{dev.capabilities}} and the \sQuote{\code{rasterImage}} capability to check that your device is supported. By default vertices are drawn as circles. } \item{label}{The vertex labels. They will be converted to character. Specify \code{NA} to omit vertex labels. The default vertex labels are the vertex ids. } \item{label.family}{The font family to be used for vertex labels. As different plotting commands can used different fonts, they interpret this parameter different ways. The basic notation is, however, understood by both \code{\link{plot.igraph}} and \code{\link{tkplot}}. \code{\link{rglplot}} does not support fonts at all right now, it ignores this parameter completely. For \code{\link{plot.igraph}} this parameter is simply passed to \code{\link[graphics]{text}} as argument \code{family}. For \code{\link{tkplot}} some conversion is performed. If this parameter is the name of an exixting Tk font, then that font is used and the \code{label.font} and \code{label.cex} parameters are ignored complerely. If it is one of the base families (serif, sans, mono) then Times, Helvetica or Courier fonts are used, there are guaranteed to exist on all systems. For the \sQuote{symbol} base family we used the symbol font is available, otherwise the first font which has \sQuote{symbol} in its name. If the parameter is not a name of the base families and it is also not a named Tk font then we pass it to \code{\link[tcltk]{tkfont.create}} and hope the user knows what she is doing. The \code{label.font} and \code{label.cex} parameters are also passed to \code{\link[tcltk]{tkfont.create}} in this case. The default value is \sQuote{serif}. } \item{label.font}{The font within the font family to use for the vertex labels. It is interpreted the same way as the the \code{font} graphical parameter: 1 is plain text, 2 is bold face, 3 is italic, 4 is bold and italic and 5 specifies the symbol font. For \code{\link{plot.igraph}} this parameter is simply passed to \code{\link[graphics]{text}}. For \code{\link{tkplot}}, if the \code{label.family} parameter is not the name of a Tk font then this parameter is used to set whether the newly created font should be italic and/or boldface. Otherwise it is ignored. For \code{\link{rglplot}} it is ignored. The default value is 1. } \item{label.cex}{The font size for vertex labels. It is interpreted as a multiplication factor of some device-dependent base font size. For \code{\link{plot.igraph}} it is simply passed to \code{\link[graphics]{text}} as argument \code{cex}. For \code{\link{tkplot}} it is multiplied by 12 and then used as the \code{size} argument for \code{\link[tcltk]{tkfont.create}}. The base font is thus 12 for tkplot. For \code{\link{rglplot}} it is ignored. The default value is 1. } \item{label.dist}{ The distance of the label from the center of the vertex. If it is 0 then the label is centered on the vertex. If it is 1 then the label is displayed beside the vertex. The default value is 0. } \item{label.degree}{ It defines the position of the vertex labels, relative to the center of the vertices. It is interpreted as an angle in radian, zero means \sQuote{to the right}, and \sQuote{\code{pi}} means to the left, up is \code{-pi/2} and down is \code{pi/2}. The default value is \code{-pi/4}. } \item{label.color}{The color of the labels, see the \code{color} vertex parameter discussed earlier for the possible values. The default value is \code{black}. } } Edge parameters require to add the \sQuote{\code{edge.}} prefix when used as arguments or set by \code{\link{igraph_options}}. The edge parameters: \describe{ \item{color}{The color of the edges, see the \code{color} vertex parameter for the possible values. By default this parameter is \code{darkgrey}. } \item{width}{The width of the edges. The default value is 1. } \item{arrow.size}{The size of the arrows. Currently this is a constant, so it is the same for every edge. If a vector is submitted then only the first element is used, ie. if this is taken from an edge attribute then only the attribute of the first edge is used for all arrows. This will likely change in the future. The default value is 1. } \item{arrow.width}{The width of the arrows. Currently this is a constant, so it is the same for every edge. If a vector is submitted then only the first element is used, ie. if this is taken from an edge attribute then only the attribute of the first edge is used for all arrows. This will likely change in the future. This argument is currently only used by \code{\link{plot.igraph}}. The default value is 1, which gives the same width as before this option appeared in igraph. } \item{lty}{The line type for the edges. Almost the same format is accepted as for the standard graphics \code{\link[graphics]{par}}, 0 and \dQuote{blank} mean no edges, 1 and \dQuote{solid} are for solid lines, the other possible values are: 2 (\dQuote{dashed}), 3 (\dQuote{dotted}), 4 (\dQuote{dotdash}), 5 (\dQuote{longdash}), 6 (\dQuote{twodash}). \code{\link{tkplot}} also accepts standard Tk line type strings, it does not however support \dQuote{blank} lines, instead of type \sQuote{0} type \sQuote{1}, ie. solid lines will be drawn. This argument is ignored for \code{\link{rglplot}}. The default value is type 1, a solid line. } \item{label}{The edge labels. They will be converted to character. Specify \code{NA} to omit edge labels. Edge labels are omitted by default.} \item{label.family}{Font family of the edge labels. See the vertex parameter with the same name for the details.} \item{label.font}{The font for the edge labels. See the corresponding vertex parameter discussed earlier for details.} \item{label.cex}{The font size for the edge labels, see the corresponding vertex parameter for details.} \item{label.color}{The color of the edge labels, see the \code{color} vertex parameters on how to specify colors. } \item{label.x}{The horizontal coordinates of the edge labels might be given here, explicitly. The \code{NA} elements will be replaced by automatically calculated coordinates. If \code{NULL}, then all edge horizontal coordinates are calculated automatically. This parameter is only supported by \code{plot.igraph}.} \item{label.y}{The same as \code{label.x}, but for vertical coordinates.} \item{curved}{Specifies whether to draw curved edges, or not. This can be a logical or a numeric vector or scalar. First the vector is replicated to have the same length as the number of edges in the graph. Then it is interpreted for each edge separately. A numeric value specifies the curvature of the edge; zero curvature means straight edges, negative values means the edge bends clockwise, positive values the opposite. \code{TRUE} means curvature 0.5, \code{FALSE} means curvature zero. By default the vector specifying the curvatire is calculated via a call to the \code{\link{curve_multiple}} function. This function makes sure that multiple edges are curved and are all visible. This parameter is ignored for loop edges. The default value is \code{FALSE}. This parameter is currently ignored by \code{\link{rglplot}}.} \item{arrow.mode}{This parameter can be used to specify for which edges should arrows be drawn. If this parameter is given by the user (in either of the three ways) then it specifies which edges will have forward, backward arrows, or both, or no arrows at all. As usual, this parameter can be a vector or a scalar value. It can be an integer or character type. If it is integer then 0 means no arrows, 1 means backward arrows, 2 is for forward arrows and 3 for both. If it is a character vector then \dQuote{<} and \dQuote{<-} specify backward, \dQuote{>} and \dQuote{->} forward arrows and \dQuote{<>} and \dQuote{<->} stands for both arrows. All other values mean no arrows, perhaps you should use \dQuote{-} or \dQuote{--} to specify no arrows. Hint: this parameter can be used as a \sQuote{cheap} solution for drawing \dQuote{mixed} graphs: graphs in which some edges are directed some are not. If you want do this, then please create a \emph{directed} graph, because as of version 0.4 the vertex pairs in the edge lists can be swapped in undirected graphs. By default, no arrows will be drawn for undirected graphs, and for directed graphs, an arrow will be drawn for each edge, according to its direction. This is not very surprising, it is the expected behavior. } \item{loop.angle}{Gives the angle in radian for plotting loop edges. See the \code{label.dist} vertex parameter to see how this is interpreted. The default value is 0. } \item{loop.angle2}{Gives the second angle in radian for plotting loop edges. This is only used in 3D, \code{loop.angle} is enough in 2D. The default value is 0. } } Other parameters: \describe{ \item{layout}{ Either a function or a numeric matrix. It specifies how the vertices will be placed on the plot. If it is a numeric matrix, then the matrix has to have one line for each vertex, specifying its coordinates. The matrix should have at least two columns, for the \code{x} and \code{y} coordinates, and it can also have third column, this will be the \code{z} coordinate for 3D plots and it is ignored for 2D plots. If a two column matrix is given for the 3D plotting function \code{\link{rglplot}} then the third column is assumed to be 1 for each vertex. If \code{layout} is a function, this function will be called with the \code{graph} as the single parameter to determine the actual coordinates. The function should return a matrix with two or three columns. For the 2D plots the third column is ignored. The default value is \code{layout_nicely}, a smart function that chooses a layouter based on the graph.} \item{margin}{The amount of empty space below, over, at the left and right of the plot, it is a numeric vector of length four. Usually values between 0 and 0.5 are meaningful, but negative values are also possible, that will make the plot zoom in to a part of the graph. If it is shorter than four then it is recycled. \code{\link{rglplot}} does not support this parameter, as it can zoom in and out the graph in a more flexible way. Its default value is 0. } \item{palette}{The color palette to use for vertex color. The default is \code{\link{categorical_pal}}, which is a color-blind friendly categorical palette. See its manual page for details and other palettes. This parameters is only supported by \code{plot}, and not by \code{tkplot} and \code{rglplot}. } \item{rescale}{Logical constant, whether to rescale the coordinates to the [-1,1]x[-1,1](x[-1,1]) interval. This parameter is not implemented for \code{tkplot}. Defaults to \code{TRUE}, the layout will be rescaled. } \item{asp}{A numeric constant, it gives the \code{asp} parameter for \code{\link{plot}}, the aspect ratio. Supply 0 here if you don't want to give an aspect ratio. It is ignored by \code{tkplot} and \code{rglplot}. Defaults to 1. } \item{frame}{Boolean, whether to plot a frame around the graph. It is ignored by \code{tkplot} and \code{rglplot}. Defaults to \code{FALSE}. } \item{main}{Overall title for the main plot. The default is empty if the \code{annotate.plot} igraph option is \code{FALSE}, and the graph's \code{name} attribute otherwise. See the same argument of the base \code{plot} function. Only supported by \code{plot}.} \item{sub}{Subtitle of the main plot, the default is empty. Only supported by \code{plot}.} \item{xlab}{Title for the x axis, the default is empty if the \code{annotate.plot} igraph option is \code{FALSE}, and the number of vertices and edges, if it is \code{TRUE}. Only supported by \code{plot}.} \item{ylab}{Title for the y axis, the default is empty. Only supported by \code{plot}.} } } \author{Gabor Csardi \email{csardi.gabor@gmail.com}} \seealso{ \code{\link{plot.igraph}}, \code{\link{tkplot}}, \code{\link{rglplot}}, \code{\link{igraph_options}}} \examples{ \dontrun{ # plotting a simple ring graph, all default parameters, except the layout g <- make_ring(10) g$layout <- layout_in_circle plot(g) tkplot(g) rglplot(g) # plotting a random graph, set the parameters in the command arguments g <- barabasi.game(100) plot(g, layout=layout_with_fr, vertex.size=4, vertex.label.dist=0.5, vertex.color="red", edge.arrow.size=0.5) # plot a random graph, different color for each component g <- sample_gnp(100, 1/100) comps <- components(g)$membership colbar <- rainbow(max(comps)+1) V(g)$color <- colbar[comps+1] plot(g, layout=layout_with_fr, vertex.size=5, vertex.label=NA) # plot communities in a graph g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6,11)) com <- cluster_spinglass(g, spins=5) V(g)$color <- com$membership+1 g <- set_graph_attr(g, "layout", layout_with_kk(g)) plot(g, vertex.label.dist=1.5) # draw a bunch of trees, fix layout igraph_options(plot.layout=layout_as_tree) plot(make_tree(20, 2)) plot(make_tree(50, 3), vertex.size=3, vertex.label=NA) tkplot(make_tree(50, 2, mode="undirected"), vertex.size=10, vertex.color="green") } } \keyword{graphs} igraph/man/union.igraph.vs.Rd0000644000175100001440000000251613430770475015652 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{union.igraph.vs} \alias{union.igraph.vs} \title{Union of vertex sequences} \usage{ \method{union}{igraph.vs}(...) } \arguments{ \item{...}{The vertex sequences to take the union of.} } \value{ A vertex sequence that contains all vertices in the given sequences, exactly once. } \description{ Union of vertex sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of vertices is lost in the result. (This is to match the behavior of the based \code{unique} function.) } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(V(g)[1:6], V(g)[5:10]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/sample_pref.Rd0000644000175100001440000000552113430770475015116 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_pref} \alias{sample_pref} \alias{sample_asym_pref} \alias{preference.game} \alias{asymmetric.preference.game} \alias{pref} \alias{asym_pref} \title{Trait-based random generation} \usage{ sample_pref(nodes, types, type.dist = rep(1, types), fixed.sizes = FALSE, pref.matrix = matrix(1, types, types), directed = FALSE, loops = FALSE) pref(...) sample_asym_pref(nodes, types, type.dist.matrix = matrix(1, types, types), pref.matrix = matrix(1, types, types), loops = FALSE) asym_pref(...) } \arguments{ \item{nodes}{The number of vertices in the graphs.} \item{types}{The number of different vertex types.} \item{type.dist}{The distribution of the vertex types, a numeric vector of length \sQuote{types} containing non-negative numbers. The vector will be normed to obtain probabilities.} \item{fixed.sizes}{Fix the number of vertices with a given vertex type label. The \code{type.dist} argument gives the group sizes (i.e. number of vertices with the different labels) in this case.} \item{pref.matrix}{A square matrix giving the preferences of the vertex types. The matrix has \sQuote{types} rows and columns.} \item{directed}{Logical constant, whether to create a directed graph.} \item{loops}{Logical constant, whether self-loops are allowed in the graph.} \item{...}{Passed to the constructor, \code{sample_pref} or \code{sample_asym_pref}.} \item{type.dist.matrix}{The joint distribution of the in- and out-vertex types.} } \value{ An igraph graph. } \description{ Generation of random graphs based on different vertex types. } \details{ Both models generate random graphs with given vertex types. For \code{sample_pref} the probability that two vertices will be connected depends on their type and is given by the \sQuote{pref.matrix} argument. This matrix should be symmetric to make sense but this is not checked. The distribution of the different vertes types is given by the \sQuote{type.dist} vector. For \code{sample_asym_pref} each vertex has an in-type and an out-type and a directed graph is created. The probability that a directed edge is realized from a vertex with a given out-type to a vertex with a given in-type is given in the \sQuote{pref.matrix} argument, which can be asymmetric. The joint distribution for the in- and out-types is given in the \sQuote{type.dist.matrix} argument. } \examples{ pf <- matrix( c(1, 0, 0, 1), nr=2) g <- sample_pref(20, 2, pref.matrix=pf) \dontrun{tkplot(g, layout=layout_with_fr)} pf <- matrix( c(0, 1, 0, 0), nr=2) g <- sample_asym_pref(20, 2, pref.matrix=pf) \dontrun{tkplot(g, layout=layout_in_circle)} } \seealso{ \code{\link{sample_traits}}. \code{\link{sample_traits_callaway}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} for the R interface } \keyword{graphs} igraph/man/predict_edges.Rd0000644000175100001440000000551613430770475015426 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{predict_edges} \alias{predict_edges} \alias{hrg.predict} \title{Predict edges based on a hierarchical random graph model} \usage{ predict_edges(graph, hrg = NULL, start = FALSE, num.samples = 10000, num.bins = 25) } \arguments{ \item{graph}{The graph to fit the model to. Edge directions are ignored in directed graphs.} \item{hrg}{A hierarchical random graph model, in the form of an \code{igraphHRG} object. \code{predict_edges}s allow this to be \code{NULL} as well, then a HRG is fitted to the graph first, from a random starting point.} \item{start}{Logical, whether to start the fitting/sampling from the supplied \code{igraphHRG} object, or from a random starting point.} \item{num.samples}{Number of samples to use for consensus generation or missing edge prediction.} \item{num.bins}{Number of bins for the edge probabilities. Give a higher number for a more accurate prediction.} } \value{ A list with entries: \item{edges}{The predicted edges, in a two-column matrix of vertex ids.} \item{prob}{Probabilities of these edges, according to the fitted model.} \item{hrg}{The (supplied or fitted) hierarchical random graph model.} } \description{ \code{predict_edges} uses a hierarchical random graph model to predict missing edges from a network. This is done by sampling hierarchical models around the optimum model, proportionally to their likelihood. The MCMC sampling is stated from \code{hrg}, if it is given and the \code{start} argument is set to \code{TRUE}. Otherwise a HRG is fitted to the graph first. } \examples{ ## We are not running these examples any more, because they ## take a long time (~15 seconds) to run and this is against the CRAN ## repository policy. Copy and paste them by hand to your R prompt if ## you want to run them. \dontrun{ ## A graph with two dense groups g <- sample_gnp(10, p=1/2) + sample_gnp(10, p=1/2) hrg <- fit_hrg(g) hrg ## The consensus tree for it consensus_tree(g, hrg=hrg, start=TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1,2)) predict_edges(g2) } } \references{ A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure and the prediction of missing links in networks. \emph{Nature} 453, 98--101 (2008); A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, \emph{Lecture Notes in Computer Science} 4503, 1--13. Springer-Verlag, Berlin Heidelberg (2007). } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/scan_stat.Rd0000644000175100001440000000417413430770476014604 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scan.R \name{scan_stat} \alias{scan_stat} \title{Scan statistics on a time series of graphs} \usage{ scan_stat(graphs, tau = 1, ell = 0, locality = c("us", "them"), ...) } \arguments{ \item{graphs}{A list of igraph graph objects. They must be all directed or all undirected and they must have the same number of vertices.} \item{tau}{The number of previous time steps to consider for the time-dependent normalization for individual vertices. In other words, the current locality statistics of each vertex will be compared to this many previous time steps of the same vertex to decide whether it is significantly larger.} \item{ell}{The number of previous time steps to consider for the aggregated scan statistics. This is essentially a smoothing parameter.} \item{locality}{Whether to calculate the \sQuote{us} or \sQuote{them} statistics.} \item{...}{Extra arguments are passed to \code{\link{local_scan}}.} } \value{ A list with entries: \item{stat}{The scan statistics in each time step. It is \code{NA} for the initial \code{tau + ell} time steps.} \item{arg_max_v}{The (numeric) vertex ids for the vertex with the largest locality statistics, at each time step. It is \code{NA} for the initial \code{tau + ell} time steps.} } \description{ Calculate scan statistics on a time series of graphs. This is done by calculating the local scan statistics for each graph and each vertex, and then normalizing across the vertices and across the time steps. } \examples{ ## Generate a bunch of SBMs, with the last one being different num_t <- 20 block_sizes <- c(10, 5, 5) p_ij <- list(p = 0.1, h = 0.9, q = 0.9) P0 <- matrix(p_ij$p, 3, 3) P0[2, 2] <- p_ij$h PA <- P0 PA[3, 3] <- p_ij$q num_v <- sum(block_sizes) tsg <- replicate(num_t - 1, P0, simplify = FALSE) \%>\% append(list(PA)) \%>\% lapply(sample_sbm, n = num_v, block.sizes = block_sizes, directed = TRUE) scan_stat(graphs = tsg, k = 1, tau = 4, ell = 2) scan_stat(graphs = tsg, locality = "them", k = 1, tau = 4, ell = 2) } \seealso{ Other scan statistics: \code{\link{local_scan}} } \concept{scan statistics} igraph/man/min_separators.Rd0000644000175100001440000000532013430770475015644 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{min_separators} \alias{min_separators} \alias{minimum.size.separators} \title{Minimum size vertex separators} \usage{ min_separators(graph) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored.} } \value{ A list of numeric vectors. Each numeric vector is a vertex separator. } \description{ Find all vertex sets of minimal size whose removal separates the graph into more components } \details{ This function implements the Kanevsky algorithm for finding all minimal-size vertex separators in an undirected graph. See the reference below for the details. In the special case of a fully connected input graph with \eqn{n} vertices, all subsets of size \eqn{n-1} are listed as the result. } \examples{ # The graph from the Moody-White paper mw <- graph.formula(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, 21-22:23, 22-23) # Cohesive subgraphs mw1 <- induced.subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced.subgraph(mw, as.character(7:16)) mw3 <- induced.subgraph(mw, as.character(17:23)) mw4 <- induced.subgraph(mw, as.character(c(7,8,11,14))) mw5 <- induced.subgraph(mw, as.character(1:7)) min_separators(mw) min_separators(mw1) min_separators(mw2) min_separators(mw3) min_separators(mw4) min_separators(mw5) # Another example, the science camp network camp <- graph.formula(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael) min_separators(camp) } \references{ Arkady Kanevsky: Finding all minimum-size separating vertex sets in a graph. \emph{Networks} 23 533--541, 1993. JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, \emph{Algorithmica} 15, 351--372, 1996. J. Moody and D. R. White. Structural cohesion and embeddedness: A hierarchical concept of social groups. \emph{American Sociological Review}, 68 103--127, Feb 2003. } \seealso{ \code{\link{is.separator}} } igraph/man/eccentricity.Rd0000644000175100001440000000312713430770475015306 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R \name{eccentricity} \alias{eccentricity} \title{Eccentricity of the vertices in a graph} \usage{ eccentricity(graph, vids = V(graph), mode = c("all", "out", "in", "total")) } \arguments{ \item{graph}{The input graph, it can be directed or undirected.} \item{vids}{The vertices for which the eccentricity is calculated.} \item{mode}{Character constant, gives whether the shortest paths to or from the given vertices should be calculated for directed graphs. If \code{out} then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} it will be considered. If \code{all}, the default, then the corresponding undirected graph will be used, edge directions will be ignored. This argument is ignored for undirected graphs.} } \value{ \code{eccentricity} returns a numeric vector, containing the eccentricity score of each given vertex. } \description{ The eccentricity of a vertex is its shortest path distance from the farthest other node in the graph. } \details{ The eccentricity of a vertex is calculated by measuring the shortest distance from (or to) the vertex, to (or from) all vertices in the graph, and taking the maximum. This implementation ignores vertex pairs that are in different components. Isolate vertices have eccentricity zero. } \examples{ g <- make_star(10, mode="undirected") eccentricity(g) } \references{ Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, 1994. } \seealso{ \code{\link{radius}} for a related concept, \code{\link{distances}} for general shortest path calculations. } igraph/man/make_empty_graph.Rd0000644000175100001440000000177113430770475016140 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_empty_graph} \alias{make_empty_graph} \alias{graph.empty} \alias{empty_graph} \title{A graph with no edges} \usage{ make_empty_graph(n = 0, directed = TRUE) empty_graph(...) } \arguments{ \item{n}{Number of vertices.} \item{directed}{Whether to create a directed graph.} \item{...}{Passed to \code{make_graph_empty}.} } \value{ An igraph graph. } \description{ A graph with no edges } \examples{ make_empty_graph(n = 10) make_empty_graph(n = 5, directed = FALSE) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{Empty graph.} \concept{determimistic constructors} igraph/man/igraph-minus.Rd0000644000175100001440000000477413430770475015235 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{igraph-minus} \alias{igraph-minus} \alias{-.igraph} \title{Delete vertices or edges from a graph} \usage{ \method{-}{igraph}(e1, e2) } \arguments{ \item{e1}{Left argument, see details below.} \item{e2}{Right argument, see details below.} } \value{ An igraph graph. } \description{ Delete vertices or edges from a graph } \details{ The minus operator (\sQuote{\code{-}}) can be used to remove vertices or edges from the graph. The operation performed is selected based on the type of the right hand side argument: \itemize{ \item If it is an igraph graph object, then the difference of the two graphs is calculated, see \code{\link{difference}}. \item If it is a numeric or character vector, then it is interpreted as a vector of vertex ids and the specified vertices will be deleted from the graph. Example: \preformatted{ g <- make_ring(10) V(g)$name <- letters[1:10] g <- g - c("a", "b")} \item If \code{e2} is a vertex sequence (e.g. created by the \code{\link{V}} function), then these vertices will be deleted from the graph. \item If it is an edge sequence (e.g. created by the \code{\link{E}} function), then these edges will be deleted from the graph. \item If it is an object created with the \code{\link{vertex}} (or the \code{\link{vertices}}) function, then all arguments of \code{\link{vertices}} are concatenated and the result is interpreted as a vector of vertex ids. These vertices will be removed from the graph. \item If it is an object created with the \code{\link{edge}} (or the \code{\link{edges}}) function, then all arguments of \code{\link{edges}} are concatenated and then interpreted as edges to be removed from the graph. Example: \preformatted{ g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] g <- g - edge("e|f") g <- g - edge("H")} \item If it is an object created with the \code{\link{path}} function, then all \code{\link{path}} arguments are concatenated and then interpreted as a path along which edges will be removed from the graph. Example: \preformatted{ g <- make_ring(10) V(g)$name <- letters[1:10] g <- g - path("a", "b", "c", "d")} } } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/graph_from_data_frame.Rd0000644000175100001440000001206413430770475017110 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R, R/data_frame.R \name{as_data_frame} \alias{as_data_frame} \alias{graph_from_data_frame} \alias{graph.data.frame} \alias{get.data.frame} \alias{from_data_frame} \title{Creating igraph graphs from data frames or vice-versa} \usage{ as_data_frame(x, what = c("edges", "vertices", "both")) graph_from_data_frame(d, directed = TRUE, vertices = NULL) from_data_frame(...) } \arguments{ \item{x}{An igraph object.} \item{what}{Character constant, whether to return info about vertices, edges, or both. The default is \sQuote{edges}.} \item{d}{A data frame containing a symbolic edge list in the first two columns. Additional columns are considered as edge attributes. Since version 0.7 this argument is coerced to a data frame with \code{as.data.frame}.} \item{directed}{Logical scalar, whether or not to create a directed graph.} \item{vertices}{A data frame with vertex metadata, or \code{NULL}. See details below. Since version 0.7 this argument is coerced to a data frame with \code{as.data.frame}, if not \code{NULL}.} \item{...}{Passed to \code{graph_from_data_frame}.} } \value{ An igraph graph object for \code{graph_from_data_frame}, and either a data frame or a list of two data frames named \code{edges} and \code{vertices} for \code{as.data.frame}. } \description{ This function creates an igraph graph from one or two data frames containing the (symbolic) edge list and edge/vertex attributes. } \details{ \code{graph_from_data_frame} creates igraph graphs from one or two data frames. It has two modes of operatation, depending whether the \code{vertices} argument is \code{NULL} or not. If \code{vertices} is \code{NULL}, then the first two columns of \code{d} are used as a symbolic edge list and additional columns as edge attributes. The names of the attributes are taken from the names of the columns. If \code{vertices} is not \code{NULL}, then it must be a data frame giving vertex metadata. The first column of \code{vertices} is assumed to contain symbolic vertex names, this will be added to the graphs as the \sQuote{\code{name}} vertex attribute. Other columns will be added as additional vertex attributes. If \code{vertices} is not \code{NULL} then the symbolic edge list given in \code{d} is checked to contain only vertex names listed in \code{vertices}. Typically, the data frames are exported from some speadsheat software like Excel and are imported into R via \code{\link{read.table}}, \code{\link{read.delim}} or \code{\link{read.csv}}. \code{as_data_frame} converts the igraph graph into one or more data frames, depending on the \code{what} argument. If the \code{what} argument is \code{edges} (the default), then the edges of the graph and also the edge attributes are returned. The edges will be in the first two columns, named \code{from} and \code{to}. (This also denotes edge direction for directed graphs.) For named graphs, the vertex names will be included in these columns, for other graphs, the numeric vertex ids. The edge attributes will be in the other columns. It is not a good idea to have an edge attribute named \code{from} or \code{to}, because then the column named in the data frame will not be unique. The edges are listed in the order of their numeric ids. If the \code{what} argument is \code{vertices}, then vertex attributes are returned. Vertices are listed in the order of their numeric vertex ids. If the \code{what} argument is \code{both}, then both vertex and edge data is returned, in a list with named entries \code{vertices} and \code{edges}. } \note{ For \code{graph_from_data_frame} \code{NA} elements in the first two columns \sQuote{d} are replaced by the string \dQuote{NA} before creating the graph. This means that all \code{NA}s will correspond to a single vertex. \code{NA} elements in the first column of \sQuote{vertices} are also replaced by the string \dQuote{NA}, but the rest of \sQuote{vertices} is not touched. In other words, vertex names (=the first column) cannot be \code{NA}, but other vertex attributes can. } \examples{ ## A simple example with a couple of actors ## The typical case is that these tables are read in from files.... actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David", "Esmeralda"), age=c(48,33,45,34,21), gender=c("F","M","F","M","F")) relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"), to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE), friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3)) g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors) print(g, e=TRUE, v=TRUE) ## The opposite operation as_data_frame(g, what="vertices") as_data_frame(g, what="edges") } \seealso{ \code{\link{graph_from_literal}} for another way to create graphs, \code{\link{read.table}} to read in tables from files. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/rglplot.Rd0000644000175100001440000000203513430770475014301 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.R \name{rglplot} \alias{rglplot} \alias{rglplot.igraph} \title{3D plotting of graphs with OpenGL} \usage{ rglplot(x, ...) } \arguments{ \item{x}{The graph to plot.} \item{\dots}{Additional arguments, see \code{\link{igraph.plotting}} for the details} } \value{ \code{NULL}, invisibly. } \description{ Using the \code{rgl} package, \code{rglplot} plots a graph in 3D. The plot can be zoomed, rotated, shifted, etc. but the coordinates of the vertices is fixed. } \details{ Note that \code{rglplot} is considered to be highly experimental. It is not very useful either. See \code{\link{igraph.plotting}} for the possible arguments. } \examples{ \dontrun{ g <- make_lattice( c(5,5,5) ) coords <- layout_with_fr(g, dim=3) rglplot(g, layout=coords) } } \seealso{ \code{\link{igraph.plotting}}, \code{\link{plot.igraph}} for the 2D version, \code{\link{tkplot}} for interactive graph drawing in 2D. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/matching.Rd0000644000175100001440000001063413430770476014415 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{is_matching} \alias{is_matching} \alias{is.matching} \alias{is.maximal.matching} \alias{is_max_matching} \alias{maximum.bipartite.matching} \alias{max_bipartite_match} \title{Graph matching} \usage{ is_matching(graph, matching, types = NULL) is_max_matching(graph, matching, types = NULL) max_bipartite_match(graph, types = NULL, weights = NULL, eps = .Machine$double.eps) } \arguments{ \item{graph}{The input graph. It might be directed, but edge directions will be ignored.} \item{matching}{A potential matching. An integer vector that gives the pair in the matching for each vertex. For vertices without a pair, supply \code{NA} here.} \item{types}{Vertex types, if the graph is bipartite. By default they are taken from the \sQuote{\code{type}} vertex attribute, if present.} \item{weights}{Potential edge weights. If the graph has an edge attribute called \sQuote{\code{weight}}, and this argument is \code{NULL}, then the edge attribute is used automatically. In weighed matching, the weights of the edges must match as much as possible.} \item{eps}{A small real number used in equality tests in the weighted bipartite matching algorithm. Two real numbers are considered equal in the algorithm if their difference is smaller than \code{eps}. This is required to avoid the accumulation of numerical errors. By default it is set to the smallest \eqn{x}, such that \eqn{1+x \ne 1}{1+x != 1} holds. If you are running the algorithm with no weights, this argument is ignored.} } \value{ \code{is_matching} and \code{is_max_matching} return a logical scalar. \code{max_bipartite_match} returns a list with components: \item{matching_size}{The size of the matching, i.e. the number of edges connecting the matched vertices.} \item{matching_weight}{The weights of the matching, if the graph was weighted. For unweighted graphs this is the same as the size of the matching.} \item{matching}{The matching itself. Numeric vertex id, or vertex names if the graph was named. Non-matched vertices are denoted by \code{NA}.} } \description{ A matching in a graph means the selection of a set of edges that are pairwise non-adjacenct, i.e. they have no common incident vertices. A matching is maximal if it is not a proper subset of any other matching. } \details{ \code{is_matching} checks a matching vector and verifies whether its length matches the number of vertices in the given graph, its values are between zero (inclusive) and the number of vertices (inclusive), and whether there exists a corresponding edge in the graph for every matched vertex pair. For bipartite graphs, it also verifies whether the matched vertices are in different parts of the graph. \code{is_max_matching} checks whether a matching is maximal. A matching is maximal if and only if there exists no unmatched vertex in a graph such that one of its neighbors is also unmatched. \code{max_bipartite_match} calculates a maximum matching in a bipartite graph. A matching in a bipartite graph is a partial assignment of vertices of the first kind to vertices of the second kind such that each vertex of the first kind is matched to at most one vertex of the second kind and vice versa, and matched vertices must be connected by an edge in the graph. The size (or cardinality) of a matching is the number of edges. A matching is a maximum matching if there exists no other matching with larger cardinality. For weighted graphs, a maximum matching is a matching whose edges have the largest possible total weight among all possible matchings. Maximum matchings in bipartite graphs are found by the push-relabel algorithm with greedy initialization and a global relabeling after every \eqn{n/2} steps where \eqn{n} is the number of vertices in the graph. } \examples{ g <- graph_from_literal( a-b-c-d-e-f ) m1 <- c("b", "a", "d", "c", "f", "e") # maximal matching m2 <- c("b", "a", "d", "c", NA, NA) # non-maximal matching m3 <- c("b", "c", "d", "c", NA, NA) # not a matching is_matching(g, m1) is_matching(g, m2) is_matching(g, m3) is_max_matching(g, m1) is_max_matching(g, m2) is_max_matching(g, m3) V(g)$type <- c(FALSE,TRUE) print_all(g, v=TRUE) max_bipartite_match(g) g2 <- graph_from_literal( a-b-c-d-e-f-g ) V(g2)$type <- rep(c(FALSE,TRUE), length=vcount(g2)) print_all(g2, v=TRUE) max_bipartite_match(g2) #' @keywords graphs } \author{ Tamas Nepusz \email{ntamas@gmail.com} } igraph/man/set_edge_attr.Rd0000644000175100001440000000235513430770475015434 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{set_edge_attr} \alias{set_edge_attr} \alias{set.edge.attribute} \title{Set edge attributes} \usage{ set_edge_attr(graph, name, index = E(graph), value) } \arguments{ \item{graph}{The graph} \item{name}{The name of the attribute to set.} \item{index}{An optional edge sequence to set the attributes of a subset of edges.} \item{value}{The new value of the attribute for all (or \code{index}) edges.} } \value{ The graph, with the edge attribute added or set. } \description{ Set edge attributes } \examples{ g <- make_ring(10) \%>\% set_edge_attr("label", value = LETTERS[1:10]) g plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/with_graph_.Rd0000644000175100001440000000120213430770475015104 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{with_graph_} \alias{with_graph_} \title{Constructor modifier to add graph attributes} \usage{ with_graph_(...) } \arguments{ \item{...}{The attributes to add. They must be named.} } \description{ Constructor modifier to add graph attributes } \examples{ make_(ring(10), with_graph_(name = "10-ring")) } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_edge_}}, \code{\link{with_vertex_}}, \code{\link{without_attr}}, \code{\link{without_loops}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/make_tree.Rd0000644000175100001440000000240213430770475014550 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_tree} \alias{make_tree} \alias{graph.tree} \alias{tree} \title{Create tree graphs} \usage{ make_tree(n, children = 2, mode = c("out", "in", "undirected")) tree(...) } \arguments{ \item{n}{Number of vertices.} \item{children}{Integer scalar, the number of children of a vertex (except for leafs)} \item{mode}{Defines the direction of the edges. \code{out} indicates that the edges point from the parent to the children, \code{in} indicates that they point from the children to their parents, while \code{undirected} creates an undirected graph.} \item{...}{Passed to \code{make_tree}.} } \value{ An igraph graph } \description{ Create a regular tree graph. } \examples{ make_tree(10, 2) make_tree(10, 3, mode = "undirected") } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}} } \concept{Trees.} \concept{determimistic constructors} igraph/man/edge_attr_names.Rd0000644000175100001440000000205313430770475015737 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{edge_attr_names} \alias{edge_attr_names} \alias{list.edge.attributes} \title{List names of edge attributes} \usage{ edge_attr_names(graph) } \arguments{ \item{graph}{The graph.} } \value{ Character vector, the names of the edge attributes. } \description{ List names of edge attributes } \examples{ g <- make_ring(10) \%>\% set_edge_attr("label", value = letters[1:10]) edge_attr_names(g) plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/sample_correlated_gnp_pair.Rd0000644000175100001440000000325713430770475020171 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_correlated_gnp_pair} \alias{sample_correlated_gnp_pair} \title{Sample a pair of correlated G(n,p) random graphs} \usage{ sample_correlated_gnp_pair(n, corr, p, directed = FALSE, permutation = NULL) } \arguments{ \item{n}{Numeric scalar, the number of vertices for the sampled graphs.} \item{corr}{A scalar in the unit interval, the target Pearson correlation between the adjacency matrices of the original the generated graph (the adjacency matrix being used as a vector).} \item{p}{A numeric scalar, the probability of an edge between two vertices, it must in the open (0,1) interval.} \item{directed}{Logical scalar, whether to generate directed graphs.} \item{permutation}{A numeric vector, a permutation vector that is applied on the vertices of the first graph, to get the second graph. If \code{NULL}, the vertices are not permuted.} } \value{ A list of two igraph objects, named \code{graph1} and \code{graph2}, which are two graphs whose adjacency matrix entries are correlated with \code{corr}. } \description{ Sample a new graph by perturbing the adjacency matrix of a given graph and shuffling its vertices. } \details{ Please see the reference given below. } \examples{ gg <- sample_correlated_gnp_pair(n = 10, corr = .8, p = .5, directed = FALSE) gg cor(as.vector(gg[[1]][]), as.vector(gg[[2]][])) } \references{ Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seeded graph matching for correlated Erdos-Renyi graphs. \url{http://arxiv.org/abs/1304.7844} } \seealso{ \code{\link{sample_correlated_gnp}}, \code{\link{sample_gnp}}. } \keyword{graphs} \keyword{graphs,random} igraph/man/cocitation.Rd0000644000175100001440000000271113430770475014753 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cocitation.R \name{cocitation} \alias{cocitation} \alias{bibcoupling} \title{Cocitation coupling} \usage{ cocitation(graph, v = V(graph)) } \arguments{ \item{graph}{The graph object to analyze} \item{v}{Vertex sequence or numeric vector, the vertex ids for which the cocitation or bibliographic coupling values we want to calculate. The default is all vertices.} } \value{ A numeric matrix with \code{length(v)} lines and \code{vcount(graph)} columns. Element \code{(i,j)} contains the cocitation or bibliographic coupling for vertices \code{v[i]} and \code{j}. } \description{ Two vertices are cocited if there is another vertex citing both of them. \code{cocitation} siply counts how many types two vertices are cocited. The bibliographic coupling of two vertices is the number of other vertices they both cite, \code{bibcoupling} calculates this. } \details{ \code{cocitation} calculates the cocitation counts for the vertices in the \code{v} argument and all vertices in the graph. \code{bibcoupling} calculates the bibliographic coupling for vertices in \code{v} and all vertices in the graph. Calculating the cocitation or bibliographic coupling for only one vertex costs the same amount of computation as for all vertices. This might change in the future. } \examples{ g <- make_ring(10) cocitation(g) bibcoupling(g) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/igraph_options.Rd0000644000175100001440000001172313430770475015647 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/par.R \name{igraph_options} \alias{igraph_options} \alias{igraph.options} \alias{getIgraphOpt} \alias{igraph_opt} \title{Parameters for the igraph package} \usage{ igraph_options(...) igraph_opt(x, default = NULL) } \arguments{ \item{\dots}{A list may be given as the only argument, or any number of arguments may be in the \code{name=value} form, or no argument at all may be given. See the Value and Details sections for explanation.} \item{x}{A character string holding an option name.} \item{default}{If the specified option is not set in the options list, this value is returned. This facilitates retrieving an option and checking whether it is set and setting it separately if not.} } \value{ \code{igraph_options} returns a list with the old values of the updated parameters, invisibly. Without any arguments, it returns the values of all options. For \code{igraph_opt}, the current value set for option \code{x}, or \code{NULL} if the option is unset. } \description{ igraph has some parameters which (usually) affect the behavior of many functions. These can be set for the whole session via \code{igraph_options}. } \details{ The parameter values set via a call to the \code{igraph_options} function will remain in effect for the rest of the session, affecting the subsequent behaviour of the other functions of the \code{igraph} package for which the given parameters are relevant. This offers the possibility of customizing the functioning of the \code{igraph} package, for instance by insertions of appropriate calls to \code{igraph_options} in a load hook for package \pkg{igraph}. The currently used parameters in alphabetical order: \describe{ \item{add.params}{Logical scalar, whether to add model parameter to the graphs that are created by the various graph constructors. By default it is \code{TRUE}.} \item{add.vertex.names}{Logical scalar, whether to add vertex names to node level indices, like degree, betweenness scores, etc. By default it is \code{TRUE}.} \item{annotate.plot}{Logical scalar, whether to annotate igraph plots with the graph's name (\code{name} graph attribute, if present) as \code{main}, and with the number of vertices and edges as \code{xlab}. Defaults to \code{FALSE}.} \item{dend.plot.type}{The plotting function to use when plotting community structure dendrograms via \code{\link{plot_dendrogram}}}. Possible values are \sQuote{auto} (the default), \sQuote{phylo}, \sQuote{hclust} and \sQuote{dendrogram}. See \code{\link{plot_dendrogram}} for details. \item{edge.attr.comb}{Specifies what to do with the edge attributes if the graph is modified. The default value is \code{list(weight="sum", name="concat", "ignore")}. See \code{\link{attribute.combination}} for details on this.} \item{nexus.url}{The base URL of the default Nexus server. See \code{\link{nexus}} for details.} \item{print.edge.attributes}{Logical constant, whether to print edge attributes when printing graphs. Defaults to \code{FALSE}.} \item{print.full}{Logical scalar, whether \code{\link{print.igraph}} should show the graph structure as well, or only a summary of the graph.} \item{print.graph.attributes}{Logical constant, whether to print graph attributes when printing graphs. Defaults to \code{FALSE}.} \item{print.vertex.attributes}{Logical constant, whether to print vertex attributes when printing graphs. Defaults to \code{FALSE}.} \item{return.vs.es}{Whether functions that return a set or sequence of vertices/edges should return formal vertex/edge sequence objects. This option was introduced in igraph version 1.0.0 and defaults to TRUE. If your package requires the old behavior, you can set it to FALSE in the \code{.onLoad} function of your package, without affecting other packages.} \item{sparsematrices}{Whether to use the \code{Matrix} package for (sparse) matrices. It is recommended, if the user works with larger graphs.} \item{verbose}{Logical constant, whether igraph functions should talk more than minimal. Eg. if \code{TRUE} thne some functions will use progress bars while computing. Defaults to \code{FALSE}.} \item{vertex.attr.comb}{Specifies what to do with the vertex attributes if the graph is modified. The default value is \code{list(name="concat", "ignore")} See \code{\link{attribute.combination}} for details on this.} } } \examples{ oldval <- igraph_opt("verbose") igraph_options(verbose = TRUE) layout_with_kk(make_ring(10)) igraph_options(verbose = oldval) oldval <- igraph_options(verbose = TRUE, sparsematrices = FALSE) make_ring(10)[] igraph_options(oldval) igraph_opt("verbose") } \seealso{ \code{igraph_options} is similar to \code{\link{options}} and \code{igraph_opt} is similar to \code{\link{getOption}}. Other igraph options: \code{\link{with_igraph_opt}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{igraph options} \keyword{graphs} igraph/man/layout_with_sugiyama.Rd0000644000175100001440000002137713430770475017077 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_sugiyama} \alias{layout_with_sugiyama} \alias{layout.sugiyama} \alias{with_sugiyama} \title{The Sugiyama graph layout generator} \usage{ layout_with_sugiyama(graph, layers = NULL, hgap = 1, vgap = 1, maxiter = 100, weights = NULL, attributes = c("default", "all", "none")) with_sugiyama(...) } \arguments{ \item{graph}{The input graph.} \item{layers}{A numeric vector or \code{NULL}. If not \code{NULL}, then it should specify the layer index of the vertices. Layers are numbered from one. If \code{NULL}, then igraph calculates the layers automatically.} \item{hgap}{Real scalar, the minimum horizontal gap between vertices in the same layer.} \item{vgap}{Real scalar, the distance between layers.} \item{maxiter}{Integer scalar, the maximum number of iterations in the crossing minimization stage. 100 is a reasonable default; if you feel that you have too many edge crossings, increase this.} \item{weights}{Optional edge weight vector. If \code{NULL}, then the 'weight' edge attribute is used, if there is one. Supply \code{NA} here and igraph ignores the edge weights. These are used only if the graph contains cycles; igraph will tend to reverse edges with smaller weights when breaking the cycles.} \item{attributes}{Which graph/vertex/edge attributes to keep in the extended graph. \sQuote{default} keeps the \sQuote{size}, \sQuote{size2}, \sQuote{shape}, \sQuote{label} and \sQuote{color} vertex attributes and the \sQuote{arrow.mode} and \sQuote{arrow.size} edge attributes. \sQuote{all} keep all graph, vertex and edge attributes, \sQuote{none} keeps none of them.} \item{...}{Passed to \code{layout_with_sugiyama}.} } \value{ A list with the components: \item{layout}{The layout, a two-column matrix, for the original graph vertices.} \item{layout.dummy}{The layout for the dummy vertices, a two column matrix.} \item{extd_graph}{The original graph, extended with dummy vertices. The \sQuote{dummy} vertex attribute is set on this graph, it is a logical attributes, and it tells you whether the vertex is a dummy vertex. The \sQuote{layout} graph attribute is also set, and it is the layout matrix for all (original and dummy) vertices.} } \description{ Sugiyama layout algorithm for layered directed acyclic graphs. The algorithm minimized edge crossings. } \details{ This layout algorithm is designed for directed acyclic graphs where each vertex is assigned to a layer. Layers are indexed from zero, and vertices of the same layer will be placed on the same horizontal line. The X coordinates of vertices within each layer are decided by the heuristic proposed by Sugiyama et al. to minimize edge crossings. You can also try to lay out undirected graphs, graphs containing cycles, or graphs without an a priori layered assignment with this algorithm. igraph will try to eliminate cycles and assign vertices to layers, but there is no guarantee on the quality of the layout in such cases. The Sugiyama layout may introduce \dQuote{bends} on the edges in order to obtain a visually more pleasing layout. This is achieved by adding dummy nodes to edges spanning more than one layer. The resulting layout assigns coordinates not only to the nodes of the original graph but also to the dummy nodes. The layout algorithm will also return the extended graph with the dummy nodes. For more details, see the reference below. } \examples{ ## Data taken from http://tehnick-8.narod.ru/dc_clients/ DC <- graph_from_literal("DC++" -+ "LinuxDC++":"BCDC++":"EiskaltDC++":"StrongDC++":"DiCe!++", "LinuxDC++" -+ "FreeDC++", "BCDC++" -+ "StrongDC++", "FreeDC++" -+ "BMDC++":"EiskaltDC++", "StrongDC++" -+ "AirDC++":"zK++":"ApexDC++":"TkDC++", "StrongDC++" -+ "StrongDC++ SQLite":"RSX++", "ApexDC++" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++" -+ "ApexDC++ Speed-Mod":"DiCe!++", "StrongDC++ SQLite" -+ "FlylinkDC++ ver >= 5xx", "ApexDC++ Speed-Mod" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++ Speed-Mod" -+ "GreylinkDC++", "FlylinkDC++ ver <= 4xx" -+ "FlylinkDC++ ver >= 5xx", "FlylinkDC++ ver <= 4xx" -+ AvaLink, "GreylinkDC++" -+ AvaLink:"RayLinkDC++":"SparkDC++":PeLink) ## Use edge types E(DC)$lty <- 1 E(DC)["BCDC++" \%->\% "StrongDC++"]$lty <- 2 E(DC)["FreeDC++" \%->\% "EiskaltDC++"]$lty <- 2 E(DC)["ApexDC++" \%->\% "FlylinkDC++ ver <= 4xx"]$lty <- 2 E(DC)["ApexDC++" \%->\% "DiCe!++"]$lty <- 2 E(DC)["StrongDC++ SQLite" \%->\% "FlylinkDC++ ver >= 5xx"]$lty <- 2 E(DC)["GreylinkDC++" \%->\% "AvaLink"]$lty <- 2 ## Layers, as on the plot layers <- list(c("DC++"), c("LinuxDC++", "BCDC++"), c("FreeDC++", "StrongDC++"), c("BMDC++", "EiskaltDC++", "AirDC++", "zK++", "ApexDC++", "TkDC++", "RSX++"), c("StrongDC++ SQLite", "ApexDC++ Speed-Mod", "DiCe!++"), c("FlylinkDC++ ver <= 4xx", "GreylinkDC++"), c("FlylinkDC++ ver >= 5xx", "AvaLink", "RayLinkDC++", "SparkDC++", "PeLink")) ## Check that we have all nodes all(sort(unlist(layers)) == sort(V(DC)$name)) ## Add some graphical parameters V(DC)$color <- "white" V(DC)$shape <- "rectangle" V(DC)$size <- 20 V(DC)$size2 <- 10 V(DC)$label <- lapply(V(DC)$name, function(x) paste(strwrap(x, 12), collapse="\\n")) E(DC)$arrow.size <- 0.5 ## Create a similar layout using the predefined layers lay1 <- layout_with_sugiyama(DC, layers=apply(sapply(layers, function(x) V(DC)$name \%in\% x), 1, which)) ## Simple plot, not very nice par(mar=rep(.1, 4)) plot(DC, layout=lay1$layout, vertex.label.cex=0.5) ## Sugiyama plot plot(lay1$extd_graph, vertex.label.cex=0.5) ## The same with automatic layer calculation ## Keep vertex/edge attributes in the extended graph lay2 <- layout_with_sugiyama(DC, attributes="all") plot(lay2$extd_graph, vertex.label.cex=0.5) ## Another example, from the following paper: ## Markus Eiglsperger, Martin Siebenhaller, Michael Kaufmann: ## An Efficient Implementation of Sugiyama's Algorithm for ## Layered Graph Drawing, Journal of Graph Algorithms and ## Applications 9, 305--325 (2005). ex <- graph_from_literal( 0 -+ 29: 6: 5:20: 4, 1 -+ 12, 2 -+ 23: 8, 3 -+ 4, 4, 5 -+ 2:10:14:26: 4: 3, 6 -+ 9:29:25:21:13, 7, 8 -+ 20:16, 9 -+ 28: 4, 10 -+ 27, 11 -+ 9:16, 12 -+ 9:19, 13 -+ 20, 14 -+ 10, 15 -+ 16:27, 16 -+ 27, 17 -+ 3, 18 -+ 13, 19 -+ 9, 20 -+ 4, 21 -+ 22, 22 -+ 8: 9, 23 -+ 9:24, 24 -+ 12:15:28, 25 -+ 11, 26 -+ 18, 27 -+ 13:19, 28 -+ 7, 29 -+ 25 ) layers <- list( 0, c(5, 17), c(2, 14, 26, 3), c(23, 10, 18), c(1, 24), 12, 6, c(29,21), c(25,22), c(11,8,15), 16, 27, c(13,19), c(9, 20), c(4, 28), 7 ) layex <- layout_with_sugiyama(ex, layers=apply(sapply(layers, function(x) V(ex)$name \%in\% as.character(x)), 1, which)) origvert <- c(rep(TRUE, vcount(ex)), rep(FALSE, nrow(layex$layout.dummy))) realedge <- as_edgelist(layex$extd_graph)[,2] <= vcount(ex) plot(layex$extd_graph, vertex.label.cex=0.5, edge.arrow.size=.5, vertex.size=ifelse(origvert, 5, 0), vertex.shape=ifelse(origvert, "square", "none"), vertex.label=ifelse(origvert, V(ex)$name, ""), edge.arrow.mode=ifelse(realedge, 2, 0)) } \references{ K. Sugiyama, S. Tagawa and M. Toda, "Methods for Visual Understanding of Hierarchical Systems". IEEE Transactions on Systems, Man and Cybernetics 11(2):109-125, 1981. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/isomorphism_class.Rd0000644000175100001440000000240413430770476016355 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{isomorphism_class} \alias{isomorphism_class} \alias{graph.isoclass} \alias{graph.isoclass.subgraph} \title{Isomorphism class of a graph} \usage{ isomorphism_class(graph, v) } \arguments{ \item{graph}{The input graph.} \item{v}{Optionally a vertex sequence. If not missing, then an induced subgraph of the input graph, consisting of this vertices, is used.} } \value{ An integer number. } \description{ The isomorphism class is a non-negative integer number. Graphs (with the same number of vertices) having the same isomorphism class are isomorphic and isomorphic graphs always have the same isomorphism class. Currently it can handle only graphs with 3 or 4 vertices. } \examples{ # create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphism_class(g1) isomorphism_class(g2) isomorphic(g1, g2) } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/union.Rd0000644000175100001440000000120013430770475013737 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{union} \alias{union} \title{Union of two or more sets} \usage{ union(...) } \arguments{ \item{...}{Arguments, their number and interpretation depends on the function that implements \code{union}.} } \value{ Depends on the function that implements this method. } \description{ This is an S3 generic function. See \code{methods("union")} for the actual implementations for various S3 classes. Initially it is implemented for igraph graphs and igraph vertex and edge sequences. See \code{\link{union.igraph}}, and \code{\link{union.igraph.vs}}. } igraph/man/edge.Rd0000644000175100001440000000306013430770475013521 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{edge} \alias{edge} \alias{edges} \title{Helper function for adding and deleting edges} \usage{ edge(...) edges(...) } \arguments{ \item{...}{See details below.} } \value{ A special object that can be used with together with igraph graphs and the plus and minus operators. } \description{ This is a helper function that simplifies adding and deleting edges to/from graphs. } \details{ \code{edges} is an alias for \code{edge}. When adding edges via \code{+}, all unnamed arguments of \code{edge} (or \code{edges}) are concatenated, and then passed to \code{\link{add_edges}}. They are interpreted as pairs of vertex ids, and an edge will added between each pair. Named arguments will be used as edge attributes for the new edges. When deleting edges via \code{-}, all arguments of \code{edge} (or \code{edges}) are concatenated via \code{c()} and passed to \code{\link{delete_edges}}. } \examples{ g <- make_ring(10) \%>\% set_edge_attr("color", value = "red") g <- g + edge(1, 5, color = "green") + edge(2, 6, color = "blue") - edge("8|9") E(g)[[]] g \%>\% add_layout_(in_circle()) \%>\% plot() g <- make_ring(10) + edges(1:10) plot(g) } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/add_layout_.Rd0000644000175100001440000000256213430770475015107 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{add_layout_} \alias{add_layout_} \title{Add layout to graph} \usage{ add_layout_(graph, ..., overwrite = TRUE) } \arguments{ \item{graph}{The input graph.} \item{...}{Additional arguments are passed to \code{\link{layout_}}.} \item{overwrite}{Whether to overwrite the layout of the graph, if it already has one.} } \value{ The input graph, with the layout added. } \description{ Add layout to graph } \examples{ (make_star(11) + make_star(11)) \%>\% add_layout_(as_star(), component_wise()) \%>\% plot() } \seealso{ \code{\link{layout_}} for a description of the layout API. Other graph layouts: \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \concept{graph layouts} igraph/man/gsize.Rd0000644000175100001440000000165413430770475013745 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{gsize} \alias{gsize} \alias{ecount} \title{The size of the graph (number of edges)} \usage{ gsize(graph) } \arguments{ \item{graph}{The graph.} } \value{ Numeric scalar, the number of edges. } \description{ \code{ecount} of an alias of this function. } \examples{ g <- sample_gnp(100, 2/100) gsize(g) # Number of edges in a G(n,p) graph replicate(100, sample_gnp(10, 1/2), simplify = FALSE) \%>\% vapply(gsize, 0) \%>\% hist() } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/scg-method.Rd0000644000175100001440000000421313430770476014651 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{scg-method} \alias{scg-method} \title{Spectral Coarse Graining} \description{ Functions to perform the Spectral Coarse Graining (SCG) of matrices and graphs. } \section{Introduction}{ The SCG functions provide a framework, called Spectral Coarse Graining (SCG), for reducing large graphs while preserving their \emph{spectral-related features}, that is features closely related with the eigenvalues and eigenvectors of a graph matrix (which for now can be the adjacency, the stochastic, or the Laplacian matrix). Common examples of such features comprise the first-passage-time of random walkers on Markovian graphs, thermodynamic properties of lattice models in statistical physics (e.g. Ising model), and the epidemic threshold of epidemic network models (SIR and SIS models). SCG differs from traditional clustering schemes by producing a \emph{coarse-grained graph} (not just a partition of the vertices), representative of the original one. As shown in [1], Principal Component Analysis can be viewed as a particular SCG, called \emph{exact SCG}, where the matrix to be coarse-grained is the covariance matrix of some data set. SCG should be of interest to practitioners of various fields dealing with problems where matrix eigenpairs play an important role, as for instance is the case of dynamical processes on networks. } \references{ D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, Shrinking Matrices while Preserving their Eigenpairs with Application to the Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on Matrix Analysis and Applications}, 2008. \url{http://people.epfl.ch/david.morton} D. Gfeller, and P. De Los Rios, Spectral Coarse Graining and Synchronization in Oscillator Networks. \emph{Physical Review Letters}, \bold{100}(17), 2008. \url{http://arxiv.org/abs/0708.2055} D. Gfeller, and P. De Los Rios, Spectral Coarse Graining of Complex Networks, \emph{Physical Review Letters}, \bold{99}(3), 2007. \url{http://arxiv.org/abs/0706.0812} } \author{ David Morton de Lachapelle, \url{http://people.epfl.ch/david.morton}. } \keyword{graphs} igraph/man/hrg.Rd0000644000175100001440000000203113430770475013372 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{hrg} \alias{hrg} \alias{hrg.create} \title{Create a hierarchical random graph from an igraph graph} \usage{ hrg(graph, prob) } \arguments{ \item{graph}{The igraph graph to create the HRG from.} \item{prob}{A vector of probabilities, one for each vertex, in the order of vertex ids.} } \value{ \code{hrg} returns an \code{igraphHRG} object. } \description{ \code{hrg} creates a HRG from an igraph graph. The igraph graph must be a directed binary tree, with \eqn{n-1} internal and \eqn{n} leaf vertices. The \code{prob} argument contains the HRG probability labels for each vertex; these are ignored for leaf vertices. } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/vertex.Rd0000644000175100001440000000246613430770475014143 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{vertex} \alias{vertex} \alias{vertices} \title{Helper function for adding and deleting vertices} \usage{ vertex(...) vertices(...) } \arguments{ \item{...}{See details below.} } \value{ A special object that can be used with together with igraph graphs and the plus and minus operators. } \description{ This is a helper function that simplifies adding and deleting vertices to/from graphs. } \details{ \code{vertices} is an alias for \code{vertex}. When adding vertices via \code{+}, all unnamed arguments are interpreted as vertex names of the new vertices. Named arguments are interpreted as vertex attributes for the new vertices. When deleting vertices via \code{-}, all arguments of \code{vertex} (or \code{vertices}) are concatenated via \code{c()} and passed to \code{\link{delete_vertices}}. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) + vertices('X', 'Y') g plot(g) } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}} } \concept{functions for manipulating graph structure} igraph/man/cluster_spinglass.Rd0000644000175100001440000001524713430770475016373 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_spinglass} \alias{cluster_spinglass} \alias{spinglass.community} \title{Finding communities in graphs based on statistical meachanics} \usage{ cluster_spinglass(graph, weights = NULL, vertex = NULL, spins = 25, parupdate = FALSE, start.temp = 1, stop.temp = 0.01, cool.fact = 0.99, update.rule = c("config", "random", "simple"), gamma = 1, implementation = c("orig", "neg"), gamma.minus = 1) } \arguments{ \item{graph}{The input graph, can be directed but the direction of the edges is neglected.} \item{weights}{The weights of the edges. Either a numeric vector or \code{NULL}. If it is null and the input graph has a \sQuote{weight} edge attribute then that will be used. If \code{NULL} and no such attribute is present then the edges will have equal weights. Set this to \code{NA} if the graph was a \sQuote{weight} edge attribute, but you don't want to use it for community detection. A larger edge weight means a stronger connection for this function.} \item{vertex}{This parameter can be used to calculate the community of a given vertex without calculating all communities. Note that if this argument is present then some other arguments are ignored.} \item{spins}{Integer constant, the number of spins to use. This is the upper limit for the number of communities. It is not a problem to supply a (reasonably) big number here, in which case some spin states will be unpopulated.} \item{parupdate}{Logical constant, whether to update the spins of the vertices in parallel (synchronously) or not. This argument is ignored if the second form of the function is used (ie. the \sQuote{\code{vertex}} argument is present). It is also not implemented in the \dQuote{neg} implementation.} \item{start.temp}{Real constant, the start temperature. This argument is ignored if the second form of the function is used (ie. the \sQuote{\code{vertex}} argument is present).} \item{stop.temp}{Real constant, the stop temperature. The simulation terminates if the temperature lowers below this level. This argument is ignored if the second form of the function is used (ie. the \sQuote{\code{vertex}} argument is present).} \item{cool.fact}{Cooling factor for the simulated annealing. This argument is ignored if the second form of the function is used (ie. the \sQuote{\code{vertex}} argument is present).} \item{update.rule}{Character constant giving the \sQuote{null-model} of the simulation. Possible values: \dQuote{simple} and \dQuote{config}. \dQuote{simple} uses a random graph with the same number of edges as the baseline probability and \dQuote{config} uses a random graph with the same vertex degrees as the input graph.} \item{gamma}{Real constant, the gamma argument of the algorithm. This specifies the balance between the importance of present and non-present edges in a community. Roughly, a comunity is a set of vertices having many edges inside the community and few edges outside the community. The default 1.0 value makes existing and non-existing links equally important. Smaller values make the existing links, greater values the missing links more important.} \item{implementation}{Character scalar. Currently igraph contains two implementations for the Spin-glass community finding algorithm. The faster original implementation is the default. The other implementation, that takes into account negative weights, can be chosen by supplying \sQuote{neg} here.} \item{gamma.minus}{Real constant, the gamma.minus parameter of the algorithm. This specifies the balance between the importance of present and non-present negative weighted edges in a community. Smaller values of gamma.minus, leads to communities with lesser negative intra-connectivity. If this argument is set to zero, the algorithm reduces to a graph coloring algorithm, using the number of spins as the number of colors. This argument is ignored if the \sQuote{orig} implementation is chosen.} } \value{ If the \code{vertex} argument is not given, ie. the first form is used then a \code{\link{cluster_spinglass}} returns a \code{\link{communities}} object. If the \code{vertex} argument is present, ie. the second form is used then a named list is returned with the following components: \item{community}{Numeric vector giving the ids of the vertices in the same community as \code{vertex}.} \item{cohesion}{The cohesion score of the result, see references.} \item{adhesion}{The adhesion score of the result, see references.} \item{inner.links}{The number of edges within the community of \code{vertex}.} \item{outer.links}{The number of edges between the community of \code{vertex} and the rest of the graph. } } \description{ This function tries to find communities in graphs via a spin-glass model and simulated annealing. } \details{ This function tries to find communities in a graph. A community is a set of nodes with many edges inside the community and few edges between outside it (i.e. between the community itself and the rest of the graph.) This idea is reversed for edges having a negative weight, ie. few negative edges inside a community and many negative edges between communities. Note that only the \sQuote{neg} implementation supports negative edge weights. The \code{spinglass.cummunity} function can solve two problems related to community detection. If the \code{vertex} argument is not given (or it is \code{NULL}), then the regular community detection problem is solved (approximately), i.e. partitioning the vertices into communities, by optimizing the an energy function. If the \code{vertex} argument is given and it is not \code{NULL}, then it must be a vertex id, and the same energy function is used to find the community of the the given vertex. See also the examples below. } \examples{ g <- sample_gnp(10, 5/10) \%du\% sample_gnp(9, 5/9) g <- add_edges(g, c(1, 12)) g <- induced_subgraph(g, subcomponent(g, 1)) cluster_spinglass(g, spins=2) cluster_spinglass(g, vertex=1) } \references{ J. Reichardt and S. Bornholdt: Statistical Mechanics of Community Detection, \emph{Phys. Rev. E}, 74, 016110 (2006), \url{http://arxiv.org/abs/cond-mat/0603718} M. E. J. Newman and M. Girvan: Finding and evaluating community structure in networks, \emph{Phys. Rev. E} 69, 026113 (2004) V.A. Traag and Jeroen Bruggeman: Community detection in networks with positive and negative links, \url{http://arxiv.org/abs/0811.2329} (2008). } \seealso{ \code{\link{communities}}, \code{\link{components}} } \author{ Jorg Reichardt for the original code and Gabor Csardi \email{csardi.gabor@gmail.com} for the igraph glue code. Changes to the original function for including the possibility of negative ties were implemented by Vincent Traag (\url{http://www.traag.net/}). } \keyword{graphs} igraph/man/which_multiple.Rd0000644000175100001440000000457013430770476015642 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{which_multiple} \alias{which_multiple} \alias{has.multiple} \alias{is.loop} \alias{is.multiple} \alias{count.multiple} \alias{count_multiple} \alias{any_multiple} \alias{which_loop} \title{Find the multiple or loop edges in a graph} \usage{ which_multiple(graph, eids = E(graph)) } \arguments{ \item{graph}{The input graph.} \item{eids}{The edges to which the query is restricted. By default this is all edges in the graph.} } \value{ \code{any_multiple} returns a logical scalar. \code{which_loop} and \code{which_multiple} return a logical vector. \code{count_multiple} returns a numeric vector. } \description{ A loop edge is an edge from a vertex to itself. An edge is a multiple edge if it has exactly the same head and tail vertices as another edge. A graph without multiple and loop edges is called a simple graph. } \details{ \code{which_loop} decides whether the edges of the graph are loop edges. \code{any_multiple} decides whether the graph has any multiple edges. \code{which_multiple} decides whether the edges of the graph are multiple edges. \code{count_multiple} counts the multiplicity of each edge of a graph. Note that the semantics for \code{which_multiple} and \code{count_multiple} is different. \code{which_multiple} gives \code{TRUE} for all occurences of a multiple edge except for one. Ie. if there are three \code{i-j} edges in the graph then \code{which_multiple} returns \code{TRUE} for only two of them while \code{count_multiple} returns \sQuote{3} for all three. See the examples for getting rid of multiple edges while keeping their original multiplicity as an edge attribute. } \examples{ # Loops g <- graph( c(1,1,2,2,3,3,4,5) ) which_loop(g) # Multiple edges g <- barabasi.game(10, m=3, algorithm="bag") any_multiple(g) which_multiple(g) count_multiple(g) which_multiple(simplify(g)) all(count_multiple(simplify(g)) == 1) # Direction of the edge is important which_multiple(graph( c(1,2, 2,1) )) which_multiple(graph( c(1,2, 2,1), dir=FALSE )) # Remove multiple edges but keep multiplicity g <- barabasi.game(10, m=3, algorithm="bag") E(g)$weight <- count_multiple(g) g <- simplify(g) any(which_multiple(g)) E(g)$weight } \seealso{ \code{\link{simplify}} to eliminate loop and multiple edges. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/write_graph.Rd0000644000175100001440000000311513430770475015131 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/foreign.R \name{write_graph} \alias{write_graph} \alias{write.graph} \title{Writing the graph to a file in some format} \usage{ write_graph(graph, file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ...) } \arguments{ \item{graph}{The graph to export.} \item{file}{A connection or a string giving the file name to write the graph to.} \item{format}{Character string giving the file format. Right now \code{pajek}, \code{graphml}, \code{dot}, \code{gml}, \code{edgelist}, \code{lgl}, \code{ncol} and \code{dimacs} are implemented. As of igraph 0.4 this argument is case insensitive.} \item{\dots}{Other, format specific arguments, see below.} } \value{ A NULL, invisibly. } \description{ \code{write_graph} is a general function for exporting graphs to foreign file formats, however not many formats are implemented right now. } \section{Edge list format}{ The \code{edgelist} format is a simple text file, with one edge in a line, the two vertex ids separated by a space character. The file is sorted by the first and the second column. This format has no additional arguments. } \examples{ g <- make_ring(10) \dontrun{write_graph(g, "/tmp/g.txt", "edgelist")} } \references{ Adai AT, Date SV, Wieland S, Marcotte EM. LGL: creating a map of protein function with an algorithm for visualizing very large biological networks. \emph{J Mol Biol.} 2004 Jun 25;340(1):179-90. } \seealso{ \code{\link{read_graph}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_lattice.Rd0000644000175100001440000000352613430770475015246 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_lattice} \alias{make_lattice} \alias{graph.lattice} \alias{lattice} \title{Create a lattice graph} \usage{ make_lattice(dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, circular = FALSE) lattice(...) } \arguments{ \item{dimvector}{A vector giving the size of the lattice in each dimension.} \item{length}{Integer constant, for regular lattices, the size of the lattice in each dimension.} \item{dim}{Integer constant, the dimension of the lattice.} \item{nei}{The distance within which (inclusive) the neighbors on the lattice will be connected. This parameter is not used right now.} \item{directed}{Whether to create a directed lattice.} \item{mutual}{Logical, if \code{TRUE} directed lattices will be mutually connected.} \item{circular}{Logical, if \code{TRUE} the lattice or ring will be circular.} \item{...}{Passed to \code{make_lattice}.} } \value{ An igraph graph. } \description{ \code{make_lattice} is a flexible function, it can create lattices of arbitrary dimensions, periodic or unperiodic ones. It has two forms. In the first form you only supply \code{dimvector}, but not \code{length} and \code{dim}. In the second form you omit \code{dimvector} and supply \code{length} and \code{dim}. } \examples{ make_lattice(c(5, 5, 5)) make_lattice(length = 5, dim = 3) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{Lattice} \concept{determimistic constructors} igraph/man/transitivity.Rd0000644000175100001440000001143013430770476015367 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{transitivity} \alias{transitivity} \title{Transitivity of a graph} \usage{ transitivity(graph, type = c("undirected", "global", "globalundirected", "localundirected", "local", "average", "localaverage", "localaverageundirected", "barrat", "weighted"), vids = NULL, weights = NULL, isolates = c("NaN", "zero")) } \arguments{ \item{graph}{The graph to analyze.} \item{type}{The type of the transitivity to calculate. Possible values: \describe{ \item{"global"}{The global transitivity of an undirected graph (directed graphs are considered as undirected ones as well). This is simply the ratio of the triangles and the connected triples in the graph. For directed graph the direction of the edges is ignored. } \item{"local"}{The local transitivity of an undirected graph, this is calculated for each vertex given in the \code{vids} argument. The local transitivity of a vertex is the ratio of the triangles connected to the vertex and the triples centered on the vertex. For directed graph the direction of the edges is ignored. } \item{"undirected"}{This is the same as \code{global}.} \item{"globalundirected"}{This is the same as \code{global}.} \item{"localundirected"}{This is the same as \code{local}.} \item{"barrat"}{The weighted transitivity as defined A. Barrat. See details below.} \item{"weighted"}{The same as \code{barrat}.} }} \item{vids}{The vertex ids for the local transitivity will be calculated. This will be ignored for global transitivity types. The default value is \code{NULL}, in this case all vertices are considered. It is slightly faster to supply \code{NULL} here than \code{V(graph)}.} \item{weights}{Optional weights for weighted transitivity. It is ignored for other transitivity measures. If it is \code{NULL} (the default) and the graph has a \code{weight} edge attribute, then it is used automatically.} \item{isolates}{Character scalar, defines how to treat vertices with degree zero and one. If it is \sQuote{\code{NaN}} then they local transitivity is reported as \code{NaN} and they are not included in the averaging, for the transitivity types that calculate an average. If there are no vertices with degree two or higher, then the averaging will still result \code{NaN}. If it is \sQuote{\code{zero}}, then we report 0 transitivity for them, and they are included in the averaging, if an average is calculated.} } \value{ For \sQuote{\code{global}} a single number, or \code{NaN} if there are no connected triples in the graph. For \sQuote{\code{local}} a vector of transitivity scores, one for each vertex in \sQuote{\code{vids}}. } \description{ Transitivity measures the probability that the adjacent vertices of a vertex are connected. This is sometimes also called the clustering coefficient. } \details{ Note that there are essentially two classes of transitivity measures, one is a vertex-level, the other a graph level property. There are several generalizations of transitivity to weighted graphs, here we use the definition by A. Barrat, this is a local vertex-level quantity, its formula is \deqn{C_i^w=\frac{1}{s_i(k_i-1)}\sum_{j,h}\frac{w_{ij}+w_{ih}}{2}a_{ij}a_{ih}a_{jh}}{ weighted C_i = 1/s_i 1/(k_i-1) sum( (w_ij+w_ih)/2 a_ij a_ih a_jh, j, h)} \eqn{s_i}{s_i} is the strength of vertex \eqn{i}{i}, see \code{\link{strength}}, \eqn{a_{ij}}{a_ij} are elements of the adjacency matrix, \eqn{k_i}{k_i} is the vertex degree, \eqn{w_{ij}}{w_ij} are the weights. This formula gives back the normal not-weighted local transitivity if all the edge weights are the same. The \code{barrat} type of transitivity does not work for graphs with multiple and/or loop edges. If you want to calculate it for a directed graph, call \code{\link{as.undirected}} with the \code{collapse} mode first. } \examples{ g <- make_ring(10) transitivity(g) g2 <- sample_gnp(1000, 10/1000) transitivity(g2) # this is about 10/1000 # Weighted version, the figure from the Barrat paper gw <- graph_from_literal(A-B:C:D:E, B-C:D, C-D) E(gw)$weight <- 1 E(gw)[ V(gw)[name == "A"] \%--\% V(gw)[name == "E" ] ]$weight <- 5 transitivity(gw, vids="A", type="local") transitivity(gw, vids="A", type="weighted") # Weighted reduces to "local" if weights are the same gw2 <- sample_gnp(1000, 10/1000) E(gw2)$weight <- 1 t1 <- transitivity(gw2, type="local") t2 <- transitivity(gw2, type="weighted") all(is.na(t1) == is.na(t2)) all(na.omit(t1 == t2)) } \references{ Wasserman, S., and Faust, K. (1994). \emph{Social Network Analysis: Methods and Applications.} Cambridge: Cambridge University Press. Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/power_centrality.Rd0000644000175100001440000001320113430770476016206 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{power_centrality} \alias{power_centrality} \alias{bonpow} \title{Find Bonacich Power Centrality Scores of Network Positions} \usage{ power_centrality(graph, nodes = V(graph), loops = FALSE, exponent = 1, rescale = FALSE, tol = 1e-07, sparse = TRUE) } \arguments{ \item{graph}{the input graph.} \item{nodes}{vertex sequence indicating which vertices are to be included in the calculation. By default, all vertices are included.} \item{loops}{boolean indicating whether or not the diagonal should be treated as valid data. Set this true if and only if the data can contain loops. \code{loops} is \code{FALSE} by default.} \item{exponent}{exponent (decay rate) for the Bonacich power centrality score; can be negative} \item{rescale}{if true, centrality scores are rescaled such that they sum to 1.} \item{tol}{tolerance for near-singularities during matrix inversion (see \code{\link{solve}})} \item{sparse}{Logical scalar, whether to use sparse matrices for the calculation. The \sQuote{Matrix} package is required for sparse matrix support} } \value{ A vector, containing the centrality scores. } \description{ \code{power_centrality} takes a graph (\code{dat}) and returns the Boncich power centralities of positions (selected by \code{nodes}). The decay rate for power contributions is specified by \code{exponent} (1 by default). } \details{ Bonacich's power centrality measure is defined by \eqn{C_{BP}\left(\alpha,\beta\right)=\alpha\left(\mathbf{I}-\beta\mathbf{A}\right)^{-1}\mathbf{A}\mathbf{1}}{C_BP(alpha,beta)=alpha (I-beta A)^-1 A 1}, where \eqn{\beta}{beta} is an attenuation parameter (set here by \code{exponent}) and \eqn{\mathbf{A}}{A} is the graph adjacency matrix. (The coefficient \eqn{\alpha}{alpha} acts as a scaling parameter, and is set here (following Bonacich (1987)) such that the sum of squared scores is equal to the number of vertices. This allows 1 to be used as a reference value for the ``middle'' of the centrality range.) When \eqn{\beta \rightarrow }{beta->1/lambda_A1}\eqn{ 1/\lambda_{\mathbf{A}1}}{beta->1/lambda_A1} (the reciprocal of the largest eigenvalue of \eqn{\mathbf{A}}{A}), this is to within a constant multiple of the familiar eigenvector centrality score; for other values of \eqn{\beta}, the behavior of the measure is quite different. In particular, \eqn{\beta} gives positive and negative weight to even and odd walks, respectively, as can be seen from the series expansion \eqn{C_{BP}\left(\alpha,\beta\right)=\alpha \sum_{k=0}^\infty \beta^k }{C_BP(alpha,beta) = alpha sum( beta^k A^(k+1) 1, k in 0..infinity )}\eqn{ \mathbf{A}^{k+1} \mathbf{1}}{C_BP(alpha,beta) = alpha sum( beta^k A^(k+1) 1, k in 0..infinity )} which converges so long as \eqn{|\beta| }{|beta|<1/lambda_A1}\eqn{ < 1/\lambda_{\mathbf{A}1}}{|beta|<1/lambda_A1}. The magnitude of \eqn{\beta}{beta} controls the influence of distant actors on ego's centrality score, with larger magnitudes indicating slower rates of decay. (High rates, hence, imply a greater sensitivity to edge effects.) Interpretively, the Bonacich power measure corresponds to the notion that the power of a vertex is recursively defined by the sum of the power of its alters. The nature of the recursion involved is then controlled by the power exponent: positive values imply that vertices become more powerful as their alters become more powerful (as occurs in cooperative relations), while negative values imply that vertices become more powerful only as their alters become \emph{weaker} (as occurs in competitive or antagonistic relations). The magnitude of the exponent indicates the tendency of the effect to decay across long walks; higher magnitudes imply slower decay. One interesting feature of this measure is its relative instability to changes in exponent magnitude (particularly in the negative case). If your theory motivates use of this measure, you should be very careful to choose a decay parameter on a non-ad hoc basis. } \note{ This function was ported (ie. copied) from the SNA package. } \section{Warning }{ Singular adjacency matrices cause no end of headaches for this algorithm; thus, the routine may fail in certain cases. This will be fixed when I get a better algorithm. \code{power_centrality} will not symmetrize your data before extracting eigenvectors; don't send this routine asymmetric matrices unless you really mean to do so. } \examples{ # Generate some test data from Bonacich, 1987: g.c <- graph( c(1,2,1,3,2,4,3,5), dir=FALSE) g.d <- graph( c(1,2,1,3,1,4,2,5,3,6,4,7), dir=FALSE) g.e <- graph( c(1,2,1,3,1,4,2,5,2,6,3,7,3,8,4,9,4,10), dir=FALSE) g.f <- graph( c(1,2,1,3,1,4,2,5,2,6,2,7,3,8,3,9,3,10,4,11,4,12,4,13), dir=FALSE) # Compute power centrality scores for (e in seq(-0.5,.5, by=0.1)) { print(round(power_centrality(g.c, exp=e)[c(1,2,4)], 2)) } for (e in seq(-0.4,.4, by=0.1)) { print(round(power_centrality(g.d, exp=e)[c(1,2,5)], 2)) } for (e in seq(-0.4,.4, by=0.1)) { print(round(power_centrality(g.e, exp=e)[c(1,2,5)], 2)) } for (e in seq(-0.4,.4, by=0.1)) { print(round(power_centrality(g.f, exp=e)[c(1,2,5)], 2)) } } \references{ Bonacich, P. (1972). ``Factoring and Weighting Approaches to Status Scores and Clique Identification.'' \emph{Journal of Mathematical Sociology}, 2, 113-120. Bonacich, P. (1987). ``Power and Centrality: A Family of Measures.'' \emph{American Journal of Sociology}, 92, 1170-1182. } \seealso{ \code{\link{eigen_centrality}} and \code{\link{alpha_centrality}} } \author{ Carter T. Butts (\url{http://www.faculty.uci.edu/profile.cfm?faculty_id=5057}), ported to igraph by Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/srand.Rd0000644000175100001440000000060213430770475013723 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/other.R \name{srand} \alias{srand} \title{Deprecated function, used to set random seed of the C library's RNG} \usage{ srand(seed) } \arguments{ \item{seed}{Ignored.} } \description{ Deprecated function, used to set random seed of the C library's RNG } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } igraph/man/upgrade_graph.Rd0000644000175100001440000000145313430770476015432 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/versions.R \name{upgrade_graph} \alias{upgrade_graph} \title{Igraph data structure versions} \usage{ upgrade_graph(graph) } \arguments{ \item{graph}{The input graph.} } \value{ The graph in the current format. } \description{ Igraph's internal data representation changes sometimes between versions. This means that it is not possible to use igraph objects that were created (and possibly saved to a file) with an older igraph version. } \details{ \code{\link{graph_version}} queries the current data format, or the data format of a possibly older igraph graph. \code{upgrade_graph} can convert an older data format to the current one. } \seealso{ graph_version to check the current data format version or the version of a graph. } igraph/man/sample_dot_product.Rd0000644000175100001440000000330413430770475016505 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_dot_product} \alias{sample_dot_product} \alias{dot_product} \title{Generate random graphs according to the random dot product graph model} \usage{ sample_dot_product(vecs, directed = FALSE) } \arguments{ \item{vecs}{A numeric matrix in which each latent position vector is a column.} \item{directed}{A logical scalar, TRUE if the generated graph should be directed.} \item{\dots}{Passed to \code{sample_dot_product}.} } \value{ An igraph graph object which is the generated random dot product graph. } \description{ In this model, each vertex is represented by a latent position vector. Probability of an edge between two vertices are given by the dot product of their latent position vectors. } \details{ The dot product of the latent position vectors should be in the [0,1] interval, otherwise a warning is given. For negative dot products, no edges are added; dot products that are larger than one always add an edge. } \examples{ ## A randomly generated graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) g <- sample_dot_product(lpvs) g ## Sample latent vectors from the surface of the unit sphere lpvs2 <- sample_sphere_surface(dim=5, n=20) g2 <- sample_dot_product(lpvs2) g2 } \references{ Christine Leigh Myers Nickel: Random dot product graphs, a model for social networks. Dissertation, Johns Hopkins University, Maryland, USA, 2006. } \seealso{ \code{\link{sample_dirichlet}}, \code{\link{sample_sphere_surface}} and \code{\link{sample_sphere_volume}} for sampling position vectors. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout.spring.Rd0000644000175100001440000000065613430770475015443 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout.spring} \alias{layout.spring} \title{Spring layout, this was removed from igraph} \usage{ layout.spring(graph, ...) } \arguments{ \item{graph}{Input graph.} \item{...}{Extra arguments are ignored.} } \value{ Layout coordinates, a two column matrix. } \description{ Now it calls the Fruchterman-Reingold layout, with a warning. } igraph/man/sample_smallworld.Rd0000644000175100001440000000324613430770475016344 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_smallworld} \alias{sample_smallworld} \alias{watts.strogatz.game} \alias{smallworld} \title{The Watts-Strogatz small-world model} \usage{ sample_smallworld(dim, size, nei, p, loops = FALSE, multiple = FALSE) smallworld(...) } \arguments{ \item{dim}{Integer constant, the dimension of the starting lattice.} \item{size}{Integer constant, the size of the lattice along each dimension.} \item{nei}{Integer constant, the neighborhood within which the vertices of the lattice will be connected.} \item{p}{Real constant between zero and one, the rewiring probability.} \item{loops}{Logical scalar, whether loops edges are allowed in the generated graph.} \item{multiple}{Logical scalar, whether multiple edges are allowed int the generated graph.} \item{...}{Passed to \code{sample_smallworld}.} } \value{ A graph object. } \description{ Generate a graph according to the Watts-Strogatz network model. } \details{ First a lattice is created with the given \code{dim}, \code{size} and \code{nei} arguments. Then the edges of the lattice are rewired uniformly randomly with probability \code{p}. Note that this function might create graphs with loops and/or multiple edges. You can use \code{\link{simplify}} to get rid of these. } \examples{ g <- sample_smallworld(1, 100, 5, 0.05) mean_distance(g) transitivity(g, type="average") } \references{ Duncan J Watts and Steven H Strogatz: Collective dynamics of \sQuote{small world} networks, Nature 393, 440-442, 1998. } \seealso{ \code{\link{make_lattice}}, \code{\link{rewire}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_bipartite.Rd0000644000175100001440000000444213430770475016146 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_bipartite} \alias{sample_bipartite} \alias{bipartite.random.game} \alias{bipartite} \title{Bipartite random graphs} \usage{ sample_bipartite(n1, n2, type = c("gnp", "gnm"), p, m, directed = FALSE, mode = c("out", "in", "all")) bipartite(...) } \arguments{ \item{n1}{Integer scalar, the number of bottom vertices.} \item{n2}{Integer scalar, the number of top vertices.} \item{type}{Character scalar, the type of the graph, \sQuote{gnp} creates a $G(n,p)$ graph, \sQuote{gnm} creates a $G(n,m)$ graph. See details below.} \item{p}{Real scalar, connection probability for $G(n,p)$ graphs. Should not be given for $G(n,m)$ graphs.} \item{m}{Integer scalar, the number of edges for $G(n,p)$ graphs. Should not be given for $G(n,p)$ graphs.} \item{directed}{Logical scalar, whether to create a directed graph. See also the \code{mode} argument.} \item{mode}{Character scalar, specifies how to direct the edges in directed graphs. If it is \sQuote{out}, then directed edges point from bottom vertices to top vertices. If it is \sQuote{in}, edges point from top vertices to bottom vertices. \sQuote{out} and \sQuote{in} do not generate mutual edges. If this argument is \sQuote{all}, then each edge direction is considered independently and mutual edges might be generated. This argument is ignored for undirected graphs.} \item{...}{Passed to \code{sample_bipartite}.} } \value{ A bipartite igraph graph. } \description{ Generate bipartite graphs using the Erdos-Renyi model } \details{ Similarly to unipartite (one-mode) networks, we can define the $G(n,p)$, and $G(n,m)$ graph classes for bipartite graphs, via their generating process. In $G(n,p)$ every possible edge between top and bottom vertices is realized with probablity $p$, independently of the rest of the edges. In $G(n,m)$, we uniformly choose $m$ edges to realize. } \examples{ ## empty graph sample_bipartite(10, 5, p=0) ## full graph sample_bipartite(10, 5, p=1) ## random bipartite graph sample_bipartite(10, 5, p=.1) ## directed bipartite graph, G(n,m) sample_bipartite(10, 5, type="Gnm", m=20, directed=TRUE, mode="all") } \seealso{ \code{\link{sample_gnp}} for the unipartite version. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_line_graph.Rd0000644000175100001440000000257513430770475015734 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_line_graph} \alias{make_line_graph} \alias{line.graph} \alias{line_graph} \title{Line graph of a graph} \usage{ make_line_graph(graph) line_graph(...) } \arguments{ \item{graph}{The input graph, it can be directed or undirected.} \item{...}{Passed to \code{make_line_graph}.} } \value{ A new graph object. } \description{ This function calculates the line graph of another graph. } \details{ The line graph \code{L(G)} of a \code{G} undirected graph is defined as follows. \code{L(G)} has one vertex for each edge in \code{G} and two vertices in \code{L(G)} are connected by an edge if their corresponding edges share an end point. The line graph \code{L(G)} of a \code{G} directed graph is slightly different, \code{L(G)} has one vertex for each edge in \code{G} and two vertices in \code{L(G)} are connected by a directed edge if the target of the first vertex's corresponding edge is the same as the source of the second vertex's corresponding edge. } \examples{ # generate the first De-Bruijn graphs g <- make_full_graph(2, directed=TRUE, loops=TRUE) make_line_graph(g) make_line_graph(make_line_graph(g)) make_line_graph(make_line_graph(make_line_graph(g))) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com}, the first version of the C code was written by Vincent Matossian. } \keyword{graphs} igraph/man/head_of.Rd0000644000175100001440000000165213430770475014207 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/basic.R \name{head_of} \alias{head_of} \title{Head of the edge(s) in a graph} \usage{ head_of(graph, es) } \arguments{ \item{graph}{The input graph.} \item{es}{The edges to query.} } \value{ A vertex sequence with the head(s) of the edge(s). } \description{ For undirected graphs, head and tail is not defined. In this case \code{head_of} returns vertices incident to the supplied edges, and \code{tail_of} returns the other end(s) of the edge(s). } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/delete_vertices.Rd0000644000175100001440000000161513430770475015767 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{delete_vertices} \alias{delete_vertices} \alias{delete.vertices} \title{Delete vertices from a graph} \usage{ delete_vertices(graph, v) } \arguments{ \item{graph}{The input graph.} \item{v}{The vertices to remove, a vertex sequence.} } \value{ The graph, with the vertices removed. } \description{ Delete vertices from a graph } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) g V(g) g2 <- delete_vertices(g, c(1,5)) \%>\% delete_vertices("B") g2 V(g2) } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/with_edge_.Rd0000644000175100001440000000125213430770475014714 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{with_edge_} \alias{with_edge_} \title{Constructor modifier to add edge attributes} \usage{ with_edge_(...) } \arguments{ \item{...}{The attributes to add. They must be named.} } \description{ Constructor modifier to add edge attributes } \examples{ make_(ring(10), with_edge_( color = "red", weight = rep(1:2, 5))) \%>\% plot() } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_graph_}}, \code{\link{with_vertex_}}, \code{\link{without_attr}}, \code{\link{without_loops}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/difference.igraph.vs.Rd0000644000175100001440000000265013430770475016613 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{difference.igraph.vs} \alias{difference.igraph.vs} \title{Difference of vertex sequences} \usage{ \method{difference}{igraph.vs}(big, small, ...) } \arguments{ \item{big}{The \sQuote{big} vertex sequence.} \item{small}{The \sQuote{small} vertex sequence.} \item{...}{Ignored, included for S3 signature compatibility.} } \value{ A vertex sequence that contains only vertices that are part of \code{big}, but not part of \code{small}. } \description{ Difference of vertex sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of vertices is lost in the result. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/igraph-es-attributes.Rd0000644000175100001440000000530613430770475016665 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-es-attributes} \alias{igraph-es-attributes} \alias{[[<-.igraph.es} \alias{[<-.igraph.es} \alias{$.igraph.es} \alias{$<-.igraph.es} \alias{E<-} \title{Query or set attributes of the edges in an edge sequence} \usage{ \method{[[}{igraph.es}(x, i) <- value \method{[}{igraph.es}(x, i) <- value \method{$}{igraph.es}(x, name) \method{$}{igraph.es}(x, name) <- value E(x, path = NULL, P = NULL, directed = NULL) <- value } \arguments{ \item{x}{An edge sequence. For \code{E<-} it is a graph.} \item{i}{Index.} \item{value}{New value of the attribute, for the edges in the edge sequence.} \item{name}{Name of the edge attribute to query or set.} \item{path}{Select edges along a path, given by a vertex sequence See \code{\link{E}}.} \item{P}{Select edges via pairs of vertices. See \code{\link{E}}.} \item{directed}{Whether to use edge directions for the \code{path} or \code{P} arguments.} } \value{ A vector or list, containing the values of the attribute \code{name} for the edges in the sequence. For numeric, character or logical attributes, it is a vector of the appropriate type, otherwise it is a list. } \description{ The \code{$} operator is a syntactic sugar to query and set edge attributes, for edges in an edge sequence. } \details{ The query form of \code{$} is a shortcut for \code{\link{edge_attr}}, e.g. \code{E(g)[idx]$attr} is equivalent to \code{edge_attr(g, attr, E(g)[idx])}. The assignment form of \code{$} is a shortcut for \code{\link{set_edge_attr}}, e.g. \code{E(g)[idx]$attr <- value} is equivalent to \code{g <- set_edge_attr(g, attr, E(g)[idx], value)}. } \examples{ # color edges of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_(gnp(100, 1/100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) E(g)$color <- "orange" E(g)[giant_v \%--\% giant_v]$color <- "blue" plot(g) } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} } \concept{vertex and edge sequences} igraph/man/print.igraph.es.Rd0000644000175100001440000000312413430770475015631 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{print.igraph.es} \alias{print.igraph.es} \title{Print an edge sequence to the screen} \usage{ \method{print}{igraph.es}(x, full = igraph_opt("print.full"), ...) } \arguments{ \item{x}{An edge sequence.} \item{full}{Whether to show the full sequence, or truncate the output to the screen size.} \item{...}{Currently ignored.} } \value{ The edge sequence, invisibly. } \description{ For long edge sequences, the printing is truncated to fit to the screen. Use \code{print} explicitly and the code{full} argument to see the full sequence. } \details{ Edge sequences created with the double bracket operator are printed differently, together with all attributes of the edges in the sequence, as a table. } \examples{ # Unnamed graphs g <- make_ring(10) E(g) # Named graphs g2 <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) E(g2) # All edges in a long sequence g3 <- make_ring(200) E(g3) E(g3) \%>\% print(full = TRUE) # Metadata g4 <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) \%>\% set_edge_attr("weight", value = 1:10) \%>\% set_edge_attr("color", value = "green") E(g4) E(g4)[[]] E(g4)[[1:5]] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.vs}} } \concept{vertex and edge sequences} igraph/man/count_triangles.Rd0000644000175100001440000000326313430770476016023 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/triangles.R \name{count_triangles} \alias{count_triangles} \alias{adjacent.triangles} \alias{triangles} \title{Find triangles in graphs} \usage{ count_triangles(graph, vids = V(graph)) } \arguments{ \item{graph}{The input graph. It might be directed, but edge directions are ignored.} \item{vids}{The vertices to query, all of them by default. This might be a vector of numeric ids, or a character vector of symbolic vertex names for named graphs.} } \value{ For \code{triangles} a numeric vector of vertex ids, the first three vertices belong to the first triangle found, etc. For \code{count_triangles} a numeric vector, the number of triangles for all vertices queried. } \description{ Count how many triangles a vertex is part of, in a graph, or just list the triangles of a graph. } \details{ \code{triangles} lists all triangles of a graph. For efficiency, all triangles are returned in a single vector. The first three vertices belong to the first triangle, etc. \code{count_triangles} counts how many triangles a vertex is part of. } \examples{ ## A small graph kite <- make_graph("Krackhardt_Kite") plot(kite) matrix(triangles(kite), nrow=3) ## Adjacenct triangles atri <- count_triangles(kite) plot(kite, vertex.label=atri) ## Always true sum(count_triangles(kite)) == length(triangles(kite)) ## Should match, local transitivity is the ## number of adjacent triangles divided by the number ## of adjacency triples transitivity(kite, type="local") count_triangles(kite) / (degree(kite) * (degree(kite)-1)/2) } \seealso{ \code{\link{transitivity}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/incident.Rd0000644000175100001440000000213013430770475014407 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{incident} \alias{incident} \title{Incident edges of a vertex in a graph} \usage{ incident(graph, v, mode = c("all", "out", "in", "total")) } \arguments{ \item{graph}{The input graph.} \item{v}{The vertex of which the indicent edges are queried.} \item{mode}{Whether to query outgoing (\sQuote{out}), incoming (\sQuote{in}) edges, or both types (\sQuote{all}). This is ignored for undirected graphs.} } \value{ An edge sequence containing the incident edges of the input vertex. } \description{ Incident edges of a vertex in a graph } \examples{ g <- make_graph("Zachary") incident(g, 1) incident(g, 34) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/layout.fruchterman.reingold.grid.Rd0000644000175100001440000000077213430770475021204 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout.fruchterman.reingold.grid} \alias{layout.fruchterman.reingold.grid} \title{Grid Fruchterman-Reingold layout, this was removed from igraph} \usage{ layout.fruchterman.reingold.grid(graph, ...) } \arguments{ \item{graph}{Input graph.} \item{...}{Extra arguments are ignored.} } \value{ Layout coordinates, a two column matrix. } \description{ Now it calls the Fruchterman-Reingold layout, with a warning. } igraph/man/max_cardinality.Rd0000644000175100001440000000346313430770475015774 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R \name{max_cardinality} \alias{max_cardinality} \alias{maximum.cardinality.search} \title{Maximum cardinality search} \usage{ max_cardinality(graph) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored, as the algorithm is defined for undirected graphs.} } \value{ A list with two components: \item{alpha}{Numeric vector. The vertices ordered according to the maximum cardinality search.} \item{alpham1}{Numeric vector. The inverse of \code{alpha}.} } \description{ Maximum cardinality search is a simple ordering a vertices that is useful in determining the chordality of a graph. } \details{ Maximum cardinality search visits the vertices in such an order that every time the vertex with the most already visited neighbors is visited. Ties are broken randomly. The algorithm provides a simple basis for deciding whether a graph is chordal, see References below, and also \code{\link{is_chordal}}. } \examples{ ## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal(A-B:C:I, B-A:C:D, C-A:B:E:H, D-B:E:F, E-C:D:F:H, F-D:E:G, G-F:H, H-C:E:G:I, I-A:H) max_cardinality(g1) is_chordal(g1, fillin=TRUE) g2 <- graph_from_literal(A-B:E, B-A:E:F:D, C-E:D:G, D-B:F:E:C:G, E-A:B:C:D:F, F-B:D:E, G-C:D:H:I, H-G:I:J, I-G:H:J, J-H:I) max_cardinality(g2) is_chordal(g2, fillin=TRUE) } \references{ Robert E Tarjan and Mihalis Yannakakis. (1984). Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs. \emph{SIAM Journal of Computation} 13, 566--579. } \seealso{ \code{\link{is_chordal}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/graph_from_adj_list.Rd0000644000175100001440000000433713430770475016622 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{graph_from_adj_list} \alias{graph_from_adj_list} \alias{graph.adjlist} \title{Create graphs from adjacency lists} \usage{ graph_from_adj_list(adjlist, mode = c("out", "in", "all", "total"), duplicate = TRUE) } \arguments{ \item{adjlist}{The adjacency list. It should be consistent, i.e. the maximum throughout all vectors in the list must be less than the number of vectors (=the number of vertices in the graph). Note that the list is expected to be 0-indexed.} \item{mode}{Character scalar, it specifies whether the graph to create is undirected (\sQuote{all} or \sQuote{total}) or directed; and in the latter case, whether it contains the outgoing (\sQuote{out}) or the incoming (\sQuote{in}) neighbors of the vertices.} \item{duplicate}{Logical scalar. For undirected graphs it gives whether edges are included in the list twice. E.g. if it is \code{TRUE} then for an undirected \code{{A,B}} edge \code{graph_from_adj_list} expects \code{A} included in the neighbors of \code{B} and \code{B} to be included in the neighbors of \code{A}. This argument is ignored if \code{mode} is \code{out} or \code{in}.} } \value{ An igraph graph object. } \description{ An adjacency list is a list of numeric vectors, containing the neighbor vertices for each vertex. This function creates an igraph graph object from such a list. } \details{ Adjacency lists are handy if you intend to do many (small) modifications to a graph. In this case adjacency lists are more efficient than igraph graphs. The idea is that you convert your graph to an adjacency list by \code{\link{as_adj_list}}, do your modifications to the graphs and finally create again an igraph graph by calling \code{graph_from_adj_list}. } \examples{ ## Directed g <- make_ring(10, dir=TRUE) al <- as_adj_list(g, mode="out") g2 <- graph_from_adj_list(al) graph.isomorphic(g, g2) ## Undirected g <- make_ring(10) al <- as_adj_list(g) g2 <- graph_from_adj_list(al, mode="all") graph.isomorphic(g, g2) ecount(g2) g3 <- graph_from_adj_list(al, mode="all", duplicate=FALSE) ecount(g3) which_multiple(g3) } \seealso{ \code{\link{as_edgelist}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/decompose.Rd0000644000175100001440000000267313430770475014604 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/components.R \name{decompose} \alias{decompose} \alias{decompose.graph} \title{Decompose a graph into components} \usage{ decompose(graph, mode = c("weak", "strong"), max.comps = NA, min.vertices = 0) } \arguments{ \item{graph}{The original graph.} \item{mode}{Character constant giving the type of the components, wither \code{weak} for weakly connected components or \code{strong} for strongly connected components.} \item{max.comps}{The maximum number of components to return. The first \code{max.comps} components will be returned (which hold at least \code{min.vertices} vertices, see the next parameter), the others will be ignored. Supply \code{NA} here if you don't want to limit the number of components.} \item{min.vertices}{The minimum number of vertices a component should contain in order to place it in the result list. Eg. supply 2 here to ignore isolate vertices.} } \value{ A list of graph objects. } \description{ Creates a separate graph for each component of a graph. } \examples{ # the diameter of each component in a random graph g <- sample_gnp(1000, 1/1000) components <- decompose(g, min.vertices=2) sapply(components, diameter) } \seealso{ \code{\link{is_connected}} to decide whether a graph is connected, \code{\link{components}} to calculate the connected components of a graph. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_gnm.Rd0000644000175100001440000000235413430770475014744 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_gnm} \alias{sample_gnm} \alias{gnm} \title{Generate random graphs according to the G(n,m) Erdos-Renyi model} \usage{ sample_gnm(n, m, directed = FALSE, loops = FALSE) gnm(...) } \arguments{ \item{n}{The number of vertices in the graph.} \item{m}{The number of edges in the graph.} \item{directed}{Logical, whether the graph will be directed, defaults to FALSE.} \item{loops}{Logical, whether to add loop edges, defaults to FALSE.} \item{...}{Passed to \code{sample_app}.} } \value{ A graph object. } \description{ This model is very simple, every possible edge is created with the same constant probability. } \details{ The graph has \sQuote{n} vertices and \sQuote{m} edges, and the \sQuote{m} edges are chosen uniformly randomly from the set of all possible edges. This set includes loop edges as well if the \code{loops} parameter is TRUE. } \examples{ g <- sample_gnm(1000, 1000) degree_distribution(g) } \references{ Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes Mathematicae} 6, 290--297 (1959). } \seealso{ \code{\link{sample_gnp}}, \code{\link{sample_pa}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/tkplot.Rd0000644000175100001440000001414513430770476014141 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/tkplot.R \name{tkplot} \alias{tkplot} \alias{tkplot.close} \alias{tkplot.off} \alias{tkplot.fit.to.screen} \alias{tkplot.reshape} \alias{tkplot.export.postscript} \alias{tkplot.canvas} \alias{tkplot.getcoords} \alias{tkplot.setcoords} \alias{tkplot.center} \alias{tkplot.rotate} \alias{tk_canvas} \alias{tk_center} \alias{tk_close} \alias{tk_postscript} \alias{tk_fit} \alias{tk_coords} \alias{tk_off} \alias{tk_reshape} \alias{tk_rotate} \alias{tk_set_coords} \title{Interactive plotting of graphs} \usage{ tkplot(graph, canvas.width = 450, canvas.height = 450, ...) tk_close(tkp.id, window.close = TRUE) tk_off() tk_fit(tkp.id, width = NULL, height = NULL) tk_center(tkp.id) tk_reshape(tkp.id, newlayout, ..., params) tk_postscript(tkp.id) tk_coords(tkp.id, norm = FALSE) tk_set_coords(tkp.id, coords) tk_rotate(tkp.id, degree = NULL, rad = NULL) tk_canvas(tkp.id) } \arguments{ \item{graph}{The \code{graph} to plot.} \item{canvas.width, canvas.height}{The size of the tkplot drawing area.} \item{\dots}{Additional plotting parameters. See \link{igraph.plotting} for the complete list.} \item{tkp.id}{The id of the tkplot window to close/reshape/etc.} \item{window.close}{Leave this on the default value.} \item{width}{The width of the rectangle for generating new coordinates.} \item{height}{The height of the rectangle for generating new coordinates.} \item{newlayout}{The new layout, see the \code{layout} parameter of tkplot.} \item{params}{Extra parameters in a list, to pass to the layout function.} \item{norm}{Logical, should we norm the coordinates.} \item{coords}{Two-column numeric matrix, the new coordinates of the vertices, in absolute coordinates.} \item{degree}{The degree to rotate the plot.} \item{rad}{The degree to rotate the plot, in radian.} } \value{ \code{tkplot} returns an integer, the id of the plot, this can be used to manipulate it from the command line. \code{tk_canvas} retuns \code{tkwin} object, the Tk canvas. \code{tk_coords} returns a matrix with the coordinates. \code{tk_close}, \code{tk_off}, \code{tk_fit}, \code{tk_reshape}, \code{tk_postscript}, \code{tk_center} and \code{tk_rotate} return \code{NULL} invisibly. } \description{ \code{tkplot} and its companion functions serve as an interactive graph drawing facility. Not all parameters of the plot can be changed interactively right now though, eg. the colors of vertices, edges, and also others have to be pre-defined. } \details{ \code{tkplot} is an interactive graph drawing facility. It is not very well developed at this stage, but it should be still useful. It's handling should be quite straightforward most of the time, here are some remarks and hints. There are different popup menus, activated by the right mouse button, for vertices and edges. Both operate on the current selection if the vertex/edge under the cursor is part of the selection and operate on the vertex/edge under the cursor if it is not. One selection can be active at a time, either a vertex or an edge selection. A vertex/edge can be added to a selection by holding the \code{control} key while clicking on it with the left mouse button. Doing this again deselect the vertex/edge. Selections can be made also from the \code{Select} menu. The `Select some vertices' dialog allows to give an expression for the vertices to be selected: this can be a list of numeric R expessions separated by commas, like `\code{1,2:10,12,14,15}' for example. Similarly in the `Select some edges' dialog two such lists can be given and all edges connecting a vertex in the first list to one in the second list will be selected. In the color dialog a color name like 'orange' or RGB notation can also be used. The \code{tkplot} command creates a new Tk window with the graphical representation of \code{graph}. The command returns an integer number, the tkplot id. The other commands utilize this id to be able to query or manipulate the plot. \code{tk_close} closes the Tk plot with id \code{tkp.id}. \code{tk_off} closes all Tk plots. \code{tk_fit} fits the plot to the given rectange (\code{width} and \code{height}), if some of these are \code{NULL} the actual phisical width od height of the plot window is used. \code{tk_reshape} applies a new layout to the plot, its optional parameters will be collected to a list analogous to \code{layout.par}. \code{tk_postscript} creates a dialog window for saving the plot in postscript format. \code{tk_canvas} returns the Tk canvas object that belongs to a graph plot. The canvas can be directly manipulated then, eg. labels can be added, it could be saved to a file programatically, etc. See an example below. \code{tk_coords} returns the coordinates of the vertices in a matrix. Each row corresponds to one vertex. \code{tk_set_coords} sets the coordinates of the vertices. A two-column matrix specifies the new positions, with each row corresponding to a single vertex. \code{tk_center} shifts the figure to the center of its plot window. \code{tk_rotate} rotates the figure, its parameter can be given either in degrees or in radians. } \section{Examples}{ \preformatted{ g <- make_ring(10) tkplot(g) ## Saving a tkplot() to a file programatically g <- make_star(10, center=10) %u% make_ring(9, directed=TRUE) E(g)$width <- sample(1:10, ecount(g), replace=TRUE) lay <- layout_nicely(g) id <- tkplot(g, layout=lay) canvas <- tk_canvas(id) tcltk::tkpostscript(canvas, file="/tmp/output.eps") tk_close(id) ## Setting the coordinates and adding a title label g <- make_ring(10) id <- tkplot(make_ring(10), canvas.width=450, canvas.height=500) canvas <- tk_canvas(id) padding <- 20 coords <- norm_coords(layout_in_circle(g), 0+padding, 450-padding, 50+padding, 500-padding) tk_set_coords(id, coords) width <- as.numeric(tkcget(canvas, "-width")) height <- as.numeric(tkcget(canvas, "-height")) tkcreate(canvas, "text", width/2, 25, text="My title", justify="center", font=tcltk::tkfont.create(family="helvetica", size=20,weight="bold")) } } \seealso{ \code{\link{plot.igraph}}, \code{\link{layout}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/spectrum.Rd0000644000175100001440000000603113430770475014460 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{spectrum} \alias{spectrum} \alias{graph.eigen} \alias{igraph.eigen.default} \title{Eigenvalues and eigenvectors of the adjacency matrix of a graph} \usage{ spectrum(graph, algorithm = c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which = list(), options = arpack_defaults) } \arguments{ \item{graph}{The input graph, can be directed or undirected.} \item{algorithm}{The algorithm to use. Currently only \code{arpack} is implemented, which uses the ARPACK solver. See also \code{\link{arpack}}.} \item{which}{A list to specify which eigenvalues and eigenvectors to calculate. By default the leading (i.e. largest magnitude) eigenvalue and the corresponding eigenvector is calculated.} \item{options}{Options for the ARPACK solver. See \code{\link{arpack_defaults}}.} } \value{ Depends on the algorithm used. For \code{arpack} a list with three entries is returned: \item{options}{See the return value for \code{arpack} for a complete description.} \item{values}{Numeric vector, the eigenvalues.} \item{vectors}{Numeric matrix, with the eigenvectors as columns.} } \description{ Calculate selected eigenvalues and eigenvectors of a (supposedly sparse) graph. } \details{ The \code{which} argument is a list and it specifies which eigenvalues and corresponding eigenvectors to calculate: There are eight options: \enumerate{ \item Eigenvalues with the largest magnitude. Set \code{pos} to \code{LM}, and \code{howmany} to the number of eigenvalues you want. \item Eigenvalues with the smallest magnitude. Set \code{pos} to \code{SM} and \code{howmany} to the number of eigenvalues you want. \item Largest eigenvalues. Set \code{pos} to \code{LA} and \code{howmany} to the number of eigenvalues you want. \item Smallest eigenvalues. Set \code{pos} to \code{SA} and \code{howmany} to the number of eigenvalues you want. \item Eigenvalues from both ends of the spectrum. Set \code{pos} to \code{BE} and \code{howmany} to the number of eigenvalues you want. If \code{howmany} is odd, then one more eigenvalue is returned from the larger end. \item Selected eigenvalues. This is not (yet) implemented currently. \item Eigenvalues in an interval. This is not (yet) implemented. \item All eigenvalues. This is not implemented yet. The standard \code{eigen} function does a better job at this, anyway. } Note that ARPACK might be unstable for graphs with multiple components, e.g. graphs with isolate vertices. } \examples{ ## Small example graph, leading eigenvector by default kite <- make_graph("Krackhardt_kite") spectrum(kite)[c("values", "vectors")] ## Double check eigen(as_adj(kite, sparse=FALSE))$vectors[,1] ## Should be the same as 'eigen_centrality' (but rescaled) cor(eigen_centrality(kite)$vector, spectrum(kite)$vectors) ## Smallest eigenvalues spectrum(kite, which=list(pos="SM", howmany=2))$values } \seealso{ \code{\link{as_adj}} to create a (sparse) adjacency matrix. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/difference.igraph.Rd0000644000175100001440000000373013430770475016164 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{difference.igraph} \alias{difference.igraph} \alias{graph.difference} \alias{\%m\%} \title{Difference of graphs} \usage{ \method{difference}{igraph}(big, small, byname = "auto", ...) } \arguments{ \item{big}{The left hand side argument of the minus operator. A directed or undirected graph.} \item{small}{The right hand side argument of the minus operator. A directed ot undirected graph.} \item{byname}{A logical scalar, or the character scalar \code{auto}. Whether to perform the operation based on symbolic vertex names. If it is \code{auto}, that means \code{TRUE} if both graphs are named and \code{FALSE} otherwise. A warning is generated if \code{auto} and one graph, but not both graphs are named.} \item{...}{Ignored, included for S3 compatibility.} } \value{ A new graph object. } \description{ The difference of two graphs are created. } \details{ \code{difference} creates the difference of two graphs. Only edges present in the first graph but not in the second will be be included in the new graph. The corresponding operator is \%m\%. If the \code{byname} argument is \code{TRUE} (or \code{auto} and the graphs are all named), then the operation is performed based on symbolic vertex names. Otherwise numeric vertex ids are used. \code{difference} keeps all attributes (graph, vertex and edge) of the first graph. Note that \code{big} and \code{small} must both be directed or both be undirected, otherwise an error message is given. } \examples{ ## Create a wheel graph wheel <- union(make_ring(10), make_star(11, center=11, mode="undirected")) V(wheel)$name <- letters[seq_len(vcount(wheel))] ## Subtract a star graph from it sstar <- make_star(6, center=6, mode="undirected") V(sstar)$name <- letters[c(1,3,5,7,9,11)] G <- wheel \%m\% sstar print_all(G) plot(G, layout=layout_nicely(wheel)) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_growing.Rd0000644000175100001440000000253713430770475015642 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_growing} \alias{sample_growing} \alias{growing.random.game} \alias{growing} \title{Growing random graph generation} \usage{ sample_growing(n, m = 1, directed = TRUE, citation = FALSE) growing(...) } \arguments{ \item{n}{Numeric constant, number of vertices in the graph.} \item{m}{Numeric constant, number of edges added in each time step.} \item{directed}{Logical, whether to create a directed graph.} \item{citation}{Logical. If \code{TRUE} a citation graph is created, ie. in each time step the added edges are originating from the new vertex.} \item{...}{Passed to \code{sample_app}.} } \value{ A new graph object. } \description{ This function creates a random graph by simulating its stochastic evolution. } \details{ This is discrete time step model, in each time step a new vertex is added to the graph and \code{m} new edges are created. If \code{citation} is \code{FALSE} these edges are connecting two uniformly randomly chosen vertices, otherwise the edges are connecting new vertex to uniformly randomly chosen old vertices. } \examples{ g <- sample_growing(500, citation=FALSE) g2 <- sample_growing(500, citation=TRUE) } \seealso{ \code{\link{sample_pa}}, \code{\link{sample_gnp}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/is_igraph.Rd0000644000175100001440000000101213430770475014555 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/basic.R \name{is_igraph} \alias{is_igraph} \alias{is.igraph} \title{Is this object an igraph graph?} \usage{ is_igraph(graph) } \arguments{ \item{graph}{An R object.} } \value{ A logical constant, \code{TRUE} if argument \code{graph} is a graph object. } \description{ Is this object an igraph graph? } \examples{ g <- make_ring(10) is_igraph(g) is_igraph(numeric(10)) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/intersection.Rd0000644000175100001440000000127013430770475015324 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{intersection} \alias{intersection} \title{Intersection of two or more sets} \usage{ intersection(...) } \arguments{ \item{...}{Arguments, their number and interpretation depends on the function that implements \code{intersection}.} } \value{ Depends on the function that implements this method. } \description{ This is an S3 generic function. See \code{methods("intersection")} for the actual implementations for various S3 classes. Initially it is implemented for igraph graphs and igraph vertex and edge sequences. See \code{\link{intersection.igraph}}, and \code{\link{intersection.igraph.vs}}. } igraph/man/cluster_optimal.Rd0000644000175100001440000000464313430770475016033 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_optimal} \alias{cluster_optimal} \alias{optimal.community} \title{Optimal community structure} \usage{ cluster_optimal(graph, weights = NULL) } \arguments{ \item{graph}{The input graph. Edge directions are ignored for directed graphs.} \item{weights}{Optional positive weight vector for optimizing weighted modularity. If the graph has a \code{weight} edge attribute, then this is used by default. Supply \code{NA} to ignore the weights of a weighted graph. Larger edge weights correspond to stronger connections.} } \value{ \code{cluster_optimal} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ This function calculates the optimal community structure of a graph, by maximizing the modularity measure over all possible partitions. } \details{ This function calculates the optimal community structure for a graph, in terms of maximal modularity score. The calculation is done by transforming the modularity maximization into an integer programming problem, and then calling the GLPK library to solve that. Please the reference below for details. Note that modularity optimization is an NP-complete problem, and all known algorithms for it have exponential time complexity. This means that you probably don't want to run this function on larger graphs. Graphs with up to fifty vertices should be fine, graphs with a couple of hundred vertices might be possible. } \section{Examples}{ \preformatted{ ## Zachary's karate club g <- make_graph("Zachary") ## We put everything into a big 'try' block, in case ## igraph was compiled without GLPK support ## The calculation only takes a couple of seconds oc <- cluster_optimal(g) ## Double check the result print(modularity(oc)) print(modularity(g, membership(oc))) ## Compare to the greedy optimizer fc <- cluster_fast_greedy(g) print(modularity(fc)) } } \references{ Ulrik Brandes, Daniel Delling, Marco Gaertler, Robert Gorke, Martin Hoefer, Zoran Nikoloski, Dorothea Wagner: On Modularity Clustering, \emph{IEEE Transactions on Knowledge and Data Engineering} 20(2):172-188, 2008. } \seealso{ \code{\link{communities}} for the documentation of the result, \code{\link{modularity}}. See also \code{\link{cluster_fast_greedy}} for a fast greedy optimizer. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/delete_vertex_attr.Rd0000644000175100001440000000224213430770475016507 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{delete_vertex_attr} \alias{delete_vertex_attr} \alias{remove.vertex.attribute} \title{Delete a vertex attribute} \usage{ delete_vertex_attr(graph, name) } \arguments{ \item{graph}{The graph} \item{name}{The name of the vertex attribute to delete.} } \value{ The graph, with the specified vertex attribute removed. } \description{ Delete a vertex attribute } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) vertex_attr_names(g) g2 <- delete_vertex_attr(g, "name") vertex_attr_names(g2) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/articulation_points.Rd0000644000175100001440000000243413430770475016713 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/components.R \name{articulation_points} \alias{articulation_points} \alias{articulation.points} \title{Articulation points of a graph} \usage{ articulation_points(graph) } \arguments{ \item{graph}{The input graph. It is treated as an undirected graph, even if it is directed.} } \value{ A numeric vector giving the vertex ids of the articulation points of the input graph. } \description{ Articuation points or cut vertices are vertices whose removal increases the number of connected components in a graph. } \details{ Articuation points or cut vertices are vertices whose removal increases the number of connected components in a graph. If the original graph was connected, then the removal of a single articulation point makes it undirected. If a graph contains no articulation points, then its vertex connectivity is at least two. } \examples{ g <- disjoint_union( make_full_graph(5), make_full_graph(5) ) clu <- components(g)$membership g <- add_edges(g, c(match(1, clu), match(2, clu)) ) articulation_points(g) } \seealso{ \code{\link{biconnected_components}}, \code{\link{components}}, \code{\link{is_connected}}, \code{\link{vertex_connectivity}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/centr_degree.Rd0000644000175100001440000000331613430770475015247 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_degree} \alias{centr_degree} \alias{centralization.degree} \title{Centralize a graph according to the degrees of vertices} \usage{ centr_degree(graph, mode = c("all", "out", "in", "total"), loops = TRUE, normalized = TRUE) } \arguments{ \item{graph}{The input graph.} \item{mode}{This is the same as the \code{mode} argument of \code{degree}.} \item{loops}{Logical scalar, whether to consider loops edges when calculating the degree.} \item{normalized}{Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum.} } \value{ A named list with the following components: \item{res}{The node-level centrality scores.} \item{centralization}{The graph level centrality index.} \item{theoretical_max}{The maximum theoretical graph level centralization score for a graph with the given number of vertices, using the same parameters. If the \code{normalized} argument was \code{TRUE}, then the result was divided by this number.} } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/count_subgraph_isomorphisms.Rd0000644000175100001440000000652013430770476020461 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{count_subgraph_isomorphisms} \alias{count_subgraph_isomorphisms} \alias{graph.count.subisomorphisms.vf2} \title{Count the isomorphic mappings between a graph and the subgraphs of another graph} \usage{ count_subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...) } \arguments{ \item{pattern}{The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{target}{The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{method}{The method to use. Possible values: \sQuote{lad}, \sQuote{vf2}. See their details below.} \item{...}{Additional arguments, passed to the various methods.} } \value{ Logical scalar, \code{TRUE} if the \code{pattern} is isomorphic to a (possibly induced) subgraph of \code{target}. } \description{ Count the isomorphic mappings between a graph and the subgraphs of another graph } \section{\sQuote{lad} method}{ This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments: \describe{ \item{domains}{If not \code{NULL}, then it specifies matching restrictions. It must be a list of \code{target} vertex sets, given as numeric vertex ids or symbolic vertex names. The length of the list must be \code{vcount(pattern)} and for each vertex in \code{pattern} it gives the allowed matching vertices in \code{target}. Defaults to \code{NULL}.} \item{induced}{Logical scalar, whether to search for an induced subgraph. It is \code{FALSE} by default.} \item{time.limit}{The processor time limit for the computation, in seconds. It defaults to \code{Inf}, which means no limit.} } } \section{\sQuote{vf2} method}{ This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments: \describe{ \item{vertex.color1, vertex.color2}{Optional integer vectors giving the colors of the vertices for colored graph isomorphism. If they are not given, but the graph has a \dQuote{color} vertex attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments. See also examples below.} \item{edge.color1, edge.color2}{Optional integer vectors giving the colors of the edges for edge-colored (sub)graph isomorphism. If they are not given, but the graph has a \dQuote{color} edge attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments.} } } \references{ LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition}, 149--159, 2001. C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, \emph{Artificial Intelligence} 174(12-13):850--864, 2010. } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/centr_betw_tmax.Rd0000644000175100001440000000247113430770475016007 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_betw_tmax} \alias{centr_betw_tmax} \alias{centralization.betweenness.tmax} \title{Theoretical maximum for betweenness centralization} \usage{ centr_betw_tmax(graph = NULL, nodes = 0, directed = TRUE) } \arguments{ \item{graph}{The input graph. It can also be \code{NULL}, if \code{nodes} is given.} \item{nodes}{The number of vertices. This is ignored if the graph is given.} \item{directed}{logical scalar, whether to use directed shortest paths for calculating betweenness.} } \value{ Real scalar, the theoratical maximum (unnormalized) graph betweenness centrality score for graphs with given order and other parameters. } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_betw(g, normalized = FALSE)$centralization \%>\% `/`(centr_betw_tmax(g)) centr_betw(g, normalized = TRUE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/print.igraph.Rd0000644000175100001440000000747513430770475015240 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/print.R \name{print.igraph} \alias{print.igraph} \alias{print_all} \alias{summary.igraph} \alias{str.igraph} \title{Print graphs to the terminal} \usage{ \method{print}{igraph}(x, full = igraph_opt("print.full"), graph.attributes = igraph_opt("print.graph.attributes"), vertex.attributes = igraph_opt("print.vertex.attributes"), edge.attributes = igraph_opt("print.edge.attributes"), names = TRUE, max.lines = igraph_opt("auto.print.lines"), ...) \method{summary}{igraph}(object, ...) } \arguments{ \item{x}{The graph to print.} \item{full}{Logical scalar, whether to print the graph structure itself as well.} \item{graph.attributes}{Logical constant, whether to print graph attributes.} \item{vertex.attributes}{Logical constant, whether to print vertex attributes.} \item{edge.attributes}{Logical constant, whether to print edge attributes.} \item{names}{Logical constant, whether to print symbolic vertex names (ie. the \code{name} vertex attribute) or vertex ids.} \item{max.lines}{The maximum number of lines to use. The rest of the output will be truncated.} \item{\dots}{Additional agruments.} \item{object}{The graph of which the summary will be printed.} } \value{ All these functions return the graph invisibly. } \description{ These functions attempt to print a graph to the terminal in a human readable form. } \details{ \code{summary.igraph} prints the number of vertices, edges and whether the graph is directed. \code{print_all} prints the same information, and also lists the edges, and optionally graph, vertex and/or edge attributes. \code{print.igraph} behaves either as \code{summary.igraph} or \code{print_all} depending on the \code{full} argument. See also the \sQuote{print.full} igraph option and \code{\link{igraph_opt}}. The graph summary printed by \code{summary.igraph} (and \code{print.igraph} and \code{print_all}) consists one or more lines. The first line contains the basic properties of the graph, and the rest contains its attributes. Here is an example, a small star graph with weighted directed edges and named vertices: \preformatted{ IGRAPH badcafe DNW- 10 9 -- In-star + attr: name (g/c), mode (g/c), center (g/n), name (v/c), weight (e/n) } The first line always starts with \code{IGRAPH}, showing you that the object is an igraph graph. Then a seven character code is printed, this the first seven characters of the unique id of the graph. See \code{\link{graph_id}} for more. Then a four letter long code string is printed. The first letter distinguishes between directed (\sQuote{\code{D}}) and undirected (\sQuote{\code{U}}) graphs. The second letter is \sQuote{\code{N}} for named graphs, i.e. graphs with the \code{name} vertex attribute set. The third letter is \sQuote{\code{W}} for weighted graphs, i.e. graphs with the \code{weight} edge attribute set. The fourth letter is \sQuote{\code{B}} for bipartite graphs, i.e. for graphs with the \code{type} vertex attribute set. Then, after two dashes, the name of the graph is printed, if it has one, i.e. if the \code{name} graph attribute is set. From the second line, the attributes of the graph are listed, separated by a comma. After the attribute names, the kind of the attribute -- graph (\sQuote{\code{g}}), vertex (\sQuote{\code{v}}) or edge (\sQuote{\code{e}}) -- is denoted, and the type of the attribute as well, character (\sQuote{\code{c}}), numeric (\sQuote{\code{n}}), logical (\sQuote{\code{l}}), or other (\sQuote{\code{x}}). As of igraph 0.4 \code{print_all} and \code{print.igraph} use the \code{max.print} option, see \code{\link[base]{options}} for details. As of igraph 1.1.1, the \code{str.igraph} function is defunct, use \code{print_all()}. } \examples{ g <- make_ring(10) g summary(g) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_hierarchical_sbm.Rd0000644000175100001440000000340513430770475017440 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_hierarchical_sbm} \alias{sample_hierarchical_sbm} \alias{hierarchical_sbm} \title{Sample the hierarchical stochastic block model} \usage{ sample_hierarchical_sbm(n, m, rho, C, p) } \arguments{ \item{n}{Integer scalar, the number of vertices.} \item{m}{Integer scalar, the number of vertices per block. \code{n / m} must be integer. Alternatively, an integer vector of block sizes, if not all the blocks have equal sizes.} \item{rho}{Numeric vector, the fraction of vertices per cluster, within a block. Must sum up to 1, and \code{rho * m} must be integer for all elements of rho. Alternatively a list of rho vectors, one for each block, if they are not the same for all blocks.} \item{C}{A square, symmetric numeric matrix, the Bernoulli rates for the clusters within a block. Its size must mach the size of the \code{rho} vector. Alternatively, a list of square matrices, if the Bernoulli rates differ in different blocks.} \item{p}{Numeric scalar, the Bernoulli rate of connections between vertices in different blocks.} \item{\dots}{Passed to \code{sample_hierarchical_sbm}.} } \value{ An igraph graph. } \description{ Sampling from a hierarchical stochastic block model of networks. } \details{ The function generates a random graph according to the hierarchical stochastic block model. } \examples{ ## Ten blocks with three clusters each C <- matrix(c(1 , 3/4, 0, 3/4, 0, 3/4, 0 , 3/4, 3/4), nrow=3) g <- sample_hierarchical_sbm(100, 10, rho=c(3, 3, 4)/10, C=C, p=1/20) g if (require(Matrix)) { image(g[]) } } \seealso{ \code{\link{sbm.game}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} \keyword{graphs,} \keyword{random} igraph/man/identical_graphs.Rd0000644000175100001440000000073613430770475016124 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{identical_graphs} \alias{identical_graphs} \title{Decide if two graphs are identical} \usage{ identical_graphs(g1, g2) } \arguments{ \item{g1, g2}{The two graphs} } \value{ Logical scalar } \description{ This is similar to \code{identical} in the \code{base} package, but ignores the mutable piece of igraph objects, that might be different, even if the two graphs are identical. } igraph/man/layout_with_kk.Rd0000644000175100001440000000776613430770475015673 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_kk} \alias{layout_with_kk} \alias{with_kk} \title{The Kamada-Kawai layout algorithm} \usage{ layout_with_kk(graph, coords = NULL, dim = 2, maxiter = 50 * vcount(graph), epsilon = 0, kkconst = vcount(graph), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, niter, sigma, initemp, coolexp, start) with_kk(...) } \arguments{ \item{graph}{The input graph. Edge directions are ignored.} \item{coords}{If not \code{NULL}, then the starting coordinates should be given here, in a two or three column matrix, depending on the \code{dim} argument.} \item{dim}{Integer scalar, 2 or 3, the dimension of the layout. Two dimensional layouts are places on a plane, three dimensional ones in the 3d space.} \item{maxiter}{The maximum number of iterations to perform. The algorithm might terminate earlier, see the \code{epsilon} argument.} \item{epsilon}{Numeric scalar, the algorithm terminates, if the maximal delta is less than this. (See the reference below for what delta means.) If you set this to zero, then the function always performs \code{maxiter} iterations.} \item{kkconst}{Numeric scalar, the Kamada-Kawai vertex attraction constant. Typical (and default) value is the number of vertices.} \item{weights}{Edge weights, larger values will result longer edges. Note that this is opposite to \code{\link{layout_with_fr}}.} \item{minx}{If not \code{NULL}, then it must be a numeric vector that gives lower boundaries for the \sQuote{x} coordinates of the vertices. The length of the vector must match the number of vertices in the graph.} \item{maxx}{Similar to \code{minx}, but gives the upper boundaries.} \item{miny}{Similar to \code{minx}, but gives the lower boundaries of the \sQuote{y} coordinates.} \item{maxy}{Similar to \code{minx}, but gives the upper boundaries of the \sQuote{y} coordinates.} \item{minz}{Similar to \code{minx}, but gives the lower boundaries of the \sQuote{z} coordinates.} \item{maxz}{Similar to \code{minx}, but gives the upper boundaries of the \sQuote{z} coordinates.} \item{niter, sigma, initemp, coolexp}{These arguments are not supported from igraph version 0.8.0 and are ignored (with a warning).} \item{start}{Deprecated synonym for \code{coords}, for compatibility.} \item{...}{Passed to \code{layout_with_kk}.} } \value{ A numeric matrix with two (dim=2) or three (dim=3) columns, and as many rows as the number of vertices, the x, y and potentially z coordinates of the vertices. } \description{ Place the vertices on the plane, or in the 3d space, based on a phyisical model of springs. } \details{ See the referenced paper below for the details of the algorithm. This function was rewritten from scratch in igraph version 0.8.0 and it follows truthfully the original publication by Kamada and Kawai now. } \examples{ g <- make_ring(10) E(g)$weight <- rep(1:2, length.out=ecount(g)) plot(g, layout=layout_with_kk, edge.label=E(g)$weight) } \references{ Kamada, T. and Kawai, S.: An Algorithm for Drawing General Undirected Graphs. \emph{Information Processing Letters}, 31/1, 7--15, 1989. } \seealso{ \code{\link{layout_with_drl}}, \code{\link{plot.igraph}}, \code{\link{tkplot}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/delete_edge_attr.Rd0000644000175100001440000000221613430770475016077 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{delete_edge_attr} \alias{delete_edge_attr} \alias{remove.edge.attribute} \title{Delete an edge attribute} \usage{ delete_edge_attr(graph, name) } \arguments{ \item{graph}{The graph} \item{name}{The name of the edge attribute to delete.} } \value{ The graph, with the specified edge attribute removed. } \description{ Delete an edge attribute } \examples{ g <- make_ring(10) \%>\% set_edge_attr("name", value = LETTERS[1:10]) edge_attr_names(g) g2 <- delete_edge_attr(g, "name") edge_attr_names(g2) } \seealso{ Other graph attributes: \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/sample_correlated_gnp.Rd0000644000175100001440000000320313430770475017145 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_correlated_gnp} \alias{sample_correlated_gnp} \title{Generate a new random graph from a given graph by randomly adding/removing edges} \usage{ sample_correlated_gnp(old.graph, corr, p = old.graph$p, permutation = NULL) } \arguments{ \item{old.graph}{The original graph.} \item{corr}{A scalar in the unit interval, the target Pearson correlation between the adjacency matrices of the original the generated graph (the adjacency matrix being used as a vector).} \item{p}{A numeric scalar, the probability of an edge between two vertices, it must in the open (0,1) interval.} \item{permutation}{A numeric vector, a permutation vector that is applied on the vertices of the first graph, to get the second graph. If \code{NULL}, the vertices are not permuted.} } \value{ An unweighted graph of the same size as \code{old.graph} such that the correlation coefficient between the entries of the two adjacency matrices is \code{corr}. Note each pair of corresponding matrix entries is a pair of correlated Bernoulli random variables. } \description{ Sample a new graph by perturbing the adjacency matrix of a given graph and shuffling its vertices. } \details{ Please see the reference given below. } \examples{ g <- sample_gnp(1000, .1) g2 <- sample_correlated_gnp(g, corr = 0.5) cor(as.vector(g[]), as.vector(g2[])) g g2 } \references{ Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seeded graph matching for correlated Erdos-Renyi graphs. \url{http://arxiv.org/abs/1304.7844} } \seealso{ \code{\link{sample_correlated_gnp_pair}}, \code{\link{sample_gnp}} } igraph/man/set_graph_attr.Rd0000644000175100001440000000221413430770475015623 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{set_graph_attr} \alias{set_graph_attr} \alias{set.graph.attribute} \title{Set a graph attribute} \usage{ set_graph_attr(graph, name, value) } \arguments{ \item{graph}{The graph.} \item{name}{The name of the attribute to set.} \item{value}{New value of the attribute.} } \value{ The graph with the new graph attribute added or set. } \description{ An existing attribute with the same name is overwritten. } \examples{ g <- make_ring(10) \%>\% set_graph_attr("layout", layout_with_fr) g plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/are_adjacent.Rd0000644000175100001440000000223313430770476015217 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structure.info.R \name{are_adjacent} \alias{are_adjacent} \alias{are.connected} \title{Are two vertices adjacent?} \usage{ are_adjacent(graph, v1, v2) } \arguments{ \item{graph}{The graph.} \item{v1}{The first vertex, tail in directed graphs.} \item{v2}{The second vertex, head in directed graphs.} } \value{ A logical scalar, \code{TRUE} is a \code{(v1, v2)} exists in the graph. } \description{ The order of the vertices only matters in directed graphs, where the existence of a directed \code{(v1, v2)} edge is queried. } \examples{ ug <- make_ring(10) ug are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1) dg <- make_ring(10, directed = TRUE) dg are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/igraph-vs-indexing2.Rd0000644000175100001440000000411413430770475016403 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-vs-indexing2} \alias{igraph-vs-indexing2} \alias{[[.igraph.vs} \title{Select vertices and show their metadata} \usage{ \method{[[}{igraph.vs}(x, ...) } \arguments{ \item{x}{A vertex sequence.} \item{...}{Additional arguments, passed to \code{[}.} } \value{ The double bracket operator returns another vertex sequence, with meta-data (attribute) printing turned on. See details below. } \description{ The double bracket operator can be used on vertex sequences, to print the meta-data (vertex attributes) of the vertices in the sequence. } \details{ Technically, when used with vertex sequences, the double bracket operator does exactly the same as the single bracket operator, but the resulting vertex sequence is printed differently: all attributes of the vertices in the sequence are printed as well. See \code{\link{[.igraph.vs}} for more about indexing vertex sequences. } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("color", value = "red") \%>\% set_vertex_attr("name", value = LETTERS[1:10]) V(g) V(g)[[]] V(g)[1:5] V(g)[[1:5]] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} \concept{vertex and edge sequences} igraph/man/r_pal.Rd0000644000175100001440000000113713430770475013715 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/palette.R \name{r_pal} \alias{r_pal} \title{The default R palette} \usage{ r_pal(n) } \arguments{ \item{n}{The number of colors to use, the maximum is eight.} } \value{ A character vector of color names. } \description{ This is the default R palette, to be able to reproduce the colors of older igraph versions. Its colors are appropriate for categories, but they are not very attractive. } \seealso{ Other palettes: \code{\link{categorical_pal}}, \code{\link{diverging_pal}}, \code{\link{sequential_pal}} } \concept{palettes} igraph/man/shapes.Rd0000644000175100001440000002307713430770475014112 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.shapes.R \name{shapes} \alias{shapes} \alias{add.vertex.shape} \alias{igraph.shape.noclip} \alias{igraph.shape.noplot} \alias{vertex.shapes} \alias{igraph.vertex.shapes} \alias{shape_noclip} \alias{shape_noplot} \alias{add_shape} \title{Various vertex shapes when plotting igraph graphs} \usage{ shapes(shape = NULL) shape_noclip(coords, el, params, end = c("both", "from", "to")) shape_noplot(coords, v = NULL, params) add_shape(shape, clip = shape_noclip, plot = shape_noplot, parameters = list()) } \arguments{ \item{shape}{Character scalar, name of a vertex shape. If it is \code{NULL} for \code{shapes}, then the names of all defined vertex shapes are returned.} \item{coords, el, params, end, v}{See parameters of the clipping/plotting functions below.} \item{clip}{An R function object, the clipping function.} \item{plot}{An R function object, the plotting function.} \item{parameters}{Named list, additional plot/vertex/edge parameters. The element named define the new parameters, and the elements themselves define their default values. Vertex parameters should have a prefix \sQuote{\code{vertex.}}, edge parameters a prefix \sQuote{\code{edge.}}. Other general plotting parameters should have a prefix \sQuote{\code{plot.}}. See Details below.} } \value{ \code{shapes} returns a character vector if the \code{shape} argument is \code{NULL}. It returns a named list with entries named \sQuote{clip} and \sQuote{plot}, both of them R functions. \code{add_shape} returns \code{TRUE}, invisibly. \code{shape_noclip} returns the appropriate columns of its \code{coords} argument. } \description{ Starting from version 0.5.1 igraph supports different vertex shapes when plotting graphs. } \details{ In igraph a vertex shape is defined by two functions: 1) provides information about the size of the shape for clipping the edges and 2) plots the shape if requested. These functions are called \dQuote{shape functions} in the rest of this manual page. The first one is the clipping function and the second is the plotting function. The clipping function has the following arguments: \describe{ \item{coords}{A matrix with four columns, it contains the coordinates of the vertices for the edge list supplied in the \code{el} argument.} \item{el}{A matrix with two columns, the edges of which some end points will be clipped. It should have the same number of rows as \code{coords}.} \item{params}{This is a function object that can be called to query vertex/edge/plot graphical parameters. The first argument of the function is \dQuote{\code{vertex}}, \dQuote{\code{edge}} or \dQuote{\code{plot}} to decide the type of the parameter, the second is a character string giving the name of the parameter. E.g. \preformatted{ params("vertex", "size") } } \item{end}{Character string, it gives which end points will be used. Possible values are \dQuote{\code{both}}, \dQuote{\code{from}} and \dQuote{\code{to}}. If \dQuote{\code{from}} the function is expected to clip the first column in the \code{el} edge list, \dQuote{\code{to}} selects the second column, \dQuote{\code{both}} selects both.} } The clipping function should return a matrix with the same number of rows as the \code{el} arguments. If \code{end} is \code{both} then the matrix must have four columns, otherwise two. The matrix contains the modified coordinates, with the clipping applied. The plotting function has the following arguments: \describe{ \item{coords}{The coordinates of the vertices, a matrix with two columns.} \item{v}{The ids of the vertices to plot. It should match the number of rows in the \code{coords} argument.} \item{params}{The same as for the clipping function, see above.} } The return value of the plotting function is not used. \code{shapes} can be used to list the names of all installed vertex shapes, by calling it without arguments, or setting the \code{shape} argument to \code{NULL}. If a shape name is given, then the clipping and plotting functions of that shape are returned in a named list. \code{add_shape} can be used to add new vertex shapes to igraph. For this one must give the clipping and plotting functions of the new shape. It is also possible to list the plot/vertex/edge parameters, in the \code{parameters} argument, that the clipping and/or plotting functions can make use of. An example would be a generic regular polygon shape, which can have a parameter for the number of sides. \code{shape_noclip} is a very simple clipping function that the user can use in their own shape definitions. It does no clipping, the edges will be drawn exactly until the listed vertex position coordinates. \code{shape_noplot} is a very simple (and probably not very useful) plotting function, that does not plot anything. } \examples{ # all vertex shapes, minus "raster", that might not be available shapes <- setdiff(shapes(), "") g <- make_ring(length(shapes)) set.seed(42) plot(g, vertex.shape=shapes, vertex.label=shapes, vertex.label.dist=1, vertex.size=15, vertex.size2=15, vertex.pie=lapply(shapes, function(x) if (x=="pie") 2:6 else 0), vertex.pie.color=list(heat.colors(5))) # add new vertex shape, plot nothing with no clipping add_shape("nil") plot(g, vertex.shape="nil") ################################################################# # triangle vertex shape mytriangle <- function(coords, v=NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1/200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } symbols(x=coords[,1], y=coords[,2], bg=vertex.color, stars=cbind(vertex.size, vertex.size, vertex.size), add=TRUE, inches=FALSE) } # clips as a circle add_shape("triangle", clip=shapes("circle")$clip, plot=mytriangle) plot(g, vertex.shape="triangle", vertex.color=rainbow(vcount(g)), vertex.size=seq(10,20,length=vcount(g))) ################################################################# # generic star vertex shape, with a parameter for number of rays mystar <- function(coords, v=NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1/200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } norays <- params("vertex", "norays") if (length(norays) != 1 && !is.null(v)) { norays <- norays[v] } mapply(coords[,1], coords[,2], vertex.color, vertex.size, norays, FUN=function(x, y, bg, size, nor) { symbols(x=x, y=y, bg=bg, stars=matrix(c(size,size/2), nrow=1, ncol=nor*2), add=TRUE, inches=FALSE) }) } # no clipping, edges will be below the vertices anyway add_shape("star", clip=shape_noclip, plot=mystar, parameters=list(vertex.norays=5)) plot(g, vertex.shape="star", vertex.color=rainbow(vcount(g)), vertex.size=seq(10,20,length=vcount(g))) plot(g, vertex.shape="star", vertex.color=rainbow(vcount(g)), vertex.size=seq(10,20,length=vcount(g)), vertex.norays=rep(4:8, length=vcount(g))) ################################################################# # Pictures as vertices. # Similar musicians from last.fm, we start from an artist and # will query two levels. We will use the XML, png and jpeg packages # for this, so these must be available. Otherwise the example is # skipped loadIfYouCan <- function(pkg) suppressWarnings(do.call(require, list(pkg))) if (loadIfYouCan("XML") && loadIfYouCan("png") && loadIfYouCan("jpeg")) { url <- paste(sep="", 'http://ws.audioscrobbler.com/', '2.0/?method=artist.getinfo&artist=\%s', '&api_key=1784468ada3f544faf9172ee8b99fca3') getartist <- function(artist) { cat("Downloading from last.fm. ... ") txt <- readLines(sprintf(url, URLencode(artist))) xml <- xmlTreeParse(txt, useInternal=TRUE) img <- xpathSApply(xml, "/lfm/artist/image[@size='medium'][1]", xmlValue) if (img != "") { con <- url(img, open="rb") bin <- readBin(con, what="raw", n=10^6) close(con) if (grepl("\\\\\\\\.png$", img)) { rast <- readPNG(bin, native=TRUE) } else if (grepl("\\\\\\\\.jpe?g$", img)) { rast <- readJPEG(bin, native=TRUE) } else { rast <- as.raster(matrix()) } } else { rast <- as.raster(numeric()) } sim <- xpathSApply(xml, "/lfm/artist/similar/artist/name", xmlValue) cat("done.\\\\n") list(name=artist, image=rast, similar=sim) } ego <- getartist("Placebo") similar <- lapply(ego$similar, getartist) edges1 <- cbind(ego$name, ego$similar) edges2 <- lapply(similar, function(x) cbind(x$name, x$similar)) edges3 <- rbind(edges1, do.call(rbind, edges2)) edges <- edges3[ edges3[,1] \%in\% c(ego$name, ego$similar) & edges3[,2] \%in\% c(ego$name, ego$similar), ] musnet <- simplify(graph_from_data_frame(edges, dir=FALSE, vertices=data.frame(name=c(ego$name, ego$similar)))) print_all(musnet) V(musnet)$raster <- c(list(ego$image), lapply(similar, "[[", "image")) plot(musnet, layout=layout_as_star, vertex.shape="raster", vertex.label=V(musnet)$name, margin=.2, vertex.size=50, vertex.size2=50, vertex.label.dist=2, vertex.label.degree=0) } else { message("You need the `XML', `png' and `jpeg' packages to run this") } } igraph/man/layout_with_gem.Rd0000644000175100001440000000525313430770475016023 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_gem} \alias{layout_with_gem} \alias{layout.gem} \alias{with_gem} \title{The GEM layout algorithm} \usage{ layout_with_gem(graph, coords = NULL, maxiter = 40 * vcount(graph)^2, temp.max = vcount(graph), temp.min = 1/10, temp.init = sqrt(vcount(graph))) with_gem(...) } \arguments{ \item{graph}{The input graph. Edge directions are ignored.} \item{coords}{If not \code{NULL}, then the starting coordinates should be given here, in a two or three column matrix, depending on the \code{dim} argument.} \item{maxiter}{The maximum number of iterations to perform. Updating a single vertex counts as an iteration. A reasonable default is 40 * n * n, where n is the number of vertices. The original paper suggests 4 * n * n, but this usually only works if the other parameters are set up carefully.} \item{temp.max}{The maximum allowed local temperature. A reasonable default is the number of vertices.} \item{temp.min}{The global temperature at which the algorithm terminates (even before reaching \code{maxiter} iterations). A reasonable default is 1/10.} \item{temp.init}{Initial local temperature of all vertices. A reasonable default is the square root of the number of vertices.} \item{...}{Passed to \code{layout_with_gem}.} } \value{ A numeric matrix with two columns, and as many rows as the number of vertices. } \description{ Place vertices on the plane using the GEM force-directed layout algorithm. } \details{ See the referenced paper below for the details of the algorithm. } \examples{ set.seed(42) g <- make_ring(10) plot(g, layout=layout_with_gem) } \references{ Arne Frick, Andreas Ludwig, Heiko Mehldau: A Fast Adaptive Layout Algorithm for Undirected Graphs, \emph{Proc. Graph Drawing 1994}, LNCS 894, pp. 388-403, 1995. } \seealso{ \code{\link{layout_with_fr}}, \code{\link{plot.igraph}}, \code{\link{tkplot}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/nexus.Rd0000644000175100001440000002135113430770475013762 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/nexus.R \name{print.nexusDatasetInfo} \alias{print.nexusDatasetInfo} \alias{summary.nexusDatasetInfoList} \alias{print.nexusDatasetInfoList} \alias{nexus_list} \alias{nexus} \alias{nexus.list} \alias{nexus.info} \alias{nexus.get} \alias{nexus.search} \alias{nexus_info} \alias{nexus_get} \alias{nexus_search} \alias{nexusDatasetInfo} \alias{[.nexusDatasetInfoList} \title{Query and download from the Nexus network repository} \usage{ \method{print}{nexusDatasetInfo}(x, ...) \method{summary}{nexusDatasetInfoList}(object, ...) \method{print}{nexusDatasetInfoList}(x, ...) nexus_list(tags = NULL, offset = 0, limit = 10, operator = c("or", "and"), order = c("date", "name", "popularity"), nexus.url = igraph_opt("nexus.url")) nexus_info(id, nexus.url = igraph_opt("nexus.url")) nexus_get(id, offset = 0, order = c("date", "name", "popularity"), nexus.url = igraph_opt("nexus.url")) nexus_search(q, offset = 0, limit = 10, order = c("date", "name", "popularity"), nexus.url = igraph_opt("nexus.url")) \method{[}{nexusDatasetInfoList}(x, i) } \arguments{ \item{x, object}{The \code{nexusDatasetInfo} object to print.} \item{\dots}{Currently ignored.} \item{tags}{A character vector, the tags that are searched. If not given (or \code{NULL}), then all datasets are listed.} \item{offset}{An offset to select part of the results. Results are listed from \code{offset}+1.} \item{limit}{The maximum number of results to return.} \item{operator}{A character scalar. If \sQuote{or} (the default), then all datasets that have at least one of the given tags, are returned. If it if \sQuote{and}, then only datasets that have all the given tags, are returned.} \item{order}{The ordering of the results, possible values are: \sQuote{date}, \sQuote{name}, \sQuote{popularity}.} \item{nexus.url}{The URL of the Nexus server. Don't change this from the default, unless you set up your own Nexus server.} \item{id}{The numeric or character id of the data set to query or download. Instead of the data set ids, it is possible to supply a \code{nexusDatasetInfo} or \code{nexusDatasetInfoList} object here directly and then the query is done on the corresponding data set(s).} \item{q}{Nexus search string. See examples below.} \item{i}{Index.} } \value{ \code{nexus_list} and \code{nexus_search} return a list of \code{nexusDatasetInfo} objects. The list also has these attributes: \describe{ \item{size}{The number of data sets returned by the query.} \item{totalsize}{The total number of data sets found for the query.} \item{offset}{The offset parameter of the query.} \item{limit}{The limit parameter of the query.} } \code{nexus_info} returns a single \code{nexusDatasetInfo} object. \code{nexus_get} returns an igraph graph object, or a list of graph objects, if the data set consists of multiple networks. } \description{ The Nexus network repository is an online collection of network data sets. These functions can be used to query it and download data from it, directly as an igraph graph. } \details{ Nexus is an online repository of networks, with an API that allow programatic queries against it, and programatic data download as well. The \code{nexus_list} and \code{nexus_info} functions query the online database. They both return \code{nexusDatasetInfo} objects. \code{nexus_info} returns more information than \code{nexus_list}. \code{nexus_search} searches Nexus, and returns a list of data sets, as \code{nexusDatasetInfo} objects. See below for some search examples. \code{nexus_get} downloads a data set from Nexus, based on its numeric id, or based on a Nexus search string. For search strings, only the first search hit is downloaded, but see also the \code{offset} argument. (If there are not data sets found, then the function returns an error.) The \code{nexusDatasetInfo} objects returned by \code{nexus_list} have the following fields: \describe{ \item{id}{The numeric id of the dataset.} \item{sid}{The character id of the dataset.} \item{name}{Character scalar, the name of the dataset.} \item{vertices/edges}{Character, the number of vertices and edges in the graph(s). Vertices and edges are separated by a slash, and if the data set consists of multiple networks, then they are separated by spaces.} \item{tags}{Character vector, the tags of the dataset. Directed graph have the tags \sQuote{directed}. Undirected graphs are tagged as \sQuote{undirected}. Other common tags are: \sQuote{weighted}, \sQuote{bipartite}, \sQuote{social network}, etc.} \item{networks}{The ids and names of the networks in the data set. The numeric and character id are separated by a slash, and multiple networks are separated by spaces.} } \code{nexusDatasetInfo} objects returned by \code{nexus_info} have the following additional fields: \describe{ \item{date}{Character scalar, e.g. \sQuote{2011-01-09}, the date when the dataset was added to the database.} \item{formats}{Character vector, the data formats in which the data set is available. The various formats are separated by semicolons.} \item{licence}{Character scalar, the licence of the dataset.} \item{licence url}{Character scalar, the URL of the licence of the dataset. Pleaase make sure you consult this before using a dataset.} \item{summary}{Character scalar, the short description of the dataset, this is usually a single sentence.} \item{description}{Character scalar, the full description of the dataset.} \item{citation}{Character scalar, the paper(s) describing the dataset. Please cite these papers if you are using the dataset in your research, the licence of most datasets requires this.} \item{attributes}{A list of lists, each list entry is a graph, vertex or edge attribute and has the following entries: \describe{ \item{type}{Type of the attribute, either \sQuote{graph}, \sQuote{vertex} or \sQuote{edge}.} \item{datatype}{Data type of the attribute, currently it can be \sQuote{numeric} and \sQuote{string}.} \item{name}{Character scalar, the name of the attribute.} \item{description}{Character scalar, the description of the attribute.} } } } The results of the Nexus queries are printed to the screen in a consise format, similar to the format of igraph graphs. A data set list (typically the result of \code{nexus_list} and \code{nexus_search}) looks like this: \preformatted{NEXUS 1-5/18 -- data set list [1] kaptail.4 39/109-223 #18 Kapferer tailor shop [2] condmatcollab2003 31163/120029 #17 Condensed matter collaborations+ [3] condmatcollab 16726/47594 #16 Condensed matter collaborations+ [4] powergrid 4941/6594 #15 Western US power grid [5] celegansneural 297/2359 #14 C. Elegans neural network } Each line here represents a data set, and the following information is given about them: the character id of the data set (e.g. \code{kaptail} or \code{powergrid}), the number of vertices and number of edges in the graph of the data sets. For data sets with multiple graphs, intervals are given here. Then the numeric id of the data set and the reamining space is filled with the name of the data set. Summary information about an individual Nexus data set is printed as \preformatted{NEXUS B--- 39 109-223 #18 kaptail -- Kapferer tailor shop + tags: directed; social network; undirected + nets: 1/KAPFTI2; 2/KAPFTS2; 3/KAPFTI1; 4/KAPFTS1} This is very similar to the header that is used for printing igraph graphs, but there are some differences as well. The four characters after the \code{NEXUS} word give the most important properties of the graph(s): the first is \sQuote{\code{U}} for undirected and \sQuote{\code{D}} for directed graphs, and \sQuote{\code{B}} if the data set contains both directed and undirected graphs. The second is \sQuote{\code{N}} named graphs. The third character is \sQuote{\code{W}} for weighted graphs, the fourth is \sQuote{\code{B}} if the data set contains bipartite graphs. Then the number of vertices and number of edges are printed, for data sets with multiple graphs, the smallest and the largest values are given. Then comes the numeric id, and the string id of the data set. The end of the first line contains the name of the data set. The second row lists the data set tags, and the third row the networks that are included in the data set. Detailed data set information is printed similarly, but it contains more fields. } \section{Examples}{ \preformatted{ nexus_list(tag="weighted") nexus_list(limit=3, order="name") nexus_list(limit=3, order="name")[[1]] nexus_info(2) g <- nexus_get(2) summary(g) ## Data sets related to 'US': nexus_search("US") ## Search for data sets that have 'network' in their name: nexus_search("name:network") ## Any word can match nexus_search("blog or US or karate") } } igraph/man/graph_from_literal.Rd0000644000175100001440000001070413430770475016460 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{graph_from_literal} \alias{graph_from_literal} \alias{graph.formula} \alias{from_literal} \title{Creating (small) graphs via a simple interface} \usage{ graph_from_literal(..., simplify = TRUE) from_literal(...) } \arguments{ \item{...}{For \code{graph_from_literal} the formulae giving the structure of the graph, see details below. For \code{from_literal} all arguments are passed to \code{graph_from_literal}.} \item{simplify}{Logical scalar, whether to call \code{\link{simplify}} on the created graph. By default the graph is simplified, loop and multiple edges are removed.} } \value{ An igraph graph } \description{ This function is useful if you want to create a small (named) graph quickly, it works for both directed and undirected graphs. } \details{ \code{graph_from_literal} is very handy for creating small graphs quickly. You need to supply one or more R expressions giving the structure of the graph. The expressions consist of vertex names and edge operators. An edge operator is a sequence of \sQuote{\code{-}} and \sQuote{\code{+}} characters, the former is for the edges and the latter is used for arrow heads. The edges can be arbitrarily long, ie. you may use as many \sQuote{\code{-}} characters to \dQuote{draw} them as you like. If all edge operators consist of only \sQuote{\code{-}} characters then the graph will be undirected, whereas a single \sQuote{\code{+}} character implies a directed graph. Let us see some simple examples. Without arguments the function creates an empty graph: \preformatted{ graph_from_literal() } A simple undirected graph with two vertices called \sQuote{A} and \sQuote{B} and one edge only: \preformatted{ graph_from_literal(A-B) } Remember that the length of the edges does not matter, so we could have written the following, this creates the same graph: \preformatted{ graph_from_literal( A-----B ) } If you have many disconnected components in the graph, separate them with commas. You can also give isolate vertices. \preformatted{ graph_from_literal( A--B, C--D, E--F, G--H, I, J, K ) } The \sQuote{\code{:}} operator can be used to define vertex sets. If an edge operator connects two vertex sets then every vertex from the first set will be connected to every vertex in the second set. The following form creates a full graph, including loop edges: \preformatted{ graph_from_literal( A:B:C:D -- A:B:C:D ) } In directed graphs, edges will be created only if the edge operator includes a arrow head (\sQuote{+}) \emph{at the end} of the edge: \preformatted{ graph_from_literal( A -+ B -+ C ) graph_from_literal( A +- B -+ C ) graph_from_literal( A +- B -- C ) } Thus in the third example no edge is created between vertices \code{B} and \code{C}. Mutual edges can be also created with a simple edge operator: \preformatted{ graph_from_literal( A +-+ B +---+ C ++ D + E) } Note again that the length of the edge operators is arbitrary, \sQuote{\code{+}}, \sQuote{\code{++}} and \sQuote{\code{+-----+}} have exactly the same meaning. If the vertex names include spaces or other special characters then you need to quote them: \preformatted{ graph_from_literal( "this is" +- "a silly" -+ "graph here" ) } You can include any character in the vertex names this way, even \sQuote{+} and \sQuote{-} characters. See more examples below. } \examples{ # A simple undirected graph g <- graph_from_literal( Alice-Bob-Cecil-Alice, Daniel-Cecil-Eugene, Cecil-Gordon ) g # Another undirected graph, ":" notation g2 <- graph_from_literal( Alice-Bob:Cecil:Daniel, Cecil:Daniel-Eugene:Gordon ) g2 # A directed graph g3 <- graph_from_literal( Alice +-+ Bob --+ Cecil +-- Daniel, Eugene --+ Gordon:Helen ) g3 # A graph with isolate vertices g4 <- graph_from_literal( Alice -- Bob -- Daniel, Cecil:Gordon, Helen ) g4 V(g4)$name # "Arrows" can be arbitrarily long g5 <- graph_from_literal( Alice +---------+ Bob ) g5 # Special vertex names g6 <- graph_from_literal( "+" -- "-", "*" -- "/", "\%\%" -- "\%/\%" ) g6 } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{determimistic constructors} igraph/man/graph_attr_names.Rd0000644000175100001440000000200513430770475016131 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{graph_attr_names} \alias{graph_attr_names} \alias{list.graph.attributes} \alias{attributes} \title{List names of graph attributes} \usage{ graph_attr_names(graph) } \arguments{ \item{graph}{The graph.} } \value{ Character vector, the names of the graph attributes. } \description{ List names of graph attributes } \examples{ g <- make_ring(10) graph_attr_names(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/embed_adjacency_matrix.Rd0000644000175100001440000000754313430770475017270 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{embed_adjacency_matrix} \alias{embed_adjacency_matrix} \title{Spectral Embedding of Adjacency Matrices} \usage{ embed_adjacency_matrix(graph, no, weights = NULL, which = c("lm", "la", "sa"), scaled = TRUE, cvec = graph.strength(graph, weights = weights)/(vcount(graph) - 1), options = igraph.arpack.default) } \arguments{ \item{graph}{The input graph, directed or undirected.} \item{no}{An integer scalar. This value is the embedding dimension of the spectral embedding. Should be smaller than the number of vertices. The largest \code{no}-dimensional non-zero singular values are used for the spectral embedding.} \item{weights}{Optional positive weight vector for calculating a weighted embedding. If the graph has a \code{weight} edge attribute, then this is used by default. In a weighted embedding, the edge weights are used instead of the binary adjacencny matrix.} \item{which}{Which eigenvalues (or singular values, for directed graphs) to use. \sQuote{lm} means the ones with the largest magnitude, \sQuote{la} is the ones (algebraic) largest, and \sQuote{sa} is the (algebraic) smallest eigenvalues. The default is \sQuote{lm}. Note that for directed graphs \sQuote{la} and \sQuote{lm} are the equivalent, because the singular values are used for the ordering.} \item{scaled}{Logical scalar, if \code{FALSE}, then \eqn{U} and \eqn{V} are returned instead of \eqn{X} and \eqn{Y}.} \item{cvec}{A numeric vector, its length is the number vertices in the graph. This vector is added to the diagonal of the adjacency matrix.} \item{options}{A named list containing the parameters for the SVD computation algorithm in ARPACK. By default, the list of values is assigned the values given by \code{\link{igraph.arpack.default}}.} } \value{ A list containing with entries: \item{X}{Estimated latent positions, an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} \item{Y}{\code{NULL} for undirected graphs, the second half of the latent positions for directed graphs, an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} \item{D}{The eigenvalues (for undirected graphs) or the singular values (for directed graphs) calculated by the algorithm.} \item{options}{A named list, information about the underlying ARPACK computation. See \code{\link{arpack}} for the details.} } \description{ Spectral decomposition of the adjacency matrices of graphs. } \details{ This function computes a \code{no}-dimensional Euclidean representation of the graph based on its adjacency matrix, \eqn{A}. This representation is computed via the singular value decomposition of the adjacency matrix, \eqn{A=UDV^T}.In the case, where the graph is a random dot product graph generated using latent position vectors in \eqn{R^{no}} for each vertex, the embedding will provide an estimate of these latent vectors. For undirected graphs the latent positions are calculated as \eqn{X=U^{no}D^{1/2}}{U[no] sqrt(D[no])}, where \eqn{U^{no}}{U[no]} equals to the first \code{no} columns of \eqn{U}, and \eqn{D^{1/2}}{sqrt(D[no])} is a diagonal matrix containing the top \code{no} singular values on the diagonal. For directed graphs the embedding is defined as the pair \eqn{X=U^{no}D^{1/2}}{U[no] sqrt(D[no])} and \eqn{Y=V^{no}D^{1/2}}{V[no] sqrt(D[no])}. (For undirected graphs \eqn{U=V}, so it is enough to keep one of them.) } \examples{ ## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_adjacency_matrix(RDP, 5) } \references{ Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, \emph{Journal of the American Statistical Association}, Vol. 107(499), 2012 } \seealso{ \code{\link{sample_dot_product}} } \keyword{graphs} igraph/man/is_directed.Rd0000644000175100001440000000155413430770475015101 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{is_directed} \alias{is_directed} \alias{is.directed} \title{Check whether a graph is directed} \usage{ is_directed(graph) } \arguments{ \item{graph}{The input graph} } \value{ Logical scalar, whether the graph is directed. } \description{ Check whether a graph is directed } \examples{ g <- make_ring(10) is_directed(g) g2 <- make_ring(10, directed = TRUE) is_directed(g2) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/graph_from_lcf.Rd0000644000175100001440000000224413430770475015570 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{graph_from_lcf} \alias{graph_from_lcf} \alias{graph.lcf} \title{Creating a graph from LCF notation} \usage{ graph_from_lcf(n, shifts, repeats = 1) } \arguments{ \item{n}{Integer, the number of vertices in the graph.} \item{shifts}{Integer vector, the shifts.} \item{repeats}{Integer constant, how many times to repeat the shifts.} } \value{ A graph object. } \description{ LCF is short for Lederberg-Coxeter-Frucht, it is a concise notation for 3-regular Hamiltonian graphs. It constists of three parameters, the number of vertices in the graph, a list of shifts giving additional edges to a cycle backbone and another integer giving how many times the shifts should be performed. See \url{http://mathworld.wolfram.com/LCFNotation.html} for details. } \examples{ # This is the Franklin graph: g1 <- graph_from_lcf(12, c(5,-5), 6) g2 <- make_graph("Franklin") isomorphic(g1, g2) } \seealso{ \code{\link{graph}} can create arbitrary graphs, see also the other functions on the its manual page for creating special graphs. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/bipartite_mapping.Rd0000644000175100001440000000325413430770475016320 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bipartite.R \name{bipartite_mapping} \alias{bipartite_mapping} \alias{bipartite.mapping} \title{Decide whether a graph is bipartite} \usage{ bipartite_mapping(graph) } \arguments{ \item{graph}{The input graph.} } \value{ A named list with two elements: \item{res}{A logical scalar, \code{TRUE} if the can be bipartite, \code{FALSE} otherwise.} \item{type}{A possibly vertex type mapping, a logical vector. If no such mapping exists, then an empty vector.} } \description{ This function decides whether the vertices of a network can be mapped to two vertex types in a way that no vertices of the same type are connected. } \details{ A bipartite graph in igraph has a \sQuote{\code{type}} vertex attribute giving the two vertex types. This function simply checks whether a graph \emph{could} be bipartite. It tries to find a mapping that gives a possible division of the vertices into two classes, such that no two vertices of the same class are connected by an edge. The existence of such a mapping is equivalent of having no circuits of odd length in the graph. A graph with loop edges cannot bipartite. Note that the mapping is not necessarily unique, e.g. if the graph has at least two components, then the vertices in the separate components can be mapped independently. } \examples{ ## A ring has just one loop, so it is fine g <- make_ring(10) bipartite_mapping(g) ## A star is fine, too g2 <- make_star(10) bipartite_mapping(g2) ## A graph containing a triangle is not fine g3 <- make_ring(10) g3 <- add_edges(g3, c(1,3)) bipartite_mapping(g3) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/assortativity.Rd0000644000175100001440000000765113430770475015554 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/assortativity.R \name{assortativity} \alias{assortativity} \alias{assortativity.degree} \alias{assortativity_degree} \alias{assortativity.nominal} \alias{assortativity_nominal} \title{Assortativity coefficient} \usage{ assortativity(graph, types1, types2 = NULL, directed = TRUE) assortativity_nominal(graph, types, directed = TRUE) assortativity_degree(graph, directed = TRUE) } \arguments{ \item{graph}{The input graph, it can be directed or undirected.} \item{types1}{The vertex values, these can be arbitrary numeric values.} \item{types2}{A second value vector to be using for the incoming edges when calculating assortativity for a directed graph. Supply \code{NULL} here if you want to use the same values for outgoing and incoming edges. This argument is ignored (with a warning) if it is not \code{NULL} and undirected assortativity coefficient is being calculated.} \item{directed}{Logical scalar, whether to consider edge directions for directed graphs. This argument is ignored for undirected graphs. Supply \code{TRUE} here to do the natural thing, i.e. use directed version of the measure for directed graphs and the undirected version for undirected graphs.} \item{types}{Vector giving the vertex types. They as assumed to be integer numbers, starting with one. Non-integer values are converted to integers with \code{\link{as.integer}}.} } \value{ A single real number. } \description{ The assortativity coefficient is positive is similar vertices (based on some external property) tend to connect to each, and negative otherwise. } \details{ The assortativity coefficient measures the level of homophyly of the graph, based on some vertex labeling or values assigned to vertices. If the coefficient is high, that means that connected vertices tend to have the same labels or similar assigned values. M.E.J. Newman defined two kinds of assortativity coefficients, the first one is for categorical labels of vertices. \code{assortativity_nominal} calculates this measure. It is defines as \deqn{r=\frac{\sum_i e_{ii}-\sum_i a_i b_i}{1-\sum_i a_i b_i}}{ r=(sum(e(i,i), i) - sum(a(i)b(i), i)) / (1 - sum(a(i)b(i), i))} where \eqn{e_{ij}}{e(i,j)} is the fraction of edges connecting vertices of type \eqn{i} and \eqn{j}, \eqn{a_i=\sum_j e_{ij}}{a(i)=sum(e(i,j), j)} and \eqn{b_j=\sum_i e_{ij}}{b(j)=sum(e(i,j), i)}. The second assortativity variant is based on values assigned to the vertices. \code{assortativity} calculates this measure. It is defined as \deqn{r=\frac1{\sigma_q^2}\sum_{jk} jk(e_{jk}-q_j q_k)}{ sum(jk(e(j,k)-q(j)q(k)), j, k) / sigma(q)^2} for undirected graphs (\eqn{q_i=\sum_j e_{ij}}{q(i)=sum(e(i,j), j)}) and as \deqn{r=\frac1{\sigma_o\sigma_i}\sum_{jk}jk(e_{jk}-q_j^o q_k^i)}{ sum(jk(e(j,k)-qout(j)qin(k)), j, k) / sigma(qin) / sigma(qout) } for directed ones. Here \eqn{q_i^o=\sum_j e_{ij}}{qout(i)=sum(e(i,j), j)}, \eqn{q_i^i=\sum_j e_{ji}}{qin(i)=sum(e(j,i), j)}, moreover, \eqn{\sigma_q}{sigma(q)}, \eqn{sigma_o}{sigma(qout)} and \eqn{sigma_i}{sigma(qin)} are the standard deviations of \eqn{q}, \eqn{q^o}{qout} and \eqn{q^i}{qin}, respectively. The reason of the difference is that in directed networks the relationship is not symmetric, so it is possible to assign different values to the outgoing and the incoming end of the edges. \code{assortativity_degree} uses vertex degree (minus one) as vertex values and calls \code{assortativity}. } \examples{ # random network, close to zero assortativity_degree(sample_gnp(10000, 3/10000)) # BA model, tends to be dissortative assortativity_degree(sample_pa(10000, m=4)) } \references{ M. E. J. Newman: Mixing patterns in networks, \emph{Phys. Rev. E} 67, 026126 (2003) \url{http://arxiv.org/abs/cond-mat/0209450} M. E. J. Newman: Assortative mixing in networks, \emph{Phys. Rev. Lett.} 89, 208701 (2002) \url{http://arxiv.org/abs/cond-mat/0205405/} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/as_long_data_frame.Rd0000644000175100001440000000174313430770475016410 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_long_data_frame} \alias{as_long_data_frame} \title{Convert a graph to a long data frame} \usage{ as_long_data_frame(graph) } \arguments{ \item{graph}{Input graph} } \value{ A long data frame. } \description{ A long data frame contains all metadata about both the vertices and edges of the graph. It contains one row for each edge, and all metadata about that edge and its incident vertices are included in that row. The names of the columns that contain the metadata of the incident vertices are prefixed with \code{from_} and \code{to_}. The first two columns are always named \code{from} and \code{to} and they contain the numeric ids of the incident vertices. The rows are listed in the order of numeric vertex ids. } \examples{ g <- make_(ring(10), with_vertex_(name = letters[1:10], color = "red"), with_edge_(weight = 1:10, color = "green") ) as_long_data_frame(g) } igraph/man/page_rank.Rd0000644000175100001440000001411413430770475014546 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{page_rank} \alias{page_rank} \alias{page.rank} \alias{page.rank.old} \alias{page_rank_old} \title{The Page Rank algorithm} \usage{ page_rank(graph, algo = c("prpack", "arpack", "power"), vids = V(graph), directed = TRUE, damping = 0.85, personalized = NULL, weights = NULL, options = NULL) page_rank_old(graph, vids = V(graph), directed = TRUE, niter = 1000, eps = 0.001, damping = 0.85, old = FALSE) } \arguments{ \item{graph}{The graph object.} \item{algo}{Character scalar, which implementation to use to carry out the calculation. The default is \code{"prpack"}, which uses the PRPACK library (https://github.com/dgleich/prpack). This is a new implementation in igraph version 0.7, and the suggested one, as it is the most stable and the fastest for all but small graphs. \code{"arpack"} uses the ARPACK library, the default implementation from igraph version 0.5 until version 0.7. \code{power} uses a simple implementation of the power method, this was the default in igraph before version 0.5 and is the same as calling \code{page_rank_old}.} \item{vids}{The vertices of interest.} \item{directed}{Logical, if true directed paths will be considered for directed graphs. It is ignored for undirected graphs.} \item{damping}{The damping factor (\sQuote{d} in the original paper).} \item{personalized}{Optional vector giving a probability distribution to calculate personalized PageRank. For personalized PageRank, the probability of jumping to a node when abandoning the random walk is not uniform, but it is given by this vector. The vector should contains an entry for each vertex and it will be rescaled to sum up to one.} \item{weights}{A numerical vector or \code{NULL}. This argument can be used to give edge weights for calculating the weighted PageRank of vertices. If this is \code{NULL} and the graph has a \code{weight} edge attribute then that is used. If \code{weights} is a numerical vector then it used, even if the graph has a \code{weights} edge attribute. If this is \code{NA}, then no edge weights are used (even if the graph has a \code{weight} edge attribute. This function interprets edge weights as connection strengths. In the random surfer model, an edge with a larger weight is more likely to be selected by the surfer.} \item{options}{Either a named list, to override some ARPACK options. See \code{\link{arpack}} for details; or a named list to override the default options for the power method (if \code{algo="power"}). The default options for the power method are \code{niter=1000} and \code{eps=0.001}. This argument is ignored if the PRPACK implementation is used.} \item{niter}{The maximum number of iterations to perform.} \item{eps}{The algorithm will consider the calculation as complete if the difference of PageRank values between iterations change less than this value for every node.} \item{old}{A logical scalar, whether the old style (pre igraph 0.5) normalization to use. See details below.} } \value{ For \code{page_rank} a named list with entries: \item{vector}{A numeric vector with the PageRank scores.} \item{value}{The eigenvalue corresponding to the eigenvector with the page rank scores. It should be always exactly one.} \item{options}{Some information about the underlying ARPACK calculation. See \code{\link{arpack}} for details. This entry is \code{NULL} if not the ARPACK implementation was used.} For \code{page_rank_old} a numeric vector of Page Rank scores. } \description{ Calculates the Google PageRank for the specified vertices. } \details{ For the explanation of the PageRank algorithm, see the following webpage: \url{http://infolab.stanford.edu/~backrub/google.html}, or the following reference: Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual Web Search Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane, Australia, April 1998. igraph 0.5 (and later) contains two PageRank calculation implementations. The \code{page_rank} function uses ARPACK to perform the calculation, see also \code{\link{arpack}}. The \code{page_rank_old} function performs a simple power method, this is the implementation that was available under the name \code{page_rank} in pre 0.5 igraph versions. Note that \code{page_rank_old} has an argument called \code{old}. If this argument is \code{FALSE} (the default), then the proper PageRank algorithm is used, i.e. \eqn{(1-d)/n} is added to the weighted PageRank of vertices to calculate the next iteration. If this argument is \code{TRUE} then \eqn{(1-d)} is added, just like in the PageRank paper; \eqn{d} is the damping factor, and \eqn{n} is the total number of vertices. A further difference is that the old implementation does not renormalize the page rank vector after each iteration. Note that the \code{old=FALSE} method is not stable, is does not necessarily converge to a fixed point. It should be avoided for new code, it is only included for compatibility with old igraph versions. Please note that the PageRank of a given vertex depends on the PageRank of all other vertices, so even if you want to calculate the PageRank for only some of the vertices, all of them must be calculated. Requesting the PageRank for only some of the vertices does not result in any performance increase at all. Since the calculation is an iterative process, the algorithm is stopped after a given count of iterations or if the PageRank value differences between iterations are less than a predefined value. } \examples{ g <- sample_gnp(20, 5/20, directed=TRUE) page_rank(g)$vector g2 <- make_star(10) page_rank(g2)$vector # Personalized PageRank g3 <- make_ring(10) page_rank(g3)$vector reset <- seq(vcount(g3)) page_rank(g3, personalized=reset)$vector } \references{ Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual Web Search Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane, Australia, April 1998. } \seealso{ Other centrality scores: \code{\link{closeness}}, \code{\link{betweenness}}, \code{\link{degree}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/modularity.igraph.Rd0000644000175100001440000000613213430770475016262 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{modularity.igraph} \alias{modularity.igraph} \alias{modularity} \alias{modularity_matrix} \alias{mod.matrix} \title{Modularity of a community structure of a graph} \usage{ \method{modularity}{igraph}(x, membership, weights = NULL, ...) modularity_matrix(graph, membership, weights = NULL) } \arguments{ \item{x, graph}{The input graph.} \item{membership}{Numeric vector, for each vertex it gives its community. The communities are numbered from one.} \item{weights}{If not \code{NULL} then a numeric vector giving edge weights.} \item{\dots}{Additional arguments, none currently.} } \value{ For \code{modularity} a numeric scalar, the modularity score of the given configuration. For \code{modularity_matrix} a numeic square matrix, its order is the number of vertices in the graph. } \description{ This function calculates how modular is a given division of a graph into subgraphs. } \details{ \code{modularity} calculates the modularity of a graph with respect to the given \code{membership} vector. The modularity of a graph with respect to some division (or vertex types) measures how good the division is, or how separated are the different vertex types from each other. It defined as \deqn{Q=\frac{1}{2m} \sum_{i,j} (A_{ij}-\frac{k_ik_j}{2m})\delta(c_i,c_j),}{Q=1/(2m) * sum( (Aij-ki*kj/(2m) ) delta(ci,cj),i,j),} here \eqn{m} is the number of edges, \eqn{A_{ij}}{Aij} is the element of the \eqn{A} adjacency matrix in row \eqn{i} and column \eqn{j}, \eqn{k_i}{ki} is the degree of \eqn{i}, \eqn{k_j}{kj} is the degree of \eqn{j}, \eqn{c_i}{ci} is the type (or component) of \eqn{i}, \eqn{c_j}{cj} that of \eqn{j}, the sum goes over all \eqn{i} and \eqn{j} pairs of vertices, and \eqn{\delta(x,y)}{delta(x,y)} is 1 if \eqn{x=y} and 0 otherwise. If edge weights are given, then these are considered as the element of the \eqn{A} adjacency matrix, and \eqn{k_i}{ki} is the sum of weights of adjacent edges for vertex \eqn{i}. \code{modularity_matrix} calculates the modularity matrix. This is a dense matrix, and it is defined as the difference of the adjacency matrix and the configuration model null model matrix. In other words element \eqn{M_{ij}}{M[i,j]} is given as \eqn{A_{ij}-d_i d_j/(2m)}{A[i,j]-d[i]d[j]/(2m)}, where \eqn{A_{ij}}{A[i,j]} is the (possibly weighted) adjacency matrix, \eqn{d_i}{d[i]} is the degree of vertex \eqn{i}, and \eqn{m} is the number of edges (or the total weights in the graph, if it is weighed). } \examples{ g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) wtc <- cluster_walktrap(g) modularity(wtc) modularity(g, membership(wtc)) } \references{ Clauset, A.; Newman, M. E. J. & Moore, C. Finding community structure in very large networks, \emph{Phyisical Review E} 2004, 70, 066111 } \seealso{ \code{\link{cluster_walktrap}}, \code{\link{cluster_edge_betweenness}}, \code{\link{cluster_fast_greedy}}, \code{\link{cluster_spinglass}} for various community detection methods. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/fit_power_law.Rd0000644000175100001440000001263613430770475015467 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/fit.R \name{fit_power_law} \alias{fit_power_law} \alias{power.law.fit} \title{Fitting a power-law distribution function to discrete data} \usage{ fit_power_law(x, xmin = NULL, start = 2, force.continuous = FALSE, implementation = c("plfit", "R.mle"), ...) } \arguments{ \item{x}{The data to fit, a numeric vector. For implementation \sQuote{\code{R.mle}} the data must be integer values. For the \sQuote{\code{plfit}} implementation non-integer values might be present and then a continuous power-law distribution is fitted.} \item{xmin}{Numeric scalar, or \code{NULL}. The lower bound for fitting the power-law. If \code{NULL}, the smallest value in \code{x} will be used for the \sQuote{\code{R.mle}} implementation, and its value will be automatically determined for the \sQuote{\code{plfit}} implementation. This argument makes it possible to fit only the tail of the distribution.} \item{start}{Numeric scalar. The initial value of the exponent for the minimizing function, for the \sQuote{\code{R.mle}} implementation. Ususally it is safe to leave this untouched.} \item{force.continuous}{Logical scalar. Whether to force a continuous distribution for the \sQuote{\code{plfit}} implementation, even if the sample vector contains integer values only (by chance). If this argument is false, igraph will assume a continuous distribution if at least one sample is non-integer and assume a discrete distribution otherwise.} \item{implementation}{Character scalar. Which implementation to use. See details below.} \item{\dots}{Additional arguments, passed to the maximum likelihood optimizing function, \code{\link[stats4]{mle}}, if the \sQuote{\code{R.mle}} implementation is chosen. It is ignored by the \sQuote{\code{plfit}} implementation.} } \value{ Depends on the \code{implementation} argument. If it is \sQuote{\code{R.mle}}, then an object with class \sQuote{\code{mle}}. It can be used to calculate confidence intervals and log-likelihood. See \code{\link[stats4]{mle-class}} for details. If \code{implementation} is \sQuote{\code{plfit}}, then the result is a named list with entries: \item{continuous}{Logical scalar, whether the fitted power-law distribution was continuous or discrete.} \item{alpha}{Numeric scalar, the exponent of the fitted power-law distribution.} \item{xmin}{Numeric scalar, the minimum value from which the power-law distribution was fitted. In other words, only the values larger than \code{xmin} were used from the input vector.} \item{logLik}{Numeric scalar, the log-likelihood of the fitted parameters.} \item{KS.stat}{Numeric scalar, the test statistic of a Kolmogorov-Smirnov test that compares the fitted distribution with the input vector. Smaller scores denote better fit.} \item{KS.p}{Numeric scalar, the p-value of the Kolmogorov-Smirnov test. Small p-values (less than 0.05) indicate that the test rejected the hypothesis that the original data could have been drawn from the fitted power-law distribution.} } \description{ \code{fit_power_law} fits a power-law distribution to a data set. } \details{ This function fits a power-law distribution to a vector containing samples from a distribution (that is assumed to follow a power-law of course). In a power-law distribution, it is generally assumed that \eqn{P(X=x)} is proportional to \eqn{x^{-alpha}}{x^-alpha}, where \eqn{x} is a positive number and \eqn{\alpha}{alpha} is greater than 1. In many real-world cases, the power-law behaviour kicks in only above a threshold value \eqn{x_{min}}{xmin}. The goal of this function is to determine \eqn{\alpha}{alpha} if \eqn{x_{min}}{xmin} is given, or to determine \eqn{x_{min}}{xmin} and the corresponding value of \eqn{\alpha}{alpha}. \code{fit_power_law} provides two maximum likelihood implementations. If the \code{implementation} argument is \sQuote{\code{R.mle}}, then the BFGS optimization (see \link[stats4]{mle}) algorithm is applied. The additional arguments are passed to the mle function, so it is possible to change the optimization method and/or its parameters. This implementation can \emph{not} to fit the \eqn{x_{min}}{xmin} argument, so use the \sQuote{\code{plfit}} implementation if you want to do that. The \sQuote{\code{plfit}} implementation also uses the maximum likelihood principle to determine \eqn{\alpha}{alpha} for a given \eqn{x_{min}}{xmin}; When \eqn{x_{min}}{xmin} is not given in advance, the algorithm will attempt to find itsoptimal value for which the \eqn{p}-value of a Kolmogorov-Smirnov test between the fitted distribution and the original sample is the largest. The function uses the method of Clauset, Shalizi and Newman to calculate the parameters of the fitted distribution. See references below for the details. } \examples{ # This should approximately yield the correct exponent 3 g <- barabasi.game(1000) # increase this number to have a better estimate d <- degree(g, mode="in") fit1 <- fit_power_law(d+1, 10) fit2 <- fit_power_law(d+1, 10, implementation="R.mle") fit1$alpha stats4::coef(fit2) fit1$logLik stats4::logLik(fit2) } \references{ Power laws, Pareto distributions and Zipf's law, M. E. J. Newman, \emph{Contemporary Physics}, 46, 323-351, 2005. Aaron Clauset, Cosma R .Shalizi and Mark E.J. Newman: Power-law distributions in empirical data. SIAM Review 51(4):661-703, 2009. } \seealso{ \code{\link[stats4]{mle}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/min_cut.Rd0000644000175100001440000000613713430770475014263 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{min_cut} \alias{min_cut} \alias{graph.mincut} \title{Minimum cut in a graph} \usage{ min_cut(graph, source = NULL, target = NULL, capacity = NULL, value.only = TRUE) } \arguments{ \item{graph}{The input graph.} \item{source}{The id of the source vertex.} \item{target}{The id of the target vertex (sometimes also called sink).} \item{capacity}{Vector giving the capacity of the edges. If this is \code{NULL} (the default) then the \code{capacity} edge attribute is used.} \item{value.only}{Logical scalar, if \code{TRUE} only the minumum cut value is returned, if \code{FALSE} the edges in the cut and a the two (or more) partitions are also returned.} } \value{ For \code{min_cut} a numeric constant, the value of the minimum cut, except if \code{value.only = FALSE}. In this case a named list with components: \item{value}{Numeric scalar, the cut value.} \item{cut}{Numeric vector, the edges in the cut.} \item{partition1}{The vertices in the first partition after the cut edges are removed. Note that these vertices might be actually in different components (after the cut edges are removed), as the graph may fall apart into more than two components.} \item{partition2}{The vertices in the second partition after the cut edges are removed. Note that these vertices might be actually in different components (after the cut edges are removed), as the graph may fall apart into more than two components.} } \description{ \code{min_cut} calculates the minimum st-cut between two vertices in a graph (if the \code{source} and \code{target} arguments are given) or the minimum cut of the graph (if both \code{source} and \code{target} are \code{NULL}). } \details{ The minimum st-cut between \code{source} and \code{target} is the minimum total weight of edges needed to remove to eliminate all paths from \code{source} to \code{target}. The minimum cut of a graph is the minimum total weight of the edges needed to remove to separate the graph into (at least) two components. (Which is to make the graph \emph{not} strongly connected in the directed case.) The maximum flow between two vertices in a graph is the same as the minimum st-cut, so \code{max_flow} and \code{min_cut} essentially calculate the same quantity, the only difference is that \code{min_cut} can be invoked without giving the \code{source} and \code{target} arguments and then minimum of all possible minimum cuts is calculated. For undirected graphs the Stoer-Wagner algorithm (see reference below) is used to calculate the minimum cut. } \examples{ g <- make_ring(100) min_cut(g, capacity=rep(1,vcount(g))) min_cut(g, value.only=FALSE, capacity=rep(1,vcount(g))) g2 <- graph( c(1,2,2,3,3,4, 1,6,6,5,5,4, 4,1) ) E(g2)$capacity <- c(3,1,2, 10,1,3, 2) min_cut(g2, value.only=FALSE) } \references{ M. Stoer and F. Wagner: A simple min-cut algorithm, \emph{Journal of the ACM}, 44 585-591, 1997. } \seealso{ \code{\link{max_flow}} for the related maximum flow problem, \code{\link{distances}}, \code{\link{edge_connectivity}}, \code{\link{vertex_connectivity}} } igraph/man/layout_with_fr.Rd0000644000175100001440000001073413430770475015662 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_fr} \alias{layout_with_fr} \alias{with_fr} \title{The Fruchterman-Reingold layout algorithm} \usage{ layout_with_fr(graph, coords = NULL, dim = 2, niter = 500, start.temp = sqrt(vcount(graph)), grid = c("auto", "grid", "nogrid"), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, coolexp, maxdelta, area, repulserad, maxiter) with_fr(...) } \arguments{ \item{graph}{The graph to lay out. Edge directions are ignored.} \item{coords}{Optional starting positions for the vertices. If this argument is not \code{NULL} then it should be an appropriate matrix of starting coordinates.} \item{dim}{Integer scalar, 2 or 3, the dimension of the layout. Two dimensional layouts are places on a plane, three dimensional ones in the 3d space.} \item{niter}{Integer scalar, the number of iterations to perform.} \item{start.temp}{Real scalar, the start temperature. This is the maximum amount of movement alloved along one axis, within one step, for a vertex. Currently it is decreased linearly to zero during the iteration.} \item{grid}{Character scalar, whether to use the faster, but less accurate grid based implementation of the algorithm. By default (\dQuote{auto}), the grid-based implementation is used if the graph has more than one thousand vertices.} \item{weights}{A vector giving edge weights. The \code{weight} edge attribute is used by default, if present. If weights are given, then the attraction along the edges will be multiplied by the given edge weights. This places vertices connected with a highly weighted edge closer to each other.} \item{minx}{If not \code{NULL}, then it must be a numeric vector that gives lower boundaries for the \sQuote{x} coordinates of the vertices. The length of the vector must match the number of vertices in the graph.} \item{maxx}{Similar to \code{minx}, but gives the upper boundaries.} \item{miny}{Similar to \code{minx}, but gives the lower boundaries of the \sQuote{y} coordinates.} \item{maxy}{Similar to \code{minx}, but gives the upper boundaries of the \sQuote{y} coordinates.} \item{minz}{Similar to \code{minx}, but gives the lower boundaries of the \sQuote{z} coordinates.} \item{maxz}{Similar to \code{minx}, but gives the upper boundaries of the \sQuote{z} coordinates.} \item{coolexp, maxdelta, area, repulserad}{These arguments are not supported from igraph version 0.8.0 and are ignored (with a warning).} \item{maxiter}{A deprecated synonym of \code{niter}, for compatibility.} \item{...}{Passed to \code{layout_with_fr}.} } \value{ A two- or three-column matrix, each row giving the coordinates of a vertex, according to the ids of the vertex ids. } \description{ Place vertices on the plane using the force-directed layout algorithm by Fruchterman and Reingold. } \details{ See the referenced paper below for the details of the algorithm. This function was rewritten from scratch in igraph version 0.8.0. } \examples{ # Fixing ego g <- sample_pa(20, m=2) minC <- rep(-Inf, vcount(g)) maxC <- rep(Inf, vcount(g)) minC[1] <- maxC[1] <- 0 co <- layout_with_fr(g, minx=minC, maxx=maxC, miny=minC, maxy=maxC) co[1,] plot(g, layout=co, vertex.size=30, edge.arrow.size=0.2, vertex.label=c("ego", rep("", vcount(g)-1)), rescale=FALSE, xlim=range(co[,1]), ylim=range(co[,2]), vertex.label.dist=0, vertex.label.color="red") axis(1) axis(2) } \references{ Fruchterman, T.M.J. and Reingold, E.M. (1991). Graph Drawing by Force-directed Placement. \emph{Software - Practice and Experience}, 21(11):1129-1164. } \seealso{ \code{\link{layout_with_drl}}, \code{\link{layout_with_kk}} for other layout algorithms. Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/as_adjacency_matrix.Rd0000644000175100001440000000537013430770475016613 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_adjacency_matrix} \alias{as_adjacency_matrix} \alias{get.adjacency} \alias{as_adj} \title{Convert a graph to an adjacency matrix} \usage{ as_adjacency_matrix(graph, type = c("both", "upper", "lower"), attr = NULL, edges = FALSE, names = TRUE, sparse = igraph_opt("sparsematrices")) as_adj(graph, type = c("both", "upper", "lower"), attr = NULL, edges = FALSE, names = TRUE, sparse = igraph_opt("sparsematrices")) } \arguments{ \item{graph}{The graph to convert.} \item{type}{Gives how to create the adjacency matrix for undirected graphs. It is ignored for directed graphs. Possible values: \code{upper}: the upper right triangle of the matrix is used, \code{lower}: the lower left triangle of the matrix is used. \code{both}: the whole matrix is used, a symmetric matrix is returned.} \item{attr}{Either \code{NULL} or a character string giving an edge attribute name. If \code{NULL} a traditional adjacency matrix is returned. If not \code{NULL} then the values of the given edge attribute are included in the adjacency matrix. If the graph has multiple edges, the edge attribute of an arbitrarily chosen edge (for the multiple edges) is included. This argument is ignored if \code{edges} is \code{TRUE}. Note that this works only for certain attribute types. If the \code{sparse} argumen is \code{TRUE}, then the attribute must be either logical or numeric. If the \code{sparse} argument is \code{FALSE}, then character is also allowed. The reason for the difference is that the \code{Matrix} package does not support character sparse matrices yet.} \item{edges}{Logical scalar, whether to return the edge ids in the matrix. For non-existant edges zero is returned.} \item{names}{Logical constant, whether to assign row and column names to the matrix. These are only assigned if the \code{name} vertex attribute is present in the graph.} \item{sparse}{Logical scalar, whether to create a sparse matrix. The \sQuote{\code{Matrix}} package must be installed for creating sparse matrices.} } \value{ A \code{vcount(graph)} by \code{vcount(graph)} (usually) numeric matrix. } \description{ Sometimes it is useful to work with a standard representation of a graph, like an adjacency matrix. } \details{ \code{as_adjacency_matrix} returns the adjacency matrix of a graph, a regular matrix if \code{sparse} is \code{FALSE}, or a sparse matrix, as defined in the \sQuote{\code{Matrix}} package, if \code{sparse} if \code{TRUE}. } \examples{ g <- sample_gnp(10, 2/10) as_adjacency_matrix(g) V(g)$name <- letters[1:vcount(g)] as_adjacency_matrix(g) E(g)$weight <- runif(ecount(g)) as_adjacency_matrix(g, attr="weight") } \seealso{ \code{\link{graph_from_adjacency_matrix}}, \code{\link{read_graph}} } igraph/man/constraint.Rd0000644000175100001440000000361313430770476015006 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{constraint} \alias{constraint} \title{Burt's constraint} \usage{ constraint(graph, nodes = V(graph), weights = NULL) } \arguments{ \item{graph}{A graph object, the input graph.} \item{nodes}{The vertices for which the constraint will be calculated. Defaults to all vertices.} \item{weights}{The weights of the edges. If this is \code{NULL} and there is a \code{weight} edge attribute this is used. If there is no such edge attribute all edges will have the same weight.} } \value{ A numeric vector of constraint scores } \description{ Given a graph, \code{constraint} calculates Burt's constraint for each vertex. } \details{ Burt's constraint is higher if ego has less, or mutually stronger related (i.e. more redundant) contacts. Burt's measure of constraint, \eqn{C_i}{C[i]}, of vertex \eqn{i}'s ego network \eqn{V_i}{V[i]}, is defined for directed and valued graphs, \deqn{C_i=\sum_{j \in V_i \setminus \{i\}} (p_{ij}+\sum_{q \in V_i \setminus \{i,j\}} p_{iq} p_{qj})^2}{ C[i] = sum( [sum( p[i,j] + p[i,q] p[q,j], q in V[i], q != i,j )]^2, j in V[i], j != i). } for a graph of order (ie. number of vertices) \eqn{N}, where proportional tie strengths are defined as \deqn{p_{ij} = \frac{a_{ij}+a_{ji}}{\sum_{k \in V_i \setminus \{i\}}(a_{ik}+a_{ki})},}{ p[i,j]=(a[i,j]+a[j,i]) / sum(a[i,k]+a[k,i], k in V[i], k != i), } \eqn{a_{ij}}{a[i,j]} are elements of \eqn{A} and the latter being the graph adjacency matrix. For isolated vertices, constraint is undefined. } \examples{ g <- sample_gnp(20, 5/20) constraint(g) } \references{ Burt, R.S. (2004). Structural holes and good ideas. \emph{American Journal of Sociology} 110, 349-399. } \author{ Jeroen Bruggeman (\url{https://sites.google.com/site/jebrug/jeroen-bruggeman-social-science}) and Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/curve_multiple.Rd0000644000175100001440000000245213430770475015660 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.common.R \name{curve_multiple} \alias{curve_multiple} \alias{autocurve.edges} \title{Optimal edge curvature when plotting graphs} \usage{ curve_multiple(graph, start = 0.5) } \arguments{ \item{graph}{The input graph.} \item{start}{The curvature at the two extreme edges. All edges will have a curvature between \code{-start} and \code{start}, spaced equally.} } \value{ A numeric vector, its length is the number of edges in the graph. } \description{ If graphs have multiple edges, then drawing them as straight lines does not show them when plotting the graphs; they will be on top of each other. One solution is to bend the edges, with diffenent curvature, so that all of them are visible. } \details{ \code{curve_multiple} calculates the optimal \code{edge.curved} vector for plotting a graph with multiple edges, so that all edges are visible. } \examples{ g <- graph( c(0,1,1,0,1,2,1,3,1,3,1,3, 2,3,2,3,2,3,2,3,0,1)+1 ) curve_multiple(g) \dontrun{ set.seed(42) plot(g) } } \seealso{ \code{\link{igraph.plotting}} for all plotting parameters, \code{\link{plot.igraph}}, \code{\link{tkplot}} and \code{\link{rglplot}} for plotting functions. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/c.igraph.es.Rd0000644000175100001440000000233413430770475014721 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{c.igraph.es} \alias{c.igraph.es} \title{Concatenate edge sequences} \usage{ \method{c}{igraph.es}(..., recursive = FALSE) } \arguments{ \item{...}{The edge sequences to concatenate. They must all refer to the same graph.} \item{recursive}{Ignored, included for S3 compatibility with the base \code{c} function.} } \value{ An edge sequence, the input sequences concatenated. } \description{ Concatenate edge sequences } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(E(g)[1], E(g)['A|B'], E(g)[1:4]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/motifs.Rd0000644000175100001440000000265313430770475014125 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/motifs.R \name{motifs} \alias{motifs} \alias{graph.motifs} \title{Graph motifs} \usage{ motifs(graph, size = 3, cut.prob = rep(0, size)) } \arguments{ \item{graph}{Graph object, the input graph.} \item{size}{The size of the motif, currently 3 and 4 are supported only.} \item{cut.prob}{Numeric vector giving the probabilities that the search graph is cut at a certain level. Its length should be the same as the size of the motif (the \code{size} argument). By default no cuts are made.} } \value{ \code{motifs} returns a numeric vector, the number of occurences of each motif in the graph. The motifs are ordered by their isomorphism classes. Note that for unconnected subgraphs, which are not considered to be motifs, the result will be \code{NA}. } \description{ Graph motifs are small connected subgraphs with a well-defined structure. These functions search a graph for various motifs. } \details{ \code{motifs} searches a graph for motifs of a given size and returns a numeric vector containing the number of different motifs. The order of the motifs is defined by their isomorphism class, see \code{\link{isomorphism_class}}. } \examples{ g <- barabasi.game(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3) } \seealso{ \code{\link{isomorphism_class}} Other graph motifs: \code{\link{count_motifs}}, \code{\link{sample_motifs}} } \concept{graph motifs} igraph/man/diverging_pal.Rd0000644000175100001440000000254213430770475015433 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/palette.R \name{diverging_pal} \alias{diverging_pal} \title{Diverging palette} \usage{ diverging_pal(n) } \arguments{ \item{n}{The number of colors in the palette. The maximum is eleven currently.} } \value{ A character vector of RGB color codes. } \description{ This is the \sQuote{PuOr} palette from \url{http://colorbrewer2.org}. It has at most eleven colors. } \details{ This is similar to \code{\link{sequential_pal}}, but it also puts emphasis on the mid-range values, plus the the two extreme ends. Use this palette, if you have such a quantity to mark with vertex colors. } \examples{ \dontrun{ library(igraphdata) data(foodwebs) fw <- foodwebs[[1]] \%>\% induced_subgraph(V(.)[ECO == 1]) \%>\% add_layout_(with_fr()) \%>\% set_vertex_attr("label", value = seq_len(gorder(.))) \%>\% set_vertex_attr("size", value = 10) \%>\% set_edge_attr("arrow.size", value = 0.3) V(fw)$color <- scales::dscale(V(fw)$Biomass \%>\% cut(10), diverging_pal) plot(fw) data(karate) karate <- karate \%>\% add_layout_(with_kk()) \%>\% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) \%>\% cut(5), diverging_pal) plot(karate) } } \seealso{ Other palettes: \code{\link{categorical_pal}}, \code{\link{r_pal}}, \code{\link{sequential_pal}} } \concept{palettes} igraph/man/ego.Rd0000644000175100001440000000573513430770476013403 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{ego_size} \alias{ego_size} \alias{ego} \alias{neighborhood} \alias{neighborhood.size} \alias{graph.neighborhood} \alias{ego_graph} \alias{connect.neighborhood} \alias{connect} \alias{make_ego_graph} \title{Neighborhood of graph vertices} \usage{ ego_size(graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0) ego(graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0) make_ego_graph(graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0) } \arguments{ \item{graph}{The input graph.} \item{order}{Integer giving the order of the neighborhood.} \item{nodes}{The vertices for which the calculation is performed.} \item{mode}{Character constant, it specifies how to use the direction of the edges if a directed graph is analyzed. For \sQuote{out} only the outgoing edges are followed, so all vertices reachable from the source vertex in at most \code{order} steps are counted. For \sQuote{"in"} all vertices from which the source vertex is reachable in at most \code{order} steps are counted. \sQuote{"all"} ignores the direction of the edges. This argument is ignored for undirected graphs.} \item{mindist}{The minimum distance to include the vertex in the result.} } \value{ \code{ego_size} returns with an integer vector. \code{ego} returns with a list of integer vectors. \code{make_ego_graph} returns with a list of graphs. \code{connect} returns with a new graph object. } \description{ These functions find the vertices not farther than a given limit from another fixed vertex, these are called the neighborhood of the vertex. } \details{ The neighborhood of a given order \code{o} of a vertex \code{v} includes all vertices which are closer to \code{v} than the order. Ie. order 0 is always \code{v} itself, order 1 is \code{v} plus its immediate neighbors, order 2 is order 1 plus the immediate neighbors of the vertices in order 1, etc. \code{ego_size} calculates the size of the neighborhoods for the given vertices with the given order. \code{ego} calculates the neighborhoods of the given vertices with the given order parameter. \code{make_ego_graph} is creates (sub)graphs from all neighborhoods of the given vertices with the given order parameter. This function preserves the vertex, edge and graph attributes. \code{connect} creates a new graph by connecting each vertex to all other vertices in its neighborhood. } \examples{ g <- make_ring(10) ego_size(g, order = 0, 1:3) ego_size(g, order = 1, 1:3) ego_size(g, order = 2, 1:3) ego(g, order = 0, 1:3) ego(g, order = 1, 1:3) ego(g, order = 2, 1:3) # attributes are preserved V(g)$name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") make_ego_graph(g, order = 2, 1:3) # connecting to the neighborhood g <- make_ring(10) g <- connect(g, 2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com}, the first version was done by Vincent Matossian } \keyword{graphs} igraph/man/contract.Rd0000644000175100001440000000267413430770475014444 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{contract} \alias{contract} \alias{contract.vertices} \title{Contract several vertices into a single one} \usage{ contract(graph, mapping, vertex.attr.comb = igraph_opt("vertex.attr.comb")) } \arguments{ \item{graph}{The input graph, it can be directed or undirected.} \item{mapping}{A numeric vector that specifies the mapping. Its elements correspond to the vertices, and for each element the id in the new graph is given.} \item{vertex.attr.comb}{Specifies how to combine the vertex attributes in the new graph. Please see \code{\link{attribute.combination}} for details.} } \value{ A new graph object. } \description{ This function creates a new graph, by merging several vertices into one. The vertices in the new graph correspond to sets of vertices in the input graph. } \details{ The attributes of the graph are kept. Graph and edge attributes are unchanged, vertex attributes are combined, according to the \code{vertex.attr.comb} parameter. } \examples{ g <- make_ring(10) g$name <- "Ring" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- runif(ecount(g)) g2 <- contract(g, rep(1:5, each=2), vertex.attr.comb=toString) ## graph and edge attributes are kept, vertex attributes are ## combined using the 'toString' function. print(g2, g=TRUE, v=TRUE, e=TRUE) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/plot.sir.Rd0000644000175100001440000000450613430770475014375 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/epi.R \name{plot.sir} \alias{plot.sir} \title{Plotting the results on multiple SIR model runs} \usage{ \method{plot}{sir}(x, comp = c("NI", "NS", "NR"), median = TRUE, quantiles = c(0.1, 0.9), color = NULL, median_color = NULL, quantile_color = NULL, lwd.median = 2, lwd.quantile = 2, lty.quantile = 3, xlim = NULL, ylim = NULL, xlab = "Time", ylab = NULL, ...) } \arguments{ \item{x}{The output of the SIR simulation, coming from the \code{\link{sir}} function.} \item{comp}{Character scalar, which component to plot. Either \sQuote{NI} (infected, default), \sQuote{NS} (susceptible) or \sQuote{NR} (recovered).} \item{median}{Logical scalar, whether to plot the (binned) median.} \item{quantiles}{A vector of (binned) quantiles to plot.} \item{color}{Color of the individual simulation curves.} \item{median_color}{Color of the median curve.} \item{quantile_color}{Color(s) of the quantile curves. (It is recycled if needed and non-needed entries are ignored if too long.)} \item{lwd.median}{Line width of the median.} \item{lwd.quantile}{Line width of the quantile curves.} \item{lty.quantile}{Line type of the quantile curves.} \item{xlim}{The x limits, a two-element numeric vector. If \code{NULL}, then it is calculated from the data.} \item{ylim}{The y limits, a two-element numeric vector. If \code{NULL}, then it is calculated from the data.} \item{xlab}{The x label.} \item{ylab}{The y label. If \code{NULL} then it is automatically added based on the \code{comp} argument.} \item{\dots}{Additional arguments are passed to \code{plot}, that is run before any of the curves are added, to create the figure.} } \value{ Nothing. } \description{ This function can conveniently plot the results of multiple SIR model simulations. } \details{ The number of susceptible/infected/recovered individuals is plotted over time, for multiple simulations. } \examples{ g <- sample_gnm(100, 100) sm <- sir(g, beta=5, gamma=1) plot(sm) } \references{ Bailey, Norman T. J. (1975). The mathematical theory of infectious diseases and its applications (2nd ed.). London: Griffin. } \seealso{ \code{\link{sir}} for running the actual simulation. } \author{ Eric Kolaczyk (\url{http://math.bu.edu/people/kolaczyk/}) and Gabor Csardi \email{csardi.gabor@gmail.com}. } \keyword{graphs} igraph/man/sample_k_regular.Rd0000644000175100001440000000266713430770475016145 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_k_regular} \alias{sample_k_regular} \alias{k.regular.game} \title{Create a random regular graph} \usage{ sample_k_regular(no.of.nodes, k, directed = FALSE, multiple = FALSE) } \arguments{ \item{no.of.nodes}{Integer scalar, the number of vertices in the generated graph.} \item{k}{Integer scalar, the degree of each vertex in the graph, or the out-degree and in-degree in a directed graph.} \item{directed}{Logical scalar, whether to create a directed graph.} \item{multiple}{Logical scalar, whether multiple edges are allowed.} } \value{ An igraph graph. } \description{ Generate a random graph where each vertex has the same degree. } \details{ This game generates a directed or undirected random graph where the degrees of vertices are equal to a predefined constant k. For undirected graphs, at least one of k and the number of vertices must be even. The game simply uses \code{\link{sample_degseq}} with appropriately constructed degree sequences. } \examples{ ## A simple ring ring <- sample_k_regular(10, 2) plot(ring) ## k-regular graphs on 10 vertices, with k=1:9 k10 <- lapply(1:9, sample_k_regular, no.of.nodes=10) layout(matrix(1:9, nrow=3, byrow=TRUE)) sapply(k10, plot, vertex.label=NA) } \seealso{ \code{\link{sample_degseq}} for a generator with prescribed degree sequence. } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/local_scan.Rd0000644000175100001440000000776713430770476014736 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scan.R \name{local_scan} \alias{local_scan} \title{Compute local scan statistics on graphs} \usage{ local_scan(graph.us, graph.them = NULL, k = 1, FUN = NULL, weighted = FALSE, mode = c("out", "in", "all"), neighborhoods = NULL, ...) } \arguments{ \item{graph.us, graph}{An igraph object, the graph for which the scan statistics will be computed} \item{graph.them}{An igraph object or \code{NULL}, if not \code{NULL}, then the \sQuote{them} statistics is computed, i.e. the neighborhoods calculated from \code{graph.us} are evaluated on \code{graph.them}.} \item{k}{An integer scalar, the size of the local neighborhood for each vertex. Should be non-negative.} \item{FUN}{Character, a function name, or a function object itself, for computing the local statistic in each neighborhood. If \code{NULL}(the default value), \code{ecount} is used for unweighted graphs (if \code{weighted=FALSE}) and a function that computes the sum of edge weights is used for weighted graphs (if \code{weighted=TRUE}). This argument is ignored if \code{k} is zero.} \item{weighted}{Logical scalar, TRUE if the edge weights should be used for computation of the scan statistic. If TRUE, the graph should be weighted. Note that this argument is ignored if \code{FUN} is not \code{NULL}, \code{"ecount"} and \code{"sumweights"}.} \item{mode}{Character scalar, the kind of neighborhoods to use for the calculation. One of \sQuote{\code{out}}, \sQuote{\code{in}}, \sQuote{\code{all}} or \sQuote{\code{total}}. This argument is ignored for undirected graphs.} \item{neighborhoods}{A list of neighborhoods, one for each vertex, or \code{NULL}. If it is not \code{NULL}, then the function is evaluated on the induced subgraphs specified by these neighborhoods. In theory this could be useful if the same \code{graph.us} graph is used for multiple \code{graph.them} arguments. Then the neighborhoods can be calculated on \code{graph.us} and used with multiple graphs. In practice, this is currently slower than simply using \code{graph.them} multiple times.} \item{\dots}{Arguments passed to \code{FUN}, the function that computes the local statistics.} } \value{ For \code{local_scan} typically a numeric vector containing the computed local statistics for each vertex. In general a list or vector of objects, as returned by \code{FUN}. } \description{ The scan statistic is a summary of the locality statistics that is computed from the local neighborhood of each vertex. The \code{local_scan} function computes the local statistics for each vertex for a given neighborhood size and the statistic function. } \details{ See the given reference below for the details on the local scan statistics. \code{local_scan} calculates exact local scan statistics. If \code{graph.them} is \code{NULL}, then \code{local_scan} computes the \sQuote{us} variant of the scan statistics. Otherwise, \code{graph.them} should be an igraph object and the \sQuote{them} variant is computed using \code{graph.us} to extract the neighborhood information, and applying \code{FUN} on these neighborhoods in \code{graph.them}. } \examples{ pair <- sample_correlated_gnp_pair(n = 10^3, corr = 0.8, p = 0.1) local_0_us <- local_scan(graph.us = pair$graph1, k = 0) local_1_us <- local_scan(graph.us = pair$graph1, k = 1) local_0_them <- local_scan(graph.us = pair$graph1, graph.them = pair$graph2, k = 0) local_1_them <- local_scan(graph.us = pair$graph1, graph.them = pair$graph2, k = 1) Neigh_1 <- neighborhood(pair$graph1, order = 1) local_1_them_nhood <- local_scan(graph.us = pair$graph1, graph.them = pair$graph2, neighborhoods = Neigh_1) } \references{ Priebe, C. E., Conroy, J. M., Marchette, D. J., Park, Y. (2005). Scan Statistics on Enron Graphs. \emph{Computational and Mathematical Organization Theory}. } \seealso{ Other scan statistics: \code{\link{scan_stat}} } \concept{scan statistics} igraph/man/subgraph_centrality.Rd0000644000175100001440000000316513430770475016674 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{subgraph_centrality} \alias{subgraph_centrality} \alias{subgraph.centrality} \title{Find subgraph centrality scores of network positions} \usage{ subgraph_centrality(graph, diag = FALSE) } \arguments{ \item{graph}{The input graph, it should be undirected, but the implementation does not check this currently.} \item{diag}{Boolean scalar, whether to include the diagonal of the adjacency matrix in the analysis. Giving \code{FALSE} here effectively eliminates the loops edges from the graph before the calculation.} } \value{ A numeric vector, the subgraph centrality scores of the vertices. } \description{ Subgraph centrality of a vertex measures the number of subgraphs a vertex participates in, weighting them according to their size. } \details{ The subgraph centrality of a vertex is defined as the number of closed loops originating at the vertex, where longer loops are exponentially downweighted. Currently the calculation is performed by explicitly calculating all eigenvalues and eigenvectors of the adjacency matrix of the graph. This effectively means that the measure can only be calculated for small graphs. } \examples{ g <- sample_pa(100, m=4, dir=FALSE) sc <- subgraph_centrality(g) cor(degree(g), sc) } \references{ Ernesto Estrada, Juan A. Rodriguez-Velazquez: Subgraph centrality in Complex Networks. \emph{Physical Review E} 71, 056103 (2005). } \seealso{ \code{\link{eigen_centrality}}, \code{\link{page_rank}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} based on the Matlab code by Ernesto Estrada } \keyword{graphs} igraph/man/canonical_permutation.Rd0000644000175100001440000000622713430770476017204 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{canonical_permutation} \alias{canonical_permutation} \alias{canonical.permutation} \title{Canonical permutation of a graph} \usage{ canonical_permutation(graph, sh = "fm") } \arguments{ \item{graph}{The input graph, treated as undirected.} \item{sh}{Type of the heuristics to use for the BLISS algorithm. See details for possible values.} } \value{ A list with the following members: \item{labeling}{The canonical parmutation which takes the input graph into canonical form. A numeric vector, the first element is the new label of vertex 0, the second element for vertex 1, etc. } \item{info}{Some information about the BLISS computation. A named list with the following members: \describe{ \item{"nof_nodes"}{The number of nodes in the search tree.} \item{"nof_leaf_nodes"}{The number of leaf nodes in the search tree.} \item{"nof_bad_nodes"}{Number of bad nodes.} \item{"nof_canupdates"}{Number of canrep updates.} \item{"max_level"}{Maximum level.} \item{"group_size"}{The size of the automorphism group of the input graph, as a string. This number is exact if igraph was compiled with the GMP library, and approximate otherwise.} } } } \description{ The canonical permutation brings every isomorphic graphs into the same (labeled) graph. } \details{ \code{canonical_permutation} computes a permutation which brings the graph into canonical form, as defined by the BLISS algorithm. All isomorphic graphs have the same canonical form. See the paper below for the details about BLISS. This and more information is available at \url{http://www.tcs.hut.fi/Software/bliss/index.html}. The possible values for the \code{sh} argument are: \describe{ \item{"f"}{First non-singleton cell.} \item{"fl"}{First largest non-singleton cell.} \item{"fs"}{First smallest non-singleton cell.} \item{"fm"}{First maximally non-trivially connectec non-singleton cell.} \item{"flm"}{Largest maximally non-trivially connected non-singleton cell.} \item{"fsm"}{Smallest maximally non-trivially connected non-singleton cell.} } See the paper in references for details about these. } \examples{ ## Calculate the canonical form of a random graph g1 <- sample_gnm(10, 20) cp1 <- canonical_permutation(g1) cf1 <- permute(g1, cp1$labeling) ## Do the same with a random permutation of it g2 <- permute(g1, sample(vcount(g1))) cp2 <- canonical_permutation(g2) cf2 <- permute(g2, cp2$labeling) ## Check that they are the same el1 <- as_edgelist(cf1) el2 <- as_edgelist(cf2) el1 <- el1[ order(el1[,1], el1[,2]), ] el2 <- el2[ order(el2[,1], el2[,2]), ] all(el1 == el2) } \references{ Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics.} 2007. } \seealso{ \code{\link{permute}} to apply a permutation to a graph, \code{\link{graph.isomorphic}} for deciding graph isomorphism, possibly based on canonical labels. } \author{ Tommi Junttila for BLISS, Gabor Csardi \email{csardi.gabor@gmail.com} for the igraph and R interfaces. } \keyword{graphs} igraph/man/isomorphic.Rd0000644000175100001440000001135613430770476015001 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{isomorphic} \alias{isomorphic} \alias{graph.isomorphic} \alias{graph.isomorphic.34} \alias{graph.isomorphic.vf2} \alias{graph.isomorphic.bliss} \alias{is_isomorphic_to} \title{Decide if two graphs are isomorphic} \usage{ isomorphic(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...) is_isomorphic_to(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...) } \arguments{ \item{graph1}{The first graph.} \item{graph2}{The second graph.} \item{method}{The method to use. Possible values: \sQuote{auto}, \sQuote{direct}, \sQuote{vf2}, \sQuote{bliss}. See their details below.} \item{...}{Additional arguments, passed to the various methods.} } \value{ Logical scalar, \code{TRUE} if the graphs are isomorphic. } \description{ Decide if two graphs are isomorphic } \section{\sQuote{auto} method}{ It tries to select the appropriate method based on the two graphs. This is the algorithm it uses: \enumerate{ \item If the two graphs do not agree on their order and size (i.e. number of vertices and edges), then return \code{FALSE}. \item If the graphs have three or four vertices, then the \sQuote{direct} method is used. \item If the graphs are directed, then the \sQuote{vf2} method is used. \item Otherwise the \sQuote{bliss} method is used. } } \section{\sQuote{direct} method}{ This method only works on graphs with three or four vertices, and it is based on a pre-calculated and stored table. It does not have any extra arguments. } \section{\sQuote{vf2} method}{ This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments: \describe{ \item{vertex.color1, vertex.color2}{Optional integer vectors giving the colors of the vertices for colored graph isomorphism. If they are not given, but the graph has a \dQuote{color} vertex attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments. See also examples below.} \item{edge.color1, edge.color2}{Optional integer vectors giving the colors of the edges for edge-colored (sub)graph isomorphism. If they are not given, but the graph has a \dQuote{color} edge attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments.} } } \section{\sQuote{bliss} method}{ Uses the BLISS algorithm by Junttila and Kaski, and it works for undirected graphs. For both graphs the \code{\link{canonical_permutation}} and then the \code{\link{permute}} function is called to transfer them into canonical form; finally the canonical forms are compared. Extra arguments: \describe{ \item{sh1}{Character constant, the heuristics to use in the BLISS algorithm, for \code{graph1}. See the \code{sh} argument of \code{\link{canonical_permutation}} for possible values.} \item{sh2}{Character constant, the heuristics to use in the BLISS algorithm, for \code{graph2}. See the \code{sh} argument of \code{\link{canonical_permutation}} for possible values.} } \code{sh1} and \code{sh2} default to \sQuote{fm}. } \examples{ # create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphic(g1, g2) # create two isomorphic graphs, by permuting the vertices of the first g1 <- barabasi.game(30, m=2, directed=FALSE) g2 <- permute(g1, sample(vcount(g1))) # should be TRUE isomorphic(g1, g2) isomorphic(g1, g2, method = "bliss") isomorphic(g1, g2, method = "vf2") # colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL) } \references{ Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics.} 2007. LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition}, 149--159, 2001. } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/plot.igraph.Rd0000644000175100001440000000563713430770475015060 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.R \name{plot.igraph} \alias{plot.igraph} \alias{plot.graph} \title{Plotting of graphs} \usage{ \method{plot}{igraph}(x, axes = FALSE, add = FALSE, xlim = c(-1, 1), ylim = c(-1, 1), mark.groups = list(), mark.shape = 1/2, mark.col = rainbow(length(mark.groups), alpha = 0.3), mark.border = rainbow(length(mark.groups), alpha = 1), mark.expand = 15, ...) } \arguments{ \item{x}{The graph to plot.} \item{axes}{Logical, whether to plot axes, defaults to FALSE.} \item{add}{Logical scalar, whether to add the plot to the current device, or delete the device's current contents first.} \item{xlim}{The limits for the horizontal axis, it is unlikely that you want to modify this.} \item{ylim}{The limits for the vertical axis, it is unlikely that you want to modify this.} \item{mark.groups}{A list of vertex id vectors. It is interpreted as a set of vertex groups. Each vertex group is highlighted, by plotting a colored smoothed polygon around and \dQuote{under} it. See the arguments below to control the look of the polygons.} \item{mark.shape}{A numeric scalar or vector. Controls the smoothness of the vertex group marking polygons. This is basically the \sQuote{shape} parameter of the \code{\link[graphics]{xspline}} function, its possible values are between -1 and 1. If it is a vector, then a different value is used for the different vertex groups.} \item{mark.col}{A scalar or vector giving the colors of marking the polygons, in any format accepted by \code{\link[graphics]{xspline}}; e.g. numeric color ids, symbolic color names, or colors in RGB.} \item{mark.border}{A scalar or vector giving the colors of the borders of the vertex group marking polygons. If it is \code{NA}, then no border is drawn.} \item{mark.expand}{A numeric scalar or vector, the size of the border around the marked vertex groups. It is in the same units as the vertex sizes. If a vector is given, then different values are used for the different vertex groups.} \item{\dots}{Additional plotting parameters. See \link{igraph.plotting} for the complete list.} } \value{ Returns \code{NULL}, invisibly. } \description{ \code{plot.igraph} is able to plot graphs to any R device. It is the non-interactive companion of the \code{tkplot} function. } \details{ One convenient way to plot graphs is to plot with \code{\link{tkplot}} first, handtune the placement of the vertices, query the coordinates by the \code{\link{tk_coords}} function and use them with \code{plot} to plot the graph to any R device. } \examples{ g <- make_ring(10) plot(g, layout=layout_with_kk, vertex.color="green") } \seealso{ \code{\link{layout}} for different layouts, \code{\link{igraph.plotting}} for the detailed description of the plotting parameters and \code{\link{tkplot}} and \code{\link{rglplot}} for other graph plotting functions. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/permute.Rd0000644000175100001440000000266313430770476014307 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{permute} \alias{permute} \alias{permute.vertices} \title{Permute the vertices of a graph} \usage{ permute(graph, permutation) } \arguments{ \item{graph}{The input graph, it can directed or undirected.} \item{permutation}{A numeric vector giving the permutation to apply. The first element is the new id of vertex 1, etc. Every number between one and \code{vcount(graph)} must appear exactly once.} } \value{ A new graph object. } \description{ Create a new graph, by permuting vertex ids. } \details{ This function creates a new graph from the input graph by permuting its vertices according to the specified mapping. Call this function with the output of \code{\link{canonical_permutation}} to create the canonical form of a graph. \code{permute} keeps all graph, vertex and edge attributes of the graph. } \examples{ # Random permutation of a random graph g <- sample_gnm(20, 50) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) # Permutation keeps all attributes g$name <- "Random graph, Gnm, 20, 50" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) g2$name V(g2)$name E(g2)$weight all(sort(E(g2)$weight) == sort(E(g)$weight)) } \seealso{ \code{\link{canonical_permutation}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/all_simple_paths.Rd0000644000175100001440000000300413430770475016133 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R \name{all_simple_paths} \alias{all_simple_paths} \title{List all simple paths from one source} \usage{ all_simple_paths(graph, from, to = V(graph), mode = c("out", "in", "all", "total")) } \arguments{ \item{graph}{The input graph.} \item{from}{The source vertex.} \item{to}{The target vertex of vertices. Defaults to all vertices.} \item{mode}{Character constant, gives whether the shortest paths to or from the given vertices should be calculated for directed graphs. If \code{out} then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} it will be considered. If \code{all}, the default, then the corresponding undirected graph will be used, ie. not directed paths are searched. This argument is ignored for undirected graphs.} } \value{ A list of integer vectors, each integer vector is a path from the source vertex to one of the target vertices. A path is given by its vertex ids. } \description{ This function lists are simple paths from one source vertex to another vertex or vertices. A path is simple if the vertices it visits are not visited more than once. } \details{ Note that potentially there are exponentially many paths between two vertices of a graph, and you may run out of memory when using this function, if your graph is lattice-like. This function currently ignored multiple and loop edges. } \examples{ g <- make_ring(10) all_simple_paths(g, 1, 5) all_simple_paths(g, 1, c(3,5)) } \keyword{graphs} igraph/man/cluster_louvain.Rd0000644000175100001440000000523513430770475016041 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_louvain} \alias{cluster_louvain} \alias{multilevel.community} \title{Finding community structure by multi-level optimization of modularity} \usage{ cluster_louvain(graph, weights = NULL) } \arguments{ \item{graph}{The input graph.} \item{weights}{Optional positive weight vector. If the graph has a \code{weight} edge attribute, then this is used by default. Supply \code{NA} here if the graph has a \code{weight} edge attribute, but you want to ignore it. Larger edge weights correspond to stronger connections.} } \value{ \code{cluster_louvain} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ This function implements the multi-level modularity optimization algorithm for finding community structure, see references below. It is based on the modularity measure and a hierarchial approach. } \details{ This function implements the multi-level modularity optimization algorithm for finding community structure, see VD Blondel, J-L Guillaume, R Lambiotte and E Lefebvre: Fast unfolding of community hierarchies in large networks, \url{http://arxiv.org/abs/arXiv:0803.0476} for the details. It is based on the modularity measure and a hierarchial approach. Initially, each vertex is assigned to a community on its own. In every step, vertices are re-assigned to communities in a local, greedy way: each vertex is moved to the community with which it achieves the highest contribution to modularity. When no vertices can be reassigned, each community is considered a vertex on its own, and the process starts again with the merged communities. The process stops when there is only a single vertex left or when the modularity cannot be increased any more in a step. This function was contributed by Tom Gregorovic. } \examples{ # This is so simple that we will have only one level g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) cluster_louvain(g) } \references{ Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte, Etienne Lefebvre: Fast unfolding of communities in large networks. J. Stat. Mech. (2008) P10008 } \seealso{ See \code{\link{communities}} for extracting the membership, modularity scores, etc. from the results. Other community detection algorithms: \code{\link{cluster_walktrap}}, \code{\link{cluster_spinglass}}, \code{\link{cluster_leading_eigen}}, \code{\link{cluster_edge_betweenness}}, \code{\link{cluster_fast_greedy}}, \code{\link{cluster_label_prop}} } \author{ Tom Gregorovic, Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/diameter.Rd0000644000175100001440000000406013430770476014411 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{diameter} \alias{diameter} \alias{get.diameter} \alias{farthest.nodes} \alias{farthest_vertices} \alias{get_diameter} \title{Diameter of a graph} \usage{ diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL) } \arguments{ \item{graph}{The graph to analyze.} \item{directed}{Logical, whether directed or undirected paths are to be considered. This is ignored for undirected graphs.} \item{unconnected}{Logical, what to do if the graph is unconnected. If FALSE, the function will return a number that is one larger the largest possible diameter, which is always the number of vertices. If TRUE, the diameters of the connected components will be calculated and the largest one will be returned.} \item{weights}{Optional positive weight vector for calculating weighted distances. If the graph has a \code{weight} edge attribute, then this is used by default.} } \value{ A numeric constant for \code{diameter}, a numeric vector for \code{get_diameter}. \code{farthest_vertices} returns a list with two entries: \itemize{ \item \code{vertices} The two vertices that are the farthest. \item \code{distance} Their distance. } } \description{ The diameter of a graph is the length of the longest geodesic. } \details{ The diameter is calculated by using a breadth-first search like method. \code{get_diameter} returns a path with the actual diameter. If there are many shortest paths of the length of the diameter, then it returns the first one found. \code{farthest_vertices} returns two vertex ids, the vertices which are connected by the diameter path. } \examples{ g <- make_ring(10) g2 <- delete_edges(g, c(1,2,1,10)) diameter(g2, unconnected=TRUE) diameter(g2, unconnected=FALSE) ## Weighted diameter set.seed(1) g <- make_ring(10) E(g)$weight <- sample(seq_len(ecount(g))) diameter(g) get_diameter(g) diameter(g, weights=NA) get_diameter(g, weights=NA) } \seealso{ \code{\link{distances}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_clusters.Rd0000644000175100001440000000214413430770475015460 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{make_clusters} \alias{make_clusters} \alias{create.communities} \title{Creates a communities object.} \usage{ make_clusters(graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE) } \arguments{ \item{graph}{The graph of the community structure.} \item{membership}{The membership vector of the community structure, a numeric vector denoting the id of the community for each vertex. It might be \code{NULL} for hierarchical community structures.} \item{algorithm}{Character string, the algorithm that generated the community structure, it can be arbitrary.} \item{merges}{A merge matrix, for hierarchical community structures (or \code{NULL} otherwise.} \item{modularity}{Modularity value of the community structure. If this is \code{TRUE} and the membership vector is available, then it the modularity values is calculated automatically.} } \value{ A \code{communities} object. } \description{ This is useful to integrate the results of community finding algorithms that are not included in igraph. } igraph/man/graph_version.Rd0000644000175100001440000000152313430770476015466 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/versions.R \name{graph_version} \alias{graph_version} \title{Igraph data structure versions} \usage{ graph_version(graph) } \arguments{ \item{graph}{The input graph. If it is missing, then the version number of the current data format is returned.} } \value{ A character scalar. } \description{ Igraph's internal data representation changes sometimes between versions. This means that it is not possible to use igraph objects that were created (and possibly saved to a file) with an older igraph version. } \details{ \code{graph_version} queries the current data format, or the data format of a possibly older igraph graph. \code{\link{upgrade_graph}} can convert an older data format to the current one. } \seealso{ upgrade_graph to convert the data format of a graph. } igraph/man/ends.Rd0000644000175100001440000000174513430770475013556 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{ends} \alias{ends} \alias{get.edges} \alias{get.edge} \title{Incident vertices of some graph edges} \usage{ ends(graph, es, names = TRUE) } \arguments{ \item{graph}{The input graph} \item{es}{The sequence of edges to query} \item{names}{Whether to return vertex names or numeric vertex ids. By default vertex names are used.} } \value{ A two column matrix of vertex names or vertex ids. } \description{ Incident vertices of some graph edges } \examples{ g <- make_ring(5) ends(g, E(g)) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/eigen_centrality.Rd0000644000175100001440000000725713430770475016156 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{eigen_centrality} \alias{eigen_centrality} \alias{evcent} \title{Find Eigenvector Centrality Scores of Network Positions} \usage{ eigen_centrality(graph, directed = FALSE, scale = TRUE, weights = NULL, options = arpack_defaults) } \arguments{ \item{graph}{Graph to be analyzed.} \item{directed}{Logical scalar, whether to consider direction of the edges in directed graphs. It is ignored for undirected graphs.} \item{scale}{Logical scalar, whether to scale the result to have a maximum score of one. If no scaling is used then the result vector has unit length in the Euclidean norm.} \item{weights}{A numerical vector or \code{NULL}. This argument can be used to give edge weights for calculating the weighted eigenvector centrality of vertices. If this is \code{NULL} and the graph has a \code{weight} edge attribute then that is used. If \code{weights} is a numerical vector then it used, even if the graph has a \code{weights} edge attribute. If this is \code{NA}, then no edge weights are used (even if the graph has a \code{weight} edge attribute. Note that if there are negative edge weights and the direction of the edges is considered, then the eigenvector might be complex. In this case only the real part is reported. This function interprets weights as connection strength. Higher weights spread the centrality better.} \item{options}{A named list, to override some ARPACK options. See \code{\link{arpack}} for details.} } \value{ A named list with components: \item{vector}{A vector containing the centrality scores.} \item{value}{The eigenvalue corresponding to the calculated eigenvector, i.e. the centrality scores.} \item{options}{A named list, information about the underlying ARPACK computation. See \code{\link{arpack}} for the details. } } \description{ \code{eigen_centrality} takes a graph (\code{graph}) and returns the eigenvector centralities of positions \code{v} within it } \details{ Eigenvector centrality scores correspond to the values of the first eigenvector of the graph adjacency matrix; these scores may, in turn, be interpreted as arising from a reciprocal process in which the centrality of each actor is proportional to the sum of the centralities of those actors to whom he or she is connected. In general, vertices with high eigenvector centralities are those which are connected to many other vertices which are, in turn, connected to many others (and so on). (The perceptive may realize that this implies that the largest values will be obtained by individuals in large cliques (or high-density substructures). This is also intelligible from an algebraic point of view, with the first eigenvector being closely related to the best rank-1 approximation of the adjacency matrix (a relationship which is easy to see in the special case of a diagonalizable symmetric real matrix via the \eqn{SLS^-1}{$S \Lambda S^{-1}$} decomposition).) From igraph version 0.5 this function uses ARPACK for the underlying computation, see \code{\link{arpack}} for more about ARPACK in igraph. } \section{WARNING }{ \code{eigen_centrality} will not symmetrize your data before extracting eigenvectors; don't send this routine asymmetric matrices unless you really mean to do so. } \examples{ #Generate some test data g <- make_ring(10, directed=FALSE) #Compute eigenvector centrality scores eigen_centrality(g) } \references{ Bonacich, P. (1987). Power and Centrality: A Family of Measures. \emph{American Journal of Sociology}, 92, 1170-1182. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} and Carter T. Butts (\url{http://www.faculty.uci.edu/profile.cfm?faculty_id=5057}) for the manual page. } \keyword{graphs} igraph/man/ivs.Rd0000644000175100001440000000507113430770475013422 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cliques.R \name{ivs} \alias{ivs} \alias{independent.vertex.sets} \alias{largest.independent.vertex.sets} \alias{maximal.independent.vertex.sets} \alias{independence.number} \alias{ivs_size} \alias{largest_ivs} \alias{maximal_ivs} \title{Independent vertex sets} \usage{ ivs(graph, min = NULL, max = NULL) } \arguments{ \item{graph}{The input graph, directed graphs are considered as undirected, loop edges and multiple edges are ignored.} \item{min}{Numeric constant, limit for the minimum size of the independent vertex sets to find. \code{NULL} means no limit.} \item{max}{Numeric constant, limit for the maximum size of the independent vertex sets to find. \code{NULL} means no limit.} } \value{ \code{ivs}, \code{largest_ivs} and \code{maximal_ivs} return a list containing numeric vertex ids, each list element is an independent vertex set. \code{ivs_size} returns an integer constant. } \description{ A vertex set is called independent if there no edges between any two vertices in it. These functions find independent vertex sets in undirected graphs } \details{ \code{ivs} finds all independent vertex sets in the network, obeying the size limitations given in the \code{min} and \code{max} arguments. \code{largest_ivs} finds the largest independent vertex sets in the graph. An independent vertex set is largest if there is no independent vertex set with more vertices. \code{maximal_ivs} finds the maximal independent vertex sets in the graph. An independent vertex set is maximal if it cannot be extended to a larger independent vertex set. The largest independent vertex sets are maximal, but the opposite is not always true. \code{independece.number} calculate the size of the largest independent vertex set(s). These functions use the algorithm described by Tsukiyama et al., see reference below. } \examples{ # Do not run, takes a couple of seconds \dontrun{ # A quite dense graph set.seed(42) g <- sample_gnp(100, 0.9) ivs_size(g) ivs(g, min=ivs_size(g)) largest_ivs(g) # Empty graph induced_subgraph(g, largest_ivs(g)[[1]]) length(maximal_ivs(g)) } } \references{ S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm for generating all the maximal independent sets. \emph{SIAM J Computing}, 6:505--517, 1977. } \seealso{ \code{\link{cliques}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} ported it from the Very Nauty Graph Library by Keith Briggs (\url{http://keithbriggs.info/}) and Gabor Csardi \email{csardi.gabor@gmail.com} wrote the R interface and this manual page. } \keyword{graphs} igraph/man/tail_of.Rd0000644000175100001440000000165313430770475014240 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/basic.R \name{tail_of} \alias{tail_of} \title{Tails of the edge(s) in a graph} \usage{ tail_of(graph, es) } \arguments{ \item{graph}{The input graph.} \item{es}{The edges to query.} } \value{ A vertex sequence with the tail(s) of the edge(s). } \description{ For undirected graphs, head and tail is not defined. In this case \code{tail_of} returns vertices incident to the supplied edges, and \code{head_of} returns the other end(s) of the edge(s). } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}} } \concept{structural queries} igraph/man/groups.Rd0000644000175100001440000000212313430770475014133 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{groups} \alias{groups} \alias{groups.default} \alias{groups.communities} \title{Groups of a vertex partitioning} \usage{ groups(x) } \arguments{ \item{x}{Some object that represents a grouping of the vertices. See details below.} } \value{ A named list of numeric or character vectors. The names are just numbers that refer to the groups. The vectors themselves are numeric or symbolic vertex ids. } \description{ Create a list of vertex groups from some graph clustering or community structure. } \details{ Currently two methods are defined for this function. The default method works on the output of \code{\link{components}}. (In fact it works on any object that is a list with an entry called \code{membership}.) The second method works on \code{\link{communities}} objects. } \examples{ g <- make_graph("Zachary") fgc <- cluster_fast_greedy(g) groups(fgc) g2 <- make_ring(10) + make_full_graph(5) groups(components(g2)) } \seealso{ \code{\link{components}} and the various community finding functions. } igraph/man/layout_with_graphopt.Rd0000644000175100001440000000625313430770475017100 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_graphopt} \alias{layout_with_graphopt} \alias{layout.graphopt} \alias{with_graphopt} \title{The graphopt layout algorithm} \usage{ layout_with_graphopt(graph, start = NULL, niter = 500, charge = 0.001, mass = 30, spring.length = 0, spring.constant = 1, max.sa.movement = 5) with_graphopt(...) } \arguments{ \item{graph}{The input graph.} \item{start}{If given, then it should be a matrix with two columns and one line for each vertex. This matrix will be used as starting positions for the algorithm. If not given, then a random starting matrix is used.} \item{niter}{Integer scalar, the number of iterations to perform. Should be a couple of hundred in general. If you have a large graph then you might want to only do a few iterations and then check the result. If it is not good enough you can feed it in again in the \code{start} argument. The default value is 500.} \item{charge}{The charge of the vertices, used to calculate electric repulsion. The default is 0.001.} \item{mass}{The mass of the vertices, used for the spring forces. The default is 30.} \item{spring.length}{The length of the springs, an integer number. The default value is zero.} \item{spring.constant}{The spring constant, the default value is one.} \item{max.sa.movement}{Real constant, it gives the maximum amount of movement allowed in a single step along a single axis. The default value is 5.} \item{...}{Passed to \code{layout_with_graphopt}.} } \value{ A numeric matrix with two columns, and a row for each vertex. } \description{ A force-directed layout algorithm, that scales relatively well to large graphs. } \details{ \code{layout_with_graphopt} is a port of the graphopt layout algorithm by Michael Schmuhl. graphopt version 0.4.1 was rewritten in C and the support for layers was removed (might be added later) and a code was a bit reorganized to avoid some unneccessary steps is the node charge (see below) is zero. graphopt uses physical analogies for defining attracting and repelling forces among the vertices and then the physical system is simulated until it reaches an equilibrium. (There is no simulated annealing or anything like that, so a stable fixed point is not guaranteed.) See also \url{http://www.schmuhl.org/graphopt/} for the original graphopt. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Michael Schmuhl for the original graphopt code, rewritten and wrapped by Gabor Csardi \email{csardi.gabor@gmail.com}. } \concept{graph layouts} \keyword{graphs} igraph/man/sample_pa.Rd0000644000175100001440000001222713430770475014563 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_pa} \alias{sample_pa} \alias{barabasi.game} \alias{ba.game} \alias{pa} \title{Generate scale-free graphs according to the Barabasi-Albert model} \usage{ sample_pa(n, power = 1, m = NULL, out.dist = NULL, out.seq = NULL, out.pref = FALSE, zero.appeal = 1, directed = TRUE, algorithm = c("psumtree", "psumtree-multiple", "bag"), start.graph = NULL) pa(...) } \arguments{ \item{n}{Number of vertices.} \item{power}{The power of the preferential attachment, the default is one, ie. linear preferential attachment.} \item{m}{Numeric constant, the number of edges to add in each time step This argument is only used if both \code{out.dist} and \code{out.seq} are omitted or NULL.} \item{out.dist}{Numeric vector, the distribution of the number of edges to add in each time step. This argument is only used if the \code{out.seq} argument is omitted or NULL.} \item{out.seq}{Numeric vector giving the number of edges to add in each time step. Its first element is ignored as no edges are added in the first time step.} \item{out.pref}{Logical, if true the total degree is used for calculating the citation probability, otherwise the in-degree is used.} \item{zero.appeal}{The \sQuote{attractiveness} of the vertices with no adjacent edges. See details below.} \item{directed}{Whether to create a directed graph.} \item{algorithm}{The algorithm to use for the graph generation. \code{psumtree} uses a partial prefix-sum tree to generate the graph, this algorithm can handle any \code{power} and \code{zero.appeal} values and never generates multiple edges. \code{psumtree-multiple} also uses a partial prefix-sum tree, but the generation of multiple edges is allowed. Before the 0.6 version igraph used this algorithm if \code{power} was not one, or \code{zero.appeal} was not one. \code{bag} is the algorithm that was previously (before version 0.6) used if \code{power} was one and \code{zero.appeal} was one as well. It works by putting the ids of the vertices into a bag (mutliset, really), exactly as many times as their (in-)degree, plus once more. Then the required number of cited vertices are drawn from the bag, with replacement. This method might generate multiple edges. It only works if \code{power} and \code{zero.appeal} are equal one.} \item{start.graph}{\code{NULL} or an igraph graph. If a graph, then the supplied graph is used as a starting graph for the preferential attachment algorithm. The graph should have at least one vertex. If a graph is supplied here and the \code{out.seq} argument is not \code{NULL}, then it should contain the out degrees of the new vertices only, not the ones in the \code{start.graph}.} \item{...}{Passed to \code{sample_pa}.} } \value{ A graph object. } \description{ The BA-model is a very simple stochastic algorithm for building a graph. } \details{ This is a simple stochastic algorithm to generate a graph. It is a discrete time step model and in each time step a single vertex is added. We start with a single vertex and no edges in the first time step. Then we add one vertex in each time step and the new vertex initiates some edges to old vertices. The probability that an old vertex is chosen is given by \deqn{P[i] \sim k_i^\alpha+a}{P[i] ~ k[i]^alpha + a} where \eqn{k_i}{k[i]} is the in-degree of vertex \eqn{i} in the current time step (more precisely the number of adjacent edges of \eqn{i} which were not initiated by \eqn{i} itself) and \eqn{\alpha}{alpha} and \eqn{a} are parameters given by the \code{power} and \code{zero.appeal} arguments. The number of edges initiated in a time step is given by the \code{m}, \code{out.dist} and \code{out.seq} arguments. If \code{out.seq} is given and not NULL then it gives the number of edges to add in a vector, the first element is ignored, the second is the number of edges to add in the second time step and so on. If \code{out.seq} is not given or null and \code{out.dist} is given and not NULL then it is used as a discrete distribution to generate the number of edges in each time step. Its first element is the probability that no edges will be added, the second is the probability that one edge is added, etc. (\code{out.dist} does not need to sum up to one, it normalized automatically.) \code{out.dist} should contain non-negative numbers and at east one element should be positive. If both \code{out.seq} and \code{out.dist} are omitted or NULL then \code{m} will be used, it should be a positive integer constant and \code{m} edges will be added in each time step. \code{sample_pa} generates a directed graph by default, set \code{directed} to \code{FALSE} to generate an undirected graph. Note that even if an undirected graph is generated \eqn{k_i}{k[i]} denotes the number of adjacent edges not initiated by the vertex itself and not the total (in- + out-) degree of the vertex, unless the \code{out.pref} argument is set to \code{TRUE}. } \examples{ g <- sample_pa(10000) degree_distribution(g) } \references{ Barabasi, A.-L. and Albert R. 1999. Emergence of scaling in random networks \emph{Science}, 286 509--512. } \seealso{ \code{\link{sample_gnp}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/E.Rd0000644000175100001440000000507413430770475013010 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{E} \alias{E} \title{Edges of a graph} \usage{ E(graph, P = NULL, path = NULL, directed = TRUE) } \arguments{ \item{graph}{The graph.} \item{P}{A list of vertices to select edges via pairs of vertices. The first and second vertices select the first edge, the third and fourth the second, etc.} \item{path}{A list of vertices, to select edges along a path. Note that this only works reliable for simple graphs. If the graph has multiple edges, one of them will be chosen arbitrarily to be included in the edge sequence.} \item{directed}{Whether to consider edge directions in the \code{P} argument, for directed graphs.} } \value{ An edge sequence of the graph. } \description{ An edge sequence is a vector containing numeric edge ids, with a special class attribute that allows custom operations: selecting subsets of edges based on attributes, or graph structure, creating the intersection, union of edges, etc. } \details{ Edge sequences are usually used as igraph function arguments that refer to edges of a graph. An edge sequence is tied to the graph it refers to: it really denoted the specific edges of that graph, and cannot be used together with another graph. An edge sequence is most often created by the \code{E()} function. The result includes edges in increasing edge id order by default (if. none of the \code{P} and \code{path} arguments are used). An edge sequence can be indexed by a numeric vector, just like a regular R vector. See links to other edge sequence operations below. } \section{Indexing edge sequences}{ Edge sequences mostly behave like regular vectors, but there are some additional indexing operations that are specific for them; e.g. selecting edges based on graph structure, or based on edge attributes. See \code{\link{[.igraph.es}} for details. } \section{Querying or setting attributes}{ Edge sequences can be used to query or set attributes for the edges in the sequence. See \code{\link{$.igraph.es}} for details. } \examples{ # Edges of an unnamed graph g <- make_ring(10) E(g) # Edges of a named graph g2 <- make_ring(10) \%>\% set_vertex_attr("name", value = letters[1:10]) E(g2) } \seealso{ Other vertex and edge sequences: \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} } \concept{vertex and edge sequences} igraph/man/mst.Rd0000644000175100001440000000360513430770475013425 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/minimum.spanning.tree.R \name{mst} \alias{mst} \alias{minimum.spanning.tree} \title{Minimum spanning tree} \usage{ mst(graph, weights = NULL, algorithm = NULL, ...) } \arguments{ \item{graph}{The graph object to analyze.} \item{weights}{Numeric algorithm giving the weights of the edges in the graph. The order is determined by the edge ids. This is ignored if the \code{unweighted} algorithm is chosen. Edge weights are interpreted as distances.} \item{algorithm}{The algorithm to use for calculation. \code{unweighted} can be used for unwieghted graphs, and \code{prim} runs Prim's algorithm for weighted graphs. If this is \code{NULL} then igraph tries to select the algorithm automatically: if the graph has an edge attribute called \code{weight} of the \code{weights} argument is not \code{NULL} then Prim's algorithm is chosen, otherwise the unwweighted algorithm is performed.} \item{\dots}{Additional arguments, unused.} } \value{ A graph object with the minimum spanning forest. (To check that it is a tree check that the number of its edges is \code{vcount(graph)-1}.) The edge and vertex attributes of the original graph are preserved in the result. } \description{ A subgraph of a connected graph is a \emph{minimum spanning tree} if it is tree, and the sum of its edge weights are the minimal among all tree subgraphs of the graph. A minimum spanning forest of a graph is the graph consisting of the minimum spanning trees of its components. } \details{ If the graph is unconnected a minimum spanning forest is returned. } \examples{ g <- sample_gnp(100, 3/100) g_mst <- mst(g) } \references{ Prim, R.C. 1957. Shortest connection networks and some generalizations \emph{Bell System Technical Journal}, 37 1389--1401. } \seealso{ \code{\link{components}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_bipartite_graph.Rd0000644000175100001440000000417513430770475016766 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R, R/make.R \name{is_bipartite} \alias{is_bipartite} \alias{make_bipartite_graph} \alias{graph.bipartite} \alias{is.bipartite} \alias{bipartite_graph} \title{Create a bipartite graph} \usage{ is_bipartite(graph) make_bipartite_graph(types, edges, directed = FALSE) bipartite_graph(...) } \arguments{ \item{graph}{The input graph.} \item{types}{A vector giving the vertex types. It will be coerced into boolean. The length of the vector gives the number of vertices in the graph.} \item{edges}{A vector giving the edges of the graph, the same way as for the regular \code{\link{graph}} function. It is checked that the edges indeed connect vertices of different kind, accoding to the supplied \code{types} vector.} \item{directed}{Whether to create a directed graph, boolean constant. Note that by default undirected graphs are created, as this is more common for bipartite graphs.} \item{...}{Passed to \code{make_bipartite_graph}.} } \value{ \code{make_bipartite_graph} returns a bipartite igraph graph. In other words, an igraph graph that has a vertex attribute named \code{type}. \code{is_bipartite} returns a logical scalar. } \description{ A bipartite graph has two kinds of vertices and connections are only allowed between different kinds. } \details{ Bipartite graphs have a \code{type} vertex attribute in igraph, this is boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} for vertices of the second kind. \code{make_bipartite_graph} basically does three things. First it checks tha \code{edges} vector against the vertex \code{types}. Then it creates a graph using the \code{edges} vector and finally it adds the \code{types} vector as a vertex attribute called \code{type}. \code{is_bipartite} checks whether the graph is bipartite or not. It just checks whether the graph has a vertex attribute called \code{type}. } \examples{ g <- make_bipartite_graph( rep(0:1,length=10), c(1:10)) print(g, v=TRUE) } \seealso{ \code{\link{graph}} to create one-mode networks } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/complementer.Rd0000644000175100001440000000206313430770475015311 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{complementer} \alias{complementer} \alias{graph.complementer} \title{Complementer of a graph} \usage{ complementer(graph, loops = FALSE) } \arguments{ \item{graph}{The input graph, can be directed or undirected.} \item{loops}{Logical constant, whether to generate loop edges.} } \value{ A new graph object. } \description{ A complementer graph contains all edges that were not present in the input graph. } \details{ \code{complementer} creates the complementer of a graph. Only edges which are \emph{not} present in the original graph will be included in the new graph. \code{complementer} keeps graph and vertex attriubutes, edge attributes are lost. } \examples{ ## Complementer of a ring g <- make_ring(10) complementer(g) ## A graph and its complementer give together the full graph g <- make_ring(10) gc <- complementer(g) gu <- union(g, gc) gu graph.isomorphic(gu, make_full_graph(vcount(g))) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/subcomponent.Rd0000644000175100001440000000225413430770476015336 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{subcomponent} \alias{subcomponent} \title{In- or out- component of a vertex} \usage{ subcomponent(graph, v, mode = c("all", "out", "in")) } \arguments{ \item{graph}{The graph to analyze.} \item{v}{The vertex to start the search from.} \item{mode}{Character string, either \dQuote{in}, \dQuote{out} or \dQuote{all}. If \dQuote{in} all vertices from which \code{v} is reachable are listed. If \dQuote{out} all vertices reachable from \code{v} are returned. If \dQuote{all} returns the union of these. It is ignored for undirected graphs.} } \value{ Numeric vector, the ids of the vertices in the same component as \code{v}. } \description{ Finds all vertices reachable from a given vertex, or the opposite: all vertices from which a given vertex is reachable via a directed path. } \details{ A breadh-first search is conducted starting from vertex \code{v}. } \examples{ g <- sample_gnp(100, 1/200) subcomponent(g, 1, "in") subcomponent(g, 1, "out") subcomponent(g, 1, "all") } \seealso{ \code{\link{components}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/vertex_attr.Rd0000644000175100001440000000262413430770475015171 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{vertex_attr} \alias{vertex_attr} \alias{get.vertex.attribute} \alias{vertex.attributes} \title{Query vertex attributes of a graph} \usage{ vertex_attr(graph, name, index = V(graph)) } \arguments{ \item{graph}{The graph.} \item{name}{Name of the attribute to query. If missing, then all vertex attributes are returned in a list.} \item{index}{A vertex sequence, to query the attribute only for these vertices.} } \value{ The value of the vertex attribute, or the list of all vertex attributes, if \code{name} is missing. } \description{ Query vertex attributes of a graph } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("color", value = "red") \%>\% set_vertex_attr("label", value = letters[1:10]) vertex_attr(g, "label") vertex_attr(g) plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}} } \concept{graph attributes} igraph/man/knn.Rd0000644000175100001440000000436713430770476013417 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{knn} \alias{knn} \alias{graph.knn} \title{Average nearest neighbor degree} \usage{ knn(graph, vids = V(graph), weights = NULL) } \arguments{ \item{graph}{The input graph. It can be directed, but it will be treated as undirected, i.e. the direction of the edges is ignored.} \item{vids}{The vertices for which the calculation is performed. Normally it includes all vertices. Note, that if not all vertices are given here, then both \sQuote{\code{knn}} and \sQuote{\code{knnk}} will be calculated based on the given vertices only.} \item{weights}{Weight vector. If the graph has a \code{weight} edge attribute, then this is used by default. If this argument is given, then vertex strength (see \code{\link{strength}}) is used instead of vertex degree. But note that \code{knnk} is still given in the function of the normal vertex degree. Weights are are used to calculate a weighted degree (also called \code{\link{strength}}) instead of the degree.} } \value{ A list with two members: \item{knn}{A numeric vector giving the average nearest neighbor degree for all vertices in \code{vids}.} \item{knnk}{A numeric vector, its length is the maximum (total) vertex degree in the graph. The first element is the average nearest neighbor degree of vertices with degree one, etc. } } \description{ Calculate the average nearest neighbor degree of the given vertices and the same quantity in the function of vertex degree } \details{ Note that for zero degree vertices the answer in \sQuote{\code{knn}} is \code{NaN} (zero divided by zero), the same is true for \sQuote{\code{knnk}} if a given degree never appears in the network. } \examples{ # Some trivial ones g <- make_ring(10) knn(g) g2 <- make_star(10) knn(g2) # A scale-free one, try to plot 'knnk' g3 <- sample_pa(1000, m=5) knn(g3) # A random graph g4 <- sample_gnp(1000, p=5/1000) knn(g4) # A weighted graph g5 <- make_star(10) E(g5)$weight <- seq(ecount(g5)) knn(g5) } \references{ Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/adjacent_vertices.Rd0000644000175100001440000000217613430770475016301 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{adjacent_vertices} \alias{adjacent_vertices} \title{Adjacent vertices of multiple vertices in a graph} \usage{ adjacent_vertices(graph, v, mode = c("out", "in", "all", "total")) } \arguments{ \item{graph}{Input graph.} \item{v}{The vertices to query.} \item{mode}{Whether to query outgoing (\sQuote{out}), incoming (\sQuote{in}) edges, or both types (\sQuote{all}). This is ignored for undirected graphs.} } \value{ A list of vertex sequences. } \description{ This function is similar to \code{\link{neighbors}}, but it queries the adjacent vertices for multiple vertices at once. } \examples{ g <- make_graph("Zachary") adjacent_vertices(g, c(1, 34)) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/layout.svd.Rd0000644000175100001440000000064213430770475014730 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout.svd} \alias{layout.svd} \title{SVD layout, this was removed from igraph} \usage{ layout.svd(graph, ...) } \arguments{ \item{graph}{Input graph.} \item{...}{Extra arguments are ignored.} } \value{ Layout coordinates, a two column matrix. } \description{ Now it calls the Fruchterman-Reingold layout, with a warning. } igraph/man/layout_on_sphere.Rd0000644000175100001440000000315513430770475016201 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_on_sphere} \alias{layout_on_sphere} \alias{on_sphere} \title{Graph layout with vertices on the surface of a sphere} \usage{ layout_on_sphere(graph) on_sphere(...) } \arguments{ \item{graph}{The input graph.} \item{...}{Passed to \code{layout_on_sphere}.} } \value{ A numeric matrix with three columns, and one row for each vertex. } \description{ Place vertices on a sphere, approximately uniformly, in the order of their vertex ids. } \details{ \code{layout_on_sphere} places the vertices (approximately) uniformly on the surface of a sphere, this is thus a 3d layout. It is not clear however what \dQuote{uniformly on a sphere} means. If you want to order the vertices differently, then permute them using the \code{\link{permute}} function. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/as_edgelist.Rd0000644000175100001440000000155513430770475015107 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_edgelist} \alias{as_edgelist} \alias{get.edgelist} \title{Convert a graph to an edge list} \usage{ as_edgelist(graph, names = TRUE) } \arguments{ \item{graph}{The graph to convert.} \item{names}{Whether to return a character matrix containing vertex names (ie. the \code{name} vertex attribute) if they exist or numeric vertex ids.} } \value{ A \code{gsize(graph)} by 2 numeric matrix. } \description{ Sometimes it is useful to work with a standard representation of a graph, like an edge list. } \details{ \code{as_edgelist} returns the list of edges in a graph. } \examples{ g <- sample_gnp(10, 2/10) as_edgelist(g) V(g)$name <- LETTERS[seq_len(gorder(g))] as_edgelist(g) } \seealso{ \code{\link{graph_from_adjacency_matrix}}, \code{\link{read_graph}} } \keyword{graphs} igraph/man/distances.Rd0000644000175100001440000002336013430770475014577 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R, R/structural.properties.R \name{distance_table} \alias{distance_table} \alias{mean_distance} \alias{distances} \alias{shortest.paths} \alias{get.shortest.paths} \alias{get.all.shortest.paths} \alias{average.path.length} \alias{path.length.hist} \alias{all_shortest_paths} \alias{shortest_paths} \title{Shortest (directed or undirected) paths between vertices} \usage{ distance_table(graph, directed = TRUE) mean_distance(graph, directed = TRUE, unconnected = TRUE) distances(graph, v = V(graph), to = V(graph), mode = c("all", "out", "in"), weights = NULL, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson")) shortest_paths(graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL, output = c("vpath", "epath", "both"), predecessors = FALSE, inbound.edges = FALSE) all_shortest_paths(graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL) } \arguments{ \item{graph}{The graph to work on.} \item{directed}{Whether to consider directed paths in directed graphs, this argument is ignored for undirected graphs.} \item{unconnected}{What to do if the graph is unconnected (not strongly connected if directed paths are considered). If TRUE only the lengths of the existing paths are considered and averaged; if FALSE the length of the missing paths are counted having length \code{vcount(graph)}, one longer than the longest possible geodesic in the network.} \item{v}{Numeric vector, the vertices from which the shortest paths will be calculated.} \item{to}{Numeric vector, the vertices to which the shortest paths will be calculated. By default it includes all vertices. Note that for \code{distances} every vertex must be included here at most once. (This is not required for \code{shortest_paths}.} \item{mode}{Character constant, gives whether the shortest paths to or from the given vertices should be calculated for directed graphs. If \code{out} then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} it will be considered. If \code{all}, the default, then the corresponding undirected graph will be used, ie. not directed paths are searched. This argument is ignored for undirected graphs.} \item{weights}{Possibly a numeric vector giving edge weights. If this is \code{NULL} and the graph has a \code{weight} edge attribute, then the attribute is used. If this is \code{NA} then no weights are used (even if the graph has a \code{weight} attribute).} \item{algorithm}{Which algorithm to use for the calculation. By default igraph tries to select the fastest suitable algorithm. If there are no weights, then an unweighted breadth-first search is used, otherwise if all weights are positive, then Dijkstra's algorithm is used. If there are negative weights and we do the calculation for more than 100 sources, then Johnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used. You can override igraph's choice by explicitly giving this parameter. Note that the igraph C core might still override your choice in obvious cases, i.e. if there are no edge weights, then the unweighted algorithm will be used, regardless of this argument.} \item{from}{Numeric constant, the vertex from or to the shortest paths will be calculated. Note that right now this is not a vector of vertex ids, but only a single vertex.} \item{output}{Character scalar, defines how to report the shortest paths. \dQuote{vpath} means that the vertices along the paths are reported, this form was used prior to igraph version 0.6. \dQuote{epath} means that the edges along the paths are reported. \dQuote{both} means that both forms are returned, in a named list with components \dQuote{vpath} and \dQuote{epath}.} \item{predecessors}{Logical scalar, whether to return the predecessor vertex for each vertex. The predecessor of vertex \code{i} in the tree is the vertex from which vertex \code{i} was reached. The predecessor of the start vertex (in the \code{from} argument) is itself by definition. If the predecessor is zero, it means that the given vertex was not reached from the source during the search. Note that the search terminates if all the vertices in \code{to} are reached.} \item{inbound.edges}{Logical scalar, whether to return the inbound edge for each vertex. The inbound edge of vertex \code{i} in the tree is the edge via which vertex \code{i} was reached. The start vertex and vertices that were not reached during the search will have zero in the corresponding entry of the vector. Note that the search terminates if all the vertices in \code{to} are reached.} } \value{ For \code{distances} a numeric matrix with \code{length(to)} columns and \code{length(v)} rows. The shortest path length from a vertex to itself is always zero. For unreachable vertices \code{Inf} is included. For \code{shortest_paths} a named list with four entries is returned: \item{vpath}{This itself is a list, of length \code{length(to)}; list element \code{i} contains the vertex ids on the path from vertex \code{from} to vertex \code{to[i]} (or the other way for directed graphs depending on the \code{mode} argument). The vector also contains \code{from} and \code{i} as the first and last elements. If \code{from} is the same as \code{i} then it is only included once. If there is no path between two vertices then a numeric vector of length zero is returned as the list element. If this output is not requested in the \code{output} argument, then it will be \code{NULL}.} \item{epath}{This is a list similar to \code{vpath}, but the vectors of the list contain the edge ids along the shortest paths, instead of the vertex ids. This entry is set to \code{NULL} if it is not requested in the \code{output} argument.} \item{predecessors}{Numeric vector, the predecessor of each vertex in the \code{to} argument, or \code{NULL} if it was not requested.} \item{inbound_edges}{Numeric vector, the inbound edge for each vertex, or \code{NULL}, if it was not requested.} For \code{all_shortest_paths} a list is returned, each list element contains a shortest path from \code{from} to a vertex in \code{to}. The shortest paths to the same vertex are collected into consecutive elements of the list. For \code{mean_distance} a single number is returned. \code{distance_table} returns a named list with two entries: \code{res} is a numeric vector, the histogram of distances, \code{unconnected} is a numeric scalar, the number of pairs for which the first vertex is not reachable from the second. The sum of the two entries is always \eqn{n(n-1)} for directed graphs and \eqn{n(n-1)/2} for undirected graphs. } \description{ \code{distances} calculates the length of all the shortest paths from or to the vertices in the network. \code{shortest_paths} calculates one shortest path (the path itself, and not just its length) from or to the given vertex. } \details{ The shortest path, or geodesic between two pair of vertices is a path with the minimal number of vertices. The functions documented in this manual page all calculate shortest paths between vertex pairs. \code{distances} calculates the lengths of pairwise shortest paths from a set of vertices (\code{from}) to another set of vertices (\code{to}). It uses different algorithms, depending on the \code{algorithm} argument and the \code{weight} edge attribute of the graph. The implemented algorithms are breadth-first search (\sQuote{\code{unweighted}}), this only works for unweighted graphs; the Dijkstra algorithm (\sQuote{\code{dijkstra}}), this works for graphs with non-negative edge weights; the Bellman-Ford algorithm (\sQuote{\code{bellman-ford}}), and Johnson's algorithm (\sQuote{\code{"johnson"}}). The latter two algorithms work with arbitrary edge weights, but (naturally) only for graphs that don't have a negative cycle. igraph can choose automatically between algorithms, and chooses the most efficient one that is appropriate for the supplied weights (if any). For automatic algorithm selection, supply \sQuote{\code{automatic}} as the \code{algorithm} argument. (This is also the default.) \code{shortest_paths} calculates a single shortest path (i.e. the path itself, not just its length) between the source vertex given in \code{from}, to the target vertices given in \code{to}. \code{shortest_paths} uses breadth-first search for unweighted graphs and Dijkstra's algorithm for weighted graphs. The latter only works if the edge weights are non-negative. \code{all_shortest_paths} calculates \emph{all} shortest paths between pairs of vertices. More precisely, between the \code{from} vertex to the vertices given in \code{to}. It uses a breadth-first search for unweighted graphs and Dijkstra's algorithm for weighted ones. The latter only supports non-negative edge weights. \code{mean_distance} calculates the average path length in a graph, by calculating the shortest paths between all pairs of vertices (both ways for directed graphs). This function does not consider edge weights currently and uses a breadth-first search. \code{distance_table} calculates a histogram, by calculating the shortest path length between each pair of vertices. For directed graphs both directions are considered, so every pair of vertices appears twice in the histogram. } \examples{ g <- make_ring(10) distances(g) shortest_paths(g, 5) all_shortest_paths(g, 1, 6:8) mean_distance(g) ## Weighted shortest paths el <- matrix(nc=3, byrow=TRUE, c(1,2,0, 1,3,2, 1,4,1, 2,3,0, 2,5,5, 2,6,2, 3,2,1, 3,4,1, 3,7,1, 4,3,0, 4,7,2, 5,6,2, 5,8,8, 6,3,2, 6,7,1, 6,9,1, 6,10,3, 8,6,1, 8,9,1, 9,10,4) ) g2 <- add_edges(make_empty_graph(10), t(el[,1:2]), weight=el[,3]) distances(g2, mode="out") } \references{ West, D.B. (1996). \emph{Introduction to Graph Theory.} Upper Saddle River, N.J.: Prentice Hall. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_as_star.Rd0000644000175100001440000000412213430770475015646 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_as_star} \alias{layout_as_star} \alias{layout.star} \alias{as_star} \title{Generate coordinates to place the vertices of a graph in a star-shape} \usage{ layout_as_star(graph, center = V(graph)[1], order = NULL) as_star(...) } \arguments{ \item{graph}{The graph to layout.} \item{center}{The id of the vertex to put in the center. By default it is the first vertex.} \item{order}{Numeric vector, the order of the vertices along the perimeter. The default ordering is given by the vertex ids.} \item{...}{Arguments to pass to \code{layout_as_star}.} } \value{ A matrix with two columns and as many rows as the number of vertices in the input graph. } \description{ A simple layout generator, that places one vertex in the center of a circle and the rest of the vertices equidistantly on the perimeter. } \details{ It is possible to choose the vertex that will be in the center, and the order of the vertices can be also given. } \examples{ g <- make_star(10) layout_as_star(g) ## Alternative form layout_(g, as_star()) } \seealso{ \code{\link{layout}} and \code{\link{layout.drl}} for other layout algorithms, \code{\link{plot.igraph}} and \code{\link{tkplot}} on how to plot graphs and \code{\link{star}} on how to create ring graphs. Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/convex_hull.Rd0000644000175100001440000000172213430770475015146 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/other.R \name{convex_hull} \alias{convex_hull} \alias{convex.hull} \title{Convex hull of a set of vertices} \usage{ convex_hull(data) } \arguments{ \item{data}{The data points, a numeric matrix with two columns.} } \value{ A named list with components: \item{resverts}{The indices of the input vertices that constritute the convex hull.} \item{rescoords}{The coordinates of the corners of the convex hull.} } \description{ Calculate the convex hull of a set of points, i.e. the covering polygon that has the smallest area. } \examples{ M <- cbind( runif(100), runif(100) ) convex_hull(M) } \references{ Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0262032937. Pages 949-955 of section 33.3: Finding the convex hull. } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/unfold_tree.Rd0000644000175100001440000000314113430770476015124 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{unfold_tree} \alias{unfold_tree} \alias{unfold.tree} \title{Convert a general graph into a forest} \usage{ unfold_tree(graph, mode = c("all", "out", "in", "total"), roots) } \arguments{ \item{graph}{The input graph, it can be either directed or undirected.} \item{mode}{Character string, defined the types of the paths used for the breadth-first search. \dQuote{out} follows the outgoing, \dQuote{in} the incoming edges, \dQuote{all} and \dQuote{total} both of them. This argument is ignored for undirected graphs.} \item{roots}{A vector giving the vertices from which the breadth-first search is performed. Typically it contains one vertex per component.} } \value{ A list with two components: \item{tree}{The result, an \code{igraph} object, a tree or a forest.} \item{vertex_index}{A numeric vector, it gives a mapping from the vertices of the new graph to the vertices of the old graph.} } \description{ Perform a breadth-first search on a graph and convert it into a tree or forest by replicating vertices that were found more than once. } \details{ A forest is a graph, whose components are trees. The \code{roots} vector can be calculated by simply doing a topological sort in all components of the graph, see the examples below. } \examples{ g <- make_tree(10) \%du\% make_tree(10) V(g)$id <- seq_len(vcount(g))-1 roots <- sapply(decompose(g), function(x) { V(x)$id[ topo_sort(x)[1]+1 ] }) tree <- unfold_tree(g, roots=roots) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/simplified.Rd0000644000175100001440000000117313430770475014745 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{simplified} \alias{simplified} \title{Constructor modifier to drop multiple and loop edges} \usage{ simplified() } \description{ Constructor modifier to drop multiple and loop edges } \examples{ sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), simplified()) } \seealso{ Other constructor modifiers: \code{\link{with_edge_}}, \code{\link{with_graph_}}, \code{\link{with_vertex_}}, \code{\link{without_attr}}, \code{\link{without_loops}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/graph_from_adjacency_matrix.Rd0000644000175100001440000001521313430770475020331 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/adjacency.R \name{graph_from_adjacency_matrix} \alias{graph_from_adjacency_matrix} \alias{graph.adjacency} \alias{from_adjacency} \title{Create graphs from adjacency matrices} \usage{ graph_from_adjacency_matrix(adjmatrix, mode = c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted = NULL, diag = TRUE, add.colnames = NULL, add.rownames = NA) from_adjacency(...) } \arguments{ \item{adjmatrix}{A square adjacency matrix. From igraph version 0.5.1 this can be a sparse matrix created with the \code{Matrix} package.} \item{mode}{Character scalar, specifies how igraph should interpret the supplied matrix. See also the \code{weighted} argument, the interpretation depends on that too. Possible values are: \code{directed}, \code{undirected}, \code{upper}, \code{lower}, \code{max}, \code{min}, \code{plus}. See details below.} \item{weighted}{This argument specifies whether to create a weighted graph from an adjacency matrix. If it is \code{NULL} then an unweighted graph is created and the elements of the adjacency matrix gives the number of edges between the vertices. If it is a character constant then for every non-zero matrix entry an edge is created and the value of the entry is added as an edge attribute named by the \code{weighted} argument. If it is \code{TRUE} then a weighted graph is created and the name of the edge attribute will be \code{weight}. See also details below.} \item{diag}{Logical scalar, whether to include the diagonal of the matrix in the calculation. If this is \code{FALSE} then the diagonal is zerod out first.} \item{add.colnames}{Character scalar, whether to add the column names as vertex attributes. If it is \sQuote{\code{NULL}} (the default) then, if present, column names are added as vertex attribute \sQuote{name}. If \sQuote{\code{NA}} then they will not be added. If a character constant, then it gives the name of the vertex attribute to add.} \item{add.rownames}{Character scalar, whether to add the row names as vertex attributes. Possible values the same as the previous argument. By default row names are not added. If \sQuote{\code{add.rownames}} and \sQuote{\code{add.colnames}} specify the same vertex attribute, then the former is ignored.} \item{...}{Passed to \code{graph_from_adjacency_matrix}.} } \value{ An igraph graph object. } \description{ \code{graph_from_adjacency_matrix} is a flexible function for creating \code{igraph} graphs from adjacency matrices. } \details{ The order of the vertices are preserved, i.e. the vertex corresponding to the first row will be vertex 0 in the graph, etc. \code{graph_from_adjacency_matrix} operates in two main modes, depending on the \code{weighted} argument. If this argument is \code{NULL} then an unweighted graph is created and an element of the adjacency matrix gives the number of edges to create between the two corresponding vertices. The details depend on the value of the \code{mode} argument: \describe{ \item{"directed"}{The graph will be directed and a matrix element gives the number of edges between two vertices.} \item{"undirected"}{This is exactly the same as \code{max}, for convenience. Note that it is \emph{not} checked whether the matrix is symmetric.} \item{"max"}{An undirected graph will be created and \code{max(A(i,j), A(j,i))} gives the number of edges.} \item{"upper"}{An undirected graph will be created, only the upper right triangle (including the diagonal) is used for the number of edges.} \item{"lower"}{An undirected graph will be created, only the lower left triangle (including the diagonal) is used for creating the edges.} \item{"min"}{undirected graph will be created with \code{min(A(i,j), A(j,i))} edges between vertex \code{i} and \code{j}.} \item{"plus"}{ undirected graph will be created with \code{A(i,j)+A(j,i)} edges between vertex \code{i} and \code{j}.} } If the \code{weighted} argument is not \code{NULL} then the elements of the matrix give the weights of the edges (if they are not zero). The details depend on the value of the \code{mode} argument: \describe{ \item{"directed"}{The graph will be directed and a matrix element gives the edge weights.} \item{"undirected"}{First we check that the matrix is symmetric. It is an error if not. Then only the upper triangle is used to create a weighted undirected graph.} \item{"max"}{An undirected graph will be created and \code{max(A(i,j), A(j,i))} gives the edge weights.} \item{"upper"}{An undirected graph will be created, only the upper right triangle (including the diagonal) is used (for the edge weights).} \item{"lower"}{An undirected graph will be created, only the lower left triangle (including the diagonal) is used for creating the edges.} \item{"min"}{An undirected graph will be created, \code{min(A(i,j), A(j,i))} gives the edge weights.} \item{"plus"}{An undirected graph will be created, \code{A(i,j)+A(j,i)} gives the edge weights.} } } \examples{ adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.9,0.1)), nc=10) g1 <- graph_from_adjacency_matrix( adjm ) adjm <- matrix(sample(0:5, 100, replace=TRUE, prob=c(0.9,0.02,0.02,0.02,0.02,0.02)), nc=10) g2 <- graph_from_adjacency_matrix(adjm, weighted=TRUE) E(g2)$weight ## various modes for weighted graphs, with some tests nzs <- function(x) sort(x [x!=0]) adjm <- matrix(runif(100), 10) adjm[ adjm<0.5 ] <- 0 g3 <- graph_from_adjacency_matrix((adjm + t(adjm))/2, weighted=TRUE, mode="undirected") g4 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="max") all(nzs(pmax(adjm, t(adjm))[upper.tri(adjm)]) == sort(E(g4)$weight)) g5 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="min") all(nzs(pmin(adjm, t(adjm))[upper.tri(adjm)]) == sort(E(g5)$weight)) g6 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="upper") all(nzs(adjm[upper.tri(adjm)]) == sort(E(g6)$weight)) g7 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="lower") all(nzs(adjm[lower.tri(adjm)]) == sort(E(g7)$weight)) g8 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="plus") d2 <- function(x) { diag(x) <- diag(x)/2; x } all(nzs((d2(adjm+t(adjm)))[lower.tri(adjm)]) == sort(E(g8)$weight)) g9 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="plus", diag=FALSE) d0 <- function(x) { diag(x) <- 0 } all(nzs((d0(adjm+t(adjm)))[lower.tri(adjm)]) == sort(E(g9)$weight)) ## row/column names rownames(adjm) <- sample(letters, nrow(adjm)) colnames(adjm) <- seq(ncol(adjm)) g10 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, add.rownames="code") summary(g10) } \seealso{ \link{graph} and \code{\link{graph_from_literal}} for other ways to create graphs. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/hub_score.Rd0000644000175100001440000000425213430770475014572 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{hub_score} \alias{hub_score} \alias{hub.score} \title{Kleinberg's hub centrality scores.} \usage{ hub_score(graph, scale = TRUE, weights = NULL, options = arpack_defaults) } \arguments{ \item{graph}{The input graph.} \item{scale}{Logical scalar, whether to scale the result to have a maximum score of one. If no scaling is used then the result vector has unit length in the Euclidean norm.} \item{weights}{Optional positive weight vector for calculating weighted scores. If the graph has a \code{weight} edge attribute, then this is used by default. This function interprets edge weights as connection strengths. In the random surfer model, an edge with a larger weight is more likely to be selected by the surfer.} \item{options}{A named list, to override some ARPACK options. See \code{\link{arpack}} for details.} } \value{ A named list with members: \item{vector}{The authority/hub scores of the vertices.} \item{value}{The corresponding eigenvalue of the calculated principal eigenvector.} \item{options}{Some information about the ARPACK computation, it has the same members as the \code{options} member returned by \code{\link{arpack}}, see that for documentation.} } \description{ The hub scores of the vertices are defined as the principal eigenvector of \eqn{A A^T}{A*t(A)}, where \eqn{A} is the adjacency matrix of the graph. } \details{ For undirected matrices the adjacency matrix is symmetric and the hub scores are the same as authority scores, see \code{\link{authority_score}}. } \examples{ ## An in-star g <- make_star(10) hub_score(g)$vector ## A ring g2 <- make_ring(10) hub_score(g2)$vector } \references{ J. Kleinberg. Authoritative sources in a hyperlinked environment. \emph{Proc. 9th ACM-SIAM Symposium on Discrete Algorithms}, 1998. Extended version in \emph{Journal of the ACM} 46(1999). Also appears as IBM Research Report RJ 10076, May 1997. } \seealso{ \code{\link{authority_score}}, \code{\link{eigen_centrality}} for eigenvector centrality, \code{\link{page_rank}} for the Page Rank scores. \code{\link{arpack}} for the underlining machinery of the computation. } igraph/man/reciprocity.Rd0000644000175100001440000000324113430770476015153 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{reciprocity} \alias{reciprocity} \title{Reciprocity of graphs} \usage{ reciprocity(graph, ignore.loops = TRUE, mode = c("default", "ratio")) } \arguments{ \item{graph}{The graph object.} \item{ignore.loops}{Logical constant, whether to ignore loop edges.} \item{mode}{See below.} } \value{ A numeric scalar between zero and one. } \description{ Calculates the reciprocity of a directed graph. } \details{ The measure of reciprocity defines the proportion of mutual connections, in a directed graph. It is most commonly defined as the probability that the opposite counterpart of a directed edge is also included in the graph. Or in adjacency matrix notation: \eqn{\sum_{ij} (A\cdot A')_{ij}}{sum(i, j, (A.*A')ij) / sum(i, j, Aij)}, where \eqn{A\cdot A'}{A.*A'} is the element-wise product of matrix \eqn{A} and its transpose. This measure is calculated if the \code{mode} argument is \code{default}. Prior to igraph version 0.6, another measure was implemented, defined as the probability of mutual connection between a vertex pair, if we know that there is a (possibly non-mutual) connection between them. In other words, (unordered) vertex pairs are classified into three groups: (1) not-connected, (2) non-reciprocaly connected, (3) reciprocally connected. The result is the size of group (3), divided by the sum of group sizes (2)+(3). This measure is calculated if \code{mode} is \code{ratio}. } \examples{ g <- sample_gnp(20, 5/20, directed=TRUE) reciprocity(g) } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_chordal_ring.Rd0000644000175100001440000000326713430770475016256 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_chordal_ring} \alias{make_chordal_ring} \alias{graph.extended.chordal.ring} \alias{chordal_ring} \title{Create an extended chordal ring graph} \usage{ make_chordal_ring(n, w) chordal_ring(...) } \arguments{ \item{n}{The number of vertices.} \item{w}{A matrix which specifies the extended chordal ring. See details below.} \item{...}{Passed to \code{make_chordal_ring}.} } \value{ An igraph graph. } \description{ \code{make_chordal_ring} creates an extended chordal ring. An extended chordal ring is regular graph, each node has the same degree. It can be obtained from a simple ring by adding some extra edges specified by a matrix. Let p denote the number of columns in the \sQuote{\code{W}} matrix. The extra edges of vertex \code{i} are added according to column \code{i mod p} in \sQuote{\code{W}}. The number of extra edges is the number of rows in \sQuote{\code{W}}: for each row \code{j} an edge \code{i->i+w[ij]} is added if \code{i+w[ij]} is less than the number of total nodes. See also Kotsis, G: Interconnection Topologies for Parallel Processing Systems, PARS Mitteilungen 11, 1-6, 1993. } \examples{ chord <- make_chordal_ring(15, matrix(c(3, 12, 4, 7, 8, 11), nr = 2)) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{determimistic constructors} igraph/man/graph_from_atlas.Rd0000644000175100001440000000305213430770475016126 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{graph_from_atlas} \alias{graph_from_atlas} \alias{graph.atlas} \alias{atlas} \title{Create a graph from the Graph Atlas} \usage{ graph_from_atlas(n) atlas(...) } \arguments{ \item{n}{The id of the graph to create.} \item{...}{Passed to \code{graph_from_atlas}.} } \value{ An igraph graph. } \description{ \code{graph_from_atlas} creates graphs from the book \sQuote{An Atlas of Graphs} by Roland C. Read and Robin J. Wilson. The atlas contains all undirected graphs with up to seven vertices, numbered from 0 up to 1252. The graphs are listed: \enumerate{ \item in increasing order of number of nodes; \item for a fixed number of nodes, in increasing order of the number of edges; \item for fixed numbers of nodes and edges, in increasing order of the degree sequence, for example 111223 < 112222; \item for fixed degree sequence, in increasing number of automorphisms. } } \examples{ ## Some randomly picked graphs from the atlas graph_from_atlas(sample(0:1252, 1)) graph_from_atlas(sample(0:1252, 1)) } \seealso{ Other determimistic constructors: \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{Graph Atlas.} \concept{determimistic constructors} igraph/man/dyad_census.Rd0000644000175100001440000000226713430770475015126 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/motifs.R \name{dyad_census} \alias{dyad_census} \alias{dyad.census} \title{Dyad census of a graph} \usage{ dyad_census(graph) } \arguments{ \item{graph}{The input graph. A warning is given if it is not directed.} } \value{ A named numeric vector with three elements: \item{mut}{The number of pairs with mutual connections.} \item{asym}{The number of pairs with non-mutual connections.} \item{null}{The number of pairs with no connection between them.} } \description{ Classify dyads in a directed graphs. The relationship between each pair of vertices is measured. It can be in three states: mutual, asymmetric or non-existent. } \examples{ g <- sample_pa(100) dyad_census(g) } \references{ Holland, P.W. and Leinhardt, S. A Method for Detecting Structure in Sociometric Data. \emph{American Journal of Sociology}, 76, 492--513. 1970. Wasserman, S., and Faust, K. \emph{Social Network Analysis: Methods and Applications.} Cambridge: Cambridge University Press. 1994. } \seealso{ \code{\link{triad_census}} for the same classification, but with triples. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/st_min_cuts.Rd0000644000175100001440000000436713430770475015157 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{st_min_cuts} \alias{st_min_cuts} \alias{stMincuts} \title{List all minimum \eqn{(s,t)}-cuts of a graph} \usage{ st_min_cuts(graph, source, target, capacity = NULL) } \arguments{ \item{graph}{The input graph. It must be directed.} \item{source}{The id of the source vertex.} \item{target}{The id of the target vertex.} \item{capacity}{Numeric vector giving the edge capacities. If this is \code{NULL} and the graph has a \code{weight} edge attribute, then this attribute defines the edge capacities. For forcing unit edge capacities, even for graphs that have a \code{weight} edge attribute, supply \code{NA} here.} } \value{ A list with entries: \item{value}{Numeric scalar, the size of the minimum cut(s).} \item{cuts}{A list of numeric vectors containing edge ids. Each vector is a minimum \eqn{(s,t)}-cut.} \item{partition1s}{A list of numeric vectors containing vertex ids, they correspond to the edge cuts. Each vertex set is a generator of the corresponding cut, i.e. in the graph \eqn{G=(V,E)}, the vertex set \eqn{X} and its complementer \eqn{V-X}, generates the cut that contains exactly the edges that go from \eqn{X} to \eqn{V-X}.} } \description{ Listing all minimum \eqn{(s,t)}-cuts of a directed graph, for given \eqn{s} and \eqn{t}. } \details{ Given a \eqn{G} directed graph and two, different and non-ajacent vertices, \eqn{s} and \eqn{t}, an \eqn{(s,t)}-cut is a set of edges, such that after removing these edges from \eqn{G} there is no directed path from \eqn{s} to \eqn{t}. The size of an \eqn{(s,t)}-cut is defined as the sum of the capacities (or weights) in the cut. For unweighed (=equally weighted) graphs, this is simply the number of edges. An \eqn{(s,t)}-cut is minimum if it is of the smallest possible size. } \examples{ # A difficult graph, from the Provan-Shier paper g <- graph_from_literal(s --+ a:b, a:b --+ t, a --+ 1:2:3:4:5, 1:2:3:4:5 --+ b) st_min_cuts(g, source="s", target="t") } \references{ JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, \emph{Algorithmica} 15, 351--372, 1996. } \seealso{ \code{\link{st_cuts}}, \code{\link{min_separators}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/rev.igraph.es.Rd0000644000175100001440000000206513430770475015274 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{rev.igraph.es} \alias{rev.igraph.es} \title{Reverse the order in an edge sequence} \usage{ \method{rev}{igraph.es}(x) } \arguments{ \item{x}{The edge sequence to reverse.} } \value{ The reversed edge sequence. } \description{ Reverse the order in an edge sequence } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g) E(g) \%>\% rev() } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/components.Rd0000644000175100001440000000512513430770475015006 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/components.R, R/structural.properties.R \name{component_distribution} \alias{component_distribution} \alias{components} \alias{no.clusters} \alias{clusters} \alias{is.connected} \alias{cluster.distribution} \alias{count_components} \alias{is_connected} \title{Connected components of a graph} \usage{ component_distribution(graph, cumulative = FALSE, mul.size = FALSE, ...) components(graph, mode = c("weak", "strong")) } \arguments{ \item{graph}{The graph to analyze.} \item{cumulative}{Logical, if TRUE the cumulative distirubution (relative frequency) is calculated.} \item{mul.size}{Logical. If TRUE the relative frequencies will be multiplied by the cluster sizes.} \item{\dots}{Additional attributes to pass to \code{cluster}, right now only \code{mode} makes sense.} \item{mode}{Character string, either \dQuote{weak} or \dQuote{strong}. For directed graphs \dQuote{weak} implies weakly, \dQuote{strong} strongly connected components to search. It is ignored for undirected graphs.} } \value{ For \code{is_connected} a logical constant. For \code{components} a named list with three components: \item{membership}{numeric vector giving the cluster id to which each vertex belongs.} \item{csize}{numeric vector giving the sizes of the clusters.} \item{no}{numeric constant, the number of clusters.} For \code{count_components} an integer constant is returned. For \code{component_distribution} a numeric vector with the relative frequencies. The length of the vector is the size of the largest component plus one. Note that (for currently unknown reasons) the first element of the vector is the number of clusters of size zero, so this is always zero. } \description{ Calculate the maximal (weakly or strongly) connected components of a graph } \details{ \code{is_connected} decides whether the graph is weakly or strongly connected. \code{components} finds the maximal (weakly or strongly) connected components of a graph. \code{count_components} does almost the same as \code{components} but returns only the number of clusters found instead of returning the actual clusters. \code{component_distribution} creates a histogram for the maximal connected component sizes. The weakly connected components are found by a simple breadth-first search. The strongly connected components are implemented by two consecutive depth-first searches. } \examples{ g <- sample_gnp(20, 1/20) clu <- components(g) groups(clu) } \seealso{ \code{\link{subcomponent}}, \code{\link{groups}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/igraph-vs-attributes.Rd0000644000175100001440000000550413430770475016706 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-vs-attributes} \alias{igraph-vs-attributes} \alias{[[<-.igraph.vs} \alias{[<-.igraph.vs} \alias{$.igraph.vs} \alias{$<-.igraph.vs} \alias{V<-} \title{Query or set attributes of the vertices in a vertex sequence} \usage{ \method{[[}{igraph.vs}(x, i) <- value \method{[}{igraph.vs}(x, i) <- value \method{$}{igraph.vs}(x, name) \method{$}{igraph.vs}(x, name) <- value V(x) <- value } \arguments{ \item{x}{A vertex sequence. For \code{V<-} it is a graph.} \item{i}{Index.} \item{value}{New value of the attribute, for the vertices in the vertex sequence.} \item{name}{Name of the vertex attribute to query or set.} } \value{ A vector or list, containing the values of attribute \code{name} for the vertices in the vertex sequence. For numeric, character or logical attributes, it is a vector of the appropriate type, otherwise it is a list. } \description{ The \code{$} operator is a syntactic sugar to query and set the attributes of the vertices in a vertex sequence. } \details{ The query form of \code{$} is a shortcut for \code{\link{vertex_attr}}, e.g. \code{V(g)[idx]$attr} is equivalent to \code{vertex_attr(g, attr, V(g)[idx])}. The assignment form of \code{$} is a shortcut for \code{\link{set_vertex_attr}}, e.g. \code{V(g)[idx]$attr <- value} is equivalent to \code{g <- set_vertex_attr(g, attr, V(g)[idx], value)}. } \examples{ g <- make_(ring(10), with_vertex_( name = LETTERS[1:10], color = sample(1:2, 10, replace=TRUE) ) ) V(g)$name V(g)$color V(g)$frame.color <- V(g)$color # color vertices of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_(gnp(100, 2/100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "blue" V(g)[giant_v]$color <- "orange" plot(g) } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} \concept{vertex and edge sequences} igraph/man/difference.igraph.es.Rd0000644000175100001440000000263113430770475016571 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{difference.igraph.es} \alias{difference.igraph.es} \title{Difference of edge sequences} \usage{ \method{difference}{igraph.es}(big, small, ...) } \arguments{ \item{big}{The \sQuote{big} edge sequence.} \item{small}{The \sQuote{small} edge sequence.} \item{...}{Ignored, included for S3 signature compatibility.} } \value{ An edge sequence that contains only edges that are part of \code{big}, but not part of \code{small}. } \description{ Difference of edge sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of edges is lost in the result. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/intersection.igraph.Rd0000644000175100001440000000421313430770475016575 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{intersection.igraph} \alias{intersection.igraph} \alias{graph.intersection} \alias{\%s\%} \title{Intersection of graphs} \usage{ \method{intersection}{igraph}(..., byname = "auto", keep.all.vertices = TRUE) } \arguments{ \item{\dots}{Graph objects or lists of graph objects.} \item{byname}{A logical scalar, or the character scalar \code{auto}. Whether to perform the operation based on symbolic vertex names. If it is \code{auto}, that means \code{TRUE} if all graphs are named and \code{FALSE} otherwise. A warning is generated if \code{auto} and some (but not all) graphs are named.} \item{keep.all.vertices}{Logical scalar, whether to keep vertices that only appear in a subset of the input graphs.} } \value{ A new graph object. } \description{ The intersection of two or more graphs are created. The graphs may have identical or overlapping vertex sets. } \details{ \code{intersection} creates the intersection of two or more graphs: only edges present in all graphs will be included. The corresponding operator is \%s\%. If the \code{byname} argument is \code{TRUE} (or \code{auto} and all graphs are named), then the operation is performed on symbolic vertex names instead of the internal numeric vertex ids. \code{intersection} keeps the attributes of all graphs. All graph, vertex and edge attributes are copied to the result. If an attribute is present in multiple graphs and would result a name clash, then this attribute is renamed by adding suffixes: _1, _2, etc. The \code{name} vertex attribute is treated specially if the operation is performed based on symbolic vertex names. In this case \code{name} must be present in all graphs, and it is not renamed in the result graph. An error is generated if some input graphs are directed and others are undirected. } \examples{ ## Common part of two social networks net1 <- graph_from_literal(D-A:B:F:G, A-C-F-A, B-E-G-B, A-B, F-G, H-F:G, H-I-J) net2 <- graph_from_literal(D-A:F:Y, B-A-X-F-H-Z, F-Y) print_all(net1 \%s\% net2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/centr_clo.Rd0000644000175100001440000000315113430770475014566 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_clo} \alias{centr_clo} \alias{centralization.closeness} \title{Centralize a graph according to the closeness of vertices} \usage{ centr_clo(graph, mode = c("out", "in", "all", "total"), normalized = TRUE) } \arguments{ \item{graph}{The input graph.} \item{mode}{This is the same as the \code{mode} argument of \code{closeness}.} \item{normalized}{Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum.} } \value{ A named list with the following components: \item{res}{The node-level centrality scores.} \item{centralization}{The graph level centrality index.} \item{theoretical_max}{The maximum theoretical graph level centralization score for a graph with the given number of vertices, using the same parameters. If the \code{normalized} argument was \code{TRUE}, then the result was divided by this number.} } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/simplify.Rd0000644000175100001440000000345313430770476014460 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/simple.R \name{simplify} \alias{simplify} \alias{is.simple} \alias{is_simple} \title{Simple graphs} \usage{ simplify(graph, remove.multiple = TRUE, remove.loops = TRUE, edge.attr.comb = igraph_opt("edge.attr.comb")) is_simple(graph) } \arguments{ \item{graph}{The graph to work on.} \item{remove.multiple}{Logical, whether the multiple edges are to be removed.} \item{remove.loops}{Logical, whether the loop edges are to be removed.} \item{edge.attr.comb}{Specifies what to do with edge attributes, if \code{remove.multiple=TRUE}. In this case many edges might be mapped to a single one in the new graph, and their attributes are combined. Please see \code{\link{attribute.combination}} for details on this.} } \value{ A new graph object with the edges deleted. } \description{ Simple graphs are graphs which do not contain loop and multiple edges. } \details{ A loop edge is an edge for which the two endpoints are the same vertex. Two edges are multiple edges if they have exactly the same two endpoints (for directed graphs order does matter). A graph is simple is it does not contain loop edges and multiple edges. \code{is_simple} checks whether a graph is simple. \code{simplify} removes the loop and/or multiple edges from a graph. If both \code{remove.loops} and \code{remove.multiple} are \code{TRUE} the function returns a simple graph. } \examples{ g <- graph( c(1,2,1,2,3,3) ) is_simple(g) is_simple(simplify(g, remove.loops=FALSE)) is_simple(simplify(g, remove.multiple=FALSE)) is_simple(simplify(g)) } \seealso{ \code{\link{which_loop}}, \code{\link{which_multiple}} and \code{\link{count_multiple}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/cluster_label_prop.Rd0000644000175100001440000000560613430770475016505 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_label_prop} \alias{cluster_label_prop} \alias{label.propagation.community} \title{Finding communities based on propagating labels} \usage{ cluster_label_prop(graph, weights = NULL, initial = NULL, fixed = NULL) } \arguments{ \item{graph}{The input graph, should be undirected to make sense.} \item{weights}{An optional weight vector. It should contain a positive weight for all the edges. The \sQuote{weight} edge attribute is used if present. Supply \sQuote{\code{NA}} here if you want to ignore the \sQuote{weight} edge attribute. Larger edge weights correspond to stronger connections.} \item{initial}{The initial state. If \code{NULL}, every vertex will have a different label at the beginning. Otherwise it must be a vector with an entry for each vertex. Non-negative values denote different labels, negative entries denote vertices without labels.} \item{fixed}{Logical vector denoting which labels are fixed. Of course this makes sense only if you provided an initial state, otherwise this element will be ignored. Also note that vertices without labels cannot be fixed.} } \value{ \code{cluster_label_prop} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ This is a fast, nearly linear time algorithm for detecting community structure in networks. In works by labeling the vertices with unique labels and then updating the labels by majority voting in the neighborhood of the vertex. } \details{ This function implements the community detection method described in: Raghavan, U.N. and Albert, R. and Kumara, S.: Near linear time algorithm to detect community structures in large-scale networks. Phys Rev E 76, 036106. (2007). This version extends the original method by the ability to take edge weights into consideration and also by allowing some labels to be fixed. From the abstract of the paper: \dQuote{In our algorithm every node is initialized with a unique label and at every step each node adopts the label that most of its neighbors currently have. In this iterative process densely connected groups of nodes form a consensus on a unique label to form communities.} } \examples{ g <- sample_gnp(10, 5/10) \%du\% sample_gnp(9, 5/9) g <- add_edges(g, c(1, 12)) cluster_label_prop(g) } \references{ Raghavan, U.N. and Albert, R. and Kumara, S.: Near linear time algorithm to detect community structures in large-scale networks. \emph{Phys Rev E} 76, 036106. (2007) } \seealso{ \code{\link{communities}} for extracting the actual results. \code{\link{cluster_fast_greedy}}, \code{\link{cluster_walktrap}} and \code{\link{cluster_spinglass}} for other community detection methods. } \author{ Tamas Nepusz \email{ntamas@gmail.com} for the C implementation, Gabor Csardi \email{csardi.gabor@gmail.com} for this manual page. } \keyword{graphs} igraph/man/sample_fitness.Rd0000644000175100001440000000611313430770475015633 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_fitness} \alias{sample_fitness} \alias{static.fitness.game} \title{Random graphs from vertex fitness scores} \usage{ sample_fitness(no.of.edges, fitness.out, fitness.in = NULL, loops = FALSE, multiple = FALSE) } \arguments{ \item{no.of.edges}{The number of edges in the generated graph.} \item{fitness.out}{A numeric vector containing the fitness of each vertex. For directed graphs, this specifies the out-fitness of each vertex.} \item{fitness.in}{If \code{NULL} (the default), the generated graph will be undirected. If not \code{NULL}, then it should be a numeric vector and it specifies the in-fitness of each vertex. If this argument is not \code{NULL}, then a directed graph is generated, otherwise an undirected one.} \item{loops}{Logical scalar, whether to allow loop edges in the graph.} \item{multiple}{Logical scalar, whether to allow multiple edges in the graph.} } \value{ An igraph graph, directed or undirected. } \description{ This function generates a non-growing random graph with edge probabilities proportional to node fitness scores. } \details{ This game generates a directed or undirected random graph where the probability of an edge between vertices \eqn{i} and \eqn{j} depends on the fitness scores of the two vertices involved. For undirected graphs, each vertex has a single fitness score. For directed graphs, each vertex has an out- and an in-fitness, and the probability of an edge from \eqn{i} to \eqn{j} depends on the out-fitness of vertex \eqn{i} and the in-fitness of vertex \eqn{j}. The generation process goes as follows. We start from \eqn{N} disconnected nodes (where \eqn{N} is given by the length of the fitness vector). Then we randomly select two vertices \eqn{i} and \eqn{j}, with probabilities proportional to their fitnesses. (When the generated graph is directed, \eqn{i} is selected according to the out-fitnesses and \eqn{j} is selected according to the in-fitnesses). If the vertices are not connected yet (or if multiple edges are allowed), we connect them; otherwise we select a new pair. This is repeated until the desired number of links are created. It can be shown that the \emph{expected} degree of each vertex will be proportional to its fitness, although the actual, observed degree will not be. If you need to generate a graph with an exact degree sequence, consider \code{\link{sample_degseq}} instead. This model is commonly used to generate static scale-free networks. To achieve this, you have to draw the fitness scores from the desired power-law distribution. Alternatively, you may use \code{\link{sample_fitness_pl}} which generates the fitnesses for you with a given exponent. } \examples{ N <- 10000 g <- sample_fitness(5*N, sample((1:50)^-2, N, replace=TRUE)) degree_distribution(g) \dontrun{plot(degree_distribution(g, cumulative=TRUE), log="xy")} } \references{ Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution in scale-free networks. \emph{Phys Rev Lett} 87(27):278701, 2001. } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/component_wise.Rd0000644000175100001440000000262613430770475015655 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{component_wise} \alias{component_wise} \title{Component-wise layout} \usage{ component_wise(merge_method = "dla") } \arguments{ \item{merge_method}{Merging algorithm, the \code{method} argument of \code{\link{merge_coords}}.} } \description{ This is a layout modifier function, and it can be used to calculate the layout separately for each component of the graph. } \examples{ g <- make_ring(10) + make_ring(10) g \%>\% add_layout_(in_circle(), component_wise()) \%>\% plot() } \seealso{ \code{\link{merge_coords}}, \code{\link{layout_}}. Other layout modifiers: \code{\link{normalize}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \concept{graph layouts} \concept{layout modifiers} igraph/man/as_membership.Rd0000644000175100001440000000137013430770475015435 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{as_membership} \alias{as_membership} \title{Declare a numeric vector as a membership vector} \usage{ as_membership(x) } \arguments{ \item{x}{The input vector.} } \value{ The input vector, with the \code{membership} class added. } \description{ This is useful if you want to use functions defined on membership vectors, but your membership vector does not come from an igraph clustering method. } \examples{ ## Compare to the correct clustering g <- (make_full_graph(10) + make_full_graph(10)) \%>\% rewire(each_edge(p = 0.2)) correct <- rep(1:2, each = 10) \%>\% as_membership fc <- cluster_fast_greedy(g) compare(correct, fc) compare(correct, membership(fc)) } igraph/man/subgraph_isomorphisms.Rd0000644000175100001440000000570313430770476017253 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{subgraph_isomorphisms} \alias{subgraph_isomorphisms} \alias{graph.get.subisomorphisms.vf2} \title{All isomorphic mappings between a graph and subgraphs of another graph} \usage{ subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...) } \arguments{ \item{pattern}{The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{target}{The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{method}{The method to use. Possible values: \sQuote{auto}, \sQuote{lad}, \sQuote{vf2}. See their details below.} \item{...}{Additional arguments, passed to the various methods.} } \value{ A list of vertex sequences, corresponding to all mappings from the first graph to the second. } \description{ All isomorphic mappings between a graph and subgraphs of another graph } \section{\sQuote{lad} method}{ This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments: \describe{ \item{domains}{If not \code{NULL}, then it specifies matching restrictions. It must be a list of \code{target} vertex sets, given as numeric vertex ids or symbolic vertex names. The length of the list must be \code{vcount(pattern)} and for each vertex in \code{pattern} it gives the allowed matching vertices in \code{target}. Defaults to \code{NULL}.} \item{induced}{Logical scalar, whether to search for an induced subgraph. It is \code{FALSE} by default.} \item{time.limit}{The processor time limit for the computation, in seconds. It defaults to \code{Inf}, which means no limit.} } } \section{\sQuote{vf2} method}{ This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments: \describe{ \item{vertex.color1, vertex.color2}{Optional integer vectors giving the colors of the vertices for colored graph isomorphism. If they are not given, but the graph has a \dQuote{color} vertex attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments. See also examples below.} \item{edge.color1, edge.color2}{Optional integer vectors giving the colors of the edges for edge-colored (sub)graph isomorphism. If they are not given, but the graph has a \dQuote{color} edge attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments.} } } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}} } \concept{graph isomorphism} igraph/man/arpack.Rd0000644000175100001440000002347613430770475014073 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \docType{data} \name{arpack_defaults} \alias{arpack_defaults} \alias{arpack} \alias{arpack-options} \alias{igraph.arpack.default} \alias{arpack.unpack.complex} \title{ARPACK eigenvector calculation} \format{An object of class \code{list} of length 14.} \usage{ arpack_defaults arpack(func, extra = NULL, sym = FALSE, options = arpack_defaults, env = parent.frame(), complex = !sym) } \arguments{ \item{func}{The function to perform the matrix-vector multiplication. ARPACK requires to perform these by the user. The function gets the vector \eqn{x} as the first argument, and it should return \eqn{Ax}, where \eqn{A} is the \dQuote{input matrix}. (The input matrix is never given explicitly.) The second argument is \code{extra}.} \item{extra}{Extra argument to supply to \code{func}.} \item{sym}{Logical scalar, whether the input matrix is symmetric. Always supply \code{TRUE} here if it is, since it can speed up the computation.} \item{options}{Options to ARPACK, a named list to overwrite some of the default option values. See details below.} \item{env}{The environment in which \code{func} will be evaluated.} \item{complex}{Whether to convert the eigenvectors returned by ARPACK into R complex vectors. By default this is not done for symmetric problems (these only have real eigenvectors/values), but only non-symmetric ones. If you have a non-symmetric problem, but you're sure that the results will be real, then supply \code{FALSE} here.} } \value{ A named list with the following members: \item{values}{Numeric vector, the desired eigenvalues.} \item{vectors}{Numeric matrix, the desired eigenvectors as columns. If \code{complex=TRUE} (the default for non-symmetric problems), then the matrix is complex.} \item{options}{A named list with the supplied \code{options} and some information about the performed calculation, including an ARPACK exit code. See the details above. } } \description{ Interface to the ARPACK library for calculating eigenvectors of sparse matrices } \details{ ARPACK is a library for solving large scale eigenvalue problems. The package is designed to compute a few eigenvalues and corresponding eigenvectors of a general \eqn{n} by \eqn{n} matrix \eqn{A}. It is most appropriate for large sparse or structured matrices \eqn{A} where structured means that a matrix-vector product \code{w <- Av} requires order \eqn{n} rather than the usual order \eqn{n^2} floating point operations. Please see \url{http://www.caam.rice.edu/software/ARPACK/} for details. This function is an interface to ARPACK. igraph does not contain all ARPACK routines, only the ones dealing with symmetric and non-symmetric eigenvalue problems using double precision real numbers. The eigenvalue calculation in ARPACK (in the simplest case) involves the calculation of the \eqn{Av} product where \eqn{A} is the matrix we work with and \eqn{v} is an arbitrary vector. The function supplied in the \code{fun} argument is expected to perform this product. If the product can be done efficiently, e.g. if the matrix is sparse, then \code{arpack} is usually able to calculate the eigenvalues very quickly. The \code{options} argument specifies what kind of calculation to perform. It is a list with the following members, they correspond directly to ARPACK parameters. On input it has the following fields: \describe{ \item{bmat}{Character constant, possible values: \sQuote{\code{I}}, stadard eigenvalue problem, \eqn{Ax=\lambda x}{A*x=lambda*x}; and \sQuote{\code{G}}, generalized eigenvalue problem, \eqn{Ax=\lambda B x}{A*x=lambda B*x}. Currently only \sQuote{\code{I}} is supported.} \item{n}{Numeric scalar. The dimension of the eigenproblem. You only need to set this if you call \code{\link{arpack}} directly. (I.e. not needed for \code{\link{eigen_centrality}}, \code{\link{page_rank}}, etc.)} \item{which}{Specify which eigenvalues/vectors to compute, character constant with exactly two characters. Possible values for symmetric input matrices: \describe{ \item{"LA"}{Compute \code{nev} largest (algebraic) eigenvalues.} \item{"SA"}{Compute \code{nev} smallest (algebraic) eigenvalues.} \item{"LM"}{Compute \code{nev} largest (in magnitude) eigenvalues.} \item{"SM"}{Compute \code{nev} smallest (in magnitude) eigenvalues.} \item{"BE"}{Compute \code{nev} eigenvalues, half from each end of the spectrum. When \code{nev} is odd, compute one more from the high end than from the low end.} } Possible values for non-symmetric input matrices: \describe{ \item{"LM"}{Compute \code{nev} eigenvalues of largest magnitude.} \item{"SM"}{Compute \code{nev} eigenvalues of smallest magnitude.} \item{"LR"}{Compute \code{nev} eigenvalues of largest real part.} \item{"SR"}{Compute \code{nev} eigenvalues of smallest real part.} \item{"LI"}{Compute \code{nev} eigenvalues of largest imaginary part.} \item{"SI"}{Compute \code{nev} eigenvalues of smallest imaginary part.} } This parameter is sometimes overwritten by the various functions, e.g. \code{\link{page_rank}} always sets \sQuote{\code{LM}}. } \item{nev}{Numeric scalar. The number of eigenvalues to be computed.} \item{tol}{Numeric scalar. Stopping criterion: the relative accuracy of the Ritz value is considered acceptable if its error is less than \code{tol} times its estimated value. If this is set to zero then machine precision is used.} \item{ncv}{Number of Lanczos vectors to be generated.} \item{ldv}{Numberic scalar. It should be set to zero in the current implementation.} \item{ishift}{Either zero or one. If zero then the shifts are provided by the user via reverse communication. If one then exact shifts with respect to the reduced tridiagonal matrix \eqn{T}. Please always set this to one.} \item{maxiter}{Maximum number of Arnoldi update iterations allowed. } \item{nb}{Blocksize to be used in the recurrence. Please always leave this on the default value, one.} \item{mode}{The type of the eigenproblem to be solved. Possible values if the input matrix is symmetric: \describe{ \item{1}{\eqn{Ax=\lambda x}{A*x=lambda*x}, \eqn{A} is symmetric.} \item{2}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is symmetric, \eqn{M} is symmetric positive definite.} \item{3}{\eqn{Kx=\lambda Mx}{K*x=lambda*M*x}, \eqn{K} is symmetric, \eqn{M} is symmetric positive semi-definite.} \item{4}{\eqn{Kx=\lambda KGx}{K*x=lambda*KG*x}, \eqn{K} is symmetric positive semi-definite, \eqn{KG} is symmetric indefinite.} \item{5}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is symmetric, \eqn{M} is symmetric positive semi-definite. (Cayley transformed mode.)} } Please note that only \code{mode==1} was tested and other values might not work properly. Possible values if the input matrix is not symmetric: \describe{ \item{1}{\eqn{Ax=\lambda x}{A*x=lambda*x}.} \item{2}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric positive definite.} \item{3}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric semi-definite.} \item{4}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric semi-definite.} } Please note that only \code{mode==1} was tested and other values might not work properly. } \item{start}{Not used currently. Later it be used to set a starting vector.} \item{sigma}{Not used currently.} \item{sigmai}{Not use currently.} On output the following additional fields are added: \describe{ \item{info}{Error flag of ARPACK. Possible values: \describe{ \item{0}{Normal exit.} \item{1}{Maximum number of iterations taken.} \item{3}{No shifts could be applied during a cycle of the Implicitly restarted Arnoldi iteration. One possibility is to increase the size of \code{ncv} relative to \code{nev}.} } ARPACK can return more error conditions than these, but they are converted to regular igraph errors. } \item{iter}{Number of Arnoldi iterations taken.} \item{nconv}{Number of \dQuote{converged} Ritz values. This represents the number of Ritz values that satisfy the convergence critetion. } \item{numop}{Total number of matrix-vector multiplications.} \item{numopb}{Not used currently.} \item{numreo}{Total number of steps of re-orthogonalization.} } } Please see the ARPACK documentation for additional details. } \examples{ # Identity matrix f <- function(x, extra=NULL) x arpack(f, options=list(n=10, nev=2, ncv=4), sym=TRUE) # Graph laplacian of a star graph (undirected), n>=2 # Note that this is a linear operation f <- function(x, extra=NULL) { y <- x y[1] <- (length(x)-1)*x[1] - sum(x[-1]) for (i in 2:length(x)) { y[i] <- x[i] - x[1] } y } arpack(f, options=list(n=10, nev=1, ncv=3), sym=TRUE) # double check eigen(laplacian_matrix(make_star(10, mode="undirected"))) ## First three eigenvalues of the adjacency matrix of a graph ## We need the 'Matrix' package for this if (require(Matrix)) { set.seed(42) g <- sample_gnp(1000, 5/1000) M <- as_adj(g, sparse=TRUE) f2 <- function(x, extra=NULL) { cat("."); as.vector(M \%*\% x) } baev <- arpack(f2, sym=TRUE, options=list(n=vcount(g), nev=3, ncv=8, which="LM", maxiter=2000)) } } \references{ D.C. Sorensen, Implicit Application of Polynomial Filters in a k-Step Arnoldi Method. \emph{SIAM J. Matr. Anal. Apps.}, 13 (1992), pp 357-385. R.B. Lehoucq, Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration. \emph{Rice University Technical Report} TR95-13, Department of Computational and Applied Mathematics. B.N. Parlett & Y. Saad, Complex Shift and Invert Strategies for Real Matrices. \emph{Linear Algebra and its Applications}, vol 88/89, pp 575-595, (1987). } \seealso{ \code{\link{eigen_centrality}}, \code{\link{page_rank}}, \code{\link{hub_score}}, \code{\link{cluster_leading_eigen}} are some of the functions in igraph which use ARPACK. The ARPACK homepage is at \url{http://www.caam.rice.edu/software/ARPACK/}. } \author{ Rich Lehoucq, Kristi Maschhoff, Danny Sorensen, Chao Yang for ARPACK, Gabor Csardi \email{csardi.gabor@gmail.com} for the R interface. } \keyword{datasets} \keyword{graphs} igraph/man/graph_from_edgelist.Rd0000644000175100001440000000301013430770475016614 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/data_frame.R \name{graph_from_edgelist} \alias{graph_from_edgelist} \alias{graph.edgelist} \alias{from_edgelist} \title{Create a graph from an edge list matrix} \usage{ graph_from_edgelist(el, directed = TRUE) from_edgelist(...) } \arguments{ \item{el}{The edge list, a two column matrix, character or numeric.} \item{directed}{Whether to create a directed graph.} \item{...}{Passed to \code{graph_from_edgelist}.} } \value{ An igraph graph. } \description{ \code{graph_from_edgelist} creates a graph from an edge list. Its argument is a two-column matrix, each row defines one edge. If it is a numeric matrix then its elements are interpreted as vertex ids. If it is a character matrix then it is interpreted as symbolic vertex names and a vertex id will be assigned to each name, and also a \code{name} vertex attribute will be added. } \examples{ el <- matrix( c("foo", "bar", "bar", "foobar"), nc = 2, byrow = TRUE) graph_from_edgelist(el) # Create a ring by hand graph_from_edgelist(cbind(1:10, c(2:10, 1))) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{Edge list} \concept{determimistic constructors} igraph/man/is_weighted.Rd0000644000175100001440000000213213430770475015107 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{is_weighted} \alias{is_weighted} \alias{is.weighted} \title{Weighted graphs} \usage{ is_weighted(graph) } \arguments{ \item{graph}{The input graph.} } \value{ A logical scalar. } \description{ In weighted graphs, a real number is assigned to each (directed or undirected) edge. } \details{ In igraph edge weights are represented via an edge attribute, called \sQuote{weight}. The \code{is_weighted} function only checks that such an attribute exists. (It does not even checks that it is a numeric edge attribute.) Edge weights are used for different purposes by the different functions. E.g. shortest path functions use it as the cost of the path; community finding methods use it as the strength of the relationship between two vertices, etc. Check the manual pages of the functions working with weighted graphs for details. } \examples{ g <- make_ring(10) shortest_paths(g, 8, 2) E(g)$weight <- seq_len(ecount(g)) shortest_paths(g, 8, 2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/igraph-vs-indexing.Rd0000644000175100001440000001220713430770475016323 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-vs-indexing} \alias{igraph-vs-indexing} \alias{[.igraph.vs} \title{Indexing vertex sequences} \usage{ \method{[}{igraph.vs}(x, ..., na_ok = FALSE) } \arguments{ \item{x}{A vertex sequence.} \item{...}{Indices, see details below.} \item{na_ok}{Whether it is OK to have \code{NA}s in the vertex sequence.} } \value{ Another vertex sequence, referring to the same graph. } \description{ Vertex sequences can be indexed very much like a plain numeric R vector, with some extras. } \details{ Vertex sequences can be indexed using both the single bracket and the double bracket operators, and they both work the same way. The only difference between them is that the double bracket operator marks the result for printing vertex attributes. } \section{Multiple indices}{ When using multiple indices within the bracket, all of them are evaluated independently, and then the results are concatenated using the \code{c()} function (except for the \code{na_ok} argument, which is special an must be named. E.g. \code{V(g)[1, 2, .nei(1)]} is equivalent to \code{c(V(g)[1], V(g)[2], V(g)[.nei(1)])}. } \section{Index types}{ Vertex sequences can be indexed with positive numeric vectors, negative numeric vectors, logical vectors, character vectors: \itemize{ \item When indexed with positive numeric vectors, the vertices at the given positions in the sequence are selected. This is the same as indexing a regular R atomic vector with positive numeric vectors. \item When indexed with negative numeric vectors, the vertices at the given positions in the sequence are omitted. Again, this is the same as indexing a regular R atomic vector. \item When indexed with a logical vector, the lengths of the vertex sequence and the index must match, and the vertices for which the index is \code{TRUE} are selected. \item Named graphs can be indexed with character vectors, to select vertices with the given names. } } \section{Vertex attributes}{ When indexing vertex sequences, vertex attributes can be refered to simply by using their names. E.g. if a graph has a \code{name} vertex attribute, then \code{V(g)[name == "foo"]} is equivalent to \code{V(g)[V(g)$name == "foo"]}. See examples below. } \section{Special functions}{ There are some special igraph functions that can be used only in expressions indexing vertex sequences: \describe{ \item{\code{.nei}}{takes a vertex sequence as its argument and selects neighbors of these vertices. An optional \code{mode} argument can be used to select successors (\code{mode="out"}), or precedessors (\code{mode="in"}) in directed graphs.} \item{\code{.inc}}{Takes an edge sequence as an argument, and selects vertices that have at least one incident edge in this edge sequence.} \item{\code{.from}}{Similar to \code{.inc}, but only considers the tails of the edges.} \item{\code{.to}}{Similar to \code{.inc}, but only considers the heads of the edges.} \item{\code{.innei}, \code{.outnei}}{\code{.innei(v)} is a shorthand for \code{.nei(v, mode = "in")}, and \code{.outnei(v)} is a shorthand for \code{.nei(v, mode = "out")}. } } Note that multiple special functions can be used together, or with regular indices, and then their results are concatenated. See more examples below. } \examples{ # ----------------------------------------------------------------- # Setting attributes for subsets of vertices largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_(gnp(100, 2/100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "green" V(g)[giant_v]$color <- "red" plot(g) # ----------------------------------------------------------------- # nei() special function g <- graph( c(1,2, 2,3, 2,4, 4,2) ) V(g)[ .nei( c(2,4) ) ] V(g)[ .nei( c(2,4), "in") ] V(g)[ .nei( c(2,4), "out") ] # ----------------------------------------------------------------- # The same with vertex names g <- graph(~ A -+ B, B -+ C:D, D -+ B) V(g)[ .nei( c('B', 'D') ) ] V(g)[ .nei( c('B', 'D'), "in" ) ] V(g)[ .nei( c('B', 'D'), "out" ) ] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} \concept{vertex and edge sequences} igraph/man/similarity.Rd0000644000175100001440000000513013430770476015004 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/similarity.R \name{similarity} \alias{similarity} \alias{similarity.jaccard} \alias{similarity.dice} \alias{similarity.invlogweighted} \title{Similarity measures of two vertices} \usage{ similarity(graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE, method = c("jaccard", "dice", "invlogweighted")) } \arguments{ \item{graph}{The input graph.} \item{vids}{The vertex ids for which the similarity is calculated.} \item{mode}{The type of neighboring vertices to use for the calculation, possible values: \sQuote{\code{out}}, \sQuote{\code{in}}, \sQuote{\code{all}}.} \item{loops}{Whether to include vertices themselves in the neighbor sets.} \item{method}{The method to use.} } \value{ A \code{length(vids)} by \code{length(vids)} numeric matrix containing the similarity scores. This argument is ignored by the \code{invlogweighted} method. } \description{ These functions calculates similarity scores for vertices based on their connection patterns. } \details{ The Jaccard similarity coefficient of two vertices is the number of common neighbors divided by the number of vertices that are neighbors of at least one of the two vertices being considered. The \code{jaccard} method calculates the pairwise Jaccard similarities for some (or all) of the vertices. The Dice similarity coefficient of two vertices is twice the number of common neighbors divided by the sum of the degrees of the vertices. Methof \code{dice} calculates the pairwise Dice similarities for some (or all) of the vertices. The inverse log-weighted similarity of two vertices is the number of their common neighbors, weighted by the inverse logarithm of their degrees. It is based on the assumption that two vertices should be considered more similar if they share a low-degree common neighbor, since high-degree common neighbors are more likely to appear even by pure chance. Isolated vertices will have zero similarity to any other vertex. Self-similarities are not calculated. See the following paper for more details: Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web. Social Networks, 25(3):211-230, 2003. } \examples{ g <- make_ring(5) similarity(g, method = "dice") similarity(g, method = "jaccard") } \references{ Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web. \emph{Social Networks}, 25(3):211-230, 2003. } \seealso{ \code{\link{cocitation}} and \code{\link{bibcoupling}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} for the manual page. } \keyword{graphs} igraph/man/cohesive_blocks.Rd0000644000175100001440000002544713430770475015774 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cohesive.blocks.R \name{cohesive_blocks} \alias{cohesive_blocks} \alias{cohesive.blocks} \alias{cohesiveBlocks} \alias{blocks} \alias{graphs_from_cohesive_blocks} \alias{blockGraphs} \alias{hierarchy} \alias{parent} \alias{plotHierarchy} \alias{export_pajek} \alias{maxcohesion} \alias{plot.cohesiveBlocks} \alias{summary.cohesiveBlocks} \alias{length.cohesiveBlocks} \alias{print.cohesiveBlocks} \alias{plot_hierarchy} \alias{max_cohesion} \alias{exportPajek} \alias{cohesion.cohesiveBlocks} \title{Calculate Cohesive Blocks} \usage{ cohesive_blocks(graph, labels = TRUE) \method{length}{cohesiveBlocks}(x) blocks(blocks) graphs_from_cohesive_blocks(blocks, graph) \method{cohesion}{cohesiveBlocks}(x, ...) hierarchy(blocks) parent(blocks) \method{print}{cohesiveBlocks}(x, ...) \method{summary}{cohesiveBlocks}(object, ...) \method{plot}{cohesiveBlocks}(x, y, colbar = rainbow(max(cohesion(x)) + 1), col = colbar[max_cohesion(x) + 1], mark.groups = blocks(x)[-1], ...) plot_hierarchy(blocks, layout = layout_as_tree(hierarchy(blocks), root = 1), ...) export_pajek(blocks, graph, file, project.file = TRUE) max_cohesion(blocks) } \arguments{ \item{graph}{For \code{cohesive_blocks} a graph object of class \code{igraph}. It must be undirected and simple. (See \code{\link{is_simple}}.) For \code{graphs_from_cohesive_blocks} and \code{export_pajek} the same graph must be supplied whose cohesive block structure is given in the \code{blocks} argument.} \item{labels}{Logical scalar, whether to add the vertex labels to the result object. These labels can be then used when reporting and plotting the cohesive blocks.} \item{blocks, x, object}{A \code{cohesiveBlocks} object, created with the \code{cohesive_blocks} function.} \item{\dots}{Additional arguments. \code{plot_hierarchy} and \code{plot} pass them to \code{plot.igraph}. \code{print} and \code{summary} ignore them.} \item{y}{The graph whose cohesive blocks are supplied in the \code{x} argument.} \item{colbar}{Color bar for the vertex colors. Its length should be at least \eqn{m+1}, where \eqn{m} is the maximum cohesion in the graph. Alternatively, the vertex colors can also be directly specified via the \code{col} argument.} \item{col}{A vector of vertex colors, in any of the usual formats. (Symbolic color names (e.g. \sQuote{red}, \sQuote{blue}, etc.) , RGB colors (e.g. \sQuote{#FF9900FF}), integer numbers referring to the current palette. By default the given \code{colbar} is used and vertices with the same maximal cohesion will have the same color.} \item{mark.groups}{A list of vertex sets to mark on the plot by circling them. By default all cohesive blocks are marked, except the one corresponding to the all vertices.} \item{layout}{The layout of a plot, it is simply passed on to \code{plot.igraph}, see the possible formats there. By default the Reingold-Tilford layout generator is used.} \item{file}{Defines the file (or connection) the Pajek file is written to. If the \code{project.file} argument is \code{TRUE}, then it can be a filename (with extension), a file object, or in general any king of connection object. The file/connection will be opened if it wasn't already. If the \code{project.file} argument is \code{FALSE}, then several files are created and \code{file} must be a character scalar containing the base name of the files, without extension. (But it can contain the path to the files.) See also details below.} \item{project.file}{Logical scalar, whether to create a single Pajek project file containing all the data, or to create separated files for each item. See details below.} } \value{ \code{cohesive_blocks} returns a \code{cohesiveBlocks} object. \code{blocks} returns a list of numeric vectors, containing vertex ids. \code{graphs_from_cohesive_blocks} returns a list of igraph graphs, corresponding to the cohesive blocks. \code{cohesion} returns a numeric vector, the cohesion of each block. \code{hierarchy} returns an igraph graph, the representation of the cohesive block hierarchy. \code{parent} returns a numeric vector giving the parent block of each cohesive block, in the block hierarchy. The block at the root of the hierarchy has no parent and \code{0} is returned for it. \code{plot_hierarchy}, \code{plot} and \code{export_pajek} return \code{NULL}, invisibly. \code{max_cohesion} returns a numeric vector with one entry for each vertex, giving the cohesion of its most cohesive block. \code{print} and \code{summary} return the \code{cohesiveBlocks} object itself, invisibly. \code{length} returns a numeric scalar, the number of blocks. } \description{ Calculates cohesive blocks for objects of class \code{igraph}. } \details{ Cohesive blocking is a method of determining hierarchical subsets of graph vertices based on their structural cohesion (or vertex connectivity). For a given graph \eqn{G}, a subset of its vertices \eqn{S\subset V(G)}{S} is said to be maximally \eqn{k}-cohesive if there is no superset of \eqn{S} with vertex connectivity greater than or equal to \eqn{k}. Cohesive blocking is a process through which, given a \eqn{k}-cohesive set of vertices, maximally \eqn{l}-cohesive subsets are recursively identified with \eqn{l>k}. Thus a hiearchy of vertex subsets is found, whith the entire graph \eqn{G} at its root. The function \code{cohesive_blocks} implements cohesive blocking. It returns a \code{cohesiveBlocks} object. \code{cohesiveBlocks} should be handled as an opaque class, i.e. its internal structure should not be accessed directly, but through the functions listed here. The function \code{length} can be used on \code{cohesiveBlocks} objects and it gives the number of blocks. The function \code{blocks} returns the actual blocks stored in the \code{cohesiveBlocks} object. They are returned in a list of numeric vectors, each containing vertex ids. The function \code{graphs_from_cohesive_blocks} is similar, but returns the blocks as (induced) subgraphs of the input graph. The various (graph, vertex and edge) attributes are kept in the subgraph. The function \code{cohesion} returns a numeric vector, the cohesion of the different blocks. The order of the blocks is the same as for the \code{blocks} and \code{graphs_from_cohesive_blocks} functions. The block hierarchy can be queried using the \code{hierarchy} function. It returns an igraph graph, its vertex ids are ordered according the order of the blocks in the \code{blocks} and \code{graphs_from_cohesive_blocks}, \code{cohesion}, etc. functions. \code{parent} gives the parent vertex of each block, in the block hierarchy, for the root vertex it gives 0. \code{plot_hierarchy} plots the hierarchy tree of the cohesive blocks on the active graphics device, by calling \code{igraph.plot}. The \code{export_pajek} function can be used to export the graph and its cohesive blocks in Pajek format. It can either export a single Pajek project file with all the information, or a set of files, depending on its \code{project.file} argument. If \code{project.file} is \code{TRUE}, then the following information is written to the file (or connection) given in the \code{file} argument: (1) the input graph, together with its attributes, see \code{\link{write_graph}} for details; (2) the hierarchy graph; and (3) one binary partition for each cohesive block. If \code{project.file} is \code{FALSE}, then the \code{file} argument must be a character scalar and it is used as the base name for the generated files. If \code{file} is \sQuote{basename}, then the following files are created: (1) \sQuote{basename.net} for the original graph; (2) \sQuote{basename_hierarchy.net} for the hierarchy graph; (3) \sQuote{basename_block_x.net} for each cohesive block, where \sQuote{x} is the number of the block, starting with one. \code{max_cohesion} returns the maximal cohesion of each vertex, i.e. the cohesion of the most cohesive block of the vertex. The generic function \code{summary} works on \code{cohesiveBlocks} objects and it prints a one line summary to the terminal. The generic function \code{print} is also defined on \code{cohesiveBlocks} objects and it is invoked automatically if the name of the \code{cohesiveBlocks} object is typed in. It produces an output like this: \preformatted{ Cohesive block structure: B-1 c 1, n 23 '- B-2 c 2, n 14 oooooooo.. .o......oo ooo '- B-4 c 5, n 7 ooooooo... .......... ... '- B-3 c 2, n 10 ......o.oo o.oooooo.. ... '- B-5 c 3, n 4 ......o.oo o......... ... } The left part shows the block structure, in this case for five blocks. The first block always corresponds to the whole graph, even if its cohesion is zero. Then cohesion of the block and the number of vertices in the block are shown. The last part is only printed if the display is wide enough and shows the vertices in the blocks, ordered by vertex ids. \sQuote{o} means that the vertex is included, a dot means that it is not, and the vertices are shown in groups of ten. The generic function \code{plot} plots the graph, showing one or more cohesive blocks in it. } \examples{ ## The graph from the Moody-White paper mw <- graph_from_literal(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, 21-22:23, 22-23) mwBlocks <- cohesive_blocks(mw) # Inspect block membership and cohesion mwBlocks blocks(mwBlocks) cohesion(mwBlocks) # Save results in a Pajek file \dontrun{ export_pajek(mwBlocks, mw, file="/tmp/mwBlocks.paj") } # Plot the results plot(mwBlocks, mw) ## The science camp network camp <- graph_from_literal(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael) campBlocks <- cohesive_blocks(camp) campBlocks plot(campBlocks, camp, vertex.label=V(camp)$name, margin=-0.2, vertex.shape="rectangle", vertex.size=24, vertex.size2=8, mark.border=1, colbar=c(NA, NA,"cyan","orange") ) } \references{ J. Moody and D. R. White. Structural cohesion and embeddedness: A hierarchical concept of social groups. \emph{American Sociological Review}, 68(1):103--127, Feb 2003. } \seealso{ \code{\link{cohesion}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} for the current implementation, Peter McMahan (\url{http://home.uchicago.edu/~mcmahan/}) wrote the first version in R. } \keyword{graphs} igraph/man/compose.Rd0000644000175100001440000000527613430770475014275 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{compose} \alias{compose} \alias{graph.compose} \alias{\%c\%} \title{Compose two graphs as binary relations} \usage{ compose(g1, g2, byname = "auto") } \arguments{ \item{g1}{The first input graph.} \item{g2}{The second input graph.} \item{byname}{A logical scalar, or the character scalar \code{auto}. Whether to perform the operation based on symbolic vertex names. If it is \code{auto}, that means \code{TRUE} if both graphs are named and \code{FALSE} otherwise. A warning is generated if \code{auto} and one graph, but not both graphs are named.} } \value{ A new graph object. } \description{ Relational composition of two graph. } \details{ \code{compose} creates the relational composition of two graphs. The new graph will contain an (a,b) edge only if there is a vertex c, such that edge (a,c) is included in the first graph and (c,b) is included in the second graph. The corresponding operator is \%c\%. The function gives an error if one of the input graphs is directed and the other is undirected. If the \code{byname} argument is \code{TRUE} (or \code{auto} and the graphs are all named), then the operation is performed based on symbolic vertex names. Otherwise numeric vertex ids are used. \code{compose} keeps the attributes of both graphs. All graph, vertex and edge attributes are copied to the result. If an attribute is present in multiple graphs and would result a name clash, then this attribute is renamed by adding suffixes: _1, _2, etc. The \code{name} vertex attribute is treated specially if the operation is performed based on symbolic vertex names. In this case \code{name} must be present in both graphs, and it is not renamed in the result graph. Note that an edge in the result graph corresponds to two edges in the input, one in the first graph, one in the second. This mapping is not injective and several edges in the result might correspond to the same edge in the first (and/or the second) graph. The edge attributes in the result graph are updated accordingly. Also note that the function may generate multigraphs, if there are more than one way to find edges (a,b) in g1 and (b,c) in g2 for an edge (a,c) in the result. See \code{\link{simplify}} if you want to get rid of the multiple edges. The function may create loop edges, if edges (a,b) and (b,a) are present in g1 and g2, respectively, then (a,a) is included in the result. See \code{\link{simplify}} if you want to get rid of the self-loops. } \examples{ g1 <- make_ring(10) g2 <- make_star(10, mode="undirected") gc <- compose(g1, g2) print_all(gc) print_all(simplify(gc)) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/disjoint_union.Rd0000644000175100001440000000325313430770475015654 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{disjoint_union} \alias{disjoint_union} \alias{graph.disjoint.union} \alias{\%du\%} \title{Disjoint union of graphs} \usage{ disjoint_union(...) x \%du\% y } \arguments{ \item{\dots}{Graph objects or lists of graph objects.} \item{x, y}{Graph objects.} } \value{ A new graph object. } \description{ The union of two or more graphs are created. The graphs are assumed to have disjoint vertex sets. } \details{ \code{disjoint_union} creates a union of two or more disjoint graphs. Thus first the vertices in the second, third, etc. graphs are relabeled to have completely disjoint graphs. Then a simple union is created. This function can also be used via the \%du\% operator. \code{graph.disjont.union} handles graph, vertex and edge attributes. In particular, it merges vertex and edge attributes using the basic \code{c()} function. For graphs that lack some vertex/edge attribute, the corresponding values in the new graph are set to \code{NA}. Graph attributes are simply copied to the result. If this would result a name clash, then they are renamed by adding suffixes: _1, _2, etc. Note that if both graphs have vertex names (ie. a \code{name} vertex attribute), then the concatenated vertex names might be non-unique in the result. A warning is given if this happens. An error is generated if some input graphs are directed and others are undirected. } \examples{ ## A star and a ring g1 <- make_star(10, mode="undirected") V(g1)$name <- letters[1:10] g2 <- make_ring(10) V(g2)$name <- letters[11:20] print_all(g1 \%du\% g2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/igraph_test.Rd0000644000175100001440000000125513430770476015133 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/test.R \name{igraph_test} \alias{igraph_test} \alias{igraphtest} \title{Run package tests} \usage{ igraph_test() } \value{ Whatever is returned by \code{test_dir} from the \code{testthat} package. } \description{ Runs all package tests. } \details{ The \code{testthat} package is needed to run all tests. The location tests themselves can be extracted from the package via \code{system.file("tests", package="igraph")}. This function simply calls the \code{test_dir} function from the \code{testthat} package on the test directory. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/radius.Rd0000644000175100001440000000276213430770475014114 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R \name{radius} \alias{radius} \title{Radius of a graph} \usage{ radius(graph, mode = c("all", "out", "in", "total")) } \arguments{ \item{graph}{The input graph, it can be directed or undirected.} \item{mode}{Character constant, gives whether the shortest paths to or from the given vertices should be calculated for directed graphs. If \code{out} then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} it will be considered. If \code{all}, the default, then the corresponding undirected graph will be used, edge directions will be ignored. This argument is ignored for undirected graphs.} } \value{ A numeric scalar, the radius of the graph. } \description{ The eccentricity of a vertex is its shortest path distance from the farthest other node in the graph. The smallest eccentricity in a graph is called its radius } \details{ The eccentricity of a vertex is calculated by measuring the shortest distance from (or to) the vertex, to (or from) all vertices in the graph, and taking the maximum. This implementation ignores vertex pairs that are in different components. Isolate vertices have eccentricity zero. } \examples{ g <- make_star(10, mode="undirected") eccentricity(g) radius(g) } \references{ Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, 1994. } \seealso{ \code{\link{eccentricity}} for the underlying calculations, code{\link{distances}} for general shortest path calculations. } igraph/man/bipartite_projection.Rd0000644000175100001440000000660713430770475017046 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/bipartite.R \name{bipartite_projection} \alias{bipartite_projection} \alias{bipartite.projection} \alias{bipartite.projection.size} \alias{bipartite_projection_size} \title{Project a bipartite graph} \usage{ bipartite_projection(graph, types = NULL, multiplicity = TRUE, probe1 = NULL, which = c("both", "true", "false"), remove.type = TRUE) } \arguments{ \item{graph}{The input graph. It can be directed, but edge directions are ignored during the computation.} \item{types}{An optional vertex type vector to use instead of the \sQuote{\code{type}} vertex attribute. You must supply this argument if the graph has no \sQuote{\code{type}} vertex attribute.} \item{multiplicity}{If \code{TRUE}, then igraph keeps the multiplicity of the edges as an edge attribute called \sQuote{weight}. E.g. if there is an A-C-B and also an A-D-B triple in the bipartite graph (but no more X, such that A-X-B is also in the graph), then the multiplicity of the A-B edge in the projection will be 2.} \item{probe1}{This argument can be used to specify the order of the projections in the resulting list. If given, then it is considered as a vertex id (or a symbolic vertex name); the projection containing this vertex will be the first one in the result list. This argument is ignored if only one projection is requested in argument \code{which}.} \item{which}{A character scalar to specify which projection(s) to calculate. The default is to calculate both.} \item{remove.type}{Logical scalar, whether to remove the \code{type} vertex attribute from the projections. This makes sense because these graphs are not bipartite any more. However if you want to combine them with each other (or other bipartite graphs), then it is worth keeping this attribute. By default it will be removed.} } \value{ A list of two undirected graphs. See details above. } \description{ A bipartite graph is projected into two one-mode networks } \details{ Bipartite graphs have a \code{type} vertex attribute in igraph, this is boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} for vertices of the second kind. \code{bipartite_projection_size} calculates the number of vertices and edges in the two projections of the bipartite graphs, without calculating the projections themselves. This is useful to check how much memory the projections would need if you have a large bipartite graph. \code{bipartite_projection} calculates the actual projections. You can use the \code{probe1} argument to specify the order of the projections in the result. By default vertex type \code{FALSE} is the first and \code{TRUE} is the second. \code{bipartite_projection} keeps vertex attributes. } \examples{ ## Projection of a full bipartite graph is a full graph g <- make_full_bipartite_graph(10,5) proj <- bipartite_projection(g) graph.isomorphic(proj[[1]], make_full_graph(10)) graph.isomorphic(proj[[2]], make_full_graph(5)) ## The projection keeps the vertex attributes M <- matrix(0, nr=5, nc=3) rownames(M) <- c("Alice", "Bob", "Cecil", "Dan", "Ethel") colnames(M) <- c("Party", "Skiing", "Badminton") M[] <- sample(0:1, length(M), replace=TRUE) M g2 <- graph_from_incidence_matrix(M) g2$name <- "Event network" proj2 <- bipartite_projection(g2) print(proj2[[1]], g=TRUE, e=TRUE) print(proj2[[2]], g=TRUE, e=TRUE) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/hrg-methods.Rd0000644000175100001440000000301713430770475015040 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{hrg-methods} \alias{hrg-methods} \title{Hierarchical random graphs} \description{ Fitting and sampling hierarchical random graph models. } \details{ A hierarchical random graph is an ensemble of undirected graphs with \eqn{n} vertices. It is defined via a binary tree with \eqn{n} leaf and \eqn{n-1} internal vertices, where the internal vertices are labeled with probabilities. The probability that two vertices are connected in the random graph is given by the probability label at their closest common ancestor. Please see references below for more about hierarchical random graphs. igraph contains functions for fitting HRG models to a given network (\code{fit_hrg}, for generating networks from a given HRG ensemble (\code{sample_hrg}), converting an igraph graph to a HRG and back (\code{hrg}, \code{hrg_tree}), for calculating a consensus tree from a set of sampled HRGs (\code{consensus_tree}) and for predicting missing edges in a network based on its HRG models (\code{predict_edges}). The igraph HRG implementation is heavily based on the code published by Aaron Clauset, at his website (not functional any more). } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/as_graphnel.Rd0000644000175100001440000000256513430770475015111 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_graphnel} \alias{as_graphnel} \alias{igraph.to.graphNEL} \title{Convert igraph graphs to graphNEL objects from the graph package} \usage{ as_graphnel(graph) } \arguments{ \item{graph}{An igraph graph object.} } \value{ \code{as_graphnel} returns a graphNEL graph object. } \description{ The graphNEL class is defined in the \code{graph} package, it is another way to represent graphs. These functions are provided to convert between the igraph and the graphNEL objects. } \details{ \code{as_graphnel} converts an igraph graph to a graphNEL graph. It converts all graph/vertex/edge attributes. If the igraph graph has a vertex attribute \sQuote{\code{name}}, then it will be used to assign vertex names in the graphNEL graph. Otherwise numeric igraph vertex ids will be used for this purpose. } \examples{ ## Undirected \dontrun{ g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode="in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4 } } \seealso{ \code{\link{graph_from_graphnel}} for the other direction, \code{\link{as_adj}}, \code{\link{graph_from_adjacency_matrix}}, \code{\link{as_adj_list}} and \code{\link{graph.adjlist}} for other graph representations. } igraph/man/get.edge.ids.Rd0000644000175100001440000000460113430770475015057 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{get.edge.ids} \alias{get.edge.ids} \title{Find the edge ids based on the incident vertices of the edges} \usage{ get.edge.ids(graph, vp, directed = TRUE, error = FALSE, multi = FALSE) } \arguments{ \item{graph}{The input graph.} \item{vp}{The indicent vertices, given as vertex ids or symbolic vertex names. They are interpreted pairwise, i.e. the first and second are used for the first edge, the third and fourth for the second, etc.} \item{directed}{Logical scalar, whether to consider edge directions in directed graphs. This argument is ignored for undirected graphs.} \item{error}{Logical scalar, whether to report an error if an edge is not found in the graph. If \code{FALSE}, then no error is reported, and zero is returned for the non-existant edge(s).} \item{multi}{Logical scalar, whether to handle multiple edges properly. If \code{FALSE}, and a pair of vertices are given twice (or more), then always the same edge id is reported back for them. If \code{TRUE}, then the edge ids of multiple edges are correctly reported.} } \value{ A numeric vector of edge ids, one for each pair of input vertices. If there is no edge in the input graph for a given pair of vertices, then zero is reported. (If the \code{error} argument is \code{FALSE}.) } \description{ Find the edges in an igraph graph that have the specified end points. This function handles multi-graph (graphs with multiple edges) and can consider or ignore the edge directions in directed graphs. } \details{ igraph vertex ids are natural numbers, starting from one, up to the number of vertices in the graph. Similarly, edges are also numbered from one, up to the number of edges. This function allows finding the edges of the graph, via their incident vertices. } \examples{ g <- make_ring(10) ei <- get.edge.ids(g, c(1,2, 4,5)) E(g)[ei] ## non-existant edge get.edge.ids(g, c(2,1, 1,4, 5,4)) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{structural queries} igraph/man/isomorphisms.Rd0000644000175100001440000000210313430770476015347 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{isomorphisms} \alias{isomorphisms} \alias{graph.get.isomorphisms.vf2} \title{Calculate all isomorphic mappings between the vertices of two graphs} \usage{ isomorphisms(graph1, graph2, method = "vf2", ...) } \arguments{ \item{graph1}{The first graph.} \item{graph2}{The second graph.} \item{method}{Currently only \sQuote{vf2} is supported, see \code{\link{isomorphic}} for details about it and extra arguments.} \item{...}{Extra arguments, passed to the various methods.} } \value{ A list of vertex sequences, corresponding to all mappings from the first graph to the second. } \description{ Calculate all isomorphic mappings between the vertices of two graphs } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/erdos.renyi.game.Rd0000644000175100001440000000364013430770475015772 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{erdos.renyi.game} \alias{erdos.renyi.game} \alias{random.graph.game} \title{Generate random graphs according to the Erdos-Renyi model} \usage{ erdos.renyi.game(n, p.or.m, type = c("gnp", "gnm"), directed = FALSE, loops = FALSE, ...) } \arguments{ \item{n}{The number of vertices in the graph.} \item{p.or.m}{Either the probability for drawing an edge between two arbitrary vertices (G(n,p) graph), or the number of edges in the graph (for G(n,m) graphs).} \item{type}{The type of the random graph to create, either \code{gnp} (G(n,p) graph) or \code{gnm} (G(n,m) graph).} \item{directed}{Logical, whether the graph will be directed, defaults to FALSE.} \item{loops}{Logical, whether to add loop edges, defaults to FALSE.} \item{\dots}{Additional arguments, ignored.} } \value{ A graph object. } \description{ This model is very simple, every possible edge is created with the same constant probability. } \details{ In G(n,p) graphs, the graph has \sQuote{n} vertices and for each edge the probability that it is present in the graph is \sQuote{p}. In G(n,m) graphs, the graph has \sQuote{n} vertices and \sQuote{m} edges, and the \sQuote{m} edges are chosen uniformly randomly from the set of all possible edges. This set includes loop edges as well if the \code{loops} parameter is TRUE. \code{random.graph.game} is an alias to this function. } \section{Deprecated}{ Since igraph version 0.8.0, both \code{erdos.renyi.game} and \code{random.graph.game} are deprecated, and \code{\link{sample_gnp}} and \code{\link{sample_gnm}} should be used instead. } \examples{ g <- erdos.renyi.game(1000, 1/1000) degree_distribution(g) } \references{ Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes Mathematicae} 6, 290--297 (1959). } \seealso{ \code{\link{sample_pa}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/centr_degree_tmax.Rd0000644000175100001440000000267513430770475016307 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_degree_tmax} \alias{centr_degree_tmax} \alias{centralization.degree.tmax} \title{Theoretical maximum for degree centralization} \usage{ centr_degree_tmax(graph = NULL, nodes = 0, mode = c("all", "out", "in", "total"), loops = FALSE) } \arguments{ \item{graph}{The input graph. It can also be \code{NULL}, if \code{nodes}, \code{mode} and \code{loops} are all given.} \item{nodes}{The number of vertices. This is ignored if the graph is given.} \item{mode}{This is the same as the \code{mode} argument of \code{degree}.} \item{loops}{Logical scalar, whether to consider loops edges when calculating the degree.} } \value{ Real scalar, the theoratical maximum (unnormalized) graph degree centrality score for graphs with given order and other parameters. } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g, normalized = FALSE)$centralization \%>\% `/`(centr_degree_tmax(g)) centr_degree(g, normalized = TRUE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/indent_print.Rd0000644000175100001440000000075713430770475015324 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/printr.R \name{indent_print} \alias{indent_print} \title{Indent a printout} \usage{ indent_print(..., .indent = " ", .printer = print) } \arguments{ \item{...}{Passed to the printing function.} \item{.indent}{Character scalar, indent the printout with this.} \item{.printer}{The printing function, defaults to \code{print}.} } \value{ The first element in \code{...}, invisibly. } \description{ Indent a printout } igraph/man/add_edges.Rd0000644000175100001440000000305513430770475014520 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{add_edges} \alias{add_edges} \alias{add.edges} \title{Add edges to a graph} \usage{ add_edges(graph, edges, ..., attr = list()) } \arguments{ \item{graph}{The input graph} \item{edges}{The edges to add, a vertex sequence with even number of vertices.} \item{...}{Additional arguments, they must be named, and they will be added as edge attributes, for the newly added edges. See also details below.} \item{attr}{A named list, its elements will be added as edge attributes, for the newly added edges. See also details below.} } \value{ The graph, with the edges (and attributes) added. } \description{ The new edges are given as a vertex sequence, e.g. internal numeric vertex ids, or vertex names. The first edge points from \code{edges[1]} to \code{edges[2]}, the second from \code{edges[3]} to \code{edges[4]}, etc. } \details{ If attributes are supplied, and they are not present in the graph, their values for the original edges of the graph are set to \code{NA}. } \examples{ g <- make_empty_graph(n = 5) \%>\% add_edges(c(1,2, 2,3, 3,4, 4,5)) \%>\% set_edge_attr("color", value = "red") \%>\% add_edges(c(5,1), color = "green") E(g)[[]] plot(g) } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/consensus_tree.Rd0000644000175100001440000000424113430770475015656 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{consensus_tree} \alias{consensus_tree} \alias{hrg.consensus} \title{Create a consensus tree from several hierarchical random graph models} \usage{ consensus_tree(graph, hrg = NULL, start = FALSE, num.samples = 10000) } \arguments{ \item{graph}{The graph the models were fitted to.} \item{hrg}{A hierarchical random graph model, in the form of an \code{igraphHRG} object. \code{consensus_tree} allows this to be \code{NULL} as well, then a HRG is fitted to the graph first, from a random starting point.} \item{start}{Logical, whether to start the fitting/sampling from the supplied \code{igraphHRG} object, or from a random starting point.} \item{num.samples}{Number of samples to use for consensus generation or missing edge prediction.} } \value{ \code{consensus_tree} returns a list of two objects. The first is an \code{igraphHRGConsensus} object, the second is an \code{igraphHRG} object. The \code{igraphHRGConsensus} object has the following members: \item{parents}{For each vertex, the id of its parent vertex is stored, or zero, if the vertex is the root vertex in the tree. The first n vertex ids (from 0) refer to the original vertices of the graph, the other ids refer to vertex groups.} \item{weights}{Numeric vector, counts the number of times a given tree split occured in the generated network samples, for each internal vertices. The order is the same as in the \code{parents} vector.} } \description{ \code{consensus_tree} creates a consensus tree from several fitted hierarchical random graph models, using phylogeny methods. If the \code{hrg} argument is given and \code{start} is set to \code{TRUE}, then it starts sampling from the given HRG. Otherwise it optimizes the HRG log-likelihood first, and then samples starting from the optimum. } \seealso{ Other hierarchical random graph functions: \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/graph_from_graphnel.Rd0000644000175100001440000000412513430770475016624 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{graph_from_graphnel} \alias{graph_from_graphnel} \alias{igraph.from.graphNEL} \title{Convert graphNEL objects from the graph package to igraph} \usage{ graph_from_graphnel(graphNEL, name = TRUE, weight = TRUE, unlist.attrs = TRUE) } \arguments{ \item{graphNEL}{The graphNEL graph.} \item{name}{Logical scalar, whether to add graphNEL vertex names as an igraph vertex attribute called \sQuote{\code{name}}.} \item{weight}{Logical scalar, whether to add graphNEL edge weights as an igraph edge attribute called \sQuote{\code{weight}}. (graphNEL graphs are always weighted.)} \item{unlist.attrs}{Logical scalar. graphNEL attribute query functions return the values of the attributes in R lists, if this argument is \code{TRUE} (the default) these will be converted to atomic vectors, whenever possible, before adding them to the igraph graph.} } \value{ \code{graph_from_graphnel} returns an igraph graph object. } \description{ The graphNEL class is defined in the \code{graph} package, it is another way to represent graphs. \code{graph_from_graphnel} takes a graphNEL graph and converts it to an igraph graph. It handles all graph/vertex/edge attributes. If the graphNEL graph has a vertex attribute called \sQuote{\code{name}} it will be used as igraph vertex attribute \sQuote{\code{name}} and the graphNEL vertex names will be ignored. } \details{ Because graphNEL graphs poorly support multiple edges, the edge attributes of the multiple edges are lost: they are all replaced by the attributes of the first of the multiple edges. } \examples{ \dontrun{ ## Undirected g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode="in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4 } } \seealso{ \code{\link{as_graphnel}} for the other direction, \code{\link{as_adj}}, \code{\link{graph_from_adjacency_matrix}}, \code{\link{as_adj_list}} and \code{\link{graph.adjlist}} for other graph representations. } igraph/man/print.igraphHRG.Rd0000644000175100001440000000517313430770475015572 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{print.igraphHRG} \alias{print.igraphHRG} \title{Print a hierarchical random graph model to the screen} \usage{ \method{print}{igraphHRG}(x, type = c("auto", "tree", "plain"), level = 3, ...) } \arguments{ \item{x}{\code{igraphHRG} object to print.} \item{type}{How to print the dendrogram, see details below.} \item{level}{The number of top levels to print from the dendrogram.} \item{...}{Additional arguments, not used currently.} } \value{ The hierarchical random graph model itself, invisibly. } \description{ \code{igraphHRG} objects can be printed to the screen in two forms: as a tree or as a list, depending on the \code{type} argument of the print function. By default the \code{auto} type is used, which selects \code{tree} for small graphs and \code{simple} (=list) for bigger ones. The \code{tree} format looks like this: \preformatted{Hierarchical random graph, at level 3: g1 p= 0 '- g15 p=0.33 1 '- g13 p=0.88 6 3 9 4 2 10 7 5 8 '- g8 p= 0.5 '- g16 p= 0.2 20 14 17 19 11 15 16 13 '- g5 p= 0 12 18 } This is a graph with 20 vertices, and the top three levels of the fitted hierarchical random graph are printed. The root node of the HRG is always vertex group #1 (\sQuote{\code{g1}} in the the printout). Vertex pairs in the left subtree of \code{g1} connect to vertices in the right subtree with probability zero, according to the fitted model. \code{g1} has two subgroups, \code{g15} and \code{g8}. \code{g15} has a subgroup of a single vertex (vertex 1), and another larger subgroup that contains vertices 6, 3, etc. on lower levels, etc. The \code{plain} printing is simpler and faster to produce, but less visual: \preformatted{Hierarchical random graph: g1 p=0.0 -> g12 g10 g2 p=1.0 -> 7 10 g3 p=1.0 -> g18 14 g4 p=1.0 -> g17 15 g5 p=0.4 -> g15 17 g6 p=0.0 -> 1 4 g7 p=1.0 -> 11 16 g8 p=0.1 -> g9 3 g9 p=0.3 -> g11 g16 g10 p=0.2 -> g4 g5 g11 p=1.0 -> g6 5 g12 p=0.8 -> g8 8 g13 p=0.0 -> g14 9 g14 p=1.0 -> 2 6 g15 p=0.2 -> g19 18 g16 p=1.0 -> g13 g2 g17 p=0.5 -> g7 13 g18 p=1.0 -> 12 19 g19 p=0.7 -> g3 20} It lists the two subgroups of each internal node, in as many columns as the screen width allows. } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/print.igraphHRGConsensus.Rd0000644000175100001440000000217713430770475017474 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{print.igraphHRGConsensus} \alias{print.igraphHRGConsensus} \title{Print a hierarchical random graph consensus tree to the screen} \usage{ \method{print}{igraphHRGConsensus}(x, ...) } \arguments{ \item{x}{\code{igraphHRGConsensus} object to print.} \item{...}{Ignored.} } \value{ The input object, invisibly, to allow method chaining. } \description{ Consensus dendrograms (\code{igraphHRGConsensus} objects) are printed simply by listing the children of each internal node of the dendrogram: \preformatted{HRG consensus tree: g1 -> 11 12 13 14 15 16 17 18 19 20 g2 -> 1 2 3 4 5 6 7 8 9 10 g3 -> g1 g2} The root of the dendrogram is \code{g3} (because it has no incoming edges), and it has two subgroups, \code{g1} and \code{g2}. } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/sample_forestfire.Rd0000644000175100001440000000573013430770475016334 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_forestfire} \alias{sample_forestfire} \alias{forest.fire.game} \title{Forest Fire Network Model} \usage{ sample_forestfire(nodes, fw.prob, bw.factor = 1, ambs = 1, directed = TRUE) } \arguments{ \item{nodes}{The number of vertices in the graph.} \item{fw.prob}{The forward burning probability, see details below.} \item{bw.factor}{The backward burning ratio. The backward burning probability is calculated as \code{bw.factor*fw.prob}.} \item{ambs}{The number of ambassador vertices.} \item{directed}{Logical scalar, whether to create a directed graph.} } \value{ A simple graph, possibly directed if the \code{directed} argument is \code{TRUE}. } \description{ This is a growing network model, which resembles of how the forest fire spreads by igniting trees close by. } \details{ The forest fire model intends to reproduce the following network characteristics, observed in real networks: \itemize{ \item Heavy-tailed in-degree distribution. \item Heavy-tailed out-degree distribution. \item Communities. \item Densification power-law. The network is densifying in time, according to a power-law rule. \item Shrinking diameter. The diameter of the network decreases in time. } The network is generated in the following way. One vertex is added at a time. This vertex connects to (cites) \code{ambs} vertices already present in the network, chosen uniformly random. Now, for each cited vertex \eqn{v} we do the following procedure: \enumerate{ \item We generate two random number, \eqn{x} and \eqn{y}, that are geometrically distributed with means \eqn{p/(1-p)} and \eqn{rp(1-rp)}. (\eqn{p} is \code{fw.prob}, \eqn{r} is \code{bw.factor}.) The new vertex cites \eqn{x} outgoing neighbors and \eqn{y} incoming neighbors of \eqn{v}, from those which are not yet cited by the new vertex. If there are less than \eqn{x} or \eqn{y} such vertices available then we cite all of them. \item The same procedure is applied to all the newly cited vertices. } } \note{ The version of the model in the published paper is incorrect in the sense that it cannot generate the kind of graphs the authors claim. A corrected version is available from \url{http://www.cs.cmu.edu/~jure/pubs/powergrowth-tkdd.pdf}, our implementation is based on this. } \examples{ g <- sample_forestfire(10000, fw.prob=0.37, bw.factor=0.32/0.37) dd1 <- degree_distribution(g, mode="in") dd2 <- degree_distribution(g, mode="out") plot(seq(along=dd1)-1, dd1, log="xy") points(seq(along=dd2)-1, dd2, col=2, pch=2) } \references{ Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs over time: densification laws, shrinking diameters and possible explanations. \emph{KDD '05: Proceeding of the eleventh ACM SIGKDD international conference on Knowledge discovery in data mining}, 177--187, 2005. } \seealso{ \code{\link{barabasi.game}} for the basic preferential attachment model. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/merge_coords.Rd0000644000175100001440000000604613430770475015274 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{merge_coords} \alias{merge_coords} \alias{layout.merge} \alias{piecewise.layout} \alias{layout_components} \title{Merging graph layouts} \usage{ merge_coords(graphs, layouts, method = "dla") layout_components(graph, layout = layout_with_kk, ...) } \arguments{ \item{graphs}{A list of graph objects.} \item{layouts}{A list of two-column matrices.} \item{method}{Character constant giving the method to use. Right now only \code{dla} is implemented.} \item{graph}{The input graph.} \item{layout}{A function object, the layout function to use.} \item{\dots}{Additional arguments to pass to the \code{layout} layout function.} } \value{ A matrix with two columns and as many lines as the total number of vertices in the graphs. } \description{ Place several graphs on the same layout } \details{ \code{merge_coords} takes a list of graphs and a list of coordinates and places the graphs in a common layout. The method to use is chosen via the \code{method} parameter, although right now only the \code{dla} method is implemented. The \code{dla} method covers the graph with circles. Then it sorts the graphs based on the number of vertices first and places the largest graph at the center of the layout. Then the other graphs are placed in decreasing order via a DLA (diffision limited aggregation) algorithm: the graph is placed randomly on a circle far away from the center and a random walk is conducted until the graph walks into the larger graphs already placed or walks too far from the center of the layout. The \code{layout_components} function disassembles the graph first into maximal connected components and calls the supplied \code{layout} function for each component separately. Finally it merges the layouts via calling \code{merge_coords}. } \examples{ # create 20 scale-free graphs and place them in a common layout graphs <- lapply(sample(5:20, 20, replace=TRUE), barabasi.game, directed=FALSE) layouts <- lapply(graphs, layout_with_kk) lay <- merge_coords(graphs, layouts) g <- disjoint_union(graphs) \dontrun{plot(g, layout=lay, vertex.size=3, labels=NA, edge.color="black")} } \seealso{ \code{\link{plot.igraph}}, \code{\link{tkplot}}, \code{\link{layout}}, \code{\link{disjoint_union}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/make_full_citation_graph.Rd0000644000175100001440000000231413430770475017630 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_full_citation_graph} \alias{make_full_citation_graph} \alias{graph.full.citation} \alias{full_citation_graph} \title{Create a complete (full) citation graph} \usage{ make_full_citation_graph(n, directed = TRUE) full_citation_graph(...) } \arguments{ \item{n}{The number of vertices.} \item{directed}{Whether to create a directed graph.} \item{...}{Passed to \code{make_full_citation_graph}.} } \value{ An igraph graph. } \description{ \code{make_full_citation_graph} creates a full citation graph. This is a directed graph, where every \code{i->j} edge is present if and only if \eqn{j\% set_vertex_attr("name", value = letters[1:10]) g2 <- g + path("a", "b", "c", "d") plot(g2) g3 <- g2 + path("e", "f", "g", weight=1:2, color="red") E(g3)[[]] g4 <- g3 + path(c("f", "c", "j", "d"), width=1:3, color="green") E(g4)[[]] } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_edges}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/sample_.Rd0000644000175100001440000000124413430770475014237 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{sample_} \alias{sample_} \title{Sample from a random graph model} \usage{ sample_(...) } \arguments{ \item{...}{Parameters, see details below.} } \description{ Generic function for sampling from network models. } \details{ TODO } \examples{ pref_matrix <- cbind(c(0.8, 0.1), c(0.1, 0.7)) blocky <- sample_(sbm(n = 20, pref.matrix = pref_matrix, block.sizes = c(10, 10))) blocky2 <- pref_matrix \%>\% sample_sbm(n = 20, block.sizes = c(10, 10)) ## Arguments are passed on from sample_ to sample_sbm blocky3 <- pref_matrix \%>\% sample_(sbm(), n = 20, block.sizes = c(10, 10)) } igraph/man/sample_fitness_pl.Rd0000644000175100001440000000655013430770475016333 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_fitness_pl} \alias{sample_fitness_pl} \alias{static.power.law.game} \title{Scale-free random graphs, from vertex fitness scores} \usage{ sample_fitness_pl(no.of.nodes, no.of.edges, exponent.out, exponent.in = -1, loops = FALSE, multiple = FALSE, finite.size.correction = TRUE) } \arguments{ \item{no.of.nodes}{The number of vertices in the generated graph.} \item{no.of.edges}{The number of edges in the generated graph.} \item{exponent.out}{Numeric scalar, the power law exponent of the degree distribution. For directed graphs, this specifies the exponent of the out-degree distribution. It must be greater than or equal to 2. If you pass \code{Inf} here, you will get back an Erdos-Renyi random network.} \item{exponent.in}{Numeric scalar. If negative, the generated graph will be undirected. If greater than or equal to 2, this argument specifies the exponent of the in-degree distribution. If non-negative but less than 2, an error will be generated.} \item{loops}{Logical scalar, whether to allow loop edges in the generated graph.} \item{multiple}{Logical scalar, whether to allow multiple edges in the generated graph.} \item{finite.size.correction}{Logical scalar, whether to use the proposed finite size correction of Cho et al., see references below.} } \value{ An igraph graph, directed or undirected. } \description{ This function generates a non-growing random graph with expected power-law degree distributions. } \details{ This game generates a directed or undirected random graph where the degrees of vertices follow power-law distributions with prescribed exponents. For directed graphs, the exponents of the in- and out-degree distributions may be specified separately. The game simply uses \code{\link{sample_fitness}} with appropriately constructed fitness vectors. In particular, the fitness of vertex \eqn{i} is \eqn{i^{-alpha}}{i^(-alpha)}, where \eqn{alpha = 1/(gamma-1)} and gamma is the exponent given in the arguments. To remove correlations between in- and out-degrees in case of directed graphs, the in-fitness vector will be shuffled after it has been set up and before \code{\link{sample_fitness}} is called. Note that significant finite size effects may be observed for exponents smaller than 3 in the original formulation of the game. This function provides an argument that lets you remove the finite size effects by assuming that the fitness of vertex \eqn{i} is \eqn{(i+i_0-1)^{-alpha}}{(i+i0-1)^(-alpha)} where \eqn{i_0}{i0} is a constant chosen appropriately to ensure that the maximum degree is less than the square root of the number of edges times the average degree; see the paper of Chung and Lu, and Cho et al for more details. } \examples{ g <- sample_fitness_pl(10000, 30000, 2.2, 2.3) \dontrun{plot(degree_distribution(g, cumulative=TRUE, mode="out"), log="xy")} } \references{ Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution in scale-free networks. \emph{Phys Rev Lett} 87(27):278701, 2001. Chung F and Lu L: Connected components in a random graph with given degree sequences. \emph{Annals of Combinatorics} 6, 125-145, 2002. Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions in scale-free networks under the Achlioptas process. \emph{Phys Rev Lett} 103:135702, 2009. } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/coreness.Rd0000644000175100001440000000301013430770476014432 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{coreness} \alias{coreness} \alias{graph.coreness} \title{K-core decomposition of graphs} \usage{ coreness(graph, mode = c("all", "out", "in")) } \arguments{ \item{graph}{The input graph, it can be directed or undirected} \item{mode}{The type of the core in directed graphs. Character constant, possible values: \code{in}: in-cores are computed, \code{out}: out-cores are computed, \code{all}: the corresponding undirected graph is considered. This argument is ignored for undirected graphs.} } \value{ Numeric vector of integer numbers giving the coreness of each vertex. } \description{ The k-core of graph is a maximal subgraph in which each vertex has at least degree k. The coreness of a vertex is k if it belongs to the k-core but not to the (k+1)-core. } \details{ The k-core of a graph is the maximal subgraph in which every vertex has at least degree k. The cores of a graph form layers: the (k+1)-core is always a subgraph of the k-core. This function calculates the coreness for each vertex. } \examples{ g <- make_ring(10) g <- add_edges(g, c(1,2, 2,3, 1,3)) coreness(g) # small core triangle in a ring } \references{ Vladimir Batagelj, Matjaz Zaversnik: An O(m) Algorithm for Cores Decomposition of Networks, 2002 Seidman S. B. (1983) Network structure and minimum degree, \emph{Social Networks}, 5, 269--287. } \seealso{ \code{\link{degree}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_on_grid.Rd0000644000175100001440000000443613430770475015643 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_on_grid} \alias{layout_on_grid} \alias{layout.grid} \alias{layout.grid.3d} \alias{on_grid} \title{Simple grid layout} \usage{ layout_on_grid(graph, width = 0, height = 0, dim = 2) on_grid(...) layout.grid.3d(graph, width = 0, height = 0) } \arguments{ \item{graph}{The input graph.} \item{width}{The number of vertices in a single row of the grid. If this is zero or negative, then for 2d layouts the width of the grid will be the square root of the number of vertices in the graph, rounded up to the next integer. Similarly, it will be the cube root for 3d layouts.} \item{height}{The number of vertices in a single column of the grid, for three dimensional layouts. If this is zero or negative, then it is determinted automatically.} \item{dim}{Two or three. Whether to make 2d or a 3d layout.} \item{...}{Passed to \code{layout_on_grid}.} } \value{ A two-column or three-column matrix. } \description{ This layout places vertices on a rectangulat grid, in two or three dimensions. } \details{ The function places the vertices on a simple rectangular grid, one after the other. If you want to change the order of the vertices, then see the \code{\link{permute}} function. } \examples{ g <- make_lattice( c(3,3) ) layout_on_grid(g) g2 <- make_lattice( c(3,3,3) ) layout_on_grid(g2, dim = 3) \dontrun{ plot(g, layout=layout_on_grid) rglplot(g, layout=layout_on_grid(g, dim = 3)) } } \seealso{ \code{\link{layout}} for other layout generators Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/graph_from_graphdb.Rd0000644000175100001440000000701113430770475016430 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/foreign.R \name{graph_from_graphdb} \alias{graph_from_graphdb} \alias{graph.graphdb} \title{Load a graph from the graph database for testing graph isomorphism.} \usage{ graph_from_graphdb(url = NULL, prefix = "iso", type = "r001", nodes = NULL, pair = "A", which = 0, base = "http://cneurocvs.rmki.kfki.hu/graphdb/gzip", compressed = TRUE, directed = TRUE) } \arguments{ \item{url}{If not \code{NULL} it is a complete URL with the file to import.} \item{prefix}{Gives the prefix. See details below. Possible values: \code{iso}, \code{i2}, \code{si4}, \code{si6}, \code{mcs10}, \code{mcs30}, \code{mcs50}, \code{mcs70}, \code{mcs90}.} \item{type}{Gives the graph type identifier. See details below. Possible values: \code{r001}, \code{r005}, \code{r01}, \code{r02}, \code{m2D}, \code{m2Dr2}, \code{m2Dr4}, \code{m2Dr6} \code{m3D}, \code{m3Dr2}, \code{m3Dr4}, \code{m3Dr6}, \code{m4D}, \code{m4Dr2}, \code{m4Dr4}, \code{m4Dr6}, \code{b03}, \code{b03m}, \code{b06}, \code{b06m}, \code{b09}, \code{b09m}.} \item{nodes}{The number of vertices in the graph.} \item{pair}{Specifies which graph of the pair to read. Possible values: \code{A} and \code{B}.} \item{which}{Gives the number of the graph to read. For every graph type there are a number of actual graphs in the database. This argument specifies which one to read.} \item{base}{The base address of the database. See details below.} \item{compressed}{Logical constant, if TRUE than the file is expected to be compressed by gzip. If \code{url} is \code{NULL} then a \sQuote{\code{.gz}} suffix is added to the filename.} \item{directed}{Logical constant, whether to create a directed graph.} } \value{ A new graph object. } \description{ This function downloads a graph from a database created for the evaluation of graph isomorphism testing algothitms. } \details{ \code{graph_from_graphdb} reads a graph from the graph database from an FTP or HTTP server or from a local copy. It has two modes of operation: If the \code{url} argument is specified then it should the complete path to a local or remote graph database file. In this case we simply call \code{\link{read_graph}} with the proper arguments to read the file. If \code{url} is \code{NULL}, and this is the default, then the filename is assembled from the \code{base}, \code{prefix}, \code{type}, \code{nodes}, \code{pair} and \code{which} arguments. Unfortunately the original graph database homepage is now defunct, but see its old version at \url{http://web.archive.org/web/20090215182331/http://amalfi.dis.unina.it/graph/db/doc/graphdbat.html} for the actual format of a graph database file and other information. } \section{Examples}{ \preformatted{ g <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="A", which=10, compressed=TRUE) g2 <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="B", which=10, compressed=TRUE) graph.isomorphic.vf2(g, g2) \% should be TRUE g3 <- graph_from_graphdb(url=paste(sep="/", "http://cneurocvs.rmki.kfki.hu", "graphdb/gzip/iso/bvg/b06m", "iso_b06m_m200.A09.gz")) } } \references{ M. De Santo, P. Foggia, C. Sansone, M. Vento: A large database of graphs and its use for benchmarking graph isomorphism algorithms, \emph{Pattern Recognition Letters}, Volume 24, Issue 8 (May 2003) } \seealso{ \code{\link{read_graph}}, \code{\link{graph.isomorphic.vf2}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/cluster_edge_betweenness.Rd0000644000175100001440000001047113430770475017670 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_edge_betweenness} \alias{cluster_edge_betweenness} \alias{edge.betweenness.community} \title{Community structure detection based on edge betweenness} \usage{ cluster_edge_betweenness(graph, weights = E(graph)$weight, directed = TRUE, edge.betweenness = TRUE, merges = TRUE, bridges = TRUE, modularity = TRUE, membership = TRUE) } \arguments{ \item{graph}{The graph to analyze.} \item{weights}{The edge weights. Supply \code{NULL} to omit edge weights. By default the \sQuote{\code{weight}} edge attribute is used, if it is present. Edge weights are used to calculate weighted edge betweenness. This means that edges are interpreted as distances, not as connection strengths.} \item{directed}{Logical constant, whether to calculate directed edge betweenness for directed graphs. It is ignored for undirected graphs.} \item{edge.betweenness}{Logical constant, whether to return the edge betweenness of the edges at the time of their removal.} \item{merges}{Logical constant, whether to return the merge matrix representing the hierarchical community structure of the network. This argument is called \code{merges}, even if the community structure algorithm itself is divisive and not agglomerative: it builds the tree from top to bottom. There is one line for each merge (i.e. split) in matrix, the first line is the first merge (last split). The communities are identified by integer number starting from one. Community ids smaller than or equal to \eqn{N}, the number of vertices in the graph, belong to singleton communities, ie. individual vertices. Before the first merge we have \eqn{N} communities numbered from one to \eqn{N}. The first merge, the first line of the matrix creates community \eqn{N+1}, the second merge creates community \eqn{N+2}, etc.} \item{bridges}{Logical constant, whether to return a list the edge removals which actually splitted a component of the graph.} \item{modularity}{Logical constant, whether to calculate the maximum modularity score, considering all possibly community structures along the edge-betweenness based edge removals.} \item{membership}{Logical constant, whether to calculate the membership vector corresponding to the highest possible modularity score.} } \value{ \code{cluster_edge_betweenness} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ Many networks consist of modules which are densely connected themselves but sparsely connected to other modules. } \details{ The edge betweenness score of an edge measures the number of shortest paths through it, see \code{\link{edge_betweenness}} for details. The idea of the edge betweenness based community structure detection is that it is likely that edges connecting separate modules have high edge betweenness as all the shortest paths from one module to another must traverse through them. So if we gradually remove the edge with the highest edge betweenness score we will get a hierarchical map, a rooted tree, called a dendrogram of the graph. The leafs of the tree are the individual vertices and the root of the tree represents the whole graph. \code{cluster_edge_betweenness} performs this algorithm by calculating the edge betweenness of the graph, removing the edge with the highest edge betweenness score, then recalculating edge betweenness of the edges and again removing the one with the highest score, etc. \code{edge.betweeness.community} returns various information collected throught the run of the algorithm. See the return value down here. } \examples{ g <- sample_pa(100, m = 2, directed = FALSE) eb <- cluster_edge_betweenness(g) g <- make_full_graph(10) \%du\% make_full_graph(10) g <- add_edges(g, c(1,11)) eb <- cluster_edge_betweenness(g) eb } \references{ M Newman and M Girvan: Finding and evaluating community structure in networks, \emph{Physical Review E} 69, 026113 (2004) } \seealso{ \code{\link{edge_betweenness}} for the definition and calculation of the edge betweenness, \code{\link{cluster_walktrap}}, \code{\link{cluster_fast_greedy}}, \code{\link{cluster_leading_eigen}} for other community detection methods. See \code{\link{communities}} for extracting the results of the community detection. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/max_flow.Rd0000644000175100001440000000646613430770475014446 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{max_flow} \alias{max_flow} \alias{graph.maxflow} \title{Maximum flow in a graph} \usage{ max_flow(graph, source, target, capacity = NULL) } \arguments{ \item{graph}{The input graph.} \item{source}{The id of the source vertex.} \item{target}{The id of the target vertex (sometimes also called sink).} \item{capacity}{Vector giving the capacity of the edges. If this is \code{NULL} (the default) then the \code{capacity} edge attribute is used. Note that the \code{weight} edge attribute is not used by this function.} } \value{ A named list with components: \item{value}{A numeric scalar, the value of the maximum flow.} \item{flow}{A numeric vector, the flow itself, one entry for each edge. For undirected graphs this entry is bit trickier, since for these the flow direction is not predetermined by the edge direction. For these graphs the elements of the this vector can be negative, this means that the flow goes from the bigger vertex id to the smaller one. Positive values mean that the flow goes from the smaller vertex id to the bigger one.} \item{cut}{A numeric vector of edge ids, the minimum cut corresponding to the maximum flow.} \item{partition1}{A numeric vector of vertex ids, the vertices in the first partition of the minimum cut corresponding to the maximum flow.} \item{partition2}{A numeric vector of vertex ids, the vertices in the second partition of the minimum cut corresponding to the maximum flow.} \item{stats}{A list with some statistics from the push-relabel algorithm. Five integer values currently: \code{nopush} is the number of push operations, \code{norelabel} the number of relabelings, \code{nogap} is the number of times the gap heuristics was used, \code{nogapnodes} is the total number of gap nodes omitted because of the gap heuristics and \code{nobfs} is the number of times a global breadth-first-search update was performed to assign better height (=distance) values to the vertices.} } \description{ In a graph where each edge has a given flow capacity the maximal flow between two vertices is calculated. } \details{ \code{max_flow} calculates the maximum flow between two vertices in a weighted (ie. valued) graph. A flow from \code{source} to \code{target} is an assignment of non-negative real numbers to the edges of the graph, satisfying two properties: (1) for each edge the flow (ie. the assigned number) is not more than the capacity of the edge (the \code{capacity} parameter or edge attribute), (2) for every vertex, except the source and the target the incoming flow is the same as the outgoing flow. The value of the flow is the incoming flow of the \code{target} vertex. The maximum flow is the flow of maximum value. } \examples{ E <- rbind( c(1,3,3), c(3,4,1), c(4,2,2), c(1,5,1), c(5,6,2), c(6,2,10)) colnames(E) <- c("from", "to", "capacity") g1 <- graph_from_data_frame(as.data.frame(E)) max_flow(g1, source=V(g1)["1"], target=V(g1)["2"]) } \references{ A. V. Goldberg and R. E. Tarjan: A New Approach to the Maximum Flow Problem \emph{Journal of the ACM} 35:921-940, 1988. } \seealso{ \code{\link{min_cut}} for minimum cut calculations, \code{\link{distances}}, \code{\link{edge_connectivity}}, \code{\link{vertex_connectivity}} } igraph/man/subgraph_isomorphic.Rd0000644000175100001440000001045413430770476016672 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{subgraph_isomorphic} \alias{subgraph_isomorphic} \alias{graph.subisomorphic.vf2} \alias{graph.subisomorphic.lad} \alias{is_subgraph_isomorphic_to} \title{Decide if a graph is subgraph isomorphic to another one} \usage{ subgraph_isomorphic(pattern, target, method = c("auto", "lad", "vf2"), ...) is_subgraph_isomorphic_to(pattern, target, method = c("auto", "lad", "vf2"), ...) } \arguments{ \item{pattern}{The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{target}{The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges.} \item{method}{The method to use. Possible values: \sQuote{auto}, \sQuote{lad}, \sQuote{vf2}. See their details below.} \item{...}{Additional arguments, passed to the various methods.} } \value{ Logical scalar, \code{TRUE} if the \code{pattern} is isomorphic to a (possibly induced) subgraph of \code{target}. } \description{ Decide if a graph is subgraph isomorphic to another one } \section{\sQuote{auto} method}{ This method currently selects \sQuote{lad}, always, as it seems to be superior on most graphs. } \section{\sQuote{lad} method}{ This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments: \describe{ \item{domains}{If not \code{NULL}, then it specifies matching restrictions. It must be a list of \code{target} vertex sets, given as numeric vertex ids or symbolic vertex names. The length of the list must be \code{vcount(pattern)} and for each vertex in \code{pattern} it gives the allowed matching vertices in \code{target}. Defaults to \code{NULL}.} \item{induced}{Logical scalar, whether to search for an induced subgraph. It is \code{FALSE} by default.} \item{time.limit}{The processor time limit for the computation, in seconds. It defaults to \code{Inf}, which means no limit.} } } \section{\sQuote{vf2} method}{ This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments: \describe{ \item{vertex.color1, vertex.color2}{Optional integer vectors giving the colors of the vertices for colored graph isomorphism. If they are not given, but the graph has a \dQuote{color} vertex attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments. See also examples below.} \item{edge.color1, edge.color2}{Optional integer vectors giving the colors of the edges for edge-colored (sub)graph isomorphism. If they are not given, but the graph has a \dQuote{color} edge attribute, then it will be used. If you want to ignore these attributes, then supply \code{NULL} for both of these arguments.} } } \examples{ # A LAD example pattern <- make_graph(~ 1:2:3:4:5, 1 - 2:5, 2 - 1:5:3, 3 - 2:4, 4 - 3:5, 5 - 4:2:1) target <- make_graph(~ 1:2:3:4:5:6:7:8:9, 1 - 2:5:7, 2 - 1:5:3, 3 - 2:4, 4 - 3:5:6:8:9, 5 - 1:2:4:6:7, 6 - 7:5:4:9, 7 - 1:5:6, 8 - 4:9, 9 - 6:4:8) domains <- list(`1` = c(1,3,9), `2` = c(5,6,7,8), `3` = c(2,4,6,7,8,9), `4` = c(1,3,9), `5` = c(2,4,8,9)) subgraph_isomorphisms(pattern, target) subgraph_isomorphisms(pattern, target, induced = TRUE) subgraph_isomorphisms(pattern, target, domains = domains) # Directed LAD example pattern <- make_graph(~ 1:2:3, 1 -+ 2:3) dring <- make_ring(10, directed = TRUE) subgraph_isomorphic(pattern, dring) } \references{ LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition}, 149--159, 2001. C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, \emph{Artificial Intelligence} 174(12-13):850--864, 2010. } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/graph_from_incidence_matrix.Rd0000644000175100001440000000661513430770475020337 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/incidence.R \name{graph_from_incidence_matrix} \alias{graph_from_incidence_matrix} \alias{graph.incidence} \alias{from_incidence_matrix} \title{Create graphs from an incidence matrix} \usage{ graph_from_incidence_matrix(incidence, directed = FALSE, mode = c("all", "out", "in", "total"), multiple = FALSE, weighted = NULL, add.names = NULL) from_incidence_matrix(...) } \arguments{ \item{incidence}{The input incidence matrix. It can also be a sparse matrix from the \code{Matrix} package.} \item{directed}{Logical scalar, whether to create a directed graph.} \item{mode}{A character constant, defines the direction of the edges in directed graphs, ignored for undirected graphs. If \sQuote{\code{out}}, then edges go from vertices of the first kind (corresponding to rows in the incidence matrix) to vertices of the second kind (columns in the incidence matrix). If \sQuote{\code{in}}, then the opposite direction is used. If \sQuote{\code{all}} or \sQuote{\code{total}}, then mutual edges are created.} \item{multiple}{Logical scalar, specifies how to interpret the matrix elements. See details below.} \item{weighted}{This argument specifies whether to create a weighted graph from the incidence matrix. If it is \code{NULL} then an unweighted graph is created and the \code{multiple} argument is used to determine the edges of the graph. If it is a character constant then for every non-zero matrix entry an edge is created and the value of the entry is added as an edge attribute named by the \code{weighted} argument. If it is \code{TRUE} then a weighted graph is created and the name of the edge attribute will be \sQuote{\code{weight}}.} \item{add.names}{A character constant, \code{NA} or \code{NULL}. \code{graph_from_incidence_matrix} can add the row and column names of the incidence matrix as vertex attributes. If this argument is \code{NULL} (the default) and the incidence matrix has both row and column names, then these are added as the \sQuote{\code{name}} vertex attribute. If you want a different vertex attribute for this, then give the name of the attributes as a character string. If this argument is \code{NA}, then no vertex attributes (other than type) will be added.} \item{...}{Passed to \code{graph_from_incidence_matrix}.} } \value{ A bipartite igraph graph. In other words, an igraph graph that has a vertex attribute \code{type}. } \description{ \code{graph_from_incidence_matrix} creates a bipartite igraph graph from an incidence matrix. } \details{ Bipartite graphs have a \sQuote{\code{type}} vertex attribute in igraph, this is boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} for vertices of the second kind. \code{graph_from_incidence_matrix} can operate in two modes, depending on the \code{multiple} argument. If it is \code{FALSE} then a single edge is created for every non-zero element in the incidence matrix. If \code{multiple} is \code{TRUE}, then the matrix elements are rounded up to the closest non-negative integer to get the number of edges to create between a pair of vertices. } \examples{ inc <- matrix(sample(0:1, 15, repl=TRUE), 3, 5) colnames(inc) <- letters[1:5] rownames(inc) <- LETTERS[1:3] graph_from_incidence_matrix(inc) } \seealso{ \code{\link{make_bipartite_graph}} for another way to create bipartite graphs } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/scg_group.Rd0000644000175100001440000001212313430770476014606 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{scg_group} \alias{scg_group} \alias{scgGrouping} \title{SCG Problem Solver} \usage{ scg_group(V, nt, mtype = c("symmetric", "laplacian", "stochastic"), algo = c("optimum", "interv_km", "interv", "exact_scg"), p = NULL, maxiter = 100) } \arguments{ \item{V}{A numeric matrix of (eigen)vectors to be preserved by the coarse graining (the vectors are to be stored column-wise in \code{V}).} \item{nt}{A vector of positive integers of length one or equal to \code{length(ev)}. When \code{algo} = \dQuote{optimum}, \code{nt} contains the number of groups used to partition each eigenvector separately. When \code{algo} is equal to \dQuote{interv\_km} or \dQuote{interv}, \code{nt} contains the number of intervals used to partition each eigenvector. The same partition size or number of intervals is used for each eigenvector if \code{nt} is a single integer. When \code{algo} = \dQuote{exact\_cg} this parameter is ignored.} \item{mtype}{The type of semi-projectors used in the SCG. For now \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are available.} \item{algo}{The algorithm used to solve the SCG problem. Possible values are \dQuote{optimum}, \dQuote{interv\_km}, \dQuote{interv} and \dQuote{exact\_scg}.} \item{p}{A probability vector of length equal to \code{nrow(V)}. \code{p} is the stationary probability distribution of a Markov chain when \code{mtype} = \dQuote{stochastic}. This parameter is ignored in all other cases.} \item{maxiter}{A positive integer giving the maximum number of iterations of the k-means algorithm when \code{algo} = \dQuote{interv\_km}. This parameter is ignored in all other cases.} } \value{ A vector of \code{nrow(V)} integers giving the group label of each object (vertex) in the partition. } \description{ This function solves the Spectral Coarse Graining (SCG) problem; either exactly, or approximately but faster. } \details{ The algorithm \dQuote{optimum} solves exactly the SCG problem for each eigenvector in \code{V}. The running time of this algorithm is \eqn{O(\max nt \cdot m^2)}{O(max(nt) m^2)} for the symmetric and laplacian matrix problems (i.e. when \code{mtype} is \dQuote{symmetric} or \dQuote{laplacian}. It is \eqn{O(m^3)} for the stochastic problem. Here \eqn{m} is the number of rows in \code{V}. In all three cases, the memory usage is \eqn{O(m^2)}. The algorithms \dQuote{interv} and \dQuote{interv\_km} solve approximately the SCG problem by performing a (for now) constant binning of the components of the eigenvectors, that is \code{nt[i]} constant-size bins are used to partition \code{V[,i]}. When \code{algo} = \dQuote{interv\_km}, the (Lloyd) k-means algorithm is run on each partition obtained by \dQuote{interv} to improve accuracy. Once a minimizing partition (either exact or approximate) has been found for each eigenvector, the final grouping is worked out as follows: two vertices are grouped together in the final partition if they are grouped together in each minimizing partition. In general the size of the final partition is not known in advance when \code{ncol(V)}>1. Finally, the algorithm \dQuote{exact\_scg} groups the vertices with equal components in each eigenvector. The last three algorithms essentially have linear running time and memory load. } \examples{ ## We are not running these examples any more, because they ## take a long time to run and this is against the CRAN repository ## policy. Copy and paste them by hand to your R prompt if ## you want to run them. \dontrun{ # eigenvectors of a random symmetric matrix M <- matrix(rexp(10^6), 10^3, 10^3) M <- (M + t(M))/2 V <- eigen(M, symmetric=TRUE)$vectors[,c(1,2)] # displays size of the groups in the final partition gr <- scg_group(V, nt=c(2,3)) col <- rainbow(max(gr)) plot(table(gr), col=col, main="Group size", xlab="group", ylab="size") ## comparison with the grouping obtained by kmeans ## for a partition of same size gr.km <- kmeans(V,centers=max(gr), iter.max=100, nstart=100)$cluster op <- par(mfrow=c(1,2)) plot(V[,1], V[,2], col=col[gr], main = "SCG grouping", xlab = "1st eigenvector", ylab = "2nd eigenvector") plot(V[,1], V[,2], col=col[gr.km], main = "K-means grouping", xlab = "1st eigenvector", ylab = "2nd eigenvector") par(op) ## kmeans disregards the first eigenvector as it ## spreads a much smaller range of values than the second one ### comparing optimal and k-means solutions ### in the one-dimensional case. x <- rexp(2000, 2) gr.true <- scg_group(cbind(x), 100) gr.km <- kmeans(x, 100, 100, 300)$cluster scg_eps(cbind(x), gr.true) scg_eps(cbind(x), gr.km) } } \references{ D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, Shrinking Matrices while Preserving their Eigenpairs with Application to the Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on Matrix Analysis and Applications}, 2008. \url{http://people.epfl.ch/david.morton} } \seealso{ \link{scg-method} for a detailed introduction. \code{\link{scg}}, \code{\link{scg_eps}} } \author{ David Morton de Lachapelle \email{david.morton@epfl.ch}, \email{david.mortondelachapelle@swissquote.ch} } \keyword{graphs} igraph/man/dfs.Rd0000644000175100001440000001003613430770476013373 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{dfs} \alias{dfs} \alias{graph.dfs} \title{Depth-first search} \usage{ dfs(graph, root, neimode = c("out", "in", "all", "total"), unreachable = TRUE, order = TRUE, order.out = FALSE, father = FALSE, dist = FALSE, in.callback = NULL, out.callback = NULL, extra = NULL, rho = parent.frame()) } \arguments{ \item{graph}{The input graph.} \item{root}{The single root vertex to start the search from.} \item{neimode}{For directed graphs specifies the type of edges to follow. \sQuote{out} follows outgoing, \sQuote{in} incoming edges. \sQuote{all} ignores edge directions completely. \sQuote{total} is a synonym for \sQuote{all}. This argument is ignored for undirected graphs.} \item{unreachable}{Logical scalar, whether the search should visit the vertices that are unreachable from the given root vertex (or vertices). If \code{TRUE}, then additional searches are performed until all vertices are visited.} \item{order}{Logical scalar, whether to return the DFS ordering of the vertices.} \item{order.out}{Logical scalar, whether to return the ordering based on leaving the subtree of the vertex.} \item{father}{Logical scalar, whether to return the father of the vertices.} \item{dist}{Logical scalar, whether to return the distance from the root of the search tree.} \item{in.callback}{If not \code{NULL}, then it must be callback function. This is called whenever a vertex is visited. See details below.} \item{out.callback}{If not \code{NULL}, then it must be callback function. This is called whenever the subtree of a vertex is completed by the algorithm. See details below.} \item{extra}{Additional argument to supply to the callback function.} \item{rho}{The environment in which the callback function is evaluated.} } \value{ A named list with the following entries: \item{root}{Numeric scalar. The root vertex that was used as the starting point of the search.} \item{neimode}{Character scalar. The \code{neimode} argument of the function call. Note that for undirected graphs this is always \sQuote{all}, irrespectively of the supplied value.} \item{order}{Numeric vector. The vertex ids, in the order in which they were visited by the search.} \item{order.out}{Numeric vector, the vertex ids, in the order of the completion of their subtree.} \item{father}{Numeric vector. The father of each vertex, i.e. the vertex it was discovered from.} \item{dist}{Numeric vector, for each vertex its distance from the root of the search tree.} Note that \code{order}, \code{order.out}, \code{father}, and \code{dist} might be \code{NULL} if their corresponding argument is \code{FALSE}, i.e. if their calculation is not requested. } \description{ Depth-first search is an algorithm to traverse a graph. It starts from a root vertex and tries to go quickly as far from as possible. } \details{ The callback functions must have the following arguments: \describe{ \item{graph}{The input graph is passed to the callback function here.} \item{data}{A named numeric vector, with the following entries: \sQuote{vid}, the vertex that was just visited and \sQuote{dist}, its distance from the root of the search tree.} \item{extra}{The extra argument.} } See examples below on how to use the callback functions. } \examples{ ## A graph with two separate trees dfs(make_tree(10) \%du\% make_tree(10), root=1, "out", TRUE, TRUE, TRUE, TRUE) ## How to use a callback f.in <- function(graph, data, extra) { cat("in:", paste(collapse=", ", data), "\\n") FALSE } f.out <- function(graph, data, extra) { cat("out:", paste(collapse=", ", data), "\\n") FALSE } tmp <- dfs(make_tree(10), root=1, "out", in.callback=f.in, out.callback=f.out) ## Terminate after the first component, using a callback f.out <- function(graph, data, extra) { data['vid'] == 1 } tmp <- dfs(make_tree(10) \%du\% make_tree(10), root=1, out.callback=f.out) } \seealso{ \code{\link{bfs}} for breadth-first search. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_.Rd0000644000175100001440000000531713430770475014300 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_} \alias{layout_} \alias{layout} \alias{print.igraph_layout_spec} \alias{print.igraph_layout_modifier} \title{Graph layouts} \usage{ layout_(graph, layout, ...) \method{print}{igraph_layout_spec}(x, ...) \method{print}{igraph_layout_modifier}(x, ...) } \arguments{ \item{graph}{The input graph.} \item{layout}{The layout specification. It must be a call to a layout specification function.} \item{...}{Further modifiers, see a complete list below. For the \code{print} methods, it is ignored.} \item{x}{The layout specification} } \value{ The return value of the layout function, usually a two column matrix. For 3D layouts a three column matrix. } \description{ This is a generic function to apply a layout function to a graph. } \details{ There are two ways to calculate graph layouts in igraph. The first way is to call a layout function (they all have prefix \code{layout_} on a graph, to get the vertex coordinates. The second way (new in igraph 0.8.0), has two steps, and it is more flexible. First you call a layout specification function (the one without the \code{layout_} prefix, and then \code{layout_} (or \code{\link{add_layout_}}) to perform the layouting. The second way is preferred, as it is more flexible. It allows operations before and after the layouting. E.g. using the \code{component_wise} argument, the layout can be calculated separately for each component, and then merged to get the final results. } \section{Modifiers}{ Modifiers modify how a layout calculation is performed. Currently implemented modifyers: \itemize{ \item \code{component_wise} calculates the layout separately for each component of the graph, and then merges them. \item \code{normalize} scales the layout to a square. } } \examples{ g <- make_ring(10) + make_full_graph(5) coords <- layout_(g, as_star()) plot(g, layout = coords) } \seealso{ \code{\link{add_layout_}} to add the layout to the graph as an attribute. Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \concept{graph layouts} igraph/man/dominator_tree.Rd0000644000175100001440000000542713430770475015641 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{dominator_tree} \alias{dominator_tree} \alias{dominator.tree} \title{Dominator tree} \usage{ dominator_tree(graph, root, mode = c("out", "in")) } \arguments{ \item{graph}{A directed graph. If it is not a flowgraph, and it contains some vertices not reachable from the root vertex, then these vertices will be collected and returned as part of the result.} \item{root}{The id of the root (or source) vertex, this will be the root of the tree.} \item{mode}{Constant, must be \sQuote{\code{in}} or \sQuote{\code{out}}. If it is \sQuote{\code{in}}, then all directions are considered as opposite to the original one in the input graph.} } \value{ A list with components: \item{dom}{ A numeric vector giving the immediate dominators for each vertex. For vertices that are unreachable from the root, it contains \code{NaN}. For the root vertex itself it contains minus one. } \item{domtree}{ A graph object, the dominator tree. Its vertex ids are the as the vertex ids of the input graph. Isolate vertices are the ones that are unreachable from the root. } \item{leftout}{ A numeric vector containing the vertex ids that are unreachable from the root. } } \description{ Dominator tree of a directed graph. } \details{ A flowgraph is a directed graph with a distinguished start (or root) vertex \eqn{r}, such that for any vertex \eqn{v}, there is a path from \eqn{r} to \eqn{v}. A vertex \eqn{v} dominates another vertex \eqn{w} (not equal to \eqn{v}), if every path from \eqn{r} to \eqn{w} contains \eqn{v}. Vertex \eqn{v} is the immediate dominator or \eqn{w}, \eqn{v=\textrm{idom}(w)}{v=idom(w)}, if \eqn{v} dominates \eqn{w} and every other dominator of \eqn{w} dominates \eqn{v}. The edges \eqn{{(\textrm{idom}(w), w)| w \ne r}}{{(idom(w),w)| w is not r}} form a directed tree, rooted at \eqn{r}, called the dominator tree of the graph. Vertex \eqn{v} dominates vertex \eqn{w} if and only if \eqn{v} is an ancestor of \eqn{w} in the dominator tree. This function implements the Lengauer-Tarjan algorithm to construct the dominator tree of a directed graph. For details see the reference below. } \examples{ ## The example from the paper g <- graph_from_literal(R-+A:B:C, A-+D, B-+A:D:E, C-+F:G, D-+L, E-+H, F-+I, G-+I:J, H-+E:K, I-+K, J-+I, K-+I:R, L-+H) dtree <- dominator_tree(g, root="R") layout <- layout_as_tree(dtree$domtree, root="R") layout[,2] <- -layout[,2] plot(dtree$domtree, layout=layout, vertex.label=V(dtree$domtree)$name) } \references{ Thomas Lengauer, Robert Endre Tarjan: A fast algorithm for finding dominators in a flowgraph, \emph{ACM Transactions on Programming Languages and Systems (TOPLAS)} I/1, 121--141, 1979. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sir.Rd0000644000175100001440000000770713430770475013426 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/epi.R, R/sir.R \name{time_bins.sir} \alias{time_bins.sir} \alias{median.sir} \alias{quantile.sir} \alias{sir} \alias{time_bins} \title{SIR model on graphs} \usage{ \method{time_bins}{sir}(x, middle = TRUE) \method{median}{sir}(x, na.rm = FALSE, ...) \method{quantile}{sir}(x, comp = c("NI", "NS", "NR"), prob, ...) sir(graph, beta, gamma, no.sim = 100) } \arguments{ \item{x}{A \code{sir} object, returned by the \code{sir} function.} \item{middle}{Logical scalar, whether to return the middle of the time bins, or the boundaries.} \item{na.rm}{Logical scalar, whether to ignore \code{NA} values. \code{sir} objects do not contain any \code{NA} values currently, so this argument is effectively ignored.} \item{\dots}{Additional arguments, ignored currently.} \item{comp}{Character scalar. The component to calculate the quantile of. \code{NI} is infected agents, \code{NS} is susceptibles, \code{NR} stands for recovered.} \item{prob}{Numeric vector of probabilities, in [0,1], they specify the quantiles to calculate.} \item{graph}{The graph to run the model on. If directed, then edge directions are ignored and a warning is given.} \item{beta}{Non-negative scalar. The rate of infection of an individual that is susceptible and has a single infected neighbor. The infection rate of a susceptible individual with n infected neighbors is n times beta. Formally this is the rate parameter of an exponential distribution.} \item{gamma}{Positive scalar. The rate of recovery of an infected individual. Formally, this is the rate parameter of an exponential distribution.} \item{no.sim}{Integer scalar, the number simulation runs to perform.} } \value{ For \code{sir} the results are returned in an object of class \sQuote{\code{sir}}, which is a list, with one element for each simulation. Each simulation is itself a list with the following elements. They are all numeric vectors, with equal length: \describe{ \item{times}{The times of the events.} \item{NS}{The number of susceptibles in the population, over time.} \item{NI}{The number of infected individuals in the population, over time.} \item{NR}{The number of recovered individuals in the population, over time.} } Function \code{time_bins} returns a numeric vector, the middle or the boundaries of the time bins, depending on the \code{middle} argument. \code{median} returns a list of three named numeric vectors, \code{NS}, \code{NI} and \code{NR}. The names within the vectors are created from the time bins. \code{quantile} returns the same vector as \code{median} (but only one, the one requested) if only one quantile is requested. If multiple quantiles are requested, then a list of these vectors is returned, one for each quantile. } \description{ Run simulations for an SIR (susceptible-infected-recovered) model, on a graph } \details{ The SIR model is a simple model from epidemiology. The individuals of the population might be in three states: susceptible, infected and recovered. Recovered people are assumed to be immune to the disease. Susceptibles become infected with a rate that depends on their number of infected neigbors. Infected people become recovered with a constant rate. The function \code{sir} simulates the model. Function \code{time_bins} bins the simulation steps, using the Freedman-Diaconis heuristics to determine the bin width. Function \code{median} and \code{quantile} calculate the median and quantiles of the results, respectively, in bins calculated with \code{time_bins}. } \examples{ g <- sample_gnm(100, 100) sm <- sir(g, beta=5, gamma=1) plot(sm) } \references{ Bailey, Norman T. J. (1975). The mathematical theory of infectious diseases and its applications (2nd ed.). London: Griffin. } \seealso{ \code{\link{plot.sir}} to conveniently plot the results } \author{ Gabor Csardi \email{csardi.gabor@gmail.com}. Eric Kolaczyk (\url{http://math.bu.edu/people/kolaczyk/}) wrote the initial version in R. } \keyword{graphs} igraph/man/count_motifs.Rd0000644000175100001440000000213313430770475015326 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/motifs.R \name{count_motifs} \alias{count_motifs} \alias{graph.motifs.no} \title{Graph motifs} \usage{ count_motifs(graph, size = 3, cut.prob = rep(0, size)) } \arguments{ \item{graph}{Graph object, the input graph.} \item{size}{The size of the motif, currently 3 and 4 are supported only.} \item{cut.prob}{Numeric vector giving the probabilities that the search graph is cut at a certain level. Its length should be the same as the size of the motif (the \code{size} argument). By default no cuts are made.} } \value{ \code{count_motifs} returns a numeric scalar. } \description{ Graph motifs are small connected subgraphs with a well-defined structure. These functions search a graph for various motifs. } \details{ \code{count_motifs} calculates the total number of motifs of a given size in graph. } \examples{ g <- barabasi.game(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3) } \seealso{ \code{\link{isomorphism_class}} Other graph motifs: \code{\link{motifs}}, \code{\link{sample_motifs}} } \concept{graph motifs} igraph/man/cluster_fast_greedy.Rd0000644000175100001440000000446613430770475016665 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_fast_greedy} \alias{cluster_fast_greedy} \alias{fastgreedy.community} \title{Community structure via greedy optimization of modularity} \usage{ cluster_fast_greedy(graph, merges = TRUE, modularity = TRUE, membership = TRUE, weights = E(graph)$weight) } \arguments{ \item{graph}{The input graph} \item{merges}{Logical scalar, whether to return the merge matrix.} \item{modularity}{Logical scalar, whether to return a vector containing the modularity after each merge.} \item{membership}{Logical scalar, whether to calculate the membership vector corresponding to the maximum modularity score, considering all possible community structures along the merges.} \item{weights}{If not \code{NULL}, then a numeric vector of edge weights. The length must match the number of edges in the graph. By default the \sQuote{\code{weight}} edge attribute is used as weights. If it is not present, then all edges are considered to have the same weight. Larger edge weights correspond to stronger connections.} } \value{ \code{cluster_fast_greedy} returns a \code{\link{communities}} object, please see the \code{\link{communities}} manual page for details. } \description{ This function tries to find dense subgraph, also called communities in graphs via directly optimizing a modularity score. } \details{ This function implements the fast greedy modularity optimization algorithm for finding community structure, see A Clauset, MEJ Newman, C Moore: Finding community structure in very large networks, http://www.arxiv.org/abs/cond-mat/0408187 for the details. } \examples{ g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) fc <- cluster_fast_greedy(g) membership(fc) sizes(fc) } \references{ A Clauset, MEJ Newman, C Moore: Finding community structure in very large networks, http://www.arxiv.org/abs/cond-mat/0408187 } \seealso{ \code{\link{communities}} for extracting the results. See also \code{\link{cluster_walktrap}}, \code{\link{cluster_spinglass}}, \code{\link{cluster_leading_eigen}} and \code{\link{cluster_edge_betweenness}} for other methods. } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} for the R interface. } \keyword{graphs} igraph/man/make_graph.Rd0000644000175100001440000002153413430770475014721 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \encoding{UTF-8} \name{make_graph} \alias{make_graph} \alias{graph.famous} \alias{graph} \alias{make_directed_graph} \alias{make_undirected_graph} \alias{directed_graph} \alias{undirected_graph} \title{Create an igraph graph from a list of edges, or a notable graph} \usage{ make_graph(edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE) make_directed_graph(edges, n = max(edges)) make_undirected_graph(edges, n = max(edges)) directed_graph(...) undirected_graph(...) } \arguments{ \item{edges}{A vector defining the edges, the first edge points from the first element to the second, the second edge from the third to the fourth, etc. For a numeric vector, these are interpreted as internal vertex ids. For character vectors, they are interpreted as vertex names. Alternatively, this can be a character scalar, the name of a notable graph. See Notable graphs below. The name is case insensitive. Starting from igraph 0.8.0, you can also include literals here, via igraph's formula notation (see \code{\link{graph_from_literal}}). In this case, the first term of the formula has to start with a \sQuote{\code{~}} character, just like regular formulae in R. See examples below.} \item{...}{For \code{make_graph}: extra arguments for the case when the graph is given via a literal, see \code{\link{graph_from_literal}}. For \code{directed_graph} and \code{undirected_graph}: Passed to \code{make_directed_graph} or \code{make_undirected_graph}.} \item{n}{The number of vertices in the graph. This argument is ignored (with a warning) if \code{edges} are symbolic vertex names. It is also ignored if there is a bigger vertex id in \code{edges}. This means that for this function it is safe to supply zero here if the vertex with the largest id is not an isolate.} \item{isolates}{Character vector, names of isolate vertices, for symbolic edge lists. It is ignored for numeric edge lists.} \item{directed}{Whether to create a directed graph.} \item{dir}{It is the same as \code{directed}, for compatibility. Do not give both of them.} \item{simplify}{For graph literals, whether to simplify the graph.} } \value{ An igraph graph. } \description{ Create an igraph graph from a list of edges, or a notable graph } \section{Notable graphs}{ \code{make_graph} can create some notable graphs. The name of the graph (case insensitive), a character scalar must be suppliced as the \code{edges} argument, and other arguments are ignored. (A warning is given is they are specified.) \code{make_graph} knows the following graphs: \describe{ \item{Bull}{The bull graph, 5 vertices, 5 edges, resembles to the head of a bull if drawn properly.} \item{Chvatal}{This is the smallest triangle-free graph that is both 4-chromatic and 4-regular. According to the Grunbaum conjecture there exists an m-regular, m-chromatic graph with n vertices for every m>1 and n>2. The Chvatal graph is an example for m=4 and n=12. It has 24 edges.} \item{Coxeter}{A non-Hamiltonian cubic symmetric graph with 28 vertices and 42 edges.} \item{Cubical}{The Platonic graph of the cube. A convex regular polyhedron with 8 vertices and 12 edges.} \item{Diamond}{A graph with 4 vertices and 5 edges, resembles to a schematic diamond if drawn properly.} \item{Dodecahedral, Dodecahedron}{Another Platonic solid with 20 vertices and 30 edges.} \item{Folkman}{The semisymmetric graph with minimum number of vertices, 20 and 40 edges. A semisymmetric graph is regular, edge transitive and not vertex transitive.} \item{Franklin}{This is a graph whose embedding to the Klein bottle can be colored with six colors, it is a counterexample to the neccessity of the Heawood conjecture on a Klein bottle. It has 12 vertices and 18 edges.} \item{Frucht}{The Frucht Graph is the smallest cubical graph whose automorphism group consists only of the identity element. It has 12 vertices and 18 edges.} \item{Grotzsch}{The Groetzsch graph is a triangle-free graph with 11 vertices, 20 edges, and chromatic number 4. It is named after German mathematician Herbert Groetzsch, and its existence demonstrates that the assumption of planarity is necessary in Groetzsch's theorem that every triangle-free planar graph is 3-colorable.} \item{Heawood}{The Heawood graph is an undirected graph with 14 vertices and 21 edges. The graph is cubic, and all cycles in the graph have six or more edges. Every smaller cubic graph has shorter cycles, so this graph is the 6-cage, the smallest cubic graph of girth 6.} \item{Herschel}{The Herschel graph is the smallest nonhamiltonian polyhedral graph. It is the unique such graph on 11 nodes, and has 18 edges.} \item{House}{The house graph is a 5-vertex, 6-edge graph, the schematic draw of a house if drawn properly, basicly a triangle of the top of a square.} \item{HouseX}{The same as the house graph with an X in the square. 5 vertices and 8 edges.} \item{Icosahedral, Icosahedron}{A Platonic solid with 12 vertices and 30 edges.} \item{Krackhardt kite}{A social network with 10 vertices and 18 edges. Krackhardt, D. Assessing the Political Landscape: Structure, Cognition, and Power in Organizations. Admin. Sci. Quart. 35, 342-369, 1990.} \item{Levi}{The graph is a 4-arc transitive cubic graph, it has 30 vertices and 45 edges.} \item{McGee}{The McGee graph is the unique 3-regular 7-cage graph, it has 24 vertices and 36 edges.} \item{Meredith}{The Meredith graph is a quartic graph on 70 nodes and 140 edges that is a counterexample to the conjecture that every 4-regular 4-connected graph is Hamiltonian.} \item{Noperfectmatching}{A connected graph with 16 vertices and 27 edges containing no perfect matching. A matching in a graph is a set of pairwise non-adjacent edges; that is, no two edges share a common vertex. A perfect matching is a matching which covers all vertices of the graph.} \item{Nonline}{A graph whose connected components are the 9 graphs whose presence as a vertex-induced subgraph in a graph makes a nonline graph. It has 50 vertices and 72 edges.} \item{Octahedral, Octahedron}{Platonic solid with 6 vertices and 12 edges.} \item{Petersen}{A 3-regular graph with 10 vertices and 15 edges. It is the smallest hypohamiltonian graph, ie. it is non-hamiltonian but removing any single vertex from it makes it Hamiltonian.} \item{Robertson}{The unique (4,5)-cage graph, ie. a 4-regular graph of girth 5. It has 19 vertices and 38 edges.} \item{Smallestcyclicgroup}{A smallest nontrivial graph whose automorphism group is cyclic. It has 9 vertices and 15 edges.} \item{Tetrahedral, Tetrahedron}{Platonic solid with 4 vertices and 6 edges.} \item{Thomassen}{The smallest hypotraceable graph, on 34 vertices and 52 edges. A hypotracable graph does not contain a Hamiltonian path but after removing any single vertex from it the remainder always contains a Hamiltonian path. A graph containing a Hamiltonian path is called tracable.} \item{Tutte}{Tait's Hamiltonian graph conjecture states that every 3-connected 3-regular planar graph is Hamiltonian. This graph is a counterexample. It has 46 vertices and 69 edges.} \item{Uniquely3colorable}{Returns a 12-vertex, triangle-free graph with chromatic number 3 that is uniquely 3-colorable.} \item{Walther}{An identity graph with 25 vertices and 31 edges. An identity graph has a single graph automorphism, the trivial one.} \item{Zachary}{Social network of friendships between 34 members of a karate club at a US university in the 1970s. See W. W. Zachary, An information flow model for conflict and fission in small groups, Journal of Anthropological Research 33, 452-473 (1977). } } } \examples{ make_graph(c(1, 2, 2, 3, 3, 4, 5, 6), directed = FALSE) make_graph(c("A", "B", "B", "C", "C", "D"), directed = FALSE) solids <- list(make_graph("Tetrahedron"), make_graph("Cubical"), make_graph("Octahedron"), make_graph("Dodecahedron"), make_graph("Icosahedron")) graph <- make_graph( ~ A-B-C-D-A, E-A:B:C:D, F-G-H-I-F, J-F:G:H:I, K-L-M-N-K, O-K:L:M:N, P-Q-R-S-P, T-P:Q:R:S, B-F, E-J, C-I, L-T, O-T, M-S, C-P, C-L, I-L, I-P) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{determimistic constructors} igraph/man/without_multiples.Rd0000644000175100001440000000117613430770475016424 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{without_multiples} \alias{without_multiples} \title{Constructor modifier to drop multiple edges} \usage{ without_multiples() } \description{ Constructor modifier to drop multiple edges } \examples{ sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), without_multiples()) } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_edge_}}, \code{\link{with_graph_}}, \code{\link{with_vertex_}}, \code{\link{without_attr}}, \code{\link{without_loops}} } \concept{constructor modifiers} igraph/man/is_printer_callback.Rd0000644000175100001440000000060413430770475016610 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/printr.R \name{is_printer_callback} \alias{is_printer_callback} \title{Is this a printer callback?} \usage{ is_printer_callback(x) } \arguments{ \item{x}{An R object.} } \description{ Is this a printer callback? } \seealso{ Other printer callbacks: \code{\link{printer_callback}} } \concept{printer callbacks} igraph/man/intersection.igraph.vs.Rd0000644000175100001440000000250613430770475017227 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{intersection.igraph.vs} \alias{intersection.igraph.vs} \title{Intersection of vertex sequences} \usage{ \method{intersection}{igraph.vs}(...) } \arguments{ \item{...}{The vertex sequences to take the intersection of.} } \value{ A vertex sequence that contains vertices that appear in all given sequences, each vertex exactly once. } \description{ Intersection of vertex sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of vertices is lost in the result. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/igraph-dollar.Rd0000644000175100001440000000235313430770475015346 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{igraph-dollar} \alias{igraph-dollar} \alias{$.igraph} \alias{$<-.igraph} \title{Getting and setting graph attributes, shortcut} \usage{ \method{$}{igraph}(x, name) \method{$}{igraph}(x, name) <- value } \arguments{ \item{x}{An igraph graph} \item{name}{Name of the attribute to get/set.} \item{value}{New value of the graph attribute.} } \description{ The \code{$} operator is a shortcut to get and and set graph attributes. It is shorter and just as readable as \code{\link{graph_attr}} and \code{\link{set_graph_attr}}. } \examples{ g <- make_ring(10) g$name g$name <- "10-ring" g$name } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/each_edge.Rd0000644000175100001440000000225413430770476014506 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rewire.R \name{each_edge} \alias{each_edge} \title{Rewires the endpoints of the edges of a graph to a random vertex} \usage{ each_edge(prob, loops = FALSE, multiple = FALSE) } \arguments{ \item{prob}{The rewiring probability, a real number between zero and one.} \item{loops}{Logical scalar, whether loop edges are allowed in the rewired graph.} \item{multiple}{Logical scalar, whether multiple edges are allowed int the generated graph.} } \description{ This function can be used together with \code{\link{rewire}}. This method rewires the endpoints of the edges with a constant probability uniformly randomly to a new vertex in a graph. } \details{ Note that this method might create graphs with multiple and/or loop edges. } \examples{ # Some random shortcuts shorten the distances on a lattice g <- make_lattice(length = 100, dim = 1, nei = 5) mean_distance(g) g <- rewire(g, each_edge(prob = 0.05)) mean_distance(g) } \seealso{ Other rewiring functions: \code{\link{keeping_degseq}}, \code{\link{rewire}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{rewiring functions} \keyword{graphs} igraph/man/igraph-attribute-combination.Rd0000644000175100001440000001144413430770475020375 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{igraph-attribute-combination} \alias{igraph-attribute-combination} \alias{attribute.combination} \title{How igraph functions handle attributes when the graph changes} \description{ Many times, when the structure of a graph is modified, vertices/edges map of the original graph map to vertices/edges in the newly created (modified) graph. For example \code{\link{simplify}} maps multiple edges to single edges. igraph provides a flexible mechanism to specify what to do with the vertex/edge attributes in these cases. } \details{ The functions that support the combination of attributes have one or two extra arguments called \code{vertex.attr.comb} and/or \code{edge.attr.comb} that specify how to perform the mapping of the attributes. E.g. \code{\link{contract}} contracts many vertices into a single one, the attributes of the vertices can be combined and stores as the vertex attributes of the new graph. The specification of the combination of (vertex or edge) attributes can be given as \enumerate{ \item a character scalar, \item a function object or \item a list of character scalars and/or function objects. } If it is a character scalar, then it refers to one of the predefined combinations, see their list below. If it is a function, then the given function is expected to perform the combination. It will be called once for each new vertex/edge in the graph, with a single argument: the attribute values of the vertices that map to that single vertex. The third option, a list can be used to specify different combination methods for different attributes. A named entry of the list corresponds to the attribute with the same name. An unnamed entry (i.e. if the name is the empty string) of the list specifies the default combination method. I.e. \preformatted{list(weight="sum", "ignore")} specifies that the weight of the new edge should be sum of the weights of the corresponding edges in the old graph; and that the rest of the attributes should be ignored (=dropped). } \section{Predefined combination functions}{ The following combination behaviors are predefined: \describe{ \item{"ignore"}{The attribute is ignored and dropped.} \item{"sum"}{The sum of the attributes is calculated. This does not work for character attributes and works for complex attributes only if they have a \code{sum} generic defined. (E.g. it works for sparse matrices from the \code{Matrix} package, because they have a \code{sum} method.)} \item{"prod"}{The product of the attributes is calculated. This does not work for character attributes and works for complex attributes only if they have a \code{prod} function defined.} \item{"min"}{The minimum of the attributes is calculated and returned. For character and complex attributes the standard R \code{min} function is used.} \item{"max"}{The maximum of the attributes is calculated and returned. For character and complex attributes the standard R \code{max} function is used.} \item{"random"}{Chooses one of the supplied attribute values, uniformly randomly. For character and complex attributes this is implemented by calling \code{sample}.} \item{"first"}{Always chooses the first attribute value. It is implemented by calling the \code{head} function.} \item{"last"}{Always chooses the last attribute value. It is implemented by calling the \code{tail} function.} \item{"mean"}{The mean of the attributes is calculated and returned. For character and complex attributes this simply calls the \code{mean} function.} \item{"median"}{The median of the attributes is selected. Calls the R \code{median} function for all attribute types.} \item{"concat"}{Concatenate the attributes, using the \code{c} function. This results almost always a complex attribute.} } } \examples{ g <- graph( c(1,2, 1,2, 1,2, 2,3, 3,4) ) E(g)$weight <- 1:5 ## print attribute values with the graph igraph_options(print.graph.attributes=TRUE) igraph_options(print.vertex.attributes=TRUE) igraph_options(print.edge.attributes=TRUE) ## new attribute is the sum of the old ones simplify(g, edge.attr.comb="sum") ## collect attributes into a string simplify(g, edge.attr.comb=toString) ## concatenate them into a vector, this creates a complex ## attribute simplify(g, edge.attr.comb="concat") E(g)$name <- letters[seq_len(ecount(g))] ## both attributes are collected into strings simplify(g, edge.attr.comb=toString) ## harmonic average of weights, names are dropped simplify(g, edge.attr.comb=list(weight=function(x) length(x)/sum(1/x), name="ignore")) } \seealso{ \code{\link{graph_attr}}, \code{\link{vertex_attr}}, \code{\link{edge_attr}} on how to use graph/vertex/edge attributes in general. \code{\link{igraph_options}} on igraph parameters. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_traits_callaway.Rd0000644000175100001440000000473413430770475017352 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_traits_callaway} \alias{sample_traits_callaway} \alias{sample_traits} \alias{callaway.traits.game} \alias{establishment.game} \alias{traits_callaway} \alias{traits} \title{Graph generation based on different vertex types} \usage{ sample_traits_callaway(nodes, types, edge.per.step = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE) traits_callaway(...) sample_traits(nodes, types, k = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE) traits(...) } \arguments{ \item{nodes}{The number of vertices in the graph.} \item{types}{The number of different vertex types.} \item{edge.per.step}{The number of edges to add to the graph per time step.} \item{type.dist}{The distribution of the vertex types. This is assumed to be stationary in time.} \item{pref.matrix}{A matrix giving the preferences of the given vertex types. These should be probabilities, ie. numbers between zero and one.} \item{directed}{Logical constant, whether to generate directed graphs.} \item{...}{Passed to the constructor, \code{sample_traits} or \code{sample_traits_callaway}.} \item{k}{The number of trials per time step, see details below.} } \value{ A new graph object. } \description{ These functions implement evolving network models based on different vertex types. } \details{ For \code{sample_traits_callaway} the simulation goes like this: in each discrete time step a new vertex is added to the graph. The type of this vertex is generated based on \code{type.dist}. Then two vertices are selected uniformly randomly from the graph. The probability that they will be connected depends on the types of these vertices and is taken from \code{pref.matrix}. Then another two vertices are selected and this is repeated \code{edges.per.step} times in each time step. For \code{sample_traits} the simulation goes like this: a single vertex is added at each time step. This new vertex tries to connect to \code{k} vertices in the graph. The probability that such a connection is realized depends on the types of the vertices involved and is taken from \code{pref.matrix}. } \examples{ # two types of vertices, they like only themselves g1 <- sample_traits_callaway(1000, 2, pref.matrix=matrix( c(1,0,0,1), nc=2)) g2 <- sample_traits(1000, 2, k=2, pref.matrix=matrix( c(1,0,0,1), nc=2)) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_with_mds.Rd0000644000175100001440000000527213430770475016037 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_mds} \alias{layout_with_mds} \alias{layout.mds} \alias{with_mds} \title{Graph layout by multidimensional scaling} \usage{ layout_with_mds(graph, dist = NULL, dim = 2, options = arpack_defaults) with_mds(...) } \arguments{ \item{graph}{The input graph.} \item{dist}{The distance matrix for the multidimensional scaling. If \code{NULL} (the default), then the unweighted shortest path matrix is used.} \item{dim}{\code{layout_with_mds} supports dimensions up to the number of nodes minus one, but only if the graph is connected; for unconnected graphs, the only possible values is 2. This is because \code{merge_coords} only works in 2D.} \item{options}{This is currently ignored, as ARPACK is not used any more for solving the eigenproblem} \item{...}{Passed to \code{layout_with_mds}.} } \value{ A numeric matrix with \code{dim} columns. } \description{ Multidimensional scaling of some distance matrix defined on the vertices of a graph. } \details{ \code{layout_with_mds} uses metric multidimensional scaling for generating the coordinates. Multidimensional scaling aims to place points from a higher dimensional space in a (typically) 2 dimensional plane, so that the distance between the points are kept as much as this is possible. By default igraph uses the shortest path matrix as the distances between the nodes, but the user can override this via the \code{dist} argument. This function generates the layout separately for each graph component and then merges them via \code{\link{merge_coords}}. } \examples{ g <- sample_gnp(100, 2/100) l <- layout_with_mds(g) plot(g, layout=l, vertex.label=NA, vertex.size=3) } \references{ Cox, T. F. and Cox, M. A. A. (2001) \emph{Multidimensional Scaling}. Second edition. Chapman and Hall. } \seealso{ \code{\link{layout}}, \code{\link{plot.igraph}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/igraph_version.Rd0000644000175100001440000000157113430770476015642 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/test.R \name{igraph_version} \alias{igraph_version} \alias{igraph.version} \title{Query igraph's version string} \usage{ igraph_version() } \value{ A character scalar, the igraph version string. } \description{ Queries igraph's original version string. See details below. } \details{ The igraph version string is the same as the version of the R package for all realeased igraph versions. For development versions and nightly builds, they might differ however. The reason for this is, that R package version numbers are not flexible enough to cover in-between releases versions, e.g. alpha and beta versions, release candidates, etc. } \examples{ ## Compare to the package version packageDescription("igraph")$Version igraph_version() } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sub-sub-.igraph.Rd0000644000175100001440000000620413430770475015526 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/indexing.R \name{[[.igraph} \alias{[[.igraph} \title{Query and manipulate a graph as it were an adjacency list} \usage{ \method{[[}{igraph}(x, i, j, from, to, ..., directed = TRUE, edges = FALSE, exact = TRUE) } \arguments{ \item{x}{The graph.} \item{i}{Index, integer, character or logical, see details below.} \item{j}{Index, integer, character or logical, see details below.} \item{from}{A numeric or character vector giving vertex ids or names. Together with the \code{to} argument, it can be used to query/set a sequence of edges. See details below. This argument cannot be present together with any of the \code{i} and \code{j} arguments and if it is present, then the \code{to} argument must be present as well.} \item{to}{A numeric or character vector giving vertex ids or names. Together with the \code{from} argument, it can be used to query/set a sequence of edges. See details below. This argument cannot be present together with any of the \code{i} and \code{j} arguments and if it is present, then the \code{from} argument must be present as well.} \item{...}{Additional arguments are not used currently.} \item{directed}{Logical scalar, whether to consider edge directions in directed graphs. It is ignored for undirected graphs.} \item{edges}{Logical scalar, whether to return edge ids.} \item{exact}{Ignored.} } \description{ Query and manipulate a graph as it were an adjacency list } \details{ The double bracket operator indexes the (imaginary) adjacency list of the graph. This can used for the following operations: \enumerate{ \item Querying the adjacent vertices for one or more vertices: \preformatted{ graph[[1:3,]] graph[[,1:3]]} The first form gives the successors, the second the predessors or the 1:3 vertices. (For undirected graphs they are equivalent.) \item Querying the incident edges for one or more vertices, if the \code{edges} argument is set to \code{TRUE}: \preformatted{ graph[[1:3, , edges=TRUE]] graph[[, 1:3, edges=TRUE]]} \item Querying the edge ids between two sets or vertices, if both indices are used. E.g. \preformatted{ graph[[v, w, edges=TRUE]]} gives the edge ids of all the edges that exist from vertices \eqn{v} to vertices \eqn{w}. } The alternative argument names \code{from} and \code{to} can be used instead of the usual \code{i} and \code{j}, to make the code more readable: \preformatted{ graph[[from = 1:3]] graph[[from = v, to = w, edges = TRUE]]} \sQuote{\code{[[}} operators allows logical indices and negative indices as well, with the usual R semantics. Vertex names are also supported, so instead of a numeric vertex id a vertex can also be given to \sQuote{\code{[}} and \sQuote{\code{[[}}. } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/c.igraph.vs.Rd0000644000175100001440000000233513430770475014743 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{c.igraph.vs} \alias{c.igraph.vs} \title{Concatenate vertex sequences} \usage{ \method{c}{igraph.vs}(..., recursive = FALSE) } \arguments{ \item{...}{The vertex sequences to concatenate. They must refer to the same graph.} \item{recursive}{Ignored, included for S3 compatibility with the base \code{c} function.} } \value{ A vertex sequence, the input sequences concatenated. } \description{ Concatenate vertex sequences } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(V(g)[1], V(g)['A'], V(g)[1:4]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/degree.Rd0000644000175100001440000000341213430770476014052 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{degree} \alias{degree} \alias{degree.distribution} \alias{degree_distribution} \title{Degree and degree distribution of the vertices} \usage{ degree(graph, v = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, normalized = FALSE) degree_distribution(graph, cumulative = FALSE, ...) } \arguments{ \item{graph}{The graph to analyze.} \item{v}{The ids of vertices of which the degree will be calculated.} \item{mode}{Character string, \dQuote{out} for out-degree, \dQuote{in} for in-degree or \dQuote{total} for the sum of the two. For undirected graphs this argument is ignored. \dQuote{all} is a synonym of \dQuote{total}.} \item{loops}{Logical; whether the loop edges are also counted.} \item{normalized}{Logical scalar, whether to normalize the degree. If \code{TRUE} then the result is divided by \eqn{n-1}, where \eqn{n} is the number of vertices in the graph.} \item{cumulative}{Logical; whether the cumulative degree distribution is to be calculated.} \item{\dots}{Additional arguments to pass to \code{degree}, eg. \code{mode} is useful but also \code{v} and \code{loops} make sense.} } \value{ For \code{degree} a numeric vector of the same length as argument \code{v}. For \code{degree_distribution} a numeric vector of the same length as the maximum degree plus one. The first element is the relative frequency zero degree vertices, the second vertices with degree one, etc. } \description{ The degree of a vertex is its most basic structural property, the number of its adjacent edges. } \examples{ g <- make_ring(10) degree(g) g2 <- sample_gnp(1000, 10/1000) degree_distribution(g2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/centr_betw.Rd0000644000175100001440000000344113430770475014754 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_betw} \alias{centr_betw} \alias{centralization.betweenness} \title{Centralize a graph according to the betweenness of vertices} \usage{ centr_betw(graph, directed = TRUE, nobigint = TRUE, normalized = TRUE) } \arguments{ \item{graph}{The input graph.} \item{directed}{logical scalar, whether to use directed shortest paths for calculating betweenness.} \item{nobigint}{Logical scalar, whether to use big integers for the betweenness calculation. This argument is passed to the \code{\link{betweenness}} function.} \item{normalized}{Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum.} } \value{ A named list with the following components: \item{res}{The node-level centrality scores.} \item{centralization}{The graph level centrality index.} \item{theoretical_max}{The maximum theoretical graph level centralization score for a graph with the given number of vertices, using the same parameters. If the \code{normalized} argument was \code{TRUE}, then the result was divided by this number.} } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/as_ids.Rd0000644000175100001440000000176413430770475014070 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{as_ids} \alias{as_ids} \alias{as_ids.igraph.vs} \alias{as_ids.igraph.es} \title{Convert a vertex or edge sequence to an ordinary vector} \usage{ as_ids(seq) \method{as_ids}{igraph.vs}(seq) \method{as_ids}{igraph.es}(seq) } \arguments{ \item{seq}{The vertex or edge sequence.} } \value{ A character or numeric vector, see details below. } \description{ Convert a vertex or edge sequence to an ordinary vector } \details{ For graphs without names, a numeric vector is returned, containing the internal numeric vertex or edge ids. For graphs with names, and vertex sequences, the vertex names are returned in a character vector. For graphs with names and edge sequences, a character vector is returned, with the \sQuote{bar} notation: \code{a|b} means an edge from vertex \code{a} to vertex \code{b}. } \examples{ g <- make_ring(10) as_ids(V(g)) as_ids(E(g)) V(g)$name <- letters[1:10] as_ids(V(g)) as_ids(E(g)) } igraph/man/read_graph.Rd0000644000175100001440000000362213430770475014715 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/foreign.R \name{read_graph} \alias{read_graph} \alias{read.graph} \alias{LGL} \alias{Pajek} \alias{GraphML} \alias{GML} \alias{DL} \alias{UCINET} \title{Reading foreign file formats} \usage{ read_graph(file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ...) } \arguments{ \item{file}{The connection to read from. This can be a local file, or a \code{http} or \code{ftp} connection. It can also be a character string with the file name or URI.} \item{format}{Character constant giving the file format. Right now \code{as_edgelist}, \code{pajek}, \code{graphml}, \code{gml}, \code{ncol}, \code{lgl}, \code{dimacs} and \code{graphdb} are supported, the default is \code{edgelist}. As of igraph 0.4 this argument is case insensitive.} \item{\dots}{Additional arguments, see below.} } \value{ A graph object. } \description{ The \code{read_graph} function is able to read graphs in various representations from a file, or from a http connection. Currently some simple formats are supported. } \details{ The \code{read_graph} function may have additional arguments depending on the file format (the \code{format} argument). See the details separately for each file format, below. } \section{Edge list format}{ This format is a simple text file with numeric vertex ids defining the edges. There is no need to have newline characters between the edges, a simple space will also do. Additional arguments: \describe{ \item{n}{The number of vertices in the graph. If it is smaller than or equal to the largest integer in the file, then it is ignored; so it is safe to set it to zero (the default).} \item{directed}{Logical scalar, whether to create a directed graph. The default value is \code{TRUE}.} } } \seealso{ \code{\link{write_graph}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/V.Rd0000644000175100001440000000450013430770475013022 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{V} \alias{V} \title{Vertices of a graph} \usage{ V(graph) } \arguments{ \item{graph}{The graph} } \value{ A vertex sequence containing all vertices, in the order of their numeric vertex ids. } \description{ Create a vertex sequence (vs) containing all vertices of a graph. } \details{ A vertex sequence is just what the name says it is: a sequence of vertices. Vertex sequences are usually used as igraph function arguments that refer to vertices of a graph. A vertex sequence is tied to the graph it refers to: it really denoted the specific vertices of that graph, and cannot be used together with another graph. At the implementation level, a vertex sequence is simply a vector containing numeric vertex ids, but it has a special class attribute which makes it possible to perform graph specific operations on it, like selecting a subset of the vertices based on graph structure, or vertex attributes. A vertex sequence is most often created by the \code{V()} function. The result of this includes all vertices in increasing vertex id order. A vertex sequence can be indexed by a numeric vector, just like a regular R vector. See \code{\link{[.igraph.vs}} and additional links to other vertex sequence operations below. } \section{Indexing vertex sequences}{ Vertex sequences mostly behave like regular vectors, but there are some additional indexing operations that are specific for them; e.g. selecting vertices based on graph structure, or based on vertex attributes. See \code{\link{[.igraph.vs}} for details. } \section{Querying or setting attributes}{ Vertex sequences can be used to query or set attributes for the vertices in the sequence. See \code{\link{$.igraph.vs}} for details. } \examples{ # Vertex ids of an unnamed graph g <- make_ring(10) V(g) # Vertex ids of a named graph g2 <- make_ring(10) \%>\% set_vertex_attr("name", value = letters[1:10]) V(g2) } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} } \concept{vertex and edge sequences} igraph/man/graph_from_isomorphism_class.Rd0000644000175100001440000000221613430770476020562 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{graph_from_isomorphism_class} \alias{graph_from_isomorphism_class} \alias{graph.isocreate} \title{Create a graph from an isomorphism class} \usage{ graph_from_isomorphism_class(size, number, directed = TRUE) } \arguments{ \item{size}{The number of vertices in the graph.} \item{number}{The isomorphism class.} \item{directed}{Whether to create a directed graph (the default).} } \value{ An igraph object, the graph of the given size, directedness and isomorphism class. } \description{ The isomorphism class is a non-negative integer number. Graphs (with the same number of vertices) having the same isomorphism class are isomorphic and isomorphic graphs always have the same isomorphism class. Currently it can handle only graphs with 3 or 4 vertices. } \seealso{ Other graph isomorphism: \code{\link{count_isomorphisms}}, \code{\link{count_subgraph_isomorphisms}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/sample_grg.Rd0000644000175100001440000000277313430770475014747 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_grg} \alias{sample_grg} \alias{grg.game} \alias{grg} \title{Geometric random graphs} \usage{ sample_grg(nodes, radius, torus = FALSE, coords = FALSE) grg(...) } \arguments{ \item{nodes}{The number of vertices in the graph.} \item{radius}{The radius within which the vertices will be connected by an edge.} \item{torus}{Logical constant, whether to use a torus instead of a square.} \item{coords}{Logical scalar, whether to add the positions of the vertices as vertex attributes called \sQuote{\code{x}} and \sQuote{\code{y}}.} \item{...}{Passed to \code{sample_grg}.} } \value{ A graph object. If \code{coords} is \code{TRUE} then with vertex attributes \sQuote{\code{x}} and \sQuote{\code{y}}. } \description{ Generate a random graph based on the distance of random point on a unit square } \details{ First a number of points are dropped on a unit square, these points correspond to the vertices of the graph to create. Two points will be connected with an undirected edge if they are closer to each other in Euclidean norm than a given radius. If the \code{torus} argument is \code{TRUE} then a unit area torus is used instead of a square. } \examples{ g <- sample_grg(1000, 0.05, torus=FALSE) g2 <- sample_grg(1000, 0.05, torus=TRUE) } \seealso{ \code{\link{sample_gnp}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com}, first version was written by Keith Briggs (\url{http://keithbriggs.info/}). } \keyword{graphs} igraph/man/is_dag.Rd0000644000175100001440000000137113430770475014046 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/paths.R \name{is_dag} \alias{is_dag} \alias{is.dag} \title{Directed acyclic graphs} \usage{ is_dag(graph) } \arguments{ \item{graph}{The input graph. It may be undirected, in which case \code{FALSE} is reported.} } \value{ A logical vector of length one. } \description{ This function tests whether the given graph is a DAG, a directed acyclic graph. } \details{ \code{is_dag} checks whether there is a directed cycle in the graph. If not, the graph is a DAG. } \examples{ g <- make_tree(10) is_dag(g) g2 <- g + edge(5,1) is_dag(g2) } \author{ Tamas Nepusz \email{ntamas@gmail.com} for the C code, Gabor Csardi \email{csardi.gabor@gmail.com} for the R interface. } \keyword{graphs} igraph/man/sample_sphere_volume.Rd0000644000175100001440000000254113430770475017036 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{sample_sphere_volume} \alias{sample_sphere_volume} \title{Sample vectors uniformly from the volume of a sphere} \usage{ sample_sphere_volume(dim, n = 1, radius = 1, positive = TRUE) } \arguments{ \item{dim}{Integer scalar, the dimension of the random vectors.} \item{n}{Integer scalar, the sample size.} \item{radius}{Numeric scalar, the radius of the sphere to sample.} \item{positive}{Logical scalar, whether to sample from the positive orthant of the sphere.} } \value{ A \code{dim} (length of the \code{alpha} vector for \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample vectors. } \description{ Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs } \details{ \code{sample_sphere_volume} generates uniform samples from \eqn{S^{dim-1}} (the \code{(dim-1)}-sphere) i.e. the Euclidean norm of the samples is smaller or equal to \code{radius}. } \examples{ lpvs.sph.vol <- sample_sphere_volume(dim=10, n=20, radius=1) RDP.graph.4 <- sample_dot_product(lpvs.sph.vol) vec.norm <- apply(lpvs.sph.vol, 2, function(x) { sum(x^2) }) vec.norm } \seealso{ Other latent position vector samplers: \code{\link{sample_dirichlet}}, \code{\link{sample_sphere_surface}} } \concept{latent position vector samplers} igraph/man/is_named.Rd0000644000175100001440000000216713430770475014403 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{is_named} \alias{is_named} \alias{is.named} \title{Named graphs} \usage{ is_named(graph) } \arguments{ \item{graph}{The input graph.} } \value{ A logical scalar. } \description{ An igraph graph is named, if there is a symbolic name associated with its vertices. } \details{ In igraph vertices can always be identified and specified via their numeric vertex ids. This is, however, not always convenient, and in many cases there exist symbolic ids that correspond to the vertices. To allow this more flexible identification of vertices, one can assign a vertex attribute called \sQuote{name} to an igraph graph. After doing this, the symbolic vertex names can be used in all igraph functions, instead of the numeric ids. Note that the uniqueness of vertex names are currently not enforced in igraph, you have to check that for yourself, when assigning the vertex names. } \examples{ g <- make_ring(10) is_named(g) V(g)$name <- letters[1:10] is_named(g) neighbors(g, "a") } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_with_lgl.Rd0000644000175100001440000000454213430770475016031 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_lgl} \alias{layout_with_lgl} \alias{with_lgl} \title{Large Graph Layout} \usage{ layout_with_lgl(graph, maxiter = 150, maxdelta = vcount(graph), area = vcount(graph)^2, coolexp = 1.5, repulserad = area * vcount(graph), cellsize = sqrt(sqrt(area)), root = NULL) with_lgl(...) } \arguments{ \item{graph}{The input graph} \item{maxiter}{The maximum number of iterations to perform (150).} \item{maxdelta}{The maximum change for a vertex during an iteration (the number of vertices).} \item{area}{The area of the surface on which the vertices are placed (square of the number of vertices).} \item{coolexp}{The cooling exponent of the simulated annealing (1.5).} \item{repulserad}{Cancellation radius for the repulsion (the \code{area} times the number of vertices).} \item{cellsize}{The size of the cells for the grid. When calculating the repulsion forces between vertices only vertices in the same or neighboring grid cells are taken into account (the fourth root of the number of \code{area}.} \item{root}{The id of the vertex to place at the middle of the layout. The default value is -1 which means that a random vertex is selected.} \item{...}{Passed to \code{layout_with_lgl}.} } \value{ A numeric matrix with two columns and as many rows as vertices. } \description{ A layout generator for larger graphs. } \details{ \code{layout_with_lgl} is for large connected graphs, it is similar to the layout generator of the Large Graph Layout software (\url{http://lgl.sourceforge.net/}). } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/which_mutual.Rd0000644000175100001440000000233413430770476015312 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{which_mutual} \alias{which_mutual} \alias{is.mutual} \title{Find mutual edges in a directed graph} \usage{ which_mutual(graph, es = E(graph)) } \arguments{ \item{graph}{The input graph.} \item{es}{Edge sequence, the edges that will be probed. By default is includes all edges in the order of their ids.} } \value{ A logical vector of the same length as the number of edges supplied. } \description{ This function checks the reciproc pair of the supplied edges. } \details{ In a directed graph an (A,B) edge is mutual if the graph also includes a (B,A) directed edge. Note that multi-graphs are not handled properly, i.e. if the graph contains two copies of (A,B) and one copy of (B,A), then these three edges are considered to be mutual. Undirected graphs contain only mutual edges by definition. } \examples{ g <- sample_gnm(10, 50, directed=TRUE) reciprocity(g) dyad_census(g) which_mutual(g) sum(which_mutual(g))/2 == dyad_census(g)$mut } \seealso{ \code{\link{reciprocity}}, \code{\link{dyad_census}} if you just want some statistics about mutual edges. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/pipe.Rd0000644000175100001440000000106513430770475013555 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/igraph-package.R \name{\%>\%} \alias{\%>\%} \title{Magrittr's pipes} \arguments{ \item{lhs}{Left hand side of the pipe.} \item{rhs}{Right hand side of the pipe.} } \value{ Result of applying the right hand side to the result of the left hand side. } \description{ igraph re-exports the \code{\%>\%} operator of magrittr, because we find it very useful. Please see the documentation in the \code{magrittr} package. } \examples{ make_ring(10) \%>\% add_edges(c(1,6)) \%>\% plot() } igraph/man/aaa-igraph-package.Rd0000644000175100001440000001623613430770475016211 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/igraph-package.R \docType{package} \name{igraph-package} \alias{igraph-package} \alias{igraph} \title{The igraph package} \description{ igraph is a library and R package for network analysis. } \section{Introduction}{ The main goals of the igraph library is to provide a set of data types and functions for 1) pain-free implementation of graph algorithms, 2) fast handling of large graphs, with millions of vertices and edges, 3) allowing rapid prototyping via high level languages like R. } \section{Igraph graphs}{ Igraph graphs have a class \sQuote{\code{igraph}}. They are printed to the screen in a special format, here is an example, a ring graph created using \code{\link{make_ring}}: \preformatted{ IGRAPH U--- 10 10 -- Ring graph + attr: name (g/c), mutual (g/x), circular (g/x) } \sQuote{\code{IGRAPH}} denotes that this is an igraph graph. Then come four bits that denote the kind of the graph: the first is \sQuote{\code{U}} for undirected and \sQuote{\code{D}} for directed graphs. The second is \sQuote{\code{N}} for named graph (i.e. if the graph has the \sQuote{\code{name}} vertex attribute set). The third is \sQuote{\code{W}} for weighted graphs (i.e. if the \sQuote{\code{weight}} edge attribute is set). The fourth is \sQuote{\code{B}} for bipartite graphs (i.e. if the \sQuote{\code{type}} vertex attribute is set). Then come two numbers, the number of vertices and the number of edges in the graph, and after a double dash, the name of the graph (the \sQuote{\code{name}} graph attribute) is printed if present. The second line is optional and it contains all the attributes of the graph. This graph has a \sQuote{\code{name}} graph attribute, of type character, and two other graph attributes called \sQuote{\code{mutual}} and \sQuote{\code{circular}}, of a complex type. A complex type is simply anything that is not numeric or character. See the documentation of \code{\link{print.igraph}} for details. If you want to see the edges of the graph as well, then use the \code{\link{print_all}} function: \preformatted{ > print_all(g) IGRAPH badcafe U--- 10 10 -- Ring graph + attr: name (g/c), mutual (g/x), circular (g/x) + edges: [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10 } } \section{Creating graphs}{ There are many functions in igraph for creating graphs, both deterministic and stochastic; stochastic graph constructors are called \sQuote{games}. To create small graphs with a given structure probably the \code{\link{graph_from_literal}} function is easiest. It uses R's formula interface, its manual page contains many examples. Another option is \code{\link{graph}}, which takes numeric vertex ids directly. \code{\link{graph.atlas}} creates graph from the Graph Atlas, \code{\link{make_graph}} can create some special graphs. To create graphs from field data, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_data_frame}} and \code{\link{graph_from_adjacency_matrix}} are probably the best choices. The igraph package includes some classic random graphs like the Erdos-Renyi GNP and GNM graphs (\code{\link{sample_gnp}}, \code{\link{sample_gnm}}) and some recent popular models, like preferential attachment (\code{\link{sample_pa}}) and the small-world model (\code{\link{sample_smallworld}}). } \section{Vertex and edge IDs}{ Vertices and edges have numerical vertex ids in igraph. Vertex ids are always consecutive and they start with one. I.e. for a graph with \eqn{n} vertices the vertex ids are between \eqn{1} and \eqn{n}. If some operation changes the number of vertices in the graphs, e.g. a subgraph is created via \code{\link{induced_subgraph}}, then the vertices are renumbered to satisfty this criteria. The same is true for the edges as well, edge ids are always between one and \eqn{m}, the total number of edges in the graph. It is often desirable to follow vertices along a number of graph operations, and vertex ids don't allow this because of the renumbering. The solution is to assign attributes to the vertices. These are kept by all operations, if possible. See more about attributes in the next section. } \section{Attributes}{ In igraph it is possible to assign attributes to the vertices or edges of a graph, or to the graph itself. igraph provides flexible constructs for selecting a set of vertices or edges based on their attribute values, see \code{\link{vertex_attr}}, \code{\link{V}} and \code{\link{E}} for details. Some vertex/edge/graph attributes are treated specially. One of them is the \sQuote{name} attribute. This is used for printing the graph instead of the numerical ids, if it exists. Vertex names can also be used to specify a vector or set of vertices, in all igraph functions. E.g. \code{\link{degree}} has a \code{v} argument that gives the vertices for which the degree is calculated. This argument can be given as a character vector of vertex names. Edges can also have a \sQuote{name} attribute, and this is treated specially as well. Just like for vertices, edges can also be selected based on their names, e.g. in the \code{\link{delete_edges}} and other functions. We note here, that vertex names can also be used to select edges. The form \sQuote{\code{from|to}}, where \sQuote{\code{from}} and \sQuote{\code{to}} are vertex names, select a single, possibly directed, edge going from \sQuote{\code{from}} to \sQuote{\code{to}}. The two forms can also be mixed in the same edge selector. Other attributes define visualization parameters, see \code{\link{igraph.plotting}} for details. Attribute values can be set to any R object, but note that storing the graph in some file formats might result the loss of complex attribute values. All attribute values are preserved if you use \code{\link[base]{save}} and \code{\link[base]{load}} to store/retrieve your graphs. } \section{Visualization}{ igraph provides three different ways for visualization. The first is the \code{\link{plot.igraph}} function. (Actually you don't need to write \code{plot.igraph}, \code{plot} is enough. This function uses regular R graphics and can be used with any R device. The second function is \code{\link{tkplot}}, which uses a Tk GUI for basic interactive graph manipulation. (Tk is quite resource hungry, so don't try this for very large graphs.) The third way requires the \code{rgl} package and uses OpenGL. See the \code{\link{rglplot}} function for the details. Make sure you read \code{\link{igraph.plotting}} before you start plotting your graphs. } \section{File formats}{ igraph can handle various graph file formats, usually both for reading and writing. We suggest that you use the GraphML file format for your graphs, except if the graphs are too big. For big graphs a simpler format is recommended. See \code{\link{read_graph}} and \code{\link{write_graph}} for details. } \section{Further information}{ The igraph homepage is at \url{http://igraph.org}. See especially the documentation section. Join the igraph-help mailing list if you have questions or comments. } igraph/man/sample_seq.Rd0000644000175100001440000000206213430770475014747 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/other.R \name{sample_seq} \alias{sample_seq} \alias{igraph.sample} \title{Sampling a random integer sequence} \usage{ sample_seq(low, high, length) } \arguments{ \item{low}{The lower limit of the interval (inclusive).} \item{high}{The higher limit of the interval (inclusive).} \item{length}{The length of the sample.} } \value{ An increasing numeric vector containing integers, the sample. } \description{ This function provides a very efficient way to pull an integer random sample sequence from an integer interval. } \details{ The algorithm runs in \code{O(length)} expected time, even if \code{high-low} is big. It is much faster (but of course less general) than the builtin \code{sample} function of R. } \examples{ rs <- sample_seq(1, 100000000, 10) rs } \references{ Jeffrey Scott Vitter: An Efficient Algorithm for Sequential Random Sampling, \emph{ACM Transactions on Mathematical Software}, 13/1, 58--67. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{datagen} igraph/man/gorder.Rd0000644000175100001440000000143113430770475014077 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{gorder} \alias{gorder} \alias{vcount} \title{Order (number of vertices) of a graph} \usage{ gorder(graph) } \arguments{ \item{graph}{The graph} } \value{ Number of vertices, numeric scalar. } \description{ Order (number of vertices) of a graph } \examples{ g <- make_ring(10) gorder(g) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/sample_dirichlet.Rd0000644000175100001440000000215113430770475016125 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{sample_dirichlet} \alias{sample_dirichlet} \title{Sample from a Dirichlet distribution} \usage{ sample_dirichlet(n, alpha) } \arguments{ \item{n}{Integer scalar, the sample size.} \item{alpha}{Numeric vector, the vector of \eqn{\alpha}{alpha} parameter for the Dirichlet distribution.} } \value{ A \code{dim} (length of the \code{alpha} vector for \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample vectors. } \description{ Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs } \details{ \code{sample_dirichlet} generates samples from the Dirichlet distribution with given \eqn{\alpha}{alpha} parameter. The sample is drawn from \code{length(alpha)-1}-simplex. } \examples{ lpvs.dir <- sample_dirichlet(n=20, alpha=rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) colSums(lpvs.dir) } \seealso{ Other latent position vector samplers: \code{\link{sample_sphere_surface}}, \code{\link{sample_sphere_volume}} } \concept{latent position vector samplers} igraph/man/match_vertices.Rd0000644000175100001440000000573613430770476015632 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/sgm.R \name{match_vertices} \alias{match_vertices} \alias{seeded.graph.match} \title{Match Graphs given a seeding of vertex correspondences} \usage{ match_vertices(A, B, m, start, iteration) } \arguments{ \item{A}{a numeric matrix, the adjacency matrix of the first graph} \item{B}{a numeric matrix, the adjacency matrix of the second graph} \item{m}{The number of seeds. The first \code{m} vertices of both graphs are matched.} \item{start}{a numeric matrix, the permutation matrix estimate is initialized with \code{start}} \item{iteration}{The number of iterations for the Frank-Wolfe algorithm} } \value{ A numeric matrix which is the permutation matrix that determines the bijection between the graphs of \code{A} and \code{B} } \description{ Given two adjacency matrices \code{A} and \code{B} of the same size, match the two graphs with the help of \code{m} seed vertex pairs which correspond to the first \code{m} rows (and columns) of the adjacency matrices. } \details{ The approximate graph matching problem is to find a bijection between the vertices of two graphs , such that the number of edge disagreements between the corresponding vertex pairs is minimized. For seeded graph matching, part of the bijection that consist of known correspondences (the seeds) is known and the problem task is to complete the bijection by estimating the permutation matrix that permutes the rows and columns of the adjacency matrix of the second graph. It is assumed that for the two supplied adjacency matrices \code{A} and \code{B}, both of size \eqn{n\times n}{n*n}, the first \eqn{m} rows(and columns) of \code{A} and \code{B} correspond to the same vertices in both graphs. That is, the \eqn{n \times n}{n*n} permutation matrix that defines the bijection is \eqn{I_{m} \bigoplus P} for a \eqn{(n-m)\times (n-m)}{(n-m)*(n-m)} permutation matrix \eqn{P} and \eqn{m} times \eqn{m} identity matrix \eqn{I_{m}}. The function \code{match_vertices} estimates the permutation matrix \eqn{P} via an optimization algorithm based on the Frank-Wolfe algorithm. See references for further details. } \examples{ #require(Matrix) g1 <- erdos.renyi.game(10, .1) randperm <- c(1:3, 3+sample(7)) g2 <- sample_correlated_gnp(g1, corr=1, p=g1$p, perm=randperm) A <- as.matrix(get.adjacency(g1)) B <- as.matrix(get.adjacency(g2)) P <-match_vertices (A, B, m=3, start=diag(rep(1, nrow(A)-3)), 20) P } \references{ Vogelstein, J. T., Conroy, J. M., Podrazik, L. J., Kratzer, S. G., Harley, E. T., Fishkind, D. E.,Vogelstein, R. J., Priebe, C. E. (2011). Fast Approximate Quadratic Programming for Large (Brain) Graph Matching. Online: \url{http://arxiv.org/abs/1112.5507} Fishkind, D. E., Adali, S., Priebe, C. E. (2012). Seeded Graph Matching Online: \url{http://arxiv.org/abs/1209.0367} } \seealso{ \code{\link{sample_correlated_gnp}},\code{\link{sample_correlated_gnp_pair}} } \author{ Vince Lyzinski \url{http://www.ams.jhu.edu/~lyzinski/} } \keyword{graphs} igraph/man/print.igraph.vs.Rd0000644000175100001440000000310013430770475015644 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{print.igraph.vs} \alias{print.igraph.vs} \title{Show a vertex sequence on the screen} \usage{ \method{print}{igraph.vs}(x, full = igraph_opt("print.full"), ...) } \arguments{ \item{x}{A vertex sequence.} \item{full}{Whether to show the full sequence, or truncate the output to the screen size.} \item{...}{These arguments are currently ignored.} } \value{ The vertex sequence, invisibly. } \description{ For long vertex sequences, the printing is truncated to fit to the screen. Use \code{print} explicitly and the \code{full} argument to see the full sequence. } \details{ Vertex sequence created with the double bracket operator are printed differently, together with all attributes of the vertices in the sequence, as a table. } \examples{ # Unnamed graphs g <- make_ring(10) V(g) # Named graphs g2 <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) V(g2) # All vertices in the sequence g3 <- make_ring(1000) V(g3) print(V(g3), full = TRUE) # Metadata g4 <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) \%>\% set_vertex_attr("color", value = "red") V(g4)[[]] V(g4)[[2:5, 7:8]] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}} } \concept{vertex and edge sequences} igraph/man/make_star.Rd0000644000175100001440000000255713430770475014575 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_star} \alias{make_star} \alias{graph.star} \alias{star} \title{Create a star graph, a tree with n vertices and n - 1 leaves} \usage{ make_star(n, mode = c("in", "out", "mutual", "undirected"), center = 1) star(...) } \arguments{ \item{n}{Number of vertices.} \item{mode}{It defines the direction of the edges, \code{in}: the edges point \emph{to} the center, \code{out}: the edges point \emph{from} the center, \code{mutual}: a directed star is created with mutual edges, \code{undirected}: the edges are undirected.} \item{center}{ID of the center vertex.} \item{...}{Passed to \code{make_star}.} } \value{ An igraph graph. } \description{ \code{star} creates a star graph, in this every single vertex is connected to the center vertex and nobody else. } \examples{ make_star(10, mode = "out") make_star(5, mode = "undirected") } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_tree}} } \concept{Star graph} \concept{determimistic constructors} igraph/man/bfs.Rd0000644000175100001440000001066313430770476013377 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{bfs} \alias{bfs} \alias{graph.bfs} \title{Breadth-first search} \usage{ bfs(graph, root, neimode = c("out", "in", "all", "total"), unreachable = TRUE, restricted = NULL, order = TRUE, rank = FALSE, father = FALSE, pred = FALSE, succ = FALSE, dist = FALSE, callback = NULL, extra = NULL, rho = parent.frame()) } \arguments{ \item{graph}{The input graph.} \item{root}{Numeric vector, usually of length one. The root vertex, or root vertices to start the search from.} \item{neimode}{For directed graphs specifies the type of edges to follow. \sQuote{out} follows outgoing, \sQuote{in} incoming edges. \sQuote{all} ignores edge directions completely. \sQuote{total} is a synonym for \sQuote{all}. This argument is ignored for undirected graphs.} \item{unreachable}{Logical scalar, whether the search should visit the vertices that are unreachable from the given root vertex (or vertices). If \code{TRUE}, then additional searches are performed until all vertices are visited.} \item{restricted}{\code{NULL} (=no restriction), or a vector of vertices (ids or symbolic names). In the latter case, the search is restricted to the given vertices.} \item{order}{Logical scalar, whether to return the ordering of the vertices.} \item{rank}{Logical scalar, whether to return the rank of the vertices.} \item{father}{Logical scalar, whether to return the father of the vertices.} \item{pred}{Logical scalar, whether to return the predecessors of the vertices.} \item{succ}{Logical scalar, whether to return the successors of the vertices.} \item{dist}{Logical scalar, whether to return the distance from the root of the search tree.} \item{callback}{If not \code{NULL}, then it must be callback function. This is called whenever a vertex is visited. See details below.} \item{extra}{Additional argument to supply to the callback function.} \item{rho}{The environment in which the callback function is evaluated.} } \value{ A named list with the following entries: \item{root}{Numeric scalar. The root vertex that was used as the starting point of the search.} \item{neimode}{Character scalar. The \code{neimode} argument of the function call. Note that for undirected graphs this is always \sQuote{all}, irrespectively of the supplied value.} \item{order}{Numeric vector. The vertex ids, in the order in which they were visited by the search.} \item{rank}{Numeric vector. The rank for each vertex.} \item{father}{Numeric vector. The father of each vertex, i.e. the vertex it was discovered from.} \item{pred}{Numeric vector. The previously visited vertex for each vertex, or 0 if there was no such vertex.} \item{succ}{Numeric vector. The next vertex that was visited after the current one, or 0 if there was no such vertex.} \item{dist}{Numeric vector, for each vertex its distance from the root of the search tree.} Note that \code{order}, \code{rank}, \code{father}, \code{pred}, \code{succ} and \code{dist} might be \code{NULL} if their corresponding argument is \code{FALSE}, i.e. if their calculation is not requested. } \description{ Breadth-first search is an algorithm to traverse a graph. We start from a root vertex and spread along every edge \dQuote{simultaneously}. } \details{ The callback function must have the following arguments: \describe{ \item{graph}{The input graph is passed to the callback function here.} \item{data}{A named numeric vector, with the following entries: \sQuote{vid}, the vertex that was just visited, \sQuote{pred}, its predecessor, \sQuote{succ}, its successor, \sQuote{rank}, the rank of the current vertex, \sQuote{dist}, its distance from the root of the search tree.} \item{extra}{The extra argument.} } See examples below on how to use the callback function. } \examples{ ## Two rings bfs(make_ring(10) \%du\% make_ring(10), root=1, "out", order=TRUE, rank=TRUE, father=TRUE, pred=TRUE, succ=TRUE, dist=TRUE) ## How to use a callback f <- function(graph, data, extra) { print(data) FALSE } tmp <- bfs(make_ring(10) \%du\% make_ring(10), root=1, "out", callback=f) ## How to use a callback to stop the search ## We stop after visiting all vertices in the initial component f <- function(graph, data, extra) { data['succ'] == -1 } bfs(make_ring(10) \%du\% make_ring(10), root=1, callback=f) } \seealso{ \code{\link{dfs}} for depth-first search. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/plot_dendrogram.igraphHRG.Rd0000644000175100001440000000735113430770475017616 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{plot_dendrogram.igraphHRG} \alias{plot_dendrogram.igraphHRG} \alias{hrg.dendrogram} \title{HRG dendrogram plot} \usage{ \method{plot_dendrogram}{igraphHRG}(x, mode = igraph_opt("dend.plot.type"), ...) } \arguments{ \item{x}{An \code{igraphHRG}, a hierarchical random graph, as returned by the \code{\link{fit_hrg}} function.} \item{mode}{Which dendrogram plotting function to use. See details below.} \item{\dots}{Additional arguments to supply to the dendrogram plotting function.} } \value{ Returns whatever the return value was from the plotting function, \code{plot.phylo}, \code{plot.dendrogram} or \code{plot.hclust}. } \description{ Plot a hierarchical random graph as a dendrogram. } \details{ \code{plot_dendrogram} supports three different plotting functions, selected via the \code{mode} argument. By default the plotting function is taken from the \code{dend.plot.type} igraph option, and it has for possible values: \itemize{ \item \code{auto} Choose automatically between the plotting functions. As \code{plot.phylo} is the most sophisticated, that is choosen, whenever the \code{ape} package is available. Otherwise \code{plot.hclust} is used. \item \code{phylo} Use \code{plot.phylo} from the \code{ape} package. \item \code{hclust} Use \code{plot.hclust} from the \code{stats} package. \item \code{dendrogram} Use \code{plot.dendrogram} from the \code{stats} package. } The different plotting functions take different sets of arguments. When using \code{plot.phylo} (\code{mode="phylo"}), we have the following syntax: \preformatted{ plot_dendrogram(x, mode="phylo", colbar = rainbow(11, start=0.7, end=0.1), edge.color = NULL, use.edge.length = FALSE, \dots) } The extra arguments not documented above: \itemize{ \item \code{colbar} Color bar for the edges. \item \code{edge.color} Edge colors. If \code{NULL}, then the \code{colbar} argument is used. \item \code{use.edge.length} Passed to \code{plot.phylo}. \item \code{dots} Attitional arguments to pass to \code{plot.phylo}. } The syntax for \code{plot.hclust} (\code{mode="hclust"}): \preformatted{ plot_dendrogram(x, mode="hclust", rect = 0, colbar = rainbow(rect), hang = 0.01, ann = FALSE, main = "", sub = "", xlab = "", ylab = "", \dots) } The extra arguments not documented above: \itemize{ \item \code{rect} A numeric scalar, the number of groups to mark on the dendrogram. The dendrogram is cut into exactly \code{rect} groups and they are marked via the \code{rect.hclust} command. Set this to zero if you don't want to mark any groups. \item \code{colbar} The colors of the rectanges that mark the vertex groups via the \code{rect} argument. \item \code{hang} Where to put the leaf nodes, this corresponds to the \code{hang} argument of \code{plot.hclust}. \item \code{ann} Whether to annotate the plot, the \code{ann} argument of \code{plot.hclust}. \item \code{main} The main title of the plot, the \code{main} argument of \code{plot.hclust}. \item \code{sub} The sub-title of the plot, the \code{sub} argument of \code{plot.hclust}. \item \code{xlab} The label on the horizontal axis, passed to \code{plot.hclust}. \item \code{ylab} The label on the vertical axis, passed to \code{plot.hclust}. \item \code{dots} Attitional arguments to pass to \code{plot.hclust}. } The syntax for \code{plot.dendrogram} (\code{mode="dendrogram"}): \preformatted{ plot_dendrogram(x, \dots) } The extra arguments are simply passed to \code{as.dendrogram}. } \examples{ g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) plot_dendrogram(hrg) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/closeness.Rd0000644000175100001440000000535013430770476014620 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{closeness} \alias{closeness} \alias{closeness.estimate} \alias{estimate_closeness} \title{Closeness centrality of vertices} \usage{ closeness(graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE) estimate_closeness(graph, vids = V(graph), mode = c("out", "in", "all", "total"), cutoff, weights = NULL, normalized = FALSE) } \arguments{ \item{graph}{The graph to analyze.} \item{vids}{The vertices for which closeness will be calculated.} \item{mode}{Character string, defined the types of the paths used for measuring the distance in directed graphs. \dQuote{in} measures the paths \emph{to} a vertex, \dQuote{out} measures paths \emph{from} a vertex, \emph{all} uses undirected paths. This argument is ignored for undirected graphs.} \item{weights}{Optional positive weight vector for calculating weighted closeness. If the graph has a \code{weight} edge attribute, then this is used by default. Weights are used for calculating weighted shortest paths, so they are interpreted as distances.} \item{normalized}{Logical scalar, whether to calculate the normalized closeness. Normalization is performed by multiplying the raw closeness by \eqn{n-1}, where \eqn{n} is the number of vertices in the graph.} \item{cutoff}{The maximum path length to consider when calculating the betweenness. If zero or negative then there is no such limit.} } \value{ Numeric vector with the closeness values of all the vertices in \code{v}. } \description{ Cloness centrality measures how many steps is required to access every other vertex from a given vertex. } \details{ The closeness centrality of a vertex is defined by the inverse of the average length of the shortest paths to/from all the other vertices in the graph: \deqn{\frac{1}{\sum_{i\ne v} d_vi}}{1/sum( d(v,i), i != v)} If there is no (directed) path between vertex \eqn{v}{\code{v}} and \eqn{i}{\code{i}} then the total number of vertices is used in the formula instead of the path length. \code{estimate_closeness} only considers paths of length \code{cutoff} or smaller, this can be run for larger graphs, as the running time is not quadratic (if \code{cutoff} is small). If \code{cutoff} is zero or negative then the function calculates the exact closeness scores. } \examples{ g <- make_ring(10) g2 <- make_star(10) closeness(g) closeness(g2, mode="in") closeness(g2, mode="out") closeness(g2, mode="all") } \references{ Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. \emph{Social Networks}, 1, 215-239. } \seealso{ \code{\link{betweenness}}, \code{\link{degree}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_de_bruijn_graph.Rd0000644000175100001440000000306613430770475016742 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_de_bruijn_graph} \alias{make_de_bruijn_graph} \alias{graph.de.bruijn} \alias{de_bruijn_graph} \title{De Bruijn graphs} \usage{ make_de_bruijn_graph(m, n) de_bruijn_graph(...) } \arguments{ \item{m}{Integer scalar, the size of the alphabet. See details below.} \item{n}{Integer scalar, the length of the labels. See details below.} \item{...}{Passed to \code{make_de_bruijn_graph}.} } \value{ A graph object. } \description{ De Bruijn graphs are labeled graphs representing the overlap of strings. } \details{ A de Bruijn graph represents relationships between strings. An alphabet of \code{m} letters are used and strings of length \code{n} are considered. A vertex corresponds to every possible string and there is a directed edge from vertex \code{v} to vertex \code{w} if the string of \code{v} can be transformed into the string of \code{w} by removing its first letter and appending a letter to it. Please note that the graph will have \code{m} to the power \code{n} vertices and even more edges, so probably you don't want to supply too big numbers for \code{m} and \code{n}. De Bruijn graphs have some interesting properties, please see another source, eg. Wikipedia for details. } \examples{ # de Bruijn graphs can be created recursively by line graphs as well g <- make_de_bruijn_graph(2,1) make_de_bruijn_graph(2,2) make_line_graph(g) } \seealso{ \code{\link{make_kautz_graph}}, \code{\link{make_line_graph}} } \author{ Gabor Csardi } \keyword{graphs} igraph/man/sample_last_cit.Rd0000644000175100001440000000363413430770475015767 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_last_cit} \alias{sample_last_cit} \alias{cited.type.game} \alias{sample_cit_types} \alias{citing.cited.type.game} \alias{sample_cit_cit_types} \alias{lastcit.game} \alias{last_cit} \alias{cit_types} \alias{cit_cit_types} \title{Random citation graphs} \usage{ sample_last_cit(n, edges = 1, agebins = n/7100, pref = (1:(agebins + 1))^-3, directed = TRUE) last_cit(...) sample_cit_types(n, edges = 1, types = rep(0, n), pref = rep(1, length(types)), directed = TRUE, attr = TRUE) cit_types(...) sample_cit_cit_types(n, edges = 1, types = rep(0, n), pref = matrix(1, nrow = length(types), ncol = length(types)), directed = TRUE, attr = TRUE) cit_cit_types(...) } \arguments{ \item{n}{Number of vertices.} \item{edges}{Number of edges per step.} \item{agebins}{Number of aging bins.} \item{pref}{Vector (\code{sample_last_cit} and \code{sample_cit_types} or matrix (\code{sample_cit_cit_types}) giving the (unnormalized) citation probabilities for the different vertex types.} \item{directed}{Logical scalar, whether to generate directed networks.} \item{...}{Passed to the actual constructor.} \item{types}{Vector of length \sQuote{\code{n}}, the types of the vertices. Types are numbered from zero.} \item{attr}{Logical scalar, whether to add the vertex types to the generated graph as a vertex attribute called \sQuote{\code{type}}.} } \value{ A new graph. } \description{ \code{sample_last_cit} creates a graph, where vertices age, and gain new connections based on how long ago their last citation happened. } \details{ \code{sample_cit_cit_types} is a stochastic block model where the graph is growing. \code{sample_cit_types} is similarly a growing stochastic block model, but the probability of an edge depends on the (potentiall) cited vertex only. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_sphere_surface.Rd0000644000175100001440000000254513430770475017163 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{sample_sphere_surface} \alias{sample_sphere_surface} \title{Sample vectors uniformly from the surface of a sphere} \usage{ sample_sphere_surface(dim, n = 1, radius = 1, positive = TRUE) } \arguments{ \item{dim}{Integer scalar, the dimension of the random vectors.} \item{n}{Integer scalar, the sample size.} \item{radius}{Numeric scalar, the radius of the sphere to sample.} \item{positive}{Logical scalar, whether to sample from the positive orthant of the sphere.} } \value{ A \code{dim} (length of the \code{alpha} vector for \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample vectors. } \description{ Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs } \details{ \code{sample_sphere_surface} generates uniform samples from \eqn{S^{dim-1}} (the \code{(dim-1)}-sphere) with radius \code{radius}, i.e. the Euclidean norm of the samples equal \code{radius}. } \examples{ lpvs.sph <- sample_sphere_surface(dim=10, n=20, radius=1) RDP.graph.3 <- sample_dot_product(lpvs.sph) vec.norm <- apply(lpvs.sph, 2, function(x) { sum(x^2) }) vec.norm } \seealso{ Other latent position vector samplers: \code{\link{sample_dirichlet}}, \code{\link{sample_sphere_volume}} } \concept{latent position vector samplers} igraph/man/random_walk.Rd0000644000175100001440000000275613430770475015126 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/random_walk.R \name{random_walk} \alias{random_walk} \title{Random walk on a graph} \usage{ random_walk(graph, start, steps, mode = c("out", "in", "all"), stuck = c("return", "error")) } \arguments{ \item{graph}{The input graph, might be undirected or directed.} \item{start}{The start vertex.} \item{steps}{The number of steps to make.} \item{mode}{How to follow directed edges. \code{"out"} steps along the edge direction, \code{"in"} is opposite to that. \code{"all"} ignores edge directions. This argument is ignored for undirected graphs.} \item{stuck}{What to do if the random walk gets stuck. \code{"return"} returns the partial walk, \code{"error"} raises an error.} } \value{ A vertex sequence containing the vertices along the walk. } \description{ Do a random walk. From the given start vertex, take the given number of steps, choosing an edge from the actual vertex uniformly randomly. Edge directions are observed in directed graphs (see the \code{mode} argument as well). Multiple and loop edges are also observed. } \examples{ ## Stationary distribution of a Markov chain g <- make_ring(10, directed = TRUE) \%u\% make_star(11, center = 11) + edge(11, 1) ec <- eigen_centrality(g, directed = TRUE)$vector pg <- page_rank(g, damping = 0.999)$vector w <- random_walk(g, start = 1, steps = 10000) ## These are similar, but not exactly the same cor(table(w), ec) ## But these are (almost) the same cor(table(w), pg) } igraph/man/make_.Rd0000644000175100001440000000262213430770475013674 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_} \alias{make_} \title{Make a new graph} \usage{ make_(...) } \arguments{ \item{...}{Parameters, see details below.} } \description{ This is is generic function for creating graphs. } \details{ \code{make_} is a generic function for creating graphs. For every graph constructor in igraph that has a \code{make_} prefix, there is a corresponding function without the prefix: e.g. for \code{\link{make_ring}} there is also \code{\link{ring}}, etc. The same is true for the random graph samplers, i.e. for each constructor with a \code{sample_} prefix, there is a corresponding function without that prefix. These shorter forms can be used together with \code{make_}. The advantage of this form is that the user can specify constructor modifiers which work with all constructors. E.g. the \code{link{with_vertex_}} modifier adds vertex attributes to the newly created graphs. See the examples and the various constructor modifiers below. } \examples{ r <- make_(ring(10)) l <- make_(lattice(c(3, 3, 3))) r2 <- make_(ring(10), with_vertex_(color = "red", name = LETTERS[1:10])) l2 <- make_(lattice(c(3, 3, 3)), with_edge_(weight = 2)) ran <- sample_(degseq(c(3,3,3,3,3,3), method = "simple"), simplified()) degree(ran) is_simple(ran) } \seealso{ simplified with_edge_ with_graph_ with_vertex_ without_loops without_multiples } igraph/man/vertex_attr-set.Rd0000644000175100001440000000273213430770475015762 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{vertex_attr<-} \alias{vertex_attr<-} \alias{vertex.attributes<-} \title{Set one or more vertex attributes} \usage{ vertex_attr(graph, name, index = V(graph)) <- value } \arguments{ \item{graph}{The graph.} \item{name}{The name of the vertex attribute to set. If missing, then \code{value} must be a named list, and its entries are set as vertex attributes.} \item{index}{An optional vertex sequence to set the attributes of a subset of vertices.} \item{value}{The new value of the attribute(s) for all (or \code{index}) vertices.} } \value{ The graph, with the vertex attribute(s) added or set. } \description{ Set one or more vertex attributes } \examples{ g <- make_ring(10) vertex_attr(g) <- list(name = LETTERS[1:10], color = rep("yellow", gorder(g))) vertex_attr(g, "label") <- V(g)$name g plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/tkigraph.Rd0000644000175100001440000000114713430770476014433 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/socnet.R \name{tkigraph} \alias{tkigraph} \title{Experimental basic igraph GUI} \usage{ tkigraph() } \value{ Returns \code{NULL}, invisibly. } \description{ This functions starts an experimental GUI to some igraph functions. The GUI was written in Tcl/Tk, so it is cross platform. } \details{ \code{tkigraph} has its own online help system, please see that for the details about how to use it. } \seealso{ \code{\link{tkplot}} for interactive plotting of graphs. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/split_join_distance.Rd0000644000175100001440000000314613430770475016646 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{split_join_distance} \alias{split_join_distance} \title{Split-join distance of two community structures} \usage{ split_join_distance(comm1, comm2) } \arguments{ \item{comm1}{The first community structure.} \item{comm2}{The second community structure.} } \value{ Two integer numbers, see details below. } \description{ The split-join distance between partitions A and B is the sum of the projection distance of A from B and the projection distance of B from A. The projection distance is an asymmetric measure and it is defined as follows: } \details{ First, each set in partition A is evaluated against all sets in partition B. For each set in partition A, the best matching set in partition B is found and the overlap size is calculated. (Matching is quantified by the size of the overlap between the two sets). Then, the maximal overlap sizes for each set in A are summed together and subtracted from the number of elements in A. The split-join distance will be returned as two numbers, the first is the projection distance of the first partition from the second, while the second number is the projection distance of the second partition from the first. This makes it easier to detect whether a partition is a subpartition of the other, since in this case, the corresponding distance will be zero. } \references{ van Dongen S: Performance criteria for graph clustering and Markov cluster experiments. Technical Report INS-R0012, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. } igraph/man/cliques.Rd0000644000175100001440000000661613430770475014274 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/cliques.R \name{cliques} \alias{cliques} \alias{largest_cliques} \alias{maximal.cliques} \alias{maximal.cliques.count} \alias{clique.number} \alias{clique_num} \alias{largest.cliques} \alias{count_max_cliques} \alias{max_cliques} \title{The functions find cliques, ie. complete subgraphs in a graph} \usage{ cliques(graph, min = NULL, max = NULL) max_cliques(graph, min = NULL, max = NULL, subset = NULL, file = NULL) } \arguments{ \item{graph}{The input graph, directed graphs will be considered as undirected ones, multiple edges and loops are ignored.} \item{min}{Numeric constant, lower limit on the size of the cliques to find. \code{NULL} means no limit, ie. it is the same as 0.} \item{max}{Numeric constant, upper limit on the size of the cliques to find. \code{NULL} means no limit.} \item{subset}{If not \code{NULL}, then it must be a vector of vertex ids, numeric or symbolic if the graph is named. The algorithm is run from these vertices only, so only a subset of all maximal cliques is returned. See the Eppstein paper for details. This argument makes it possible to easily parallelize the finding of maximal cliques.} \item{file}{If not \code{NULL}, then it must be a file name, i.e. a character scalar. The output of the algorithm is written to this file. (If it exists, then it will be overwritten.) Each clique will be a separate line in the file, given with the numeric ids of its vertices, separated by whitespace.} } \value{ \code{cliques}, \code{largest_cliques} and \code{clique_num} return a list containing numeric vectors of vertex ids. Each list element is a clique. \code{max_cliques} returns \code{NULL}, invisibly, if its \code{file} argument is not \code{NULL}. The output is written to the specified file in this case. \code{clique_num} and \code{count_max_cliques} return an integer scalar. } \description{ These functions find all, the largest or all the maximal cliques in an undirected graph. The size of the largest clique can also be calculated. } \details{ \code{cliques} find all complete subgraphs in the input graph, obeying the size limitations given in the \code{min} and \code{max} arguments. \code{largest_cliques} finds all largest cliques in the input graph. A clique is largest if there is no other clique including more vertices. \code{max_cliques} finds all maximal cliques in the input graph. A clique in maximal if it cannot be extended to a larger clique. The largest cliques are always maximal, but a maximal clique is not neccessarily the largest. \code{count_max_cliques} counts the maximal cliques. \code{clique_num} calculates the size of the largest clique(s). The current implementation of these functions searches for maximal independent vertex sets (see \code{\link{ivs}}) in the complementer graph. } \examples{ # this usually contains cliques of size six g <- sample_gnp(100, 0.3) clique_num(g) cliques(g, min=6) largest_cliques(g) # To have a bit less maximal cliques, about 100-200 usually g <- sample_gnp(100, 0.03) max_cliques(g) } \references{ For maximal cliques the following algorithm is implemented: David Eppstein, Maarten Loffler, Darren Strash: Listing All Maximal Cliques in Sparse Graphs in Near-optimal Time. \url{http://arxiv.org/abs/1006.5440} } \seealso{ \code{\link{ivs}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/without_attr.Rd0000644000175100001440000000115013430770475015350 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{without_attr} \alias{without_attr} \title{Construtor modifier to remove all attributes from a graph} \usage{ without_attr() } \description{ Construtor modifier to remove all attributes from a graph } \examples{ g1 <- make_ring(10) g1 g2 <- make_(ring(10), without_attr()) g2 } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_edge_}}, \code{\link{with_graph_}}, \code{\link{with_vertex_}}, \code{\link{without_loops}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/edge_attr.Rd0000644000175100001440000000256713430770475014566 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{edge_attr} \alias{edge_attr} \alias{get.edge.attribute} \alias{edge.attributes} \title{Query edge attributes of a graph} \usage{ edge_attr(graph, name, index = E(graph)) } \arguments{ \item{graph}{The graph} \item{name}{The name of the attribute to query. If missing, then all edge attributes are returned in a list.} \item{index}{An optional edge sequence, to query edge attributes for a subset of edges.} } \value{ The value of the edge attribute, or the list of all edge attributes if \code{name} is missing. } \description{ Query edge attributes of a graph } \examples{ g <- make_ring(10) \%>\% set_edge_attr("weight", value = 1:10) \%>\% set_edge_attr("color", value = "red") g plot(g, edge.width = E(g)$weight) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/as_adj_list.Rd0000644000175100001440000000251213430770475015072 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_adj_list} \alias{as_adj_list} \alias{get.adjedgelist} \alias{as_adj_edge_list} \alias{get.adjlist} \title{Adjacency lists} \usage{ as_adj_list(graph, mode = c("all", "out", "in", "total")) as_adj_edge_list(graph, mode = c("all", "out", "in", "total")) } \arguments{ \item{graph}{The input graph.} \item{mode}{Character scalar, it gives what kind of adjacent edges/vertices to include in the lists. \sQuote{\code{out}} is for outgoing edges/vertices, \sQuote{\code{in}} is for incoming edges/vertices, \sQuote{\code{all}} is for both. This argument is ignored for undirected graphs.} } \value{ A list of numeric vectors. } \description{ Create adjacency lists from a graph, either for adjacent edges or for neighboring vertices } \details{ \code{as_adj_list} returns a list of numeric vectors, which include the ids of neighbor vertices (according to the \code{mode} argument) of all vertices. \code{as_adj_edge_list} returns a list of numeric vectors, which include the ids of adjacent edgs (according to the \code{mode} argument) of all vertices. } \examples{ g <- make_ring(10) as_adj_list(g) as_adj_edge_list(g) } \seealso{ \code{\link{as_edgelist}}, \code{\link{as_adj}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/printer_callback.Rd0000644000175100001440000000213513430770475016116 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/printr.R \name{printer_callback} \alias{printer_callback} \title{Create a printer callback function} \usage{ printer_callback(fun) } \arguments{ \item{fun}{The function to use as a printer callback function.} } \description{ A printer callback fucntion is a function can performs the actual printing. It has a number of subcommands, that are called by the \code{printer} package, in a form \preformatted{ printer_callback("subcommand", argument1, argument2, ...) } See the examples below. } \details{ The subcommands: \describe{ \item{\code{length}}{The length of the data to print, the number of items, in natural units. E.g. for a list of objects, it is the number of objects.} \item{\code{min_width}}{TODO} \item{\code{width}}{Width of one item, if \code{no} items will be printed. TODO} \item{\code{print}}{Argument: \code{no}. Do the actual printing, print \code{no} items.} \item{\code{done}}{TODO} } } \seealso{ Other printer callbacks: \code{\link{is_printer_callback}} } \concept{printer callbacks} igraph/man/centr_eigen.Rd0000644000175100001440000000416413430770475015105 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_eigen} \alias{centr_eigen} \alias{centralization.evcent} \title{Centralize a graph according to the eigenvector centrality of vertices} \usage{ centr_eigen(graph, directed = FALSE, scale = TRUE, options = arpack_defaults, normalized = TRUE) } \arguments{ \item{graph}{The input graph.} \item{directed}{logical scalar, whether to use directed shortest paths for calculating eigenvector centrality.} \item{scale}{Whether to rescale the eigenvector centrality scores, such that the maximum score is one.} \item{options}{This is passed to \code{\link{eigen_centrality}}, the options for the ARPACK eigensolver.} \item{normalized}{Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum.} } \value{ A named list with the following components: \item{vector}{The node-level centrality scores.} \item{value}{The corresponding eigenvalue.} \item{options}{ARPACK options, see the return value of \code{\link{eigen_centrality}} for details.} \item{centralization}{The graph level centrality index.} \item{theoretical_max}{The same as above, the theoretical maximum centralization score for a graph with the same number of vertices.} } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization # The most centralized graph according to eigenvector centrality g0 <- make_graph(c(2,1), n = 10, dir = FALSE) g1 <- make_star(10, mode = "undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/with_vertex_.Rd0000644000175100001440000000132513430770475015326 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{with_vertex_} \alias{with_vertex_} \title{Constructor modifier to add vertex attributes} \usage{ with_vertex_(...) } \arguments{ \item{...}{The attributes to add. They must be named.} } \description{ Constructor modifier to add vertex attributes } \examples{ make_(ring(10), with_vertex_( color = "#7fcdbb", frame.color = "#7fcdbb", name = LETTERS[1:10])) \%>\% plot() } \seealso{ Other constructor modifiers: \code{\link{simplified}}, \code{\link{with_edge_}}, \code{\link{with_graph_}}, \code{\link{without_attr}}, \code{\link{without_loops}}, \code{\link{without_multiples}} } \concept{constructor modifiers} igraph/man/difference.Rd0000644000175100001440000000130513430770475014707 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{difference} \alias{difference} \title{Difference of two sets} \usage{ difference(...) } \arguments{ \item{...}{Arguments, their number and interpretation depends on the function that implements \code{difference}.} } \value{ Depends on the function that implements this method. } \description{ This is an S3 generic function. See \code{methods("difference")} for the actual implementations for various S3 classes. Initially it is implemented for igraph graphs (difference of edges in two graphs), and igraph vertex and edge sequences. See \code{\link{difference.igraph}}, and \code{\link{difference.igraph.vs}}. } igraph/man/rep.igraph.Rd0000644000175100001440000000133213430770475014654 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{rep.igraph} \alias{rep.igraph} \alias{*.igraph} \title{Replicate a graph multiple times} \usage{ \method{rep}{igraph}(x, n, mark = TRUE, ...) \method{*}{igraph}(x, n) } \arguments{ \item{x}{The input graph.} \item{n}{Number of times to replicate it.} \item{mark}{Whether to mark the vertices with a \code{which} attribute, an integer number denoting which replication the vertex is coming from.} \item{...}{Additional arguments to satisfy S3 requirements, currently ignored.} } \description{ The new graph will contain the input graph the given number of times, as unconnected components. } \examples{ rings <- make_ring(5) * 5 } igraph/man/delete_graph_attr.Rd0000644000175100001440000000212213430770475016270 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{delete_graph_attr} \alias{delete_graph_attr} \alias{remove.graph.attribute} \title{Delete a graph attribute} \usage{ delete_graph_attr(graph, name) } \arguments{ \item{graph}{The graph.} \item{name}{Name of the attribute to delete.} } \value{ The graph, with the specified attribute removed. } \description{ Delete a graph attribute } \examples{ g <- make_ring(10) graph_attr_names(g) g2 <- delete_graph_attr(g, "name") graph_attr_names(g2) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/unique.igraph.es.Rd0000644000175100001440000000252713430770475016011 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{unique.igraph.es} \alias{unique.igraph.es} \title{Remove duplicate edges from an edge sequence} \usage{ \method{unique}{igraph.es}(x, incomparables = FALSE, ...) } \arguments{ \item{x}{An edge sequence.} \item{incomparables}{a vector of values that cannot be compared. Passed to base function \code{duplicated}. See details there.} \item{...}{Passed to base function \code{duplicated()}.} } \value{ An edge sequence with the duplicate vertices removed. } \description{ Remove duplicate edges from an edge sequence } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g)[1, 1:5, 1:10, 5:10] E(g)[1, 1:5, 1:10, 5:10] \%>\% unique() } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/vertex.shape.pie.Rd0000644000175100001440000000323313424602743016002 0ustar hornikusers\name{Pie charts as vertices} \alias{vertex.shape.pie} \concept{Vertex shapes} \title{Using pie charts as vertices in graph plots} \description{ More complex vertex images can be used to express addtional information about vertices. E.g. pie charts can be used as vertices, to denote vertex classes, fuzzy classification of vertices, etc. } \details{ The vertex shape \sQuote{pie} makes igraph draw a pie chart for every vertex. There are some extra graphical vertex parameters that specify how the pie charts will look like: \describe{ \item{pie}{Numeric vector, gives the sizes of the pie slices.} \item{pie.color}{A list of color vectors to use for the pies. If it is a list of a single vector, then this is used for all pies. It the color vector is shorter than the number of areas in a pie, then it is recycled.} \item{pie.border}{The color of the border line of the pie charts, in the same format as \code{pie.color}.} \item{pie.angle}{The slope of shading lines, given as an angle in degrees (counter-clockwise).} \item{pie.density}{The density of the shading lines, in lines per inch. Non-positive values inhibit the drawing of shading lines.} \item{pie.lty}{The line type of the border of the slices.} } } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \seealso{ \code{\link{igraph.plotting}}, \code{\link{plot.igraph}} } \examples{ g <- make_ring(10) values <- lapply(1:10, function(x) sample(1:10,3)) if (interactive()) { plot(g, vertex.shape="pie", vertex.pie=values, vertex.pie.color=list(heat.colors(5)), vertex.size=seq(10,30,length=10), vertex.label=NA) } } \keyword{graphs} igraph/man/centralize.Rd0000644000175100001440000000542113430770475014760 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centralize} \alias{centralize} \alias{centralization} \alias{centralize.scores} \title{Centralization of a graph} \usage{ centralize(scores, theoretical.max = 0, normalized = TRUE) } \arguments{ \item{scores}{The vertex level centrality scores.} \item{theoretical.max}{Real scalar. The graph level centrality score of the most centralized graph with the same number of vertices as the graph under study. This is only used if the \code{normalized} argument is set to \code{TRUE}.} \item{normalized}{Logical scalar. Whether to normalize the graph level centrality score by dividing by the supplied theoretical maximum.} } \value{ A real scalar, the centralization of the graph from which \code{scores} were derived. } \description{ Centralization is a method for creating a graph level centralization measure from the centrality scores of the vertices. } \details{ Centralization is a general method for calculating a graph-level centrality score based on node-level centrality measure. The formula for this is \deqn{C(G)=\sum_v (\max_w c_w - c_v),}{ C(G)=sum( max(c(w), w) - c(v),v),} where \eqn{c_v}{c(v)} is the centrality of vertex \eqn{v}. The graph-level centrality score can be normalized by dividing by the maximum theoretical score for a graph with the same number of vertices, using the same parameters, e.g. directedness, whether we consider loop edges, etc. For degree, closeness and betweenness the most centralized structure is some version of the star graph, in-star, out-star or undirected star. For eigenvector centrality the most centralized structure is the graph with a single edge (and potentially many isolates). \code{centralize} implements general centralization formula to calculate a graph-level score from vertex-level scores. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m=4) centr_degree(g)$centralization centr_clo(g, mode="all")$centralization centr_eigen(g, directed=FALSE)$centralization # The most centralized graph according to eigenvector centrality g0 <- graph( c(2,1), n=10, dir=FALSE ) g1 <- make_star(10, mode="undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization } \references{ Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. \emph{Social Networks} 1, 215--239. Wasserman, S., and Faust, K. (1994). \emph{Social Network Analysis: Methods and Applications.} Cambridge University Press. } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}} } \concept{centralization related} igraph/man/scg_eps.Rd0000644000175100001440000000370213430770476014244 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{scg_eps} \alias{scg_eps} \alias{scgNormEps} \title{Error of the spectral coarse graining (SCG) approximation} \usage{ scg_eps(V, groups, mtype = c("symmetric", "laplacian", "stochastic"), p = NULL, norm = c("row", "col")) } \arguments{ \item{V}{A numeric matrix of (eigen)vectors assumed normalized. The vectors are to be stored column-wise in \code{V}).} \item{groups}{A vector of \code{nrow(V)} integers labeling each group vertex in the partition.} \item{mtype}{The type of semi-projector used for the SCG. For now \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are available.} \item{p}{A probability vector of length \code{nrow(V)}. \code{p} is the stationary probability distribution of a Markov chain when \code{mtype} = \dQuote{stochastic}. This parameter is ignored otherwise.} \item{norm}{Either \dQuote{row} or \dQuote{col}. If set to \dQuote{row} the rows of the Laplacian matrix sum to zero and the rows of the stochastic matrix sum to one; otherwise it is the columns.} } \value{ \code{scg_eps} returns with a numeric vector whose \eqn{i}th component is \eqn{\Vert v_i-Pv_i\Vert}{|v[i]-Pv[i]|} (see Details). } \description{ \code{scg_eps} computes \eqn{\Vert v_i-Pv_i\Vert}{|v[i]-Pv[i]|}, where \eqn{v_i}{v[i]} is the \eqn{i}th eigenvector in \code{V} and \eqn{P} is the projector corresponding to the \code{mtype} argument. } \examples{ v <- rexp(20) km <- kmeans(v,5) sum(km$withinss) scg_eps(cbind(v), km$cluster)^2 } \references{ D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, Shrinking Matrices while Preserving their Eigenpairs with Application to the Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on Matrix Analysis and Applications}, 2008. \url{http://people.epfl.ch/david.morton} } \seealso{ \link{scg-method} and \code{\link{scg}}. } \author{ David Morton de Lachapelle, \url{http://people.epfl.ch/david.morton}. } igraph/man/intersection.igraph.es.Rd0000644000175100001440000000246713430770475017214 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{intersection.igraph.es} \alias{intersection.igraph.es} \title{Intersection of edge sequences} \usage{ \method{intersection}{igraph.es}(...) } \arguments{ \item{...}{The edge sequences to take the intersection of.} } \value{ An edge sequence that contains edges that appear in all given sequences, each edge exactly once. } \description{ Intersection of edge sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of edges is lost in the result. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9]) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/sample_hrg.Rd0000644000175100001440000000133713430770475014743 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{sample_hrg} \alias{sample_hrg} \alias{hrg.game} \title{Sample from a hierarchical random graph model} \usage{ sample_hrg(hrg) } \arguments{ \item{hrg}{A hierarchical random graph model.} } \value{ An igraph graph. } \description{ \code{sample_hrg} samples a graph from a given hierarchical random graph model. } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}} } \concept{hierarchical random graph functions} igraph/man/scg_semi_proj.Rd0000644000175100001440000000761313430770476015451 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{scg_semi_proj} \alias{scg_semi_proj} \alias{scgSemiProjectors} \title{Semi-Projectors} \usage{ scg_semi_proj(groups, mtype = c("symmetric", "laplacian", "stochastic"), p = NULL, norm = c("row", "col"), sparse = igraph_opt("sparsematrices")) } \arguments{ \item{groups}{A vector of \code{nrow(X)} or \code{vcount(X)} integers giving the group label of every vertex in the partition.} \item{mtype}{The type of semi-projectors. For now \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are available.} \item{p}{A probability vector of length \code{length(gr)}. \code{p} is the stationary probability distribution of a Markov chain when \code{mtype} = \dQuote{stochastic}. This parameter is ignored in all other cases.} \item{norm}{Either \dQuote{row} or \dQuote{col}. If set to \dQuote{row} the rows of the Laplacian matrix sum up to zero and the rows of the stochastic sum up to one; otherwise it is the columns.} \item{sparse}{Logical scalar, whether to return sparse matrices.} } \value{ \item{L}{The semi-projector \eqn{L}.} \item{R}{The semi-projector \eqn{R}.} } \description{ A function to compute the \eqn{L} and \eqn{R} semi-projectors for a given partition of the vertices. } \details{ The three types of semi-projectors are defined as follows. Let \eqn{\gamma(j)}{gamma(j)} label the group of vertex \eqn{j} in a partition of all the vertices. The symmetric semi-projectors are defined as \deqn{L_{\alpha j}=R_{\alpha j}= }{% L[alpha,j] = R[alpha,j] = 1/sqrt(|alpha|) delta[alpha,gamma(j)],}\deqn{ \frac{1}{\sqrt{|\alpha|}}\delta_{\alpha\gamma(j)},}{% L[alpha,j] = R[alpha,j] = 1/sqrt(|alpha|) delta[alpha,gamma(j)],} the (row) Laplacian semi-projectors as \deqn{L_{\alpha j}=\frac{1}{|\alpha|}\delta_{\alpha\gamma(j)}\,\,\,\, }{% L[alpha,j] = 1/|alpha| delta[alpha,gamma(j)] and R[alpha,j] = delta[alpha,gamma(j)],}\deqn{ \textrm{and}\,\,\,\, R_{\alpha j}=\delta_{\alpha\gamma(j)},}{% L[alpha,j] = 1/|alpha| delta[alpha,gamma(j)] and R[alpha,j] = delta[alpha,gamma(j)],} and the (row) stochastic semi-projectors as \deqn{L_{\alpha j}=\frac{p_{1}(j)}{\sum_{k\in\gamma(j)}p_{1}(k)}\,\,\,\, }{% L[alpha,j] = p[1][j] / sum(p[1][k]; k in gamma(j)) delta[alpha,gamma(j)] and R[alpha,j] = delta[alpha,gamma(j)],}\deqn{ \textrm{and}\,\,\,\, R_{\alpha j}=\delta_{\alpha\gamma(j)\delta_{\alpha\gamma(j)}},}{% L[alpha,j] = p[1][j] / sum(p[1][k]; k in gamma(j)) delta[alpha,gamma(j)] and R[alpha,j] = delta[alpha,gamma(j)],} where \eqn{p_1}{p[1]} is the (left) eigenvector associated with the one-eigenvalue of the stochastic matrix. \eqn{L} and \eqn{R} are defined in a symmetric way when \code{norm = col}. All these semi-projectors verify various properties described in the reference. } \examples{ library(Matrix) # compute the semi-projectors and projector for the partition # provided by a community detection method g <- sample_pa(20, m = 1.5, directed = FALSE) eb <- cluster_edge_betweenness(g) memb <- membership(eb) lr <- scg_semi_proj(memb) #In the symmetric case L = R tcrossprod(lr$R) # same as lr$R \%*\% t(lr$R) P <- crossprod(lr$R) # same as t(lr$R) \%*\% lr$R #P is an orthogonal projector isSymmetric(P) sum( (P \%*\% P-P)^2 ) ## use L and R to coarse-grain the graph Laplacian lr <- scg_semi_proj(memb, mtype="laplacian") L <- laplacian_matrix(g) Lt <- lr$L \%*\% L \%*\% t(lr$R) ## or better lr$L \%*\% tcrossprod(L,lr$R) rowSums(Lt) } \references{ D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, Shrinking Matrices while Preserving their Eigenpairs with Application to the Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on Matrix Analysis and Applications}, 2008. \url{http://people.epfl.ch/david.morton} } \seealso{ \link{scg-method} for a detailed introduction. \code{\link{scg}}, \code{\link{scg_eps}}, \code{\link{scg_group}} } \author{ David Morton de Lachapelle, \url{http://people.epfl.ch/david.morton}. } igraph/man/graph_.Rd0000644000175100001440000000073513430770475014063 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{graph_} \alias{graph_} \title{Convert object to a graph} \usage{ graph_(...) } \arguments{ \item{...}{Parameters, see details below.} } \description{ This is a generic function to convert R objects to igraph graphs. } \details{ TODO } \examples{ ## These are equivalent graph_(cbind(1:5,2:6), from_edgelist(directed = FALSE)) graph_(cbind(1:5,2:6), from_edgelist(), directed = FALSE) } igraph/man/is_separator.Rd0000644000175100001440000000176513430770475015322 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{is_separator} \alias{is_separator} \alias{is.separator} \title{Vertex separators} \usage{ is_separator(graph, candidate) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored.} \item{candidate}{A numeric vector giving the vertex ids of the candidate separator.} } \value{ A logical scalar, whether the supplied vertex set is a (minimal) vertex separator or not. } \description{ Check whether a given set of vertices is a vertex separator. } \details{ \code{is_separator} decides whether the supplied vertex set is a vertex separator. A vertex set is a vertex separator if its removal results a disconnected graph. In the special case of a fully connected graph with \eqn{n} vertices, each set of \eqn{n-1} vertices is considered to be a vertex separator. } \seealso{ \code{\link{is_min_separator}}, \code{\link{min_separators}} lists all vertex separator of minimum size. } igraph/man/is_graphical.Rd0000644000175100001440000000261313430770475015245 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/degseq.R \name{is_graphical} \alias{is_graphical} \alias{is.graphical.degree.sequence} \title{Is a degree sequence graphical?} \usage{ is_graphical(out.deg, in.deg = NULL) } \arguments{ \item{out.deg}{Integer vector, the degree sequence for undirected graphs, or the out-degree sequence for directed graphs.} \item{in.deg}{\code{NULL} or an integer vector. For undireted graphs, it should be \code{NULL}. For directed graphs it specifies the in-degrees.} } \value{ A logical scalar. } \description{ Determine whether the given vertex degrees (in- and out-degrees for directed graphs) can be reliazed in a simple graph, i.e. a graph without multiple or loop edges. } \references{ Hakimi SL: On the realizability of a set of integers as degrees of the vertices of a simple graph. \emph{J SIAM Appl Math} 10:496-506, 1962. PL Erdos, I Miklos and Z Toroczkai: A simple Havel-Hakimi type algorithm to realize graphical degree sequences of directed graphs. \emph{The Electronic Journal of Combinatorics} 17(1):R66, 2010. } \seealso{ Other graphical degree sequences g <- sample_gnp(100, 2/100) is_degseq(degree(g)) is_graphical(degree(g)): \code{\link{is_degseq}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \concept{graphical degree sequences g <- sample_gnp(100, 2/100) is_degseq(degree(g)) is_graphical(degree(g))} \keyword{graphs} igraph/man/strength.Rd0000644000175100001440000000304713430770475014460 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{strength} \alias{strength} \alias{graph.strength} \title{Strength or weighted vertex degree} \usage{ strength(graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, weights = NULL) } \arguments{ \item{graph}{The input graph.} \item{vids}{The vertices for which the strength will be calculated.} \item{mode}{Character string, \dQuote{out} for out-degree, \dQuote{in} for in-degree or \dQuote{all} for the sum of the two. For undirected graphs this argument is ignored.} \item{loops}{Logical; whether the loop edges are also counted.} \item{weights}{Weight vector. If the graph has a \code{weight} edge attribute, then this is used by default. If the graph does not have a \code{weight} edge attribute and this argument is \code{NULL}, then a warning is given and \code{\link{degree}} is called.} } \value{ A numeric vector giving the strength of the vertices. } \description{ Summing up the edge weights of the adjacent edges for each vertex. } \examples{ g <- make_star(10) E(g)$weight <- seq(ecount(g)) strength(g) strength(g, mode="out") strength(g, mode="in") # No weights, a warning is given g <- make_ring(10) strength(g) } \references{ Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004) } \seealso{ \code{\link{degree}} for the unweighted version. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/st_cuts.Rd0000644000175100001440000000316413430770475014306 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{st_cuts} \alias{st_cuts} \alias{stCuts} \title{List all (s,t)-cuts of a graph} \usage{ st_cuts(graph, source, target) } \arguments{ \item{graph}{The input graph. It must be directed.} \item{source}{The source vertex.} \item{target}{The target vertex.} } \value{ A list with entries: \item{cuts}{A list of numeric vectors containing edge ids. Each vector is an \eqn{(s,t)}-cut.} \item{partition1s}{A list of numeric vectors containing vertex ids, they correspond to the edge cuts. Each vertex set is a generator of the corresponding cut, i.e. in the graph \eqn{G=(V,E)}, the vertex set \eqn{X} and its complementer \eqn{V-X}, generates the cut that contains exactly the edges that go from \eqn{X} to \eqn{V-X}.} } \description{ List all (s,t)-cuts in a directed graph. } \details{ Given a \eqn{G} directed graph and two, different and non-ajacent vertices, \eqn{s} and \eqn{t}, an \eqn{(s,t)}-cut is a set of edges, such that after removing these edges from \eqn{G} there is no directed path from \eqn{s} to \eqn{t}. } \examples{ # A very simple graph g <- graph_from_literal(a -+ b -+ c -+ d -+ e) st_cuts(g, source="a", target="e") # A somewhat more difficult graph g2 <- graph_from_literal(s --+ a:b, a:b --+ t, a --+ 1:2:3, 1:2:3 --+ b) st_cuts(g2, source="s", target="t") } \references{ JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, \emph{Algorithmica} 15, 351--372, 1996. } \seealso{ \code{\link{st_min_cuts}} to list all minimum cuts. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/console.Rd0000644000175100001440000000164613430770475014267 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/console.R \name{console} \alias{console} \alias{igraph.console} \title{The igraph console} \usage{ console() } \value{ \code{NULL}, invisibly. } \description{ The igraph console is a GUI windows that shows what the currently running igraph function is doing. } \details{ The console can be started by calling the \code{console} function. Then it stays open, until the user closes it. Another way to start it to set the \code{verbose} igraph option to \dQuote{tkconsole} via \code{igraph_options}. Then the console (re)opens each time an igraph function supporting it starts; to close it, set the \code{verbose} option to another value. The console is written in Tcl/Tk and required the \code{tcltk} package. } \seealso{ \code{\link{igraph_options}} and the \code{verbose} option. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout_with_dh.Rd0000644000175100001440000001250013430770475015637 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_with_dh} \alias{layout_with_dh} \alias{layout.davidson.harel} \alias{with_dh} \title{The Davidson-Harel layout algorithm} \usage{ layout_with_dh(graph, coords = NULL, maxiter = 10, fineiter = max(10, log2(vcount(graph))), cool.fact = 0.75, weight.node.dist = 1, weight.border = 0, weight.edge.lengths = edge_density(graph)/10, weight.edge.crossings = 1 - sqrt(edge_density(graph)), weight.node.edge.dist = 0.2 * (1 - edge_density(graph))) with_dh(...) } \arguments{ \item{graph}{The graph to lay out. Edge directions are ignored.} \item{coords}{Optional starting positions for the vertices. If this argument is not \code{NULL} then it should be an appropriate matrix of starting coordinates.} \item{maxiter}{Number of iterations to perform in the first phase.} \item{fineiter}{Number of iterations in the fine tuning phase.} \item{cool.fact}{Cooling factor.} \item{weight.node.dist}{Weight for the node-node distances component of the energy function.} \item{weight.border}{Weight for the distance from the border component of the energy function. It can be set to zero, if vertices are allowed to sit on the border.} \item{weight.edge.lengths}{Weight for the edge length component of the energy function.} \item{weight.edge.crossings}{Weight for the edge crossing component of the energy function.} \item{weight.node.edge.dist}{Weight for the node-edge distance component of the energy function.} \item{...}{Passed to \code{layout_with_dh}.} } \value{ A two- or three-column matrix, each row giving the coordinates of a vertex, according to the ids of the vertex ids. } \description{ Place vertices of a graph on the plane, according to the simulated annealing algorithm by Davidson and Harel. } \details{ This function implements the algorithm by Davidson and Harel, see Ron Davidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. ACM Transactions on Graphics 15(4), pp. 301-331, 1996. The algorithm uses simulated annealing and a sophisticated energy function, which is unfortunately hard to parameterize for different graphs. The original publication did not disclose any parameter values, and the ones below were determined by experimentation. The algorithm consists of two phases, an annealing phase, and a fine-tuning phase. There is no simulated annealing in the second phase. Our implementation tries to follow the original publication, as much as possible. The only major difference is that coordinates are explicitly kept within the bounds of the rectangle of the layout. } \examples{ set.seed(42) ## Figures from the paper g_1b <- make_star(19, mode="undirected") + path(c(2:19, 2)) + path(c(seq(2, 18, by=2), 2)) plot(g_1b, layout=layout_with_dh) g_2 <- make_lattice(c(8, 3)) + edges(1,8, 9,16, 17,24) plot(g_2, layout=layout_with_dh) g_3 <- make_empty_graph(n=70) plot(g_3, layout=layout_with_dh) g_4 <- make_empty_graph(n=70, directed=FALSE) + edges(1:70) plot(g_4, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_5a <- make_ring(24) plot(g_5a, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_5b <- make_ring(40) plot(g_5b, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_6 <- make_lattice(c(2,2,2)) plot(g_6, layout=layout_with_dh) g_7 <- graph_from_literal(1:3:5 -- 2:4:6) plot(g_7, layout=layout_with_dh, vertex.label=V(g_7)$name) g_8 <- make_ring(5) + make_ring(10) + make_ring(5) + edges(1,6, 2,8, 3, 10, 4,12, 5,14, 7,16, 9,17, 11,18, 13,19, 15,20) plot(g_8, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_9 <- make_lattice(c(3,2,2)) plot(g_9, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_10 <- make_lattice(c(6,6)) plot(g_10, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_11a <- make_tree(31, 2, mode="undirected") plot(g_11a, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_11b <- make_tree(21, 4, mode="undirected") plot(g_11b, layout=layout_with_dh, vertex.size=5, vertex.label=NA) g_12 <- make_empty_graph(n=37, directed=FALSE) + path(1:5,10,22,31,37:33,27,16,6,1) + path(6,7,11,9,10) + path(16:22) + path(27:31) + path(2,7,18,28,34) + path(3,8,11,19,29,32,35) + path(4,9,20,30,36) + path(1,7,12,14,19,24,26,30,37) + path(5,9,13,15,19,23,25,28,33) + path(3,12,16,25,35,26,22,13,3) plot(g_12, layout=layout_with_dh, vertex.size=5, vertex.label=NA) } \references{ Ron Davidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. \emph{ACM Transactions on Graphics} 15(4), pp. 301-331, 1996. } \seealso{ \code{\link{layout_with_fr}}, \code{\link{layout_with_kk}} for other layout algorithms. Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} igraph/man/sample_motifs.Rd0000644000175100001440000000270513430770475015464 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/motifs.R \name{sample_motifs} \alias{sample_motifs} \alias{graph.motifs.est} \title{Graph motifs} \usage{ sample_motifs(graph, size = 3, cut.prob = rep(0, size), sample.size = vcount(graph)/10, sample = NULL) } \arguments{ \item{graph}{Graph object, the input graph.} \item{size}{The size of the motif, currently 3 and 4 are supported only.} \item{cut.prob}{Numeric vector giving the probabilities that the search graph is cut at a certain level. Its length should be the same as the size of the motif (the \code{size} argument). By default no cuts are made.} \item{sample.size}{The number of vertices to use as a starting point for finding motifs. Only used if the \code{sample} argument is \code{NULL}.} \item{sample}{If not \code{NULL} then it specifies the vertices to use as a starting point for finding motifs.} } \value{ A numeric scalar, an estimate for the total number of motifs in the graph. } \description{ Graph motifs are small connected subgraphs with a well-defined structure. These functions search a graph for various motifs. } \details{ \code{sample_motifs} estimates the total number of motifs of a given size in a graph based on a sample. } \examples{ g <- barabasi.game(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3) } \seealso{ \code{\link{isomorphism_class}} Other graph motifs: \code{\link{count_motifs}}, \code{\link{motifs}} } \concept{graph motifs} igraph/man/categorical_pal.Rd0000644000175100001440000000200613430770475015725 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/palette.R \name{categorical_pal} \alias{categorical_pal} \title{Palette for categories} \usage{ categorical_pal(n) } \arguments{ \item{n}{The number of colors in the palette. We simply take the first \code{n} colors from the total 8.} } \value{ A character vector of RGB color codes. } \description{ This is a color blind friendly palette from \url{http://jfly.iam.u-tokyo.ac.jp/color}. It has 8 colors. } \details{ This is the suggested palette for visualizations where vertex colors mark categories, e.g. community membership. } \section{Examples}{ \preformatted{ library(igraphdata) data(karate) karate <- karate %>% add_layout_(with_fr()) %>% set_vertex_attr("size", value = 10) cl_k <- cluster_optimal(karate) V(karate)$color <- membership(cl_k) karate$palette <- categorical_pal(length(cl_k)) plot(karate) } } \seealso{ Other palettes: \code{\link{diverging_pal}}, \code{\link{r_pal}}, \code{\link{sequential_pal}} } \concept{palettes} igraph/man/sub-.igraph.Rd0000644000175100001440000001241613430770475014741 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/indexing.R \name{[.igraph} \alias{[.igraph} \title{Query and manipulate a graph as it were an adjacency matrix} \usage{ \method{[}{igraph}(x, i, j, ..., from, to, sparse = igraph_opt("sparsematrices"), edges = FALSE, drop = TRUE, attr = if (is_weighted(x)) "weight" else NULL) } \arguments{ \item{x}{The graph.} \item{i}{Index. Vertex ids or names or logical vectors. See details below.} \item{j}{Index. Vertex ids or names or logical vectors. See details below.} \item{...}{Currently ignored.} \item{from}{A numeric or character vector giving vertex ids or names. Together with the \code{to} argument, it can be used to query/set a sequence of edges. See details below. This argument cannot be present together with any of the \code{i} and \code{j} arguments and if it is present, then the \code{to} argument must be present as well.} \item{to}{A numeric or character vector giving vertex ids or names. Together with the \code{from} argument, it can be used to query/set a sequence of edges. See details below. This argument cannot be present together with any of the \code{i} and \code{j} arguments and if it is present, then the \code{from} argument must be present as well.} \item{sparse}{Logical scalar, whether to return sparse matrices.} \item{edges}{Logical scalar, whether to return edge ids.} \item{drop}{Ignored.} \item{attr}{If not \code{NULL}, then it should be the name of an edge attribute. This attribute is queried and returned.} } \value{ A scalar or matrix. See details below. } \description{ Query and manipulate a graph as it were an adjacency matrix } \details{ The single bracket indexes the (possibly weighted) adjacency matrix of the graph. Here is what you can do with it: \enumerate{ \item Check whether there is an edge between two vertices (\eqn{v} and \eqn{w}) in the graph: \preformatted{ graph[v, w]} A numeric scalar is returned, one if the edge exists, zero otherwise. \item Extract the (sparse) adjacency matrix of the graph, or part of it: \preformatted{ graph[] graph[1:3,5:6] graph[c(1,3,5),]} The first variants returns the full adjacency matrix, the other two return part of it. \item The \code{from} and \code{to} arguments can be used to check the existence of many edges. In this case, both \code{from} and \code{to} must be present and they must have the same length. They must contain vertex ids or names. A numeric vector is returned, of the same length as \code{from} and \code{to}, it contains ones for existing edges edges and zeros for non-existing ones. Example: \preformatted{ graph[from=1:3, to=c(2,3,5)]}. \item For weighted graphs, the \code{[} operator returns the edge weights. For non-esistent edges zero weights are returned. Other edge attributes can be queried as well, by giving the \code{attr} argument. \item Querying edge ids instead of the existance of edges or edge attributes. E.g. \preformatted{ graph[1, 2, edges=TRUE]} returns the id of the edge between vertices 1 and 2, or zero if there is no such edge. \item Adding one or more edges to a graph. For this the element(s) of the imaginary adjacency matrix must be set to a non-zero numeric value (or \code{TRUE}): \preformatted{ graph[1, 2] <- 1 graph[1:3,1] <- 1 graph[from=1:3, to=c(2,3,5)] <- TRUE} This does not affect edges that are already present in the graph, i.e. no multiple edges are created. \item Adding weighted edges to a graph. The \code{attr} argument contains the name of the edge attribute to set, so it does not have to be \sQuote{weight}: \preformatted{ graph[1, 2, attr="weight"]<- 5 graph[from=1:3, to=c(2,3,5)] <- c(1,-1,4)} If an edge is already present in the network, then only its weights or other attribute are updated. If the graph is already weighted, then the \code{attr="weight"} setting is implicit, and one does not need to give it explicitly. \item Deleting edges. The replacement syntax allow the deletion of edges, by specifying \code{FALSE} or \code{NULL} as the replacement value: \preformatted{ graph[v, w] <- FALSE} removes the edge from vertex \eqn{v} to vertex \eqn{w}. As this can be used to delete edges between two sets of vertices, either pairwise: \preformatted{ graph[from=v, to=w] <- FALSE} or not: \preformatted{ graph[v, w] <- FALSE } if \eqn{v} and \eqn{w} are vectors of edge ids or names. } \sQuote{\code{[}} allows logical indices and negative indices as well, with the usual R semantics. E.g. \preformatted{ graph[degree(graph)==0, 1] <- 1} adds an edge from every isolate vertex to vertex one, and \preformatted{ G <- make_empty_graph(10) G[-1,1] <- TRUE} creates a star graph. Of course, the indexing operators support vertex names, so instead of a numeric vertex id a vertex can also be given to \sQuote{\code{[}} and \sQuote{\code{[[}}. } \seealso{ Other structural queries: \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/norm_coords.Rd0000644000175100001440000000360013430770475015141 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{norm_coords} \alias{norm_coords} \alias{layout.norm} \title{Normalize coordinates for plotting graphs} \usage{ norm_coords(layout, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1) } \arguments{ \item{layout}{A matrix with two or three columns, the layout to normalize.} \item{xmin, xmax}{The limits for the first coordinate, if one of them or both are \code{NULL} then no normalization is performed along this direction.} \item{ymin, ymax}{The limits for the second coordinate, if one of them or both are \code{NULL} then no normalization is performed along this direction.} \item{zmin, zmax}{The limits for the third coordinate, if one of them or both are \code{NULL} then no normalization is performed along this direction.} } \value{ A numeric matrix with at the same dimension as \code{layout}. } \description{ Rescale coordinates linearly to be within given bounds. } \details{ \code{norm_coords} normalizes a layout, it linearly transforms each coordinate separately to fit into the given limits. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/embed_laplacian_matrix.Rd0000644000175100001440000001042313430770475017262 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{embed_laplacian_matrix} \alias{embed_laplacian_matrix} \title{Spectral Embedding of the Laplacian of a Graph} \usage{ embed_laplacian_matrix(graph, no, weights = NULL, which = c("lm", "la", "sa"), degmode = c("out", "in", "all", "total"), type = c("default", "D-A", "DAD", "I-DAD", "OAP"), scaled = TRUE, options = igraph.arpack.default) } \arguments{ \item{graph}{The input graph, directed or undirected.} \item{no}{An integer scalar. This value is the embedding dimension of the spectral embedding. Should be smaller than the number of vertices. The largest \code{no}-dimensional non-zero singular values are used for the spectral embedding.} \item{weights}{Optional positive weight vector for calculating a weighted embedding. If the graph has a \code{weight} edge attribute, then this is used by default. For weighted embedding, edge weights are used instead of the binary adjacency matrix, and vertex stregth (see \code{\link{strength}}) is used instead of the degrees.} \item{which}{Which eigenvalues (or singular values, for directed graphs) to use. \sQuote{lm} means the ones with the largest magnitude, \sQuote{la} is the ones (algebraic) largest, and \sQuote{sa} is the (algebraic) smallest eigenvalues. The default is \sQuote{lm}. Note that for directed graphs \sQuote{la} and \sQuote{lm} are the equivalent, because the singular values are used for the ordering.} \item{degmode}{TODO} \item{type}{The type of the Laplacian to use. Various definitions exist for the Laplacian of a graph, and one can choose between them with this argument. Possible values: \code{D-A} means \eqn{D-A} where \eqn{D} is the degree matrix and \eqn{A} is the adjacency matrix; \code{DAD} means \eqn{D^{1/2}}{D^1/2} times \eqn{A} times \eqn{D^{1/2}{D^1/2}}, \eqn{D^{1/2}}{D^1/2} is the inverse of the square root of the degree matrix; \code{I-DAD} means \eqn{I-D^{1/2}}{I-D^1/2}, where \eqn{I} is the identity matrix. \code{OAP} is \eqn{O^{1/2}AP^{1/2}}{O^1/2 A P^1/2}, where \eqn{O^{1/2}}{O^1/2} is the inverse of the square root of the out-degree matrix and \eqn{P^{1/2}}{P^1/2} is the same for the in-degree matrix. \code{OAP} is not defined for undireted graphs, and is the only defined type for directed graphs. The default (i.e. type \code{default}) is to use \code{D-A} for undirected graphs and \code{OAP} for directed graphs.} \item{scaled}{Logical scalar, if \code{FALSE}, then \eqn{U} and \eqn{V} are returned instead of \eqn{X} and \eqn{Y}.} \item{options}{A named list containing the parameters for the SVD computation algorithm in ARPACK. By default, the list of values is assigned the values given by \code{\link{igraph.arpack.default}}.} } \value{ A list containing with entries: \item{X}{Estimated latent positions, an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} \item{Y}{\code{NULL} for undirected graphs, the second half of the latent positions for directed graphs, an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} \item{D}{The eigenvalues (for undirected graphs) or the singular values (for directed graphs) calculated by the algorithm.} \item{options}{A named list, information about the underlying ARPACK computation. See \code{\link{arpack}} for the details.} } \description{ Spectral decomposition of Laplacian matrices of graphs. } \details{ This function computes a \code{no}-dimensional Euclidean representation of the graph based on its Laplacian matrix, \eqn{L}. This representation is computed via the singular value decomposition of the Laplacian matrix. They are essentially doing the same as \code{\link{embed_adjacency_matrix}}, but work on the Laplacian matrix, instead of the adjacency matrix. } \examples{ ## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_laplacian_matrix(RDP, 5) } \references{ Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, \emph{Journal of the American Statistical Association}, Vol. 107(499), 2012 } \seealso{ \code{\link{embed_adjacency_matrix}}, \code{\link{sample_dot_product}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/edge_attr-set.Rd0000644000175100001440000000267413430770475015356 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{edge_attr<-} \alias{edge_attr<-} \alias{edge.attributes<-} \title{Set one or more edge attributes} \usage{ edge_attr(graph, name, index = E(graph)) <- value } \arguments{ \item{graph}{The graph.} \item{name}{The name of the edge attribute to set. If missing, then \code{value} must be a named list, and its entries are set as edge attributes.} \item{index}{An optional edge sequence to set the attributes of a subset of edges.} \item{value}{The new value of the attribute(s) for all (or \code{index}) edges.} } \value{ The graph, with the edge attribute(s) added or set. } \description{ Set one or more edge attributes } \examples{ g <- make_ring(10) edge_attr(g) <- list(name = LETTERS[1:10], color = rep("green", gsize(g))) edge_attr(g, "label") <- E(g)$name g plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/automorphisms.Rd0000644000175100001440000000452213430770476015534 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{automorphisms} \alias{automorphisms} \alias{graph.automorphisms} \title{Number of automorphisms} \usage{ automorphisms(graph, sh = "fm") } \arguments{ \item{graph}{The input graph, it is treated as undirected.} \item{sh}{The splitting heuristics for the BLISS algorithm. Possible values are: \sQuote{\code{f}}: first non-singleton cell, \sQuote{\code{fl}}: first largest non-singleton cell, \sQuote{\code{fs}}: first smallest non-singleton cell, \sQuote{\code{fm}}: first maximally non-trivially connected non-singleton cell, \sQuote{\code{flm}}: first largest maximally non-trivially connected non-singleton cell, \sQuote{\code{fsm}}: first smallest maximally non-trivially connected non-singleton cell.} } \value{ A named list with the following members: \item{group_size}{The size of the automorphism group of the input graph, as a string. This number is exact if igraph was compiled with the GMP library, and approximate otherwise.} \item{nof_nodes}{The number of nodes in the search tree.} \item{nof_leaf_nodes}{The number of leaf nodes in the search tree.} \item{nof_bad_nodes}{Number of bad nodes.} \item{nof_canupdates}{Number of canrep updates.} \item{max_level}{Maximum level.} } \description{ Calculate the number of automorphisms of a graph, i.e. the number of isomorphisms to itself. } \details{ An automorphism of a graph is a permutation of its vertices which brings the graph into itself. This function calculates the number of automorphism of a graph using the BLISS algorithm. See also the BLISS homepage at \url{http://www.tcs.hut.fi/Software/bliss/index.html}. } \examples{ ## A ring has n*2 automorphisms, you can "turn" it by 0-9 vertices ## and each of these graphs can be "flipped" g <- make_ring(10) automorphisms(g) } \references{ Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics.} 2007. } \seealso{ \code{\link{canonical_permutation}}, \code{\link{permute}} } \author{ Tommi Junttila (\url{http://users.ics.aalto.fi/tjunttil/}) for BLISS and Gabor Csardi \email{csardi.gabor@gmail.com} for the igraph glue code and this manual page. } \keyword{graphs} igraph/man/igraph-es-indexing2.Rd0000644000175100001440000000375613430770475016375 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{igraph-es-indexing2} \alias{igraph-es-indexing2} \alias{[[.igraph.es} \title{Select edges and show their metadata} \usage{ \method{[[}{igraph.es}(x, ...) } \arguments{ \item{x}{An edge sequence.} \item{...}{Additional arguments, passed to \code{[}.} } \value{ Another edge sequence, with metadata printing turned on. See details below. } \description{ The double bracket operator can be used on edge sequences, to print the meta-data (edge attributes) of the edges in the sequence. } \details{ Technically, when used with edge sequences, the double bracket operator does exactly the same as the single bracket operator, but the resulting edge sequence is printed differently: all attributes of the edges in the sequence are printed as well. See \code{\link{[.igraph.es}} for more about indexing edge sequences. } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]), with_edge_(weight = 1:10, color = "green")) E(g) E(g)[[]] E(g)[[.inc('A')]] } \seealso{ Other vertex and edge sequences: \code{\link{E}}, \code{\link{V}}, \code{\link{igraph-es-attributes}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-attributes}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{print.igraph.es}}, \code{\link{print.igraph.vs}} Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} \concept{vertex and edge sequences} igraph/man/centr_eigen_tmax.Rd0000644000175100001440000000266113430770475016136 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_eigen_tmax} \alias{centr_eigen_tmax} \alias{centralization.evcent.tmax} \title{Theoretical maximum for betweenness centralization} \usage{ centr_eigen_tmax(graph = NULL, nodes = 0, directed = FALSE, scale = TRUE) } \arguments{ \item{graph}{The input graph. It can also be \code{NULL}, if \code{nodes} is given.} \item{nodes}{The number of vertices. This is ignored if the graph is given.} \item{directed}{logical scalar, whether to use directed shortest paths for calculating betweenness.} \item{scale}{Whether to rescale the eigenvector centrality scores, such that the maximum score is one.} } \value{ Real scalar, the theoratical maximum (unnormalized) graph betweenness centrality score for graphs with given order and other parameters. } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_eigen(g, normalized = FALSE)$centralization \%>\% `/`(centr_eigen_tmax(g)) centr_eigen(g, normalized = TRUE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo_tmax}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/layout_nicely.Rd0000644000175100001440000000453713430770475015507 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_nicely} \alias{layout_nicely} \alias{layout.auto} \alias{nicely} \title{Choose an appropriate graph layout algorithm automatically} \usage{ layout_nicely(graph, dim = 2, ...) nicely(...) } \arguments{ \item{graph}{The input graph} \item{dim}{Dimensions, should be 2 or 3.} \item{\dots}{For \code{layout_nicely} the extra arguments are passed to the real layout function. For \code{nicely} all argument are passed to \code{layout_nicely}.} } \value{ A numeric matrix with two or three columns. } \description{ This function tries to choose an appropriate graph layout algorithm for the graph, automatically, based on a simple algorithm. See details below. } \details{ \code{layout_nicely} tries to choose an appropriate layout function for the supplied graph, and uses that to generate the layout. The current implementation works like this: \enumerate{ \item If the graph has a graph attribute called \sQuote{layout}, then this is used. If this attribute is an R function, then it is called, with the graph and any other extra arguments. \item Otherwise, if the graph has vertex attributes called \sQuote{x} and \sQuote{y}, then these are used as coordinates. If the graph has an additional \sQuote{z} vertex attribute, that is also used. \item Otherwise, if the graph is connected and has less than 1000 vertices, the Fruchterman-Reingold layout is used, by calling \code{layout_with_fr}. \item Otherwise the DrL layout is used, \code{layout_with_drl} is called. } } \seealso{ \code{\link{plot.igraph}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/unique.igraph.vs.Rd0000644000175100001440000000254113430770475016026 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{unique.igraph.vs} \alias{unique.igraph.vs} \title{Remove duplicate vertices from a vertex sequence} \usage{ \method{unique}{igraph.vs}(x, incomparables = FALSE, ...) } \arguments{ \item{x}{A vertex sequence.} \item{incomparables}{a vector of values that cannot be compared. Passed to base function \code{duplicated}. See details there.} \item{...}{Passed to base function \code{duplicated()}.} } \value{ A vertex sequence with the duplicate vertices removed. } \description{ Remove duplicate vertices from a vertex sequence } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g)[1, 1:5, 1:10, 5:10] V(g)[1, 1:5, 1:10, 5:10] \%>\% unique() } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}} } \concept{vertex and edge sequence operations} igraph/man/normalize.Rd0000644000175100001440000000257513430770475014627 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{normalize} \alias{normalize} \title{Normalize layout} \usage{ normalize(xmin = -1, xmax = 1, ymin = xmin, ymax = xmax, zmin = xmin, zmax = xmax) } \arguments{ \item{xmin, xmax}{Minimum and maximum for x coordinates.} \item{ymin, ymax}{Minimum and maximum for y coordinates.} \item{zmin, zmax}{Minimum and maximum for z coordinates.} } \description{ Scale coordinates of a layout. } \examples{ layout_(make_ring(10), with_fr(), normalize()) } \seealso{ \code{\link{merge_coords}}, \code{\link{layout_}}. Other layout modifiers: \code{\link{component_wise}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}} } \concept{graph layouts} \concept{layout modifiers} igraph/man/make_ring.Rd0000644000175100001440000000245113430770475014554 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_ring} \alias{make_ring} \alias{graph.ring} \alias{ring} \title{Create a ring graph} \usage{ make_ring(n, directed = FALSE, mutual = FALSE, circular = TRUE) ring(...) } \arguments{ \item{n}{Number of vertices.} \item{directed}{Whether the graph is directed.} \item{mutual}{Whether directed edges are mutual. It is ignored in undirected graphs.} \item{circular}{Whether to create a circular ring. A non-circular ring is essentially a \dQuote{line}: a tree where every non-leaf vertex has one child.} \item{...}{Passed to \code{make_ring}.} } \value{ An igraph graph. } \description{ A ring is a one-dimensional lattice and this function is a special case of \code{\link{make_lattice}}. } \examples{ print_all(make_ring(10)) print_all(make_ring(10, directed = TRUE, mutual = TRUE)) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_full_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{determimistic constructors} igraph/man/cluster_leading_eigen.Rd0000644000175100001440000001171013430770475017131 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{cluster_leading_eigen} \alias{cluster_leading_eigen} \alias{leading.eigenvector.community} \title{Community structure detecting based on the leading eigenvector of the community matrix} \usage{ cluster_leading_eigen(graph, steps = -1, weights = NULL, start = NULL, options = arpack_defaults, callback = NULL, extra = NULL, env = parent.frame()) } \arguments{ \item{graph}{The input graph. Should be undirected as the method needs a symmetric matrix.} \item{steps}{The number of steps to take, this is actually the number of tries to make a step. It is not a particularly useful parameter.} \item{weights}{An optional weight vector. The \sQuote{weight} edge attribute is used if present. Supply \sQuote{\code{NA}} here if you want to ignore the \sQuote{weight} edge attribute. Larger edge weights correspond to stronger connections between vertices.} \item{start}{\code{NULL}, or a numeric membership vector, giving the start configuration of the algorithm.} \item{options}{A named list to override some ARPACK options.} \item{callback}{If not \code{NULL}, then it must be callback function. This is called after each iteration, after calculating the leading eigenvector of the modularity matrix. See details below.} \item{extra}{Additional argument to supply to the callback function.} \item{env}{The environment in which the callback function is evaluated.} } \value{ \code{cluster_leading_eigen} returns a named list with the following members: \item{membership}{The membership vector at the end of the algorithm, when no more splits are possible.} \item{merges}{The merges matrix starting from the state described by the \code{membership} member. This is a two-column matrix and each line describes a merge of two communities, the first line is the first merge and it creates community \sQuote{\code{N}}, \code{N} is the number of initial communities in the graph, the second line creates community \code{N+1}, etc. } \item{options}{Information about the underlying ARPACK computation, see \code{\link{arpack}} for details. } } \description{ This function tries to find densely connected subgraphs in a graph by calculating the leading non-negative eigenvector of the modularity matrix of the graph. } \details{ The function documented in these section implements the \sQuote{leading eigenvector} method developed by Mark Newman, see the reference below. The heart of the method is the definition of the modularity matrix, \code{B}, which is \code{B=A-P}, \code{A} being the adjacency matrix of the (undirected) network, and \code{P} contains the probability that certain edges are present according to the \sQuote{configuration model}. In other words, a \code{P[i,j]} element of \code{P} is the probability that there is an edge between vertices \code{i} and \code{j} in a random network in which the degrees of all vertices are the same as in the input graph. The leading eigenvector method works by calculating the eigenvector of the modularity matrix for the largest positive eigenvalue and then separating vertices into two community based on the sign of the corresponding element in the eigenvector. If all elements in the eigenvector are of the same sign that means that the network has no underlying comuunity structure. Check Newman's paper to understand why this is a good method for detecting community structure. } \section{Callback functions}{ The \code{callback} argument can be used to supply a function that is called after each eigenvector calculation. The following arguments are supplied to this function: \describe{ \item{membership}{The actual membership vector, with zero-based indexing.} \item{community}{The community that the algorithm just tried to split, community numbering starts with zero here.} \item{value}{The eigenvalue belonging to the leading eigenvector the algorithm just found.} \item{vector}{The leading eigenvector the algorithm just found.} \item{multiplier}{An R function that can be used to multiple the actual modularity matrix with an arbitrary vector. Supply the vector as an argument to perform this multiplication. This function can be used with ARPACK.} \item{extra}{The \code{extra} argument that was passed to \code{cluster_leading_eigen}. } The callback function should return a scalar number. If this number is non-zero, then the clustering is terminated. } } \examples{ g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) lec <- cluster_leading_eigen(g) lec cluster_leading_eigen(g, start=membership(lec)) } \references{ MEJ Newman: Finding community structure using the eigenvectors of matrices, Physical Review E 74 036104, 2006. } \seealso{ \code{\link{modularity}}, \code{\link{cluster_walktrap}}, \code{\link{cluster_edge_betweenness}}, \code{\link{cluster_fast_greedy}}, \code{\link[stats]{as.dendrogram}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/as.directed.Rd0000644000175100001440000000561313430770475015010 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as.directed} \alias{as.directed} \alias{as.undirected} \title{Convert between directed and undirected graphs} \usage{ as.directed(graph, mode = c("mutual", "arbitrary")) as.undirected(graph, mode = c("collapse", "each", "mutual"), edge.attr.comb = igraph_opt("edge.attr.comb")) } \arguments{ \item{graph}{The graph to convert.} \item{mode}{Character constant, defines the conversion algorithm. For \code{as.directed} it can be \code{mutual} or \code{arbitrary}. For \code{as.undirected} it can be \code{each}, \code{collapse} or \code{mutual}. See details below.} \item{edge.attr.comb}{Specifies what to do with edge attributes, if \code{mode="collapse"} or \code{mode="mutual"}. In these cases many edges might be mapped to a single one in the new graph, and their attributes are combined. Please see \code{\link{attribute.combination}} for details on this.} } \value{ A new graph object. } \description{ \code{as.directed} converts an undirected graph to directed, \code{as.undirected} does the opposite, it converts a directed graph to undirected. } \details{ Conversion algorithms for \code{as.directed}: \describe{ \item{"arbitrary"}{The number of edges in the graph stays the same, an arbitrarily directed edge is created for each undirected edge.} \item{"mutual"}{Two directed edges are created for each undirected edge, one in each direction.} } Conversion algorithms for \code{as.undirected}: \describe{ \item{"each"}{The number of edges remains constant, an undirected edge is created for each directed one, this version might create graphs with multiple edges.} \item{"collapse"}{One undirected edge will be created for each pair of vertices which are connected with at least one directed edge, no multiple edges will be created.} \item{"mutual"}{One undirected edge will be created for each pair of mutual edges. Non-mutual edges are ignored. This mode might create multiple edges if there are more than one mutual edge pairs between the same pair of vertices. } } } \examples{ g <- make_ring(10) as.directed(g, "mutual") g2 <- make_star(10) as.undirected(g) # Combining edge attributes g3 <- make_ring(10, directed=TRUE, mutual=TRUE) E(g3)$weight <- seq_len(ecount(g3)) ug3 <- as.undirected(g3) print(ug3, e=TRUE) \dontrun{ x11(width=10, height=5) layout(rbind(1:2)) plot( g3, layout=layout_in_circle, edge.label=E(g3)$weight) plot(ug3, layout=layout_in_circle, edge.label=E(ug3)$weight) } g4 <- graph(c(1,2, 3,2,3,4,3,4, 5,4,5,4, 6,7, 7,6,7,8,7,8, 8,7,8,9,8,9, 9,8,9,8,9,9, 10,10,10,10)) E(g4)$weight <- seq_len(ecount(g4)) ug4 <- as.undirected(g4, mode="mutual", edge.attr.comb=list(weight=length)) print(ug4, e=TRUE) } \seealso{ \code{\link{simplify}} for removing multiple and/or loop edges from a graph. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/fit_hrg.Rd0000644000175100001440000000660113430770475014243 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{fit_hrg} \alias{fit_hrg} \alias{hrg.fit} \title{Fit a hierarchical random graph model} \usage{ fit_hrg(graph, hrg = NULL, start = FALSE, steps = 0) } \arguments{ \item{graph}{The graph to fit the model to. Edge directions are ignored in directed graphs.} \item{hrg}{A hierarchical random graph model, in the form of an \code{igraphHRG} object. \code{fit_hrg} allows this to be \code{NULL}, in which case a random starting point is used for the fitting.} \item{start}{Logical, whether to start the fitting/sampling from the supplied \code{igraphHRG} object, or from a random starting point.} \item{steps}{The number of MCMC steps to make. If this is zero, then the MCMC procedure is performed until convergence.} } \value{ \code{fit_hrg} returns an \code{igraphHRG} object. This is a list with the following members: \item{left}{Vector that contains the left children of the internal tree vertices. The first vertex is always the root vertex, so the first element of the vector is the left child of the root vertex. Internal vertices are denoted with negative numbers, starting from -1 and going down, i.e. the root vertex is -1. Leaf vertices are denoted by non-negative number, starting from zero and up.} \item{right}{Vector that contains the right children of the vertices, with the same encoding as the \code{left} vector.} \item{prob}{The connection probabilities attached to the internal vertices, the first number belongs to the root vertex (i.e. internal vertex -1), the second to internal vertex -2, etc.} \item{edges}{The number of edges in the subtree below the given internal vertex.} \item{vertices}{The number of vertices in the subtree below the given internal vertex, including itself.} } \description{ \code{fit_hrg} fits a HRG to a given graph. It takes the specified \code{steps} number of MCMC steps to perform the fitting, or a convergence criteria if the specified number of steps is zero. \code{fit_hrg} can start from a given HRG, if this is given in the \code{hrg} argument and the \code{start} argument is \code{TRUE}. } \examples{ ## We are not running these examples any more, because they ## take a long time (~15 seconds) to run and this is against the CRAN ## repository policy. Copy and paste them by hand to your R prompt if ## you want to run them. \dontrun{ ## A graph with two dense groups g <- sample_gnp(10, p=1/2) + sample_gnp(10, p=1/2) hrg <- fit_hrg(g) hrg ## The consensus tree for it consensus_tree(g, hrg=hrg, start=TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1,2)) predict_edges(g2) } } \references{ A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure and the prediction of missing links in networks. \emph{Nature} 453, 98--101 (2008); A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, \emph{Lecture Notes in Computer Science} 4503, 1--13. Springer-Verlag, Berlin Heidelberg (2007). } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{hrg-methods}}, \code{\link{hrg_tree}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/topo_sort.Rd0000644000175100001440000000270413430770476014652 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{topo_sort} \alias{topo_sort} \alias{topological.sort} \title{Topological sorting of vertices in a graph} \usage{ topo_sort(graph, mode = c("out", "all", "in")) } \arguments{ \item{graph}{The input graph, should be directed} \item{mode}{Specifies how to use the direction of the edges. For \dQuote{\code{out}}, the sorting order ensures that each node comes before all nodes to which it has edges, so nodes with no incoming edges go first. For \dQuote{\code{in}}, it is quite the opposite: each node comes before all nodes from which it receives edges. Nodes with no outgoing edges go first.} } \value{ A vertex sequence (by default, but see the \code{return.vs.es} option of \code{\link{igraph_options}}) containing vertices in topologically sorted order. } \description{ A topological sorting of a directed acyclic graph is a linear ordering of its nodes where each node comes before all nodes to which it has edges. } \details{ Every DAG has at least one topological sort, and may have many. This function returns a possible topological sort among them. If the graph is not acyclic (it has at least one cycle), a partial topological sort is returned and a warning is issued. } \examples{ g <- barabasi.game(100) topo_sort(g) } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} for the R interface } \keyword{graphs} igraph/man/layout_in_circle.Rd0000644000175100001440000000372513430770475016151 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_in_circle} \alias{layout_in_circle} \alias{in_circle} \title{Graph layout with vertices on a circle.} \usage{ layout_in_circle(graph, order = V(graph)) in_circle(...) } \arguments{ \item{graph}{The input graph.} \item{order}{The vertices to place on the circle, in the order of their desired placement. Vertices that are not included here will be placed at (0,0).} \item{...}{Passed to \code{layout_in_circle}.} } \value{ A numeric matrix with two columns, and one row for each vertex. } \description{ Place vertices on a circle, in the order of their vertex ids. } \details{ If you want to order the vertices differently, then permute them using the \code{\link{permute}} function. } \examples{ ## Place vertices on a circle, order them according to their ## community \dontrun{ library(igraphdata) data(karate) karate_groups <- cluster_optimal(karate) coords <- layout_in_circle(karate, order = order(membership(karate_groups))) V(karate)$label <- sub("Actor ", "", V(karate)$name) V(karate)$label.color <- membership(karate_groups) V(karate)$shape <- "none" plot(karate, layout = coords) } } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/vertex_attr_names.Rd0000644000175100001440000000216113430770475016350 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{vertex_attr_names} \alias{vertex_attr_names} \alias{list.vertex.attributes} \title{List names of vertex attributes} \usage{ vertex_attr_names(graph) } \arguments{ \item{graph}{The graph.} } \value{ Character vector, the names of the vertex attributes. } \description{ List names of vertex attributes } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("name", value = LETTERS[1:10]) \%>\% set_vertex_attr("color", value = rep("green", 10)) vertex_attr_names(g) plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/hrg_tree.Rd0000644000175100001440000000134413430770475014417 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{hrg_tree} \alias{hrg_tree} \title{Create an igraph graph from a hierarchical random graph model} \usage{ hrg_tree(hrg) } \arguments{ \item{hrg}{A hierarchical random graph model.} } \value{ An igraph graph. } \description{ \code{hrg_tree} creates the corresponsing igraph tree of a hierarchical random graph model. } \seealso{ Other hierarchical random graph functions: \code{\link{consensus_tree}}, \code{\link{fit_hrg}}, \code{\link{hrg-methods}}, \code{\link{hrg}}, \code{\link{predict_edges}}, \code{\link{print.igraphHRGConsensus}}, \code{\link{print.igraphHRG}}, \code{\link{sample_hrg}} } \concept{hierarchical random graph functions} igraph/man/betweenness.Rd0000644000175100001440000000766113430770476015153 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{estimate_betweenness} \alias{estimate_betweenness} \alias{betweenness} \alias{edge.betweenness} \alias{betweenness.estimate} \alias{edge.betweenness.estimate} \alias{edge_betweenness} \alias{estimate_edge_betweenness} \title{Vertex and edge betweenness centrality} \usage{ estimate_betweenness(graph, vids = V(graph), directed = TRUE, cutoff, weights = NULL, nobigint = TRUE) betweenness(graph, v = V(graph), directed = TRUE, weights = NULL, nobigint = TRUE, normalized = FALSE) edge_betweenness(graph, e = E(graph), directed = TRUE, weights = NULL) } \arguments{ \item{graph}{The graph to analyze.} \item{vids}{The vertices for which the vertex betweenness estimation will be calculated.} \item{directed}{Logical, whether directed paths should be considered while determining the shortest paths.} \item{cutoff}{The maximum path length to consider when calculating the betweenness. If zero or negative then there is no such limit.} \item{weights}{Optional positive weight vector for calculating weighted betweenness. If the graph has a \code{weight} edge attribute, then this is used by default. Weights are used to calculate weighted shortest paths, so they are interpreted as distances.} \item{nobigint}{Logical scalar, whether to use big integers during the calculation. This is only required for lattice-like graphs that have very many shortest paths between a pair of vertices. If \code{TRUE} (the default), then big integers are not used.} \item{v}{The vertices for which the vertex betweenness will be calculated.} \item{normalized}{Logical scalar, whether to normalize the betweenness scores. If \code{TRUE}, then the results are normalized according to \deqn{B^n=\frac{2B}{n^2-3n+2}}{Bnorm=2*B/(n*n-3*n+2)}, where \eqn{B^n}{Bnorm} is the normalized, \eqn{B} the raw betweenness, and \eqn{n} is the number of vertices in the graph.} \item{e}{The edges for which the edge betweenness will be calculated.} } \value{ A numeric vector with the betweenness score for each vertex in \code{v} for \code{betweenness}. A numeric vector with the edge betweenness score for each edge in \code{e} for \code{edge_betweenness}. \code{estimate_betweenness} returns the estimated betweenness scores for vertices in \code{vids}, \code{estimate_edge_betweenness} the estimated edge betweenness score for \emph{all} edges; both in a numeric vector. } \description{ The vertex and edge betweenness are (roughly) defined by the number of geodesics (shortest paths) going through a vertex or an edge. } \details{ The vertex betweenness of vertex \eqn{v}{\code{v}} is defined by \deqn{\sum_{i\ne j, i\ne v, j\ne v} g_{ivj}/g_{ij}}{sum( g_ivj / g_ij, i!=j,i!=v,j!=v)} The edge betweenness of edge \eqn{e}{\code{e}} is defined by \deqn{\sum_{i\ne j} g{iej}/g_{ij}.}{sum( g_iej / g_ij, i!=j).} \code{betweenness} calculates vertex betweenness, \code{edge_betweenness} calculates edge betweenness. \code{estimate_betweenness} only considers paths of length \code{cutoff} or smaller, this can be run for larger graphs, as the running time is not quadratic (if \code{cutoff} is small). If \code{cutoff} is zero or negative then the function calculates the exact betweenness scores. \code{estimate_edge_betweenness} is similar, but for edges. For calculating the betweenness a similar algorithm to the one proposed by Brandes (see References) is used. } \note{ \code{edge_betweenness} might give false values for graphs with multiple edges. } \examples{ g <- sample_gnp(10, 3/10) betweenness(g) edge_betweenness(g) } \references{ Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. \emph{Social Networks}, 1, 215-239. Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. \emph{Journal of Mathematical Sociology} 25(2):163-177, 2001. } \seealso{ \code{\link{closeness}}, \code{\link{degree}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sequential_pal.Rd0000644000175100001440000000175413430770475015633 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/palette.R \name{sequential_pal} \alias{sequential_pal} \title{Sequential palette} \usage{ sequential_pal(n) } \arguments{ \item{n}{The number of colors in the palette. The maximum is nine currently.} } \value{ A character vector of RGB color codes. } \description{ This is the \sQuote{OrRd} palette from \url{http://colorbrewer2.org}. It has at most nine colors. } \details{ Use this palette, if vertex colors mark some ordinal quantity, e.g. some centrality measure, or some ordinal vertex covariate, like the age of people, or their seniority level. } \examples{ \dontrun{ library(igraphdata) data(karate) karate <- karate \%>\% add_layout_(with_kk()) \%>\% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) \%>\% cut(5), sequential_pal) plot(karate) } } \seealso{ Other palettes: \code{\link{categorical_pal}}, \code{\link{diverging_pal}}, \code{\link{r_pal}} } \concept{palettes} igraph/man/subgraph.Rd0000644000175100001440000000445413430770476014441 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{subgraph} \alias{subgraph} \alias{induced.subgraph} \alias{subgraph.edges} \alias{induced_subgraph} \title{Subgraph of a graph} \usage{ subgraph(graph, v) induced_subgraph(graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch")) subgraph.edges(graph, eids, delete.vertices = TRUE) } \arguments{ \item{graph}{The original graph.} \item{v}{Numeric vector, the vertices of the original graph which will form the subgraph.} \item{vids}{Numeric vector, the vertices of the original graph which will form the subgraph.} \item{impl}{Character scalar, to choose between two implementation of the subgraph calculation. \sQuote{\code{copy_and_delete}} copies the graph first, and then deletes the vertices and edges that are not included in the result graph. \sQuote{\code{create_from_scratch}} searches for all vertices and edges that must be kept and then uses them to create the graph from scratch. \sQuote{\code{auto}} chooses between the two implementations automatically, using heuristics based on the size of the original and the result graph.} \item{eids}{The edge ids of the edges that will be kept in the result graph.} \item{delete.vertices}{Logical scalar, whether to remove vertices that do not have any adjacent edges in \code{eids}.} } \value{ A new graph object. } \description{ \code{subgraph} creates a subgraph of a graph, containing only the specified vertices and all the edges among them. } \details{ \code{induced_subgraph} calculates the induced subgraph of a set of vertices in a graph. This means that exactly the specified vertices and all the edges between them will be kept in the result graph. \code{subgraph.edges} calculates the subgraph of a graph. For this function one can specify the vertices and edges to keep. This function will be renamed to \code{subgraph} in the next major version of igraph. The \code{subgraph} function does the same as \code{induced.graph} currently (assuming \sQuote{\code{auto}} as the \code{impl} argument), but it is deprecated and will be removed in the next major version of igraph. } \examples{ g <- make_ring(10) g2 <- induced_subgraph(g, 1:7) g3 <- subgraph.edges(g, 1:5, 1:5) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/as_incidence_matrix.Rd0000644000175100001440000000404713430770475016613 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/conversion.R \name{as_incidence_matrix} \alias{as_incidence_matrix} \alias{get.incidence} \title{Incidence matrix of a bipartite graph} \usage{ as_incidence_matrix(graph, types = NULL, attr = NULL, names = TRUE, sparse = FALSE) } \arguments{ \item{graph}{The input graph. The direction of the edges is ignored in directed graphs.} \item{types}{An optional vertex type vector to use instead of the \code{type} vertex attribute. You must supply this argument if the graph has no \code{type} vertex attribute.} \item{attr}{Either \code{NULL} or a character string giving an edge attribute name. If \code{NULL}, then a traditional incidence matrix is returned. If not \code{NULL} then the values of the given edge attribute are included in the incidence matrix. If the graph has multiple edges, the edge attribute of an arbitrarily chosen edge (for the multiple edges) is included.} \item{names}{Logical scalar, if \code{TRUE} and the vertices in the graph are named (i.e. the graph has a vertex attribute called \code{name}), then vertex names will be added to the result as row and column names. Otherwise the ids of the vertices are used as row and column names.} \item{sparse}{Logical scalar, if it is \code{TRUE} then a sparse matrix is created, you will need the \code{Matrix} package for this.} } \value{ A sparse or dense matrix. } \description{ This function can return a sparse or dense incidence matrix of a bipartite network. The incidence matrix is an \eqn{n} times \eqn{m} matrix, \eqn{n} and \eqn{m} are the number of vertices of the two kinds. } \details{ Bipartite graphs have a \code{type} vertex attribute in igraph, this is boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} for vertices of the second kind. } \examples{ g <- make_bipartite_graph( c(0,1,0,1,0,0), c(1,2,2,3,3,4) ) as_incidence_matrix(g) } \seealso{ \code{\link{graph_from_incidence_matrix}} for the opposite operation. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/is_degseq.Rd0000644000175100001440000000335413430770475014566 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/degseq.R \name{is_degseq} \alias{is_degseq} \alias{is.degree.sequence} \title{Check if a degree sequence is valid for a multi-graph} \usage{ is_degseq(out.deg, in.deg = NULL) } \arguments{ \item{out.deg}{Integer vector, the degree sequence for undirected graphs, or the out-degree sequence for directed graphs.} \item{in.deg}{\code{NULL} or an integer vector. For undireted graphs, it should be \code{NULL}. For directed graphs it specifies the in-degrees.} } \value{ A logical scalar. } \description{ \code{is_degseq} checks whether the given vertex degrees (in- and out-degrees for directed graphs) can be realized by a graph. Note that the graph does not have to be simple, it may contain loop and multiple edges. For undirected graphs, it also checks whether the sum of degrees is even. For directed graphs, the function checks whether the lengths of the two degree vectors are equal and whether their sums are also equal. These are known sufficient and necessary conditions for a degree sequence to be valid. } \references{ Hakimi SL: On the realizability of a set of integers as degrees of the vertices of a simple graph. \emph{J SIAM Appl Math} 10:496-506, 1962. PL Erdos, I Miklos and Z Toroczkai: A simple Havel-Hakimi type algorithm to realize graphical degree sequences of directed graphs. \emph{The Electronic Journal of Combinatorics} 17(1):R66, 2010. } \seealso{ Other graphical degree sequences g <- sample_gnp(100, 2/100) is_degseq(degree(g)) is_graphical(degree(g)): \code{\link{is_graphical}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \concept{graphical degree sequences g <- sample_gnp(100, 2/100) is_degseq(degree(g)) is_graphical(degree(g))} \keyword{graphs} igraph/man/dim_select.Rd0000644000175100001440000000504513430770475014732 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/embedding.R \name{dim_select} \alias{dim_select} \title{Dimensionality selection for singular values using profile likelihood.} \usage{ dim_select(sv) } \arguments{ \item{sv}{A numeric vector, the ordered singular values.} } \value{ A numeric scalar, the estimate of \eqn{d}. } \description{ Select the number of significant singular values, by finding the \sQuote{elbow} of the scree plot, in a principled way. } \details{ The input of the function is a numeric vector which contains the measure of \sQuote{importance} for each dimension. For spectral embedding, these are the singular values of the adjacency matrix. The singular values are assumed to be generated from a Gaussian mixture distribution with two components that have different means and same variance. The dimensionality \eqn{d} is chosen to maximize the likelihood when the \eqn{d} largest singular values are assigned to one component of the mixture and the rest of the singular values assigned to the other component. This function can also be used for the general separation problem, where we assume that the left and the right of the vector are coming from two Normal distributions, with different means, and we want to know their border. See examples below. } \examples{ # Generate the two groups of singular values with # Gaussian mixture of two components that have different means sing.vals <- c( rnorm (10, mean=1, sd=1), rnorm(10, mean=3, sd=1) ) dim.chosen <- dim_select(sing.vals) dim.chosen # Sample random vectors with multivariate normal distribution # and normalize to unit length lpvs <- matrix(rnorm(200), 10, 20) lpvs <- apply(lpvs, 2, function(x) { (abs(x) / sqrt(sum(x^2))) }) RDP.graph <- sample_dot_product(lpvs) dim_select( embed_adjacency_matrix(RDP.graph, 10)$D ) # Sample random vectors with the Dirichlet distribution lpvs.dir <- sample_dirichlet(n=20, rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) dim_select( embed_adjacency_matrix(RDP.graph.2, 10)$D ) # Sample random vectors from hypersphere with radius 1. lpvs.sph <- sample_sphere_surface(dim=10, n=20, radius=1) RDP.graph.3 <- sample_dot_product(lpvs.sph) dim_select( embed_adjacency_matrix(RDP.graph.3, 10)$D ) } \references{ M. Zhu, and A. Ghodsi (2006). Automatic dimensionality selection from the scree plot via the use of profile likelihood. \emph{Computational Statistics and Data Analysis}, Vol. 51, 918--930. } \seealso{ \code{\link{embed_adjacency_matrix}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/diversity.Rd0000644000175100001440000000333413430770475014643 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centrality.R \name{diversity} \alias{diversity} \alias{graph.diversity} \title{Graph diversity} \usage{ diversity(graph, weights = NULL, vids = V(graph)) } \arguments{ \item{graph}{The input graph. Edge directions are ignored.} \item{weights}{\code{NULL}, or the vector of edge weights to use for the computation. If \code{NULL}, then the \sQuote{weight} attibute is used. Note that this measure is not defined for unweighted graphs.} \item{vids}{The vertex ids for which to calculate the measure.} } \value{ A numeric vector, its length is the number of vertices. } \description{ Calculates a measure of diversity for all vertices. } \details{ The diversity of a vertex is defined as the (scaled) Shannon entropy of the weights of its incident edges: \deqn{D(i)=\frac{H(i)}{\log k_i}}{D(i)=H(i)/log(k[i])} and \deqn{H(i)=-\sum_{j=1}^{k_i} p_{ij}\log p_{ij},}{H(i) = -sum(p[i,j] log(p[i,j]), j=1..k[i]),} where \deqn{p_{ij}=\frac{w_{ij}}{\sum_{l=1}^{k_i}}V_{il},}{p[i,j] = w[i,j] / sum(w[i,l], l=1..k[i]),} and \eqn{k_i}{k[i]} is the (total) degree of vertex \eqn{i}, \eqn{w_{ij}}{w[i,j]} is the weight of the edge(s) between vertices \eqn{i} and \eqn{j}. For vertices with degree less than two the function returns \code{NaN}. } \examples{ g1 <- sample_gnp(20, 2/20) g2 <- sample_gnp(20, 2/20) g3 <- sample_gnp(20, 5/20) E(g1)$weight <- 1 E(g2)$weight <- runif(ecount(g2)) E(g3)$weight <- runif(ecount(g3)) diversity(g1) diversity(g2) diversity(g3) } \references{ Nathan Eagle, Michael Macy and Rob Claxton: Network Diversity and Economic Development, \emph{Science} \bold{328}, 1029--1031, 2010. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/make_kautz_graph.Rd0000644000175100001440000000252613430770475016137 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_kautz_graph} \alias{make_kautz_graph} \alias{graph.kautz} \alias{kautz_graph} \title{Kautz graphs} \usage{ make_kautz_graph(m, n) kautz_graph(...) } \arguments{ \item{m}{Integer scalar, the size of the alphabet. See details below.} \item{n}{Integer scalar, the length of the labels. See details below.} \item{...}{Passed to \code{make_kautz_graph}.} } \value{ A graph object. } \description{ Kautz graphs are labeled graphs representing the overlap of strings. } \details{ A Kautz graph is a labeled graph, vertices are labeled by strings of length \code{n+1} above an alphabet with \code{m+1} letters, with the restriction that every two consecutive letters in the string must be different. There is a directed edge from a vertex \code{v} to another vertex \code{w} if it is possible to transform the string of \code{v} into the string of \code{w} by removing the first letter and appending a letter to it. Kautz graphs have some interesting properties, see eg. Wikipedia for details. } \examples{ make_line_graph(make_kautz_graph(2,1)) make_kautz_graph(2,2) } \seealso{ \code{\link{make_de_bruijn_graph}}, \code{\link{make_line_graph}} } \author{ Gabor Csardi , the first version in R was written by Vincent Matossian. } \keyword{graphs} igraph/man/graph_attr-set.Rd0000644000175100001440000000246513430770475015551 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{graph_attr<-} \alias{graph_attr<-} \alias{graph.attributes<-} \title{Set all or some graph attributes} \usage{ graph_attr(graph, name) <- value } \arguments{ \item{graph}{The graph.} \item{name}{The name of the attribute to set. If missing, then \code{value} should be a named list, and all list members are set as attributes.} \item{value}{The value of the attribute to set} } \value{ The graph, with the attribute(s) added. } \description{ Set all or some graph attributes } \examples{ g <- make_graph(~ A - B:C:D) graph_attr(g, "name") <- "4-star" g graph_attr(g) <- list(layout = layout_with_fr(g), name = "4-star layed out") plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/is_min_separator.Rd0000644000175100001440000000347513430770475016165 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{is_min_separator} \alias{is_min_separator} \alias{is.minimal.separator} \title{Minumal vertex separators} \usage{ is_min_separator(graph, candidate) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored.} \item{candidate}{A numeric vector giving the vertex ids of the candidate separator.} } \value{ A logical scalar, whether the supplied vertex set is a (minimal) vertex separator or not. } \description{ Check whether a given set of vertices is a minimal vertex separator. } \details{ \code{is_min_separator} decides whether the supplied vertex set is a minimal vertex separator. A minimal vertex separator is a vertex separator, such that none of its subsets is a vertex separator. In the special case of a fully connected graph with \eqn{n} vertices, each set of \eqn{n-1} vertices is considered to be a vertex separator. } \examples{ # The graph from the Moody-White paper mw <- graph_from_literal(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, 21-22:23, 22-23) # Cohesive subgraphs mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced_subgraph(mw, as.character(7:16)) mw3 <- induced_subgraph(mw, as.character(17:23)) mw4 <- induced_subgraph(mw, as.character(c(7,8,11,14))) mw5 <- induced_subgraph(mw, as.character(1:7)) check.sep <- function(G) { sep <- min_separators(G) sapply(sep, is_min_separator, graph=G) } check.sep(mw) check.sep(mw1) check.sep(mw2) check.sep(mw3) check.sep(mw4) check.sep(mw5) } \seealso{ \code{\link{min_separators}} lists all vertex separator of minimum size. } igraph/man/sample_pa_age.Rd0000644000175100001440000001316613430770475015402 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_pa_age} \alias{sample_pa_age} \alias{aging.prefatt.game} \alias{aging.barabasi.game} \alias{aging.ba.game} \alias{pa_age} \title{Generate an evolving random graph with preferential attachment and aging} \usage{ sample_pa_age(n, pa.exp, aging.exp, m = NULL, aging.bin = 300, out.dist = NULL, out.seq = NULL, out.pref = FALSE, directed = TRUE, zero.deg.appeal = 1, zero.age.appeal = 0, deg.coef = 1, age.coef = 1, time.window = NULL) pa_age(...) } \arguments{ \item{n}{The number of vertices in the graph.} \item{pa.exp}{The preferantial attachment exponent, see the details below.} \item{aging.exp}{The exponent of the aging, usually a non-positive number, see details below.} \item{m}{The number of edges each new vertex creates (except the very first vertex). This argument is used only if both the \code{out.dist} and \code{out.seq} arguments are NULL.} \item{aging.bin}{The number of bins to use for measuring the age of vertices, see details below.} \item{out.dist}{The discrete distribution to generate the number of edges to add in each time step if \code{out.seq} is NULL. See details below.} \item{out.seq}{The number of edges to add in each time step, a vector containing as many elements as the number of vertices. See details below.} \item{out.pref}{Logical constant, whether to include edges not initiated by the vertex as a basis of preferential attachment. See details below.} \item{directed}{Logical constant, whether to generate a directed graph. See details below.} \item{zero.deg.appeal}{The degree-dependent part of the \sQuote{attractiveness} of the vertices with no adjacent edges. See also details below.} \item{zero.age.appeal}{The age-dependent part of the \sQuote{attrativeness} of the vertices with age zero. It is usually zero, see details below.} \item{deg.coef}{The coefficient of the degree-dependent \sQuote{attractiveness}. See details below.} \item{age.coef}{The coefficient of the age-dependent part of the \sQuote{attractiveness}. See details below.} \item{time.window}{Integer constant, if NULL only adjacent added in the last \code{time.windows} time steps are counted as a basis of the preferential attachment. See also details below.} \item{...}{Passed to \code{sample_pa_age}.} } \value{ A new graph. } \description{ This function creates a random graph by simulating its evolution. Each time a new vertex is added it creates a number of links to old vertices and the probability that an old vertex is cited depends on its in-degree (preferential attachment) and age. } \details{ This is a discrete time step model of a growing graph. We start with a network containing a single vertex (and no edges) in the first time step. Then in each time step (starting with the second) a new vertex is added and it initiates a number of edges to the old vertices in the network. The probability that an old vertex is connected to is proportional to \deqn{P[i] \sim (c\cdot k_i^\alpha+a)(d\cdot l_i^\beta+b)\cdot }{% P[i] ~ (c k[i]^alpha + a) (d l[i]^beta + a)} Here \eqn{k_i}{k[i]} is the in-degree of vertex \eqn{i} in the current time step and \eqn{l_i}{l[i]} is the age of vertex \eqn{i}. The age is simply defined as the number of time steps passed since the vertex is added, with the extension that vertex age is divided to be in \code{aging.bin} bins. \eqn{c}, \eqn{\alpha}{alpha}, \eqn{a}, \eqn{d}, \eqn{\beta}{beta} and \eqn{b} are parameters and they can be set via the following arguments: \code{pa.exp} (\eqn{\alpha}{alpha}, mandatory argument), \code{aging.exp} (\eqn{\beta}{beta}, mandatory argument), \code{zero.deg.appeal} (\eqn{a}, optional, the default value is 1), \code{zero.age.appeal} (\eqn{b}, optional, the default is 0), \code{deg.coef} (\eqn{c}, optional, the default is 1), and \code{age.coef} (\eqn{d}, optional, the default is 1). The number of edges initiated in each time step is governed by the \code{m}, \code{out.seq} and \code{out.pref} parameters. If \code{out.seq} is given then it is interpreted as a vector giving the number of edges to be added in each time step. It should be of length \code{n} (the number of vertices), and its first element will be ignored. If \code{out.seq} is not given (or NULL) and \code{out.dist} is given then it will be used as a discrete probability distribution to generate the number of edges. Its first element gives the probability that zero edges are added at a time step, the second element is the probability that one edge is added, etc. (\code{out.seq} should contain non-negative numbers, but if they don't sum up to 1, they will be normalized to sum up to 1. This behavior is similar to the \code{prob} argument of the \code{sample} command.) By default a directed graph is generated, but it \code{directed} is set to \code{FALSE} then an undirected is created. Even if an undirected graph is generaed \eqn{k_i}{k[i]} denotes only the adjacent edges not initiated by the vertex itself except if \code{out.pref} is set to \code{TRUE}. If the \code{time.window} argument is given (and not NULL) then \eqn{k_i}{k[i]} means only the adjacent edges added in the previous \code{time.window} time steps. This function might generate graphs with multiple edges. } \examples{ # The maximum degree for graph with different aging exponents g1 <- sample_pa_age(10000, pa.exp=1, aging.exp=0, aging.bin=1000) g2 <- sample_pa_age(10000, pa.exp=1, aging.exp=-1, aging.bin=1000) g3 <- sample_pa_age(10000, pa.exp=1, aging.exp=-3, aging.bin=1000) max(degree(g1)) max(degree(g2)) max(degree(g3)) } \seealso{ \code{\link{sample_pa}}, \code{\link{sample_gnp}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/count_isomorphisms.Rd0000644000175100001440000000307313430770476016566 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/topology.R \name{count_isomorphisms} \alias{count_isomorphisms} \alias{graph.count.isomorphisms.vf2} \title{Count the number of isomorphic mappings between two graphs} \usage{ count_isomorphisms(graph1, graph2, method = "vf2", ...) } \arguments{ \item{graph1}{The first graph.} \item{graph2}{The second graph.} \item{method}{Currently only \sQuote{vf2} is supported, see \code{\link{isomorphic}} for details about it and extra arguments.} \item{...}{Passed to the individual methods.} } \value{ Number of isomirphic mappings between the two graphs. } \description{ Count the number of isomorphic mappings between two graphs } \examples{ # colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL) } \references{ LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition}, 149--159, 2001. } \seealso{ Other graph isomorphism: \code{\link{count_subgraph_isomorphisms}}, \code{\link{graph_from_isomorphism_class}}, \code{\link{isomorphic}}, \code{\link{isomorphism_class}}, \code{\link{isomorphisms}}, \code{\link{subgraph_isomorphic}}, \code{\link{subgraph_isomorphisms}} } \concept{graph isomorphism} igraph/man/as.igraph.Rd0000644000175100001440000000153713430770475014500 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/hrg.R \name{as.igraph} \alias{as.igraph} \alias{as.igraph.igraphHRG} \title{Conversion to igraph} \usage{ as.igraph(x, ...) } \arguments{ \item{x}{The object to convert.} \item{\dots}{Additional arguments. None currently.} } \value{ All these functions return an igraph graph. } \description{ These fucntions convert various objects to igraph graphs. } \details{ You can use \code{as.igraph} to convert various objects to igraph graphs. Right now the following objects are supported: \itemize{ \item codeigraphHRG These objects are created by the \code{\link{fit_hrg}} and \code{\link{consensus_tree}} functions. } } \examples{ g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) as.igraph(hrg) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com}. } \keyword{graphs} igraph/man/union.igraph.Rd0000644000175100001440000000400013430770475015211 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/operators.R \name{union.igraph} \alias{union.igraph} \alias{graph.union} \alias{\%u\%} \title{Union of graphs} \usage{ \method{union}{igraph}(..., byname = "auto") } \arguments{ \item{\dots}{Graph objects or lists of graph objects.} \item{byname}{A logical scalar, or the character scalar \code{auto}. Whether to perform the operation based on symbolic vertex names. If it is \code{auto}, that means \code{TRUE} if all graphs are named and \code{FALSE} otherwise. A warning is generated if \code{auto} and some (but not all) graphs are named.} } \value{ A new graph object. } \description{ The union of two or more graphs are created. The graphs may have identical or overlapping vertex sets. } \details{ \code{union} creates the union of two or more graphs. Edges which are included in at least one graph will be part of the new graph. This function can be also used via the \%u\% operator. If the \code{byname} argument is \code{TRUE} (or \code{auto} and all graphs are named), then the operation is performed on symbolic vertex names instead of the internal numeric vertex ids. \code{union} keeps the attributes of all graphs. All graph, vertex and edge attributes are copied to the result. If an attribute is present in multiple graphs and would result a name clash, then this attribute is renamed by adding suffixes: _1, _2, etc. The \code{name} vertex attribute is treated specially if the operation is performed based on symbolic vertex names. In this case \code{name} must be present in all graphs, and it is not renamed in the result graph. An error is generated if some input graphs are directed and others are undirected. } \examples{ ## Union of two social networks with overlapping sets of actors net1 <- graph_from_literal(D-A:B:F:G, A-C-F-A, B-E-G-B, A-B, F-G, H-F:G, H-I-J) net2 <- graph_from_literal(D-A:F:Y, B-A-X-F-H-Z, F-Y) print_all(net1 \%u\% net2) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/is_chordal.Rd0000644000175100001440000000530613430770475014731 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/decomposition.R \name{is_chordal} \alias{is_chordal} \alias{is.chordal} \title{Chordality of a graph} \usage{ is_chordal(graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored, as the algorithm is defined for undirected graphs.} \item{alpha}{Numeric vector, the maximal chardinality ordering of the vertices. If it is \code{NULL}, then it is automatically calculated by calling \code{\link{max_cardinality}}, or from \code{alpham1} if that is given..} \item{alpham1}{Numeric vector, the inverse of \code{alpha}. If it is \code{NULL}, then it is automatically calculated by calling \code{\link{max_cardinality}}, or from \code{alpha}.} \item{fillin}{Logical scalar, whether to calculate the fill-in edges.} \item{newgraph}{Logical scalar, whether to calculate the triangulated graph.} } \value{ A list with three members: \item{chordal}{Logical scalar, it is \code{TRUE} iff the input graph is chordal.} \item{fillin}{If requested, then a numeric vector giving the fill-in edges. \code{NULL} otherwise.} \item{newgraph}{If requested, then the triangulated graph, an \code{igraph} object. \code{NULL} otherwise.} } \description{ A graph is chordal (or triangulated) if each of its cycles of four or more nodes has a chord, which is an edge joining two nodes that are not adjacent in the cycle. An equivalent definition is that any chordless cycles have at most three nodes. } \details{ The chordality of the graph is decided by first performing maximum cardinality search on it (if the \code{alpha} and \code{alpham1} arguments are \code{NULL}), and then calculating the set of fill-in edges. The set of fill-in edges is empty if and only if the graph is chordal. It is also true that adding the fill-in edges to the graph makes it chordal. } \examples{ ## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal(A-B:C:I, B-A:C:D, C-A:B:E:H, D-B:E:F, E-C:D:F:H, F-D:E:G, G-F:H, H-C:E:G:I, I-A:H) max_cardinality(g1) is_chordal(g1, fillin=TRUE) g2 <- graph_from_literal(A-B:E, B-A:E:F:D, C-E:D:G, D-B:F:E:C:G, E-A:B:C:D:F, F-B:D:E, G-C:D:H:I, H-G:I:J, I-G:H:J, J-H:I) max_cardinality(g2) is_chordal(g2, fillin=TRUE) } \references{ Robert E Tarjan and Mihalis Yannakakis. (1984). Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs. \emph{SIAM Journal of Computation} 13, 566--579. } \seealso{ \code{\link{max_cardinality}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/running_mean.Rd0000644000175100001440000000166213430770475015303 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/other.R \name{running_mean} \alias{running_mean} \alias{running.mean} \title{Running mean of a time series} \usage{ running_mean(v, binwidth) } \arguments{ \item{v}{The numeric vector.} \item{binwidth}{Numeric constant, the size of the bin, should be meaningful, ie. smaller than the length of \code{v}.} } \value{ A numeric vector of length \code{length(v)-binwidth+1} } \description{ \code{running_mean} calculates the running mean in a vector with the given bin width. } \details{ The running mean of \code{v} is a \code{w} vector of length \code{length(v)-binwidth+1}. The first element of \code{w} id the average of the first \code{binwidth} elements of \code{v}, the second element of \code{w} is the average of elements \code{2:(binwidth+1)}, etc. } \examples{ running_mean(1:100, 10) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{manip} igraph/man/neighbors.Rd0000644000175100001440000000233113430770475014575 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{neighbors} \alias{neighbors} \title{Neighboring (adjacent) vertices in a graph} \usage{ neighbors(graph, v, mode = c("out", "in", "all", "total")) } \arguments{ \item{graph}{The input graph.} \item{v}{The vertex of which the adjacent vertices are queried.} \item{mode}{Whether to query outgoing (\sQuote{out}), incoming (\sQuote{in}) edges, or both types (\sQuote{all}). This is ignored for undirected graphs.} } \value{ A vertex sequence containing the neighbors of the input vertex. } \description{ A vertex is a neighbor of another one (in other words, the two vertices are adjacent), if they are incident to the same edge. } \examples{ g <- make_graph("Zachary") n1 <- neighbors(g, 1) n34 <- neighbors(g, 34) intersection(n1, n34) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident_edges}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/graph_id.Rd0000644000175100001440000000136113430770475014374 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{graph_id} \alias{graph_id} \title{Get the id of a graph} \usage{ graph_id(x, ...) } \arguments{ \item{x}{A graph or a vertex sequence or an edge sequence.} \item{...}{Not used currently.} } \value{ The id of the graph, a character scalar. For vertex and edge sequences the id of the graph they were created from. } \description{ Graph ids are used to check that a vertex or edge sequence belongs to a graph. If you create a new graph by changing the structure of a graph, the new graph will have a new id. Changing the attributes will not change the id. } \examples{ g <- make_ring(10) graph_id(g) graph_id(V(g)) graph_id(E(g)) g2 <- g + 1 graph_id(g2) } igraph/man/triad_census.Rd0000644000175100001440000000357713430770475015315 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/motifs.R \name{triad_census} \alias{triad_census} \alias{triad.census} \title{Triad census, subgraphs with three vertices} \usage{ triad_census(graph) } \arguments{ \item{graph}{The input graph, it should be directed. An undirected graph results a warning, and undefined results.} } \value{ A numeric vector, the subgraph counts, in the order given in the above description. } \description{ This function counts the different subgraphs of three vertices in a graph. } \details{ Triad census was defined by David and Leinhardt (see References below). Every triple of vertices (A, B, C) are classified into the 16 possible states: \describe{ \item{003}{A,B,C, the empty graph.} \item{012}{A->B, C, the graph with a single directed edge.} \item{102}{A<->B, C, the graph with a mutual connection between two vertices.} \item{021D}{A<-B->C, the out-star.} \item{021U}{A->B<-C, the in-star.} \item{021C}{A->B->C, directed line.} \item{111D}{A<->B<-C.} \item{111U}{A<->B->C.} \item{030T}{A->B<-C, A->C.} \item{030C}{A<-B<-C, A->C.} \item{201}{A<->B<->C.} \item{120D}{A<-B->C, A<->C.} \item{120U}{A->B<-C, A<->C.} \item{120C}{A->B->C, A<->C.} \item{210}{A->B<->C, A<->C.} \item{300}{A<->B<->C, A<->C, the complete graph.} } This functions uses the RANDESU motif finder algorithm to find and count the subgraphs, see \code{\link{motifs}}. } \examples{ g <- sample_gnm(15, 45, directed = TRUE) triad_census(g) } \references{ See also Davis, J.A. and Leinhardt, S. (1972). The Structure of Positive Interpersonal Relations in Small Groups. In J. Berger (Ed.), Sociological Theories in Progress, Volume 2, 218-251. Boston: Houghton Mifflin. } \seealso{ \code{\link{dyad_census}} for classifying binary relationships, \code{\link{motifs}} for the underlying implementation. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/vertex_connectivity.Rd0000644000175100001440000000716513430770475016742 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{vertex_connectivity} \alias{vertex_connectivity} \alias{vertex.connectivity} \alias{vertex.disjoint.paths} \alias{cohesion} \alias{vertex_disjoint_paths} \alias{graph.cohesion} \alias{cohesion.igraph} \title{Vertex connectivity.} \usage{ vertex_connectivity(graph, source = NULL, target = NULL, checks = TRUE) \method{cohesion}{igraph}(x, checks = TRUE, ...) } \arguments{ \item{graph, x}{The input graph.} \item{source}{The id of the source vertex, for \code{vertex_connectivity} it can be \code{NULL}, see details below.} \item{target}{The id of the target vertex, for \code{vertex_connectivity} it can be \code{NULL}, see details below.} \item{checks}{Logical constant. Whether to check that the graph is connected and also the degree of the vertices. If the graph is not (strongly) connected then the connectivity is obviously zero. Otherwise if the minimum degree is one then the vertex connectivity is also one. It is a good idea to perform these checks, as they can be done quickly compared to the connectivity calculation itself. They were suggested by Peter McMahan, thanks Peter.} \item{...}{Ignored.} } \value{ A scalar real value. } \description{ The vertex connectivity of a graph or two vertices, this is recently also called group cohesion. } \details{ The vertex connectivity of two vertices (\code{source} and \code{target}) in a directed graph is the minimum number of vertices needed to remove from the graph to eliminate all (directed) paths from \code{source} to \code{target}. \code{vertex_connectivity} calculates this quantity if both the \code{source} and \code{target} arguments are given and they're not \code{NULL}. The vertex connectivity of a graph is the minimum vertex connectivity of all (ordered) pairs of vertices in the graph. In other words this is the minimum number of vertices needed to remove to make the graph not strongly connected. (If the graph is not strongly connected then this is zero.) \code{vertex_connectivity} calculates this quantitty if neither the \code{source} nor \code{target} arguments are given. (Ie. they are both \code{NULL}.) A set of vertex disjoint directed paths from \code{source} to \code{vertex} is a set of directed paths between them whose vertices do not contain common vertices (apart from \code{source} and \code{target}). The maximum number of vertex disjoint paths between two vertices is the same as their vertex connectivity in most cases (if the two vertices are not connected by an edge). The cohesion of a graph (as defined by White and Harary, see references), is the vertex connectivity of the graph. This is calculated by \code{cohesion}. These three functions essentially calculate the same measure(s), more precisely \code{vertex_connectivity} is the most general, the other two are included only for the ease of using more descriptive function names. } \examples{ g <- barabasi.game(100, m=1) g <- delete_edges(g, E(g)[ 100 \%--\% 1 ]) g2 <- barabasi.game(100, m=5) g2 <- delete_edges(g2, E(g2)[ 100 \%--\% 1]) vertex_connectivity(g, 100, 1) vertex_connectivity(g2, 100, 1) vertex_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5/50) g <- as.directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) cohesion(g) } \references{ White, Douglas R and Frank Harary 2001. The Cohesiveness of Blocks In Social Networks: Node Connectivity and Conditional Density. \emph{Sociological Methodology} 31 (1) : 305-359. } \seealso{ \code{\link{max_flow}}, \code{\link{edge_connectivity}}, \code{\link{edge_disjoint_paths}}, \code{\link{adhesion}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/stochastic_matrix.Rd0000644000175100001440000000312413430770476016347 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{stochastic_matrix} \alias{stochastic_matrix} \alias{get.stochastic} \title{Stochastic matrix of a graph} \usage{ stochastic_matrix(graph, column.wise = FALSE, sparse = igraph_opt("sparsematrices")) } \arguments{ \item{graph}{The input graph. Must be of class \code{igraph}.} \item{column.wise}{If \code{FALSE}, then the rows of the stochastic matrix sum up to one; otherwise it is the columns.} \item{sparse}{Logical scalar, whether to return a sparse matrix. The \code{Matrix} package is needed for sparse matrices.} } \value{ A regular matrix or a matrix of class \code{Matrix} if a \code{sparse} argument was \code{TRUE}. } \description{ Retrieves the stochastic matrix of a graph of class \code{igraph}. } \details{ Let \eqn{M} be an \eqn{n \times n}{n x n} adjacency matrix with real non-negative entries. Let us define \eqn{D = \textrm{diag}(\sum_{i}M_{1i}, \dots, \sum_{i}M_{ni})}{D=diag( sum(M[1,i], i), ..., sum(M[n,i], i) )} The (row) stochastic matrix is defined as \deqn{W = D^{-1}M,}{W = inv(D) M,} where it is assumed that \eqn{D} is non-singular. Column stochastic matrices are defined in a symmetric way. } \examples{ library(Matrix) ## g is a large sparse graph g <- sample_pa(n = 10^5, power = 2, directed = FALSE) W <- stochastic_matrix(g, sparse=TRUE) ## a dense matrix here would probably not fit in the memory class(W) ## may not be exactly 1, due to numerical errors max(abs(rowSums(W))-1) } \seealso{ \code{\link{as_adj}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/graph_attr.Rd0000644000175100001440000000217313430770475014754 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{graph_attr} \alias{graph_attr} \alias{get.graph.attribute} \alias{graph.attributes} \title{Graph attributes of a graph} \usage{ graph_attr(graph, name) } \arguments{ \item{graph}{Input graph.} \item{name}{The name of attribute to query. If missing, then all attributes are returned in a list.} } \value{ A list of graph attributes, or a single graph attribute. } \description{ Graph attributes of a graph } \examples{ g <- make_ring(10) graph_attr(g) graph_attr(g, "name") } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{set_vertex_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/man/layout_as_bipartite.Rd0000644000175100001440000000513713430770475016667 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_as_bipartite} \alias{layout_as_bipartite} \alias{layout.bipartite} \alias{as_bipartite} \title{Simple two-row layout for bipartite graphs} \usage{ layout_as_bipartite(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100) as_bipartite(...) } \arguments{ \item{graph}{The bipartite input graph. It should have a logical \sQuote{\code{type}} vertex attribute, or the \code{types} argument must be given.} \item{types}{A logical vector, the vertex types. If this argument is \code{NULL} (the default), then the \sQuote{\code{type}} vertex attribute is used.} \item{hgap}{Real scalar, the minimum horizontal gap between vertices in the same layer.} \item{vgap}{Real scalar, the distance between the two layers.} \item{maxiter}{Integer scalar, the maximum number of iterations in the crossing minimization stage. 100 is a reasonable default; if you feel that you have too many edge crossings, increase this.} \item{...}{Arguments to pass to \code{layout_as_bipartite}.} } \value{ A matrix with two columns and as many rows as the number of vertices in the input graph. } \description{ Minimize edge-crossings in a simple two-row (or column) layout for bipartite graphs. } \details{ The layout is created by first placing the vertices in two rows, according to their types. Then the positions within the rows are optimized to minimize edge crossings, using the Sugiyama algorithm (see \code{\link{layout_with_sugiyama}}). } \examples{ # Random bipartite graph inc <- matrix(sample(0:1, 50, replace = TRUE, prob=c(2,1)), 10, 5) g <- graph_from_incidence_matrix(inc) plot(g, layout = layout_as_bipartite, vertex.color=c("green","cyan")[V(g)$type+1]) # Two columns g \%>\% add_layout_(as_bipartite()) \%>\% plot() } \seealso{ \code{\link{layout_with_sugiyama}} Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/printr.Rd0000644000175100001440000000036113430770475014134 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/printr.R \docType{package} \name{printr} \alias{printr} \alias{printr-package} \title{Better printing of R packages} \description{ Better printing of R packages } igraph/man/layout_randomly.Rd0000644000175100001440000000307513430770475016045 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_randomly} \alias{layout_randomly} \alias{randomly} \title{Randomly place vertices on a plane or in 3d space} \usage{ layout_randomly(graph, dim = 2) randomly(...) } \arguments{ \item{graph}{The input graph.} \item{dim}{Integer scalar, the dimension of the space to use. It must be 2 or 3.} \item{...}{Parameters to pass to \code{layout_randomly}.} } \value{ A numeric matrix with two or three columns. } \description{ This function uniformly randomly places the vertices of the graph in two or three dimensions. } \details{ Randomly places vertices on a [-1,1] square (in 2d) or in a cube (in 3d). It is probably a useless layout, but it can use as a starting point for other layout generators. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_as_tree}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/laplacian_matrix.Rd0000644000175100001440000000366413430770476016140 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{laplacian_matrix} \alias{laplacian_matrix} \alias{graph.laplacian} \title{Graph Laplacian} \usage{ laplacian_matrix(graph, normalized = FALSE, weights = NULL, sparse = igraph_opt("sparsematrices")) } \arguments{ \item{graph}{The input graph.} \item{normalized}{Whether to calculate the normalized Laplacian. See definitions below.} \item{weights}{An optional vector giving edge weights for weighted Laplacian matrix. If this is \code{NULL} and the graph has an edge attribute called \code{weight}, then it will be used automatically. Set this to \code{NA} if you want the unweighted Laplacian on a graph that has a \code{weight} edge attribute.} \item{sparse}{Logical scalar, whether to return the result as a sparse matrix. The \code{Matrix} package is required for sparse matrices.} } \value{ A numeric matrix. } \description{ The Laplacian of a graph. } \details{ The Laplacian Matrix of a graph is a symmetric matrix having the same number of rows and columns as the number of vertices in the graph and element (i,j) is d[i], the degree of vertex i if if i==j, -1 if i!=j and there is an edge between vertices i and j and 0 otherwise. A normalized version of the Laplacian Matrix is similar: element (i,j) is 1 if i==j, -1/sqrt(d[i] d[j]) if i!=j and there is an edge between vertices i and j and 0 otherwise. The weighted version of the Laplacian simply works with the weighted degree instead of the plain degree. I.e. (i,j) is d[i], the weighted degree of vertex i if if i==j, -w if i!=j and there is an edge between vertices i and j with weight w, and 0 otherwise. The weighted degree of a vertex is the sum of the weights of its adjacent edges. } \examples{ g <- make_ring(10) laplacian_matrix(g) laplacian_matrix(g, norm=TRUE) laplacian_matrix(g, norm=TRUE, sparse=FALSE) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/keeping_degseq.Rd0000644000175100001440000000225013430770476015570 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rewire.R \name{keeping_degseq} \alias{keeping_degseq} \title{Graph rewiring while preserving the degree distribution} \usage{ keeping_degseq(loops = FALSE, niter = 100) } \arguments{ \item{loops}{Whether to allow destroying and creating loop edges.} \item{niter}{Number of rewiring trials to perform.} } \description{ This function can be used together with \code{\link{rewire}} to randomly rewire the edges while preserving the original graph's degree distribution. } \details{ The rewiring algorithm chooses two arbitrary edges in each step ((a,b) and (c,d)) and substitutes them with (a,d) and (c,b), if they not already exists in the graph. The algorithm does not create multiple edges. } \examples{ g <- make_ring(10) g \%>\% rewire(keeping_degseq(niter = 20)) \%>\% degree() print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10))) } \seealso{ \code{\link{sample_degseq}} Other rewiring functions: \code{\link{each_edge}}, \code{\link{rewire}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{rewiring functions} \keyword{graphs} igraph/man/min_st_separators.Rd0000644000175100001440000000252113430770475016352 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/flow.R \name{min_st_separators} \alias{min_st_separators} \alias{minimal.st.separators} \title{Minimum size vertex separators} \usage{ min_st_separators(graph) } \arguments{ \item{graph}{The input graph. It may be directed, but edge directions are ignored.} } \value{ A list of numeric vectors. Each vector contains a vertex set (defined by vertex ids), each vector is an (s,t) separator of the input graph, for some \eqn{s} and \eqn{t}. } \description{ List all vertex sets that are minimal (s,t) separators for some s and t, in an undirected graph. } \details{ A \eqn{(s,t)} vertex separator is a set of vertices, such that after their removal from the graph, there is no path between \eqn{s} and \eqn{t} in the graph. A \eqn{(s,t)} vertex separator is minimal if none of its subsets is an \eqn{(s,t)} vertex separator. } \examples{ ring <- make_ring(4) min_st_separators(ring) chvatal <- make_graph("chvatal") min_st_separators(chvatal) } \references{ Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating All the Minimal Separators of a Graph, In: Peter Widmayer, Gabriele Neyer and Stephan Eidenbenz (editors): \emph{Graph-theoretic concepts in computer science}, 1665, 167--172, 1999. Springer. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/edge_density.Rd0000644000175100001440000000306513430770476015266 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/structural.properties.R \name{edge_density} \alias{edge_density} \alias{graph.density} \title{Graph density} \usage{ edge_density(graph, loops = FALSE) } \arguments{ \item{graph}{The input graph.} \item{loops}{Logical constant, whether to allow loop edges in the graph. If this is TRUE then self loops are considered to be possible. If this is FALSE then we assume that the graph does not contain any loop edges and that loop edges are not meaningful.} } \value{ A real constant. This function returns \code{NaN} (=0.0/0.0) for an empty graph with zero vertices. } \description{ The density of a graph is the ratio of the number of edges and the number of possible edges. } \details{ Note that this function may return strange results for graph with multiple edges, density is ill-defined for graphs with multiple edges. } \examples{ g1 <- make_empty_graph(n=10) g2 <- make_full_graph(n=10) g3 <- sample_gnp(n=10, 0.4) # loop edges g <- graph( c(1,2, 2,2, 2,3) ) edge_density(g, loops=FALSE) # this is wrong!!! edge_density(g, loops=TRUE) # this is right!!! edge_density(simplify(g), loops=FALSE) # this is also right, but different } \references{ Wasserman, S., and Faust, K. (1994). Social Network Analysis: Methods and Applications. Cambridge: Cambridge University Press. } \seealso{ \code{\link{vcount}}, \code{\link{ecount}}, \code{\link{simplify}} to get rid of the multiple and/or loop edges. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/sample_degseq.Rd0000644000175100001440000000716113430770475015434 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_degseq} \alias{sample_degseq} \alias{degree.sequence.game} \alias{degseq} \title{Generate random graphs with a given degree sequence} \usage{ sample_degseq(out.deg, in.deg = NULL, method = c("simple", "vl", "simple.no.multiple")) degseq(...) } \arguments{ \item{out.deg}{Numeric vector, the sequence of degrees (for undirected graphs) or out-degrees (for directed graphs). For undirected graphs its sum should be even. For directed graphs its sum should be the same as the sum of \code{in.deg}.} \item{in.deg}{For directed graph, the in-degree sequence. By default this is \code{NULL} and an undirected graph is created.} \item{method}{Character, the method for generating the graph. Right now the \dQuote{simple}, \dQuote{simple.no.multiple} and \dQuote{vl} methods are implemented.} \item{...}{Passed to \code{sample_degree}.} } \value{ The new graph object. } \description{ It is often useful to create a graph with given vertex degrees. This is exactly what \code{sample_degseq} does. } \details{ The \dQuote{simple} method connects the out-stubs of the edges (undirected graphs) or the out-stubs and in-stubs (directed graphs) together. This way loop edges and also multiple edges may be generated. This method is not adequate if one needs to generate simple graphs with a given degree sequence. The multiple and loop edges can be deleted, but then the degree sequence is distorted and there is nothing to ensure that the graphs are sampled uniformly. The \dQuote{simple.no.multiple} method is similar to \dQuote{simple}, but tries to avoid multiple and loop edges and restarts the generation from scratch if it gets stuck. It is not guaranteed to sample uniformly from the space of all possible graphs with the given sequence, but it is relatively fast and it will eventually succeed if the provided degree sequence is graphical, but there is no upper bound on the number of iterations. The \dQuote{vl} method is a more sophisticated generator. The algorithm and the implementation was done by Fabien Viger and Matthieu Latapy. This generator always generates undirected, connected simple graphs, it is an error to pass the \code{in.deg} argument to it. The algorithm relies on first creating an initial (possibly unconnected) simple undirected graph with the given degree sequence (if this is possible at all). Then some rewiring is done to make the graph connected. Finally a Monte-Carlo algorithm is used to randomize the graph. The \dQuote{vl} samples from the undirected, connected simple graphs unformly. } \examples{ ## The simple generator g <- sample_degseq(rep(2,100)) degree(g) is_simple(g) # sometimes TRUE, but can be FALSE g2 <- sample_degseq(1:10, 10:1) degree(g2, mode="out") degree(g2, mode="in") ## The vl generator g3 <- sample_degseq(rep(2,100), method="vl") degree(g3) is_simple(g3) # always TRUE ## Exponential degree distribution ## Note, that we correct the degree sequence if its sum is odd degs <- sample(1:100, 100, replace=TRUE, prob=exp(-0.5*(1:100))) if (sum(degs) \%\% 2 != 0) { degs[1] <- degs[1] + 1 } g4 <- sample_degseq(degs, method="vl") all(degree(g4) == degs) ## Power-law degree distribution ## Note, that we correct the degree sequence if its sum is odd degs <- sample(1:100, 100, replace=TRUE, prob=(1:100)^-2) if (sum(degs) \%\% 2 != 0) { degs[1] <- degs[1] + 1 } g5 <- sample_degseq(degs, method="vl") all(degree(g5) == degs) } \seealso{ \code{\link{sample_gnp}}, \code{\link{sample_pa}}, \code{\link{simplify}} to get rid of the multiple and/or loops edges. } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/plot_dendrogram.communities.Rd0000644000175100001440000001004113430770475020325 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{plot_dendrogram} \alias{plot_dendrogram} \alias{dendPlot} \alias{plot_dendrogram.communities} \title{Community structure dendrogram plots} \usage{ plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...) \method{plot_dendrogram}{communities}(x, mode = igraph_opt("dend.plot.type"), ..., use.modularity = FALSE, palette = categorical_pal(8)) } \arguments{ \item{x}{An object containing the community structure of a graph. See \code{\link{communities}} for details.} \item{mode}{Which dendrogram plotting function to use. See details below.} \item{\dots}{Additional arguments to supply to the dendrogram plotting function.} \item{use.modularity}{Logical scalar, whether to use the modularity values to define the height of the branches.} \item{palette}{The color palette to use for colored plots.} } \value{ Returns whatever the return value was from the plotting function, \code{plot.phylo}, \code{plot.dendrogram} or \code{plot.hclust}. } \description{ Plot a hierarchical community structure as a dendrogram. } \details{ \code{plot_dendrogram} supports three different plotting functions, selected via the \code{mode} argument. By default the plotting function is taken from the \code{dend.plot.type} igraph option, and it has for possible values: \itemize{ \item \code{auto} Choose automatically between the plotting functions. As \code{plot.phylo} is the most sophisticated, that is choosen, whenever the \code{ape} package is available. Otherwise \code{plot.hclust} is used. \item \code{phylo} Use \code{plot.phylo} from the \code{ape} package. \item \code{hclust} Use \code{plot.hclust} from the \code{stats} package. \item \code{dendrogram} Use \code{plot.dendrogram} from the \code{stats} package. } The different plotting functions take different sets of arguments. When using \code{plot.phylo} (\code{mode="phylo"}), we have the following syntax: \preformatted{ plot_dendrogram(x, mode="phylo", colbar = palette(), edge.color = NULL, use.edge.length = FALSE, \dots) } The extra arguments not documented above: \itemize{ \item \code{colbar} Color bar for the edges. \item \code{edge.color} Edge colors. If \code{NULL}, then the \code{colbar} argument is used. \item \code{use.edge.length} Passed to \code{plot.phylo}. \item \code{dots} Attitional arguments to pass to \code{plot.phylo}. } The syntax for \code{plot.hclust} (\code{mode="hclust"}): \preformatted{ plot_dendrogram(x, mode="hclust", rect = 0, colbar = palette(), hang = 0.01, ann = FALSE, main = "", sub = "", xlab = "", ylab = "", \dots) } The extra arguments not documented above: \itemize{ \item \code{rect} A numeric scalar, the number of groups to mark on the dendrogram. The dendrogram is cut into exactly \code{rect} groups and they are marked via the \code{rect.hclust} command. Set this to zero if you don't want to mark any groups. \item \code{colbar} The colors of the rectanges that mark the vertex groups via the \code{rect} argument. \item \code{hang} Where to put the leaf nodes, this corresponds to the \code{hang} argument of \code{plot.hclust}. \item \code{ann} Whether to annotate the plot, the \code{ann} argument of \code{plot.hclust}. \item \code{main} The main title of the plot, the \code{main} argument of \code{plot.hclust}. \item \code{sub} The sub-title of the plot, the \code{sub} argument of \code{plot.hclust}. \item \code{xlab} The label on the horizontal axis, passed to \code{plot.hclust}. \item \code{ylab} The label on the vertical axis, passed to \code{plot.hclust}. \item \code{dots} Attitional arguments to pass to \code{plot.hclust}. } The syntax for \code{plot.dendrogram} (\code{mode="dendrogram"}): \preformatted{ plot_dendrogram(x, \dots) } The extra arguments are simply passed to \code{as.dendrogram}. } \examples{ karate <- make_graph("Zachary") fc <- cluster_fast_greedy(karate) plot_dendrogram(fc) } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/layout.deprecated.Rd0000644000175100001440000000147213430770475016236 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout.reingold.tilford} \alias{layout.reingold.tilford} \alias{layout.circle} \alias{layout.sphere} \alias{layout.random} \alias{layout.fruchterman.reingold} \alias{layout.kamada.kawai} \alias{layout.lgl} \title{Deprecated layout functions} \usage{ layout.reingold.tilford(..., params = list()) layout.circle(..., params = list()) layout.sphere(..., params = list()) layout.random(..., params = list()) layout.fruchterman.reingold(..., params = list()) layout.kamada.kawai(..., params = list()) layout.lgl(..., params = list()) } \arguments{ \item{...}{Passed to the new layout functions.} \item{params}{Passed to the new layout functions as arguments.} } \description{ Please use the new names, see \code{\link{layout_}}. } igraph/man/igraph_demo.Rd0000644000175100001440000000205513430770475015076 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/demo.R \name{igraph_demo} \alias{igraph_demo} \alias{igraphdemo} \title{Run igraph demos, step by step} \usage{ igraph_demo(which) } \arguments{ \item{which}{If not given, then the names of the available demos are listed. Otherwise it should be either a filename or the name of an igraph demo.} } \value{ Returns \code{NULL}, invisibly. } \description{ Run one of the accompanying igraph demos, somewhat interactively, using a Tk window. } \details{ This function provides a somewhat nicer interface to igraph demos that come with the package, than the standard \code{\link{demo}} function. Igraph demos are divided into chunks and \code{igraph_demo} runs them chunk by chunk, with the possibility of inspecting the workspace between two chunks. The \code{tcltk} package is needed for \code{igraph_demo}. } \examples{ igraph_demo() if (interactive()) { igraph_demo("centrality") } } \seealso{ \code{\link{demo}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/with_igraph_opt.Rd0000644000175100001440000000117213430770475016006 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/par.R \name{with_igraph_opt} \alias{with_igraph_opt} \title{Run code with a temporary igraph options setting} \usage{ with_igraph_opt(options, code) } \arguments{ \item{options}{A named list of the options to change.} \item{code}{The code to run.} } \value{ The result of the \code{code}. } \description{ Run code with a temporary igraph options setting } \examples{ with_igraph_opt( list(sparsematrices = FALSE), make_ring(10)[] ) igraph_opt("sparsematrices") } \seealso{ Other igraph options: \code{\link{igraph_options}} } \concept{igraph options} igraph/man/sample_gnp.Rd0000644000175100001440000000226313430770475014746 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_gnp} \alias{sample_gnp} \alias{gnp} \title{Generate random graphs according to the G(n,p) Erdos-Renyi model} \usage{ sample_gnp(n, p, directed = FALSE, loops = FALSE) gnp(...) } \arguments{ \item{n}{The number of vertices in the graph.} \item{p}{The probability for drawing an edge between two arbitrary vertices (G(n,p) graph).} \item{directed}{Logical, whether the graph will be directed, defaults to FALSE.} \item{loops}{Logical, whether to add loop edges, defaults to FALSE.} \item{...}{Passed to \code{sample_app}.} } \value{ A graph object. } \description{ This model is very simple, every possible edge is created with the same constant probability. } \details{ The graph has \sQuote{n} vertices and for each edge the probability that it is present in the graph is \sQuote{p}. } \examples{ g <- sample_gnp(1000, 1/1000) degree_distribution(g) } \references{ Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes Mathematicae} 6, 290--297 (1959). } \seealso{ \code{\link{sample_gnm}}, \code{\link{sample_pa}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/scg.Rd0000644000175100001440000002221013430770476013370 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/scg.R \name{scg} \alias{scg} \title{All-in-one Function for the SCG of Matrices and Graphs} \usage{ scg(X, ev, nt, groups = NULL, mtype = c("symmetric", "laplacian", "stochastic"), algo = c("optimum", "interv_km", "interv", "exact_scg"), norm = c("row", "col"), direction = c("default", "left", "right"), evec = NULL, p = NULL, use.arpack = FALSE, maxiter = 300, sparse = igraph_opt("sparsematrices"), output = c("default", "matrix", "graph"), semproj = FALSE, epairs = FALSE, stat.prob = FALSE) } \arguments{ \item{X}{The input graph or square matrix. Can be of class \code{igraph}, \code{matrix} or \code{Matrix}.} \item{ev}{A vector of positive integers giving the indexes of the eigenpairs to be preserved. For real eigenpairs, 1 designates the eigenvalue with largest algebraic value, 2 the one with second largest algebraic value, etc. In the complex case, it is the magnitude that matters.} \item{nt}{A vector of positive integers of length one or equal to \code{length(ev)}. When \code{algo} = \dQuote{optimum}, \code{nt} contains the number of groups used to partition each eigenvector separately. When \code{algo} is equal to \dQuote{interv\_km} or \dQuote{interv}, \code{nt} contains the number of intervals used to partition each eigenvector. The same partition size or number of intervals is used for each eigenvector if \code{nt} is a single integer. When \code{algo} = \dQuote{exact\_cg} this parameter is ignored.} \item{groups}{A vector of \code{nrow(X)} or \code{vcount(X)} integers labeling each group vertex in the partition. If this parameter is supplied most part of the function is bypassed.} \item{mtype}{Character scalar. The type of semi-projector to be used for the SCG. For now \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are available.} \item{algo}{Character scalar. The algorithm used to solve the SCG problem. Possible values are \dQuote{optimum}, \dQuote{interv\_km}, \dQuote{interv} and \dQuote{exact\_scg}.} \item{norm}{Character scalar. Either \dQuote{row} or \dQuote{col}. If set to \dQuote{row} the rows of the Laplacian matrix sum up to zero and the rows of the stochastic matrix sum up to one; otherwise it is the columns.} \item{direction}{Character scalar. When set to \dQuote{right}, resp. \dQuote{left}, the parameters \code{ev} and \code{evec} refer to right, resp. left eigenvectors. When passed \dQuote{default} it is the SCG described in the reference below that is applied (common usage). This argument is currently not implemented, and right eigenvectors are always used.} \item{evec}{A numeric matrix of (eigen)vectors to be preserved by the coarse graining (the vectors are to be stored column-wise in \code{evec}). If supplied, the eigenvectors should correspond to the indexes in \code{ev} as no cross-check will be done.} \item{p}{A probability vector of length \code{nrow(X)} (or \code{vcount(X)}). \code{p} is the stationary probability distribution of a Markov chain when \code{mtype} = \dQuote{stochastic}. This parameter is ignored in all other cases.} \item{use.arpack}{Logical scalar. When set to \code{TRUE} uses the function \code{\link{arpack}} to compute eigenpairs. This parameter should be set to \code{TRUE} if one deals with large (over a few thousands) AND sparse graphs or matrices. This argument is not implemented currently and LAPACK is used for solving the eigenproblems.} \item{maxiter}{A positive integer giving the maximum number of iterations for the k-means algorithm when \code{algo} = \dQuote{interv\_km}. This parameter is ignored in all other cases.} \item{sparse}{Logical scalar. Whether to return sparse matrices in the result, if matrices are requested.} \item{output}{Character scalar. Set this parameter to \dQuote{default} to retrieve a coarse-grained object of the same class as \code{X}.} \item{semproj}{Logical scalar. Set this parameter to \code{TRUE} to retrieve the semi-projectors of the SCG.} \item{epairs}{Logical scalar. Set this to \code{TRUE} to collect the eigenpairs computed by \code{scg}.} \item{stat.prob}{Logical scalar. This is to collect the stationary probability \code{p} when dealing with stochastic matrices.} } \value{ \item{Xt}{The coarse-grained graph, or matrix, possibly a sparse matrix.} \item{groups}{A vector of \code{nrow(X)} or \code{vcount(X)} integers giving the group label of each object (vertex) in the partition.} \item{L}{The semi-projector \eqn{L} if \code{semproj = TRUE}.} \item{R}{The semi-projector \eqn{R} if \code{semproj = TRUE}.} \item{values}{The computed eigenvalues if \code{epairs = TRUE}.} \item{vectors}{The computed or supplied eigenvectors if \code{epairs = TRUE}.} \item{p}{The stationary probability vector if \code{mtype = stochastic} and \code{stat.prob = TRUE}. For other matrix types this is missing.} } \description{ This function handles all the steps involved in the Spectral Coarse Graining (SCG) of some matrices and graphs as described in the reference below. } \details{ Please see \link{scg-method} for an introduction. In the following \eqn{V} is the matrix of eigenvectors for which the SCG is solved. \eqn{V} is calculated from \code{X}, if it is not given in the \code{evec} argument. The algorithm \dQuote{optimum} solves exactly the SCG problem for each eigenvector in \code{V}. The running time of this algorithm is \eqn{O(\max nt \cdot m^2)}{O(max(nt) m^2)} for the symmetric and laplacian matrix problems (i.e. when \code{mtype} is \dQuote{symmetric} or \dQuote{laplacian}. It is \eqn{O(m^3)} for the stochastic problem. Here \eqn{m} is the number of rows in \code{V}. In all three cases, the memory usage is \eqn{O(m^2)}. The algorithms \dQuote{interv} and \dQuote{interv\_km} solve approximately the SCG problem by performing a (for now) constant binning of the components of the eigenvectors, that is \code{nt[i]} constant-size bins are used to partition \code{V[,i]}. When \code{algo} = \dQuote{interv\_km}, the (Lloyd) k-means algorithm is run on each partition obtained by \dQuote{interv} to improve accuracy. Once a minimizing partition (either exact or approximate) has been found for each eigenvector, the final grouping is worked out as follows: two vertices are grouped together in the final partition if they are grouped together in each minimizing partition. In general the size of the final partition is not known in advance when \code{ncol(V)}>1. Finally, the algorithm \dQuote{exact\_scg} groups the vertices with equal components in each eigenvector. The last three algorithms essentially have linear running time and memory load. } \examples{ ## We are not running these examples any more, because they ## take a long time (~20 seconds) to run and this is against the CRAN ## repository policy. Copy and paste them by hand to your R prompt if ## you want to run them. \dontrun{ # SCG of a toy network g <- make_full_graph(5) \%du\% make_full_graph(5) \%du\% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6, 11)) cg <- scg(g, 1, 3, algo="exact_scg") #plot the result layout <- layout_with_kk(g) nt <- vcount(cg$Xt) col <- rainbow(nt) vsize <- table(cg$groups) ewidth <- round(E(cg$Xt)$weight,2) op <- par(mfrow=c(1,2)) plot(g, vertex.color = col[cg$groups], vertex.size = 20, vertex.label = NA, layout = layout) plot(cg$Xt, edge.width = ewidth, edge.label = ewidth, vertex.color = col, vertex.size = 20*vsize/max(vsize), vertex.label=NA, layout = layout_with_kk) par(op) ## SCG of real-world network library(igraphdata) data(immuno) summary(immuno) n <- vcount(immuno) interv <- c(100,100,50,25,12,6,3,2,2) cg <- scg(immuno, ev= n-(1:9), nt=interv, mtype="laplacian", algo="interv", epairs=TRUE) ## are the eigenvalues well-preserved? gt <- cg$Xt nt <- vcount(gt) Lt <- laplacian_matrix(gt) evalt <- eigen(Lt, only.values=TRUE)$values[nt-(1:9)] res <- cbind(interv, cg$values, evalt) res <- round(res,5) colnames(res) <- c("interv","lambda_i","lambda_tilde_i") rownames(res) <- c("N-1","N-2","N-3","N-4","N-5","N-6","N-7","N-8","N-9") print(res) ## use SCG to get the communities com <- scg(laplacian_matrix(immuno), ev=n-c(1,2), nt=2)$groups col <- rainbow(max(com)) layout <- layout_nicely(immuno) plot(immuno, layout=layout, vertex.size=3, vertex.color=col[com], vertex.label=NA) ## display the coarse-grained graph gt <- simplify(as.undirected(gt)) layout.cg <- layout_with_kk(gt) com.cg <- scg(laplacian_matrix(gt), nt-c(1,2), 2)$groups vsize <- sqrt(as.vector(table(cg$groups))) op <- par(mfrow=c(1,2)) plot(immuno, layout=layout, vertex.size=3, vertex.color=col[com], vertex.label=NA) plot(gt, layout=layout.cg, vertex.size=15*vsize/max(vsize), vertex.color=col[com.cg],vertex.label=NA) par(op) } } \references{ D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, Shrinking Matrices while Preserving their Eigenpairs with Application to the Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on Matrix Analysis and Applications}, 2008. \url{http://people.epfl.ch/david.morton} } \seealso{ \link{scg-method} for an introduction. \code{\link{scg_eps}}, \code{\link{scg_group}} and \code{\link{scg_semi_proj}}. } \author{ David Morton de Lachapelle, \url{http://people.epfl.ch/david.morton}. } \keyword{graphs} igraph/man/layout_as_tree.Rd0000644000175100001440000000732313430770475015642 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout.R \name{layout_as_tree} \alias{layout_as_tree} \alias{as_tree} \title{The Reingold-Tilford graph layout algorithm} \usage{ layout_as_tree(graph, root = numeric(), circular = FALSE, rootlevel = numeric(), mode = c("out", "in", "all"), flip.y = TRUE) as_tree(...) } \arguments{ \item{graph}{The input graph.} \item{root}{The index of the root vertex or root vertices. If this is a non-empty vector then the supplied vertex ids are used as the roots of the trees (or a single tree if the graph is connected). If it is an empty vector, then the root vertices are automatically calculated based on topological sorting, performed with the opposite mode than the \code{mode} argument. After the vertices have been sorted, one is selected from each component.} \item{circular}{Logical scalar, whether to plot the tree in a circular fashion. Defaults to \code{FALSE}, so the tree branches are going bottom-up (or top-down, see the \code{flip.y} argument.} \item{rootlevel}{This argument can be useful when drawing forests which are not trees (i.e. they are unconnected and have tree components). It specifies the level of the root vertices for every tree in the forest. It is only considered if the \code{roots} argument is not an empty vector.} \item{mode}{Specifies which edges to consider when building the tree. If it is \sQuote{out}, then only the outgoing, if it is \sQuote{in}, then only the incoming edges of a parent are considered. If it is \sQuote{all} then all edges are used (this was the behavior in igraph 0.5 and before). This parameter also influences how the root vertices are calculated, if they are not given. See the \code{roots} parameter.} \item{flip.y}{Logical scalar, whether to flip the \sQuote{y} coordinates. The default is flipping because that puts the root vertex on the top.} \item{...}{Passed to \code{layout_as_tree}.} } \value{ A numeric matrix with two columns, and one row for each vertex. } \description{ A tree-like layout, it is perfect for trees, acceptable for graphs with not too many cycles. } \details{ Arranges the nodes in a tree where the given node is used as the root. The tree is directed downwards and the parents are centered above its children. For the exact algorithm, the refernce below. If the given graph is not a tree, a breadth-first search is executed first to obtain a possible spanning tree. } \examples{ tree <- make_tree(20, 3) plot(tree, layout=layout_as_tree) plot(tree, layout=layout_as_tree(tree, flip.y=FALSE)) plot(tree, layout=layout_as_tree(tree, circular=TRUE)) tree2 <- make_tree(10, 3) + make_tree(10, 2) plot(tree2, layout=layout_as_tree) plot(tree2, layout=layout_as_tree(tree2, root=c(1,11), rootlevel=c(2,1))) } \references{ Reingold, E and Tilford, J (1981). Tidier drawing of trees. \emph{IEEE Trans. on Softw. Eng.}, SE-7(2):223--228. } \seealso{ Other graph layouts: \code{\link{add_layout_}}, \code{\link{component_wise}}, \code{\link{layout_as_bipartite}}, \code{\link{layout_as_star}}, \code{\link{layout_in_circle}}, \code{\link{layout_nicely}}, \code{\link{layout_on_grid}}, \code{\link{layout_on_sphere}}, \code{\link{layout_randomly}}, \code{\link{layout_with_dh}}, \code{\link{layout_with_fr}}, \code{\link{layout_with_gem}}, \code{\link{layout_with_graphopt}}, \code{\link{layout_with_kk}}, \code{\link{layout_with_lgl}}, \code{\link{layout_with_mds}}, \code{\link{layout_with_sugiyama}}, \code{\link{layout_}}, \code{\link{merge_coords}}, \code{\link{norm_coords}}, \code{\link{normalize}} } \author{ Tamas Nepusz \email{ntamas@gmail.com} and Gabor Csardi \email{csardi.gabor@gmail.com} } \concept{graph layouts} \keyword{graphs} igraph/man/delete_edges.Rd0000644000175100001440000000154313430770475015232 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{delete_edges} \alias{delete_edges} \alias{delete.edges} \title{Delete edges from a graph} \usage{ delete_edges(graph, edges) } \arguments{ \item{graph}{The input graph.} \item{edges}{The edges to remove, specified as an edge sequence.} } \value{ The graph, with the edges removed. } \description{ Delete edges from a graph } \examples{ g <- make_ring(10) \%>\% delete_edges(seq(1, 9, by = 2)) g g <- make_ring(10) \%>\% delete_edges("10|1") g } \seealso{ Other functions for manipulating graph structure: \code{\link{+.igraph}}, \code{\link{add_edges}}, \code{\link{add_vertices}}, \code{\link{delete_vertices}}, \code{\link{edge}}, \code{\link{igraph-minus}}, \code{\link{path}}, \code{\link{vertex}} } \concept{functions for manipulating graph structure} igraph/man/union.igraph.es.Rd0000644000175100001440000000251513430770475015630 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{union.igraph.es} \alias{union.igraph.es} \title{Union of edge sequences} \usage{ \method{union}{igraph.es}(...) } \arguments{ \item{...}{The edge sequences to take the union of.} } \value{ An edge sequence that contains all edges in the given sequences, exactly once. } \description{ Union of edge sequences } \details{ They must belong to the same graph. Note that this function has \sQuote{set} semantics and the multiplicity of edges is lost in the result. (This is to match the behavior of the based \code{unique} function.) } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(E(g)[1:6], E(g)[5:9], E(g)['A|J']) } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{rev.igraph.vs}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/graphlet_basis.Rd0000644000175100001440000000631213430770475015607 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/glet.R \name{graphlet_basis} \alias{graphlet_basis} \alias{graphlets} \alias{graphlets.project} \alias{graphlet_proj} \alias{graphlets.candidate.basis} \title{Graphlet decomposition of a graph} \usage{ graphlet_basis(graph, weights = NULL) graphlet_proj(graph, weights = NULL, cliques, niter = 1000, Mu = rep(1, length(cliques))) } \arguments{ \item{graph}{The input graph, edge directions are ignored. Only simple graph (i.e. graphs without self-loops and multiple edges) are supported.} \item{weights}{Edge weights. If the graph has a \code{weight} edge attribute and this argument is \code{NULL} (the default), then the \code{weight} edge attribute is used.} \item{cliques}{A list of vertex ids, the graphlet basis to use for the projection.} \item{niter}{Integer scalar, the number of iterations to perform.} \item{Mu}{Starting weights for the projection.} } \value{ \code{graphlets} returns a list with two members: \item{cliques}{A list of subgraphs, the candidate graphlet basis. Each subgraph is give by a vector of vertex ids.} \item{Mu}{The weights of the subgraphs in graphlet basis.} \code{graphlet_basis} returns a list of two elements: \item{cliques}{A list of subgraphs, the candidate graphlet basis. Each subgraph is give by a vector of vertex ids.} \item{thresholds}{The weight thresholds used for finding the subgraphs.} \code{graphlet_proj} return a numeric vector, the weights of the graphlet basis subgraphs. } \description{ Graphlet decomposition models a weighted undirected graph via the union of potentially overlapping dense social groups. This is done by a two-step algorithm. In the first step a candidate set of groups (a candidate basis) is created by finding cliques if the thresholded input graph. In the second step these the graph is projected on the candidate basis, resulting a weight coefficient for each clique in the candidate basis. } \details{ igraph contains three functions for performing the graph decomponsition of a graph. The first is \code{graphlets}, which performed both steps on the method and returns a list of subgraphs, with their corresponding weights. The second and third functions correspond to the first and second steps of the algorithm, and they are useful if the user wishes to perform them individually: \code{graphlet_basis} and \code{graphlet_proj}. } \examples{ ## Create an example graph first D1 <- matrix(0, 5, 5) D2 <- matrix(0, 5, 5) D3 <- matrix(0, 5, 5) D1[1:3, 1:3] <- 2 D2[3:5, 3:5] <- 3 D3[2:5, 2:5] <- 1 g <- simplify(graph_from_adjacency_matrix(D1 + D2 + D3, mode="undirected", weighted=TRUE)) V(g)$color <- "white" E(g)$label <- E(g)$weight E(g)$label.cex <- 2 E(g)$color <- "black" layout(matrix(1:6, nrow=2, byrow=TRUE)) co <- layout_with_kk(g) par(mar=c(1,1,1,1)) plot(g, layout=co) ## Calculate graphlets gl <- graphlets(g, niter=1000) ## Plot graphlets for (i in 1:length(gl$cliques)) { sel <- gl$cliques[[i]] V(g)$color <- "white" V(g)[sel]$color <- "#E495A5" E(g)$width <- 1 E(g)[ V(g)[sel] \%--\% V(g)[sel] ]$width <- 2 E(g)$label <- "" E(g)[ width == 2 ]$label <- round(gl$Mu[i], 2) E(g)$color <- "black" E(g)[ width == 2 ]$color <- "#E495A5" plot(g, layout=co) } } igraph/man/layout_with_drl.Rd0000644000175100001440000001120513430770475016026 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/layout_drl.R \name{layout_with_drl} \alias{layout_with_drl} \alias{layout.drl} \alias{drl_defaults} \alias{igraph.drl.coarsen} \alias{igraph.drl.coarsest} \alias{igraph.drl.default} \alias{igraph.drl.final} \alias{igraph.drl.refine} \alias{with_drl} \title{The DrL graph layout generator} \usage{ layout_with_drl(graph, use.seed = FALSE, seed = matrix(runif(vcount(graph) * 2), ncol = 2), options = drl_defaults$default, weights = E(graph)$weight, fixed = NULL, dim = 2) with_drl(...) } \arguments{ \item{graph}{The input graph, in can be directed or undirected.} \item{use.seed}{Logical scalar, whether to use the coordinates given in the \code{seed} argument as a starting point.} \item{seed}{A matrix with two columns, the starting coordinates for the vertices is \code{use.seed} is \code{TRUE}. It is ignored otherwise.} \item{options}{Options for the layout generator, a named list. See details below.} \item{weights}{Optional edge weights. Supply \code{NULL} here if you want to weight edges equally. By default the \code{weight} edge attribute is used if the graph has one. Larger weights correspond to stronger connections, and the vertices will be placed closer to each other.} \item{fixed}{Logical vector, it can be used to fix some vertices. All vertices for which it is \code{TRUE} are kept at the coordinates supplied in the \code{seed} matrix. It is ignored it \code{NULL} or if \code{use.seed} is \code{FALSE}.} \item{dim}{Either \sQuote{2} or \sQuote{3}, it specifies whether we want a two dimensional or a three dimensional layout. Note that because of the nature of the DrL algorithm, the three dimensional layout takes significantly longer to compute.} \item{...}{Passed to \code{layout_with_drl}.} } \value{ A numeric matrix with two columns. } \description{ DrL is a force-directed graph layout toolbox focused on real-world large-scale graphs, developed by Shawn Martin and colleagues at Sandia National Laboratories. } \details{ This function implements the force-directed DrL layout generator. The generator has the following parameters: \describe{ \item{edge.cut}{Edge cutting is done in the late stages of the algorithm in order to achieve less dense layouts. Edges are cut if there is a lot of stress on them (a large value in the objective function sum). The edge cutting parameter is a value between 0 and 1 with 0 representing no edge cutting and 1 representing maximal edge cutting. } \item{init.iterations}{Number of iterations in the first phase.} \item{init.temperature}{Start temperature, first phase.} \item{init.attraction}{Attraction, first phase.} \item{init.damping.mult}{Damping, first phase.} \item{liquid.iterations}{Number of iterations, liquid phase.} \item{liquid.temperature}{Start temperature, liquid phase.} \item{liquid.attraction}{Attraction, liquid phase.} \item{liquid.damping.mult}{Damping, liquid phase.} \item{expansion.iterations}{Number of iterations, expansion phase.} \item{expansion.temperature}{Start temperature, expansion phase.} \item{expansion.attraction}{Attraction, expansion phase.} \item{expansion.damping.mult}{Damping, expansion phase.} \item{cooldown.iterations}{Number of iterations, cooldown phase.} \item{cooldown.temperature}{Start temperature, cooldown phase.} \item{cooldown.attraction}{Attraction, cooldown phase.} \item{cooldown.damping.mult}{Damping, cooldown phase.} \item{crunch.iterations}{Number of iterations, crunch phase.} \item{crunch.temperature}{Start temperature, crunch phase.} \item{crunch.attraction}{Attraction, crunch phase.} \item{crunch.damping.mult}{Damping, crunch phase.} \item{simmer.iterations}{Number of iterations, simmer phase.} \item{simmer.temperature}{Start temperature, simmer phase.} \item{simmer.attraction}{Attraction, simmer phase.} \item{simmer.damping.mult}{Damping, simmer phase.} There are five pre-defined parameter settings as well, these are called \code{drl_defaults$default}, \code{drl_defaults$coarsen}, \code{drl_defaults$coarsest}, \code{drl_defaults$refine} and \code{drl_defaults$final}. } } \examples{ g <- as.undirected(sample_pa(100, m=1)) l <- layout_with_drl(g, options=list(simmer.attraction=0)) \dontrun{ plot(g, layout=l, vertex.size=3, vertex.label=NA) } } \references{ See the following technical report: Martin, S., Brown, W.M., Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) Layout. SAND Reports, 2008. 2936: p. 1-10. } \seealso{ \code{\link{layout}} for other layout generators. } \author{ Shawn Martin (\url{http://www.cs.otago.ac.nz/homepages/smartin/}) and Gabor Csardi \email{csardi.gabor@gmail.com} for the R/igraph interface and the three dimensional version. } \keyword{graphs} igraph/man/sample_islands.Rd0000644000175100001440000000164113430770475015616 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_islands} \alias{sample_islands} \alias{interconnected.islands.game} \title{A graph with subgraphs that are each a random graph.} \usage{ sample_islands(islands.n, islands.size, islands.pin, n.inter) } \arguments{ \item{islands.n}{The number of islands in the graph.} \item{islands.size}{The size of islands in the graph.} \item{islands.pin}{The probability to create each possible edge into each island.} \item{n.inter}{The number of edges to create between two islands.} } \value{ An igraph graph. } \description{ Create a number of Erdos-Renyi random graphs with identical parameters, and connect them with the specified number of edges. } \section{Examples}{ \preformatted{ g <- sample_islands(3, 10, 5/10, 1) oc <- cluster_optimal(g) oc } } \seealso{ \code{\link{sample_gnp}} } \author{ Samuel Thiriot } \keyword{graphs} igraph/man/incident_edges.Rd0000644000175100001440000000212413430770475015561 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/interface.R \name{incident_edges} \alias{incident_edges} \title{Incident edges of multiple vertices in a graph} \usage{ incident_edges(graph, v, mode = c("out", "in", "all", "total")) } \arguments{ \item{graph}{Input graph.} \item{v}{The vertices to query} \item{mode}{Whether to query outgoing (\sQuote{out}), incoming (\sQuote{in}) edges, or both types (\sQuote{all}). This is ignored for undirected graphs.} } \value{ A list of edge sequences. } \description{ This function is similar to \code{\link{incident}}, but it queries multiple vertices at once. } \examples{ g <- make_graph("Zachary") incident_edges(g, c(1, 34)) } \seealso{ Other structural queries: \code{\link{[.igraph}}, \code{\link{[[.igraph}}, \code{\link{adjacent_vertices}}, \code{\link{are_adjacent}}, \code{\link{ends}}, \code{\link{get.edge.ids}}, \code{\link{gorder}}, \code{\link{gsize}}, \code{\link{head_of}}, \code{\link{incident}}, \code{\link{is_directed}}, \code{\link{neighbors}}, \code{\link{tail_of}} } \concept{structural queries} igraph/man/compare.Rd0000644000175100001440000000527113430770475014251 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{compare} \alias{compare} \alias{compare.communities} \alias{compare.membership} \title{Compares community structures using various metrics} \usage{ compare(comm1, comm2, method = c("vi", "nmi", "split.join", "rand", "adjusted.rand")) } \arguments{ \item{comm1}{A \code{\link{communities}} object containing a community structure; or a numeric vector, the membership vector of the first community structure. The membership vector should contain the community id of each vertex, the numbering of the communities starts with one.} \item{comm2}{A \code{\link{communities}} object containing a community structure; or a numeric vector, the membership vector of the second community structure, in the same format as for the previous argument.} \item{method}{Character scalar, the comparison method to use. Possible values: \sQuote{vi} is the variation of information (VI) metric of Meila (2003), \sQuote{nmi} is the normalized mutual information measure proposed by Danon et al. (2005), \sQuote{split.join} is the split-join distance of can Dongen (2000), \sQuote{rand} is the Rand index of Rand (1971), \sQuote{adjusted.rand} is the adjusted Rand index by Hubert and Arabie (1985).} } \value{ A real number. } \description{ This function assesses the distance between two community structures. } \examples{ g <- make_graph("Zachary") sg <- cluster_spinglass(g) le <- cluster_leading_eigen(g) compare(sg, le, method="rand") compare(membership(sg), membership(le)) } \references{ Meila M: Comparing clusterings by the variation of information. In: Scholkopf B, Warmuth MK (eds.). \emph{Learning Theory and Kernel Machines: 16th Annual Conference on Computational Learning Theory and 7th Kernel Workshop}, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes in Computer Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1. Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community structure identification. \emph{J Stat Mech} P09008, 2005. van Dongen S: Performance criteria for graph clustering and Markov cluster experiments. Technical Report INS-R0012, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. Rand WM: Objective criteria for the evaluation of clustering methods. \emph{J Am Stat Assoc} 66(336):846-850, 1971. Hubert L and Arabie P: Comparing partitions. \emph{Journal of Classification} 2:193-218, 1985. } \seealso{ \code{\link{cluster_walktrap}}, \code{\link{cluster_edge_betweenness}}, \code{\link{cluster_fast_greedy}}, \code{\link{cluster_spinglass}} for various community detection methods. } \author{ Tamas Nepusz \email{ntamas@gmail.com} } \keyword{graphs} igraph/man/make_full_graph.Rd0000644000175100001440000000206013430770475015734 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_full_graph} \alias{make_full_graph} \alias{graph.full} \alias{full_graph} \title{Create a full graph} \usage{ make_full_graph(n, directed = FALSE, loops = FALSE) full_graph(...) } \arguments{ \item{n}{Number of vertices.} \item{directed}{Whether to create a directed graph.} \item{loops}{Whether to add self-loops to the graph.} \item{...}{Passed to \code{make_full_graph}.} } \value{ An igraph graph } \description{ Create a full graph } \examples{ make_full_graph(5) print_all(make_full_graph(4, directed = TRUE)) } \seealso{ Other determimistic constructors: \code{\link{graph_from_atlas}}, \code{\link{graph_from_edgelist}}, \code{\link{graph_from_literal}}, \code{\link{make_chordal_ring}}, \code{\link{make_empty_graph}}, \code{\link{make_full_citation_graph}}, \code{\link{make_graph}}, \code{\link{make_lattice}}, \code{\link{make_ring}}, \code{\link{make_star}}, \code{\link{make_tree}} } \concept{Full graph} \concept{determimistic constructors} igraph/man/rewire.Rd0000644000175100001440000000132413430770475014113 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/rewire.R \name{rewire} \alias{rewire} \title{Rewiring edges of a graph} \usage{ rewire(graph, with) } \arguments{ \item{graph}{The graph to rewire} \item{with}{A function call to one of the rewiring methods, see details below.} } \value{ The rewired graph. } \description{ See the links below for the implemented rewiring methods. } \examples{ g <- make_ring(10) g \%>\% rewire(each_edge(p = .1, loops = FALSE)) \%>\% plot(layout=layout_in_circle) print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10))) } \seealso{ Other rewiring functions: \code{\link{each_edge}}, \code{\link{keeping_degseq}} } \concept{rewiring functions} igraph/man/make_full_bipartite_graph.Rd0000644000175100001440000000327713430770475020012 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/make.R \name{make_full_bipartite_graph} \alias{make_full_bipartite_graph} \alias{graph.full.bipartite} \alias{full_bipartite_graph} \title{Create a full bipartite graph} \usage{ make_full_bipartite_graph(n1, n2, directed = FALSE, mode = c("all", "out", "in")) full_bipartite_graph(...) } \arguments{ \item{n1}{The number of vertices of the first kind.} \item{n2}{The number of vertices of the second kind.} \item{directed}{Logical scalar, whether the graphs is directed.} \item{mode}{Scalar giving the kind of edges to create for directed graphs. If this is \sQuote{\code{out}} then all vertices of the first kind are connected to the others; \sQuote{\code{in}} specifies the opposite direction; \sQuote{\code{all}} creates mutual edges. This argument is ignored for undirected graphs.x} \item{...}{Passed to \code{make_full_bipartite_graph}.} } \value{ An igraph graph, with the \sQuote{\code{type}} vertex attribute set. } \description{ Bipartite graphs are also called two-mode by some. This function creates a bipartite graph in which every possible edge is present. } \details{ Bipartite graphs have a \sQuote{\code{type}} vertex attribute in igraph, this is boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} for vertices of the second kind. } \examples{ g <- make_full_bipartite_graph(2, 3) g2 <- make_full_bipartite_graph(2, 3, dir=TRUE) g3 <- make_full_bipartite_graph(2, 3, dir=TRUE, mode="in") g4 <- make_full_bipartite_graph(2, 3, dir=TRUE, mode="all") } \seealso{ \code{\link{make_full_graph}} for creating one-mode full graphs } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/centr_clo_tmax.Rd0000644000175100001440000000246113430770475015622 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/centralization.R \name{centr_clo_tmax} \alias{centr_clo_tmax} \alias{centralization.closeness.tmax} \title{Theoretical maximum for closeness centralization} \usage{ centr_clo_tmax(graph = NULL, nodes = 0, mode = c("out", "in", "all", "total")) } \arguments{ \item{graph}{The input graph. It can also be \code{NULL}, if \code{nodes} is given.} \item{nodes}{The number of vertices. This is ignored if the graph is given.} \item{mode}{This is the same as the \code{mode} argument of \code{closeness}.} } \value{ Real scalar, the theoratical maximum (unnormalized) graph closeness centrality score for graphs with given order and other parameters. } \description{ See \code{\link{centralize}} for a summary of graph centralization. } \examples{ # A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_clo(g, normalized = FALSE)$centralization \%>\% `/`(centr_clo_tmax(g)) centr_clo(g, normalized = TRUE)$centralization } \seealso{ Other centralization related: \code{\link{centr_betw_tmax}}, \code{\link{centr_betw}}, \code{\link{centr_clo}}, \code{\link{centr_degree_tmax}}, \code{\link{centr_degree}}, \code{\link{centr_eigen_tmax}}, \code{\link{centr_eigen}}, \code{\link{centralize}} } \concept{centralization related} igraph/man/communities.Rd0000644000175100001440000002323113430770475015153 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/community.R \name{membership} \alias{membership} \alias{communities} \alias{algorithm} \alias{crossing} \alias{cutat} \alias{merges} \alias{sizes} \alias{cut_at} \alias{is.hierarchical} \alias{print.communities} \alias{plot.communities} \alias{length.communities} \alias{as.dendrogram.communities} \alias{as.hclust.communities} \alias{code_len} \alias{asPhylo} \alias{asPhylo.communities} \alias{showtrace} \alias{code.length} \alias{as_phylo} \alias{as_phylo.communities} \alias{show_trace} \alias{is_hierarchical} \alias{modularity.communities} \title{Functions to deal with the result of network community detection} \usage{ membership(communities) \method{print}{communities}(x, ...) \method{modularity}{communities}(x, ...) \method{length}{communities}(x) sizes(communities) algorithm(communities) merges(communities) crossing(communities, graph) code_len(communities) is_hierarchical(communities) \method{as.dendrogram}{communities}(object, hang = -1, use.modularity = FALSE, ...) \method{as.hclust}{communities}(x, hang = -1, use.modularity = FALSE, ...) as_phylo(x, ...) \method{as_phylo}{communities}(x, use.modularity = FALSE, ...) cut_at(communities, no, steps) show_trace(communities) \method{plot}{communities}(x, y, col = membership(x), mark.groups = communities(x), edge.color = c("black", "red")[crossing(x, y) + 1], ...) } \arguments{ \item{communities, x, object}{A \code{communities} object, the result of an igraph community detection function.} \item{\dots}{Additional arguments. \code{plot.communities} passes these to \code{\link{plot.igraph}}. The other functions silently ignore them.} \item{graph}{An igraph graph object, corresponding to \code{communities}.} \item{hang}{Numeric scalar indicating how the height of leaves should be computed from the heights of their parents; see \code{\link{plot.hclust}}.} \item{use.modularity}{Logical scalar, whether to use the modularity values to define the height of the branches.} \item{no}{Integer scalar, the desired number of communities. If too low or two high, then an error message is given. Exactly one of \code{no} and \code{steps} must be supplied.} \item{steps}{The number of merge operations to perform to produce the communities. Exactly one of \code{no} and \code{steps} must be supplied.} \item{y}{An igraph graph object, corresponding to the communities in \code{x}.} \item{col}{A vector of colors, in any format that is accepted by the regular R plotting methods. This vector gives the colors of the vertices explicitly.} \item{mark.groups}{A list of numeric vectors. The communities can be highlighted using colored polygons. The groups for which the polygons are drawn are given here. The default is to use the groups given by the communities. Supply \code{NULL} here if you do not want to highlight any groups.} \item{edge.color}{The colors of the edges. By default the edges within communities are colored green and other edges are red.} \item{membership}{Numeric vector, one value for each vertex, the membership vector of the community structure. Might also be \code{NULL} if the community structure is given in another way, e.g. by a merge matrix.} \item{algorithm}{If not \code{NULL} (meaning an unknown algorithm), then a character scalar, the name of the algorithm that produced the community structure.} \item{merges}{If not \code{NULL}, then the merge matrix of the hierarchical community structure. See \code{merges} below for more information on its format.} \item{modularity}{Numeric scalar or vector, the modularity value of the community structure. It can also be \code{NULL}, if the modularity of the (best) split is not available.} } \value{ \code{print} returns the \code{communities} object itself, invisibly. \code{length} returns an integer scalar. \code{sizes} returns a numeric vector. \code{membership} returns a numeric vector, one number for each vertex in the graph that was the input of the community detection. \code{modularity} returns a numeric scalar. \code{algorithm} returns a character scalar. \code{crossing} returns a logical vector. \code{is_hierarchical} returns a logical scalar. \code{merges} returns a two-column numeric matrix. \code{cut_at} returns a numeric vector, the membership vector of the vertices. \code{as.dendrogram} returns a \code{\link[stats]{dendrogram}} object. \code{show_trace} returns a character vector. \code{code_len} returns a numeric scalar for communities found with the InfoMAP method and \code{NULL} for other methods. \code{plot} for \code{communities} objects returns \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@gmail.com} } \description{ igraph community detection functions return their results as an object from the \code{communities} class. This manual page describes the operations of this class. } \details{ Community structure detection algorithms try to find dense subgraphs in directed or undirected graphs, by optimizing some criteria, and usually using heuristics. igraph implements a number of community detection methods (see them below), all of which return an object of the class \code{communities}. Because the community structure detection algorithms are different, \code{communities} objects do not always have the same structure. Nevertheless, they have some common operations, these are documented here. The \code{print} generic function is defined for \code{communities}, it prints a short summary. The \code{length} generic function call be called on \code{communities} and returns the number of communities. The \code{sizes} function returns the community sizes, in the order of their ids. \code{membership} gives the division of the vertices, into communities. It returns a numeric vector, one value for each vertex, the id of its community. Community ids start from one. Note that some algorithms calculate the complete (or incomplete) hierarchical structure of the communities, and not just a single partitioning. For these algorithms typically the membership for the highest modularity value is returned, but see also the manual pages of the individual algorithms. \code{communities} is also the name of a function, that returns a list of communities, each identified by their vertices. The vertices will have symbolic names if the \code{add.vertex.names} igraph option is set, and the graph itself was named. Otherwise numeric vertex ids are used. \code{modularity} gives the modularity score of the partitioning. (See \code{\link{modularity.igraph}} for details. For algorithms that do not result a single partitioning, the highest modularity value is returned. \code{algorithm} gives the name of the algorithm that was used to calculate the community structure. \code{crossing} returns a logical vector, with one value for each edge, ordered according to the edge ids. The value is \code{TRUE} iff the edge connects two different communities, according to the (best) membership vector, as returned by \code{membership()}. \code{is_hierarchical} checks whether a hierarchical algorithm was used to find the community structure. Some functions only make sense for hierarchical methods (e.g. \code{merges}, \code{cut_at} and \code{as.dendrogram}). \code{merges} returns the merge matrix for hierarchical methods. An error message is given, if a non-hierarchical method was used to find the community structure. You can check this by calling \code{is_hierarchical} on the \code{communities} object. \code{cut_at} cuts the merge tree of a hierarchical community finding method, at the desired place and returns a membership vector. The desired place can be expressed as the desired number of communities or as the number of merge steps to make. The function gives an error message, if called with a non-hierarchical method. \code{as.dendrogram} converts a hierarchical community structure to a \code{dendrogram} object. It only works for hierarchical methods, and gives an error message to others. See \code{\link[stats]{dendrogram}} for details. \code{as.hclust} is similar to \code{as.dendrogram}, but converts a hierarchical community structure to a \code{hclust} object. \code{as_phylo} converts a hierarchical community structure to a \code{phylo} object, you will need the \code{ape} package for this. \code{show_trace} works (currently) only for communities found by the leading eigenvector method (\code{\link{cluster_leading_eigen}}), and returns a character vector that gives the steps performed by the algorithm while finding the communities. \code{code_len} is defined for the InfoMAP method (\code{\link{cluster_infomap}} and returns the code length of the partition. It is possibly to call the \code{plot} function on \code{communities} objects. This will plot the graph (and uses \code{\link{plot.igraph}} internally), with the communities shown. By default it colores the vertices according to their communities, and also marks the vertex groups corresponding to the communities. It passes additional arguments to \code{\link{plot.igraph}}, please see that and also \code{\link{igraph.plotting}} on how to change the plot. } \examples{ karate <- make_graph("Zachary") wc <- cluster_walktrap(karate) modularity(wc) membership(wc) plot(wc, karate) } \seealso{ See \code{\link{plot_dendrogram}} for plotting community structure dendrograms. See \code{\link{compare}} for comparing two community structures on the same graph. The different methods for finding communities, they all return a \code{communities} object: \code{\link{cluster_edge_betweenness}}, \code{\link{cluster_fast_greedy}}, \code{\link{cluster_label_prop}}, \code{\link{cluster_leading_eigen}}, \code{\link{cluster_louvain}}, \code{\link{cluster_optimal}}, \code{\link{cluster_spinglass}}, \code{\link{cluster_walktrap}}. } \keyword{graphs} igraph/man/sample_sbm.Rd0000644000175100001440000000330313430770475014737 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/games.R \name{sample_sbm} \alias{sample_sbm} \alias{sbm.game} \alias{sbm} \title{Sample stochastic block model} \usage{ sample_sbm(n, pref.matrix, block.sizes, directed = FALSE, loops = FALSE) } \arguments{ \item{n}{Number of vertices in the graph.} \item{pref.matrix}{The matrix giving the Bernoulli rates. This is a \eqn{K\times K}{KxK} matrix, where \eqn{K} is the number of groups. The probability of creating an edge between vertices from groups \eqn{i} and \eqn{j} is given by element \eqn{(i,j)}. For undirected graphs, this matrix must be symmetric.} \item{block.sizes}{Numeric vector giving the number of vertices in each group. The sum of the vector must match the number of vertices.} \item{directed}{Logical scalar, whether to generate a directed graph.} \item{loops}{Logical scalar, whether self-loops are allowed in the graph.} \item{\dots}{Passed to \code{sample_sbm}.} } \value{ An igraph graph. } \description{ Sampling from the stochastic block model of networks } \details{ This function samples graphs from a stochastic block model by (doing the equivalent of) Bernoulli trials for each potential edge with the probabilities given by the Bernoulli rate matrix, \code{pref.matrix}. } \examples{ ## Two groups with not only few connection between groups pm <- cbind( c(.1, .001), c(.001, .05) ) g <- sample_sbm(1000, pref.matrix=pm, block.sizes=c(300,700)) g } \references{ Faust, K., & Wasserman, S. (1992a). Blockmodels: Interpretation and evaluation. \emph{Social Networks}, 14, 5--61. } \seealso{ \code{\link{sample_gnp}}, \code{\link{sample_gnm}} } \author{ Gabor Csardi \email{csardi.gabor@gmail.com} } \keyword{graphs} igraph/man/rev.igraph.vs.Rd0000644000175100001440000000206613430770475015316 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/iterators.R \name{rev.igraph.vs} \alias{rev.igraph.vs} \title{Reverse the order in a vertex sequence} \usage{ \method{rev}{igraph.vs}(x) } \arguments{ \item{x}{The vertex sequence to reverse.} } \value{ The reversed vertex sequence. } \description{ Reverse the order in a vertex sequence } \examples{ g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g) \%>\% rev() } \seealso{ Other vertex and edge sequence operations: \code{\link{c.igraph.es}}, \code{\link{c.igraph.vs}}, \code{\link{difference.igraph.es}}, \code{\link{difference.igraph.vs}}, \code{\link{igraph-es-indexing2}}, \code{\link{igraph-es-indexing}}, \code{\link{igraph-vs-indexing2}}, \code{\link{igraph-vs-indexing}}, \code{\link{intersection.igraph.es}}, \code{\link{intersection.igraph.vs}}, \code{\link{rev.igraph.es}}, \code{\link{union.igraph.es}}, \code{\link{union.igraph.vs}}, \code{\link{unique.igraph.es}}, \code{\link{unique.igraph.vs}} } \concept{vertex and edge sequence operations} igraph/man/set_vertex_attr.Rd0000644000175100001440000000240413430770475016040 0ustar hornikusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/attributes.R \name{set_vertex_attr} \alias{set_vertex_attr} \alias{set.vertex.attribute} \title{Set vertex attributes} \usage{ set_vertex_attr(graph, name, index = V(graph), value) } \arguments{ \item{graph}{The graph.} \item{name}{The name of the attribute to set.} \item{index}{An optional vertex sequence to set the attributes of a subset of vertices.} \item{value}{The new value of the attribute for all (or \code{index}) vertices.} } \value{ The graph, with the vertex attribute added or set. } \description{ Set vertex attributes } \examples{ g <- make_ring(10) \%>\% set_vertex_attr("label", value = LETTERS[1:10]) g plot(g) } \seealso{ Other graph attributes: \code{\link{delete_edge_attr}}, \code{\link{delete_graph_attr}}, \code{\link{delete_vertex_attr}}, \code{\link{edge_attr<-}}, \code{\link{edge_attr_names}}, \code{\link{edge_attr}}, \code{\link{graph_attr<-}}, \code{\link{graph_attr_names}}, \code{\link{graph_attr}}, \code{\link{igraph-dollar}}, \code{\link{igraph-vs-attributes}}, \code{\link{set_edge_attr}}, \code{\link{set_graph_attr}}, \code{\link{vertex_attr<-}}, \code{\link{vertex_attr_names}}, \code{\link{vertex_attr}} } \concept{graph attributes} igraph/DESCRIPTION0000644000175100001440000000362713567553110013266 0ustar hornikusersPackage: igraph Version: 1.2.4.2 Title: Network Analysis and Visualization Author: See AUTHORS file. Maintainer: Gábor Csárdi Description: Routines for simple graphs and network analysis. It can handle large graphs very well and provides functions for generating random and regular graphs, graph visualization, centrality methods and much more. Depends: methods Imports: graphics, grDevices, magrittr, Matrix, pkgconfig (>= 2.0.0), stats, utils Suggests: ape, digest, graph, igraphdata, rgl, scales, stats4, tcltk, testthat License: GPL (>= 2) URL: http://igraph.org SystemRequirements: gmp (optional), libxml2 (optional), glpk (optional) BugReports: https://github.com/igraph/igraph/issues Encoding: UTF-8 RoxygenNote: 6.1.1 Collate: 'adjacency.R' 'auto.R' 'assortativity.R' 'attributes.R' 'basic.R' 'bipartite.R' 'centrality.R' 'centralization.R' 'cliques.R' 'cocitation.R' 'cohesive.blocks.R' 'community.R' 'components.R' 'console.R' 'conversion.R' 'data_frame.R' 'decomposition.R' 'degseq.R' 'demo.R' 'embedding.R' 'epi.R' 'fit.R' 'flow.R' 'foreign.R' 'games.R' 'glet.R' 'hrg.R' 'igraph-package.R' 'incidence.R' 'indexing.R' 'interface.R' 'iterators.R' 'layout.R' 'layout_drl.R' 'lazyeval.R' 'make.R' 'minimum.spanning.tree.R' 'motifs.R' 'nexus.R' 'operators.R' 'other.R' 'package.R' 'palette.R' 'par.R' 'paths.R' 'plot.R' 'plot.common.R' 'plot.shapes.R' 'pp.R' 'print.R' 'printr.R' 'random_walk.R' 'rewire.R' 'scan.R' 'scg.R' 'sgm.R' 'similarity.R' 'simple.R' 'sir.R' 'socnet.R' 'sparsedf.R' 'structural.properties.R' 'structure.info.R' 'test.R' 'tkplot.R' 'topology.R' 'triangles.R' 'utils.R' 'uuid.R' 'versions.R' 'weakref.R' 'zzz-deprecate.R' NeedsCompilation: yes Packaged: 2019-11-13 08:31:37 UTC; maechler Repository: CRAN Date/Publication: 2019-11-27 20:02:16 UTC igraph/tests/0000755000175100001440000000000013562737551012722 5ustar hornikusersigraph/tests/testthat/0000755000175100001440000000000013567553110014552 5ustar hornikusersigraph/tests/testthat/test-graph-ids.R0000644000175100001440000000264413177712334017540 0ustar hornikusers context("Graph ids") test_that("ids change when updating the graph", { g <- make_ring(10) g2 <- g + 1 g3 <- g + edge(1,5) g4 <- set_vertex_attr(g, "color", value = "red") expect_false( graph_id(g) == graph_id(g2) ) expect_false( graph_id(g) == graph_id(g3) ) }) test_that("ids don't change when attributes change", { g <- make_ring(10) V(g)$color <- "green" E(g)$weight <- 1 g2 <- set_vertex_attr(g, "color", value = "red") g3 <- set_edge_attr(g, "weight", value = 3) g4 <- set_vertex_attr(g, "name", value = LETTERS[1:10]) g5 <- set_edge_attr(g, "name", value = LETTERS[1:10]) expect_equal(graph_id(g), graph_id(g2)) expect_equal(graph_id(g), graph_id(g3)) expect_equal(graph_id(g), graph_id(g4)) expect_equal(graph_id(g), graph_id(g5)) }) test_that("ids of vertex and edge sequences are correct", { g <- make_ring(10) vs <- V(g) vs2 <- vs[1:5] es <- E(g) es2 <- es[1:5] expect_equal(graph_id(g), graph_id(vs)) expect_equal(graph_id(g), graph_id(vs2)) expect_equal(graph_id(g), graph_id(es)) expect_equal(graph_id(g), graph_id(es2)) }) test_that("ids of vertex and edge sequence remain after removing graph", { g <- make_ring(10) id <- graph_id(g) vs <- V(g) vs2 <- vs[1:5] es <- E(g) es2 <- es[1:5] rm(g) gc() expect_equal(id, graph_id(vs)) expect_equal(id, graph_id(vs2)) expect_equal(id, graph_id(es)) expect_equal(id, graph_id(es2)) }) igraph/tests/testthat/test_degree.sequence.game.R0000644000175100001440000000173413177712334021715 0ustar hornikusers context("sample_degseq") test_that("sample_degseq works", { library(igraph) gc <- function(graph) { clu <- components(graph) induced_subgraph(graph, which(clu$membership==which.max(clu$csize))) } g <- gc(sample_gnp(1000, 2/1000)) nG <- sample_degseq(degree(g), method="simple") expect_that(degree(nG), equals(degree(g))) nG <- sample_degseq(degree(g), method="vl") expect_that(degree(nG), equals(degree(g))) expect_that(is_connected(nG), is_true()) expect_that(is_simple(nG), is_true()) ##### g <- sample_gnp(1000, 1/1000) nG <- sample_degseq(degree(g), method="simple") expect_that(degree(nG), equals(degree(g))) g2 <- sample_gnp(1000, 2/1000, dir=TRUE) nG2 <- sample_degseq(degree(g, mode="out"), degree(g, mode="in"), method="simple") expect_that(degree(nG, mode="out"), equals(degree(g, mode="out"))) expect_that(degree(nG, mode="in"), equals(degree(g, mode="in"))) }) igraph/tests/testthat/test_edge.betweenness.community.R0000644000175100001440000000174713177712334023217 0ustar hornikusers context("cluster_edge_betweenness") test_that("cluster_edge_betweenness works", { library(igraph) g <- make_graph("Zachary") ebc <- cluster_edge_betweenness(g) expect_that(max(ebc$modularity), equals(modularity(g, ebc$membership))) expect_that(as.vector(membership(ebc)), equals(c(1, 1, 2, 1, 3, 3, 3, 1, 4, 5, 3, 1, 1, 1, 4, 4, 3, 1, 4, 1, 4, 1, 4, 4, 2, 2, 4, 2, 2, 4, 4, 2, 4, 4))) expect_that(length(ebc), equals(5)) expect_that(as.numeric(sizes(ebc)), equals(c(10, 6, 5, 12, 1))) d <- as.dendrogram(ebc) expect_that(print(d), prints_text("2 branches.*34 members.*height 33")) expect_that(print(d[[1]]), prints_text("2 branches.*15 members.*height 31")) expect_that(print(d[[2]]), prints_text("2 branches.*19 members.*height 32")) m2 <- cut_at(ebc, no=3) expect_that(modularity(g, m2), equals(ebc$modularity[length(ebc$modularity)-2])) }) igraph/tests/testthat/test_operators4.R0000644000175100001440000002355713177712334020054 0ustar hornikusers context("operators on named graphs") test_that("disjoint union works for named graphs", { library(igraph) g1 <- g2 <- make_ring(10) g1$foo <- "bar" V(g1)$name <- letters[ 1:10] V(g2)$name <- letters[11:20] E(g1)$weight <- 1:10 E(g2)$weight <- 10:1 V(g1)$a1 <- 1:10 V(g2)$a2 <- 11:20 E(g1)$b1 <- 1:10 E(g2)$b2 <- 11:20 g <- disjoint_union(g1, g2) expect_that(sort(graph_attr_names(g)), equals(c("circular_1", "circular_2", "foo", "mutual_1", "mutual_2", "name_1", "name_2"))) expect_that(sort(vertex_attr_names(g)), equals(c("a1", "a2", "name"))) expect_that(sort(edge_attr_names(g)), equals(c("b1", "b2", "weight"))) expect_that(V(g)$name, equals(letters[1:20])) expect_that(V(g)$a1, equals(c(1:10, rep(NA, 10)))) expect_that(V(g)$a2, equals(c(rep(NA, 10), 11:20))) expect_that(E(g)$weight, equals(c(1:10, 10:1))) expect_that(E(g)$b1, equals(c(1:10, rep(NA, 10)))) expect_that(E(g)$b2, equals(c(rep(NA, 10), 11:20))) }) test_that("disjoint union gives warning for non-unique vertex names", { library(igraph) g1 <- make_ring(5); V(g1)$name <- letters[1:5] g2 <- make_ring(5); V(g2)$name <- letters[5:9] expect_that(disjoint_union(g1, g2), gives_warning("Duplicate vertex names in disjoint union")) }) test_that("union of unnamed graphs works", { library(igraph) g1 <- make_ring(10) g2 <- make_ring(13) g1$foo <- "bar" E(g1)$weight <- 1:10 E(g2)$weight <- 13:1 V(g1)$a1 <- 1:10 V(g2)$a2 <- 11:23 E(g1)$b1 <- letters[1:10] E(g2)$b2 <- letters[11:23] g <- graph.union(g1, g2) expect_that(sort(graph_attr_names(g)), equals(c("circular_1", "circular_2", "foo", "mutual_1", "mutual_2", "name_1", "name_2"))) expect_that(sort(vertex_attr_names(g)), equals(c("a1", "a2"))) expect_that(sort(edge_attr_names(g)), equals(c("b1", "b2", "weight_1", "weight_2"))) df1 <- as_data_frame(g) df1 <- df1[ order(df1$from, df1$to), c(1,2,3,5,4,6)] df2 <- merge(as_data_frame(g1), as_data_frame(g2), by=c("from", "to"), all=TRUE) rownames(df1) <- seq_len(nrow(df1)) colnames(df2) <- c("from", "to", "weight_1", "b1", "weight_2", "b2") expect_that(df1, equals(df2)) }) test_that("union of named graphs works", { library(igraph) g1 <- make_ring(10) g2 <- make_ring(13) V(g1)$name <- letters[seq_len(vcount(g1))] V(g2)$name <- letters[seq_len(vcount(g2))] g1$foo <- "bar" E(g1)$weight <- 1:10 E(g2)$weight <- 13:1 V(g1)$a1 <- 1:10 V(g2)$a2 <- 11:23 E(g1)$b1 <- letters[1:10] E(g2)$b2 <- letters[11:23] g <- graph.union(g1, g2) expect_that(sort(graph_attr_names(g)), equals(c("circular_1", "circular_2", "foo", "mutual_1", "mutual_2", "name_1", "name_2"))) expect_that(sort(vertex_attr_names(g)), equals(c("a1", "a2", "name"))) expect_that(sort(edge_attr_names(g)), equals(c("b1", "b2", "weight_1", "weight_2"))) df1 <- as_data_frame(g, what="both") g.v <- read.table(stringsAsFactors=FALSE, textConnection(" a1 a2 name a 1 11 a b 2 12 b c 3 13 c d 4 14 d e 5 15 e f 6 16 f g 7 17 g h 8 18 h i 9 19 i j 10 20 j k NA 21 k l NA 22 l m NA 23 m ")) expect_that(df1$vertices, equals(g.v)) g.e <- read.table(stringsAsFactors=FALSE, textConnection(" from to weight_1 weight_2 b1 b2 1 l m NA 2 NA v 2 k l NA 3 NA u 3 j k NA 4 NA t 4 i j 9 5 i s 5 h i 8 6 h r 6 g h 7 7 g q 7 f g 6 8 f p 8 e f 5 9 e o 9 d e 4 10 d n 10 c d 3 11 c m 11 b c 2 12 b l 12 a m NA 1 NA w 13 a j 10 NA j NA 14 a b 1 13 a k ")) rownames(df1$edges) <- rownames(df1$edges) expect_that(df1$edges, equals(g.e)) }) test_that("intersection of named graphs works", { library(igraph) g1 <- make_ring(10) g2 <- make_ring(13) V(g1)$name <- letters[V(g1)] V(g2)$name <- letters[V(g2)] g1$foo <- "bar" E(g1)$weight <- 1:10 E(g2)$weight <- 13:1 V(g1)$a1 <- 1:10 V(g2)$a2 <- 11:23 E(g1)$b1 <- letters[1:10] E(g2)$b2 <- letters[11:23] g <- intersection(g1, g2, keep.all.vertices=FALSE) expect_that(sort(graph_attr_names(g)), equals(c("circular_1", "circular_2", "foo", "mutual_1", "mutual_2", "name_1", "name_2"))) expect_that(sort(vertex_attr_names(g)), equals(c("a1", "a2", "name"))) expect_that(sort(edge_attr_names(g)), equals(c("b1", "b2", "weight_1", "weight_2"))) df1 <- as_data_frame(g, what="both") g.e <- read.table(stringsAsFactors=FALSE, textConnection(" from to weight_1 weight_2 b1 b2 1 i j 9 5 i s 2 h i 8 6 h r 3 g h 7 7 g q 4 f g 6 8 f p 5 e f 5 9 e o 6 d e 4 10 d n 7 c d 3 11 c m 8 b c 2 12 b l 9 a b 1 13 a k ")) rownames(df1$edges) <- rownames(df1$edges) expect_that(df1$edges, equals(g.e)) g.v <- read.table(stringsAsFactors=FALSE, textConnection(" a1 a2 name a 1 11 a b 2 12 b c 3 13 c d 4 14 d e 5 15 e f 6 16 f g 7 17 g h 8 18 h i 9 19 i j 10 20 j ")) expect_that(df1$vertices, equals(g.v)) gg <- intersection(g1, g2, keep.all.vertices=TRUE) df2 <- as_data_frame(gg, what="both") rownames(df2$edges) <- rownames(df2$edges) expect_that(df2$edges, equals(g.e)) gg.v <- read.table(stringsAsFactors=FALSE, textConnection(" a1 a2 name a 1 11 a b 2 12 b c 3 13 c d 4 14 d e 5 15 e f 6 16 f g 7 17 g h 8 18 h i 9 19 i j 10 20 j k NA 21 k l NA 22 l m NA 23 m ")) expect_that(df2$vertices, equals(gg.v)) }) test_that("difference of named graphs works", { library(igraph) g1 <- make_ring(10) g2 <- make_star(11, center=11, mode="undirected") V(g1)$name <- letters[1:10] V(g2)$name <- letters[1:11] g <- g1 %u% g2 sg <- make_ring(4) V(sg)$name <- letters[c(1,2,3,11)] df1 <- as_data_frame(g - sg, what="both") t1.e <- read.table(stringsAsFactors=FALSE, textConnection(" from to 1 a j 2 b k 3 c d 4 j k 5 i k 6 h k 7 g k 8 f k 9 e k 10 d k 11 d e 12 e f 13 f g 14 g h 15 h i 16 i j ")) rownames(df1$edges) <- rownames(df1$edges) expect_that(df1$edges, equals(t1.e)) expect_that(df1$vertices, equals(data.frame(row.names=letters[1:11], name=letters[1:11], stringsAsFactors=FALSE))) gg <- sg - g expect_that(ecount(gg), equals(0)) expect_that(V(gg)$name, equals(letters[c(1:3,11)])) }) test_that("compose works for named graphs", { library(igraph) g1 <- graph_from_literal( A-B:D:E, B-C:D, C-D, D-E ) g2 <- graph_from_literal( A-B-E-A ) V(g1)$bar1 <- seq_len(vcount(g1)) V(g2)$bar2 <- seq_len(vcount(g2)) V(g1)$foo <- letters[seq_len(vcount(g1))] V(g2)$foo <- letters[seq_len(vcount(g2))] E(g1)$bar1 <- seq_len(ecount(g1)) E(g2)$bar2 <- seq_len(ecount(g2)) E(g1)$foo <- letters[seq_len(ecount(g1))] E(g2)$foo <- letters[seq_len(ecount(g2))] g <- compose(g1, g2) df <- as_data_frame(g, what="both") df.v <- read.table(stringsAsFactors=FALSE, textConnection(" bar1 foo_1 foo_2 bar2 name A 1 a a 1 A B 2 b b 2 B D 3 c NA NA D E 4 d c 3 E C 5 e NA NA C ")) expect_that(df$vertices, equals(df.v)) df.e <- read.table(stringsAsFactors=FALSE, textConnection(" from to bar1 foo_1 foo_2 bar2 1 A B 3 c c 3 2 A A 3 c b 2 3 A E 1 a c 3 4 A A 1 a a 1 5 B E 1 a b 2 6 B B 1 a a 1 7 B D 6 f c 3 8 A D 6 f b 2 9 D E 4 d c 3 10 A D 4 d a 1 11 D E 2 b b 2 12 B D 2 b a 1 13 E E 3 c b 2 14 B E 3 c a 1 15 E C 5 e c 3 16 A C 5 e a 1 ")) rownames(df$edges) <- rownames(df$edges) expect_that(df$edges, equals(df.e)) }) test_that("intersection of non-named graphs keeps attributes properly", { library(igraph) set.seed(42) g <- sample_gnp(10, 1/2) g2 <- sample_gnp(10, 1/2) E(g)$weight <- sample(ecount(g)) E(g2)$weight <- sample(ecount(g2)) gi <- intersection(g, g2) rn <- function(D) { rownames(D) <- paste(D[,1], D[,2], sep="-") D } df <- rn(as_data_frame(g)) df2 <- rn(as_data_frame(g2)) dfi <- rn(as_data_frame(gi)) expect_that(df[rownames(dfi), ], is_equivalent_to(dfi[, 1:3])) expect_that(df2[rownames(dfi), ], is_equivalent_to(dfi[, c(1,2,4)])) }) test_that("union of non-named graphs keeps attributes properly", { library(igraph) set.seed(42) g <- sample_gnp(10, 1/2) g2 <- sample_gnp(10, 1/2) E(g)$weight <- sample(ecount(g)) E(g2)$weight <- sample(ecount(g2)) gu <- graph.union(g, g2) rn <- function(D) { rownames(D) <- paste(D[,1], D[,2], sep="-") D } df <- rn(as_data_frame(g)) df2 <- rn(as_data_frame(g2)) dfu <- rn(as_data_frame(gu)) expect_that(dfu[rownames(df), 1:3], is_equivalent_to(df)) expect_that(dfu[rownames(df2), c(1,2,4)], is_equivalent_to(df2)) expect_that(dfu[!rownames(dfu) %in% rownames(df), 3], equals(rep(NA_real_, ecount(gu)-ecount(g)))) expect_that(dfu[!rownames(dfu) %in% rownames(df2), 4], equals(rep(NA_real_, ecount(gu)-ecount(g2)))) }) igraph/tests/testthat/test_layout.mds.R0000644000175100001440000000143613247212322020027 0ustar hornikusers context("layout_with_mds") test_that("layout_with_mds works", { library(igraph) ## A tree g <- make_tree(10, 2, "undirected") mymds <- function(g) { sp <- distances(g) sp <- sp * sp sp <- sp - rowMeans(sp) - rep(rowMeans(sp), each=nrow(sp)) + mean(sp) sp <- sp / -2 ei <- eigen(sp) va <- sqrt(abs(ei$values[1:2])) ei$vectors[,1:2] * rep(va, each=nrow(sp)) } expect_that(mymds(g), equals(layout_with_mds(g))) ## plot(g, layout=ll) ## A graph with multiple components, just test that it runs set.seed(42) g <- make_ring(10) + make_ring(3) expect_that(ncol(layout_with_mds(g)), equals(2)) ## Small stress test for (i in 1:10) { g <- sample_gnp(100, 2/100) l <- layout_with_mds(g) expect_that(ncol(l), equals(2)) } }) igraph/tests/testthat/test_graph.adhesion.R0000644000175100001440000000305713177712334020635 0ustar hornikusers context("adhesion") test_that("adhesion works", { library(igraph) g <- make_graph("Zachary") expect_that(adhesion(g), equals(1)) expect_that(cohesion(g), equals(1)) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) expect_that(adhesion(kite), equals(1)) expect_that(cohesion(kite), equals(1)) camp <- graph_from_literal(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael) expect_that(adhesion(camp), equals(2)) expect_that(cohesion(camp), equals(2)) }) igraph/tests/testthat/test_adjacency.spectral.embedding.R0000644000175100001440000002001013177712334023401 0ustar hornikusers context("adjacency spectral embedding") std <- function(x) { x <- zapsmall(x) apply(x, 2, function(col) { if (any(col < 0) && col[which(col != 0)[1]] < 0) { -col } else { col } }) } mag_order <- function(x) { order(abs(x), sign(x), decreasing=TRUE) } mag_sort <- function(x) { x[mag_order(x)] } test_that("Undirected, unweighted case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 15, type="gnm", directed=FALSE) no <- 7 A <- g[] A <- A + 1/2 * diag(degree(g)) ss <- eigen(A) U <- std(ss$vectors) X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) au_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=TRUE) as_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=FALSE) expect_that(as_la$D, equals(ss$values[1:no])) expect_that(au_la$D, equals(ss$values[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(std(au_la$X), equals(X[,1:no])) au_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=TRUE) as_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=FALSE) expect_that(as_lm$D, equals(mag_sort(ss$values)[1:no])) expect_that(au_lm$D, equals(mag_sort(ss$values)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(ss$values)][,1:no]))) expect_that(std(au_lm$X), equals(X[,mag_order(ss$values)][,1:no])) au_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=TRUE) as_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=FALSE) expect_that(as_sa$D, equals(ss$values[vcount(g)-1:no+1])) expect_that(au_sa$D, equals(ss$values[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(au_sa$X), equals(X[,vcount(g)-1:no+1])) }) test_that("Undirected, weighted case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) no <- 3 A <- g[] A <- A + 1/2 * diag(degree(g)) ss <- eigen(A) U <- std(ss$vectors) X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) au_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=TRUE) as_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=FALSE) expect_that(as_la$D, equals(ss$values[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(au_la$D, equals(ss$values[1:no])) expect_that(std(au_la$X), equals(X[,1:no])) au_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=TRUE) as_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=FALSE) expect_that(as_lm$D, equals(mag_sort(ss$values)[1:no])) expect_that(au_lm$D, equals(mag_sort(ss$values)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(ss$values)][,1:no]))) expect_that(std(au_lm$X), equals(X[,mag_order(ss$values)][,1:no])) au_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=TRUE) as_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=FALSE) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(au_sa$X), equals(X[,vcount(g)-1:no+1])) }) test_that("Directed, unweighted case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=TRUE) no <- 3 A <- g[] A <- A + 1/2 * diag(degree(g)) ss <- svd(A) U <- std(ss$u) V <- std(ss$v) X <- std(ss$u %*% sqrt(diag(ss$d))) Y <- std(ss$v %*% sqrt(diag(ss$d))) au_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=TRUE) as_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=FALSE) expect_that(as_la$D, equals(ss$d[1:no])) expect_that(au_la$D, equals(ss$d[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(std(as_la$Y), equals(std(V[,1:no]))) expect_that(std(au_la$X), equals(X[,1:no])) expect_that(std(au_la$Y), equals(Y[,1:no])) au_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=TRUE) as_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=FALSE) expect_that(as_lm$D, equals(ss$d[1:no])) expect_that(au_lm$D, equals(ss$d[1:no])) expect_that(std(as_lm$X), equals(std(U[,1:no]))) expect_that(std(as_lm$Y), equals(std(V[,1:no]))) expect_that(std(au_lm$X), equals(X[,1:no])) expect_that(std(au_lm$Y), equals(Y[,1:no])) au_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=TRUE) as_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=FALSE) expect_that(as_sa$D, equals(ss$d[vcount(g)-1:no+1])) expect_that(au_sa$D, equals(ss$d[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(as_sa$Y), equals(std(V[,vcount(g)-1:no+1]))) expect_that(std(au_sa$X), equals(X[,vcount(g)-1:no+1])) expect_that(std(au_sa$Y), equals(Y[,vcount(g)-1:no+1])) }) test_that("Directed, weighted case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=TRUE) E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) no <- 3 A <- g[] A <- A + 1/2 * diag(degree(g)) ss <- svd(A) U <- std(ss$u) V <- std(ss$v) X <- std(ss$u %*% sqrt(diag(ss$d))) Y <- std(ss$v %*% sqrt(diag(ss$d))) au_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=TRUE) as_la <- embed_adjacency_matrix(g, no=no, which="la", cvec=degree(g)/2, scaled=FALSE) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(std(as_la$Y), equals(std(V[,1:no]))) expect_that(std(au_la$X), equals(X[,1:no])) expect_that(std(au_la$Y), equals(Y[,1:no])) au_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=TRUE) as_lm <- embed_adjacency_matrix(g, no=no, which="lm", cvec=degree(g)/2, scaled=FALSE) expect_that(std(as_lm$X), equals(std(U[,1:no]))) expect_that(std(as_lm$Y), equals(std(V[,1:no]))) expect_that(std(au_lm$X), equals(X[,1:no])) expect_that(std(au_lm$Y), equals(Y[,1:no])) au_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=TRUE) as_sa <- embed_adjacency_matrix(g, no=no, which="sa", cvec=degree(g)/2, scaled=FALSE) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(as_sa$Y), equals(std(V[,vcount(g)-1:no+1]))) expect_that(std(au_sa$X), equals(X[,vcount(g)-1:no+1])) expect_that(std(au_sa$Y), equals(Y[,vcount(g)-1:no+1])) }) test_that("Issue #50 is resolved", { library(igraph) set.seed(12345) g <- erdos.renyi.game(15, .4) w <- -log(runif(ecount(g))) X1 <- embed_adjacency_matrix(g, 2, weights= w) E(g)$weight <- w X2 <- embed_adjacency_matrix(g, 2) expect_that(X1$D, equals(X2$D)) }) test_that("Issue #51 is resolved", { library(igraph) set.seed(12345) pref.matrix <- diag(0.2, 2) + 0.2 block.sizes <- c(800, 800) n <- sum(block.sizes) g <- sbm.game(n, pref.matrix, block.sizes, directed=TRUE) for (i in 1:25) { ase <- embed_adjacency_matrix(g, 2) expect_that(mean(ase$X %*% t(ase$Y)), equals(0.299981018354173)) } }) igraph/tests/testthat/test_get.edgelist.R0000644000175100001440000000033713177712334020317 0ustar hornikusers context("edgelist") test_that("as_edgelist works", { library(igraph) g <- sample_gnp(100, 3/100) e <- as_edgelist(g) g2 <- graph(t(e), n=vcount(g), dir=FALSE) expect_that(graph.isomorphic(g, g2), is_true()) }) igraph/tests/testthat/test_largest.cliques.R0000644000175100001440000000046613177712334021051 0ustar hornikusers context("largest_cliques") test_that("largest_cliques works", { library(igraph) g <- sample_gnp(50,20/50) lc <- largest_cliques(g) ## TODO: this only checks that these are cliques expect_that(unique(sapply(lc, function(x) edge_density(induced_subgraph(g, x)))), equals(1)) }) igraph/tests/testthat/test_sir.R0000644000175100001440000000064613177712334016541 0ustar hornikusers context("SIR epidemics model on a network") test_that("SIR works", { skip_on_os("solaris") set.seed(42) library(digest) library(igraph) g <- sample_gnm(50, 50) res <- sir(g, beta=5, gamma=1, no.sim=10) if (.Machine$sizeof.pointer == 4) { expect_that(digest(res), equals("b73a8ad03b832b3543f2f03d07330398")) } else { expect_that(digest(res), equals("bc42d0cbe0bb3321e83979c0432f9cea")) } }) igraph/tests/testthat/test_assortativity.R0000644000175100001440000000323613177712334020667 0ustar hornikusers context("assortativity") test_that("assortativity works", { library(igraph) g <- read_graph(f <- gzfile("celegansneural.gml.gz"), format="gml") assR <- function(graph) { indeg <- degree(graph, mode="in") outdeg <- degree(graph, mode="out") el <- as_edgelist(graph, names=FALSE) J <- outdeg[el[,1]]-1 K <- indeg[el[,2]]-1 num <- sum(J*K) - sum(J)*sum(K)/ecount(graph) den1 <- sum(J*J) - sum(J)^2/ecount(graph) den2 <- sum(K*K) - sum(K)^2/ecount(graph) num / sqrt(den1) / sqrt(den2) } asd <- assortativity_degree(g) as <- assortativity(g, degree(g, mode="out"), degree(g, mode="in")) as2 <- assR(g) expect_that(asd, equals(as)) expect_that(asd, equals(as2)) asu <- assortativity_degree(simplify(as.undirected(g, mode="collapse"))) expect_that(asu, equals(-0.16319921031570466807)) p <- read_graph(f <- gzfile("power.gml.gz"), format="gml") p.asd <- assortativity_degree(p) p.as <- assortativity(p, degree(p)) p.as2 <- assR(as.directed(p, mode="mutual")) expect_that(p.asd, equals(p.as)) expect_that(p.asd, equals(p.as2)) }) test_that("nominal assortativity works", { library(igraph) o <- read_graph(f <- gzfile("football.gml.gz"), format="gml") o <- simplify(o) an <- assortativity_nominal(o, V(o)$value+1) el <- as_edgelist(o, names=FALSE) etm <- matrix(0, nr=max(V(o)$value)+1, nc=max(V(o)$value)+1) for (e in 1:nrow(el)) { t1 <- V(o)$value[ el[e,1] ]+1 t2 <- V(o)$value[ el[e,2] ]+1 etm[t1, t2] <- etm[t1, t2] + 1 etm[t2, t1] <- etm[t2, t1] + 1 } etm <- etm/sum(etm) an2 <- ( sum(diag(etm))-sum(etm %*% etm) ) / ( 1-sum(etm %*% etm) ) expect_that(an, equals(an2)) }) igraph/tests/testthat/test-vs-operators.R0000644000175100001440000003042613177712334020325 0ustar hornikusers context("VS/ES operators") test_that("c on attached vs", { g <- make_ring(10) vg <- V(g)[1:5] vg2 <- V(g)[6:10] expect_equivalent(c(vg, vg2), V(g)) expect_equal(get_vs_graph_id(c(vg, vg2)), get_graph_id(g)) vg <- V(g) vg2 <- V(g)[FALSE] expect_equivalent(c(vg, vg2), V(g)) expect_equivalent(c(vg2, vg), V(g)) vg <- V(g)[c(2,5,6,8)] expect_equivalent(c(vg, vg), V(g)[c(2,5,6,8,2,5,6,8)]) }) test_that("c on detached vs", { g <- make_ring(10) vg <- V(g)[1:5] vg2 <- V(g)[6:10] vg3 <- V(g) vg4 <- V(g)[FALSE] vg5 <- V(g)[c(2,5,6,8)] vg6 <- V(g)[c(2,5,6,8,2,5,6,8)] rm(g) gc() expect_equivalent(c(vg, vg2), vg3) expect_equivalent(c(vg3, vg4), vg3) expect_equivalent(c(vg4, vg3), vg3) expect_equivalent(c(vg5, vg5), vg6) }) test_that("c on attached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g)[1:5] vg2 <- V(g)[6:10] expect_equivalent(c(vg, vg2), V(g)) expect_equal(names(c(vg, vg2)), names(V(g))) vg <- V(g) vg2 <- V(g)[FALSE] expect_equivalent(c(vg, vg2), V(g)) expect_equal(names(c(vg, vg2)), names(V(g))) expect_equivalent(c(vg2, vg), V(g)) expect_equal(names(c(vg2, vg)), names(V(g))) vg <- V(g)[c(2,5,6,8)] expect_equivalent(c(vg, vg), V(g)[c(2,5,6,8,2,5,6,8)]) expect_equal(names(c(vg, vg)), names(V(g)[c(2,5,6,8,2,5,6,8)])) }) test_that("c on detached vs, names", { g <- make_ring(10) vg <- V(g)[1:5] vg2 <- V(g)[6:10] vg3 <- V(g) vg4 <- V(g)[FALSE] vg5 <- V(g)[c(2,5,6,8)] vg6 <- V(g)[c(2,5,6,8,2,5,6,8)] rm(g) gc() expect_equivalent(c(vg, vg2), vg3) expect_equal(names(c(vg, vg2)), names(vg3)) expect_equivalent(c(vg3, vg4), vg3) expect_equal(names(c(vg3, vg4)), names(vg3)) expect_equivalent(c(vg4, vg3), vg3) expect_equal(names(c(vg3, vg4)), names(vg3)) expect_equivalent(c(vg5, vg5), vg6) expect_equal(names(c(vg5, vg5)), names(vg6)) }) test_that("union on attached vs", { g <- make_ring(10) v1 <- V(g)[1:7] v2 <- V(g)[6:10] vu <- union(v1, v2) expect_equivalent(vu, V(g)) expect_equivalent(union(V(g)), V(g)) v3 <- V(g)[FALSE] expect_equivalent(union(V(g), v3), V(g)) expect_equivalent(union(v3, V(g), v3), V(g)) expect_equivalent(union(v3), v3) expect_equivalent(union(v3, v3, v3), v3) expect_equivalent(union(v3, v3), v3) }) test_that("union on detached vs", { g <- make_ring(10) vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] vu <- union(v1, v2) v3 <- V(g)[FALSE] rm(g) gc() expect_equivalent(vu, vg) expect_equivalent(union(vg), vg) expect_equivalent(union(vg, v3), vg) expect_equivalent(union(v3, vg, v3), vg) expect_equivalent(union(v3), v3) expect_equivalent(union(v3, v3, v3), v3) expect_equivalent(union(v3, v3), v3) }) test_that("union on attached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] v1 <- V(g)[1:7] v2 <- V(g)[6:10] vu <- union(v1, v2) expect_equivalent(vu, V(g)) expect_equal(names(vu), names(V(g))) expect_equivalent(union(V(g)), V(g)) expect_equal(names(union(V(g))), names(V(g))) v3 <- V(g)[FALSE] expect_equivalent(union(V(g), v3), V(g)) expect_equal(names(union(V(g), v3)), names(V(g))) expect_equivalent(union(v3, V(g), v3), V(g)) expect_equal(names(union(v3, V(g), v3)), names(V(g))) expect_equivalent(union(v3), v3) expect_equal(names(union(v3)), names(v3)) expect_equivalent(union(v3, v3, v3), v3) expect_equal(names(union(v3, v3, v3)), names(v3)) expect_equivalent(union(v3, v3), v3) expect_equal(names(union(v3, v3)), names(v3)) }) test_that("union on detached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] rm(g) gc() vu <- union(v1, v2) expect_equivalent(vu, vg) expect_equal(names(vu), names(vg)) expect_equivalent(union(vg), vg) expect_equal(names(union(vg)), names(vg)) expect_equivalent(union(vg, v3), vg) expect_equal(names(union(vg, v3)), names(vg)) expect_equivalent(union(v3, vg, v3), vg) expect_equal(names(union(v3, vg, v3)), names(vg)) expect_equivalent(union(v3), v3) expect_equal(names(union(v3)), names(v3)) expect_equivalent(union(v3, v3, v3), v3) expect_equal(names(union(v3, v3, v3)), names(v3)) expect_equivalent(union(v3, v3), v3) expect_equal(names(union(v3, v3)), names(v3)) }) test_that("intersection on attached vs", { g <- make_ring(10) vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] v12 <- V(g)[6:7] v13 <- V(g)[FALSE] v14 <- V(g)[1:3] v24 <- V(g)[FALSE] vi1 <- intersection(v1, v2) expect_equivalent(vi1, v12) vi2 <- intersection(v1, v3) expect_equivalent(vi2, v13) vi3 <- intersection(v1, v4) expect_equivalent(vi3, v14) vi4 <- intersection(v1, vg) expect_equivalent(vi4, v1) vi5 <- intersection(v2, v4) expect_equivalent(vi5, v24) vi6 <- intersection(v3, vg) expect_equivalent(vi6, v3) }) test_that("intersection on detached vs", { g <- make_ring(10) vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] v12 <- V(g)[6:7] v13 <- V(g)[FALSE] v14 <- V(g)[1:3] v24 <- V(g)[FALSE] rm(g) gc() vi1 <- intersection(v1, v2) expect_equivalent(vi1, v12) vi2 <- intersection(v1, v3) expect_equivalent(vi2, v13) vi3 <- intersection(v1, v4) expect_equivalent(vi3, v14) vi4 <- intersection(v1, vg) expect_equivalent(vi4, v1) vi5 <- intersection(v2, v4) expect_equivalent(vi5, v24) vi6 <- intersection(v3, vg) expect_equivalent(vi6, v3) }) test_that("intersection on attached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] v12 <- V(g)[6:7] v13 <- V(g)[FALSE] v14 <- V(g)[1:3] v24 <- V(g)[FALSE] vi1 <- intersection(v1, v2) expect_equivalent(vi1, v12) expect_equal(names(vi1), names(v12)) vi2 <- intersection(v1, v3) expect_equivalent(vi2, v13) expect_equal(names(vi2), names(v13)) vi3 <- intersection(v1, v4) expect_equivalent(vi3, v14) expect_equal(names(vi3), names(v14)) vi4 <- intersection(v1, vg) expect_equivalent(vi4, v1) expect_equal(names(vi4), names(v1)) vi5 <- intersection(v2, v4) expect_equivalent(vi5, v24) expect_equal(names(vi5), names(v24)) vi6 <- intersection(v3, vg) expect_equivalent(vi6, v3) expect_equal(names(vi6), names(v3)) }) test_that("intersection on detached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] v12 <- V(g)[6:7] v13 <- V(g)[FALSE] v14 <- V(g)[1:3] v24 <- V(g)[FALSE] rm(g) gc() vi1 <- intersection(v1, v2) expect_equivalent(vi1, v12) expect_equal(names(vi1), names(v12)) vi2 <- intersection(v1, v3) expect_equivalent(vi2, v13) expect_equal(names(vi2), names(v13)) vi3 <- intersection(v1, v4) expect_equivalent(vi3, v14) expect_equal(names(vi3), names(v14)) vi4 <- intersection(v1, vg) expect_equivalent(vi4, v1) expect_equal(names(vi4), names(v1)) vi5 <- intersection(v2, v4) expect_equivalent(vi5, v24) expect_equal(names(vi5), names(v24)) vi6 <- intersection(v3, vg) expect_equivalent(vi6, v3) expect_equal(names(vi6), names(v3)) }) test_that("difference on attached vs", { g <- make_ring(10) vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] vr1 <- V(g)[8:10] vr2 <- V(g) vr3 <- V(g)[1:5] vr4 <- V(g)[4:7] vr5 <- V(g)[FALSE] vr6 <- V(g)[FALSE] vd1 <- difference(vg, v1) vd2 <- difference(vg, v3) vd3 <- difference(v1, v2) vd4 <- difference(v1, v4) vd5 <- difference(v3, v3) vd6 <- difference(v3, v4) expect_equivalent(vd1, vr1) expect_equivalent(vd2, vr2) expect_equivalent(vd3, vr3) expect_equivalent(vd4, vr4) expect_equivalent(vd5, vr5) expect_equivalent(vd6, vr6) }) test_that("difference on detached vs", { g <- make_ring(10) vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] vr1 <- V(g)[8:10] vr2 <- V(g) vr3 <- V(g)[1:5] vr4 <- V(g)[4:7] vr5 <- V(g)[FALSE] vr6 <- V(g)[FALSE] rm(g) gc() vd1 <- difference(vg, v1) vd2 <- difference(vg, v3) vd3 <- difference(v1, v2) vd4 <- difference(v1, v4) vd5 <- difference(v3, v3) vd6 <- difference(v3, v4) expect_equivalent(vd1, vr1) expect_equivalent(vd2, vr2) expect_equivalent(vd3, vr3) expect_equivalent(vd4, vr4) expect_equivalent(vd5, vr5) expect_equivalent(vd6, vr6) }) test_that("difference on attached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] vr1 <- V(g)[8:10] vr2 <- V(g) vr3 <- V(g)[1:5] vr4 <- V(g)[4:7] vr5 <- V(g)[FALSE] vr6 <- V(g)[FALSE] vd1 <- difference(vg, v1) vd2 <- difference(vg, v3) vd3 <- difference(v1, v2) vd4 <- difference(v1, v4) vd5 <- difference(v3, v3) vd6 <- difference(v3, v4) expect_equivalent(vd1, vr1) expect_equal(names(vd1), names(vr1)) expect_equivalent(vd2, vr2) expect_equal(names(vd2), names(vr2)) expect_equivalent(vd3, vr3) expect_equal(names(vd3), names(vr3)) expect_equivalent(vd4, vr4) expect_equal(names(vd4), names(vr4)) expect_equivalent(vd5, vr5) expect_equal(names(vd5), names(vr5)) expect_equivalent(vd6, vr6) expect_equal(names(vd6), names(vr6)) }) test_that("difference on detached vs, names", { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g) v1 <- V(g)[1:7] v2 <- V(g)[6:10] v3 <- V(g)[FALSE] v4 <- V(g)[1:3] vr1 <- V(g)[8:10] vr2 <- V(g) vr3 <- V(g)[1:5] vr4 <- V(g)[4:7] vr5 <- V(g)[FALSE] vr6 <- V(g)[FALSE] rm(g) gc() vd1 <- difference(vg, v1) vd2 <- difference(vg, v3) vd3 <- difference(v1, v2) vd4 <- difference(v1, v4) vd5 <- difference(v3, v3) vd6 <- difference(v3, v4) expect_equivalent(vd1, vr1) expect_equal(names(vd1), names(vr1)) expect_equivalent(vd2, vr2) expect_equal(names(vd2), names(vr2)) expect_equivalent(vd3, vr3) expect_equal(names(vd3), names(vr3)) expect_equivalent(vd4, vr4) expect_equal(names(vd4), names(vr4)) expect_equivalent(vd5, vr5) expect_equal(names(vd5), names(vr5)) expect_equivalent(vd6, vr6) expect_equal(names(vd6), names(vr6)) }) test_that("rev on attached vs", { for (i in 1:10) { g <- make_ring(10) idx <- seq_len(i) vg <- V(g)[idx] vgr <- V(g)[rev(idx)] vg2 <- rev(vg) expect_equivalent(vg2, vgr) } }) test_that("rev on detached vs", { for (i in 1:10) { g <- make_ring(10) idx <- seq_len(i) vg <- V(g)[idx] vgr <- V(g)[rev(idx)] rm(g) gc() vg2 <- rev(vg) expect_equivalent(vg2, vgr) } }) test_that("rev on attached vs, names", { for (i in 1:10) { g <- make_ring(10) V(g)$name <- letters[1:10] idx <- seq_len(i) vg <- V(g)[idx] vgr <- V(g)[rev(idx)] vg2 <- rev(vg) expect_equivalent(vg2, vgr) expect_equal(names(vg2), names(vgr)) } }) test_that("rev on detached vs, names", { for (i in 1:10) { g <- make_ring(10) V(g)$name <- letters[1:10] idx <- seq_len(i) vg <- V(g)[idx] vgr <- V(g)[rev(idx)] rm(g) gc() vg2 <- rev(vg) expect_equivalent(vg2, vgr) expect_equal(names(vg2), names(vgr)) } }) unique_tests <- list( list(1:5, 1:5), list(c(1,1,2:5), 1:5), list(c(1,1,1,1), 1), list(c(1,2,2,2), 1:2), list(c(2,2,1,1), 2:1), list(c(1,2,1,2), 1:2), list(c(), c()) ) test_that("unique on attached vs", { sapply(unique_tests, function(d) { g <- make_ring(10) vg <- unique(V(g)[ d[[1]] ]) vr <- V(g)[ d[[2]] ] expect_equivalent(vg, vr) }) }) test_that("unique on detached vs", { sapply(unique_tests, function(d) { g <- make_ring(10) vg <- V(g)[ d[[1]] ] vr <- V(g)[ d[[2]] ] rm(g) gc() vg <- unique(vg) expect_equivalent(vg, vr) }) }) test_that("unique on attached vs, names", { sapply(unique_tests, function(d) { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- unique(V(g)[ d[[1]] ]) vr <- V(g)[ d[[2]] ] expect_equivalent(vg, vr) }) }) test_that("unique on detached vs, names", { sapply(unique_tests, function(d) { g <- make_ring(10) V(g)$name <- letters[1:10] vg <- V(g)[ d[[1]] ] vr <- V(g)[ d[[2]] ] rm(g) gc() vg <- unique(vg) expect_equivalent(vg, vr) }) }) igraph/tests/testthat/test_optimal.community.R0000644000175100001440000000173213247053761021431 0ustar hornikusers context("cluster_optimal") test_that("cluster_optimal works", { skip_if_no_glpk() library(igraph) g <- make_graph("Zachary") oc <- cluster_optimal(g) expect_that(as.vector(membership(oc)), equals(c(1, 1, 1, 1, 2, 2, 2, 1, 3, 3, 2, 1, 1, 1, 3, 3, 2, 1, 3, 1, 3, 1, 3, 4, 4, 4, 3, 4, 4, 3, 3, 4, 3, 3) )) expect_that(modularity(g, oc$membership), equals(oc$modularity)) expect_that(length(oc), equals(4)) expect_that(sizes(oc), equals(structure(c(11L, 5L, 12L, 6L), .Dim=4L, .Dimnames=structure(list(`Community sizes`=c("1", "2", "3", "4")), .Names="Community sizes"), class="table") )) }) test_that("weighted cluster_optimal works", { skip_if_no_glpk() library(igraph) set.seed(42) g <- make_full_graph(5) + make_ring(5) E(g)$weight <- sample(1:2, ecount(g), replace=TRUE) oc <- cluster_optimal(g) expect_that(modularity(oc), equals(0.4032)) }) igraph/tests/testthat/test_get.all.shortest.paths.R0000644000175100001440000000243513177712334022260 0ustar hornikusers context("all_shortest_paths") test_that("all_shortest_paths works", { library(igraph) edges <- matrix(c("s", "a", 2, "s", "b", 4, "a", "t", 4, "b", "t", 2, "a", "1", 1, "a", "2", 1, "a", "3", 2, "1", "b", 1, "2", "b", 2, "3", "b", 1), byrow=TRUE, ncol=3, dimnames=list(NULL, c("from", "to", "weight"))) edges <- as.data.frame(edges) edges[[3]] <- as.numeric(as.character(edges[[3]])) g <- graph_from_data_frame(as.data.frame(edges)) sortlist <- function(list) { list <- lapply(list, sort) list <- lapply(list, as.vector) list[order(sapply(list, paste, collapse="!"))] } sp1 <- all_shortest_paths(g, "s", "t", weights=NA) expect_that(sortlist(sp1$res), equals(list(c(1, 2, 7), c(1, 3, 7)))) expect_that(sp1$nrgeo, equals(c(1,1,1,1,1,1,2))) sp2 <- all_shortest_paths(g, "s", "t") expect_that(sortlist(sp2$res), equals(list(c(1, 2, 3, 4, 7), c(1, 2, 7), c(1, 3, 7)))) expect_that(sp2$nrgeo, equals(c(1,1,2,1,1,1,3))) ## TODO ## E(g)$weight <- E(g)$weight - 1 ## all_shortest_paths(g, "s", "t") }) igraph/tests/testthat/test_get.adjacency.R0000644000175100001440000000124513177712334020437 0ustar hornikusers context("as_adj") test_that("as_adj works", { library(igraph) g <- sample_gnp(50, 1/50) A <- as_adj(g, sparse=FALSE) g2 <- graph_from_adjacency_matrix(A, mode="undirected") expect_that(graph.isomorphic(g, g2), is_true()) ### A <- as_adj(g, sparse=TRUE) g2 <- graph_from_adjacency_matrix(A, mode="undirected") expect_that(graph.isomorphic(g, g2), is_true()) ### g <- sample_gnp(50, 2/50, directed=TRUE) A <- as_adj(g, sparse=FALSE) g2 <- graph_from_adjacency_matrix(A) expect_that(graph.isomorphic(g, g2), is_true()) ### A <- as_adj(g, sparse=TRUE) g2 <- graph_from_adjacency_matrix(A) expect_that(graph.isomorphic(g, g2), is_true()) }) igraph/tests/testthat/test_forestfire.R0000644000175100001440000000136513177712334020113 0ustar hornikusers context("sample_forestfire") test_that("sample_forestfire works", { library(igraph) set.seed(42) pars <- list(sparse=c(0.35, 0.2/0.35), densifying=c(0.37, 0.32/0.37), dense=c(0.38, 0.38/0.37)) N <- 5000 G <- lapply(pars, function(x) sample_forestfire(N, fw=x[1], bw=x[2])) xv <- log(2:N) co <- sapply(G, function(x) { yv <- log(cumsum(degree(x, mode="out"))[-1]) coef(lm( yv ~ xv ))[2] }) expect_that(co, equals(structure(c(1.06045500245466, 1.22800967143684, 1.96234121488344), .Names = c("sparse.xv", "densifying.xv", "dense.xv")))) }) igraph/tests/testthat/test_dot.product.game.R0000644000175100001440000000252113177712334021113 0ustar hornikusers context("Dot-product random graphs") test_that("Dot product rng works", { library(igraph) set.seed(42) vecs <- cbind(c(0,1,1,1,0)/3, c(0,1,1,0,1)/3, c(1,1,1,1,0)/4, c(0,1,1,1,0)) g <- sample_dot_product(vecs) g0 <- graph.formula(1:2:3-4) expect_that(g[], is_equivalent_to(g0[])) g2 <- sample_dot_product(vecs, directed=TRUE) g20 <- graph.formula(1:2:3:4, 1-+3, 1-+4, 3-+4, 4+-1, 4+-3) expect_that(g[], is_equivalent_to(g20[])) vecs <- replicate(5, rep(1/2, 4)) g <- sample_dot_product(vecs) expect_that(g[], is_equivalent_to(graph.full(5)[])) g2 <- sample_dot_product(vecs, directed=TRUE) expect_that(g2[], is_equivalent_to(graph.full(5, directed=TRUE)[])) vecs <- replicate(100, rep(sqrt(1/8), 4)) g <- sample_dot_product(vecs) expect_that(ecount(g), equals(2454)) g2 <- sample_dot_product(vecs, directed=TRUE) expect_that(ecount(g2), equals(4938)) }) test_that("Dot product rng gives warnings", { library(igraph) vecs <- cbind(c(1,1,1)/3, -c(1,1,1)/3) expect_that(g <- sample_dot_product(vecs), gives_warning("Negative connection probability in dot-product graph")) vecs <- cbind(c(1,1,1), c(1,1,1)) expect_that(g <- sample_dot_product(vecs), gives_warning(paste(sep="", "Greater than 1 connection probability ", "in dot-product graph"))) }) igraph/tests/testthat/test_cliques.R0000644000175100001440000000130113177712334017376 0ustar hornikusers context("cliques") test_that("cliques works", { library(igraph) set.seed(42) check.clique <- function(graph, vids) { s <- induced_subgraph(graph, vids) ecount(s) == vcount(s) * (vcount(s)-1) / 2 } g <- sample_gnp(100, 0.3) expect_that(clique_num(g), equals(6)) cl <- sapply(cliques(g, min=6), check.clique, graph=g) lcl <- sapply(largest_cliques(g), check.clique, graph=g) expect_that(cl, equals(lcl)) expect_that(cl, equals(rep(TRUE, 17))) expect_that(lcl, equals(rep(TRUE, 17))) ## To have a bit less maximal cliques, about 100-200 usually g <- sample_gnp(100, 0.03) expect_that(all(sapply(max_cliques(g), check.clique, graph=g)), is_true()) }) igraph/tests/testthat/test_clusters.R0000644000175100001440000000247213177712334017607 0ustar hornikusers context("components") test_that("components works", { library(igraph) set.seed(42) gc <- function(graph) { cl <- components(graph) induced_subgraph(graph, which(cl$membership==which.max(cl$csize))) } rg <- function(n) { gc(sample_gnp(n, 1/n)) } G <- lapply(1:30, function(x) rg(sample(100, 1))) Gsize <- sapply(G, vcount) allg <- disjoint_union(G) clu <- components(allg) expect_that(as.numeric(table(clu$membership)), equals(clu$csize)) expect_that(sort(clu$csize), equals(sort(Gsize))) expect_that(clu$no, equals(length(G))) }) test_that("components names results", { library(igraph) g <- make_ring(10) + make_full_graph(5) V(g)$name <- letters[1:15] clu <- components(g) expect_that(names(clu$membership), equals(letters[1:15])) }) test_that("groups works", { library(igraph) g <- make_ring(10) + make_full_graph(5) gr <- groups(components(g)) expect_that(gr, equals(structure(list(`1` = 1:10, `2` = 11:15), .Dim = 2L, .Dimnames = list( c("1", "2"))))) V(g)$name <- letters[1:15] gr <- groups(components(g)) expect_that(gr, equals(structure(list(`1` = letters[1:10], `2` = letters[11:15]), .Dim = 2L, .Dimnames = list(c("1", "2"))))) }) igraph/tests/testthat/test_bug-1073705-indexing.R0000644000175100001440000000120413177712334021137 0ustar hornikusers context("Bug 1073705") test_that("Weighted indexing does not remove edges", { library(igraph) g <- make_ring(10) g[1, 2, attr="weight"] <- 0 expect_that("weight" %in% edge_attr_names(g), is_true()) expect_that(E(g)$weight, equals(c(0, rep(NA, 9)))) el <- as_edgelist(g) g[from=el[,1], to=el[,2], attr="sim"] <- rep(0:1, length=ecount(g)) expect_that("sim" %in% edge_attr_names(g), is_true()) expect_that(E(g)$sim, equals(rep(0:1, 5))) V(g)$name <- letters[seq_len(vcount(g))] el <- as_edgelist(g) g[from=el[,1], to=el[,2], attr="sim"] <- rep(1:0, length=ecount(g)) expect_that(E(g)$sim, equals(rep(1:0, 5))) }) igraph/tests/testthat/test_graph.kautz.R0000644000175100001440000000143413177712334020176 0ustar hornikusers context("make_kautz_graph") test_that("make_kautz_graph works", { library(igraph) g <- make_kautz_graph(2,3) expect_that(g$name, equals("Kautz graph 2-3")) expect_that(g$m, equals(2)) expect_that(g$n, equals(3)) el <- as_edgelist(g) el <- el[order(el[,1], el[,2]),] expect_that(el, equals( structure(c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), .Dim = c(48L, 2L)) )) }) igraph/tests/testthat/test_pajek.R0000644000175100001440000000116413177712334017032 0ustar hornikusers context("Pajek file format") test_that("writing Pajek files works", { library(igraph) g <- make_ring(9) V(g)$color <- c("red", "green", "yellow") tc <- rawConnection(raw(0), "w") write_graph(g, format="pajek", file=tc) out <- rawToChar(rawConnectionValue(tc)) close(tc) expect_that(out, equals("*Vertices 9\r\n1 \"1\" ic \"red\"\r\n2 \"2\" ic \"green\"\r\n3 \"3\" ic \"yellow\"\r\n4 \"4\" ic \"red\"\r\n5 \"5\" ic \"green\"\r\n6 \"6\" ic \"yellow\"\r\n7 \"7\" ic \"red\"\r\n8 \"8\" ic \"green\"\r\n9 \"9\" ic \"yellow\"\r\n*Edges\r\n1 2\r\n2 3\r\n3 4\r\n4 5\r\n5 6\r\n6 7\r\n7 8\r\n8 9\r\n1 9\r\n")) }) igraph/tests/testthat/test_graph.compose.R0000644000175100001440000000050313177712334020501 0ustar hornikusers context("compose") test_that("compose works", { library(igraph) g1 <- sample_gnp(50, 3/50, directed=TRUE) gi <- graph( rep(1:vcount(g1), each=2), dir=TRUE ) g2 <- compose(g1, gi) g3 <- compose(gi, g1) expect_that(graph.isomorphic(g1, g2), is_true()) expect_that(graph.isomorphic(g1, g3), is_true()) }) igraph/tests/testthat/test_degree.R0000644000175100001440000000156613177712334017201 0ustar hornikusers context("degree") test_that("degree works", { library(igraph) g <- sample_gnp(100, 1/100) d <- degree(g) el <- as_edgelist(g) expect_that(as.numeric(table(el)), equals(d[d!=0])) expect_that(degree(g) / (vcount(g)-1), equals(degree(g, normalized=TRUE))) g2 <- sample_gnp(100, 2/100, dir=TRUE) din <- degree(g2, mode="in") dout <- degree(g2, mode="out") el2 <- as_edgelist(g2) expect_that(as.numeric(table(el2[,1])), equals(dout[dout!=0])) expect_that(as.numeric(table(el2[,2])), equals(din[din!=0])) expect_that(degree(g2, mode="in") / (vcount(g2)-1), equals(degree(g2, mode="in", normalized=TRUE))) expect_that(degree(g2, mode="out") / (vcount(g2)-1), equals(degree(g2, mode="out", normalized=TRUE))) expect_that(degree(g2, mode="all") / (vcount(g2)-1), equals(degree(g2, mode="all", normalized=TRUE))) }) igraph/tests/testthat/test_delete.edges.R0000644000175100001440000000063613177712334020273 0ustar hornikusers context("delete_edges") test_that("delete_edges works", { library(igraph) g <- graph_from_literal(A:B:C - D:E:F, D-E-F) g2 <- delete_edges(g, E(g, P=c("D", "E"))) expect_that(as.matrix(g2[]), is_equivalent_to(cbind(c(0,0,0,1,1,1), c(0,0,0,1,1,1), c(0,0,0,1,1,1), c(1,1,1,0,0,0), c(1,1,1,0,0,1), c(1,1,1,0,1,0)))) }) igraph/tests/testthat/test_bug-1019624.R0000644000175100001440000000044713177712334017344 0ustar hornikusers context("Bug 1019624") test_that("weighted graph_from_adjacency_matrix works on integer matrices", { library(igraph) data <- matrix(c(0,0,0,2, 0,0,0,0, 0,0,0,2, 0,1,0,0), 4) g <- graph_from_adjacency_matrix(data, weighted=TRUE) expect_that(as.matrix(g[]), is_equivalent_to(data)) }) igraph/tests/testthat/test_add.vertices.R0000644000175100001440000000125613177712334020315 0ustar hornikusers context("add_vertices") test_that("add_vertices works", { library(igraph) g <- graph_from_literal(A-B-C-D-E) g2 <- add_vertices(g, (nv <- 4)) expect_that(vcount(g2), equals(vcount(g) + nv)) expect_that(ecount(g2), equals(ecount(g))) expect_that(as_edgelist(g2), equals(as_edgelist(g))) }) test_that("add_vertices handles attributes properly", { library(igraph) g <- graph_from_literal(A-B-C-D-E) g3 <- add_vertices(g, (nv <- 3), attr=list(name=(names <- c("F","G","H")), weight=weights <- 1:3)) expect_that(V(g3)$name, equals(c(V(g)$name, names))) expect_that(V(g3)$weight, equals(c(rep(NA, vcount(g)), weights))) }) igraph/tests/testthat/test_graph.bipartite.R0000644000175100001440000000100313177712334021013 0ustar hornikusers context("make_bipartite_graph") test_that("make_bipartite_graph works", { library(igraph) I <- matrix(sample(0:1, 35, replace=TRUE, prob=c(3,1)), nc=5) g <- graph_from_incidence_matrix(I) edges <- unlist(sapply(seq_len(nrow(I)), function(x) { w <- which(I[x,] != 0) + nrow(I) if (length(w)!=0) { as.vector(rbind(x, w)) } else { numeric() } })) g2 <- make_bipartite_graph(seq_len(nrow(I)+ncol(I)) > nrow(I), edges) I2 <- as_incidence_matrix(g2) expect_that(I2, is_equivalent_to(I)) }) igraph/tests/testthat/test_graph.mincut.R0000644000175100001440000000060713177712334020340 0ustar hornikusers context("min_cut") test_that("min_cut works", { library(igraph) g2 <- graph( c(1,2,2,3,3,4, 1,6,6,5,5,4, 4,1) ) E(g2)$capacity <- c(3,1,2, 10,1,3, 2) mc <- min_cut(g2, value.only=FALSE) expect_that(mc$value, equals(1)) expect_that(as.vector(mc$cut), equals(2)) expect_that(as.vector(mc$partition1), equals(2)) expect_that(as.vector(mc$partition2), equals(c(1,3:6))) }) igraph/tests/testthat/test_walktrap.community.R0000644000175100001440000000220513177712334021605 0ustar hornikusers context("cluster_walktrap") test_that("cluster_walktrap works", { library(igraph) g <- make_graph("Zachary") set.seed(42) wc <- cluster_walktrap(g) expect_that(modularity(g, membership(wc)), equals(modularity(wc))) expect_that(as.vector(membership(wc)), equals(c(1, 1, 2, 1, 5, 5, 5, 1, 2, 2, 5, 1, 1, 2, 3, 3, 5, 1, 3, 1, 3, 1, 3, 4, 4, 4, 3, 4, 2, 3, 2, 2, 3, 3))) expect_that(length(wc), equals(5)) expect_that(sizes(wc), equals(structure(c(9L, 7L, 9L, 4L, 5L), .Dim=5L, .Dimnames = structure(list(`Community sizes` = c("1", "2", "3", "4", "5")), .Names = "Community sizes"), class = "table"))) d <- as.dendrogram(wc) expect_that(print(d), prints_text("2 branches.*34 members.*height 33")) expect_that(print(d[[1]]), prints_text("2 branches.*20 members.*height 31")) expect_that(print(d[[2]]), prints_text("2 branches.*14 members.*height 32")) m2 <- cut_at(wc, no=3) expect_that(modularity(g, m2), equals(wc$modularity[length(wc$modularity)-2], tolerance=1e-7)) }) igraph/tests/testthat/test_bonpow.R0000644000175100001440000000552513177712334017251 0ustar hornikusers context("Bonacich's power centrality") test_that("Power centrality works", { library(igraph) ## Generate some test data from Bonacich, 1987: fig1 <- graph_from_literal( A -+ B -+ C:D ) fig1.bp <- lapply(seq(0, 0.8, by=0.2), function(x) round(power_centrality(fig1, exponent=x), 2)) expect_that(fig1.bp, equals(list(c(A=0.89, B=1.79, C=0, D=0), c(A=1.15, B=1.64, C=0, D=0), c(A=1.34, B=1.49, C=0, D=0), c(A=1.48, B=1.35, C=0, D=0), c(A=1.59, B=1.22, C=0, D=0)))) g.c <- graph( c(1,2,1,3,2,4,3,5), dir=FALSE) bp.c <- lapply(seq(-.5, .5, by=0.1), function(x) round(power_centrality(g.c, exponent=x), 2)[c(1,2,4)]) expect_that(bp.c, equals(list(c(0.00, 1.58, 0.00), c(0.73, 1.45, 0.36), c(0.97, 1.34, 0.49), c(1.09, 1.27, 0.54), c(1.15, 1.23, 0.58), c(1.20, 1.20, 0.60), c(1.22, 1.17, 0.61), c(1.25, 1.16, 0.62), c(1.26, 1.14, 0.63), c(1.27, 1.13, 0.64), c(1.28, 1.12, 0.64)))) g.d <- graph( c(1,2,1,3,1,4,2,5,3,6,4,7), dir=FALSE) bp.d <- lapply(seq(-.4, .4, by=0.1), function(x) round(power_centrality(g.d, exponent=x), 2)[c(1,2,5)]) expect_that(bp.d, equals(list(c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54), c(1.62, 1.08, 0.54)))) g.e <- graph( c(1,2,1,3,1,4,2,5,2,6,3,7,3,8,4,9,4,10), dir=FALSE) bp.e <- lapply(seq(-.4, .4, by=0.1), function(x) round(power_centrality(g.e, exponent=x), 2)[c(1,2,5)]) expect_that(bp.e, equals(list(c(-1.00, 1.67, -0.33), c(0.36, 1.81, 0.12), c( 1.00, 1.67, 0.33), c(1.30, 1.55, 0.43), c( 1.46, 1.46, 0.49), c(1.57, 1.40, 0.52), c( 1.63, 1.36, 0.54), c(1.68, 1.33, 0.56), c( 1.72, 1.30, 0.57)))) g.f <- graph( c(1,2,1,3,1,4,2,5,2,6,2,7,3,8,3,9,3,10,4,11,4,12,4,13), dir=FALSE) bp.f <- lapply(seq(-.4, .4, by=0.1), function(x) round(power_centrality(g.f, exponent=x), 2)[c(1,2,5)]) expect_that(bp.f, equals(list(c(-1.72, 1.53, -0.57), c(-0.55, 2.03, -0.18), c( 0.44, 2.05, 0.15), c( 1.01, 1.91, 0.34), c( 1.33, 1.78, 0.44), c( 1.52, 1.67, 0.51), c( 1.65, 1.59, 0.55), c( 1.74, 1.53, 0.58), c( 1.80, 1.48, 0.60)))) }) igraph/tests/testthat/test_evcent.R0000644000175100001440000000303613177712334017224 0ustar hornikusers context("eigen_centrality") test_that("eigen_centrality works", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) evc <- round(eigen_centrality(kite)$vector, 3) expect_that(evc, equals(structure(c(0.732, 0.732, 0.594, 1, 0.827, 0.594, 0.827, 0.407, 0.1, 0.023), .Names = c("Andre", "Beverly", "Carol", "Diane", "Fernando", "Ed", "Garth", "Heather", "Ike", "Jane")))) ## Eigenvector-centrality, small stress-test is.principal <- function(M, lambda, eps=1e-12) { abs(eigen(M)$values[1] - lambda) < eps } is.ev <- function(M, v, lambda, eps=1e-12) { max(abs(M %*% v - lambda * v)) < eps } is.good <- function(M, v, lambda, eps=1e-12) { is.principal(M, lambda, eps) && is.ev(M, v, lambda, eps) } for (i in 1:1000) { G <- sample_gnm(10, sample(1:20, 1)) ev <- eigen_centrality(G) expect_that(is.good(as_adj(G, sparse=FALSE), ev$vector, ev$value), is_true()) } }) igraph/tests/testthat/test_iterators.R0000644000175100001440000000403113177712334017750 0ustar hornikusers context("iterators") test_that("iterators work", { library(igraph) ## Create a small ring graph, assign attributes ring <- graph_from_literal( A-B-C-D-E-F-G-A ) E(ring)$weight <- seq_len(ecount(ring)) ## Selection based on attributes expect_that(sort(E(ring)[ weight < 4 ]$weight), equals(1:3)) expect_that(V(ring)[ c("A", "C") ]$name, equals(c("A", "C"))) ## TODO: %--%, %->%, other special functions }) test_that("complex attributes work", { library(igraph) g <- make_ring(10) foo <- lapply(1:vcount(g), seq, from=1) V(g)$foo <- foo V(g)$foo[[5]][1:3] <- 0 expect_that(V(g)[(1:10)[-5]]$foo, equals(foo[-5])) expect_that(V(g)[[5]]$foo, equals(c(0,0,0,4,5))) expect_that(V(g)[5]$foo, equals(list(c(0,0,0,4,5)))) V(g)$foo <- foo V(g)[[5]]$foo[1:3] <- 0 expect_that(V(g)[(1:10)[-5]]$foo, equals(foo[-5])) expect_that(V(g)[[5]]$foo, equals(c(0,0,0,4,5))) expect_that(V(g)[5]$foo, equals(list(c(0,0,0,4,5)))) V(g)$foo <- foo V(g)[5]$foo[[1]][1:3] <- 0 expect_that(V(g)[(1:10)[-5]]$foo, equals(foo[-5])) expect_that(V(g)[[5]]$foo, equals(c(0,0,0,4,5))) expect_that(V(g)[5]$foo, equals(list(c(0,0,0,4,5)))) }) test_that("we got rid of confusing indexing by numbers", { g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$weight <- seq(ecount(g)) expect_equal(as.vector(V(g)[6:10][1:5]), 6:10) expect_equal(as.vector(E(g)[6:10][1:5]), 6:10) }) test_that("selecting edges using vertex names works", { g <- make_ring(10) V(g)$name <- letters[1:10] e1 <- E(g)[c('a|b', 'c|d')] expect_equal(as.vector(e1), c(1,3)) }) test_that("indexing with characters work as expected", { g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] expect_equal(as.vector(V(g)[letters[3:6]]), 3:6) expect_equal(as.vector(E(g)[LETTERS[4:7]]), 4:7) ## expect_equal(as.vector(E(g)[c('a|b', 'c|d')]), c(1,3)) expect_error(V(g)[1:5]['h'], 'Unknown vertex selected') expect_error(E(g)[1:5]['H'], 'Unknown edge selected') expect_error(E(g)[6:9]['a|b'], 'Unknown edge selected') }) igraph/tests/testthat/test_modularity_matrix.R0000644000175100001440000000071013177712334021511 0ustar hornikusers context("modularity_matrix") test_that("modularity_matrix works", { library(igraph) kar <- make_graph("zachary") fc <- cluster_fast_greedy(kar) m1 <- modularity(kar, membership(fc)) m2 <- modularity(kar, membership(fc), weights=rep(1, ecount(kar))) expect_that(m1, equals(m2)) B1 <- modularity_matrix(kar, membership(fc)) B2 <- modularity_matrix(kar, membership(fc), weights=rep(1, ecount(kar))) expect_that(B1, equals(B2)) }) igraph/tests/testthat/test-vs-es-quirks.R0000644000175100001440000000126013177712334020224 0ustar hornikusers context("Vertex and edge sequence quirks") test_that("graph is not updated if not in LHS", { g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]), with_edge_(weight = 1:10)) vs <- V(g)[1:5] vs$name <- letters[1:5] expect_equal(V(g)$name, LETTERS[1:10]) es <- E(g) es$weight <- 0 expect_equal(E(g)$weight, 1:10) }) test_that("graph is updated if in LHS", { g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]), with_edge_(weight = 1:10)) V(g)[1:5]$name <- letters[1:5] expect_equal(V(g)$name, c(letters[1:5], LETTERS[6:10])) E(g)[1:5]$weight <- 0 expect_equal(E(g)$weight, c(rep(0, 5), 6:10)) }) igraph/tests/testthat/test_dimSelect.R0000644000175100001440000000164313177712334017653 0ustar hornikusers context("Dimensionality selection") test_that("dimensionality selection works", { library(igraph) set.seed(42) k <- graph.famous("zachary") ev <- eigen(get.adjacency(k), only.values=TRUE)$values kdim <- dim_select(ev) expect_that(kdim, equals(4)) expect_that(dim_select(1:100), equals(50)) ## Some regression tests expect_that(dim_select(runif(100)), equals(69)) expect_that(dim_select(runif(100)), equals(88)) expect_that(dim_select(runif(100)), equals(3)) expect_that(dim_select(runif(100)), equals(99)) ## Some more meaningful tests x <- c(rnorm(50, mean=0, sd=1), rnorm(50, mean=5, sd=1)) expect_that(dim_select(x), equals(50)) x <- c(rnorm(10, mean=0, sd=1), rnorm(90, mean=2, sd=1)) expect_that(dim_select(x), equals(10)) x <- c(10, rnorm(99, mean=0, sd=1)) expect_that(dim_select(x), equals(1)) x <- c(rnorm(99, mean=0, sd=1), 10) expect_that(dim_select(x), equals(99)) }) igraph/tests/testthat/test_indexing3.R0000644000175100001440000000033113177712334017623 0ustar hornikusers context("Indexing") test_that("Indexing multi-graphs as adjacency list", { g <- make_graph(~ A -+ B:C, A -+ B:C:D, simplify = FALSE) e <- g[['A', 'B', edges = TRUE]] expect_equal(sort(e[[1]]), E(g)[1,3]) }) igraph/tests/testthat/test_maximal_cliques.R0000644000175100001440000000666513177712334021130 0ustar hornikusers context("Maximal cliques") mysort <- function(x) { xl <- sapply(x, length) x <- lapply(x, sort) xc <- sapply(x, paste, collapse="-") x[order(xl, xc)] } unvs <- function(x) lapply(x, as.vector) bk4 <- function(graph, min=0, max=Inf) { Gamma <- function(v) { neighbors(graph, v) } bkpivot <- function(PX, R) { P <- if (PX$PE >= PX$PS) { PX$PX[PX$PS:PX$PE] } else { numeric() } X <- if (PX$XE >= PX$XS) { PX$PX[PX$XS:PX$XE] } else { numeric() } if (length(P) == 0 && length(X) == 0) { if (length(R) >= min && length(R) <= max) { list(R) } else { list() } } else if (length(P) != 0) { psize <- sapply(c(P, X), function(u) length(intersect(P, Gamma(u)))) u <- c(P, X)[which.max(psize)] pres <- list() for (v in setdiff(P, Gamma(u))) { p0 <- if (PX$PS > 1) { PX$PX[1:(PX$PS-1)] } else { numeric() } p1 <- setdiff(P, Gamma(v)) p2 <- intersect(P, Gamma(v)) x1 <- intersect(X, Gamma(v)) x2 <- setdiff(X, Gamma(v)) x0 <- if (PX$XE < length(PX$PX)) { PX$PX[(PX$XE+1):length(PX$PX)] } else { numeric() } newPX <- list(PX=c(p0, p1, p2, x1, x2, x0), PS=length(p0) + length(p1) + 1, PE=length(p0) + length(p1) + length(p2), XS=length(p0) + length(p1) + length(p2) + 1, XE=length(p0) + length(p1) + length(p2) + length(x1)) pres <- c(pres, bkpivot(newPX, c(R, v))) vpos <- which(PX$PX==v) tmp <- PX$PX[PX$PE] PX$PX[PX$PE] <- v PX$PX[vpos] <- tmp PX$PE <- PX$PE - 1 PX$XS <- PX$XS - 1 P <- if (PX$PE >= PX$PS) { PX$PX[PX$PS:PX$PE] } else { numeric() } X <- if (PX$XE >= PX$XS) { PX$PX[PX$XS:PX$XE] } else { numeric() } if (any(duplicated(PX$PX))) { stop("foo2") } } pres } } res <- list() cord <- order(coreness(graph)) for (v in seq_along(cord)) { if (v != length(cord)) { P <- intersect(Gamma(cord[v]), cord[(v+1):length(cord)]) } else { P <- numeric() } if (v != 1) { X <- intersect(Gamma(cord[v]), cord[1:(v-1)]) } else { X <- numeric() } PX <- list(PX=c(P, X), PS=1, PE=length(P), XS=length(P)+1, XE=length(P)+length(X)) res <- c(res, bkpivot(PX, cord[v])) } lapply(res, as.integer) } ################################################################# test_that("Maximal cliques work", { library(igraph) set.seed(42) G <- sample_gnm(1000, 1000) cli <- make_full_graph(10) for (i in 1:10) { G <- permute(G, sample(vcount(G))) G <- G %u% cli } G <- simplify(G) cl1 <- mysort(bk4(G, min=3)) cl2 <- mysort(unvs(max_cliques(G, min=3))) expect_that(cl1, is_identical_to(cl2)) }) test_that("Maximal cliques work for subsets", { library(igraph) set.seed(42) G <- sample_gnp(100, .5) cl1 <- mysort(unvs(max_cliques(G, min=8))) c1 <- unvs(max_cliques(G, min=8, subset=1:13)) c2 <- unvs(max_cliques(G, min=8, subset=14:100)) cl2 <- mysort(c(c1, c2)) expect_that(cl1, is_identical_to(cl2)) }) test_that("Counting maximal cliques works", { library(igraph) set.seed(42) G <- sample_gnp(100, .5) cl1 <- count_max_cliques(G, min=8) c1 <- count_max_cliques(G, min=8, subset=1:13) c2 <- count_max_cliques(G, min=8, subset=14:100) cl2 <- c1+c2 expect_that(cl1, is_identical_to(cl2)) }) igraph/tests/testthat/test_graph.edgelist.R0000644000175100001440000000120413177712334020633 0ustar hornikusers context("graph_from_edgelist") test_that("graph_from_edgelist works", { library(igraph) g <- sample_gnp(50, 5/50) el <- as_edgelist(g) g2 <- graph_from_edgelist(el, dir=FALSE) expect_that(graph.isomorphic(g, g2), is_true()) #### g <- sample_gnp(50, 5/50, dir=TRUE) el <- as_edgelist(g) g2 <- graph_from_edgelist(el, dir=TRUE) expect_that(graph.isomorphic(g, g2), is_true()) #### g <- sample_gnp(26, 5/26, dir=TRUE) el <- as_edgelist(g) n <- letters[1:26] names(n) <- 1:26 mode(el) <- "character" el[] <- n[el] g2 <- graph_from_edgelist(el, dir=TRUE) expect_that(graph.isomorphic(g, g2), is_true()) }) igraph/tests/testthat/test_independent.vertex.sets.R0000644000175100001440000000041013177712334022517 0ustar hornikusers context("ivs") test_that("ivs works", { library(igraph) g <- sample_gnp(50, 0.8) ivs <- ivs(g, min=ivs_size(g)) ec <- sapply(seq_along(ivs), function(x) ecount(induced_subgraph(g, ivs[[x]]))) expect_that(unique(ec), equals(0)) }) igraph/tests/testthat/test-constructor-modifiers.R0000644000175100001440000000531713177712334022226 0ustar hornikusers context("Constructor modifiers") test_that("without_attr", { set.seed(42) g <- sample_gnp(10, 2/10) %>% delete_graph_attr("name") %>% delete_graph_attr("type") %>% delete_graph_attr("loops") %>% delete_graph_attr("p") set.seed(42) g2 <- sample_(gnp(10, 2/10), without_attr()) expect_true(identical_graphs(g, g2)) expect_equal(graph_attr_names(g2), character()) expect_equal(vertex_attr_names(g2), character()) expect_equal(edge_attr_names(g2), character()) }) test_that("without_loops", { g <- make_graph(~ A - A:B:C, B - A:B:C, simplify = FALSE) %>% simplify(remove.multiple = FALSE) g2 <- make_(from_literal(A - A:B:C, B - A:B:C, simplify = FALSE), without_loops()) expect_true(identical_graphs(g, g2)) expect_true(all(!which_loop(g2))) }) test_that("without_multiple", { g <- make_graph(~ A - A:B:C, B - A:B:C, simplify = FALSE) %>% simplify(remove.loops = FALSE) g2 <- make_(from_literal(A - A:B:C, B - A:B:C, simplify = FALSE), without_multiples()) expect_true(identical_graphs(g, g2)) expect_true(all(!which_multiple(g2))) }) test_that("simplified", { g <- make_graph(~ A - A:B:C, B - A:B:C) g2 <- make_(from_literal(A - A:B:C, B - A:B:C, simplify = FALSE), simplified()) expect_true(identical_graphs(g, g2)) expect_true(all(!which_multiple(g2))) expect_true(all(!which_loop(g2))) }) test_that("with_vertex_", { g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("foo", value = paste0("xx", 1:3)) g2 <- make_(from_literal(A - A:B:C, B - A:B:C), with_vertex_(color = "red", foo = paste0("xx", 1:3)) ) expect_true(identical_graphs(g, g2)) expect_equal(V(g2)$color, rep("red", gorder(g2))) expect_equal(V(g2)$foo, paste0("xx", 1:3)) }) test_that("with_edge_", { g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_edge_attr("color", value = "red") %>% set_edge_attr("foo", value = seq_len(3)) g2 <- make_(from_literal(A - A:B:C, B - A:B:C), with_edge_(color = "red", foo = seq_len(3))) expect_true(identical_graphs(g, g2)) expect_equal(E(g)$color, E(g2)$color) expect_equal(E(g)$foo, E(g2)$foo) }) test_that("with_graph_", { g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_graph_attr("color", value = "red") %>% set_graph_attr("foo", value = 1:5) g2 <- make_(from_literal(A - A:B:C, B - A:B:C), with_graph_(color = "red", foo = 1:5)) expect_true(identical_graphs(g, g2)) expect_equal(g$color, g2$color) expect_equal(g$foo, g2$foo) }) igraph/tests/testthat/test_sample.R0000644000175100001440000000170713177712334017224 0ustar hornikusers context("Various samplers") test_that("Sampling from a Dirichlet works", { library(igraph) set.seed(42) sd <- sample_dirichlet(100, alpha=c(1, 1, 1)) expect_that(dim(sd), equals(c(3, 100))) expect_that(colSums(sd), equals(rep(1, 100))) expect_that(mean(sd), equals(1/3)) expect_that(sd(sd), equals(0.248901845755354)) ## Corner cases sd1 <- sample_dirichlet(1, alpha=c(2, 2, 2)) expect_that(dim(sd1), equals(c(3, 1))) sd0 <- sample_dirichlet(0, alpha=c(3, 3, 3)) expect_that(dim(sd0), equals(c(3, 0))) ## Errors expect_that(sample_dirichlet(-1, alpha=c(1,1,1,1)), throws_error("should be non-negative")) expect_that(sample_dirichlet(5, alpha=c(1)), throws_error("must have at least two entries")) expect_that(sample_dirichlet(5, alpha=c(0, 1, 1)), throws_error("must be positive")) expect_that(sample_dirichlet(5, alpha=c(1, -1, -1)), throws_error("must be positive")) }) igraph/tests/testthat/test-old-data-type.R0000644000175100001440000000661613177712334020331 0ustar hornikusers context("Old data type and VS/ES") test_that("VS/ES work with old data type", { karate <- structure(list( 34, FALSE, c(1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 17, 19, 21, 31, 2, 3, 7, 13, 17, 19, 21, 30, 3, 7, 8, 9, 13, 27, 28, 32, 7, 12, 13, 6, 10, 6, 10, 16, 16, 30, 32, 33, 33, 33, 32, 33, 32, 33, 32, 33, 33, 32, 33, 32, 33, 25, 27, 29, 32, 33, 25, 27, 31, 31, 29, 33, 33, 31, 33, 32, 33, 32, 33, 32, 33, 33), c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 8, 8, 8, 9, 13, 14, 14, 15, 15, 18, 18, 19, 20, 20, 22, 22, 23, 23, 23, 23, 23, 24, 24, 24, 25, 26, 26, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32), c(0, 1, 16, 2, 17, 24, 3, 4, 5, 35, 37, 6, 18, 25, 32, 7, 26, 27, 8, 36, 38, 9, 10, 33, 11, 19, 28, 34, 39, 40, 12, 20, 13, 21, 14, 22, 57, 62, 29, 58, 63, 30, 59, 66, 23, 41, 15, 64, 65, 69, 31, 42, 46, 48, 50, 53, 55, 60, 71, 73, 75, 43, 44, 45, 47, 49, 51, 52, 54, 56, 61, 67, 68, 70, 72, 74, 76, 77), c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77), c(0, 0, 1, 3, 6, 7, 8, 11, 15, 17, 18, 21, 22, 24, 28, 28, 28, 30, 32, 32, 34, 34, 36, 36, 36, 36, 38, 38, 41, 42, 44, 46, 50, 61, 78), c(0, 16, 24, 32, 35, 37, 40, 41, 41, 44, 45, 45, 45, 45, 46, 48, 50, 50, 50, 52, 53, 55, 55, 57, 62, 65, 66, 68, 69, 71, 73, 75, 77, 78, 78), list(c(1, 0, 1), structure(list( name = "Zachary's karate club network", Citation = "Wayne W. Zachary. An Information Flow Model for Conflict and Fission in Small Groups. Journal of Anthropological Research Vol. 33, No. 4 452-473", Author = "Wayne W. Zachary"), .Names = c("name", "Citation", "Author")), structure(list( Faction = c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), name = c("Mr Hi", "Actor 2", "Actor 3", "Actor 4", "Actor 5", "Actor 6", "Actor 7", "Actor 8", "Actor 9", "Actor 10", "Actor 11", "Actor 12", "Actor 13", "Actor 14", "Actor 15", "Actor 16", "Actor 17", "Actor 18", "Actor 19", "Actor 20", "Actor 21", "Actor 22", "Actor 23", "Actor 24", "Actor 25", "Actor 26", "Actor 27", "Actor 28", "Actor 29", "Actor 30", "Actor 31", "Actor 32", "Actor 33", "John A" )), .Names = c("Faction", "name")), structure(list( weight = c(4, 5, 3, 3, 3, 3, 2, 2, 2, 3, 1, 3, 2, 2, 2, 2, 6, 3, 4, 5, 1, 2, 2, 2, 3, 4, 5, 1, 3, 2, 2, 2, 3, 3, 3, 2, 3, 5, 3, 3, 3, 3, 3, 4, 2, 3, 3, 2, 3, 4, 1, 2, 1, 3, 1, 2, 3, 5, 4, 3, 5, 4, 2, 3, 2, 7, 4, 2, 4, 2, 2, 4, 2, 3, 3, 4, 4, 5)), .Names = "weight"))), class = "igraph") karate2 <- upgrade_graph(karate) vs <- V(karate) vs2 <- V(karate2) expect_equal(length(vs), length(vs2)) expect_equal(vs$name, vs2$name) }) igraph/tests/testthat/test_bipartite.random.game.R0000644000175100001440000000357013177712334022115 0ustar hornikusers context("sample_bipartite") test_that("sample_bipartite works", { library(igraph) set.seed(42) g1 <- sample_bipartite(10, 5, type="gnp", p=.1) expect_that(g1$name, equals("Bipartite Gnp random graph")) expect_that(vcount(g1), equals(15)) expect_that(ecount(g1), equals(7)) expect_that(bipartite_mapping(g1)$res, is_true()) expect_that(is_directed(g1), is_false()) g2 <- sample_bipartite(10, 5, type="gnp", p=.1, directed=TRUE) expect_that(vcount(g2), equals(15)) expect_that(ecount(g2), equals(6)) expect_that(bipartite_mapping(g2)$res, is_true()) expect_that(is_directed(g2), is_true()) expect_that(print_all(g2), prints_text("5->11")); g3 <- sample_bipartite(10, 5, type="gnp", p=.1, directed=TRUE, mode="in") expect_that(print_all(g3), prints_text("11->3")); g4 <- sample_bipartite(10, 5, type="gnm", m=8) expect_that(vcount(g4), equals(15)) expect_that(ecount(g4), equals(8)) expect_that(bipartite_mapping(g4)$res, is_true()) expect_that(is_directed(g4), is_false()) g5 <- sample_bipartite(10, 5, type="gnm", m=8, directed=TRUE) expect_that(vcount(g5), equals(15)) expect_that(ecount(g5), equals(8)) expect_that(bipartite_mapping(g5)$res, is_true()) expect_that(is_directed(g5), is_true()) expect_that(print_all(g5), prints_text("5->12")) g6 <- sample_bipartite(10, 5, type="gnm", m=8, directed=TRUE, mode="in") expect_that(vcount(g6), equals(15)) expect_that(ecount(g6), equals(8)) expect_that(bipartite_mapping(g6)$res, is_true()) expect_that(is_directed(g6), is_true()) expect_that(print_all(g6), prints_text("12->10")) ##### g7 <- sample_bipartite(10, 5, type="gnp", p=0.9999, directed=TRUE, mode="all") expect_that(ecount(g7), equals(100)) g8 <- sample_bipartite(10, 5, type="gnm", m=99, directed=TRUE, mode="all") expect_that(ecount(g8), equals(99)) }) igraph/tests/testthat/test_graph.density.R0000644000175100001440000000055513177712334020522 0ustar hornikusers context("edge_density") test_that("edge_density works", { library(igraph) g <- sample_gnp(50, 4/50) gd <- edge_density(g) gd2 <- ecount(g) / vcount(g) / (vcount(g)-1) * 2 expect_that(gd, equals(gd2)) #### g <- sample_gnp(50, 4/50, dir=TRUE) gd <- edge_density(g) gd2 <- ecount(g) / vcount(g) / (vcount(g)-1) expect_that(gd, equals(gd2)) }) igraph/tests/testthat/test_closeness.R0000644000175100001440000000355513177712334017744 0ustar hornikusers context("closeness") test_that("closeness works", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) clo <- closeness(kite) * (vcount(kite)-1) expect_that(round(sort(clo, decreasing=TRUE), 3), equals(c(Fernando=0.643, Garth=0.643, Diane=0.600, Heather=0.600, Andre=0.529, Beverly=0.529, Carol=0.500, Ed=0.500, Ike=0.429, Jane=0.310))) clo2 <- closeness(kite, normalized=TRUE) expect_that(clo, equals(clo2)) }) ## TODO: weighted closeness test_that("closeness centralization works", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) c1 <- closeness(kite, normalized=TRUE) c2 <- centr_clo(kite) expect_that(unname(c1), equals(c2$res)) expect_that(c2$centralization, equals(0.270374931581828)) expect_that(c2$theoretical_max, equals(4.23529411764706)) }) igraph/tests/testthat/test_fastgreedy.community.R0000644000175100001440000000172713177712334022125 0ustar hornikusers context("cluster_fast_greedy") test_that("cluster_fast_greedy works", { library(igraph) set.seed(42) g <- make_graph("Zachary") fc <- cluster_fast_greedy(g) expect_that(modularity(g, fc$membership), equals(max(fc$modularity))) expect_that(as.vector(membership(fc)), equals(c(1, 3, 3, 3, 1, 1, 1, 3, 2, 3, 1, 1, 3, 3, 2, 2, 1, 3, 2, 1, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2))) expect_that(length(fc), equals(3)) expect_that(as.numeric(sizes(fc)), equals(c(8, 17, 9))) d <- as.dendrogram(fc) expect_that(print(d), prints_text("2 branches.*34 members.*height 33")) expect_that(print(d[[1]]), prints_text("2 branches.*17 members.*height 32")) expect_that(print(d[[2]]), prints_text("2 branches.*17 members.*height 30")) m2 <- cut_at(fc, no=3) expect_that(modularity(g, m2), equals(fc$modularity[length(fc$modularity)-2])) }) igraph/tests/testthat/test_canonical.permutation.R0000644000175100001440000000107113177712334022232 0ustar hornikusers context("canonical_permutation") test_that("canonical_permutation works", { library(igraph) g1 <- sample_gnm(10, 20) cp1 <- canonical_permutation(g1) cf1 <- permute(g1, cp1$labeling) ## Do the same with a random permutation of it g2 <- permute(g1, sample(vcount(g1))) cp2 <- canonical_permutation(g2) cf2 <- permute(g2, cp2$labeling) ## Check that they are the same el1 <- as_edgelist(cf1) el2 <- as_edgelist(cf2) el1 <- el1[ order(el1[,1], el1[,2]), ] el2 <- el2[ order(el2[,1], el2[,2]), ] expect_that(el1, equals(el2)) }) igraph/tests/testthat/test_get.adjlist.R0000644000175100001440000000206513177712334020151 0ustar hornikusers context("as_adj_list") test_that("as_adj_list works", { library(igraph) g <- sample_gnp(50, 2/50) al <- as_adj_list(g) g2 <- graph_from_adj_list(al, mode="all") expect_that(graph.isomorphic(g, g2), is_true()) expect_that(graph.isomorphic.vf2(g, g2, vertex.color1=1:vcount(g), vertex.color2=1:vcount(g2))$iso, is_true()) #### el <- as_adj_edge_list(g) for (i in 1:vcount(g)) { a <- E(g)[.inc(i)] expect_that(length(a), is_equivalent_to(length(el[[i]]))) expect_that(sort(el[[i]]), is_equivalent_to(sort(a))) } g <- sample_gnp(50, 4/50, directed=TRUE) el1 <- as_adj_edge_list(g, mode="out") el2 <- as_adj_edge_list(g, mode="in") for (i in 1:vcount(g)) { a <- E(g)[.from(i)] expect_that(length(a), is_equivalent_to(length(el1[[i]]))) expect_that(sort(el1[[i]]), is_equivalent_to(sort(a))) } for (i in 1:vcount(g)) { a <- E(g)[.to(i)] expect_that(length(a), is_equivalent_to(length(el2[[i]]))) expect_that(sort(el2[[i]]), is_equivalent_to(sort(a))) } }) igraph/tests/testthat/test_as.undirected.R0000644000175100001440000000134713177712334020473 0ustar hornikusers context("as.undirected") test_that("as.undirected keeps attributes", { library(igraph) g <- graph_from_literal(A+-+B, A--+C, C+-+D) g$name <- "Tiny graph" E(g)$weight <- seq_len(ecount(g)) g2 <- as.undirected(g, mode="collapse") ; df2 <- as_data_frame(g2) g3 <- as.undirected(g, mode="each") ; df3 <- as_data_frame(g3) g4 <- as.undirected(g, mode="mutual") ; df4 <- as_data_frame(g4) expect_that(g2$name, equals(g$name)) expect_that(g3$name, equals(g$name)) expect_that(g4$name, equals(g$name)) expect_that(df2[order(df2[,1], df2[,2]),]$weight, equals(c(4,2,9))) expect_that(df3[order(df3[,1], df3[,2]),]$weight, equals(c(1,3,2,4,5))) expect_that(df4[order(df4[,1], df4[,2]),]$weight, equals(c(4,9))) }) igraph/tests/testthat/test_laplacian.spectral.embedding.R0000644000175100001440000003625313177712334023424 0ustar hornikusers context("Spectral embedding of the Laplacian") std <- function(x) { x <- zapsmall(x) apply(x, 2, function(col) { if (any(col < 0) && col[which(col != 0)[1]] < 0) { -col } else { col } }) } mag_order <- function(x) { order(abs(x), sign(x), decreasing=TRUE) } mag_sort <- function(x) { x[mag_order(x)] } test_that("Undirected, unweighted, D-A case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) no <- 3 A <- diag(degree(g)) - g[] ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(ss$values))) Y <- std(ss$vectors %*% sqrt(diag(ss$values))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="D-A", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="D-A", scaled=FALSE) expect_that(au_la$D, equals(D[1:no])) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="D-A", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="D-A", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="D-A", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="D-A", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Undirected, unweighted, DAD case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) no <- 3 D12 <- diag(1/sqrt(degree(g))) A <- D12 %*% g[] %*% D12 ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) Y <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="DAD", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="DAD", scaled=FALSE) expect_that(au_la$D, equals(abs(D[1:no]))) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="DAD", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="DAD", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="DAD", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="DAD", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Undirected, unweighted, I-DAD case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) no <- 3 D12 <- diag(1/sqrt(degree(g))) A <- diag(vcount(g)) - D12 %*% g[] %*% D12 ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) Y <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="I-DAD", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="I-DAD", scaled=FALSE) expect_that(au_la$D, equals(abs(D[1:no]))) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="I-DAD", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="I-DAD", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="I-DAD", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="I-DAD", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Undirected, weighted, D-A case works", { library(igraph) set.seed(42*42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) no <- 3 A <- diag(graph.strength(g)) - g[] ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(abs(D)))) Y <- std(ss$vectors %*% sqrt(diag(abs(D)))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="D-A", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="D-A", scaled=FALSE) expect_that(au_la$D, equals(abs(D[1:no]))) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="D-A", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="D-A", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="D-A", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="D-A", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(X[,vcount(g)-1:no+1], tolerance=.Machine$double.eps ^ 0.25)) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Undirected, unweighted, DAD case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) no <- 3 D12 <- diag(1/sqrt(degree(g))) A <- D12 %*% g[] %*% D12 ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) Y <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="DAD", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="DAD", scaled=FALSE) expect_that(au_la$D, equals(abs(D[1:no]))) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="DAD", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="DAD", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="DAD", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="DAD", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Undirected, unweighted, I-DAD case works", { library(igraph) set.seed(42) g <- random.graph.game(10, 20, type="gnm", directed=FALSE) no <- 3 D12 <- diag(1/sqrt(degree(g))) A <- diag(vcount(g)) - D12 %*% g[] %*% D12 ss <- eigen(A) D <- ss$values U <- ss$vectors X <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) Y <- std(ss$vectors %*% sqrt(diag(abs(ss$values)))) ## LA au_la <- embed_laplacian_matrix(g, no=no, which="la", type="I-DAD", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="I-DAD", scaled=FALSE) expect_that(au_la$D, equals(abs(D[1:no]))) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) ## LM au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="I-DAD", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="I-DAD", scaled=FALSE) expect_that(au_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(au_lm$X), equals(std(X[,mag_order(D)][,1:no]))) expect_that(as_lm$D, equals(mag_sort(D)[1:no])) expect_that(std(as_lm$X), equals(std(U[,mag_order(D)][,1:no]))) ## SA au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="I-DAD", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="I-DAD", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) }) test_that("Directed, unweighted, OAP case works", { library(igraph) set.seed(42*42) g <- random.graph.game(10, 30, type="gnm", directed=TRUE) no <- 3 O12 <- diag(1/sqrt(degree(g, mode="out"))) P12 <- diag(1/sqrt(degree(g, mode="in"))) A <- O12 %*% g[] %*% P12 ss <- svd(A) D <- ss$d U <- ss$u V <- ss$v X <- std(ss$u %*% sqrt(diag(ss$d))) Y <- std(ss$v %*% sqrt(diag(ss$d))) au_la <- embed_laplacian_matrix(g, no=no, which="la", type="OAP", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="OAP", scaled=FALSE) expect_that(au_la$D, equals(D[1:no])) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(std(au_la$Y), equals(std(Y[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(std(as_la$Y), equals(std(V[,1:no]))) au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="OAP", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="OAP", scaled=FALSE) expect_that(au_lm$D, equals(D[1:no])) expect_that(std(au_lm$X), equals(std(X[,1:no]))) expect_that(std(au_lm$Y), equals(std(Y[,1:no]))) expect_that(as_lm$D, equals(D[1:no])) expect_that(std(as_lm$X), equals(std(U[,1:no]))) expect_that(std(as_lm$Y), equals(std(V[,1:no]))) au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="OAP", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="OAP", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(std(au_sa$Y), equals(std(Y[,vcount(g)-1:no+1]), tolerance=sqrt(sqrt(.Machine$double.eps)))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(as_sa$Y), equals(std(V[,vcount(g)-1:no+1]))) }) test_that("Directed, weighted case works", { library(igraph) set.seed(42*42) g <- random.graph.game(10, 30, type="gnm", directed=TRUE) E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) no <- 3 O12 <- diag(1/sqrt(graph.strength(g, mode="out"))) P12 <- diag(1/sqrt(graph.strength(g, mode="in"))) A <- O12 %*% g[] %*% P12 ss <- svd(A) D <- ss$d U <- ss$u V <- ss$v X <- std(ss$u %*% sqrt(diag(ss$d))) Y <- std(ss$v %*% sqrt(diag(ss$d))) au_la <- embed_laplacian_matrix(g, no=no, which="la", type="OAP", scaled=TRUE) as_la <- embed_laplacian_matrix(g, no=no, which="la", type="OAP", scaled=FALSE) expect_that(au_la$D, equals(D[1:no])) expect_that(std(au_la$X), equals(std(X[,1:no]))) expect_that(std(au_la$Y), equals(std(Y[,1:no]))) expect_that(as_la$D, equals(D[1:no])) expect_that(std(as_la$X), equals(std(U[,1:no]))) expect_that(std(as_la$Y), equals(std(V[,1:no]))) au_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="OAP", scaled=TRUE) as_lm <- embed_laplacian_matrix(g, no=no, which="lm", type="OAP", scaled=FALSE) expect_that(au_lm$D, equals(D[1:no])) expect_that(std(au_lm$X), equals(std(X[,1:no]))) expect_that(std(au_lm$Y), equals(std(Y[,1:no]))) expect_that(as_lm$D, equals(D[1:no])) expect_that(std(as_lm$X), equals(std(U[,1:no]))) expect_that(std(as_lm$Y), equals(std(V[,1:no]))) au_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="OAP", scaled=TRUE) as_sa <- embed_laplacian_matrix(g, no=no, which="sa", type="OAP", scaled=FALSE) expect_that(au_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(au_sa$X), equals(std(X[,vcount(g)-1:no+1]))) expect_that(std(au_sa$Y), equals(std(Y[,vcount(g)-1:no+1]), tolerance=sqrt(sqrt(.Machine$double.eps)))) expect_that(as_sa$D, equals(D[vcount(g)-1:no+1])) expect_that(std(as_sa$X), equals(std(U[,vcount(g)-1:no+1]))) expect_that(std(as_sa$Y), equals(std(V[,vcount(g)-1:no+1]))) }) igraph/tests/testthat/test_get.shortest.paths.R0000644000175100001440000000166213177712334021512 0ustar hornikusers context("shortest_paths") test_that("shortest_paths works", { library(igraph) edges <- matrix(c("s", "a", 2, "s", "b", 4, "a", "t", 4, "b", "t", 2, "a", "1", 1, "a", "2", 1, "a", "3", 2, "1", "b", 1, "2", "b", 2, "3", "b", 1), byrow=TRUE, ncol=3, dimnames=list(NULL, c("from", "to", "weight"))) edges <- as.data.frame(edges) edges[[3]] <- as.numeric(as.character(edges[[3]])) g <- graph_from_data_frame(as.data.frame(edges)) all1 <- all_shortest_paths(g, "s", "t", weights=NA)$res all2 <- all_shortest_paths(g, "s", "t")$res s1 <- shortest_paths(g, "s", "t", weights=NA) s2 <- get.shortest.paths(g, "s", "t") expect_that(s1$vpath %in% all1, is_true()) expect_that(s2$vpath %in% all2, is_true()) }) igraph/tests/testthat/test_hsbm.R0000644000175100001440000000640413177712334016673 0ustar hornikusers context("Hierarchical stochastic block models") test_that("HSBM works", { library(igraph) set.seed(42) C <- matrix(c(1 , 1/2, 0, 1/2, 0, 1/2, 0 , 1/2, 1/2), nrow=3) g <- sample_hierarchical_sbm(100, 10, rho=c(3,3,4)/10, C=C, p=0) expect_that(ecount(g), equals(172)) expect_that(vcount(g), equals(100)) expect_that(is.directed(g), is_false()) set.seed(42) g2 <- sample_hierarchical_sbm(100, 10, rho=c(3,3,4)/10, C=C, p=1) expect_that(ecount(g2), equals(ecount(g) + 10 * 9 * (90 + 10) / 2)) expect_that(vcount(g2), equals(100)) expect_that(is.simple(g2), is_true()) set.seed(42) g3 <- sample_hierarchical_sbm(100, 10, rho=c(3,3,4)/10, C=C, p=1e-15) expect_that(ecount(g3), equals(ecount(g))) expect_that(vcount(g3), equals(100)) expect_that(is.simple(g3), is_true()) set.seed(42) g4 <- sample_hierarchical_sbm(100, 10, rho=c(3,3,4)/10, C=C, p=1-1e-15) expect_that(ecount(g4), equals(ecount(g2))) expect_that(vcount(g4), equals(100)) expect_that(is.simple(g4), is_true()) }) test_that("HSBM with 1 cluster per block works", { library(igraph) res <- Matrix(0, nrow=10, ncol=10) res[6:10, 1:5] <- res[1:5, 6:10] <- 1 g <- sample_hierarchical_sbm(10, 5, rho=1, C=matrix(0), p=1) expect_that(g[], equals(res)) }) test_that("HSBM with list arguments works", { library(igraph) b <- 5 C <- matrix(c(1 , 1/2, 0, 1/2, 0, 1/2, 0 , 1/2, 1/2), nrow=3) m <- 10 rho <- c(3,3,4)/10 set.seed(42) g <- sample_hierarchical_sbm(b*m, m, rho=rho, C=C, p=0) set.seed(42) g2 <- sample_hierarchical_sbm(b*m, rep(m, b), rho=rho, C=C, p=0) expect_that(g[], equals(g2[])) set.seed(42) g3 <- sample_hierarchical_sbm(b*m, m, rho=replicate(b, rho, simplify=FALSE), C=C, p=0) expect_that(g[], equals(g3[])) set.seed(42) g4 <- sample_hierarchical_sbm(b*m, m, rho=rho, C=replicate(b, C, simplify=FALSE), p=0) expect_that(g[], equals(g4[])) expect_that(sample_hierarchical_sbm(b*m, rep(m, b), rho=list(rho, rho), C=C, p=0), throws_error("Lengths of `m', `rho' and `C' must match")) ### n <- function(x) x/sum(x) rho1 <- n(c(1,2)) C1 <- matrix(0, nrow=2, ncol=2) rho2 <- n(c(3,3,4)) C2 <- matrix(0, nrow=3, ncol=3) rho3 <- 1 C3 <- matrix(0) rho4 <- n(c(2,1)) C4 <- matrix(0, nrow=2, ncol=2) gg1 <- sample_hierarchical_sbm(21, m=c(3, 10, 5, 3), rho=list(rho1, rho2, rho3, rho4), C=list(C1, C2, C3, C4), p=1) expect_that(is.simple(gg1), is_true()) set.seed(42) gg11 <- sample_hierarchical_sbm(21, m=c(3, 10, 5, 3), rho=list(rho1, rho2, rho3, rho4), C=list(C1, C2, C3, C4), p=1-1e-10) expect_that(gg1[], equals(gg11[])) rho1 <- n(c(1,2)) C1 <- matrix(1, nrow=2, ncol=2) rho2 <- n(c(3,3,4)) C2 <- matrix(1, nrow=3, ncol=3) rho3 <- 1 C3 <- matrix(1) rho4 <- n(c(2,1)) C4 <- matrix(1, nrow=2, ncol=2) gg2 <- sample_hierarchical_sbm(21, m=c(3, 10, 5, 3), rho=list(rho1, rho2, rho3, rho4), C=list(C1, C2, C3, C4), p=0) expect_that(is.simple(gg2), is_true()) gg22 <- sample_hierarchical_sbm(21, m=c(3, 10, 5, 3), rho=list(rho1, rho2, rho3, rho4), C=list(C1, C2, C3, C4), p=1) expect_that(gg1[] + gg2[], equals(gg22[])) }) igraph/tests/testthat/test_bipartite.projection.R0000644000175100001440000000667213177712334022107 0ustar hornikusers context("bipartite_projection") test_that("bipartite_projection works", { library(igraph) set.seed(42) g <- make_full_bipartite_graph(10,5) proj <- bipartite_projection(g) expect_that(graph.isomorphic(proj[[1]], make_full_graph(10)), is_true()) expect_that(graph.isomorphic(proj[[2]], make_full_graph(5)), is_true()) M <- matrix(0, nr=5, nc=3) rownames(M) <- c("Alice", "Bob", "Cecil", "Dan", "Ethel") colnames(M) <- c("Party", "Skiing", "Badminton") M[] <- sample(0:1, length(M), replace=TRUE) M g2 <- graph_from_incidence_matrix(M) expect_that(as.matrix(g2[1:5,6:8]), equals(M)) expect_that(as.matrix(g2[1:5,1:5]), is_equivalent_to(matrix(0, 5, 5))) expect_that(as.matrix(g2[6:8,6:8]), is_equivalent_to(matrix(0, 3, 3))) g2$name <- "Event network" proj2 <- bipartite_projection(g2) expect_that(as.matrix(proj2[[1]][]), is_equivalent_to(cbind(c(0,2,0,2,2), c(2,0,1,2,2), c(0,1,0,0,0), c(2,2,0,0,2), c(2,2,0,2,0)))) expect_that(as.matrix(proj2[[2]][]), is_equivalent_to(cbind(c(0,4,1), c(4,0,1), c(1,1,0)))) bs <- bipartite_projection_size(g2) expect_that(bs$vcount1, equals(vcount(proj2[[1]]))) expect_that(bs$ecount1, equals(ecount(proj2[[1]]))) expect_that(bs$vcount2, equals(vcount(proj2[[2]]))) expect_that(bs$ecount2, equals(ecount(proj2[[2]]))) }) test_that("bipartite_projection can calculate only one projection", { library(igraph) set.seed(42) g <- sample_bipartite(5, 10, p=.3) proj <- bipartite_projection(g) proj1 <- bipartite_projection(g, which="false") proj2 <- bipartite_projection(g, which="true") expect_that(graph.isomorphic(proj$proj1, proj1), is_true()) expect_that(graph.isomorphic(proj$proj2, proj2), is_true()) expect_that(vertex.attributes(proj$proj1), equals(vertex.attributes(proj1))) expect_that(vertex.attributes(proj$proj2), equals(vertex.attributes(proj2))) expect_that(edge_attr(proj$proj1), equals(edge_attr(proj1))) expect_that(edge_attr(proj$proj2), equals(edge_attr(proj2))) }) test_that("bipartite_projection removes 'type' attribute if requested", { library(igraph) g <- make_full_bipartite_graph(10,5) proj <- bipartite_projection(g) proj1 <- bipartite_projection(g, which="true") proj2 <- bipartite_projection(g, which="false") proj3 <- bipartite_projection(g, remove.type=FALSE) proj4 <- bipartite_projection(g, which="true", remove.type=FALSE) proj5 <- bipartite_projection(g, which="false", remove.type=FALSE) expect_that("type" %in% vertex_attr_names(proj[[1]]), is_false()) expect_that("type" %in% vertex_attr_names(proj[[2]]), is_false()) expect_that("type" %in% vertex_attr_names(proj1), is_false()) expect_that("type" %in% vertex_attr_names(proj2), is_false()) expect_that("type" %in% vertex_attr_names(proj3[[1]]), is_true()) expect_that("type" %in% vertex_attr_names(proj3[[2]]), is_true()) expect_that("type" %in% vertex_attr_names(proj4), is_true()) expect_that("type" %in% vertex_attr_names(proj5), is_true()) }) test_that("bipartite_projection breaks for non-bipartite graphs (#543)", { library(igraph) g <- graph_from_literal(A-0, B-1, A-1, 0-1) V(g)$type <- V(g)$name %in% LETTERS expect_that(bipartite_projection_size(g), throws_error("Non-bipartite edge found in bipartite projection")) expect_that(bipartite_projection(g), throws_error("Non-bipartite edge found in bipartite projection")) }) igraph/tests/testthat/test_decompose.graph.R0000644000175100001440000000231513177712334021015 0ustar hornikusers context("decompose") test_that("decompose works", { library(igraph) g <- sample_gnp(1000, 1/1500) G <- decompose(g) clu <- components(g) Gsizes <- sapply(G, vcount) expect_that(sort(clu$csize), equals(sort(Gsizes))) }) test_that("decompose works for many components", { library(igraph) g <- make_empty_graph(50001) tmp <- decompose(g) expect_that(1, equals(1)) }) test_that("decompose works for many components and attributes", { library(igraph) g <- make_empty_graph(50001) V(g)$name <- 1:vcount(g) tmp <- decompose(g) expect_that(1, equals(1)) }) test_that("decompose keeps attributes", { library(igraph) g <- make_ring(10) + make_ring(5) V(g)$name <- letters[1:(10+5)] E(g)$name <- apply(as_edgelist(g), 1, paste, collapse="-") d <- decompose(g) d <- d[order(sapply(d, vcount))] expect_that(length(d), equals(2)) expect_that(sapply(d, vcount), equals(c(5,10))) expect_that(V(d[[1]])$name, equals(letters[1:5+10])) expect_that(V(d[[2]])$name, equals(letters[1:10])) e1 <- apply(as_edgelist(d[[1]]), 1, paste, collapse="-") e2 <- apply(as_edgelist(d[[2]]), 1, paste, collapse="-") expect_that(E(d[[1]])$name, equals(e1)) expect_that(E(d[[2]])$name, equals(e2)) }) igraph/tests/testthat/test-index-es.R0000644000175100001440000000176413177712334017400 0ustar hornikusers context("VS/ES indexing") test_that("I can index a vs twice", { edges <- data.frame( stringsAsFactors = TRUE, from = c("BOS", "JFK", "DEN", "BOS", "JFK", "DEN"), to = c("JFK", "DEN", "ABQ", "JFK", "DEN", "ABQ"), carrier = c("foo", "foo", "foo", "bar", "bar", "bar") ) vertices <- data.frame( stringsAsFactors = TRUE, id = c("BOS", "JFK", "DEN", "ABQ"), state = c("MA", "NY", "CO", "NM") ) g <- graph_from_data_frame(edges, vertices = vertices) x <- V(g)[ 3:4 ] [ state == 'NM' ] expect_equal(x, V(g)['ABQ']) }) test_that("I can index an es twice", { edges <- data.frame( stringsAsFactors = TRUE, from = c("BOS", "JFK", "DEN", "BOS", "JFK", "DEN"), to = c("JFK", "DEN", "ABQ", "JFK", "DEN", "ABQ"), carrier = c("foo", "foo", "foo", "bar", "bar", "bar") ) g <- graph_from_data_frame(edges) x <- E(g)['BOS' %->% 'JFK'][carrier == 'foo'] expect_equal(x, E(g)[ carrier == 'foo' & .from('BOS') & .to('JFK')]) }) igraph/tests/testthat/test_graph.knn.R0000644000175100001440000000252213177712334017625 0ustar hornikusers context("knn") test_that("knn works", { library(igraph) set.seed(42) ## Some trivial ones g <- make_ring(10) expect_that(knn(g), equals(list(knn=rep(2,10), knnk=c(NaN, 2)))) g2 <- make_star(10) expect_that(knn(g2), equals(list(knn=c(1, rep(9,9)), knnk=c(9, rep(NaN, 7), 1)))) ## A scale-free one, try to plot 'knnk' g3 <- simplify(sample_pa(1000, m=5)) r3 <- knn(g3) expect_that(r3$knn[43], equals(46)) expect_that(r3$knn[1000], equals(192.4)) expect_that(r3$knnk[100], equals(18.78)) expect_that(length(r3$knnk), equals(359)) ## A random graph g4 <- sample_gnp(1000, p=5/1000) r4 <- knn(g4) expect_that(r4$knn[1000], equals(20/3)) expect_that(length(r4$knnk), equals(15)) expect_that(r4$knnk[12], equals(19/3)) ## A weighted graph g5 <- make_star(10) E(g5)$weight <- seq(ecount(g5)) r5 <- knn(g5) expect_that(r5, equals(structure(list(knn = c(1, 45, 22.5, 15, 11.25, 9, 7.5, 6.42857142857143, 5.625, 5), knnk = c(14.1448412698413, NaN, NaN, NaN, NaN, NaN, NaN, NaN, 1)), .Names = c("knn", "knnk")) )) }) igraph/tests/testthat/test_indexing2.R0000644000175100001440000000566313177712334017637 0ustar hornikusers context("Assignments via indexing") library(igraph) am <- function(x) { x <- as.matrix(x) dimnames(x) <- NULL x } test_that("[ can add and delete edges", { g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) A[1,2] <- g[1,2] <- TRUE expect_that(am(g[]), equals(A)) A[2,1] <- g[2,1] <- TRUE expect_that(am(g[]), equals(A)) g[2,1] <- NULL ; A[2,1] <- 0 expect_that(am(g[]), equals(A)) A[1,2] <- g[1,2] <- FALSE expect_that(am(g[]), equals(A)) g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) A[-1,1] <- g[-1,1] <- 1 expect_that(am(g[]), equals(A)) }) test_that("[ can set weights and delete weighted edges", { g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) g <- set_edge_attr(g, "weight", c(), 1) A[1,2] <- g[1,2] <- 1 expect_that(am(g[]), equals(A)) A[2,1] <- g[2,1] <- 2 expect_that(am(g[]), equals(A)) A[1,2] <- g[1,2] <- 3 expect_that(am(g[]), equals(A)) A[1:2,2:3] <- g[1:2,2:3] <- -1 expect_that(am(g[]), equals(A)) g[1,2] <- NULL ; A[1,2] <- 0 expect_that(am(g[]), equals(A)) }) test_that("[ can add edges and ste weights via vertex names", { g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) V(g)$name <- letters[1:vcount(g)] rownames(A) <- colnames(A) <- letters[1:vcount(g)] A['a', 'b'] <- g['a','b'] <- TRUE A['b', 'c'] <- g['b','c'] <- TRUE expect_that(am(g[]), equals(am(A))) A[c('a','f'), c('f','a')] <- g[c('a','f'),c('f','a')] <- TRUE expect_that(am(g[]), equals(am(A))) A[A==1] <- NA A[c('a','c','h'), c('a', 'b', 'c')] <- g[c('a','c','h'), c('a','b','c'), attr="weight"] <- 3 expect_that(am(g[]), equals(am(A))) }) test_that("[ and the from-to notation", { g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) V(g)$name <- letters[1:vcount(g)] rownames(A) <- colnames(A) <- letters[1:vcount(g)] g[from=c('a','c','h'), to=c('a','b','c')] <- 1 A['a','a'] <- A['c','b'] <- A['h','c'] <- 1 expect_that(g[from=c('a','c','h','d'), to=c('a','b','c','e')], equals(c(1,1,1,0))) expect_that(am(g[]), equals(am(A))) g[from=c('a','c','h','a'), to=c('a','a','a','e'), attr="weight"] <- 3 A[A!=0] <- NA ; A['a','a'] <- A['c','a'] <- A['h','a'] <- A['a','e'] <- 3 expect_that(g[from=c('a','c','h','a','c','c'), to=c('a','a','a','e','f','b')], equals(c(3,3,3,3,0,NA))) expect_that(am(g[]), equals(am(A))) }) test_that("[ and from-to with multiple values", { g <- make_empty_graph(10) ; A <- matrix(0, 10, 10) V(g)$name <- letters[1:vcount(g)] rownames(A) <- colnames(A) <- letters[1:vcount(g)] g[from=c('a','c','h'), to=c('a','b','c')] <- 1 A['a','a'] <- A['c','b'] <- A['h','c'] <- 1 g[from=c('a','c','h','a'), to=c('a','a','a','e'), attr="weight"] <- 5:8 A[A!=0] <- NA ; A['a','a'] <- 5 ; A['c','a'] <- 6 ; A['h','a'] <- 7 A['a','e'] <- 8 expect_that(g[from=c('a','c','h','a','c','c'), to=c('a','a','a','e','f','b')], equals(c(5:8,0,NA))) expect_that(am(g[]), equals(am(A))) }) igraph/tests/testthat/test_hrg.R0000644000175100001440000000045113177712334016516 0ustar hornikusers context("Hierarchical random graphs") test_that("Starting from state works (#225)", { library(igraph) set.seed(42) g <- sample_gnp(10, p=1/2) + sample_gnp(10, p=1/2) hrg <- fit_hrg(g) hrg2 <- fit_hrg(g, hrg=hrg, start=TRUE, steps=1) expect_that(hrg2, is_equivalent_to(hrg)) }) igraph/tests/testthat/test_bug-1073800-clique.R0000644000175100001440000000046413177712334020617 0ustar hornikusers context("Bug 1073800") test_that("Largest cliques is correct", { library(igraph) unvs <- function(x) lapply(x, as.vector) adj <- matrix(1, nrow=11, ncol=11) - diag(11) g <- graph_from_adjacency_matrix(adj) lc <- suppressWarnings(largest_cliques(g)) expect_that(unvs(lc), equals(list(1:11))) }) igraph/tests/testthat/test_graph.adjlist.R0000644000175100001440000000065013177712334020471 0ustar hornikusers context("graph_from_adj_list") test_that("graph_from_adj_list works", { library(igraph) g <- sample_gnp(100, 3/100) al <- as_adj_list(g) g2 <- graph_from_adj_list(al, mode="all") expect_that(graph.isomorphic(g, g2), is_true()) ## g <- sample_gnp(100, 3/100, dir=TRUE) al <- as_adj_list(g, mode="out") g2 <- graph_from_adj_list(al, mode="out") expect_that(graph.isomorphic(g, g2), is_true()) }) igraph/tests/testthat/test_graph.formula.R0000644000175100001440000000053213177712334020503 0ustar hornikusers context("graph_from_literal") test_that("simplify argument works", { library(igraph) g1 <- graph_from_literal(1-1, 1-2, 1-2) g2 <- graph_from_literal(1-1, 1-2, 1-2, simplify=FALSE) expect_that(vcount(g1), equals(2)) expect_that(ecount(g1), equals(1)) expect_that(vcount(g2), equals(2)) expect_that(ecount(g2), equals(3)) }) igraph/tests/testthat/test_attributes.R0000644000175100001440000001321513177712334020126 0ustar hornikusers context("attributes") test_that("assigning and querying attributes work", { library(igraph) ## Create a small ring graph, assign attributes ring <- graph_from_literal( A-B-C-D-E-F-G-A ) E(ring)$weight <- seq_len(ecount(ring)) ## Query attributes expect_that(V(ring)$name, equals(LETTERS[seq_len(vcount(ring))])) expect_that(E(ring)$weight, equals(seq_len(ecount(ring)))) }) test_that("brackering works", { library(igraph) g <- graph(c(1,2, 1,3, 3,4)) g <- set_vertex_attr(g, name="weight", value=1:vcount(g)) g <- set_edge_attr(g, name="weight", value=1:ecount(g)) g <- set_graph_attr(g, name="name", "foo") graph2 <- set_vertex_attr(g, name="weight", value=rep(1, vcount(g))) graph2 <- set_edge_attr(g, name="weight", value=rep(1, ecount(g))) graph2 <- set_graph_attr(g, name="name", "foobar") expect_that(vertex_attr(g, name="weight"), equals(1:4)) expect_that(edge_attr(g, name="weight"), equals(1:3)) expect_that(graph_attr(g, name="name"), equals("foo")) }) test_that("brackering works with a function", { library(igraph) library(testthat) g <- graph(c(1,2, 1,3, 3,4)) g <- set_vertex_attr(g, name="weight", value=1:vcount(g)) g <- set_edge_attr(g, name="weight", value=1:ecount(g)) g <- set_graph_attr(g, name="name", "foo") run.test <- function(graph) { graph2 <- set_vertex_attr(graph, name="weight", value=rep(1, vcount(graph))) graph2 <- set_edge_attr(graph, name="weight", value=rep(1, ecount(graph))) graph2 <- set_graph_attr(graph, name="name", "foobar") } g2 <- run.test(g) expect_that(vertex_attr(g, name="weight"), equals(1:4)) expect_that(edge_attr(g, name="weight"), equals(1:3)) expect_that(graph_attr(g, name="name"), equals("foo")) }) test_that("brackering works with shortcuts", { library(igraph) g <- graph(c(1,2, 1,3, 3,4)) g <- set_vertex_attr(g, name="weight", value=1:vcount(g)) g <- set_edge_attr(g, name="weight", value=1:ecount(g)) g <- set_graph_attr(g, name="name", "foo") run.test <- function(graph) { V(graph)$weight <- rep(1, vcount(graph)) E(graph)$weight <- rep(1, ecount(graph)) graph$name <- "foobar" } g2 <- run.test(g) expect_that(vertex_attr(g, name="weight"), equals(1:4)) expect_that(edge_attr(g, name="weight"), equals(1:3)) expect_that(graph_attr(g, name="name"), equals("foo")) }) ## TODO: subsetting test_that("we can query all attributes at once", { g <- graph(c(1,2, 1,3, 2,4)) expect_equal(graph_attr(g), structure(list(), .Names = character(0))) expect_equal(vertex_attr(g), list()) expect_equal(edge_attr(g), list()) g$name <- "toy" g$layout <- cbind(1:4, 1:4) V(g)$name <- letters[1:4] V(g)$color <- rainbow(4) E(g)$weight <- 1:3 E(g)$label <- LETTERS[1:3] expect_equal(graph_attr(g), list(name = "toy", layout = cbind(1:4, 1:4))) expect_equal(vertex_attr(g), list(name = letters[1:4], color = rainbow(4))) expect_equal(edge_attr(g), list(weight = 1:3, label = LETTERS[1:3])) }) test_that("we can query single attributes with the generic functions", { g <- graph(c(1,2, 1,3, 2,4)) g$name <- "toy" g$layout <- cbind(1:4, 1:4) V(g)$name <- letters[1:4] V(g)$color <- rainbow(4) E(g)$weight <- 1:3 E(g)$label <- LETTERS[1:3] expect_equal(graph_attr(g, "name"), "toy") expect_equal(graph_attr(g, "layout"), cbind(1:4, 1:4)) expect_equal(vertex_attr(g, "name"), letters[1:4]) expect_equal(vertex_attr(g, "color"), rainbow(4)) expect_equal(edge_attr(g, "weight"), 1:3) expect_equal(edge_attr(g, "label"), LETTERS[1:3]) }) test_that("we can query a subset of vertices", { g <- graph(c(1,2, 1,3, 2,4)) V(g)$name <- letters[1:4] V(g)$color <- as.list(rainbow(4)) E(g)$weight <- 1:3 E(g)$label <- as.list(LETTERS[1:3]) expect_equal(vertex_attr(g, "name", c(1,3)), letters[c(1,3)]) expect_equal(vertex_attr(g, "color", c("a", "c")), as.list(rainbow(4))[c(1,3)]) expect_equal(edge_attr(g, "weight", 2:3), 2:3) expect_equal(edge_attr(g, "label", 2:3), as.list(LETTERS[1:3])[2:3]) }) test_that("we can set all attributes at once", { g <- graph(c(1,2, 1,3, 2,4)) g$name <- "toy" g$layout <- cbind(1:4, 1:4) V(g)$name <- letters[1:4] V(g)$color <- as.list(rainbow(4)) E(g)$weight <- 1:3 E(g)$label <- as.list(LETTERS[1:3]) g2 <- graph(c(2,1, 3,1, 4,1)) graph_attr(g2) <- graph_attr(g) expect_equal(graph_attr(g2), graph_attr(g)) vertex_attr(g2) <- vertex_attr(g) expect_equal(vertex_attr(g2), vertex_attr(g)) edge_attr(g2) <- edge_attr(g) expect_equal(edge_attr(g2), edge_attr(g)) }) test_that("we can set all attributes some vertices/edges", { g <- graph(c(1,2, 1,3, 2,4)) V(g)$name <- letters[1:4] V(g)$color <- as.list(rainbow(4)) E(g)$weight <- 1:3 E(g)$label <- as.list(LETTERS[1:3]) g2 <- graph(c(2,1, 3,1, 4,1, 2,5, 3,6)) vertex_attr(g2, index = c(1, 2, 4, 5)) <- vertex_attr(g) expect_equal(vertex_attr(g2), list(name = c("a", "b", NA_character_, "c", "d", NA_character_),color = list(rainbow(4)[1], rainbow(4)[2], NULL, rainbow(4)[3], rainbow(4)[4], NULL))) edge_attr(g2, index = c(1, 3, 5)) <- edge_attr(g) expect_equal(edge_attr(g2), list(weight = c(1L, NA_integer_, 2L, NA_integer_, 3L), label = list("A", NULL, "B", NULL, "C"))) }) test_that("cannot use vs/es from another graph", { g <- graph.ring(10) g2 <- g + 1 v <- V(g)[1:4] expect_error(g2 - v, "Cannot use a vertex sequence from another graph") e <- E(g)[1:2] expect_error(g2 - e, "Cannot use an edge sequence from another graph") }) igraph/tests/testthat/test_articulation.points.R0000644000175100001440000000053713177712334021754 0ustar hornikusers context("articulation_points") test_that("articulation_points works", { library(igraph) g <- make_full_graph(5) + make_full_graph(5) clu <- components(g)$membership g <- add_edges(g, c(match(1,clu), match(2,clu)) ) ap <- as.vector(articulation_points(g)) deg <- degree(g) expect_that(sort(which(deg==max(deg))), equals(sort(ap))) }) igraph/tests/testthat/power.gml.gz0000644000175100001440000013143613177712334017040 0ustar hornikusers‹l÷Dpower.gml¥ýË®6M²œ‰Íy…¾‚îž'Í¥‘fDsƒÝÔ¶HèöµÄúÀbZÔcö'7@€øjÙÎ?ßÈ8X¸{Äóù×ùÿå?ÿëßþ—ÿëø×ÿçßþoÿòÿýý‡ÿãoÿùÿøÛÿýû¯û?ÿ×ÿô·^[ýêßÿW«ŸŸóùwÿé_ÿÃÿûûwÿ÷·¿ýÇÿý_ÿåý/ÿòÿöóûÿã?ÿÇùýÿþÿÿûßþö¿ÿýû÷ÿä_ð¿üï ÿûÀÿ~Àÿ~Âÿ~Áÿ~ÃÿþÐïÂL¿xÑO^ô›ýèE¿zÑÏ^ô»ýðE¿¼è—~kúåE¿¼è—ýò¢_^ôË‹~yÑ/oúåM¿¼±›Ó/oúåM¿¼é—7ýò¦_Þôˇ~ùÐ/úåƒ#œ~ùÐ/úåC¿|è—ýòƒ~ùA¿ü _~Ð/?pr£_~Ð/?è—ôËúå'ýò“~ùI¿ü¤_~Ò/?q^§_~Ò/?é—ŸôË/úåýò‹~ùE¿ü¢_~Ñ/¿pI£_~Ñ/¿è—ßôËoúå7ýò›~ùM¿ü¦_~Ó/¿q5§_~Ó/è—?ôËúåýò‡~ùC¿ü¡_þÐ/ÐȰ“A+óƒ^æÍ̺™´3?èg~ÐÐü £ùAKóƒm`ì¶:vtléØÓ±©cWǶ}ÝBc·ÐÙ-´v ½ÝBs·ÐÝ-´w ýÝBƒ·Ðá-´x =ÞB“·Ðå-´y }ÞB£·Ðé-´z ½ÞB³·Ðí-´{ ýÞB÷Ðñ-´| =ßBÓ·Ðõ-´} }ßBã·Ðù-´~ ½ßBó·Ðý-´ ýßB¸Ð.´€ =àB¸Ð.´ }àB#¸Ð .´‚ ½àB3¸Ð .´ƒ ýàBC¸Ð.´„ =áBS¸Ð.´… }áBc¸Ð.´† ½áBs¸Ð.´‡ ýáBƒ¸Ð!.´ˆ =âB“¸Ð%.´‰ }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±8þÇ@Ä6à 9 Èa@Žr }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸXè }b¡O,ô‰…>±Ð'úÄBŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±9cÌ)cΛ¤1¶§9ỏcÎsê}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'6úÄFŸØè}b£Olô‰>±Ñ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>q¸Æ‹ ¹ÊË M!¶Wr©!×r±!úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8è}â Oô‰ƒ>qÐ'úÄAŸ8èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰ŸJác)|.…¦ðÉs4Û€§ðé>ž‚>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñ@Ÿx O<Ð'èô‰úÄ}â>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'ž|Ž™2óIf>ÊÌg™ù0³9ÍŒmÀç™ù@3úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žèOô‰'úÄ}â‰>ñDŸx¢O<Ñ'žè/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸxñÍ7|õ ß}×ßðí7|ý ßc.ÀÁ6à+pÐ'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â…>ñBŸx¡O¼Ð'^è/ô‰úÄ }â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O¼Ñ'Þèoô‰7úÄ›ïJäËù¶D¾.‘ïKä ùÆD¾2ÑÜ™ˆm€>ñFŸx£O¼Ñ'Þèoô‰7úÄ}â>ñFŸx£O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>èô‰úÄ}âƒ>ñAŸø O|Ð'>|»6_¯Í÷kóÛ|Ã6_±Íwló%Û|˶¹fÛܳÍm››¶ÍUÛæ®msÙ¶¹mÛ\·mîÛ6nóÛ?|åöß¹ý×nÿð­Û?|íöß»ýÃoÿðÍÛ?|õöß½ý×oÿðíÛ?|ýöß¿ýÃpÿð Ü?|÷ßÁý×pÿð-Ü?| ÷ßÃýÃqÿðMÜ?|÷ßÅý×qÿðmÜ?|÷ßÇýÃrÿðÜ?|%÷ßÉý×rÿð­Ü?|-÷ßËýÃsÿðÍÜ?|5÷ßÍý×sÿðíÜ?|=÷ßÏýÃtÿð Ý?|E÷ßÑý×tÿð-Ý?|M÷ßÓýÃuÿðMÝ?|U÷ßÕý×uÿðmÝ?|]÷ß×ýÃvÿðÝ?|e÷ßÙý×vÿð­Ý?|m÷ßÛýÃwÿðÍÝ?|u÷ßÝý×wÿðíÝ?|}÷ßßýÃxÿð Þ?|…÷ßáý×xÿð-Þ?|÷ßãýÃyÿðMÞ?|•÷{Q}1Ôƒ}1Ü~1äƒ~1ìqô‡áÖ0C€1À1C1ö¢cH0cX0ch0cx0cˆ0 c˜0 c¨0 c¸0 cÈ0 cØ0cè0cø0c1c1c(1c81cH1cX1ch1cx1cˆ1c˜1c¨1c¸1cÈ1cØ1cè1cø1 c2!c2"c(2#c82$cH2%cX2&ch2'cx2(cˆ2)c˜2*c¨2+Ã\™Å`™Åd™Åh™Ål™Åp™Åt™Åx™Å|™Å€™Å„™Åˆ™ÅŒ™Å™Å”™Å˜™Åœ™Å ™Å¤™Å¨™Å¬™Å°™Å´™Å¸™Å¼™ÅÀ™ÅÄ™ÅÈ™ÅÌ™ÅЙÅÔ™ÅØ™ÅÜ™Åà™Åä™Åè™Åì™Åð™Åô™Åø™Åü™ÅšÅšÅšÅ šÅšÅšÅšÅšÅ šÅ$šÅ(šÅ,šÅ0šÅ4šÅ8šÅ<šÅ@šÅDšÅHšÅLšÅPšÅTšÅXšÅ\šÅ`šÅdšÅhšÅlšÅpšÅtšÅxšÅ|šÅ€šÅ„šÅˆšÅŒšÅšÅ”šÅ˜šÅœšÅ šÅ¤šÅ¨šÅ¬šÅ°šÅ´šÅ¸šÅ¼šÅÀšÅÄšÅÈšÅÌšÅКÅÔšÅØšÅÜšÅàšÅäšÅèšÅìšÅðšÅôšÅøšÅüšÅ›Å›Å›Å ›Å›Å›Å›Å›Å ›Å$›Å(›Å,›Å0›Å4›Å8›Å<›Å@›ÅD›ÅH›ÅL›ÅP›ÅT›ÅX›Å\›Å`›Åd›Åh›Ål›Åp›Åt›Åx›Å|›Å€›Å„›Åˆ›ÅŒ›Å›Å”›Å˜›Åœ›Å ›Å¤›Å¨›Å¬›Å°›Å´›Å¸›Å¼›ÅÀ›ÅÄ›ÅÈ›ÅÌ›ÅЛÅÔ›ÅØ›ÅÜ›Åà›Åä›Åè›Åì›Åð›Åô›Åø›Åü›ÅœÅœÅœÅ œÅœÅœÅœÅœÅ œÅ$œÅ(œÅ,œÅ0œÅ4œÅ8œÅ<œÅ@œÅDœÅHœÅLœÅPœÅTœÅXœÅ\œÅ`œÅdœÅhœÅlœÅpœÅtœÅxœÅ|œÅ€œÅ„œÅˆœÅŒœÅœÅ”œÅ˜œÅœœÅ œÅ¤œÅ¨œÅ¬œÅ°œÅ´œÅ¸œÅ¼œÅÀœÅÄœÅÈœÅÌœÅМÅÔœÅØœÅÜœÅàœÅäœÅèœÅìœÅðœÅôœÅøœÅüœÅÅÅÅ ÅÅÅÅÅ Å$Å(Å,Å0Å4Å8Å<Å@ÅDÅHÅLÅPÅTÅXÅ\Å`ÅdÅhÅlÅpÅtÅxÅ|ŀńňŌÅŔŘŜŠŤŨŬŰŴŸżÅÀÅÄÅÈÅÌÅÐÅÔÅØÅÜÅàÅäÅèÅìÅðÅôÅøÅüŞŞŞŠžÅžÅžÅžÅžÅ žÅ$žÅ(žÅ,žÅ0žÅ4žÅ8žÅ<žÅ@žÅDžÅHžÅLžÅPžÅTžÅXžÅ\žÅ`žÅdžÅhžÅlžÅpžÅtžÅxžÅ|žÅ€žÅ„žÅˆžÅŒžÅžÅ”žÅ˜žÅœžÅ žÅ¤žÅ¨žÅ¬žÅ°žÅ´žÅ¸žÅ¼žÅÀžÅÄžÅÈžÅÌžÅОÅÔžÅØžÅÜžÅàžÅäžÅèžÅìžÅðžÅôžÅøžÅüžÅŸÅŸÅŸÅ ŸÅŸÅŸÅŸÅŸÅ ŸÅ$ŸÅ(ŸÅ,ŸÅ0ŸÅ4ŸÅ8ŸÅ<ŸÅ@ŸÅDŸÅHŸÅLŸÅPŸÅTŸÅXŸÅ\ŸÅ`ŸÅdŸÅhŸÅlŸÅpŸÅtŸÅxŸÅ|ŸÅ€ŸÅ„ŸÅˆŸÅŒŸÅŸÅ”ŸÅ˜ŸÅœŸÅ ŸÅ¤ŸÅ¨ŸÅ¬ŸÅ°ŸÅ´ŸÅ¸ŸÅ¼ŸÅÀŸÅÄŸÅÈŸÅÌŸÅПÅÔŸÅØŸÅÜŸÅàŸÅäŸÅèŸÅìŸÅðŸÅôŸÅøŸÅüŸÅ Å Å Å  Å Å Å Å Å  Å$ Å( Å, Å0 Å4 Å8 Å< Å@ ÅD ÅH ÅL ÅP ÅT ÅX Å\ Å` Åd Åh Ål Åp Åt Åx Å| Å€ Å„ Åˆ ÅŒ Å Å” Å˜ Åœ Å  Å¤ Å¨ Å¬ Å° Å´ Å¸ Å¼ ÅÀ ÅÄ ÅÈ ÅÌ ÅРÅÔ ÅØ ÅÜ Åà Åä Åè Åì Åð Åô Åø Åü Å¡Å¡Å¡Å ¡Å¡Å¡Å¡Å¡Å ¡Å$¡Å(¡Å,¡Å0¡Å4¡Å8¡Å<¡Å@¡ÅD¡ÅH¡ÅL¡ÅP¡ÅT¡ÅX¡Å\¡Å`¡Åd¡Åh¡Ål¡Åp¡Åt¡Åx¡Å|¡Å€¡Å„¡Åˆ¡ÅŒ¡Å¡Å”¡Å˜¡Åœ¡Å ¡Å¤¡Å¨¡Å¬¡Å°¡Å´¡Å¸¡Å¼¡ÅÀ¡ÅÄ¡ÅÈ¡ÅÌ¡ÅСÅÔ¡ÅØ¡ÅÜ¡Åà¡Åä¡Åè¡Åì¡Åð¡Åô¡Åø¡Åü¡Å¢Å¢Å¢Å ¢Å¢Å¢Å¢Å¢Å ¢Å$¢Å(¢Å,¢Å0¢Å4¢Å8¢Å<¢Å@¢ÅD¢ÅH¢ÅL¢ÅP¢ÅT¢ÅX¢Å\¢Å`¢Åd¢Åh¢Ål¢Åp¢Åt¢Åx¢Å|¢Å€¢Å„¢Åˆ¢ÅŒ¢Å¢Å”¢Å˜¢Åœ¢Å ¢Å¤¢Å¨¢Å¬¢Å°¢Å´¢Å¸¢Å¼¢ÅÀ¢ÅÄ¢ÅÈ¢ÅÌ¢ÅТÅÔ¢ÅØ¢ÅÜ¢Åà¢Åä¢Åè¢Åì¢Åð¢Åô¢Åø¢Åü¢Å£Å£Å£Å £Å£Å£Å£Å£Å £Å$£Å(£Å,£Å0£Å4£Å8£Å<£Å@£ÅD£ÅH£ÅL£ÅP£ÅT£ÅX£Å\£Å`£Åd£Åh£Ål£Åp£Åt£Åx£Å|£Å€£Å„£Åˆ£ÅŒ£Å£Å”£Å˜£Åœ£Å £Å¤£Å¨£Å¬£Å°£Å´£Å¸£Å¼£ÅÀ£ÅÄ£ÅÈ£ÅÌ£ÅУÅÔ£ÅØ£ÅÜ£Åà£Åä£Åè£Åì£Åð£Åô£Åø£Åü£Å¤Å¤Å¤Å ¤Å¤Å¤Å¤Å¤Å ¤Å$¤Å(¤Å,¤Å0¤Å4¤Å8¤Å<¤Å@¤ÅD¤ÅH¤ÅL¤ÅP¤ÅT¤ÅX¤Å\¤Å`¤Åd¤Åh¤Ål¤Åp¤Åt¤Åx¤Å|¤Å€¤Å„¤Åˆ¤ÅŒ¤Å¤Å”¤Å˜¤Åœ¤Å ¤Å¤¤Å¨¤Å¬¤Å°¤Å´¤Å¸¤Å¼¤ÅÀ¤ÅĤÅȤÅ̤ÅФÅÔ¤ÅØ¤ÅܤÅà¤Åä¤Åè¤Åì¤Åð¤Åô¤Åø¤Åü¤Å¥Å¥Å¥Å ¥Å¥Å¥Å¥Å¥Å ¥Å$¥Å(¥Å,¥Å0¥Å4¥Å8¥Å<¥Å@¥ÅD¥ÅH¥ÅL¥ÅP¥ÅT¥ÅX¥Å\¥Å`¥Åd¥Åh¥Ål¥Åp¥Åt¥Åx¥Å|¥Å€¥Å„¥Åˆ¥ÅŒ¥Å¥Å”¥Å˜¥Åœ¥Å ¥Å¤¥Å¨¥Å¬¥Å°¥Å´¥Å¸¥Å¼¥ÅÀ¥ÅÄ¥ÅÈ¥ÅÌ¥ÅÐ¥ÅÔ¥ÅØ¥ÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥bîR1w©˜»TÌ]*æ.s—йKÅÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥fîR3w©™»ÔÌ]jæ.5s—š¹KÍÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]æ. s—†¹KÃÜ¥aîÒ0wi˜»4Ì]šp—þå?þ§üéÿóŸÿë¿þ¯ÿò·û¿ýã¿ü‡ýOÿò_þvþUáe„Ïÿ(¼ð¿àÿ®|œ²ÿGåñ—•ÿ}´ÿS鼤í¤Ç_—ž/é8éõ×¥¯F]®UëÕªË5k=ùúÕXíZ _Õö©¯Æj÷aûÕXízjß]úüeéÛ›ýwéßÄýSé_×·t\c‰Ô5–HÝ ïî⦊ÿ¶UûïÒr-p¼†a¹Ÿu¼¾V¹Ÿõ–ÚOp¼>ìáÌùjà ˜óÕVùê-í^õ|OÁnh‰Ô5«H]³žïAð×¥§ëX"u_àz}Ó-."uŸàzõÁË-×kʲ})Çþª× ¼\[]¯¶ºÜSïW\î]ïW¼]¼ß˦ëƒ÷kξìSÏ¿Ü÷{hÿeåázë[z»~u?Yú¼¾Àí>Öóš/.׬ÏÛ¸f}KË5ë[:ý7\DjŸúYîÃ>ïUó¯K­¿}ÞË‹ýZï>h[àÝ mwygû³Þý՚ן·yö>û­µNûçÕeí÷wÉ_[äþŽù«Ï}}^;Äÿ'ùGóº®ðwZÉ?žk ÷Ï_Ÿ’×{#cç9ÑÞ^ûú‡íë5ÙÛÕnÉ&Éï’dïã·)²ûùñÍöÞÿ,ß÷ñûCûß÷ÖÚç¾÷V¶_ŠÔŽz}»eõßÁ/ÿt¶Ã¿µvNí?ˆEE\þÉÒƒþºÖOkïíëã?Ç{«ë·ð"¶+ì&vkÁ&¶¿¯ÿúN^´åµï}œýuo­]¿Wøvï¿Ýõ­÷&=¼ï{4ÛÑñÖ.¿~©Øþºy} ?FG6à>dõ—íÆ"þòÊÿÀýsñ«WØ£h—5këd ~Ïš6ðw$Ò_n‹·¿µnÞ“Ûÿ"ïåÑF†Ö|¾µÞÙÌýá×ɪëÛXľ }Xv/ù¥ºm:¤oúp}xcYLýƒe1µ_OÄ6¶÷w¾Õ?¢%vè‰ÖNCoí?[ÿ\üŽû¿G“ïÈÇùå-þzLV´Ÿœ^ùþòäçÓÏàÆôŽå|õ7?BÞÚåûÐùîC6îùwþØ_~òùáç½# v~{kmLy½ã”—}‡·vÙPé&¶úzoæý[¼ž7ßÚåwÝ×{Þ´Ÿî­µ±µu}™6EìÇÒõŽkø7þëa3ÑþƒáúÏů.ï—›KvX¾S¼‡‡íòoí²ÿ¿SìþêÇ{O„?¾k¾Åa4=Äïhz¿G“ýÔoíò‘û¥µüÖÞžû0ð_û裊íä}¿z§Ý@ú"ö[‹û½Nû‰SÄÞE¾Ó §P·¬éþ÷IWöï®lGŸh½=•$†"Ï—n/bïž÷nÏïDDlÓêç<þïìà[ìçûwžÄÇ%ÿãW3ÛZ€õNÁøiù9¿*{Lž׽ãGÞPµÄ|Ó½ÅmCB-Á&ß‘Dì;’D¦Â“ßb?Eüé5ü€±°oqÛÚÓMüåÉ6öÖKL ïHïëO-¿Ï#”M/¨ØXÛ$‡ˆÃ€U±=¿,bÜo /Úý ˆÛÆ"{}0Tý>Ñ6þÖ¹´Ib· svɆ×vÑ·8½³ŒÛÎõaS£b›~qÛ8R—t$/–MºoçwG²õx-a@»©i‰ìÙú6· gu¿gQGqÛz±–œÝþobß²kóO÷åŸ,]Ôög{K,Ç@Û‘ä¶[âÒý¥‹ŠØ†}EÜ6`®b…\\ÄïSû~2Ÿ/» =½òáÉmÑ´œñEóö£ˆØ[ˆäà{tÛ˜L Øâ¶Uý>g’ž||yò{ Ú<”ˆÛÆÌ[‚Õ6&³‰mç‹Û;s¹·$¼³ÔÆû×x‹mªßööãˆØ/m*¶ýYÄÞªâd|;YßGH û·ŸŸ%Ýàç 9œÞYn6ú"ïüÅÆ‹Ø†³Zνسˆý>ž>÷ù!À®b+±ßK¦Æ;™·¸íe?­i/boãEìm¼Š?¼F{{yJ|ÿƇÜDŸÇÿ¼ØžHl9Üžü!²Ý’kóãûz¥ÔŸe+íû³dñ>ˆÛ öõóá^_6é"¶78õ%Ö~îK†•ýÜ—,@þ>¹/kŠœ™ñ±‚÷ÅOíûÆõ!E¢b¿{‹Û&m7±oºw¯ó;úûËAR«¾éÞâö#Eò°Aüî6Úï4¥î{åöÆwF³íU1ý>KÑ~#ýÎ;¶Í;öûÄCû9ô}0!=ù5ïû7~›)›îëwŠ2‰ß­ìŸwÖ1‰Ÿ¿.žwº/‰åû¹Ùh´ÀÞ^\ù.š›˜wêllêl$ÁÞù}Y”M5Ì;g5ö(áüÈG±­ñNC…Ö±]äçñ{ͼ3I,šmGZÒ¶ëK-i ·Rmbç5Tlcü#‘xÿ¹%^î»hÉG±_Ä6?‰·®ˆSkˆØîwG²e³óÛûs$okdDú³ˆm•ô´ŒnÛ*¶]TŠ}­å™wö ‰eʵ]TÄ6à4ýe~îóËk¼Å6Ä2/¿};Ë5¾#=_Þù-¶÷›©ØFâçQ±—ÜdË‹D<þ:ëw<ù![¶‰m;?2Rl¯{‡“Çæv7±mgû¬€|;«ØŽÁçKGz‡ª}xê9¿4Æ[ì#{‚Sýè-Íü^¬B׸¿¼Æ;MêãooñØÐåñ¾¾æøq=ôx_sبÂ&vÒñ>©pØ®CiAü¾z×›z½m:»ic»¾±‰Ý*qÈáåzJÛtïxòaSÇûž‰ÃF#wˆ8‰ß7‘Ú½ÿñ®¿><ŒëÈ=ì>ìx‡[ÏîR±²\Ã`Ç`Ë´M§bÛtïØìaC—Ç»þ:ŒÁwPô°{Çãçmœÿ¬/Ãêø=mà÷”X®ÿoñi’§~í:x¾+xýj%âÓÆÌO‰Û)Wħ=tJà×N¹">m¥ÀùŽåž6ù¾Ã³§µ=›Ø~Á–v¶M'bk¨Î–Îoû†ˆÃ±E%<ë»è[¦¯w,÷´„óq=íF씸¨Ÿrß¡ÎÓ^î{¾’§ †¨ØîÚ6±Vï°áik—N‰ªYãz¾£j§Ý.©Ø†ÁUlK/7±·9±I.Û¨Ú)±/{2RÅ~z‹ƒGR±oçwG²QbÛÄœŠm°ZÅ6è´‰}ӽͶÿ(çÏñ{Mñí,b{Úþ”p–-tñi‹ ÏS̶ÿo±½òTä¥í¢§ø:Û‘D쬈ýÒ&b¡:%èä}Ý[|Úºãóí9-*á¼¾ÌÏoñi+Ïw´ç´èÏw´'‰¿Øû1x}ù(oñé÷ƒ·„Yì;¿Åa±ïu·ô ;ˆØÏ"¶åuç;—ÄýE||ù²Û¹NÄ~¤bÿ¹ß+¬·j"¯!b»Þ_lüýeF± ”Ä7lkˆØæ€Tl¯*8™mGzd9¶íü|éÏïPçé÷°ïPçé·Òìýk¼ÅÞ#½C§-z<ßÑËÓ^‰wý|Øâ]´Ó—ˆý2¡b;E|ÙªÎMìŸ,¹ ÷Q.‰¸Ú¦Š-£ãúù`¿Þ7ˆ_6[zý|°j*Eæ:ßtχw~Çr/kã¯wxö´™t_¶¨æ’X®ÿ"¶¾NÄ—Ÿ¯wà÷²ßëø½là÷Zœ¹Š- FÄ—_øµ“¹ˆO›¦ñeCp›Øö:‰?Ûš_~ʱl_ï’æËF{. V‡v~¯ƒ¡éÄ1Úþ¬bßÎb/¿¼³õ¢*é%¾ìM›Ø·†¸ÿeûïßù-Ÿû-¶iø—­3¿Þµñ©eúò­ñ{ô.¤¿lTíêªK²Ö‹ø²)’ëõ¸ìaÛÉ%Y?ɼŗŸ Tì›NbŒþ£Èçöïü^­|Gz§H.?}½‹Ò/q½Þ)’ËÖPmbûßù”$~»•¾ÞYËæ€®wÍvhºwŠ$,ô›Ø”ûº¿mÍö&öŸûþòŸ÷“í|KûyCÄ·‹Þ·;ú[bæA,¾Î¿†ˆý|‹mޤoø×±íÏ"ïüšŸo›¸—ÌÏþ5î÷“íTð®¿m‰Ñ-ÑxëÌE|ÛÐý]2™Û¦{Gão›ŠR±Í.Ýõ¥?‹ØÖöÜ5_ž<_žüîH6–{ëÕ%¾5ÞÉ¥ßïðìm¯¹õÎûoñm#®÷;ˆzÛrwÛˆëÝç—'¿Å6ˆz¿o#¹mdû~י߶Îü~ÇEo߸ß7{Ü6Ôy´³ýïPgèHïPçí§Ü÷½·=“~¿ã¢·ÝðÞï°ámãÏ›Ø~ÛìÒ}|é¢"¶ñMl?÷»À;ŒA{÷%bo¶ßw,Ü6ˆz_¦¯w\4¼Æ;Ôzˆý;«Ø6ÝûrƒÛ;s‡(S®r}yþŸ‡wžƒØ·³ôgÿdéÏvtŸ²LøÖxÏu~ ¾k¶“øù ¾¾tþw°:Ì¢W}™E¯/³è;J|ÛÜñ}ÉÚíßYV+ÿäûËk¼¿ ßß_¾à-ó†)"öïü.–¾m¼î¾ûËk¼Å~Ÿ"bfyG‰SÓ½Å>œu˼á¿à[lCʛط†¸/ÿ×ñýEü¥??2ÉØv~¾¬ƒ"¶µ—÷#Ó—íü"ö!‹G:¿)"öcðùÒŸEls*öªç‹½±MSª8¼ó—]›ˆmœû'¿‡•°"O~A¿Ax‡î};??ÖÛµ[Å6fþHRÀ6ÝóS_^ãÃj¥b{"ãù‘Í£ëü*¶âù™/Oþ0ŸŸó‹X– ß‘î/âçƒxý|xg‰™ÛXÁ³dd;ÿ;–ûØÂãMìfÑMl;ÿ;Jœ^CĶשطƇ­ÇS_¾ „”­ |ÞAÔÇ$7±m:Û/ø.µM¯!bÿEl¿ ~­½ÜÄÎɨØV,ˆø±‡†6±ÿ(ï^gì›ØÿÀ·ØÏüoñ§w~l”øy×?ÿ}³ü—Å_žüØ)·Å?Ûø‡Öø’xÞÜÆÇÖ??ïÐ}¿{ Y<ïhüc£ñÏû"—Ç^Šò¼C÷ Ý?ïÐýcCpÏ;tÿØØ×óÝ?¶üìy‡î¿h¾«”»|Þ…ÇIüngo!DlýóóŽó?Þ^¾£ñ¡#ÒEý;¿ÛÙÖ}=‡´³ç·Ø†,žs}xçSú³Kö¯ñî϶áy‡g[Äû¼#®-â}Þ×0ɨؾÆ;<ºè%ýÙÎ"¶EbÏ%ßþ@ûv±_»ßåÁa ¾#®©5äì¿Ó¾®-Ü{ÞaÑÇÆœž[šÙÎå*¶Í|Ë„äßùÝÌöZˆç5 Cð5|l]Û#QCÿàçÃßqÀÇVö<ïÐÞc1>|ÛDl«rUlãSÏ#s¨ít"ö÷ùb DìCN‚úòóÑ;L¶|}¤‡Ú%SÄöôàóÀ¥ò˜rýüÈÄï>á¯úÝ£í]¿êW—þómäï®gæ¯úø7¨ífEÕ~ˆ‘‹u3䦶9©MmWŒMmï½SõŸŸmä×7ùýMþ|’/Ùù_*j›ÝØÔöž _µ¸!ßEm‹¨UýçÍŒ¼>½¸¬ áÅ[^ʼn%F <üÃB¢êÜUÄÍ…VS^E†~ø>2àlDô÷Ï2àlLô÷Ï2‚lUîú)q'þ]Tíg-QÛ@’ª¿§_²Tn¯øýs}k–ûïMm3G¿êùôìùôl1AA-ËŠŸ>Em#»ªþc1>ÈCG¹IÿþYÆ­0þýóÛiW¡êÐæââ‹ëòé.vûáù¯Ðâ-Ñ·‰¨Ãª¢obë£å2¯„6ÑÕ3<\& þý³,ˆöʸß?ËØÿ¤¶›Ú—ûU‹»µa¤ß?ZâDmƒ¿ê÷.(L,ýÍ€¶Œ ôžOòùù&—Î,ÎÈ^È7ãHW “œ„òƒMq[Áø©<ýPÝjùùBåé—ªá í¨kKø©"†¦.ü(µmj!øUߟÞä­sÑ|ïoj[ï¥ê8¨Ü†ÀWÁO[JQÛPõ®öm(jvRuìä*|“ûO´ÉûKÍO¢‡,èa}_ø<Ñ[œ\Ρ^!4b}{ñ÷ì6Ï’ Á Q‡Ä!ómx¶ìA¾<;í´%{öN‡Nü¡ÁE-Iކ œ¨CPîP“¦ ™ÊÃK”ZQ&Ð4U¨<ô[•‡©Bä6õ¿~N™+lÂè÷ÏõM.ã"lsNi÷°ß¾d S×%öÏ&7ÿ,=ì¢6¹ïb—|¦j¿åé¶¶ë÷Ï×7¹´{°º›Ü¦çç›\{¤w•‡wßä¾ÝUnÓq¿–á–G6Á×=Ç7¹v‚Ð2"Y«G;ôw¿ù^ï Úï¿m»¯wNì÷ßvh/Éè„õzIFgùµfiFÇ÷™%É‹å×à%Áñe«–ÿüj÷¶÷U¨:=•/3^b^¶÷÷Ïï{{¹Ä¦ökðz‡Çž,üUKðÛé%1É$—@Óò&yµvÞðtí¼þ§ªÜ–Fþþùþ&>É%´¼ß\£³€›<¼Œ|¦0iŒ´Œ÷a»Ü&Ù?.ùZ‡,4~±Äç/[Ìôûgõ2v)Pùò±uªËó_U íò1„uJ'ó†Êm•ÐïŸuÅösû).ÏÛ•§>£r_R±ÉÃZpÊÄá£e›Ü–ýþùþ$—Áò¸]î[Få~ß±.é‘¶–ê÷ÏÇ7¹ôŸÑTùòQ°u©) O}¦òÛQÿù¹Ìa¾å+…éý]¿9~_°Þœ¿ïæÛåVá[ýV_åFåáÝe?¶ìÁ‘_¹lü¶Yå+Lyºcò5*_a†|dËv²ÁZ¡·?:ôüWÕ Ö7ùò¡óMî·oõ#À5ú•¿¾j¥»7?…ír;°K6{å7{õ>§›åºŽÙ±§òò³LéÞЦZ:‡ù¯$[Éò[É’Zµò)Ë’‹ }ô¡ÞûÔñ»7QÿþÛw-ù =¦>E ª>YÈÒm­¯o©êo/#ÖÝ/’›ÜOî»<¼û{‚,‹®Ò­jx‘ûU²Þ»ò;ô^9ëÃ&õ.¸ñW“ªÚß–ü«–QꃻÜϽ*÷Õbdl…ý&/Ÿs+‰U”O-—ʇJ¢ å'»Ü7äèÜä2iøaih#4¤Æ*|Îh“û’‹ÒbŸŒPùòiš’úàÙTž¾êHŸñ1ÈzÇY&L£[ß!ª~ìjdü,£r¿©-‰ù”lìr?Hˆ¨|ªÞéÚ4CJþµì}0«Nݾû¯¤rŸWyùà@I†4-‘Pªô2-ó)ø«òòu½»<üT‘ûNUô}Fäå« J‚2ž.¹ã ¾ýšorùªa¨ªÜ—É”†|Âà»´Ïø)òòuo%1Ÿ(—¯V&‰ù¤íÕ-Àjýý³¬ª¡ÝE^ÁŠß+ö-#AŸJ/#ò°ëØä¾Ý%¤T>4W#*{¯\§Tß#UVIÂWØ×jÞ^<ù+ X‚8i‰Wyè2’ƒ_>“¢òòÁ³–ˆRo©¼|uBkŒÈ—@ª¼ýœ×r7þTé2¾ r“û°¢ÊÛ§1[§ú)RåaÑÞäéÝOywÛß[£g>ŽÓ?šm¶ʃQy{³Ôr79U^~YÝåa4é:éåWìðt=_ëƒý>_ûçÿÜȵ.ϦMîûûú´sVyù½í&÷‰õÖ#¹ÞŸôûíŸÿs#×Á>Ó§²¦–bŸöíÖ¨¨ß6µDEÓ˨܇OZœ:"½ƒPyù³–›ÜoWUÞéé—ÈÃÓïor¡…¯ªÂËå˜cšßUîó¨¼}„£õX¤wKÝšðËAë^FãôáéZXúééåÏô¨¼ÃàÓú6yJK¸}¸µÍçTžf ûª–MÖ&‘wMbŽrM~û¯:ŸÂ‹*o¿‡k­ž ÃCäíƒÀ›<˜Z 1ûdÊS×R¾0ø4Æö£ûþÐ2²j‡,u…aGÙzÒÌü´œï ÁŸ>´û‰ãP§~ªöw?®Ûz~/˜+‘§å@åÁGÞ2-ù¬à&A Íc„0šÈÛ§=Z*iË×ÛµdIBº¿õܤ¿M¨µN75¤¬|!†-ç&;Ä–¶ ÿLîü¤§r_§ÛZˆðt‘‡v´!ÃO¹OÙ´U Ï*ï°£”4IûTÙHÞ#t‚Mîg‚Mî÷ó£þ=<]¼˜wØ*Ÿ„áúøj˜Ñ”¯sÛäÞí(õËê&÷74©¼“\>ßÝçGã-A.CÕ6Øä~ŠTùø„Ðhõµßò©¼|m4Kâ缑,I()M{ø4µÊC…ôhÃWϨ¼CCê©b?½orÜßä~5Pyûr•Ï’ìòð2ߺ؛ϔ®°˜íÀuèb¼{èÀ*÷OßÊä}ˈ<ø“Ñ„_VUÞ>V¤òñQ…MÆj}²À*ŸÐßÙ©oê”±-Ùӻȃ-Íeùx¡ÊC4r“ûÏhêËD¦t ú€ÊóÈ'x%É6M°3’> U¦›Üç²T_FÖš0öTîÏ?¨||Rpô@CªšœòÇgUêUÞ>’:zµC«"ù~•‡Z´ÑÄZ0šX Bc¤yF3e¾²^åã3e#‰µòG=FÏnø8í&˪ÈǧFóp>¢§ò s¤ž ñï]þéé!œ>šå Û&‘I^SꀻD§òñ7ŸŒ¤K;õwM…†ü”ÿTy¸h4] ¶Êý­*OÃC’±+Ìï‡&|'Øäáݵ&´Œžëï.›a|Pùë&¹Ûøôùöt™–RŸ‘U;Ds6yhH«þ’]ž®—ùU[ä¡&j¶k‡BCª£Iä>9¥òP7ªòäõÈZˆjÎ<øHÍ™ë¦9ó°ˆ|ÂL rŸ3ÍȧwêÎÆm½î)5¤ž /#ÓRpKr!S¨žQyÚ{ˆ|ÂFh“û™@"údì&^LO†Ð©ö'4¤^S^F§¥Ðîzyïbr÷Ô„ŸªwO}“wˆ\VðC[ä†RMŠœæÒ¿ow=¢éo¾9s9Áþè™K_´­òP•‡á!g.S\Whú:i•w؉|BþHNtN˜Rß':0‰½ !¢Zf÷°ÔhDhF½Q,L×Ûd~™Üä¾Çˆ|ÂÀ–¢Œ •‡¡'5ÉEª<µŒÊûëBöIž¶pz³vx‹<\ ±ÉC$UåþžÎÑ[èÂt­Õ-ÁÍlòO/jRG¯(÷5Ø*ïÕ+ñ<}`äÒºp°Ê'ô½ã.8‚Gcn~4é•x!¬+òpÇÎ|»AO團Þhžž. YÈÅêáko:­LÈö•¯û9´ÇOK*w ?º'³ÓÒ&÷g›)ž qÚCŠgB–OåËOKÇVkc;°ÊËÏ*%*—ÛÁñð™>Õ|¨»zh¡?¢òCÜäaÒÓkXýVEå±e4ßïW>•‡XëŠ|ÑÇ¡uEA®uE¡eTîCQ*q±c»BÖ&‘|úø£ÊþóPp³OÛzAmX䥤äv_JJRùᚇÖ*‡-òöa…C½‡,òÃÛ ò!‘CŸ>¶¯ò¦>4ߦT•‡uUËÂy¨…ð?U©DþÄÚ!YíÃNz‰lXÊ4 žž.«‡J% X²«Gp©’]r‡w—¯êS<‡dW+4¤f(ý‘†CRŽG0W’rtêE–þz£S™4~zÊÝ‘‡?qJ€ñôCû”`pK§†ÑünøT¾©·û§ˆû(?ýýñÔËñ¼e>u7ìËÙOÙ Ÿþäø)ÕE;eGy†U[6q§O5lrŸÂ?õ*2ŧÊOP?ån±Ó—³ŸŠ–õgxNÙQž~«²ÉC–=_ê3"?ýnø”=ßéÃhçÆ[õí.ò4a‹üôvÿT>«Ôª<7œŠöðip•'‡½•Sú†Ô[¨¼Ý?oý„½É}ˈü .U6 Gè3"?}Øø” ÆpÄMåg˜°e{{§§U€>M¢ò#8=‘Ÿa–²¾Ã"©ü ^ìÑå ¼ŒXˆ0aë^;ɵ×·»ì†Ï0¿«ÜoU®ŸOû¦Mî.—Öºùb•>–zýh(ÊÎÀ—lüÃÊwiy™wz—Ô\~Zº~>yàK/[ò1½K !(}iÝ’¿ÏëRh„Ÿ#/©[:ýbs-}ÛÀ v±¹¼à ï®úäg.-æñ‡C®RÛé?“È/_ûsi1Oèï²ñ¿BCêU8~~Wùé Ê¥q‚ôôOû¦K bB¡Ê¿¾$¬púŒÿµÄø [I aðµ.”¾e´Ž#LK­C;üT‰¥úÜÊÛÛÎK/| ³˜fø»>. Zœþ°ë./ó–_Iþîb—ßk_ómS¹7ä—T+œ¡KµÂ寨Øåáe4úãR£?þdÀ&󻢴¤•þ ˜Ê¯ôSõH‘—š“÷í.7Zœ¾¨ä’:ŽÓ{àM:°Þh–2\ù(Ä%wN\Á‹IÇåSkס3AxwYl|!Òuª1ôƒïÔÝAëe¾e´0#´Ì©1l?<ôþ_árIÔíý]ïÜk“éNŸÍºô ¾ßš«üòAºëRÇáß]ë8|æ’cïgzºìÊÂXÝä~Ósì¡‹é9ö°®JQI@R\RTNø«ü No“û>£dâ°ò][ò‹¼È/þ4é‹Â/©p¹|Ôí’ —#|&‘‡¤ã¥1a)ù†Ç&O×û}»¿#µá²ÔKB©—?¥pi-OØh(55ŒÈƒ“Pjˆ^^JõüKƒa‡(Gž“cùÜÏóÍ`«E©<ÔÜZ3è*<Ò[J ÇŸÛä¡‹)ÖÁÛ÷[ }Jþ–LC¸ÃùÖ3̾¦Då§‹©üòi[òáµ[‹/S'Ð#Ïá§J–ÄgU~øò™[k5}Fs“§§K‡gîí@ux™ß½Û¿µVÓïnoÉÁ„ ó­g˜}9Á&÷ÉÛ»Ô‡ŸªûÏðîZX^F/ˆ ?UäažÙXÙþeD~ùƒŽ÷V êß]k5}(õ–”MØlrì¼5æ¥-!äçÈí`oxw‰YøðÌ­9˜?qˆüöU¬wkÌ"¼Ì[~{Ë|Kæ ŽCä·ßšßzÕÛ}•‡xË- ¡p§í­Ÿˆ»%î´Pùác·¢µ}õÁ-žP9qK}ï™~ªlâ¾=ýž@«‡ƒ¹Òt“/ؽGS”ßä¾üý>¾yÉNÝ>¤wKºéÇÇÓUÐ|·f§|äUåWpK’Ì å3÷¡M?‹I2+Ê?EÝT*…nI•þ^“[¯ ÷Q·[r_áÞªûÔB ßî[Źÿªzw¶§ßЧÃC+Î}ÞîVšuˆÏˆüJí.aã0‹éýÓÁ¥êj_#{Ë‘çÓG;U~ùšðûÒ<†w•c(7Dß>(}Kf-Ê?Ý­ò´jKfíô•B·ä¾Ž`®4÷º˜ÈÃ}÷–* ?U×ÕПþ·¦Ê |ëæÙ¿»fÖBŸ‘dÖ<Á–ûòcUr_¡HDåw˜ôôçà°5Wâ’ÍJ‡dOï®^ì“ü )é©´ÒäWØÙè}¿aðé9_±rËÁ€ ÖMÏ„ …^ Âõz=p0W›ÜU‘ß>=ukz*5¤F;ýXݲYáÝUî;°Êý¹™MžÞ]&ìÔ Ô؆|$=uùB‹G¡ã~«¢òÇ÷÷gã‚ÛϤòÓé%wû™à‘ôÔå7q›ÜG!IOýøó*5TÏv:$|&é‘~g£òËg@ÉfMê3z¢ÈN*«ö³´¿ûv—|Óé—ág»À÷“¼}€ñ‘ôTù¤£Ê/e~$›*ýU~û$û#—}„ è&OŸIëC'ÈU˜ T†‡&¿Â”º4¬à'lÍ•y‡­òñe$¿Æ[7•ß¡ë5(>ϧòà vyxwY=ÂÚ¤—‡¡-òÛžz$7a4‰üÃCoN-#Û[ŸÒ|$W.YQy8Fùè­)Þþ¨ôªòÇç½b×× ¨<>ý=<ÂÎæ‘,âã“ìÏv[Møªoù㯾|$q÷„¡­ò`Fí~xºä=|ÔMå!kþŒöß›ÜwIÜ]>rõhâ.Ø}ÍÄùü#¹²p'‹ÊÏ0ÏèI®0a‹<Üýôl dÿSE.UùÚ]ä·¿hð‘<_HO©üöQˆ]îÛ]Ó‚a‹(ò;LKŠaó»r•ƒÃþv™Ó&÷ÑN•ßÁKŽ2 ¿T~…(„޳쫢6y’oòÁÑGRš·v>z-³O:ªüòµÌÏ©æÊ÷ÈSǪ÷Swþ«JÂ4DÈŇÝÈã Ó°6º5ÿ$/sŠ<4¤Æ–‚\k™ý ¬ÞðUõ0Ÿ¸Sùã‹×ö†ùýÒ ¨_†5¥ìÏvX0üTõ3¾ÏH4ÜÞ±ÉC' h8ò¬òÇW+<’}|9壇S˼å¿àñQFnè‘"?»KÂôö·3=š0 !@=ý—Þ]'½ —þöÚÛ=máé‚@ò•*BXAŽÿˆ…Ê`÷%(,^¼ve’0}|õå#Ð'ä›4Âõ"¿}¹Í£w¢ûSk*¿}ᣇ CÔÃ…Á ˆü Qfɯ†+‹T_æøö2 K™d@Ã…¦*¿BŒC¦i‘×ëß=Bå—¯uSyJ5ˆü r•Ûù½~$Ùë÷«ÿDîÚ}“ûíí¯\ïÑwí¾Éï$ÿÂ4ÚäþÜÁ¯\¯Øý$¿Ò»ËBièýÊõßÐî2VÓÓµà1üT=ä_.ú•«¹òý}»—пŒÈ¿=ý÷å|»K*ù²b“ß¶vÿW®—Sú¡­r»lòÇ®«¿rÖüʵ‡ŸªõÀ¡ÝõоŸ ô”¦Ýkoò ƒORÉ>‚²É;µûk4ýù?7rYùl~u“ûCn›ÜÇ êG¯¾´å6›ü¶{>•ÿy9#—¼aorOîù•Ëà C[SÉ6ƱËmøW®•£¾¨ÜC•ÿþ;4¤l³ÂðØäá«Ê6+,ò"ìYó_¹Üò&½ÒáñQæ†Ãgyò‘šJöv)¨«­+Ÿïï’¨ö'Låb®l-³Êÿü׌\C¯áe4ô~ªÒo|¹¯¤û•ëý¾GJ^Û‡6¹?bñ+WäWxº^ z¤„Ã)‡iãÓuÏçûŒÞjóM*ÿó_3rµ¾!ßòØß%'?öv›M~…þ.GuýÍ ›ü¶©µ_¹œZ³±¥_¹,ea4n³ü¤÷–ÿ1,F.%‰¶LåŸþçåŒ\Çjè32¡‹Inø¶ñ÷ú‘ÜðÍ€Öä†'8½K\j˜ 4•œž®÷èû†¼d¡ £I¯©µ)ÍM~Ø4ø¯\3qáÝņuõ’€‹-ðý•ËÊúŒ¦ ±%•‡ø»È}Ö¼~$•œúÌ->2½Œtà}ç†ÿ¬U]n À~ÿ||{•ûþ®÷ÔS«‰ê`P¶Trø©zåKhÈ/g7ùmë ~åšÍ -£ŽÃ·ûóm–̳/¼Ûäþ Ø¯ü[Ôìmzé‘6¯ý+?¥eÂËHœ ,šì Á"=Ì•ÊCÄð‘MØ€J*9¾»fžÃËÈð!@‘§á¡yí°5W[ú©º‰³C{é1co;׬–¢øOäöÝw¹m™%ùÕÝ_?ŸÆêÒt¬_ŠüwÒ /#ýÝ/ÛÜ÷ÈMn ‘6¹?¦ðûg=7R¼XêZËlg1‘WØ"®¥1=ÿU57ìCÞkiÔÍ·Œ¤cÇ;l•_>(ò??ÝÈ%äíg1‘ÿ)1r­ ŸIvÃ~Ò[’ìõg„~åb®RCJ¾) >97<>7¬òÛ§Á—žNO×;\>=ý±·$ª<9½%¹á ¶ÈC…‹ÊÇWE-M%‡‰CrÃa‹(ò?K›‘ë)ÿ™ôTrè‘%cÕžú•ëBž.¦Öžüú•ë!æÐ ôTCËÊg,mòå À–Þ>ìÃ9*¿ÃÊ'©äøtÚŸävi,×#Ò¡eôˆt˜R%•<¡e47~jK÷{•¯°Øh²×ïÊD^ÉÏH²÷ò¥BK1ûd€ÈSEåËHý•Ë®,l&Z}dø©"OXN …XäñÝõÑðîϧw×ãÝá«jæÙÔU¾|žoI¢º|èUå·= WK2Ïþ`¤Ê+ >É<džÔhgø©ŸÂõ"Ó’œd¿íud*ÿ]ÊÂO¹½åüŸÈýÄ!Y󴮪<øwIƒ/Ÿ;Xz¬> íùÎYš5¶ž“3|ÿôô?/gäŸJýUžv‡¦üй¿ØäŸÈ½1ã¿¶ü¤§w¨ûTÃ’:޽y…ÏÒ+ÂÖü”­yè*O/#¥qa7,òÛ—ÛˆüO|ÒÈ¥Å×vŠüO8ÓÈ5›ž~~“¹u“‡£\ë”°±¯1\×Ï7¹„sÂOy(XRöáO²«üO÷_–¯©•²Ps¥ò#,Û á§Þòî¾Ï\ºE ïþm'u+-DÞÁvJDzGÓÿ,Ç»CM®ÇÿDþç;¹LKaŽÜ®\-#l»¯7„-â-³XØkßßâ3·æùÂÓ5‚Ú]×~&²ø™4$âûû#A {hÿŸÈ}ˈ|…–‘”pÄBäŠÙŒ\¯OÇ>Ó&í.òÔôX/zðÅkKonðÇÐTîa¿rå"†—‘¼G˜ôM:úøÑðî²™‘ÚGV>ï°ëG†‡? WR˜áñ¿–˜žß —ÂýhùŸ—3òùöSGžnÛ½Þ¥áòƒ’“é¡Ä°–6{¿Gv(ØÝå¾ßåí7ˆ¢þÓN]îw%ÙÕò!‹*yu;òDýñáÞÍÈç›ü¹J’ä+žh—‡—Q¹oÈ–ÞîׂzçÛ/ðÕߺ@k³[?P’´‹¿T¾’ßÕìrß0’ó(¼Fg0ÿSUîOà×HðÁ–]î_Fâ×Q.¤wס äýM~ŠÜU r¥,a(`Ùå¾q—ûŸªr+‰Z•wJuÊððyá’PN’K('Êå3ùD]Ú2~&`Kù:ˆ]nír½£'¿ÿö/#!…òùšz‡ÚGCDWx•ûüú&÷[ÕMîã¢u‹ÍøROX‚%tRÞç—œ˜)öÙåŸî»£°)¶¢$t?’ÈÖæ–YÃoöJilÈŽ¿|Y}=Ú}ý»«ÜWÔ£îÄwßGíFx~}ŸQy›Ü~¦–jùÝ[ÿèÀ¶ïÞº•ô¦ýÞ^þ+µî$Ó»è`²c¯t0}”Û>ÐïmmHïµTø—¯Çh)Ùý±uÓì§ÊÛoš[÷Ø>,ÓïMóá'÷Ö-vú¥ê“|g_º§ O—æ ›ÜÇ {élm'È^bM|RJåíoˆêÒÉÝ¿L©÷=l“ÛuLå&÷O侨<ôH‰œ„b–àF”Ï7¹öÈðî*÷CUj»Ã¬òöõD­™0´EÞ>ÒiiöÙåŸîjëŒêŸÞ2<¼ok ä„þ®r_~´ÉýI8•§N —…½dkÊgj6¹¯€hY…áÑ:aû±*1«ö!®íþ«Jám¨…êwÌÊŸÌñŸÿ–‘K3ú}DKéj…#ò ÜäaÍ–ÂØø2ßáQëRzŒ/‡k‰v˜P5Ra‘·åõ;°x‡…éÐEÕw©þlŸ4Úåá—ê4ž®]&4û·.£ò°K¹¿þW®‹jxwM_„§K‡ ¾M®¶*Ykø7l÷TîoŽh Ðzx[µh;ô÷MÊ}@¡¥ 1ÄTÞ>°¸ÉýùÙM:°”DF¹¦ B»ëâ: ¾0_Ÿ:øü ¯QzÛä!x¢Aý°¨<ø‘{Sµ¦ ÂîSåa­yá ‰°·yZVUîóF­éŸØä!$&òö•›Üç/ZîfK‘·¯¿ïK&Ž0š4³“ZFæ™Ôî2Ï„}¹ÈÃÁûÖ4SÚ"ƒïþöSe&H@f‚0šn«ÁBhF-ìo«~ÂÖ,–/³Úä¡Ý·™*m‘·¯iØä!J«ò°·Õœ¯öØäaJy¨GÞä!8£ò0qH†/ÊoòO%*ƒO·*¡¿‹<„ODÞ!\¨éÆó¸u3~ªÊCŸÑàÌ7¹¯ÔÞåaxˆÜ§¨[n ‰X•§eXåaÒÓ¬pøLš· ¡N‘wØ<¿k©CÅ¥¨cì]åþnð–{;dƒ6ùǧûö|›•TüÉ£=¿’©<ìƒÄüPyû¡~tì…–yHÆ?ÏùHî>ÊÅýøÍðhªß÷w•O;Zž.£ÉOb£¥>p¥ò­$Hï®…¶Ïlr?-©¼}íß&÷ÇHYCˆnr¿3¹1¡mr¿SÙä¾´EåíÏ`Ìϧèû&÷³•pø§KMÆx;3Z“ácÒ*Îm´(#½Ì§¢áy×p„æ]Âqyg5Zðá‹K7¹«<œô© Žv´>Ä1•Oê¯ÁqùDªö~`ÞªCTÞþ‹]~¨ÚßðMEîýÀhÝŒßÔ¨>4ïÛÁ~ÿíÛq“û¡$¹õñ¡–]Vèî£ïîû¯ð}éHªtÂ|*éÆpàs$Ý8ÁBnòðti™`eTîõ#ùÃpUÙHÊn|n$kú»Êý5É#ÁîÀ2‰^‡»%wyxúõíé*÷O—øò„%ûÖ† r™Å|df$´ß]'`?<$ø7þ4ÀHx.õ÷[GÓ7¹¯^ …)æÑ†ô£Iåa$á´”I¼b‚áAxú!Ûì€õQùá3|Ç6¤}w•¾Ðæ½g¸{ì-ÓáË"Ù~ÛqȦ&ÊµÏØ|ˆy?|Œëòëè=ÄÓFù§•o“‡N òÃïS6yxwñ´ã‹ 7¹Oª¥ÃÃÿT)¿Ëð¡ŽÙO©‡H‡Ëf©xQ8ê“1ªŽ ßìR4œ>ê¶YõvãÐ9éÓÓ¹f“ûó!%ÌÁë«<9+Ù—¡»«<µŒÈ}\é8t;^F>ô#ò ×´[ ¼ŒÈƒ÷9Ôˆ}zúá#‡† ÂÐVyêbº%óKÍ¡3ÿLR­=¾LìÐðIÚ[´Åw`•‡Xå¾ÔJåáJ¶M&Žw¥yè1o±¯Êq¸#û8uÎ"ÃÔ§R AJÁ&]]CP¡ÉUPNhÈK÷KáetIõr paò•׿;X…í•Èßä>™rh€+x•û‚áMzäm ?U»XhHÙÑøÜË&÷u›£rĹ4•Þ]náÝemòY,•‡Ü¤ÊO¿jŸ’l ±ñMî«rvyhH‘{C®òØî*ÿÔ2vu. ÂÓURvþe¤Vðð'ãÏÒ(”™-QäýíÝ[ZÆ÷™oiX•ǧ«u )r¿_UyÚ*÷NOågèï›<|U Ey¹ä„ƒ?µ4Ì­],<]:Ï2œ[ 9Èå3Ù:Ï„Ÿª—ðt™g©òôôOu›ÜïÊNAçž±pŽúÿ™TîƒEç|ÊÙš/÷ee*¥Y§$ÀÏ0-iFÛ—Qª<¾Ìùí§JÃCrÔ§¿‚n—|ºŸÅ$¥}ú„ù.÷‹Í¡;Èeå ‹ü¡+ŸwM܆åàø?5ùé«ONÍ7†E^sv>¶tÊýMÉBÈÅ@!bxJòë øüPWùékÇwyhéÀÁ^Ÿ*uÏKÛ=<]Œ¡½ž—FPÂËÌ·§ÛÙˆüð7B«üô'\Ïwž/” ‰ú÷á¾ÿjÙ{˜€µì=XM"&¹|¥ÐݵJ>½»ÊýW’TÙz˜Õûš¢SR6gøª[ÆÿTÉcœ¾–à”;BIÆ©ï£Ó²÷0çILúô1éëGWût•‡Í¥5øéé‰ò~üÒ|?ͨüôx€KƒÌ~»zI9 ¾ëGû{hé~ð]?šöø(-ó–_¾.ãÒã~&PùéÇê%ÑËPª{éé„$×…Ïw1^ú•ìÚ"€¡!µìýÛÓ}aÑ.·“žÊãW•ìëÐ. 饖‘é×Fû‹<>]†~âЀazíÀv¡Tùå÷ý—ÄÑœ«>T~ù Û%ç6þ÷Òs>½ºÉÃB)Ç<ÒÓUî Ê%ÀËg.‰^¾âÒC$>5¬ò°¾ôˆ¹O"^Ò»‚… Û,Ä&ÿøtÿS5èÖU‘_Þ¿_£uHáéëÛÓ¥ÏøÃk;Ó^æÓ˜Kbt—Ñ]t»|òö’ðÌ勯C§¥ —\ªDsN­¿´ØÜ_o¦òÓ§=.-6÷¥*?ýÎFå—¿7ëÚªÇ}ÓHT’k9Èeúû© ¥ï‘*K™È¯àRO 2ûÁ'ò4‹‰<~UMóùþ.A·+ØÎS‡ÇG¹_ä%Fws%1ºëòcUkñþIŠë£\ó¥¾\:-¹8ì0Gª<¬«[ÔÍ7¤ÈS»ßj®ÂˬÓÓ}õðuk}€oH­ô÷•—„/T麵G†§ÿ–§_ÁJ0ÅgDž<ÊC¿5äzæ+t1Yµ}9ð%Õò¡bEå!UvI,õ¡(¥†½‡È¯àg´žÝ'7¹Ô^©M!‘§ÐV>“D ƒ¹R¹¿ªHå—/©½¤j;ÍÀ”¾Â2üJ§Í°†°ƒûÙäö£ÞR…^}—ÛÁ´Ë­ƒ¸5žîcE÷vI•n aûYi—‡Ÿúîa·_Éî­¬Úvw•‡ü-ñôøt™¯C»ë­¡> ¬òp8DåWøªRk|¥§Ê}ÝZÞëžÊCÚc“{KpëE ~5¸õ.¡Ðß5Z·F¼Ã<#ïÛG拾˜oHI‡iIä·ßKÜÂö»Û]D¼o“¾%„_FåáeF^&<]mß D~{£wk<Ý‹¼KC©áe4ž^Fåáe¤¿‡Á÷aK ê?Wèù»ÜþÀÄý.y||yøo»xGðf§ÆwùWRùí½ûýŽìÇw9¿½Ë)ïâ»—V‡ùQå~Û¡òÛŸ†»µÎ8ÌšekªÊ} ÒÝŸB3›üãÓý®\å·¿0çÖ I°>*÷›•ß¾FúÖ¢g´º5¡L¡Èo¿+¿µèÙïÊ7y0´"¿ýáŠ[ïK/£w”„—ÑR±Ðîš® OסÝuÕ rÝHø.¦÷x%ù»GÞ¾*n“§§Ë¢ê¤*¿“\{dx™ù&×…/´Œ®MA®)>ßßUîë§6y˜Ež¦T­÷¥b*¿}‘ÿ-ùÆÛ×ÜÝ’L/#òô2’@¼Ãrpª‰ /Sß^F¦Ô`P4ßV‘§¥ìü¶ïØä¡eĺ·té¤ç'ìMîßõ-„¶ÉÃÓuŽ OWyxºô_WkÕ~ØJ¨<½»t‚(’ôäíãÑ·¤'o`¾/M ‡§k°Åw`•‡°^ækT DnI ž! -ò;¬šo )òÛg3w¹ÿªšÍ ñ ‘‡ÊƒMž~ª ¾oO¿Ã„­Ç%|u–ÊÃA×[OW$¹ ¾Ôexø\é­ÉÏôtݯ†á!rŸâSyêÀš+ “ÞvîÄw`Í•úLÖ­éÉaùíO(Üšžô%Ø»Üw`½ö),"¿BòHÎÌÜ! !éÉ#,6›Ü÷H½öé«Ü~¦Go‰òs¤Êo_“ñHÂññ‰€GŽ~Ò{äˆÍí3à&}:þÑ{œ’\{¤íbfÓÓõ¦¥ðS?Ý´¤òpm“û™@å·¦?š,MOW¹ÿ©’ý||(êÑ‹™üb³ËíÄñh²Ô‡¼ŸíxPx™°}åÑË|´^å©Ïˆüò7<ÛAá3‰Ü›Z•‡½Ç£X—Ô2"÷«‡ÊcC¾åìnruyô¬’þlr©}JýLÚ «üöwe<š¹Mï.vß{1•?am’ÌíãC€dnãWUyøª:šÂÓ¯oOÿ6#ÙÛ',ÚŽõ¯¤c£\/¹÷Sª^Y\ê;{›.ÉÛÇ'M¯†Á$òËWߪýñ•B¦†ý]¼*OÿÄWSy(…xô(ª?-±Éܧ‰ç0ç©ÜŸßyô «¯CÚå¾e$OýøÄÄsêðð?UäOhHÅ…˜…È“s“Lòü¸ÈŸ·{ô «ëªü }FåéÝõ ßßE~ùT™ÊïàOômzºØÈ`Åôª»ÔÅ´Ð?]þá2éç[Â_åḄÊï0«Ü×”ó+ÿæÛåö,ê.·e“û+~å¯ÑôûïðUïoO¿åéáݵª/|U‘‡>£GäíÎf“ß¡e¤H$õH=€ºØÒèOxºÌÖºír»ÝåaÒ¹7†¿rÚééŠ -ó’ÿþ;<]oEû$?~ÜB©ò߇v×[ÑBŸQyhw•‡þ.ž 5¤Èí‰úMî/¯Ûä·­ø•9¯ô+×ûýËHùŒÏ‚ÿÊ¿”ÏüÊ5œä²+³5T¿rM"ú.¦WØhç¯üËA›Üþ•ËW }¦tãïåR—áãb¿rµû_äþkF.Û[{íÓ¯\¦¥0ÏhmƒÝÞþʥݭ!ßäOX¶ër}Ëè…¶¡Gª<ôw‘û­ù&O3Á[þÛR~¬n—ñ†w×ÀnxÙØÒŸß?ë%jáeô6i?<ô0¸Ýk«ü÷ß¡‹}¹÷i“?öÒ •ÿþ;üT±ÌÁëÙñà°˜ö|oy|)nð%W¿r¡Ý¥žà Û[ÍøÛ3n¿rÝ•…w׳ã.Æñ+§>Ó–Ârqøþ®8ß¾e>%ªåzSª÷M¨ö.¿rYµíÕÖ¿rÙø‡eX’½Opš½ »ƒSK'¼üýý?÷?õ’ÅÆ&2~åý–‡YLå!N°ÉÃOý6¿«<„¢$µæo¨ý•+~ÎO*;JI~-uû•k…‹º¤§îðîšž à–.¾ê­~&¼Œìõ3Á­]Ìw½ÙÖé©<>½Õ8¸¥û[–Ò ù-kSØ•é%Èaï!瀯àßo±?¶²èW®{CˈŸ ÓÒ£ ¥º&¿lzêW®¨Žðt‰„U[ÓSaã¯ü¹0¥j6ËÞVó+·d‹7¹ÏÙüÊe{º˜&¿lN~“û£Y¿r=ò ÙCå·‘?ßž®£ÉþÔ¥÷ÛúÈ_¹noí<³Éo;Ïlr]šüò»áMîr“ÛJÿ_¹,e¶øWþ¥Ò“ûJºMþø¥lI¾É_c¸Éý­X*ÿýLáe4r^Fvò>¥¹$ùuùˆá’ôTØ{ˆüÏÖ…åšÍòÁÑ% $ãË.÷©µ¥Gžý¾i“ûÊ/{àW®¸ ?¨ÜžÞå©!e¬z/¶äöé°5W¹?"ô+ÿR’¨ò?› #×ó×ßä©‹½ÃhËÖÔþþY¢Ì~›µ$ÅóMþç¿Ær½9ÛÇ –d„ÒÄ¡'¤ÓÓ%Œ–²’¥Ì\ÖvsvÏ7¹,a¡”RÈLìr?-•vmaõ¯üËe*ÿ]ùü´¤òÔgîûÿùÊäá3©<ôÈç[Ë<ßZæù·¼Ì ã5àâ{ä&÷Ÿé-ÿÓ¡\)ø–Qyð‘"÷G@åÝ÷_UÉûííÒsïŸäþkF.ûU{+–ÊS,ui:6òÖ|Shw‘ûèÊ—Ïk¯-Ùë­›${}‘ì¯üË)ž_¹"…—‘.Zf$ÀèSkk¤‹Ù£-¿rqza–ÕžöµÉCiiÂ4=]^xºô™0akÂ4½Œ,6ö`ä¯üS=°Èãrpè&î“ÜWJÿÊ×7¹–õù¡­Ç»ÃÖ\ÎkûC»Ü'aTžvòzQ¸/xÜä>(½ô𸎮ã›KÝä~&ÐÃã¾Üf“‡E^òÚ+u½ƒ(4¤'¹Þ÷I~…øÐøŒºž×³Ø[þghäÒ߃K•¼ö¦¥S·YáÝ5Nà{¤¤ÁŸ`;OéÁþHÖü¶7üÊeã:°3~|UÔ’“½!Ù»äì­ÿÊõòa?ψ<”$.Íɇ‡^bz"Õh"ÿScû—åË—õ-9ìqŽ¿r½$ÑÏz˜ÖÄ,=L›ž®È¬ ?v6*¶žŽ .õ–ýjX†¥ü EjEîï˜û•+[ÒÏÛ¡N¿®Þº û.¦9ù°Øˆ|…ÅFåa¡”Œ¿lò3t±[v”aw På0¿«<øw)?XÁvêaZ_%¢r'ºÊÿíG“–„YLä)þ.åOðï†s‚\2 Áv>2¿‡Á§õamÒŒÈÞêùU_­ ò'Ì‘›<4¤¸¥ÐßE¾B*YÓ†ŠÊS'øÂØä—?¦PR­²æ*ÁQ•‡hgéA`oPJ‹|(ª´üÀ¯*«Ç&÷³XéÉ^@¯´¸ÁÃÚîs/£µù—ƒï›<'—¦õ›‰Ò_ˆTZ থRý<£ò[Rùãצ’ŒÿéK´j}Ú‰<ílT¾ü¹ƒÒó«¾ °”7í'=•{ÖÈ&Os¤wõ;ùÒ#£aðIN~ÂLð–ÿù¯¹^lâ?“¯ÃðÐSš>=%ò¹Úå¾Ï”Fj?ÉÓXÕKÎ}H¤$…ŽH—òO'ªK/9Oré‘~¯­rOQü•‹ŸYþe4Ùë}¤Êƒ1,Í ‡X²·áÈhiö6 >ÉÞ>ÚYzɹÏk—žŽM/óŽvVpzQxpz ‘Nr _†Ÿ*ɯ0¿ËUÞ§¸”ž½Mr=îêß]Ò±G°8ÈeZ Xä—e/üÊeGf1½Û§Öj$>V>•‡.¦ÙÛ° ëùUp)e§§kÂÔ>Í€†µéIÏçÊJ¦‡¯¾ùŸiÊÈ%ºŒá[þÇW¹’LÂÓÅ2O Ð38lÍ€ú£\¥÷a'¹N©A®Û¬ ×9ÒËõtl’‹ô§ÖJŽ»†€zIZ0™ÚítlxwIÂø´`ɽÌi7¬×8‡±ºÝËì{¤ä(ËG÷7yÚ*÷)üÚ®qí.!À0¥ê5ÎahŸß "¯Ð ô^æ`;ås(¼Ûåþ3é­Ï¡eôædŸoùŸ ©‘Ky™Ï”ÞmœäbPÂhÒÛ‡CÞ䟞jPDþçÆ˜¿,/_S—Ú?q¼åŽF®—á„–ùÂÖÙäÉ¥^2Vƒ1ÔËŠÃgÒtlEéið0Ü2š|zªä4øéŠüOÞÏÈeê³**÷·±ª<´«<Ôîr?q¨<¥õæä°Ò£éÁÏh¢:ä=D^!–ª'Ù}Ui*9˜«-ó¾êóíéz'ú;ÙûçåŒ\v6a#¤ˆê0é=pñç(Kr”6ÏLz~#ÔKZÆOK*ooúÈøý·ýª-·S–/·ÙåáeF^ÆŽÕ–wí›–vûhg¿£Ì¿ÿrí3áed&_UN µGîòðtí‘þ3µ4¤?lµÉýêÑïÐkl‘·0îrÿUUîC¯ÝÚßíÄÑïHm~•‡–yû±*÷éµ?·Éýå~»Üw`9|Ò>¦×rŸ^ê‘rÄ¢}H¤%ؾög“‡§ߦ%•ûv:¿‡—‘†ôY•Mî ïúÐ Û÷•ûc -õï±!EîïéSÖU_à»É}<²¥º¾½AÙä¾:§ÏúötM~9PyzºÎb¡ed¬ú‹Å[¢?íO:¶Äg¢\žîëÅZʇ£\ê Âêñ|Ú®|A®_Õ¾ûHØøÈÕüèr`_Fåã÷«ó#?Õ§G,󸔿.÷ï¾d«â7 *íÜåv¬nr?ÏÒ†´C{ÄÚ#õ3íã‘Sº³ñí¾Ùý —Ÿê#(#v¼ã±ûŸåv&˜údPT>>>3R˜‘¾ªÚ}_¶ËýOÝä~h·ö÷Oï>¡Ï´®«áeDm„‚\­[hH‘ûxä´z1ÿSGƒ~hΑAþÞL˜–twàëGª:,e›Ü7¤T+LX›d«’ä‡Î‘¾eÙfù‡Ê'Ì‘Ûf·ŒÕwÎÈî`üî`Žû“\ý{X(ÅaÏéê;¯ýçÿÜÈu7쇇È='®Gý{zº¬|¾Ìi“§Ÿ*£Éï=6yz™Å‚ÓÓ½‡¿½l—û¼ÉýÐùøíí.ÿöt¿ÍÝf/&òñÛ¬Ñ]YxºÈãÓ5|éÇê¥q1ßÅTîSšsé®,¼»ÎA.C;Ì×§øÌ\ê߃ü['Ø6ϾHöv|qòÜÚî~&¸53ž®r?Våúìñ1½Mî¤Î­s¤ï"Ÿ£9;Á\m1ÿ2’ç D±yäÝÓÓµ¿û¡ý¨ãð_õÑ$LxºÌÀ>:’EŒ?Uå¾Ïlr;øŽŸŸ//³ËmÛåáe´ÏØŸºËÃ˨<¼ŒC¿+Ûä~>~ÔG¹&íXUy@÷;üª}H(êð¶óDõágà]nùC]‡_W7yzºLØ>ãȵ¶í‹JŽ-êäÏ'¹DÝ94Œæ¡F £I䇋FóŽãûRÇ—õmò0ø$'?~¯}hLÏ'LU>¾Ðô@W¸©äÈÕøä×!ið 8¶¼¶Ÿ–Z ŠoÈVÇῪÈfë˜O[•cK²û–Ñ@—¥è ·}lr_Duh +½ûõI~èêáªÊúzh`÷“<>]JAƒãxmñãú>Ì¡óÁÈCBn‡ß¬[þÞT‘‡C”Ç¡ÕwÇ㓽>$ ö)*GcMÈû”Ê&÷Õì‡æïýyQ•‡K!ŽóSæKåÉûhì2,Ù» ë˜Èãg¹‡ =RC>–sh02ؼSÝIèÀº/÷æýÔÁž®Å3þér Óc ¹…§k,Ç&•û»; ¹¥§Ï·§ë¢êÛ]"tGp´*÷ÇCzQ®µ6~¬Š<œ>4þ¶d*ŽVåÁûHt1>ýSÌø³!´±Ý:Az*¡ÅÇw¬ÐÏ_†Lmr}x´ZÍðhÙ‰…}žÈ¿ë!—âþŠš]îç:9'j"U>þ8ú!áÖŸ_£³a6z4¸äZÿà{úVßæÛ]BÅiz‘ØïÖGýƒ§±_oN ˆúEãüQ·i»˜ÊÂÙåáÝeBòqSøjGz÷·<ð¦N‰pž>Âyþ|ÚÒž?Ò RËh€ÈNէܶ‚,*O ©Çˆ|úXå㫉N‰ýž>S~ê!%ŸxQy@ŸorO:—ÆÜÃÓ?Õ*mòôt-Æí.£É_zj ÚŸ~Qùá«+N‰[ÆÁ)Õ¢Q®EŽvå;µ¸Ô‡6Tb¿§Ö¢†™@äáÖ¯Sh¡m“‡†,@…Ÿ*á_éz–,>Á{J MK*÷±_•>ÎrjzÁ;ŽMîs§¤BdYåã·©›<µŒ,e>*®òÃNέ~Ù/Zì‹UnÉ8µJ7|U•û ç)©‘ö{SªtÏÔ2}Ó$Ú?¹µ¿,?}øé”4Jئnò0ãµ&ÇüÓ¥¼øôgOeµß4Z^ìÙ*÷í’u 5·§f]R˨<¼Ì·¯ºÉÃÓß_õôñÓSR@ã¯j85§ãÏ*ª<Ü_pê9Ë0[«<8ZÉ¥M“–uû½­ÊÐßUî/>9·3¢¾ÏˆüðAÅóÐܱŸ8Tî·ñ»<|UÙN¦†Ôˆ~h æ†>#Ûɰ·Õã°ah‹<”Ÿ’NKûrÍùã*?à ¬ù±0qˆüô·RœšNóIx•‡s *¸îSSRÁ·‰<Üc{žj€ý)ò#Ìï§îÃOÕ|pøªºØ„§‹<|U)I?ÂÎYKÒÃWùÏ©é´à—UúŒ¦ÓÂB¹ÉûϷ§«<<ýS‚WåÂ'—Æ.ýÄ¡rÕÚyéà /£r?ø¶£¡et÷>Ó§ 8T8§4ð·Wž’ üûÿ¹‘¯or=ºîýŒÈOìÔl`X=DÈW§$'¬|*÷Ù£Srgˆ¶è¹„åùéï/8oÝ€ú,Y»4ÏhÖ.D¹$¯v&¹Îïþ§Š<\†¦ò3Lz[ÎU‘Áa W«Ó˨ýù(-#Ø—ý†Çƒ\gàð2"O?UÂ9a#´e O— ÛWWœzÚÄŸÝRùéSæ×¦ÌíÓUj?¯-¹žþ©²ôÒ{Rü<£ò¹äøH¨ßå¶Ï\’‹ 53*?½ãPùåGÓ¥gYüʷɽݿ$1|ùÌ×¥‰a¿”©üð‹¼Ê/Šº~tãž.r?é©<Ð0/Í#‡vW¹/X»$Ó\ªÊÃeõ—^–ãe*Oןô–FÝ‚\ψ~“û­Ê¥™^á&÷)óKéH!ÄùMî·ˆ*?ý^û’LïZFS·Þ lò0qˆ<\Q½Ëý”ªrŸvÞä~w òË”k»í)´Œì›|1õ%Iípõ”ÊŸžº4©íw6»ÜwàÒ™ <]ÊÔ2"«‡ÈOŸ ¸4ežÞ]sà¡Ïh `ø©êC'øtk¨Ê»ä’;¼Â…‘—ôUH›<ÌÀ’2!•Ÿah˵Y¡8r“ûsA—m ¸5bèûŒmLnIròár¨]~ªž ñ‡È/_yé9Ë`D~újÇ«uGéW‘‡ó)—ú NOå¾ÀPåã3q—7¾¢D姯‹»¶«áézìÞ÷H©´ÑÎKŽÃþ.©K+-|‘Þ.?Uw”áé2š|ôÒ{߾ɯ°zH ÿò™‰KròQ.3A0W’J¾Âª-ÉÞ+,e’½½B|f“û) ¯Ð#%¿zùó‡—$L£\Û=üÔW»§)ò­œ·ëÿ\>,ê?ÿ-#—oä«i/É8^>Þ}]߯†äÕ®Œ”DY”ë¸-#ò°§²®à”$ñuùÄ×&÷AÝëÖäòQC¸õ£zÛ¦ò°.©< %I|]¾€j—|zø©Ò!Ãn“‡>#25¤ÊýP•,\šUvd’´KøÑ•#<]å~ÕSy˜7T¶¶N‘᧪<<]†‡?ÈwIZíò—žlò°#{tþ(÷ý}“‡N £éÛËø¤Ý%Y¸4ÏlòÐÅž//sKZíò‰ÞûG]^xº.6ö§Þ?:<ìO½%ñuû îý£‹Í'y|ú%òÐ2ò™üÄqËɼۧHnIbÜ>I}/5KÖBÜ’¸ý¡¬[bï·ß|Þõí§nòðtíb¾e$Â|ûÄ]:Gúþ.òÛ_ÂrKèòöñ[‚‹·)Ü­ éß}“ûw—háí³Î·„ÿnŸQ¹%žwûó8·Äó‚u»%„RÝ’›<|U•[ƒ¢ò4-©Üïo ÐÝ>ÈuK-Êuõð/#A®ò4øæÛ”ªrŸ<ºGß TžRä>tyº%?ˆüöñë{¾-*÷ÙÏûÐ.æ¿êñió¬òÛò[Ψó­á¿`Ý4ü—ÞýÛ)‡fÒb£rž¹5é÷«*¿ýI’[B—·»nr¿ç»Oíþ§žºò…§kŦS=°M*÷±¥MúŒÊýô>uÒ ï.ò`PTuo_;sŸº+ O—uÕgûo¼†}Ó&÷óŒÈo×½¯os¤„oŸýÜäÁþ\º®†§K'ðA‹[ÎzܾdûÖ s˜°5ÈüM~ûÇ-Aæ;ì(/º…–ÑeØÏrxãöÇZn J§m–¥ï0<4(æw‰ÔÞ>úsߺ™ðŸI#µ¡Ü:q„—¹¥Þ·z1/ô«~“‡—yÔîû–‘Xjêï ³Ø£ ¥.e¾‹ipÔC%vyxw +|“‡­ù&_UäþÖ§M–•ûÃ׻ܦçÛÐ~Ô2‡†Ô½vxw‘ûHíóó)ú³É}èu—‡§Ëüî··›Ü盞µ¶Ý7¹OÂ<eö²lòô2"÷=RåJ?òö)•¼ËíðØä»¼Éý2¼Ë¿½»OO=z¬%=ý-|)å#ÇZÂq“§véÏmr¿oz~t ?UcØáeÄ ø…r“ûšÏRƒâª&aübó, 0†§‹Ü‰<šâIO×±ê'=•‡þ¾t] Oy˜–4=å-³Êã˨ܯM*÷{Gse~k®òÇ'¿vyhM„wÿ6VUæ•û«îTþøèÏ£IG f“û#÷LS»ÉÓÓ5àòI‚£f@ÓÓ?%LUþøÒ£ùU5Ó&XNðr &MK£«‡ï’5Â<#ÉÞ',6’½}üÁ“GÒ±×?’_}BÀe“ûU[RšéÝå$É–•ûƒ´ä(Ÿ xNmH¿È«Ü‡^w¹ÿL’E||Òq“ûsd£\‡¶ÿ©—~Õðt•û.&‰»4š.ýªáÝUÚ]ä>é¸Ë¿½L˜%‹˜Rå>Å󼳈áÚËçÖ‰ÀϨ*a9ªòO{ë¼á¿’ÊC(U2šOþ¼3šá`·¨óÿõvÉ!>Á‰=:mø5ûѯäßýÑyÀ7»ÊCxtUõ½]åÁŽ?:)…§[³UníÉüüè<ðMnú¿òWŸùónäj \'ø•ËD`³M¿rébvô+×>ä:²Ýgú•_Ò2®ÏüþYúŒ«ÿDîºØüHô=Êå3ÙUu—ÛmЯ\¿j«q /#r;Våò™lhô÷Ï÷[n·óS_VU•ÇÑ´É}CªÜÞF÷+×å <ýÕ ê²õ-¿òþ7ÈÃFåWþš 걡Ñ_¹ÌvåSùoCúYìüórF.‹Mê3Ú#ÃˈÜNüÊÕtúáñ–ç,r›ÿÜåöâŽùiþÝ5¼fà–•ÏÖˆìr¼üýs}{ºN©~Õ~ËcV¹u©¿r]†ÃO÷ÓmÌm—ÛrÇ]nsY¿~ íj·RùŸm‘‘ËL`ƒõ»Ü&4åê8BŸÑ•/Œ&qvS¦ò8´UnóŸÿDƪLið©Ü¿Ì¨Ãö`4˜žþmâP¹=;õûg™gì5ô¿îorÝj‘ÿþÛ÷™ÑÑäû»ÊmõûïŸe›‰ÑÁ÷M†öèàócutöÃCå©Ï¨Ü¿ŒÆÇm^âW.=ÒÆ­~ÿ,=Ò†ÿ‰<<]£¾ÏÒmÐâ÷Ϻ³ O×þî¿ê!]Ìž:ø•ë„^FäÁ-âÅÂô\ßä² í~J Ó’¦1„}J öGŽZÅwWs^Fw6þ«žÇ·w×)54¤ÈCôçÔh§ŸRå˜Øc«RUþç¿fä2é…EþÒþäÒßC»oßî—ôÈèºÄ2ÛXêïŸoòó›\¾ª­ñÞåöÔÊÿí;Á¥ëªŸ–néa§ò`;7¹_WUnÓv»ãGözg–ŸPEýç¿eäïeÒ&(ÕÒm±îØ rIžaùðøz‡öÓ'z«ýÍЪþ}ßè%VÆÇÒU¾üFx•¶zø¥"O?Uåþ›J,}ÙÓmÿDîÇÝ&]à=µßÄ«Üß;=KÂ×ËG¡–DŒ—½‚ê÷χÈý:£qQ[ú+×±Þýþö2*÷/#´eoþßåá«nòO÷ŸitöøÎóàÝ_µ¬y>ø·ËýØÓx›B©<þÒWˆco´C†Ÿú|’2_‡v¨ió}@å>³ºÉý®ciðÏïáUž,¡Ê}ðoßÖ•ûýØ&÷u9K‚iSy˜€UîƒP»Ü>‰D¦)òø6:²¸$²˜ä×·Uå¡Ýß‘Åò`"•Ç–QyØ^ºóӌʃ¥•¨¨,ª:í%UnK@åÚÃ˨_O—é:ìlßQÎ;˜B‰‰¦‘ªòôKEî´»ÜO· ŸLY·t0{Æõ÷ÏÒ|LtÝê®ýO½¥„Øœ9—¯ZR—þcoMÚäi¤ª<5äýíetþ _UäaÓðoä<ºJúϤò0‡©Ügv6y03›ÜÏy›<¼Œ`ÿ™Tž~ªàðî"‹°ÊCÞäßž‚ËJ-æGå>Ý¡r$v“?!t-†B9›ÜÎbõ£æÝ>½4á×øMî§Ô’tGØ—or_زɽµª]›BËÈàó¦s“ûütméŽorŸ,ßä©edmòe“{©òò¥ú‘•ÏO©*+_ifÇÇCJ2;ËçjêÙ9B;.{vÞØä¾¬w“‡î®‰£Ô0º7ð_Iäå^i¢)|T•{³TK·Âá§êØ íþ–Wúª¥õ#{éPý$OcOú¤>#cÏû“Mþñé>0ªòò«p-IYÆÊã)òòºÚ2‚¾Gª<¬Â"¯°Ö¨Üïn«4Àá¿jiøÏ÷H‘Wp¥[ð2Ÿâ×%‡ Bì½J-°%C;}&‘‡5^S«©etôr9w¢´¥©Õ$ÿ.ÍĦw—NàkrJ·:$n£üSjµZ^>Z×䟊›jô3ùX3±>½£ò -³%nÃÓµ¸)<ýS:¾$·Zyóûçû›\ǪowÍOúIiÑ×dÔ¡ƒÏ÷wM ú}ßF“fáÒÓuŽ ri÷Ð#%­–zä©«¶ÿ©’øŠòw»—O°oòÐ2*–ù›J‘ÿ¾LhÈO¡¥:Å—ª™¯`ݶ̗w©©/Žº.µnA®æ*Èû›|¾ÉorI’—½§èŸÈ}'ØäÞ H¡yHN•¤lB!OÝjȃ¼¿Éu¯亮ú™@3<>_·.¾èÍCI®¡¥ð™th{ù£¡%?<2´ýá„’"ùòyŒ’ú¯ÊÓ»‹ÜŸh ºÅ¦òOï~}zw‰Ñµq´ÄèÚ$éCûŒÿª‡þÔor2d—û†Ty°£‹ï.rŸÞ徿K0ýT‰¦.¦ò0V7¹ï‘ïøbù°nK¡|ûjóMîK[‹±ÙUîƒóÛ¹ÉC;Jÿõ¥ -áÅø2*/#r²Øå~á“Xgû(pK¬3ÊuŠô_Uå>ßO¹Ï©ìòo/>“Ê})ZKX7M3*ÓÌ&ï®3Á·wO ©òo/ãë[ZÞíO¢nò0Gª< ¾M:°Èý™™–`}²À*³˜Ê-*âW®¾0´»ÈS»‹<µ»Èöÿ’å láT„Êê½ÉýO•4Fš#U¦¥Mž®fÉÕMîg‚MîÛ]åaÒÛäŸ>“.”ßZÆ'§úÖÕÃw1•§>óm~¿uþ&O-£sä·§û”cßߢ3*O?Uä!ˆvëÎel6¹ŸgæG—áoro6¹ÿL›ÜOØ›ÜY­âH ©rûUw¹íÀ›Ü÷÷]n—áMîûû.í®r»òmr_é¦òñå£Å6Þnr¿6ÍîlBŸÑMhÈO±¥]ò“'Øä~囟OYÁMž^Fs_ßä~'¿É}Àe~tm _õÓÚ´ÉÓXUù§—‰£IW¾ðUuåó«‡h…Í&£Iåa9ùøªÔYºò…§kÞÃÕ¥›8?øTÆêÒ`QxwÍ„–ù”tÜä¡orß#Ežúû&ŸiDÞ]X„¯¤pxÝeù9oé>(4ŒÊÃ˨Üû•ûÊ&÷5Û³¾­›<üÔo‹ÇÒÅ#¼ŒæzCË|›¯Už.ƒã$€}ÕHàø “GÀ‰a‚|¦•ã}H·ýõ±#gt'¬brF׃—åïš8_e*âAPµúŽå}ö%ó->R‡}_׿ŒìÖÂr¾É}‡•Cß,à&÷ï.Õ­Vh9R>!nó®?½}DvÞ'Ê0BÕᓊÚ'ÄD}û:U‡©YÔ¾$WÔéæøÑCùa‰;´+~iò?=ù¯ËƒŸÛä¡o©<4ûk½õgtDüç¿Åòwu°?‹-â05¿Åá–v}4oºêû®¨ò6z×@ßÁ@Ÿºè‡vQ¹ÿž*÷'F*¬ãç×)7ÈuÊ rr½\j'™¤zpžþ]°×¡ö\äîÐ)©_)0ÂòK¡¹w`‚\J»&„/¤øjB~PJŒ&$6yxwýªßäé§Êg 1¬GfÇ`]¥þc‚•lû#(iÜñi­Cò²ã7Ó»<<]»˜m•þNœC’f‡?~H®çð‡Âw6¦ÊïÒDþÛí„}hÄÏbÇ;£Ñá4„ÈÛÝ¿Œæü.æpóáÁo‡D&eGÓ!¡ÆÃß pÈiãÃÂCb‡‡rÚøð‘õCø¦N ·ð~gh„Ï_>qh„ÏO‡áü¤wH®¼UùŸáò×å>¬v¼ãdñeF[Æ?]‚GéeFûLx‘ûàç¡áŸN<äÈîáצ]Þ]§TßgäØëø{òT~øÊÇC.¾;B'8´øwª­ñðC.¾ ög“û’ºãÐ8¼»È}ÜîÐÍ¡§®Úþ3©ÜokÝÙ„Iï½³I^ì­J¸£û8µG†w¹?ÝyÈÊǪŽ÷ ɧ!9òøSÇû´[•߀Šü÷ß¾‹m›8ß"?‚[ºt±ñ}F6qGú©2ÏøpÈ&÷ÿMîƒDÇ­Öͯ²çKÖí}y\‡ ‘ǵIä‡/1:äMü©Òg|Xù-âá/j?äŒK|ºÌÁ‹É—ñ·Nªüð1ÔC®¦K¦VåéÝUî'=¹ø.Äg6¹B²×Nv_åað=:-ù†”#Q.› _•¯òÇRGwe~ÒS¹Ïænâü<£rºó”(DØÉŸ["Èeó›8• ±ËÃ˼ÖÕ§çÆÅl»«üô3Áù£=ÒNK*?|ðüÑi;ð)”Óï(OqøÈ¹tÏçÛ]å>‚¢òÓG®Î¥}&ÈuïaǪÊS»oÑ;¿oro;Ï¥],4¤Ô?ÉÃVåÔP”ßøŸRÆv†iI#W~mÚåþ3i +´û&÷£Iãb>U¶Ëû«1ôŸIîø‹r5†áÝßòÓ¥O¹ðôëêù-b¨òÃߘy äðþý”‚ÃÓ—3ˆß¤òòÞä¡!ß¡Vûh§ÈãñÔ`‘ï3"?}5Ú©Ù,ÏPÛäa›¥É¯à°E(–*?}²w“ûSZ§ a)ù铽›ÜÄœšçó¹ƒóÔè¾ïï[ž/|U‰\ùrúóÔ±Þ]_˜åžÕdP$‹8>Ïw^jjý´¤YÄpÑ,¢/zVùâ‘*ûUM:ús7*?}mò¹š††”†¶ÈÏôU_ý½Ãùz‘Ç`‘V½†yæú…ùf`MdžÈÕ&÷í~ë6Ë¿»ÊÃðP¹Ï•š0 Sê­ÃÃ7¤&LËOK*»a‘Ÿa±Qy˜°UHšì “žÈϰ5ßráHƒO²·§?W¹ÉôôhLÏ•‡œÍ£^,<}}{º _ˆ¤ò3éÞ¹á6Lä¿ÿöcu“‡§k”9¼»îB'>²ˆ›Ü¶û¥¹a¿®nro÷Uv—´{yiæÙ&•‡à%åò¡¨Då§ß7]’Ò¼|*ù’¤ãå£û—d/ŸZÛä>†}IÒñJ?Uåáݵ¢ËŽ&•§—‘´àå7 —¦Ö¼…ØäþœÍ¥™8¿UQyt©üòЫ¾uÉ•]~ÒÛå¾GªÜÛŸKre—_(w¹]Ê6yú©*]L;pxw•ûw—ÄÝåùKn"¹|!Ò./£¡Wß2­“^x÷C^Æ•û Ý%y¾Ë¯Ú»<üTá§Jó™‰]~ªXŸ;Pùå³·›ÜoU.I:^>ÐuIZðò†|“û$ÌõÎóU ‡^šô¡Kò|é3Iž/-ò*O ©«vx•û,gU.ŸìÝåá3I÷áœMî7 ×·¤£È_ÆI:¦Áwèüî;ÊÃXUyh•ûÄÝ&÷•E—äùR{çùâgÒ´`jw«Á ¨üãÓ}žï:t) _UצÐ#eð…‰Cîá¸|&îz'¿:€R¯-µæŸ¾%|ùå£?שñwÿUUîÏ7][F(¼Œžâ òOòKr6?fÿ—å‡O²_z”+lUD~ù(ó%)žË‡//Iñ\¾ÒâÒƒb¾Ô_å§Oöîrßß%Î{\—-ÂOÕI/4¤NKA.aãà°%Mrù¼Ç%‰Œí¼$3BÞ—œ+»|éÄ%çÊΰñד_áÝoýL~¬ª<¬M*÷å×&ÒËÈÚú»åòQæK[Û©!oŸoRùå‹J.9=u…wt7ìÛ]å> ~=úU}W¹¨_P/ó©Êûztm /£Œá§jŸ ï®)Ûo ¨ûIïÖy’:Ïwë 1~¬ÞB2ˆr½¤Âö÷[C%ù§w·‡ Öí–b’\Ï7ùµé–KÁ2ßzÉ¡»õHQ’:ãKt?”±Þr¤èöSê-GŠBòëÖC?að©ÜĨ<´«üöÁÑ[Ž…ú÷[R —ÏóÝš;ð%¸*¿}2àÖÜ¿0ìÖC?ÞßzŠÇ‡ÑTÒ$›<½»”ø}“Ê/oÈï÷)žn¿ºåšñpÜUän/¾õZr_²rKÈûö·oßïwµÏªˆüÏË}ûyf´eüÓUƪD™£¼¿ÉGä¾¼ãÀnayì3£íž~Ë»‡Ï¤rß#%RÛ>h!òØg«aÛä~x¼C€Uþ°•Èÿíç÷wÄð sžÄï0£ÒìéÕ¥Ù}Ií.÷}@ Ôo_N°Ëý²ºÉýÿŽ/vùs·F/}ªì~Wœw¨g¿%yû(ÚýGþ.5¡eôìIx÷OŒ*¿}†g—‡Ï¤Çäý$&ò4_«è¦ò;ìƒ.íbáézÏrxw‘ûÐ’Èã¯ò0‹]ÚßýÐV¹/èº% |‡ÍÁ­®3<}}{™×r°ÒÃÅ£†uò],ß·%ò8¨ÜR¸oÂÓE|žÊÃjð¾­Ï0²7¹ŸfäÞµo/óg¤¹ÌÁ£ÞºðùUåaì©Üߌvß2Íøcb"ÏO×½Aøª"sÞ&÷X ýÓ¼¡ò0_?:ÍøÕàщÃw‚w^Âøñûñ×å>­¶ËC»¼æõvÂ’"¹}Vâ~4zärݺ?!ò8Cª<Ì*!IÀÄŸªC/|U‘ûÀè# ˜°2mr¿sÞåáéï%ûÇ·ŒÈÿ¸•¿,üÝdƒnŸóx~tU ?UåáéºÙ±ªòÇ'KIÅ–Q¹äšn_ç¦òøt‡„§?Ÿ~êÒØ?}©Wò@äO3<’šJƒoé”j§¥GSS¡‹Ijêñ¥òÏÒv÷-£É£Ð’8³É}tq—ûXòd·¦ïòðS%­–Þý5ø.¿?õŸÿ˜‘ËPõf鑜×ÊÀóòyßt’‡¢þý÷GyxõãÛÓ¯o¿Tåþû·~QßwUîýì#GTR˼¨„<¿¨ÿüÇþý¿û÷ÿîÿØœ×Y:´igraph/tests/testthat/test-version.R0000644000175100001440000000121613177712334017341 0ustar hornikusers context("igraph_version") test_that("igraph_version returns a version string", { ## This is essentially a semver regex, we do not allow a ## leading 'v' and space after regex <- paste0( "\\b", # word boundary "(?:0|[1-9][0-9]*)\\.", # major "(?:0|[1-9][0-9]*)\\.", # minor "(?:0|[1-9][0-9]*)", # patch "(?:-[\\da-zA-Z\\-]+(?:\\.[\\da-zA-Z\\-]+)*)?", # prerelease "(?:\\+[\\da-zA-Z\\-]+(?:\\.[\\da-zA-Z\\-]+)*)?", # word boundary "\\b" ) expect_true(grepl(regex, igraph_version())) }) igraph/tests/testthat/test_minimal.st.separators.R0000644000175100001440000000042113177712334022170 0ustar hornikusers context("min_st_separators") test_that("min_st_separators works", { library(igraph) g <- make_graph("Zachary") msts <- min_st_separators(g) is <- sapply(msts, is_separator, graph=g) expect_that(unique(is), equals(TRUE)) ## TODO: check that it is minimal }) igraph/tests/testthat/test_print.R0000644000175100001440000000335613177712334017101 0ustar hornikusers context("print.igraph") test_that("print.igraph works", { library(igraph) igraph_options(print.full=TRUE) options(width=76) g <- make_ring(5) expect_that(summary(g), prints_text("attr:.* name[ ]*[(]g/c[)]")) expect_that(print(g), prints_text("attr:.* name[ ]*[(]g/c[)]")) expect_that(print(g), prints_text("1--2")) V(g)$name <- letters[1:vcount(g)] expect_that(summary(g), prints_text("name[ ]*[(]v/c[)]")) expect_that(print(g), prints_text("a--b")) set.seed(42) E(g)$weight <- sample(ecount(g)) expect_that(summary(g), prints_text("weight[\n |]*[(]e/n[)]")) g$name <- "A ring" expect_that(summary(g), prints_text("A ring")) expect_that(print(g, v=T), prints_text("vertex attributes")) expect_that(print(g, e=T), prints_text("edges [(]vertex names[)] and")) set.seed(42) g2 <- sample_gnp(13, p=0.6, directed=TRUE) expect_that(print(g2), prints_text("1 ->")) g3 <- sample_gnp(20, p=0.8) expect_that(print(g3), prints_text("1 --")) g4 <- make_star(100) expect_that(print(g4), prints_text("2->1")) g5 <- make_star(100, mode="out") expect_that(print(g5), prints_text("1->")) g6 <- sample_pa(100, m=6, directed=FALSE) expect_that(print(g6), prints_text(" ")) kite <- make_empty_graph(directed=FALSE) + LETTERS[1:10] kite <- kite + edges('A','B','A','C','A','D','A','F', 'B','D','B','E','B','G', 'C','D','C','F', 'D','E','D','F','D','G', 'E','G', 'F','G','F','H', 'G','H', 'H','I','I','J') expect_that(print(kite), prints_text("A -- ")) igraph_options(print.full=FALSE) }) test_that("print.igraph.es uses vertex names", { g <- make_directed_graph(c("A", "B")) expect_output(print(E(g)), "A\\s*->\\s*B") }) igraph/tests/testthat/test_delete.vertices.R0000644000175100001440000000042213177712334021021 0ustar hornikusers context("delete_vertices") test_that("delete_vertices works", { library(igraph) g <- graph_from_literal(A:B:C - D:E:F, D-E-F) g2 <- delete_vertices(g, "A") g3 <- delete_vertices(g, match("A", V(g)$name)) expect_that(graph.isomorphic(g2, g3), is_true()) }) igraph/tests/testthat/test_layout.merge.R0000644000175100001440000000076413247212322020346 0ustar hornikusers context("merge_coords") test_that("merge_coords works", { library(igraph) set.seed(42) g <- list(make_ring(10), make_ring(5)) l <- lapply(g, layout_with_mds) l lm <- merge_coords(g, l) expect_that(is.matrix(lm), is_true()) expect_that(ncol(lm), equals(2)) expect_that(nrow(lm), equals(sum(sapply(g, vcount)))) ########## ## Stress test for (i in 1:10) { g <- sample_gnp(100, 2/100) l <- layout_with_mds(g) expect_that(dim(l), equals(c(vcount(g), 2))) } }) igraph/tests/testthat/test_minimum.size.separators.R0000644000175100001440000000157213177712334022551 0ustar hornikusers context("min_separators") test_that("min_separators works", { library(igraph) camp <- graph_from_literal(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael) camp <- simplify(camp) sep <- min_separators(camp) expect_that(all(sapply(sep, is_min_separator, graph=camp)), is_true()) }) igraph/tests/testthat/test_watts.strogatz.game.R0000644000175100001440000000044113177712334021663 0ustar hornikusers context("sample_smallworld") test_that("sample_smallworld works", { library(igraph) for (i in 1:50) { p <- runif(1) d <- sample(1:3, 1) nei <- sample(2:5, 1) g <- sample_smallworld(d, 10, nei, p, loops=FALSE) expect_that(any(which_loop(g)), is_false()) } }) igraph/tests/testthat/test_graph.coreness.R0000644000175100001440000000033113177712334020654 0ustar hornikusers context("coreness") test_that("coreness works", { library(igraph) g <- make_ring(10) g <- add_edges(g, c(1,2, 2,3, 1,3)) gc <- coreness(g) expect_that(gc, equals(c(3,3,3,2,2,2,2,2,2,2))) }) igraph/tests/testthat/test_layout.fr.R0000644000175100001440000000113013177712334017654 0ustar hornikusers context("Fruchterman-Reingold layout") test_that("", { skip_on_os("solaris") library(igraph) set.seed(42) g <- make_ring(10) l <- layout_with_fr(g, niter=50, start.temp=sqrt(10)/10) if (.Machine$sizeof.pointer == 4) { expect_that(sum(l), equals(10.794223604849)) } else { expect_that(sum(l), equals(10.7943032688805)) } set.seed(42) g <- make_star(30) l <- layout_with_fr(g, niter=500, dim=3, start.temp=20) if (.Machine$sizeof.pointer == 4) { expect_that(sum(l), equals(1004.00737470853)) } else { expect_that(sum(l), equals(941.472420651506)) } }) igraph/tests/testthat/test_leading.eigenvector.community.R0000644000175100001440000000407413177712334023702 0ustar hornikusers context("cluster_leading_eigen") test_that("cluster_leading_eigen works", { library(igraph) ## Check-test f <- function(membership, community, value, vector, multiplier, extra) { M <- sapply(1:length(vector), function(x) { v <- rep(0, length(vector)) v[x] <- 1 multiplier(v) }) ev <- eigen(M) ret <- 0 expect_that(ev$values[1], equals(value)) if (sign(ev$vectors[1,1]) != sign(vector[1])) { ev$vectors <- -ev$vectors } expect_that(ev$vectors[,1], equals(vector)) 0 } g <- make_graph("Zachary") lc <- cluster_leading_eigen(g, callback=f) expect_that(lc$modularity, equals(modularity(g, lc$membership))) expect_that(as.vector(membership(lc)), equals(c(1, 3, 3, 3, 1, 1, 1, 3, 2, 2, 1, 1, 3, 3, 2, 2, 1, 3, 2, 3, 2, 3, 2, 4, 4, 4, 2, 4, 4, 2, 2, 4, 2, 2))) expect_that(length(lc), equals(4)) expect_that(sizes(lc), equals(structure(c(7L, 12L, 9L, 6L), .Dim = 4L, .Dimnames = structure(list(`Community sizes` = c("1", "2", "3", "4")), .Names = "Community sizes"), class = "table"))) ## Check that the modularity matrix is correct f <- function(membership, community, value, vector, multiplier, extra) { M <- sapply(1:length(vector), function(x) { v <- rep(0, length(vector)) v[x] <- 1 multiplier(v) }) myc <- membership==community B <- A[myc,myc] - (deg[myc] %*% t(deg[myc]))/2/ec BG <- B-diag(rowSums(B)) expect_that(M, equals(BG)) 0 } g <- make_graph("Zachary") A <- as_adj(g, sparse=FALSE) ec <- ecount(g) deg <- degree(g) lc <- cluster_leading_eigen(g, callback=f) ## Stress-test for (i in 1:100) { g <- sample_gnm(20, sample(5:40, 1)) lec1 <- cluster_leading_eigen(g) lec2 <- cluster_leading_eigen(g) expect_that(as.vector(membership(lec1)), equals(as.vector(membership(lec2)))) } }) igraph/tests/testthat/test_graph.subisomorphic.lad.R0000644000175100001440000000303513177712334022464 0ustar hornikusers context("graph.subisomorphic, lad") test_that("graph.subisomorphic, method = 'lad' works", { library(igraph) pattern <- graph_from_literal(1:2:3:4:5, 1 - 2:5, 2 - 1:5:3, 3 - 2:4, 4 - 3:5, 5 - 4:2:1) target <- graph_from_literal(1:2:3:4:5:6:7:8:9, 1 - 2:5:7, 2 - 1:5:3, 3 - 2:4, 4 - 3:5:6:8:9, 5 - 1:2:4:6:7, 6 - 7:5:4:9, 7 - 1:5:6, 8 - 4:9, 9 - 6:4:8) domains <- list(`1` = c(1,3,9), `2` = c(5,6,7,8), `3` = c(2,4,6,7,8,9), `4` = c(1,3,9), `5` = c(2,4,8,9)) i1 <- subgraph_isomorphic(pattern, target, method = "lad") i2 <- subgraph_isomorphic(pattern, target, induced=TRUE, method = "lad") i3 <- subgraph_isomorphic(pattern, target, domains=domains, method = "lad") expect_that(i1, is_true()) expect_that(i2, is_true()) expect_that(i3, is_true()) }) test_that("LAD stress test", { library(igraph) set.seed(42) N <- 100 for (i in 1:N) { target <- sample_gnp(20, .5) pn <- sample(4:18, 1) pattern <- induced_subgraph(target, sample(vcount(target), pn)) iso <- subgraph_isomorphic(pattern, target, induced=TRUE, method = "lad") expect_that(iso, is_true()) } set.seed(42) for (i in 1:N) { target <- sample_gnp(20, 1/20) pn <- sample(5:18, 1) pattern <- sample_gnp(pn, .6) iso <- subgraph_isomorphic(pattern, target, induced=TRUE, method = "lad") expect_that(iso, is_false()) } }) igraph/tests/testthat/test_is.chordal.R0000644000175100001440000000224413177712334017766 0ustar hornikusers context("is_chordal") test_that("is_chordal works", { library(igraph) ## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal(A-B:C:I, B-A:C:D, C-A:B:E:H, D-B:E:F, E-C:D:F:H, F-D:E:G, G-F:H, H-C:E:G:I, I-A:H) mc <- max_cardinality(g1) mc$alpha <- as.vector(mc$alpha) expect_that(mc, equals(list(alpha=c(9,4,6,8,3,5,7,2,1), alpham1=c(9,8,5,2,6,3,7,4,1)))) ic <- is_chordal(g1, fillin=TRUE) expect_that(ic$chordal, equals(FALSE)) expect_that(unique(sort(ic$fillin)), equals(c(1,2,5,6,7,8))) expect_that(ic$newgraph, equals(NULL)) g2 <- graph_from_literal(A-B:E, B-A:E:F:D, C-E:D:G, D-B:F:E:C:G, E-A:B:C:D:F, F-B:D:E, G-C:D:H:I, H-G:I:J, I-G:H:J, J-H:I) mc2 <- max_cardinality(g2) mc2$alpha <- as.vector(mc2$alpha) mc2$alpham1 <- as.vector(mc2$alpham1) expect_that(mc2, equals(list(alpha=c(10,8,9,6,7,5,4,2,3,1), alpham1=c(10,8,9,7,6,4,5,2,3,1)))) ic2 <- is_chordal(g2, fillin=TRUE) expect_that(ic2, equals(list(chordal=TRUE, fillin=numeric(), newgraph=NULL))) }) igraph/tests/testthat/test_neighbors.R0000644000175100001440000000041113177712334017712 0ustar hornikusers context("neighbors") test_that("neighbors works", { library(igraph) g <- sample_gnp(100, 20/100) al <- as_adj_list(g, mode="all") for (i in 1:length(al)) { n <- neighbors(g, i, mode="out") expect_that(sort(n), is_equivalent_to(al[[i]])) } }) igraph/tests/testthat/test_graph.adjacency.R0000644000175100001440000001370413562737506020772 0ustar hornikusers context("graph.adjancency") test_that("graph_from_adjacency_matrix works", { library(igraph) M1 <- rbind(c(0,0,1,1), c(1,0,0,0), c(0,1,0,1), c(1,0,0,1)) g1 <- graph_from_adjacency_matrix(M1) el1 <- as_edgelist(g1) expect_that(el1[order(el1[,1], el1[,2]),], equals(structure(c(1, 1, 2, 3, 3, 4, 4, 3, 4, 1, 2, 4, 1, 4), .Dim = c(7L, 2L)))) M2 <- rbind(c(0,1,1,1), c(1,0,0,0), c(1,0,0,1), c(1,0,1,0)) g2 <- graph_from_adjacency_matrix(M2, mode="undirected") el2 <- as_edgelist(g2) expect_that(el2[order(el2[,1], el2[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4), .Dim = c(4L, 2L)))) M3 <- rbind(c(0,1,1,2), c(1,0,0,0), c(1,0,0,0), c(1,0,1,0)) g3 <- graph_from_adjacency_matrix(M3, mode="min") el3 <- as_edgelist(g3) expect_that(el3[order(el3[,1], el3[,2]),], equals(structure(c(1, 1, 1, 2, 3, 4), .Dim=c(3L, 2L)))) M4 <- rbind(c(0,1,1,2), c(1,0,0,0), c(1,0,0,0), c(1,0,1,0)) g4 <- graph_from_adjacency_matrix(M4, mode="max") el4 <- as_edgelist(g4) expect_that(el4[order(el4[,1], el4[,2]),], equals(structure(c(1, 1, 1, 1, 3, 2, 3, 4, 4, 4), .Dim=c(5L, 2L)))) M5 <- rbind(c(0,1,1,2), c(1,0,0,0), c(1,0,0,0), c(1,0,1,0)) g5 <- graph_from_adjacency_matrix(M5, mode="upper") el5 <- as_edgelist(g5) expect_that(el5[order(el5[,1], el5[,2]),], equals(structure(c(1, 1, 1, 1, 2, 3, 4, 4), .Dim=c(4L, 2L)))) M6 <- rbind(c(0,1,1,2), c(1,0,0,0), c(1,0,0,0), c(1,0,1,0)) g6 <- graph_from_adjacency_matrix(M6, mode="lower") el6 <- as_edgelist(g6) expect_that(el6[order(el6[,1], el6[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4), .Dim=c(4L, 2L)))) M7 <- rbind(c(0,1,1,2), c(1,0,0,0), c(1,0,0,0), c(1,0,1,0)) g7 <- graph_from_adjacency_matrix(M7, mode="plus") el7 <- as_edgelist(g7) expect_that(el7[order(el7[,1], el7[,2]),], equals(structure(c(1, 1, 1, 1, 1, 1, 1, 3, 2, 2, 3, 3, 4, 4, 4, 4), .Dim = c(8L, 2L)))) M8 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g8 <- graph_from_adjacency_matrix(M8, mode="directed", weighted=TRUE) el8 <- cbind(as_edgelist(g8), E(g8)$weight) expect_that(el8[order(el8[,1], el8[,2]),], equals(structure(c(1, 1, 1, 2, 3, 4, 4, 2, 3, 4, 1, 1, 1, 3, 1, 1, 0.5, 1, 1, 1, 2), .Dim = c(7L, 3L)))) M9 <- rbind(c(0,1,1,3), c(1,0,0,0), c(1,0,0,2), c(3,0,2,0)) g9 <- graph_from_adjacency_matrix(M9, mode="undirected", weighted=TRUE) el9 <- cbind(as_edgelist(g9), E(g9)$weight) expect_that(el9[order(el9[,1], el9[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4, 1, 1, 3, 2), .Dim = c(4L, 3L)))) M10 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g10 <- graph_from_adjacency_matrix(M10, mode="max", weighted=TRUE) el10 <- cbind(as_edgelist(g10), E(g10)$weight) expect_that(el10[order(el10[,1], el10[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4, 1, 1, 1, 2), .Dim = c(4L, 3L)))) M11 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g11 <- graph_from_adjacency_matrix(M11, mode="min", weighted=TRUE) el11 <- cbind(as_edgelist(g11), E(g11)$weight) expect_that(el11[order(el11[,1], el11[,2]),], equals(structure(c(1, 1, 1, 2, 3, 4, 1, 1, 0.5), .Dim = c(3L, 3L)))) M12 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g12 <- graph_from_adjacency_matrix(M12, mode="lower", weighted=TRUE) el12 <- cbind(as_edgelist(g12), E(g12)$weight) expect_that(el12[order(el12[,1], el12[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4, 1, 1, 1, 2), .Dim = c(4L, 3L)))) M13 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g13 <- graph_from_adjacency_matrix(M13, mode="upper", weighted=TRUE) el13 <- cbind(as_edgelist(g13), E(g13)$weight) expect_that(el13[order(el13[,1], el13[,2]),], equals(structure(c(1, 1, 1, 2, 3, 4, 1, 1, 0.5), .Dim = c(3L, 3L)))) M14 <- rbind(c(0,1,1,0.5), c(1,0,0,0), c(1,0,0,0), c(1,0,2,0)) g14 <- graph_from_adjacency_matrix(M14, mode="plus", weighted=TRUE) el14 <- cbind(as_edgelist(g14), E(g14)$weight) expect_that(el14[order(el14[,1], el14[,2]),], equals(structure(c(1, 1, 1, 3, 2, 3, 4, 4, 2, 2, 1.5, 2), .Dim = c(4L, 3L)))) }) test_that("graph_from_adjacency_matrix 2 edge bug is fixed", { library(Matrix) library(igraph) A <- Matrix(0, 10, 10, sparse=TRUE) A[3,5] <- A[5,3] <- 1 g <- graph_from_adjacency_matrix(A, mode="undirected") expect_that(g[], equals(A)) }) test_that("graph.adjacenct empty graph bug is fixed", { library(Matrix) library(igraph) A <- Matrix(0, 10, 10, sparse=TRUE) g <- graph_from_adjacency_matrix(A, mode="undirected") ## unname(.): as.matrix(A) has no dimnames, the other has dimnames list(NULL, NULL) : expect_that(unname(as.matrix(g[])), equals(unname(as.matrix(A)))) }) test_that("bug #554 is fixed", { library(igraph) library(Matrix) M <- Matrix(0, 5, 5) M[1,2] <- M[2,1] <- M[3,4] <- M[4,3] <- 1 g <- graph_from_adjacency_matrix(M, mode="undirected", weighted=TRUE) expect_that(g[], equals(M)) }) igraph/tests/testthat/test_edgenames.R0000644000175100001440000000263413177712334017673 0ustar hornikusers context("edge names") test_that("edge names work", { library(igraph) ## named edges igraph_options(print.edge.attributes = TRUE) g <- make_ring(10) E(g)$name <- letters[1:ecount(g)] g2 <- delete_edges(g, c("b", "d", "e")) expect_that(as_edgelist(g2), equals(structure(c(1, 3, 6, 7, 8, 9, 1, 2, 4, 7, 8, 9, 10, 10), .Dim = c(7L, 2L)))) ## named vertices g <- make_ring(10) V(g)$name <- letters[1:vcount(g)] g3 <- delete_edges(g, c("a|b", "f|g", "c|b")) expect_that(as_edgelist(g3), equals(structure(c("c", "d", "e", "g", "h", "i", "a", "d", "e", "f", "h", "i", "j", "j"), .Dim = c(7L, 2L)))) ## no names at all, but select edges based on vertices g <- make_ring(10) g4 <- delete_edges(g, c("1|2", "8|7", "1|10")) expect_that(as_edgelist(g4), equals(structure(c(2, 3, 4, 5, 6, 8, 9, 3, 4, 5, 6, 7, 9, 10), .Dim = c(7L, 2L)))) ## mix edge names and vertex names g <- make_ring(10) V(g)$name <- letters[1:vcount(g)] E(g)$name <- LETTERS[1:ecount(g)] g5 <- delete_edges(g, c("a|b", "F", "j|i")) expect_that(as_edgelist(g5), equals(structure(c("b", "c", "d", "e", "g", "h", "a", "c", "d", "e", "f", "h", "i", "j"), .Dim = c(7L, 2L)))) }) igraph/tests/testthat/test_dyad.census.R0000644000175100001440000000072713177712334020164 0ustar hornikusers context("dyad_census") test_that("dyad_census works", { library(igraph) ce <- simplify(read_graph(gzfile("celegansneural.gml.gz"), format="gml")) dc <- dyad_census(ce) expect_that(dc, equals(list(mut=197, asym=1951, null=41808))) expect_that(sum(which_mutual(ce)), equals(dc$mut * 2)) expect_that(ecount(as.undirected(ce, mode="collapse")) - dc$mut, equals(dc$asym)) expect_that(sum(unlist(dc)), equals(vcount(ce) * (vcount(ce)-1) / 2)) }) igraph/tests/testthat/test_multilevel.community.R0000644000175100001440000000135413177712334022146 0ustar hornikusers context("cluster_louvain") test_that("cluster_louvain works", { library(igraph) g <- make_graph("Zachary") mc <- cluster_louvain(g) expect_that(as.vector(membership(mc)), equals(c(2, 2, 2, 2, 1, 1, 1, 2, 4, 2, 1, 2, 2, 2, 4, 4, 1, 2, 4, 2, 4, 2, 4, 3, 3, 3, 4, 3, 3, 4, 4, 3, 4, 4) )) expect_that(modularity(g, mc$membership), equals(max(mc$modularity))) expect_that(length(mc), equals(4)) expect_that(sizes(mc), equals(structure(c(5L, 12L, 6L, 11L), .Dim = 4L, .Dimnames = structure(list(`Community sizes` = c("1", "2", "3", "4")), .Names = "Community sizes"), class = "table") )) }) igraph/tests/testthat/test-isomorphism.R0000644000175100001440000000636413177712334020236 0ustar hornikusers context("New isomorphism API") test_that("isomorphic", { g <- graph_(from_literal(A - B - C - A)) expect_true(isomorphic(g, g)) expect_true(isomorphic(g, g, method = "direct")) expect_true(isomorphic(g, g, method = "vf2")) expect_true(isomorphic(g, g, method = "bliss")) g2 <- graph_(from_literal(A - B - C)) expect_false(isomorphic(g, g2)) expect_false(isomorphic(g, g2, method = "direct")) expect_false(isomorphic(g, g2, method = "vf2")) expect_false(isomorphic(g, g2, method = "bliss")) }) test_that("subgraph_isomorphic", { g <- graph_(from_literal(A - B - C - D - E - A)) g2 <- graph_(from_literal(A - B - C - D)) expect_true(subgraph_isomorphic(g2, g)) expect_true(subgraph_isomorphic(g2, g, method = "vf2")) expect_true(subgraph_isomorphic(g2, g, method = "lad")) g3 <- graph_(from_literal(A - B - C - A)) expect_false(subgraph_isomorphic(g3, g)) expect_false(subgraph_isomorphic(g3, g, method = "vf2")) expect_false(subgraph_isomorphic(g3, g, method = "lad")) }) test_that("count_isomorphisms", { g <- graph_(from_literal(A - B - C - D - A)) expect_equal(count_isomorphisms(g, g), 8) g2 <- graph_(from_literal(A - B - C - A)) expect_equal(count_isomorphisms(g, g2), 0) }) test_that("count_subgraph_isomorphisms", { g <- graph_(from_literal(A - B - C - D - A)) g2 <- graph_(from_literal(A - B - C - D)) expect_equal(count_subgraph_isomorphisms(g2, g, method = "lad"), 8) expect_equal(count_subgraph_isomorphisms(g2, g, method = "vf2"), 8) g3 <- graph_(from_literal(A - B - C - A)) expect_equal(count_subgraph_isomorphisms(g3, g, method = "lad"), 0) expect_equal(count_subgraph_isomorphisms(g3, g, method = "vf2"), 0) }) test_that("isomorphisms", { g <- graph_(from_literal(A - B - C - D - A)) g2 <- graph_(from_literal(W - X - Y - Z - W)) res <- list(V(g2)[1,2,3,4], V(g2)[1,4,3,2], V(g2)[2,1,4,3], V(g2)[2,3,4,1], V(g2)[3,2,1,4], V(g2)[3,4,1,2], V(g2)[4,1,2,3], V(g2)[4,3,2,1]) expect_equivalent(isomorphisms(g, g2), res) g3 <- graph_(from_literal(X - Y - Z - X)) expect_equal(isomorphisms(g, g3), list()) }) test_that("subgraph_isomorphisms, lad", { g <- graph_(from_literal(A - B - C - D - A)) g2 <- graph_(from_literal(Z - X - Y)) res <- list(V(g)[1,4,3], V(g)[1,2,3], V(g)[2,1,4], V(g)[2,3,4], V(g)[3,2,1], V(g)[3,4,1], V(g)[4,3,2], V(g)[4,1,2]) expect_equivalent(subgraph_isomorphisms(g2, g, method = "lad"), res) g3 <- graph_(from_literal(X - Y - Z - X)) expect_equal(subgraph_isomorphisms(g3, g, method = "lad"), list()) }) test_that("subgraph_isomorphisms, vf2", { g <- graph_(from_literal(A - B - C - D - A)) g2 <- graph_(from_literal(Z - X - Y)) res <- list(V(g)[1,2,3], V(g)[1,4,3], V(g)[2,1,4], V(g)[2,3,4], V(g)[3,2,1], V(g)[3,4,1], V(g)[4,1,2], V(g)[4,3,2]) expect_equivalent(subgraph_isomorphisms(g2, g, method = "vf2"), res) g3 <- graph_(from_literal(X - Y - Z - X)) expect_equal(subgraph_isomorphisms(g3, g, method = "vf2"), list()) }) igraph/tests/testthat/test-notable.R0000644000175100001440000000165013177712334017302 0ustar hornikusers context("Notable graphs") test_that("notable graphs work with make_graph", { g <- make_graph("Levi") g2 <- graph.famous("Levi") expect_true(identical_graphs(g, g2)) }) test_that("make_graph for notable graphs is case insensitive", { g <- make_graph("Levi") g2 <- make_graph("levi") expect_true(identical_graphs(g, g2)) }) test_that("spaces are replaced in make_graph for notable graphs", { g <- make_graph("Krackhardt_Kite") g2 <- make_graph("Krackhardt kite") expect_true(identical_graphs(g, g2)) }) test_that("warnings are given for extra arguments in make_graph for notables", { g0 <- make_graph("Levi") expect_warning(g1 <- make_graph("Levi", n = 10)) expect_warning(g2 <- make_graph("Levi", isolates = "foo")) expect_warning(g3 <- make_graph("Levi", directed = FALSE)) expect_true(identical_graphs(g0, g1)) expect_true(identical_graphs(g0, g2)) expect_true(identical_graphs(g0, g3)) }) igraph/tests/testthat/test_graph.de.bruijn.R0000644000175100001440000000057513177712334020725 0ustar hornikusers context("make_de_bruijn_graph") test_that("make_de_bruijn_graph works", { library(igraph) g <- make_de_bruijn_graph(2,1) g2 <- make_de_bruijn_graph(2,2) g3 <- make_line_graph(g) expect_that(graph.isomorphic(g3, graph(c(1,1,3,1,1,2,3,2,2,3, 4,3,2,4,4,4))), is_true()) expect_that(graph.isomorphic(g2, g3), is_true()) }) igraph/tests/testthat/test-new-layout-api.R0000644000175100001440000000203113177712334020523 0ustar hornikusers `%>%` <- magrittr::`%>%` context("New layout API") test_that("two step layouting works", { g <- make_ring(10) l1 <- layout_as_star(g) l2 <- layout_(g, as_star()) expect_identical(l1, l2) }) test_that("parameters go through", { g <- make_ring(10) l1 <- layout_as_star(g, center = 5) l2 <- layout_(g, as_star(center = 5)) expect_identical(l1, l2) }) test_that("parameters are evaluated early", { g <- make_ring(10) l1 <- layout_as_star(g, center = 5) cc <- 5 spec <- as_star(center = cc) cc <- 10 l2 <- layout_(g, spec) expect_identical(l1, l2) }) test_that("piping form is OK, too", { g <- make_ring(10) l1 <- layout_as_star(g, center = 5) l2 <- g %>% layout_(as_star(center = 5)) expect_identical(l1, l2) }) test_that("add_layout_ works", { g <- make_ring(10) l1 <- layout_as_star(g, center = 5) l2 <- add_layout_(g, as_star(center = 5))$layout expect_identical(l1, l2) l3 <- g %>% add_layout_(as_star(center = 5)) %>% graph_attr("layout") expect_identical(l1, l3) }) igraph/tests/testthat/test_scan.R0000644000175100001440000001376213177712334016673 0ustar hornikusers context("Local scan statistics") library(igraph) require(digest) set.seed(12345) n <- 10^3 p <- 0.1 g <- erdos.renyi.game(n,p) E(g)$weight = sample(ecount(g)) gp <- erdos.renyi.game(n,p) E(gp)$weight = sample(ecount(gp)) test_that("General scan-stat works, US, scan-0, unweighted", { s1 <- local_scan(g, k=0) expect_that(digest(s1), equals("659ffaaf303742f0806a79b8ff3d88b3")) }) test_that("General scan-stat works, US, scan-0, weighted", { s1 <- local_scan(g, k=0, weighted=TRUE) expect_that(digest(s1), equals("0f8d7ac831389cea04e0bfc5e2510c73")) }) test_that("General scan-stat works, US, scan-1, unweighted", { s1 <- local_scan(g) expect_that(digest(s1), equals("df0fd77489f70cc47f682dc31d9f52f5")) }) test_that("General scan-stat works, US, scan-1, weighted", { s1 <- local_scan(g, k=1, weighted=TRUE) expect_that(digest(s1), equals("af720916ae4b49881745d2dcdd614401")) }) test_that("General scan-stat works, US, scan-2, unweighted", { s1 <- local_scan(g, k=2) expect_that(digest(s1), equals("6f47f47abde25d00d615dd56826cca5a")) }) test_that("General scan-stat works, US, scan-2, weighted", { s1 <- local_scan(g, k=2, weighted=TRUE) expect_that(digest(s1), equals("e02e9d58168ee5d53850497f6d4c76b0")) }) test_that("General scan-stat works, THEM, scan-0, unweighted", { s1 <- local_scan(g, gp, k=0) expect_that(digest(s1), equals("f584f7d287f8f89f5f7882165ca41b8c")) }) test_that("General scan-stat works, THEM, scan-0, weighted", { s1 <- local_scan(g, gp, k=0, weighted=TRUE) expect_that(digest(s1), equals("213db8e7517d1e6406da3dbd55281ed1")) }) test_that("General scan-stat works, THEM, scan-1, unweighted", { s1 <- local_scan(g, gp, k=1) expect_that(digest(s1), equals("e9ca740ebba2fd1db4abe939954b2638")) }) test_that("General scan-stat works, THEM, scan-1, weighted", { s1 <- local_scan(g, gp, k=1, weighted=TRUE) expect_that(digest(s1), equals("a98e9a03eda7feaae8524dc9348ad74b")) }) test_that("General scan-stat works, THEM, scan-2, unweighted", { s1 <- local_scan(g, gp, k=2) expect_that(digest(s1), equals("a3237a9a55e9d86ab471c81a291eb03b")) }) test_that("General scan-stat works, THEM, scan-2, weighted", { s1 <- local_scan(g, gp, k=2, weighted=TRUE) expect_that(digest(s1), equals("995d0b6a952834ff6e534efc2cfb917b")) }) test_that("Neighborhoods work for us", { nei <- neighborhood(g, order=1) s1 <- local_scan(g, neighborhoods=nei) expect_that(digest(s1), equals("df0fd77489f70cc47f682dc31d9f52f5")) s1 <- local_scan(g, k=1, weighted=TRUE, neighborhoods=nei) expect_that(digest(s1), equals("af720916ae4b49881745d2dcdd614401")) nei <- neighborhood(g, order=2) s1 <- local_scan(g, k=2, neighborhoods=nei) expect_that(digest(s1), equals("6f47f47abde25d00d615dd56826cca5a")) s1 <- local_scan(g, k=2, weighted=TRUE, neighborhoods=nei) expect_that(digest(s1), equals("e02e9d58168ee5d53850497f6d4c76b0")) }) test_that("Neighborhoods work for them", { nei <- neighborhood(g, order=1) s1 <- local_scan(g, gp, k=1, neighborhoods=nei) expect_that(digest(s1), equals("e9ca740ebba2fd1db4abe939954b2638")) s1 <- local_scan(g, gp, k=1, weighted=TRUE, neighborhoods=nei) expect_that(digest(s1), equals("a98e9a03eda7feaae8524dc9348ad74b")) nei <- neighborhood(g, order=2) s1 <- local_scan(g, gp, k=2, neighborhoods=nei) expect_that(digest(s1), equals("a3237a9a55e9d86ab471c81a291eb03b")) s1 <- local_scan(g, gp, k=2, weighted=TRUE, neighborhoods=nei) expect_that(digest(s1), equals("995d0b6a952834ff6e534efc2cfb917b")) }) set.seed(42) n <- 10^3 p <- 0.1 g <- erdos.renyi.game(n, p, directed=TRUE) E(g)$weight = sample(ecount(g)) gp <- erdos.renyi.game(n, p) E(gp)$weight = sample(ecount(gp)) ## US, scan-0, unweighted, directed ## TODO test_that("General scan-stat works, US, scan-1, unweighted, directed", { s1o <- local_scan(g, k=1, weighted=FALSE, mode="out") expect_that(digest(s1o), equals("ac463c21b2b6bc91abf82f0141a4a7d4")) s1i <- local_scan(g, k=1, weighted=FALSE, mode="in") expect_that(digest(s1i), equals("13fdaaeec54118e217821b56d8c3ff03")) }) test_that("General scan-stat works, US, scan-1, weighted, directed", { s1o <- local_scan(g, k=1, weighted=TRUE, mode="out") expect_that(digest(s1o), equals("da8e14f2ba63efc74b5fd7b9d8f79bbc")) s1i <- local_scan(g, k=1, weighted=TRUE, mode="in") expect_that(digest(s1i), equals("f5f07eebb907ae0a244195a20971be11")) }) ## US, scan-2, unweighted, directed ## TODO test_that("Issue 18 is resolved", { library(igraph) g <- graph(c(1,2,2,1, 1,3,3,1, 2,4, 3,4, 3,5,5,3, 4,5,5,4)) expect_that(local_scan(g, mode="all"), equals(c(4, 3, 7, 6, 5))) expect_that(local_scan(g, mode="out"), equals(c(4, 3, 7, 2, 5))) expect_that(local_scan(g, mode="in"), equals(c(4, 2, 4, 6, 5))) }) test_that("Issue 18 is really resolved", { library(igraph) el <- c(1, 5, 1, 7, 2, 5, 2, 7, 2, 10, 2, 13, 2, 18, 3, 5, 3, 10, 3, 13, 4, 5, 4, 10, 5, 7, 5, 10, 5, 13, 5, 18, 6, 3, 6, 5, 6, 7, 6, 13, 7, 5, 8, 5, 8, 10, 8, 18, 9, 3, 9, 5, 9, 7, 9, 10, 11, 5, 12, 5, 12, 7, 14, 5, 14, 7, 14, 13, 14, 18, 15, 5, 15, 13, 15, 18, 16, 5, 16, 10, 16, 13, 16, 18, 17, 5) g <- graph(el) sc1 <- sapply(graph.neighborhood(g, order=1, mode="all"), ecount) sc2 <- local_scan(graph.us=g, mode="all", k=1) expect_that(sc1, equals(sc2)) g2 <- induced.subgraph(g, 5:8) sc21 <- sapply(graph.neighborhood(g2, order=1, mode="all"), ecount) sc22 <- local_scan(graph.us=g2, mode="all", k=1) expect_that(sc21, equals(sc22)) }) test_that("Issue 20 is resolved", { library(igraph) set.seed(12345) g1 <- erdos.renyi.game(n=20, p=0.1, directed=TRUE) g2 <- erdos.renyi.game(n=20, p=0.1, directed=TRUE) ls <- local_scan(g2, g1, k=1, mode="all") correct <- c(4, 1, 2, 1, 1, 8, 1, 2, 0, 5, 2, 3, 3, 4, 5, 3, 5, 4, 2, 1) expect_that(ls, equals(correct)) }) test_that("FUN argument works, #32", { library(igraph) r1 <- local_scan(graph.ring(10), k=1, FUN="ecount") r2 <- local_scan(graph.ring(10), k=1, FUN=ecount) expect_that(r1, equals(rep(2, 10))) expect_that(r2, equals(rep(2, 10))) }) igraph/tests/testthat/test_ba.game.R0000644000175100001440000000405413177712334017233 0ustar hornikusers context("sample_pa") test_that("sample_pa works", { library(igraph) g <- sample_pa(100, m=2) expect_that(ecount(g), equals(197)) expect_that(vcount(g), equals(100)) expect_that(is_simple(g), is_true()) g2 <- sample_pa(100, m=2, algorithm="psumtree-multiple") expect_that(ecount(g2), equals(198)) expect_that(vcount(g2), equals(100)) expect_that(is_simple(g2), is_false()) g3 <- sample_pa(100, m=2, algorithm="bag") expect_that(ecount(g3), equals(198)) expect_that(vcount(g3), equals(100)) expect_that(is_simple(g3), is_false()) }) test_that("sample_pa can start from a graph", { library(igraph) set.seed(1234) g4 <- sample_pa(10, m=1, algorithm="bag", start.graph=make_empty_graph(5)) expect_that(ecount(g4), equals(5)) expect_that(vcount(g4), equals(10)) expect_that(degree(g4), equals(c(2,0,0,0,1,2,1,1,2,1))) g6 <- sample_pa(10, m=1, algorithm="bag", start.graph=make_star(10)) expect_that(graph.isomorphic(g6, make_star(10)), is_true()) g7 <- sample_pa(10, m=3, algorithm="psumtree-multiple", start.graph=make_empty_graph(5)) expect_that(degree(g7, mode="out"), equals(c(0,0,0,0,0, 3,3,3,3,3))) g8 <- sample_pa(10, m=3, algorithm="psumtree-multiple", start.graph=make_star(5)) expect_that(degree(g8, mode="out"), equals(c(0,1,1,1,1, 3,3,3,3,3))) expect_that(graph.isomorphic(induced_subgraph(g8, 1:5), make_star(5)), is_true()) g9 <- sample_pa(10, m=3, algorithm="psumtree-multiple", start.graph=make_star(10)) expect_that(graph.isomorphic(g9, make_star(10)), is_true()) g10 <- sample_pa(10, m=3, start.graph=make_empty_graph(5)) expect_that(degree(g10, mode="out"), equals(c(0,0,0,0,0, 3,3,3,3,3))) g11 <- sample_pa(10, m=3, start.graph=make_star(5)) expect_that(degree(g11, mode="out"), equals(c(0,1,1,1,1, 3,3,3,3,3))) expect_that(graph.isomorphic(induced_subgraph(g11, 1:5), make_star(5)), is_true()) g12 <- sample_pa(10, m=3, start.graph=make_star(10)) expect_that(graph.isomorphic(g12, make_star(10)), is_true()) }) igraph/tests/testthat/test-vs-es-printing.R0000644000175100001440000000710413177712334020543 0ustar hornikusers context("Detailed printing of vs and es") test_that("vs printing", { set.seed(42) g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("weight", value = sample(1:10, 3)) sid <- substr(graph_id(g), 1, 7) o1 <- c( paste0("+ 1/3 vertex, named, from ", sid, ":"), " name color weight", "1 A red 10") expect_output(print(V(g)[[1]]), paste(o1, collapse = "\n"), fixed = TRUE) o2 <- c( paste0("+ 1/3 vertex, named, from ", sid, ":"), " name color weight", "2 B red 9") expect_output(print(V(g)[[2]]), paste(o2, collapse = "\n"), fixed = TRUE) o3 <- c( paste0("+ 2/3 vertices, named, from ", sid, ":"), " name color weight", "1 A red 10", "2 B red 9") expect_output(print(V(g)[[1:2]]), paste(o3, collapse = "\n"), fixed = TRUE) o4 <- c( paste0("+ 2/3 vertices, named, from ", sid, ":"), " name color weight", "2 B red 9", "3 C red 3") expect_output(print(V(g)[[2:3]]), paste(o4, collapse = "\n"), fixed = TRUE) }) test_that("vs printing, complex attributes", { set.seed(42) g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("weight", value = sample(1:10, 3)) %>% set_vertex_attr("cplx", value = replicate(3, 1:4, simplify = FALSE)) sid <- substr(graph_id(g), 1, 7) o1 <- c( paste0("+ 1/3 vertex, named, from ", sid, ":"), "$name", "[1] \"A\"", "", "$color", "[1] \"red\"", "", "$weight", "[1] 10", "", "$cplx", "$cplx[[1]]", "[1] 1 2 3 4", "", "") expect_output(print(V(g)[[1]]), paste(o1, collapse = "\n"), fixed = TRUE) o2 <- c( paste0("+ 2/3 vertices, named, from ", sid, ":"), "$name", "[1] \"B\" \"C\"", "", "$color", "[1] \"red\" \"red\"", "", "$weight", "[1] 9 3", "", "$cplx", "$cplx[[1]]", "[1] 1 2 3 4", "", "$cplx[[2]]", "[1] 1 2 3 4", "", "") expect_output(print(V(g)[[2:3]]), paste(o2, collapse = "\n"), fixed = TRUE) }) test_that("es printing", { set.seed(42) g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_edge_attr("color", value = "red") %>% set_edge_attr("weight", value = sample(1:10, 3)) sid <- substr(graph_id(g), 1, 7) o1 <- c( paste0("+ 1/3 edge from ", sid, " (vertex names):"), " tail head tid hid color weight", "1 A B 1 2 red 10") expect_output(print(E(g)[[1]]), paste(o1, collapse = "\n"), fixed = TRUE) o2 <- c( paste0("+ 2/3 edges from ", sid, " (vertex names):"), " tail head tid hid color weight", "2 A C 1 3 red 9", "3 B C 2 3 red 3") expect_output(print(E(g)[[2:3]]), paste(o2, collapse = "\n"), fixed = TRUE) }) test_that("es printing, complex attributes", { set.seed(42) g <- make_graph(~ A - A:B:C, B - A:B:C) %>% set_edge_attr("color", value = "red") %>% set_edge_attr("weight", value = sample(1:10, 3)) %>% set_edge_attr("cmpx", value = replicate(3, 1:4, simplify = FALSE)) sid <- substr(graph_id(g), 1, 7) o1 <- c( paste0("+ 1/3 edge from ", sid, " (vertex names):"), "$color", "[1] \"red\"", "", "$weight", "[1] 10", "", "$cmpx", "$cmpx[[1]]", "[1] 1 2 3 4", "", "") expect_output(print(E(g)[[1]]), paste(o1, collapse = "\n"), fixed = TRUE) o2 <- c( paste0("+ 2/3 edges from ", sid, " (vertex names):"), "$color", "[1] \"red\" \"red\"", "", "$weight", "[1] 9 3", "", "$cmpx", "$cmpx[[1]]", "[1] 1 2 3 4", "", "$cmpx[[2]]", "[1] 1 2 3 4", "", "") expect_output(print(E(g)[[2:3]]), paste(o2, collapse = "\n"), fixed = TRUE) }) igraph/tests/testthat/test_transitivity.R0000644000175100001440000000172513177712334020514 0ustar hornikusers context("transitivity") test_that("transitivity works", { library(igraph) set.seed(42) g <- sample_gnp(100, p=10/100) t1 <- transitivity(g, type="global") expect_that(t1, equals(0.10483870967741935887)) t2 <- transitivity(g, type="average") expect_that(t2, equals(0.10159943848720931481)) t3 <- transitivity(g, type="local", vids=V(g)) t33 <- transitivity(g, type="local") est3 <- structure(c(0, 0.06667, 0.1028, 0.1016, 0.1333, 0.2222), .Names = c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max."), class = c("summaryDefault", "table")) expect_that(summary(t3), equals(est3, tolerance = 0.001)) expect_that(summary(t33), equals(est3, tolerance = 0.001)) }) test_that("no integer overflow", { library(igraph) set.seed(42) g <- graph.star(80000, mode="undirected") + edges(sample(2:1000), 100) mtr <- min(transitivity(g, type="local"), na.rm=TRUE) expect_true(mtr > 0) }) igraph/tests/testthat/test_get.incidence.R0000644000175100001440000000114213177712334020433 0ustar hornikusers context("as_incidence_matrix") test_that("as_incidence_matrix works", { library(igraph) ## Dense I <- matrix(sample(0:1, 35, replace=TRUE, prob=c(3,1)), nc=5) g <- graph_from_incidence_matrix(I) I2 <- as_incidence_matrix(g) expect_that(I, is_equivalent_to(I2)) expect_that(rownames(I2), equals(as.character(1:7))) expect_that(colnames(I2), equals(as.character(8:12))) ## Sparse I3 <- as_incidence_matrix(g, sparse=TRUE) expect_that(as.matrix(I3), is_equivalent_to(I)) expect_that(rownames(I3), equals(as.character(1:7))) expect_that(colnames(I3), equals(as.character(8:12))) }) igraph/tests/testthat/test_biconnected.components.R0000644000175100001440000000145713177712334022406 0ustar hornikusers context("biconnected_components") test_that("biconnected_components works", { library(igraph) g <- make_full_graph(5) + make_full_graph(5) clu <- components(g)$membership g <- add_edges(g, c(match(1,clu), match(2,clu)) ) sortlist <- function(list) { list <- lapply(list, sort) list <- lapply(list, as.vector) list[order(sapply(list, paste, collapse="x"))] } bc <- biconnected_components(g) expect_that(bc$no, equals(3)) expect_that(sortlist(bc$tree_edges), equals(list(c(11,15,18,20), c(1,5,8,10), 21))) expect_that(sortlist(bc$component_edges), equals(list(11:20, 1:10, 21))) expect_that(sortlist(bc$components), equals(list(1:5, c(1,6), 6:10))) expect_that(sort(as.vector(bc$articulation_points)), equals(c(1,6))) }) igraph/tests/testthat/test_get.edge.R0000644000175100001440000000037313177712334017423 0ustar hornikusers context("ends") test_that("ends works", { library(igraph) g <- sample_gnp(100, 3/100) edges <- unlist(lapply(seq_len(ecount(g)), ends, graph=g)) g2 <- graph(edges, dir=FALSE, n=vcount(g)) expect_that(graph.isomorphic(g, g2), is_true()) }) igraph/tests/testthat/test_sdf.R0000644000175100001440000000273313177712334016517 0ustar hornikusers context("sdf") test_that("sdf works", { library(igraph) sdf <- igraph:::sdf `[.igraphSDF` <- igraph:::`[.igraphSDF` `[<-.igraphSDF` <- igraph:::`[<-.igraphSDF` as.data.frame.igraphSDF <- igraph:::as.data.frame.igraphSDF sdf <- sdf(id=1:10, color="black") expect_that(as.data.frame(sdf), equals(data.frame(id=1:10, color="black"))) ## access expect_that(sdf[1,"id"], equals(1)) expect_that(sdf[1:4, "id"], equals(1:4)) expect_that(sdf[, "id"], equals(1:10)) expect_that(sdf[1, "color"], equals("black")) expect_that(sdf[1:4, "color"], equals(rep("black", 4))) expect_that(sdf[, "color"], equals(rep("black", 10))) ## set sdf2 <- sdf sdf2[5, "id"] <- 100 expect_that(as.data.frame(sdf2), equals(data.frame(id=c(1:4,100,6:10), color="black"))) sdf2 <- sdf sdf2[, "id"] <- 0 expect_that(as.data.frame(sdf2), equals(data.frame(id=rep(0,10), color="black"))) sdf2 <- sdf sdf2[2:10, "id"] <- 1 expect_that(as.data.frame(sdf2), equals(data.frame(id=rep(1,10), color="black"))) sdf2 <- sdf sdf2[, "color"] <- "white" expect_that(as.data.frame(sdf2), equals(data.frame(id=1:10, color="white"))) sdf2 <- sdf sdf2[5:6, "color"] <- "white" expect_that(as.data.frame(sdf2), equals(data.frame(id=1:10, color=c(rep("black", 4), rep("white", 2), rep("black", 4))))) }) igraph/tests/testthat/test_edge.betweenness.R0000644000175100001440000000222613177712334021165 0ustar hornikusers context("edge_betweenness") test_that("edge_betweenness works", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) bet <- betweenness(kite) ebet <- edge_betweenness(kite) bet2 <- sapply(1:vcount(kite), function(x) { ae <- E(kite)[ .inc(x) ] (sum(ebet[ae])-vcount(kite)+1) / 2 }) expect_that(unname(bet), equals(bet2)) #### Weighted E(kite)$weight <- sample(1:10, ecount(kite), replace=TRUE) bet <- betweenness(kite) ebet <- edge_betweenness(kite) bet2 <- sapply(1:vcount(kite), function(x) { ae <- E(kite)[ .inc(x) ] (sum(ebet[ae])-vcount(kite)+1) / 2 }) expect_that(unname(bet), equals(bet2)) }) igraph/tests/testthat/test_largest.independent.vertex.sets.R0000644000175100001440000000060513177712334024165 0ustar hornikusers context("largest_ivs") test_that("largest_ivs works", { library(igraph) g <- sample_gnp(50, 0.8) livs <- largest_ivs(g) expect_that(unique(sapply(livs, length)), equals(ivs_size(g))) ec <- sapply(seq_along(livs), function(x) ecount(induced_subgraph(g, livs[[x]]))) expect_that(unique(ec), equals(0)) ## TODO: check that they are largest }) igraph/tests/testthat/test_graph.bfs.R0000644000175100001440000000160313177712334017610 0ustar hornikusers context("BFS") test_that("BFS works from multiple root vertices", { library(igraph) g <- make_ring(10) %du% make_ring(10) expect_that(as.vector(bfs(g, 1)$order), equals(c(1,2,10,3,9,4,8,5,7,6,11,12,20,13,19,14,18,15,17,16))) expect_that(as.vector(bfs(g, 1, unreachable=FALSE)$order), equals(c(1,2,10,3,9,4,8,5,7,6,rep(NaN, 10)))) expect_that(as.vector(bfs(g,c(1, 12), unreachable=FALSE)$order), equals(c(1,2,10,3,9,4,8,5,7,6,12,11,13,20,14,19,15,18,16,17))) expect_that(as.vector(bfs(g,c(12, 1, 15), unreachable=FALSE)$order), equals(c(12,11,13,20,14,19,15,18,16,17,1,2,10,3,9,4,8,5,7,6))) }) test_that("issue 133", { g <- graph_from_edgelist(matrix(c(1,2,2,3), ncol = 2, byrow = TRUE)) expect_equal( bfs(g, 1, restricted = c(1, 2), unreachable = FALSE)$order, V(g)[c(1, 2, NA_real_), na_ok = TRUE] ) }) igraph/tests/testthat/test_constraint.R0000644000175100001440000000231513177712334020123 0ustar hornikusers context("constraint") test_that("constraint works", { library(igraph) constraint.orig <- function(graph, nodes=V(graph), attr=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } idx <- degree(graph) != 0 A <- as_adj(graph, attr=attr, sparse=FALSE) A <- A[idx, idx] n <- sum(idx) one <- c(rep(1,n)) CZ <- A + t(A) cs <- CZ %*% one # degree of vertices ics <- 1/cs CS <- ics %*% t(one) # 1/degree of vertices P <- CZ * CS #intermediate result: proportionate tie strengths PSQ <- P%*%P #sum paths of length two P.bi <- as.numeric(P>0) #exclude paths to non-contacts (& reflexive): PC <- (P + (PSQ*P.bi))^2 #dyadic constraint ci <- PC %*% one #overall constraint dim(ci) <- NULL ci2 <- numeric(vcount(graph)) ci2[idx] <- ci ci2[!idx] <- NaN ci2[nodes] } karate <- make_graph("Zachary") c1 <- constraint(karate) c2 <- constraint.orig(karate) expect_that(c1, equals(c2)) set.seed(42) E(karate)$weight <- sample(1:10, replace=TRUE, ecount(karate)) wc1 <- constraint(karate) wc2 <- constraint.orig(karate, attr="weight") expect_that(wc1, equals(wc2)) }) igraph/tests/testthat/test_triangles.R0000644000175100001440000000260113177712334017725 0ustar hornikusers context("Triangles") test_that("Listing triangles works", { triangles <- function(...) as.vector(igraph::triangles(...)) g1 <- make_empty_graph(directed=TRUE) g2 <- make_empty_graph(directed=FALSE) expect_that(triangles(g1), equals(numeric())) expect_that(triangles(g2), equals(numeric())) g3 <- make_empty_graph(n=1, directed=TRUE) g4 <- make_empty_graph(n=1, directed=FALSE) expect_that(triangles(g3), equals(numeric())) expect_that(triangles(g4), equals(numeric())) g5 <- make_empty_graph(n=100, directed=TRUE) g6 <- make_empty_graph(n=100, directed=FALSE) expect_that(triangles(g5), equals(numeric())) expect_that(triangles(g6), equals(numeric())) g7 <- make_ring(3, directed=FALSE) g8 <- make_ring(3, directed=TRUE) g9 <- graph_from_literal(A-+B:C, B-+C) expect_that(sort(triangles(g7)), equals(1:3)) expect_that(sort(triangles(g8)), equals(1:3)) expect_that(sort(triangles(g9)), equals(1:3)) g10 <- make_full_graph(5, directed=FALSE) g11 <- make_full_graph(5, directed=TRUE) r10 <- c(1L, 2L, 5L, 1L, 2L, 3L, 1L, 2L, 4L, 1L, 3L, 5L, 1L, 3L, 4L, 1L, 4L, 5L, 2L, 3L, 5L, 2L, 3L, 4L, 2L, 4L, 5L, 3L, 4L, 5L) r11 <- c(1L, 2L, 5L, 1L, 2L, 4L, 1L, 2L, 3L, 1L, 3L, 5L, 1L, 3L, 4L, 1L, 4L, 5L, 2L, 4L, 5L, 2L, 3L, 5L, 2L, 3L, 4L, 3L, 4L, 5L) expect_that(triangles(g10), equals(r10)) expect_that(triangles(g11), equals(r11)) }) igraph/tests/testthat/test_alpha.centrality.R0000644000175100001440000000501313177712334021177 0ustar hornikusers context("alpha_centrality") test_that("dense alpha_centrality works", { library(igraph) g.1 <- graph( c(1,3,2,3,3,4,4,5) ) ac1 <- alpha_centrality(g.1, sparse=FALSE) expect_that(ac1, equals(c(1, 1, 3, 4, 5))) g.2 <- graph( c(2,1,3,1,4,1,5,1) ) ac2 <- alpha_centrality(g.2, sparse=FALSE) expect_that(ac2, equals(c(5,1,1,1,1))) g.3 <- graph( c(1,2,2,3,3,4,4,1,5,1) ) ac3 <- alpha_centrality(g.3, alpha=0.5, sparse=FALSE) expect_that(ac3, equals(c(76, 68, 64, 62, 30)/30)) }) test_that("sparse alpha_centrality works", { if (require(Matrix, quietly=TRUE)) { library(igraph) g.1 <- graph( c(1,3,2,3,3,4,4,5) ) ac1 <- alpha_centrality(g.1, sparse=TRUE) expect_that(ac1, equals(c(1, 1, 3, 4, 5))) g.2 <- graph( c(2,1,3,1,4,1,5,1) ) ac2 <- alpha_centrality(g.2, sparse=TRUE) expect_that(ac2, equals(c(5,1,1,1,1))) g.3 <- graph( c(1,2,2,3,3,4,4,1,5,1) ) ac3 <- alpha_centrality(g.3, alpha=0.5, sparse=TRUE) expect_that(ac3, equals(c(76, 68, 64, 62, 30)/30)) } }) ############################## ## weighted version test_that("weighted dense alpha_centrality works", { library(igraph) star <- make_star(10) E(star)$weight <- sample(ecount(star)) ac1 <- alpha_centrality(star, sparse=FALSE) expect_that(ac1, equals(c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))) ac2 <- alpha_centrality(star, weights="weight", sparse=FALSE) expect_that(ac2, equals(c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))) ac3 <- alpha_centrality(star, weights=NA, sparse=FALSE) expect_that(ac3, equals(c(vcount(star), 1, 1, 1, 1, 1, 1, 1, 1, 1))) }) test_that("weighted sparse alpha_centrality works", { if (require("Matrix", quietly=TRUE)) { library(igraph) star <- make_star(10) E(star)$weight <- sample(ecount(star)) ac1 <- alpha_centrality(star, sparse=TRUE) expect_that(ac1, equals(c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))) ac2 <- alpha_centrality(star, weights="weight", sparse=TRUE) expect_that(ac2, equals(c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))) ac3 <- alpha_centrality(star, weights=NA, sparse=TRUE) expect_that(ac3, equals(c(vcount(star), 1, 1, 1, 1, 1, 1, 1, 1, 1))) } }) test_that("undirected, alpha centrality works, #653", { if (require("Matrix", quietly = TRUE)) { library(igraph) g <- make_ring(10) ac1 <- alpha_centrality(g, sparse = TRUE) ac2 <- alpha_centrality(g, sparse = FALSE) expect_that(ac1, equals(ac2)) g2 <- as.directed(g, mode="mutual") ac3 <- alpha_centrality(g, sparse = FALSE) expect_that(ac1, equals(ac3)) } }) igraph/tests/testthat/test_graph.data.frame.R0000644000175100001440000000240713177712334021043 0ustar hornikusers context("graph_from_data_frame") test_that("graph_from_data_frame works", { library(igraph) ; igraph_options(print.full=TRUE) actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David", "Esmeralda"), age=c(48,33,45,34,21), gender=c("F","M","F","M","F"), stringsAsFactors=FALSE) relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", "David", "Esmeralda"), to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE), friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3), stringsAsFactors=FALSE) g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors) df <- as_data_frame(g, what="both") expect_that(df$vertices, is_equivalent_to(actors)) expect_that(df$edges, equals(relations)) }) test_that("graph_from_data_frame works on matrices", { library(igraph) el <- cbind(1:5,5:1,weight=1:5) g <- graph_from_data_frame(el) g <- delete_vertex_attr(g, "name") el2 <- as_data_frame(g) expect_that(as.data.frame(el), is_equivalent_to(el2)) }) igraph/tests/testthat/test_label.propagation.community.R0000644000175100001440000000152213177712334023362 0ustar hornikusers context("cluster_label_prop") test_that("label.probagation.community works", { library(igraph) g <- make_graph("Zachary") set.seed(42) lpc <- cluster_label_prop(g) expect_that(lpc$modularity, equals(modularity(g, lpc$membership))) expect_that(as.vector(membership(lpc)), equals(c(1, 1, 2, 1, 3, 3, 3, 1, 2, 2, 3, 1, 1, 1, 2, 2, 3, 1, 2, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2))) expect_that(length(lpc), equals(3)) expect_that(sizes(lpc), equals(structure(c(10L, 19L, 5L), .Dim = 3L, .Dimnames = structure(list(`Community sizes` = c("1", "2", "3")), .Names = "Community sizes"), class = "table"))) }) igraph/tests/testthat/test-versions.R0000644000175100001440000000067213177712334017531 0ustar hornikusers context("Data version and conversion") test_that("we create graphs of the current version", { g <- make_ring(10) v1 <- graph_version(g) v2 <- graph_version() expect_equal(v1, v2) }) test_that("we can upgrade from 0.4.0 to 0.8.0", { g <- make_ring(10) g <- unclass(g) g[[10]] <- NULL class(g) <- "igraph" expect_equal(graph_version(g), "0.4.0") g2 <- upgrade_graph(g) expect_equal(graph_version(g2), "0.8.0") }) igraph/tests/testthat/test-make_graph.R0000644000175100001440000000217513177712334017757 0ustar hornikusers context("make_graph") test_that("make_graph works", { g <- make_graph(1:10) g2 <- make_empty_graph(n = 10) + edges(1:10) expect_true(identical_graphs(g, g2)) }) test_that("make_graph works for numeric edges and isolates", { g <- make_graph(1:10, n = 20) g2 <- make_empty_graph(n = 20) + edges(1:10) expect_true(identical_graphs(g, g2)) }) test_that("make_graph handles names", { g <- make_graph(letters[1:10]) g2 <- make_empty_graph() + vertices(letters[1:10]) + edges(letters[1:10]) expect_true(identical_graphs(g, g2)) }) test_that("make_graph hadles names and isolates", { g <- make_graph(letters[1:10], isolates = letters[11:20]) g2 <- make_empty_graph() + vertices(letters[1:20]) + edges(letters[1:10]) expect_true(identical_graphs(g, g2)) }) test_that("make_graph gives warning for ignored arguments", { expect_warning( make_graph(letters[1:10], n = 10) ) expect_warning( make_graph(1:10, isolates = 11:12) ) }) test_that("a make_graph bug is fixed", { E <- cbind(1, 3) d <- 3 g <- graph(as.vector(t(E)), d, FALSE) expect_equal(vcount(g), 3) expect_equal(ecount(g), 1) }) igraph/tests/testthat/test_authority.score.R0000644000175100001440000000312613247101612021067 0ustar hornikusers context("authority_score") test_that("authority score works", { library(igraph) ashs <- function(graph, as=TRUE) { mscale <- function(x) { if (sd(x)!=0) { x <- scale(x) } if (x[1] < 0) { x <- -x } x } A <- as_adj(graph, sparse=FALSE) if (as) { s1 <- eigen(t(A) %*% A)$vectors[,1] s2 <- authority_score(graph)$vector } else { s1 <- eigen(A %*% t(A))$vectors[,1] s2 <- hub_score(graph)$vector } expect_that(mscale(s1), is_equivalent_to(mscale(s2))) } g1 <- sample_pa(100, m=10) ashs(g1) ashs(g1, as=FALSE) g2 <- sample_gnp(100, 2/100) ashs(g2) ashs(g2, as=FALSE) }) test_that("authority scores of a ring are all one", { library(igraph) g3 <- make_ring(100) expect_that(authority_score(g3)$vector, equals(rep(1, vcount(g3)))) expect_that(hub_score(g3)$vector, equals(rep(1, vcount(g3)))) }) test_that("authority_score survives stress test", { skip_on_cran() set.seed(42) is.principal <- function(M, lambda) { expect_that(eigen(M)$values[1], equals(lambda)) } is.ev <- function(M, v, lambda) { expect_that(as.vector(M %*% v), equals(lambda * v)) } is.good <- function(M, v, lambda) { is.principal(M, lambda) is.ev(M, v, lambda) } for (i in 1:100) { G <- sample_gnm(10, sample(1:20, 1)) as <- authority_score(G) M <- as_adj(G, sparse = FALSE) is.good(t(M) %*% M, as$vector, as$value) } for (i in 1:100) { G <- sample_gnm(10, sample(1:20, 1)) hs <- hub_score(G) M <- as_adj(G, sparse = FALSE) is.good(M %*% t(M), hs$vector, hs$value) } }) igraph/tests/testthat/test_as.directed.R0000644000175100001440000000212113177712334020117 0ustar hornikusers context("as.directed") test_that("as.directed works", { library(igraph) g <- sample_gnp(100, 2/100) g2 <- as.directed(g, mode="mutual") g3 <- as.directed(g, mode="arbitrary") expect_that(degree(g), equals(degree(g3))) expect_that(degree(g), equals(degree(g2) / 2)) expect_that(graph.isomorphic(g, as.undirected(g2)), is_true()) expect_that(graph.isomorphic(g, as.undirected(g3)), is_true()) }) test_that("as.directed keeps attributes", { library(igraph) g <- graph_from_literal( A-B-C, D-A, E ) g$name <- "Small graph" g2 <- as.directed(g, mode="mutual") g3 <- as.directed(g, mode="arbitrary") expect_that(g2$name, equals(g$name)) expect_that(V(g2)$name, equals(V(g)$name)) expect_that(g3$name, equals(g$name)) expect_that(V(g3)$name, equals(V(g)$name)) E(g)$weight <- seq_len(ecount(g)) g4 <- as.directed(g, "mutual") ; df4 <- as_data_frame(g4) g5 <- as.directed(g, "arbitrary") ; df5 <- as_data_frame(g5) expect_that(df4[order(df4[,1], df4[,2]),]$weight, equals(c(1,2,1,3,3,2))) expect_that(df5[order(df5[,1], df5[,2]),]$weight, equals(1:3)) }) igraph/tests/testthat/test_igraph.options.R0000644000175100001440000000200613562543101020670 0ustar hornikusers context("igraph_options") test_that("igraph_options works", { library(igraph) igraph_options(verbose=TRUE) expect_that(igraph_opt("verbose"), is_true()) igraph_options(verbose=FALSE) expect_that(igraph_opt("verbose"), is_false()) }) test_that("we can restore old options", { old_1 <- igraph_opt("sparsematrices") old_2 <- igraph_opt("annotate.plot") old <- igraph_options(sparsematrices = FALSE, annotate.plot = TRUE) expect_equal(igraph_opt("sparsematrices"), FALSE) expect_equal(igraph_opt("annotate.plot"), TRUE) igraph_options(old) expect_equal(igraph_opt("sparsematrices"), old_1) expect_equal(igraph_opt("annotate.plot"), old_2) }) test_that("with_igraph_opt works", { on.exit(try(igraph_options(old)), add = TRUE) old <- igraph_options(sparsematrices = TRUE) res <- with_igraph_opt(list(sparsematrices = FALSE), make_ring(3)[]) expect_equal(igraph_opt("sparsematrices"), TRUE) expect_equal(class(res)[1], "matrix") }) igraph/tests/testthat/test_communities.R0000644000175100001440000000652613247054413020276 0ustar hornikusers context("communities") test_that("community detection functions work", { library(igraph) set.seed(42) F <- list("cluster_edge_betweenness", "cluster_fast_greedy", "cluster_label_prop", "cluster_leading_eigen", "cluster_louvain", "cluster_spinglass", "cluster_walktrap") if (has_glpk()) F <- c(F, list("cluster_optimal")) karate <- make_graph("Zachary") for (f in F) { f <- get(f) comm <- f(karate) expect_that(modularity(comm), equals(modularity(karate, membership(comm)))) cc <- communities(comm) expect_that(all(!duplicated(unlist(cc))), is_true()) expect_that(all(unlist(cc) <= vcount(karate) & unlist(cc) >= 1), is_true()) expect_that(length(comm), equals(max(membership(comm)))) } fc <- cluster_fast_greedy(karate) m1 <- modularity(karate, cut_at(fc, no=1)) m2 <- modularity(karate, cut_at(fc, no=2)) m3 <- modularity(karate, cut_at(fc, no=3)) m4 <- modularity(karate, cut_at(fc, no=4)) expect_that(m1, equals(0)) expect_that(m2, equals(0.3717948718)) expect_that(m3, equals(0.3806706114)) expect_that(m4, equals(0.3759861933)) cr <- crossing(fc, karate) expect_that(cr, equals(c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE) )) }) test_that("creating communities objects works", { library(igraph) set.seed(42) karate <- make_graph("Zachary") membership <- sample(1:2, vcount(karate), replace=TRUE) mod <- modularity(karate, membership) comm <- make_clusters(algorithm="random", membership=membership, modularity = mod) expect_that(as.vector(membership(comm)), equals(membership)) expect_that(modularity(comm), equals(mod)) expect_that(algorithm(comm), equals("random")) }) test_that("communities function works", { skip_if_no_glpk() library(igraph) g <- make_graph("Zachary") oc <- cluster_optimal(g) gr <- communities(oc) expect_that(gr, equals (structure(list(`1` = c(1L, 2L, 3L, 4L, 8L, 12L, 13L, 14L, 18L, 20L, 22L), `2` = c(5L, 6L, 7L, 11L, 17L), `3` = c(9L, 10L, 15L, 16L, 19L, 21L, 23L, 27L, 30L, 31L, 33L, 34L), `4` = c(24L, 25L, 26L, 28L, 29L, 32L)), .Dim = 4L, .Dimnames = list(c("1", "2", "3", "4"))))) g <- make_ring(5) + make_ring(5) V(g)$name <- letters[1:10] oc <- cluster_optimal(g) gr <- communities(oc) expect_that(gr, equals(structure(list(`1` = letters[1:5], `2` = letters[6:10]), .Dim = 2L, .Dimnames = list(c("1", "2"))))) }) igraph/tests/testthat/helper.R0000644000175100001440000000033313247054347016156 0ustar hornikusers has_glpk <- function() { glpk <- TRUE tryCatch( cluster_optimal(make_ring(10)), error = function(e) glpk <<- FALSE ) glpk } skip_if_no_glpk <- function() { if (!has_glpk()) skip("No GLPK library") } igraph/tests/testthat/test_correlated.R0000644000175100001440000000371213177712334020065 0ustar hornikusers context("Correlated E-R random graphs") ## Not very meaningful tests. They good for testing that the ## functions run, but not much more test_that("sample_correlated_gnp works", { library(igraph) set.seed(42) g <- erdos.renyi.game(10, .1) g2 <- sample_correlated_gnp(g, corr=1, p=g$p, perm=NULL) expect_that(g[], equals(g2[])) g3 <- sample_correlated_gnp(g, corr=0, p=g$p, perm=NULL) c3 <- cor(as.vector(g[]), as.vector(g3[])) expect_that(abs(c3) < .3, is_true()) }) test_that("sample_correlated_gnp_pair works", { library(igraph) set.seed(42) gp <- sample_correlated_gnp_pair(10, corr=.95, p=.1, perm=NULL) expect_that(abs(ecount(gp[[1]]) - ecount(gp[[2]])) < 3, is_true()) }) ## Some corner cases test_that("sample_correlated_gnp corner cases work", { library(igraph) set.seed(42) is.full <- function(g) { g2 <- graph.full(vcount(g), directed=is.directed(g)) graph.isomorphic(g, g2) } g <- erdos.renyi.game(10, .3) g2 <- sample_correlated_gnp(g, corr=0.000001, p=.99999999) expect_that(is.full(g2), is_true()) g3 <- sample_correlated_gnp(g, corr=0.000001, p=0.0000001) expect_that(ecount(g3), equals(0)) expect_that(vcount(g3), equals(10)) gg <- erdos.renyi.game(10, .3, directed=TRUE) gg2 <- sample_correlated_gnp(gg, corr=0.000001, p=.99999999) expect_that(is.full(gg2), is_true()) gg3 <- sample_correlated_gnp(gg, corr=0.000001, p=0.0000001) expect_that(ecount(gg3), equals(0)) expect_that(vcount(gg3), equals(10)) }) test_that("permutation works for sample_correlated_gnp", { library(igraph) set.seed(42) g <- erdos.renyi.game(10, .3) perm <- sample(vcount(g)) g2 <- sample_correlated_gnp(g, corr=.99999, p=.3, permutation=perm) g <- permute.vertices(g, perm) expect_that(g[], equals(g2[])) g <- erdos.renyi.game(10, .3) perm <- sample(vcount(g)) g2 <- sample_correlated_gnp(g, corr=1, p=.3, permutation=perm) g <- permute.vertices(g, perm) expect_that(g[], equals(g2[])) }) igraph/tests/testthat/test_average.path.length.R0000644000175100001440000000155113177712334021565 0ustar hornikusers context("mean_distance") test_that("mean_distance works", { library(igraph) apl <- function(graph) { sp <- distances(graph, mode="out") if (is_directed(graph)) { diag(sp) <- NA } else { sp[lower.tri(sp, diag=TRUE)] <- NA } sp[sp=="Inf"] <- NA mean(sp, na.rm=TRUE) } giant.component <- function(graph, mode="weak") { clu <- components(graph, mode=mode) induced_subgraph(graph, which(clu$membership==which.max(clu$csize))) } g <- giant.component(sample_gnp(100, 3/100)) expect_that(apl(g), equals(mean_distance(g))) g <- giant.component(sample_gnp(100, 6/100, dir=TRUE), mode="strong") expect_that(apl(g), equals(mean_distance(g))) g <- sample_gnp(100, 2/100) expect_that(apl(g), equals(mean_distance(g))) g <- sample_gnp(100, 4/100, dir=TRUE) expect_that(apl(g), equals(mean_distance(g))) }) igraph/tests/testthat/test_edge.connectivity.R0000644000175100001440000000251113177712334021356 0ustar hornikusers context("edge_connectivity") test_that("edge_connectivity works", { library(igraph) gc <- function(graph) { clu <- components(graph) induced_subgraph(graph, which(clu$membership==which.max(clu$csize))) } g <- gc(sample_gnp(30, 8/30)) ec <- edge_connectivity(g) ecST <- Inf for (j in 1:(vcount(g)-1)) { for (k in (j+1):vcount(g)) { ec2 <- edge_connectivity(g, source=j, target=k) if (ec2 < ecST) { ecST <- ec2 } } } expect_that(ec, equals(ecST)) #### kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) ec1 <- edge_connectivity(kite, source="Heather", target="Andre") ec2 <- edge_connectivity(kite, source="Garth", target="Andre") ec3 <- edge_connectivity(kite, source="Garth", target="Ike") expect_that(ec1, equals(2)) expect_that(ec2, equals(4)) expect_that(ec3, equals(1)) }) igraph/tests/testthat/test_graph.atlas.R0000644000175100001440000000065013177712334020143 0ustar hornikusers context("graph.atlas") test_that("graph.atlas works", { library(igraph) g124 <- graph.atlas(124) expect_that(graph.isomorphic(g124, graph(c(1,2,2,3,3,4,4,5,1,5,1,3,2,6), directed=FALSE)), is_true()) g234 <- graph.atlas(234) expect_that(graph.isomorphic(g234, graph(c(1,6,2,6,3,6,4,6,5,6), n=7, directed=FALSE)), is_true()) }) igraph/tests/testthat/test_operators.R0000644000175100001440000000272113177712334017756 0ustar hornikusers context("operators") test_that("operators work", { library(igraph) o <- function(x) x[order(x[,1], x[,2]),] g1 <- make_ring(10) g2 <- make_star(11, center=11, mode="undirected") gu <- union(g1, g2) expect_that(vcount(gu), equals(11)) expect_that(ecount(gu), equals(20)) expect_that(o(rbind(as_edgelist(g1), as_edgelist(g2))), equals(o(as_edgelist(gu)))) gdu <- disjoint_union(g1, g2) expect_that(o(as_edgelist(gdu)), equals(o(rbind(as_edgelist(g1), as_edgelist(g2)+vcount(g1))))) #### expect_that(graph.isomorphic(difference(gu, g1), g2), is_true()) #### expect_that(graph.isomorphic(intersection(gu, g2), g2), is_true()) expect_that(graph.isomorphic(intersection(gu, g1, keep.all.vertices=FALSE), g1),is_true()) #### x <- complementer(complementer(g2)) expect_true(identical_graphs(x, g2)) #### gc <- compose(gu, g1) expect_that(vcount(gc), equals(11)) expect_that(ecount(gc), equals(60)) expect_that(diameter(gc), equals(2)) }) test_that("Union of directed named graphs", { graphs <- list( make_graph( ~1:2:3:4:5, 1-+2, 1-+3, 2-+3, 2-+4, 3-+4, 1-+5, 3-+5), make_graph( ~1:2:3:4:5, 2-+3, 1-+4, 2-+4, 3-+4, 2-+5, 3-+5), make_graph( ~1:2:3:4:5, 1-+2, 1-+3, 2-+4, 3-+4, 1-+5, 4-+5) ) gg <- graph.union(graphs) expect_equal(vcount(gg), 5) expect_equal(ecount(gg), 10) }) igraph/tests/testthat/test_indexing.R0000644000175100001440000002233013177712334017543 0ustar hornikusers context("Indexing") mm <- function(...) { v <- as.numeric(as.vector(list(...))) matrix(v, nrow=sqrt(length(v))) } am <- function(x) { x <- as.matrix(x) dimnames(x) <- NULL x } library(igraph) library(Matrix, quietly=TRUE, warn.conflicts=FALSE) g <- make_tree(20) test_that("[ indexing works", { ## Are these vertices connected? expect_that(g[1,2], equals(1)) expect_that(am(g[c(1,1,7), c(2,3,14)]), equals(mm(1,1,0, 1,1,0, 0,0,1))) expect_that(am(g[c(1,1,7), c(5,3,12)]), equals(mm(0,0,0, 1,1,0 ,0,0,0))) expect_that(am(g[c(1,1,1,1), c(2,3,2,2)]), equals(matrix(1, 4, 4))) expect_that(am(g[c(8,17), c(17,8)]), equals(mm(1,0, 0,0))) }) V(g)$name <- letters[1:vcount(g)] test_that("[ indexing works with symbolic names", { ## The same with symbolic names expect_that(g['a','b'], equals(1)) expect_that(am(g[c('a','a','g'), c('b','c','n')]), equals(mm(1,1,0, 1,1,0, 0,0,1))) expect_that(am(g[c('a','a','g'), c('e','c','l')]), equals(mm(0,0,0, 1,1,0, 0,0,0))) expect_that(am(g[c('a','a','a','a'), c('b','c','b','b')]), equals(matrix(1, 4, 4))) expect_that(am(g[c('h','q'), c('q','h')]), equals(mm(1,0, 0,0))) }) test_that("[ indexing works with logical vectors", { ## Logical vectors lres <- structure(c(0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(2L, 20L), .Dimnames = list(c("b", "c"), c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"))) expect_that(g[degree(g,mode="in")==0,2], equals(1)) expect_that(as.matrix(g[2:3,TRUE]), equals(lres)) }) test_that("[ indexing works with negative indices", { ## Negative indices nres <- structure(c(0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(2L, 19L), .Dimnames=list(c("b", "c"), c("b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t"))) expect_that(as.matrix(g[2:3,-1]), equals(nres)) }) el <- as_edgelist(g, names=FALSE) E(g)$weight <- el[,1] * el[,2] test_that("[ indexing works with weighted graphs", { ## Weighted graphs expect_that(g[1,2], equals(2)) expect_that(am(g[c(1,1,7), c(2,3,14)]), equals(mm(2,2,0, 3,3,0, 0,0,98))) expect_that(am(g[c(1,1,7), c(5,3,12)]), equals(mm(0,0,0, 3,3,0, 0,0,0))) expect_that(am(g[c(1,1,1,1), c(2,3,2,2)]), equals(mm(2,2,2,2, 3,3,3,3, 2,2,2,2, 2,2,2,2))) expect_that(am(g[c(8,17), c(17,8)]), equals(mm(136,0, 0,0))) }) test_that("[ indexing works with weighted graphs and symbolic names", { ## Weighted graph, with symbolic names expect_that(g['a','b'], equals(2)) expect_that(am(g[c('a','a','g'), c('b','c','n')]), equals(mm(2,2,0, 3,3,0, 0,0,98))) expect_that(am(g[c('a','a','g'), c('e','c','l')]), equals(mm(0,0,0, 3,3,0, 0,0,0))) expect_that(am(g[c('a','a','a','a'), c('b','c','b','b')]), equals(mm(2,2,2,2, 3,3,3,3, 2,2,2,2, 2,2,2,2))) expect_that(am(g[c('h','q'), c('q','h')]), equals(mm(136,0, 0,0))) }) ################################################################ test_that("[[ indexing works", { ## Adjacent vertices expect_that(g[[1, ]], is_equivalent_to(list(a=V(g)[2:3]))) expect_that(g[[, 2]], is_equivalent_to(list(b=V(g)[1]))) expect_that(g[[, 2, directed=FALSE]], is_equivalent_to(list(b=V(g)[c(1,4,5)]))) expect_that(g[[2, directed=FALSE]], is_equivalent_to(list(b=V(g)[c(1,4,5)]))) expect_that(g[[1:3, ]], is_equivalent_to(list(a=V(g)[2:3], b=V(g)[4:5], c=V(g)[6:7]))) expect_that(g[[, 1:3]], is_equivalent_to(list(a=V(g)[numeric()], b=V(g)[1], c=V(g)[1]))) }) test_that("[[ indexing works with symbolic names", { ## Same with vertex names expect_that(g[['a', ]], is_equivalent_to(list(a=V(g)[2:3]))) expect_that(g[[, 'b']], is_equivalent_to(list(b=V(g)[1]))) expect_that(g[[, 'b', directed=FALSE]], is_equivalent_to(list(b=V(g)[c(1,4,5)]))) expect_that(g[['b', directed=FALSE]], is_equivalent_to(list(b=V(g)[c(1,4,5)]))) expect_that(g[[letters[1:3],]], is_equivalent_to(list(a=V(g)[2:3], b=V(g)[4:5], c=V(g)[6:7]))) expect_that(g[[, letters[1:3]]], is_equivalent_to(list(a=V(g)[numeric()], b=V(g)[1], c=V(g)[1]))) }) test_that("[[ indexing works with logical vectors", { ## Logical vectors expect_that(g[[degree(g,mode="in")==0,]], is_equivalent_to(list(a=V(g)[2:3]))) }) test_that("[[ indexing works with filtering on both ends", { ## Filtering on both ends expect_that(g[[1:10, 1:10]], is_equivalent_to(list(a=V(g)[2:3], b=V(g)[4:5], c=V(g)[6:7], d=V(g)[8:9], e=V(g)[10], f=V(g)[numeric()], g=V(g)[numeric()], h=V(g)[numeric()], i=V(g)[numeric()], j=V(g)[numeric()]))) }) ################################################################ test_that("[ can query edge ids", { ## Query edge ids expect_that(g[1,2, edges=TRUE], equals(1)) expect_that(am(g[c(1,1,7), c(2,3,14), edges=TRUE]), equals(mm(1,1,0, 2,2,0, 0,0,13))) expect_that(am(g[c(1,1,7), c(5,3,12), edges=TRUE]), equals(mm(0,0,0, 2,2,0, 0,0,0))) expect_that(am(g[c(1,1,1,1), c(2,3,2,2), edges=TRUE]), equals(mm(1,1,1,1, 2,2,2,2, 1,1,1,1, 1,1,1,1))) expect_that(am(g[c(8,17), c(17,8), edges=TRUE]), equals(mm(16,0, 0,0))) }) test_that("[ can query edge ids with symbolic names", { ## The same with symbolic names expect_that(g['a','b', edges=TRUE], equals(1)) expect_that(am(g[c('a','a','g'), c('b','c','n'), edges=TRUE]), equals(mm(1,1,0, 2,2,0, 0,0,13))) expect_that(am(g[c('a','a','g'), c('e','c','l'), edges=TRUE]), equals(mm(0,0,0, 2,2,0, 0,0,0))) expect_that(am(g[c('a','a','a','a'), c('b','c','b','b'), edges=TRUE]), equals(mm(1,1,1,1, 2,2,2,2, 1,1,1,1, 1,1,1,1))) expect_that(am(g[c('h','q'), c('q','h'), edges=TRUE]), equals(mm(16,0 ,0,0))) }) ################################################################ test_that("[[ can query incident edges", { ## Incident edges of vertices expect_that(g[[1, , edges=TRUE]], is_equivalent_to(list(a=E(g)[1:2]))) expect_that(g[[, 2, edges=TRUE]], is_equivalent_to(list(b=E(g)[1]))) expect_that(g[[, 2, directed=FALSE, edges=TRUE]], is_equivalent_to(list(b=E(g)[c(3,4,1)]))) expect_that(g[[2, directed=FALSE, edges=TRUE]], is_equivalent_to(list(b=E(g)[c(3,4,1)]))) expect_that(g[[1:3, , edges=TRUE]], is_equivalent_to(list(a=E(g)[1:2], b=E(g)[3:4], c=E(g)[5:6]))) expect_that(g[[, 1:3, edges=TRUE]], is_equivalent_to(list(a=E(g)[numeric()], b=E(g)[1], c=E(g)[2]))) }) test_that("[[ queries edges with vertex names", { ## Same with vertex names expect_that(g[['a', , edges=TRUE]], is_equivalent_to(list(a=E(g)[1:2]))) expect_that(g[[, 'b', edges=TRUE]], is_equivalent_to(list(b=E(g)[1]))) expect_that(g[[, 'b', directed=FALSE, edges=TRUE]], is_equivalent_to(list(b=E(g)[c(3,4,1)]))) expect_that(g[['b', directed=FALSE, edges=TRUE]], is_equivalent_to(list(b=E(g)[c(3,4,1)]))) expect_that(g[[letters[1:3],, edges=TRUE]], is_equivalent_to(list(a=E(g)[1:2], b=E(g)[3:4], c=E(g)[5:6]))) expect_that(g[[, letters[1:3], edges=TRUE]], is_equivalent_to(list(a=E(g)[numeric()], b=E(g)[1], c=E(g)[2]))) ## Filtering on both ends expect_that(g[[1:10, 1:10, edges=TRUE]], is_equivalent_to(list(E(g)[1:2], E(g)[3:4], E(g)[5:6], E(g)[7:8], E(g)[9], E(g)[numeric()], E(g)[numeric()], E(g)[numeric()], E(g)[numeric()], E(g)[numeric()]))) }) ################################################################# test_that("[ handles from and to properly", { ## from & to g <- make_tree(20) expect_that(g[from=c(1,2,2,3), to=c(3,4,8,7)], equals(c(1,1,0,1))) V(g)$name <- letters[1:20] expect_that(g[from=c("a","b","b","c"), to=c("c","d","h","g")], equals(c(1,1,0,1))) E(g)$weight <- (1:ecount(g)) ^ 2 expect_that(g[from=c("a","b","b","c"), to=c("c","d","h","g")], equals(c(4,9,0,36))) expect_that(g[from=c("a","b","b","c"), to=c("c","d","h","g"), edges=TRUE], equals(c(2,3,0,6))) }) test_that("[[ works with from and to", { g <- make_tree(20) expect_equivalent(g[[1, ]], g[[from = 1]]) expect_equivalent(g[[, 1]], g[[to = 1]]) expect_equivalent(g[[1:5, 4:10]], g[[from = 1:5, to = 4:10]]) expect_error(g[[1, from = 1]], "Cannot give both") expect_error(g[[, 2, to = 10]], "Cannot give both") }) test_that("[[ returns vertex and edges sequences", { g <- make_tree(20) expect_true(is_igraph_vs(g[[1]][[1]])) expect_true(is_igraph_es(g[[1, edges = TRUE]][[1]])) expect_true(is_igraph_vs(g[[1:3, 2:6]][[1]])) expect_true(is_igraph_es(g[[1:3, 2:6, edges = TRUE]][[1]])) }) igraph/tests/testthat/test_fartherst.nodes.R0000644000175100001440000000167013177712334021053 0ustar hornikusers context("farthest_vertices") test_that("farthest_vertices works", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) fn <- farthest_vertices(kite) fn$vertices <- as.vector(fn$vertices) expect_that(fn, equals(list(vertices = c(1, 10), distance = 4))) expect_that(distances(kite, v=fn$vertices[1], to=fn$vertices[2])[1], equals(fn$distance)) expect_that(diameter(kite), equals(fn$distance)) }) igraph/tests/testthat/test_count.multiple.R0000644000175100001440000000240513177712334020721 0ustar hornikusers context("count_multiple") test_that("count_multiple works", { library(igraph) set.seed(42) g <- barabasi.game(10, m=3, algorithm="bag") im <- which_multiple(g) cm <- count_multiple(g) expect_that(im, equals(c(FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE))) expect_that(cm, equals(c(3, 3, 3, 3, 3, 3, 1, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2))) expect_that(count_multiple(simplify(g)), equals(rep(1, ecount(simplify(g))))) ## Direction of the edge is important expect_that(which_multiple(graph( c(1,2, 2,1) )), equals(c(FALSE, FALSE))) expect_that(which_multiple(graph( c(1,2, 2,1), dir=FALSE )), equals(c(FALSE, TRUE))) ## Remove multiple edges but keep multiplicity g <- barabasi.game(10, m=3, algorithm="bag") E(g)$weight <- 1 g <- simplify(g) expect_that(any(which_multiple(g)), is_false()) expect_that(E(g)$weight, equals(c(3, 2, 1, 2, 1, 3, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1))) }) igraph/tests/testthat/test_operators3.R0000644000175100001440000000200113177712334020030 0ustar hornikusers context("infix operators") test_that("infix operators work", { library(igraph) g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] g <- g - c("a", "b") expect_that(vcount(g), equals(8)) expect_that(ecount(g), equals(7)) expect_that(graph.isomorphic(g, make_lattice(8)), is_true()) g <- g - edge("e|f") expect_that(graph.isomorphic(g, make_lattice(5) + make_lattice(3)), is_true()) g <- g - edge("H") expect_that(graph.isomorphic(g, graph_from_literal(a-b-c, d-e-f, g-h)), is_true()) g <- make_ring(10) V(g)$name <- letters[1:10] g <- g - path("a", "b", "c", "d") expect_that(graph.isomorphic(g, make_lattice(8) + 2), is_true()) expect_that(graph.isomorphic(g - V(g)[c('d', 'g')], make_lattice(4) + make_lattice(2) + 2), is_true()) expect_that(graph.isomorphic(g - E(g)['f' %--% 'g'], make_lattice(5) + make_lattice(3) + 2), is_true()) }) igraph/tests/testthat/test_sphere.R0000644000175100001440000000200313177712334017217 0ustar hornikusers context("Sampling points from a sphere") test_that("Sampling sphere surface works", { library(igraph) library(digest) set.seed(42) s1 <- sample_sphere_surface(4, 100, positive=FALSE) expect_that(colSums(s1^2), equals(rep(1, 100))) s2 <- sample_sphere_surface(3, 100, radius=2, positive=FALSE) expect_that(sqrt(colSums(s2^2)), equals(rep(2, 100))) s3 <- sample_sphere_surface(2, 100, radius=1/2, positive=TRUE) expect_that(sqrt(colSums(s3^2)), equals(rep(1/2, 100))) expect_that(all(s3 >= 0), is_true()) }) test_that("Sampling sphere volume works", { library(igraph) library(digest) set.seed(42) s1 <- sample_sphere_volume(4, 10000, positive=FALSE) expect_that(all(colSums(s1^2) < 1), is_true()) s2 <- sample_sphere_volume(3, 100, radius=2, positive=FALSE) expect_that(all(sqrt(colSums(s2^2)) < 2), is_true()) s3 <- sample_sphere_volume(2, 100, radius=1/2, positive=TRUE) expect_that(all(sqrt(colSums(s3^2)) < 1/2), is_true()) expect_that(all(s3 >= 0), is_true()) }) igraph/tests/testthat/test_girth.R0000644000175100001440000000065413177712334017060 0ustar hornikusers context("girth") test_that("girth works", { library(igraph) ## No circle in a tree g <- make_tree(1000, 3) gi <- girth(g) expect_that(gi$girth, equals(0)) expect_that(as.vector(gi$circle), equals(numeric())) ## The worst case running time is for a ring g <- make_ring(100) gi <- girth(g) expect_that(gi$girth, equals(100)) expect_that(sort(diff(as.vector(gi$circle))), equals(c(-99, rep(1, 98)))) }) igraph/tests/testthat/test_graph.subisomorphic.vf2.R0000644000175100001440000000112313177712334022415 0ustar hornikusers context("graph.subisomorphic.vf2") test_that("graph.subisomorphic.vf2 works", { library(igraph) set.seed(42) g1 <- sample_gnp(20,6/20) g2 <- sample_gnp(20,6/20) g <- g1 %du% g2 ig1 <- graph.subisomorphic.vf2(g, g1) ig2 <- graph.subisomorphic.vf2(g, g2) expect_that(ig1$iso, is_true()) expect_that(ig1$map12, equals(c(1:vcount(g1), rep(0, vcount(g2))))) expect_that(ig1$map21, equals(1:vcount(g1))) expect_that(ig2$iso, is_true()) expect_that(ig2$map12, equals(c(rep(0, vcount(g1)), 1:vcount(g2)))) expect_that(ig2$map21, equals(1:vcount(g2) + vcount(g1))) }) igraph/tests/testthat/test-weakref.R0000644000175100001440000000413013177712334017276 0ustar hornikusers context("Weak references") test_that("we can create weak references", { g <- new.env() g$foo <- "bar" value <- "foobar" vs <- make_weak_ref(key = g, value = value) expect_identical(typeof(vs), "weakref") expect_identical(weak_ref_key(vs), g) expect_identical(weak_ref_value(vs), value) }) test_that("weak references are weak", { g <- new.env() g$foo <- "bar" value <- "foobar" vs <- make_weak_ref(key = g, value = value) rm(g) gc() expect_null(weak_ref_key(vs)) expect_null(weak_ref_value(vs)) }) test_that("weak reference finalizer is called", { g <- new.env() g$foo <- "bar" value <- "foobar" hello <- "" fin <- function(env) hello <<- "world" vs <- make_weak_ref(key = g, value = value, finalizer = fin) rm(g) gc() expect_equal(hello, "world") }) test_that("weak reference on an embedded env", { g <- list(yes = new.env()) g[[1]]$foo <- "bar" value <- "foobar" vs <- make_weak_ref(key = g[[1]], value = value) rm(g) gc() expect_null(weak_ref_key(vs)) expect_null(weak_ref_value(vs)) }) test_that("embed myself, and weak ref", { g <- list(yes = new.env()) assign("foo", g, envir = g[[1]]) value <- "foobar" hello <- "" fin <- function(env) hello <<- "world" vs <- make_weak_ref(key = g[[1]], value = value, finalizer = fin) rm(g) gc() expect_null(weak_ref_key(vs)) expect_null(weak_ref_value(vs)) expect_equal(hello, "world") }) test_that("embed myself, and weak ref as attribute", { g <- list(yes = new.env()) assign("foo", g, envir = g[[1]]) value <- "foobar" hello <- "" fin <- function(env) hello <<- "world" z <- "footoo" attr(z, "env") <- make_weak_ref(key = g[[1]], value = value, finalizer = fin) rm(g) gc() expect_null(weak_ref_key(attr(z, "env"))) expect_null(weak_ref_value(attr(z, "env"))) expect_equal(hello, "world") }) test_that("weak refs work for vs", { g <- make_ring(10) vs <- V(g) expect_true(!is.null(get_vs_ref(g))) expect_true(!is.null(weak_ref_key(attr(vs, "env")))) rm(g) gc() expect_null(weak_ref_key(attr(vs, "env"))) }) igraph/tests/testthat/test_arpack.R0000644000175100001440000000540213247212322017166 0ustar hornikusers context("arpack") test_that("arpack works for identity matrix", { library(igraph) f <- function(x, extra=NULL) x res <- arpack(f, options=list(n=10, nev=2, ncv=4), sym=TRUE) expect_that(res$values, equals(c(1,1))) }) test_that("arpack works on the Laplacian of a star", { library(igraph) f <- function(x, extra=NULL) { y <- x y[1] <- (length(x)-1)*x[1] - sum(x[-1]) for (i in 2:length(x)) { y[i] <- x[i] - x[1] } y } r1 <- arpack(f, options=list(n=10, nev=1, ncv=3), sym=TRUE) r2 <- eigen(laplacian_matrix(make_star(10, mode="undirected"))) correctSign <- function(x) { if (x[1]<0) { -x } else { x } } expect_that(r1$values, equals(r2$values[1])) expect_that(correctSign(r1$vectors), equals(correctSign(r2$vectors[,1]))) }) #### # Complex case test_that("arpack works for non-symmetric matrices", { library(igraph) A <- structure(c(-6, -6, 7, 6, 1, -9, -3, 2, -9, -7, 0, 1, -7, 8, -7, 10, 0, 0, 1, 1, 10, 0, 8, -4, -4, -5, 8, 9, -6, 9, 3, 8, 6, -1, 9, -9, -6, -3, -1, -7, 8, -4, -4, 10, 0, 5, -2, 0, 7, 10, 1, 4, -8, 3, 5, 3, -7, -9, 10, -1, -4, -7, -1, 7, 5, -5, 1, -4, 9, -2, 10, 1, -7, 7, 6, 7, -3, 0, 9, -5, -8, 1, -3, -3, -8, -7, -8, 10, 8, 7, 0, 6, -7, -8, 10, 10, 1, 0, -2, 6), .Dim = c(10L, 10L)) f <- function(x, extra=NULL) A %*% x res <- arpack(f, options=list(n=10, nev=3, ncv=7), sym=FALSE) ## This is needed because they might return a different complex conjugate expect_that(abs(res$values/eigen(A)$values[1:3]), equals(c(1,1,1))) expect_that((res$values[1] * res$vectors[,1]) / (A %*% res$vectors[,1]), equals(cbind(rep(1+0i, nrow(A))))) expect_that((res$values[2] * res$vectors[,2]) / (A %*% res$vectors[,2]), equals(cbind(rep(1+0i, nrow(A))))) expect_that(abs((res$values[3] * res$vectors[,3]) / (A %*% res$vectors[,3])), equals(cbind(rep(1, nrow(A))))) f <- function(x, extra=NULL) A %*% x res <- arpack(f, options=list(n=10, nev=4, ncv=9), sym=FALSE) ## This is needed because they might return a different complex conjugate expect_that(abs(res$values/eigen(A)$values[1:4]), equals(rep(1, 4))) expect_that((res$values[1] * res$vectors[,1]) / (A %*% res$vectors[,1]), equals(cbind(rep(1+0i, nrow(A))))) expect_that((res$values[2] * res$vectors[,2]) / (A %*% res$vectors[,2]), equals(cbind(rep(1+0i, nrow(A))))) expect_that(abs((res$values[3] * res$vectors[,3]) / (A %*% res$vectors[,3])), equals(cbind(rep(1, nrow(A))))) expect_that(abs((res$values[4] * res$vectors[,4]) / (A %*% res$vectors[,4])), equals(cbind(rep(1, nrow(A))))) }) #### # TODO: further tests for typically hard cases igraph/tests/testthat/test_bug-1033045.R0000644000175100001440000000043113177712334017326 0ustar hornikusers context("Bug 1033045") test_that("Minimal s-t separators work", { library(igraph) g <- graph_from_literal(a -- 1:3 -- 5 -- 2:4 -- b, 1 -- 2, 3 -- 4) stsep <- min_st_separators(g) ims <- sapply(stsep, is_min_separator, graph=g) expect_that(ims, equals(rep(TRUE, 9))) }) igraph/tests/testthat/test_sbm.game.R0000644000175100001440000000200313177712334017422 0ustar hornikusers context("Stochastic block models") test_that("Generating stochastic block models works", { library(igraph) pm <- matrix(1, nrow=2, ncol=2) bs <- c(4,6) g1 <- sample_sbm(10, pref.matrix=pm, block.sizes=bs, directed=FALSE, loops=FALSE) expect_that(graph.isomorphic(g1, make_full_graph(10, directed=FALSE, loops=FALSE)), is_true()) g2 <- sample_sbm(10, pref.matrix=pm, block.sizes=bs, directed=FALSE, loops=TRUE) g2x <- make_full_graph(10, directed=FALSE, loops=TRUE) expect_that(g2[sparse=FALSE], equals(g2x[sparse=FALSE])) g3 <- sample_sbm(10, pref.matrix=pm, block.sizes=bs, directed=TRUE, loops=FALSE) g3x <- make_full_graph(10, directed=TRUE, loops=FALSE) expect_that(g3[sparse=FALSE], equals(g3x[sparse=FALSE])) g4 <- sample_sbm(10, pref.matrix=pm, block.sizes=bs, directed=TRUE, loops=TRUE) g4x <- make_full_graph(10, directed=TRUE, loops=TRUE) expect_that(g4[sparse=FALSE], equals(g4x[sparse=FALSE])) }) igraph/tests/testthat/test_all.st.cuts.R0000644000175100001440000000241413177712334020111 0ustar hornikusers context("all.st.cuts") test_that("all.st.cuts works", { library(igraph) unvs <- function(x) lapply(x, as.vector) g <- graph_from_literal( a -+ b -+ c -+ d -+ e ) cc <- st_cuts(g, source="a", target="e") expect_that(unvs(cc$cuts), equals(list(1,2,3,4))) expect_that(unvs(cc$partition1s), equals(list(1, 1:2, 1:3, 1:4))) g2 <- graph_from_literal( s -+ a:b -+ t, a -+ 1:2:3 -+ b ) cc <- st_cuts(g2, source="s", target="t") expect_that(unvs(cc$cuts), equals(list(c(1,2), c(1,7), c(2,3,4,5,6), c(2,3,4,5,10), c(2,3,4,6,9), c(2,3,4,9,10), c(2,3,5,6,8), c(2,3,5,8,10), c(2,3,6,8,9), c(2,3,8,9,10), c(3,7)))) expect_that(unvs(cc$partition1s), equals(list(1, c(1,3), c(1,2), c(1,2,7), c(1,2,6), c(1,2,6,7), c(1,2,5), c(1,2,5,7), c(1,2,5,6), c(1,2,5,6,7), c(1,2,5,6,7,3)))) g3 <- graph_from_literal( s -+ a:b -+ t, a -+ 1:2:3:4:5 -+ b ) cc <- st_min_cuts(g2, source="s", target="t") expect_that(cc$value, equals(2)) expect_that(unvs(cc$cuts), equals(list(c(1,2), c(1,7), c(3,7)))) expect_that(unvs(cc$partition1s), equals(list(1, c(1,3), c(1,3,2,7,6,5)))) }) igraph/tests/testthat/test_betweenness.R0000644000175100001440000000521613177712334020264 0ustar hornikusers context("betweenness") test_that("betweenness works for kite graph", { library(igraph) kite <- graph_from_literal(Andre - Beverly:Carol:Diane:Fernando, Beverly - Andre:Diane:Ed:Garth, Carol - Andre:Diane:Fernando, Diane - Andre:Beverly:Carol:Ed:Fernando:Garth, Ed - Beverly:Diane:Garth, Fernando - Andre:Carol:Diane:Garth:Heather, Garth - Beverly:Diane:Ed:Fernando:Heather, Heather - Fernando:Garth:Ike, Ike - Heather:Jane, Jane - Ike) nf <- (vcount(kite)-1) * (vcount(kite)-2) /2 bet <- structure(betweenness(kite) / nf, names=V(kite)$name) bet <- round(sort(bet, decreasing=TRUE), 3) expect_that(bet, equals(structure(c(0.389, 0.231, 0.231, 0.222, 0.102, 0.023, 0.023, 0.000, 0.000, 0.000), names=c("Heather", "Fernando", "Garth", "Ike", "Diane", "Andre", "Beverly", "Carol", "Ed", "Jane")))) bet2 <- structure(betweenness(kite, normalized=TRUE), names=V(kite)$name) bet2 <- round(sort(bet2, decreasing=TRUE), 3) expect_that(bet2, equals(bet)) }) test_that("weighted betweenness works", { library(igraph) nontriv <- graph( c(0,19,0,16,0,20,1,19,2,5,3,7,3,8, 4,15,4,11,5,8,5,19,6,7,6,10,6,8, 6,9,7,20,9,10,9,20,10,19, 11,12,11,20,12,15,13,15, 14,18,14,16,14,17,15,16,17,18)+1, dir=FALSE ) E(nontriv)$weight <- c(0.5249, 1, 0.1934, 0.6274, 0.5249, 0.0029, 0.3831, 0.05, 0.6274, 0.3831, 0.5249, 0.0587, 0.0579, 0.0562, 0.0562, 0.1934, 0.6274, 0.6274, 0.6274, 0.0418, 0.6274, 0.3511, 0.3511, 0.1486, 1, 1, 0.0711, 0.2409) nontrivRes <- c(20,0,0,0,0,19,80,85,32,0,10, 75,70,0,36,81,60,0,19,19,86) bet <- betweenness(nontriv) expect_that(bet, equals(nontrivRes)) }) test_that("normalization works well", { library(igraph) g1 <- graph_from_literal( 0 +-+ 1 +-+ 2 ) b11 <- betweenness(g1, normalized=TRUE, directed=FALSE) expect_that(b11, equals(c('0'=0, '1'=1, '2'=0))) b12 <- betweenness(g1, normalized=TRUE, directed=TRUE) expect_that(b12, equals(c('0'=0, '1'=1, '2'=0))) g2 <- graph_from_literal( 0 --- 1 --- 2 ) b2 <- betweenness(g2, normalized=TRUE) expect_that(b2, equals(c('0'=0, '1'=1, '2'=0))) }) igraph/tests/testthat/test_graphlets.R0000644000175100001440000001124113424614724017725 0ustar hornikusers context("Graphlets") sortgl <- function(x) { cl <- lapply(x$cliques, sort) n <- sapply(cl, length) list(cliques=cl[order(n)], thresholds=x$thresholds[order(n)]) } test_that("Graphlets work for some simple graphs", { library(igraph) g <- make_full_graph(5) E(g)$weight <- 1 gl <- graphlet_basis(g) expect_that(names(gl), equals(c("cliques", "thresholds"))) expect_that(length(gl$cliques), equals(1)) expect_that(sort(gl$cliques[[1]]), equals(1:vcount(g))) expect_that(gl$thresholds, equals(1)) g2 <- make_full_graph(5) E(g2)$weight <- 1 E(g2)[1%--%2]$weight <- 2 gl2 <- sortgl(graphlet_basis(g2)) expect_that(gl2, equals(list(cliques=list(1:2, 1:5), thresholds=c(2,1)))) }) test_that("Graphlets filtering works", { library(igraph) gt <- data.frame(from =c("A", "A", "B", "B", "B", "C", "C", "D"), to =c("B", "C", "C", "D", "E", "D", "E", "E"), weight=c( 8 , 8 , 8 , 5 , 5 , 5 , 5 , 5 )) g <- graph_from_data_frame(gt, directed=FALSE, vertices=data.frame(LETTERS[1:5])) gl <- sortgl(graphlet_basis(g)) expect_that(gl$cliques, equals(list(1:3, 2:5))) expect_that(gl$thresholds, equals(c(8, 5))) }) ## Naive version of graphlets unvs <- function(x) lapply(x, as.vector) threshold.net <- function(graph, level) { N <- vcount(graph) graph.t <- delete_edges(graph, which(E(graph)$weight < level)) clqt <- unvs(max_cliques(graph.t)) clqt <- lapply(clqt, sort) clqt[order(sapply(clqt, length), decreasing=TRUE)] } graphlets.old <- function(graph) { if (!is_weighted(graph)) { stop("Graph not weighted") } if (min(E(graph)$weight) <= 0 || !any(is.finite(E(graph)$weight))) { stop("Edge weights must be non-negative and finite") } ## Do all thresholds cl <- lapply(sort(unique(E(graph)$weight)), function(w) { threshold.net(graph, w) }) ## Put the cliques in one long list clv <- unlist(cl, recursive=FALSE) ## Sort the vertices within the cliques cls <- lapply(clv, sort) ## Delete duplicate cliques clu <- unique(cls) ## Delete cliques that consist of single vertices clf <- clu[sapply(clu, length) != 1] clf } test_that("Graphlets work for a bigger graph", { library(igraph) set.seed(42) g <- make_graph("zachary") E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) gl <- graphlet_basis(g) gl2 <- graphlets.old(g) glo <- sort(sapply(unvs(gl$cliques), paste, collapse="-")) gl2o <- sort(sapply(gl2, paste, collapse="-")) expect_that(glo, equals(gl2o)) }) graphlets.project.old <- function(graph, cliques, iter, Mu=NULL) { if (!is_weighted(graph)) { stop("Graph not weighted") } if (min(E(graph)$weight) <= 0 || !any(is.finite(E(graph)$weight))) { stop("Edge weights must be non-negative and finite") } if (length(iter) != 1 || !is.numeric(iter) || !is.finite(iter) || iter != as.integer(iter)) { stop("`iter' must be a non-negative finite integer scalar") } clf <- cliques ## Create vertex-clique list first vcl <- vector(length=vcount(graph), mode="list") for (i in 1:length(clf)) { for (j in clf[[i]]) { vcl[[j]] <- c(vcl[[j]], i) } } ## Create edge-clique list from this, it is useful to have the edge list ## of the graph at hand el <- as_edgelist(graph, names=FALSE) ecl <- vector(length=ecount(graph), mode="list") for (i in 1:ecount(graph)) { edge <- el[i,] ecl[[i]] <- intersect(vcl[[edge[1]]], vcl[[edge[2]]]) } ## We will also need a clique-edge list, the edges in the cliques system.time({ cel <- vector(length=length(clf), mode="list") for (i in 1:length(ecl)) { for (j in ecl[[i]]) { cel[[j]] <- c(cel[[j]], i) } } }) ## OK, we are ready to do the projection now if (is.null(Mu)) { Mu <- rep(1, length(clf)) } origw <- E(graph)$weight w <- numeric(length(ecl)) a <- sapply(clf, function(x) length(x) * (length(x) + 1) / 2) for (i in 1:iter) { for (j in 1:length(ecl)) { w[j] <- sum(Mu[ ecl[[j]] ]) } for (j in 1:length(clf)) { Mu[j] <- Mu[j] * sum(origw[cel[[j]]] / (w[cel[[j]]] + .0001)) / a[j] } } ## Sort the cliques according to their weights Smb <- sort(Mu, decreasing=TRUE, index=TRUE) list(cliques=clf[Smb$ix], Mu=Mu[Smb$ix]) } test_that("Graphlet projection works", { library(igraph) D1 <- matrix(0, 5, 5) D2 <- matrix(0, 5, 5) D3 <- matrix(0, 5, 5) D1[1:3, 1:3] <- 2 D2[3:5, 3:5] <- 3 D3[2:5, 2:5] <- 1 g <- graph_from_adjacency_matrix(D1 + D2 + D3, mode="undirected", weighted=TRUE) g <- simplify(g) gl <- graphlet_basis(g) glp <- graphlets(g) glp2 <- graphlets.project.old(g, cliques=gl$cliques, iter=1000) glp$cliques <- unvs(glp$cliques) expect_that(glp, equals(glp2)) }) igraph/tests/testthat/test_graph.complementer.R0000644000175100001440000000032713177712334021532 0ustar hornikusers context("complementer") test_that("complementer works", { library(igraph) g <- sample_gnp(50, 3/50) g2 <- complementer(g) g3 <- complementer(g2) expect_that(graph.isomorphic(g, g3), is_true()) }) igraph/tests/testthat/test_bug-1032819.R0000644000175100001440000000045013177712334017337 0ustar hornikusers context("Bug 1032819") test_that("VF2 isomorphism considers colors", { library(igraph) g <- make_full_graph(3) path <- make_ring(3, circular=F) V(g)$color <- c(1,1,2) V(path)$color <- c(1,2,1) n <- count_subgraph_isomorphisms(path, g, method = "vf2") expect_that(n, equals(2)) }) igraph/tests/testthat/test_graph.isoclass.R0000644000175100001440000000077113177712334020663 0ustar hornikusers context("isomorphism_class") test_that("isomorphism_class works", { library(igraph) g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) expect_that(isomorphism_class(g1), equals(10)) expect_that(isomorphism_class(g2), equals(11)) g1 <- add_vertices(g1, 3) expect_that(graph.isoclass.subgraph(g1, 1:3), equals(10)) expect_that(graph.isoclass.subgraph(g1 %du% g2, 1:3), equals(10)) expect_that(graph.isoclass.subgraph(g1 %du% g2, 7:9), equals(11)) }) igraph/tests/testthat/test_neighborhood.R0000644000175100001440000000361413177712334020411 0ustar hornikusers context("ego") test_that("ego works", { library(igraph) neig <- function(graph, order, vertices) { sp <- distances(graph) v <- unique(unlist(lapply(vertices, function(x) { w <- which(sp[x,] <= order) }))) induced_subgraph(graph, c(v,vertices)) } g <- sample_gnp(50, 5/50) v <- sample(vcount(g), 1) g1 <- make_ego_graph(g, 2, v)[[1]] g2 <- neig(g, 2, v) expect_that(graph.isomorphic(g1, g2), is_true()) ######### nei <- function(graph, order, vertices) { sp <- distances(graph) v <- unique(unlist(lapply(vertices, function(x) { w <- which(sp[x,] <= order) }))) v } v1 <- ego(g, 2, v)[[1]] v2 <- nei(g, 2, v) expect_that(as.vector(sort(v1)), equals(sort(v2))) ######### s <- ego_size(g, 2, v)[[1]] expect_that(s, equals(length(v1))) }) test_that("mindist works", { library(igraph) g <- make_ring(10) expect_that(ego_size(g, order=2, mindist=0), equals(rep(5, 10))) expect_that(ego_size(g, order=2, mindist=1), equals(rep(4, 10))) expect_that(ego_size(g, order=2, mindist=2), equals(rep(2, 10))) unvs <- function(x) lapply(x, as.vector) n0 <- unvs(ego(g, order=2, 5:6, mindist=0)) n1 <- unvs(ego(g, order=2, 5:6, mindist=1)) n2 <- unvs(ego(g, order=2, 5:6, mindist=2)) expect_that(lapply(n0, sort), equals(list(3:7, 4:8))) expect_that(lapply(n1, sort), equals(list(c(3,4,6,7), c(4,5,7,8)))) expect_that(lapply(n2, sort), equals(list(c(3,7), c(4,8)))) ng0 <- make_ego_graph(g, order=2, 5:6, mindist=0) ng1 <- make_ego_graph(g, order=2, 5:6, mindist=1) ng2 <- make_ego_graph(g, order=2, 5:6, mindist=2) expect_that(sapply(ng0, vcount), equals(c(5,5))) expect_that(sapply(ng1, vcount), equals(c(4,4))) expect_that(sapply(ng2, vcount), equals(c(2,2))) expect_that(sapply(ng0, ecount), equals(c(4,4))) expect_that(sapply(ng1, ecount), equals(c(2,2))) expect_that(sapply(ng2, ecount), equals(c(0,0))) }) igraph/tests/testthat/test-random_walk.R0000644000175100001440000000120513177712334020150 0ustar hornikusers context("Random walks") test_that("Undirected", { set.seed(42) g <- make_ring(10) w <- random_walk(g, start = 1, steps = 10) expect_equivalent(w, structure(c(1L, 10L, 9L, 8L, 9L, 10L, 9L, 10L, 1L, 10L), class = "igraph.vs")) }) test_that("Directed", { set.seed(42) g <- make_ring(10, directed = TRUE) w <- as_ids(random_walk(g, start = 1, steps = 5)) expect_equal(w, 1:5) w2 <- as_ids(random_walk(g, start = 5, steps = 5, mode = "in")) expect_equal(w2, 5:1) set.seed(42) w3 <- as_ids(random_walk(g, start = 1, steps = 5, mode = "all")) expect_equal(w3, c(1, 10, 9, 8, 9)) }) igraph/tests/testthat/test_dominator.tree.R0000644000175100001440000000154713177712334020677 0ustar hornikusers context("dominator_tree") test_that("dominator_tree works", { library(igraph) g <- graph_from_literal(R-+A:B:C, A-+D, B-+A:D:E, C-+F:G, D-+L, E-+H, F-+I, G-+I:J, H-+E:K, I-+K, J-+I, K-+I:R, L-+H) dtree <- dominator_tree(g, root="R") dtree$dom <- V(g)$name[ as.vector(dtree$dom) ] dtree$leftout <- V(g)$name[ dtree$leftout ] expect_that(dtree$dom, equals(c("R", "R", "R", "R", "R", "C", "C", "D", "R", "R", "G", "R"))) expect_that(dtree$leftout, equals(character())) expect_that(as_edgelist(dtree$domtree), equals(structure(c("R", "R", "R", "R", "R", "C", "C", "D", "R", "R", "G", "R", "A", "B", "C", "D", "E", "F", "G", "L", "H", "I", "J", "K"), .Dim = c(12L, 2L)))) }) igraph/tests/testthat/test_psumtree.R0000644000175100001440000000101713177712334017601 0ustar hornikusers context("Prefix sum tree") test_that("Prefix sum tree works", { library(igraph) set.seed(42) mysample <- function(x, size, prob=NULL) { if (!is.null(prob)) { prob <- as.numeric(prob) } .Call(C_R_igraph_psumtree_draw, as.integer(x), as.integer(size), prob) } S <- mysample(100, 10000) expect_that(range(table(S)), equals(c(69, 129))) S2 <- mysample(100, 10000, rep(1:2, each=50)) expect_that(range(table(S2)[1:50]), equals(c(45, 85))) expect_that(range(table(S2)[51:100]), equals(c(103, 160))) }) igraph/tests/testthat/test_motifs.R0000644000175100001440000000577713177712334017257 0ustar hornikusers context("motifs") test_that("motif finding works", { library(igraph) set.seed(123) b <- sample_gnp(10000, 4/10000, directed=TRUE) mno <- count_motifs(b) mno0 <- count_motifs(b, cut.prob=c(1/3, 0, 0)) mno1 <- count_motifs(b, cut.prob=c(0, 0, 1/3)) mno2 <- count_motifs(b, cut.prob=c(0, 1/3, 0)) expect_that(c(mno0/mno, mno1/mno, mno2/mno), equals(c(0.654821903845065, 0.666289144345659, 0.668393831285275))) mno3 <- count_motifs(b, cut.prob=c(0, 1/3, 1/3)) mno4 <- count_motifs(b, cut.prob=c(1/3, 0, 1/3)) mno5 <- count_motifs(b, cut.prob=c(1/3, 1/3, 0)) expect_that(c(mno3/mno, mno4/mno, mno5/mno), equals(c(0.443959957465819, 0.441952797125797, 0.446004870037941) )) ###################### set.seed(123) b <- sample_gnp(10000, 4/10000, directed=TRUE) m <- motifs(b) m0 <- motifs(b, cut.prob=c(1/3, 0, 0)) m1 <- motifs(b, cut.prob=c(0, 1/3, 0)) m2 <- motifs(b, cut.prob=c(0, 0, 1/3)) expect_that(m0/m, equals(c(NA, NA, 0.653972107372707, NA, 0.653993015279859, 0.612244897959184, 0.657514670174019, 0.63013698630137, NaN, 0.538461538461538, NaN, 0.565217391304348, NaN, NaN, NaN, NaN))) expect_that(m1/m, equals(c(NA, NA, 0.669562138856225, NA, 0.66808158454082, 0.73469387755102, 0.670819000404694, 0.657534246575342, NaN, 0.769230769230769, NaN, 0.739130434782609, NaN, NaN, NaN, NaN) )) expect_that(m2/m, equals(c(NA, NA, 0.666451718949538, NA, 0.665291458452201, 0.591836734693878, 0.666683528935654, 0.671232876712329, NaN, 0.753846153846154, NaN, 0.565217391304348, NaN, NaN, NaN, NaN) )) m3 <- motifs(b, cut.prob=c(0, 1/3, 1/3)) m4 <- motifs(b, cut.prob=c(1/3, 1/3, 0)) m5 <- motifs(b, cut.prob=c(1/3, 1/3, 0)) expect_that(m3/m, equals(c(NA, NA, 0.445611905574732, NA, 0.442789875290769, 0.448979591836735, 0.444695973290166, 0.424657534246575, NaN, 0.369230769230769, NaN, 0.608695652173913, NaN, NaN, NaN, NaN))) expect_that(m4/m, equals(c(NA, NA, 0.439251981944392, NA, 0.439284975327761, 0.73469387755102, 0.445088021044112, 0.465753424657534, NaN, 0.630769230769231, NaN, 0.565217391304348, NaN, NaN, NaN, NaN) )) expect_that(m5/m, equals(c(NA, NA, 0.439985332979302, NA, 0.440288166730411, 0.346938775510204, 0.44159753136382, 0.452054794520548, NaN, 0.323076923076923, NaN, 0.347826086956522, NaN, NaN, NaN, NaN) )) }) igraph/tests/testthat/test-vs-es.R0000644000175100001440000001400613177712334016712 0ustar hornikusers context("Vertex and edge sequences") test_that("we can create vertex/edge seqs", { g <- make_ring(10) V(g) %&&% expect_true(TRUE) E(g) %&&% expect_true(TRUE) V(g)$name <- letters[1:10] V(g) %&&% expect_true(TRUE) E(g) %&&% expect_true(TRUE) g <- make_ring(10) E(g)$name <- LETTERS[1:10] E(g) %&&% expect_true(TRUE) }) test_that("vs/es keeps names", { g <- make_ring(10) V(g)$name <- letters[1:10] vs <- V(g) expect_equal(vs$name, names(vs)) vs2 <- vs[4:7] expect_equal(vs2$name, names(vs2)) E(g)$name <- LETTERS[1:10] es <- E(g) expect_equal(es$name, names(es)) es2 <- es[4:7] expect_equal(es2$name, names(es2)) }) test_that("vs/es refers to the graph", { g <- make_ring(10) vs <- V(g) es <- E(g) expect_identical(get_vs_graph(vs), g) expect_identical(get_es_graph(es), g) }) test_that("vs/es refers to the original graph", { g <- g2 <- make_ring(10) vs <- V(g) es <- E(g) g <- g + 4 expect_identical(get_vs_graph(vs), g2) expect_identical(get_es_graph(es), g2) }) test_that("vs/es references are weak", { g <- make_ring(10) vs <- V(g) es <- E(g) rm(g) gc() expect_null(get_vs_graph(vs)) expect_null(get_es_graph(es)) }) test_that("save/load breaks references", { g <- make_ring(10) vs <- V(g) es <- E(g) tmp <- tempfile() on.exit(try(unlink(tmp))) save(vs, es, file = tmp) rm(vs, es) gc() load(tmp) expect_null(get_vs_graph(vs)) expect_null(get_es_graph(es)) }) test_that("we can use vs/es with broken refs", { g <- make_ring(10) vs <- V(g) es <- E(g) rm(g) gc() g2 <- make_ring(10) ## TODO }) test_that("vs/es keeps names after graph is deleted", { g <- make_ring(10) V(g)$name <- letters[1:10] vs <- V(g) E(g)$name <- LETTERS[1:10] es <- E(g) rm(g) gc() expect_equal(names(vs), letters[1:10]) vs2 <- vs[4:7] expect_equal(names(vs2), letters[4:7]) expect_equal(names(es), LETTERS[1:10]) es2 <- es[4:7] expect_equal(names(es2), LETTERS[4:7]) }) test_that("both edge and vertex names", { g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] es <- E(g) expect_equal(as.vector(es), 1:10) expect_equal(names(es), LETTERS[1:10]) el <- as_edgelist(g) expect_equal(attr(es, "vnames"), paste(el[,1], el[,2], sep = "|")) x1 <- es[LETTERS[4:7]] x2 <- E(g)[4:7] expect_equal(as.vector(x1), as.vector(x2)) expect_equal(names(x1), names(x2)) expect_equal(attr(x1, "vnames"), attr(x2, "vnames")) y1 <- es[c('a|b', 'd|e')] y2 <- E(g)[c(1,4)] expect_equal(as.vector(y1), as.vector(y2)) expect_equal(names(y1), names(y2)) expect_equal(attr(y1, "vnames"), attr(y2, "vnames")) }) test_that("printing connected vs/es works", { g <- make_ring(10) vs <- V(g) es <- E(g) sid <- substr(graph_id(g), 1, 7) expect_output( print(vs), fixed = TRUE, paste0("+ 10/10 vertices, from ", sid, ":\n [1] 1 2 3 4 5 6 7 8 9 10") ) expect_output( print(es), fixed = TRUE, paste0("+ 10/10 edges from ", sid, ":\n [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10") ) vs2 <- vs[1:5] es2 <- es[1:5] expect_output(print(vs2), fixed = TRUE, paste0("+ 5/10 vertices, from ", sid, ":\n[1] 1 2 3 4 5")) expect_output(print(es2), fixed = TRUE, paste0("+ 5/10 edges from ", sid, ":\n[1] 1--2 2--3 3--4 4--5 5--6")) vs3 <- vs[numeric()] es3 <- es[numeric()] expect_output(print(vs3), fixed = TRUE, paste0("+ 0/10 vertices, from ", sid, ":")) expect_output(print(es3), fixed = TRUE, paste0("+ 0/10 edges from ", sid, ":")) V(g)$name <- letters[1:10] vs <- V(g) es <- E(g) expect_output( print(vs), fixed = TRUE, paste0("+ 10/10 vertices, named, from ", sid, ":\n [1] a b c d e f g h i j") ) expect_output( print(es), fixed = TRUE, paste0("+ 10/10 edges from ", sid, " (vertex names):\n", " [1] a--b b--c c--d d--e e--f f--g g--h h--i i--j a--j") ) vs2 <- vs[1:5] es2 <- es[1:5] expect_output( print(vs2), fixed = TRUE, paste0("+ 5/10 vertices, named, from ", sid, ":\n[1] a b c d e") ) expect_output( print(es2), fixed = TRUE, paste0("+ 5/10 edges from ", sid, " (vertex names):\n", "[1] a--b b--c c--d d--e e--f") ) vs3 <- vs[numeric()] es3 <- es[numeric()] expect_output(print(vs3), fixed = TRUE, paste0("+ 0/10 vertices, named, from ", sid, ":")) expect_output(print(es3), fixed = TRUE, paste0("+ 0/10 edges from ", sid, " (vertex names):")) }) test_that("printing unconnected vs/es works", { g <- make_ring(10) vs <- V(g) es <- E(g) sid <- substr(graph_id(g), 1, 7) rm(g) gc() expect_output( print(vs), fixed = TRUE, paste0("+ 10/? vertices, from ", sid, " (deleted):\n [1] 1 2 3 4 5 6 7 8 9 10") ) expect_output( print(es), fixed = TRUE, paste0("+ 10/? edges from ", sid, " (deleted):\n [1] 1 2 3 4 5 6 7 8 9 10") ) g <- make_ring(10) V(g)$name <- letters[1:10] vs <- V(g) es <- E(g) sid <- substr(graph_id(g), 1, 7) rm(g) gc() expect_output( print(vs), fixed = TRUE, paste0("+ 10/? vertices, named, from ", sid, " (deleted):\n [1] a b c d e f g h i j") ) expect_output( print(es), fixed = TRUE, paste0("+ 10/? edges from ", sid, " (deleted) (vertex names):\n [1] a|b b|c c|d d|e e|f f|g g|h h|i i|j a|j") ) }) test_that("unconnected vs/es can be reused with the same graph", { g <- make_ring(10) vs <- V(g) es <- E(g)[1:5] tmp <- tempfile() on.exit(unlink(tmp)) save(g, es, vs, file = tmp) rm(g, es, vs) gc() load(tmp) expect_equal(degree(g, v = vs), rep(2, 10)) expect_true(identical_graphs( delete_edges(g, es), delete_edges(g, 1:5) )) }) test_that("indexing without arguments", { g <- make_ring(10) x <- V(g)[] expect_equal(V(g), x) x2 <- V(g)[[]] v <- V(g) attr(v, "single") <- TRUE expect_equal(v, x2) }) igraph/tests/testthat/test_sgm.R0000644000175100001440000000237213177712334016530 0ustar hornikusers context("Seeded graph matching") test_that("SGM works", { library(igraph) set.seed(42) vc <- 10 nos <- 3 g1 <- erdos.renyi.game(vc, .5) randperm <- c(1:nos, nos + sample(vc-nos)) g2 <- sample_correlated_gnp(g1, corr=.7, p=g1$p, perm=randperm) P <-match_vertices (g1[], g2[], m=nos, start=matrix(1/(vc-nos), vc-nos, vc-nos), iteration=20) expect_that(c(1:nos, P$corr[,2]), equals(randperm)) expect_that(apply(P$P != 0, 1, which), equals(randperm)) expect_that(apply(P$D != 0, 1, which), equals(randperm[(nos+1):vc] - nos)) ## Slightly bigger set.seed(42) vc <- 100 nos <- 10 g1 <- erdos.renyi.game(vc, .1); perm <- c(1:nos, sample(vc-nos)+nos) g2 <- sample_correlated_gnp(g1, corr=1, p=g1$p, perm=perm) P <- match_vertices(g1[], g2[], m=nos, start=matrix(1/(vc-nos), vc-nos, vc-nos), iteration=20) test_that(P$corr[,2], equals(perm[(nos+1):vc])) expect_that(apply(P$P != 0, 1, which), equals(perm)) expect_that(apply(P$D != 0, 1, which), equals(perm[(nos+1):vc] - nos)) }) test_that("LSAP does not change input matrix", { x <- matrix(c(5, 1, 4, 3, 5, 2, 2, 4, 4), nrow = 3) solve_LSAP(x) expect_equal(x, matrix(c(5, 1, 4, 3, 5, 2, 2, 4, 4), nrow = 3)) }) igraph/tests/testthat/test_graph.eigen.R0000644000175100001440000000125613177712334020131 0ustar hornikusers context("Eigenproblems") test_that("spectrum works for symmetric matrices", { library(igraph) set.seed(42) std <- function(x) { x <- zapsmall(x) apply(x, 2, function(col) { if (any(col < 0) && col[which(col != 0)[1]] < 0) { -col } else { col } }) } g <- sample_gnp(50, 5/50) e0 <- eigen(as_adj(g, sparse=FALSE)) e1 <- spectrum(g, which=list(howmany=4, pos="LA")) expect_that(e0$values[1:4], equals(e1$values)) expect_that(std(e0$vectors[,1:4]), equals(std(e1$vectors))) e2 <- spectrum(g, which=list(howmany=4, pos="SA")) expect_that(e0$values[50:47], equals(e2$values)) expect_that(std(e0$vectors[,50:47]), equals(std(e2$vectors))) }) igraph/tests/testthat/test_add.edges.R0000644000175100001440000000321313177712334017553 0ustar hornikusers context("add_edges") test_that("add_edges keeps edge id order", { library(igraph) g <- make_empty_graph(10) edges <- c(1,2, 2,3, 3,4, 1,6, 1,7, 9,10) g2 <- add_edges(g, edges) ec <- ecount(g2) ec2 <- length(edges)/2 expect_equal(ec, ec2) expect_equal(get.edge.ids(g2, edges), seq_len(length(edges)/2)) }) test_that("add_edges adds attributes", { library(igraph) g <- make_empty_graph(10) g3 <- add_edges(g, (edges <- c(1,5, 2,6, 3,10, 4,5)), attr=list(weight=(weights <- c(1,2,1,-1))) ) expect_that(ecount(g3), equals(length(edges)/2)) expect_that(get.edge.ids(g3, edges), equals(seq_len(length(edges)/2))) expect_that(E(g3)$weight, equals(weights)) }) test_that("add_edges unknown attributes to NA", { library(igraph) g <- make_empty_graph(10) g2 <- add_edges(g, (edges <- c(1,2, 2,3, 3,4, 1,6, 1,7, 9,10)) ) g4 <- add_edges(g2, c(1,4, 4,6, 7,1), attr=list(weight=c(-1,1,-2.5))) expect_that(all(is.na(E(g4)$weight[seq_len(length(edges)/2)])), is_true()) }) test_that("add_edges appends attributes properly", { library(igraph) g <- make_empty_graph(10) g3 <- add_edges(g, (edges1 <- c(1,5, 2,6, 3,10, 4,5)), attr=list(weight=(weights1 <- c(1,2,1,-1))) ) g5 <- add_edges(g3, (edges2 <- c(10,9, 10,10, 1,1)), attr=list(weight=(weights2 <- c(100,100,100))) ) expect_that(E(g5)$weight, equals(c(weights1, weights2))) }) test_that("add_edges signals error for zero vertex ids", { library(igraph) g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) expect_that(add_edges(g, c(0,5, 0,10, 5,10)), throws_error("Invalid vertex id")) }) igraph/tests/testthat/test_are.connected.R0000644000175100001440000000125213177712334020446 0ustar hornikusers context("are_adjacent") test_that("are_adjacent works", { library(igraph) g <- graph_from_literal( A-B-C, B-D ) expect_that(are_adjacent(g, "A", "B"), is_true()) expect_that(are_adjacent(g, "B", "A"), is_true()) expect_that(are_adjacent(g, "A", "D"), is_false()) g2 <- graph( c(1,2, 2,3, 3,4), dir= FALSE ) expect_that(are_adjacent(g2, 1,2), is_true()) expect_that(are_adjacent(g2, 3,2), is_true()) expect_that(are_adjacent(g2, 4,1), is_false()) g3 <- graph_from_literal( A-+B-+C, B-+D ) expect_that(are_adjacent(g3, "A", "C"), is_false()) expect_that(are_adjacent(g3, "A", "B"), is_true()) expect_that(are_adjacent(g3, "B", "A"), is_false()) }) igraph/tests/testthat/test_contract.vertices.R0000644000175100001440000000133413177712334021377 0ustar hornikusers context("contract") test_that("contract works", { library(igraph) set.seed(42) g <- make_ring(10) g$name <- "Ring" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- sample(ecount(g)) g2 <- contract(g, rep(1:5, each=2), vertex.attr.comb=toString) ## graph and edge attributes are kept, vertex attributes are ## combined using the 'toString' function. expect_that(g2$name, equals(g$name)) expect_that(V(g2)$name, equals(c("a, b", "c, d", "e, f", "g, h", "i, j"))) expect_that(as.matrix(g2[]), is_equivalent_to(cbind(c(10,9,0,0,7), c(9,3,6,0,0), c(0,6,4,8,0), c(0,0,8,5,1), c(7,0,0,1,2)))) }) igraph/tests/testthat/test_graph.maxflow.R0000644000175100001440000000104313177712334020511 0ustar hornikusers context("max_flow") test_that("max_flow works", { library(igraph) E <- rbind( c(1,3,3), c(3,4,1), c(4,2,2), c(1,5,1), c(5,6,2), c(6,2,10)) colnames(E) <- c("from", "to", "capacity") g1 <- graph_from_data_frame(as.data.frame(E)) fl <- max_flow(g1, source="1", target="2") expect_that(fl$value, equals(2)) expect_that(as.vector(fl$flow), equals(rep(1, 6))) expect_that(sort(as.vector(fl$cut)), equals(c(2,4))) expect_that(sort(as.vector(fl$partition1)), equals(1:2)) expect_that(sort(as.vector(fl$partition2)), equals(3:6)) }) igraph/tests/testthat/test_unfold.tree.R0000644000175100001440000000060013177712334020157 0ustar hornikusers context("unfold_tree") test_that("unfold_tree works", { library(igraph) g <- make_tree(7, 2) g <- add_edges(g, c(2,7, 1,4)) g2 <- unfold_tree(g, roots=1) expect_that(graph.isomorphic(g2$tree, graph(c(1,2, 1,3, 2,8, 2,5, 3,6, 3,9, 2,7, 1,4))), is_true()) expect_that(g2$vertex_index, equals(c(1,2,3,4,5,6,7,4,7))) }) igraph/tests/testthat/test_get.diameter.R0000644000175100001440000000100413177712334020301 0ustar hornikusers context("get_diameter") test_that("get_diameter works", { library(igraph) g <- make_ring(10) E(g)$weight <- sample(seq_len(ecount(g))) d <- diameter(g) gd <- get_diameter(g) sp <- distances(g) expect_that(d, equals(max(sp))) expect_that(sp[ gd[1], gd[length(gd)] ], equals(d)) d <- diameter(g, weights=NA) gd <- get_diameter(g, weights=NA) sp <- distances(g, weights=NA) expect_that(d, equals(max(sp))) length(gd) == d + 1 expect_that(sp[ gd[1], gd[length(gd)] ], equals(d)) }) igraph/tests/testthat/test-make.R0000644000175100001440000000323413177712334016573 0ustar hornikusers context("Make API") test_that("make_ works, order of arguments does not matter", { g0 <- make_undirected_graph(1:10) g1 <- make_(undirected_graph(1:10)) g2 <- make_(undirected_graph(), 1:10) g3 <- make_(1:10, undirected_graph()) expect_true(identical_graphs(g0, g1)) expect_true(identical_graphs(g0, g2)) expect_true(identical_graphs(g0, g3)) }) test_that("sample_, graph_ also work", { g0 <- make_undirected_graph(1:10) g1 <- sample_(undirected_graph(1:10)) g2 <- sample_(undirected_graph(), 1:10) g3 <- sample_(1:10, undirected_graph()) expect_true(identical_graphs(g0, g1)) expect_true(identical_graphs(g0, g2)) expect_true(identical_graphs(g0, g3)) g4 <- graph_(undirected_graph(1:10)) g5 <- graph_(undirected_graph(), 1:10) g6 <- graph_(1:10, undirected_graph()) expect_true(identical_graphs(g0, g4)) expect_true(identical_graphs(g0, g5)) expect_true(identical_graphs(g0, g6)) }) test_that("error messages are proper", { expect_error(make_(), "Don't know how to make_") expect_error(make_(1:10), "Don't know how to make_") expect_error(graph_(), "Don't know how to graph_") expect_error(graph_(1:10), "Don't know how to graph_") expect_error(graph_(directed_graph(), directed_graph()), "Don't know how to graph_") expect_error(sample_(), "Don't know how to sample_") expect_error(sample_(1:10), "Don't know how to sample_") expect_error(sample_(directed_graph(), directed_graph()), "Don't know how to sample_") }) test_that("we pass arguments unevaluated", { g0 <- graph_from_literal(A -+ B:C) g1 <- graph_(from_literal(A -+ B:C)) expect_true(identical_graphs(g0, g1)) }) igraph/tests/testthat/football.gml.gz0000644000175100001440000000706713177712334017510 0ustar hornikusers‹ ðÁDfootball.gml[oÛÆ…ßó+„<œgQE²oŽÛ´iã$hÒ}˜XŒDX&RJêþúCÇvªo$./(^ÖìÙ³g;͈=o˰kÚÉÓ‹Ð^M^•_®C=iêÉÛ°›üºßNf³É4ýa>û!YNfÓéòé“u>mžüïÉd²ªÚòrW®&ÓþêfUöÜþûɤºûw“É6|(·“§ÏÚj½ ×ÿmöõúé×ÿð9l÷å$ëÿþ¯ƒ“ÃÁÏ·M[­ÂÛ]Ø•‡ƒ§ƒg‡ƒ_4_Âá ÙÀ ùá ßBÝ…îhÂùÀØÅáØÞ„åßÕeã¬3=ù®ü;tïÊË3çòp䛲®´Ziv8òm³ßmʶ>ÛêcÓÖŒ•ˆÈEœµÕ?M}¼=Cƒ Ìê«rÝdynzr8öJ@©WM»Û|µ÷áØdˆQÉìhpo³ÛmU7D,‡$Ì$|)»]/ÅÙ² {7ð¢ºÜTëP[Óƒhï«î²©»Ê›L{Ó\WæÑÎöö\l14Žìºjo‰àÕŸU»®z6ÇÇ)ò ÕYÿg¸޶3ðêó—gΘP÷'Èý± g+f NwuÚ¿ òú|eïyh›žþ#¼2xô,l·GC‡¶v&݇ks@¥gýY-=H‰‚ƒ»]SŸ7Ûm¹.FÍÁ¨Û3ûÀIktÂÉ¿ô¶^ÿܖ屟²Ú;å-c!HvJí¡MžƒhÏö?†mc) †½½iÃå¾óì ^—õ® ÛI‡Æƒ\?—M¿Ú#·1¸ÞüÄäcó${³oW{+ˆ/À®ž–MVÉ©‘vü]Ì8¼®û°ºÜï[/@¬ŸÂè8¶XÄüÐáèÅÐhìÇý•å¸ Øó¶ìêcs z‘èõzSÜcë—fë¬u‚T¿W—žª)8õb6R0ê}è6½¯ŠTŠg)èt—w;,NÁ¤‡,ö¢ÜmšUÕí¼õ‚L¿õ‡×¡` ½©v»®ÏlÖV–‘.ã÷—W7N$KA£—;ê>W},rèæGc«P§FƒZ'Ç_4uÛxùÃ̺¨z§Ñ5;«.[&®«ÛCäìÔÜú3Ô«²ýPmw޽—sN»ZmËwå­Þ]y"‡\8(vª`\wJºîö¯OŸª£É—²]”ן6œzˆ/KpíUù90’e ¢½nûºÎrË‚Þо™3ðë«78†,•c.½²£>ƒÝ0Èè½Býk3&3Í¢†Ã‡6tWÁš8=2Ô×ü]?2ëÛ©°,ÍæÃ.Ô›våp$·þ 2vÛ!+¨õõ§­•_æàÖ«ðþz(ÓÉÎöwèÎþsálQõvmùc¸.­IçG“þ´}ºÆbUV½¾ÚöñÿÚbUÎ6V³-WÖ ÊI¤ý6ÔV@ËÁ¢öQ0Ï£I;ϹåtR‡5°“E Ñmá~ÄÜ¡m-À¥³öúÆ1RÁD½ª/û°vÖ /@¤³ª}Þ´—VyP€D¿ïwë²íœcV€C÷e˜³ŸHô-;±ÃdqœYÝŽ>†›rg ‚¤Š‹C§§.BÛmÂvku»¦QJuWCÙµE2=ΫNÍC»•L£æB×5û¶rÖœLA®ómyÝ1MìÂN£¸w›˜¼ ÝŸåšæî³ ®ÊžØ%Ë…áÙA´õê–&ž­YÞ{V;[H¦'ò*;î%Ó˜d7½Ÿ]YKf³ý+­Ï7m__UÁ*DvÝÇ]2$ìºß÷dŸUímz®=èÉî;ŸVšM÷_—PU'#E¹Zÿ;òö\–÷X»Ð®ËÝ7ûžÎ3\¸ÓCàÂÎpéꘗ˜3,¹ TæP™çžü÷ÈT!±Û‰šP_¨ÚžJÔ%6Ý’Å÷!õô \"­O¨\j« &Ëé,l¤Ü{D*×”ûPp?QÇiò'êˆÎ@Ô™²¡r~ åô3w§ˆôeΔ£'T.‰gOm¡rM@*F)ÙG¨ÜPž}i(žR©*ϾBâð)'A¤<&TjŠs:“Få‘–ôËìõ ?!E"çTo*"õÎgæCµTFiuTç8Ôse¹ï*MTð ŠØ„*ÎícM¤\š\…Ê­‚[Ñögž"×ï'*Tr…i´:„Ê  ³”¶¢³ô¡s©ÀÒ7€ïY •©B$U. Np.)`{V"5±9¿<¬t­Ò¬„ÊUÑ ûRõq¡’Ø~:G˜K]•ªR¨?¿ö¬„* ,†T&RM¿@¼Z¨Ã²°óêH¨œùšª£º°û"DJú/­å¢­¥ª ÁÒ¨”*ue¾.>€J·Fèdh Ò~ "‚ÊÝb–»ÅŒAžUB% ÙK“ºúý Be¼XØ•P$Tº &ÒV ØRDÁ…ä c«d‹ÝR$R{kÎo#ç’„J©,Å$­Ø®”gЂ‘TeÖ”ñJ6žY¶ÉÖ3Ë6Å«Hª²@ÊæªÔÕ®©\‰”¼Ž Ò o6R/ PuXRøëT.Ê/ •¼Ž ê FPÉkF)Õ¯F#¨\ƒ›<-”êCeÖ’" ¤Rjê[P¹*Ùâ—é_§~9œ2ªèš"¤Òv5J¤L#¨ÜVB%Y²¤R.ŸU£4*§—R‹ï„¦jýK^*Z*o •NˆPµ*"ʬ‘ªò˜PuZ U\]2 ËùULÔ Xú=aBeE¨t—TêÊF¯”Ê‚TR9ƒÜWVÄr ¨€•þr9÷¥2k‘K¨<„~õ¾D ^Jj*çg"0b~Iûª?j#õqeÊ"-e7ЉÔTaÆàCõ¦2»’¶¢®rYÈC–ò´ªiÍìF:!¾ •GÐAèBzA¿#Ah*7–R¥]™ If1’ ¨¬r •Uf$Õ‡ú«’1¡’,ö ."5¯ õç×öç ‚2jÆüNÑŠP™5ER­•^ˆPéÛ"äãA* x•!k’Á-ó3¼ªè’ùi[æg£‘T_W™ f~6šñ…”•ûÊ´Qn–ÝêÊüV¡²•!¿“ ô›R„ÊØB¨ ™ßêÊ`eR;Œ„úP郘 Ê]¥P~ùšU~ÒFèRn/œ¤`‚)¹â_ceHÚ2¹Y~O,ósÑHª´+uõ¡z ¨«ÕÁ Y£>ƒþíX$ÕFÊô.šß‡J¶2g”ª2i”¦òSáHª¯«Þ;k%r9ÂVþúåV±-êCu~I©rü÷Ÿ„Êv¤€ôWÌÛ4çs¥¡òÞP¹¬ÜýB¨\•çÍïCe"@¨âUÎWõŠ­„f*¸*Ûí‘T¹­ÔUÚŠ øPMûw ¹ŸŠªw€Y«T• ¶¯€Lps?mÎý¼=G2˜K]™6K.¾S™âævŠK¤>.~6ÙJ²Å®F,ʾt&RÖø„ÊjœP1 ÕÞ‚ºÊýg5â[@&¹ßì%T{¿Äˆ¤Êƒíw› Õ[à× 9sa*o•%¡²p!Tû+B¥±¨«ÜX¾€“^9®ÜXfã’„LÇ}t ¢®¾:ú×9/-Å|ÜFê—™»¤¥JŒÈÜY»(haÿ¾›Hù+t¦øjQ„Ê_¬û%£5ùR¥ T–Hª´TH©¬\|©ÒcGÐ Hcñ¹¨¯€ o‘T¹±üA´¤ ëyü/ª-À6¾ÜX¶ñ¥±ü—2Ô×Uæ-…ýKK"µÃ`EæK•íB%±9¿JEÕäü>TWÿÁ,¡²-E¨ C„Ê¡z[Yfް€/Uï«ÿ+›e†lΪý0¥JbSª\–ÿV‡PyéA¨Ìò Í}¨LÆ ¿$"TëÊòMË¿!*ü[Be™) IÈ¢PêÊBËFêHH¡r³X>J—I©òh±z“‘I!måßûªéÊBOúwJ•à,*)@¤tC\•ÜWÖyr_YgI[±$ô¡¹´«· H ø÷Y„êtPùf„±>Öøp`ä礈•á8Âêd;F¬üJ±òIr„]Ž0™|@ë0¼ò\S–gòsÄÊ|+ÂÚ ¼ˆó¡2猗¦Z¬Â¹š94Ù¬Ì|>MúÍë½ðo#¬tå¶Ð¦#äÊpvd« ‹Ë©Ö—ß!Xöî"¬l4FX,c}µÛ±¿’Ae5ôð•[þ÷×"ì ½küMˆ¶/?G¨«¿–H¬LÞ#¬ì¸ÄúŽ0™„²Ú½ã‘ ~ä°ùåq,W›—W¡ú`Ú_·ˆm¦Ùëßâá£Îß•5j„-´yíïëFÐG>~q„\ù >ÆŽ€êĥ؉G>Öà:ó=¥ÖØG"<+öGB&•}$ !ôq³[Gk¡‚æƒý½ÊªÙ`¿­Œ ¤ÿ~›#ÂÊ÷µ±\M2ÿÙj„•¯Q¾ïÕþ{Ð+NV›Ì¿WŽÅ>]#°>þ=t„}$ùŸØ’”üعÎâ’]bå-s„Õ1>ÂJ+›DXù,#–+#a¤ï¹òI¯Äël–X‰}dml<è½°?¦/MúdD«&RׇÞyM×¼#°:^$#ÚÄzÛˆ£Ã¬¼R±š¾l}húrm#l¦“¾H®æ[šÄj×Çkp­¯ÿm‹«{ÑÿrBóí—Xy¹aå=`l3-×÷cõG½m`¾5¡Ä#ñÍÿ-h,w„Ñɸ¶1FÓ›½W¿ó=ù?og@ðã‚igraph/tests/testthat/test_is.bipartite.R0000644000175100001440000000072113177712334020333 0ustar hornikusers context("is_bipartite") test_that("is_bipartite works", { library(igraph) I <- matrix(sample(0:1, 35, replace=TRUE, prob=c(3,1)), nc=5) g <- graph_from_incidence_matrix(I) expect_that(bipartite_mapping(g)$res, is_true()) set.seed(42) I <- matrix(sample(0:1, 35, replace=TRUE, prob=c(3,1)), nc=5) g <- graph_from_incidence_matrix(I) expect_that(bipartite_mapping(g), equals(list(res=TRUE, type=c(rep(FALSE, 7), rep(TRUE, 5))))) }) igraph/tests/testthat/test_graphNEL.R0000644000175100001440000000164013177712334017377 0ustar hornikusers context("graphNEL conversion") test_that("graphNEL conversion works", { if (!requireNamespace("graph", quietly = TRUE)) skip("No graph package") library(graph, warn.conflicts=FALSE) g <- sample_gnp(100, 5/100) N <- as_graphnel(g) g2 <- graph_from_graphnel(N) gi <- graph.isomorphic.vf2(g, g2) expect_that(gi$iso, is_true()) expect_that(gi$map12, equals(1:vcount(g))) expect_that(gi$map21, equals(1:vcount(g))) ## Attributes V(g)$name <- as.character(vcount(g):1) E(g)$weight <- sample(1:10, ecount(g), replace=TRUE) g$name <- "Foobar" N <- as_graphnel(g) g2 <- graph_from_graphnel(N) expect_that(graph.isomorphic(g, g2), is_true()) expect_that(V(g)$name, equals(V(g2)$name)) A <- as_adj(g, attr="weight", sparse=FALSE) A2 <- as_adj(g2, attr="weight", sparse=FALSE) expect_that(A, equals(A)) expect_that(g$name, equals(g2$name)) suppressWarnings(unloadNamespace("graph")) }) igraph/tests/testthat/dyad.census.R0000644000175100001440000000123013177712334017113 0ustar hornikusers context("dyad_census") test_that("dyad_census works", { library(igraph) g1 <- make_ring(10) expect_that(dc1 <- dyad_census(g1), gives_warning("undirected")) expect_that(dc1, equals(list(mut=10, asym=0, null=35))) g2 <- make_ring(10, directed=TRUE, mutual=TRUE) dc2 <- dyad_census(g2) expect_that(dc2, equals(list(mut=10, asym=0, null=35))) g3 <- make_ring(10, directed=TRUE, mutual=FALSE) dc3 <- dyad_census(g3) expect_that(dc3, equals(list(mut=0, asym=10, null=35))) g4 <- make_empty_graph(2000000) expect_that(dc4 <- dyad_census(g4), gives_warning("Integer overflow")) expect_that(dc4, equals(list(mut=0, asym=0, null=0))) }) igraph/tests/testthat/test_layout.kk.R0000644000175100001440000000331113423360014017641 0ustar hornikusers context("Kamada-Kawai layouts") test_that("Kamada-Kawai layout generator works", { skip_on_cran() library(igraph) g <- make_ring(10) l <- layout_with_kk(g, maxiter=50) if (Sys.info()["sysname"] == "Darwin") { expect_that(sum(l), equals(-1.13071769106689)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "x86_64") { expect_that(sum(l), equals(-6.77278645472984e-05)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "i686") { expect_that(sum(l), equals(0.914809637353466)) } g <- make_star(30) l <- layout_with_kk(g, maxiter=500) if (Sys.info()["sysname"] == "Darwin") { expect_that(sum(l), equals(-85.6883999492408)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "x86_64") { expect_that(sum(l), equals(-86.1405864709501)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "i686") { expect_that(sum(l), equals(-85.142223229617)) } g <- make_ring(10) E(g)$weight <- rep(1:2, length.out=ecount(g)) l <- layout_with_kk(g, maxiter=500) if (Sys.info()["sysname"] == "Darwin") { expect_that(sum(l), equals(1.61069099387368)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "x86_64") { expect_that(sum(l), equals(-1.83036635516248)) } else if (Sys.info()["sysname"] == "Linux" && Sys.info()["machine"] == "i686") { expect_that(sum(l), equals(0.0631144692360025)) } }) test_that("3D Kamada-Kawai layout generator works", { library(igraph) g <- make_star(30) l <- layout_with_kk(g, maxiter=5000, dim=3) expect_that(sum(l), equals(61.0559727551764)) }) igraph/tests/testthat/test_diameter.R0000644000175100001440000000171313177712334017532 0ustar hornikusers context("diameter") test_that("diameter works", { library(igraph) gc <- function(graph) { clu <- components(graph) induced_subgraph(graph, which(clu$membership==which.max(clu$csize))) } #### Undirected g <- gc(sample_gnp(30, 3/30)) sp <- distances(g) expect_that(max(sp), equals(diameter(g))) g <- gc(sample_gnp(100, 1/100)) sp <- distances(g) sp[sp==Inf] <- NA expect_that(max(sp, na.rm=TRUE), equals(diameter(g))) #### Directed g <- sample_gnp(30, 3/30, dir=TRUE) sp <- distances(g, mode="out") sp[sp==Inf] <- NA expect_that(max(sp, na.rm=TRUE), equals(diameter(g, unconnected=TRUE))) #### Weighted E(g)$weight <- sample(1:10, ecount(g), replace=TRUE) sp <- distances(g, mode="out") sp[sp==Inf] <- NA expect_that(max(sp, na.rm=TRUE), equals(diameter(g, unconnected=TRUE))) #### Bug #680538 g <- make_tree(30, mode="undirected") E(g)$weight <- 2 expect_that(diameter(g, unconnected=FALSE), equals(16)) }) igraph/tests/testthat/celegansneural.gml.gz0000644000175100001440000002715713177712334020700 0ustar hornikusers‹xó“Lcelegansneural.gml­É®-ÇqEçúŠ}Á©¬Þ3Ãc{䙡->P‚eÉ Eû÷ý,èRµ÷aì»2 œu³‰ÌÈè2ëŸ~üúÝŸÿôã—_ÿów?þÇ—ùú¿ÿùÝ¿üé_þõw?}ùÇŸ~ø²._–ñûý¯ûËx½Ž_ÿꇿû¯ßýêß~õåË÷¿ÿñëoÿüõû/Ë·ÿøãŸ¾ÿúíÿÿÿ¿|ùý÷_^ù—?|÷ï_ÿðå×˯¿ý×o~áWËóW{ù³ñüÙ9ªŸ­ò³³úÙ&?»ªŸíÏŸ•mÏ_ݯêg§ü¬ük—ÌÚ^öíÖßÝåüª–µü¡Hâ¨ÿ Š¢¬Èâªÿžã®ÿžH£†ˆc+—À¢ò(¦ò¨ÿœÈcÔëXÄq—Ã"{+'Òõßi,¡ƒ›þp/(òXÖú/ŠDÂïD"õˆE"G¹ß†îòw«n£üHd)7檩U•Hd”ã]u”+pUy„†ýa=bȲÖQD~'"Y_åjÝD&åÜD$µ¶7‰”ýÛt“¼Ê¥ºm:º‡"”r¦7É«î¡j­Rmmª¶^åêßTo•s¸‹DêS$R/­]D²•‹‰¬u÷Tk•‚Ûu“”ó·‹@Fý;Ý"¥Üv‘ÇV÷O•V­e‘G­¥ÈZ®ƒCR[ ‡n‘­þ¡HdÔ‰„¿§[¤\1‡J¤^Z‡ˆdÔ3£J«ü{§ž#¥DN‘ÈVÛ‹*‘zOÉZ.ÖS7IhZwÉ«nZözÌ*”W¹OÕ[k¹NÝ(µX.K­ª/=ß_¥îºD0ký;Õ]åP.õFêß™ÁU7,R9ë©Q©¥VºT*µ:¼L*ådß*•z÷ݪ¿jwH…RöðÖÍR›·n–ZsÞ*–zºoõLʳâV±ÔžÓ-b¹ê?(R9Ë‘|3¤‡¥ô¾YFÒÅú<ûfÊ<¹‡?©‚©æåe’©}²—ž-å†ù¶Ùu<åT~S]ÚÍRÚß´¦Œ<4.â9ê¶Õ•¿ê¿¨®üR{™ËbÇ~¹¿–ÅlãZ>êÐïa<"ž:Ô±¨O_ë©Eú³^mêÖŸa*E8WÝ´:öWÝ´zö[=juí—Úƒ]Ô¹¿ÂE4Wh[C_µW¼¨w¿…°‘Èf¯7Ž:ø{ÅÀê?©>þ]ÆœüÚZÔÍ¿ky¯vâ„ÆuãÔ»V]ý=tR7Nø‹ªÖîze¨¯…¶uçÔÂ1g? 5BY7­ÿRxõøÐI‘ÍQ‹[=þQ[6‹:ýa]¨Ó„ѨKSù–ÍüÌuµøq­Îw3 êí©gSýÿ%œyuèaÙMBõ:²(@í‚-µ…¼h$`Ôvåb±€ -P;C‹†Fm /‡–ëùÔÀö˜Å‚µ¡QQÛó‹Å‚B²È@8ý,4P;Ê‹F05<0êØç¢‚å¬Ç®!‚²#F¦ ‚JÔ(ÁG¿† FXÉ(ǪF F9\4T0‚AzYP­–‘ F0=4Z0‚¤ñ‚¥Žô/1¯Ðº:§Á4Ô Ál „Uw™ŒjrYºþ¥FÖ:L³Ü¶BîNeÜY Œ:®¾hü`ÔñÀÅuP¹MFáoZh'üMõ„Âõ8ª—ñ²ŒZø¥™ u²QãK×H¨3íãe"*Ç>4°Ô÷°HB]©04’0êPÿÐHÂUçx5’PñÊêäã°PB}l %ÔJiX(¡Þc±dthÝ$Tª…±˜„êòbCh]¤µ»<3êê¿©…d4,ÜS·nÕuôjhHaÔ ¡aõ7¬b Žtañ¸zgjTaÔ!Ÿ1,ß~©‡Q}Ä «åKXõa44°°ÔæÊð ‚zDYµC<4´0êøÐØÂ¨sÖ µã>4¸0êckhta©Ã Cà K]°46«ð¨çÓ á—ªëjÃfl&£z>-Ä4Øf†w-÷Ít]˜%ÕuuÚaxmA-# 2ÔEt u¹ØÐ ÃJ¨vÛGá—*£P|dA†:ã9<ÈPkE 2ÔiÙaA†:X?v«[«GdA†:d4,ÈP‡Œ†êÈþ° CíÀ 2Ԏ̰ Cíê 2ŒÚðduToX!ì# 2Ô6ú° CªµSÕŽá° C]Ý54È0‚9-TËȃ õ|Z!xdÁ“± C]2<ÈP·îA†Zšd禂ǥA†NC 2kMƒ #èäËʪ굤A† e-Èô¼êàÒРõF´dÞ™ê€À¸­1Ãjõt°ë4ȰþÍ®ûúýûåÿé§ûõ¯5þþîǾþù¯¥üÿóÝ~úú—GÐx@ƒBk§¥­ÓÒÞiéx@…Îtuºw? -@‹÷›Rj¡¨]B]O ¯¼­»ÓųÓÃDô_ÛšàèÞÒ>¶¦ñÜ`[CÖüÙ¡>’†ÓØsdi öT7ÇèÂ2ì¹öÓôvô°³7%W«µÑ™‘«7²¥ÕÅ­7T9*v¼zØsõóõx.Žá)'»!®NíæsUG¶ÑYÞ+3*Åžƒ‹J^±£7'8„¨Ø‰>Åž %ê?ÅžàëDµX\—–”ÄΗq= »l‚]x¯63®Êa}"öµÏÆ¢¼;±¯ Ù<‘{5´ØGm ŸsŠ=…ÅhS±A³ä†Ñ,¹axý+†‰bxo+Ö[[»¡’’Xxöϲ“ÑÐSLŒ_ÞÜŽ]HNÅ.el‰¢`ܳÖ$ÖΊáMW'¢ä,ÙÂpæÒ€ Åð2Ñg2 @0 ÕÄK–z{`ñ®Ly¡8^f°¼ÝÎÑÕzù¢'ªq¸þO¹‹.Åð7 _¾SŒjØaW“é7/0ÁhªH©«76l †o¬*†o9)†Ç&±Q~?¶Ž°Å{…ŠÑ×ÐÀ ¾ ·õZ³8ÞÞµ¡å­å©øöµ–VbÝ%¿Gª­ÑDþPû ®Uägaõªai+F¯¡†‰Ž ŸpŠÑ ”u_#U ?Z VAŠáK«ŠaõªXs%ã]ªN•:íñj­‚ ÞßjÃâM ß;ŠÑë2†ÉÇ›ãnûªv¾|§ãPÃ^1ºœ•Âu%ÖGÙᜓÃ*©/Å6ªšmJ¨eƒ£ipõ>Ö² .Ϥ`TW*…+«“‹3ñÒªö‘Ʀ­5ªô;¨¡˜„­âæV±áª›z~FÏÃh ·ax¿ÕŽÎ„zk'² ËR‹ ñ¢Ôr?|“Z[£F½bøÎ‰uËM° ëuòÂG‡á`WgÍc'Ã*HM¬ëõñ¤.„b+ÞnV"Eí%V µÏOS­?ÀUPÆqÓ°ç}+†ï­µ÷ŸªÐ[y8±jþ¢‡­Ôm_{IÃð'ŽXk4þ±©ÝKÃè–S  ¬5z·Ã0ºS·ÒîMóo~L@-QzÂYkø1ÚÆ›hîèÃh~uE1¬(·úvFœbÔîUL+9⤇+96³òðƒ-á.çNy{Í~®½~òݪ~³ÅÊ×{“‰7‚“w{Ù“(u¾V¬ùš—+¶V©¼R£×.]W [Q›>¥B+UõŸª Òˆ…wG¢zÖ*/¼ z頭ΙÄÖÔŽ¥õŸŠá#¤ÎFð>nø± u“¬9Á"×|YA9.µ¶éÖ©kÃx¹ÕV›öQÁ†¤B|÷¨õl¾RøhT Û¿ÖGZäe¤×… £ÆÉ^»-­ŸÚëÄGÚß{/§°×¾U¼¬³+=¶§ö/Í"íµqÏ[×uë5†MfÅð*é…}múéÚê™x6x»ikT»îz¥ËZmµ•Ž¥°'`Ö$ŠÑP†b8ƯŽåíµ‰r]ßÅÇvâµUßMŒì]1TL¼Ód•(†+嬓Xm &n_²°­“´àǦëmšØ{}5.N‰:bx•†/ÅïêâЊ«½W¨ö:õƒ{í¾%z×[3xw«¯B_êØÍ5jµÆÕk(y‹òV'«eí%M†ÚTbKA;‰[+ü‹‡°PøåeÅd•ðÖp®Ê†öœ‘¸ÔŸ¥Ï(†Íuƒéë†aO¥çt›Ø°¡ ØÕœê«[kXq)Ö[ÉV\Šá½­Äþ=5ˆg½°á½›«ÜÕyëÍF¥N,9m //’^'¥–/®ÁpuV[YkØèÒ)¡oà(&>~´0´5~æëàX4͵5ìÓ–‰òm3z»tÅG¾ÆB{›ôÀ®‘ª„Þ.Å¥øGýª'ÇðKõ!îßú–¸)¶Q ¶y­5,Áðg­Qçи½ë§5ž”ÂåAŠí4ÿ©˜(×ø‘ibi×¥¬ñéZ¥xô‚š†Q›Ë üF#H‡Æ_x™(Gï¡(FJá  mñ)hÀ°;#XÞ í5wô€?µjXSØ UŽzÂJ=ç?j®:dÎgßG´ÁÏØ*¡†¹M >»µ—½Áñ勤{;{Іá¥Ü+9Wl£†ùQÎ)~GG?|„ÏŽòƒNq‘…ëmhô~¦bÜR(?û¨Ùñnk~ Jãó4¨fÄf‰¶FýY½¯ª®›9êÜÃÄ”àMªSқɫr­8ï™(ǽmŽzëŠaÇHÃEËÊa¹ u÷ã•ÕG/Eåè­“1°6¯ !9†¿Ü¦"xP)‚d3Ù›\i#ÃÚÜ– ÞujeÃVPZ‰‡wýù&ÞÚ‰e} ·Ö‹}FŸ#S ±ãrÓ°&>ëM N‰Ök —sYkX+¨¸©Asjõ$lL)©KN¦aø{õÇ¢8†]ZÅô]˜‰æè£ØF-JŰgƒ£E—§Fzi•¢Ùuè*Q ÇtÑ^kZ%ŠáSÑ0Z]bŽ)†ë Mnô ¶ÖzØÚ[É88£Vʶ¸ðgQµ5êã(vâÖìF'žÍZP¹Ùå¾Vcúpi”·qô›K6¸æ¤àçÎ^dY1j«)…ß±TL‚xQàõ3!qU¶ž 9ë@cìc/§VAÃÃʤþEœH-Îía|&5ÒÕ¢øf«Kz£ê­G•P?×Ï;‰¿‰vª—OÝnÅð§l£·•ÂÙðþÑï~ÓÊD›H<ÿöÑjlÝ=îz5¹¥É•åiV”¢s©u„•ÂúκHµ²õ‘Þâ1ŒnKÓo= 'åÕb8¦£ÞÞÖZÃùOÅzt\jÌàë ÎQWÌ9ZÐâõœÃ{Õ8ê}+'³’ŽbÅ®æèZ3«5j¬5n4î ††qØd0û>>|òG]@ç¨Ýlœœ)Äs©S€§SwWlH±C\ÓµžŠ/µ¸¹"3+2ã°"3ouãðæ3+²ðÑ·¨Éêï·M4'ø¸ÊÔcjQšL9®Éì3lÍÅÉ5™k2ã°&3k2›¬ÉšµÊ œõöðøZÕJá´ªu?e 6¬µÞ”,/¼…´—X?ÔµX³“ØUÓº‰Þ:Á­«¸4#Þ¢š3³Æp%ºrØz¸Ë–R¸T)z]D)þž–st-+·àBå°o®¶7¬—Ôœ²I¡:ÏäÝÛBwœÍdk,ø£ ÎÑ-gSÙ[–¸„Ý0zÀ¦²×IÕ2¬·º°Õ¦6o ˜RŬØs"ã¢Ô <=õ£Rxöµ‹x‰è|Кb¸HÀ†F mÃzÓ?›q·BêJQÐ(oе³ÝwÃzV9‰ü§ü½{ÊØÔ¶ÊúÔ†sø<ÐÒ¬gmµ`ݧ‹cúż¦õÞ^ÒõÃtÓ8Ô»¾ƒGgžÌPí#z„ŽN_†¢%)†áóǾ£{Ö91ÿÒ”¾ ‘º3o 5§?¦ÿÄ#T ß1/ÁðQäÜsO$×8j¿vÓ#Ìg?ÆárÀŸƒk±×`—;i`øc—ÿ¼°é3ÊâÊ|±Ã=“ä¥8ˆÃ3o =Ê ä{ÉÚ£GàØ›|ƒü­=¾)”Â…™™yqÙ[äÙÓxiÆÄÀ1qúZÔ²ÇñÅmW†h”ÚAlø¾µØß„u kB€¸BícQþ¬¸¹æÖ«J4tfÜ"iÕ,Áú–SÞ…·Á®ÒÈ›Ï]˜JÞ@®Úô=&ú¾­7¸ðcÔ@¾ÊÛcŸ˜À:Âf?Årž˜\¬ö61|# 8á7Õµ”y€ÊÑ2$㸠lµ›|‰*ˆ+¼£Ížò›Šž4Dò¡X~^£ü04ð©gòÙd÷åøíËß|Û—Wí² õöÆ,ZÅ7“‚,…Qé[iÒ°fkj<åÚúÜâ[{|ëÖHȶ…É[øÆã6BøÜAžRñ‡˜ÄõeÒ¬žaø‹Ùoý<{ òwä ä¡'{?Ÿ+ ë(W†e@v¢£¸DóêûÅ5·¡ƒ8n¥àÀT×z‡7¯Ç‚ ĵ,kdþ¨WpÂ?·›=ÅV¬bÜ51ÊaÏfE"²ýÔ:é¼%t>¹9ê]å‹Ô$OQ%g7! ž|3o{ «7gt¥Eo¢ ·?ÄÏAì…*xðí¤ôiÖÕ8cYš5>±aá­§\³Y [zÞU¾ÜB¡e–¾UZbÁ@îÞ)Èûÿ0_gó~Šq£T9®ƒëלf8¾¬=™—)’/¶–O®Ú¬A>©V¿Ç…o 7K-¦‡ýtoû£v;ŠNbGÝ9\%â$A9Ø•"~S{Y4ùâǾųäÎîÀw)ßÀî~ÄŸ¶z¹>ÖìÇÄ ``»E~Èåh ßÈåU‡O€Þ­ï脉c#ä NÁ‰À@~ȹâ0°+މÀ.LðÀ@~ØUô³ù.iL]9žÜs0°»&»ûqâ0«cË)÷¸ #·N g?5¤†ó”–Þ¬nìubk° å{¸›Sö¹-¦àÉCMZÀ¯ˆøù޲›c¼ùgsƒø°ñ³ÅXÈi /òqîMA¾‡G}').kËpXVRvF´ÄŒÔ9i“g' |aݯ VÄŠM±ÎžO´7Q£ã o¸ø±FUqö­AlM)Èó!Þ ÎÚšÁ™ãxGív 6¥ l·¨;8ÏõŸ5Þ$ßúvYÛ >;|k‘/%–î]zàDQ‘‚zÊrè\ŒÖS\½h-Nè ë*—¿€Ý‡þ£uk=Ýšë¦)‹‰+Ö^sFüÊÛ”r•ª¹é g ?ùl¶Ç‹ Ä _çžC,[6påûBÓ¶<ªé vl ä&¸¾ ƒgFoa¯Ö89¾c ÅÆÇÝoñ}q”X1¾íÃR3ãÃ/¾;ˆŸ%ò%ƒ?ð÷Ö"¾èkàÝ\ÝËќձóƒÍ*=p­­Ë±»rðûo ޾ØÇq"ŸTn¼ë=J³3Ç^”Ãï¾ °)Ãqt§ôh®Ó?Küâ mq œƒ8+5¬Bˆ«F«gÁêÆ’Ò|¡Zå?mlbâafYèƒþ=l"²(Ü͆~·[íšÅÐÒÀrÂg×{U<¶¤ßWî57ñHÒ¨ó;K^3õkc9Œ]'†²Fl&†|fè+øo 8³]x½Ææ”ÇyV ñãh †aØ%]ëŒÂ ‡…oýäù·2 Ä’W ?þkþ‚s8Pãó‚m6ŸK-ê±l’Àg¶q8üaSŠÛªÁ}, Ë à-¡±ÊAúxyÑÊ:ÊNpJF9l[?¹ÒnbÏë…:®c”Ã÷S•Ó=?Ñ /ò¹®0ŸKÚSüð”q]Qp]a¾Öì2?í©2.Dk‘oCkñ)ýôT_Pµñ·}¼¹Æ°ùñk`SŒƒ¿mécäK\@ü„eµtŽB([æ!ê}Q. áx˜r¸ßÆÇ·¾^¦ìÍ ÷ÑW»¾‡=mù}*XŒy{ÜЫ/6抱+j $ºf¦†ßOT»“å%ÃŒ+'ãøádWðø"µË‚]PîQÎŒ‘'9 œ½=Ç=ýÔÄ‹ÛmïÄ“ªñG®£ê«{ýä9 垊-†ÊÃõì&† “Ín´q¡{£Í[lJpð[BÖâÅ­„p£-Û%*Eî“ØƒŠ½©Áu›Þ÷òL]4;:áªì»êbLDtßã4µqݵö⦉)Òîb›ðdmÙ4¥?x)Íj©¾õà žÙŠ*_ðÌ#ì¾ài ìÄ,~a³A>£á¥ÊÜQË:=Ošìã‡oãLuõÙbv,™Ã->ËñÝo 7‡Ã%˜©ÉÁ›x³üÊŒrÜʼS\7†ñ’ù3&ÛR0§œÄCTŒ¿Bæ V7Û¨::ƒqõf ÷ÚÄ‘ù o#¶¦Äõ þ–œ·ˆMiù%o¬m¬Á7vWw3 ä×¹±uc-ò̬·ˆÏbk‘þ òÊVkÇÛ ä:»:îjªªÁ#vò›※‚ö57òÜØÝ"~1Gø äŸ_ðùn´1òýoQ~\’ã Ø©yZCà=š œ°8öî »Õô Nä?­Å›ÿr-g ·µœºÙàÄ•&yŠh³X8.Âw«ceçIµ°Ÿ4™Û´X ßö\—G÷,[ˆŒDçØÀ IÚ»2Ý®Nh}¬iBXW¹è¾Öã³Ê—¹}á¸ÙÕ ›á“j1ŽçÜdkEc NMZ‹Žª8ˆ3w ò|nøï~åDA®¨,Þ„ªÖщÝo`s„úFÄ”0º]å.ðÞ'î4+ØÝÄœÛ-Їׂ§Â­Á oEq¸Ù@¾mˆ<ùn-Þ8n¨ ßRÞ vª}RqˆËçï ùWŽ”›XàŠåŸVpâV{b»EÆø”Z¸A†½F#¾‹ë€Ãm†]ñƒ¯T±±á >Â<úo fF²<êBÍO¦U#ü†º¼¦TÁ™®ÚEs¾öº«Y©˜Ø{wGÝd+¯ïRå¾ݾ†w¾³@κ¯yn|gwáIÚ<È«îk¤‚ÇĪ»ºƒ4'€k³å¹¸ë®Æ×þ»J†eùW=ÆÍ9#e3GA*¨aù˜’?Ôhá[RÁ‰ÏÐY‹ª°òìX“ žÚNúdvBÒ2RÍ[Xª¦Ë³c$®5çIÚ4ûdZÍP†«‚ƒ?Úlà1±è¬IlDµ…õÉ옅Å×ÎÖW>;JØ?c÷s‡Ÿø–rÒÍt•¿âè]]z-š-ì#XØ1UvÔö'-ª}rãÓ@nÐø\:yˆ_r4påf€‚"Ž™å0Ÿ“ÇsäPû-¹Å³~m%ºfÊá(»5·à¤®ƒ8²ç V6ÂH¾ðà-bµzªË¢EöyvÔM’焎‰6þ¢¾üÁq%ŸWuÌpNÀÜšòÐoçUn…–ø(WpâÕYq8ÈÀç¤Æ‹‡6Äg?c€E9¹•±qøÓm6>þ¶—ƒØYQ?S­>ݬ›¼ØÅ@š7ÉóÇc½EülƒüñXoßʳ1òÇc­Eþx¬ïC~¾Y©tSŽ3šßºÚyÍ’Iƒ_?PðÆFªrü _6Í]<ñz¬ƒÍ…:ñz¬ƒø’³ƒ¸4ßAœ`;»o蜖}ä Nƒ8âÝäãÔ^ræ6JH惸âäžjÔˆ_VPCcYþ)lÄÁ™¹±òZ\ fàÄ7IÁ™“ªpÍ QΛpÂa°q½“ƒ|S…PÜLW/~ô¬ƒxù%Ù3-ç¾0™»Ú­¶eÍeA†ÌsÞÈw=9ù b#× IjÒúâÓ²Ýyz¬E\ÕqÖá¦5võzÕ³§õ²œ5vp½Å&8±v. H¬:ÑB*ؘ³eŒq8ˆ½g&'¤¬óä˜×m2gºjV 6X®:'›‡hÏb)jzôE'ךãñ4ñ[N òr`k)Ú@n(È=Ná^v‰PâÛy+†ÏÎ䮑¼èÀAQõQò%Wwf¦Aµ!òîuÔ`nÑ|.ò)·™öøEyPÁ‰¹«érXOùk^ÖS8²%Ý1ŸbÌZ<¸YÅÕŽCŒo_–Šn©|¼ÈÅòâyˆÖ"vÇ®®ßp©E½c_õ2·¯ñù+îVk“¿Ìe FÆA|þÈߨñ1bõï]Åž‘üÀqë*#öþÔë`Qx‹ÝÉ8ä-vA^ZëâÀ–£Í*ÿ¾–µ¸v·óÆ@þæƒØ<¶Éá8¡‘•äOÐ.Ûã·eÔ¹²2«ÇàSG[ÕÁçˆIuyPÅAœÆ7PK«'ä¡F@´¬œY8Às>À‘—ª=ôಠEçx^ã/U[s‡|cØ&pÂÙÀæq‚bw›ø ŠƒØ¹½ëU^2½ÕM¹&ÚÜ ³ˆöü¬EþBÂ]~b"Ë0|b"¯‹ÁàSñ3·ÖU~GÞ@ÉŠN€¼?py¹…¹f„Áßcrñ7× 7ÀtfzÃ+PŽ™øå*Ñ@®u>ùS×_L¬/fP«!x¾÷¶Â ~üÚçE¸c¢]•Dq^nÝÂÛ‚¯8n£àDÜæ®ÃoYö€;÷/äOFYƒ<|YÚ@j¿M'uØ”}˜7° bbq[J ÛUü pñWW\úÍŽÞ4xò²þ…Å›`8‰lœ.Ò‰i–ÌÛÃõn>/8—ð6BZ'aàMíÞàÄv²!òCF{JƒQÞ`wjf6~¨!žY7ö¥e„èÕ,÷n‹£»õñëÇoâàZJAìs¿‘Ÿù¶9ÚKîÙâÄ®{hfßÜgÓÜ®Z3Àœ͘u¸}†Vùq¨ÖÁ ÿY3_|…Û‡ˆºCœð„CYþÔÜðnwhÖÌÀ -. žƒ&h“ž×©r<>¤—¤ù*µ+Ëü@Õi ˜qü9ù¿8º]=¹…ªYATÔ9åvŸp8_úa!Làú%pn€Ûín€—NfÚ›0À튄–-8a€Û5nn€kƒ|Û‡+5ùt²¼5×À&Å®ø'ìhíªTVMLêŒm`sKÍØÑ&ne(8aG7_ }[ãí%Ç­ŒºTbf7NØÑ–òæsc• Ü^°› ª*^œ\ù1lݾâKuã¥ùY²Žg#ì*V¯›q>åøé¦ÃãN›M'-ô‰áA"áΦüÎf{¸´î£èïgsÏèbiy¼d¤7é ÄU@Îá£t©Óùñâ‹"Þ ¾ õ>µLºabàÀwÌ <±o¹hží93yjF=5Yˆ£žš‰eçönЇõ…bÍÖ>¼·ip¢ÖÁÀ Ÿ½ÖU^vb-òÃÉÇÈ÷¡|± ȃX¶hºSƒ ª?ŠË?@Üž¥>øaa ®vPP>491À‰5£A.‰:^žûiµûØÒ[BØ;ÏKˆ{sná¶åÒ BÛÔàâ]ïéľ!áΤ†EtÕ““׸½bÙlq¢úÓºÊ#n>98á Në;Èm”úêÆ‡_¢pW×Å„Ígïûàà§‚ünŠ·ˆï²È¿îôQ6òK~)Ç&Îo±ö7» 6ÂïDñ©á]ÅRËßä7†úú|j4¸Ào| s—&øÂ—!~~Þ¸‰ø g¬›Ü®qÉsÝf ¶ù¼«ø 6× ½«ÿl0¯6õMñ»`£ö¡'8½ó11Àš×Η›|›×ŽsB NˆZÆ÷…9Ãx‘ª‹ÙknB“Z0ƒK°QMöÔBsf&v“}<–¯˜¿ˆ_ò¹üp2°½º›]1…MþÜ2«ùe[{³rÝÁî"Çù»·h¦>® 2[4â¾¼Gwv¸å ¾æd}Ý›-Ž‹ëF“×ýÖ"_¬–³åºÃòÒÍÅ:á{ûäð“Ê@œG5úïm•ãª"¹½©/,>æ¸ð"FoÁx༦‚ú-­¬9¬‚ùÙ` L8a:¤×²<ìF=×ݪéM]E>9!ç“'ÇÒS;ŸíêÆuN¨¸Í`]Æ{º«Ópàž*ȵên©ì†íuø=sK³£uÔ>s]ëxW똟ââ3UA™šxÜ(÷±öH ÜHqnã&6×Ì(Z<†&÷Ïc³Z\3O0oâ`2féÈ'Çì°&'†_VÄvÍŽ¯Ód1δÈç¦[zc ~Yþ¡f'oûð ·¨¬ô†omQ–j> Äâ8¬ž»þG¤ŽKÕ¸ÛpòÍa ¿.k äëgZäU»G¨fɦ˜’Õ^ÜÛÊ@oä¾Ö†ê'}ÝÚMv Î#„cóô¤plîk©ú¤¯G»Éð}ÅÜäY7™§Ç@ît(9Ó×€Ï-†·<5tpàìú¦@œ×3r_»5§†ø{u ê óì¸òÙ Z22øÖÜê¾æA*(a€Ot]î«z>(Ô4@^! 0NývÛçžOS®¸üÃAlðžµRþdŒê·بWPÃd¹« Øà=keþÉ5`ÍKÄö§‚¼ðÛœXãÖӥ٢Ꜽ¬¯øì3œ­¹Eu•Ä€ˆ§¹üyÕ³>Ísšü²C; WȰyJß@ž™¿jó!.ò6g/Xò©±º%. sêðSÞ">sÄ’uµ;«<óxi¶ƒ)8Q3n /!p+G›cœÙÅvÇÈóòÍ¡ /tuÛŽ¾äÚ+§Ùℵj 7ìŠqæñ•È… IäBÀ"rµM•¹`à$înÖ+Üͺƒ;8ã‘ áÃÈ5ÚmõxØ\¸?½‚ÿ›_ýN‚ß 5igraph/tests/testthat.R0000644000175100001440000000013613456351035014674 0ustar hornikuserslibrary(testthat) library(igraph) suppressWarnings(RNGversion("3.5.0")) test_check("igraph") igraph/configure.ac0000644000175100001440000001114213430770211014025 0ustar hornikusersAC_INIT(igraph, 1.2.4, csardi.gabor@gmail.com) AC_CONFIG_SRCDIR(src/rinterface.c) AC_CONFIG_HEADERS(src/config.h) : ${R_HOME=`R RHOME`} if test -z "${R_HOME}"; then echo "could not determine R_HOME" exit 1 fi CC=`"${R_HOME}/bin/R" CMD config CC` CXX=`"${R_HOME}/bin/R" CMD config CXX` FC=`"${R_HOME}/bin/R" CMD config FC` CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS` CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS` CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS` FCFLAGS=`"${R_HOME}/bin/R" CMD config FCFLAGS` FLIBS=`"${R_HOME}/bin/R" CMD config FLIBS` AC_LANG(C) AC_PROG_CC # Fortran compiler, we need to check if it is the GNU compiler AC_PROG_FC if test "x$ac_cv_fc_compiler_gnu" == xyes; then AC_DEFINE([HAVE_GFORTRAN], [1], [Define to 1 if using the GNU fortran compiler]) fi # Tricky check for C++ compiler, because Autoconf has a weird bug: # http://lists.gnu.org/archive/html/autoconf/2006-03/msg00067.html AC_PROG_CXX AC_LANG_PUSH([C++]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include const char hw[] = "Hello, World\n";]], [[std::cout << hw;]])], [AC_PROG_CXXCPP cxx_error=no], [AC_MSG_ERROR([no C++ compiler found or it cannot create executables])]) AC_LANG_POP([C++]) LIBS_SAVE=$LIBS LIBS="$LIBS -lm" AC_CHECK_FUNCS([rintf finite expm1 rint log2 logbl snprintf log1p round fmin stpcpy]) AC_CHECK_DECL([stpcpy], [AC_DEFINE([HAVE_STPCPY_SIGNATURE], [1], [Define to 1 if the stpcpy function has a signature])]) LIBS=$LIBS_SAVE AC_CHECK_HEADER([sys/times.h], [AC_DEFINE([HAVE_TIMES_H], [1], [Define to 1 if you have the sys/times.h header])]) AC_CHECK_HEADERS([ \ net/if.h \ netinet/in.h \ net/if_dl.h \ sys/sockio.h \ sys/un.h \ sys/socket.h \ sys/ioctl.h \ sys/time.h \ sys/file.h \ ]) AC_CHECK_MEMBER([struct sockaddr.sa_len], AC_DEFINE_UNQUOTED([HAVE_SA_LEN], [1], [Define if struct sockaddr contains sa_len]), [], [#include #include ]) graphml_support=yes AC_ARG_ENABLE(graphml, AC_HELP_STRING([--disable-graphml], [Disable support for GraphML format]), [graphml_support=$enableval], [graphml_support=yes]) HAVE_LIBXML=0 if test $graphml_support = yes; then AC_PATH_PROG([XML2CONFIG], [xml2-config], [none]) if test "$XML2CONFIG" = "none"; then graphml_support=no else XML2_LIBS=`$XML2CONFIG --libs` XML2_CFLAGS=`$XML2CONFIG --cflags` AC_CHECK_LIB([xml2], [xmlSAXUserParseFile], [ OLDCFLAGS=${CFLAGS} OLDCPPFLAGS=${CPPFLAGS} CFLAGS=${XML2_CFLAGS} CPPFLAGS=${XML2_CFLAGS} AC_CHECK_HEADER([libxml/parser.h], [ HAVE_LIBXML=1 AC_DEFINE([HAVE_LIBXML], [1], [Define to 1 if you have the libxml2 libraries installed]) CFLAGS="${OLDCFLAGS} ${XML2_CFLAGS}" CPPFLAGS="${OLDCFLAGS} ${XML2_CFLAGS}" AC_SUBST(XML2_LIBS) AC_SUBST(XML2_CFLAGS) ], [ graphml_support=no CFLAGS=${OLDCFLAGS} CPPFLAGS=${OLDCPPFLAGS} ]) ], [ graphml_support=no ]) fi fi AC_SUBST(HAVE_LIBXML) AC_LANG_PUSH([C++]) HAVE_GMP=0 GMP_LIBS="" gmp_support=no AC_ARG_ENABLE(gmp, AC_HELP_STRING([--disable-gmp], [Compile without the GMP library])) if test "x$enable_gmp" != "xno"; then AC_CHECK_LIB([gmp], [__gmpz_add], [ AC_CHECK_HEADER([gmp.h], [ HAVE_GMP=1 AC_DEFINE([HAVE_GMP], [1], [Define to 1 if you have the GMP library]) gmp_support=yes GMP_LIBS="-lgmp" ]) ]) fi AC_SUBST(HAVE_GMP) AC_SUBST(GMP_LIBS) AC_LANG_POP([C++]) glpk_support=no AC_ARG_ENABLE(glpk, AC_HELP_STRING([--enable-glpk], [Enable support for GLPK]), [glpk_support=$enableval], [glpk_support=yes]) HAVE_GLPK=0 if test $glpk_support = yes; then glpk_support=no AC_CHECK_LIB([glpk], [glp_read_mps], [ AC_CHECK_HEADER([glpk.h], [ AC_EGREP_CPP(yes, [ #include #if GLP_MAJOR_VERSION > 4 || (GLP_MAJOR_VERSION == 4 && GLP_MINOR_VERSION >= 38) yes #endif ], [ AC_DEFINE([HAVE_GLPK], [1], [Define to 1 if you have the GLPK library]) HAVE_GLPK=1 glpk_support=yes GLPK_LIBS="-lglpk" AC_SUBST(GLPK_LIBS) ]) ]) ]) fi AC_SUBST(HAVE_GLPK) AC_DEFINE(IGRAPH_THREAD_LOCAL, [], [We don't care about thread-local storage in R]) AC_CONFIG_FILES([src/Makevars.tmp:src/Makevars.in], [ if test -f src/Makevars && cmp -s src/Makevars.tmp src/Makevars; then AC_MSG_NOTICE([creating src/Makevars]) AC_MSG_NOTICE([src/Makevars is unchanged]) rm src/Makevars.tmp else AC_MSG_NOTICE([creating src/Makevars]) mv src/Makevars.tmp src/Makevars fi ] ) AC_OUTPUT igraph/src/0000755000175100001440000000000013562473035012341 5ustar hornikusersigraph/src/pottsmodel_2.h0000644000175100001440000001534413431000472015116 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt This file was modified by Vincent Traag The original copyright notice follows here */ /*************************************************************************** pottsmodel.h - description ------------------- begin : Fri May 28 2004 copyright : (C) 2004 by email : ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef POTTSMODEL_H #define POTTSMODEL_H #include "NetDataTypes.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #define qmax 500 class PottsModel { private: // HugeArray neg_gammalookup; // HugeArray pos_gammalookup; DL_Indexed_List *new_spins; DL_Indexed_List *previous_spins; HugeArray*> correlation; network *net; unsigned int q; unsigned int operation_mode; FILE *Qfile, *Magfile; double Qmatrix[qmax+1][qmax+1]; double* Qa; double* weights; double total_degree_sum; unsigned long num_of_nodes; unsigned long num_of_links; unsigned long k_max; double energy; double acceptance; double *neighbours; public: PottsModel(network *net, unsigned int q, int norm_by_degree); ~PottsModel(); double* color_field; unsigned long assign_initial_conf(int spin); unsigned long initialize_lookup(double kT, double gamma); double initialize_Qmatrix(void); double calculate_Q(void); double calculate_genQ(double gamma); double FindStartTemp(double gamma, double prob, double ts); long HeatBathParallelLookupZeroTemp(double gamma, double prob, unsigned int max_sweeps); double HeatBathLookupZeroTemp(double gamma, double prob, unsigned int max_sweeps); long HeatBathParallelLookup(double gamma, double prob, double kT, unsigned int max_sweeps); double HeatBathLookup(double gamma, double prob, double kT, unsigned int max_sweeps); double GammaSweep(double gamma_start, double gamma_stop, double prob, unsigned int steps, bool non_parallel=true, int repetitions=1); double GammaSweepZeroTemp(double gamma_start, double gamma_stop, double prob, unsigned int steps, bool non_parallel=true, int repetitions=1); long WriteCorrelationMatrix(char *filename); double calculate_energy(double gamma); long WriteClusters(igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *csize, igraph_vector_t *membership, double kT, double gamma); long WriteSoftClusters(char *filename, double threshold); double Get_Energy(void) { return energy;} double FindCommunityFromStart(double gamma, double prob, char *nodename, igraph_vector_t *result, igraph_real_t *cohesion, igraph_real_t *adhesion, igraph_integer_t *inner_links, igraph_integer_t *outer_links); }; class PottsModelN { private: // HugeArray neg_gammalookup; // HugeArray pos_gammalookup; DL_Indexed_List *new_spins; DL_Indexed_List *previous_spins; HugeArray*> correlation; network *net; unsigned int q; //number of communities double m_p; //number of positive ties (or sum of degrees), this equals the number of edges only if it is undirected and each edge has a weight of 1 double m_n; //number of negative ties (or sum of degrees) unsigned int num_nodes; //number of nodes bool is_directed; bool is_init; double *degree_pos_in; //Postive indegree of the nodes (or sum of weights) double *degree_neg_in; //Negative indegree of the nodes (or sum of weights) double *degree_pos_out; //Postive outdegree of the nodes (or sum of weights) double *degree_neg_out; //Negative outdegree of the nodes (or sum of weights) double *degree_community_pos_in; //Positive sum of indegree for communities double *degree_community_neg_in; //Negative sum of indegree for communities double *degree_community_pos_out; //Positive sum of outegree for communities double *degree_community_neg_out; //Negative sum of outdegree for communities unsigned int *csize; //The number of nodes in each community unsigned int *spin; //The membership of each node double *neighbours; //Array of neighbours of a vertex in each community double *weights; //Weights of all possible transitions to another community public: PottsModelN(network *n, unsigned int num_communities, bool directed); ~PottsModelN(); void assign_initial_conf(bool init_spins); double FindStartTemp(double gamma, double lambda, double ts); double HeatBathLookup(double gamma, double lambda, double t, unsigned int max_sweeps); double HeatBathJoin(double gamma, double lambda); double HeatBathLookupZeroTemp(double gamma, double lambda, unsigned int max_sweeps); long WriteClusters(igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *community_size, igraph_vector_t *membership, igraph_matrix_t *adhesion, igraph_matrix_t *normalised_adhesion, igraph_real_t *polarization, double t, double d_p, double d_n, double gamma, double lambda); }; #endif igraph/src/progress.c0000644000175100001440000001332013431000472014332 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_progress.h" #include "config.h" static IGRAPH_THREAD_LOCAL igraph_progress_handler_t *igraph_i_progress_handler=0; static IGRAPH_THREAD_LOCAL char igraph_i_progressmsg_buffer[1000]; /** * \function igraph_progress * Report progress * * Note that the usual way to report progress is the \ref IGRAPH_PROGRESS * macro, as that takes care of the return value of the progress * handler. * \param message A string describing the function or algorithm * that is reporting the progress. Current igraph functions * always use the name \p message argument if reporting from the * same function. * \param percent Numeric, the percentage that was completed by the * algorithm or function. * \param data User-defined data. Current igraph functions that * report progress pass a null pointer here. Users can * write their own progress handlers and functions with progress * reporting, and then pass some meaningfull context here. * \return If there is a progress handler installed and * it does not return \c IGRAPH_SUCCESS, then \c IGRAPH_INTERRUPTED * is returned. * * Time complexity: O(1). */ int igraph_progress(const char *message, igraph_real_t percent, void *data) { if (igraph_i_progress_handler) { if (igraph_i_progress_handler(message, percent, data) != IGRAPH_SUCCESS) return IGRAPH_INTERRUPTED; } return IGRAPH_SUCCESS; } /** * \function igraph_progressf * Report progress, printf-like version * * This is a more flexible version of \ref igraph_progress(), with * a printf-like template string. First the template string * is filled with the additional arguments and then \ref * igraph_progress() is called. * * Note that there is an upper limit for the length of * the \p message string, currently 1000 characters. * \param message A string describing the function or algorithm * that is reporting the progress. For this function this is a * template string, using the same syntax as the standard * \c libc \c printf function. * \param percent Numeric, the percentage that was completed by the * algorithm or function. * \param data User-defined data. Current igraph functions that * report progress pass a null pointer here. Users can * write their own progress handlers and functions with progress * reporting, and then pass some meaningfull context here. * \param ... Additional argument that were specified in the * \p message argument. * \return If there is a progress handler installed and * it does not return \c IGRAPH_SUCCESS, then \c IGRAPH_INTERRUPTED * is returned. * \return */ int igraph_progressf(const char *message, igraph_real_t percent, void *data, ...) { va_list ap; va_start(ap, data); vsnprintf(igraph_i_progressmsg_buffer, sizeof(igraph_i_progressmsg_buffer) / sizeof(char), message, ap); return igraph_progress(igraph_i_progressmsg_buffer, percent, data); } #ifndef USING_R /** * \function igraph_progress_handler_stderr * A simple predefined progress handler * * This simple progress handler first prints \p message, and then * the percentage complete value in a short message to standard error. * \param message A string describing the function or algorithm * that is reporting the progress. Current igraph functions * always use the name \p message argument if reporting from the * same function. * \param percent Numeric, the percentage that was completed by the * algorithm or function. * \param data User-defined data. Current igraph functions that * report progress pass a null pointer here. Users can * write their own progress handlers and functions with progress * reporting, and then pass some meaningfull context here. * \return This function always returns with \c IGRAPH_SUCCESS. * * Time complexity: O(1). */ int igraph_progress_handler_stderr(const char *message, igraph_real_t percent, void* data) { IGRAPH_UNUSED(data); fputs(message, stderr); fprintf(stderr, "%.1f percent ready\n", (double)percent); return 0; } #endif /** * \function igraph_set_progress_handler * Install a progress handler, or remove the current handler * * There is a single simple predefined progress handler: * \ref igraph_progress_handler_stderr(). * \param new_handler Pointer to a function of type * \ref igraph_progress_handler_t, the progress handler function to * install. To uninstall the current progress handler, this argument * can be a null pointer. * \return Pointer to the previously installed progress handler function. * * Time complexity: O(1). */ igraph_progress_handler_t * igraph_set_progress_handler(igraph_progress_handler_t new_handler) { igraph_progress_handler_t *previous_handler=igraph_i_progress_handler; igraph_i_progress_handler = new_handler; return previous_handler; } igraph/src/drl_layout_3d.h0000644000175100001440000000561213431000472015244 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains compile time parameters which affect the entire // DrL program. #define DRL_VERSION "3.2 5/5/2006" // compile time parameters for MPI message passing #define MAX_PROCS 256 // maximum number of processors #define MAX_FILE_NAME 250 // max length of filename #define MAX_INT_LENGTH 4 // max length of integer suffix of intermediate .coord file // Compile time adjustable parameters for the Density grid #define GRID_SIZE 100 // size of Density grid #define VIEW_SIZE 250.0 // actual physical size of layout plane // these values use more memory but have // little effect on performance or layout #define RADIUS 10 // radius for density fall-off: // larger values tends to slow down // the program and clump the data #define HALF_VIEW 125.0 // 1/2 of VIEW_SIZE #define VIEW_TO_GRID .4 // ratio of GRID_SIZE to VIEW_SIZE /* // original values for VxOrd #define GRID_SIZE 400 // size of VxOrd Density grid #define VIEW_SIZE 1600.0 // actual physical size of VxOrd plane #define RADIUS 10 // radius for density fall-off #define HALF_VIEW 800 // 1/2 of VIEW_SIZE #define VIEW_TO_GRID .25 // ratio of GRID_SIZE to VIEW_SIZE */ igraph/src/math.c0000644000175100001440000002072513431000472013426 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include "config.h" #include "igraph_math.h" #include "igraph_types.h" #ifdef _MSC_VER # define isinf(x) (!_finite(x) && !_isnan(x)) #endif int igraph_finite(double x) { #ifdef isfinite return isfinite(x); #elif HAVE_ISFINITE == 1 return isfinite(x); #elif HAVE_FINITE == 1 return finite(x); #else /* neither finite nor isfinite work. Do we really need the AIX exception? */ # ifdef _AIX # include return FINITE(x); # else return (!isnan(x) & (x != IGRAPH_POSINFINITY) & (x != IGRAPH_NEGINFINITY)); # endif #endif } double igraph_log2(const double a) { return log(a)/log(2.0); } int igraph_chebyshev_init(const double *dos, int nos, double eta) { int i, ii; double err; if (nos < 1) return 0; err = 0.0; i = 0; /* just to avoid compiler warnings */ for (ii=1; ii<=nos; ii++) { i = nos - ii; err += fabs(dos[i]); if (err > eta) { return i; } } return i; } double igraph_chebyshev_eval(double x, const double *a, const int n) { double b0, b1, b2, twox; int i; if (n < 1 || n > 1000) IGRAPH_NAN; if (x < -1.1 || x > 1.1) IGRAPH_NAN; twox = x * 2; b2 = b1 = 0; b0 = 0; for (i = 1; i <= n; i++) { b2 = b1; b1 = b0; b0 = twox * b1 - b2 + a[n - i]; } return (b0 - b2) * 0.5; } double igraph_log1p(double x) { /* series for log1p on the interval -.375 to .375 * with weighted error 6.35e-32 * log weighted error 31.20 * significant figures required 30.93 * decimal places required 32.01 */ static const double alnrcs[43] = { +.10378693562743769800686267719098e+1, -.13364301504908918098766041553133e+0, +.19408249135520563357926199374750e-1, -.30107551127535777690376537776592e-2, +.48694614797154850090456366509137e-3, -.81054881893175356066809943008622e-4, +.13778847799559524782938251496059e-4, -.23802210894358970251369992914935e-5, +.41640416213865183476391859901989e-6, -.73595828378075994984266837031998e-7, +.13117611876241674949152294345011e-7, -.23546709317742425136696092330175e-8, +.42522773276034997775638052962567e-9, -.77190894134840796826108107493300e-10, +.14075746481359069909215356472191e-10, -.25769072058024680627537078627584e-11, +.47342406666294421849154395005938e-12, -.87249012674742641745301263292675e-13, +.16124614902740551465739833119115e-13, -.29875652015665773006710792416815e-14, +.55480701209082887983041321697279e-15, -.10324619158271569595141333961932e-15, +.19250239203049851177878503244868e-16, -.35955073465265150011189707844266e-17, +.67264542537876857892194574226773e-18, -.12602624168735219252082425637546e-18, +.23644884408606210044916158955519e-19, -.44419377050807936898878389179733e-20, +.83546594464034259016241293994666e-21, -.15731559416479562574899253521066e-21, +.29653128740247422686154369706666e-22, -.55949583481815947292156013226666e-23, +.10566354268835681048187284138666e-23, -.19972483680670204548314999466666e-24, +.37782977818839361421049855999999e-25, -.71531586889081740345038165333333e-26, +.13552488463674213646502024533333e-26, -.25694673048487567430079829333333e-27, +.48747756066216949076459519999999e-28, -.92542112530849715321132373333333e-29, +.17578597841760239233269760000000e-29, -.33410026677731010351377066666666e-30, +.63533936180236187354180266666666e-31, }; static IGRAPH_THREAD_LOCAL int nlnrel = 0; static IGRAPH_THREAD_LOCAL double xmin = 0.0; if (xmin == 0.0) xmin = -1 + sqrt(DBL_EPSILON);/*was sqrt(d1mach(4)); */ if (nlnrel == 0) /* initialize chebychev coefficients */ nlnrel = igraph_chebyshev_init(alnrcs, 43, DBL_EPSILON/20);/*was .1*d1mach(3)*/ if (x == 0.) return 0.;/* speed */ if (x == -1) return(IGRAPH_NEGINFINITY); if (x < -1) return(IGRAPH_NAN); if (fabs(x) <= .375) { /* Improve on speed (only); again give result accurate to IEEE double precision: */ if(fabs(x) < .5 * DBL_EPSILON) return x; if( (0 < x && x < 1e-8) || (-1e-9 < x && x < 0)) return x * (1 - .5 * x); /* else */ return x * (1 - x * igraph_chebyshev_eval(x / .375, alnrcs, nlnrel)); } /* else */ /* if (x < xmin) { */ /* /\* answer less than half precision because x too near -1 *\/ */ /* ML_ERROR(ME_PRECISION, "log1p"); */ /* } */ return log(1 + x); } long double igraph_fabsl(long double a) { if (a<0) { return -a; } else { return a; } } double igraph_fmin(double a, double b) { if (b 0) { va_start(args, format); n = _vsnprintf(buffer, count, format, args); buffer[count-1] = 0; va_end(args); } else n=0; return n; } #endif int igraph_is_nan(double x) { return isnan(x); } int igraph_is_inf(double x) { return isinf(x) != 0; } int igraph_is_posinf(double x) { return isinf(x) == 1; } int igraph_is_neginf(double x) { return isinf(x) == -1; } /** * \function igraph_almost_equals * Compare two double-precision floats with a tolerance * * Determines whether two double-precision floats are "almost equal" * to each other with a given level of tolerance on the relative error. * * \param a the first float * \param b the second float * \param eps the level of tolerance on the relative error. The relative * error is defined as \c "abs(a-b) / (abs(a) + abs(b))". The * two numbers are considered equal if this is less than \c eps. * * \return nonzero if the two floats are nearly equal to each other within * the given level of tolerance, zero otherwise */ int igraph_almost_equals(double a, double b, double eps) { return igraph_cmp_epsilon(a, b, eps) == 0 ? 1 : 0; } /** * \function igraph_cmp_epsilon * Compare two double-precision floats with a tolerance * * Determines whether two double-precision floats are "almost equal" * to each other with a given level of tolerance on the relative error. * * \param a the first float * \param b the second float * \param eps the level of tolerance on the relative error. The relative * error is defined as \c "abs(a-b) / (abs(a) + abs(b))". The * two numbers are considered equal if this is less than \c eps. * * \return zero if the two floats are nearly equal to each other within * the given level of tolerance, positive number if the first float is * larger, negative number if the second float is larger */ int igraph_cmp_epsilon(double a, double b, double eps) { double diff; double abs_diff; if (a == b) { /* shortcut, handles infinities */ return 0; } diff = a-b; abs_diff = fabs(diff); if (a == 0 || b == 0 || diff < DBL_MIN) { /* a or b is zero or both are extremely close to it; relative * error is less meaningful here so just compare it with * epsilon */ return abs_diff < (eps * DBL_MIN) ? 0 : (diff < 0 ? -1 : 1); } else { /* use relative error */ return (abs_diff / (fabs(a) + fabs(b)) < eps) ? 0 : (diff < 0 ? -1 : 1); } } igraph/src/igraph_threading.h0000644000175100001440000000225713431000472016001 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_THREADING_H #define IGRAPH_THREADING_H #include "igraph_decls.h" __BEGIN_DECLS /** * \define IGRAPH_THREAD_SAFE * * Macro that is defined to be 1 if the current build of the * igraph library is thread-safe, and 0 if it is not. */ #define IGRAPH_THREAD_SAFE 0 __END_DECLS #endif igraph/src/dlaqrb.f0000644000175100001440000004405013431000472013742 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdlaqrb c c\Description: c Compute the eigenvalues and the Schur decomposition of an upper c Hessenberg submatrix in rows and columns ILO to IHI. Only the c last component of the Schur vectors are computed. c c This is mostly a modification of the LAPACK routine dlahqr. c c\Usage: c call igraphdlaqrb c ( WANTT, N, ILO, IHI, H, LDH, WR, WI, Z, INFO ) c c\Arguments c WANTT Logical variable. (INPUT) c = .TRUE. : the full Schur form T is required; c = .FALSE.: only eigenvalues are required. c c N Integer. (INPUT) c The order of the matrix H. N >= 0. c c ILO Integer. (INPUT) c IHI Integer. (INPUT) c It is assumed that H is already upper quasi-triangular in c rows and columns IHI+1:N, and that H(ILO,ILO-1) = 0 (unless c ILO = 1). SLAQRB works primarily with the Hessenberg c submatrix in rows and columns ILO to IHI, but applies c transformations to all of H if WANTT is .TRUE.. c 1 <= ILO <= max(1,IHI); IHI <= N. c c H Double precision array, dimension (LDH,N). (INPUT/OUTPUT) c On entry, the upper Hessenberg matrix H. c On exit, if WANTT is .TRUE., H is upper quasi-triangular in c rows and columns ILO:IHI, with any 2-by-2 diagonal blocks in c standard form. If WANTT is .FALSE., the contents of H are c unspecified on exit. c c LDH Integer. (INPUT) c The leading dimension of the array H. LDH >= max(1,N). c c WR Double precision array, dimension (N). (OUTPUT) c WI Double precision array, dimension (N). (OUTPUT) c The real and imaginary parts, respectively, of the computed c eigenvalues ILO to IHI are stored in the corresponding c elements of WR and WI. If two eigenvalues are computed as a c complex conjugate pair, they are stored in consecutive c elements of WR and WI, say the i-th and (i+1)th, with c WI(i) > 0 and WI(i+1) < 0. If WANTT is .TRUE., the c eigenvalues are stored in the same order as on the diagonal c of the Schur form returned in H, with WR(i) = H(i,i), and, if c H(i:i+1,i:i+1) is a 2-by-2 diagonal block, c WI(i) = sqrt(H(i+1,i)*H(i,i+1)) and WI(i+1) = -WI(i). c c Z Double precision array, dimension (N). (OUTPUT) c On exit Z contains the last components of the Schur vectors. c c INFO Integer. (OUPUT) c = 0: successful exit c > 0: SLAQRB failed to compute all the eigenvalues ILO to IHI c in a total of 30*(IHI-ILO+1) iterations; if INFO = i, c elements i+1:ihi of WR and WI contain those eigenvalues c which have been successfully computed. c c\Remarks c 1. None. c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c dlabad LAPACK routine that computes machine constants. c dlamch LAPACK routine that determines machine constants. c dlanhs LAPACK routine that computes various norms of a matrix. c dlanv2 LAPACK routine that computes the Schur factorization of c 2 by 2 nonsymmetric matrix in standard form. c dlarfg LAPACK Householder reflection construction routine. c dcopy Level 1 BLAS that copies one vector to another. c drot Level 1 BLAS that applies a rotation to a 2 by 2 matrix. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.4' c Modified from the LAPACK routine dlahqr so that only the c last component of the Schur vectors are computed. c c\SCCS Information: @(#) c FILE: laqrb.F SID: 2.2 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c 1. None c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdlaqrb ( wantt, n, ilo, ihi, h, ldh, wr, wi, & z, info ) c c %------------------% c | Scalar Arguments | c %------------------% c logical wantt integer ihi, ilo, info, ldh, n c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & h( ldh, * ), wi( * ), wr( * ), z( * ) c c %------------% c | Parameters | c %------------% c Double precision & zero, one, dat1, dat2 parameter (zero = 0.0D+0, one = 1.0D+0, dat1 = 7.5D-1, & dat2 = -4.375D-1) c c %------------------------% c | Local Scalars & Arrays | c %------------------------% c integer i, i1, i2, itn, its, j, k, l, m, nh, nr Double precision & cs, h00, h10, h11, h12, h21, h22, h33, h33s, & h43h34, h44, h44s, ovfl, s, smlnum, sn, sum, & t1, t2, t3, tst1, ulp, unfl, v1, v2, v3 Double precision & v( 3 ), work( 1 ) c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlamch, dlanhs external dlamch, dlanhs c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, dlabad, dlanv2, dlarfg, drot c c %-----------------------% c | Executable Statements | c %-----------------------% c info = 0 c c %--------------------------% c | Quick return if possible | c %--------------------------% c if( n.eq.0 ) & return if( ilo.eq.ihi ) then wr( ilo ) = h( ilo, ilo ) wi( ilo ) = zero return end if c c %---------------------------------------------% c | Initialize the vector of last components of | c | the Schur vectors for accumulation. | c %---------------------------------------------% c do 5 j = 1, n-1 z(j) = zero 5 continue z(n) = one c nh = ihi - ilo + 1 c c %-------------------------------------------------------------% c | Set machine-dependent constants for the stopping criterion. | c | If norm(H) <= sqrt(OVFL), overflow should not occur. | c %-------------------------------------------------------------% c unfl = dlamch( 'safe minimum' ) ovfl = one / unfl call dlabad( unfl, ovfl ) ulp = dlamch( 'precision' ) smlnum = unfl*( nh / ulp ) c c %---------------------------------------------------------------% c | I1 and I2 are the indices of the first row and last column | c | of H to which transformations must be applied. If eigenvalues | c | only are computed, I1 and I2 are set inside the main loop. | c | Zero out H(J+2,J) = ZERO for J=1:N if WANTT = .TRUE. | c | else H(J+2,J) for J=ILO:IHI-ILO-1 if WANTT = .FALSE. | c %---------------------------------------------------------------% c if( wantt ) then i1 = 1 i2 = n do 8 i=1,i2-2 h(i1+i+1,i) = zero 8 continue else do 9 i=1, ihi-ilo-1 h(ilo+i+1,ilo+i-1) = zero 9 continue end if c c %---------------------------------------------------% c | ITN is the total number of QR iterations allowed. | c %---------------------------------------------------% c itn = 30*nh c c ------------------------------------------------------------------ c The main loop begins here. I is the loop index and decreases from c IHI to ILO in steps of 1 or 2. Each iteration of the loop works c with the active submatrix in rows and columns L to I. c Eigenvalues I+1 to IHI have already converged. Either L = ILO or c H(L,L-1) is negligible so that the matrix splits. c ------------------------------------------------------------------ c i = ihi 10 continue l = ilo if( i.lt.ilo ) & go to 150 c %--------------------------------------------------------------% c | Perform QR iterations on rows and columns ILO to I until a | c | submatrix of order 1 or 2 splits off at the bottom because a | c | subdiagonal element has become negligible. | c %--------------------------------------------------------------% do 130 its = 0, itn c c %----------------------------------------------% c | Look for a single small subdiagonal element. | c %----------------------------------------------% c do 20 k = i, l + 1, -1 tst1 = abs( h( k-1, k-1 ) ) + abs( h( k, k ) ) if( tst1.eq.zero ) & tst1 = dlanhs( '1', i-l+1, h( l, l ), ldh, work ) if( abs( h( k, k-1 ) ).le.max( ulp*tst1, smlnum ) ) & go to 30 20 continue 30 continue l = k if( l.gt.ilo ) then c c %------------------------% c | H(L,L-1) is negligible | c %------------------------% c h( l, l-1 ) = zero end if c c %-------------------------------------------------------------% c | Exit from loop if a submatrix of order 1 or 2 has split off | c %-------------------------------------------------------------% c if( l.ge.i-1 ) & go to 140 c c %---------------------------------------------------------% c | Now the active submatrix is in rows and columns L to I. | c | If eigenvalues only are being computed, only the active | c | submatrix need be transformed. | c %---------------------------------------------------------% c if( .not.wantt ) then i1 = l i2 = i end if c if( its.eq.10 .or. its.eq.20 ) then c c %-------------------% c | Exceptional shift | c %-------------------% c s = abs( h( i, i-1 ) ) + abs( h( i-1, i-2 ) ) h44 = dat1*s h33 = h44 h43h34 = dat2*s*s c else c c %-----------------------------------------% c | Prepare to use Wilkinson's double shift | c %-----------------------------------------% c h44 = h( i, i ) h33 = h( i-1, i-1 ) h43h34 = h( i, i-1 )*h( i-1, i ) end if c c %-----------------------------------------------------% c | Look for two consecutive small subdiagonal elements | c %-----------------------------------------------------% c do 40 m = i - 2, l, -1 c c %---------------------------------------------------------% c | Determine the effect of starting the double-shift QR | c | iteration at row M, and see if this would make H(M,M-1) | c | negligible. | c %---------------------------------------------------------% c h11 = h( m, m ) h22 = h( m+1, m+1 ) h21 = h( m+1, m ) h12 = h( m, m+1 ) h44s = h44 - h11 h33s = h33 - h11 v1 = ( h33s*h44s-h43h34 ) / h21 + h12 v2 = h22 - h11 - h33s - h44s v3 = h( m+2, m+1 ) s = abs( v1 ) + abs( v2 ) + abs( v3 ) v1 = v1 / s v2 = v2 / s v3 = v3 / s v( 1 ) = v1 v( 2 ) = v2 v( 3 ) = v3 if( m.eq.l ) & go to 50 h00 = h( m-1, m-1 ) h10 = h( m, m-1 ) tst1 = abs( v1 )*( abs( h00 )+abs( h11 )+abs( h22 ) ) if( abs( h10 )*( abs( v2 )+abs( v3 ) ).le.ulp*tst1 ) & go to 50 40 continue 50 continue c c %----------------------% c | Double-shift QR step | c %----------------------% c do 120 k = m, i - 1 c c ------------------------------------------------------------ c The first iteration of this loop determines a reflection G c from the vector V and applies it from left and right to H, c thus creating a nonzero bulge below the subdiagonal. c c Each subsequent iteration determines a reflection G to c restore the Hessenberg form in the (K-1)th column, and thus c chases the bulge one step toward the bottom of the active c submatrix. NR is the order of G. c ------------------------------------------------------------ c nr = min( 3, i-k+1 ) if( k.gt.m ) & call dcopy( nr, h( k, k-1 ), 1, v, 1 ) call dlarfg( nr, v( 1 ), v( 2 ), 1, t1 ) if( k.gt.m ) then h( k, k-1 ) = v( 1 ) h( k+1, k-1 ) = zero if( k.lt.i-1 ) & h( k+2, k-1 ) = zero else if( m.gt.l ) then h( k, k-1 ) = -h( k, k-1 ) end if v2 = v( 2 ) t2 = t1*v2 if( nr.eq.3 ) then v3 = v( 3 ) t3 = t1*v3 c c %------------------------------------------------% c | Apply G from the left to transform the rows of | c | the matrix in columns K to I2. | c %------------------------------------------------% c do 60 j = k, i2 sum = h( k, j ) + v2*h( k+1, j ) + v3*h( k+2, j ) h( k, j ) = h( k, j ) - sum*t1 h( k+1, j ) = h( k+1, j ) - sum*t2 h( k+2, j ) = h( k+2, j ) - sum*t3 60 continue c c %----------------------------------------------------% c | Apply G from the right to transform the columns of | c | the matrix in rows I1 to min(K+3,I). | c %----------------------------------------------------% c do 70 j = i1, min( k+3, i ) sum = h( j, k ) + v2*h( j, k+1 ) + v3*h( j, k+2 ) h( j, k ) = h( j, k ) - sum*t1 h( j, k+1 ) = h( j, k+1 ) - sum*t2 h( j, k+2 ) = h( j, k+2 ) - sum*t3 70 continue c c %----------------------------------% c | Accumulate transformations for Z | c %----------------------------------% c sum = z( k ) + v2*z( k+1 ) + v3*z( k+2 ) z( k ) = z( k ) - sum*t1 z( k+1 ) = z( k+1 ) - sum*t2 z( k+2 ) = z( k+2 ) - sum*t3 else if( nr.eq.2 ) then c c %------------------------------------------------% c | Apply G from the left to transform the rows of | c | the matrix in columns K to I2. | c %------------------------------------------------% c do 90 j = k, i2 sum = h( k, j ) + v2*h( k+1, j ) h( k, j ) = h( k, j ) - sum*t1 h( k+1, j ) = h( k+1, j ) - sum*t2 90 continue c c %----------------------------------------------------% c | Apply G from the right to transform the columns of | c | the matrix in rows I1 to min(K+3,I). | c %----------------------------------------------------% c do 100 j = i1, i sum = h( j, k ) + v2*h( j, k+1 ) h( j, k ) = h( j, k ) - sum*t1 h( j, k+1 ) = h( j, k+1 ) - sum*t2 100 continue c c %----------------------------------% c | Accumulate transformations for Z | c %----------------------------------% c sum = z( k ) + v2*z( k+1 ) z( k ) = z( k ) - sum*t1 z( k+1 ) = z( k+1 ) - sum*t2 end if 120 continue 130 continue c c %-------------------------------------------------------% c | Failure to converge in remaining number of iterations | c %-------------------------------------------------------% c info = i return 140 continue if( l.eq.i ) then c c %------------------------------------------------------% c | H(I,I-1) is negligible: one eigenvalue has converged | c %------------------------------------------------------% c wr( i ) = h( i, i ) wi( i ) = zero else if( l.eq.i-1 ) then c c %--------------------------------------------------------% c | H(I-1,I-2) is negligible; | c | a pair of eigenvalues have converged. | c | | c | Transform the 2-by-2 submatrix to standard Schur form, | c | and compute and store the eigenvalues. | c %--------------------------------------------------------% c call dlanv2( h( i-1, i-1 ), h( i-1, i ), h( i, i-1 ), & h( i, i ), wr( i-1 ), wi( i-1 ), wr( i ), wi( i ), & cs, sn ) if( wantt ) then c c %-----------------------------------------------------% c | Apply the transformation to the rest of H and to Z, | c | as required. | c %-----------------------------------------------------% c if( i2.gt.i ) & call drot( i2-i, h( i-1, i+1 ), ldh, h( i, i+1 ), ldh, & cs, sn ) call drot( i-i1-1, h( i1, i-1 ), 1, h( i1, i ), 1, cs, sn ) sum = cs*z( i-1 ) + sn*z( i ) z( i ) = cs*z( i ) - sn*z( i-1 ) z( i-1 ) = sum end if end if c c %---------------------------------------------------------% c | Decrement number of remaining iterations, and return to | c | start of the main loop with new value of I. | c %---------------------------------------------------------% c itn = itn - its i = l - 1 go to 10 150 continue return c c %---------------% c | End of igraphdlaqrb | c %---------------% c end igraph/src/visitors.c0000644000175100001440000004411613431000472014357 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph R package. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_visitor.h" #include "igraph_memory.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_dqueue.h" #include "igraph_stack.h" #include "config.h" /** * \function igraph_bfs * Breadth-first search * * A simple breadth-first search, with a lot of different results and * the possibility to call a callback whenever a vertex is visited. * It is allowed to supply null pointers as the output arguments the * user is not interested in, in this case they will be ignored. * * * If not all vertices can be reached from the supplied root vertex, * then additional root vertices will be used, in the order of their * vertex ids. * \param graph The input graph. * \param root The id of the root vertex. It is ignored if the \c * roots argument is not a null pointer. * \param roots Pointer to an initialized vector, or a null * pointer. If not a null pointer, then it is a vector * containing root vertices to start the BFS from. The vertices * are considered in the order they appear. If a root vertex * was already found while searching from another one, then no * search is conducted from it. * \param mode For directed graphs, it defines which edges to follow. * \c IGRAPH_OUT means following the direction of the edges, * \c IGRAPH_IN means the opposite, and * \c IGRAPH_ALL ignores the direction of the edges. * This parameter is ignored for undirected graphs. * \param unreachable Logical scalar, whether the search should visit * the vertices that are unreachable from the given root * node(s). If true, then additional searches are performed * until all vertices are visited. * \param restricted If not a null pointer, then it must be a pointer * to a vector containing vertex ids. The BFS is carried out * only on these vertices. * \param order If not null pointer, then the vertex ids of the graph are * stored here, in the same order as they were visited. * \param rank If not a null pointer, then the rank of each vertex is * stored here. * \param father If not a null pointer, then the id of the father of * each vertex is stored here. * \param pred If not a null pointer, then the id of vertex that was * visited before the current one is stored here. If there is * no such vertex (the current vertex is the root of a search * tree), then -1 is stored. * \param succ If not a null pointer, then the id of the vertex that * was visited after the current one is stored here. If there * is no such vertex (the current one is the last in a search * tree), then -1 is stored. * \param dist If not a null pointer, then the distance from the root of * the current search tree is stored here. * \param callback If not null, then it should be a pointer to a * function of type \ref igraph_bfshandler_t. This function * will be called, whenever a new vertex is visited. * \param extra Extra argument to pass to the callback function. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. * * \example examples/simple/igraph_bfs.c * \example examples/simple/igraph_bfs2.c */ int igraph_bfs(const igraph_t *graph, igraph_integer_t root, const igraph_vector_t *roots, igraph_neimode_t mode, igraph_bool_t unreachable, const igraph_vector_t *restricted, igraph_vector_t *order, igraph_vector_t *rank, igraph_vector_t *father, igraph_vector_t *pred, igraph_vector_t *succ, igraph_vector_t *dist, igraph_bfshandler_t *callback, void *extra) { igraph_dqueue_t Q; long int no_of_nodes=igraph_vcount(graph); long int actroot=0; igraph_vector_char_t added; igraph_lazy_adjlist_t adjlist; long int act_rank=0; long int pred_vec=-1; long int rootpos=0; long int noroots= roots ? igraph_vector_size(roots) : 1; if (!roots && (root < 0 || root >= no_of_nodes)) { IGRAPH_ERROR("Invalid root vertex in BFS", IGRAPH_EINVAL); } if (roots) { igraph_real_t min, max; igraph_vector_minmax(roots, &min, &max); if (min < 0 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid root vertex in BFS", IGRAPH_EINVAL); } } if (restricted) { igraph_real_t min, max; igraph_vector_minmax(restricted, &min, &max); if (min < 0 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid vertex id in restricted set", IGRAPH_EINVAL); } } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("Invalid mode argument", IGRAPH_EINVMODE); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } IGRAPH_CHECK(igraph_vector_char_init(&added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_char_destroy, &added); IGRAPH_CHECK(igraph_dqueue_init(&Q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &Q); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, mode, /*simplify=*/ 0)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); /* Mark the vertices that are not in the restricted set, as already found. Special care must be taken for vertices that are not in the restricted set, but are to be used as 'root' vertices. */ if (restricted) { long int i, n=igraph_vector_size(restricted); igraph_vector_char_fill(&added, 1); for (i=0; i * If not all vertices can be reached from the supplied root vertex, * then additional root vertices will be used, in the order of their * vertex ids. * \param graph The input graph. * \param root The id of the root vertex. * \param mode For directed graphs, it defines which edges to follow. * \c IGRAPH_OUT means following the direction of the edges, * \c IGRAPH_IN means the opposite, and * \c IGRAPH_ALL ignores the direction of the edges. * This parameter is ignored for undirected graphs. * \param unreachable Logical scalar, whether the search should visit * the vertices that are unreachable from the given root * node(s). If true, then additional searches are performed * until all vertices are visited. * \param order If not null pointer, then the vertex ids of the graph are * stored here, in the same order as they were discovered. * \param order_out If not a null pointer, then the vertex ids of the * graphs are stored here, in the order of the completion of * their subtree. * \param father If not a null pointer, then the id of the father of * each vertex is stored here. * \param dist If not a null pointer, then the distance from the root of * the current search tree is stored here. * \param in_callback If not null, then it should be a pointer to a * function of type \ref igraph_dfshandler_t. This function * will be called, whenever a new vertex is discovered. * \param out_callback If not null, then it should be a pointer to a * function of type \ref igraph_dfshandler_t. This function * will be called, whenever the subtree of a vertex is completed. * \param extra Extra argument to pass to the callback function(s). * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. */ int igraph_dfs(const igraph_t *graph, igraph_integer_t root, igraph_neimode_t mode, igraph_bool_t unreachable, igraph_vector_t *order, igraph_vector_t *order_out, igraph_vector_t *father, igraph_vector_t *dist, igraph_dfshandler_t *in_callback, igraph_dfshandler_t *out_callback, void *extra) { long int no_of_nodes=igraph_vcount(graph); igraph_lazy_adjlist_t adjlist; igraph_stack_t stack; igraph_vector_char_t added; igraph_vector_long_t nptr; long int actroot; long int act_rank=0; long int rank_out=0; long int act_dist=0; if (root < 0 || root >= no_of_nodes) { IGRAPH_ERROR("Invalid root vertex for DFS", IGRAPH_EINVAL); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("Invalid mode argument", IGRAPH_EINVMODE); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } IGRAPH_CHECK(igraph_vector_char_init(&added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_char_destroy, &added); IGRAPH_CHECK(igraph_stack_init(&stack, 100)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, mode, /*simplify=*/ 0)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_vector_long_init(&nptr, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &nptr); # define FREE_ALL() do { \ igraph_vector_long_destroy(&nptr); \ igraph_lazy_adjlist_destroy(&adjlist); \ igraph_stack_destroy(&stack); \ igraph_vector_char_destroy(&added); \ IGRAPH_FINALLY_CLEAN(4); } while (0) /* Resize result vectors and fill them with IGRAPH_NAN */ # define VINIT(v) if (v) { \ igraph_vector_resize(v, no_of_nodes); \ igraph_vector_fill(v, IGRAPH_NAN); } VINIT(order); VINIT(order_out); VINIT(father); VINIT(dist); # undef VINIT IGRAPH_CHECK(igraph_stack_push(&stack, root)); VECTOR(added)[(long int)root] = 1; if (father) { VECTOR(*father)[(long int)root] = -1; } if (order) { VECTOR(*order)[act_rank++] = root; } if (dist) { VECTOR(*dist)[(long int)root] = 0; } if (in_callback) { igraph_bool_t terminate=in_callback(graph, root, 0, extra); if (terminate) { FREE_ALL(); return 0; } } for (actroot=0; actroot 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_vector.h" #include "igraph_types_internal.h" typedef struct { void *scanner; int eof; char errmsg[300]; int has_weights; igraph_vector_t *vector; igraph_vector_t *weights; igraph_trie_t *trie; } igraph_i_ncol_parsedata_t; igraph/src/foreign-graphml.c0000644000175100001440000016167313431000472015566 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph R package. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_foreign.h" #include "config.h" #include /* isnan */ #include "igraph_math.h" #include "igraph_attributes.h" #include "igraph_interface.h" #include "igraph_types_internal.h" #include /* isspace */ #include #include "igraph_memory.h" #include /* va_start & co */ #define GRAPHML_NAMESPACE_URI "http://graphml.graphdrawing.org/xmlns" #if HAVE_LIBXML == 1 #include #include xmlEntity blankEntityStruct = { #ifndef XML_WITHOUT_CORBA 0, #endif XML_ENTITY_DECL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, XML_EXTERNAL_GENERAL_PARSED_ENTITY, 0, 0, 0, 0, 0, 1 }; xmlEntityPtr blankEntity = &blankEntityStruct; #define GRAPHML_PARSE_ERROR_WITH_CODE(state, msg, code) do { \ if (state->successful) { \ igraph_error(msg, __FILE__, __LINE__, code); \ igraph_i_graphml_sax_handler_error(state, msg); \ } \ } while (0) #define GRAPHML_PARSE_ERROR(state, msg) \ GRAPHML_PARSE_ERROR_WITH_CODE(state, msg, IGRAPH_PARSEERROR) #define RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, msg, code) do { \ GRAPHML_PARSE_ERROR_WITH_CODE(state, msg, code); \ return; \ } while (1) #define RETURN_GRAPHML_PARSE_ERROR(state, msg) do { \ GRAPHML_PARSE_ERROR(state, msg); \ return; \ } while (1) /* TODO: proper error handling */ typedef struct igraph_i_graphml_attribute_record_t { const char *id; /* GraphML id */ enum { I_GRAPHML_BOOLEAN, I_GRAPHML_INTEGER, I_GRAPHML_LONG, I_GRAPHML_FLOAT, I_GRAPHML_DOUBLE, I_GRAPHML_STRING, I_GRAPHML_UNKNOWN_TYPE } type; /* GraphML type */ union { igraph_real_t as_numeric; igraph_bool_t as_boolean; char* as_string; } default_value; /* Default value of the attribute, if any */ igraph_attribute_record_t record; } igraph_i_graphml_attribute_record_t; struct igraph_i_graphml_parser_state { enum { START, INSIDE_GRAPHML, INSIDE_GRAPH, INSIDE_NODE, INSIDE_EDGE, INSIDE_KEY, INSIDE_DEFAULT, INSIDE_DATA, FINISH, UNKNOWN, ERROR } st; igraph_t *g; igraph_trie_t node_trie; igraph_strvector_t edgeids; igraph_vector_t edgelist; igraph_vector_int_t prev_state_stack; unsigned int unknown_depth; int index; igraph_bool_t successful, edges_directed, destroyed; igraph_trie_t v_names; igraph_vector_ptr_t v_attrs; igraph_trie_t e_names; igraph_vector_ptr_t e_attrs; igraph_trie_t g_names; igraph_vector_ptr_t g_attrs; igraph_i_graphml_attribute_record_t* current_attr_record; xmlChar *data_key; igraph_attribute_elemtype_t data_type; char *error_message; char *data_char; long int act_node; }; static void igraph_i_report_unhandled_attribute_target(const char* target, const char* file, int line) { igraph_warningf("Attribute target '%s' is not handled; ignoring corresponding " "attribute specifications", file, line, 0, target); } igraph_real_t igraph_i_graphml_parse_numeric(const char* char_data, igraph_real_t default_value) { double result; if (char_data == 0) return default_value; if (sscanf(char_data, "%lf", &result) == 0) return default_value; return result; } igraph_bool_t igraph_i_graphml_parse_boolean(const char* char_data, igraph_bool_t default_value) { int value; if (char_data == 0) return default_value; if (!strcasecmp("true", char_data)) return 1; if (!strcasecmp("yes", char_data)) return 1; if (!strcasecmp("false", char_data)) return 0; if (!strcasecmp("no", char_data)) return 0; if (sscanf(char_data, "%d", &value) == 0) return default_value; return value != 0; } void igraph_i_graphml_attribute_record_destroy(igraph_i_graphml_attribute_record_t* rec) { if (rec->record.type==IGRAPH_ATTRIBUTE_NUMERIC) { if (rec->record.value != 0) { igraph_vector_destroy((igraph_vector_t*)rec->record.value); igraph_Free(rec->record.value); } } else if (rec->record.type==IGRAPH_ATTRIBUTE_STRING) { if (rec->record.value != 0) { igraph_strvector_destroy((igraph_strvector_t*)rec->record.value); if (rec->default_value.as_string != 0) { igraph_Free(rec->default_value.as_string); } igraph_Free(rec->record.value); } } else if (rec->record.type==IGRAPH_ATTRIBUTE_BOOLEAN) { if (rec->record.value != 0) { igraph_vector_bool_destroy((igraph_vector_bool_t*)rec->record.value); igraph_Free(rec->record.value); } } if (rec->id != 0) { igraph_Free(rec->id); } if (rec->record.name != 0) { igraph_Free(rec->record.name); } } void igraph_i_graphml_destroy_state(struct igraph_i_graphml_parser_state* state) { if (state->destroyed) return; state->destroyed=1; igraph_trie_destroy(&state->node_trie); igraph_strvector_destroy(&state->edgeids); igraph_trie_destroy(&state->v_names); igraph_trie_destroy(&state->e_names); igraph_trie_destroy(&state->g_names); igraph_vector_destroy(&state->edgelist); igraph_vector_int_destroy(&state->prev_state_stack); if (state->error_message) { free(state->error_message); } if (state->data_key) { free(state->data_key); } if (state->data_char) { free(state->data_char); } igraph_vector_ptr_destroy_all(&state->v_attrs); igraph_vector_ptr_destroy_all(&state->e_attrs); igraph_vector_ptr_destroy_all(&state->g_attrs); IGRAPH_FINALLY_CLEAN(1); } void igraph_i_graphml_sax_handler_error(void *state0, const char* msg, ...) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; va_list ap; va_start(ap, msg); if (state->error_message == 0) state->error_message=igraph_Calloc(4096, char); state->successful=0; state->st=ERROR; vsnprintf(state->error_message, 4096, msg, ap); va_end(ap); } xmlEntityPtr igraph_i_graphml_sax_handler_get_entity(void *state0, const xmlChar* name) { xmlEntityPtr predef = xmlGetPredefinedEntity(name); IGRAPH_UNUSED(state0); if (predef != NULL) return predef; IGRAPH_WARNING("unknown XML entity found\n"); return blankEntity; } void igraph_i_graphml_handle_unknown_start_tag(struct igraph_i_graphml_parser_state *state) { if (state->st != UNKNOWN) { igraph_vector_int_push_back(&state->prev_state_stack, state->st); state->st=UNKNOWN; state->unknown_depth=1; } else { state->unknown_depth++; } } void igraph_i_graphml_sax_handler_start_document(void *state0) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; int ret; state->st=START; state->successful=1; state->edges_directed=0; state->destroyed=0; state->data_key=0; state->error_message=0; state->data_char=0; state->unknown_depth=0; ret=igraph_vector_int_init(&state->prev_state_stack, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } ret=igraph_vector_int_reserve(&state->prev_state_stack, 32); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_vector_int_destroy, &state->prev_state_stack); ret=igraph_vector_ptr_init(&state->v_attrs, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&state->v_attrs, igraph_i_graphml_attribute_record_destroy); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->v_attrs); ret=igraph_vector_ptr_init(&state->e_attrs, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&state->e_attrs, igraph_i_graphml_attribute_record_destroy); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->e_attrs); ret=igraph_vector_ptr_init(&state->g_attrs, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&state->g_attrs, igraph_i_graphml_attribute_record_destroy); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &state->g_attrs); ret=igraph_vector_init(&state->edgelist, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_vector_destroy, &state->edgelist); ret=igraph_trie_init(&state->node_trie, 1); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_trie_destroy, &state->node_trie); ret=igraph_strvector_init(&state->edgeids, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_strvector_destroy, &state->edgeids); ret=igraph_trie_init(&state->v_names, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_trie_destroy, &state->v_names); ret=igraph_trie_init(&state->e_names, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_trie_destroy, &state->e_names); ret=igraph_trie_init(&state->g_names, 0); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } IGRAPH_FINALLY(igraph_trie_destroy, &state->g_names); IGRAPH_FINALLY_CLEAN(10); IGRAPH_FINALLY(igraph_i_graphml_destroy_state, state); } void igraph_i_graphml_sax_handler_end_document(void *state0) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; long i, l; int r; igraph_attribute_record_t idrec, eidrec; const char *idstr="id"; igraph_bool_t already_has_vertex_id=0, already_has_edge_id=0; if (!state->successful) return; if (state->index<0) { igraph_vector_ptr_t vattr, eattr, gattr; long int esize=igraph_vector_ptr_size(&state->e_attrs); const void **tmp; r=igraph_vector_ptr_init(&vattr, igraph_vector_ptr_size(&state->v_attrs)+1); if (r) { igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r); igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file"); return; } IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vattr); if (igraph_strvector_size(&state->edgeids) != 0) { esize++; } r=igraph_vector_ptr_init(&eattr, esize); if (r) { igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r); igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file"); return; } IGRAPH_FINALLY(igraph_vector_ptr_destroy, &eattr); r=igraph_vector_ptr_init(&gattr, igraph_vector_ptr_size(&state->g_attrs)); if (r) { igraph_error("Cannot parse GraphML file", __FILE__, __LINE__, r); igraph_i_graphml_sax_handler_error(state, "Cannot parse GraphML file"); return; } IGRAPH_FINALLY(igraph_vector_ptr_destroy, &gattr); for (i=0; iv_attrs); i++) { igraph_i_graphml_attribute_record_t *graphmlrec= VECTOR(state->v_attrs)[i]; igraph_attribute_record_t *rec=&graphmlrec->record; /* Check that the name of the vertex attribute is not 'id'. If it is then we cannot the complimentary 'id' attribute. */ if (! strcmp(rec->name, idstr)) { already_has_vertex_id=1; } if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*)rec->value; long int origsize=igraph_vector_size(vec); long int nodes=igraph_trie_size(&state->node_trie); igraph_vector_resize(vec, nodes); for (l=origsize; ldefault_value.as_numeric; } } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value; long int origsize=igraph_strvector_size(strvec); long int nodes=igraph_trie_size(&state->node_trie); igraph_strvector_resize(strvec, nodes); for (l=origsize; ldefault_value.as_string); } } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *boolvec=(igraph_vector_bool_t*)rec->value; long int origsize=igraph_vector_bool_size(boolvec); long int nodes=igraph_trie_size(&state->node_trie); igraph_vector_bool_resize(boolvec, nodes); for (l=origsize; ldefault_value.as_boolean; } } VECTOR(vattr)[i]=rec; } if (!already_has_vertex_id) { idrec.name=idstr; idrec.type=IGRAPH_ATTRIBUTE_STRING; tmp=&idrec.value; igraph_trie_getkeys(&state->node_trie, (const igraph_strvector_t **)tmp); VECTOR(vattr)[i]=&idrec; } else { igraph_vector_ptr_pop_back(&vattr); } for (i=0; ie_attrs); i++) { igraph_i_graphml_attribute_record_t *graphmlrec= VECTOR(state->e_attrs)[i]; igraph_attribute_record_t *rec=&graphmlrec->record; if (! strcmp(rec->name, idstr)) { already_has_edge_id=1; } if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*)rec->value; long int origsize=igraph_vector_size(vec); long int edges=igraph_vector_size(&state->edgelist)/2; igraph_vector_resize(vec, edges); for (l=origsize; ldefault_value.as_numeric; } } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value; long int origsize=igraph_strvector_size(strvec); long int edges=igraph_vector_size(&state->edgelist)/2; igraph_strvector_resize(strvec, edges); for (l=origsize; ldefault_value.as_string); } } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *boolvec=(igraph_vector_bool_t*)rec->value; long int origsize=igraph_vector_bool_size(boolvec); long int edges=igraph_vector_size(&state->edgelist)/2; igraph_vector_bool_resize(boolvec, edges); for (l=origsize; ldefault_value.as_boolean; } } VECTOR(eattr)[i]=rec; } if (igraph_strvector_size(&state->edgeids) != 0) { if (!already_has_edge_id) { long int origsize=igraph_strvector_size(&state->edgeids); eidrec.name=idstr; eidrec.type=IGRAPH_ATTRIBUTE_STRING; igraph_strvector_resize(&state->edgeids, igraph_vector_size(&state->edgelist)/2); for (; origsize < igraph_strvector_size(&state->edgeids); origsize++) { igraph_strvector_set(&state->edgeids, origsize, ""); } eidrec.value=&state->edgeids; VECTOR(eattr)[(long int)igraph_vector_ptr_size(&eattr)-1]=&eidrec; } else { igraph_vector_ptr_pop_back(&eattr); IGRAPH_WARNING("Could not add edge ids, " "there is already an 'id' edge attribute"); } } for (i=0; ig_attrs); i++) { igraph_i_graphml_attribute_record_t *graphmlrec= VECTOR(state->g_attrs)[i]; igraph_attribute_record_t *rec=&graphmlrec->record; if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*)rec->value; long int origsize=igraph_vector_size(vec); igraph_vector_resize(vec, 1); for (l=origsize; l<1; l++) { VECTOR(*vec)[l] = graphmlrec->default_value.as_numeric; } } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value; long int origsize=igraph_strvector_size(strvec); igraph_strvector_resize(strvec, 1); for (l=origsize; l<1; l++) { igraph_strvector_set(strvec, l, graphmlrec->default_value.as_string); } } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *boolvec=(igraph_vector_bool_t*)rec->value; long int origsize=igraph_vector_bool_size(boolvec); igraph_vector_bool_resize(boolvec, 1); for (l=origsize; l<1; l++) { VECTOR(*boolvec)[l] = graphmlrec->default_value.as_boolean; } } VECTOR(gattr)[i]=rec; } igraph_empty_attrs(state->g, 0, state->edges_directed, &gattr); igraph_add_vertices(state->g, (igraph_integer_t) igraph_trie_size(&state->node_trie), &vattr); igraph_add_edges(state->g, &state->edgelist, &eattr); igraph_vector_ptr_destroy(&vattr); igraph_vector_ptr_destroy(&eattr); igraph_vector_ptr_destroy(&gattr); IGRAPH_FINALLY_CLEAN(3); } igraph_i_graphml_destroy_state(state); } #define toXmlChar(a) (BAD_CAST(a)) #define fromXmlChar(a) ((char *)(a)) /* not the most elegant way... */ #define XML_ATTR_LOCALNAME(it) (*(it)) #define XML_ATTR_PREFIX(it) (*(it+1)) #define XML_ATTR_URI(it) (*(it+2)) #define XML_ATTR_VALUE_START(it) (*(it+3)) #define XML_ATTR_VALUE_END(it) (*(it+4)) #define XML_ATTR_VALUE(it) *(it+3), (*(it+4))-(*(it+3)) igraph_i_graphml_attribute_record_t* igraph_i_graphml_add_attribute_key( const xmlChar** attrs, int nb_attrs, struct igraph_i_graphml_parser_state *state) { xmlChar **it; xmlChar *localname; igraph_trie_t *trie=0; igraph_vector_ptr_t *ptrvector=0; long int id; unsigned short int skip=0; int i, ret; igraph_i_graphml_attribute_record_t *rec; if (!state->successful) return 0; rec = igraph_Calloc(1, igraph_i_graphml_attribute_record_t); if (rec==0) { GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", IGRAPH_ENOMEM); return 0; } IGRAPH_FINALLY(igraph_free, rec); rec->type = I_GRAPHML_UNKNOWN_TYPE; for (i=0, it=(xmlChar**)attrs; i < nb_attrs; i++, it+=5) { if (XML_ATTR_URI(it) != 0 && !xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), XML_ATTR_URI(it))) continue; localname = XML_ATTR_LOCALNAME(it); if (xmlStrEqual(localname, toXmlChar("id"))) { rec->id=fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); } else if (xmlStrEqual(localname, toXmlChar("attr.name"))) { rec->record.name=fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); } else if (xmlStrEqual(localname, toXmlChar("attr.type"))) { if (!xmlStrncmp(toXmlChar("boolean"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_BOOLEAN; rec->record.type=IGRAPH_ATTRIBUTE_BOOLEAN; rec->default_value.as_boolean=0; } else if (!xmlStrncmp(toXmlChar("string"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_STRING; rec->record.type=IGRAPH_ATTRIBUTE_STRING; rec->default_value.as_string=strdup(""); } else if (!xmlStrncmp(toXmlChar("float"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_FLOAT; rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC; rec->default_value.as_numeric=IGRAPH_NAN; } else if (!xmlStrncmp(toXmlChar("double"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_DOUBLE; rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC; rec->default_value.as_numeric=IGRAPH_NAN; } else if (!xmlStrncmp(toXmlChar("int"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_INTEGER; rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC; rec->default_value.as_numeric=IGRAPH_NAN; } else if (!xmlStrncmp(toXmlChar("long"), XML_ATTR_VALUE(it))) { rec->type=I_GRAPHML_LONG; rec->record.type=IGRAPH_ATTRIBUTE_NUMERIC; rec->default_value.as_numeric=IGRAPH_NAN; } else { GRAPHML_PARSE_ERROR(state, "Cannot parse GraphML file, unknown attribute type"); return 0; } } else if (xmlStrEqual(*it, toXmlChar("for"))) { /* graph, vertex or edge attribute? */ if (!xmlStrncmp(toXmlChar("graph"), XML_ATTR_VALUE(it))) { trie=&state->g_names; ptrvector=&state->g_attrs; } else if (!xmlStrncmp(toXmlChar("node"), XML_ATTR_VALUE(it))) { trie=&state->v_names; ptrvector=&state->v_attrs; } else if (!xmlStrncmp(toXmlChar("edge"), XML_ATTR_VALUE(it))) { trie=&state->e_names; ptrvector=&state->e_attrs; } else if (!xmlStrncmp(toXmlChar("graphml"), XML_ATTR_VALUE(it))) { igraph_i_report_unhandled_attribute_target("graphml", __FILE__, __LINE__); skip=1; } else if (!xmlStrncmp(toXmlChar("hyperedge"), XML_ATTR_VALUE(it))) { igraph_i_report_unhandled_attribute_target("hyperedge", __FILE__, __LINE__); skip=1; } else if (!xmlStrncmp(toXmlChar("port"), XML_ATTR_VALUE(it))) { igraph_i_report_unhandled_attribute_target("port", __FILE__, __LINE__); skip=1; } else if (!xmlStrncmp(toXmlChar("endpoint"), XML_ATTR_VALUE(it))) { igraph_i_report_unhandled_attribute_target("endpoint", __FILE__, __LINE__); skip=1; } else if (!xmlStrncmp(toXmlChar("all"), XML_ATTR_VALUE(it))) { /* TODO: we should handle this */ igraph_i_report_unhandled_attribute_target("all", __FILE__, __LINE__); skip=1; } else { GRAPHML_PARSE_ERROR(state, "Cannot parse GraphML file, unknown value in the 'for' attribute of a tag"); return 0; } } } /* throw an error if there is no ID; this is a clear violation of the GraphML * DTD */ if (rec->id == 0) { GRAPHML_PARSE_ERROR(state, "Found tag with no 'id' attribute"); return 0; } /* in case of a missing attr.name attribute, use the id as the attribute name */ if (rec->record.name == 0) { rec->record.name=strdup(rec->id); } /* if the attribute type is missing, throw an error */ if (!skip && rec->type == I_GRAPHML_UNKNOWN_TYPE) { igraph_warningf("Ignoring because of a missing or unknown 'attr.type' attribute", __FILE__, __LINE__, 0, rec->id); skip = 1; } /* if the value of the 'for' attribute was unknown, throw an error */ if (!skip && trie == 0) { GRAPHML_PARSE_ERROR(state, "Cannot parse GraphML file, missing 'for' attribute in a tag"); return 0; } /* if the code above requested skipping the attribute, free everything and * return */ if (skip) { igraph_free(rec); IGRAPH_FINALLY_CLEAN(1); return 0; } /* add to trie, attribues */ igraph_trie_get(trie, rec->id, &id); if (id != igraph_trie_size(trie)-1) { GRAPHML_PARSE_ERROR(state, "Cannot parse GraphML file, duplicate attribute"); return 0; } ret=igraph_vector_ptr_push_back(ptrvector, rec); if (ret) { GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot read GraphML file", ret); return 0; } /* Ownership of 'rec' is now taken by ptrvector so we can clean the * finally stack */ IGRAPH_FINALLY_CLEAN(1); /* rec */ /* create the attribute values */ switch (rec->record.type) { igraph_vector_t *vec; igraph_vector_bool_t *boolvec; igraph_strvector_t *strvec; case IGRAPH_ATTRIBUTE_BOOLEAN: boolvec=igraph_Calloc(1, igraph_vector_bool_t); if (boolvec==0) { GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", IGRAPH_ENOMEM); return 0; } rec->record.value=boolvec; igraph_vector_bool_init(boolvec, 0); break; case IGRAPH_ATTRIBUTE_NUMERIC: vec=igraph_Calloc(1, igraph_vector_t); if (vec==0) { GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", IGRAPH_ENOMEM); return 0; } rec->record.value=vec; igraph_vector_init(vec, 0); break; case IGRAPH_ATTRIBUTE_STRING: strvec=igraph_Calloc(1, igraph_strvector_t); if (strvec==0) { GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", IGRAPH_ENOMEM); return 0; } rec->record.value=strvec; igraph_strvector_init(strvec, 0); break; default: break; } return rec; } void igraph_i_graphml_attribute_data_setup(struct igraph_i_graphml_parser_state *state, const xmlChar **attrs, int nb_attrs, igraph_attribute_elemtype_t type) { xmlChar **it; int i; if (!state->successful) return; for (i=0, it=(xmlChar**)attrs; i < nb_attrs; i++, it+=5) { if (XML_ATTR_URI(it) != 0 && !xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), XML_ATTR_URI(it))) continue; if (xmlStrEqual(*it, toXmlChar("key"))) { if (state->data_key) { free(state->data_key); } state->data_key=xmlStrndup(XML_ATTR_VALUE(it)); if (state->data_char) { free(state->data_char); } state->data_char=0; state->data_type=type; } else { /* ignore */ } } } void igraph_i_graphml_append_to_data_char(struct igraph_i_graphml_parser_state *state, const xmlChar *data, int len) { long int data_char_new_start=0; if (!state->successful) return; if (state->data_char) { data_char_new_start=(long int) strlen(state->data_char); state->data_char=igraph_Realloc(state->data_char, (size_t)(data_char_new_start+len+1), char); } else { state->data_char=igraph_Calloc((size_t) len+1, char); } if (state->data_char==0) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", IGRAPH_ENOMEM); } memcpy(state->data_char+data_char_new_start, data, (size_t) len*sizeof(xmlChar)); state->data_char[data_char_new_start+len]='\0'; } void igraph_i_graphml_attribute_data_finish(struct igraph_i_graphml_parser_state *state) { const char *key=fromXmlChar(state->data_key); igraph_attribute_elemtype_t type=state->data_type; igraph_trie_t *trie=0; igraph_vector_ptr_t *ptrvector=0; igraph_i_graphml_attribute_record_t *graphmlrec; igraph_attribute_record_t *rec; long int recid, id=0; int ret; switch (type) { case IGRAPH_ATTRIBUTE_GRAPH: trie=&state->g_names; ptrvector=&state->g_attrs; id=0; break; case IGRAPH_ATTRIBUTE_VERTEX: trie=&state->v_names; ptrvector=&state->v_attrs; id=state->act_node; break; case IGRAPH_ATTRIBUTE_EDGE: trie=&state->e_names; ptrvector=&state->e_attrs; id=igraph_vector_size(&state->edgelist)/2-1; /* hack */ break; default: /* impossible */ break; } igraph_trie_check(trie, key, &recid); if (recid < 0) { /* no such attribute key, issue a warning */ igraph_warningf( "unknown attribute key '%s' in a tag, ignoring attribute", __FILE__, __LINE__, 0, key ); igraph_Free(state->data_char); return; } graphmlrec=VECTOR(*ptrvector)[recid]; rec=&graphmlrec->record; switch (rec->type) { igraph_vector_bool_t *boolvec; igraph_vector_t *vec; igraph_strvector_t *strvec; long int s, i; const char* strvalue; case IGRAPH_ATTRIBUTE_BOOLEAN: boolvec=(igraph_vector_bool_t *)rec->value; s=igraph_vector_bool_size(boolvec); if (id >= s) { ret=igraph_vector_bool_resize(boolvec, id+1); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } for (i=s; idefault_value.as_boolean; } } VECTOR(*boolvec)[id] = igraph_i_graphml_parse_boolean(state->data_char, graphmlrec->default_value.as_boolean); break; case IGRAPH_ATTRIBUTE_NUMERIC: vec=(igraph_vector_t *)rec->value; s=igraph_vector_size(vec); if (id >= s) { ret=igraph_vector_resize(vec, id+1); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } for (i=s; idefault_value.as_numeric; } } VECTOR(*vec)[id] = igraph_i_graphml_parse_numeric(state->data_char, graphmlrec->default_value.as_numeric); break; case IGRAPH_ATTRIBUTE_STRING: strvec=(igraph_strvector_t *)rec->value; s=igraph_strvector_size(strvec); if (id >= s) { ret=igraph_strvector_resize(strvec, id+1); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } strvalue = graphmlrec->default_value.as_string; for (i=s;idata_char) { strvalue = state->data_char; } else { strvalue = graphmlrec->default_value.as_string; } ret=igraph_strvector_set(strvec, id, strvalue); if (ret) { RETURN_GRAPHML_PARSE_ERROR_WITH_CODE(state, "Cannot parse GraphML file", ret); } break; default: break; } if (state->data_char) { igraph_Free(state->data_char); } } void igraph_i_graphml_attribute_default_value_finish( struct igraph_i_graphml_parser_state *state) { igraph_i_graphml_attribute_record_t *graphmlrec=state->current_attr_record; if (graphmlrec == 0) { igraph_warning("state->current_attr_record was null where it should have been " "non-null; this is probably a bug. Please notify the developers!", __FILE__, __LINE__, 0); return; } if (state->data_char == 0) return; switch (graphmlrec->record.type) { case IGRAPH_ATTRIBUTE_BOOLEAN: graphmlrec->default_value.as_boolean = igraph_i_graphml_parse_boolean( state->data_char, 0); break; case IGRAPH_ATTRIBUTE_NUMERIC: graphmlrec->default_value.as_numeric = igraph_i_graphml_parse_numeric( state->data_char, IGRAPH_NAN); break; case IGRAPH_ATTRIBUTE_STRING: if (state->data_char) { if (graphmlrec->default_value.as_string != 0) { free(graphmlrec->default_value.as_string); } graphmlrec->default_value.as_string = strdup(state->data_char); } break; default: break; } if (state->data_char) { igraph_Free(state->data_char); } } void igraph_i_graphml_sax_handler_start_element_ns( void *state0, const xmlChar* localname, const xmlChar* prefix, const xmlChar* uri, int nb_namespaces, const xmlChar** namespaces, int nb_attributes, int nb_defaulted, const xmlChar** attributes) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; xmlChar** it; char* attr_value; long int id1, id2; int i; if (!state->successful) return; if (!xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), uri)) { /* Tag is in a different namespace, so treat it as an unknown start * tag irrespectively of our state */ igraph_i_graphml_handle_unknown_start_tag(state); return; } switch (state->st) { case START: /* If we are in the START state and received a graphml tag, * change to INSIDE_GRAPHML state. Otherwise, change to UNKNOWN. */ if (xmlStrEqual(localname, toXmlChar("graphml"))) state->st=INSIDE_GRAPHML; else igraph_i_graphml_handle_unknown_start_tag(state); break; case INSIDE_GRAPHML: /* If we are in the INSIDE_GRAPHML state and received a graph tag, * change to INSIDE_GRAPH state if the state->index counter reached * zero (this is to handle multiple graphs in the same file). * Otherwise, change to UNKNOWN. */ if (xmlStrEqual(localname, toXmlChar("graph"))) { if (state->index==0) { state->st=INSIDE_GRAPH; for (i=0, it=(xmlChar**)attributes; i < nb_attributes; i++, it+=5) { if (XML_ATTR_URI(it) != 0 && !xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), XML_ATTR_URI(it))) { /* Attribute is from a different namespace, so skip it */ continue; } if (xmlStrEqual(*it, toXmlChar("edgedefault"))) { if (!xmlStrncmp(toXmlChar("directed"), XML_ATTR_VALUE(it))) { state->edges_directed=1; } else if (!xmlStrncmp(toXmlChar("undirected"), XML_ATTR_VALUE(it))) { state->edges_directed=0; } } } } state->index--; } else if (xmlStrEqual(localname, toXmlChar("key"))) { state->current_attr_record = igraph_i_graphml_add_attribute_key(attributes, nb_attributes, state); state->st=INSIDE_KEY; } else { igraph_i_graphml_handle_unknown_start_tag(state); } break; case INSIDE_KEY: /* If we are in the INSIDE_KEY state, check for default tag */ if (xmlStrEqual(localname, toXmlChar("default"))) state->st=INSIDE_DEFAULT; else igraph_i_graphml_handle_unknown_start_tag(state); break; case INSIDE_DEFAULT: /* If we are in the INSIDE_DEFAULT state, every further tag will be unknown */ igraph_i_graphml_handle_unknown_start_tag(state); break; case INSIDE_GRAPH: /* If we are in the INSIDE_GRAPH state, check for node and edge tags */ if (xmlStrEqual(localname, toXmlChar("edge"))) { id1=-1; id2=-1; for (i=0, it=(xmlChar**)attributes; i < nb_attributes; i++, it+=5) { if (XML_ATTR_URI(it) != 0 && !xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), XML_ATTR_URI(it))) { /* Attribute is from a different namespace, so skip it */ continue; } if (xmlStrEqual(*it, toXmlChar("source"))) { attr_value = fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); igraph_trie_get(&state->node_trie, attr_value, &id1); free(attr_value); } else if (xmlStrEqual(*it, toXmlChar("target"))) { attr_value = fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); igraph_trie_get(&state->node_trie, attr_value, &id2); free(attr_value); } else if (xmlStrEqual(*it, toXmlChar("id"))) { long int edges=igraph_vector_size(&state->edgelist)/2+1; long int origsize=igraph_strvector_size(&state->edgeids); attr_value = fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); igraph_strvector_resize(&state->edgeids, edges); for (;origsize < edges-1; origsize++) { igraph_strvector_set(&state->edgeids, origsize, ""); } igraph_strvector_set(&state->edgeids, edges-1, attr_value); free(attr_value); } } if (id1>=0 && id2>=0) { igraph_vector_push_back(&state->edgelist, id1); igraph_vector_push_back(&state->edgelist, id2); } else { igraph_i_graphml_sax_handler_error(state, "Edge with missing source or target encountered"); return; } state->st=INSIDE_EDGE; } else if (xmlStrEqual(localname, toXmlChar("node"))) { id1=-1; for (i=0, it=(xmlChar**)attributes; i < nb_attributes; i++, it+=5) { if (XML_ATTR_URI(it) != 0 && !xmlStrEqual(toXmlChar(GRAPHML_NAMESPACE_URI), XML_ATTR_URI(it))) { /* Attribute is from a different namespace, so skip it */ continue; } if (xmlStrEqual(XML_ATTR_LOCALNAME(it), toXmlChar("id"))) { attr_value = fromXmlChar(xmlStrndup(XML_ATTR_VALUE(it))); igraph_trie_get(&state->node_trie, attr_value, &id1); free(attr_value); break; } } if (id1 >= 0) { state->act_node = id1; } else { state->act_node = -1; igraph_i_graphml_sax_handler_error(state, "Node with missing id encountered"); return; } state->st=INSIDE_NODE; } else if (xmlStrEqual(localname, toXmlChar("data"))) { igraph_i_graphml_attribute_data_setup(state, attributes, nb_attributes, IGRAPH_ATTRIBUTE_GRAPH); igraph_vector_int_push_back(&state->prev_state_stack, state->st); state->st=INSIDE_DATA; } else igraph_i_graphml_handle_unknown_start_tag(state); break; case INSIDE_NODE: if (xmlStrEqual(localname, toXmlChar("data"))) { igraph_i_graphml_attribute_data_setup(state, attributes, nb_attributes, IGRAPH_ATTRIBUTE_VERTEX); igraph_vector_int_push_back(&state->prev_state_stack, state->st); state->st=INSIDE_DATA; } break; case INSIDE_EDGE: if (xmlStrEqual(localname, toXmlChar("data"))) { igraph_i_graphml_attribute_data_setup(state, attributes, nb_attributes, IGRAPH_ATTRIBUTE_EDGE); igraph_vector_int_push_back(&state->prev_state_stack, state->st); state->st=INSIDE_DATA; } break; case INSIDE_DATA: /* We do not expect any new tags within a tag */ igraph_i_graphml_handle_unknown_start_tag(state); break; case UNKNOWN: igraph_i_graphml_handle_unknown_start_tag(state); break; default: break; } } void igraph_i_graphml_sax_handler_end_element_ns(void *state0, const xmlChar* localname, const xmlChar* prefix, const xmlChar* uri) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; if (!state->successful) return; IGRAPH_UNUSED(localname); IGRAPH_UNUSED(prefix); IGRAPH_UNUSED(uri); switch (state->st) { case INSIDE_GRAPHML: state->st=FINISH; break; case INSIDE_GRAPH: state->st=INSIDE_GRAPHML; break; case INSIDE_KEY: state->current_attr_record = 0; state->st=INSIDE_GRAPHML; break; case INSIDE_DEFAULT: igraph_i_graphml_attribute_default_value_finish(state); state->st=INSIDE_KEY; break; case INSIDE_NODE: state->st=INSIDE_GRAPH; break; case INSIDE_EDGE: state->st=INSIDE_GRAPH; break; case INSIDE_DATA: igraph_i_graphml_attribute_data_finish(state); state->st = igraph_vector_int_pop_back(&state->prev_state_stack); break; case UNKNOWN: state->unknown_depth--; if (!state->unknown_depth) { state->st = igraph_vector_int_pop_back(&state->prev_state_stack); } break; default: break; } } void igraph_i_graphml_sax_handler_chars(void* state0, const xmlChar* ch, int len) { struct igraph_i_graphml_parser_state *state= (struct igraph_i_graphml_parser_state*)state0; if (!state->successful) return; switch (state->st) { case INSIDE_KEY: break; case INSIDE_DATA: case INSIDE_DEFAULT: igraph_i_graphml_append_to_data_char(state, ch, len); break; default: /* just ignore it */ break; } } static xmlSAXHandler igraph_i_graphml_sax_handler={ /* internalSubset = */ 0, /* isStandalone = */ 0, /* hasInternalSubset = */ 0, /* hasExternalSubset = */ 0, /* resolveEntity = */ 0, /* getEntity = */ igraph_i_graphml_sax_handler_get_entity, /* entityDecl = */ 0, /* notationDecl = */ 0, /* attributeDecl = */ 0, /* elementDecl = */ 0, /* unparsedEntityDecl = */ 0, /* setDocumentLocator = */ 0, /* startDocument = */ igraph_i_graphml_sax_handler_start_document, /* endDocument = */ igraph_i_graphml_sax_handler_end_document, /* startElement = */ 0, /* endElement = */ 0, /* reference = */ 0, /* characters = */ igraph_i_graphml_sax_handler_chars, /* ignorableWhitespaceFunc = */ 0, /* processingInstruction = */ 0, /* comment = */ 0, /* warning = */ igraph_i_graphml_sax_handler_error, /* error = */ igraph_i_graphml_sax_handler_error, /* fatalError = */ igraph_i_graphml_sax_handler_error, /* getParameterEntity = */ 0, /* cdataBlock = */ 0, /* externalSubset = */ 0, /* initialized = */ XML_SAX2_MAGIC, /* _private = */ 0, /* startElementNs = */ igraph_i_graphml_sax_handler_start_element_ns, /* endElementNs = */ igraph_i_graphml_sax_handler_end_element_ns, /* serror = */ 0 }; #endif #define IS_FORBIDDEN_CONTROL_CHAR(x) ((x) < ' ' && (x) != '\t' && (x) != '\r' && (x) != '\n') int igraph_i_xml_escape(char* src, char** dest) { long int destlen=0; char *s, *d; unsigned char ch; for (s=src; *s; s++, destlen++) { ch = (unsigned char)(*s); if (ch == '&') destlen += 4; else if (ch == '<') destlen += 3; else if (ch == '>') destlen += 3; else if (ch == '"') destlen += 5; else if (ch == '\'') destlen += 5; else if (IS_FORBIDDEN_CONTROL_CHAR(ch)) { char msg[4096]; snprintf(msg, 4096, "Forbidden control character 0x%02X found in igraph_i_xml_escape", ch); IGRAPH_ERROR(msg, IGRAPH_EINVAL); } } *dest=igraph_Calloc(destlen+1, char); if (!*dest) IGRAPH_ERROR("Not enough memory", IGRAPH_ENOMEM); for (s=src, d=*dest; *s; s++, d++) { ch = (unsigned char)(*s); switch (ch) { case '&': strcpy(d, "&"); d+=4; break; case '<': strcpy(d, "<"); d+=3; break; case '>': strcpy(d, ">"); d+=3; break; case '"': strcpy(d, """); d+=5; break; case '\'': strcpy(d, "'"); d+=5; break; default: *d = ch; } } *d=0; return 0; } /** * \ingroup loadsave * \function igraph_read_graph_graphml * \brief Reads a graph from a GraphML file. * * * GraphML is an XML-based file format for representing various types of * graphs. Currently only the most basic import functionality is implemented * in igraph: it can read GraphML files without nested graphs and hyperedges. * Attributes of the graph are loaded only if an attribute interface * is attached, ie. if you use igraph from R or Python. * * * Graph attribute names are taken from the \c attr.name attributes of the * \c key tags in the GraphML file. Since \c attr.name is not mandatory, * igraph will fall back to the \c id attribute of the \c key tag if * \c attr.name is missing. * * \param graph Pointer to an uninitialized graph object. * \param instream A stream, it should be readable. * \param index If the GraphML file contains more than one graph, the one * specified by this index will be loaded. Indices start from * zero, so supply zero here if your GraphML file contains only * a single graph. * * \return Error code: * \c IGRAPH_PARSEERROR: if there is a * problem reading the file, or the file is syntactically * incorrect. * \c IGRAPH_UNIMPLEMENTED: the GraphML functionality was disabled * at compile-time * * \example examples/simple/graphml.c */ int igraph_read_graph_graphml(igraph_t *graph, FILE *instream, int index) { #if HAVE_LIBXML == 1 xmlParserCtxtPtr ctxt; struct igraph_i_graphml_parser_state state; int res; char buffer[4096]; if (index<0) IGRAPH_ERROR("Graph index must be non-negative", IGRAPH_EINVAL); xmlInitParser(); /* Create a progressive parser context */ state.g=graph; state.index=index<0?0:index; res=(int) fread(buffer, 1, 4096, instream); ctxt=xmlCreatePushParserCtxt(&igraph_i_graphml_sax_handler, &state, buffer, res, NULL); /* ctxt=xmlCreateIOParserCtxt(&igraph_i_graphml_sax_handler, &state, */ /* igraph_i_libxml2_read_callback, */ /* igraph_i_libxml2_close_callback, */ /* instream, XML_CHAR_ENCODING_NONE); */ if (ctxt==NULL) IGRAPH_ERROR("Can't create progressive parser context", IGRAPH_PARSEERROR); /* Set parsing options */ if (xmlCtxtUseOptions(ctxt, XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_NONET | XML_PARSE_NSCLEAN | XML_PARSE_NOCDATA | XML_PARSE_HUGE )) IGRAPH_ERROR("Cannot set options for the parser context", IGRAPH_EINVAL); /* Parse the file */ while ((res=(int) fread(buffer, 1, 4096, instream))>0) { xmlParseChunk(ctxt, buffer, res, 0); if (!state.successful) break; } xmlParseChunk(ctxt, buffer, res, 1); /* Free the context */ xmlFreeParserCtxt(ctxt); if (!state.successful) { if (state.error_message != 0) IGRAPH_ERROR(state.error_message, IGRAPH_PARSEERROR); else IGRAPH_ERROR("Malformed GraphML file", IGRAPH_PARSEERROR); } if (state.index>=0) IGRAPH_ERROR("Graph index was too large", IGRAPH_EINVAL); return 0; #else IGRAPH_ERROR("GraphML support is disabled", IGRAPH_UNIMPLEMENTED); #endif } /** * \ingroup loadsave * \function igraph_write_graph_graphml * \brief Writes the graph to a file in GraphML format * * * GraphML is an XML-based file format for representing various types of * graphs. See the GraphML Primer (http://graphml.graphdrawing.org/primer/graphml-primer.html) * for detailed format description. * * \param graph The graph to write. * \param outstream The stream object to write to, it should be * writable. * \param prefixattr Logical value, whether to put a prefix in front of the * attribute names to ensure uniqueness if the graph has vertex and * edge (or graph) attributes with the same name. * \return Error code: * \c IGRAPH_EFILE if there is an error * writing the file. * * Time complexity: O(|V|+|E|) otherwise. All * file operations are expected to have time complexity * O(1). * * \example examples/simple/graphml.c */ int igraph_write_graph_graphml(const igraph_t *graph, FILE *outstream, igraph_bool_t prefixattr) { int ret; igraph_integer_t l, vc; igraph_eit_t it; igraph_strvector_t gnames, vnames, enames; igraph_vector_t gtypes, vtypes, etypes; long int i; igraph_vector_t numv; igraph_strvector_t strv; igraph_vector_bool_t boolv; const char *gprefix= prefixattr ? "g_" : ""; const char *vprefix= prefixattr ? "v_" : ""; const char *eprefix= prefixattr ? "e_" : ""; ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n", GRAPHML_NAMESPACE_URI); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); /* dump the elements if any */ IGRAPH_VECTOR_INIT_FINALLY(&numv, 1); IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1); IGRAPH_VECTOR_BOOL_INIT_FINALLY(&boolv, 1); IGRAPH_STRVECTOR_INIT_FINALLY(&gnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&vnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&enames, 0); IGRAPH_VECTOR_INIT_FINALLY(>ypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&vtypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&etypes, 0); igraph_i_attribute_get_info(graph, &gnames, >ypes, &vnames, &vtypes, &enames, &etypes); /* graph attributes */ for (i=0; i\n", gprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) { ret=fprintf(outstream, " \n", gprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { ret=fprintf(outstream, " \n", gprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } igraph_Free(name_escaped); } /* vertex attributes */ for (i=0; i\n", vprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) { ret=fprintf(outstream, " \n", vprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { ret=fprintf(outstream, " \n", vprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } igraph_Free(name_escaped); } /* edge attributes */ for (i=0; i\n", eprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_NUMERIC) { ret=fprintf(outstream, " \n", eprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { ret=fprintf(outstream, " \n", eprefix, name_escaped, name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } igraph_Free(name_escaped); } ret=fprintf(outstream, " \n", (igraph_is_directed(graph)?"directed":"undirected")); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); /* Write the graph atributes before anything else */ for (i=0; i", gprefix, name_escaped); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_STRING) { char *s, *s_escaped; igraph_strvector_get(&gnames, i, &name); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " ", gprefix, name_escaped); igraph_Free(name_escaped); IGRAPH_CHECK(igraph_i_attribute_get_string_graph_attr(graph, name, &strv)); igraph_strvector_get(&strv, 0, &s); IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped)); ret=fprintf(outstream, "%s", s_escaped); igraph_Free(s_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(gtypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_strvector_get(&gnames, i, &name); IGRAPH_CHECK(igraph_i_attribute_get_bool_graph_attr(graph, name, &boolv)); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " %s\n", gprefix, name_escaped, VECTOR(boolv)[0] ? "true" : "false"); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } /* Let's dump the nodes first */ vc=igraph_vcount(graph); for (l=0; l\n", (long)l); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); for (i=0; i", vprefix, name_escaped); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_STRING) { char *s, *s_escaped; igraph_strvector_get(&vnames, i, &name); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " ", vprefix, name_escaped); igraph_Free(name_escaped); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, name, igraph_vss_1(l), &strv)); igraph_strvector_get(&strv, 0, &s); IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped)); ret=fprintf(outstream, "%s", s_escaped); igraph_Free(s_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(vtypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_strvector_get(&vnames, i, &name); IGRAPH_CHECK(igraph_i_attribute_get_bool_vertex_attr(graph, name, igraph_vss_1(l), &boolv)); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " %s\n", vprefix, name_escaped, VECTOR(boolv)[0] ? "true" : "false"); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } ret=fprintf(outstream, " \n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } /* Now the edges */ IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); while (!IGRAPH_EIT_END(it)) { igraph_integer_t from, to; char *name, *name_escaped; long int edge=IGRAPH_EIT_GET(it); igraph_edge(graph, (igraph_integer_t) edge, &from, &to); ret=fprintf(outstream, " \n", (long int)from, (long int)to); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); for (i=0; i", eprefix, name_escaped); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=igraph_real_fprintf_precise(outstream, VECTOR(numv)[0]); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_STRING) { char *s, *s_escaped; igraph_strvector_get(&enames, i, &name); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " ", eprefix, name_escaped); igraph_Free(name_escaped); IGRAPH_CHECK(igraph_i_attribute_get_string_edge_attr(graph, name, igraph_ess_1((igraph_integer_t) edge), &strv)); igraph_strvector_get(&strv, 0, &s); IGRAPH_CHECK(igraph_i_xml_escape(s, &s_escaped)); ret=fprintf(outstream, "%s", s_escaped); igraph_Free(s_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); ret=fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } else if (VECTOR(etypes)[i] == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_strvector_get(&enames, i, &name); IGRAPH_CHECK(igraph_i_attribute_get_bool_edge_attr(graph, name, igraph_ess_1((igraph_integer_t) edge), &boolv)); IGRAPH_CHECK(igraph_i_xml_escape(name, &name_escaped)); ret=fprintf(outstream, " %s\n", eprefix, name_escaped, VECTOR(boolv)[0] ? "true" : "false"); igraph_Free(name_escaped); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } } ret=fprintf(outstream, " \n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); IGRAPH_EIT_NEXT(it); } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); ret=fprintf(outstream, " \n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); fprintf(outstream, "\n"); if (ret<0) IGRAPH_ERROR("Write failed", IGRAPH_EFILE); igraph_strvector_destroy(&gnames); igraph_strvector_destroy(&vnames); igraph_strvector_destroy(&enames); igraph_vector_destroy(>ypes); igraph_vector_destroy(&vtypes); igraph_vector_destroy(&etypes); igraph_vector_destroy(&numv); igraph_strvector_destroy(&strv); igraph_vector_bool_destroy(&boolv); IGRAPH_FINALLY_CLEAN(9); return 0; } igraph/src/gengraph_graph_molloy_hash.cpp0000644000175100001440000007321713431000472020413 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_definitions.h" #include #include #include #include #include "gengraph_qsort.h" #include "gengraph_hash.h" #include "gengraph_degree_sequence.h" #include "gengraph_graph_molloy_hash.h" #include "config.h" #include "igraph_math.h" #include "igraph_constructors.h" #include "igraph_error.h" #include "igraph_statusbar.h" #include "igraph_progress.h" namespace gengraph { //_________________________________________________________________________ void graph_molloy_hash::compute_neigh() { int *p = links; for(int i=0; i=i) *(p++)=d; } assert(p==hc+2+n+a/2); return hc; } //_________________________________________________________________________ bool graph_molloy_hash::is_connected() { bool *visited = new bool[n]; int *buff = new int[n]; int comp_size = depth_search(visited, buff); delete[] visited; delete[] buff; return (comp_size==n); } //_________________________________________________________________________ int* graph_molloy_hash::backup() { int *b = new int[a/2]; int *c = b; int *p = links; for(int i=0; ii) *(c++)=*p; assert(c==b+(a/2)); return b; } //_________________________________________________________________________ void graph_molloy_hash::restore(int* b) { init(); int i; int *dd = new int[n]; memcpy(dd,deg,sizeof(int)*n); for(i=0; inb_swaps && maxtimes>all_swaps) { // Backup graph int *save = backup(); // Prepare counters, K, T unsigned long swaps = 0; int K_int = 0; if(type == FINAL_HEURISTICS || type == BRUTE_FORCE_HEURISTICS) K_int=int(K); unsigned long T_int = (unsigned long)(floor(T)); if(T_int<1) T_int=1; // compute cost cost += T_int; if(K_int>2) cost += (unsigned long)(K_int)*(unsigned long)(T_int); // Perform T edge swap attempts for(int i=T_int; i>0; i--) { // try one swap swaps += (unsigned long)(random_edge_swap(K_int, Kbuff, visited)); all_swaps++; // Verbose if(nb_swaps+swaps>next) { next = (nb_swaps+swaps)+max((unsigned long)(100),(unsigned long)(times/1000)); int progress = int(double(nb_swaps+swaps) / double(times)); igraph_progress("Shuffle", progress, 0); } } // test connectivity cost+=(unsigned long)(a/2); bool ok = is_connected(); // performance monitor { avg_T += double(T_int); avg_K += double(K_int); if(ok) successes++; else failures++; } // restore graph if needed, and count validated swaps if(ok) nb_swaps += swaps; else { restore(save); next=nb_swaps; } delete[] save; // Adjust K and T following the heuristics. switch(type) { int steps; case GKAN_HEURISTICS: if (ok) T+=1.0; else T*=0.5; break; case FAB_HEURISTICS: steps = 50 / (8+failures+successes); if(steps<1) steps=1; while(steps--) if(ok) T*=1.17182818; else T*=0.9; if(T>double(5*a)) T=double(5*a); break; case FINAL_HEURISTICS: if(ok) { if((K+10.0)*T>5.0*double(a)) K/=1.03; else T*=2; } else { K*=1.35; delete[] Kbuff; Kbuff = new int[int(K)+1]; } break; case OPTIMAL_HEURISTICS: if(ok) T=double(optimal_window()); break; case BRUTE_FORCE_HEURISTICS: K*=2; delete[] Kbuff; Kbuff = new int[int(K)+1]; break; default: IGRAPH_ERROR("Error in graph_molloy_hash::shuffle(): " "Unknown heuristics type", IGRAPH_EINVAL); return 0; } } delete[] Kbuff; delete[] visited; if (maxtimes <= all_swaps) { IGRAPH_WARNING("Cannot shuffle graph, maybe there is only a single one?"); } // Status report { igraph_status("*** Shuffle Monitor ***\n", 0); igraph_statusf(" - Average cost : %f / validated edge swap\n", 0, double(cost)/double(nb_swaps)); igraph_statusf(" - Connectivity tests : %d (%d successes, %d failures)\n", 0, successes + failures, successes, failures); igraph_statusf(" - Average window : %d\n", 0, int(avg_T/double(successes+failures))); if(type==FINAL_HEURISTICS || type==BRUTE_FORCE_HEURISTICS) igraph_statusf(" - Average isolation test width : %f\n", 0, avg_K/double(successes+failures)); } return nb_swaps; } //_________________________________________________________________________ void graph_molloy_hash::print(FILE *f) { int i,j; for(i=0; i i) { VECTOR(edges)[ptr++] = i; VECTOR(edges)[ptr++] = neigh[i][j]; } } } } IGRAPH_CHECK(igraph_create(graph, &edges, n, /*undirected=*/ 0)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } //_________________________________________________________________________ bool graph_molloy_hash::try_shuffle(int T, int K, int *backup_graph) { // init all int *Kbuff = NULL; bool *visited = NULL; if(K>2) { Kbuff = new int[K]; visited = new bool[n]; for(int i=0; i=double(trials)*param) return false; double comb = 1.0; double fact = 1.0; for(int i=0; i %s\n",success, trials, param, (sum < _TRUST_BERNOULLI_LOWER) ? "lower" : "can't say"); return (sum < _TRUST_BERNOULLI_LOWER); } //_________________________________________________________________________ #define _MIN_SUCCESS_FOR_BERNOULLI_TRUST 100 double graph_molloy_hash::average_cost(int T, int *backup, double min_cost) { if(T<1) return 1e+99; int successes = 0; int trials = 0; while(successes < _MIN_SUCCESS_FOR_BERNOULLI_TRUST && !bernoulli_param_is_lower(successes, trials, 1.0/min_cost)) { if(try_shuffle(T,0,backup)) successes++; trials++; } if(successes >= _MIN_SUCCESS_FOR_BERNOULLI_TRUST) return double(trials)/double(successes)*(1.0+double(a/2)/double(T)); else return 2.0*min_cost; } //_________________________________________________________________________ int graph_molloy_hash::optimal_window() { int Tmax; int optimal_T=1; double min_cost=1e+99; int *back=backup(); // on cherche une borne sup pour Tmax int been_greater = 0; for(Tmax=1; Tmax<=5*a ;Tmax*=2) { double c = average_cost(Tmax, back, min_cost); if(c > 1.5 * min_cost) break; if(c > 1.2 * min_cost && ++been_greater >= 3) break; if(c < min_cost) { min_cost = c; optimal_T = Tmax; } igraph_statusf("Tmax = %d [%f]", 0, Tmax, min_cost); } // on cree Tmin int Tmin = int(0.5*double(a)/(min_cost-1.0)); igraph_statusf("Optimal T is in [%d, %d]\n", 0, Tmin, Tmax); // on cherche autour double span = 2.0; int try_again = 4; while(span>1.05 && optimal_T <= 5*a) { igraph_statusf("Best T [cost]: %d [%f]", 0, optimal_T, min_cost); int T_low = int(double(optimal_T)/span); int T_high = int(double(optimal_T)*span); double c_low = average_cost(T_low , back, min_cost); double c_high = average_cost(T_high, back, min_cost); if(c_lowdeg[t2] ? f1 : t2, K, Kbuff, visited); // assert(verify()); sum_K += effective_isolated(deg[f2]>deg[t1] ? f2 : t1, K, Kbuff, visited); // assert(verify()); // undo swap swap_edges(f1,t2,f2,t1); // assert(verify()); } delete[] Kbuff; delete[] visited; return double(sum_K)/double(2*quality); } //_________________________________________________________________________ long graph_molloy_hash::effective_isolated(int v, int K, int *Kbuff, bool *visited) { int i; for(i=0; i=dmax) { left_to_explore = 0; return; } *(Kbuff++) = v; visited[v] = true; // print(); // fflush(stdout); calls++; int *copy = NULL; int *w = neigh[v]; if(IS_HASH(deg[v])) { copy = new int[deg[v]]; H_copy(copy,w,deg[v]); w = copy; } qsort(deg, w, deg[v]); w+=deg[v]; for(int i=deg[v]; i--; ) { if(visited[*--w]) calls++; else depth_isolated(*w, calls, left_to_explore, dmax, Kbuff, visited); if(left_to_explore==0) break; } if(copy!=NULL) delete[] copy; } //_________________________________________________________________________ int graph_molloy_hash::depth_search(bool *visited, int *buff, int v0) { for(int i=0; in) n=i; n++; // degrees ? if(VERBOSE()) fprintf(stderr,"%d, #edges=",n); int *degs = new int[n]; rewind(f); while(fgets(buff,FBUFF_SIZE,f)) { int d = 0; if(sscanf(buff,"%d",&i)==1) { char *b = buff; while(skip_int(b)) d++; degs[i]=d; } } // allocate memory degree_sequence dd(n,degs); if(VERBOSE()) fprintf(stderr,"%d\nAllocating memory...",dd.sum()); alloc(dd); // add edges if(VERBOSE()) fprintf(stderr,"done\nCreating edges..."); rewind(f); for(i=0; im) m=deg[k]; return m; } bool graph_molloy_hash::havelhakimi() { int i; int dmax = max_degree()+1; // Sort vertices using basket-sort, in descending degrees int *nb = new int[dmax]; int *sorted = new int[n]; // init basket for(i=0; i=0; i--) { int t=nb[i]; nb[i]=c; c+=t; } // sort for(i=0; i0; ) { // pick a vertex. we could pick any, but here we pick the one with biggest degree int v = sorted[first]; // look for current degree of v while(nb[d]<=first) d--; // store it in dv int dv = d; // bind it ! c -= dv; int dc = d; // residual degree of vertices we bind to int fc = ++first; // position of the first vertex with degree dc while(dv>0 && dc>0) { int lc = nb[dc]; if(lc!=fc) { while(dv>0 && lc>fc) { // binds v with sorted[--lc] dv--; int w = sorted[--lc]; add_edge(v,w); } fc = nb[dc]; nb[dc] = lc; } dc--; } if(dv != 0) { // We couldn't bind entirely v if(VERBOSE()) { fprintf(stderr,"Error in graph_molloy_hash::havelhakimi() :\n"); fprintf(stderr,"Couldn't bind vertex %d entirely (%d edges remaining)\n",v,dv); } delete[] nb; delete[] sorted; return false; } } assert(c==0); delete[] nb; delete[] sorted; return true; } bool graph_molloy_hash::make_connected() { assert(verify()); if(a/2 < n-1) { // fprintf(stderr,"\ngraph::make_connected() failed : #edges < #vertices-1\n"); return false; } int i; // Data struct for the visit : // - buff[] contains vertices to visit // - dist[V] is V's distance modulo 4 to the root of its comp, or -1 if it hasn't been visited yet #define MC_BUFF_SIZE (n+2) int *buff = new int[MC_BUFF_SIZE]; unsigned char * dist = new unsigned char[n]; #define NOT_VISITED 255 #define FORBIDDEN 254 for(i=n; i>0; dist[--i]=NOT_VISITED); // Data struct to store components : either surplus trees or surplus edges are stored at buff[]'s end // - A Tree is coded by one of its vertices // - An edge (a,b) is coded by the TWO ints a and b int *ffub = buff+MC_BUFF_SIZE; edge *edges = (edge *) ffub; int *trees = ffub; int *min_ffub = buff+1+(MC_BUFF_SIZE%2 ? 0 : 1); // There will be only one "fatty" component, and trees. edge fatty_edge; fatty_edge.from = -1; bool enough_edges = false; // start main loop for(int v0=0; v0min_ffub) min_ffub+=2; // update limit of ffub's storage //assert(verify()); } else if(dist[w]==next_dist || (w!=HASH_NONE && w>v && dist[w]==current_dist)) { // we found a removable edge if(is_a_tree) { // we must first merge with the fatty component is_a_tree = false; if(fatty_edge.from < 0) { // we ARE the first component! fatty is us fatty_edge.from = v; fatty_edge.to = w; } else { // we connect to fatty swap_edges(fatty_edge.from, fatty_edge.to, v, w); //assert(verify()); } } else { // we have removable edges to give! if(trees!=ffub) { // some trees still.. Let's merge with them! assert(trees>=min_ffub); assert(edges==(edge *)ffub); swap_edges(v,w,*trees,neigh[*trees][0]); trees++; //assert(verify()); } else if(!enough_edges) { // Store the removable edge for future use if(edges<=(edge *)min_ffub+1) enough_edges = true; else { edges--; edges->from = v; edges->to = w; } } } } } } // Mark component while(to_visit!=buff) dist[*(--to_visit)] = FORBIDDEN; // Check if it is a tree if(is_a_tree ) { assert(deg[v0]!=0); if(edges!=(edge *)ffub) { // let's bind the tree we found with a removable edge in stock assert(trees == ffub); if(edges<(edge *)min_ffub) edges=(edge *)min_ffub; swap_edges(v0,neigh[v0][0],edges->from,edges->to); edges++; assert(verify()); } else { // add the tree to the list of trees assert(trees>min_ffub); *(--trees) = v0; assert(verify()); } } } delete[] buff; delete[] dist; return(trees == ffub); } int64_t graph_molloy_hash::slow_connected_shuffle(int64_t times) { assert(verify()); int64_t nb_swaps = 0; int T = 1; while(times>nb_swaps) { // Backup graph int *save = backup(); // Swaps int swaps = 0; for(int i=T; i>0; i--) { // Pick two random vertices a and c int f1 = pick_random_vertex(); int f2 = pick_random_vertex(); // Check that f1 != f2 if(f1==f2) continue; // Get two random edges (f1,*f1t1) and (f2,*f2t2) int *f1t1 = random_neighbour(f1); int t1 = *f1t1; int *f2t2 = random_neighbour(f2); int t2 = *f2t2; // Check simplicity if(t1==t2 || f1==t2 || f2==t1) continue; if(is_edge(f1,t2) || is_edge(f2,t1)) continue; // Swap H_rpl(neigh[f1],deg[f1],f1t1,t2); H_rpl(neigh[f2],deg[f2],f2t2,t1); H_rpl(neigh[t1],deg[t1],f1,f2); H_rpl(neigh[t2],deg[t2],f2,f1); swaps++; } // test connectivity bool ok = is_connected(); if(ok) { nb_swaps += swaps; } else { restore(save); } delete[] save; } return nb_swaps; } int graph_molloy_hash::width_search(unsigned char *dist, int *buff, int v0) { for(int i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "infomap_Node.h" Node::Node(){ exit = 0.0; size = 0.0; selfLink = 0.0; } Node::Node(int nodenr, double tpweight){ teleportWeight = tpweight; exit = 0.0; size = 0.0; selfLink = 0.0; members.push_back(nodenr); // members = [nodenr] } void cpyNode(Node *newNode, Node *oldNode){ newNode->exit = oldNode->exit; newNode->size = oldNode->size; newNode->teleportWeight = oldNode->teleportWeight; newNode->danglingSize = oldNode->danglingSize; int Nmembers = oldNode->members.size(); newNode->members = vector(Nmembers); for (int i=0;imembers[i] = oldNode->members[i]; newNode->selfLink = oldNode->selfLink; int NoutLinks = oldNode->outLinks.size(); newNode->outLinks = vector >(NoutLinks); for (int i=0;ioutLinks[i].first = oldNode->outLinks[i].first; newNode->outLinks[i].second = oldNode->outLinks[i].second; } int NinLinks = oldNode->inLinks.size(); newNode->inLinks = vector >(NinLinks); for (int i=0;iinLinks[i].first = oldNode->inLinks[i].first; newNode->inLinks[i].second = oldNode->inLinks[i].second; } } igraph/src/triangles_template1.h0000644000175100001440000000522713431000472016446 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ long int no_of_nodes=igraph_vcount(graph); igraph_vit_t vit; long int nodes_to_calc; igraph_vector_t *neis1, *neis2; igraph_real_t triangles; long int i, j, k; long int neilen1, neilen2; long int *neis; igraph_lazy_adjlist_t adjlist; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); neis=igraph_Calloc(no_of_nodes, long int); if (neis==0) { IGRAPH_ERROR("local undirected transitivity failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, neis); IGRAPH_CHECK(igraph_vector_resize(res, nodes_to_calc)); igraph_lazy_adjlist_init(graph, &adjlist, IGRAPH_ALL, IGRAPH_SIMPLIFY); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int node=IGRAPH_VIT_GET(vit); IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_lazy_adjlist_get(&adjlist, (igraph_integer_t) node); neilen1=igraph_vector_size(neis1); for (j=0; j 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_datatype.h" #include "igraph_interface.h" #include "igraph_attributes.h" #include "igraph_memory.h" #include /* memset & co. */ #include "config.h" /* Internal functions */ int igraph_i_create_start(igraph_vector_t *res, igraph_vector_t *el, igraph_vector_t *index, igraph_integer_t nodes); /** * \section about_basic_interface * * This is the very minimal API in \a igraph. All the other * functions use this minimal set for creating and manipulating * graphs. * * This is a very important principle since it makes possible to * implement other data representations by implementing only this * minimal set. */ /** * \ingroup interface * \function igraph_empty * \brief Creates an empty graph with some vertices and no edges. * * * The most basic constructor, all the other constructors should call * this to create a minimal graph object. Our use of the term "empty graph" * in the above description should be distinguished from the mathematical * definition of the empty or null graph. Strictly speaking, the empty or null * graph in graph theory is the graph with no vertices and no edges. However * by "empty graph" as used in \c igraph we mean a graph having zero or more * vertices, but no edges. * \param graph Pointer to a not-yet initialized graph object. * \param n The number of vertices in the graph, a non-negative * integer number is expected. * \param directed Boolean; whether the graph is directed or not. Supported * values are: * \clist * \cli IGRAPH_DIRECTED * The graph will be \em directed. * \cli IGRAPH_UNDIRECTED * The graph will be \em undirected. * \endclist * \return Error code: * \c IGRAPH_EINVAL: invalid number of vertices. * * Time complexity: O(|V|) for a graph with * |V| vertices (and no edges). * * \example examples/simple/igraph_empty.c */ int igraph_empty(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed) { return igraph_empty_attrs(graph, n, directed, 0); } /** * \ingroup interface * \function igraph_empty_attrs * \brief Creates an empty graph with some vertices, no edges and some graph attributes. * * * Use this instead of \ref igraph_empty() if you wish to add some graph * attributes right after initialization. This function is currently * not very interesting for the ordinary user. Just supply 0 here or * use \ref igraph_empty(). * \param graph Pointer to a not-yet initialized graph object. * \param n The number of vertices in the graph; a non-negative * integer number is expected. * \param directed Boolean; whether the graph is directed or not. Supported * values are: * \clist * \cli IGRAPH_DIRECTED * Create a \em directed graph. * \cli IGRAPH_UNDIRECTED * Create an \em undirected graph. * \endclist * \param attr The attributes. * \return Error code: * \c IGRAPH_EINVAL: invalid number of vertices. * * Time complexity: O(|V|) for a graph with * |V| vertices (and no edges). */ int igraph_empty_attrs(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, void* attr) { if (n<0) { IGRAPH_ERROR("cannot create empty graph with negative number of vertices", IGRAPH_EINVAL); } if (!IGRAPH_FINITE(n)) { IGRAPH_ERROR("number of vertices is not finite (NA, NaN or Inf)", IGRAPH_EINVAL); } graph->n=0; graph->directed=directed; IGRAPH_VECTOR_INIT_FINALLY(&graph->from, 0); IGRAPH_VECTOR_INIT_FINALLY(&graph->to, 0); IGRAPH_VECTOR_INIT_FINALLY(&graph->oi, 0); IGRAPH_VECTOR_INIT_FINALLY(&graph->ii, 0); IGRAPH_VECTOR_INIT_FINALLY(&graph->os, 1); IGRAPH_VECTOR_INIT_FINALLY(&graph->is, 1); VECTOR(graph->os)[0]=0; VECTOR(graph->is)[0]=0; /* init attributes */ graph->attr=0; IGRAPH_CHECK(igraph_i_attribute_init(graph, attr)); /* add the vertices */ IGRAPH_CHECK(igraph_add_vertices(graph, n, 0)); IGRAPH_FINALLY_CLEAN(6); return 0; } /** * \ingroup interface * \function igraph_destroy * \brief Frees the memory allocated for a graph object. * * * This function should be called for every graph object exactly once. * * * This function invalidates all iterators (of course), but the * iterators of a graph should be destroyed before the graph itself * anyway. * \param graph Pointer to the graph to free. * \return Error code. * * Time complexity: operating system specific. */ int igraph_destroy(igraph_t *graph) { IGRAPH_I_ATTRIBUTE_DESTROY(graph); igraph_vector_destroy(&graph->from); igraph_vector_destroy(&graph->to); igraph_vector_destroy(&graph->oi); igraph_vector_destroy(&graph->ii); igraph_vector_destroy(&graph->os); igraph_vector_destroy(&graph->is); return 0; } /** * \ingroup interface * \function igraph_copy * \brief Creates an exact (deep) copy of a graph. * * * This function deeply copies a graph object to create an exact * replica of it. The new replica should be destroyed by calling * \ref igraph_destroy() on it when not needed any more. * * * You can also create a shallow copy of a graph by simply using the * standard assignment operator, but be careful and do \em not * destroy a shallow replica. To avoid this mistake, creating shallow * copies is not recommended. * \param to Pointer to an uninitialized graph object. * \param from Pointer to the graph object to copy. * \return Error code. * * Time complexity: O(|V|+|E|) for a * graph with |V| vertices and * |E| edges. * * \example examples/simple/igraph_copy.c */ int igraph_copy(igraph_t *to, const igraph_t *from) { to->n=from->n; to->directed=from->directed; IGRAPH_CHECK(igraph_vector_copy(&to->from, &from->from)); IGRAPH_FINALLY(igraph_vector_destroy, &to->from); IGRAPH_CHECK(igraph_vector_copy(&to->to, &from->to)); IGRAPH_FINALLY(igraph_vector_destroy, &to->to); IGRAPH_CHECK(igraph_vector_copy(&to->oi, &from->oi)); IGRAPH_FINALLY(igraph_vector_destroy, &to->oi); IGRAPH_CHECK(igraph_vector_copy(&to->ii, &from->ii)); IGRAPH_FINALLY(igraph_vector_destroy, &to->ii); IGRAPH_CHECK(igraph_vector_copy(&to->os, &from->os)); IGRAPH_FINALLY(igraph_vector_destroy, &to->os); IGRAPH_CHECK(igraph_vector_copy(&to->is, &from->is)); IGRAPH_FINALLY(igraph_vector_destroy, &to->is); IGRAPH_I_ATTRIBUTE_COPY(to, from, 1,1,1); /* does IGRAPH_CHECK */ IGRAPH_FINALLY_CLEAN(6); return 0; } /** * \ingroup interface * \function igraph_add_edges * \brief Adds edges to a graph object. * * * The edges are given in a vector, the * first two elements define the first edge (the order is * from, to for directed * graphs). The vector * should contain even number of integer numbers between zero and the * number of vertices in the graph minus one (inclusive). If you also * want to add new vertices, call igraph_add_vertices() first. * \param graph The graph to which the edges will be added. * \param edges The edges themselves. * \param attr The attributes of the new edges, only used by high level * interfaces currently, you can supply 0 here. * \return Error code: * \c IGRAPH_EINVEVECTOR: invalid (odd) * edges vector length, \c IGRAPH_EINVVID: * invalid vertex id in edges vector. * * This function invalidates all iterators. * * * Time complexity: O(|V|+|E|) where * |V| is the number of vertices and * |E| is the number of * edges in the \em new, extended graph. * * \example examples/simple/igraph_add_edges.c */ int igraph_add_edges(igraph_t *graph, const igraph_vector_t *edges, void *attr) { long int no_of_edges=igraph_vector_size(&graph->from); long int edges_to_add=igraph_vector_size(edges)/2; long int i=0; igraph_error_handler_t *oldhandler; int ret1, ret2; igraph_vector_t newoi, newii; igraph_bool_t directed=igraph_is_directed(graph); if (igraph_vector_size(edges) % 2 != 0) { IGRAPH_ERROR("invalid (odd) length of edges vector", IGRAPH_EINVEVECTOR); } if (!igraph_vector_isininterval(edges, 0, igraph_vcount(graph)-1)) { IGRAPH_ERROR("cannot add edges", IGRAPH_EINVVID); } /* from & to */ IGRAPH_CHECK(igraph_vector_reserve(&graph->from, no_of_edges+edges_to_add)); IGRAPH_CHECK(igraph_vector_reserve(&graph->to , no_of_edges+edges_to_add)); while (i VECTOR(*edges)[i+1]) { igraph_vector_push_back(&graph->from, VECTOR(*edges)[i++]); /* reserved */ igraph_vector_push_back(&graph->to, VECTOR(*edges)[i++]); /* reserved */ } else { igraph_vector_push_back(&graph->to, VECTOR(*edges)[i++]); /* reserved */ igraph_vector_push_back(&graph->from, VECTOR(*edges)[i++]); /* reserved */ } } /* disable the error handler temporarily */ oldhandler=igraph_set_error_handler(igraph_error_handler_ignore); /* oi & ii */ ret1=igraph_vector_init(&newoi, no_of_edges); ret2=igraph_vector_init(&newii, no_of_edges); if (ret1 != 0 || ret2 != 0) { igraph_vector_resize(&graph->from, no_of_edges); /* gets smaller */ igraph_vector_resize(&graph->to, no_of_edges); /* gets smaller */ igraph_set_error_handler(oldhandler); IGRAPH_ERROR("cannot add edges", IGRAPH_ERROR_SELECT_2(ret1, ret2)); } ret1=igraph_vector_order(&graph->from, &graph->to, &newoi, graph->n); ret2=igraph_vector_order(&graph->to , &graph->from, &newii, graph->n); if (ret1 != 0 || ret2 != 0) { igraph_vector_resize(&graph->from, no_of_edges); igraph_vector_resize(&graph->to, no_of_edges); igraph_vector_destroy(&newoi); igraph_vector_destroy(&newii); igraph_set_error_handler(oldhandler); IGRAPH_ERROR("cannot add edges", IGRAPH_ERROR_SELECT_2(ret1, ret2)); } /* Attributes */ if (graph->attr) { igraph_set_error_handler(oldhandler); ret1=igraph_i_attribute_add_edges(graph, edges, attr); igraph_set_error_handler(igraph_error_handler_ignore); if (ret1 != 0) { igraph_vector_resize(&graph->from, no_of_edges); igraph_vector_resize(&graph->to, no_of_edges); igraph_vector_destroy(&newoi); igraph_vector_destroy(&newii); igraph_set_error_handler(oldhandler); IGRAPH_ERROR("cannot add edges", ret1); } } /* os & is, its length does not change, error safe */ igraph_i_create_start(&graph->os, &graph->from, &newoi, graph->n); igraph_i_create_start(&graph->is, &graph->to , &newii, graph->n); /* everything went fine */ igraph_vector_destroy(&graph->oi); igraph_vector_destroy(&graph->ii); graph->oi=newoi; graph->ii=newii; igraph_set_error_handler(oldhandler); return 0; } /** * \ingroup interface * \function igraph_add_vertices * \brief Adds vertices to a graph. * * * This function invalidates all iterators. * * \param graph The graph object to extend. * \param nv Non-negative integer giving the number of * vertices to add. * \param attr The attributes of the new vertices, only used by * high level interfaces, you can supply 0 here. * \return Error code: * \c IGRAPH_EINVAL: invalid number of new * vertices. * * Time complexity: O(|V|) where * |V| is * the number of vertices in the \em new, extended graph. * * \example examples/simple/igraph_add_vertices.c */ int igraph_add_vertices(igraph_t *graph, igraph_integer_t nv, void *attr) { long int ec=igraph_ecount(graph); long int i; if (nv < 0) { IGRAPH_ERROR("cannot add negative number of vertices", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_reserve(&graph->os, graph->n+nv+1)); IGRAPH_CHECK(igraph_vector_reserve(&graph->is, graph->n+nv+1)); igraph_vector_resize(&graph->os, graph->n+nv+1); /* reserved */ igraph_vector_resize(&graph->is, graph->n+nv+1); /* reserved */ for (i=graph->n+1; in+nv+1; i++) { VECTOR(graph->os)[i]=ec; VECTOR(graph->is)[i]=ec; } graph->n += nv; if (graph->attr) { IGRAPH_CHECK(igraph_i_attribute_add_vertices(graph, nv, attr)); } return 0; } /** * \ingroup interface * \function igraph_delete_edges * \brief Removes edges from a graph. * * * The edges to remove are given as an edge selector. * * * This function cannot remove vertices, they will be kept, even if * they lose all their edges. * * * This function invalidates all iterators. * \param graph The graph to work on. * \param edges The edges to remove. * \return Error code. * * Time complexity: O(|V|+|E|) where * |V| * and |E| are the number of vertices * and edges in the \em original graph, respectively. * * \example examples/simple/igraph_delete_edges.c */ int igraph_delete_edges(igraph_t *graph, igraph_es_t edges) { long int no_of_edges=igraph_ecount(graph); long int no_of_nodes=igraph_vcount(graph); long int edges_to_remove=0; long int remaining_edges; igraph_eit_t eit; igraph_vector_t newfrom, newto, newoi; int *mark; long int i, j; mark=igraph_Calloc(no_of_edges, int); if (mark==0) { IGRAPH_ERROR("Cannot delete edges", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, mark); IGRAPH_CHECK(igraph_eit_create(graph, edges, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); for (IGRAPH_EIT_RESET(eit); !IGRAPH_EIT_END(eit); IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); if (mark[e]==0) { edges_to_remove++; mark[e]++; } } remaining_edges=no_of_edges-edges_to_remove; /* We don't need the iterator any more */ igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); IGRAPH_VECTOR_INIT_FINALLY(&newfrom, remaining_edges); IGRAPH_VECTOR_INIT_FINALLY(&newto, remaining_edges); /* Actually remove the edges, move from pos i to pos j in newfrom/newto */ for (i=0,j=0; jfrom)[i]; VECTOR(newto)[j] = VECTOR(graph->to)[i]; j++; } } /* Create index, this might require additional memory */ IGRAPH_VECTOR_INIT_FINALLY(&newoi, remaining_edges); IGRAPH_CHECK(igraph_vector_order(&newfrom, &newto, &newoi, no_of_nodes)); IGRAPH_CHECK(igraph_vector_order(&newto, &newfrom, &graph->ii, no_of_nodes)); /* Edge attributes, we need an index that gives the ids of the original edges for every new edge. */ if (graph->attr) { igraph_vector_t idx; IGRAPH_VECTOR_INIT_FINALLY(&idx, remaining_edges); for (i=0, j=0; ifrom); igraph_vector_destroy(&graph->to); igraph_vector_destroy(&graph->oi); graph->from=newfrom; graph->to=newto; graph->oi=newoi; IGRAPH_FINALLY_CLEAN(3); igraph_Free(mark); IGRAPH_FINALLY_CLEAN(1); /* Create start vectors, no memory is needed for this */ igraph_i_create_start(&graph->os, &graph->from, &graph->oi, (igraph_integer_t) no_of_nodes); igraph_i_create_start(&graph->is, &graph->to, &graph->ii, (igraph_integer_t) no_of_nodes); /* Nothing to deallocate... */ return 0; } /** * \ingroup interface * \function igraph_delete_vertices * \brief Removes vertices (with all their edges) from the graph. * * * This function changes the ids of the vertices (except in some very * special cases, but these should not be relied on anyway). * * * This function invalidates all iterators. * * \param graph The graph to work on. * \param vertices The ids of the vertices to remove in a * vector. The vector may contain the same id more * than once. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the original graph. * * \example examples/simple/igraph_delete_vertices.c */ int igraph_delete_vertices(igraph_t *graph, const igraph_vs_t vertices) { return igraph_delete_vertices_idx(graph, vertices, /* idx= */ 0, /* invidx= */ 0); } int igraph_delete_vertices_idx(igraph_t *graph, const igraph_vs_t vertices, igraph_vector_t *idx, igraph_vector_t *invidx) { long int no_of_edges=igraph_ecount(graph); long int no_of_nodes=igraph_vcount(graph); igraph_vector_t edge_recoding, vertex_recoding; igraph_vector_t *my_vertex_recoding=&vertex_recoding; igraph_vit_t vit; igraph_t newgraph; long int i, j; long int remaining_vertices, remaining_edges; if (idx) { my_vertex_recoding=idx; IGRAPH_CHECK(igraph_vector_resize(idx, no_of_nodes)); igraph_vector_null(idx); } else { IGRAPH_VECTOR_INIT_FINALLY(&vertex_recoding, no_of_nodes); } IGRAPH_VECTOR_INIT_FINALLY(&edge_recoding, no_of_edges); IGRAPH_CHECK(igraph_vit_create(graph, vertices, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); /* mark the vertices to delete */ for (; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit) ) { long int vertex=IGRAPH_VIT_GET(vit); if (vertex < 0 || vertex >= no_of_nodes) { IGRAPH_ERROR("Cannot delete vertices", IGRAPH_EINVVID); } VECTOR(*my_vertex_recoding)[vertex]=1; } /* create vertex recoding vector */ for (remaining_vertices=0, i=0; ifrom)[i]; long int to=(long int) VECTOR(graph->to)[i]; if (VECTOR(*my_vertex_recoding)[from] != 0 && VECTOR(*my_vertex_recoding)[to ] != 0) { VECTOR(edge_recoding)[i]=remaining_edges+1; remaining_edges++; } } /* start creating the graph */ newgraph.n=(igraph_integer_t) remaining_vertices; newgraph.directed=graph->directed; /* allocate vectors */ IGRAPH_VECTOR_INIT_FINALLY(&newgraph.from, remaining_edges); IGRAPH_VECTOR_INIT_FINALLY(&newgraph.to, remaining_edges); IGRAPH_VECTOR_INIT_FINALLY(&newgraph.oi, remaining_edges); IGRAPH_VECTOR_INIT_FINALLY(&newgraph.ii, remaining_edges); IGRAPH_VECTOR_INIT_FINALLY(&newgraph.os, remaining_vertices+1); IGRAPH_VECTOR_INIT_FINALLY(&newgraph.is, remaining_vertices+1); /* Add the edges */ for (i=0, j=0; j0) { long int from=(long int) VECTOR(graph->from)[i]; long int to=(long int) VECTOR(graph->to )[i]; VECTOR(newgraph.from)[j]=VECTOR(*my_vertex_recoding)[from]-1; VECTOR(newgraph.to )[j]=VECTOR(*my_vertex_recoding)[to]-1; j++; } } /* update oi & ii */ IGRAPH_CHECK(igraph_vector_order(&newgraph.from, &newgraph.to, &newgraph.oi, remaining_vertices)); IGRAPH_CHECK(igraph_vector_order(&newgraph.to, &newgraph.from, &newgraph.ii, remaining_vertices)); IGRAPH_CHECK(igraph_i_create_start(&newgraph.os, &newgraph.from, &newgraph.oi, (igraph_integer_t) remaining_vertices)); IGRAPH_CHECK(igraph_i_create_start(&newgraph.is, &newgraph.to, &newgraph.ii, (igraph_integer_t) remaining_vertices)); /* attributes */ IGRAPH_I_ATTRIBUTE_COPY(&newgraph, graph, /*graph=*/ 1, /*vertex=*/0, /*edge=*/0); IGRAPH_FINALLY_CLEAN(6); IGRAPH_FINALLY(igraph_destroy, &newgraph); if (newgraph.attr) { igraph_vector_t iidx; IGRAPH_VECTOR_INIT_FINALLY(&iidx, remaining_vertices); for (i=0; in; } /** * \ingroup interface * \function igraph_ecount * \brief The number of edges in a graph. * * \param graph The graph. * \return Number of edges. * * Time complexity: O(1) */ igraph_integer_t igraph_ecount(const igraph_t *graph) { return (igraph_integer_t) igraph_vector_size(&graph->from); } /** * \ingroup interface * \function igraph_neighbors * \brief Adjacent vertices to a vertex. * * \param graph The graph to work on. * \param neis This vector will contain the result. The vector should * be initialized beforehand and will be resized. Starting from igraph * version 0.4 this vector is always sorted, the vertex ids are * in increasing order. * \param pnode The id of the node for which the adjacent vertices are * to be searched. * \param mode Defines the way adjacent vertices are searched in * directed graphs. It can have the following values: * \c IGRAPH_OUT, vertices reachable by an * edge from the specified vertex are searched; * \c IGRAPH_IN, vertices from which the * specified vertex is reachable are searched; * \c IGRAPH_ALL, both kinds of vertices are * searched. * This parameter is ignored for undirected graphs. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * \c IGRAPH_EINVMODE: invalid mode argument. * \c IGRAPH_ENOMEM: not enough memory. * * Time complexity: O(d), * d is the number * of adjacent vertices to the queried vertex. * * \example examples/simple/igraph_neighbors.c */ int igraph_neighbors(const igraph_t *graph, igraph_vector_t *neis, igraph_integer_t pnode, igraph_neimode_t mode) { long int length=0, idx=0; long int i, j; long int node=pnode; if (node<0 || node>igraph_vcount(graph)-1) { IGRAPH_ERROR("cannot get neighbors", IGRAPH_EINVVID); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("cannot get neighbors", IGRAPH_EINVMODE); } if (! graph->directed) { mode=IGRAPH_ALL; } /* Calculate needed space first & allocate it*/ if (mode & IGRAPH_OUT) { length += (VECTOR(graph->os)[node+1] - VECTOR(graph->os)[node]); } if (mode & IGRAPH_IN) { length += (VECTOR(graph->is)[node+1] - VECTOR(graph->is)[node]); } IGRAPH_CHECK(igraph_vector_resize(neis, length)); if (!igraph_is_directed(graph) || mode != IGRAPH_ALL) { if (mode & IGRAPH_OUT) { j=(long int) VECTOR(graph->os)[node+1]; for (i=(long int) VECTOR(graph->os)[node]; ito)[ (long int)VECTOR(graph->oi)[i] ]; } } if (mode & IGRAPH_IN) { j=(long int) VECTOR(graph->is)[node+1]; for (i=(long int) VECTOR(graph->is)[node]; ifrom)[ (long int)VECTOR(graph->ii)[i] ]; } } } else { /* both in- and out- neighbors in a directed graph, we need to merge the two 'vectors' */ long int jj1=(long int) VECTOR(graph->os)[node+1]; long int j2=(long int) VECTOR(graph->is)[node+1]; long int i1=(long int) VECTOR(graph->os)[node]; long int i2=(long int) VECTOR(graph->is)[node]; while (i1 < jj1 && i2 < j2) { long int n1=(long int) VECTOR(graph->to)[ (long int)VECTOR(graph->oi)[i1] ]; long int n2=(long int) VECTOR(graph->from)[ (long int)VECTOR(graph->ii)[i2] ]; if (n1n2) { VECTOR(*neis)[idx++]=n2; i2++; } else { VECTOR(*neis)[idx++]=n1; VECTOR(*neis)[idx++]=n2; i1++; i2++; } } while (i1 < jj1) { long int n1=(long int) VECTOR(graph->to)[ (long int)VECTOR(graph->oi)[i1] ]; VECTOR(*neis)[idx++]=n1; i1++; } while (i2 < j2) { long int n2=(long int) VECTOR(graph->from)[ (long int)VECTOR(graph->ii)[i2] ]; VECTOR(*neis)[idx++]=n2; i2++; } } return 0; } /** * \ingroup internal * */ int igraph_i_create_start(igraph_vector_t *res, igraph_vector_t *el, igraph_vector_t *iindex, igraph_integer_t nodes) { # define EDGE(i) (VECTOR(*el)[ (long int) VECTOR(*iindex)[(i)] ]) long int no_of_nodes; long int no_of_edges; long int i, j, idx; no_of_nodes=nodes; no_of_edges=igraph_vector_size(el); /* result */ IGRAPH_CHECK(igraph_vector_resize(res, nodes+1)); /* create the index */ if (igraph_vector_size(el)==0) { /* empty graph */ igraph_vector_null(res); } else { idx=-1; for (i=0; i<=EDGE(0); i++) { idx++; VECTOR(*res)[idx]=0; } for (i=1; iTRUE if the graph is directed, * FALSE otherwise. * * Time complexity: O(1) * * \example examples/simple/igraph_is_directed.c */ igraph_bool_t igraph_is_directed(const igraph_t *graph) { return graph->directed; } /** * \ingroup interface * \function igraph_degree * \brief The degree of some vertices in a graph. * * * This function calculates the in-, out- or total degree of the * specified vertices. * \param graph The graph. * \param res Vector, this will contain the result. It should be * initialized and will be resized to be the appropriate size. * \param vids Vector, giving the vertex ids of which the degree will * be calculated. * \param mode Defines the type of the degree. Valid modes are: * \c IGRAPH_OUT, out-degree; * \c IGRAPH_IN, in-degree; * \c IGRAPH_ALL, total degree (sum of the * in- and out-degree). * This parameter is ignored for undirected graphs. * \param loops Boolean, gives whether the self-loops should be * counted. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * \c IGRAPH_EINVMODE: invalid mode argument. * * Time complexity: O(v) if * loops is * TRUE, and * O(v*d) * otherwise. v is the number of * vertices for which the degree will be calculated, and * d is their (average) degree. * * \sa \ref igraph_strength() for the version that takes into account * edge weights. * * \example examples/simple/igraph_degree.c */ int igraph_degree(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops) { long int nodes_to_calc; long int i, j; igraph_vit_t vit; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("degree calculation failed", IGRAPH_EINVMODE); } nodes_to_calc=IGRAPH_VIT_SIZE(vit); if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } IGRAPH_CHECK(igraph_vector_resize(res, nodes_to_calc)); igraph_vector_null(res); if (loops) { if (mode & IGRAPH_OUT) { for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid=IGRAPH_VIT_GET(vit); VECTOR(*res)[i] += (VECTOR(graph->os)[vid+1]-VECTOR(graph->os)[vid]); } } if (mode & IGRAPH_IN) { for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid=IGRAPH_VIT_GET(vit); VECTOR(*res)[i] += (VECTOR(graph->is)[vid+1]-VECTOR(graph->is)[vid]); } } } else { /* no loops */ if (mode & IGRAPH_OUT) { for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid=IGRAPH_VIT_GET(vit); VECTOR(*res)[i] += (VECTOR(graph->os)[vid+1]-VECTOR(graph->os)[vid]); for (j=(long int) VECTOR(graph->os)[vid]; jos)[vid+1]; j++) { if (VECTOR(graph->to)[ (long int)VECTOR(graph->oi)[j] ]==vid) { VECTOR(*res)[i] -= 1; } } } } if (mode & IGRAPH_IN) { for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid=IGRAPH_VIT_GET(vit); VECTOR(*res)[i] += (VECTOR(graph->is)[vid+1]-VECTOR(graph->is)[vid]); for (j=(long int) VECTOR(graph->is)[vid]; jis)[vid+1]; j++) { if (VECTOR(graph->from)[ (long int)VECTOR(graph->ii)[j] ]==vid) { VECTOR(*res)[i] -= 1; } } } } } /* loops */ igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_edge * \brief Gives the head and tail vertices of an edge. * * \param graph The graph object. * \param eid The edge id. * \param from Pointer to an \type igraph_integer_t. The tail of the edge * will be placed here. * \param to Pointer to an \type igraph_integer_t. The head of the edge * will be placed here. * \return Error code. The current implementation always returns with * success. * \sa \ref igraph_get_eid() for the opposite operation. * * Added in version 0.2. * * Time complexity: O(1). */ int igraph_edge(const igraph_t *graph, igraph_integer_t eid, igraph_integer_t *from, igraph_integer_t *to) { if (igraph_is_directed(graph)) { *from = (igraph_integer_t) VECTOR(graph->from)[(long int)eid]; *to = (igraph_integer_t) VECTOR(graph->to )[(long int)eid]; } else { *from = (igraph_integer_t) VECTOR(graph->to )[(long int)eid]; *to = (igraph_integer_t) VECTOR(graph->from)[(long int)eid]; } return 0; } int igraph_edges(const igraph_t *graph, igraph_es_t eids, igraph_vector_t *edges) { igraph_eit_t eit; long int n, ptr=0; IGRAPH_CHECK(igraph_eit_create(graph, eids, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); n=IGRAPH_EIT_SIZE(eit); IGRAPH_CHECK(igraph_vector_resize(edges, n*2)); if (igraph_is_directed(graph)) { for (; !IGRAPH_EIT_END(eit); IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); VECTOR(*edges)[ptr++]=IGRAPH_FROM(graph, e); VECTOR(*edges)[ptr++]=IGRAPH_TO(graph, e); } } else { for (; !IGRAPH_EIT_END(eit); IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); VECTOR(*edges)[ptr++]=IGRAPH_TO(graph, e); VECTOR(*edges)[ptr++]=IGRAPH_FROM(graph, e); } } igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); return 0; } /* This is an unsafe macro. Only supply variable names, i.e. no expressions as parameters, otherwise nasty things can happen */ #define BINSEARCH(start,end,value,iindex,edgelist,N,pos) \ do { \ while ((start) < (end)) { \ long int mid=(start)+((end)-(start))/2; \ long int e=(long int) VECTOR((iindex))[mid]; \ if (VECTOR((edgelist))[e] < (value)) { \ (start)=mid+1; \ } else { \ (end)=mid; \ } \ } \ if ((start)<(N)) { \ long int e=(long int) VECTOR((iindex))[(start)]; \ if (VECTOR((edgelist))[e] == (value)) { \ *(pos)=(igraph_integer_t) e; \ } \ } } while(0) #define FIND_DIRECTED_EDGE(graph,xfrom,xto,eid) \ do { \ long int start=(long int) VECTOR(graph->os)[xfrom]; \ long int end=(long int) VECTOR(graph->os)[xfrom+1]; \ long int N=end; \ long int start2=(long int) VECTOR(graph->is)[xto]; \ long int end2=(long int) VECTOR(graph->is)[xto+1]; \ long int N2=end2; \ if (end-startoi,graph->to,N,eid); \ } else { \ BINSEARCH(start2,end2,xfrom,graph->ii,graph->from,N2,eid); \ } \ } while (0) #define FIND_UNDIRECTED_EDGE(graph,from,to,eid) \ do { \ long int xfrom1= from > to ? from : to; \ long int xto1= from > to ? to : from; \ FIND_DIRECTED_EDGE(graph,xfrom1,xto1,eid); \ } while (0) /** * \function igraph_get_eid * \brief Get the edge id from the end points of an edge. * * For undirected graphs \c pfrom and \c pto are exchangeable. * * \param graph The graph object. * \param eid Pointer to an integer, the edge id will be stored here. * \param pfrom The starting point of the edge. * \param pto The end point of the edge. * \param directed Logical constant, whether to search for directed * edges in a directed graph. Ignored for undirected graphs. * \param error Logical scalar, whether to report an error if the edge * was not found. If it is false, then -1 will be assigned to \p eid. * \return Error code. * \sa \ref igraph_edge() for the opposite operation. * * Time complexity: O(log (d)), where d is smaller of the out-degree * of \c pfrom and in-degree of \c pto if \p directed is true. If \p directed * is false, then it is O(log(d)+log(d2)), where d is the same as before and * d2 is the minimum of the out-degree of \c pto and the in-degree of \c pfrom. * * \example examples/simple/igraph_get_eid.c * * Added in version 0.2. */ int igraph_get_eid(const igraph_t *graph, igraph_integer_t *eid, igraph_integer_t pfrom, igraph_integer_t pto, igraph_bool_t directed, igraph_bool_t error) { long int from=pfrom, to=pto; long int nov=igraph_vcount(graph); if (from < 0 || to < 0 || from > nov-1 || to > nov-1) { IGRAPH_ERROR("cannot get edge id", IGRAPH_EINVVID); } *eid=-1; if (igraph_is_directed(graph)) { /* Directed graph */ FIND_DIRECTED_EDGE(graph,from,to,eid); if (!directed && *eid < 0) { FIND_DIRECTED_EDGE(graph,to,from,eid); } } else { /* Undirected graph, they only have one mode */ FIND_UNDIRECTED_EDGE(graph,from,to,eid); } if (*eid < 0) { if (error) { IGRAPH_ERROR("Cannot get edge id, no such edge", IGRAPH_EINVAL); } } return IGRAPH_SUCCESS; } int igraph_get_eids_pairs(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, igraph_bool_t directed, igraph_bool_t error); int igraph_get_eids_path(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error); int igraph_get_eids_pairs(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, igraph_bool_t directed, igraph_bool_t error) { long int n=igraph_vector_size(pairs); long int no_of_nodes=igraph_vcount(graph); long int i; igraph_integer_t eid=-1; if (n % 2 != 0) { IGRAPH_ERROR("Cannot get edge ids, invalid length of edge ids", IGRAPH_EINVAL); } if (!igraph_vector_isininterval(pairs, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot get edge ids, invalid vertex id", IGRAPH_EINVVID); } IGRAPH_CHECK(igraph_vector_resize(eids, n/2)); if (igraph_is_directed(graph)) { for (i=0; iVECTOR(pairs)[0] and * VECTOR(pairs)[1] give the first * pair, VECTOR(pairs)[2] and * VECTOR(pairs)[3] the second pair, etc. * * * If the \c pairs argument is a null pointer, and \c path is not a * null pointer, then the \c path is interpreted as a path given by * vertex ids and the edges along the path are returned. * * * If neither \c pairs nor \c path are null pointers, then both are * considered (first \c pairs and then \c path), and the results are * concatenated. * * * If the \c error argument is true, then it is an error to give pairs * of vertices that are not connected. Otherwise -1 is * reported for not connected vertices. * * * If there are multiple edges in the graph, then these are ignored; * i.e. for a given pair of vertex ids, always the same edge id is * returned, even if the pair is given multiple time in \c pairs or in * \c path. See \ref igraph_get_eids_multi() for a similar function * that works differently in case of multiple edges. * * \param graph The input graph. * \param eids Pointer to an initialized vector, the result is stored * here. It will be resized as needed. * \param pairs Vector giving pairs of vertices, or a null pointer. * \param path Vector giving vertex ids along a path, or a null * pointer. * \param directed Logical scalar, whether to consider edge directions * in directed graphs. This is ignored for undirected graphs. * \param error Logical scalar, whether it is an error to supply * non-connected vertices. If false, then -1 is * returned for non-connected pairs. * \return Error code. * * Time complexity: O(n log(d)), where n is the number of queried * edges and d is the average degree of the vertices. * * \sa \ref igraph_get_eid() for a single edge, \ref * igraph_get_eids_multi() for a version that handles multiple edges * better (at a cost). * * \example examples/simple/igraph_get_eids.c */ int igraph_get_eids(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error) { if (!pairs && !path) { igraph_vector_clear(eids); return 0; } else if (pairs && !path) { return igraph_get_eids_pairs(graph, eids, pairs, directed, error); } else if (!pairs && path) { return igraph_get_eids_path(graph, eids, path, directed, error); } else { /* both */ igraph_vector_t tmp; IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_CHECK(igraph_get_eids_pairs(graph, eids, pairs, directed, error)); IGRAPH_CHECK(igraph_get_eids_path(graph, &tmp, path, directed, error)); IGRAPH_CHECK(igraph_vector_append(eids, &tmp)); igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } } #undef BINSEARCH #undef FIND_DIRECTED_EDGE #undef FIND_UNDIRECTED_EDGE #define BINSEARCH(start,end,value,iindex,edgelist,N,pos,seen) \ do { \ while ((start) < (end)) { \ long int mid=(start)+((end)-(start))/2; \ long int e=(long int) VECTOR((iindex))[mid]; \ if (VECTOR((edgelist))[e] < (value)) { \ (start)=mid+1; \ } else { \ (end)=mid; \ } \ } \ if ((start)<(N)) { \ long int e=(long int) VECTOR((iindex))[(start)]; \ while ((start)<(N) && seen[e] && VECTOR(edgelist)[e] == (value)) { \ (start)++; \ e=(long int) VECTOR(iindex)[(start)]; \ } \ if ((start)<(N) && !(seen[e]) && VECTOR(edgelist)[e] == (value)) { \ *(pos)=(igraph_integer_t) e; \ } \ } } while(0) #define FIND_DIRECTED_EDGE(graph,xfrom,xto,eid,seen) \ do { \ long int start=(long int) VECTOR(graph->os)[xfrom]; \ long int end=(long int) VECTOR(graph->os)[xfrom+1]; \ long int N=end; \ long int start2=(long int) VECTOR(graph->is)[xto]; \ long int end2=(long int) VECTOR(graph->is)[xto+1]; \ long int N2=end2; \ if (end-startoi,graph->to,N,eid,seen); \ } else { \ BINSEARCH(start2,end2,xfrom,graph->ii,graph->from,N2,eid,seen); \ } \ } while (0) #define FIND_UNDIRECTED_EDGE(graph,from,to,eid,seen) \ do { \ long int xfrom1= from > to ? from : to; \ long int xto1= from > to ? to : from; \ FIND_DIRECTED_EDGE(graph,xfrom1,xto1,eid,seen); \ } while (0) int igraph_get_eids_multipairs(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, igraph_bool_t directed, igraph_bool_t error); int igraph_get_eids_multipath(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error); int igraph_get_eids_multipairs(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, igraph_bool_t directed, igraph_bool_t error) { long int n=igraph_vector_size(pairs); long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_bool_t *seen; long int i; igraph_integer_t eid=-1; if (n % 2 != 0) { IGRAPH_ERROR("Cannot get edge ids, invalid length of edge ids", IGRAPH_EINVAL); } if (!igraph_vector_isininterval(pairs, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot get edge ids, invalid vertex id", IGRAPH_EINVVID); } seen=igraph_Calloc(no_of_edges, igraph_bool_t); if (seen==0) { IGRAPH_ERROR("Cannot get edge ids", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, seen); IGRAPH_CHECK(igraph_vector_resize(eids, n/2)); if (igraph_is_directed(graph)) { for (i=0; i= 0) { seen[(long int)(eid)]=1; } else if (error) { IGRAPH_ERROR("Cannot get edge id, no such edge", IGRAPH_EINVAL); } } } else { for (i=0; i= 0) { seen[(long int)(eid)]=1; } else if (error) { IGRAPH_ERROR("Cannot get edge id, no such edge", IGRAPH_EINVAL); } } } igraph_Free(seen); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_get_eids_multipath(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error) { long int n=igraph_vector_size(path); long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_bool_t *seen; long int i; igraph_integer_t eid=-1; if (!igraph_vector_isininterval(path, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot get edge ids, invalid vertex id", IGRAPH_EINVVID); } seen=igraph_Calloc(no_of_edges, igraph_bool_t); if (!seen) { IGRAPH_ERROR("Cannot get edge ids", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, seen); IGRAPH_CHECK(igraph_vector_resize(eids, n==0 ? 0 : n-1)); if (igraph_is_directed(graph)) { for (i=0; i= 0) { seen[(long int)(eid)]=1; } else if (error) { IGRAPH_ERROR("Cannot get edge id, no such edge", IGRAPH_EINVAL); } } } else { for (i=0; i= 0) { seen[(long int)(eid)]=1; } else if (error) { IGRAPH_ERROR("Cannot get edge id, no such edge", IGRAPH_EINVAL); } } } igraph_Free(seen); IGRAPH_FINALLY_CLEAN(1); return 0; } #undef BINSEARCH #undef FIND_DIRECTED_EDGE #undef FIND_UNDIRECTED_EDGE /** * \function igraph_get_eids_multi * \brief Query edge ids based on their adjacent vertices, handle multiple edges. * * This function operates in two modes. If the \c pairs argument is * not a null pointer, but the \c path argument is, then it searches * for the edge ids of all pairs of vertices given in \c pairs. The * pairs of vertex ids are taken consecutively from the vector, * i.e. VECTOR(pairs)[0] and * VECTOR(pairs)[1] give the first pair, * VECTOR(pairs)[2] and VECTOR(pairs)[3] the * second pair, etc. * * * If the \c pairs argument is a null pointer, and \c path is not a * null pointer, then the \c path is interpreted as a path given by * vertex ids and the edges along the path are returned. * * * If the \c error argument is true, then it is an error to give pairs of * vertices that are not connected. Otherwise -1 is * returned for not connected vertex pairs. * * * An error is triggered if both \c pairs and \c path are non-null * pointers. * * * This function handles multiple edges properly, i.e. if the same * pair is given multiple times and they are indeed connected by * multiple edges, then each time a different edge id is reported. * * \param graph The input graph. * \param eids Pointer to an initialized vector, the result is stored * here. It will be resized as needed. * \param pairs Vector giving pairs of vertices, or a null pointer. * \param path Vector giving vertex ids along a path, or a null * pointer. * \param directed Logical scalar, whether to consider edge directions * in directed graphs. This is ignored for undirected graphs. * \param error Logical scalar, whether to report an error if * non-connected vertices are specified. If false, then -1 * is returned for non-connected vertex pairs. * \return Error code. * * Time complexity: O(|E|+n log(d)), where |E| is the number of edges * in the graph, n is the number of queried edges and d is the average * degree of the vertices. * * \sa \ref igraph_get_eid() for a single edge, \ref * igraph_get_eids() for a faster version that does not handle * multiple edges. */ int igraph_get_eids_multi(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error) { if (!pairs && !path) { igraph_vector_clear(eids); return 0; } else if (pairs && !path) { return igraph_get_eids_multipairs(graph, eids, pairs, directed, error); } else if (!pairs && path) { return igraph_get_eids_multipath(graph, eids, path, directed, error); } else { /* both */ IGRAPH_ERROR("Give `pairs' or `path' but not both", IGRAPH_EINVAL); } } /** * \function igraph_adjacent * \brief Gives the incident edges of a vertex. * * This function was superseded by \ref igraph_incident() in igraph 0.6. * Please use \ref igraph_incident() instead of this function. * * * Added in version 0.2, deprecated in version 0.6. */ int igraph_adjacent(const igraph_t *graph, igraph_vector_t *eids, igraph_integer_t pnode, igraph_neimode_t mode) { IGRAPH_WARNING("igraph_adjacent is deprecated, use igraph_incident"); return igraph_incident(graph, eids, pnode, mode); } /** * \function igraph_incident * \brief Gives the incident edges of a vertex. * * \param graph The graph object. * \param eids An initialized \type vector_t object. It will be resized * to hold the result. * \param pnode A vertex id. * \param mode Specifies what kind of edges to include for directed * graphs. \c IGRAPH_OUT means only outgoing edges, \c IGRAPH_IN only * incoming edges, \c IGRAPH_ALL both. This parameter is ignored for * undirected graphs. * \return Error code. \c IGRAPH_EINVVID: invalid \p pnode argument, * \c IGRAPH_EINVMODE: invalid \p mode argument. * * Added in version 0.2. * * Time complexity: O(d), the number of incident edges to \p pnode. */ int igraph_incident(const igraph_t *graph, igraph_vector_t *eids, igraph_integer_t pnode, igraph_neimode_t mode) { long int length=0, idx=0; long int i, j; long int node=pnode; if (node<0 || node>igraph_vcount(graph)-1) { IGRAPH_ERROR("cannot get neighbors", IGRAPH_EINVVID); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("cannot get neighbors", IGRAPH_EINVMODE); } if (! graph->directed) { mode=IGRAPH_ALL; } /* Calculate needed space first & allocate it*/ if (mode & IGRAPH_OUT) { length += (VECTOR(graph->os)[node+1] - VECTOR(graph->os)[node]); } if (mode & IGRAPH_IN) { length += (VECTOR(graph->is)[node+1] - VECTOR(graph->is)[node]); } IGRAPH_CHECK(igraph_vector_resize(eids, length)); if (mode & IGRAPH_OUT) { j=(long int) VECTOR(graph->os)[node+1]; for (i=(long int) VECTOR(graph->os)[node]; ioi)[i]; } } if (mode & IGRAPH_IN) { j=(long int) VECTOR(graph->is)[node+1]; for (i=(long int) VECTOR(graph->is)[node]; iii)[i]; } } return 0; } igraph/src/bigint.h0000644000175100001440000000665113431000472013760 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_BIGINT_H #define IGRAPH_BIGINT_H #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #include "igraph_types.h" #include "igraph_vector.h" #include "bignum.h" #include /* Arbitrary precision integer */ #define BASE_LIMB #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LIMB typedef struct igraph_biguint_t { igraph_vector_limb_t v; } igraph_biguint_t; #define IGRAPH_BIGUINT_DEFAULT_SIZE 5 int igraph_biguint_init(igraph_biguint_t *b); void igraph_biguint_destroy(igraph_biguint_t *b); int igraph_biguint_copy(igraph_biguint_t *to, igraph_biguint_t *from); int igraph_biguint_extend(igraph_biguint_t *b, limb_t l); int igraph_biguint_size(igraph_biguint_t *b); int igraph_biguint_resize(igraph_biguint_t *b, int newlength); int igraph_biguint_reserve(igraph_biguint_t *b, int length); int igraph_biguint_zero(igraph_biguint_t *b); int igraph_biguint_set_limb(igraph_biguint_t *b, int value); igraph_real_t igraph_biguint_get(igraph_biguint_t *b); int igraph_biguint_compare_limb(igraph_biguint_t *b, limb_t l); int igraph_biguint_compare(igraph_biguint_t *left, igraph_biguint_t *right); igraph_bool_t igraph_biguint_equal(igraph_biguint_t *left, igraph_biguint_t *right); igraph_bool_t igraph_biguint_bigger(igraph_biguint_t *left, igraph_biguint_t *right); igraph_bool_t igraph_biguint_biggerorequal(igraph_biguint_t *left, igraph_biguint_t *right); int igraph_biguint_inc(igraph_biguint_t *res, igraph_biguint_t *b); int igraph_biguint_dec(igraph_biguint_t *res, igraph_biguint_t *b); int igraph_biguint_add_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l); int igraph_biguint_sub_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l); int igraph_biguint_mul_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l); int igraph_biguint_add(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right); int igraph_biguint_sub(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right); int igraph_biguint_mul(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right); int igraph_biguint_div(igraph_biguint_t *q, igraph_biguint_t *r, igraph_biguint_t *u, igraph_biguint_t *v); int igraph_biguint_print(igraph_biguint_t *b); int igraph_biguint_fprint(igraph_biguint_t *b, FILE *file); __END_DECLS #endif igraph/src/attributes.c0000644000175100001440000002733213431000472014664 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_attributes.h" #include "igraph_memory.h" #include "config.h" #include #include /* Should you ever want to have a thread-local attribute handler table, prepend * IGRAPH_THREAD_LOCAL to the following declaration */ igraph_attribute_table_t *igraph_i_attribute_table=0; int igraph_i_attribute_init(igraph_t *graph, void *attr) { graph->attr=0; if (igraph_i_attribute_table) { return igraph_i_attribute_table->init(graph, attr); } else { return 0; } } void igraph_i_attribute_destroy(igraph_t *graph) { if (igraph_i_attribute_table) { igraph_i_attribute_table->destroy(graph); } } int igraph_i_attribute_copy(igraph_t *to, const igraph_t *from, igraph_bool_t ga, igraph_bool_t va, igraph_bool_t ea) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->copy(to, from, ga, va, ea); } else { return 0; } } int igraph_i_attribute_add_vertices(igraph_t *graph, long int nv, void *attr) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->add_vertices(graph, nv, attr); } else { return 0; } } int igraph_i_attribute_permute_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->permute_vertices(graph, newgraph, idx); } else { return 0; } } int igraph_i_attribute_combine_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->combine_vertices(graph, newgraph, merges, comb); } else { return 0; } } int igraph_i_attribute_add_edges(igraph_t *graph, const igraph_vector_t *edges, void *attr) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->add_edges(graph, edges, attr); } else { return 0; } } int igraph_i_attribute_permute_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->permute_edges(graph, newgraph, idx); } else { return 0; } } int igraph_i_attribute_combine_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->combine_edges(graph, newgraph, merges, comb); } else { return 0; } } int igraph_i_attribute_get_info(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_info(graph, gnames, gtypes, vnames, vtypes, enames, etypes); } else { return 0; } } igraph_bool_t igraph_i_attribute_has_attr(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->has_attr(graph, type, name); } else { return 0; } } int igraph_i_attribute_gettype(const igraph_t *graph, igraph_attribute_type_t *type, igraph_attribute_elemtype_t elemtype, const char *name) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->gettype(graph, type, elemtype, name); } else { return 0; } } int igraph_i_attribute_get_numeric_graph_attr(const igraph_t *graph, const char *name, igraph_vector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_numeric_graph_attr(graph, name, value); } else { return 0; } } int igraph_i_attribute_get_numeric_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_numeric_vertex_attr(graph, name, vs, value); } else { return 0; } } int igraph_i_attribute_get_numeric_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_numeric_edge_attr(graph, name, es, value); } else { return 0; } } int igraph_i_attribute_get_string_graph_attr(const igraph_t *graph, const char *name, igraph_strvector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_string_graph_attr(graph, name, value); } else { return 0; } } int igraph_i_attribute_get_string_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_strvector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_string_vertex_attr(graph, name, vs, value); } else { return 0; } } int igraph_i_attribute_get_string_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_strvector_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_string_edge_attr(graph, name, es, value); } else { return 0; } } int igraph_i_attribute_get_bool_graph_attr(const igraph_t *graph, const char *name, igraph_vector_bool_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_bool_graph_attr(graph, name, value); } else { return 0; } } int igraph_i_attribute_get_bool_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_bool_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_bool_vertex_attr(graph, name, vs, value); } else { return 0; } } int igraph_i_attribute_get_bool_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_bool_t *value) { if (igraph_i_attribute_table) { return igraph_i_attribute_table->get_bool_edge_attr(graph, name, es, value); } else { return 0; } } /** * \function igraph_i_set_attribute_table * \brief Attach an attribute table. * * This function attaches attribute handling code to the igraph library. * Note that the attribute handler table is \em not thread-local even if * igraph is compiled in thread-local mode. In the vast majority of cases, * this is not a significant restriction. * * \param table Pointer to an \ref igraph_attribute_table_t object * containing the functions for attribute manipulation. Supply \c * NULL here if you don't want attributes. * \return Pointer to the old attribute handling table. * * Time complexity: O(1). */ igraph_attribute_table_t * igraph_i_set_attribute_table(const igraph_attribute_table_t * table) { igraph_attribute_table_t *old=igraph_i_attribute_table; igraph_i_attribute_table=(igraph_attribute_table_t*) table; return old; } igraph_bool_t igraph_has_attribute_table() { return igraph_i_attribute_table != 0; } int igraph_attribute_combination_init(igraph_attribute_combination_t *comb) { IGRAPH_CHECK(igraph_vector_ptr_init(&comb->list, 0)); return 0; } void igraph_attribute_combination_destroy(igraph_attribute_combination_t *comb) { long int i, n=igraph_vector_ptr_size(&comb->list); for (i=0; ilist)[i]; if (rec->name) { igraph_Free(rec->name); } igraph_Free(rec); } igraph_vector_ptr_destroy(&comb->list); } int igraph_attribute_combination_add(igraph_attribute_combination_t *comb, const char *name, igraph_attribute_combination_type_t type, igraph_function_pointer_t func) { long int i, n=igraph_vector_ptr_size(&comb->list); /* Search, in case it is already there */ for (i=0; ilist)[i]; const char *n=r->name; if ( (!name && !n) || (name && n && !strcmp(n, name)) ) { r->type=type; r->func=func; break; } } if (i==n) { /* This is a new attribute name */ igraph_attribute_combination_record_t *rec= igraph_Calloc(1, igraph_attribute_combination_record_t); if (!rec) { IGRAPH_ERROR("Cannot create attribute combination data", IGRAPH_ENOMEM); } if (!name) { rec->name=0; } else { rec->name=strdup(name); } rec->type=type; rec->func=func; IGRAPH_CHECK(igraph_vector_ptr_push_back(&comb->list, rec)); } return 0; } int igraph_attribute_combination_remove(igraph_attribute_combination_t *comb, const char *name) { long int i, n=igraph_vector_ptr_size(&comb->list); /* Search, in case it is already there */ for (i=0; ilist)[i]; const char *n=r->name; if ( (!name && !n) || (name && n && !strcmp(n, name)) ) { break; } } if (i!=n) { igraph_attribute_combination_record_t *r=VECTOR(comb->list)[i]; if (r->name) { igraph_Free(r->name); } igraph_Free(r); igraph_vector_ptr_remove(&comb->list, i); } else { /* It is not there, we don't do anything */ } return 0; } int igraph_attribute_combination_query(const igraph_attribute_combination_t *comb, const char *name, igraph_attribute_combination_type_t *type, igraph_function_pointer_t *func) { long int i, def=-1, len=igraph_vector_ptr_size(&comb->list); for (i=0; ilist)[i]; const char *n=rec->name; if ( (!name && !n) || (name && n && !strcmp(n, name)) ) { *type=rec->type; *func=rec->func; return 0; } if (!n) { def=i; } } if (def==-1) { /* Did not find anything */ *type=IGRAPH_ATTRIBUTE_COMBINE_DEFAULT; *func=0; } else { igraph_attribute_combination_record_t *rec=VECTOR(comb->list)[def]; *type=rec->type; *func=rec->func; } return 0; } int igraph_attribute_combination(igraph_attribute_combination_t *comb, ...) { va_list ap; IGRAPH_CHECK(igraph_attribute_combination_init(comb)); va_start(ap, comb); while (1) { igraph_function_pointer_t func=0; igraph_attribute_combination_type_t type; const char *name; name=va_arg(ap, const char *); if (name == IGRAPH_NO_MORE_ATTRIBUTES) { break; } type=(igraph_attribute_combination_type_t)va_arg(ap, int); if (type == IGRAPH_ATTRIBUTE_COMBINE_FUNCTION) { #if defined(__GNUC__) func=va_arg(ap, void (*)(void)); #else func=va_arg(ap, void*); #endif } if (strlen(name)==0) { name=0; } IGRAPH_CHECK(igraph_attribute_combination_add(comb, name, type, func)); } va_end(ap); return 0; } igraph/src/other.c0000644000175100001440000003352613431000472013621 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_nongraph.h" #include "igraph_types.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" #include "igraph_types_internal.h" #include "config.h" #include "plfit/error.h" #include "plfit/plfit.h" #include #include #include /** * \ingroup nongraph * \function igraph_running_mean * \brief Calculates the running mean of a vector. * * * The running mean is defined by the mean of the * previous \p binwidth values. * \param data The vector containing the data. * \param res The vector containing the result. This should be * initialized before calling this function and will be * resized. * \param binwidth Integer giving the width of the bin for the running * mean calculation. * \return Error code. * * Time complexity: O(n), * n is the length of * the data vector. */ int igraph_running_mean(const igraph_vector_t *data, igraph_vector_t *res, igraph_integer_t binwidth) { double sum=0; long int i; /* Check */ if (igraph_vector_size(data) < binwidth) { IGRAPH_ERROR("Vector too short for this binwidth", IGRAPH_EINVAL); } /* Memory for result */ IGRAPH_CHECK(igraph_vector_resize(res, (long int)(igraph_vector_size(data)-binwidth+1))); /* Initial bin */ for (i=0; i * The convex hull is determined by the Graham scan algorithm. * See the following reference for details: * * * Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford * Stein. Introduction to Algorithms, Second Edition. MIT Press and * McGraw-Hill, 2001. ISBN 0262032937. Pages 949-955 of section 33.3: * Finding the convex hull. * * \param data vector containing the coordinates. The length of the * vector must be even, since it contains X-Y coordinate pairs. * \param resverts the vector containing the result, e.g. the vector of * vertex indices used as the corners of the convex hull. Supply * \c NULL here if you are only interested in the coordinates of * the convex hull corners. * \param rescoords the matrix containing the coordinates of the selected * corner vertices. Supply \c NULL here if you are only interested in * the vertex indices. * \return Error code: * \c IGRAPH_ENOMEM: not enough memory * * Time complexity: O(n log(n)) where n is the number of vertices * * \example examples/simple/igraph_convex_hull.c */ int igraph_convex_hull(const igraph_matrix_t *data, igraph_vector_t *resverts, igraph_matrix_t *rescoords) { igraph_integer_t no_of_nodes; long int i, pivot_idx=0, last_idx, before_last_idx, next_idx, j; igraph_real_t* angles; igraph_vector_t stack; igraph_indheap_t order; igraph_real_t px, py, cp; no_of_nodes=(igraph_integer_t) igraph_matrix_nrow(data); if (igraph_matrix_ncol(data) != 2) { IGRAPH_ERROR("matrix must have 2 columns", IGRAPH_EINVAL); } if (no_of_nodes == 0) { if (resverts != 0) { IGRAPH_CHECK(igraph_vector_resize(resverts, 0)); } if (rescoords != 0) { IGRAPH_CHECK(igraph_matrix_resize(rescoords, 0, 2)); } /**************************** this is an exit here *********/ return 0; } angles=igraph_Calloc(no_of_nodes, igraph_real_t); if (!angles) IGRAPH_ERROR("not enough memory for angle array", IGRAPH_ENOMEM); IGRAPH_FINALLY(free, angles); IGRAPH_VECTOR_INIT_FINALLY(&stack, 0); /* Search for the pivot vertex */ for (i=1; i= 2) ? (long int) VECTOR(stack)[j-2] : -1; } } /* Create result vector */ if (resverts != 0) { igraph_vector_clear(resverts); IGRAPH_CHECK(igraph_vector_append(resverts, &stack)); } if (rescoords != 0) { igraph_matrix_select_rows(data, rescoords, &stack); } /* Free everything */ igraph_vector_destroy(&stack); igraph_indheap_destroy(&order); IGRAPH_FINALLY_CLEAN(2); return 0; } static const char* igraph_i_plfit_error_message = 0; static void igraph_i_plfit_error_handler_store(const char *reason, const char *file, int line, int plfit_errno) { igraph_i_plfit_error_message = reason; } /** * \ingroup nongraph * \function igraph_power_law_fit * \brief Fits a power-law distribution to a vector of numbers * * This function fits a power-law distribution to a vector containing samples * from a distribution (that is assumed to follow a power-law of course). In * a power-law distribution, it is generally assumed that P(X=x) is * proportional to x-alpha, where x is a positive number and alpha * is greater than 1. In many real-world cases, the power-law behaviour kicks * in only above a threshold value \em xmin. The goal of this functions is to * determine \em alpha if \em xmin is given, or to determine \em xmin and the * corresponding value of \em alpha. * * * The function uses the maximum likelihood principle to determine \em alpha * for a given \em xmin; in other words, the function will return the \em alpha * value for which the probability of drawing the given sample is the highest. * When \em xmin is not given in advance, the algorithm will attempt to find * the optimal \em xmin value for which the p-value of a Kolmogorov-Smirnov * test between the fitted distribution and the original sample is the largest. * The function uses the method of Clauset, Shalizi and Newman to calculate the * parameters of the fitted distribution. See the following reference for * details: * * * Aaron Clauset, Cosma R .Shalizi and Mark E.J. Newman: Power-law * distributions in empirical data. SIAM Review 51(4):661-703, 2009. * * \param data vector containing the samples for which a power-law distribution * is to be fitted. Note that you have to provide the \em samples, * not the probability density function or the cumulative * distribution function. For example, if you wish to fit * a power-law to the degrees of a graph, you can use the output of * \ref igraph_degree directly as an input argument to * \ref igraph_power_law_fit * \param result the result of the fitting algorithm. See \ref igraph_plfit_result_t * for more details. * \param xmin the minimum value in the sample vector where the power-law * behaviour is expected to kick in. Samples smaller than \c xmin * will be ignored by the algoritm. Pass zero here if you want to * include all the samples. If \c xmin is negative, the algorithm * will attempt to determine its best value automatically. * \param force_continuous assume that the samples in the \c data argument come * from a continuous distribution even if the sample vector * contains integer values only (by chance). If this argument is * false, igraph will assume a continuous distribution if at least * one sample is non-integer and assume a discrete distribution * otherwise. * \return Error code: * \c IGRAPH_ENOMEM: not enough memory * \c IGRAPH_EINVAL: one of the arguments is invalid * \c IGRAPH_EOVERFLOW: overflow during the fitting process * \c IGRAPH_EUNDERFLOW: underflow during the fitting process * \c IGRAPH_FAILURE: the underlying algorithm signaled a failure * without returning a more specific error code * * Time complexity: in the continuous case, O(n log(n)) if \c xmin is given. * In the discrete case, the time complexity is dominated by the complexity of * the underlying L-BFGS algorithm that is used to optimize alpha. If \c xmin * is not given, the time complexity is multiplied by the number of unique * samples in the input vector (although it should be faster in practice). * * \example examples/simple/igraph_power_law_fit.c */ int igraph_power_law_fit(const igraph_vector_t* data, igraph_plfit_result_t* result, igraph_real_t xmin, igraph_bool_t force_continuous) { plfit_error_handler_t* plfit_stored_error_handler; plfit_result_t plfit_result; plfit_continuous_options_t cont_options; plfit_discrete_options_t disc_options; igraph_bool_t discrete = force_continuous ? 0 : 1; igraph_bool_t finite_size_correction; int retval; size_t i, n; n = (size_t) igraph_vector_size(data); finite_size_correction = (n < 50); if (discrete) { /* Does the vector contain discrete values only? */ for (i = 0; i < n; i++) { if ((long int)(VECTOR(*data)[i]) != VECTOR(*data)[i]) { discrete = 0; break; } } } plfit_stored_error_handler = plfit_set_error_handler(igraph_i_plfit_error_handler_store); if (discrete) { plfit_discrete_options_init(&disc_options); disc_options.finite_size_correction = (plfit_bool_t) finite_size_correction; if (xmin >= 0) { retval = plfit_estimate_alpha_discrete(VECTOR(*data), n, xmin, &disc_options, &plfit_result); } else { retval = plfit_discrete(VECTOR(*data), n, &disc_options, &plfit_result); } } else { plfit_continuous_options_init(&cont_options); cont_options.finite_size_correction = (plfit_bool_t) finite_size_correction; if (xmin >= 0) { retval = plfit_estimate_alpha_continuous(VECTOR(*data), n, xmin, &cont_options, &plfit_result); } else { retval = plfit_continuous(VECTOR(*data), n, &cont_options, &plfit_result); } } plfit_set_error_handler(plfit_stored_error_handler); switch (retval) { case PLFIT_FAILURE: IGRAPH_ERROR(igraph_i_plfit_error_message, IGRAPH_FAILURE); break; case PLFIT_EINVAL: IGRAPH_ERROR(igraph_i_plfit_error_message, IGRAPH_EINVAL); break; case PLFIT_UNDRFLOW: IGRAPH_ERROR(igraph_i_plfit_error_message, IGRAPH_EUNDERFLOW); break; case PLFIT_OVERFLOW: IGRAPH_ERROR(igraph_i_plfit_error_message, IGRAPH_EOVERFLOW); break; case PLFIT_ENOMEM: IGRAPH_ERROR(igraph_i_plfit_error_message, IGRAPH_ENOMEM); break; default: break; } if (result) { result->continuous = !discrete; result->alpha = plfit_result.alpha; result->xmin = plfit_result.xmin; result->L = plfit_result.L; result->D = plfit_result.D; result->p = plfit_result.p; } return 0; } /** * Internal function, floating point division * Used only in compilers not supporting INFINITY and HUGE_VAL to create * infinity values */ double igraph_i_fdiv(const double a, const double b) { return a / b; } igraph/src/CHOLMOD.diff0000644000175100001440000000550713430770171014262 0ustar hornikusersdiff -r -x '*.o' -x '*.lo' -x .deps -x .dirstamp -x .libs CHOLMOD-orig/Include/cholmod_blas.h CHOLMOD/Include/cholmod_blas.h 108,115c108,115 < #define BLAS_DTRSV dtrsv < #define BLAS_DGEMV dgemv < #define BLAS_DTRSM dtrsm < #define BLAS_DGEMM dgemm < #define BLAS_DSYRK dsyrk < #define BLAS_DGER dger < #define BLAS_DSCAL dscal < #define LAPACK_DPOTRF dpotrf --- > #define BLAS_DTRSV igraphdtrsv > #define BLAS_DGEMV igraphdgemv > #define BLAS_DTRSM igraphdtrsm > #define BLAS_DGEMM igraphdgemm > #define BLAS_DSYRK igraphdsyrk > #define BLAS_DGER igraphdger > #define BLAS_DSCAL igraphdscal > #define LAPACK_DPOTRF igraphdpotrf 128,135c128,135 < #define BLAS_DTRSV dtrsv_ < #define BLAS_DGEMV dgemv_ < #define BLAS_DTRSM dtrsm_ < #define BLAS_DGEMM dgemm_ < #define BLAS_DSYRK dsyrk_ < #define BLAS_DGER dger_ < #define BLAS_DSCAL dscal_ < #define LAPACK_DPOTRF dpotrf_ --- > #define BLAS_DTRSV igraphdtrsv_ > #define BLAS_DGEMV igraphdgemv_ > #define BLAS_DTRSM igraphdtrsm_ > #define BLAS_DGEMM igraphdgemm_ > #define BLAS_DSYRK igraphdsyrk_ > #define BLAS_DGER igraphdger_ > #define BLAS_DSCAL igraphdscal_ > #define LAPACK_DPOTRF igraphdpotrf_ diff -r -x '*.o' -x '*.lo' -x .deps -x .dirstamp -x .libs CHOLMOD-orig/Supernodal/cholmod_super_numeric.c CHOLMOD/Supernodal/cholmod_super_numeric.c 79,82c79,82 < #define COMPLEX < #include "t_cholmod_super_numeric.c" < #define ZOMPLEX < #include "t_cholmod_super_numeric.c" --- > /* #define COMPLEX */ > /* #include "t_cholmod_super_numeric.c" */ > /* #define ZOMPLEX */ > /* #include "t_cholmod_super_numeric.c" */ 283,290c283,290 < case CHOLMOD_COMPLEX: < ok = c_cholmod_super_numeric (A, F, beta, L, C, Common) ; < break ; < < case CHOLMOD_ZOMPLEX: < /* This operates on complex L, not zomplex */ < ok = z_cholmod_super_numeric (A, F, beta, L, C, Common) ; < break ; --- > /* case CHOLMOD_COMPLEX: */ > /* ok = c_cholmod_super_numeric (A, F, beta, L, C, Common) ; */ > /* break ; */ > > /* case CHOLMOD_ZOMPLEX: */ > /* /\* This operates on complex L, not zomplex *\/ */ > /* ok = z_cholmod_super_numeric (A, F, beta, L, C, Common) ; */ > /* break ; */ diff -r -x '*.o' -x '*.lo' -x .deps -x .dirstamp -x .libs CHOLMOD-orig/Supernodal/cholmod_super_solve.c CHOLMOD/Supernodal/cholmod_super_solve.c 29,30c29,30 < #define COMPLEX < #include "t_cholmod_super_solve.c" --- > /* #define COMPLEX */ > /* #include "t_cholmod_super_solve.c" */ 112,114c112,114 < case CHOLMOD_COMPLEX: < c_cholmod_super_lsolve (L, X, E, Common) ; < break ; --- > /* case CHOLMOD_COMPLEX: */ > /* c_cholmod_super_lsolve (L, X, E, Common) ; */ > /* break ; */ 205,207c205,207 < case CHOLMOD_COMPLEX: < c_cholmod_super_ltsolve (L, X, E, Common) ; < break ; --- > /* case CHOLMOD_COMPLEX: */ > /* c_cholmod_super_ltsolve (L, X, E, Common) ; */ > /* break ; */ igraph/src/interrupt.c0000644000175100001440000000276413431000472014534 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interrupt.h" #include "config.h" #include #include #include IGRAPH_THREAD_LOCAL igraph_interruption_handler_t *igraph_i_interruption_handler=0; int igraph_allow_interruption(void* data) { if (igraph_i_interruption_handler) { return igraph_i_interruption_handler(data); } return IGRAPH_SUCCESS; } igraph_interruption_handler_t * igraph_set_interruption_handler (igraph_interruption_handler_t * new_handler) { igraph_interruption_handler_t * previous_handler = igraph_i_interruption_handler; igraph_i_interruption_handler = new_handler; return previous_handler; } igraph/src/pottsmodel_2.cpp0000644000175100001440000021365513431000472015456 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt This file was modified by Vincent Traag The original copyright notice follows here */ /*************************************************************************** pottsmodel.cpp - description ------------------- begin : Fri May 28 2004 copyright : (C) 2004 by email : ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include #include #include #include #include "pottsmodel_2.h" #include "NetRoutines.h" using namespace std; #include "igraph_random.h" #include "igraph_interrupt_internal.h" #include "config.h" //################################################################################################# PottsModel::PottsModel(network *n, unsigned int qvalue, int m) : acceptance(0) { DLList_Iter iter; NNode *n_cur; unsigned int *i_ptr; net=n; q=qvalue; operation_mode=m; k_max=0; //needed in calculating modularity Qa =new double[q+1]; //weights for each spin state needed in Monte Carlo process weights=new double[q+1]; //bookkeeping of occupation numbers of spin states or the number of links in community color_field=new double[q+1]; neighbours=new double[q+1]; num_of_nodes=net->node_list->Size(); num_of_links=net->link_list->Size(); n_cur=iter.First(net->node_list); //these lists are needed to keep track of spin states for parallel update mode new_spins=new DL_Indexed_List(); previous_spins=new DL_Indexed_List(); while (!iter.End()) { if (k_maxGet_Degree()) k_max=n_cur->Get_Degree(); i_ptr=new unsigned int; *i_ptr=0; new_spins->Push(i_ptr); i_ptr=new unsigned int; *i_ptr=0; previous_spins->Push(i_ptr); n_cur=iter.Next(); } return; } //####################################################### //Destructor of PottsModel //######################################################## PottsModel::~PottsModel() { /* The DLItem destructor does not delete its item currently, because of some bad design. As a workaround, we delete them here by hand */ new_spins->delete_items(); previous_spins->delete_items(); delete new_spins; delete previous_spins; delete [] Qa; delete [] weights; delete [] color_field; delete [] neighbours; return; } //##################################################### //Assing an initial random configuration of spins to nodes //if called with negative argument or the spin used as argument //when called with positve one. //This may be handy, if you want to warm up the network. //#################################################### unsigned long PottsModel::assign_initial_conf(int spin) { int s; DLList_Iter iter; DLList_Iter l_iter; NNode *n_cur; NLink *l_cur; double sum_weight; double av_k_squared=0.0; double av_k=0.0; // printf("Assigning initial configuration...\n"); // initialize colorfield for (unsigned int i=0; i<=q; i++) color_field[i]=0.0; // total_degree_sum=0.0; n_cur=iter.First(net->node_list); while (!iter.End()) { if (spin<0) s=RNG_INTEGER(1,q); else s=spin; n_cur->Set_ClusterIndex(s); l_cur=l_iter.First(n_cur->Get_Links()); sum_weight=0; while (!l_iter.End()) { sum_weight+=l_cur->Get_Weight(); //weight should be one, in case we are not using it. l_cur=l_iter.Next(); } // we set the sum of the weights or the degree as the weight of the node, this way // we do not have to calculate it again. n_cur->Set_Weight(sum_weight); av_k_squared+=sum_weight*sum_weight; av_k+=sum_weight; // in case we want all links to be contribute equally - parameter gamm=fixed if (operation_mode==0) { color_field[s]++; } else { color_field[s]+=sum_weight; } // or in case we want to use a weight of each link that is proportional to k_i\times k_j total_degree_sum+=sum_weight; n_cur=iter.Next(); } av_k_squared/=double(net->node_list->Size()); av_k/=double(net->node_list->Size()); // total_degree_sum-=av_k_squared/av_k; // printf("Total Degree Sum=2M=%f\n",total_degree_sum); return net->node_list->Size(); } //##################################################################### //If I ever manage to write a decent LookUp function, it will be here //##################################################################### unsigned long PottsModel::initialize_lookup(double kT, double gamma) { IGRAPH_UNUSED(kT); IGRAPH_UNUSED(gamma); /* double beta; // the look-up table contains all entries of exp(-beta(-neighbours+gamma*h)) // as needed in the HeatBath algorithm beta=1.0/kT; for (long w=0; w<=k_max+num_of_nodes; w++) { neg_lookup[w]=exp(-beta*-w } delta_ij[0]=1.0; for (long w=-num_of_nodes-k_max; w<=k_max+num_of_nodes; w++) { } // wenn wir spaeter exp(-1/kT*gamma*(nk+1-nj) fuer eine spin-flip von j nach k benoetigen schauen wir nur noch hier nach for (unsigned long n=1; n<=num_of_nodes; n++) { gamma_term[n]=exp(-double(n)/kT*gamma); } gamma_term[0]=1.0; */ return 1; } //##################################################################### // Q denotes the modulary of the network // This function calculates it initially // In the event of a spin changing its state, it only needs updating // Note that Qmatrix and Qa are only counting! The normalization // by num_of_links is done later //#################################################################### double PottsModel::initialize_Qmatrix(void) { DLList_Iter l_iter; NLink *l_cur; unsigned int i,j; //initialize with zeros num_of_links=net->link_list->Size(); for (i=0; i<=q; i++) { Qa[i]=0.0; for (j=i; j<=q; j++) { Qmatrix[i][j]=0.0; Qmatrix[j][i]=0.0; } } //go over all links and make corresponding entries in Q matrix //An edge connecting state i wiht state j will get an entry in Qij and Qji l_cur=l_iter.First(net->link_list); while (!l_iter.End()) { i=l_cur->Get_Start()->Get_ClusterIndex(); j=l_cur->Get_End()->Get_ClusterIndex(); //printf("%d %d\n",i,j); Qmatrix[i][j]+=l_cur->Get_Weight(); Qmatrix[j][i]+=l_cur->Get_Weight(); l_cur=l_iter.Next(); } //Finally, calculate sum over rows and keep in Qa for (i=0; i<=q; i++) { for (j=0; j<=q; j++) Qa[i]+=Qmatrix[i][j]; } return calculate_Q(); } //#################################################################### // This function does the actual calculation of Q from the matrix // The normalization by num_of_links is done here //#################################################################### double PottsModel::calculate_Q() { double Q=0.0; for (unsigned int i=0; i<=q; i++) { Q+=Qmatrix[i][i]-Qa[i]*Qa[i]/double(2.0*net->sum_weights); if ((Qa[i]<0.0) || Qmatrix[i][i]<0.0) { // printf("Negatives Qa oder Qii\n\n\n"); //printf("Press any key to continue\n\n"); //cin >> Q; } } Q/=double(2.0*net->sum_weights); return Q; } double PottsModel::calculate_genQ(double gamma) { double Q=0.0; for (unsigned int i=0; i<=q; i++) { Q+=Qmatrix[i][i]-gamma*Qa[i]*Qa[i]/double(2.0*net->sum_weights); if ((Qa[i]<0.0) || Qmatrix[i][i]<0.0) { // printf("Negatives Qa oder Qii\n\n\n"); //printf("Press any key to continue\n\n"); //cin >> Q; } } Q/=double(2.0*net->sum_weights); return Q; } //####################################################################### // This function calculates the Energy for the standard Hamiltonian // given a particular value of gamma and the current spin states // ##################################################################### double PottsModel::calculate_energy(double gamma) { double e=0.0; DLList_Iter l_iter; NLink *l_cur; l_cur=l_iter.First(net->link_list); //every in-cluster edge contributes -1 while (!l_iter.End()) { if (l_cur->Get_Start()->Get_ClusterIndex()==l_cur->Get_End()->Get_ClusterIndex()) e--;; l_cur=l_iter.Next(); } //and the penalty term contributes according to cluster sizes for (unsigned int i=1; i<=q; i++) { e+=gamma*0.5*double(color_field[i])*double((color_field[i]-1)); } energy=e; return e; } //########################################################################## // We would like to start from a temperature with at least 95 of all proposed // spin changes accepted in 50 sweeps over the network // The function returns the Temperature found //######################################################################### double PottsModel::FindStartTemp(double gamma, double prob, double ts) { double kT; kT=ts; //assing random initial condition assign_initial_conf(-1); //initialize Modularity matrix, from now on, it will be updated at every spin change initialize_Qmatrix(); // the factor 1-1/q is important, since even, at infinite temperature, // only 1-1/q of all spins do change their state, since a randomly chooses new // state is with prob. 1/q the old state. while (acceptance<(1.0-1.0/double(q))*0.95) //want 95% acceptance { kT=kT*1.1; // if I ever have a lookup table, it will need initialization for every kT //initialize_lookup(kT,k_max,net->node_list->Size()); HeatBathParallelLookup(gamma,prob, kT,50); // printf("kT=%f acceptance=%f\n", kT, acceptance); } kT*=1.1; // just to be sure... // printf("Starting with acceptance ratio: %1.6f bei kT=%2.4f\n",acceptance,kT); return kT; } //############################################################## //This function does a parallel update at zero T //Hence, it is really fast on easy problems //max sweeps is the maximum number of sweeps it should perform, //if it does not converge earlier //############################################################## long PottsModel::HeatBathParallelLookupZeroTemp(double gamma, double prob, unsigned int max_sweeps) { DLList_Iter iter, net_iter; DLList_Iter l_iter; DLList_Iter i_iter, i_iter2; NNode *node, *n_cur; NLink *l_cur; unsigned int *SPIN, *P_SPIN, new_spin, spin_opt, old_spin, spin, sweep; // long h; // degree; unsigned long changes; double h, delta=0, deltaE, deltaEmin, w, degree; //HugeArray neighbours; bool cyclic=0; sweep=0; changes=1; while (sweepnode_list); SPIN=i_iter.First(new_spins); while (!net_iter.End()) { // How many neigbors of each type? // set them all zero for (unsigned int i=0; i<=q; i++) neighbours[i]=0; degree=node->Get_Weight(); //Loop over all links (=neighbours) l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { //printf("%s %s\n",node->Get_Name(),n_cur->Get_Name()); w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } neighbours[n_cur->Get_ClusterIndex()]+=w; l_cur=l_iter.Next(); } //Search optimal Spin old_spin=node->Get_ClusterIndex(); //degree=node->Get_Degree(); switch (operation_mode) { case 0: { delta=1.0; break; } case 1: { //newman modularity prob=degree/total_degree_sum; delta=degree; break; } } spin_opt=old_spin; deltaEmin=0.0; for (spin=1; spin<=q; spin++) // all possible spin states { if (spin!=old_spin) { h=color_field[spin]+delta-color_field[old_spin]; deltaE=double(neighbours[old_spin]-neighbours[spin])+gamma*prob*double(h); if (deltaEnode_list); SPIN=i_iter.First(new_spins); P_SPIN=i_iter2.First(previous_spins); while (!net_iter.End()) { old_spin=node->Get_ClusterIndex(); new_spin=*SPIN; if (new_spin!=old_spin) // Do we really have a change?? { changes++; node->Set_ClusterIndex(new_spin); //this is important!! //In Parallel update, there occur cyclic attractors of size two //which then make the program run for ever if (new_spin!=*P_SPIN) cyclic=false; *P_SPIN=old_spin; color_field[old_spin]--; color_field[new_spin]++; //Qmatrix update //iteration over all neighbours l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } Qmatrix[old_spin][n_cur->Get_ClusterIndex()]-=w; Qmatrix[new_spin][n_cur->Get_ClusterIndex()]+=w; Qmatrix[n_cur->Get_ClusterIndex()][old_spin]-=w; Qmatrix[n_cur->Get_ClusterIndex()][new_spin]+=w; Qa[old_spin]-=w; Qa[new_spin]+=w; l_cur=l_iter.Next(); } // while l_iter } node=net_iter.Next(); SPIN=i_iter.Next(); P_SPIN=i_iter2.Next(); } // while (!net_iter.End()) } // while markov // In case of a cyclic attractor, we want to interrupt if (cyclic) { // printf("Cyclic attractor!\n"); acceptance=0.0; return 0; } else { acceptance=double(changes)/double(num_of_nodes); return changes; } } //################################################################################### //The same function as before, but rather than parallel update, it pics the nodes to update //randomly //################################################################################### double PottsModel::HeatBathLookupZeroTemp(double gamma, double prob, unsigned int max_sweeps) { DLList_Iter iter; DLList_Iter l_iter; DLList_Iter i_iter, i_iter2; NNode *node, *n_cur; NLink *l_cur; unsigned int new_spin, spin_opt, old_spin, spin, sweep; long r;// degree; unsigned long changes; double delta=0, h, deltaE, deltaEmin,w,degree; //HugeArray neighbours; sweep=0; changes=0; while (sweep(long)num_of_nodes-1)) r=RNG_INTEGER(0,num_of_nodes-1); /* r=long(double(num_of_nodes*double(rand())/double(RAND_MAX+1.0)));*/ node=net->node_list->Get(r); // Wir zaehlen, wieviele Nachbarn von jedem spin vorhanden sind // erst mal alles Null setzen for (unsigned int i=0; i<=q; i++) neighbours[i]=0; degree=node->Get_Weight(); //Loop over all links (=neighbours) l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { //printf("%s %s\n",node->Get_Name(),n_cur->Get_Name()); w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } neighbours[n_cur->Get_ClusterIndex()]+=w; l_cur=l_iter.Next(); } //Search optimal Spin old_spin=node->Get_ClusterIndex(); //degree=node->Get_Degree(); switch (operation_mode) { case 0: { delta=1.0; break; } case 1: { //newman modularity prob=degree/total_degree_sum; delta=degree; break; } } spin_opt=old_spin; deltaEmin=0.0; for (spin=1; spin<=q; spin++) // alle moeglichen Spins { if (spin!=old_spin) { h=color_field[spin]+delta-color_field[old_spin]; deltaE=double(neighbours[old_spin]-neighbours[spin])+gamma*prob*double(h); if (deltaESet_ClusterIndex(new_spin); color_field[old_spin]-=delta; color_field[new_spin]+=delta; //Qmatrix update //iteration over all neighbours l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } Qmatrix[old_spin][n_cur->Get_ClusterIndex()]-=w; Qmatrix[new_spin][n_cur->Get_ClusterIndex()]+=w; Qmatrix[n_cur->Get_ClusterIndex()][old_spin]-=w; Qmatrix[n_cur->Get_ClusterIndex()][new_spin]+=w; Qa[old_spin]-=w; Qa[new_spin]+=w; l_cur=l_iter.Next(); } // while l_iter } } // for n } // while markov acceptance=double(changes)/double(num_of_nodes)/double(sweep); return acceptance; } //##################################################################################### //This function performs a parallel update at Terperature T //##################################################################################### long PottsModel::HeatBathParallelLookup(double gamma, double prob, double kT, unsigned int max_sweeps) { DLList_Iter iter, net_iter; DLList_Iter l_iter; DLList_Iter i_iter, i_iter2; NNode *node, *n_cur; NLink *l_cur; unsigned int new_spin, spin_opt, old_spin; unsigned int *SPIN, *P_SPIN; unsigned int sweep; long max_q; unsigned long changes, /*degree,*/ problemcount; //HugeArray neighbours; double h, delta=0, norm, r, beta,minweight, prefac=0,w, degree; bool cyclic=0, found; unsigned long num_of_nodes; sweep=0; changes=1; num_of_nodes=net->node_list->Size(); while (sweepnode_list); SPIN=i_iter.First(new_spins); while (!net_iter.End()) { // Initialize neighbours and weights problemcount=0; for (unsigned int i=0; i<=q; i++) { neighbours[i]=0; weights[i]=0; } norm=0.0; degree=node->Get_Weight(); //Loop over all links (=neighbours) l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { //printf("%s %s\n",node->Get_Name(),n_cur->Get_Name()); w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } neighbours[n_cur->Get_ClusterIndex()]+=w; l_cur=l_iter.Next(); } //Search optimal Spin old_spin=node->Get_ClusterIndex(); //degree=node->Get_Degree(); switch (operation_mode) { case 0: { prefac=1.0; delta=1.0; break; } case 1: { //newman modularity prefac=1.0; prob=degree/total_degree_sum; delta=degree; break; } } spin_opt=old_spin; beta=1.0/kT*prefac; minweight=0.0; weights[old_spin]=0.0; for (unsigned spin=1; spin<=q; spin++) // loop over all possible new spins { if (spin!=old_spin) // only if we have a different than old spin! { h=color_field[spin]+delta-color_field[old_spin]; weights[spin]=double(neighbours[old_spin]-neighbours[spin])+gamma*prob*double(h); if (weights[spin]node_list); SPIN=i_iter.First(new_spins); P_SPIN=i_iter2.First(previous_spins); while (!net_iter.End()) { old_spin=node->Get_ClusterIndex(); new_spin=*SPIN; if (new_spin!=old_spin) // Did we really change something?? { changes++; node->Set_ClusterIndex(new_spin); if (new_spin!=*P_SPIN) cyclic=false; *P_SPIN=old_spin; color_field[old_spin]-=delta; color_field[new_spin]+=delta; //Qmatrix update //iteration over all neighbours l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } Qmatrix[old_spin][n_cur->Get_ClusterIndex()]-=w; Qmatrix[new_spin][n_cur->Get_ClusterIndex()]+=w; Qmatrix[n_cur->Get_ClusterIndex()][old_spin]-=w; Qmatrix[n_cur->Get_ClusterIndex()][new_spin]+=w; Qa[old_spin]-=w; Qa[new_spin]+=w; l_cur=l_iter.Next(); } // while l_iter } node=net_iter.Next(); SPIN=i_iter.Next(); P_SPIN=i_iter2.Next(); } // while (!net_iter.End()) } // while markov max_q=0; for (unsigned int i=1; i<=q; i++) if (color_field[i]>max_q) max_q=long(color_field[i]); //again, we would not like to end up in cyclic attractors if (cyclic && changes) { // printf("Cyclic attractor!\n"); acceptance=double(changes)/double(num_of_nodes); return 0; } else { acceptance=double(changes)/double(num_of_nodes); return changes; } } //############################################################## // This is the function generally used for optimisation, // as the parallel update has its flaws, due to the cyclic attractors //############################################################## double PottsModel::HeatBathLookup(double gamma, double prob, double kT, unsigned int max_sweeps) { DLList_Iter iter; DLList_Iter l_iter; DLList_Iter i_iter, i_iter2; NNode *node, *n_cur; NLink *l_cur; unsigned int new_spin, spin_opt, old_spin; unsigned int sweep; long max_q, rn; unsigned long changes, /*degree,*/ problemcount; double degree,w, delta=0, h; //HugeArray neighbours; double norm, r, beta,minweight, prefac=0; bool found; long int num_of_nodes; sweep=0; changes=0; num_of_nodes=net->node_list->Size(); while (sweepnum_of_nodes-1)) rn=RNG_INTEGER(0, num_of_nodes-1); /* rn=long(double(num_of_nodes*double(rand())/double(RAND_MAX+1.0))); */ node=net->node_list->Get(rn); // initialize the neighbours and the weights problemcount=0; for (unsigned int i=0; i<=q; i++) { neighbours[i]=0.0; weights[i]=0.0; } norm=0.0; degree=node->Get_Weight(); //Loop over all links (=neighbours) l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { //printf("%s %s\n",node->Get_Name(),n_cur->Get_Name()); w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } neighbours[n_cur->Get_ClusterIndex()]+=w; l_cur=l_iter.Next(); } //Look for optimal spin old_spin=node->Get_ClusterIndex(); //degree=node->Get_Degree(); switch (operation_mode) { case 0: { prefac=1.0; delta=1.0; break; } case 1: {//newman modularity prefac=1.0; prob=degree/total_degree_sum; delta=degree; break; } } spin_opt=old_spin; beta=1.0/kT*prefac; minweight=0.0; weights[old_spin]=0.0; for (unsigned spin=1; spin<=q; spin++) // all possible new spins { if (spin!=old_spin) // except the old one! { h=color_field[spin]-(color_field[old_spin]-delta); weights[spin]=neighbours[old_spin]-neighbours[spin]+gamma*prob*h; if (weights[spin]Set_ClusterIndex(new_spin); color_field[old_spin]-=delta; color_field[new_spin]+=delta; //Qmatrix update //iteration over all neighbours l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } Qmatrix[old_spin][n_cur->Get_ClusterIndex()]-=w; Qmatrix[new_spin][n_cur->Get_ClusterIndex()]+=w; Qmatrix[n_cur->Get_ClusterIndex()][old_spin]-=w; Qmatrix[n_cur->Get_ClusterIndex()][new_spin]+=w; Qa[old_spin]-=w; Qa[new_spin]+=w; l_cur=l_iter.Next(); } // while l_iter } } // for n } // while markov max_q=0; for (unsigned int i=1; i<=q; i++) if (color_field[i]>max_q) max_q=long(color_field[i]+0.5); acceptance=double(changes)/double(num_of_nodes)/double(sweep); return acceptance; } //############################################################################################### //# Here we try to minimize the affinity to the rest of the network //############################################################################################### double PottsModel::FindCommunityFromStart(double gamma, double prob, char *nodename, igraph_vector_t *result, igraph_real_t *cohesion, igraph_real_t *adhesion, igraph_integer_t *my_inner_links, igraph_integer_t *my_outer_links) { DLList_Iter iter, iter2; DLList_Iter l_iter; DLList* to_do; DLList* community; NNode *start_node=0, *n_cur, *neighbor, *max_aff_node, *node; NLink *l_cur; bool found=false, add=false, remove=false; double degree, delta_aff_add, delta_aff_rem, max_delta_aff, Ks=0.0, Kr=0, kis, kir, w; long community_marker=5; long to_do_marker=10; double inner_links=0, outer_links=0, aff_r, aff_s; IGRAPH_UNUSED(prob); to_do=new DLList; community=new DLList; // find the node in the network n_cur=iter.First(net->node_list); while (!found && !iter.End()) { if (0==strcmp(n_cur->Get_Name(),nodename)) { start_node=n_cur; found=true; start_node->Set_Affinity(0.0); community->Push(start_node); start_node->Set_Marker(community_marker); Ks=start_node->Get_Weight(); Kr=total_degree_sum-start_node->Get_Weight(); } n_cur=iter.Next(); } if (!found) { // printf("%s not found found. Aborting.\n",nodename); // fprintf(file,"%s not found found. Aborting.\n",nodename); delete to_do; delete community; return -1; } //############################# // initialize the to_do list and community with the neighbours of start node //############################# neighbor=iter.First(start_node->Get_Neighbours()); while (!iter.End()) { // printf("Adding node %s to comunity.\n",neighbor->Get_Name()); community->Push(neighbor); neighbor->Set_Marker(community_marker); Ks+=neighbor->Get_Weight(); Kr-=neighbor->Get_Weight(); neighbor=iter.Next(); } node=iter.First(community); while (!iter.End()) { //now add at the second neighbors to the to_do list neighbor=iter2.First(node->Get_Neighbours()); while (!iter2.End()) { if ((long)neighbor->Get_Marker()!=community_marker && (long)neighbor->Get_Marker()!=to_do_marker) { to_do->Push(neighbor); neighbor->Set_Marker(to_do_marker); // printf("Adding node %s to to_do list.\n",neighbor->Get_Name()); } neighbor=iter2.Next(); } node=iter.Next(); } //############# //repeat, as long as we are still adding nodes to the communtiy //############# add=true; remove=true; while (add || remove) { //############################# //calculate the affinity changes of all nodes for adding every node in the to_do list to the community //############################## IGRAPH_ALLOW_INTERRUPTION(); /* This is not clean.... */ max_delta_aff=0.0; max_aff_node=NULL; add=false; node=iter.First(to_do); while (!iter.End()) { //printf("Checking Links of %s\n",node->Get_Name()); degree=node->Get_Weight(); kis=0.0; kir=0.0; // For every of the neighbors, check, count the links to the community l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } if ((long)n_cur->Get_Marker()==community_marker) { kis+=w; //the weight/number of links to the community } else { kir+=w; //the weight/number of links to the rest of the network } l_cur=l_iter.Next(); } aff_r=kir-gamma/total_degree_sum*(Kr-degree)*degree; aff_s=kis-gamma/total_degree_sum*Ks*degree; delta_aff_add=aff_r-aff_s; // if (aff_s>=aff_r && delta_aff_add<=max_delta_aff) { if (delta_aff_add<=max_delta_aff) { node->Set_Affinity(aff_s); max_delta_aff=delta_aff_add; max_aff_node=node; add=true; } //printf("%s in to_do list with affinity %f\n",node->Get_Name(),node->Get_Affinity()); node=iter.Next(); } //################ //calculate the affinity changes for removing every single node from the community //################ inner_links=0; outer_links=0; remove=false; node=iter.First(community); while (!iter.End()) { //printf("Checking Links of %s\n",node->Get_Name()); degree=node->Get_Weight(); kis=0.0; kir=0.0; // For every of the neighbors, check, count the links to the community l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } if ((long)n_cur->Get_Marker()==community_marker) { kis+=w; inner_links+=w; //summing all w gives twice the number of inner links(weights) } else { kir+=w; outer_links+=w; } l_cur=l_iter.Next(); } // if (kir+kis!=degree) { printf("error kir=%f\tkis=%f\tk=%f\n",kir,kis,degree); } aff_r=kir-gamma/total_degree_sum*Kr*degree; aff_s=kis-gamma/total_degree_sum*(Ks-degree)*degree; delta_aff_rem=aff_s-aff_r; node->Set_Affinity(aff_s); // we should not remove the nodes, we have just added if (delta_aff_remGet_Name(),node->Get_Affinity()); node=iter.Next(); } inner_links=inner_links*0.5; //################ // Now check, whether we want to remove or add a node //################ if (add) { //################ //add the node of maximum affinity to the community //############### community->Push(max_aff_node); max_aff_node->Set_Marker(community_marker); //delete node from to_do to_do->fDelete(max_aff_node); //update the sum of degrees in the community Ks+=max_aff_node->Get_Weight(); Kr-=max_aff_node->Get_Weight(); // printf("Adding node %s to community with affinity of %f delta_aff: %f.\n",max_aff_node->Get_Name(), max_aff_node->Get_Affinity(),max_delta_aff); //now add all neighbors of this node, that are not already //in the to_do list or in the community neighbor=iter.First(max_aff_node->Get_Neighbours()); while (!iter.End()) { if ((long)neighbor->Get_Marker()!=community_marker && (long)neighbor->Get_Marker()!=to_do_marker) { to_do->Push(neighbor); neighbor->Set_Marker(to_do_marker); //printf("Adding node %s to to_do list.\n",neighbor->Get_Name()); } neighbor=iter.Next(); } } if (remove) { //################ //remove those with negative affinities //################ community->fDelete(max_aff_node); max_aff_node->Set_Marker(to_do_marker); //update the sum of degrees in the community Ks-=max_aff_node->Get_Weight(); Kr+=max_aff_node->Get_Weight(); //add the node to to_do again to_do->Push(max_aff_node); // printf("Removing node %s from community with affinity of %f delta_aff: %f.\n",max_aff_node->Get_Name(), max_aff_node->Get_Affinity(),max_delta_aff); } IGRAPH_ALLOW_INTERRUPTION(); /* This is not clean.... */ } //################### //write the node in the community to a file //################### // TODO return this instead of writing it // fprintf(file,"Number_of_nodes:\t%d\n",community->Size()); // fprintf(file,"Inner_Links:\t%f\n",inner_links); // fprintf(file,"Outer_Links:\t%f\n",Ks-2*inner_links); // fprintf(file,"Cohesion:\t%f\n",inner_links-gamma/total_degree_sum*Ks*Ks*0.5); // fprintf(file,"Adhesion:\t%f\n",outer_links-gamma/total_degree_sum*Ks*Kr); // fprintf(file,"\n"); if (cohesion) { *cohesion=inner_links-gamma/total_degree_sum*Ks*Ks*0.5; } if (adhesion) { *adhesion=outer_links-gamma/total_degree_sum*Ks*Kr; } if (my_inner_links) { *my_inner_links=inner_links; } if (my_outer_links) { *my_outer_links=outer_links; } if (result) { node=iter.First(community); igraph_vector_resize(result, 0); while (!iter.End()) { // printf("%s in community.\n",node->Get_Name()); // fprintf(file,"%s\t%f\n",node->Get_Name(),node->Get_Affinity()); IGRAPH_CHECK(igraph_vector_push_back(result, node->Get_Index())); node=iter.Next(); } } // printf("%d nodes in community around %s\n",community->Size(),start_node->Get_Name()); // fclose(file); unsigned int size=community->Size(); delete to_do; delete community; return size; } //################################################################################################ // this Function writes the clusters to disk //################################################################################################ long PottsModel::WriteClusters(igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *csize, igraph_vector_t *membership, double kT, double gamma) { NNode *n_cur, *n_cur2; /* double a1,a2,a3,p,p1,p2; long n,N,lin,lout; */ DLList_Iter iter, iter2; HugeArray inner_links; HugeArray outer_links; HugeArray nodes; //den Header schreiben // p=2.0*double(num_of_links)/double(num_of_nodes)/double(num_of_nodes-1); // fprintf(file," Nodes=\t%lu\n",num_of_nodes); // fprintf(file," Links=\t%lu\n",num_of_links); // fprintf(file," q=\t%d\n",q); // fprintf(file," p=\t%f\n",p); // fprintf(file," Modularity=\t%f\n",calculate_Q()); // fprintf(file,"Temperature=\t%f\n", kT); // fprintf(file,"Cluster\tNodes\tInnerLinks\tOuterLinks\tp_in\tp_out\t\n"); if (temperature) { *temperature=kT; } if (csize || membership || modularity) { // TODO: count the number of clusters for (unsigned int spin=1; spin<=q; spin++) { inner_links[spin]=0; outer_links[spin]=0; nodes[spin]=0; n_cur=iter.First(net->node_list); while (!iter.End()) { if (n_cur->Get_ClusterIndex()==spin) { nodes[spin]++; n_cur2=iter2.First(n_cur->Get_Neighbours()); while (!iter2.End()) { if (n_cur2->Get_ClusterIndex()==spin) inner_links[spin]++; else outer_links[spin]++; n_cur2=iter2.Next(); } } n_cur=iter.Next(); } } } if (modularity) { *modularity=0.0; for (unsigned int spin=1; spin<=q; spin++) { if (nodes[spin]>0) { double t1= inner_links[spin] / net->sum_weights / 2.0; double t2= (inner_links[spin] + outer_links[spin]) / net->sum_weights / 2.0; *modularity += t1; *modularity -= gamma * t2 * t2; } } } if (csize) { igraph_vector_resize(csize, 0); for (unsigned int spin=1; spin<=q; spin++) { if (nodes[spin]>0) { inner_links[spin]/=2; // fprintf(file,"Cluster\tNodes\tInnerLinks\tOuterLinks\tp_in\tp_out\n"); /* N=num_of_nodes; n=nodes[spin]; lin=inner_links[spin]; lout=outer_links[spin]; a1=N*log((double)N)-n*log((double)n)*(N-n)*log((double)N-n); if ((lin==long(n*(n-1)*0.5+0.5)) || (n==1)) a2=0.0; else a2=(n*(n-1)*0.5 )*log((double)n*(n-1)*0.5 )-(n*(n-1)*0.5 )- (n*(n-1)*0.5-lin)*log((double)n*(n-1)*0.5-lin)+(n*(n-1)*0.5-lin)- lin*log((double)lin )+lin; */ /* if ((lout==n*(N-n)) || n==N) a3=0.0; else a3=(n*(N-n) )*log((double)n*(N-n) )-(n*(N-n))- (n*(N-n)-lout)*log((double)n*(N-n)-lout)+(n*(N-n)-lout)- lout*log((double)lout )+lout; */ /* p1=(lin+lout)*log((double)p); p2=(0.5*n*(n-1)-lin + n*(N-n)-lout)*log((double)1.0-p); */ // fprintf(file,"%d\t%d\t%d\t%d\t%f\t%f\t%f\n",spin,nodes[spin], inner_links[spin], outer_links[spin], p_in, p_out,log_num_exp); IGRAPH_CHECK(igraph_vector_push_back(csize, nodes[spin])); } } // fprintf(file,"\n"); } //die Elemente der Cluster if (membership) { long int no=-1; IGRAPH_CHECK(igraph_vector_resize(membership, num_of_nodes)); for (unsigned int spin=1; spin<=q; spin++) { if (nodes[spin]>0) { no++; } n_cur=iter.First(net->node_list); while (!iter.End()) { if (n_cur->Get_ClusterIndex()==spin) { // fprintf(file,"%d\t%s\n",spin,n_cur->Get_Name()); VECTOR(*membership)[ n_cur->Get_Index() ]=no; } n_cur=iter.Next(); } } } return num_of_nodes; } //################################################################################################ //This function writes the soft clusters after a gamma sweep //that is, it groups every node together that was found in // more than threshold percent together with the other node // in the same cluster //################################################################################################ // Does not work at the moment !!! //################################################################################################ // long PottsModel::WriteSoftClusters(char *filename, double threshold) // { // FILE *file; // NNode *n_cur, *n_cur2; // DLList_Iter iter, iter2; // DL_Indexed_List*> *cl_list, *old_clusterlist; // ClusterList *cl_cur; // double max; // file=fopen(filename,"w"); // if (!file) { // printf("Could not open %s for writing.\n",filename); // return -1; // } // max=correlation[0]->Get(0); // //printf("max=%f\n",max); // cl_list=new DL_Indexed_List*>(); // n_cur=iter.First(net->node_list); // while (!iter.End()) // { // cl_cur=new ClusterList(); // cl_list->Push(cl_cur); // n_cur2=iter2.First(net->node_list); // while (!iter2.End()) // { // if (double(correlation[n_cur->Get_Index()]->Get(n_cur2->Get_Index()))/max>threshold) // cl_cur->Push(n_cur2); // n_cur2=iter2.Next(); // } // n_cur=iter.Next(); // } // old_clusterlist=net->cluster_list; // net->cluster_list=cl_list; // clear_all_markers(net); // //printf("Es gibt %d Cluster\n",cl_list->Size()); // reduce_cliques2(net, false, 15); // //printf("Davon bleiben %d Cluster uebrig\n",cl_list->Size()); // clear_all_markers(net); // while (net->cluster_list->Size()){ // cl_cur=net->cluster_list->Pop(); // while (cl_cur->Size()) // { // n_cur=cl_cur->Pop(); // fprintf(file,"%s\n",n_cur->Get_Name()); // //printf("%s\n",n_cur->Get_Name()); // } // fprintf(file,"\n"); // } // net->cluster_list=old_clusterlist; // fclose(file); // return 1; // } //############################################################################# // Performs a gamma sweep //############################################################################# double PottsModel::GammaSweep(double gamma_start, double gamma_stop, double prob, unsigned int steps, bool non_parallel, int repetitions) { double stepsize; double kT, kT_start; long changes; double gamma, acc; NNode *n_cur, *n_cur2; DLList_Iter iter, iter2; stepsize=(gamma_stop-gamma_start)/double(steps); n_cur=iter.First(net->node_list); while (!iter.End()) { correlation[n_cur->Get_Index()]=new HugeArray(); n_cur2=iter2.First(net->node_list); while (!iter2.End()) { correlation[n_cur->Get_Index()]->Set(n_cur->Get_Index())=0.0; n_cur2=iter2.Next(); } n_cur=iter.Next(); } for (unsigned int n=0; n<=steps; n++) { assign_initial_conf(-1); initialize_Qmatrix(); gamma=gamma_start+stepsize*n; kT=0.5; acceptance=0.5; while (acceptance<(1.0-1.0/double(q))*0.95) //wollen 95% Acceptance { kT*=1.1; //initialize_lookup(kT,kmax,net->node_list->Size()); if (!non_parallel) HeatBathParallelLookup(gamma,prob, kT,25); else HeatBathLookup(gamma,prob, kT,25); // printf("kT=%f acceptance=%f\n", kT, acceptance); } // printf("Starting with gamma=%f\n", gamma); kT_start=kT; for (int i=0; i0) && (kT>0.01)) { kT=kT*0.99; //initialize_lookup(kT,kmax,net->node_list->Size()); if (!non_parallel) { changes=HeatBathParallelLookup(gamma, prob, kT, 50); // printf("kT: %f \t Changes %li\n",kT, changes); } else { acc=HeatBathLookup(gamma, prob, kT, 50); if (acc>(1.0-1.0/double(q))*0.01) changes=1; else changes=0; // printf("kT: %f Acceptance: %f\n",kT, acc); } } // printf("Finisched with acceptance: %1.6f bei kT=%2.4f und gamma=%2.4f\n",acceptance,kT, gamma); // fprintf(file,"%f\t%f\n",gamma_,acceptance); // fprintf(file2,"%f\t%f\n",gamma_,kT); // fprintf(file3,"%f\t%d\n",gamma_,count_clusters(5)); //Die Correlation berechnen n_cur=iter.First(net->node_list); while (!iter.End()) { n_cur2=iter2.First(net->node_list); while (!iter2.End()) { if (n_cur->Get_ClusterIndex()==n_cur2->Get_ClusterIndex()) { correlation[n_cur->Get_Index()]->Set(n_cur2->Get_Index())+=0.5; } n_cur2=iter2.Next(); } n_cur=iter.Next(); } } // for i } //for n return kT; } //############################################################################# //Performs a Gamma sweep at zero T //############################################################################# double PottsModel::GammaSweepZeroTemp(double gamma_start, double gamma_stop, double prob, unsigned int steps, bool non_parallel, int repetitions) { double stepsize; long changes; double gamma, acc; long runs; NNode *n_cur, *n_cur2; DLList_Iter iter, iter2; stepsize=(gamma_stop-gamma_start)/double(steps); n_cur=iter.First(net->node_list); while (!iter.End()) { correlation[n_cur->Get_Index()]=new HugeArray(); n_cur2=iter2.First(net->node_list); while (!iter2.End()) { correlation[n_cur->Get_Index()]->Set(n_cur->Get_Index())=0.0; n_cur2=iter2.Next(); } n_cur=iter.Next(); } for (unsigned int n=0; n<=steps; n++) { assign_initial_conf(-1); initialize_Qmatrix(); gamma=gamma_start+stepsize*n; // printf("Starting with gamma=%f\n", gamma); for (int i=0; i0 && runs<250) { //initialize_lookup(kT,kmax,net->node_list->Size()); if (!non_parallel) { changes=HeatBathParallelLookupZeroTemp(gamma, prob, 1); // printf("Changes %li\n", changes); } else { acc=HeatBathLookupZeroTemp(gamma, prob, 1); if (acc>(1.0-1.0/double(q))*0.01) changes=1; else changes=0; // printf("Acceptance: %f\n", acc); } runs++; } // printf("Finisched with Modularity: %1.6f bei Gamma=%1.6f\n",calculate_Q(), gamma); // fprintf(file,"%f\t%f\n",gamma_,acceptance); // fprintf(file2,"%f\t%f\n",gamma_,kT); // fprintf(file3,"%f\t%d\n",gamma_,count_clusters(5)); //Die Correlation berechnen n_cur=iter.First(net->node_list); while (!iter.End()) { n_cur2=iter2.First(net->node_list); while (!iter2.End()) { if (n_cur->Get_ClusterIndex()==n_cur2->Get_ClusterIndex()) { correlation[n_cur->Get_Index()]->Set(n_cur2->Get_Index())+=0.5; correlation[n_cur2->Get_Index()]->Set(n_cur->Get_Index())+=0.5; } n_cur2=iter2.Next(); } n_cur=iter.Next(); } } // for i } //for n return gamma; } //####################################################################### //----------------------------------------------------------------------- //####################################################################### // This function writes the Correlation Matrix that results from a // Gamma-Sweep, this matrix is used to make ps files of it. // ###################################################################### // long PottsModel::WriteCorrelationMatrix(char *filename) // { // FILE *file, *file2; // char filename2[255]; // NNode *n_cur, *n_cur2; // DLList_Iter iter, iter2; // sprintf(filename2,"%s.mat",filename); // file=fopen(filename,"w"); // if (!file) { // printf("Could not open %s for writing.\n",filename); // return -1; // } // file2=fopen(filename2,"w"); // if (!file2) { // printf("Could not open %s for writing.\n",filename2); // return -1; // } // //write the header in one line // n_cur=iter.First(net->node_list); // while (!iter.End()) // { // fprintf(file, "\t%s",n_cur->Get_Name()); // n_cur=iter.Next(); // } // fprintf(file, "\n"); // //fprintf(file, "%d\t%d\n",net->node_list->Size(),net->node_list->Size()); // long r=0,c=0; // n_cur=iter.First(net->node_list); // while (!iter.End()) // { // fprintf(file, "%s",n_cur->Get_Name()); // r++; // n_cur2=iter2.First(net->node_list); // while (!iter2.End()) // { // c++; // fprintf(file,"\t%f",correlation[n_cur->Get_Index()]->Get(n_cur2->Get_Index())); // fprintf(file2,"%li\t%li\t%f\n",r,c,correlation[n_cur->Get_Index()]->Get(n_cur2->Get_Index())); // n_cur2=iter2.Next(); // } // fprintf(file,"\n"); // n_cur=iter.Next(); // } // fclose(file); // fclose(file2); // return 1; // } //############################################################################## //################################################################################################# PottsModelN::PottsModelN(network *n, unsigned int num_communities, bool directed) { //Set internal variable net = n; q = num_communities; is_directed = directed; is_init = false; num_nodes = net->node_list->Size(); } //####################################################### //Destructor of PottsModel //######################################################## PottsModelN::~PottsModelN() { delete degree_pos_in; delete degree_neg_in; delete degree_pos_out; delete degree_neg_out; delete degree_community_pos_in; delete degree_community_neg_in; delete degree_community_pos_out; delete degree_community_neg_out; delete weights; delete neighbours; delete csize; delete spin; return; } void PottsModelN::assign_initial_conf(bool init_spins) { #ifdef DEBUG printf("Start assigning.\n"); #endif int s; DLList_Iter iter; DLList_Iter l_iter; NNode *n_cur; NLink *l_cur; if(init_spins) { #ifdef DEBUG printf("Initializing spin.\n"); #endif //Bookkeeping of the various degrees (positive/negative) and (in/out) degree_pos_in = new double[num_nodes]; //Postive indegree of the nodes (or sum of weights) degree_neg_in = new double[num_nodes]; //Negative indegree of the nodes (or sum of weights) degree_pos_out = new double[num_nodes]; //Postive outdegree of the nodes (or sum of weights) degree_neg_out = new double[num_nodes]; //Negative outdegree of the nodes (or sum of weights) spin = new unsigned int[num_nodes]; //The spin state of each node } if (is_init) { delete degree_community_pos_in; delete degree_community_neg_in; delete degree_community_pos_out; delete degree_community_neg_out; delete weights; delete neighbours; delete csize; } is_init = true; //Bookkeep of occupation numbers of spin states or the number of links in community... degree_community_pos_in = new double[q+1]; //Positive sum of indegree for communities degree_community_neg_in = new double[q+1]; //Negative sum of indegree for communities degree_community_pos_out = new double[q+1];//Positive sum of outegree for communities degree_community_neg_out = new double[q+1]; //Negative sum of outdegree for communities //...and of weights and neighbours for in the HeathBathLookup weights = new double[q+1]; //The weights for changing to another spin state neighbours = new double[q+1]; //The number of neighbours (or weights) in different spin states csize = new unsigned int[q+1]; //The number of nodes in each community //Initialize communities for (unsigned int i=0; i<=q; i++) { degree_community_pos_in[i] = 0.0; degree_community_neg_in[i] = 0.0; degree_community_pos_out[i] = 0.0; degree_community_neg_out[i] = 0.0; csize[i] = 0; } //Initialize vectors if (init_spins) { for (unsigned int i = 0; i < num_nodes; i++) { degree_pos_in[i] = 0.0; degree_neg_in[i] = 0.0; degree_pos_out[i] = 0.0; degree_neg_out[i] = 0.0; #ifdef DEBUG printf("Initializing spin %d", i); #endif spin[i] = 0; } } m_p=0.0; m_n=0.0; //Set community for each node, and //correctly store it in the bookkeeping double sum_weight_pos_in, sum_weight_pos_out, sum_weight_neg_in, sum_weight_neg_out; //double av_w = 0.0, av_k=0.0; //int l = 0; #ifdef DEBUG printf("Visiting each node.\n"); #endif for (unsigned int v = 0; v < num_nodes; v++) { if (init_spins) { s = RNG_INTEGER(1, q); //The new spin s spin[v] = (unsigned int)s; } else s = spin[v]; #ifdef DEBUG printf("Spin %d assigned to node %d.\n", s, v); #endif n_cur = net->node_list->Get(v); l_cur = l_iter.First(n_cur->Get_Links()); sum_weight_pos_in = 0.0; sum_weight_pos_out = 0.0; sum_weight_neg_in = 0.0; sum_weight_neg_out = 0.0; while (!l_iter.End()) { double w = l_cur->Get_Weight(); //av_w = (av_w*l + w)/(l+1); //Average weight //l++; if (l_cur->Get_Start() == n_cur) //From this to other, so outgoing link if (w > 0) sum_weight_pos_out += w; //Increase positive outgoing weight else sum_weight_neg_out -= w; //Increase negative outgoing weight else if (w > 0) sum_weight_pos_in += w; //Increase positive incoming weight else sum_weight_neg_in -= w; //Increase negative incoming weight l_cur=l_iter.Next(); } if (!is_directed) { double sum_weight_pos = sum_weight_pos_out + sum_weight_pos_in; sum_weight_pos_out = sum_weight_pos; sum_weight_pos_in = sum_weight_pos; double sum_weight_neg = sum_weight_neg_out + sum_weight_neg_in; sum_weight_neg_out = sum_weight_neg; sum_weight_neg_in = sum_weight_neg; } //av_k = (av_k*l + sum_weight_pos_in)/(l+1); //Average k if (init_spins) { //Set the degrees correctly degree_pos_in[v] = sum_weight_pos_in; degree_neg_in[v] = sum_weight_neg_in; degree_pos_out[v] = sum_weight_pos_out; degree_neg_out[v] = sum_weight_neg_out; } //Correct the community bookkeeping degree_community_pos_in[s] += sum_weight_pos_in; degree_community_neg_in[s] += sum_weight_neg_in; degree_community_pos_out[s] += sum_weight_pos_out; degree_community_neg_out[s] += sum_weight_neg_out; //Community just increased csize[s]++; //Sum the weights (notice that sum of indegrees equals sum of outdegrees) m_p += sum_weight_pos_in; m_n += sum_weight_neg_in; } #ifdef DEBUG printf("Done assigning.\n"); #endif return; } //############################################################## // This is the function generally used for optimisation, // as the parallel update has its flaws, due to the cyclic attractors //############################################################## double PottsModelN::HeatBathLookup(double gamma, double lambda, double t, unsigned int max_sweeps) { #ifdef DEBUG printf("Starting sweep at temperature %f.\n", t); #endif DLList_Iter iter; DLList_Iter l_iter; DLList_Iter i_iter, i_iter2; NNode *node, *n_cur; NLink *l_cur; /* The new_spin contains the spin to which we will update, * the spin_opt is the optional spin we will consider and * the old_spin is the spin of the node we are currently * changing. */ unsigned int new_spin, spin_opt, old_spin; unsigned int sweep; //current sweep unsigned long changes, problemcount; //Number of changes and number of problems encountered double exp_old_spin; //The expectation value for the old spin double exp_spin; //The expectation value for the other spin(s) int v; //The node we will be investigating //The variables required for the calculations double delta_pos_out, delta_pos_in, delta_neg_out, delta_neg_in; double k_v_pos_out, k_v_pos_in, k_v_neg_out, k_v_neg_in; //weight of edge double w; double beta = 1/t; //Weight for probabilities double r = 0.0; //random number used for assigning new spin double maxweight = 0.0; double sum_weights = 0.0; //sum_weights for normalizing the probabilities sweep=0; changes=0; double m_pt = m_p; double m_nt = m_n; if (m_pt < 0.001) m_pt = 1; if (m_nt < 0.001) m_nt = 1; while (sweepnode_list->Get(v); /*******************************************/ // initialize the neighbours and the weights problemcount=0; for (unsigned int i=0; i<=q; i++) { neighbours[i]=0.0; weights[i]=0.0; } //Loop over all links (=neighbours) l_cur=l_iter.First(node->Get_Links()); while (!l_iter.End()) { w=l_cur->Get_Weight(); if (node==l_cur->Get_Start()) { n_cur=l_cur->Get_End(); } else { n_cur=l_cur->Get_Start(); } //Add the link to the correct cluster neighbours[spin[n_cur->Get_Index()]]+=w; l_cur=l_iter.Next(); } //We now have the weight of the (in and out) neighbours //in each cluster available to us. /*******************************************/ old_spin=spin[v]; //Look for optimal spin //Set the appropriate variable delta_pos_out = degree_pos_out[v]; delta_pos_in = degree_pos_in[v]; delta_neg_out = degree_neg_out[v]; delta_neg_in = degree_neg_in[v]; k_v_pos_out = gamma*delta_pos_out/m_pt; k_v_pos_in = gamma*delta_pos_in/m_pt; k_v_neg_out = lambda*delta_neg_out/m_nt; k_v_neg_in = lambda*delta_neg_in/m_nt; //The expectation value for the old spin if (is_directed) exp_old_spin = (k_v_pos_out * (degree_community_pos_in[old_spin] - delta_pos_in) - k_v_neg_out * (degree_community_neg_in[old_spin] - delta_neg_in)) + (k_v_pos_in * (degree_community_pos_out[old_spin] - delta_pos_out) - k_v_neg_in * (degree_community_neg_out[old_spin] - delta_neg_out)); else exp_old_spin = (k_v_pos_out * (degree_community_pos_in[old_spin] - delta_pos_in) - k_v_neg_out * (degree_community_neg_in[old_spin] - delta_neg_in)); /*******************************************/ //Calculating probabilities for each transition to another //community. maxweight=0.0; weights[old_spin]=0.0; for (spin_opt=1; spin_opt<=q; spin_opt++) // all possible new spins { if (spin_opt!=old_spin) // except the old one! { if (is_directed) exp_spin = (k_v_pos_out * degree_community_pos_in[spin_opt] - k_v_neg_out * degree_community_neg_in[spin_opt]) + (k_v_pos_in * degree_community_pos_out[spin_opt] - k_v_neg_in * degree_community_neg_out[spin_opt]); else exp_spin = (k_v_pos_out * degree_community_pos_in[spin_opt] - k_v_neg_out * degree_community_neg_in[spin_opt]); weights[spin_opt] = (neighbours[spin_opt] - exp_spin) - (neighbours[old_spin] - exp_old_spin); if (weights[spin_opt] > maxweight) maxweight = weights[spin_opt]; } } // for spin //Calculate exp. prob. an sum_weights = 0.0; for (spin_opt=1; spin_opt<=q; spin_opt++) // all possible new spins { weights[spin_opt] -= maxweight; //subtract maxweight for numerical stability (otherwise overflow). weights[spin_opt] = exp((double)(beta*weights[spin_opt])); sum_weights += weights[spin_opt]; } // for spin /*******************************************/ /*******************************************/ //Choose a new spin dependent on the calculated probabilities r = RNG_UNIF(0, sum_weights); new_spin = 1; bool found = false; while (!found && new_spin <= q) { if (r <= weights[new_spin]) { spin_opt = new_spin; //We have found are new spin found = true; break; } else r -= weights[new_spin]; //Perhaps the next spin is the one we want new_spin++; } //Some weird thing happened. We haven't found a new spin //while that shouldn't be the case. Numerical problems? if (!found) problemcount++; new_spin=spin_opt; //If there wasn't a problem we should have found //our new spin. /*******************************************/ /*******************************************/ //The new spin is available to us, so change //all the appropriate counters. if (new_spin!=old_spin) // Did we really change something?? { changes++; spin[v] = new_spin; //The new spin increase by one, and the old spin decreases by one csize[new_spin]++; csize[old_spin]--; //Change the sums of degree for the old spin... degree_community_pos_in[old_spin] -= delta_pos_in; degree_community_neg_in[old_spin] -= delta_neg_in; degree_community_pos_out[old_spin] -= delta_pos_out; degree_community_neg_out[old_spin] -= delta_neg_out; //...and for the new spin degree_community_pos_in[new_spin] += delta_pos_in; degree_community_neg_in[new_spin] += delta_neg_in; degree_community_pos_out[new_spin] += delta_pos_out; degree_community_neg_out[new_spin] += delta_neg_out; } //We have no change a node from old_spin to new_spin /*******************************************/ } // for n } // while sweep #ifdef DEBUG printf("Done %d sweeps.\n", max_sweeps); printf("%d changes made for %d nodes.\n", changes, num_nodes); printf("Last node is %d and last random number is %f with sum of weights %f with spin %d.\n", v, r, sum_weights, old_spin); #endif return (double(changes)/double(num_nodes)/double(sweep)); } //We need to begin at a suitable temperature. That is, a temperature at which //enough nodes may change their initially assigned communties double PottsModelN::FindStartTemp(double gamma, double lambda, double ts) { double kT; kT=ts; //assing random initial condition assign_initial_conf(true); // the factor 1-1/q is important, since even, at infinite temperature, // only 1-1/q of all spins do change their state, since a randomly chooses new // state is with prob. 1/q the old state. double acceptance = 0.0; while (acceptance<(1.0-1.0/double(q))*0.95) //want 95% acceptance { kT=kT*1.1; acceptance=HeatBathLookup(gamma,lambda, kT,50); } kT*=1.1; // just to be sure... return kT; } long PottsModelN::WriteClusters(igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *community_size, igraph_vector_t *membership, igraph_matrix_t *adhesion, igraph_matrix_t *normalised_adhesion, igraph_real_t *polarization, double t, double d_p, double d_n, double gamma, double lambda) { IGRAPH_UNUSED(gamma); IGRAPH_UNUSED(lambda); #ifdef DEBUG printf("Start writing clusters.\n"); #endif //Reassign each community so that we retrieve a community assignment 1 through num_communities unsigned int *cluster_assign = new unsigned int[q+1]; for (unsigned int i = 0; i <= q; i++) { cluster_assign[i] = 0; } int num_clusters = 0; //Find out what the new communities will be for (unsigned int i = 0; i < num_nodes; i++) { int s = spin[i]; if (cluster_assign[s] == 0) { num_clusters++; cluster_assign[s] = num_clusters; #ifdef DEBUG printf("Setting cluster %d to %d.\n", s, num_clusters); #endif } } /* DLList_Iter iter; NNode *n_cur=iter.First(net->node_list); n_cur = iter.First(net->node_list); */ //And now assign each node to its new community q = num_clusters; for (unsigned int i = 0; i < num_nodes; i++) { #ifdef DEBUG printf("Setting node %d to %d.\n", i, cluster_assign[spin[i]]); #endif unsigned int s = cluster_assign[spin[i]]; spin[i] = s; #ifdef DEBUG printf("Have set node %d to %d.\n", i, s); #endif } assign_initial_conf(false); delete[] cluster_assign; if (temperature) { *temperature=t; } if (community_size) { //Initialize the vector IGRAPH_CHECK(igraph_vector_resize(community_size, q)); for (unsigned int spin_opt = 1; spin_opt <= q; spin_opt++) { //Set the community size VECTOR(*community_size)[spin_opt-1]=csize[spin_opt]; } } //Set the membership if (membership) { IGRAPH_CHECK(igraph_vector_resize(membership, num_nodes)); for (unsigned int i = 0; i < num_nodes; i++) { VECTOR(*membership)[ i ]= spin[i]-1; } } double Q = 0.0; //Modularity if (adhesion) { IGRAPH_CHECK(igraph_matrix_resize(adhesion, q, q)); IGRAPH_CHECK(igraph_matrix_resize(normalised_adhesion, q, q)); double **num_links_pos = 0; double **num_links_neg = 0; //memory allocated for elements of rows. num_links_pos = new double *[q+1] ; num_links_neg = new double *[q+1] ; //memory allocated for elements of each column. for( unsigned int i = 0 ; i < q+1 ; i++) { num_links_pos[i] = new double[q+1]; num_links_neg[i] = new double[q+1]; } //Init num_links for (unsigned int i = 0; i <= q; i++) { for (unsigned int j = 0; j <= q; j++) { num_links_pos[i][j] = 0.0; num_links_neg[i][j] = 0.0; } } DLList_Iter iter_l; NLink *l_cur = iter_l.First(net->link_list); double w = 0.0; while (!iter_l.End()) { w = l_cur->Get_Weight(); unsigned int a = spin[l_cur->Get_Start()->Get_Index()]; unsigned int b = spin[l_cur->Get_End()->Get_Index()]; if (w > 0) { num_links_pos[a][b] += w; if (!is_directed && a != b) //Only one edge is defined in case it is undirected num_links_pos[b][a] += w; } else { num_links_neg[a][b] -= w; if (!is_directed && a != b) //Only one edge is defined in case it is undirected num_links_neg[b][a] -= w; } l_cur = iter_l.Next(); } //while links #ifdef DEBUG printf("d_p: %f\n", d_p); printf("d_n: %f\n", d_n); #endif double expected = 0.0; double a = 0.0; double normal_a = 0.0; double delta, u_p, u_n; double max_expected, max_a; //We don't take into account the lambda or gamma for //computing the modularity and adhesion, since they //are then incomparable to other definitions. for (unsigned int i = 1; i <= q; i++) { for (unsigned int j = 1; j <= q; j++) { if (!is_directed && i == j) expected = degree_community_pos_out[i] * degree_community_pos_in[j]/(m_p == 0 ? 1 : 2*m_p) - degree_community_neg_out[i] * degree_community_neg_in[j]/(m_n == 0 ? 1 : 2*m_n); else expected = degree_community_pos_out[i] * degree_community_pos_in[j]/(m_p == 0 ? 1: m_p) - degree_community_neg_out[i] * degree_community_neg_in[j]/(m_n == 0 ? 1 : m_n); a = (num_links_pos[i][j] - num_links_neg[i][j]) - expected; if (i == j) //cohesion { if (is_directed) delta = d_p * csize[i] * (csize[i] - 1); //Maximum amount else delta = d_p * csize[i] * (csize[i] - 1)/2; //Maximum amount u_p = delta - num_links_pos[i][i]; //Add as many positive links we can u_n = -num_links_neg[i][i]; //Delete as many negative links we can Q += a; } else //adhesion { if (is_directed) delta = d_n * csize[i] * csize[j]*2; //Maximum amount else delta = d_n * csize[i] * csize[j]; //Maximum amount u_p = -num_links_pos[i][j]; //Delete as many positive links we can u_n = delta - num_links_neg[i][j]; //Add as many negative links we can } if (!is_directed && i == j) max_expected = (degree_community_pos_out[i] + u_p) * (degree_community_pos_in[j] + u_p)/((m_p + u_p) == 0 ? 1 : 2*(m_p + u_p)) - (degree_community_neg_out[i] - u_n) * (degree_community_neg_in[j] + u_n)/((m_n + u_n) == 0 ? 1 : 2*(m_n + u_n)); else max_expected = (degree_community_pos_out[i] + u_p) * (degree_community_pos_in[j] + u_p)/((m_p + u_p) == 0 ? 1 : m_p + u_p) - (degree_community_neg_out[i] - u_n) * (degree_community_neg_in[j] + u_n)/((m_n + u_n) == 0 ? 1 : m_n + u_n); //printf("%f/%f %d/%d\t", num_links_pos[i][j], num_links_neg[i][j], csize[i], csize[j]); //printf("%f/%f - %f(%f)\t", u_p, u_n, expected, max_expected); max_a = ((num_links_pos[i][j] + u_p) - (num_links_neg[i][j] + u_n)) - max_expected; //In cases where we haven't actually found a ground state //the adhesion/cohesion *might* not be negative/positive, //hence the maximum adhesion and cohesion might behave quite //strangely. In order to prevent that, we limit them to 1 in //absolute value, and prevent from dividing by zero (even if //chuck norris would). if (i == j) normal_a = a/(max_a == 0 ? a : max_a); else normal_a = -a/(max_a == 0 ? a : max_a); if (normal_a > 1) normal_a = 1; else if (normal_a < -1) normal_a = -1; MATRIX(*adhesion, i - 1, j - 1) = a; MATRIX(*normalised_adhesion, i - 1, j - 1) = normal_a; } //for j //printf("\n"); } //for i //free the allocated memory for( unsigned int i = 0 ; i < q+1 ; i++ ) { delete [] num_links_pos[i] ; delete [] num_links_neg[i]; } delete [] num_links_pos ; delete [] num_links_neg ; } //adhesion if (modularity) { if (is_directed) *modularity=Q/(m_p + m_n); else *modularity=2*Q/(m_p + m_n); //Correction for the way m_p and m_n are counted. Modularity is 1/m, not 1/2m } if (polarization) { double sum_ad = 0.0; for (unsigned int i = 0; i < q; i++) { for (unsigned int j = 0; j < q; j++) { if (i != j) { sum_ad -= MATRIX(*normalised_adhesion, i, j); } } } *polarization= sum_ad/(q*q - q); } #ifdef DEBUG printf("Finished writing cluster.\n"); #endif return num_nodes; } igraph/src/NetDataTypes.h0000644000175100001440000005411213431000472015044 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt The original copyright notice follows here */ /*************************************************************************** NetDataTypes.h - description ------------------- begin : Mon Oct 6 2003 copyright : (C) 2003 by Joerg Reichardt email : reichardt@mitte ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef NETDATATYPES_H #define NETDATATYPES_H #include //########################################################################################### struct HUGE_INDEX { unsigned int field_index; unsigned long in_field_index; }; template class HugeArray { private: unsigned long int size; unsigned int highest_field_index; unsigned long max_bit_left; unsigned long max_index; DATA *data; DATA *fields[32]; public: HUGE_INDEX get_huge_index(unsigned long); DATA &Set(unsigned long); DATA Get(unsigned long); HugeArray(void); ~HugeArray(void); DATA &operator[](unsigned long); unsigned long Size(void) {return max_index;} } ; //############################################################################################### template class DLList; template class DL_Indexed_List; template class ClusterList; template class DLList_Iter; template class DLItem { friend class DLList ; friend class DL_Indexed_List; friend class DLList_Iter; private: L_DATA item; unsigned long index; DLItem *previous; DLItem *next; DLItem(L_DATA i, unsigned long ind); DLItem(L_DATA i, unsigned long ind, DLItem *p, DLItem *n); ~DLItem(); public: void del() { delete item; } }; template class DLList { friend class DLList_Iter; protected: DLItem *head; DLItem *tail; unsigned long number_of_items; DLItem *pInsert(L_DATA, DLItem*); L_DATA pDelete(DLItem*); public: DLList(void); ~DLList(); unsigned long Size(void) { return number_of_items; } int Insert(L_DATA, unsigned long); int Delete(unsigned long); int fDelete(L_DATA); L_DATA Push(L_DATA); L_DATA Pop(void); L_DATA Get(unsigned long); int Enqueue(L_DATA); L_DATA Dequeue(void); unsigned long Is_In_List(L_DATA); void delete_items(); }; template class DL_Indexed_List : virtual public DLList { friend class DLList_Iter; private: DLItem *pInsert(L_DATA, DLItem*); L_DATA pDelete(DLItem*); HugeArray*> array; unsigned long last_index; public: DL_Indexed_List(void); ~DL_Indexed_List(); L_DATA Push(L_DATA); L_DATA Pop(void); L_DATA Get(unsigned long); }; //##################################################################################################### template class DLList_Iter { private: DLList *list; DLItem *current; bool end_reached; public: DLList_Iter(void); ~DLList_Iter() {end_reached=true;}; L_DATA Next(void); L_DATA Previous(void); L_DATA First(DLList *l); L_DATA Last(DLList *l); bool End(void) {return end_reached;} DLItem *Get_Current(void) {return current;} L_DATA Get_Current_Item(void) {return current->item;} void Set_Current(DLItem *c) {current=c;} void Set_Status(bool s) {end_reached=s;} bool Swap(DLList_Iter); //swapt die beiden Elemente, wenn sie in der gleichen Liste stehen!! }; //##################################################################################################### struct RGBcolor { unsigned int red; unsigned int green; unsigned int blue; char pajek_c[20]; }; //------------------------------------------------------------------------------- class NLink; class NNode { friend class NLink; private : unsigned long index; unsigned long cluster_index; unsigned long marker, affiliations; unsigned long *state_history; unsigned int max_states; long distance; double clustering; double weight; double affinity; // double old_weight; DLList *neighbours; //list with pointers to neighbours DLList *n_links; DLList *global_link_list; char name[255]; RGBcolor color; public : NNode(unsigned long, unsigned long, DLList*, char*, int); ~NNode(); unsigned long Get_Index(void) { return(index); } unsigned long Get_ClusterIndex(void) { return(cluster_index);} unsigned long Get_Marker(void) { return marker;} void Set_Marker(unsigned long m) {marker=m;} unsigned long Get_Affiliations(void) { return affiliations;} void Set_Affiliations(unsigned long m) {affiliations=m;} void Set_ClusterIndex(unsigned long ci) { cluster_index=ci; return;} void Set_Index(unsigned long i) {index=i; return;} unsigned long Get_Degree(void) { return(neighbours->Size());} char *Get_Name(void) {return name;} void Set_Name(char* n) {strcpy(name,n);} double Get_Links_Among_Neigbours(void); double Get_Clustering(void); double Get_Weight(void) {return weight;} double Get_Affinity(void) {return affinity;} unsigned long *Get_StateHistory(void) {return state_history;} void Add_StateHistory(unsigned int q); // double Get_OldWeight(void) {return old_weight;} void Set_Weight(double w) {weight=w;} void Set_Affinity(double w) {affinity=w;} // void Set_OldWeight(double w) {old_weight=w;} long Get_Distance(void) {return distance;} void Set_Distance(long d) {distance=d;} int Connect_To(NNode*, double); DLList *Get_Neighbours(void) {return neighbours;} DLList *Get_Links(void) {return n_links;} int Disconnect_From(NNode*); int Disconnect_From_All(void); bool Is_Linked_To(NNode*); RGBcolor Get_Color(void) {return color;} void Set_Color(RGBcolor c); NLink *Get_LinkToNeighbour(NNode *neighbour); }; //##################################################################################################### class NLink { friend class NNode; private : NNode *start; NNode *end; double weight; double old_weight; unsigned long index; unsigned long marker; public : NLink( NNode*, NNode*, double); ~NLink(); unsigned long Get_Start_Index(void) { return(start->Get_Index()); } unsigned long Get_End_Index(void) { return(end->Get_Index()); } NNode *Get_Start(void) {return(start);} NNode *Get_End(void) {return(end);} double Get_Weight(void) {return weight;} void Set_Weight(double w) {weight=w;} double Get_OldWeight(void) {return old_weight;} void Set_OldWeight(double w) {old_weight=w;} unsigned long Get_Marker(void) {return marker;} void Set_Marker(unsigned long m) {marker=m;} unsigned long Get_Index() {return index;} void Set_Index(unsigned long i) {index=i;} }; //##################################################################################################### template class ClusterList : public DLList { friend class DLList_Iter; private: long links_out_of_cluster; unsigned long links_inside_cluster; unsigned long frequency; double cluster_energy; DLList *candidates; long marker; public: ClusterList(void); ~ClusterList(); long Get_Links_OOC(void) {return(links_out_of_cluster);} void Set_Links_OOC(long looc) {links_out_of_cluster=looc;} unsigned long Get_Links_IC(void) {return(links_inside_cluster);} unsigned long Get_Frequency(void) {return(frequency);} void IncreaseFrequency(void) {frequency++;} void Set_Links_IC(unsigned long lic) {links_inside_cluster=lic;} double Get_Energy(void) {return (cluster_energy);} void Set_Energy(double e) {cluster_energy=e;} DLList *Get_Candidates(void) {return candidates;} bool operator<(ClusterList &b); bool operator==(ClusterList &b); long Get_Marker(void) {return marker;} void Set_Marker(long m) {marker=m;} }; //##################################################################################################### template class DL_Node_List : virtual public DL_Indexed_List { friend class DLList_Iter; private: DLItem *pInsert(NNode*, DLItem*); NNode* pDelete(DLItem*); HugeArray*> array; unsigned long last_index; public: DL_Node_List(void); ~DL_Node_List(); NNode* Push(NNode*); NNode* Pop(void); NNode* Get(unsigned long); int Delete(unsigned long); }; //##################################################################################################### struct cluster_join_move { ClusterList *c1; ClusterList *c2; double joint_energy; long joint_looc; unsigned long joint_lic; } ; struct network { DL_Indexed_List *node_list; DL_Indexed_List *link_list; DL_Indexed_List*> *cluster_list; DL_Indexed_List *moveset; unsigned long max_k; unsigned long min_k; unsigned long diameter; double av_weight; double max_weight; double min_weight; double sum_weights; double av_k; double av_bids; unsigned long max_bids; unsigned long min_bids; unsigned long sum_bids; } ; /* struct network { DLList *node_list; DLList *link_list; DLList*> *cluster_list; DLList *moveset; } ; */ template HugeArray::HugeArray(void) { max_bit_left=1<<31; //wir setzen das 31. Bit auf 1 size=2; max_index=0; highest_field_index=0; data=new DATA[2]; //ein extra Platz fuer das Nullelement data[0]=0; data[1]=0; for (int i=0; i<32; i++) fields[i]=NULL; fields[highest_field_index]=data; } template HugeArray::~HugeArray(void) { for (unsigned int i=0; i<=highest_field_index; i++) { data=fields[i]; delete [] data; } } template HUGE_INDEX HugeArray::get_huge_index(unsigned long index) { HUGE_INDEX h_index; unsigned int shift_index=0; unsigned long help_index; help_index=index; if (index<2) { h_index.field_index=0; h_index.in_field_index=index; return h_index; } // wie oft muessen wir help_index nach links shiften, damit das 31. Bit gesetzt ist?? while (!(max_bit_left & help_index)) { help_index <<= 1; shift_index++; } h_index.field_index=31-shift_index; // das hoechste besetzte Bit im Index help_index=1 << h_index.field_index; // in help_index wird das hoechste besetzte Bit von Index gesetzt h_index.in_field_index=(index ^ help_index); // index XOR help_index, womit alle bits unter dem hoechsten erhalten bleiben return h_index; } template DATA &HugeArray::Set(unsigned long int index) { HUGE_INDEX h_index; unsigned long data_size; while (size DATA HugeArray::Get(unsigned long index) { return(Set(index)); } template DATA &HugeArray::operator[](unsigned long index) { return(Set(index)); } //############################################################################### template DLItem::DLItem(L_DATA i, unsigned long ind) : item(i), index(ind), previous(0), next(0) { } template DLItem::DLItem(L_DATA i, unsigned long ind, DLItem *p, DLItem *n) : item(i), index(ind), previous(p), next(n) { } template DLItem::~DLItem() { //delete item; //eigentlich muessten wir pruefen, ob item ueberhaupt ein Pointer ist... //previous=NULL; //next=NULL; } //###################################################################################################################### template DLList::DLList(void) { head=tail=NULL; number_of_items=0; head=new DLItem(NULL,0); //fuer head und Tail gibt es das gleiche Array-Element!! Vorsicht!! tail=new DLItem(NULL,0); if ( !head || !tail ) { if (head) delete(head); if (tail) delete(tail); return; } else { head->next=tail; tail->previous=head; } } template DLList::~DLList() { DLItem *cur=head, *next; while (cur) { next=cur->next; delete(cur); cur=next; } number_of_items=0; // printf("Liste Zerstoert!\n"); } template void DLList::delete_items() { DLItem *cur, *next; cur=this->head; while (cur) { next=cur->next; cur->del(); cur=next; } this->number_of_items=0; } //privates Insert template DLItem *DLList::pInsert(L_DATA data, DLItem *pos) { DLItem *i=new DLItem(data, number_of_items+1, pos->previous, pos); if (i) { pos->previous->next=i; pos->previous=i; number_of_items++; return(i); } else return(0); } //privates delete template L_DATA DLList::pDelete(DLItem *i) { L_DATA data=i->item; i->previous->next=i->next; i->next->previous=i->previous; // array[i->index]=0; delete(i); number_of_items--; return(data); } //oeffentliches Insert template int DLList::Insert(L_DATA data, unsigned long pos) { if ((pos<0)||(pos>(number_of_items))) return(0); DLItem *cur=head; while(pos--) cur=cur->next; return(pInsert(data,cur)!=0); } //oeffentliche Delete template int DLList::Delete(unsigned long pos) { if ((pos<0)||(pos>(number_of_items))) return(0); DLItem *cur=head; while(pos--) cur=cur->next; return(pDelete(cur)!=0); } //oeffentliche Delete template int DLList::fDelete(L_DATA data) { if ((number_of_items==0) || (!data)) return(0); DLItem *cur; cur=head->next; while ((cur!=tail) && (cur->item!=data)) cur=cur->next; if (cur!=tail) return(pDelete(cur)!=0); return(0); } template L_DATA DLList::Push(L_DATA data) { DLItem *tmp; tmp=pInsert(data,tail); if (tmp) return (tmp->item); return(0); } template L_DATA DLList::Pop(void) { return(pDelete(tail->previous)); } template L_DATA DLList::Get(unsigned long pos) { if ((pos<1)||(pos>(number_of_items+1))) return(0); // return(array[pos]->item); DLItem *cur=head; while(pos--) cur=cur->next; return(cur->item); } template int DLList::Enqueue(L_DATA data) { return(pInsert(data,tail)!=0); } template L_DATA DLList::Dequeue(void) { return(pDelete(head->next)); } //gibt Index des gesuchte Listenelement zurueck, besser waere eigentlich zeiger template unsigned long DLList::Is_In_List(L_DATA data) { DLItem *cur=head, *next; unsigned long pos=0; while (cur) { next=cur->next; if (cur->item==data) return(pos) ; cur=next; pos++; } return(0); } //###################################################################################################################### template DL_Indexed_List::DL_Indexed_List(void) : DLList() { last_index=0; } template DL_Indexed_List::~DL_Indexed_List() { /* This is already done by the DLList destructor */ /* DLItem *cur, *next; */ /* cur=this->head; */ /* while (cur) */ /* { */ /* next=cur->next; */ /* delete(cur); */ /* cur=next; */ /* } */ /* this->number_of_items=0; */ // printf("Liste Zerstoert!\n"); } //privates Insert template DLItem *DL_Indexed_List::pInsert(L_DATA data, DLItem *pos) { DLItem *i=new DLItem(data, last_index, pos->previous, pos); if (i) { pos->previous->next=i; pos->previous=i; this->number_of_items++; array[last_index]=i; last_index++; return(i); } else return(0); } //privates delete template L_DATA DL_Indexed_List::pDelete(DLItem *i) { L_DATA data=i->item; i->previous->next=i->next; i->next->previous=i->previous; array[i->index]=0; last_index=i->index; delete(i); this->number_of_items--; return(data); } template L_DATA DL_Indexed_List::Push(L_DATA data) { DLItem *tmp; tmp=pInsert(data,this->tail); if (tmp) return (tmp->item); return(0); } template L_DATA DL_Indexed_List::Pop(void) { return(pDelete(this->tail->previous)); } template L_DATA DL_Indexed_List::Get(unsigned long pos) { if (pos > this->number_of_items - 1) return(0); return(array[pos]->item); } //####################################################################################### //************************************************************************************************************ template ClusterList::ClusterList(void) : DLList() { links_out_of_cluster=0; links_inside_cluster=0; frequency=1; cluster_energy=1e30; candidates=new DLList(); marker=0; } template ClusterList::~ClusterList() { while (candidates->Size()) { candidates->Pop(); } delete candidates; } template bool ClusterList::operator==(ClusterList &b) { bool found=false; L_DATA n_cur, n_cur_b; DLList_Iter a_iter,b_iter; if (this->Size()!=b.Size()) return false; n_cur=a_iter.First(this); while (!(a_iter.End())) { found=false; n_cur_b=b_iter.First(&b); while (!(b_iter.End()) && !found) { if (n_cur==n_cur_b) found=true; n_cur_b=b_iter.Next(); } if (!found) return false; n_cur=a_iter.Next(); } return(found); } //A bool ClusterList::operator<(ClusterList &b) { bool found=false; L_DATA n_cur, n_cur_b; DLList_Iter a_iter, b_iter; if (this->Size()>=b.Size()) return false; n_cur=a_iter.First(this); while (!(a_iter.End())) { found=false; n_cur_b=b_iter.First(&b); while (!(b_iter.End()) && !found) { if (n_cur==n_cur_b) found=true; n_cur_b=b_iter.Next(); } if (!found) return false; n_cur=a_iter.Next(); } return(found); } //##################################################################################### template DLList_Iter::DLList_Iter() { list=NULL; current=NULL; end_reached=true; } template L_DATA DLList_Iter::Next(void) { current=current->next; if (current==(list->tail)) end_reached=true; return(current->item); } template L_DATA DLList_Iter::Previous(void) { current=current->previous; if (current==(list->head)) end_reached=true; return(current->item); } template L_DATA DLList_Iter::First(DLList *l) { list=l; current=list->head->next; if (current==(list->tail)) end_reached=true; else end_reached=false; return(current->item); } template L_DATA DLList_Iter::Last(DLList *l) { list=l; current=list->tail->previous; if (current==(list->head)) end_reached=true; // falls die List leer ist else end_reached=false; return(current->item); } template bool DLList_Iter::Swap(DLList_Iter b) { L_DATA h; if (list!=b.list) return false; //elemeten muessen aus der gleichen List stammen if (end_reached || b.end_reached) return false; h=current->item; current->item=b.current->item; b.current->item=h; return true; } #endif igraph/src/microscopic_update.c0000644000175100001440000016321613431000472016354 0ustar hornikusers/* -*- mode: C -*- */ /* Microscopic update rules for dealing with agent-level strategy revision. Copyright (C) 2011 Minh Van Nguyen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_iterators.h" #include "igraph_interface.h" #include "igraph_microscopic_update.h" #include "igraph_nongraph.h" #include "igraph_random.h" #include /* * Internal use only. * Compute the cumulative proportionate values of a vector. The vector is * assumed to hold values associated with edges. * * \param graph The graph object representing the game network. No error * checks will be performed on this graph. You are responsible for * ensuring that this is a valid graph for the particular * microscopic update rule at hand. * \param U A vector of edge values for which we want to compute cumulative * proportionate values. So U[i] is the value of the edge with ID i. * With a local perspective, we would only compute cumulative * proportionate values for some combination of U. This vector could * be, for example, a vector of weights for edges in \p graph. It is * assumed that each value of U is nonnegative; it is your * responsibility to ensure this. Furthermore, this vector must have a * length the same as the number of edges in \p graph; you are * responsible for ensuring this condition holds. * \param V Pointer to an uninitialized vector. The cumulative proportionate * values will be computed and stored here. No error checks will be * performed on this parameter. * \param islocal Boolean; this flag controls which perspective to use. If * true then we use the local perspective; otherwise we use the global * perspective. In the context of this function, the local perspective * for a vertex v consists of all edges incident on v. In contrast, the * global perspective for v consists of all edges in \p graph. * \param vid The vertex to use if we are considering a local perspective, * i.e. if \p islocal is true. This vertex will be ignored if * \p islocal is false. That is, if \p islocal is false then it is safe * pass the value -1 here. On the other hand, if \p islocal is true then * it is assumed that this is indeed a vertex of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. This * is only relevant if we are considering the local perspective, i.e. if * \p islocal is true. If we are considering the global perspective, * then this parameter would be ignored. In other words, if \p islocal * is false then it is safe to pass the value \p IGRAPH_ALL here. If * \p graph is undirected, then we use all the immediate neighbours of * \p vid. Thus if you know that \p graph is undirected, then it is * safe to pass the value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a digraph and we are considering the local * perspective. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph and we are considering the local * perspective. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph and we are considering a local * perspective. Also use this value if \p graph is undirected or we * are considering the global perspective. * \endclist * \return Codes: * \clist * \cli IGRAPH_EINVAL * This error code is returned in the following case: The vector * \p U, or some combination of its values, sums to zero. * \cli IGRAPH_SUCCESS * This signal is returned if the cumulative proportionate values * were successfully computed. * \endclist * * Time complexity: O(2n) where n is the number of edges in the perspective * of \p vid. */ int igraph_ecumulative_proportionate_values(const igraph_t *graph, const igraph_vector_t *U, igraph_vector_t *V, igraph_bool_t islocal, igraph_integer_t vid, igraph_neimode_t mode) { igraph_eit_t A; /* all edges in v's perspective */ igraph_es_t es; igraph_integer_t e; igraph_real_t C; /* cumulative probability */ igraph_real_t P; /* probability */ igraph_real_t S; /* sum of values */ long int i; /* Set the perspective. Let v be the vertex under consideration. The local */ /* perspective for v consists of edges incident on it. In contrast, the */ /* global perspective for v are all edges in the given graph. Hence in the */ /* global perspective, we will ignore the given vertex and the given */ /* neighbourhood type, but instead consider all edges in the given graph. */ if (islocal) IGRAPH_CHECK(igraph_es_incident(&es, vid, mode)); else IGRAPH_CHECK(igraph_es_all(&es, IGRAPH_EDGEORDER_ID)); IGRAPH_FINALLY(igraph_es_destroy, &es); /* Sum up all the values of vector U in the perspective for v. This sum */ /* will be used in normalizing each value. */ /* NOTE: Here we assume that each value to be summed is nonnegative, */ /* and at least one of the values is nonzero. The behaviour resulting */ /* from all values being zero would be division by zero later on when */ /* we normalize each value. We check to see that the values sum to zero. */ /* NOTE: In this function, the order in which we iterate through the */ /* edges of interest should be the same as the order in which we do so */ /* in the caller function. If the caller function doesn't care about the */ /* order of values in the resulting vector V, then there's no need to take */ /* special notice of that order. But in some cases the order of values in */ /* V is taken into account, for example, in the Moran process. */ S = 0.0; IGRAPH_CHECK(igraph_eit_create(graph, es, &A)); IGRAPH_FINALLY(igraph_eit_destroy, &A); while (!IGRAPH_EIT_END(A)) { e = (igraph_integer_t)IGRAPH_EIT_GET(A); S += (igraph_real_t)VECTOR(*U)[e]; IGRAPH_EIT_NEXT(A); } /* avoid division by zero later on */ if (S == (igraph_real_t)0.0) { igraph_eit_destroy(&A); igraph_es_destroy(&es); IGRAPH_FINALLY_CLEAN(2); IGRAPH_ERROR("Vector of values sums to zero", IGRAPH_EINVAL); } /* Get cumulative probability and relative value for each edge in the */ /* perspective of v. The vector V holds the cumulative proportionate */ /* values of all edges in v's perspective. The value V[0] is the */ /* cumulative proportionate value of the first edge in the edge iterator */ /* A. The value V[1] is the cumulative proportionate value of the second */ /* edge in the iterator A. And so on. */ C = 0.0; i = 0; IGRAPH_EIT_RESET(A); IGRAPH_VECTOR_INIT_FINALLY(V, IGRAPH_EIT_SIZE(A)); while (!IGRAPH_EIT_END(A)) { e = (igraph_integer_t)IGRAPH_EIT_GET(A); /* NOTE: Beware of division by zero here. This can happen if the vector */ /* of values, or the combination of interest, sums to zero. */ P = (igraph_real_t)VECTOR(*U)[e] / S; C += P; VECTOR(*V)[i] = C; i++; IGRAPH_EIT_NEXT(A); } igraph_eit_destroy(&A); igraph_es_destroy(&es); /* Pop V, A and es from the finally stack -- that's three items */ IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /* * Internal use only. * Compute the cumulative proportionate values of a vector. The vector is * assumed to hold values associated with vertices. * * \param graph The graph object representing the game network. No error * checks will be performed on this graph. You are responsible for * ensuring that this is a valid graph for the particular * microscopic update rule at hand. * \param U A vector of vertex values for which we want to compute cumulative * proportionate values. The vector could be, for example, a vector of * fitness for vertices of \p graph. It is assumed that each value of U * is nonnegative; it is your responsibility to ensure this. Also U, or * a combination of interest, is assumed to sum to a positive value; * this condition will be checked. * \param V Pointer to an uninitialized vector. The cumulative proportionate * values will be computed and stored here. No error checks will be * performed on this parameter. * \param islocal Boolean; this flag controls which perspective to use. If * true then we use the local perspective; otherwise we use the global * perspective. The local perspective for a vertex v is the set of all * immediate neighbours of v. In contrast, the global perspective * for v is the vertex set of \p graph. * \param vid The vertex to use if we are considering a local perspective, * i.e. if \p islocal is true. This vertex will be ignored if * \p islocal is false. That is, if \p islocal is false then it is safe * pass the value -1 here. On the other hand, if \p islocal is true then * it is assumed that this is indeed a vertex of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. This * is only relevant if we are considering the local perspective, i.e. if * \p islocal is true. If we are considering the global perspective, * then this parameter would be ignored. In other words, if \p islocal * is false then it is safe to pass the value \p IGRAPH_ALL here. If * \p graph is undirected, then we use all the immediate neighbours of * \p vid. Thus if you know that \p graph is undirected, then it is * safe to pass the value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a digraph and we are considering the local * perspective. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph and we are considering the local * perspective. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph and we are considering a local * perspective. Also use this value if \p graph is undirected or we * are considering the global perspective. * \endclist * \return Codes: * \clist * \cli IGRAPH_EINVAL * This error code is returned in the following case: The vector * \p U, or some combination of its values, sums to zero. * \cli IGRAPH_SUCCESS * This signal is returned if the cumulative proportionate values * were successfully computed. * \endclist * * Time complexity: O(2n) where n is the number of vertices in the * perspective of vid. */ int igraph_vcumulative_proportionate_values(const igraph_t *graph, const igraph_vector_t *U, igraph_vector_t *V, igraph_bool_t islocal, igraph_integer_t vid, igraph_neimode_t mode) { igraph_integer_t v; igraph_real_t C; /* cumulative probability */ igraph_real_t P; /* probability */ igraph_real_t S; /* sum of values */ igraph_vit_t A; /* all vertices in v's perspective */ igraph_vs_t vs; long int i; /* Set the perspective. Let v be the vertex under consideration; it might */ /* be that we want to update v's strategy. The local perspective for v */ /* consists of its immediate neighbours. In contrast, the global */ /* perspective for v are all the vertices in the given graph. Hence in the */ /* global perspective, we will ignore the given vertex and the given */ /* neighbourhood type, but instead consider all vertices in the given */ /* graph. */ if (islocal) IGRAPH_CHECK(igraph_vs_adj(&vs, vid, mode)); else IGRAPH_CHECK(igraph_vs_all(&vs)); IGRAPH_FINALLY(igraph_vs_destroy, &vs); /* Sum up all the values of vector U in the perspective for v. This */ /* sum will be used in normalizing each value. If we are using a local */ /* perspective, then we also need to consider the quantity of v in */ /* computing the sum. */ /* NOTE: Here we assume that each value to be summed is nonnegative, */ /* and at least one of the values is nonzero. The behaviour resulting */ /* from all values being zero would be division by zero later on when */ /* we normalize each value. We check to see that the values sum to zero. */ /* NOTE: In this function, the order in which we iterate through the */ /* vertices of interest should be the same as the order in which we do so */ /* in the caller function. If the caller function doesn't care about the */ /* order of values in the resulting vector V, then there's no need to take */ /* special notice of that order. But in some cases the order of values in */ /* V is taken into account, for example, in roulette wheel selection. */ S = 0.0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &A)); IGRAPH_FINALLY(igraph_vit_destroy, &A); while (!IGRAPH_VIT_END(A)) { v = (igraph_integer_t)IGRAPH_VIT_GET(A); S += (igraph_real_t)VECTOR(*U)[v]; IGRAPH_VIT_NEXT(A); } if (islocal) S += (igraph_real_t)VECTOR(*U)[vid]; /* avoid division by zero later on */ if (S == (igraph_real_t)0.0) { igraph_vit_destroy(&A); igraph_vs_destroy(&vs); IGRAPH_FINALLY_CLEAN(2); IGRAPH_ERROR("Vector of values sums to zero", IGRAPH_EINVAL); } /* Get cumulative probability and relative value for each vertex in the */ /* perspective of v. The vector V holds the cumulative proportionate */ /* values of all vertices in v's perspective. The value V[0] is the */ /* cumulative proportionate value of the first vertex in the vertex */ /* iterator A. The value V[1] is the cumulative proportionate value of */ /* the second vertex in the iterator A. And so on. If we are using the */ /* local perspective, then we also need to consider the cumulative */ /* proportionate value of v. In the case of the local perspective, we */ /* don't need to compute and store v's cumulative proportionate value, */ /* but we pretend that such value is appended to the vector V. */ C = 0.0; i = 0; IGRAPH_VIT_RESET(A); IGRAPH_VECTOR_INIT_FINALLY(V, IGRAPH_VIT_SIZE(A)); while (!IGRAPH_VIT_END(A)) { v = (igraph_integer_t)IGRAPH_VIT_GET(A); /* NOTE: Beware of division by zero here. This can happen if the vector */ /* of values, or a combination of interest, sums to zero. */ P = (igraph_real_t)VECTOR(*U)[v] / S; C += P; VECTOR(*V)[i] = C; i++; IGRAPH_VIT_NEXT(A); } igraph_vit_destroy(&A); igraph_vs_destroy(&vs); /* Pop V, A and vs from the finally stack -- that's three items */ IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /* * Internal use only. * A set of standard tests to be performed prior to strategy updates. The * tests contained in this function are common to many strategy revision * functions in this file. This function is meant to be invoked from within * a specific strategy update function in order to perform certain common * tests, including sanity checks and conditions under which no strategy * updates are necessary. * * \param graph The graph object representing the game network. This cannot * be the empty or trivial graph, but must have at least two vertices * and one edge. If \p graph has one vertex, then no strategy update * would take place. Furthermore, if \p graph has at least two vertices * but zero edges, then strategy update would also not take place. * \param vid The vertex whose strategy is to be updated. It is assumed that * \p vid represents a vertex in \p graph. No checking is performed and * it is your responsibility to ensure that \p vid is indeed a vertex * of \p graph. If an isolated vertex is provided, i.e. the input * vertex has degree 0, then no strategy update would take place and * \p vid would retain its current strategy. Strategy update would also * not take place if the local neighbourhood of \p vid are its * in-neighbours (respectively out-neighbours), but \p vid has zero * in-neighbours (respectively out-neighbours). Loops are ignored in * computing the degree (in, out, all) of \p vid. * \param quantities A vector of quantities providing the quantity of each * vertex in \p graph. Think of each entry of the vector as being * generated by a function such as the fitness function for the game. * So if the vector represents fitness quantities, then each vector * entry is the fitness of some vertex. The length of this vector must * be the same as the number of vertices in the vertex set of \p graph. * \param strategies A vector of the current strategies for the vertex * population. Each strategy is identified with a nonnegative integer, * whose interpretation depends on the payoff matrix of the game. * Generally we use the strategy ID as a row or column index of the * payoff matrix. The length of this vector must be the same as the * number of vertices in the vertex set of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. If * \p graph is undirected, then we use all the immediate neighbours of * \p vid. Thus if you know that \p graph is undirected, then it is safe * to pass the value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph. Also use this value if * \p graph is undirected. * \endclist * \param updates Boolean; at the end of this test suite, this flag * indicates whether to proceed with strategy revision. If true then * strategy revision should proceed; otherwise there is no need to * continue with revising a vertex's strategy. A caller function that * invokes this function would use the value of \p updates to * determine whether to proceed with strategy revision. * \param islocal Boolean; this flag controls which perspective to use. If * true then we use the local perspective; otherwise we use the global * perspective. The local perspective for \p vid is the set of all * immediate neighbours of \p vid. In contrast, the global perspective * for \p vid is the vertex set of \p graph. * \return Codes: * \clist * \cli IGRAPH_EINVAL * This error code is returned in each of the following cases: * (1) Any of the parameters \p graph, \p quantities, or * \p strategies is a null pointer. (2) The vector \p quantities * or \p strategies has a length different from the number of * vertices in \p graph. (3) The parameter \p graph is the empty * or null graph, i.e. the graph with zero vertices and edges. * \cli IGRAPH_SUCCESS * This signal is returned if no errors were raised. You should use * the value of the boolean \p updates to decide whether to go * ahead with updating a vertex's strategy. * \endclist */ int igraph_microscopic_standard_tests(const igraph_t *graph, igraph_integer_t vid, const igraph_vector_t *quantities, const igraph_vector_t *strategies, igraph_neimode_t mode, igraph_bool_t *updates, igraph_bool_t islocal) { igraph_integer_t nvert; igraph_vector_t degv; *updates=1; /* sanity checks */ if (graph == NULL) { IGRAPH_ERROR("Graph is a null pointer", IGRAPH_EINVAL); } if (quantities == NULL) { IGRAPH_ERROR("Quantities vector is a null pointer", IGRAPH_EINVAL); } if (strategies == NULL) { IGRAPH_ERROR("Strategies vector is a null pointer", IGRAPH_EINVAL); } /* the empty graph */ nvert=igraph_vcount(graph); if (nvert < 1) { IGRAPH_ERROR("Graph cannot be the empty graph", IGRAPH_EINVAL); } /* invalid vector length */ if (nvert != (igraph_integer_t)igraph_vector_size(quantities)) { IGRAPH_ERROR("Size of quantities vector different from number of vertices", IGRAPH_EINVAL); } if (nvert != (igraph_integer_t)igraph_vector_size(strategies)) { IGRAPH_ERROR("Size of strategies vector different from number of vertices", IGRAPH_EINVAL); } /* Various conditions under which no strategy updates will take place. That * is, the vertex retains its current strategy. */ /* given graph has < 2 vertices */ if (nvert < 2) { *updates=0; } /* graph has >= 2 vertices, but no edges */ if (igraph_ecount(graph) < 1) { *updates=0; } /* Test for vertex isolation, depending on the perspective given. For * undirected graphs, a given vertex v is isolated if its degree is zero. * If we are considering in-neighbours (respectively out-neighbours), then * we say that v is isolated if its in-degree (respectively out-degree) is * zero. In general, this vertex isolation test is only relevant if we are * using a local perspective, i.e. if we only consider the immediate * neighbours (local perspective) of v as opposed to all vertices in the * vertex set of the graph (global perspective). */ if (islocal) { /* Moving on ahead with vertex isolation test, since local perspective */ /* is requested. */ IGRAPH_VECTOR_INIT_FINALLY(°v, 1); IGRAPH_CHECK(igraph_degree(graph, °v, igraph_vss_1(vid), mode, IGRAPH_NO_LOOPS)); if (VECTOR(degv)[0] < 1) *updates = 0; igraph_vector_destroy(°v); IGRAPH_FINALLY_CLEAN(1); } return IGRAPH_SUCCESS; } /** * \ingroup spatialgames * \function igraph_deterministic_optimal_imitation * \brief Adopt a strategy via deterministic optimal imitation. * * A simple deterministic imitation strategy where a vertex revises its * strategy to that which yields a local optimal. Here "local" is with * respect to the immediate neighbours of the vertex. The vertex retains its * current strategy where this strategy yields a locally optimal quantity. * The quantity in this case could be a measure such as fitness. * * \param graph The graph object representing the game network. This cannot * be the empty or trivial graph, but must have at least two vertices * and one edge. If \p graph has one vertex, then no strategy update * would take place. Furthermore, if \p graph has at least two vertices * but zero edges, then strategy update would also not take place. * \param vid The vertex whose strategy is to be updated. It is assumed that * \p vid represents a vertex in \p graph. No checking is performed and * it is your responsibility to ensure that \p vid is indeed a vertex * of \p graph. If an isolated vertex is provided, i.e. the input * vertex has degree 0, then no strategy update would take place and * \p vid would retain its current strategy. Strategy update would also * not take place if the local neighbourhood of \p vid are its * in-neighbours (respectively out-neighbours), but \p vid has zero * in-neighbours (respectively out-neighbours). Loops are ignored in * computing the degree (in, out, all) of \p vid. * \param optimality Logical; controls the type of optimality to be used. * Supported values are: * \clist * \cli IGRAPH_MAXIMUM * Use maximum deterministic imitation, where the strategy of the * vertex with maximum quantity (e.g. fitness) would be adopted. We * update the strategy of \p vid to that which yields a local * maximum. * \cli IGRAPH_MINIMUM * Use minimum deterministic imitation. That is, the strategy of the * vertex with minimum quantity would be imitated. In other words, * update to the strategy that yields a local minimum. * \endclist * \param quantities A vector of quantities providing the quantity of each * vertex in \p graph. Think of each entry of the vector as being * generated by a function such as the fitness function for the game. * So if the vector represents fitness quantities, then each vector * entry is the fitness of some vertex. The length of this vector must * be the same as the number of vertices in the vertex set of \p graph. * \param strategies A vector of the current strategies for the vertex * population. The updated strategy for \p vid would be stored here. * Each strategy is identified with a nonnegative integer, whose * interpretation depends on the payoff matrix of the game. Generally * we use the strategy ID as a row or column index of the payoff * matrix. The length of this vector must be the same as the number of * vertices in the vertex set of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. If * \p graph is undirected, then we use all the immediate neighbours of * \p vid. Thus if you know that \p graph is undirected, then it is safe * to pass the value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph. Also use this value if * \p graph is undirected. * \endclist * \return The error code \p IGRAPH_EINVAL is returned in each of the * following cases: (1) Any of the parameters \p graph, \p quantities, * or \p strategies is a null pointer. (2) The vector \p quantities * or \p strategies has a length different from the number of vertices * in \p graph. (3) The parameter \p graph is the empty or null graph, * i.e. the graph with zero vertices and edges. * * Time complexity: O(2d), where d is the degree of the vertex \p vid. * * \example examples/simple/igraph_deterministic_optimal_imitation.c */ int igraph_deterministic_optimal_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_optimal_t optimality, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode) { igraph_integer_t i, k, v; igraph_real_t q; igraph_vector_t adj; igraph_bool_t updates; IGRAPH_CHECK(igraph_microscopic_standard_tests(graph, vid, quantities, strategies, mode, &updates, /*is local?*/ 1)); if (!updates) { return IGRAPH_SUCCESS; } /* Nothing to do */ /* Choose a locally optimal strategy to imitate. This can be either maximum * or minimum deterministic imitation. By now we know that the given vertex v * has degree >= 1 and at least 1 edge. Then within its immediate * neighbourhood adj(v) and including v itself, there exists a vertex whose * strategy yields a local optimal quantity. */ /* Random permutation of adj(v). This ensures that if there are multiple */ /* candidates with an optimal strategy, then we choose one such candidate */ /* at random. */ IGRAPH_VECTOR_INIT_FINALLY(&adj, 0); IGRAPH_CHECK(igraph_neighbors(graph, &adj, vid, mode)); IGRAPH_CHECK(igraph_vector_shuffle(&adj)); /* maximum deterministic imitation */ i = vid; q = (igraph_real_t)VECTOR(*quantities)[vid]; if (optimality == IGRAPH_MAXIMUM) { for (k = 0; k < igraph_vector_size(&adj); k++) { v = (igraph_integer_t) VECTOR(adj)[k]; if ((igraph_real_t)VECTOR(*quantities)[v] > q) { i = v; q = (igraph_real_t)VECTOR(*quantities)[v]; } } } else { /* minimum deterministic imitation */ for (k = 0; k < igraph_vector_size(&adj); k++) { v = (igraph_integer_t) VECTOR(adj)[k]; if ((igraph_real_t)VECTOR(*quantities)[v] < q) { i = v; q = (igraph_real_t)VECTOR(*quantities)[v]; } } } /* Now i is a vertex with a locally optimal quantity, the value of which */ /* is q. Update the strategy of vid to that of i. */ VECTOR(*strategies)[vid] = VECTOR(*strategies)[i]; igraph_vector_destroy(&adj); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \ingroup spatialgames * \function igraph_moran_process * \brief The Moran process in a network setting. * * This is an extension of the classic Moran process to a network setting. * The Moran process is a model of haploid (asexual) reproduction within a * population having a fixed size. In the network setting, the Moran process * operates on a weighted graph. At each time step a vertex a is chosen for * reproduction and another vertex b is chosen for death. Vertex a gives birth * to an identical clone c, which replaces b. Vertex c is a clone of a in that * c inherits both the current quantity (e.g. fitness) and current strategy * of a. * * * The graph G representing the game network is assumed to be simple, * i.e. free of loops and without multiple edges. If, on the other hand, G has * a loop incident on some vertex v, then it is possible that when v is chosen * for reproduction it would forgo this opportunity. In particular, when v is * chosen for reproduction and v is also chosen for death, the clone of v * would be v itself with its current vertex ID. In effect v forgoes its * chance for reproduction. * * \param graph The graph object representing the game network. This cannot * be the empty or trivial graph, but must have at least two vertices * and one edge. The Moran process will not take place in each of the * following cases: (1) If \p graph has one vertex. (2) If \p graph has * at least two vertices but zero edges. * \param weights A vector of all edge weights for \p graph. Thus weights[i] * means the weight of the edge with edge ID i. For the purpose of the * Moran process, each weight is assumed to be positive; it is your * responsibility to ensure this condition holds. The length of this * vector must be the same as the number of edges in \p graph. * \param quantities A vector of quantities providing the quantity of each * vertex in \p graph. The quantity of the new clone will be stored * here. Think of each entry of the vector as being generated by a * function such as the fitness function for the game. So if the vector * represents fitness quantities, then each vector entry is the fitness * of some vertex. The length of this vector must be the same as the * number of vertices in the vertex set of \p graph. For the purpose of * the Moran process, each vector entry is assumed to be nonnegative; * no checks will be performed for this. It is your responsibility to * ensure that at least one entry is positive. Furthermore, this vector * cannot be a vector of zeros; this condition will be checked. * \param strategies A vector of the current strategies for the vertex * population. The strategy of the new clone will be stored here. Each * strategy is identified with a nonnegative integer, whose * interpretation depends on the payoff matrix of the game. Generally * we use the strategy ID as a row or column index of the payoff * matrix. The length of this vector must be the same as the number of * vertices in the vertex set of \p graph. * \param mode Defines the sort of neighbourhood to consider for the vertex a * chosen for reproduction. This is only relevant if \p graph is * directed. If \p graph is undirected, then it is safe to pass the * value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of a. This option is only relevant when * \p graph is directed. * \cli IGRAPH_IN * Use the in-neighbours of a. Again this option is only relevant * when \p graph is directed. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of a. This option is only * relevant if \p graph is directed. Also use this value if * \p graph is undirected. * \endclist * \return The error code \p IGRAPH_EINVAL is returned in each of the following * cases: (1) Any of the parameters \p graph, \p weights, * \p quantities or \p strategies is a null pointer. (2) The vector * \p quantities or \p strategies has a length different from the * number of vertices in \p graph. (3) The vector \p weights has a * length different from the number of edges in \p graph. (4) The * parameter \p graph is the empty or null graph, i.e. the graph with * zero vertices and edges. (5) The vector \p weights, or the * combination of interest, sums to zero. (6) The vector \p quantities, * or the combination of interest, sums to zero. * * Time complexity: depends on the random number generator, but is usually * O(n) where n is the number of vertices in \p graph. * * * References: * \clist * \cli (Lieberman et al. 2005) * E. Lieberman, C. Hauert, and M. A. Nowak. Evolutionary dynamics on * graphs. \emb Nature, \eme 433(7023):312--316, 2005. * \cli (Moran 1958) * P. A. P. Moran. Random processes in genetics. \emb Mathematical * Proceedings of the Cambridge Philosophical Society, \eme 54(1):60--71, * 1958. * \endclist * * \example examples/simple/igraph_moran_process.c */ int igraph_moran_process(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode) { igraph_bool_t updates; igraph_integer_t a = -1; /* vertex chosen for reproduction */ igraph_integer_t b = -1; /* vertex chosen for death */ igraph_integer_t e, nedge, u, v; igraph_real_t r; /* random number */ igraph_vector_t deg; igraph_vector_t V; /* vector of cumulative proportionate values */ igraph_vit_t vA; /* vertex list */ igraph_eit_t eA; /* edge list */ igraph_vs_t vs; igraph_es_t es; long int i; /* don't test for vertex isolation, hence vid = -1 and islocal = 0 */ IGRAPH_CHECK(igraph_microscopic_standard_tests(graph, /*vid*/ -1, quantities, strategies, mode, &updates, /*is local?*/ 0)); if (!updates) return IGRAPH_SUCCESS; /* nothing more to do */ if (weights == NULL) IGRAPH_ERROR("Weights vector is a null pointer", IGRAPH_EINVAL); nedge = igraph_ecount(graph); if (nedge != (igraph_integer_t)igraph_vector_size(weights)) { IGRAPH_ERROR("Size of weights vector different from number of edges", IGRAPH_EINVAL); } /* Cumulative proportionate quantities. We are using the global */ /* perspective, hence islocal = 0, vid = -1 and mode = IGRAPH_ALL. */ IGRAPH_CHECK(igraph_vcumulative_proportionate_values(graph, quantities, &V, /*is local?*/ 0, /*vid*/ -1, /*mode*/ IGRAPH_ALL)); /* Choose a vertex for reproduction from among all vertices in the graph. */ /* The vertex is chosen proportionate to its quantity and such that its */ /* degree is >= 1. In case we are considering in-neighbours (respectively */ /* out-neighbours), the chosen vertex must have in-degree (respectively */ /* out-degree) >= 1. All loops will be ignored. At this point, we know */ /* that the graph has at least one edge, which may be directed or not. */ /* Furthermore the quantities of all vertices sum to a positive value. */ /* Hence at least one vertex will be chosen for reproduction. */ IGRAPH_CHECK(igraph_vs_all(&vs)); IGRAPH_FINALLY(igraph_vs_destroy, &vs); IGRAPH_CHECK(igraph_vit_create(graph, vs, &vA)); IGRAPH_FINALLY(igraph_vit_destroy, &vA); RNG_BEGIN(); r = RNG_UNIF01(); RNG_END(); i = 0; IGRAPH_VECTOR_INIT_FINALLY(°, 1); while (!IGRAPH_VIT_END(vA)) { u = (igraph_integer_t)IGRAPH_VIT_GET(vA); IGRAPH_CHECK(igraph_degree(graph, °, igraph_vss_1(u), mode, IGRAPH_NO_LOOPS)); if (VECTOR(deg)[0] < 1) { i++; IGRAPH_VIT_NEXT(vA); continue; } if (r <= VECTOR(V)[i]) { /* we have found our candidate vertex for reproduction */ a = u; break; } i++; IGRAPH_VIT_NEXT(vA); } /* By now we should have chosen a vertex for reproduction. Check this. */ assert(a >= 0); /* Cumulative proportionate weights. We are using the local perspective */ /* with respect to vertex a, which has been chosen for reproduction. */ /* The degree of a is deg(a) >= 1 with respect to the mode "mode", which */ /* can flag either the in-degree, out-degree or all degree of a. But it */ /* still might happen that the edge weights of interest would sum to zero. */ /* An error would be raised in that case. */ igraph_vector_destroy(&V); IGRAPH_CHECK(igraph_ecumulative_proportionate_values(graph, weights, &V, /*is local?*/ 1, /*vertex*/ a, mode)); /* Choose a vertex for death from among all vertices in a's perspective. */ /* Let E be all the edges in the perspective of a. If (u,v) \in E is any */ /* such edge, then we have a = u or a = v. That is, any edge in E has a */ /* for one of its endpoints. As G is assumed to be a simple graph, then */ /* exactly one of u or v is the vertex a. Without loss of generality, we */ /* assume that each edge in E has the form (a, v_i). Then the vertex v_j */ /* chosen for death is chosen proportionate to the weight of the edge */ /* (a, v_j). */ IGRAPH_CHECK(igraph_es_incident(&es, a, mode)); IGRAPH_FINALLY(igraph_es_destroy, &es); IGRAPH_CHECK(igraph_eit_create(graph, es, &eA)); IGRAPH_FINALLY(igraph_eit_destroy, &eA); RNG_BEGIN(); r = RNG_UNIF01(); RNG_END(); i = 0; while (!IGRAPH_EIT_END(eA)) { e = (igraph_integer_t)IGRAPH_EIT_GET(eA); if (r <= VECTOR(V)[i]) { /* We have found our candidate vertex for death; call this vertex b. */ /* As G is simple, then a =/= b. Check the latter condition. */ IGRAPH_CHECK(igraph_edge(graph, /*edge ID*/ e, /*tail vertex*/ &u, /*head vertex*/ &v)); if (a == u) b = v; else b = u; assert(a != b); /* always true if G is simple */ break; } i++; IGRAPH_EIT_NEXT(eA); } /* By now a vertex a is chosen for reproduction and a vertex b is chosen */ /* for death. Check that b has indeed been chosen. Clone vertex a and kill */ /* vertex b. Let the clone c have the vertex ID of b, and the strategy and */ /* quantity of a. */ assert(b >= 0); VECTOR(*quantities)[b] = VECTOR(*quantities)[a]; VECTOR(*strategies)[b] = VECTOR(*strategies)[a]; igraph_vector_destroy(°); igraph_vector_destroy(&V); igraph_vit_destroy(&vA); igraph_eit_destroy(&eA); igraph_vs_destroy(&vs); igraph_es_destroy(&es); IGRAPH_FINALLY_CLEAN(6); return IGRAPH_SUCCESS; } /** * \ingroup spatialgames * \function igraph_roulette_wheel_imitation * \brief Adopt a strategy via roulette wheel selection. * * A simple stochastic imitation strategy where a vertex revises its * strategy to that of a vertex u chosen proportionate to u's quantity * (e.g. fitness). This is a special case of stochastic imitation, where a * candidate is not chosen uniformly at random but proportionate to its * quantity. * * \param graph The graph object representing the game network. This cannot * be the empty or trivial graph, but must have at least two vertices * and one edge. If \p graph has one vertex, then no strategy update * would take place. Furthermore, if \p graph has at least two vertices * but zero edges, then strategy update would also not take place. * \param vid The vertex whose strategy is to be updated. It is assumed that * \p vid represents a vertex in \p graph. No checking is performed and * it is your responsibility to ensure that \p vid is indeed a vertex * of \p graph. If an isolated vertex is provided, i.e. the input * vertex has degree 0, then no strategy update would take place and * \p vid would retain its current strategy. Strategy update would also * not take place if the local neighbourhood of \p vid are its * in-neighbours (respectively out-neighbours), but \p vid has zero * in-neighbours (respectively out-neighbours). Loops are ignored in * computing the degree (in, out, all) of \p vid. * \param islocal Boolean; this flag controls which perspective to use in * computing the relative quantity. If true then we use the local * perspective; otherwise we use the global perspective. The local * perspective for \p vid is the set of all immediate neighbours of * \p vid. In contrast, the global perspective for \p vid is the * vertex set of \p graph. * \param quantities A vector of quantities providing the quantity of each * vertex in \p graph. Think of each entry of the vector as being * generated by a function such as the fitness function for the game. * So if the vector represents fitness quantities, then each vector * entry is the fitness of some vertex. The length of this vector must * be the same as the number of vertices in the vertex set of \p graph. * For the purpose of roulette wheel selection, each vector entry is * assumed to be nonnegative; no checks will be performed for this. It * is your responsibility to ensure that at least one entry is nonzero. * Furthermore, this vector cannot be a vector of zeros; this condition * will be checked. * \param strategies A vector of the current strategies for the vertex * population. The updated strategy for \p vid would be stored here. * Each strategy is identified with a nonnegative integer, whose * interpretation depends on the payoff matrix of the game. Generally * we use the strategy ID as a row or column index of the payoff * matrix. The length of this vector must be the same as the number of * vertices in the vertex set of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. This * is only relevant if we are considering the local perspective, i.e. if * \p islocal is true. If we are considering the global perspective, * then it is safe to pass the value \p IGRAPH_ALL here. If \p graph is * undirected, then we use all the immediate neighbours of \p vid. Thus * if you know that \p graph is undirected, then it is safe to pass the * value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a digraph and we are considering the local * perspective. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph and we are considering the local * perspective. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph. Also use this value if * \p graph is undirected or we are considering the global * perspective. * \endclist * \return The error code \p IGRAPH_EINVAL is returned in each of the following * cases: (1) Any of the parameters \p graph, \p quantities, or * \p strategies is a null pointer. (2) The vector \p quantities or * \p strategies has a length different from the number of vertices * in \p graph. (3) The parameter \p graph is the empty or null graph, * i.e. the graph with zero vertices and edges. (4) The vector * \p quantities sums to zero. * * Time complexity: O(n) where n is the number of vertices in the perspective * to consider. If we consider the global perspective, then n is the number * of vertices in the vertex set of \p graph. On the other hand, for the local * perspective n is the degree of \p vid, excluding loops. * * * Reference: * \clist * \cli (Yu & Gen 2010) * X. Yu and M. Gen. \emb Introduction to Evolutionary Algorithms. \eme * Springer, 2010, pages 18--20. * \endclist * * \example examples/simple/igraph_roulette_wheel_imitation.c */ int igraph_roulette_wheel_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_bool_t islocal, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode) { igraph_bool_t updates; igraph_integer_t u; igraph_real_t r; /* random number */ igraph_vector_t V; /* vector of cumulative proportionate quantities */ igraph_vit_t A; /* all vertices in v's perspective */ igraph_vs_t vs; long int i; IGRAPH_CHECK(igraph_microscopic_standard_tests(graph, vid, quantities, strategies, mode, &updates, islocal)); if (!updates) return IGRAPH_SUCCESS; /* nothing further to do */ /* set the perspective */ if (islocal) IGRAPH_CHECK(igraph_vs_adj(&vs, vid, mode)); else IGRAPH_CHECK(igraph_vs_all(&vs)); IGRAPH_FINALLY(igraph_vs_destroy, &vs); IGRAPH_CHECK(igraph_vit_create(graph, vs, &A)); IGRAPH_FINALLY(igraph_vit_destroy, &A); IGRAPH_CHECK(igraph_vcumulative_proportionate_values(graph, quantities, &V, islocal, vid, mode)); /* Finally, choose a vertex u to imitate. The vertex u is chosen */ /* proportionate to its quantity. In the case of a local perspective, we */ /* pretend that v's cumulative proportionate quantity has been appended to */ /* the vector V. Let V be of length n so that V[n-1] is the last element */ /* of V, and let r be a real number chosen uniformly at random from the */ /* unit interval [0,1]. If r > V[i] for all i < n, then v defaults to */ /* retaining its current strategy. Similarly in the case of the global */ /* perspective, if r > V[i] for all i < n - 1 then v would adopt the */ /* strategy of the vertex whose cumulative proportionate quantity is */ /* V[n-1]. */ /* NOTE: Here we assume that the order in which we iterate through the */ /* vertices in A is the same as the order in which we do so in the */ /* invoked function igraph_vcumulative_proportionate_values(). */ /* Otherwise we would incorrectly associate each V[i] with a vertex in A. */ RNG_BEGIN(); r = RNG_UNIF01(); RNG_END(); i = 0; while (!IGRAPH_VIT_END(A)) { if (r <= VECTOR(V)[i]) { /* We have found our candidate vertex for imitation. Update strategy */ /* of v to that of u, and exit the selection loop. */ u = (igraph_integer_t)IGRAPH_VIT_GET(A); VECTOR(*strategies)[vid] = VECTOR(*strategies)[u]; break; } i++; IGRAPH_VIT_NEXT(A); } /* By now, vertex v should either retain its current strategy or it has */ /* adopted the strategy of a vertex in its perspective. Nothing else to */ /* do, but clean up. */ igraph_vector_destroy(&V); igraph_vit_destroy(&A); igraph_vs_destroy(&vs); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /** * \ingroup spatialgames * \function igraph_stochastic_imitation * \brief Adopt a strategy via stochastic imitation with uniform selection. * * A simple stochastic imitation strategy where a vertex revises its * strategy to that of a vertex chosen uniformly at random from its local * neighbourhood. This is called stochastic imitation via uniform selection, * where the strategy to imitate is chosen via some random process. For the * purposes of this function, we use uniform selection from a pool of * candidates. * * \param graph The graph object representing the game network. This cannot * be the empty or trivial graph, but must have at least two vertices * and one edge. If \p graph has one vertex, then no strategy update * would take place. Furthermore, if \p graph has at least two vertices * but zero edges, then strategy update would also not take place. * \param vid The vertex whose strategy is to be updated. It is assumed that * \p vid represents a vertex in \p graph. No checking is performed and * it is your responsibility to ensure that \p vid is indeed a vertex * of \p graph. If an isolated vertex is provided, i.e. the input * vertex has degree 0, then no strategy update would take place and * \p vid would retain its current strategy. Strategy update would also * not take place if the local neighbourhood of \p vid are its * in-neighbours (respectively out-neighbours), but \p vid has zero * in-neighbours (respectively out-neighbours). Loops are ignored in * computing the degree (in, out, all) of \p vid. * \param algo This flag controls which algorithm to use in stochastic * imitation. Supported values are: * \clist * \cli IGRAPH_IMITATE_AUGMENTED * Augmented imitation. Vertex \p vid imitates the strategy of the * chosen vertex u provided that doing so would increase the * quantity (e.g. fitness) of \p vid. Augmented imitation can be * thought of as "imitate if better". * \cli IGRAPH_IMITATE_BLIND * Blind imitation. Vertex \p vid blindly imitates the strategy of * the chosen vertex u, regardless of whether doing so would * increase or decrease the quantity of \p vid. * \cli IGRAPH_IMITATE_CONTRACTED * Contracted imitation. Here vertex \p vid imitates the strategy of * the chosen vertex u if doing so would decrease the quantity of * \p vid. Think of contracted imitation as "imitate if worse". * \endclist * \param quantities A vector of quantities providing the quantity of each * vertex in \p graph. Think of each entry of the vector as being * generated by a function such as the fitness function for the game. * So if the vector represents fitness quantities, then each vector * entry is the fitness of some vertex. The length of this vector must * be the same as the number of vertices in the vertex set of \p graph. * \param strategies A vector of the current strategies for the vertex * population. The updated strategy for \p vid would be stored here. * Each strategy is identified with a nonnegative integer, whose * interpretation depends on the payoff matrix of the game. Generally * we use the strategy ID as a row or column index of the payoff * matrix. The length of this vector must be the same as the number of * vertices in the vertex set of \p graph. * \param mode Defines the sort of neighbourhood to consider for \p vid. If * \p graph is undirected, then we use all the immediate neighbours of * \p vid. Thus if you know that \p graph is undirected, then it is safe * to pass the value \p IGRAPH_ALL here. Supported values are: * \clist * \cli IGRAPH_OUT * Use the out-neighbours of \p vid. This option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_IN * Use the in-neighbours of \p vid. Again this option is only relevant * when \p graph is a directed graph. * \cli IGRAPH_ALL * Use both the in- and out-neighbours of \p vid. This option is only * relevant if \p graph is a digraph. Also use this value if * \p graph is undirected. * \endclist * \return The error code \p IGRAPH_EINVAL is returned in each of the following * cases: (1) Any of the parameters \p graph, \p quantities, or * \p strategies is a null pointer. (2) The vector \p quantities or * \p strategies has a length different from the number of vertices * in \p graph. (3) The parameter \p graph is the empty or null graph, * i.e. the graph with zero vertices and edges. (4) The parameter * \p algo refers to an unsupported stochastic imitation algorithm. * * Time complexity: depends on the uniform random number generator, but should * usually be O(1). * * \example examples/simple/igraph_stochastic_imitation.c */ int igraph_stochastic_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_imitate_algorithm_t algo, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode) { igraph_bool_t updates; igraph_integer_t u; igraph_vector_t adj; int i; /* sanity checks */ if (algo != IGRAPH_IMITATE_AUGMENTED && algo != IGRAPH_IMITATE_BLIND && algo != IGRAPH_IMITATE_CONTRACTED) { IGRAPH_ERROR("Unsupported stochastic imitation algorithm", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_microscopic_standard_tests(graph, vid, quantities, strategies, mode, &updates, /*is local?*/ 1)); if (!updates) return IGRAPH_SUCCESS; /* nothing more to do */ /* immediate neighbours of v */ IGRAPH_VECTOR_INIT_FINALLY(&adj, 0); IGRAPH_CHECK(igraph_neighbors(graph, &adj, vid, mode)); /* Blind imitation. Let v be the vertex whose strategy we want to revise. */ /* Choose a vertex u uniformly at random from the immediate neighbours of */ /* v, including v itself. Then blindly update the strategy of v to that of */ /* u, irrespective of whether doing so would increase or decrease the */ /* quantity (e.g. fitness) of v. Here v retains its current strategy if */ /* the chosen vertex u is indeed v itself. */ if (algo == IGRAPH_IMITATE_BLIND) { IGRAPH_CHECK(igraph_vector_push_back(&adj, vid)); RNG_BEGIN(); i = (int) RNG_INTEGER(0, igraph_vector_size(&adj) - 1); RNG_END(); u = (igraph_integer_t) VECTOR(adj)[i]; VECTOR(*strategies)[vid] = VECTOR(*strategies)[u]; } /* Augmented imitation. Let v be the vertex whose strategy we want to */ /* revise. Let f be the quantity function for the game. Choose a vertex u */ /* uniformly at random from the immediate neighbours of v; do not include */ /* v. Then v imitates the strategy of u if f(u) > f(v). Otherwise v */ /* retains its current strategy. */ else if (algo == IGRAPH_IMITATE_AUGMENTED) { RNG_BEGIN(); i = (int) RNG_INTEGER(0, igraph_vector_size(&adj) - 1); RNG_END(); u = (igraph_integer_t) VECTOR(adj)[i]; if (VECTOR(*quantities)[u] > VECTOR(*quantities)[vid]) VECTOR(*strategies)[vid] = VECTOR(*strategies)[u]; } /* Contracted imitation. Let v be the vertex whose strategy we want to */ /* update and let f be the quantity function for the game. Choose a vertex */ /* u uniformly at random from the immediate neighbours of v, excluding v */ /* itself. Then v imitates the strategy of u provided that f(u) < f(v). */ /* Otherwise v retains its current strategy. */ else if (algo == IGRAPH_IMITATE_CONTRACTED) { RNG_BEGIN(); i = (int) RNG_INTEGER(0, igraph_vector_size(&adj) - 1); RNG_END(); u = (igraph_integer_t) VECTOR(adj)[i]; if (VECTOR(*quantities)[u] < VECTOR(*quantities)[vid]) VECTOR(*strategies)[vid] = VECTOR(*strategies)[u]; } /* clean up */ igraph_vector_destroy(&adj); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } igraph/src/vector_ptr.c0000644000175100001440000004604713431000472014671 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_vector_ptr.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \section about_igraph_vector_ptr_objects Pointer vectors * (igraph_vector_ptr_t) * * The \type igraph_vector_ptr_t data type is very similar to * the \type igraph_vector_t type, but it stores generic pointers instead of * real numbers. * * This type has the same space complexity as \type * igraph_vector_t, and most implemented operations work the same way * as for \type igraph_vector_t. * * This type is mostly used to pass to or receive from a set of * graphs to some \a igraph functions, such as \ref * igraph_decompose(), which decomposes a graph to connected * components. * * The same \ref VECTOR macro used for ordinary vectors can be * used for pointer vectors as well, please note that a typeless * generic pointer will be provided by this macro and you may need to * cast it to a specific pointer before starting to work with it. * * Pointer vectors may have an associated item destructor function * which takes a pointer and returns nothing. The item destructor will * be called on each item in the pointer vector when it is destroyed by * \ref igraph_vector_ptr_destroy() or \ref igraph_vector_ptr_destroy_all(), * or when its elements are freed by \ref igraph_vector_ptr_free_all(). * Note that the semantics of an item destructor does not coincide with * C++ destructors; for instance, when a pointer vector is resized to a * smaller size, the extra items will \em not be destroyed automatically! * Nevertheless, item destructors may become handy in many cases; for * instance, a vector of graphs generated by \ref igraph_decompose() can * be destroyed with a single call to \ref igraph_vector_ptr_destroy_all() * if the item destructor is set to \ref igraph_destroy(). */ /** * \ingroup vectorptr * \function igraph_vector_ptr_init * \brief Initialize a pointer vector (constructor). * * * This is the constructor of the pointer vector data type. All * pointer vectors constructed this way should be destroyed via * calling \ref igraph_vector_ptr_destroy(). * \param v Pointer to an uninitialized * igraph_vector_ptr_t object, to be created. * \param size Integer, the size of the pointer vector. * \return Error code: * \c IGRAPH_ENOMEM if out of memory * * Time complexity: operating system dependent, the amount of \quote * time \endquote required to allocate \p size elements. */ int igraph_vector_ptr_init (igraph_vector_ptr_t* v, int long size) { long int alloc_size= size > 0 ? size : 1; assert(v != NULL); if (size < 0) { size=0; } v->stor_begin=igraph_Calloc(alloc_size, void*); if (v->stor_begin==0) { IGRAPH_ERROR("vector ptr init failed", IGRAPH_ENOMEM); } v->stor_end=v->stor_begin + alloc_size; v->end=v->stor_begin+size; v->item_destructor=0; return 0; } /** */ const igraph_vector_ptr_t *igraph_vector_ptr_view (const igraph_vector_ptr_t *v, void *const *data, long int length) { igraph_vector_ptr_t *v2=(igraph_vector_ptr_t*) v; v2->stor_begin=(void **)data; v2->stor_end=(void**)data+length; v2->end=v2->stor_end; v2->item_destructor=0; return v; } /** * \ingroup vectorptr * \function igraph_vector_ptr_destroy * \brief Destroys a pointer vector. * * * The destructor for pointer vectors. * \param v Pointer to the pointer vector to destroy. * * Time complexity: operating system dependent, the \quote time * \endquote required to deallocate O(n) bytes, n is the number of * elements allocated for the pointer vector (not necessarily the * number of elements in the vector). */ void igraph_vector_ptr_destroy (igraph_vector_ptr_t* v) { assert(v != 0); if (v->stor_begin != 0) { igraph_Free(v->stor_begin); v->stor_begin = NULL; } } void igraph_i_vector_ptr_call_item_destructor_all(igraph_vector_ptr_t* v) { void **ptr; if (v->item_destructor != 0) { for (ptr=v->stor_begin; ptrend; ptr++) { if (*ptr != 0) v->item_destructor(*ptr); } } } /** * \ingroup vectorptr * \function igraph_vector_ptr_free_all * \brief Frees all the elements of a pointer vector. * * If an item destructor is set for this pointer vector, this function will * first call the destructor on all elements of the vector and then * free all the elements using free(). If an item destructor is not set, * the elements will simply be freed. * * \param v Pointer to the pointer vector whose elements will be freed. * * Time complexity: operating system dependent, the \quote time * \endquote required to call the destructor n times and then * deallocate O(n) pointers, each pointing to a memory area of * arbitrary size. n is the number of elements in the pointer vector. */ void igraph_vector_ptr_free_all (igraph_vector_ptr_t* v) { void **ptr; assert(v != 0); assert(v->stor_begin != 0); igraph_i_vector_ptr_call_item_destructor_all(v); for (ptr=v->stor_begin; ptrend; ptr++) { igraph_Free(*ptr); } } /** * \ingroup vectorptr * \function igraph_vector_ptr_destroy_all * \brief Frees all the elements and destroys the pointer vector. * * This function is equivalent to \ref igraph_vector_ptr_free_all() * followed by \ref igraph_vector_ptr_destroy(). * * \param v Pointer to the pointer vector to destroy. * * Time complexity: operating system dependent, the \quote time * \endquote required to deallocate O(n) pointers, each pointing to * a memory area of arbitrary size, plus the \quote time \endquote * required to deallocate O(n) bytes, n being the number of elements * allocated for the pointer vector (not necessarily the number of * elements in the vector). */ void igraph_vector_ptr_destroy_all (igraph_vector_ptr_t* v) { assert(v != 0); assert(v->stor_begin != 0); igraph_vector_ptr_free_all(v); igraph_vector_ptr_set_item_destructor(v, 0); igraph_vector_ptr_destroy(v); } /** * \ingroup vectorptr * \brief Reserves memory for a pointer vector for later use. * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_vector_ptr_reserve (igraph_vector_ptr_t* v, long int size) { long int actual_size=igraph_vector_ptr_size(v); void **tmp; assert(v != NULL); assert(v->stor_begin != NULL); if (size <= igraph_vector_ptr_size(v)) { return 0; } tmp=igraph_Realloc(v->stor_begin, (size_t) size, void*); if (tmp==0) { IGRAPH_ERROR("vector ptr reserve failed", IGRAPH_ENOMEM); } v->stor_begin=tmp; v->stor_end=v->stor_begin + size; v->end=v->stor_begin+actual_size; return 0; } /** * \ingroup vectorptr * \brief Decides whether the pointer vector is empty. */ igraph_bool_t igraph_vector_ptr_empty (const igraph_vector_ptr_t* v) { assert(v != NULL); assert(v->stor_begin != NULL); return v->stor_begin == v->end; } /** * \ingroup vectorptr * \function igraph_vector_ptr_size * \brief Gives the number of elements in the pointer vector. * * \param v The pointer vector object. * \return The size of the object, ie. the number of pointers stored. * * Time complexity: O(1). */ long int igraph_vector_ptr_size (const igraph_vector_ptr_t* v) { assert(v != NULL); /* assert(v->stor_begin != NULL); */ /* TODO */ return v->end - v->stor_begin; } /** * \ingroup vectorptr * \function igraph_vector_ptr_clear * \brief Removes all elements from a pointer vector. * * * This function resizes a pointer to vector to zero length. Note that * the pointed objects are \em not deallocated, you should call * free() on them, or make sure that their allocated memory is freed * in some other way, you'll get memory leaks otherwise. If you have * set up an item destructor earlier, the destructor will be called * on every element. * * * Note that the current implementation of this function does * \em not deallocate the memory required for storing the * pointers, so making a pointer vector smaller this way does not give * back any memory. This behavior might change in the future. * \param v The pointer vector to clear. * * Time complexity: O(1). */ void igraph_vector_ptr_clear (igraph_vector_ptr_t* v) { assert(v != NULL); assert(v->stor_begin != NULL); igraph_i_vector_ptr_call_item_destructor_all(v); v->end = v->stor_begin; } /** * \ingroup vectorptr * \function igraph_vector_ptr_push_back * \brief Appends an element to the back of a pointer vector. * * \param v The pointer vector. * \param e The new element to include in the pointer vector. * \return Error code. * \sa igraph_vector_push_back() for the corresponding operation of * the ordinary vector type. * * Time complexity: O(1) or O(n), n is the number of elements in the * vector. The pointer vector implementation ensures that n subsequent * push_back operations need O(n) time to complete. */ int igraph_vector_ptr_push_back (igraph_vector_ptr_t* v, void* e) { assert(v != NULL); assert(v->stor_begin != NULL); /* full, allocate more storage */ if (v->stor_end == v->end) { long int new_size = igraph_vector_ptr_size(v) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(igraph_vector_ptr_reserve(v, new_size)); } *(v->end) = e; v->end += 1; return 0; } void *igraph_vector_ptr_pop_back (igraph_vector_ptr_t *v) { assert(v != NULL); assert(v->stor_begin != NULL); assert(v->stor_begin != v->end); v->end -= 1; return *(v->end); } /** * \ingroup vectorptr * \function igraph_vector_ptr_insert * \brief Inserts a single element into a pointer vector. * * Note that this function does not do range checking. Insertion will shift the * elements from the position given to the end of the vector one position to the * right, and the new element will be inserted in the empty space created at * the given position. The size of the vector will increase by one. * * \param v The pointer vector object. * \param pos The position where the new element is inserted. * \param e The inserted element */ int igraph_vector_ptr_insert(igraph_vector_ptr_t* v, long int pos, void* e) { long int size = igraph_vector_ptr_size(v); IGRAPH_CHECK(igraph_vector_ptr_resize(v, size+1)); if (posstor_begin+pos+1, v->stor_begin+pos, sizeof(void*) * (size_t) (size-pos)); } v->stor_begin[pos] = e; return 0; } /** * \ingroup vectorptr * \function igraph_vector_ptr_e * \brief Access an element of a pointer vector. * * \param v Pointer to a pointer vector. * \param pos The index of the pointer to return. * \return The pointer at \p pos position. * * Time complexity: O(1). */ void* igraph_vector_ptr_e (const igraph_vector_ptr_t* v, long int pos) { assert(v != NULL); assert(v->stor_begin != NULL); return * (v->stor_begin + pos); } /** * \ingroup vectorptr * \function igraph_vector_ptr_set * \brief Assign to an element of a pointer vector. * * \param v Pointer to a pointer vector. * \param pos The index of the pointer to update. * \param value The new pointer to set in the vector. * * Time complexity: O(1). */ void igraph_vector_ptr_set (igraph_vector_ptr_t* v, long int pos, void* value) { assert(v != NULL); assert(v->stor_begin != NULL); *(v->stor_begin + pos) = value; } /** * \ingroup vectorptr * \brief Set all elements of a pointer vector to the NULL pointer. */ void igraph_vector_ptr_null (igraph_vector_ptr_t* v) { assert(v != NULL); assert(v->stor_begin != NULL); if (igraph_vector_ptr_size(v)>0) { memset(v->stor_begin, 0, sizeof(void*) * (size_t) igraph_vector_ptr_size(v)); } } /** * \ingroup vectorptr * \function igraph_vector_ptr_resize * \brief Resizes a pointer vector. * * * Note that if a vector is made smaller the pointed object are not * deallocated by this function and the item destructor is not called * on the extra elements. * * \param v A pointer vector. * \param newsize The new size of the pointer vector. * \return Error code. * * Time complexity: O(1) if the vector if made smaller. Operating * system dependent otherwise, the amount of \quote time \endquote * needed to allocate the memory for the vector elements. */ int igraph_vector_ptr_resize(igraph_vector_ptr_t* v, long int newsize) { IGRAPH_CHECK(igraph_vector_ptr_reserve(v, newsize)); v->end = v->stor_begin+newsize; return 0; } /** * \ingroup vectorptr * \brief Initializes a pointer vector from an array (constructor). * * \return Error code: * \c IGRAPH_ENOMEM if out of memory */ int igraph_vector_ptr_init_copy(igraph_vector_ptr_t *v, void* *data, long int length) { v->stor_begin=igraph_Calloc(length, void*); if (v->stor_begin==0) { IGRAPH_ERROR("cannot init ptr vector from array", IGRAPH_ENOMEM); } v->stor_end=v->stor_begin+length; v->end=v->stor_end; v->item_destructor=0; memcpy(v->stor_begin, data, (size_t) length * sizeof(void*)); return 0; } /** * \ingroup vectorptr * \brief Copy the contents of a pointer vector to a regular C array. */ void igraph_vector_ptr_copy_to(const igraph_vector_ptr_t *v, void** to) { assert(v != NULL); assert(v->stor_begin != NULL); if (v->end != v->stor_begin) { memcpy(to, v->stor_begin, sizeof(void*) * (size_t) (v->end - v->stor_begin)); } } /** * \ingroup vectorptr * \function igraph_vector_ptr_copy * \brief Copy a pointer vector (constructor). * * * This function creates a pointer vector by copying another one. This * is shallow copy, only the pointers in the vector will be copied. * * * It is potentially dangerous to copy a pointer vector with an associated * item destructor. The copied vector will inherit the item destructor, * which may cause problems when both vectors are destroyed as the items * might get destroyed twice. Make sure you know what you are doing when * copying a pointer vector with an item destructor, or unset the item * destructor on one of the vectors later. * * \param to Pointer to an uninitialized pointer vector object. * \param from A pointer vector object. * \return Error code: * \c IGRAPH_ENOMEM if out of memory * * Time complexity: O(n) if allocating memory for n elements can be * done in O(n) time. */ int igraph_vector_ptr_copy(igraph_vector_ptr_t *to, const igraph_vector_ptr_t *from) { assert(from != NULL); /* assert(from->stor_begin != NULL); */ /* TODO */ to->stor_begin=igraph_Calloc(igraph_vector_ptr_size(from), void*); if (to->stor_begin==0) { IGRAPH_ERROR("cannot copy ptr vector", IGRAPH_ENOMEM); } to->stor_end=to->stor_begin+igraph_vector_ptr_size(from); to->end=to->stor_end; to->item_destructor=from->item_destructor; memcpy(to->stor_begin, from->stor_begin, (size_t) igraph_vector_ptr_size(from)*sizeof(void*)); return 0; } /** * \ingroup vectorptr * \brief Remove an element from a pointer vector. */ void igraph_vector_ptr_remove(igraph_vector_ptr_t *v, long int pos) { assert(v != NULL); assert(v->stor_begin != NULL); if (pos+1stor_begin+pos, v->stor_begin+pos+1, sizeof(void*) * (size_t) (igraph_vector_ptr_size(v)-pos-1)); } v->end--; } /** * \ingroup vectorptr * \brief Sort the pointer vector based on an external comparison function * * Sometimes it is necessary to sort the pointers in the vector based on * the property of the element being referenced by the pointer. This * function allows us to sort the vector based on an arbitrary external * comparison function which accepts two \c void* pointers \c p1 and \c p2 * and returns an integer less than, equal to or greater than zero if the * first argument is considered to be respectively less than, equal to, or * greater than the second. \c p1 and \c p2 will point to the pointer in the * vector, so they have to be double-dereferenced if one wants to get access * to the underlying object the address of which is stored in \c v . */ void igraph_vector_ptr_sort(igraph_vector_ptr_t *v, int (*compar)(const void*, const void*)) { qsort(v->stor_begin, (size_t) igraph_vector_ptr_size(v), sizeof(void*), compar); } int igraph_vector_ptr_index_int(igraph_vector_ptr_t *v, const igraph_vector_int_t *idx) { void **tmp; int i, n=igraph_vector_int_size(idx); tmp=igraph_Calloc(n, void*); if (!tmp) { IGRAPH_ERROR("Cannot index pointer vector", IGRAPH_ENOMEM); } for (i=0; istor_begin); v->stor_begin = tmp; v->stor_end = v->end = tmp + n; return 0; } int igraph_vector_ptr_append (igraph_vector_ptr_t *to, const igraph_vector_ptr_t *from) { long int origsize=igraph_vector_ptr_size(to); long int othersize=igraph_vector_ptr_size(from); long int i; IGRAPH_CHECK(igraph_vector_ptr_resize(to, origsize+othersize)); for (i=0; istor_begin[origsize]=from->stor_begin[i]; } return 0; } /** * \ingroup vectorptr * \function igraph_vector_ptr_set_item_destructor * \brief Sets the item destructor for this pointer vector. * * The item destructor is a function which will be called on every non-null * pointer stored in this vector when \ref igraph_vector_ptr_destroy(), * igraph_vector_ptr_destroy_all() or \ref igraph_vector_ptr_free_all() * is called. * * \return The old item destructor. * * Time complexity: O(1). */ igraph_finally_func_t* igraph_vector_ptr_set_item_destructor( igraph_vector_ptr_t *v, igraph_finally_func_t *func) { igraph_finally_func_t* result = v->item_destructor; v->item_destructor = func; return result; } /** * \ingroup vectorptr * \function igraph_vector_ptr_get_item_destructor * \brief Gets the current item destructor for this pointer vector. * * The item destructor is a function which will be called on every non-null * pointer stored in this vector when \ref igraph_vector_ptr_destroy(), * igraph_vector_ptr_destroy_all() or \ref igraph_vector_ptr_free_all() * is called. * * \return The current item destructor. * * Time complexity: O(1). */ igraph_finally_func_t* igraph_vector_ptr_get_item_destructor(const igraph_vector_ptr_t *v) { assert(v != 0); return v->item_destructor; } igraph/src/version.c0000644000175100001440000000414713431000472014162 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2008-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_version.h" #include static const char *igraph_version_string=IGRAPH_VERSION; /** * \function igraph_version * Return the version of the igraph C library * * \param version_string Pointer to a string pointer. If not null, it * is set to the igraph version string, e.g. "0.6" or "0.5.3". This * string should not be modified or deallocated. * \param major If not a null pointer, then it is set to the major * igraph version. E.g. for version "0.5.3" this is 0. * \param minor If not a null pointer, then it is set to the minor * igraph version. E.g. for version "0.5.3" this is 5. * \param subminor If not a null pointer, then it is set to the * subminor igraph version. E.g. for version "0.5.3" this is 3. * \return Error code. * * Time complexity: O(1). * * \example examples/simple/igraph_version.c */ int igraph_version(const char **version_string, int *major, int *minor, int *subminor) { int i1, i2, i3; int *p1= major ? major : &i1, *p2= minor ? minor : &i2, *p3= subminor ? subminor : &i3; if (version_string) { *version_string = igraph_version_string; } *p1 = *p2 = *p3 = 0; sscanf(IGRAPH_VERSION, "%i.%i.%i", p1, p2, p3); return 0; } igraph/src/triangles_template.h0000644000175100001440000000714113431000472016362 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ long int no_of_nodes=igraph_vcount(graph); long int node, i, j, nn; igraph_adjlist_t allneis; igraph_vector_int_t *neis1, *neis2; long int neilen1, neilen2, deg1; long int *neis; long int maxdegree; igraph_vector_int_t order; igraph_vector_int_t rank; igraph_vector_t degree; igraph_vector_int_init(&order, no_of_nodes); IGRAPH_FINALLY(igraph_vector_int_destroy, &order); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, IGRAPH_LOOPS)); maxdegree=(long int) igraph_vector_max(°ree)+1; igraph_vector_order1_int(°ree, &order, maxdegree); igraph_vector_int_init(&rank, no_of_nodes); IGRAPH_FINALLY(igraph_vector_int_destroy, &rank); for (i=0; i=0; nn--) { node=VECTOR(order)[nn]; IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_adjlist_get(&allneis, node); neilen1=igraph_vector_int_size(neis1); deg1=(long int) VECTOR(degree)[node]; /* Mark the neighbors of the node */ for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_structural.h" #include "igraph_error.h" #include "igraph_adjlist.h" #include "igraph_interface.h" /** * \function igraph_maximum_cardinality_search * Maximum cardinality search * * This function implements the maximum cardinality search algorithm * discussed in * Robert E Tarjan and Mihalis Yannakakis: Simple linear-time * algorithms to test chordality of graphs, test acyclicity of * hypergraphs, and selectively reduce acyclic hypergraphs. * SIAM Journal of Computation 13, 566--579, 1984. * * \param graph The input graph. Can be directed, but the direction * of the edges is ignored. * \param alpha Pointer to an initialized vector, the result is stored here. * It will be resized, as needed. Upon return it contains * the rank of the each vertex. * \param alpham1 Pointer to an initialized vector or a \c NULL * pointer. If not \c NULL, then the inverse of \p alpha is stored * here. * \return Error code. * * Time complexity: O(|V|+|E|), linear in terms of the number of * vertices and edges. * * \sa \ref igraph_is_chordal(). */ int igraph_maximum_cardinality_search(const igraph_t *graph, igraph_vector_t *alpha, igraph_vector_t *alpham1) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_long_t size; igraph_vector_long_t head, next, prev; /* doubly linked list with head */ long int i; igraph_adjlist_t adjlist; /***************/ /* local j, v; */ /***************/ long int j, v; if (no_of_nodes == 0) { igraph_vector_clear(alpha); if (alpham1) igraph_vector_clear(alpham1); return IGRAPH_SUCCESS; } IGRAPH_CHECK(igraph_vector_long_init(&size, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &size); IGRAPH_CHECK(igraph_vector_long_init(&head, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &head); IGRAPH_CHECK(igraph_vector_long_init(&next, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &next); IGRAPH_CHECK(igraph_vector_long_init(&prev, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &prev); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_vector_resize(alpha, no_of_nodes)); if (alpham1) { IGRAPH_CHECK(igraph_vector_resize(alpham1, no_of_nodes)); } /***********************************************/ /* for i in [0,n-1] -> set(i) := emptyset rof; */ /***********************************************/ /* nothing to do, 'head' contains all zeros */ /*********************************************************/ /* for v in vertices -> size(v):=0; add v to set(0) rof; */ /*********************************************************/ VECTOR(head)[0]=1; for (v=0; v=1 -> */ /**************/ while (i>=1) { long int x, k, len; igraph_vector_int_t *neis; /********************************/ /* v := delete any from set(j) */ /********************************/ v=VECTOR(head)[j]-1; x=VECTOR(next)[v]; VECTOR(head)[j]=x; if (x != 0) { VECTOR(prev)[x-1]=0; } /*************************************************/ /* alpha(v) := i; alpham1(i) := v; size(v) := -1 */ /*************************************************/ VECTOR(*alpha)[v]=i-1; if (alpham1) { VECTOR(*alpham1)[i-1]=v; } VECTOR(size)[v]=-1; /********************************************/ /* for {v,w} in E such that size(w) >= 0 -> */ /********************************************/ neis=igraph_adjlist_get(&adjlist, v); len=igraph_vector_int_size(neis); for (k=0; k= 0) { /******************************/ /* delete w from set(size(w)) */ /******************************/ long int nw=VECTOR(next)[w]; long int pw=VECTOR(prev)[w]; if (nw != 0) { VECTOR(prev)[nw-1] = pw; } if (pw != 0) { VECTOR(next)[pw-1] = nw; } else { VECTOR(head)[ws]=nw; } /******************************/ /* size(w) := size(w)+1 */ /******************************/ VECTOR(size)[w] += 1; /******************************/ /* add w to set(size(w)) */ /******************************/ ws=VECTOR(size)[w]; nw=VECTOR(head)[ws]; VECTOR(next)[w]=nw; VECTOR(prev)[w]=0; if (nw != 0) { VECTOR(prev)[nw-1]=w+1; } VECTOR(head)[ws]=w+1; } } /***********************/ /* i := i-1; j := j+1; */ /***********************/ i -= 1; j += 1; /*********************************************/ /* do j>=0 and set(j)=emptyset -> j:=j-1; od */ /*********************************************/ if (j < no_of_nodes) { while (j>=0 && VECTOR(head)[j]==0) j--; } } igraph_adjlist_destroy(&adjlist); igraph_vector_long_destroy(&prev); igraph_vector_long_destroy(&next); igraph_vector_long_destroy(&head); igraph_vector_long_destroy(&size); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_is_chordal * Decides whether a graph is chordal * * A graph is chordal if each of its cycles of four or more nodes * has a chord, which is an edge joining two nodes that are not * adjacent in the cycle. An equivalent definition is that any * chordless cycles have at most three nodes. * * If either \p alpha or \p alpha1 is given, then the other is * calculated by taking simply the inverse. If neither are given, * then \ref igraph_maximum_cardinality_search() is called to calculate * them. * \param graph The input graph, it might be directed, but edge * direction is ignored. * \param alpha Either an alpha vector coming from * \ref igraph_maximum_cardinality_search() (on the same graph), or a * null pointer. * \param alpham1 Either an inverse alpha vector coming from \ref * igraph_maximum_cardinality_search() (on the same graph) or a null * pointer. * \param chordal Pointer to a boolean, the result is stored here. * \param fill_in Pointer to an initialized vector, or a null * pointer. If not a null pointer, then the fill-in of the graph is * stored here. The fill-in is the set of edges that are needed to * make the graph chordal. The vector is resized as needed. * \param newgraph Pointer to an uninitialized graph, or a null * pointer. If not a null pointer, then a new triangulated graph is * created here. This essentially means adding the fill-in edges to * the original graph. * \return Error code. * * Time complexity: O(n). * * \sa \ref igraph_maximum_cardinality_search(). */ int igraph_is_chordal(const igraph_t *graph, const igraph_vector_t *alpha, const igraph_vector_t *alpham1, igraph_bool_t *chordal, igraph_vector_t *fill_in, igraph_t *newgraph) { long int no_of_nodes=igraph_vcount(graph); const igraph_vector_t *my_alpha=alpha, *my_alpham1=alpham1; igraph_vector_t v_alpha, v_alpham1; igraph_vector_long_t f, index; long int i; igraph_adjlist_t adjlist; igraph_vector_long_t mark; igraph_bool_t calc_edges= fill_in || newgraph; igraph_vector_t *my_fill_in=fill_in, v_fill_in; /*****************/ /* local v, w, x */ /*****************/ long int v, w, x; if (!chordal && !calc_edges) { /* Nothing to calculate */ return 0; } if (!alpha && !alpham1) { IGRAPH_VECTOR_INIT_FINALLY(&v_alpha, no_of_nodes); my_alpha=&v_alpha; IGRAPH_VECTOR_INIT_FINALLY(&v_alpham1, no_of_nodes); my_alpham1=&v_alpham1; IGRAPH_CHECK(igraph_maximum_cardinality_search(graph, (igraph_vector_t*) my_alpha, (igraph_vector_t*) my_alpham1)); } else if (alpha && !alpham1) { long int v; IGRAPH_VECTOR_INIT_FINALLY(&v_alpham1, no_of_nodes); my_alpham1=&v_alpham1; for (v=0; v */ /*********************/ for (i=0; i */ /******************************************/ neis=igraph_adjlist_get(&adjlist, w); len=igraph_vector_int_size(neis); for (j=0; j= i) { continue; } /**********/ /* x := v */ /**********/ x=v; /********************/ /* do index(x) */ /********************/ while (VECTOR(index)[x] < i) { /******************/ /* index(x) := i; */ /******************/ VECTOR(index)[x] = i; /**********************************/ /* add {x,w} to E union F(alpha); */ /**********************************/ if (VECTOR(mark)[x] != w+1) { if (chordal) { *chordal=0; } if (my_fill_in) { IGRAPH_CHECK(igraph_vector_push_back(my_fill_in, x)); IGRAPH_CHECK(igraph_vector_push_back(my_fill_in, w)); } if (!calc_edges) { /* make sure that we exit from all loops */ i=no_of_nodes; j=len; break; } } /*************/ /* x := f(x) */ /*************/ x=VECTOR(f)[x]; } /* while (VECTOR(index)[x] < i) */ /*****************************/ /* if (f(x)=x -> f(x):=w; fi */ /*****************************/ if (VECTOR(f)[x] == x) { VECTOR(f)[x] = w; } } } igraph_vector_long_destroy(&mark); igraph_adjlist_destroy(&adjlist); igraph_vector_long_destroy(&index); igraph_vector_long_destroy(&f); IGRAPH_FINALLY_CLEAN(4); if (newgraph) { IGRAPH_CHECK(igraph_copy(newgraph, graph)); IGRAPH_FINALLY(igraph_destroy, newgraph); IGRAPH_CHECK(igraph_add_edges(newgraph, my_fill_in, 0)); IGRAPH_FINALLY_CLEAN(1); } if (!fill_in && newgraph) { igraph_vector_destroy(&v_fill_in); IGRAPH_FINALLY_CLEAN(1); } if (!alpha && !alpham1) { igraph_vector_destroy(&v_alpham1); igraph_vector_destroy(&v_alpha); IGRAPH_FINALLY_CLEAN(2); } else if (alpha && !alpham1) { igraph_vector_destroy(&v_alpham1); IGRAPH_FINALLY_CLEAN(1); } else if (!alpha && alpham1) { igraph_vector_destroy(&v_alpha); IGRAPH_FINALLY_CLEAN(1); } return 0; } igraph/src/foreign-dl-header.h0000644000175100001440000000243113431000472015750 0ustar hornikusers/* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" typedef enum { IGRAPH_DL_MATRIX, IGRAPH_DL_EDGELIST1, IGRAPH_DL_NODELIST1 } igraph_i_dl_type_t; typedef struct { void *scanner; int eof; int mode; long int n; long int from, to; igraph_vector_t edges; igraph_vector_t weights; igraph_strvector_t labels; igraph_trie_t trie; igraph_i_dl_type_t type; char errmsg[300]; } igraph_i_dl_parsedata_t; igraph/src/foreign-gml-header.h0000644000175100001440000000176713431000472016143 0ustar hornikusers/* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_gml_tree.h" typedef struct { void *scanner; int eof; char errmsg[300]; igraph_gml_tree_t *tree; } igraph_i_gml_parsedata_t; igraph/src/scg_exact_scg.c0000644000175100001440000000410213431000472015260 0ustar hornikusers/* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * The exact_coarse_graining function labels all the objects whose * components in 'v' are equal. The result is stored in 'gr'. Labels * are positive consecutive integers starting from 0. * See also Section 5.4.1 (last paragraph) of the above reference. */ #include "igraph_memory.h" #include "scg_headers.h" #include int igraph_i_exact_coarse_graining(const igraph_real_t *v, int *gr, const int n) { int i, gr_nb; igraph_i_scg_indval_t *w = igraph_Calloc(n, igraph_i_scg_indval_t); if (!w) { IGRAPH_ERROR("SCG error", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, w); for(i=0; i 1e-14 ) { gr_nb++; } gr[w[i].ind] = gr_nb; } igraph_Free(w); IGRAPH_FINALLY_CLEAN(1); return 0; } igraph/src/DensityGrid.h0000644000175100001440000000533613431000472014730 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __DENSITY_GRID_H__ #define __DENSITY_GRID_H__ // Compile time adjustable parameters #include using namespace std; #include "drl_layout.h" #include "drl_Node.h" #ifdef MUSE_MPI #include #endif namespace drl { class DensityGrid { public: // Methods void Init(); void Subtract(Node &n, bool first_add, bool fine_first_add, bool fineDensity); void Add(Node &n, bool fineDensity ); float GetDensity(float Nx, float Ny, bool fineDensity); // Contructor/Destructor DensityGrid() {}; ~DensityGrid(); private: // Private Members void Subtract( Node &N ); void Add( Node &N ); void fineSubtract( Node &N ); void fineAdd( Node &N ); // new dynamic variables -- SBM float (*fall_off)[RADIUS*2+1]; float (*Density)[GRID_SIZE]; deque* Bins; // old static variables //float fall_off[RADIUS*2+1][RADIUS*2+1]; //float Density[GRID_SIZE][GRID_SIZE]; //deque Bins[GRID_SIZE][GRID_SIZE]; }; } // namespace drl #endif // __DENSITY_GRID_H__ igraph/src/dnaup2.f0000644000175100001440000007606513431000472013701 0ustar hornikusersc\BeginDoc c c\Name: igraphdnaup2 c c\Description: c Intermediate level interface called by igraphdnaupd. c c\Usage: c call igraphdnaup2 c ( IDO, BMAT, N, WHICH, NEV, NP, TOL, RESID, MODE, IUPD, c ISHIFT, MXITER, V, LDV, H, LDH, RITZR, RITZI, BOUNDS, c Q, LDQ, WORKL, IPNTR, WORKD, INFO ) c c\Arguments c c IDO, BMAT, N, WHICH, NEV, TOL, RESID: same as defined in igraphdnaupd. c MODE, ISHIFT, MXITER: see the definition of IPARAM in igraphdnaupd. c c NP Integer. (INPUT/OUTPUT) c Contains the number of implicit shifts to apply during c each Arnoldi iteration. c If ISHIFT=1, NP is adjusted dynamically at each iteration c to accelerate convergence and prevent stagnation. c This is also roughly equal to the number of matrix-vector c products (involving the operator OP) per Arnoldi iteration. c The logic for adjusting is contained within the current c subroutine. c If ISHIFT=0, NP is the number of shifts the user needs c to provide via reverse comunication. 0 < NP < NCV-NEV. c NP may be less than NCV-NEV for two reasons. The first, is c to keep complex conjugate pairs of "wanted" Ritz values c together. The igraphsecond, is that a leading block of the current c upper Hessenberg matrix has split off and contains "unwanted" c Ritz values. c Upon termination of the IRA iteration, NP contains the number c of "converged" wanted Ritz values. c c IUPD Integer. (INPUT) c IUPD .EQ. 0: use explicit restart instead implicit update. c IUPD .NE. 0: use implicit update. c c V Double precision N by (NEV+NP) array. (INPUT/OUTPUT) c The Arnoldi basis vectors are returned in the first NEV c columns of V. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (NEV+NP) by (NEV+NP) array. (OUTPUT) c H is used to store the generated upper Hessenberg matrix c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c RITZR, Double precision arrays of length NEV+NP. (OUTPUT) c RITZI RITZR(1:NEV) (resp. RITZI(1:NEV)) contains the real (resp. c imaginary) part of the computed Ritz values of OP. c c BOUNDS Double precision array of length NEV+NP. (OUTPUT) c BOUNDS(1:NEV) contain the error bounds corresponding to c the computed Ritz values. c c Q Double precision (NEV+NP) by (NEV+NP) array. (WORKSPACE) c Private (replicated) work array used to accumulate the c rotation in the shift application step. c c LDQ Integer. (INPUT) c Leading dimension of Q exactly as declared in the calling c program. c c WORKL Double precision work array of length at least c (NEV+NP)**2 + 3*(NEV+NP). (INPUT/WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. It is used in shifts calculation, shifts c application and convergence checking. c c On exit, the last 3*(NEV+NP) locations of WORKL contain c the Ritz values (real,imaginary) and associated Ritz c estimates of the current Hessenberg matrix. They are c listed in the same order as returned from igraphdneigh. c c If ISHIFT .EQ. O and IDO .EQ. 3, the first 2*NP locations c of WORKL are used in reverse communication to hold the user c supplied shifts. c c IPNTR Integer array of length 3. (OUTPUT) c Pointer to mark the starting locations in the WORKD for c vectors used by the Arnoldi iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X. c IPNTR(2): pointer to the current result vector Y. c IPNTR(3): pointer to the vector B * X when used in the c shift-and-invert mode. X is the current operand. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (WORKSPACE) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The user should not use WORKD c as temporary workspace during the iteration !!!!!!!!!! c See Data Distribution Note in DNAUPD. c c INFO Integer. (INPUT/OUTPUT) c If INFO .EQ. 0, a randomly initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c Error flag on output. c = 0: Normal return. c = 1: Maximum number of iterations taken. c All possible eigenvalues of OP has been found. c NP returns the number of converged Ritz values. c = 2: No shifts could be applied. c = -8: Error return from LAPACK eigenvalue calculation; c This should never happen. c = -9: Starting vector is zero. c = -9999: Could not build an Arnoldi factorization. c Size that was built in returned in NP. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c c\Routines called: c igraphdgetv0 ARPACK initial vector generation routine. c igraphdnaitr ARPACK Arnoldi factorization routine. c igraphdnapps ARPACK application of implicit shifts routine. c igraphdnconv ARPACK convergence of Ritz values routine. c igraphdneigh ARPACK compute Ritz values and error bounds routine. c igraphdngets ARPACK reorder Ritz values and error bounds routine. c igraphdsortc ARPACK sorting routine. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdmout ARPACK utility routine that prints matrices c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c dcopy Level 1 BLAS that copies one vector to another . c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c dswap Level 1 BLAS that swaps two vectors. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: naup2.F SID: 2.4 DATE OF SID: 7/30/96 RELEASE: 2 c c\Remarks c 1. None c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdnaup2 & ( ido, bmat, n, which, nev, np, tol, resid, mode, iupd, & ishift, mxiter, v, ldv, h, ldh, ritzr, ritzi, bounds, & q, ldq, workl, ipntr, workd, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1, which*2 integer ido, info, ishift, iupd, mode, ldh, ldq, ldv, mxiter, & n, nev, np Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% c integer ipntr(13) Double precision & bounds(nev+np), h(ldh,nev+np), q(ldq,nev+np), resid(n), & ritzi(nev+np), ritzr(nev+np), v(ldv,nev+np), & workd(3*n), workl( (nev+np)*(nev+np+3) ) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c character wprime*2 logical cnorm, getv0, initv, update, ushift integer ierr, iter, j, kplusp, msglvl, nconv, nevbef, nev0, & np0, nptemp, numcnv Double precision & rnorm, temp, eps23 c c %-----------------------% c | Local array arguments | c %-----------------------% c integer kp(4) save c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, igraphdgetv0, igraphdnaitr, igraphdnconv, & igraphdneigh, igraphdngets, igraphdnapps, & igraphdvout, igraphivout, igraphsecond c c %--------------------% c | External Functions | c %--------------------% c Double precision & ddot, dnrm2, dlapy2, dlamch external ddot, dnrm2, dlapy2, dlamch c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic min, max, abs, sqrt c c %-----------------------% c | Executable Statements | c %-----------------------% c if (ido .eq. 0) then c call igraphsecond (t0) c msglvl = mnaup2 c c %-------------------------------------% c | Get the machine dependent constant. | c %-------------------------------------% c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0 / 3.0D+0) c nev0 = nev np0 = np c c %-------------------------------------% c | kplusp is the bound on the largest | c | Lanczos factorization built. | c | nconv is the current number of | c | "converged" eigenvlues. | c | iter is the counter on the current | c | iteration step. | c %-------------------------------------% c kplusp = nev + np nconv = 0 iter = 0 c c %---------------------------------------% c | Set flags for computing the first NEV | c | steps of the Arnoldi factorization. | c %---------------------------------------% c getv0 = .true. update = .false. ushift = .false. cnorm = .false. c if (info .ne. 0) then c c %--------------------------------------------% c | User provides the initial residual vector. | c %--------------------------------------------% c initv = .true. info = 0 else initv = .false. end if end if c c %---------------------------------------------% c | Get a possibly random starting vector and | c | force it into the range of the operator OP. | c %---------------------------------------------% c 10 continue c if (getv0) then call igraphdgetv0 (ido, bmat, 1, initv, n, 1, v, ldv, resid, & rnorm, ipntr, workd, info) c if (ido .ne. 99) go to 9000 c if (rnorm .eq. zero) then c c %-----------------------------------------% c | The initial vector is zero. Error exit. | c %-----------------------------------------% c info = -9 go to 1100 end if getv0 = .false. ido = 0 end if c c %-----------------------------------% c | Back from reverse communication : | c | continue with update step | c %-----------------------------------% c if (update) go to 20 c c %-------------------------------------------% c | Back from computing user specified shifts | c %-------------------------------------------% c if (ushift) go to 50 c c %-------------------------------------% c | Back from computing residual norm | c | at the end of the current iteration | c %-------------------------------------% c if (cnorm) go to 100 c c %----------------------------------------------------------% c | Compute the first NEV steps of the Arnoldi factorization | c %----------------------------------------------------------% c call igraphdnaitr (ido, bmat, n, 0, nev, mode, resid, rnorm, v, & ldv, h, ldh, ipntr, workd, info) c c %---------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP and possibly B | c %---------------------------------------------------% c if (ido .ne. 99) go to 9000 c if (info .gt. 0) then np = info mxiter = iter info = -9999 go to 1200 end if c c %--------------------------------------------------------------% c | | c | M A I N ARNOLDI I T E R A T I O N L O O P | c | Each iteration implicitly restarts the Arnoldi | c | factorization in place. | c | | c %--------------------------------------------------------------% c 1000 continue c iter = iter + 1 c if (msglvl .gt. 0) then call igraphivout (logfil, 1, iter, ndigit, & '_naup2: **** Start of major iteration number ****') end if c c %-----------------------------------------------------------% c | Compute NP additional steps of the Arnoldi factorization. | c | Adjust NP since NEV might have been updated by last call | c | to the shift application routine igraphdnapps. | c %-----------------------------------------------------------% c np = kplusp - nev c if (msglvl .gt. 1) then call igraphivout (logfil, 1, nev, ndigit, & '_naup2: The length of the current Arnoldi factorization') call igraphivout (logfil, 1, np, ndigit, & '_naup2: Extend the Arnoldi factorization by') end if c c %-----------------------------------------------------------% c | Compute NP additional steps of the Arnoldi factorization. | c %-----------------------------------------------------------% c ido = 0 20 continue update = .true. c call igraphdnaitr (ido, bmat, n, nev, np, mode, resid, rnorm, & v, ldv, h, ldh, ipntr, workd, info) c c %---------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP and possibly B | c %---------------------------------------------------% c if (ido .ne. 99) go to 9000 c if (info .gt. 0) then np = info mxiter = iter info = -9999 go to 1200 end if update = .false. c if (msglvl .gt. 1) then call igraphdvout (logfil, 1, rnorm, ndigit, & '_naup2: Corresponding B-norm of the residual') end if c c %--------------------------------------------------------% c | Compute the eigenvalues and corresponding error bounds | c | of the current upper Hessenberg matrix. | c %--------------------------------------------------------% c call igraphdneigh (rnorm, kplusp, h, ldh, ritzr, ritzi, bounds, & q, ldq, workl, ierr) c if (ierr .ne. 0) then info = -8 go to 1200 end if c c %----------------------------------------------------% c | Make a copy of eigenvalues and corresponding error | c | bounds obtained from igraphdneigh. | c %----------------------------------------------------% c call dcopy(kplusp, ritzr, 1, workl(kplusp**2+1), 1) call dcopy(kplusp, ritzi, 1, workl(kplusp**2+kplusp+1), 1) call dcopy(kplusp, bounds, 1, workl(kplusp**2+2*kplusp+1), 1) c c %---------------------------------------------------% c | Select the wanted Ritz values and their bounds | c | to be used in the convergence test. | c | The wanted part of the spectrum and corresponding | c | error bounds are in the last NEV loc. of RITZR, | c | RITZI and BOUNDS respectively. The variables NEV | c | and NP may be updated if the NEV-th wanted Ritz | c | value has a non zero imaginary part. In this case | c | NEV is increased by one and NP decreased by one. | c | NOTE: The last two arguments of igraphdngets are no | c | longer used as of version 2.1. | c %---------------------------------------------------% c nev = nev0 np = np0 numcnv = nev call igraphdngets (ishift, which, nev, np, ritzr, ritzi, & bounds, workl, workl(np+1)) if (nev .eq. nev0+1) numcnv = nev0+1 c c %-------------------% c | Convergence test. | c %-------------------% c call dcopy (nev, bounds(np+1), 1, workl(2*np+1), 1) call igraphdnconv (nev, ritzr(np+1), ritzi(np+1), & workl(2*np+1), tol, nconv) c if (msglvl .gt. 2) then kp(1) = nev kp(2) = np kp(3) = numcnv kp(4) = nconv call igraphivout (logfil, 4, kp, ndigit, & '_naup2: NEV, NP, NUMCNV, NCONV are') call igraphdvout (logfil, kplusp, ritzr, ndigit, & '_naup2: Real part of the eigenvalues of H') call igraphdvout (logfil, kplusp, ritzi, ndigit, & '_naup2: Imaginary part of the eigenvalues of H') call igraphdvout (logfil, kplusp, bounds, ndigit, & '_naup2: Ritz estimates of the current NCV Ritz values') end if c c %---------------------------------------------------------% c | Count the number of unwanted Ritz values that have zero | c | Ritz estimates. If any Ritz estimates are equal to zero | c | then a leading block of H of order equal to at least | c | the number of Ritz values with zero Ritz estimates has | c | split off. None of these Ritz values may be removed by | c | shifting. Decrease NP the number of shifts to apply. If | c | no shifts may be applied, then prepare to exit | c %---------------------------------------------------------% c nptemp = np do 30 j=1, nptemp if (bounds(j) .eq. zero) then np = np - 1 nev = nev + 1 end if 30 continue c if ( (nconv .ge. numcnv) .or. & (iter .gt. mxiter) .or. & (np .eq. 0) ) then c if (msglvl .gt. 4) then call igraphdvout(logfil, kplusp, workl(kplusp**2+1), & ndigit, & '_naup2: Real part of the eig computed by _neigh:') call igraphdvout(logfil, kplusp, & workl(kplusp**2+kplusp+1), ndigit, & '_naup2: Imag part of the eig computed by _neigh:') call igraphdvout(logfil, kplusp, & workl(kplusp**2+kplusp*2+1), ndigit, & '_naup2: Ritz eistmates computed by _neigh:') end if c c %------------------------------------------------% c | Prepare to exit. Put the converged Ritz values | c | and corresponding bounds in RITZ(1:NCONV) and | c | BOUNDS(1:NCONV) respectively. Then sort. Be | c | careful when NCONV > NP | c %------------------------------------------------% c c %------------------------------------------% c | Use h( 3,1 ) as storage to communicate | c | rnorm to _neupd if needed | c %------------------------------------------% h(3,1) = rnorm c c %----------------------------------------------% c | To be consistent with igraphdngets, we first do a | c | pre-processing sort in order to keep complex | c | conjugate pairs together. This is similar | c | to the pre-processing sort used in igraphdngets | c | except that the sort is done in the opposite | c | order. | c %----------------------------------------------% c if (which .eq. 'LM') wprime = 'SR' if (which .eq. 'SM') wprime = 'LR' if (which .eq. 'LR') wprime = 'SM' if (which .eq. 'SR') wprime = 'LM' if (which .eq. 'LI') wprime = 'SM' if (which .eq. 'SI') wprime = 'LM' c call igraphdsortc (wprime, .true., kplusp, ritzr, ritzi, & bounds) c c %----------------------------------------------% c | Now sort Ritz values so that converged Ritz | c | values appear within the first NEV locations | c | of ritzr, ritzi and bounds, and the most | c | desired one appears at the front. | c %----------------------------------------------% c if (which .eq. 'LM') wprime = 'SM' if (which .eq. 'SM') wprime = 'LM' if (which .eq. 'LR') wprime = 'SR' if (which .eq. 'SR') wprime = 'LR' if (which .eq. 'LI') wprime = 'SI' if (which .eq. 'SI') wprime = 'LI' c call igraphdsortc(wprime, .true., kplusp, ritzr, ritzi, & bounds) c c %--------------------------------------------------% c | Scale the Ritz estimate of each Ritz value | c | by 1 / max(eps23,magnitude of the Ritz value). | c %--------------------------------------------------% c do 35 j = 1, nev0 temp = max(eps23,dlapy2(ritzr(j), & ritzi(j))) bounds(j) = bounds(j)/temp 35 continue c c %----------------------------------------------------% c | Sort the Ritz values according to the scaled Ritz | c | esitmates. This will push all the converged ones | c | towards the front of ritzr, ritzi, bounds | c | (in the case when NCONV < NEV.) | c %----------------------------------------------------% c wprime = 'LR' call igraphdsortc(wprime, .true., nev0, bounds, ritzr, & ritzi) c c %----------------------------------------------% c | Scale the Ritz estimate back to its original | c | value. | c %----------------------------------------------% c do 40 j = 1, nev0 temp = max(eps23, dlapy2(ritzr(j), & ritzi(j))) bounds(j) = bounds(j)*temp 40 continue c c %------------------------------------------------% c | Sort the converged Ritz values again so that | c | the "threshold" value appears at the front of | c | ritzr, ritzi and bound. | c %------------------------------------------------% c call igraphdsortc(which, .true., nconv, ritzr, ritzi, & bounds) c if (msglvl .gt. 1) then call igraphdvout (logfil, kplusp, ritzr, ndigit, & '_naup2: Sorted real part of the eigenvalues') call igraphdvout (logfil, kplusp, ritzi, ndigit, & '_naup2: Sorted imaginary part of the eigenvalues') call igraphdvout (logfil, kplusp, bounds, ndigit, & '_naup2: Sorted ritz estimates.') end if c c %------------------------------------% c | Max iterations have been exceeded. | c %------------------------------------% c if (iter .gt. mxiter .and. nconv .lt. numcnv) info = 1 c c %---------------------% c | No shifts to apply. | c %---------------------% c if (np .eq. 0 .and. nconv .lt. numcnv) info = 2 c np = nconv go to 1100 c else if ( (nconv .lt. numcnv) .and. (ishift .eq. 1) ) then c c %-------------------------------------------------% c | Do not have all the requested eigenvalues yet. | c | To prevent possible stagnation, adjust the size | c | of NEV. | c %-------------------------------------------------% c nevbef = nev nev = nev + min(nconv, np/2) if (nev .eq. 1 .and. kplusp .ge. 6) then nev = kplusp / 2 else if (nev .eq. 1 .and. kplusp .gt. 3) then nev = 2 end if np = kplusp - nev c c %---------------------------------------% c | If the size of NEV was just increased | c | resort the eigenvalues. | c %---------------------------------------% c if (nevbef .lt. nev) & call igraphdngets (ishift, which, nev, np, ritzr, ritzi, & bounds, workl, workl(np+1)) c end if c if (msglvl .gt. 0) then call igraphivout (logfil, 1, nconv, ndigit, & '_naup2: no. of "converged" Ritz values at this iter.') if (msglvl .gt. 1) then kp(1) = nev kp(2) = np call igraphivout (logfil, 2, kp, ndigit, & '_naup2: NEV and NP are') call igraphdvout (logfil, nev, ritzr(np+1), ndigit, & '_naup2: "wanted" Ritz values -- real part') call igraphdvout (logfil, nev, ritzi(np+1), ndigit, & '_naup2: "wanted" Ritz values -- imag part') call igraphdvout (logfil, nev, bounds(np+1), ndigit, & '_naup2: Ritz estimates of the "wanted" values ') end if end if c if (ishift .eq. 0) then c c %-------------------------------------------------------% c | User specified shifts: reverse comminucation to | c | compute the shifts. They are returned in the first | c | 2*NP locations of WORKL. | c %-------------------------------------------------------% c ushift = .true. ido = 3 go to 9000 end if c 50 continue c c %------------------------------------% c | Back from reverse communication; | c | User specified shifts are returned | c | in WORKL(1:2*NP) | c %------------------------------------% c ushift = .false. c if ( ishift .eq. 0 ) then c c %----------------------------------% c | Move the NP shifts from WORKL to | c | RITZR, RITZI to free up WORKL | c | for non-exact shift case. | c %----------------------------------% c call dcopy (np, workl, 1, ritzr, 1) call dcopy (np, workl(np+1), 1, ritzi, 1) end if c if (msglvl .gt. 2) then call igraphivout (logfil, 1, np, ndigit, & '_naup2: The number of shifts to apply ') call igraphdvout (logfil, np, ritzr, ndigit, & '_naup2: Real part of the shifts') call igraphdvout (logfil, np, ritzi, ndigit, & '_naup2: Imaginary part of the shifts') if ( ishift .eq. 1 ) & call igraphdvout (logfil, np, bounds, ndigit, & '_naup2: Ritz estimates of the shifts') end if c c %---------------------------------------------------------% c | Apply the NP implicit shifts by QR bulge chasing. | c | Each shift is applied to the whole upper Hessenberg | c | matrix H. | c | The first 2*N locations of WORKD are used as workspace. | c %---------------------------------------------------------% c call igraphdnapps (n, nev, np, ritzr, ritzi, v, ldv, & h, ldh, resid, q, ldq, workl, workd) c c %---------------------------------------------% c | Compute the B-norm of the updated residual. | c | Keep B*RESID in WORKD(1:N) to be used in | c | the first step of the next call to igraphdnaitr. | c %---------------------------------------------% c cnorm = .true. call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(n+1), 1) ipntr(1) = n + 1 ipntr(2) = 1 ido = 2 c c %----------------------------------% c | Exit in order to compute B*RESID | c %----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd, 1) end if c 100 continue c c %----------------------------------% c | Back from reverse communication; | c | WORKD(1:N) := B*RESID | c %----------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c if (bmat .eq. 'G') then rnorm = ddot (n, resid, 1, workd, 1) rnorm = sqrt(abs(rnorm)) else if (bmat .eq. 'I') then rnorm = dnrm2(n, resid, 1) end if cnorm = .false. c if (msglvl .gt. 2) then call igraphdvout (logfil, 1, rnorm, ndigit, & '_naup2: B-norm of residual for compressed factorization') call igraphdmout (logfil, nev, nev, h, ldh, ndigit, & '_naup2: Compressed upper Hessenberg matrix H') end if c go to 1000 c c %---------------------------------------------------------------% c | | c | E N D O F M A I N I T E R A T I O N L O O P | c | | c %---------------------------------------------------------------% c 1100 continue c mxiter = iter nev = numcnv c 1200 continue ido = 99 c c %------------% c | Error Exit | c %------------% c call igraphsecond (t1) tnaup2 = t1 - t0 c 9000 continue c c %---------------% c | End of igraphdnaup2 | c %---------------% c return end igraph/src/st-cuts.c0000644000175100001440000014022613431000472014076 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_flow.h" #include "igraph_flow_internal.h" #include "igraph_error.h" #include "igraph_memory.h" #include "igraph_constants.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_conversion.h" #include "igraph_constructors.h" #include "igraph_structural.h" #include "igraph_components.h" #include "igraph_types_internal.h" #include "config.h" #include "igraph_math.h" #include "igraph_dqueue.h" #include "igraph_visitor.h" #include "igraph_marked_queue.h" #include "igraph_stack.h" #include "igraph_estack.h" /* * \function igraph_even_tarjan_reduction * Even-Tarjan reduction of a graph * * \example examples/simple/even_tarjan.c */ int igraph_even_tarjan_reduction(const igraph_t *graph, igraph_t *graphbar, igraph_vector_t *capacity) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); long int new_no_of_nodes=no_of_nodes*2; long int new_no_of_edges=no_of_nodes + no_of_edges * 2; igraph_vector_t edges; long int edgeptr=0, capptr=0; long int i; IGRAPH_VECTOR_INIT_FINALLY(&edges, new_no_of_edges * 2); if (capacity) { IGRAPH_CHECK(igraph_vector_resize(capacity, new_no_of_edges)); } /* Every vertex 'i' is replaced by two vertices, i' and i'' */ /* id[i'] := id[i] ; id[i''] := id[i] + no_of_nodes */ /* One edge for each original vertex, for i, we add (i',i'') */ for (i=0; i 0) { long int from=IGRAPH_FROM(graph, i); long int to=IGRAPH_TO(graph, i); igraph_real_t c=VECTOR(*capacity)[i]; VECTOR(*tmp)[edgeptr++] = from; VECTOR(*tmp)[edgeptr++] = to; if (residual_capacity) { VECTOR(*residual_capacity)[capptr++] = c; } } } IGRAPH_CHECK(igraph_create(residual, tmp, (igraph_integer_t) no_of_nodes, IGRAPH_DIRECTED)); return 0; } int igraph_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, igraph_vector_t *residual_capacity, const igraph_vector_t *flow) { igraph_vector_t tmp; long int no_of_edges=igraph_ecount(graph); if (igraph_vector_size(capacity) != no_of_edges) { IGRAPH_ERROR("Invalid `capacity' vector size", IGRAPH_EINVAL); } if (igraph_vector_size(flow) != no_of_edges) { IGRAPH_ERROR("Invalid `flow' vector size", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_CHECK(igraph_i_residual_graph(graph, capacity, residual, residual_capacity, flow, &tmp)); igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_reverse_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, const igraph_vector_t *flow, igraph_vector_t *tmp) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); long int i, no_new_edges=0; long int edgeptr=0; for (i=0; i 0) { no_new_edges++; } if (VECTOR(*flow)[i] < cap) { no_new_edges++; } } IGRAPH_CHECK(igraph_vector_resize(tmp, no_new_edges*2)); for (i=0; i 0) { VECTOR(*tmp)[edgeptr++] = from; VECTOR(*tmp)[edgeptr++] = to; } if (VECTOR(*flow)[i] < cap) { VECTOR(*tmp)[edgeptr++] = to; VECTOR(*tmp)[edgeptr++] = from; } } IGRAPH_CHECK(igraph_create(residual, tmp, (igraph_integer_t) no_of_nodes, IGRAPH_DIRECTED)); return 0; } int igraph_reverse_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, const igraph_vector_t *flow) { igraph_vector_t tmp; long int no_of_edges=igraph_ecount(graph); if (capacity && igraph_vector_size(capacity) != no_of_edges) { IGRAPH_ERROR("Invalid `capacity' vector size", IGRAPH_EINVAL); } if (igraph_vector_size(flow) != no_of_edges) { IGRAPH_ERROR("Invalid `flow' vector size", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_CHECK(igraph_i_reverse_residual_graph(graph, capacity, residual, flow, &tmp)); igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } typedef struct igraph_i_dbucket_t { igraph_vector_long_t head; igraph_vector_long_t next; } igraph_i_dbucket_t; int igraph_i_dbucket_init(igraph_i_dbucket_t *buck, long int size) { IGRAPH_CHECK(igraph_vector_long_init(&buck->head, size)); IGRAPH_FINALLY(igraph_vector_long_destroy, &buck->head); IGRAPH_CHECK(igraph_vector_long_init(&buck->next, size)); IGRAPH_FINALLY_CLEAN(1); return 0; } void igraph_i_dbucket_destroy(igraph_i_dbucket_t *buck) { igraph_vector_long_destroy(&buck->head); igraph_vector_long_destroy(&buck->next); } int igraph_i_dbucket_insert(igraph_i_dbucket_t *buck, long int bid, long int elem) { /* Note: we can do this, since elem is not in any buckets */ VECTOR(buck->next)[elem]=VECTOR(buck->head)[bid]; VECTOR(buck->head)[bid]=elem+1; return 0; } long int igraph_i_dbucket_empty(const igraph_i_dbucket_t *buck, long int bid) { return VECTOR(buck->head)[bid] == 0; } long int igraph_i_dbucket_delete(igraph_i_dbucket_t *buck, long int bid) { long int elem=VECTOR(buck->head)[bid]-1; VECTOR(buck->head)[bid]=VECTOR(buck->next)[elem]; return elem; } int igraph_i_dominator_LINK(long int v, long int w, igraph_vector_long_t *ancestor) { VECTOR(*ancestor)[w] = v+1; return 0; } /* TODO: don't always reallocate path */ int igraph_i_dominator_COMPRESS(long int v, igraph_vector_long_t *ancestor, igraph_vector_long_t *label, igraph_vector_long_t *semi) { igraph_stack_long_t path; long int w=v; long int top, pretop; IGRAPH_CHECK(igraph_stack_long_init(&path, 10)); IGRAPH_FINALLY(igraph_stack_long_destroy, &path); while (VECTOR(*ancestor)[w] != 0) { IGRAPH_CHECK(igraph_stack_long_push(&path, w)); w=VECTOR(*ancestor)[w]-1; } top=igraph_stack_long_pop(&path); while (!igraph_stack_long_empty(&path)) { pretop=igraph_stack_long_pop(&path); if (VECTOR(*semi)[VECTOR(*label)[top]] < VECTOR(*semi)[VECTOR(*label)[pretop]]) { VECTOR(*label)[pretop] = VECTOR(*label)[top]; } VECTOR(*ancestor)[pretop]=VECTOR(*ancestor)[top]; top=pretop; } igraph_stack_long_destroy(&path); IGRAPH_FINALLY_CLEAN(1); return 0; } long int igraph_i_dominator_EVAL(long int v, igraph_vector_long_t *ancestor, igraph_vector_long_t *label, igraph_vector_long_t *semi) { if (VECTOR(*ancestor)[v] == 0) { return v; } else { igraph_i_dominator_COMPRESS(v, ancestor, label, semi); return VECTOR(*label)[v]; } } /* TODO: implement the faster version. */ /** * \function igraph_dominator_tree * Calculates the dominator tree of a flowgraph * * A flowgraph is a directed graph with a distinguished start (or * root) vertex r, such that for any vertex v, there is a path from r * to v. A vertex v dominates another vertex w (not equal to v), if * every path from r to w contains v. Vertex v is the immediate * dominator or w, v=idom(w), if v dominates w and every other * dominator of w dominates v. The edges {(idom(w), w)| w is not r} * form a directed tree, rooted at r, called the dominator tree of the * graph. Vertex v dominates vertex w if and only if v is an ancestor * of w in the dominator tree. * * This function implements the Lengauer-Tarjan algorithm * to construct the dominator tree of a directed graph. For details * please see Thomas Lengauer, Robert Endre Tarjan: A fast algorithm * for finding dominators in a flowgraph, ACM Transactions on * Programming Languages and Systems (TOPLAS) I/1, 121--141, 1979. * * \param graph A directed graph. If it is not a flowgraph, and it * contains some vertices not reachable from the root vertex, * then these vertices will be collected in the \c leftout * vector. * \param root The id of the root (or source) vertex, this will be the * root of the tree. * \param dom Pointer to an initialized vector or a null pointer. If * not a null pointer, then the immediate dominator of each * vertex will be stored here. For vertices that are not * reachable from the root, \c IGRAPH_NAN is stored here. For * the root vertex itself, -1 is added. * \param domtree Pointer to an uninitialized igraph_t, or NULL. If * not a null pointer, then the dominator tree is returned * here. The graph contains the vertices that are unreachable * from the root (if any), these will be isolates. * \param leftout Pointer to an initialized vector object, or NULL. If * not NULL, then the ids of the vertices that are unreachable * from the root vertex (and thus not part of the dominator * tree) are stored here. * \param mode Constant, must be \c IGRAPH_IN or \c IGRAPH_OUT. If it * is \c IGRAPH_IN, then all directions are considered as * opposite to the original one in the input graph. * \return Error code. * * Time complexity: very close to O(|E|+|V|), linear in the number of * edges and vertices. More precisely, it is O(|V|+|E|alpha(|E|,|V|)), * where alpha(|E|,|V|) is a functional inverse of Ackermann's * function. * * \example examples/simple/dominator_tree.c */ int igraph_dominator_tree(const igraph_t *graph, igraph_integer_t root, igraph_vector_t *dom, igraph_t *domtree, igraph_vector_t *leftout, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_adjlist_t succ, pred; igraph_vector_t parent; igraph_vector_long_t semi; /* +1 always */ igraph_vector_t vertex; /* +1 always */ igraph_i_dbucket_t bucket; igraph_vector_long_t ancestor; igraph_vector_long_t label; igraph_neimode_t invmode= mode==IGRAPH_IN ? IGRAPH_OUT: IGRAPH_IN; long int i; igraph_vector_t vdom, *mydom=dom; long int component_size=0; if (root < 0 || root >= no_of_nodes) { IGRAPH_ERROR("Invalid root vertex id for dominator tree", IGRAPH_EINVAL); } if (!igraph_is_directed(graph)) { IGRAPH_ERROR("Dominator tree of an undirected graph requested", IGRAPH_EINVAL); } if (mode == IGRAPH_ALL) { IGRAPH_ERROR("Invalid neighbor mode for dominator tree", IGRAPH_EINVAL); } if (dom) { IGRAPH_CHECK(igraph_vector_resize(dom, no_of_nodes)); } else { mydom=&vdom; IGRAPH_VECTOR_INIT_FINALLY(mydom, no_of_nodes); } igraph_vector_fill(mydom, IGRAPH_NAN); IGRAPH_CHECK(igraph_vector_init(&parent, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_destroy, &parent); IGRAPH_CHECK(igraph_vector_long_init(&semi, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &semi); IGRAPH_CHECK(igraph_vector_init(&vertex, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_destroy, &vertex); IGRAPH_CHECK(igraph_vector_long_init(&ancestor, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &ancestor); IGRAPH_CHECK(igraph_vector_long_init_seq(&label, 0, no_of_nodes-1)); IGRAPH_FINALLY(igraph_vector_long_destroy, &label); IGRAPH_CHECK(igraph_adjlist_init(graph, &succ, mode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &succ); IGRAPH_CHECK(igraph_adjlist_init(graph, &pred, invmode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &pred); IGRAPH_CHECK(igraph_i_dbucket_init(&bucket, no_of_nodes)); IGRAPH_FINALLY(igraph_i_dbucket_destroy, &bucket); /* DFS first, to set semi, vertex and parent, step 1 */ IGRAPH_CHECK(igraph_dfs(graph, root, mode, /*unreachable=*/ 0, /*order=*/ &vertex, /*order_out=*/ 0, /*father=*/ &parent, /*dist=*/ 0, /*in_callback=*/ 0, /*out_callback=*/ 0, /*extra=*/ 0)); for (i=0; i0; i--) { long int w=(long int) VECTOR(vertex)[i]-1; igraph_vector_int_t *predw=igraph_adjlist_get(&pred, w); long int j, n=igraph_vector_int_size(predw); for (j=0; jstack; igraph_vector_bool_t *nomark=data->nomark; const igraph_vector_bool_t *GammaX=data->GammaX; const igraph_vector_t *map=data->map; long int realvid=(long int) VECTOR(*map)[(long int)vid]; IGRAPH_UNUSED(graph); IGRAPH_UNUSED(dist); if (VECTOR(*GammaX)[(long int)realvid]) { if (!igraph_stack_empty(stack)) { long int top=(long int) igraph_stack_top(stack); VECTOR(*nomark)[top]=1; /* we just found a smaller one */ } igraph_stack_push(stack, realvid); /* TODO: error check */ } return 0; } igraph_bool_t igraph_i_all_st_cuts_minimal_dfs_otcb(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t dist, void *extra) { igraph_i_all_st_cuts_minimal_dfs_data_t *data=extra; igraph_stack_t *stack=data->stack; const igraph_vector_t *map=data->map; long int realvid=(long int) VECTOR(*map)[(long int)vid]; IGRAPH_UNUSED(graph); IGRAPH_UNUSED(dist); if (!igraph_stack_empty(stack) && igraph_stack_top(stack) == realvid) { igraph_stack_pop(stack); } return 0; } int igraph_i_all_st_cuts_minimal(const igraph_t *graph, const igraph_t *domtree, long int root, const igraph_marked_queue_t *X, const igraph_vector_bool_t *GammaX, const igraph_vector_t *invmap, igraph_vector_t *minimal) { long int no_of_nodes=igraph_vcount(graph); igraph_stack_t stack; igraph_vector_bool_t nomark; igraph_i_all_st_cuts_minimal_dfs_data_t data; long int i; IGRAPH_UNUSED(X); IGRAPH_CHECK(igraph_stack_init(&stack, 10)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_CHECK(igraph_vector_bool_init(&nomark, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &nomark); data.stack=&stack; data.nomark=&nomark; data.GammaX=GammaX; data.root=root; data.map=invmap; /* We mark all GammaX elements as minimal first. TODO: actually, we could just use GammaX to return the minimal elements. */ for (i=0; i0) { IGRAPH_CHECK(igraph_i_all_st_cuts_minimal(graph, &domtree, root, S, &GammaS, &Sbar_invmap, &M)); } igraph_vector_clear(Isv); IGRAPH_VECTOR_INIT_FINALLY(&Nuv, 0); IGRAPH_VECTOR_INIT_FINALLY(&Isv_min, 0); IGRAPH_VECTOR_INIT_FINALLY(&GammaS_vec, 0); for (i=0; i determine I(S,v)-K. I(S,v) contains all vertices that are in Nu(v) and that are reachable from Gamma(S) via a path in Nu(v). */ IGRAPH_CHECK(igraph_bfs(graph, /*root=*/ -1, /*roots=*/ &GammaS_vec, /*mode=*/ IGRAPH_OUT, /*unreachable=*/ 0, /*restricted=*/ &Nuv, /*order=*/ &Isv_min, /*rank=*/ 0, /*father=*/ 0, /*pred=*/ 0, /*succ=*/ 0, /*dist=*/ 0, /*callback=*/ 0, /*extra=*/ 0)); for (isvlen=0; isvlenactive; long int no_of_nodes=igraph_vcount(graph); long int i; igraph_vector_t Sbar_map, Sbar_invmap; igraph_vector_t keep; igraph_t Sbar; igraph_vector_t M; long int nomin; IGRAPH_UNUSED(source); IGRAPH_UNUSED(target); if (igraph_marked_queue_size(S) == no_of_nodes) { igraph_vector_clear(Isv); return 0; } /* Create the graph induced by Sbar */ IGRAPH_VECTOR_INIT_FINALLY(&Sbar_map, 0); IGRAPH_VECTOR_INIT_FINALLY(&Sbar_invmap, 0); IGRAPH_VECTOR_INIT_FINALLY(&keep, 0); for (i=0; i= no_of_nodes) { IGRAPH_ERROR("Invalid `source' vertex", IGRAPH_EINVAL); } if (target < 0 || target >= no_of_nodes) { IGRAPH_ERROR("Invalid `target' vertex", IGRAPH_EINVAL); } if (source==target) { IGRAPH_ERROR("`source' and 'target' are the same vertex", IGRAPH_EINVAL); } if (!partition1s) { mypartition1s=&vpartition1s; IGRAPH_CHECK(igraph_vector_ptr_init(mypartition1s, 0)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, mypartition1s); } /* -------------------------------------------------------------------- */ /* We need to calculate the maximum flow first */ IGRAPH_VECTOR_INIT_FINALLY(&flow, 0); IGRAPH_CHECK(igraph_maxflow(graph, value, &flow, /*cut=*/ 0, /*partition1=*/ 0, /*partition2=*/ 0, /*source=*/ source, /*target=*/ target, capacity, &stats)); /* -------------------------------------------------------------------- */ /* Then we need the reverse residual graph */ IGRAPH_CHECK(igraph_reverse_residual_graph(graph, capacity, &residual, &flow)); IGRAPH_FINALLY(igraph_destroy, &residual); /* -------------------------------------------------------------------- */ /* We shrink it to its strongly connected components */ IGRAPH_VECTOR_INIT_FINALLY(&NtoL, 0); IGRAPH_CHECK(igraph_clusters(&residual, /*membership=*/ &NtoL, /*csize=*/ 0, /*no=*/ &proj_nodes, IGRAPH_STRONG)); IGRAPH_CHECK(igraph_contract_vertices(&residual, /*mapping=*/ &NtoL, /*vertex_comb=*/ 0)); IGRAPH_CHECK(igraph_simplify(&residual, /*multiple=*/ 1, /*loops=*/ 1, /*edge_comb=*/ 0)); newsource=(long int) VECTOR(NtoL)[(long int)source]; newtarget=(long int) VECTOR(NtoL)[(long int)target]; /* TODO: handle the newsource == newtarget case */ /* -------------------------------------------------------------------- */ /* Determine the active vertices in the projection */ IGRAPH_VECTOR_INIT_FINALLY(&VE1, 0); IGRAPH_CHECK(igraph_vector_bool_init(&VE1bool, proj_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &VE1bool); for (i=0; i 0) { long int from=IGRAPH_FROM(graph, i); long int to=IGRAPH_TO(graph, i); long int pfrom=(long int) VECTOR(NtoL)[from]; long int pto=(long int) VECTOR(NtoL)[to]; if (!VECTOR(VE1bool)[pfrom]) { VECTOR(VE1bool)[pfrom] = 1; VE1size++; } if (!VECTOR(VE1bool)[pto]) { VECTOR(VE1bool)[pto] = 1; VE1size++; } } } IGRAPH_CHECK(igraph_vector_reserve(&VE1, VE1size)); for (i=0; i vRhs.Transparent() ? Transparent() : vRhs.Transparent(); return Color(Red()+vRhs.Red(),Green()+vRhs.Green(),Blue()+vRhs.Blue(), trans); } void Color::Red(double vRed) { mRed = unit_limiter(vRed); } double Color::Red() const { return mRed; } void Color::Green(double vGreen) { mGreen = unit_limiter(vGreen); } double Color::Green() const { return mGreen; } void Color::Blue(double vBlue) { mBlue = unit_limiter(vBlue); } double Color::Blue() const { return mBlue; } void Color::Transparent(double vTransparent) { mTransparent = unit_limiter(vTransparent); } double Color::Transparent() const { return mTransparent; } unsigned char Color::RedByte() const { return ByteValue(mRed); } unsigned char Color::GreenByte() const { return ByteValue(mGreen); } unsigned char Color::BlueByte() const { return ByteValue(mBlue); } unsigned char Color::TransparentByte() const { return ByteValue(mTransparent); } unsigned char Color::ByteValue(double vZeroToOne) const { return (unsigned char)(vZeroToOne*255.0); } } // namespace igraph igraph/src/simpleraytracer/RayVector.cpp0000755000175100001440000000433413431000472020162 0ustar hornikusers#include "RayVector.h" #include namespace igraph { Vector::Vector() { mI = mJ = mK = 0.0; } Vector::Vector(const Point& vStartPoint, const Point& vEndPoint) { mI = vEndPoint.X() - vStartPoint.X(); mJ = vEndPoint.Y() - vStartPoint.Y(); mK = vEndPoint.Z() - vStartPoint.Z(); } Vector::Vector(double vI, double vJ, double vK) { mI = vI; mJ = vJ; mK = vK; } Vector::~Vector() {} // returns a unit vector of this vector Vector Vector::Normalize() const { double magnitude = Magnitude(); return Vector(mI/magnitude, mJ/magnitude, mK/magnitude); } void Vector::NormalizeThis() { *this = Normalize(); } void Vector::ReverseDirection() { *this = *this * -1.0; } bool Vector::IsSameDirection(const Vector& rVector) const { return ( this->Normalize().Dot(rVector.Normalize()) > 0.0 ); } void Vector::I(double vI) { mI = vI; } double Vector::I() const { return mI; } void Vector::J(double vJ) { mJ = vJ; } double Vector::J() const { return mJ; } void Vector::K(double vK) { mK = vK; } double Vector::K() const { return mK; } // returns the dot product of this and rVector double Vector::Dot(const Vector& rVector) const { return mI*rVector.I() + mJ*rVector.J() + mK*rVector.K(); } // returns the cross product of this and vVector Vector Vector::Cross(const Vector& rVector) const { return Vector(mJ*rVector.K() - rVector.J()*mK, -1.0*(mI*rVector.K() - rVector.I()*mK), mI*rVector.J() - rVector.I()*mJ); } // returns the sum of this vector with another vector Vector Vector::operator+ (Vector vRhs) const { return Vector(mI + vRhs.I(), mJ + vRhs.J(), mK + vRhs.K()); } // returns the sume of a vector and a Point Point Vector::operator+ (Point vRhs) const { return Point(mI + vRhs.X(), mJ + vRhs.Y(), mK + vRhs.Z()); } // returns the difference of two vectors Vector Vector::operator- (Vector vRhs) const { return Vector(mI-vRhs.I(), mJ-vRhs.J(), mK-vRhs.K()); } // returns multiplication of a scalar with this vector Vector Vector::operator* (double vRhs) const { return Vector(mI*vRhs, mJ*vRhs, mK*vRhs); } // converts this vector to a point Point Vector::ToPoint() const { return Point(mI,mJ,mK); } // returns the magnitude double Vector::Magnitude() const { return sqrt(mI*mI + mJ*mJ + mK*mK); } } // namespace igraph igraph/src/simpleraytracer/unit_limiter.cpp0000755000175100001440000000035313431000472020745 0ustar hornikusers#include "unit_limiter.h" namespace igraph { double unit_limiter(double vUnitDouble) { double result = vUnitDouble; if (result < 0.0) result = 0.0; else if (result > 1.0) result = 1.0; return result; } } // namespace igraph igraph/src/simpleraytracer/Ray.cpp0000755000175100001440000000105613431000472016775 0ustar hornikusers#include "Ray.h" namespace igraph { Ray::Ray() {} Ray::~Ray() {} Ray::Ray(const Point& rOrigin, const Vector& rDirection) { Direction(rDirection); Origin(rOrigin); } Ray::Ray(const Point& rOrigin, const Point& rEndPoint) { Direction(Vector(rOrigin,rEndPoint)); Origin(rOrigin); } const Point& Ray::Origin() const { return mOrigin; } void Ray::Origin(Point vOrigin) { mOrigin = vOrigin; } const Vector& Ray::Direction() const { return mDirection; } void Ray::Direction(Vector vDirection) { mDirection = vDirection; } } // namespace igraph igraph/src/simpleraytracer/Light.cpp0000755000175100001440000000126413431000472017312 0ustar hornikusers#include "Light.h" #include "unit_limiter.h" namespace igraph { Light::Light() : mLightPoint(0,0,0) { mIntensity = 0.1; } Light::Light(const Point& rLightPoint) : mLightPoint(rLightPoint) { mIntensity = 0.1; } Light::~Light() {} const Point& Light::LightPoint() const { return mLightPoint; } void Light::LightPoint(const Point& rLightPoint) { mLightPoint = rLightPoint; } double Light::Intensity() const { return mIntensity; } void Light::Intensity(double vIntensity) { mIntensity = unit_limiter(vIntensity); } const Color& Light::LightColor() const { return mLightColor; } void Light::LightColor(const Color& rLightColor) { mLightColor = rLightColor; } } // namespace igraph igraph/src/simpleraytracer/Light.h0000755000175100001440000000122313431000472016752 0ustar hornikusers#ifndef LIGHT_H #define LIGHT_H #include "Point.h" #include "Color.h" #include using namespace std; namespace igraph { class Light { public: Light(); // creates a light at the origin Light(const Point& rLightPoint); ~Light(); const Point& LightPoint() const; void LightPoint(const Point& rLightPoint); double Intensity() const; void Intensity(double vIntensity); const Color& LightColor() const; void LightColor(const Color& rLightColor); private: Point mLightPoint; double mIntensity; // 0 to 1 Color mLightColor; }; typedef list LightList; typedef list::iterator LightListIterator; } // namespace igraph #endif igraph/src/simpleraytracer/RayVector.h0000755000175100001440000000224213431000472017623 0ustar hornikusers/** Vector.h */ #ifndef VECTOR_H #define VECTOR_H #include "Point.h" namespace igraph { class Vector { public: Vector(); Vector(const Point& vStartPoint, const Point& vEndPoint); Vector(double vI, double vJ, double vK); ~Vector(); Vector Normalize() const; // returns a unit vector of this vector void NormalizeThis(); void ReverseDirection(); bool IsSameDirection(const Vector& rVector) const; void I(double vI); double I() const; void J(double vJ); double J() const; void K(double vK); double K() const; double Dot(const Vector& rVector) const; // returns the dot product of this and rVector Vector Cross(const Vector& rVector) const; // returns the cross product of this and rVector Vector operator+ (Vector vRhs) const; // returns the sum of two vectors Vector operator- (Vector vRhs) const; // returns the difference of two vectors Point operator+ (Point vRhs) const; // returns the sum of a vector and a Point Vector operator* (double vRhs) const; // returns multiplication of a scalar with a vector Point ToPoint() const; // converts a vector to a point double Magnitude() const; private: double mI, mJ, mK; }; } // namespace igraph #endif igraph/src/simpleraytracer/Color.h0000755000175100001440000000156013431000472016765 0ustar hornikusers/** Color.h */ #ifndef COLOR_H #define COLOR_H namespace igraph { class Color { public: Color(); Color(double vRed, double vGreen, double vBlue, double vTransparent=1.0); ~Color(); Color operator* (double vRhs) const; // returns multiplication of a scalar with a vector Color operator+ (const Color& vRhs) const; // returns the addition of this color with another color void Red(double vRed); double Red() const; void Green(double vGreen); double Green() const; void Blue(double vBlue); double Blue() const; void Transparent(double vTransparent); double Transparent() const; unsigned char RedByte() const; unsigned char GreenByte() const; unsigned char BlueByte() const; unsigned char TransparentByte() const; private: unsigned char ByteValue(double vZeroToOne) const; double mRed, mGreen, mBlue, mTransparent; }; } // namespace igraph #endif igraph/src/simpleraytracer/Point.cpp0000755000175100001440000000253313431000472017334 0ustar hornikusers#include "Point.h" #include namespace igraph { Point::Point() { X(0.0); Y(0.0); Z(0.0); Name(0); } Point::Point(double vX, double vY, double vZ, int vName) { X(vX); Y(vY); Z(vZ); Name(vName); } Point::Point(double vX, double vY, double vZ) { X(vX); Y(vY); Z(vZ); Name(0); } Point::~Point() {} double Point::X() const { return mX; } void Point::X(double vX) { mX = vX; } double Point::Y() const { return mY; } void Point::Y(double vY) { mY = vY; } double Point::Z() const { return mZ; } void Point::Z(double vZ) { mZ = vZ; } int Point::Name() const { return mName; } void Point::Name(int vName) { mName = vName; } double Point::Distance(const Point& rPoint) const { return sqrt( (rPoint.X() - mX)*(rPoint.X() - mX) + (rPoint.Y() - mY)*(rPoint.Y() - mY) + (rPoint.Z() - mZ)*(rPoint.Z() - mZ) ); } bool Point::operator==(const Point& vRhs) const { bool result = true; /* if ( mX + .001 <= vRhs.X() ) result = false; if ( mX - .001 >= vRhs.X() ) result = false; if ( mY + .001 <= vRhs.Y() ) result = false; if ( mY - .001 >= vRhs.Y() ) result = false; if ( mZ + .001 <= vRhs.Z() ) result = false; if ( mZ - .001 >= vRhs.Z() ) result = false; */ if ( mX != vRhs.X() ) result = false; if ( mY != vRhs.Y() ) result = false; if ( mZ != vRhs.Z() ) result = false; return result; } } // namespace igraph igraph/src/simpleraytracer/Triangle.cpp0000755000175100001440000000515113431000472020007 0ustar hornikusers#include "Triangle.h" #include namespace igraph { Triangle::Triangle() {} Triangle::Triangle(const Point& rPoint1, const Point& rPoint2, const Point& rPoint3) { Type("Triangle"); mPoint1 = rPoint1; mPoint2 = rPoint2; mPoint3 = rPoint3; } Triangle::~Triangle() { } bool Triangle::Intersect(const Ray& vRay, Point& rIntersectPoint) const { Vector pointb_minus_pointa (mPoint1, mPoint2); Vector pointb_minus_pointc (mPoint1, mPoint3); /* Vector plane_normal = pointb_minus_pointa.Cross(pointb_minus_pointc); // get the plane normal facing the right way: Vector plane_normal_normalized = plane_normal.Normalize(); Vector triangle_to_ray_origin = Vector(mPoint1, vRay.Origin() ); triangle_to_ray_origin.NormalizeThis(); if ( plane_normal_normalized.Dot(triangle_to_ray_origin) < 0.0 ) { plane_normal = plane_normal * -1.0; plane_normal_normalized = plane_normal_normalized * -1.0; } // check that the ray is actually facing the triangle Vector ray_direction_normalized = vRay.Direction().Normalize(); if ( plane_normal_normalized.Dot(ray_direction_normalized) > 0.0 ) return false; */ Vector plane_normal = this->Normal(mPoint1, vRay.Origin()); Vector ray_direction_normalized = vRay.Direction().Normalize(); if ( plane_normal.IsSameDirection(ray_direction_normalized) ) return false; Vector b_minus_u (vRay.Origin(), mPoint2); double t = plane_normal.Dot(b_minus_u) / plane_normal.Dot(vRay.Direction()); Point p = (vRay.Direction() * t) + vRay.Origin(); Vector p_minus_a (mPoint1, p); Vector p_minus_b (mPoint2, p); Vector p_minus_c (mPoint3, p); Vector pointc_minus_pointb (mPoint2, mPoint3); Vector pointa_minus_pointc (mPoint3, mPoint1); double test1 = (pointb_minus_pointa.Cross(p_minus_a)).Dot(plane_normal); double test2 = (pointc_minus_pointb.Cross(p_minus_b)).Dot(plane_normal); double test3 = (pointa_minus_pointc.Cross(p_minus_c)).Dot(plane_normal); if ((test1 > 0 && test2 > 0 && test3 > 0) || (test1 < 0 && test2 < 0 && test3 < 0)) { rIntersectPoint = p; return true; } else return false; } Vector Triangle::Normal(const Point& rSurfacePoint, const Point& rOffSurface) const { Vector pointb_minus_pointa (mPoint1, mPoint2); Vector pointb_minus_pointc (mPoint1, mPoint3); Vector plane_normal = pointb_minus_pointa.Cross(pointb_minus_pointc).Normalize(); // get the plane normal facing the right way: Vector triangle_to_off_surface_point = Vector(mPoint1, rOffSurface ); triangle_to_off_surface_point.NormalizeThis(); if ( !plane_normal.IsSameDirection(triangle_to_off_surface_point) ) { plane_normal.ReverseDirection(); } return plane_normal; } } // namespace igraph igraph/src/simpleraytracer/RayTracer.h0000755000175100001440000000255613431000472017611 0ustar hornikusers/** RayTraceCanvas.h */ #ifndef RAY_TRACER_H #define RAY_TRACER_H #include #include "Point.h" #include "Shape.h" #include "Color.h" #include "Light.h" namespace igraph { class Image { public: int width, height; double *red, *green, *blue, *trans; }; class RayTracer { public: RayTracer(); ~RayTracer(); void RayTrace(Image &result); void AddShape(Shape* pShape); void AddLight(Light* pLight); void BackgroundColor(const Color& rBackgroundColor); void EyePoint(const Point& rEyePoint); void AmbientColor(const Color& rAmbient); void AmbientIntensity(double vAmbientIntensity); private: Color Render(const Ray& rRay, bool vIsReflecting = false, const Shape* pReflectingFrom = 0 ); // vEyeRay should be true if the ray we are tracing is a ray from the eye, otherwise it should be false Shape* QueryScene(const Ray& rRay, Point& rIntersectionPoint, bool vIsReflecting = false, const Shape* pReflectingFrom = 0); double Shade(const Shape* pShapeToShade, const Point& rPointOnShapeToShade); double Specular(const Shape* pShapeToShade, const Point& rPointOnShapeToShade, const Light* pLight); Color mBackgroundColor; Color mAmbientColor; Point mEyePoint; Color mSpecularColor; double mAmbientIntensity; ShapeList* mpShapes; LightList* mpLights; int mRecursions; int mRecursionLimit; int mAntiAliasDetail; }; } // namespace igraph #endif igraph/src/simpleraytracer/Shape.cpp0000755000175100001440000000402313431000472017277 0ustar hornikusers#include "Shape.h" #include "unit_limiter.h" namespace igraph { Shape::Shape() { mName = 0; mAmbientReflectivity = .6; mSpecularReflectivity = 0; mDiffuseReflectivity = 0; mSpecularSize = 64; } Shape::~Shape() {} int Shape::Name() const { return mName; } void Shape::Name(int vName) { mName = vName; } const Color& Shape::ShapeColor() const { return mShapeColor; } void Shape::ShapeColor(const Color& rColor) { mShapeColor = rColor; } double Shape::AmbientReflectivity() const { return mAmbientReflectivity; } double Shape::SpecularReflectivity() const { return mSpecularReflectivity; } double Shape::DiffuseReflectivity() const { return mDiffuseReflectivity; } void Shape::AmbientReflectivity(double rReflectivity) { mAmbientReflectivity = unit_limiter(rReflectivity); } void Shape::SpecularReflectivity(double rReflectivity) { mSpecularReflectivity = unit_limiter(rReflectivity); } void Shape::DiffuseReflectivity(double rReflectivity) { mDiffuseReflectivity = unit_limiter(rReflectivity); } Ray Shape::Reflect(const Point& rReflectFrom, const Ray& rIncidentRay) const { Ray result; // the reflected ray Vector result_direction; // the reflected direction vector Vector incident_unit = rIncidentRay.Direction().Normalize(); Vector normal = this->Normal(rReflectFrom, rIncidentRay.Origin() ); if ( !normal.IsSameDirection(incident_unit) ) normal.ReverseDirection(); // we want the normal in the same direction of the incident ray. result.Origin(rReflectFrom); result.Direction( normal*2.0*normal.Dot(incident_unit) - incident_unit ); /* if ( normal.Dot(rIncidentRay.Direction().Normalize()) < 0.0 ) normal.ReverseDirection(); result.Origin(rReflectFrom); result.Direction((normal*2.0) - rIncidentRay.Direction().Normalize()); */ return result; } const string& Shape::Type() const { return mType; } void Shape::Type(const string& rType) { mType = rType; } int Shape::SpecularSize() const { return mSpecularSize; } void Shape::SpecularSize(int vSpecularSize) { mSpecularSize = vSpecularSize; } } // namespace igraph igraph/src/simpleraytracer/Triangle.h0000755000175100001440000000073513431000472017457 0ustar hornikusers/** Triangle.h */ #ifndef TRIANGLE_H #define TRIANGLE_H #include "Shape.h" namespace igraph { class Triangle : public Shape { public: Triangle(); Triangle(const Point& rPoint1, const Point& rPoint2, const Point& rPoint3); ~Triangle(); virtual bool Intersect(const Ray& vRay, Point& vIntersectPoint) const; virtual Vector Normal(const Point& rSurfacePoint, const Point& rOffSurface) const; private: Point mPoint1, mPoint2, mPoint3; }; } // namespace igraph #endif igraph/src/simpleraytracer/RIgraphRay.cpp0000644000175100001440000000514413431000472020251 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library R interface. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph.h" #include "igraph_error.h" #include "RayTracer.h" #include "Sphere.h" #include "config.h" #include #include #include using namespace igraph; extern "C" { SEXP R_igraph_getsphere(SEXP pos, SEXP radius, SEXP color, SEXP bgcolor, SEXP lightpos, SEXP lightcolor, SEXP width, SEXP height) { /* All error checking is done at the R level */ int i; double *spos=REAL(pos); double *scolor=REAL(color); double *svgcolor=REAL(bgcolor); int no_lights=GET_LENGTH(lightpos); RayTracer* p_ray_tracer; Sphere * sphere; int swidth=INTEGER(width)[0]; int sheight=INTEGER(height)[0]; int nopixels=swidth * sheight; SEXP result, dim; Image image; p_ray_tracer = new RayTracer(); p_ray_tracer->EyePoint(Point(0,0,0)); for (i=0; iIntensity(1); light->LightColor(Color(lcol[0], lcol[1], lcol[2])); p_ray_tracer->AddLight(light); } sphere = new Sphere(Point(spos[0], spos[1], spos[2]), REAL(radius)[0]); sphere->ShapeColor(Color(scolor[0], scolor[1], scolor[2])); p_ray_tracer->AddShape(sphere); PROTECT(result=NEW_NUMERIC(nopixels * 4)); PROTECT(dim=NEW_INTEGER(3)); INTEGER(dim)[0]=swidth; INTEGER(dim)[1]=sheight; INTEGER(dim)[2]=4; SET_DIM(result, dim); image.width=swidth; image.height=sheight; image.red=REAL(result); image.green=image.red + nopixels; image.blue=image.green + nopixels; image.trans=image.blue + nopixels; p_ray_tracer->RayTrace(image); delete p_ray_tracer; UNPROTECT(2); return result; } } // extern C igraph/src/simpleraytracer/Ray.h0000755000175100001440000000071413431000472016442 0ustar hornikusers/** Ray.h */ #ifndef RAY_H #define RAY_H #include "RayVector.h" #include "Point.h" namespace igraph { class Ray { public: Ray(); Ray(const Point& rOrigin, const Vector& rDirection); Ray(const Point& rOrigin, const Point& rEndPoint); ~Ray(); void Origin(Point vPoint); const Point& Origin() const; const Vector& Direction() const; void Direction(Vector vDirection); private: Vector mDirection; Point mOrigin; }; } // namespace igraph #endif igraph/src/simpleraytracer/RayTracer.cpp0000755000175100001440000002016513431000472020140 0ustar hornikusers#include "RayTracer.h" #include "unit_limiter.h" #include #include namespace igraph { RayTracer::RayTracer() : mBackgroundColor(0,0,0,0), mAmbientColor(0,0,0), mEyePoint(0,0,0), mSpecularColor(1,1,1) { // begin settings mAmbientIntensity = .7; mRecursionLimit = 700; mAntiAliasDetail = 1; // end settings mRecursions = 0; mpShapes = new ShapeList; mpLights = new LightList; } RayTracer::~RayTracer() { ShapeListIterator iter1 = mpShapes->begin(); while ( iter1 != mpShapes->end() ) { delete *iter1; iter1++; } delete mpShapes; LightListIterator iter2 = mpLights->begin(); while ( iter2 != mpLights->end() ) { delete *iter2; iter2++; } delete mpLights; } void RayTracer::RayTrace(Image &result) { int mWidth=result.width; int mHeight=result.height; Ray eye_ray(mEyePoint,Vector(0,0,1)); Color draw_color; double i_inc, j_inc, anti_alias_i_inc, anti_alias_j_inc; // amount to increment the ray in each direction double i, j, anti_alias_i, anti_alias_j; // the i and j values of the ray int pixel_x, pixel_y, anti_alias_pixel_x, anti_alias_pixel_y; // the pixels being drawn double average_red_byte, average_green_byte, average_blue_byte, average_trans_byte; int anti_alias_count; // the number of anti aliases (used in averaging) int idx=0; i_inc = 2.0/(double)mWidth; j_inc = 2.0/(double)mHeight; anti_alias_i_inc = 1.0/(double)mAntiAliasDetail; anti_alias_j_inc = 1.0/(double)mAntiAliasDetail; pixel_y = 0; j = 1.0; for (; pixel_y < mHeight; j -= j_inc, pixel_y++) { pixel_x = 0; i = -1.0; for (; pixel_x < mWidth; i += i_inc, pixel_x++) { anti_alias_pixel_y = 0; anti_alias_j = 0.0; average_red_byte = 0; average_green_byte = 0; average_blue_byte = 0; average_trans_byte = 0; anti_alias_count = 0; for (; anti_alias_pixel_y < mAntiAliasDetail; anti_alias_j += anti_alias_j_inc, anti_alias_pixel_y++) { anti_alias_pixel_x = 0; anti_alias_i = 0.0; for (; anti_alias_pixel_x < mAntiAliasDetail; anti_alias_i += anti_alias_i_inc, anti_alias_pixel_x++) { anti_alias_count++; eye_ray.Direction( Vector(i+(anti_alias_i*i_inc),j+(anti_alias_j*j_inc),1.0) ); draw_color = Render(eye_ray); average_red_byte = average_red_byte + ((double)draw_color.RedByte() - average_red_byte)/(double)anti_alias_count; average_green_byte = average_green_byte + ((double)draw_color.GreenByte() - average_green_byte)/(double)anti_alias_count; average_blue_byte = average_blue_byte + ((double)draw_color.BlueByte() - average_blue_byte)/(double)anti_alias_count; average_trans_byte = average_trans_byte + ((double)draw_color.TransparentByte() - average_trans_byte)/(double)anti_alias_count; } } result.red [idx] = average_red_byte/255; result.green[idx] = average_green_byte/255; result.blue [idx] = average_blue_byte/255; result.trans[idx] = average_trans_byte/255; idx++; } } } Color RayTracer::Render(const Ray& rRay, bool vIsReflecting, const Shape* pReflectingFrom ) { mRecursions++; Shape* closest_shape; Point intersect_point; Color result; if (vIsReflecting) closest_shape = QueryScene(rRay, intersect_point, vIsReflecting, pReflectingFrom); else closest_shape = QueryScene(rRay, intersect_point); if (closest_shape == NULL && !vIsReflecting) { mRecursions = 0; return mBackgroundColor; } if (closest_shape == NULL && vIsReflecting) { mRecursions = 0; return mAmbientColor*mAmbientIntensity; } if ( mRecursions > mRecursionLimit ) { mRecursions = 0; return Color(0,0,0); // mAmbientColor*mAmbientIntensity; } result = closest_shape->ShapeColor()*Shade(closest_shape, intersect_point); Ray backwards_ray(intersect_point,rRay.Direction()*-1); if ( closest_shape->DiffuseReflectivity() > 0.0 ) result = result + (Render( closest_shape->Reflect(intersect_point,backwards_ray), true, closest_shape )*closest_shape->DiffuseReflectivity()); return (result + mSpecularColor); } double RayTracer::Shade(const Shape* pShapeToShade, const Point& rPointOnShapeToShade) { double intensity = mAmbientIntensity * pShapeToShade->AmbientReflectivity(); // the ambient intensity of the scene Ray light_ray; // the ray that goes from the intersection point to the light sources double dot_product; Shape* closest_shape; // the shape closest from the intersection point to the light source Point light_intersect; // the intersection point of the ray that goes from the intersection point to the light source light_ray.Origin(rPointOnShapeToShade); // lightRay. org= object. intersect; Ray light_ray_from_light; LightListIterator iter = mpLights->begin(); mSpecularColor.Red(0); mSpecularColor.Green(0); mSpecularColor.Blue(0); while ( iter != mpLights->end() ) // foreach light in LightList do { light_ray.Direction(Vector(rPointOnShapeToShade,(*iter)->LightPoint())); // lightRay. dir= light. dir light_ray_from_light.Origin((*iter)->LightPoint()); light_ray_from_light.Direction(Vector((*iter)->LightPoint(),rPointOnShapeToShade)); closest_shape = QueryScene(light_ray_from_light, light_intersect); if ( closest_shape == NULL || (closest_shape == pShapeToShade && light_ray.Direction().Dot(pShapeToShade->Normal(rPointOnShapeToShade, light_ray_from_light.Origin() )) >= 0.0 ) ) //if (QueryScene( lightRay)= NIL) { Vector normal_vector = pShapeToShade->Normal(rPointOnShapeToShade, Point() ); dot_product = normal_vector.Dot(light_ray.Direction().Normalize()); dot_product *= (*iter)->Intensity(); if (dot_product < 0.0) { if (pShapeToShade->Type() == "Triangle") dot_product = dot_product*-1.0; else dot_product = 0.0; } intensity = unit_limiter( intensity + dot_product ); if ( light_ray.Direction().Dot(pShapeToShade->Normal(rPointOnShapeToShade, light_ray_from_light.Origin() )) >= 0.0 ) { double specular = Specular(pShapeToShade, rPointOnShapeToShade, *iter); mSpecularColor = mSpecularColor + Color(specular,specular,specular); } } iter++; } return intensity; } double RayTracer::Specular(const Shape* pShapeToShade, const Point& rPointOnShapeToShade, const Light* pLight) { Ray reflected = pShapeToShade->Reflect(rPointOnShapeToShade,Ray(rPointOnShapeToShade, pLight->LightPoint())); Vector eye_vector(rPointOnShapeToShade, mEyePoint); Vector reflected_vector = reflected.Direction().Normalize(); eye_vector.NormalizeThis(); double dot_product = eye_vector.Dot(reflected_vector); int n = pShapeToShade->SpecularSize(); double specular_intensity = dot_product/(n - n*dot_product+ dot_product); return unit_limiter(specular_intensity*pLight->Intensity()); } Shape* RayTracer::QueryScene(const Ray& rRay, Point& rIntersectionPoint, bool vIsReflecting, const Shape* pReflectingFrom) { Shape* closest_shape = NULL; Point intersect_point; double closest_distance; double intersect_distance; bool found_intersection = false; ShapeListIterator iter = mpShapes->begin(); while ( iter != mpShapes->end() ) { if ( (*iter)->Intersect( rRay, intersect_point ) ) { intersect_distance = intersect_point.Distance(rRay.Origin()); if ( !found_intersection && (*iter) != pReflectingFrom) { found_intersection = true; rIntersectionPoint = intersect_point; closest_shape = *iter; closest_distance = intersect_distance; } else if ( intersect_distance < closest_distance && (*iter) != pReflectingFrom ) { rIntersectionPoint = intersect_point; closest_shape = *iter; closest_distance = intersect_distance; } } iter++; } return closest_shape; } void RayTracer::AddShape(Shape* pShape) { // should check if a shape with the same name already exists mpShapes->push_back(pShape); } void RayTracer::AddLight(Light* pLight) { // should check if a shape with the same name already exists mpLights->push_back(pLight); } void RayTracer::BackgroundColor(const Color& rBackgroundColor) { mBackgroundColor = rBackgroundColor; } void RayTracer::EyePoint(const Point& rEyePoint) { mEyePoint = rEyePoint; } void RayTracer::AmbientColor(const Color& rAmbientColor) { mAmbientColor = rAmbientColor; } void RayTracer::AmbientIntensity(double vAmbientIntensity) { mAmbientIntensity = unit_limiter(vAmbientIntensity); } } // namespace igraph igraph/src/simpleraytracer/Sphere.cpp0000755000175100001440000000250113431000472017464 0ustar hornikusers#include "Sphere.h" #include namespace igraph { Sphere::Sphere() {} Sphere::Sphere(Point vCenter, double vRadius) { Type("Sphere"); mCenter = vCenter; mRadius = vRadius; } Sphere::~Sphere() { } bool Sphere::Intersect(const Ray& vRay, Point& vIntersectPoint) const { double c; Vector V; Vector EO(vRay.Origin(), mCenter); double v; double disc; double d; Vector E(Point(0,0,0), vRay.Origin()); // E = vector from origin to ray origin Vector P; c = mCenter.Distance(vRay.Origin()); //c = distance from eye to center of sphere V = vRay.Direction(); V.NormalizeThis(); v = EO.Dot(V); double v2 = V.Dot(EO.Normalize()); if (v2 >= 0.0) { disc = mRadius*mRadius - (EO.Dot(EO) - v*v); if (disc <= 0) return false; else { d = sqrt(disc); P = E + V*(v-d); vIntersectPoint = P.ToPoint(); return true; } } else return false; } Vector Sphere::Normal(const Point& rSurfacePoint, const Point& rOffSurface) const { // currently does not take rOffSurface point into account, // it should check if this point is inside the sphere, if it is // return a normal facing the center. Vector radius_vector (mCenter, rSurfacePoint); return (radius_vector.Normalize()); } double Sphere::Radius() const { return mRadius; } const Point& Sphere::Center() const { return mCenter; } } // namespace igraph igraph/src/simpleraytracer/unit_limiter.h0000755000175100001440000000021113431000472020403 0ustar hornikusers#ifndef ZERO_TO_ONE_H #define ZERO_TO_ONE_H namespace igraph { double unit_limiter(double vUnitDouble); } // namespace igraph #endif igraph/src/simpleraytracer/Shape.h0000755000175100001440000000302713431000472016747 0ustar hornikusers/** Shape.h */ #ifndef SHAPE_H #define SHAPE_H #include #include "Color.h" #include "Ray.h" #include "Point.h" #include using namespace std; namespace igraph { class Shape { public: Shape(); virtual ~Shape(); virtual bool Intersect(const Ray& rRay, Point& rIntersectPoint) const = 0; virtual Vector Normal(const Point& rSurfacePoint, const Point& rOffSurface) const = 0; // returns a normalized vector that is the normal of this shape from the surface point // it also takes the rOffSurface point into account, for example: // if rSurfacePoint is on top of a triangle, then the normal returned will be going up. Ray Reflect(const Point& rReflectFrom, const Ray& rRay) const; void Name(int vName); int Name() const; const Color& ShapeColor() const; void ShapeColor(const Color& rColor); double SpecularReflectivity() const; void SpecularReflectivity(double rReflectivity); double DiffuseReflectivity() const; void DiffuseReflectivity(double rReflectivity); double AmbientReflectivity() const; void AmbientReflectivity(double rReflectivity); int SpecularSize() const; void SpecularSize(int vSpecularSize); const string& Type() const; void Type(const string& rType); private: int mName; string mType; Color mShapeColor; double mSpecularReflectivity; // from 0 to 1 int mSpecularSize; // 1 to 64 double mDiffuseReflectivity; // from 0 to 1 double mAmbientReflectivity; // from 0 to 1 }; typedef list ShapeList; typedef list::iterator ShapeListIterator; } // namespace igraph #endif igraph/src/simpleraytracer/Sphere.h0000755000175100001440000000074213431000472017136 0ustar hornikusers/** Sphere.h */ #ifndef SPHERE_H #define SPHERE_H #include "Shape.h" namespace igraph { class Sphere : public Shape { public: Sphere(); Sphere(Point vCenter, double vRadius); ~Sphere(); virtual bool Intersect(const Ray& vRay, Point& vIntersectPoint) const; virtual Vector Normal(const Point& rSurfacePoint, const Point& rOffSurface) const; double Radius() const; const Point& Center() const; private: Point mCenter; double mRadius; }; } // namespace igraph #endif igraph/src/simpleraytracer/Point.h0000755000175100001440000000147313431000472017003 0ustar hornikusers/** this is a simple generic class representing a 3d point with a name. it also defines the PointList type, which is a linked list of Points */ #ifndef POINT_H #define POINT_H #include using namespace std; namespace igraph { class Point { public: Point(); // creates a point at the origin with name 0 Point(double vX, double vY, double vZ, int vName); Point(double vX, double vY, double vZ); ~Point(); double X() const; void X(double vX); double Y() const; void Y(double vY); double Z() const; void Z(double vZ); int Name() const; void Name(int vName); double Distance(const Point& rPoint) const; bool operator==(const Point& vRhs) const; private: double mX, mY, mZ; int mName; }; typedef list PointList; typedef list::iterator PointListIterator; } // namespace igraph #endif igraph/src/eigen.c0000644000175100001440000012117713431000472013567 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_eigen.h" #include "igraph_qsort.h" #include "igraph_blas.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include #include #include int igraph_i_eigen_arpackfun_to_mat(igraph_arpack_function_t *fun, int n, void *extra, igraph_matrix_t *res) { int i; igraph_vector_t v; IGRAPH_CHECK(igraph_matrix_init(res, n, n)); IGRAPH_FINALLY(igraph_matrix_destroy, res); IGRAPH_VECTOR_INIT_FINALLY(&v, n); VECTOR(v)[0]=1; IGRAPH_CHECK(fun(/*to=*/ &MATRIX(*res, 0, 0), /*from=*/ VECTOR(v), n, extra)); for (i=1; ihowmany-1, pr=0; IGRAPH_VECTOR_INIT_FINALLY(&val1, 0); IGRAPH_VECTOR_INIT_FINALLY(&val2, 0); if (vectors) { IGRAPH_CHECK(igraph_matrix_init(&vec1, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &vec1); IGRAPH_CHECK(igraph_matrix_init(&vec2, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &vec1); } IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ 1, /*iu=*/ which->howmany, /*abstol=*/ 1e-14, &val1, vectors ? &vec1 : 0, /*support=*/ 0)); IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ n-which->howmany+1, /*iu=*/ n, /*abstol=*/ 1e-14, &val2, vectors ? &vec2 : 0, /*support=*/ 0)); if (values) { IGRAPH_CHECK(igraph_vector_resize(values, which->howmany)); } if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, which->howmany)); } while (pr < which->howmany) { if (p2 < 0 || fabs(VECTOR(val1)[p1]) > fabs(VECTOR(val2)[p2])) { if (values) { VECTOR(*values)[pr]=VECTOR(val1)[p1]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec1,0,p1), sizeof(igraph_real_t) * (size_t) n); } p1++; pr++; } else { if (values) { VECTOR(*values)[pr]=VECTOR(val2)[p2]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec2,0,p2), sizeof(igraph_real_t) * (size_t) n); } p2--; pr++; } } if (vectors) { igraph_matrix_destroy(&vec2); igraph_matrix_destroy(&vec1); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_destroy(&val2); igraph_vector_destroy(&val1); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_sm(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { igraph_vector_t val; igraph_matrix_t vec; int i, w=0, n=(int) igraph_matrix_nrow(A); igraph_real_t small; int p1, p2, pr=0; IGRAPH_VECTOR_INIT_FINALLY(&val, 0); if (vectors) { IGRAPH_MATRIX_INIT_FINALLY(&vec, 0, 0); } IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_ALL, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ 0, /*iu=*/ 0, /*abstol=*/ 1e-14, &val, vectors ? &vec : 0, /*support=*/ 0)); /* Look for smallest value */ small=fabs(VECTOR(val)[0]); for (i=1; ihowmany)); } if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, which->howmany)); } while (pr < which->howmany) { if (p2 == n-1 || fabs(VECTOR(val)[p1]) < fabs(VECTOR(val)[p2])) { if (values) { VECTOR(*values)[pr]=VECTOR(val)[p1]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec,0,p1), sizeof(igraph_real_t) * (size_t) n); } p1--; pr++; } else { if (values) { VECTOR(*values)[pr]=VECTOR(val)[p2]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec,0,p2), sizeof(igraph_real_t) * (size_t) n); } p2++; pr++; } } if (vectors) { igraph_matrix_destroy(&vec); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&val); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_la(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { /* TODO: ordering? */ int n=(int) igraph_matrix_nrow(A); int il=n-which->howmany+1; IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ il, /*iu=*/ n, /*abstol=*/ 1e-14, values, vectors, /*support=*/ 0)); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_sa(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { /* TODO: ordering? */ IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ 1, /*iu=*/ which->howmany, /*abstol=*/ 1e-14, values, vectors, /*support=*/ 0)); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_be(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { /* TODO: ordering? */ igraph_matrix_t vec1, vec2; igraph_vector_t val1, val2; int n=(int) igraph_matrix_nrow(A); int p1=0, p2=which->howmany/2, pr=0; IGRAPH_VECTOR_INIT_FINALLY(&val1, 0); IGRAPH_VECTOR_INIT_FINALLY(&val2, 0); if (vectors) { IGRAPH_CHECK(igraph_matrix_init(&vec1, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &vec1); IGRAPH_CHECK(igraph_matrix_init(&vec2, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &vec1); } IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ 1, /*iu=*/ (which->howmany)/2, /*abstol=*/ 1e-14, &val1, vectors ? &vec1 : 0, /*support=*/ 0)); IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ n-(which->howmany)/2, /*iu=*/ n, /*abstol=*/ 1e-14, &val2, vectors ? &vec2 : 0, /*support=*/ 0)); if (values) { IGRAPH_CHECK(igraph_vector_resize(values, which->howmany)); } if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, which->howmany)); } while (pr < which->howmany) { if (pr % 2) { if (values) { VECTOR(*values)[pr]=VECTOR(val1)[p1]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec1,0,p1), sizeof(igraph_real_t) * (size_t) n); } p1++; pr++; } else { if (values) { VECTOR(*values)[pr]=VECTOR(val2)[p2]; } if (vectors) { memcpy(&MATRIX(*vectors,0,pr), &MATRIX(vec2,0,p2), sizeof(igraph_real_t) * (size_t) n); } p2--; pr++; } } if (vectors) { igraph_matrix_destroy(&vec2); igraph_matrix_destroy(&vec1); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_destroy(&val2); igraph_vector_destroy(&val1); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_all(const igraph_matrix_t *A, igraph_vector_t *values, igraph_matrix_t *vectors) { IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_ALL, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ 0, /*iu=*/ 0, /*abstol=*/ 1e-14, values, vectors, /*support=*/ 0)); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_iv(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_INTERVAL, /*vl=*/ which->vl, /*vu=*/ which->vu, /*vestimate=*/ which->vestimate, /*il=*/ 0, /*iu=*/ 0, /*abstol=*/ 1e-14, values, vectors, /*support=*/ 0)); return 0; } int igraph_i_eigen_matrix_symmetric_lapack_sel(const igraph_matrix_t *A, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { IGRAPH_CHECK(igraph_lapack_dsyevr(A, IGRAPH_LAPACK_DSYEV_SELECT, /*vl=*/ 0, /*vu=*/ 0, /*vestimate=*/ 0, /*il=*/ which->il, /*iu=*/ which->iu, /*abstol=*/ 1e-14, values, vectors, /*support=*/ 0)); return 0; } int igraph_i_eigen_matrix_symmetric_lapack(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, const igraph_eigen_which_t *which, igraph_vector_t *values, igraph_matrix_t *vectors) { const igraph_matrix_t *myA=A; igraph_matrix_t mA; /* First we need to create a dense square matrix */ if (A) { n=(int) igraph_matrix_nrow(A); } else if (sA) { n=(int) igraph_sparsemat_nrow(sA); IGRAPH_CHECK(igraph_matrix_init(&mA, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &mA); IGRAPH_CHECK(igraph_sparsemat_as_matrix(&mA, sA)); myA=&mA; } else if (fun) { IGRAPH_CHECK(igraph_i_eigen_arpackfun_to_mat(fun, n, extra, &mA)); IGRAPH_FINALLY(igraph_matrix_destroy, &mA); myA=&mA; } switch (which->pos) { case IGRAPH_EIGEN_LM: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_lm(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SM: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_sm(myA, which, values, vectors)); break; case IGRAPH_EIGEN_LA: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_la(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SA: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_sa(myA, which, values, vectors)); break; case IGRAPH_EIGEN_BE: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_be(myA, which, values, vectors)); break; case IGRAPH_EIGEN_ALL: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_all(myA, values, vectors)); break; case IGRAPH_EIGEN_INTERVAL: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_iv(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SELECT: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack_sel(myA, which, values, vectors)); break; default: /* This cannot happen */ break; } if (!A) { igraph_matrix_destroy(&mA); IGRAPH_FINALLY_CLEAN(1); } return 0; } typedef struct igraph_i_eigen_matrix_sym_arpack_data_t { const igraph_matrix_t *A; const igraph_sparsemat_t *sA; } igraph_i_eigen_matrix_sym_arpack_data_t; int igraph_i_eigen_matrix_sym_arpack_cb(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_eigen_matrix_sym_arpack_data_t *data= (igraph_i_eigen_matrix_sym_arpack_data_t *) extra; if (data->A) { igraph_blas_dgemv_array(/*transpose=*/ 0, /*alpha=*/ 1.0, data->A, from, /*beta=*/ 0.0, to); } else { /* data->sA */ igraph_vector_t vto, vfrom; igraph_vector_view(&vto, to, n); igraph_vector_view(&vfrom, to, n); igraph_vector_null(&vto); igraph_sparsemat_gaxpy(data->sA, &vfrom, &vto); } return 0; } int igraph_i_eigen_matrix_symmetric_arpack_be(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors) { igraph_vector_t tmpvalues, tmpvalues2; igraph_matrix_t tmpvectors, tmpvectors2; igraph_i_eigen_matrix_sym_arpack_data_t myextra = { A, sA }; int low=(int) floor(which->howmany/2.0), high=(int) ceil(which->howmany/2.0); int l1, l2, w; if (low + high >= n) { IGRAPH_ERROR("Requested too many eigenvalues/vectors", IGRAPH_EINVAL); } if (!fun) { fun=igraph_i_eigen_matrix_sym_arpack_cb; extra=(void*) &myextra; } IGRAPH_VECTOR_INIT_FINALLY(&tmpvalues, high); IGRAPH_MATRIX_INIT_FINALLY(&tmpvectors, n, high); IGRAPH_VECTOR_INIT_FINALLY(&tmpvalues2, low); IGRAPH_MATRIX_INIT_FINALLY(&tmpvectors2, n, low); options->n=n; options->nev=high; options->ncv= 2*options->nev < n ? 2*options->nev : n; options->which[0]='L'; options->which[1]='A'; IGRAPH_CHECK(igraph_arpack_rssolve(fun, extra, options, storage, &tmpvalues, &tmpvectors)); options->nev=low; options->ncv= 2*options->nev < n ? 2*options->nev : n; options->which[0]='S'; options->which[1]='A'; IGRAPH_CHECK(igraph_arpack_rssolve(fun, extra, options, storage, &tmpvalues2, &tmpvectors2)); IGRAPH_CHECK(igraph_vector_resize(values, low+high)); IGRAPH_CHECK(igraph_matrix_resize(vectors, n, low+high)); l1=0; l2=0; w=0; while (w < which->howmany) { VECTOR(*values)[w] = VECTOR(tmpvalues)[l1]; memcpy(&MATRIX(*vectors, 0, w), &MATRIX(tmpvectors, 0, l1), (size_t) n * sizeof(igraph_real_t)); w++; l1++; if (w < which->howmany) { VECTOR(*values)[w] = VECTOR(tmpvalues2)[l2]; memcpy(&MATRIX(*vectors, 0, w), &MATRIX(tmpvectors2, 0, l2), (size_t) n * sizeof(igraph_real_t)); w++; l2++; } } igraph_matrix_destroy(&tmpvectors2); igraph_vector_destroy(&tmpvalues2); igraph_matrix_destroy(&tmpvectors); igraph_vector_destroy(&tmpvalues); IGRAPH_FINALLY_CLEAN(4); return 0; } int igraph_i_eigen_matrix_symmetric_arpack(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors) { /* For ARPACK we need a matrix multiplication operation. This can be done in any format, so everything is fine, we don't have to convert. */ igraph_i_eigen_matrix_sym_arpack_data_t myextra = { A, sA }; if (!options) { IGRAPH_ERROR("`options' must be given for ARPACK algorithm", IGRAPH_EINVAL); } if (which->pos == IGRAPH_EIGEN_BE) { return igraph_i_eigen_matrix_symmetric_arpack_be(A, sA, fun, n, extra, which, options, storage, values, vectors); } else { switch (which->pos) { case IGRAPH_EIGEN_LM: options->which[0]='L'; options->which[1]='M'; options->nev=which->howmany; break; case IGRAPH_EIGEN_SM: options->which[0]='S'; options->which[1]='M'; options->nev=which->howmany; break; case IGRAPH_EIGEN_LA: options->which[0]='L'; options->which[1]='A'; options->nev=which->howmany; break; case IGRAPH_EIGEN_SA: options->which[0]='S'; options->which[1]='A'; options->nev=which->howmany; break; case IGRAPH_EIGEN_ALL: options->which[0]='L'; options->which[1]='M'; options->nev=n; break; case IGRAPH_EIGEN_INTERVAL: IGRAPH_ERROR("Interval of eigenvectors with ARPACK", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_SELECT: IGRAPH_ERROR("Selected eigenvalues with ARPACK", IGRAPH_UNIMPLEMENTED); /* TODO */ break; default: /* This cannot happen */ break; } options->n=n; options->ncv= 2*options->nev < n ? 2*options->nev : n; if (!fun) { fun=igraph_i_eigen_matrix_sym_arpack_cb; extra=(void*) &myextra; } IGRAPH_CHECK(igraph_arpack_rssolve(fun, extra, options, storage, values, vectors)); return 0; } } /* Get the eigenvalues and the eigenvectors from the compressed form. Order them according to the ordering criteria. Comparison functions for the reordering first */ typedef int (*igraph_i_eigen_matrix_lapack_cmp_t)(void*, const void*, const void *); typedef struct igraph_i_eml_cmp_t { const igraph_vector_t *mag, *real, *imag; } igraph_i_eml_cmp_t; /* TODO: these should be defined in some header */ #define EPS (DBL_EPSILON*100) #define LESS(a,b) ((a) < (b)-EPS) #define MORE(a,b) ((a) > (b)+EPS) #define ZERO(a) ((a) > -EPS && (a) < EPS) #define NONZERO(a) ((a) < -EPS || (a) > EPS) /* Largest magnitude. Ordering is according to 1 Larger magnitude 2 Real eigenvalues before complex ones 3 Larger real part 4 Larger imaginary part */ int igraph_i_eigen_matrix_lapack_cmp_lm(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_m=VECTOR(*myextra->mag)[*aa]; igraph_real_t b_m=VECTOR(*myextra->mag)[*bb]; if (LESS(a_m, b_m)) { return 1; } else if (MORE(a_m, b_m)) { return -1; } else { igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (ZERO(a_i) && NONZERO(b_i)) { return -1; } if (NONZERO(a_i) && ZERO(b_i)) { return 1; } if (MORE(a_r, b_r)) { return -1; } if (LESS(a_r, b_r)) { return 1; } if (MORE(a_i, b_i)) { return -1; } if (LESS(a_i, b_i)) { return 1; } } return 0; } /* Smallest marginude. Ordering is according to 1 Magnitude (smaller first) 2 Complex eigenvalues before real ones 3 Smaller real part 4 Smaller imaginary part This ensures that lm has exactly the opposite order to sm */ int igraph_i_eigen_matrix_lapack_cmp_sm(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_m=VECTOR(*myextra->mag)[*aa]; igraph_real_t b_m=VECTOR(*myextra->mag)[*bb]; if (MORE(a_m, b_m)) { return 1; } else if (LESS(a_m, b_m)) { return -1; } else { igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (NONZERO(a_i) && ZERO(b_i)) { return -1; } if (ZERO(a_i) && NONZERO(b_i)) { return 1; } if (LESS(a_r, b_r)) { return -1; } if (MORE(a_r, b_r)) { return 1; } if (LESS(a_i, b_i)) { return -1; } if (MORE(a_i, b_i)) { return 1; } } return 0; } /* Largest real part. Ordering is according to 1 Larger real part 2 Real eigenvalues come before complex ones 3 Larger complex part */ int igraph_i_eigen_matrix_lapack_cmp_lr(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; if (MORE(a_r, b_r)) { return -1; } else if (LESS(a_r, b_r)) { return 1; } else { igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (ZERO(a_i) && NONZERO(b_i)) { return -1; } if (NONZERO(a_i) && ZERO(b_i)) { return 1; } if (MORE(a_i, b_i)) { return -1; } if (LESS(a_i, b_i)) { return 1; } } return 0; } /* Largest real part. Ordering is according to 1 Smaller real part 2 Complex eigenvalues come before real ones 3 Smaller complex part This is opposite to LR */ int igraph_i_eigen_matrix_lapack_cmp_sr(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; if (LESS(a_r, b_r)) { return -1; } else if (MORE(a_r, b_r)) { return 1; } else { igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (NONZERO(a_i) && ZERO(b_i)) { return -1; } if (ZERO(a_i) && NONZERO(b_i)) { return 1; } if (LESS(a_i, b_i)) { return -1; } if (MORE(a_i, b_i)) { return 1; } } return 0; } /* Order: 1 Larger imaginary part 2 Real eigenvalues before complex ones 3 Larger real part */ int igraph_i_eigen_matrix_lapack_cmp_li(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (MORE(a_i, b_i)) { return -1; } else if (LESS(a_i, b_i)) { return 1; } else { igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; if (ZERO(a_i) && NONZERO(b_i)) { return -1; } if (NONZERO(a_i) && ZERO(b_i)) { return 1; } if (MORE(a_r, b_r)) { return -1; } if (LESS(a_r, b_r)) { return 1; } } return 0; } /* Order: 1 Smaller imaginary part 2 Complex eigenvalues before real ones 3 Smaller real part Order is opposite to LI */ int igraph_i_eigen_matrix_lapack_cmp_si(void *extra, const void *a, const void *b) { igraph_i_eml_cmp_t *myextra=(igraph_i_eml_cmp_t *) extra; int *aa=(int*) a, *bb=(int*) b; igraph_real_t a_i=VECTOR(*myextra->imag)[*aa]; igraph_real_t b_i=VECTOR(*myextra->imag)[*bb]; if (LESS(a_i, b_i)) { return -1; } else if (MORE(a_i, b_i)) { return 1; } else { igraph_real_t a_r=VECTOR(*myextra->real)[*aa]; igraph_real_t b_r=VECTOR(*myextra->real)[*bb]; if (NONZERO(a_i) && ZERO(b_i)) { return -1; } if (ZERO(a_i) && NONZERO(b_i)) { return 1; } if (LESS(a_r, b_r)) { return -1; } if (MORE(a_r, b_r)) { return 1; } } return 0; } #undef EPS #undef LESS #undef MORE #undef ZERO #undef NONZERO #define INITMAG() \ do { \ int i; \ IGRAPH_VECTOR_INIT_FINALLY(&mag, nev); \ hasmag=1; \ for (i=0; ipos) { case IGRAPH_EIGEN_LM: INITMAG(); cmpfunc=igraph_i_eigen_matrix_lapack_cmp_lm; howmany=which->howmany; break; case IGRAPH_EIGEN_ALL: INITMAG(); cmpfunc=igraph_i_eigen_matrix_lapack_cmp_sm; howmany=nev; break; case IGRAPH_EIGEN_SM: INITMAG(); cmpfunc=igraph_i_eigen_matrix_lapack_cmp_sm; howmany=which->howmany; break; case IGRAPH_EIGEN_LR: cmpfunc=igraph_i_eigen_matrix_lapack_cmp_lr; howmany=which->howmany; break; case IGRAPH_EIGEN_SR: cmpfunc=igraph_i_eigen_matrix_lapack_cmp_sr; howmany=which->howmany; break; case IGRAPH_EIGEN_SELECT: INITMAG(); cmpfunc=igraph_i_eigen_matrix_lapack_cmp_sm; start=which->il-1; howmany=which->iu - which->il + 1; break; case IGRAPH_EIGEN_LI: cmpfunc=igraph_i_eigen_matrix_lapack_cmp_li; howmany=which->howmany; break; case IGRAPH_EIGEN_SI: cmpfunc=igraph_i_eigen_matrix_lapack_cmp_si; howmany=which->howmany; break; case IGRAPH_EIGEN_INTERVAL: case IGRAPH_EIGEN_BE: default: IGRAPH_ERROR("Unimplemented eigenvalue ordering", IGRAPH_UNIMPLEMENTED); break; } for (i=0; ipos) { case IGRAPH_EIGEN_LM: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_lm(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SM: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_sm(myA, which, values, vectors)); break; case IGRAPH_EIGEN_LR: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_lr(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SR: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_sr(myA, which, values, vectors)); break; case IGRAPH_EIGEN_LI: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_li(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SI: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_si(myA, which, values, vectors)); break; case IGRAPH_EIGEN_SELECT: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_select(myA, which, values, vectors)); break; case IGRAPH_EIGEN_ALL: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack_all(myA, which, values, vectors)); break; default: /* This cannot happen */ break; } if (!A) { igraph_matrix_destroy(&mA); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_eigen_checks(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n) { if ( (A?1:0)+(sA?1:0)+(fun?1:0) != 1) { IGRAPH_ERROR("Exactly one of 'A', 'sA' and 'fun' must be given", IGRAPH_EINVAL); } if (A) { if (n != igraph_matrix_ncol(A) || n != igraph_matrix_nrow(A)) { IGRAPH_ERROR("Invalid matrix", IGRAPH_NONSQUARE); } } else if (sA) { if (n != igraph_sparsemat_ncol(sA) || n != igraph_sparsemat_nrow(sA)) { IGRAPH_ERROR("Invalid matrix", IGRAPH_NONSQUARE); } } return 0; } /** * \function igraph_eigen_matrix_symmetric * * \example examples/simple/igraph_eigen_matrix_symmetric.c */ int igraph_eigen_matrix_symmetric(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors) { IGRAPH_CHECK(igraph_i_eigen_checks(A, sA, fun, n)); if (which->pos != IGRAPH_EIGEN_LM && which->pos != IGRAPH_EIGEN_SM && which->pos != IGRAPH_EIGEN_LA && which->pos != IGRAPH_EIGEN_SA && which->pos != IGRAPH_EIGEN_BE && which->pos != IGRAPH_EIGEN_ALL && which->pos != IGRAPH_EIGEN_INTERVAL && which->pos != IGRAPH_EIGEN_SELECT) { IGRAPH_ERROR("Invalid 'pos' position in 'which'", IGRAPH_EINVAL); } switch (algorithm) { case IGRAPH_EIGEN_AUTO: if (which->howmany==n || n < 100) { IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack(A, sA, fun, n, extra, which, values, vectors)); } else { IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_arpack(A, sA, fun, n, extra, which, options, storage, values, vectors)); } break; case IGRAPH_EIGEN_LAPACK: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_lapack(A, sA, fun, n ,extra, which, values, vectors)); break; case IGRAPH_EIGEN_ARPACK: IGRAPH_CHECK(igraph_i_eigen_matrix_symmetric_arpack(A, sA, fun, n, extra, which, options, storage, values, vectors)); break; default: IGRAPH_ERROR("Unknown 'algorithm'", IGRAPH_EINVAL); } return 0; } /** * \function igraph_eigen_matrix * */ int igraph_eigen_matrix(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_complex_t *values, igraph_matrix_complex_t *vectors) { IGRAPH_CHECK(igraph_i_eigen_checks(A, sA, fun, n)); if (which->pos != IGRAPH_EIGEN_LM && which->pos != IGRAPH_EIGEN_SM && which->pos != IGRAPH_EIGEN_LR && which->pos != IGRAPH_EIGEN_SR && which->pos != IGRAPH_EIGEN_LI && which->pos != IGRAPH_EIGEN_SI && which->pos != IGRAPH_EIGEN_SELECT && which->pos != IGRAPH_EIGEN_ALL) { IGRAPH_ERROR("Invalid 'pos' position in 'which'", IGRAPH_EINVAL); } switch (algorithm) { case IGRAPH_EIGEN_AUTO: IGRAPH_ERROR("'AUTO' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_LAPACK: IGRAPH_CHECK(igraph_i_eigen_matrix_lapack(A, sA, fun, n, extra, which, values, vectors)); /* TODO */ break; case IGRAPH_EIGEN_ARPACK: IGRAPH_ERROR("'ARPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_COMP_AUTO: IGRAPH_ERROR("'COMP_AUTO' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_COMP_LAPACK: IGRAPH_ERROR("'COMP_LAPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_COMP_ARPACK: IGRAPH_ERROR("'COMP_ARPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; default: IGRAPH_ERROR("Unknown `algorithm'", IGRAPH_EINVAL); } return 0; } int igraph_i_eigen_adjacency_arpack_sym_cb(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_adjlist_t *adjlist = (igraph_adjlist_t *) extra; igraph_vector_int_t *neis; int i, j, nlen; for (i=0; ipos == IGRAPH_EIGEN_INTERVAL) { IGRAPH_ERROR("ARPACK adjacency eigensolver does not implement " "`INTERNAL' eigenvalues", IGRAPH_UNIMPLEMENTED); } if (which->pos == IGRAPH_EIGEN_SELECT) { IGRAPH_ERROR("ARPACK adjacency eigensolver does not implement " "`SELECT' eigenvalues", IGRAPH_UNIMPLEMENTED); } if (which->pos == IGRAPH_EIGEN_ALL) { IGRAPH_ERROR("ARPACK adjacency eigensolver does not implement " "`ALL' eigenvalues", IGRAPH_UNIMPLEMENTED); } switch (which->pos) { case IGRAPH_EIGEN_LM: options->which[0]='L'; options->which[1]='M'; options->nev=which->howmany; break; case IGRAPH_EIGEN_SM: options->which[0]='S'; options->which[1]='M'; options->nev=which->howmany; break; case IGRAPH_EIGEN_LA: options->which[0]='L'; options->which[1]='A'; options->nev=which->howmany; break; case IGRAPH_EIGEN_SA: options->which[0]='S'; options->which[1]='A'; options->nev=which->howmany; break; case IGRAPH_EIGEN_ALL: options->which[0]='L'; options->which[1]='M'; options->nev=n; break; case IGRAPH_EIGEN_BE: IGRAPH_ERROR("Eigenvectors from both ends with ARPACK", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_INTERVAL: IGRAPH_ERROR("Interval of eigenvectors with ARPACK", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_SELECT: IGRAPH_ERROR("Selected eigenvalues with ARPACK", IGRAPH_UNIMPLEMENTED); /* TODO */ break; default: /* This cannot happen */ break; } options->n=n; options->ncv= 2*options->nev < n ? 2*options->nev : n; IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_eigen_adjacency_arpack_sym_cb, extra, options, storage, values, vectors)); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_eigen_adjacency * */ int igraph_eigen_adjacency(const igraph_t *graph, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_complex_t *cmplxvalues, igraph_matrix_complex_t *cmplxvectors) { if (which->pos != IGRAPH_EIGEN_LM && which->pos != IGRAPH_EIGEN_SM && which->pos != IGRAPH_EIGEN_LA && which->pos != IGRAPH_EIGEN_SA && which->pos != IGRAPH_EIGEN_BE && which->pos != IGRAPH_EIGEN_SELECT && which->pos != IGRAPH_EIGEN_INTERVAL && which->pos != IGRAPH_EIGEN_ALL) { IGRAPH_ERROR("Invalid 'pos' position in 'which'", IGRAPH_EINVAL); } switch (algorithm) { case IGRAPH_EIGEN_AUTO: IGRAPH_ERROR("'AUTO' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_LAPACK: IGRAPH_ERROR("'LAPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_ARPACK: IGRAPH_CHECK(igraph_i_eigen_adjacency_arpack(graph, which, options, storage, values, vectors, cmplxvalues, cmplxvectors)); break; case IGRAPH_EIGEN_COMP_AUTO: IGRAPH_ERROR("'COMP_AUTO' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_COMP_LAPACK: IGRAPH_ERROR("'COMP_LAPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; case IGRAPH_EIGEN_COMP_ARPACK: IGRAPH_ERROR("'COMP_ARPACK' algorithm not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ break; default: IGRAPH_ERROR("Unknown `algorithm'", IGRAPH_EINVAL); } return 0; } /** * \function igraph_eigen_laplacian * */ int igraph_eigen_laplacian(const igraph_t *graph, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_complex_t *cmplxvalues, igraph_matrix_complex_t *cmplxvectors) { IGRAPH_ERROR("'igraph_eigen_laplacian'", IGRAPH_UNIMPLEMENTED); /* TODO */ return 0; } igraph/src/matrix.pmt0000644000175100001440000013237413430770203014370 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include #include /* memcpy & co. */ #include /** * \section about_igraph_matrix_t_objects About \type igraph_matrix_t objects * * This type is just an interface to \type igraph_vector_t. * * The \type igraph_matrix_t type usually stores n * elements in O(n) space, but not always. See the documentation of * the vector type. */ /** * \section igraph_matrix_constructor_and_destructor Matrix constructors and * destructors */ /** * \ingroup matrix * \function igraph_matrix_init * \brief Initializes a matrix. * * * Every matrix needs to be initialized before using it. This is done * by calling this function. A matrix has to be destroyed if it is not * needed any more; see \ref igraph_matrix_destroy(). * \param m Pointer to a not yet initialized matrix object to be * initialized. * \param nrow The number of rows in the matrix. * \param ncol The number of columns in the matrix. * \return Error code. * * Time complexity: usually O(n), * n is the * number of elements in the matrix. */ int FUNCTION(igraph_matrix,init)(TYPE(igraph_matrix) *m, long int nrow, long int ncol) { int ret1; ret1=FUNCTION(igraph_vector,init)(&m->data, nrow*ncol); m->nrow=nrow; m->ncol=ncol; return ret1; } const TYPE(igraph_matrix) *FUNCTION(igraph_matrix,view)(const TYPE(igraph_matrix) *m, const BASE *data, long int nrow, long int ncol) { TYPE(igraph_matrix) *m2=(TYPE(igraph_matrix)*)m; FUNCTION(igraph_vector,view)(&m2->data, data, nrow * ncol); m2->nrow=nrow; m2->ncol=ncol; return m; } /** * \ingroup matrix * \function igraph_matrix_destroy * \brief Destroys a matrix object. * * * This function frees all the memory allocated for a matrix * object. The destroyed object needs to be reinitialized before using * it again. * \param m The matrix to destroy. * * Time complexity: operating system dependent. */ void FUNCTION(igraph_matrix,destroy)(TYPE(igraph_matrix) *m) { FUNCTION(igraph_vector,destroy)(&m->data); } /** * \ingroup matrix * \function igraph_matrix_capacity * \brief Returns the number of elements allocated for a matrix. * * Note that this might be different from the size of the matrix (as * queried by \ref igraph_matrix_size(), and specifies how many elements * the matrix can hold, without reallocation. * \param v Pointer to the (previously initialized) matrix object * to query. * \return The allocated capacity. * * \sa \ref igraph_matrix_size(), \ref igraph_matrix_nrow(), * \ref igraph_matrix_ncol(). * * Time complexity: O(1). */ long int FUNCTION(igraph_matrix,capacity)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,capacity)(&m->data); } /** * \section igraph_matrix_accessing_elements Accessing elements of a matrix */ /** * \ingroup matrix * \function igraph_matrix_resize * \brief Resizes a matrix. * * * This function resizes a matrix by adding more elements to it. * The matrix contains arbitrary data after resizing it. * That is, after calling this function you cannot expect that element * (i,j) in the matrix remains the * same as before. * \param m Pointer to an already initialized matrix object. * \param nrow The number of rows in the resized matrix. * \param ncol The number of columns in the resized matrix. * \return Error code. * * Time complexity: O(1) if the * matrix gets smaller, usually O(n) * if it gets larger, n is the * number of elements in the resized matrix. */ int FUNCTION(igraph_matrix,resize)(TYPE(igraph_matrix) *m, long int nrow, long int ncol) { FUNCTION(igraph_vector,resize)(&m->data, nrow*ncol); m->nrow=nrow; m->ncol=ncol; return 0; } /** * \ingroup matrix * \function igraph_matrix_resize_min * \brief Deallocates unused memory for a matrix. * * * Note that this function might fail if there is not enough memory * available. * * * Also note, that this function leaves the matrix intact, i.e. * it does not destroy any of the elements. However, usually it involves * copying the matrix in memory. * \param m Pointer to an initialized matrix. * \return Error code. * * \sa \ref igraph_matrix_resize(). * * Time complexity: operating system dependent. */ int FUNCTION(igraph_matrix,resize_min)(TYPE(igraph_matrix) *m) { TYPE(igraph_vector) tmp; long int size=FUNCTION(igraph_matrix,size)(m); long int capacity=FUNCTION(igraph_matrix,capacity)(m); if (size == capacity) { return 0; } IGRAPH_CHECK(FUNCTION(igraph_vector,init)(&tmp, size)); FUNCTION(igraph_vector,update)(&tmp, &m->data); FUNCTION(igraph_vector,destroy)(&m->data); m->data = tmp; return 0; } /** * \ingroup matrix * \function igraph_matrix_size * \brief The number of elements in a matrix. * * \param m Pointer to an initialized matrix object. * \return The size of the matrix. * * Time complexity: O(1). */ long int FUNCTION(igraph_matrix,size)(const TYPE(igraph_matrix) *m) { return (m->nrow) * (m->ncol); } /** * \ingroup matrix * \function igraph_matrix_nrow * \brief The number of rows in a matrix. * * \param m Pointer to an initialized matrix object. * \return The number of rows in the matrix. * * Time complexity: O(1). */ long int FUNCTION(igraph_matrix,nrow)(const TYPE(igraph_matrix) *m) { return m->nrow; } /** * \ingroup matrix * \function igraph_matrix_ncol * \brief The number of columns in a matrix. * * \param m Pointer to an initialized matrix object. * \return The number of columns in the matrix. * * Time complexity: O(1). */ long int FUNCTION(igraph_matrix,ncol)(const TYPE(igraph_matrix) *m) { return m->ncol; } /** * \ingroup matrix * \function igraph_matrix_copy_to * \brief Copies a matrix to a regular C array. * * * The matrix is copied columnwise, as this is the format most * programs and languages use. * The C array should be of sufficient size; there are (of course) no * range checks. * \param m Pointer to an initialized matrix object. * \param to Pointer to a C array; the place to copy the data to. * \return Error code. * * Time complexity: O(n), * n is the number of * elements in the matrix. */ void FUNCTION(igraph_matrix,copy_to)(const TYPE(igraph_matrix) *m, BASE *to) { FUNCTION(igraph_vector,copy_to)(&m->data, to); } /** * \ingroup matrix * \function igraph_matrix_null * \brief Sets all elements in a matrix to zero. * * \param m Pointer to an initialized matrix object. * * Time complexity: O(n), * n is the number of elements in * the matrix. */ void FUNCTION(igraph_matrix,null)(TYPE(igraph_matrix) *m) { FUNCTION(igraph_vector,null)(&m->data); } /** * \ingroup matrix * \function igraph_matrix_add_cols * \brief Adds columns to a matrix. * \param m The matrix object. * \param n The number of columns to add. * \return Error code, \c IGRAPH_ENOMEM if there is * not enough memory to perform the operation. * * Time complexity: linear with the number of elements of the new, * resized matrix. */ int FUNCTION(igraph_matrix,add_cols)(TYPE(igraph_matrix) *m, long int n) { FUNCTION(igraph_matrix,resize)(m, m->nrow, m->ncol+n); return 0; } /** * \ingroup matrix * \function igraph_matrix_add_rows * \brief Adds rows to a matrix. * \param m The matrix object. * \param n The number of rows to add. * \return Error code, \c IGRAPH_ENOMEM if there * isn't enough memory for the operation. * * Time complexity: linear with the number of elements of the new, * resized matrix. */ int FUNCTION(igraph_matrix,add_rows)(TYPE(igraph_matrix) *m, long int n) { long int i; FUNCTION(igraph_vector,resize)(&m->data, (m->ncol)*(m->nrow+n)); for (i=m->ncol-1; i>=0; i--) { FUNCTION(igraph_vector,move_interval2)(&m->data, (m->nrow)*i, (m->nrow)*(i+1), (m->nrow+n)*i); } m->nrow += n; return 0; } /** * \ingroup matrix * \function igraph_matrix_remove_col * \brief Removes a column from a matrix. * * \param m The matrix object. * \param col The column to remove. * \return Error code, always returns with success. * * Time complexity: linear with the number of elements of the new, * resized matrix. */ int FUNCTION(igraph_matrix,remove_col)(TYPE(igraph_matrix) *m, long int col) { FUNCTION(igraph_vector,remove_section)(&m->data, (m->nrow)*col, (m->nrow)*(col+1)); m->ncol--; return 0; } /** * \ingroup matrix * \function igraph_matrix_permdelete_rows * \brief Removes rows from a matrix (for internal use). * * Time complexity: linear with the number of elements of the original * matrix. */ int FUNCTION(igraph_matrix,permdelete_rows)(TYPE(igraph_matrix) *m, long int *index, long int nremove) { long int i, j; for (j=0; jnrow; j++) { if (index[j] != 0) { for (i=0; incol; i++) { MATRIX(*m, index[j]-1, i) = MATRIX(*m, j, i); } } } /* Remove unnecessary elements from the end of each column */ for (i=0; incol; i++) FUNCTION(igraph_vector,remove_section)(&m->data, (i+1)*(m->nrow-nremove), (i+1)*(m->nrow-nremove)+nremove); FUNCTION(igraph_matrix,resize)(m, m->nrow-nremove, m->ncol); return 0; } /** * \ingroup matrix * \function igraph_matrix_delete_rows_neg * \brief Removes columns from a matrix (for internal use). * * Time complexity: linear with the number of elements of the original * matrix. */ int FUNCTION(igraph_matrix,delete_rows_neg)(TYPE(igraph_matrix) *m, const igraph_vector_t *neg, long int nremove) { long int i, j, idx=0; for (i=0; incol; i++) { for (j=0; jnrow; j++) { if (VECTOR(*neg)[j] >= 0) { MATRIX(*m, idx++, i) = MATRIX(*m, j, i); } } idx=0; } FUNCTION(igraph_matrix,resize)(m, m->nrow-nremove, m->ncol); return 0; } /** * \ingroup matrix * \function igraph_matrix_copy * \brief Copies a matrix. * * * Creates a matrix object by copying from an existing matrix. * \param to Pointer to an uninitialized matrix object. * \param from The initialized matrix object to copy. * \return Error code, \c IGRAPH_ENOMEM if there * isn't enough memory to allocate the new matrix. * * Time complexity: O(n), the number * of elements in the matrix. */ int FUNCTION(igraph_matrix,copy)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from) { to->nrow = from->nrow; to->ncol = from->ncol; return FUNCTION(igraph_vector,copy)(&to->data, &from->data); } #ifndef NOTORDERED /** * \function igraph_matrix_max * * Returns the maximal element of a matrix. * \param m The matrix object. * \return The maximum element. For empty matrix the returned value is * undefined. * * Added in version 0.2. * * Time complexity: O(n), the number of elements in the matrix. */ igraph_real_t FUNCTION(igraph_matrix,max)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,max)(&m->data); } #endif /** * \function igraph_matrix_scale * * Multiplies each element of the matrix by a constant. * \param m The matrix. * \param by The constant. * * Added in version 0.2. * * Time complexity: O(n), the number of elements in the matrix. */ void FUNCTION(igraph_matrix,scale)(TYPE(igraph_matrix) *m, BASE by) { FUNCTION(igraph_vector,scale)(&m->data, by); } /** * \function igraph_matrix_select_rows * \brief Select some rows of a matrix. * * This function selects some rows of a matrix and returns them in a * new matrix. The result matrix should be initialized before calling * the function. * \param m The input matrix. * \param res The result matrix. It should be initialized and will be * resized as needed. * \param rows Vector; it contains the row indices (starting with * zero) to extract. Note that no range checking is performed. * \return Error code. * * Time complexity: O(nm), n is the number of rows, m the number of * columns of the result matrix. */ int FUNCTION(igraph_matrix,select_rows)(const TYPE(igraph_matrix) *m, TYPE(igraph_matrix) *res, const igraph_vector_t *rows) { long int norows=igraph_vector_size(rows); long int i, j, ncols=FUNCTION(igraph_matrix,ncol)(m); IGRAPH_CHECK(FUNCTION(igraph_matrix,resize)(res, norows, ncols)); for (i=0; i=m->ncol) { IGRAPH_ERROR("Index out of range for selecting matrix column", IGRAPH_EINVAL); } IGRAPH_CHECK(FUNCTION(igraph_vector,get_interval)(&m->data, res, nrow*index, nrow*(index+1))); return 0; } /** * \function igraph_matrix_sum * \brief Sum of elements. * * Returns the sum of the elements of a matrix. * \param m The input matrix. * \return The sum of the elements. * * Time complexity: O(mn), the number of elements in the matrix. */ BASE FUNCTION(igraph_matrix,sum)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,sum)(&m->data); } /** * \function igraph_matrix_all_e * \brief Are all elements equal? * * \param lhs The first matrix. * \param rhs The second matrix. * \return Positive integer (=true) if the elements in the \p lhs are all * equal to the corresponding elements in \p rhs. Returns \c 0 * (=false) if the dimensions of the matrices don't match. * * Time complexity: O(nm), the size of the matrices. */ igraph_bool_t FUNCTION(igraph_matrix,all_e)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return lhs->ncol==rhs->ncol && lhs->nrow==rhs->nrow && FUNCTION(igraph_vector,all_e)(&lhs->data, &rhs->data); } igraph_bool_t FUNCTION(igraph_matrix,is_equal)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return FUNCTION(igraph_matrix,all_e)(lhs, rhs); } #ifndef NOTORDERED /** * \function igraph_matrix_all_l * \brief Are all elements less? * * \param lhs The first matrix. * \param rhs The second matrix. * \return Positive integer (=true) if the elements in the \p lhs are all * less than the corresponding elements in \p rhs. Returns \c 0 * (=false) if the dimensions of the matrices don't match. * * Time complexity: O(nm), the size of the matrices. */ igraph_bool_t FUNCTION(igraph_matrix,all_l)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return lhs->ncol==rhs->ncol && lhs->nrow==rhs->nrow && FUNCTION(igraph_vector,all_l)(&lhs->data, &rhs->data); } /** * \function igraph_matrix_all_g * \brief Are all elements greater? * * \param lhs The first matrix. * \param rhs The second matrix. * \return Positive integer (=true) if the elements in the \p lhs are all * greater than the corresponding elements in \p rhs. Returns \c 0 * (=false) if the dimensions of the matrices don't match. * * Time complexity: O(nm), the size of the matrices. */ igraph_bool_t FUNCTION(igraph_matrix,all_g)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return lhs->ncol==rhs->ncol && lhs->nrow==rhs->nrow && FUNCTION(igraph_vector,all_g)(&lhs->data, &rhs->data); } /** * \function igraph_matrix_all_le * \brief Are all elements less or equal? * * \param lhs The first matrix. * \param rhs The second matrix. * \return Positive integer (=true) if the elements in the \p lhs are all * less than or equal to the corresponding elements in \p * rhs. Returns \c 0 (=false) if the dimensions of the matrices * don't match. * * Time complexity: O(nm), the size of the matrices. */ igraph_bool_t FUNCTION(igraph_matrix,all_le)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return lhs->ncol==rhs->ncol && lhs->nrow==rhs->nrow && FUNCTION(igraph_vector,all_le)(&lhs->data, &rhs->data); } /** * \function igraph_matrix_all_ge * \brief Are all elements greater or equal? * * \param lhs The first matrix. * \param rhs The second matrix. * \return Positive integer (=true) if the elements in the \p lhs are all * greater than or equal to the corresponding elements in \p * rhs. Returns \c 0 (=false) if the dimensions of the matrices * don't match. * * Time complexity: O(nm), the size of the matrices. */ igraph_bool_t FUNCTION(igraph_matrix,all_ge)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs) { return lhs->ncol==rhs->ncol && lhs->nrow==rhs->nrow && FUNCTION(igraph_vector,all_ge)(&lhs->data, &rhs->data); } #endif #ifndef NOTORDERED /** * \function igraph_matrix_maxdifference * \brief Maximum absolute difference between two matrices. * * Calculate the maximum absolute difference of two matrices. Both matrices * must be non-empty. If their dimensions differ then a warning is given and * the comparison is performed by vectors columnwise from both matrices. * The remaining elements in the larger vector are ignored. * \param m1 The first matrix. * \param m2 The second matrix. * \return The element with the largest absolute value in \c m1 - \c m2. * * Time complexity: O(mn), the elements in the smaller matrix. */ igraph_real_t FUNCTION(igraph_matrix,maxdifference)(const TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2) { long int col1=FUNCTION(igraph_matrix,ncol)(m1); long int col2=FUNCTION(igraph_matrix,ncol)(m2); long int row1=FUNCTION(igraph_matrix,nrow)(m1); long int row2=FUNCTION(igraph_matrix,nrow)(m2); if (col1 != col2 || row1 != row2) { IGRAPH_WARNING("Comparing non-conformant matrices"); } return FUNCTION(igraph_vector,maxdifference)(&m1->data, &m2->data); } #endif /** * \function igraph_matrix_transpose * \brief Transpose a matrix. * * Calculate the transpose of a matrix. Note that the function * reallocates the memory used for the matrix. * \param m The input (and output) matrix. * \return Error code. * * Time complexity: O(mn), the number of elements in the matrix. */ int FUNCTION(igraph_matrix,transpose)(TYPE(igraph_matrix) *m) { long int nrow=m->nrow; long int ncol=m->ncol; if (nrow>1 && ncol>1) { TYPE(igraph_vector) newdata; long int i, size=nrow*ncol, mod=size-1; FUNCTION(igraph_vector,init)(&newdata, size); IGRAPH_FINALLY(FUNCTION(igraph_vector,destroy), &newdata); for (i=0; idata)[ (i*nrow) % mod ]; } VECTOR(newdata)[size-1]=VECTOR(m->data)[size-1]; FUNCTION(igraph_vector,destroy)(&m->data); IGRAPH_FINALLY_CLEAN(1); m->data=newdata; } m->nrow=ncol; m->ncol=nrow; return 0; } /** * \function igraph_matrix_e * Extract an element from a matrix. * * Use this if you need a function for some reason and cannot use the * \ref MATRIX macro. Note that no range checking is performed. * \param m The input matrix. * \param row The row index. * \param col The column index. * \return The element in the given row and column. * * Time complexity: O(1). */ BASE FUNCTION(igraph_matrix,e)(const TYPE(igraph_matrix) *m, long int row, long int col) { return MATRIX(*m, row, col); } /** * \function igraph_matrix_e_ptr * Pointer to an element of a matrix. * * The function returns a pointer to an element. No range checking is * performed. * \param m The input matrix. * \param row The row index. * \param col The column index. * \return Pointer to the element in the given row and column. * * Time complexity: O(1). */ BASE* FUNCTION(igraph_matrix,e_ptr)(const TYPE(igraph_matrix) *m, long int row, long int col) { return &MATRIX(*m, row, col); } /** * \function igraph_matrix_set * Set an element. * * Set an element of a matrix. No range checking is performed. * \param m The input matrix. * \param row The row index. * \param col The column index. * \param value The new value of the element. * * Time complexity: O(1). */ void FUNCTION(igraph_matrix,set)(TYPE(igraph_matrix)* m, long int row, long int col, BASE value) { MATRIX(*m, row, col) = value; } /** * \function igraph_matrix_fill * Fill with an element. * * Set the matrix to a constant matrix. * \param m The input matrix. * \param e The element to set. * * Time complexity: O(mn), the number of elements. */ void FUNCTION(igraph_matrix,fill)(TYPE(igraph_matrix) *m, BASE e) { FUNCTION(igraph_vector,fill)(&m->data, e); } /** * \function igraph_matrix_update * Update from another matrix. * * This function replicates \p from in the matrix \p to. * Note that \p to must be already initialized. * \param to The result matrix. * \param from The matrix to replicate; it is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,update)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from) { IGRAPH_CHECK(FUNCTION(igraph_matrix,resize)(to, from->nrow, from->ncol)); FUNCTION(igraph_vector,update)(&to->data, &from->data); return 0; } /** * \function igraph_matrix_rbind * Combine two matrices rowwise. * * This function places the rows of \p from below the rows of \c to * and stores the result in \p to. The number of columns in the two * matrices must match. * \param to The upper matrix; the result is also stored here. * \param from The lower matrix. It is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements in the newly created * matrix. */ int FUNCTION(igraph_matrix,rbind)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from) { long int tocols=to->ncol, fromcols=from->ncol; long int torows=to->nrow, fromrows=from->nrow; long int offset, c, r, index, offset2; if (tocols != fromcols) { IGRAPH_ERROR("Cannot do rbind, number of columns do not match", IGRAPH_EINVAL); } IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(&to->data, tocols * (fromrows+torows))); to->nrow += fromrows; offset=(tocols-1) * fromrows; index=tocols*torows-1; for (c=tocols-1; c>0; c--) { for (r=0; rdata)[index+offset] = VECTOR(to->data)[index]; } offset -= fromrows; } offset=torows; offset2=0; for (c=0; cdata)+offset, VECTOR(from->data)+offset2, sizeof(BASE) * (size_t) fromrows); offset+=fromrows+torows; offset2+=fromrows; } return 0; } /** * \function igraph_matrix_cbind * Combine matrices columnwise. * * This function places the columns of \p from on the right of \p to, * and stores the result in \p to. * \param to The left matrix; the result is stored here too. * \param from The right matrix. It is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements on the new matrix. */ int FUNCTION(igraph_matrix,cbind)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from) { long int tocols=to->ncol, fromcols=from->ncol; long int torows=to->nrow, fromrows=from->nrow; if (torows != fromrows) { IGRAPH_ERROR("Cannot do rbind, number of rows do not match", IGRAPH_EINVAL); } IGRAPH_CHECK(FUNCTION(igraph_matrix,resize)(to, torows, tocols+fromcols)); FUNCTION(igraph_vector,copy_to)(&from->data, VECTOR(to->data)+tocols*torows); return 0; } /** * \function igraph_matrix_swap * Swap two matrices. * * The contents of the two matrices will be swapped. They must have the * same dimensions. * \param m1 The first matrix. * \param m2 The second matrix. * \return Error code. * * Time complexity: O(mn), the number of elements in the matrices. */ int FUNCTION(igraph_matrix,swap)(TYPE(igraph_matrix) *m1, TYPE(igraph_matrix) *m2) { if (m1->nrow != m2->nrow || m1->ncol != m2->ncol) { IGRAPH_ERROR("Cannot swap non-conformant matrices", IGRAPH_EINVAL); } return FUNCTION(igraph_vector,swap)(&m1->data, &m2->data); } /** * \function igraph_matrix_get_row * Extract a row. * * Extract a row from a matrix and return it as a vector. * \param m The input matrix. * \param res Pointer to an initialized vector; it will be resized if * needed. * \param index The index of the row to select. * \return Error code. * * Time complexity: O(n), the number of columns in the matrix. */ int FUNCTION(igraph_matrix,get_row)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res, long int index) { long int rows=m->nrow, cols=m->ncol; long int i, j; if (index >= rows) { IGRAPH_ERROR("Index out of range for selecting matrix row", IGRAPH_EINVAL); } IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(res, cols)); for (i=index, j=0; jdata)[i]; } return 0; } /** * \function igraph_matrix_set_row * Set a row from a vector. * * Sets the elements of a row with the given vector. This has the effect of * setting row \c index to have the elements in the vector \c v. The length of * the vector and the number of columns in the matrix must match, * otherwise an error is triggered. * \param m The input matrix. * \param v The vector containing the new elements of the row. * \param index Index of the row to set. * \return Error code. * * Time complexity: O(n), the number of columns in the matrix. */ int FUNCTION(igraph_matrix,set_row)(TYPE(igraph_matrix) *m, const TYPE(igraph_vector) *v, long int index) { long int rows=m->nrow, cols=m->ncol; long int i, j; if (index >= rows) { IGRAPH_ERROR("Index out of range for selecting matrix row", IGRAPH_EINVAL); } if (FUNCTION(igraph_vector,size)(v) != cols) { IGRAPH_ERROR("Cannot set matrix row, invalid vector length", IGRAPH_EINVAL); } for (i=index, j=0; jdata)[i]=VECTOR(*v)[j]; } return 0; } /** * \function igraph_matrix_set_col * Set a column from a vector. * * Sets the elements of a column with the given vector. In effect, column * \c index will be set with elements from the vector \c v. The length of * the vector and the number of rows in the matrix must match, * otherwise an error is triggered. * \param m The input matrix. * \param v The vector containing the new elements of the column. * \param index Index of the column to set. * \return Error code. * * Time complexity: O(m), the number of rows in the matrix. */ int FUNCTION(igraph_matrix,set_col)(TYPE(igraph_matrix) *m, const TYPE(igraph_vector) *v, long int index) { long int rows=m->nrow, cols=m->ncol; long int i, j; if (index >= cols) { IGRAPH_ERROR("Index out of range for setting matrix column", IGRAPH_EINVAL); } if (FUNCTION(igraph_vector,size)(v) != rows) { IGRAPH_ERROR("Cannot set matrix column, invalid vector length", IGRAPH_EINVAL); } for (i=index*rows, j=0; jdata)[i]=VECTOR(*v)[j]; } return 0; } /** * \function igraph_matrix_swap_rows * Swap two rows. * * Swap two rows in the matrix. * \param m The input matrix. * \param i The index of the first row. * \param j The index of the second row. * \return Error code. * * Time complexity: O(n), the number of columns. */ int FUNCTION(igraph_matrix,swap_rows)(TYPE(igraph_matrix) *m, long int i, long int j) { long int ncol=m->ncol, nrow=m->nrow; long int n=nrow*ncol; long int index1, index2; if (i>=nrow || j>=nrow) { IGRAPH_ERROR("Cannot swap rows, index out of range", IGRAPH_EINVAL); } if (i==j) { return 0; } for (index1=i, index2=j; index1data)[index1]; VECTOR(m->data)[index1]=VECTOR(m->data)[index2]; VECTOR(m->data)[index2]=tmp; } return 0; } /** * \function igraph_matrix_swap_cols * Swap two columns. * * Swap two columns in the matrix. * \param m The input matrix. * \param i The index of the first column. * \param j The index of the second column. * \return Error code. * * Time complexity: O(m), the number of rows. */ int FUNCTION(igraph_matrix,swap_cols)(TYPE(igraph_matrix) *m, long int i, long int j) { long int ncol=m->ncol, nrow=m->nrow; long int k, index1, index2; if (i>=ncol || j >= ncol) { IGRAPH_ERROR("Cannot swap columns, index out of range", IGRAPH_EINVAL); } if (i==j) { return 0; } for (index1=i*nrow, index2=j*nrow, k=0; kdata)[index1]; VECTOR(m->data)[index1]=VECTOR(m->data)[index2]; VECTOR(m->data)[index2]=tmp; } return 0; } /** * \function igraph_matrix_add_constant * Add a constant to every element. * * \param m The input matrix. * \param plud The constant to add. * * Time complexity: O(mn), the number of elements. */ void FUNCTION(igraph_matrix,add_constant)(TYPE(igraph_matrix) *m, BASE plus) { FUNCTION(igraph_vector,add_constant)(&m->data, plus); } /** * \function igraph_matrix_add * Add two matrices. * * Add \p m2 to \p m1, and store the result in \p m1. The dimensions of the * matrices must match. * \param m1 The first matrix; the result will be stored here. * \param m2 The second matrix; it is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,add)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2) { if (m1->nrow != m2->nrow || m1->ncol != m2->ncol) { IGRAPH_ERROR("Cannot add non-conformant matrices", IGRAPH_EINVAL); } return FUNCTION(igraph_vector,add)(&m1->data, &m2->data); } /** * \function igraph_matrix_sub * Difference of two matrices. * * Subtract \p m2 from \p m1 and store the result in \p m1. * The dimensions of the two matrices must match. * \param m1 The first matrix; the result is stored here. * \param m2 The second matrix; it is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,sub)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2) { if (m1->nrow != m2->nrow || m1->ncol != m2->ncol) { IGRAPH_ERROR("Cannot subtract non-conformant matrices", IGRAPH_EINVAL); } return FUNCTION(igraph_vector,sub)(&m1->data, &m2->data); } /** * \function igraph_matrix_mul_elements * Elementwise multiplication. * * Multiply \p m1 by \p m2 elementwise and store the result in \p m1. * The dimensions of the two matrices must match. * \param m1 The first matrix; the result is stored here. * \param m2 The second matrix; it is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,mul_elements)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2) { if (m1->nrow != m2->nrow || m1->ncol != m2->ncol) { IGRAPH_ERROR("Cannot multiply non-conformant matrices", IGRAPH_EINVAL); } return FUNCTION(igraph_vector,mul)(&m1->data, &m2->data); } /** * \function igraph_matrix_div_elements * Elementwise division. * * Divide \p m1 by \p m2 elementwise and store the result in \p m1. * The dimensions of the two matrices must match. * \param m1 The dividend. The result is store here. * \param m2 The divisor. It is left unchanged. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,div_elements)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2) { if (m1->nrow != m2->nrow || m1->ncol != m2->ncol) { IGRAPH_ERROR("Cannot divide non-conformant matrices", IGRAPH_EINVAL); } return FUNCTION(igraph_vector,div)(&m1->data, &m2->data); } #ifndef NOTORDERED /** * \function igraph_matrix_min * Minimum element. * * Returns the smallest element of a non-empty matrix. * \param m The input matrix. * \return The smallest element. * * Time complexity: O(mn), the number of elements. */ igraph_real_t FUNCTION(igraph_matrix,min)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,min)(&m->data); } /** * \function igraph_matrix_which_min * Indices of the minimum. * * Gives the indices of the (first) smallest element in a non-empty * matrix. * \param m The matrix. * \param i Pointer to a long int. The row index of the * minimum is stored here. * \param j Pointer to a long int. The column index of * the minimum is stored here. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,which_min)(const TYPE(igraph_matrix) *m, long int *i, long int *j) { long int vmin=FUNCTION(igraph_vector,which_min)(&m->data); *i = vmin % m->nrow; *j = vmin / m->nrow; return 0; } /** * \function igraph_matrix_which_max * Indices of the maximum. * * Gives the indices of the (first) largest element in a non-empty * matrix. * \param m The matrix. * \param i Pointer to a long int. The row index of the * maximum is stored here. * \param j Pointer to a long int. The column index of * the maximum is stored here. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,which_max)(const TYPE(igraph_matrix) *m, long int *i, long int *j) { long int vmax=FUNCTION(igraph_vector,which_max)(&m->data); *i = vmax % m->nrow; *j = vmax / m->nrow; return 0; } /** * \function igraph_matrix_minmax * Minimum and maximum * * The maximum and minimum elements of a non-empty matrix. * \param m The input matrix. * \param min Pointer to a base type. The minimum is stored here. * \param max Pointer to a base type. The maximum is stored here. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,minmax)(const TYPE(igraph_matrix) *m, BASE *min, BASE *max) { return FUNCTION(igraph_vector,minmax)(&m->data, min, max); } /** * \function igraph_matrix_which_minmax * Indices of the minimum and maximum * * Find the positions of the smallest and largest elements of a * non-empty matrix. * \param m The input matrix. * \param imin Pointer to a long int, the row index of * the minimum is stored here. * \param jmin Pointer to a long int, the column index of * the minimum is stored here. * \param imax Pointer to a long int, the row index of * the maximum is stored here. * \param jmax Pointer to a long int, the column index of * the maximum is stored here. * \return Error code. * * Time complexity: O(mn), the number of elements. */ int FUNCTION(igraph_matrix,which_minmax)(const TYPE(igraph_matrix) *m, long int *imin, long int *jmin, long int *imax, long int *jmax) { long int vmin, vmax; FUNCTION(igraph_vector,which_minmax)(&m->data, &vmin, &vmax); *imin = vmin % m->nrow; *jmin = vmin / m->nrow; *imax = vmax % m->nrow; *jmax = vmax / m->nrow; return 0; } #endif /** * \function igraph_matrix_isnull * Check for a null matrix. * * Checks whether all elements are zero. * \param m The input matrix. * \return Boolean, \c TRUE is \p m contains only zeros and \c FALSE * otherwise. * * Time complexity: O(mn), the number of elements. */ igraph_bool_t FUNCTION(igraph_matrix,isnull)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,isnull)(&m->data); } /** * \function igraph_matrix_empty * Check for an empty matrix. * * It is possible to have a matrix with zero rows or zero columns, or * even both. This functions checks for these. * \param m The input matrix. * \return Boolean, \c TRUE if the matrix contains zero elements, and * \c FALSE otherwise. * * Time complexity: O(1). */ igraph_bool_t FUNCTION(igraph_matrix,empty)(const TYPE(igraph_matrix) *m) { return FUNCTION(igraph_vector,empty)(&m->data); } /** * \function igraph_matrix_is_symmetric * Check for symmetric matrix. * * A non-square matrix is not symmetric by definition. * \param m The input matrix. * \return Boolean, \c TRUE if the matrix is square and symmetric, \c * FALSE otherwise. * * Time complexity: O(mn), the number of elements. O(1) for non-square * matrices. */ igraph_bool_t FUNCTION(igraph_matrix,is_symmetric)(const TYPE(igraph_matrix) *m) { long int n=m->nrow; long int r,c; if (m->ncol != n) { return 0; } for (r=1; rdata); } /** * \function igraph_matrix_rowsum * Rowwise sum. * * Calculate the sum of the elements in each row. * \param m The input matrix. * \param res Pointer to an initialized vector; the result is stored * here. It will be resized if necessary. * \return Error code. * * Time complexity: O(mn), the number of elements in the matrix. */ int FUNCTION(igraph_matrix,rowsum)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res) { long int nrow=m->nrow, ncol=m->ncol; long int r, c; BASE sum; IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(res, nrow)); for (r=0; rnrow, ncol=m->ncol; long int r, c; BASE sum; IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(res, ncol)); for (c=0; cdata, e); } /** * \function igraph_matrix_search * Search from a given position. * * Search for an element in a matrix and start the search from the * given position. The search is performed columnwise. * \param m The input matrix. * \param from The position to search from, the positions are * enumerated columnwise. * \param what The element to search for. * \param pos Pointer to a long int. If the element is * found, then this is set to the position of its first appearance. * \param row Pointer to a long int. If the element is * found, then this is set to its row index. * \param col Pointer to a long int. If the element is * found, then this is set to its column index. * \return Boolean, \c TRUE if the element is found, \c FALSE * otherwise. * * Time complexity: O(mn), the number of elements. */ igraph_bool_t FUNCTION(igraph_matrix,search)(const TYPE(igraph_matrix) *m, long int from, BASE what, long int *pos, long int *row, long int *col) { igraph_bool_t find=FUNCTION(igraph_vector,search)(&m->data, from, what, pos); if (find) { *row = *pos % m->nrow; *col = *pos / m->nrow; } return find; } /** * \function igraph_matrix_remove_row * Remove a row. * * A row is removed from the matrix. * \param m The input matrix. * \param row The index of the row to remove. * \return Error code. * * Time complexity: O(mn), the number of elements in the matrix. */ int FUNCTION(igraph_matrix,remove_row)(TYPE(igraph_matrix) *m, long int row) { long int c, r, index=row+1, leap=1, n=m->nrow * m->ncol; if (row >= m->nrow) { IGRAPH_ERROR("Cannot remove row, index out of range", IGRAPH_EINVAL); } for (c=0; cncol; c++) { for (r=0; rnrow-1 && index < n; r++) { VECTOR(m->data)[index-leap] = VECTOR(m->data)[index]; index++; } leap++; index++; } m->nrow--; FUNCTION(igraph_vector,resize)(&m->data, m->nrow * m->ncol); return 0; } /** * \function igraph_matrix_select_cols * \brief Select some columns of a matrix. * * This function selects some columns of a matrix and returns them in a * new matrix. The result matrix should be initialized before calling * the function. * \param m The input matrix. * \param res The result matrix. It should be initialized and will be * resized as needed. * \param cols Vector; it contains the column indices (starting with * zero) to extract. Note that no range checking is performed. * \return Error code. * * Time complexity: O(nm), n is the number of rows, m the number of * columns of the result matrix. */ int FUNCTION(igraph_matrix,select_cols)(const TYPE(igraph_matrix) *m, TYPE(igraph_matrix) *res, const igraph_vector_t *cols) { long int ncols=igraph_vector_size(cols); long int nrows=m->nrow; long int i, j; IGRAPH_CHECK(FUNCTION(igraph_matrix,resize)(res, nrows, ncols)); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_INTERRUPT_INTERNAL_H #define IGRAPH_INTERRUPT_INTERNAL_H #include "config.h" #include "igraph_interrupt.h" #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS extern IGRAPH_THREAD_LOCAL igraph_interruption_handler_t *igraph_i_interruption_handler; /** * \define IGRAPH_ALLOW_INTERRUPTION * \brief * * This macro should be called when interruption is allowed. It calls * \ref igraph_allow_interruption() with the proper parameters and if that returns * anything but \c IGRAPH_SUCCESS then * the macro returns the "calling" function as well, with the proper * error code (\c IGRAPH_INTERRUPTED). */ #define IGRAPH_ALLOW_INTERRUPTION() \ do { \ if (igraph_i_interruption_handler) { if (igraph_allow_interruption(NULL) != IGRAPH_SUCCESS) return IGRAPH_INTERRUPTED; \ } } while (0) #define IGRAPH_ALLOW_INTERRUPTION_NORETURN() \ do { \ if (igraph_i_interruption_handler) { igraph_allow_interruption(NULL); } \ } while (0) __END_DECLS #endif igraph/src/igraph_set.c0000644000175100001440000002003113431000472014610 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_memory.h" #include "igraph_error.h" #include "igraph_types_internal.h" #include "config.h" #include #include /* memmove */ #define SET(s) ((s).stor_begin) /** * \ingroup set * \function igraph_set_init * \brief Initializes a set. * * \param set pointer to the set to be initialized * \param size the expected number of elements in the set * * \return error code: * \c IGRAPH_ENOMEM if there is not enough memory. * * Time complexity: operating system dependent, should be around * O(n), n is the expected size of the set. */ int igraph_set_init(igraph_set_t *set, int long size) { long int alloc_size = size > 0 ? size : 1; if (size < 0) { size = 0; } set->stor_begin=igraph_Calloc(alloc_size, igraph_integer_t); set->stor_end=set->stor_begin + alloc_size; set->end=set->stor_begin; return 0; } /** * \ingroup set * \function igraph_set_destroy * \brief Destroys a set object. * * \param set pointer to the set to be destroyed * * Time complexity: operating system dependent. */ void igraph_set_destroy(igraph_set_t* set) { assert(set != 0); if (set->stor_begin != 0) { igraph_Free(set->stor_begin); set->stor_begin = NULL; } } /** * \ingroup set * \function igraph_set_inited * \brief Determines whether a set is initialized or not. * * This function checks whether the internal storage for the members of the * set has been allocated or not, and it assumes that the pointer for the * internal storage area contains \c NULL if the area is not initialized yet. * This only applies if you have allocated an array of sets with \c igraph_Calloc or * if you used the \c IGRAPH_SET_NULL constant to initialize the set. * * \param set The set object. * * Time complexity: O(1) */ igraph_bool_t igraph_set_inited(igraph_set_t* set) { return (set->stor_begin != 0); } /** * \ingroup set * \function igraph_set_reserve * \brief Reserve memory for a set. * * \param set The set object. * \param size the new \em allocated size of the set. * * Time complexity: operating system dependent, should be around * O(n), n is the new allocated size of the set. */ int igraph_set_reserve(igraph_set_t* set, long int size) { long int actual_size = igraph_set_size(set); igraph_integer_t *tmp; assert(set != NULL); assert(set->stor_begin != NULL); if (size <= actual_size) return 0; tmp=igraph_Realloc(set->stor_begin, (size_t) size, igraph_integer_t); if (tmp==0) { IGRAPH_ERROR("cannot reserve space for set", IGRAPH_ENOMEM); } set->stor_begin=tmp; set->stor_end=set->stor_begin+size; set->end=set->stor_begin+actual_size; return 0; } /** * \ingroup set * \function igraph_set_empty * \brief Decides whether the size of the set is zero. * * \param set The set object. * \return Non-zero number if the size of the set is not zero and * zero otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_set_empty(const igraph_set_t* set) { assert(set != NULL); assert(set->stor_begin != NULL); return set->stor_begin == set->end; } /** * \ingroup set * \function igraph_set_clear * \brief Removes all elements from a set. * * * This function simply sets the size of the set to zero, it does * not free any allocated memory. For that you have to call * \ref igraph_set_destroy(). * \param v The set object. * * Time complexity: O(1). */ void igraph_set_clear(igraph_set_t* set) { assert(set != NULL); assert(set->stor_begin != NULL); set->end = set->stor_begin; } /** * \ingroup set * \function igraph_vector_set * \brief Gives the size (=length) of the set. * * \param v The set object * \return The size of the set. * * Time complexity: O(1). */ long int igraph_set_size(const igraph_set_t* set) { assert(set != NULL); assert(set->stor_begin != NULL); return set->end-set->stor_begin; } /** * \ingroup set * \function igraph_set_add * \brief Adds an element to the set. * * \param set The set object. * \param e The element to be added. * \return Error code: * \c IGRAPH_ENOMEM: not enough memory. * * Time complexity: O(log(n)), n is the number of elements in \p set. */ int igraph_set_add(igraph_set_t* set, igraph_integer_t e) { long int left, right, middle; long int size; assert(set != NULL); assert(set->stor_begin != NULL); size = igraph_set_size(set); /* search where to insert the new element */ left = 0; right = size-1; while (left < right-1) { middle = (left+right)/2; if (SET(*set)[middle] > e) { right = middle; } else if (SET(*set)[middle] < e) { left = middle; } else { left = middle; break; } } if (right >= 0 && SET(*set)[left] != e && SET(*set)[right] == e) { left = right; } while (left < size && set->stor_begin[left] < e) left++; if (left >= size || set->stor_begin[left] != e) { /* full, allocate more storage */ if (set->stor_end == set->end) { long int new_size = size * 2; if (new_size == 0) new_size = 1; IGRAPH_CHECK(igraph_set_reserve(set, new_size)); } /* Element should be inserted at position 'left' */ if (left < size) memmove(set->stor_begin+left+1, set->stor_begin+left, (size_t) (size-left)*sizeof(set->stor_begin[0])); set->stor_begin[left] = e; set->end += 1; } return 0; } /** * \ingroup set * \function igraph_set_contains * \brief Checks whether a given element is in the set or not. * * \param set The set object. * \param e The element being sought. * \return Positive integer (true) if \p e is found, zero (false) otherwise. * * Time complexity: O(log(n)), n is the number of elements in \p set. */ int igraph_set_contains(igraph_set_t* set, igraph_integer_t e) { long int left, right, middle; assert(set != NULL); assert(set->stor_begin != NULL); left = 0; right = igraph_set_size(set)-1; /* search for the new element */ while (left < right-1) { middle = (left+right)/2; if (SET(*set)[middle] > e) { right = middle; } else if (SET(*set)[middle] < e) { left = middle; } else { left = middle; return 1; } } if (SET(*set)[left] != e && SET(*set)[right] == e) return 1; return (SET(*set)[left] == e); } /** * \ingroup set * \function igraph_set_iterate * \brief Iterates through the element to the set. * * Elements are returned in an arbitrary order. * * \param set The set object. * \param state Internal state of the iteration. * This should be a pointer to a \c long variable * which must be zero for the first invocation. * The object should not be adjusted and its value should * not be used for anything during the iteration. * \param element The next element or \c NULL (if the iteration * has ended) is returned here. * * \return Nonzero if there are more elements, zero otherwise. */ igraph_bool_t igraph_set_iterate(igraph_set_t* set, long int* state, igraph_integer_t* element) { assert(set != 0); assert(set->stor_begin != 0); assert(state != 0); assert(element != 0); if (*state < igraph_set_size(set)) { *element = set->stor_begin[*state]; *state = *state+1; return 1; } else { *element = 0; return 0; } } igraph/src/igraph_hashtable.c0000644000175100001440000001000713431000472015752 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include int igraph_hashtable_init(igraph_hashtable_t *ht) { IGRAPH_CHECK(igraph_trie_init(&ht->keys, 1)); IGRAPH_FINALLY(igraph_trie_destroy, &ht->keys); IGRAPH_CHECK(igraph_strvector_init(&ht->elements, 0)); IGRAPH_FINALLY(igraph_trie_destroy, &ht->elements); IGRAPH_CHECK(igraph_strvector_init(&ht->defaults, 0)); IGRAPH_FINALLY_CLEAN(2); return 0; } void igraph_hashtable_destroy(igraph_hashtable_t *ht) { igraph_trie_destroy(&ht->keys); igraph_strvector_destroy(&ht->elements); igraph_strvector_destroy(&ht->defaults); } /* Note: may leave the hash table in an inconsistent state if a new element is added, but this is not a big problem, since while the defaults, or the defaults plus the elements may contain more elements than the keys trie, but the data is always retrieved based on the trie */ int igraph_hashtable_addset(igraph_hashtable_t *ht, const char *key, const char *def, const char *elem){ long int size=igraph_trie_size(&ht->keys); long int newid; IGRAPH_CHECK(igraph_trie_get(&ht->keys, key, &newid)); if (newid==size) { /* this is a new element */ IGRAPH_CHECK(igraph_strvector_resize(&ht->defaults, newid+1)); IGRAPH_CHECK(igraph_strvector_resize(&ht->elements, newid+1)); IGRAPH_CHECK(igraph_strvector_set(&ht->defaults, newid, def)); IGRAPH_CHECK(igraph_strvector_set(&ht->elements, newid, elem)); } else { /* set an already existing element */ IGRAPH_CHECK(igraph_strvector_set(&ht->elements, newid, elem)); } return 0; } /* Previous comment also applies here */ int igraph_hashtable_addset2(igraph_hashtable_t *ht, const char *key, const char *def, const char *elem, int elemlen) { long int size=igraph_trie_size(&ht->keys); long int newid; char *tmp; IGRAPH_CHECK(igraph_trie_get(&ht->keys, key, &newid)); tmp=igraph_Calloc(elemlen+1, char); if (tmp==0) { IGRAPH_ERROR("cannot add element to hash table", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp); strncpy(tmp, elem, elemlen); tmp[elemlen]='\0'; if (newid==size) { IGRAPH_CHECK(igraph_strvector_resize(&ht->defaults, newid+1)); IGRAPH_CHECK(igraph_strvector_resize(&ht->elements, newid+1)); IGRAPH_CHECK(igraph_strvector_set(&ht->defaults, newid, def)); IGRAPH_CHECK(igraph_strvector_set(&ht->elements, newid, tmp)); } else { IGRAPH_CHECK(igraph_strvector_set(&ht->elements, newid, tmp)); } igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_hashtable_get(igraph_hashtable_t *ht, const char *key, char **elem) { long int newid; IGRAPH_CHECK(igraph_trie_get(&ht->keys, key, &newid)); igraph_strvector_get(&ht->elements, newid, elem); return 0; } int igraph_hashtable_reset(igraph_hashtable_t *ht) { igraph_strvector_destroy(&ht->elements); IGRAPH_CHECK(igraph_strvector_copy(&ht->elements, &ht->defaults)); return 0; } int igraph_hashtable_getkeys(igraph_hashtable_t *ht, const igraph_strvector_t **sv) { return igraph_trie_getkeys(&ht->keys, sv); } igraph/src/random_walk.c0000644000175100001440000002361013431000472014767 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_paths.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_random.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" /** * \function igraph_random_walk * Perform a random walk on a graph * * Performs a random walk with a given length on a graph, from the given * start vertex. Edge directions are (potentially) considered, depending on * the \p mode argument. * * \param graph The input graph, it can be directed or undirected. * Multiple edges are respected, so are loop edges. * \param walk An allocated vector, the result is stored here. * It will be resized as needed. * \param start The start vertex for the walk. * \param steps The number of steps to take. If the random walk gets * stuck, then the \p stuck argument specifies what happens. * \param mode How to walk along the edges in direted graphs. * \c IGRAPH_OUT means following edge directions, \c IGRAPH_IN means * going opposite the edge directions, \c IGRAPH_ALL means ignoring * edge directions. This argument is ignored for undirected graphs. * \param stuck What to do if the random walk gets stuck. * \c IGRAPH_RANDOM_WALK_STUCK_RETURN means that the function returns * with a shorter walk; \c IGRAPH_RANDOM_WALK_STUCK_ERROR means * that an error is reported. In both cases \p walk is truncated * to contain the actual interrupted walk. * \return Error code. * * Time complexity: O(l + d), where \c l is the length of the * walk, and \c d is the total degree of the visited nodes. */ int igraph_random_walk(const igraph_t *graph, igraph_vector_t *walk, igraph_integer_t start, igraph_neimode_t mode, igraph_integer_t steps, igraph_random_walk_stuck_t stuck) { /* TODO: - multiple walks potentially from multiple start vertices - weights */ igraph_lazy_adjlist_t adj; igraph_integer_t vc = igraph_vcount(graph); igraph_integer_t i; if (start < 0 || start >= vc) { IGRAPH_ERROR("Invalid start vertex", IGRAPH_EINVAL); } if (steps < 0) { IGRAPH_ERROR("Invalid number of steps", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adj, mode, IGRAPH_DONT_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adj); IGRAPH_CHECK(igraph_vector_resize(walk, steps)); RNG_BEGIN(); VECTOR(*walk)[0] = start; for (i = 1; i < steps; i++) { igraph_vector_t *neis; igraph_integer_t nn; neis = igraph_lazy_adjlist_get(&adj, start); nn = igraph_vector_size(neis); if (IGRAPH_UNLIKELY(nn == 0)) { igraph_vector_resize(walk, i); if (stuck == IGRAPH_RANDOM_WALK_STUCK_RETURN) { break; } else { IGRAPH_ERROR("Random walk got stuck", IGRAPH_ERWSTUCK); } } start = VECTOR(*walk)[i] = VECTOR(*neis)[ RNG_INTEGER(0, nn - 1) ]; } RNG_END(); igraph_lazy_adjlist_destroy(&adj); IGRAPH_FINALLY_CLEAN(1); return 0; } /* Used as item destructor for 'cdfs' in igraph_random_edge_walk(). */ static void vec_destr(igraph_vector_t *vec) { if (vec != NULL) igraph_vector_destroy(vec); } /** * \function igraph_random_edge_walk * \brief Perform a random walk on a graph and return the traversed edges * * Performs a random walk with a given length on a graph, from the given * start vertex. Edge directions are (potentially) considered, depending on * the \p mode argument. * * \param graph The input graph, it can be directed or undirected. * Multiple edges are respected, so are loop edges. * \param weights A vector of non-negative edge weights. * It is assumed that at least one strictly positive weight is found among the * outgoing edges of each vertex. If it is a NULL pointer, all edges are considered * to have equal weight. * \param edgewalk An initialized vector; the indices of traversed edges are stored here. * It will be resized as needed. * \param start The start vertex for the walk. * \param steps The number of steps to take. If the random walk gets * stuck, then the \p stuck argument specifies what happens. * \param mode How to walk along the edges in direted graphs. * \c IGRAPH_OUT means following edge directions, \c IGRAPH_IN means * going opposite the edge directions, \c IGRAPH_ALL means ignoring * edge directions. This argument is ignored for undirected graphs. * \param stuck What to do if the random walk gets stuck. * \c IGRAPH_RANDOM_WALK_STUCK_RETURN means that the function returns * with a shorter walk; \c IGRAPH_RANDOM_WALK_STUCK_ERROR means * that an error is reported. In both cases, \p edgewalk is truncated * to contain the actual interrupted walk. * * \return Error code. * */ int igraph_random_edge_walk(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *edgewalk, igraph_integer_t start, igraph_neimode_t mode, igraph_integer_t steps, igraph_random_walk_stuck_t stuck) { igraph_integer_t vc = igraph_vcount(graph); igraph_integer_t ec = igraph_ecount(graph); igraph_integer_t i; igraph_inclist_t il; igraph_vector_t weight_temp; igraph_vector_ptr_t cdfs; /* cumulative distribution vectors for each node, used for weighted choice */ /* the fourth igraph_neimode_t value, IGRAPH_TOTAL, is disallowed */ if (! (mode == IGRAPH_ALL || mode == IGRAPH_IN || mode == IGRAPH_OUT)) IGRAPH_ERROR("Invalid mode parameter", IGRAPH_EINVMODE); /* ref switch statement at end of main loop */ if (! igraph_is_directed(graph)) mode = IGRAPH_ALL; if (start < 0 || start >= vc) IGRAPH_ERROR("Invalid start vertex", IGRAPH_EINVAL); if (steps < 0) IGRAPH_ERROR("Invalid number of steps", IGRAPH_EINVAL); if (weights) { if (igraph_vector_size(weights) != ec) IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); if (igraph_vector_min(weights) < 0) IGRAPH_ERROR("Weights must be non-negative", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_resize(edgewalk, steps)); IGRAPH_CHECK(igraph_inclist_init(graph, &il, mode)); IGRAPH_FINALLY(igraph_inclist_destroy, &il); IGRAPH_VECTOR_INIT_FINALLY(&weight_temp, 0); /* cdf vectors will be computed lazily */ IGRAPH_CHECK(igraph_vector_ptr_init(&cdfs, vc)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &cdfs); IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&cdfs, vec_destr); for (i=0; i < vc; ++i) VECTOR(cdfs)[i] = NULL; RNG_BEGIN(); for (i=0; i < steps; ++i) { long degree, edge, idx; igraph_vector_int_t *edges = igraph_inclist_get(&il, start); degree = igraph_vector_int_size(edges); /* are we stuck? */ if (IGRAPH_UNLIKELY(degree == 0)) { igraph_vector_resize(edgewalk, i); /* can't fail since size is reduced, skip IGRAPH_CHECK */ if (stuck == IGRAPH_RANDOM_WALK_STUCK_RETURN) break; else IGRAPH_ERROR("Random walk got stuck", IGRAPH_ERWSTUCK); } if (weights) /* weighted: choose an out-edge with probability proportional to its weight */ { igraph_real_t r; igraph_vector_t **cd = (igraph_vector_t **) &(VECTOR(cdfs)[start]); /* compute out-edge cdf for this node if not already done */ if (IGRAPH_UNLIKELY(! *cd)) { long j; *cd = igraph_malloc(sizeof(igraph_vector_t)); if (*cd == NULL) IGRAPH_ERROR("random edge walk failed", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_init(*cd, degree)); IGRAPH_CHECK(igraph_vector_resize(&weight_temp, degree)); for (j=0; j < degree; ++j) VECTOR(weight_temp)[j] = VECTOR(*weights)[ VECTOR(*edges)[j] ]; IGRAPH_CHECK(igraph_vector_cumsum(*cd, &weight_temp)); } r = RNG_UNIF(0, VECTOR( **cd )[degree-1]); igraph_vector_binsearch(*cd, r, &idx); } else /* unweighted: choose an out-edge at random */ { idx = RNG_INTEGER(0, degree-1); } edge = VECTOR(*edges)[idx]; VECTOR(*edgewalk)[i] = edge; /* travel along edge in a direction specified by 'mode' */ /* note: 'mode' is always set to IGRAPH_ALL for undirected graphs */ switch (mode) { case IGRAPH_OUT: start = IGRAPH_TO(graph, edge); break; case IGRAPH_IN: start = IGRAPH_FROM(graph, edge); break; case IGRAPH_ALL: { igraph_integer_t next = IGRAPH_TO(graph, edge); if (start == next) start = IGRAPH_FROM(graph, edge); else start = next; } break; } IGRAPH_ALLOW_INTERRUPTION(); } RNG_END(); igraph_vector_ptr_destroy_all(&cdfs); igraph_vector_destroy(&weight_temp); igraph_inclist_destroy(&il); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } igraph/src/feedback_arc_set.c0000644000175100001440000005427513431000472015730 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_centrality.h" #include "igraph_components.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_dqueue.h" #include "igraph_error.h" #include "igraph_glpk_support.h" #include "igraph_interface.h" #include "igraph_memory.h" #include "igraph_structural.h" #include "igraph_types.h" #include "igraph_visitor.h" int igraph_i_feedback_arc_set_ip(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights); /** * \ingroup structural * \function igraph_feedback_arc_set * \brief Calculates a feedback arc set of the graph using different * algorithms. * * * A feedback arc set is a set of edges whose removal makes the graph acyclic. * We are usually interested in \em minimum feedback arc sets, i.e. sets of edges * whose total weight is minimal among all the feedback arc sets. * * * For undirected graphs, the problem is simple: one has to find a maximum weight * spanning tree and then remove all the edges not in the spanning tree. For directed * graphs, this is an NP-hard problem, and various heuristics are usually used to * find an approximate solution to the problem. This function implements a few of * these heuristics. * * \param graph The graph object. * \param result An initialized vector, the result will be returned here. * \param weights Weight vector or NULL if no weights are specified. * \param algo The algorithm to use to solve the problem if the graph is directed. * Possible values: * \clist * \cli IGRAPH_FAS_EXACT_IP * Finds a \em minimum feedback arc set using integer programming (IP). * The complexity of this algorithm is exponential of course. * \cli IGRAPH_FAS_APPROX_EADES * Finds a feedback arc set using the heuristic of Eades, Lin and * Smyth (1993). This is guaranteed to be smaller than |E|/2 - |V|/6, * and it is linear in the number of edges (i.e. O(|E|)). * For more details, see Eades P, Lin X and Smyth WF: A fast and effective * heuristic for the feedback arc set problem. In: Proc Inf Process Lett * 319-323, 1993. * \endclist * * \return Error code: * \c IGRAPH_EINVAL if an unknown method was specified or the weight vector * is invalid. * * \example examples/simple/igraph_feedback_arc_set.c * \example examples/simple/igraph_feedback_arc_set_ip.c * * Time complexity: depends on \p algo, see the time complexities there. */ int igraph_feedback_arc_set(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_fas_algorithm_t algo) { if (weights && igraph_vector_size(weights) < igraph_ecount(graph)) IGRAPH_ERROR("cannot calculate feedback arc set, weight vector too short", IGRAPH_EINVAL); if (!igraph_is_directed(graph)) return igraph_i_feedback_arc_set_undirected(graph, result, weights, 0); switch (algo) { case IGRAPH_FAS_EXACT_IP: return igraph_i_feedback_arc_set_ip(graph, result, weights); case IGRAPH_FAS_APPROX_EADES: return igraph_i_feedback_arc_set_eades(graph, result, weights, 0); default: IGRAPH_ERROR("Invalid algorithm", IGRAPH_EINVAL); } } /** * Solves the feedback arc set problem for undirected graphs. */ int igraph_i_feedback_arc_set_undirected(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_vector_t *layering) { igraph_vector_t edges; long int i, j, n, no_of_nodes = igraph_vcount(graph); IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_nodes-1); if (weights) { /* Find a maximum weight spanning tree. igraph has a routine for minimum * spanning trees, so we negate the weights */ igraph_vector_t vcopy; IGRAPH_CHECK(igraph_vector_copy(&vcopy, weights)); IGRAPH_FINALLY(igraph_vector_destroy, &vcopy); igraph_vector_scale(&vcopy, -1); IGRAPH_CHECK(igraph_minimum_spanning_tree(graph, &edges, &vcopy)); igraph_vector_destroy(&vcopy); IGRAPH_FINALLY_CLEAN(1); } else { /* Any spanning tree will do */ IGRAPH_CHECK(igraph_minimum_spanning_tree(graph, &edges, 0)); } /* Now we have a bunch of edges that constitute a spanning forest. We have * to come up with a layering, and return those edges that are not in the * spanning forest */ igraph_vector_sort(&edges); IGRAPH_CHECK(igraph_vector_push_back(&edges, -1)); /* guard element */ if (result != 0) { igraph_vector_clear(result); n = igraph_ecount(graph); for (i = 0, j = 0; i < n; i++) { if (i == VECTOR(edges)[j]) { j++; continue; } IGRAPH_CHECK(igraph_vector_push_back(result, i)); } } if (layering != 0) { igraph_vector_t degrees; igraph_vector_t roots; IGRAPH_VECTOR_INIT_FINALLY(°rees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&roots, no_of_nodes); IGRAPH_CHECK(igraph_strength(graph, °rees, igraph_vss_all(), IGRAPH_ALL, 0, weights)); IGRAPH_CHECK((int) igraph_vector_qsort_ind(°rees, &roots, /* descending = */ 1)); IGRAPH_CHECK(igraph_bfs(graph, /* root = */ 0, /* roots = */ &roots, /* mode = */ IGRAPH_OUT, /* unreachable = */ 0, /* restricted = */ 0, /* order = */ 0, /* rank = */ 0, /* father = */ 0, /* pred = */ 0, /* succ = */ 0, /* dist = */ layering, /* callback = */ 0, /* extra = */ 0)); igraph_vector_destroy(°rees); igraph_vector_destroy(&roots); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * Solves the feedback arc set problem using the heuristics of Eades et al. */ int igraph_i_feedback_arc_set_eades(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_vector_t *layers) { long int i, j, k, v, eid, no_of_nodes=igraph_vcount(graph), nodes_left; igraph_dqueue_t sources, sinks; igraph_vector_t neis; igraph_vector_t indegrees, outdegrees; igraph_vector_t instrengths, outstrengths; long int* ordering; long int order_next_pos = 0, order_next_neg = -1; igraph_real_t diff, maxdiff; ordering = igraph_Calloc(no_of_nodes, long int); IGRAPH_FINALLY(igraph_free, ordering); IGRAPH_VECTOR_INIT_FINALLY(&indegrees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&outdegrees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&instrengths, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&outstrengths, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_dqueue_init(&sources, 0)); IGRAPH_FINALLY(igraph_dqueue_destroy, &sources); IGRAPH_CHECK(igraph_dqueue_init(&sinks, 0)); IGRAPH_FINALLY(igraph_dqueue_destroy, &sinks); IGRAPH_CHECK(igraph_degree(graph, &indegrees, igraph_vss_all(), IGRAPH_IN, 0)); IGRAPH_CHECK(igraph_degree(graph, &outdegrees, igraph_vss_all(), IGRAPH_OUT, 0)); if (weights) { IGRAPH_CHECK(igraph_strength(graph, &instrengths, igraph_vss_all(), IGRAPH_IN, 0, weights)); IGRAPH_CHECK(igraph_strength(graph, &outstrengths, igraph_vss_all(), IGRAPH_OUT, 0, weights)); } else { IGRAPH_CHECK(igraph_vector_update(&instrengths, &indegrees)); IGRAPH_CHECK(igraph_vector_update(&outstrengths, &outdegrees)); } /* Find initial sources and sinks */ nodes_left = no_of_nodes; for (i = 0; i < no_of_nodes; i++) { if (VECTOR(indegrees)[i] == 0) { if (VECTOR(outdegrees)[i] == 0) { /* Isolated vertex, we simply ignore it */ nodes_left--; ordering[i] = order_next_pos++; VECTOR(indegrees)[i] = VECTOR(outdegrees)[i] = -1; } else { /* This is a source */ igraph_dqueue_push(&sources, i); } } else if (VECTOR(outdegrees)[i] == 0) { /* This is a sink */ igraph_dqueue_push(&sinks, i); } } /* While we have any nodes left... */ while (nodes_left > 0) { /* (1) Remove the sources one by one */ while (!igraph_dqueue_empty(&sources)) { i=(long)igraph_dqueue_pop(&sources); /* Add the node to the ordering */ ordering[i] = order_next_pos++; /* Exclude the node from further searches */ VECTOR(indegrees)[i] = VECTOR(outdegrees)[i] = -1; /* Get the neighbors and decrease their degrees */ IGRAPH_CHECK(igraph_incident(graph, &neis, (igraph_integer_t) i, IGRAPH_OUT)); j = igraph_vector_size(&neis); for (i = 0; i < j; i++) { eid = (long int) VECTOR(neis)[i]; k = IGRAPH_TO(graph, eid); if (VECTOR(indegrees)[k] <= 0) { /* Already removed, continue */ continue; } VECTOR(indegrees)[k]--; VECTOR(instrengths)[k] -= (weights ? VECTOR(*weights)[eid] : 1.0); if (VECTOR(indegrees)[k] == 0) IGRAPH_CHECK(igraph_dqueue_push(&sources, k)); } nodes_left--; } /* (2) Remove the sinks one by one */ while (!igraph_dqueue_empty(&sinks)) { i=(long)igraph_dqueue_pop(&sinks); /* Maybe the vertex became sink and source at the same time, hence it * was already removed in the previous iteration. Check it. */ if (VECTOR(indegrees)[i] < 0) continue; /* Add the node to the ordering */ ordering[i] = order_next_neg--; /* Exclude the node from further searches */ VECTOR(indegrees)[i] = VECTOR(outdegrees)[i] = -1; /* Get the neighbors and decrease their degrees */ IGRAPH_CHECK(igraph_incident(graph, &neis, (igraph_integer_t) i, IGRAPH_IN)); j = igraph_vector_size(&neis); for (i = 0; i < j; i++) { eid = (long int) VECTOR(neis)[i]; k = IGRAPH_FROM(graph, eid); if (VECTOR(outdegrees)[k] <= 0) { /* Already removed, continue */ continue; } VECTOR(outdegrees)[k]--; VECTOR(outstrengths)[k] -= (weights ? VECTOR(*weights)[eid] : 1.0); if (VECTOR(outdegrees)[k] == 0) IGRAPH_CHECK(igraph_dqueue_push(&sinks, k)); } nodes_left--; } /* (3) No more sources or sinks. Find the node with the largest * difference between its out-strength and in-strength */ v = -1; maxdiff = -IGRAPH_INFINITY; for (i = 0; i < no_of_nodes; i++) { if (VECTOR(outdegrees)[i] < 0) continue; diff = VECTOR(outstrengths)[i]-VECTOR(instrengths)[i]; if (diff > maxdiff) { maxdiff = diff; v = i; } } if (v >= 0) { /* Remove vertex v */ ordering[v] = order_next_pos++; /* Remove outgoing edges */ IGRAPH_CHECK(igraph_incident(graph, &neis, (igraph_integer_t) v, IGRAPH_OUT)); j = igraph_vector_size(&neis); for (i = 0; i < j; i++) { eid = (long int) VECTOR(neis)[i]; k = IGRAPH_TO(graph, eid); if (VECTOR(indegrees)[k] <= 0) { /* Already removed, continue */ continue; } VECTOR(indegrees)[k]--; VECTOR(instrengths)[k] -= (weights ? VECTOR(*weights)[eid] : 1.0); if (VECTOR(indegrees)[k] == 0) IGRAPH_CHECK(igraph_dqueue_push(&sources, k)); } /* Remove incoming edges */ IGRAPH_CHECK(igraph_incident(graph, &neis, (igraph_integer_t) v, IGRAPH_IN)); j = igraph_vector_size(&neis); for (i = 0; i < j; i++) { eid = (long int) VECTOR(neis)[i]; k = IGRAPH_FROM(graph, eid); if (VECTOR(outdegrees)[k] <= 0) { /* Already removed, continue */ continue; } VECTOR(outdegrees)[k]--; VECTOR(outstrengths)[k] -= (weights ? VECTOR(*weights)[eid] : 1.0); if (VECTOR(outdegrees)[k] == 0 && VECTOR(indegrees)[k] > 0) IGRAPH_CHECK(igraph_dqueue_push(&sinks, k)); } VECTOR(outdegrees)[v] = -1; VECTOR(indegrees)[v] = -1; nodes_left--; } } igraph_dqueue_destroy(&sinks); igraph_dqueue_destroy(&sources); igraph_vector_destroy(&neis); igraph_vector_destroy(&outstrengths); igraph_vector_destroy(&instrengths); igraph_vector_destroy(&outdegrees); igraph_vector_destroy(&indegrees); IGRAPH_FINALLY_CLEAN(7); /* Tidy up the ordering */ for (i = 0; i < no_of_nodes; i++) { if (ordering[i] < 0) ordering[i] += no_of_nodes; } /* Find the feedback edges based on the ordering */ if (result != 0) { igraph_vector_clear(result); j = igraph_ecount(graph); for (i = 0; i < j; i++) { long int from = IGRAPH_FROM(graph, i), to = IGRAPH_TO(graph, i); if (from == to || ordering[from] > ordering[to]) IGRAPH_CHECK(igraph_vector_push_back(result, i)); } } /* If we have also requested a layering, return that as well */ if (layers != 0) { igraph_vector_t ranks; igraph_vector_long_t order_vec; IGRAPH_CHECK(igraph_vector_resize(layers, no_of_nodes)); igraph_vector_null(layers); igraph_vector_long_view(&order_vec, ordering, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&ranks, 0); IGRAPH_CHECK((int) igraph_vector_long_qsort_ind(&order_vec, &ranks, 0)); for (i = 0; i < no_of_nodes; i++) { long int from = (long int) VECTOR(ranks)[i]; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) from, IGRAPH_OUT)); k = igraph_vector_size(&neis); for (j = 0; j < k; j++) { long int to = (long int) VECTOR(neis)[j]; if (from == to) continue; if (ordering[from] > ordering[to]) continue; if (VECTOR(*layers)[to] < VECTOR(*layers)[from] + 1) VECTOR(*layers)[to] = VECTOR(*layers)[from] + 1; } } igraph_vector_destroy(&neis); igraph_vector_destroy(&ranks); IGRAPH_FINALLY_CLEAN(2); } /* Free the ordering vector */ igraph_free(ordering); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * Solves the feedback arc set problem using integer programming. */ int igraph_i_feedback_arc_set_ip(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights) { #ifndef HAVE_GLPK IGRAPH_ERROR("GLPK is not available", IGRAPH_UNIMPLEMENTED); #else igraph_integer_t no_of_components; igraph_integer_t no_of_vertices = igraph_vcount(graph); igraph_integer_t no_of_edges = igraph_ecount(graph); igraph_vector_t membership, ordering, vertex_remapping; igraph_vector_ptr_t vertices_by_components, edges_by_components; long int i, j, k, l, m, n, from, to; igraph_real_t weight; glp_prob *ip; glp_iocp parm; IGRAPH_VECTOR_INIT_FINALLY(&membership, 0); IGRAPH_VECTOR_INIT_FINALLY(&ordering, 0); IGRAPH_VECTOR_INIT_FINALLY(&vertex_remapping, no_of_vertices); igraph_vector_clear(result); /* Decompose the graph into connected components */ IGRAPH_CHECK(igraph_clusters(graph, &membership, 0, &no_of_components, IGRAPH_WEAK)); /* Construct vertex and edge lists for each of the components */ IGRAPH_CHECK(igraph_vector_ptr_init(&vertices_by_components, no_of_components)); IGRAPH_CHECK(igraph_vector_ptr_init(&edges_by_components, no_of_components)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &vertices_by_components); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &edges_by_components); for (i = 0; i < no_of_components; i++) { igraph_vector_t* vptr; vptr = igraph_Calloc(1, igraph_vector_t); if (vptr == 0) IGRAPH_ERROR("cannot calculate feedback arc set using IP", IGRAPH_ENOMEM); IGRAPH_FINALLY(free, vptr); IGRAPH_CHECK(igraph_vector_init(vptr, 0)); IGRAPH_FINALLY_CLEAN(1); VECTOR(vertices_by_components)[i] = vptr; } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&vertices_by_components, igraph_vector_destroy); for (i = 0; i < no_of_components; i++) { igraph_vector_t* vptr; vptr = igraph_Calloc(1, igraph_vector_t); if (vptr == 0) IGRAPH_ERROR("cannot calculate feedback arc set using IP", IGRAPH_ENOMEM); IGRAPH_FINALLY(free, vptr); IGRAPH_CHECK(igraph_vector_init(vptr, 0)); IGRAPH_FINALLY_CLEAN(1); VECTOR(edges_by_components)[i] = vptr; } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&edges_by_components, igraph_vector_destroy); for (i = 0; i < no_of_vertices; i++) { j = (long int) VECTOR(membership)[i]; IGRAPH_CHECK(igraph_vector_push_back(VECTOR(vertices_by_components)[j], i)); } for (i = 0; i < no_of_edges; i++) { j = (long int) VECTOR(membership)[(long)IGRAPH_FROM(graph, i)]; IGRAPH_CHECK(igraph_vector_push_back(VECTOR(edges_by_components)[j], i)); } #define VAR2IDX(i, j) (i*(n-1)+j-(i+1)*i/2) /* Configure GLPK */ glp_term_out(GLP_OFF); glp_init_iocp(&parm); parm.br_tech = GLP_BR_DTH; parm.bt_tech = GLP_BT_BLB; parm.pp_tech = GLP_PP_ALL; parm.presolve = GLP_ON; parm.binarize = GLP_OFF; parm.cb_func = igraph_i_glpk_interruption_hook; /* Solve an IP for feedback arc sets in each of the components */ for (i = 0; i < no_of_components; i++) { igraph_vector_t* vertices_in_comp = (igraph_vector_t*)VECTOR(vertices_by_components)[i]; igraph_vector_t* edges_in_comp = (igraph_vector_t*)VECTOR(edges_by_components)[i]; /* * Let x_ij denote whether layer(i) < layer(j). * * The standard formulation of the problem is as follows: * * max sum_{i,j} w_ij x_ij * * subject to * * (1) x_ij + x_ji = 1 (i.e. either layer(i) < layer(j) or layer(i) > layer(j)) * for all i < j * (2) x_ij + x_jk + x_ki <= 2 for all i < j, i < k, j != k * * Note that x_ij = 1 implies that x_ji = 0 and vice versa; in other words, * x_ij = 1 - x_ji. Thus, we can get rid of the (1) constraints and half of the * x_ij variables (where j < i) if we rewrite constraints of type (2) as follows: * * (2a) x_ij + x_jk - x_ik <= 1 for all i < j, i < k, j < k * (2b) x_ij - x_kj - x_ik <= 0 for all i < j, i < k, j > k * * The goal function then becomes: * * max sum_{i 0) { glp_add_cols(ip, (int) k); for (j = 1; j <= k; j++) glp_set_col_kind(ip, (int) j, GLP_BV); } /* Set up coefficients in the goal function */ k = igraph_vector_size(edges_in_comp); for (j = 0; j < k; j++) { l = (long int) VECTOR(*edges_in_comp)[j]; from = (long int) VECTOR(vertex_remapping)[(long)IGRAPH_FROM(graph, l)]; to = (long int) VECTOR(vertex_remapping)[(long)IGRAPH_TO(graph, l)]; if (from == to) continue; weight = weights ? VECTOR(*weights)[l] : 1; if (from < to) { l = VAR2IDX(from, to); glp_set_obj_coef(ip, (int) l, glp_get_obj_coef(ip, (int) l) + weight); } else { l = VAR2IDX(to, from); glp_set_obj_coef(ip, (int) l, glp_get_obj_coef(ip, (int) l) - weight); } } /* Add constraints */ if (n > 1) { glp_add_rows(ip, (int)(n*(n-1)/2 + n*(n-1)*(n-2)/3)); m = 1; for (j = 0; j < n; j++) { int ind[4]; double val[4] = {0, 1, 1, -1}; for (k = j+1; k < n; k++) { ind[1] = (int) VAR2IDX(j, k); /* Type (2a) */ val[2] = 1; for (l = k+1; l < n; l++, m++) { ind[2] = (int) VAR2IDX(k, l); ind[3] = (int) VAR2IDX(j, l); glp_set_row_bnds(ip, (int) m, GLP_UP, 1, 1); glp_set_mat_row(ip, (int) m, 3, ind, val); } /* Type (2b) */ val[2] = -1; for (l = j+1; l < k; l++, m++) { ind[2] = (int) VAR2IDX(l, k); ind[3] = (int) VAR2IDX(j, l); glp_set_row_bnds(ip, (int) m, GLP_UP, 0, 0); glp_set_mat_row(ip, (int) m, 3, ind, val); } } } } /* Solve the problem */ IGRAPH_GLPK_CHECK(glp_intopt(ip, &parm), "Feedback arc set using IP failed"); /* Find the ordering of the vertices */ IGRAPH_CHECK(igraph_vector_resize(&ordering, n)); igraph_vector_null(&ordering); m = n * (n-1) / 2; j = 0; k = 1; for (l = 1; l <= m; l++) { /* variable l always corresponds to the (j, k) vertex pair */ /* printf("(%ld, %ld) = %g\n", i, j, glp_mip_col_val(ip, l)); */ if (glp_mip_col_val(ip, (int) l) > 0) { /* j comes earlier in the ordering than k */ VECTOR(ordering)[j]++; } else { /* k comes earlier in the ordering than j */ VECTOR(ordering)[k]++; } k++; if (k == n) { j++; k = j+1; } } /* Find the feedback edges */ k = igraph_vector_size(edges_in_comp); for (j = 0; j < k; j++) { l = (long int) VECTOR(*edges_in_comp)[j]; from = (long int) VECTOR(vertex_remapping)[(long)IGRAPH_FROM(graph, l)]; to = (long int) VECTOR(vertex_remapping)[(long)IGRAPH_TO(graph, l)]; if (from == to || VECTOR(ordering)[from] < VECTOR(ordering)[to]) IGRAPH_CHECK(igraph_vector_push_back(result, l)); } /* Clean up */ glp_delete_prob(ip); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_ptr_destroy_all(&vertices_by_components); igraph_vector_ptr_destroy_all(&edges_by_components); igraph_vector_destroy(&vertex_remapping); igraph_vector_destroy(&ordering); igraph_vector_destroy(&membership); IGRAPH_FINALLY_CLEAN(5); return IGRAPH_SUCCESS; #endif } igraph/src/gengraph_vertex_cover.h0000644000175100001440000000415613431000472017070 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _VERTEX_COVER_H #define _VERTEX_COVER_H // vertex_cover() builds a list of vertices which covers every edge of the graph // Input is a classical adjacency-list graph // As an output, vertex_cover() modify the degrees in degs[], so that // any vertex with a degree > 0 belongs to the vertex coverage. // Moreover, vertex_cover() keeps links[] intact, permuting only the adjacency lists #include "gengraph_box_list.h" #ifndef register #define register #endif namespace gengraph { void vertex_cover(int n, int *links, int *deg, int **neigh = NULL) { int i; // create and initialize neigh[] if (neigh==NULL) { neigh = new int*[n]; neigh[0] = links; for(i=1; i=0) bl.pop_vertex(v, neigh); // remove vertex of max degree and its highest-degree neighbour if(!bl.is_empty()) { v=bl.get_max(); int *w = neigh[v]; register int v2 = *(w++); register int dm = deg[v2]; register int k = deg[v]-1; while(k--) if(deg[*(w++)]>dm) { v2 = *(w-1); dm=deg[v2]; }; bl.pop_vertex(v, neigh); bl.pop_vertex(v2,neigh); } } while(!bl.is_empty()); } } // namespace gengraph #endif //_VERTEX_COVER_H igraph/src/foreign-ncol-parser.c0000644000175100001440000013270413431000472016352 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Using locations. */ #define YYLSP_NEEDED 1 /* Substitute the variable and function names. */ #define yyparse igraph_ncol_yyparse #define yylex igraph_ncol_yylex #define yyerror igraph_ncol_yyerror #define yylval igraph_ncol_yylval #define yychar igraph_ncol_yychar #define yydebug igraph_ncol_yydebug #define yynerrs igraph_ncol_yynerrs #define yylloc igraph_ncol_yylloc /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ALNUM = 258, NEWLINE = 259, ERROR = 260 }; #endif /* Tokens. */ #define ALNUM 258 #define NEWLINE 259 #define ERROR 260 /* Copy the first part of user declarations. */ #line 23 "src/foreign-ncol-parser.y" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include "foreign-ncol-header.h" #include "foreign-ncol-parser.h" #define yyscan_t void* int igraph_ncol_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_ncol_yyerror(YYLTYPE* locp, igraph_i_ncol_parsedata_t *context, const char *s); char *igraph_ncol_yyget_text (yyscan_t yyscanner ); int igraph_ncol_yyget_leng (yyscan_t yyscanner ); igraph_real_t igraph_ncol_get_number(const char *str, long int len); #define scanner context->scanner /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 82 "src/foreign-ncol-parser.y" { long int edgenum; double weightnum; } /* Line 193 of yacc.c. */ #line 169 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 194 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 2 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 10 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 6 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 5 /* YYNRULES -- Number of rules. */ #define YYNRULES 8 /* YYNRULES -- Number of states. */ #define YYNSTATES 12 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 260 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 4, 7, 10, 14, 19, 21 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 7, 0, -1, -1, 7, 4, -1, 7, 8, -1, 9, 9, 4, -1, 9, 9, 10, 4, -1, 3, -1, 3, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 96, 96, 97, 98, 101, 106, 114, 119 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "ALNUM", "NEWLINE", "ERROR", "$accept", "input", "edge", "edgeid", "weight", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 6, 7, 7, 7, 8, 8, 9, 10 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 0, 2, 2, 3, 4, 1, 1 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 2, 0, 1, 7, 3, 4, 0, 0, 8, 5, 0, 6 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 1, 5, 6, 10 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -3 static const yytype_int8 yypact[] = { -3, 0, -3, -3, -3, -3, 2, -2, -3, -3, 3, -3 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -3, -3, -3, 4, -3 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 2, 8, 9, 3, 4, 3, 0, 11, 0, 0, 7 }; static const yytype_int8 yycheck[] = { 0, 3, 4, 3, 4, 3, -1, 4, -1, -1, 6 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 7, 0, 3, 4, 8, 9, 9, 3, 4, 10, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc, scanner) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_ncol_parsedata_t* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_ncol_parsedata_t* context; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_ncol_parsedata_t* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_ncol_parsedata_t* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, igraph_i_ncol_parsedata_t* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; igraph_i_ncol_parsedata_t* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, igraph_i_ncol_parsedata_t* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; igraph_i_ncol_parsedata_t* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (igraph_i_ncol_parsedata_t* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (igraph_i_ncol_parsedata_t* context) #else int yyparse (context) igraph_i_ncol_parsedata_t* context; #endif #endif { /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: #line 101 "src/foreign-ncol-parser.y" { igraph_vector_push_back(context->vector, (yyvsp[(1) - (3)].edgenum)); igraph_vector_push_back(context->vector, (yyvsp[(2) - (3)].edgenum)); igraph_vector_push_back(context->weights, 0); ;} break; case 6: #line 106 "src/foreign-ncol-parser.y" { igraph_vector_push_back(context->vector, (yyvsp[(1) - (4)].edgenum)); igraph_vector_push_back(context->vector, (yyvsp[(2) - (4)].edgenum)); igraph_vector_push_back(context->weights, (yyvsp[(3) - (4)].weightnum)); context->has_weights = 1; ;} break; case 7: #line 114 "src/foreign-ncol-parser.y" { igraph_trie_get2(context->trie, igraph_ncol_yyget_text(scanner), igraph_ncol_yyget_leng(scanner), &(yyval.edgenum)); ;} break; case 8: #line 119 "src/foreign-ncol-parser.y" { (yyval.weightnum)=igraph_ncol_get_number(igraph_ncol_yyget_text(scanner), igraph_ncol_yyget_leng(scanner)); ;} break; /* Line 1267 of yacc.c. */ #line 1444 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (&yylloc, context, yymsg); } else { yyerror (&yylloc, context, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 122 "src/foreign-ncol-parser.y" int igraph_ncol_yyerror(YYLTYPE* locp, igraph_i_ncol_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in NCOL file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_ncol_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } igraph/src/triangles.c0000644000175100001440000007574713431000472014503 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_transitivity.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" #include "igraph_centrality.h" #include "igraph_motifs.h" /** * \function igraph_transitivity_avglocal_undirected * \brief Average local transitivity (clustering coefficient). * * The transitivity measures the probability that two neighbors of a * vertex are connected. In case of the average local transitivity, * this probability is calculated for each vertex and then the average * is taken. Vertices with less than two neighbors require special treatment, * they will either be left out from the calculation or they will be considered * as having zero transitivity, depending on the \c mode argument. * * * Note that this measure is different from the global transitivity measure * (see \ref igraph_transitivity_undirected() ) as it simply takes the * average local transitivity across the whole network. See the following * reference for more details: * * * D. J. Watts and S. Strogatz: Collective dynamics of small-world networks. * Nature 393(6684):440-442 (1998). * * * Clustering coefficient is an alternative name for transitivity. * * \param graph The input graph, directed graphs are considered as * undirected ones. * \param res Pointer to a real variable, the result will be stored here. * \param mode Defines how to treat vertices with degree less than two. * \c IGRAPH_TRANSITIVITY_NAN leaves them out from averaging, * \c IGRAPH_TRANSITIVITY_ZERO includes them with zero transitivity. * The result will be \c NaN if the mode is \c IGRAPH_TRANSITIVITY_NAN * and there are no vertices with more than one neighbor. * * \return Error code. * * \sa \ref igraph_transitivity_undirected(), \ref * igraph_transitivity_local_undirected(). * * Time complexity: O(|V|*d^2), |V| is the number of vertices in the * graph and d is the average degree. */ int igraph_transitivity_avglocal_undirected(const igraph_t *graph, igraph_real_t *res, igraph_transitivity_mode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_real_t sum=0.0; igraph_integer_t count=0; long int node, i, j, nn; igraph_adjlist_t allneis; igraph_vector_int_t *neis1, *neis2; long int neilen1, neilen2; long int *neis; long int maxdegree; igraph_vector_t order; igraph_vector_t rank; igraph_vector_t degree; igraph_vector_t triangles; IGRAPH_VECTOR_INIT_FINALLY(&order, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, IGRAPH_LOOPS)); maxdegree=(long int) igraph_vector_max(°ree)+1; igraph_vector_order1(°ree, &order, maxdegree); igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(1); IGRAPH_VECTOR_INIT_FINALLY(&rank, no_of_nodes); for (i=0; i= 0; nn--) { node=(long int) VECTOR(order)[nn]; IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_adjlist_get(&allneis, node); neilen1=igraph_vector_int_size(neis1); /* Mark the neighbors of 'node' */ for (i=0; i VECTOR(rank)[node]) { neis2=igraph_adjlist_get(&allneis, nei); neilen2=igraph_vector_int_size(neis2); for (j=0; j= 2) { sum += VECTOR(triangles)[node] / neilen1 / (neilen1-1) * 2.0; count++; } else if (mode == IGRAPH_TRANSITIVITY_ZERO) { count++; } } *res = sum/count; igraph_vector_destroy(&triangles); igraph_Free(neis); igraph_adjlist_destroy(&allneis); igraph_vector_destroy(&rank); igraph_vector_destroy(&order); IGRAPH_FINALLY_CLEAN(5); return 0; } int igraph_transitivity_local_undirected1(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode) { #define TRANSIT #include "triangles_template1.h" #undef TRANSIT return 0; } int igraph_transitivity_local_undirected2(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_vit_t vit; long int nodes_to_calc, affected_nodes; long int maxdegree=0; long int i, j, k, nn; igraph_lazy_adjlist_t adjlist; igraph_vector_t indexv, avids, rank, order, triangles, degree; long int *neis; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, IGRAPH_ALL, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); IGRAPH_VECTOR_INIT_FINALLY(&indexv, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&avids, 0); IGRAPH_CHECK(igraph_vector_reserve(&avids, nodes_to_calc)); k=0; for (i=0; i maxdegree) { maxdegree = deg; } } igraph_vector_order1(°ree, &order, maxdegree+1); igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(1); IGRAPH_VECTOR_INIT_FINALLY(&rank, affected_nodes); for (i=0; i=0; nn--) { long int node=(long int) VECTOR(avids) [ (long int) VECTOR(order)[nn] ]; igraph_vector_t *neis1, *neis2; long int neilen1, neilen2; long int nodeindex=(long int) VECTOR(indexv)[node]; long int noderank=(long int) VECTOR(rank) [nodeindex-1]; /* fprintf(stderr, "node %li (indexv %li, rank %li)\n", node, */ /* (long int)VECTOR(indexv)[node]-1, noderank); */ IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_lazy_adjlist_get(&adjlist, (igraph_integer_t) node); neilen1=igraph_vector_size(neis1); for (i=0; i noderank) { neis2=igraph_lazy_adjlist_get(&adjlist, (igraph_integer_t) nei); neilen2=igraph_vector_size(neis2); for (j=0; j nei2) { */ /* l2++; */ /* } else { */ /* triangles+=1; */ /* l1++; l2++; */ /* } */ /* } */ /* } */ /* /\* We're done with 'node' *\/ */ /* VECTOR(*res)[i] = triangles / triples; */ /* } */ /* igraph_lazy_adjlist_destroy(&adjlist); */ /* igraph_vit_destroy(&vit); */ /* IGRAPH_FINALLY_CLEAN(2); */ /* return 0; */ /* } */ /* This removes loop, multiple edges and edges that point "backwards" according to the rank vector. */ int igraph_i_trans4_al_simplify(igraph_adjlist_t *al, const igraph_vector_int_t *rank) { long int i; long int n=al->length; igraph_vector_int_t mark; igraph_vector_int_init(&mark, n); IGRAPH_FINALLY(igraph_vector_int_destroy, &mark); for (i=0; iadjs[i]; int j, l=igraph_vector_int_size(v); int irank=VECTOR(*rank)[i]; VECTOR(mark)[i] = i+1; for (j=0; j irank && VECTOR(mark)[e] != i+1) { VECTOR(mark)[e]=i+1; j++; } else { VECTOR(*v)[j] = igraph_vector_int_tail(v); igraph_vector_int_pop_back(v); l--; } } } igraph_vector_int_destroy(&mark); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_transitivity_local_undirected4(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode) { #define TRANSIT 1 #include "triangles_template.h" #undef TRANSIT return 0; } /** * \function igraph_transitivity_local_undirected * \brief Calculates the local transitivity (clustering coefficient) of a graph. * * The transitivity measures the probability that two neighbors of a * vertex are connected. In case of the local transitivity, this * probability is calculated separately for each vertex. * * * Note that this measure is different from the global transitivity measure * (see \ref igraph_transitivity_undirected() ) as it calculates a transitivity * value for each vertex individually. See the following reference for more * details: * * * D. J. Watts and S. Strogatz: Collective dynamics of small-world networks. * Nature 393(6684):440-442 (1998). * * * Clustering coefficient is an alternative name for transitivity. * * \param graph The input graph, it can be directed but direction of * the edges will be ignored. * \param res Pointer to an initialized vector, the result will be * stored here. It will be resized as needed. * \param vids Vertex set, the vertices for which the local * transitivity will be calculated. * \param mode Defines how to treat vertices with degree less than two. * \c IGRAPH_TRANSITIVITY_NAN returns \c NaN for these vertices, * \c IGRAPH_TRANSITIVITY_ZERO returns zero. * \return Error code. * * \sa \ref igraph_transitivity_undirected(), \ref * igraph_transitivity_avglocal_undirected(). * * Time complexity: O(n*d^2), n is the number of vertices for which * the transitivity is calculated, d is the average vertex degree. */ int igraph_transitivity_local_undirected(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode) { if (igraph_vs_is_all(&vids)) { return igraph_transitivity_local_undirected4(graph, res, vids, mode); } else { igraph_vit_t vit; long int size; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); size=IGRAPH_VIT_SIZE(vit); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); if (size < 100) { return igraph_transitivity_local_undirected1(graph, res, vids, mode); } else { return igraph_transitivity_local_undirected2(graph, res, vids, mode); } } return 0; } int igraph_adjacent_triangles1(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids) { # include "triangles_template1.h" return 0; } int igraph_adjacent_triangles4(const igraph_t *graph, igraph_vector_t *res) { # include "triangles_template.h" return 0; } /** * \function igraph_adjacent_triangles * Count the number of triangles a vertex is part of * * \param graph The input graph. Edge directions are ignored. * \param res Initiliazed vector, the results are stored here. * \param vids The vertices to perform the calculation for. * \return Error mode. * * \sa \ref igraph_list_triangles() to list them. * * Time complexity: O(d^2 n), d is the average vertex degree of the * queried vertices, n is their number. */ int igraph_adjacent_triangles(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids) { if (igraph_vs_is_all(&vids)) { return igraph_adjacent_triangles4(graph, res); } else { return igraph_adjacent_triangles1(graph, res, vids); } return 0; } /** * \function igraph_list_triangles * Find all triangles in a graph * * \param graph The input graph, edge directions are ignored. * \param res Pointer to an initialized integer vector, the result * is stored here, in a long list of triples of vertex ids. * Each triple is a triangle in the graph. Each triangle is * listed exactly once. * \return Error code. * * \sa \ref igraph_transitivity_undirected() to count the triangles, * \ref igraph_adjacent_triangles() to count the triangles a vertex * participates in. * * Time complexity: O(d^2 n), d is the average degree, n is the number * of vertices. */ int igraph_list_triangles(const igraph_t *graph, igraph_vector_int_t *res) { # define TRIANGLES # include "triangles_template.h" # undef TRIANGLES return 0; } /** * \ingroup structural * \function igraph_transitivity_undirected * \brief Calculates the transitivity (clustering coefficient) of a graph. * * * The transitivity measures the probability that two neighbors of a * vertex are connected. More precisely, this is the ratio of the * triangles and connected triples in the graph, the result is a * single real number. Directed graphs are considered as undirected ones. * * * Note that this measure is different from the local transitivity measure * (see \ref igraph_transitivity_local_undirected() ) as it calculates a single * value for the whole graph. See the following reference for more details: * * * S. Wasserman and K. Faust: Social Network Analysis: Methods and * Applications. Cambridge: Cambridge University Press, 1994. * * * Clustering coefficient is an alternative name for transitivity. * * \param graph The graph object. * \param res Pointer to a real variable, the result will be stored here. * \param mode Defines how to treat graphs with no connected triples. * \c IGRAPH_TRANSITIVITY_NAN returns \c NaN in this case, * \c IGRAPH_TRANSITIVITY_ZERO returns zero. * \return Error code: * \c IGRAPH_ENOMEM: not enough memory for * temporary data. * * \sa \ref igraph_transitivity_local_undirected(), * \ref igraph_transitivity_avglocal_undirected(). * * Time complexity: O(|V|*d^2), |V| is the number of vertices in * the graph, d is the average node degree. * * \example examples/simple/igraph_transitivity.c */ int igraph_transitivity_undirected(const igraph_t *graph, igraph_real_t *res, igraph_transitivity_mode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_real_t triples=0, triangles=0; long int node, nn; long int maxdegree; long int *neis; igraph_vector_t order; igraph_vector_t rank; igraph_vector_t degree; igraph_adjlist_t allneis; igraph_vector_int_t *neis1, *neis2; long int i, j, neilen1, neilen2; IGRAPH_VECTOR_INIT_FINALLY(&order, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, IGRAPH_LOOPS)); maxdegree=(long int) igraph_vector_max(°ree)+1; igraph_vector_order1(°ree, &order, maxdegree); igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(1); IGRAPH_VECTOR_INIT_FINALLY(&rank, no_of_nodes); for (i=0; i=0; nn--) { node=(long int) VECTOR(order)[nn]; IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_adjlist_get(&allneis, node); neilen1=igraph_vector_int_size(neis1); triples += (double)neilen1 * (neilen1-1); /* Mark the neighbors of 'node' */ for (i=0; i VECTOR(rank)[node]) { neis2=igraph_adjlist_get(&allneis, nei); neilen2=igraph_vector_int_size(neis2); for (j=0; j=0; nn--) { long int adjlen1, adjlen2; igraph_real_t triples; long int node=(long int) VECTOR(order)[nn]; IGRAPH_ALLOW_INTERRUPTION(); adj1=igraph_inclist_get(&incident, node); adjlen1=igraph_vector_int_size(adj1); triples = VECTOR(degree)[node] * (adjlen1-1) / 2.0; /* Mark the neighbors of the node */ for (i=0; i VECTOR(rank)[node]) { adj2=igraph_inclist_get(&incident, nei); adjlen2=igraph_vector_int_size(adj2); for (j=0; j 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FLOWGRAPH_H #define FLOWGRAPH_H #include #include #include "igraph_interface.h" #include "infomap_Node.h" class FlowGraph{ private: void init(int n, const igraph_vector_t *nodeWeights); public: FlowGraph(int n); FlowGraph(int n, const igraph_vector_t *nodeWeights); FlowGraph(FlowGraph * fgraph); FlowGraph(FlowGraph * fgraph, int sub_Nnode, int * sub_members); FlowGraph(const igraph_t * graph, const igraph_vector_t *e_weights, const igraph_vector_t *v_weights); ~FlowGraph(); void swap(FlowGraph * fgraph); void initiate(); void eigenvector(); void calibrate(); void back_to(FlowGraph * fgraph); /*************************************************************************/ Node **node; int Nnode; double alpha,beta; int Ndanglings; vector danglings; // id of dangling nodes double exit; // double exitFlow; // double exit_log_exit; // double size_log_size; // double nodeSize_log_nodeSize; // \sum_{v in V} p log(p) double codeLength; }; void delete_FlowGraph(FlowGraph *fgraph); #endif igraph/src/gengraph_powerlaw.h0000644000175100001440000000554613431000472016221 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef _POWERLAW_H #define _POWERLAW_H // pascalou #ifndef pascalou #include "gengraph_definitions.h" #endif // Discrete integer power-law : P(X=min+k) is proportionnal to (k+k0)^-alpha // - possibility to determine a range [Min, Max] of possible samples // - possibility to automatically compute k0 to obtain a given mean z namespace gengraph { #define POWERLAW_TABLE 10000 class powerlaw { private: double alpha; // Exponent int mini; // Minimum sample int maxi; // Maximum sample double offset; // Offset int tabulated; // Number of values to tabulate int *table; // Table containing cumulative distribution for k=mini..mini+tabulated-1 int *dt; // Table delimiters int max_dt; // number of delimiters - 1 double proba_big; // Probability to take a non-tabulated value double table_mul; // equal to (1-proba_big)/(RAND_MAX+1) // Sample a non-tabulated value >= mini+tabulated inline double big_sample(double randomfloat) { return double(mini)+pow(_a * randomfloat + _b, _exp)-offset; } inline double big_inv_sample(double s) { return (pow(s-double(mini)+offset,1.0/_exp)-_b)/_a; } double _exp, _a, _b; // Cached values used by big_sample(); // Dichotomic adjust of offset, so that to_adjust() returns value with // a precision of eps. Note that to_adjust() must be an increasing function of offset. void adjust_offset_mean(double value, double eps, double fac); public: int sample(); // Return a random integer double proba(int); // Return probability to return integer double error(); // Returns relative numerical error done by this class double mean(); // Returns mean of the sampler int median(); // Returns median of the sampler // Initialize the power-law sampler. void init_to_offset(double, int); // Same, but also returns the offset found double init_to_mean(double); double init_to_median(double); inline void init() { init_to_offset(double(mini),POWERLAW_TABLE); }; ~powerlaw(); powerlaw(double exponent, int mini, int maxi=-1); }; } // namespace gengraph #endif //_POWERLAW_H igraph/src/cliquer/0000755000175100001440000000000013561251636014005 5ustar hornikusersigraph/src/cliquer/README0000644000175100001440000000377613430770176014702 0ustar hornikusers Cliquer - routines for clique searching --------------------------------------- Cliquer is a set of C routines for finding cliques in an arbitrary weighted graph. It uses an exact branch-and-bound algorithm recently developed by Patric Ostergard. It is designed with the aim of being efficient while still being flexible and easy to use. Cliquer was developed on Linux, and it should compile without modification on most modern UNIX systems. Other operating systems may require minor changes to the source code. Features: * support for both weighted and unweighted graphs (faster routines for unweighted graphs) * search for maximum clique / maximum-weight clique * search for clique with size / weight within a given range * restrict search to maximal cliques * store found cliques in memory * call a user-defined function for every clique found * Cliquer is re-entrant, so you can use the clique-searching functions from within the callback function The full documentation can be obtained via the www page of Cliquer . License Cliquer is Copyright (C) 2002 Sampo Niskanen, Patric Ostergard. Cliquer is licensed under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The full license is included in the file LICENSE. Basically, you can use Cliquer for any purpose, provided that any programs or modifications you make and distribute are also licensed under the GNU GPL. ABSOLUTELY NO GUARANTEES OR WARRANTIES are made concerning the suitability, correctness, or any other aspect of these routines. Contact Cliquer was mainly written by Sampo Niskanen . For bug-fixes, feedback, and, in particular, for putting your name on the mailing list for important information regarding Cliquer, please contact: Patric Ostergard Department of Communications and Networking Aalto University P.O. Box 13000, 00076 Aalto FINLAND igraph/src/cliquer/reorder.h0000644000175100001440000000172413431000472015606 0ustar hornikusers #ifndef CLIQUER_REORDER_H #define CLIQUER_REORDER_H #include "set.h" #include "graph.h" extern void reorder_set(set_t s,int *order); extern void reorder_graph(graph_t *g, int *order); extern int *reorder_duplicate(int *order,int n); extern void reorder_invert(int *order,int n); extern void reorder_reverse(int *order,int n); extern int *reorder_ident(int n); extern boolean reorder_is_bijection(int *order,int n); #define reorder_by_default reorder_by_greedy_coloring extern int *reorder_by_greedy_coloring(graph_t *g, boolean weighted); extern int *reorder_by_weighted_greedy_coloring(graph_t *g, boolean weighted); extern int *reorder_by_unweighted_greedy_coloring(graph_t *g,boolean weighted); extern int *reorder_by_degree(graph_t *g, boolean weighted); extern int *reorder_by_random(graph_t *g, boolean weighted); extern int *reorder_by_ident(graph_t *g, boolean weighted); extern int *reorder_by_reverse(graph_t *g, boolean weighted); #endif /* !CLIQUER_REORDER_H */ igraph/src/cliquer/set.h0000644000175100001440000002225713431000472014743 0ustar hornikusers /* * This file contains the set handling routines. * * Copyright (C) 2002 Sampo Niskanen, Patric Östergård. * Licensed under the GNU GPL, read the file LICENSE for details. */ #ifndef CLIQUER_SET_H #define CLIQUER_SET_H #include #include #include #include #include "misc.h" /* * Sets are arrays of setelement's (typically unsigned long int's) with * representative bits for each value they can contain. The values * are numbered 0,...,n-1. */ /*** Variable types and constants. ***/ /* * If setelement hasn't been declared: * - use "unsigned long int" as setelement * - try to deduce size from ULONG_MAX */ #ifndef ELEMENTSIZE typedef unsigned long int setelement; # if (ULONG_MAX == 65535) # define ELEMENTSIZE 16 # elif (ULONG_MAX == 4294967295) # define ELEMENTSIZE 32 # else # define ELEMENTSIZE 64 # endif #endif /* !ELEMENTSIZE */ typedef setelement * set_t; /*** Counting amount of 1 bits in a setelement ***/ /* Array for amount of 1 bits in a byte. */ static int set_bit_count[256] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8 }; /* The following macros assume that all higher bits are 0. * They may in some cases be useful also on with other ELEMENTSIZE's, * so we define them all. */ #define SET_ELEMENT_BIT_COUNT_8(a) (set_bit_count[(a)]) #define SET_ELEMENT_BIT_COUNT_16(a) (set_bit_count[(a)>>8] + \ set_bit_count[(a)&0xFF]) #define SET_ELEMENT_BIT_COUNT_32(a) (set_bit_count[(a)>>24] + \ set_bit_count[((a)>>16)&0xFF] + \ set_bit_count[((a)>>8)&0xFF] + \ set_bit_count[(a)&0xFF]) #define SET_ELEMENT_BIT_COUNT_64(a) (set_bit_count[(a)>>56] + \ set_bit_count[((a)>>48)&0xFF] + \ set_bit_count[((a)>>40)&0xFF] + \ set_bit_count[((a)>>32)&0xFF] + \ set_bit_count[((a)>>24)&0xFF] + \ set_bit_count[((a)>>16)&0xFF] + \ set_bit_count[((a)>>8)&0xFF] + \ set_bit_count[(a)&0xFF]) #if (ELEMENTSIZE==64) # define SET_ELEMENT_BIT_COUNT(a) SET_ELEMENT_BIT_COUNT_64(a) # define FULL_ELEMENT ((setelement)0xFFFFFFFFFFFFFFFF) #elif (ELEMENTSIZE==32) # define SET_ELEMENT_BIT_COUNT(a) SET_ELEMENT_BIT_COUNT_32(a) # define FULL_ELEMENT ((setelement)0xFFFFFFFF) #elif (ELEMENTSIZE==16) # define SET_ELEMENT_BIT_COUNT(a) SET_ELEMENT_BIT_COUNT_16(a) # define FULL_ELEMENT ((setelement)0xFFFF) #else # error "SET_ELEMENT_BIT_COUNT(a) not defined for current ELEMENTSIZE" #endif /*** Macros and functions ***/ /* * Gives a value with bit x (counting from lsb up) set. * * Making this as a table might speed up things on some machines * (though on most modern machines it's faster to shift instead of * using memory). Making it a macro makes it easy to change. */ #define SET_BIT_MASK(x) ((setelement)1<<(x)) /* Set element handling macros */ #define SET_ELEMENT_INTERSECT(a,b) ((a)&(b)) #define SET_ELEMENT_UNION(a,b) ((a)|(b)) #define SET_ELEMENT_DIFFERENCE(a,b) ((a)&(~(b))) #define SET_ELEMENT_CONTAINS(e,v) ((e)&SET_BIT_MASK(v)) /* Set handling macros */ #define SET_ADD_ELEMENT(s,a) \ ((s)[(a)/ELEMENTSIZE] |= SET_BIT_MASK((a)%ELEMENTSIZE)) #define SET_DEL_ELEMENT(s,a) \ ((s)[(a)/ELEMENTSIZE] &= ~SET_BIT_MASK((a)%ELEMENTSIZE)) #define SET_CONTAINS_FAST(s,a) (SET_ELEMENT_CONTAINS((s)[(a)/ELEMENTSIZE], \ (a)%ELEMENTSIZE)) #define SET_CONTAINS(s,a) (((a)0); n=(size/ELEMENTSIZE+1)+1; s=calloc(n,sizeof(setelement)); s[0]=size; return &(s[1]); } /* * set_free() * * Free the memory associated with set s. */ UNUSED_FUNCTION INLINE static void set_free(set_t s) { ASSERT(s!=NULL); free(&(s[-1])); } /* * set_resize() * * Resizes set s to given size. If the size is less than SET_MAX_SIZE(s), * the last elements are dropped. * * Returns a pointer to the new set. */ UNUSED_FUNCTION INLINE static set_t set_resize(set_t s, int size) { int n; ASSERT(size>0); n=(size/ELEMENTSIZE+1); s=((setelement *)realloc(s-1,(n+1)*sizeof(setelement)))+1; if (n>SET_ARRAY_LENGTH(s)) memset(s+SET_ARRAY_LENGTH(s),0, (n-SET_ARRAY_LENGTH(s))*sizeof(setelement)); if (size < SET_MAX_SIZE(s)) s[(size-1)/ELEMENTSIZE] &= (FULL_ELEMENT >> (ELEMENTSIZE-size%ELEMENTSIZE)); s[-1]=size; return s; } /* * set_size() * * Returns the number of elements in set s. */ UNUSED_FUNCTION INLINE static int set_size(set_t s) { int count=0; setelement *c; for (c=s; c < s+SET_ARRAY_LENGTH(s); c++) count+=SET_ELEMENT_BIT_COUNT(*c); return count; } /* * set_duplicate() * * Returns a newly allocated duplicate of set s. */ UNUSED_FUNCTION INLINE static set_t set_duplicate(set_t s) { set_t new; new=set_new(SET_MAX_SIZE(s)); memcpy(new,s,SET_ARRAY_LENGTH(s)*sizeof(setelement)); return new; } /* * set_copy() * * Copies set src to dest. If dest is NULL, is equal to set_duplicate. * If dest smaller than src, it is freed and a new set of the same size as * src is returned. */ UNUSED_FUNCTION INLINE static set_t set_copy(set_t dest,set_t src) { if (dest==NULL) return set_duplicate(src); if (SET_MAX_SIZE(dest)=0) { * // i is in set s * } */ UNUSED_FUNCTION INLINE static int set_return_next(set_t s, int n) { if (n<0) n=0; else n++; if (n >= SET_MAX_SIZE(s)) return -1; while (n%ELEMENTSIZE) { if (SET_CONTAINS(s,n)) return n; n++; if (n >= SET_MAX_SIZE(s)) return -1; } while (s[n/ELEMENTSIZE]==0) { n+=ELEMENTSIZE; if (n >= SET_MAX_SIZE(s)) return -1; } while (!SET_CONTAINS(s,n)) { n++; if (n >= SET_MAX_SIZE(s)) return -1; } return n; } /* * set_print() * * Prints the size and contents of set s to stdout. * Mainly useful for debugging purposes and trivial output. */ /* UNUSED_FUNCTION static void set_print(set_t s) { int i; printf("size=%d(max %d)",set_size(s),(int)SET_MAX_SIZE(s)); for (i=0; iedges[(i)],(j))) #define GRAPH_IS_EDGE(g,i,j) (((i)<((g)->n))?SET_CONTAINS((g)->edges[(i)], \ (j)):FALSE) #define GRAPH_ADD_EDGE(g,i,j) do { \ SET_ADD_ELEMENT((g)->edges[(i)],(j)); \ SET_ADD_ELEMENT((g)->edges[(j)],(i)); \ } while (FALSE) #define GRAPH_DEL_EDGE(g,i,j) do { \ SET_DEL_ELEMENT((g)->edges[(i)],(j)); \ SET_DEL_ELEMENT((g)->edges[(j)],(i)); \ } while (FALSE) extern graph_t *graph_new(int n); extern void graph_free(graph_t *g); extern void graph_resize(graph_t *g, int size); extern void graph_crop(graph_t *g); extern boolean graph_weighted(graph_t *g); extern int graph_edge_count(graph_t *g); /* extern graph_t *graph_read_dimacs(FILE *fp); extern graph_t *graph_read_dimacs_file(char *file); extern boolean graph_write_dimacs_ascii(graph_t *g, char *comment,FILE *fp); extern boolean graph_write_dimacs_ascii_file(graph_t *g,char *comment, char *file); extern boolean graph_write_dimacs_binary(graph_t *g, char *comment,FILE *fp); extern boolean graph_write_dimacs_binary_file(graph_t *g, char *comment, char *file); */ extern void graph_print(graph_t *g); extern boolean graph_test(graph_t *g, FILE *output); extern int graph_test_regular(graph_t *g); UNUSED_FUNCTION INLINE static int graph_subgraph_weight(graph_t *g,set_t s) { int i,j; int count=0; setelement e; for (i=0; iweights[i*ELEMENTSIZE+j]; e = e>>1; } } } return count; } UNUSED_FUNCTION INLINE static int graph_vertex_degree(graph_t *g, int v) { return set_size(g->edges[v]); } #endif /* !CLIQUER_GRAPH_H */ igraph/src/cliquer/cliquerconf.h0000644000175100001440000000361213431000472016454 0ustar hornikusers #ifndef CLIQUERCONF_H #define CLIQUERCONF_H /* * setelement is the basic memory type used in sets. It is often fastest * to be as large as can fit into the CPU registers. * * ELEMENTSIZE is the size of one setelement, measured in bits. It must * be either 16, 32 or 64 (otherwise additional changes must be made to * the source). * * The default is to use "unsigned long int" and attempt to guess the * size using , which should work pretty well. Check functioning * with "make test". */ /* typedef unsigned long int setelement; */ /* #define ELEMENTSIZE 64 */ /* * INLINE is a command prepended to function declarations to instruct the * compiler to inline the function. If inlining is not desired, define blank. * * The default is to use "inline", which is recognized by most compilers. */ /* #define INLINE */ /* #define INLINE __inline__ */ #if __STDC_VERSION__ >= 199901L #define INLINE inline #else #if defined(_MSC_VER) #define INLINE __inline #elif defined(__GNUC__) #define INLINE __inline__ #else #define INLINE #endif #endif /* * Set handling functions are defined as static functions in set.h for * performance reasons. This may cause unnecessary warnings from the * compiler. Some compilers (such as GCC) have the possibility to turn * off the warnings on a per-function basis using a flag prepended to * the function declaration. * * The default is to use the correct attribute when compiling with GCC, * or no flag otherwise. */ /* #define UNUSED_FUNCTION __attribute__((unused)) */ /* #define UNUSED_FUNCTION */ /* * Uncommenting the following will disable all assertions (checks that * function arguments and other variables are correct). This is highly * discouraged, as it allows bugs to go unnoticed easier. The assertions * are set so that they do not slow down programs notably. */ /* #define ASSERT(x) */ #endif /* !CLIQUERCONF_H */ igraph/src/cliquer/reorder.c0000644000175100001440000002140613431000472015600 0ustar hornikusers /* * This file contains the vertex reordering routines. * * Copyright (C) 2002 Sampo Niskanen, Patric Östergård. * Licensed under the GNU GPL, read the file LICENSE for details. */ #include "reorder.h" #include #include #include /* * reorder_set() * * Reorders the set s with a function i -> order[i]. * * Note: Assumes that order is the same size as SET_MAX_SIZE(s). */ void reorder_set(set_t s,int *order) { set_t tmp; int i,j; setelement e; ASSERT(reorder_is_bijection(order,SET_MAX_SIZE(s))); tmp=set_new(SET_MAX_SIZE(s)); for (i=0; i<(SET_MAX_SIZE(s)/ELEMENTSIZE); i++) { e=s[i]; if (e==0) continue; for (j=0; j>1; } } if (SET_MAX_SIZE(s)%ELEMENTSIZE) { e=s[i]; for (j=0; j<(SET_MAX_SIZE(s)%ELEMENTSIZE); j++) { if (e&1) { SET_ADD_ELEMENT(tmp,order[i*ELEMENTSIZE+j]); } e = e>>1; } } set_copy(s,tmp); set_free(tmp); return; } /* * reorder_graph() * * Reorders the vertices in the graph with function i -> order[i]. * * Note: Assumes that order is of size g->n. */ void reorder_graph(graph_t *g, int *order) { int i; set_t *tmp_e; int *tmp_w; ASSERT(reorder_is_bijection(order,g->n)); tmp_e=malloc(g->n * sizeof(set_t)); tmp_w=malloc(g->n * sizeof(int)); for (i=0; in; i++) { reorder_set(g->edges[i],order); tmp_e[order[i]]=g->edges[i]; tmp_w[order[i]]=g->weights[i]; } for (i=0; in; i++) { g->edges[i]=tmp_e[i]; g->weights[i]=tmp_w[i]; } free(tmp_e); free(tmp_w); return; } /* * reorder_duplicate() * * Returns a newly allocated duplicate of the given ordering. */ int *reorder_duplicate(int *order,int n) { int *new; new=malloc(n*sizeof(int)); memcpy(new,order,n*sizeof(int)); return new; } /* * reorder_invert() * * Inverts the given ordering so that new[old[i]]==i. * * Note: Asserts that order is a bijection. */ void reorder_invert(int *order,int n) { int *new; int i; ASSERT(reorder_is_bijection(order,n)); new=malloc(n*sizeof(int)); for (i=0; i {0,...,n-1}. * * Returns TRUE if it is a bijection, FALSE otherwise. */ boolean reorder_is_bijection(int *order,int n) { boolean *used; int i; used=calloc(n,sizeof(boolean)); for (i=0; i=n) { free(used); return FALSE; } if (used[order[i]]) { free(used); return FALSE; } used[order[i]]=TRUE; } for (i=0; in); } /* * reorder_by_reverse() * * Returns a reverse identity ordering. */ int *reorder_by_reverse(graph_t *g,boolean weighted) { int i; int *order; order=malloc(g->n * sizeof(int)); for (i=0; i < g->n; i++) order[i]=g->n-i-1; return order; } /* * reorder_by_greedy_coloring() * * Equivalent to reorder_by_weighted_greedy_coloring or * reorder_by_unweighted_greedy_coloring according to the value of weighted. */ int *reorder_by_greedy_coloring(graph_t *g,boolean weighted) { if (weighted) return reorder_by_weighted_greedy_coloring(g,weighted); else return reorder_by_unweighted_greedy_coloring(g,weighted); } /* * reorder_by_unweighted_greedy_coloring() * * Returns an ordering for the graph g by coloring the clique one * color at a time, always adding the vertex of largest degree within * the uncolored graph, and numbering these vertices 0, 1, ... * * Experimentally efficient for use with unweighted graphs. */ int *reorder_by_unweighted_greedy_coloring(graph_t *g,boolean weighted) { int i,j,v; boolean *tmp_used; int *degree; /* -1 for used vertices */ int *order; int maxdegree,maxvertex=0; boolean samecolor; tmp_used=calloc(g->n,sizeof(boolean)); degree=calloc(g->n,sizeof(int)); order=calloc(g->n,sizeof(int)); for (i=0; i < g->n; i++) { for (j=0; j < g->n; j++) { ASSERT(!((i==j) && GRAPH_IS_EDGE(g,i,j))); if (GRAPH_IS_EDGE(g,i,j)) degree[i]++; } } v=0; while (v < g->n) { /* Reset tmp_used. */ memset(tmp_used,0,g->n * sizeof(boolean)); do { /* Find vertex to be colored. */ maxdegree=0; samecolor=FALSE; for (i=0; i < g->n; i++) { if (!tmp_used[i] && degree[i] >= maxdegree) { maxvertex=i; maxdegree=degree[i]; samecolor=TRUE; } } if (samecolor) { order[v]=maxvertex; degree[maxvertex]=-1; v++; /* Mark neighbors not to color with same * color and update neighbor degrees. */ for (i=0; i < g->n; i++) { if (GRAPH_IS_EDGE(g,maxvertex,i)) { tmp_used[i]=TRUE; degree[i]--; } } } } while (samecolor); } free(tmp_used); free(degree); return order; } /* * reorder_by_weighted_greedy_coloring() * * Returns an ordering for the graph g by coloring the clique one * color at a time, always adding the vertex that (in order of importance): * 1. has the minimum weight in the remaining graph * 2. has the largest sum of weights surrounding the vertex * * Experimentally efficient for use with weighted graphs. */ int *reorder_by_weighted_greedy_coloring(graph_t *g, boolean weighted) { int i,j,p=0; int cnt; int *nwt; /* Sum of surrounding vertices' weights */ int min_wt,max_nwt; boolean *used; int *order; nwt=malloc(g->n * sizeof(int)); order=malloc(g->n * sizeof(int)); used=calloc(g->n,sizeof(boolean)); for (i=0; i < g->n; i++) { nwt[i]=0; for (j=0; j < g->n; j++) if (GRAPH_IS_EDGE(g, i, j)) nwt[i] += g->weights[j]; } for (cnt=0; cnt < g->n; cnt++) { min_wt=INT_MAX; max_nwt=-1; for (i=g->n-1; i>=0; i--) if ((!used[i]) && (g->weights[i] < min_wt)) min_wt=g->weights[i]; for (i=g->n-1; i>=0; i--) { if (used[i] || (g->weights[i] > min_wt)) continue; if (nwt[i] > max_nwt) { max_nwt=nwt[i]; p=i; } } order[cnt]=p; used[p]=TRUE; for (j=0; j < g->n; j++) if ((!used[j]) && (GRAPH_IS_EDGE(g, p, j))) nwt[j] -= g->weights[p]; } free(nwt); free(used); ASSERT(reorder_is_bijection(order,g->n)); return order; } /* * reorder_by_degree() * * Returns a reordering of the graph g so that the vertices with largest * degrees (most neighbors) are first. */ int *reorder_by_degree(graph_t *g, boolean weighted) { int i,j,v; int *degree; int *order; int maxdegree,maxvertex=0; degree=calloc(g->n,sizeof(int)); order=calloc(g->n,sizeof(int)); for (i=0; i < g->n; i++) { for (j=0; j < g->n; j++) { ASSERT(!((i==j) && GRAPH_IS_EDGE(g,i,j))); if (GRAPH_IS_EDGE(g,i,j)) degree[i]++; } } for (v=0; v < g->n; v++) { maxdegree=0; for (i=0; i < g->n; i++) { if (degree[i] >= maxdegree) { maxvertex=i; maxdegree=degree[i]; } } order[v]=maxvertex; degree[maxvertex]=-1; /* used */ /*** Max. degree withing unselected graph: for (i=0; i < g->n; i++) { if (GRAPH_IS_EDGE(g,maxvertex,i)) degree[i]--; } ***/ } free(degree); return order; } /* * reorder_by_random() * * Returns a random reordering for graph g. * Note: Used the functions rand() and srand() to generate the random * numbers. srand() is re-initialized every time reorder_by_random() * is called using the system time. */ int *reorder_by_random(graph_t *g, boolean weighted) { int i,r; int *new; boolean *used; new=calloc(g->n, sizeof(int)); used=calloc(g->n, sizeof(boolean)); for (i=0; i < g->n; i++) { do { r = igraph_rng_get_integer(igraph_rng_default(), 0, g->n - 1); } while (used[r]); new[i]=r; used[r]=TRUE; } free(used); return new; } igraph/src/cliquer/cliquer_graph.c0000644000175100001440000004006413431000472016764 0ustar hornikusers /* * This file contains the graph handling routines. * * Copyright (C) 2002 Sampo Niskanen, Patric Östergård. * Licensed under the GNU GPL, read the file LICENSE for details. */ #include #include #include #include "graph.h" #ifdef USING_R #include #endif /* static graph_t *graph_read_dimacs_binary(FILE *fp,char *firstline); static graph_t *graph_read_dimacs_ascii(FILE *fp,char *firstline); */ /* * graph_new() * * Returns a newly allocated graph with n vertices all with weight 1, * and no edges. */ graph_t *graph_new(int n) { graph_t *g; int i; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(n>0); g=malloc(sizeof(graph_t)); g->n=n; g->edges=malloc(g->n * sizeof(set_t)); g->weights=malloc(g->n * sizeof(int)); for (i=0; i < g->n; i++) { g->edges[i]=set_new(n); g->weights[i]=1; } return g; } /* * graph_free() * * Frees the memory associated with the graph g. */ void graph_free(graph_t *g) { int i; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(g!=NULL); ASSERT(g->n > 0); for (i=0; i < g->n; i++) { set_free(g->edges[i]); } free(g->weights); free(g->edges); free(g); return; } /* * graph_resize() * * Resizes graph g to given size. If size > g->n, the new vertices are * not connected to any others and their weights are set to 1. * If size < g->n, the last g->n - size vertices are removed. */ void graph_resize(graph_t *g, int size) { int i; ASSERT(g!=NULL); ASSERT(g->n > 0); ASSERT(size > 0); if (g->n == size) return; /* Free/alloc extra edge-sets */ for (i=size; i < g->n; i++) set_free(g->edges[i]); g->edges=realloc(g->edges, size * sizeof(set_t)); for (i=g->n; i < size; i++) g->edges[i]=set_new(size); /* Resize original sets */ for (i=0; i < MIN(g->n,size); i++) { g->edges[i]=set_resize(g->edges[i],size); } /* Weights */ g->weights=realloc(g->weights,size * sizeof(int)); for (i=g->n; iweights[i]=1; g->n=size; return; } /* * graph_crop() * * Resizes the graph so as to remove all highest-valued isolated vertices. */ void graph_crop(graph_t *g) { int i; for (i=g->n-1; i>=1; i--) if (set_size(g->edges[i])>0) break; graph_resize(g,i+1); return; } /* * graph_weighted() * * Returns TRUE if all vertex weights of graph g are all the same. * * Note: Does NOT require weights to be 1. */ boolean graph_weighted(graph_t *g) { int i,w; w=g->weights[0]; for (i=1; i < g->n; i++) if (g->weights[i] != w) return TRUE; return FALSE; } /* * graph_edge_count() * * Returns the number of edges in graph g. */ int graph_edge_count(graph_t *g) { int i; int count=0; for (i=0; i < g->n; i++) { count += set_size(g->edges[i]); } return count/2; } #if 0 /* * graph_write_dimacs_ascii_file() * * Writes an ASCII dimacs-format file of graph g, with comment, to * given file. * * Returns TRUE if successful, FALSE if an error occurred. */ boolean graph_write_dimacs_ascii_file(graph_t *g, char *comment, char *file) { FILE *fp; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(file!=NULL); if ((fp=fopen(file,"wb"))==NULL) return FALSE; if (!graph_write_dimacs_ascii(g,comment,fp)) { fclose(fp); return FALSE; } fclose(fp); return TRUE; } /* * graph_write_dimacs_ascii() * * Writes an ASCII dimacs-format file of graph g, with comment, to the * file stream fp. * * Returns TRUE if successful, FALSE if an error occurred. */ boolean graph_write_dimacs_ascii(graph_t *g, char *comment, FILE *fp) { int i,j; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(graph_test(g,NULL)); ASSERT(fp!=NULL); if (comment) fprintf(fp,"c %s\n",comment); fprintf(fp,"p edge %d %d\n",g->n,graph_edge_count(g)); for (i=0; i < g->n; i++) if (g->weights[i]!=1) fprintf(fp,"n %d %d\n",i+1,g->weights[i]); for (i=0; i < g->n; i++) for (j=0; j= headersize) { \ headersize+=1024; \ header=realloc(header,headersize); \ } \ strncat(header,s,1000); \ headerlength+=strlen(s); boolean graph_write_dimacs_binary(graph_t *g, char *comment,FILE *fp) { char *buf; char *header=NULL; int headersize=0; int headerlength=0; int i,j; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(graph_test(g,NULL)); ASSERT(fp!=NULL); buf=malloc(MAX(1024,g->n/8+1)); header=malloc(1024); header[0]=0; headersize=1024; if (comment) { strcpy(buf,"c "); strncat(buf,comment,1000); strcat(buf,"\n"); STR_APPEND(buf); } sprintf(buf,"p edge %d %d\n",g->n,graph_edge_count(g)); STR_APPEND(buf); for (i=0; i < g->n; i++) { if (g->weights[i]!=1) { sprintf(buf,"n %d %d\n",i+1,g->weights[i]); STR_APPEND(buf); } } fprintf(fp,"%d\n",(int)strlen(header)); fprintf(fp,"%s",header); free(header); for (i=0; i < g->n; i++) { memset(buf,0,i/8+1); for (j=0; j=strlen(str)) /* blank line */ return TRUE; if (str[i+1]!=0 && !isspace(str[i+1])) /* not 1-char field */ return FALSE; switch (str[i]) { case 'c': return TRUE; case 'p': if (g->n != 0) return FALSE; if (sscanf(str," p %15s %d %d %2s",tmp,&(g->n),&i,tmp)!=3) return FALSE; if (g->n <= 0) return FALSE; g->edges=calloc(g->n,sizeof(set_t)); for (i=0; in; i++) g->edges[i]=set_new(g->n); g->weights=calloc(g->n,sizeof(int)); for (i=0; in; i++) g->weights[i]=1; return TRUE; case 'n': if ((g->n <= 0) || (g->weights == NULL)) return FALSE; if (sscanf(str," n %d %d %2s",&i,&w,tmp)!=2) return FALSE; if (i<1 || i>g->n) return FALSE; if (w<=0) return FALSE; g->weights[i-1]=w; return TRUE; case 'e': if ((g->n <= 0) || (g->edges == NULL)) return FALSE; if (sscanf(str," e %d %d %2s",&i,&j,tmp)!=2) return FALSE; if (i<1 || j<1 || i>g->n || j>g->n) return FALSE; if (i==j) /* We want antireflexive graphs. */ return TRUE; GRAPH_ADD_EDGE(g,i-1,j-1); return TRUE; case 'd': case 'v': case 'x': return TRUE; default: fprintf(stderr,"Warning: ignoring field '%c' in " "input.\n",str[i]); return TRUE; } } /* * graph_read_dimacs_binary() * * Reads a dimacs-format binary file from file stream fp with the first * line being firstline. * * Returns the newly-allocated graph or NULL if an error occurred. * * TODO: This function leaks memory when reading erroneous files. */ static graph_t *graph_read_dimacs_binary(FILE *fp,char *firstline) { int length=0; graph_t *g; int i,j; char *buffer; char *start; char *end; char **buf; char tmp[10]; if (sscanf(firstline," %d %2s",&length,tmp)!=1) return NULL; if (length<=0) { fprintf(stderr,"Malformed preamble: preamble size < 0.\n"); return NULL; } buffer=malloc(length+2); if (fread(buffer,1,length,fp)n <= 0) { fprintf(stderr,"Malformed preamble: number of " "vertices <= 0\n"); free(g); return NULL; } /* Binary part. */ buf=calloc(g->n,sizeof(char*)); for (i=0; i < g->n; i++) { buf[i]=calloc(g->n,1); if (fread(buf[i],1,i/8+1,fp) < (i/8+1)) { fprintf(stderr,"Unexpected end of file when " "reading graph.\n"); return NULL; } } for (i=0; i < g->n; i++) { for (j=0; jn <= 0) { free(g); fprintf(stderr,"Unexpected end of file when reading graph.\n"); return NULL; } return g; } #endif #ifndef USING_R /* * graph_print() * * Prints a representation of the graph g to stdout (along with any errors * noticed). Mainly useful for debugging purposes and trivial output. * * The output consists of a first line describing the dimensions and then * one line per vertex containing the vertex number (numbered 0,...,n-1), * the vertex weight (if the graph is weighted), "->" and then a list * of all vertices it is adjacent to. */ void graph_print(graph_t *g) { int i,j; int asymm=0; int refl=0; int nonpos=0; int extra=0; unsigned int weight=0; boolean weighted; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); if (g==NULL) { printf(" WARNING: Graph pointer is NULL!\n"); return; } if (g->n <= 0) { printf(" WARNING: Graph has %d vertices " "(should be positive)!\n",g->n); return; } weighted=graph_weighted(g); printf("%s graph has %d vertices, %d edges (density %.2f).\n", weighted?"Weighted":((g->weights[0]==1)? "Unweighted":"Semi-weighted"), g->n,graph_edge_count(g), (float)graph_edge_count(g)/((float)(g->n - 1)*(g->n)/2)); for (i=0; i < g->n; i++) { printf("%2d",i); if (weighted) { printf(" w=%d",g->weights[i]); if (g->weights[i] <= 0) { printf("*NON-POSITIVE*"); nonpos++; } } if (weight < INT_MAX) weight+=g->weights[i]; printf(" ->"); for (j=0; j < g->n; j++) { if (SET_CONTAINS_FAST(g->edges[i],j)) { printf(" %d",j); if (i==j) { printf("*REFLEXIVE*"); refl++; } if (!SET_CONTAINS_FAST(g->edges[j],i)) { printf("*ASYMMERTIC*"); asymm++; } } } for (j=g->n; j < SET_ARRAY_LENGTH(g->edges[i])*ELEMENTSIZE; j++) { if (SET_CONTAINS_FAST(g->edges[i],j)) { printf(" %d*NON-EXISTENT*",j); extra++; } } printf("\n"); } if (asymm) printf(" WARNING: Graph contained %d asymmetric edges!\n", asymm); if (refl) printf(" WARNING: Graph contained %d reflexive edges!\n", refl); if (nonpos) printf(" WARNING: Graph contained %d non-positive vertex " "weights!\n",nonpos); if (extra) printf(" WARNING: Graph contained %d edges to " "non-existent vertices!\n",extra); if (weight>=INT_MAX) printf(" WARNING: Total graph weight >= INT_MAX!\n"); return; } #endif /* * graph_test() * * Tests graph g to be valid. Checks that g is non-NULL, the edges are * symmetric and anti-reflexive, and that all vertex weights are positive. * If output is non-NULL, prints a few lines telling the status of the graph * to file descriptor output. * * Returns TRUE if the graph is valid, FALSE otherwise. */ boolean graph_test(graph_t *g,FILE *output) { int i,j; int edges=0; int asymm=0; int nonpos=0; int refl=0; int extra=0; unsigned int weight=0; boolean weighted; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); if (g==NULL) { if (output) fprintf(output," WARNING: Graph pointer is NULL!\n"); return FALSE; } weighted=graph_weighted(g); for (i=0; i < g->n; i++) { if (g->edges[i]==NULL) { if (output) fprintf(output," WARNING: Graph edge set " "NULL!\n" " (further warning suppressed)\n"); return FALSE; } if (SET_MAX_SIZE(g->edges[i]) < g->n) { if (output) fprintf(output," WARNING: Graph edge set " "too small!\n" " (further warnings suppressed)\n"); return FALSE; } for (j=0; j < g->n; j++) { if (SET_CONTAINS_FAST(g->edges[i],j)) { edges++; if (i==j) { refl++; } if (!SET_CONTAINS_FAST(g->edges[j],i)) { asymm++; } } } for (j=g->n; j < SET_ARRAY_LENGTH(g->edges[i])*ELEMENTSIZE; j++) { if (SET_CONTAINS_FAST(g->edges[i],j)) extra++; } if (g->weights[i] <= 0) nonpos++; if (weightweights[i]; } edges/=2; /* Each is counted twice. */ if (output) { /* Semi-weighted means all weights are equal, but not 1. */ fprintf(output,"%s graph has %d vertices, %d edges " "(density %.2f).\n", weighted?"Weighted": ((g->weights[0]==1)?"Unweighted":"Semi-weighted"), g->n,edges,(float)edges/((float)(g->n - 1)*(g->n)/2)); if (asymm) fprintf(output," WARNING: Graph contained %d " "asymmetric edges!\n",asymm); if (refl) fprintf(output," WARNING: Graph contained %d " "reflexive edges!\n",refl); if (nonpos) fprintf(output," WARNING: Graph contained %d " "non-positive vertex weights!\n",nonpos); if (extra) fprintf(output," WARNING: Graph contained %d edges " "to non-existent vertices!\n",extra); if (weight>=INT_MAX) fprintf(output," WARNING: Total graph weight >= " "INT_MAX!\n"); if (asymm==0 && refl==0 && nonpos==0 && extra==0 && weight=INT_MAX) return FALSE; return TRUE; } /* * graph_test_regular() * * Returns the vertex degree for regular graphs, or -1 if the graph is * not regular. */ int graph_test_regular(graph_t *g) { int i,n; n=set_size(g->edges[0]); for (i=1; i < g->n; i++) { if (set_size(g->edges[i]) != n) return -1; } return n; } igraph/src/cliquer/misc.h0000644000175100001440000000243513431000472015077 0ustar hornikusers #ifndef CLIQUER_MISC_H #define CLIQUER_MISC_H #include "cliquerconf.h" /* * We #define boolean instead of using a typedef because nauty.h uses it * also. AFAIK, there is no way to check for an existing typedef, and * re-typedefing is illegal (even when using exactly the same datatype!). */ #ifndef boolean #define boolean int #endif /* * The original cliquer source has some functions incorrectly marked as unused, * thus leave this undefined. */ #define UNUSED_FUNCTION /* * Default inlining directive: "inline" */ #ifndef INLINE #define INLINE inline #endif #include #include #ifndef ASSERT #ifdef USING_R #include #define ASSERT(expr) \ if (!(expr)) { \ error("cliquer file %s: line %d: assertion failed: " \ "(%s)\n",__FILE__,__LINE__,#expr); \ } #else #define ASSERT(expr) \ if (!(expr)) { \ fprintf(stderr,"cliquer file %s: line %d: assertion failed: " \ "(%s)\n",__FILE__,__LINE__,#expr); \ abort(); \ } #endif #endif /* !ASSERT */ #ifndef FALSE #define FALSE (0) #endif #ifndef TRUE #define TRUE (!FALSE) #endif #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif #ifndef ABS #define ABS(v) (((v)<0)?(-(v)):(v)) #endif #endif /* !CLIQUER_MISC_H */ igraph/src/cliquer/cliquer.c0000644000175100001440000013047113431000472015605 0ustar hornikusers /* * This file contains the clique searching routines. * * Copyright (C) 2002 Sampo Niskanen, Patric Östergård. * Licensed under the GNU GPL, read the file LICENSE for details. */ #include #include #include /* #include #include #include */ #include "cliquer.h" #include "config.h" #ifdef USING_R #include #endif /* Default cliquer options */ IGRAPH_THREAD_LOCAL clique_options clique_default_options = { reorder_by_default, NULL, /*clique_print_time*/ NULL, NULL, NULL, NULL, NULL, 0 }; /* Calculate d/q, rounding result upwards/downwards. */ #define DIV_UP(d,q) (((d)+(q)-1)/(q)) #define DIV_DOWN(d,q) ((int)((d)/(q))) /* Global variables used: */ /* These must be saved and restored in re-entrance. */ static IGRAPH_THREAD_LOCAL int *clique_size; /* c[i] == max. clique size in {0,1,...,i-1} */ static IGRAPH_THREAD_LOCAL set_t current_clique; /* Current clique being searched. */ static IGRAPH_THREAD_LOCAL set_t best_clique; /* Largest/heaviest clique found so far. */ /*static struct tms cputimer;*/ /* Timer for opts->time_function() */ /*static struct timeval realtimer;*/ /* Timer for opts->time_function() */ static IGRAPH_THREAD_LOCAL int clique_list_count=0; /* No. of cliques in opts->clique_list[] */ static IGRAPH_THREAD_LOCAL int weight_multiplier=1; /* Weights multiplied by this when passing * to time_function(). */ /* List cache (contains memory blocks of size g->n * sizeof(int)) */ static IGRAPH_THREAD_LOCAL int **temp_list=NULL; static IGRAPH_THREAD_LOCAL int temp_count=0; /* * Macros for re-entrance. ENTRANCE_SAVE() must be called immediately * after variable definitions, ENTRANCE_RESTORE() restores global * variables to original values. entrance_level should be increased * and decreased accordingly. */ static IGRAPH_THREAD_LOCAL int entrance_level=0; /* How many levels for entrance have occurred? */ #define ENTRANCE_SAVE() \ int *old_clique_size = clique_size; \ set_t old_current_clique = current_clique; \ set_t old_best_clique = best_clique; \ int old_clique_list_count = clique_list_count; \ int old_weight_multiplier = weight_multiplier; \ int **old_temp_list = temp_list; \ int old_temp_count = temp_count; \ /*struct tms old_cputimer; \ struct timeval old_realtimer; \ memcpy(&old_cputimer,&cputimer,sizeof(struct tms)); \ memcpy(&old_realtimer,&realtimer,sizeof(struct timeval));*/ #define ENTRANCE_RESTORE() \ clique_size = old_clique_size; \ current_clique = old_current_clique; \ best_clique = old_best_clique; \ clique_list_count = old_clique_list_count; \ weight_multiplier = old_weight_multiplier; \ temp_list = old_temp_list; \ temp_count = old_temp_count; \ /*memcpy(&cputimer,&old_cputimer,sizeof(struct tms)); \ memcpy(&realtimer,&old_realtimer,sizeof(struct timeval));*/ /* Number of clock ticks per second (as returned by sysconf(_SC_CLK_TCK)) */ /*static int clocks_per_sec=0;*/ /* Recursion and helper functions */ static boolean sub_unweighted_single(int *table, int size, int min_size, graph_t *g); static int sub_unweighted_all(int *table, int size, int min_size, int max_size, boolean maximal, graph_t *g, clique_options *opts); static int sub_weighted_all(int *table, int size, int weight, int current_weight, int prune_low, int prune_high, int min_weight, int max_weight, boolean maximal, graph_t *g, clique_options *opts); static boolean store_clique(set_t clique, graph_t *g, clique_options *opts); static boolean is_maximal(set_t clique, graph_t *g); static boolean false_function(set_t clique,graph_t *g,clique_options *opts); /***** Unweighted searches *****/ /* * Unweighted searches are done separately from weighted searches because * some effective pruning methods can be used when the vertex weights * are all 1. Single and all clique finding routines are separated, * because the single clique finding routine can store the found clique * while it is returning from the recursion, thus requiring no implicit * storing of the current clique. When searching for all cliques the * current clique must be stored. */ /* * unweighted_clique_search_single() * * Searches for a single clique of size min_size. Stores maximum clique * sizes into clique_size[]. * * table - the order of the vertices in g to use * min_size - minimum size of clique to search for. If min_size==0, * searches for a maximum clique. * g - the graph * opts - time printing options * * opts->time_function is called after each base-level recursion, if * non-NULL. * * Returns the size of the clique found, or 0 if min_size>0 and a clique * of that size was not found (or if time_function aborted the search). * The largest clique found is stored in current_clique. * * Note: Does NOT use opts->user_function of opts->clique_list. */ static int unweighted_clique_search_single(int *table, int min_size, graph_t *g, clique_options *opts) { /* struct tms tms; struct timeval timeval; */ int i,j; int v,w; int *newtable; int newsize; v=table[0]; clique_size[v]=1; set_empty(current_clique); SET_ADD_ELEMENT(current_clique,v); if (min_size==1) return 1; if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } for (i=1; i < g->n; i++) { w=v; v=table[i]; newsize=0; for (j=0; jtime_function) { gettimeofday(&timeval,NULL); times(&tms); if (!opts->time_function(entrance_level, i+1,g->n,clique_size[v] * weight_multiplier, (double)(tms.tms_utime- cputimer.tms_utime)/ clocks_per_sec, timeval.tv_sec- realtimer.tv_sec+ (double)(timeval.tv_usec- realtimer.tv_usec)/ 1000000,opts)) { temp_list[temp_count++]=newtable; return 0; } } */ if (min_size) { if (clique_size[v]>=min_size) { temp_list[temp_count++]=newtable; return clique_size[v]; } if (clique_size[v]+g->n-i-1 < min_size) { temp_list[temp_count++]=newtable; return 0; } } } temp_list[temp_count++]=newtable; if (min_size) return 0; return clique_size[v]; } /* * sub_unweighted_single() * * Recursion function for searching for a single clique of size min_size. * * table - subset of the vertices in graph * size - size of table * min_size - size of clique to look for within the subgraph * (decreased with every recursion) * g - the graph * * Returns TRUE if a clique of size min_size is found, FALSE otherwise. * If a clique of size min_size is found, it is stored in current_clique. * * clique_size[] for all values in table must be defined and correct, * otherwise inaccurate results may occur. */ static boolean sub_unweighted_single(int *table, int size, int min_size, graph_t *g) { int i; int v; int *newtable; int *p1, *p2; /* Zero or one vertices needed anymore. */ if (min_size <= 1) { if (size>0 && min_size==1) { set_empty(current_clique); SET_ADD_ELEMENT(current_clique,table[0]); return TRUE; } if (min_size==0) { set_empty(current_clique); return TRUE; } return FALSE; } if (size < min_size) return FALSE; /* Dynamic memory allocation with cache */ if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } for (i = size-1; i >= 0; i--) { v = table[i]; if (clique_size[v] < min_size) break; /* This is faster when compiling with gcc than placing * this in the for-loop condition. */ if (i+1 < min_size) break; /* Very ugly code, but works faster than "for (i=...)" */ p1 = newtable; for (p2=table; p2 < table+i; p2++) { int w = *p2; if (GRAPH_IS_EDGE(g, v, w)) { *p1 = w; p1++; } } /* Avoid unneccessary loops (next size == p1-newtable) */ if (p1-newtable < min_size-1) continue; /* Now p1-newtable >= min_size-1 >= 2-1 == 1, so we can use * p1-newtable-1 safely. */ if (clique_size[newtable[p1-newtable-1]] < min_size-1) continue; if (sub_unweighted_single(newtable,p1-newtable, min_size-1,g)) { /* Clique found. */ SET_ADD_ELEMENT(current_clique,v); temp_list[temp_count++]=newtable; return TRUE; } } temp_list[temp_count++]=newtable; return FALSE; } /* * unweighted_clique_search_all() * * Searches for all cliques with size at least min_size and at most * max_size. Stores the cliques as opts declares. * * table - the order of the vertices in g to search * start - first index where the subgraph table[0], ..., table[start] * might include a requested kind of clique * min_size - minimum size of clique to search for. min_size > 0 ! * max_size - maximum size of clique to search for. If no upper limit * is desired, use eg. INT_MAX * maximal - requires cliques to be maximal * g - the graph * opts - time printing and clique storage options * * Cliques found are stored as defined by opts->user_function and * opts->clique_list. opts->time_function is called after each * base-level recursion, if non-NULL. * * clique_size[] must be defined and correct for all values of * table[0], ..., table[start-1]. * * Returns the number of cliques stored (not neccessarily number of cliques * in graph, if user/time_function aborts). */ static int unweighted_clique_search_all(int *table, int start, int min_size, int max_size, boolean maximal, graph_t *g, clique_options *opts) { /* struct timeval timeval; struct tms tms; */ int i,j; int v; int *newtable; int newsize; int count=0; if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } clique_list_count=0; set_empty(current_clique); for (i=start; i < g->n; i++) { v=table[i]; clique_size[v]=min_size; /* Do not prune here. */ newsize=0; for (j=0; jtime_function) { gettimeofday(&timeval,NULL); times(&tms); if (!opts->time_function(entrance_level, i+1,g->n,min_size * weight_multiplier, (double)(tms.tms_utime- cputimer.tms_utime)/ clocks_per_sec, timeval.tv_sec- realtimer.tv_sec+ (double)(timeval.tv_usec- realtimer.tv_usec)/ 1000000,opts)) { /* Abort. */ break; } } #endif } temp_list[temp_count++]=newtable; return count; } /* * sub_unweighted_all() * * Recursion function for searching for all cliques of given size. * * table - subset of vertices of graph g * size - size of table * min_size - minimum size of cliques to search for (decreased with * every recursion) * max_size - maximum size of cliques to search for (decreased with * every recursion). If no upper limit is desired, use * eg. INT_MAX * maximal - require cliques to be maximal (passed through) * g - the graph * opts - storage options * * All cliques of suitable size found are stored according to opts. * * Returns the number of cliques found. If user_function returns FALSE, * then the number of cliques is returned negative. * * Uses current_clique to store the currently-being-searched clique. * clique_size[] for all values in table must be defined and correct, * otherwise inaccurate results may occur. */ static int sub_unweighted_all(int *table, int size, int min_size, int max_size, boolean maximal, graph_t *g, clique_options *opts) { int i; int v; int n; int *newtable; int *p1, *p2; int count=0; /* Amount of cliques found */ if (min_size <= 0) { if ((!maximal) || is_maximal(current_clique,g)) { /* We've found one. Store it. */ count++; if (!store_clique(current_clique,g,opts)) { return -count; } } if (max_size <= 0) { /* If we add another element, size will be too big. */ return count; } } if (size < min_size) { return count; } /* Dynamic memory allocation with cache */ if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } for (i=size-1; i>=0; i--) { v = table[i]; if (clique_size[v] < min_size) { break; } if (i+1 < min_size) { break; } /* Very ugly code, but works faster than "for (i=...)" */ p1 = newtable; for (p2=table; p2 < table+i; p2++) { int w = *p2; if (GRAPH_IS_EDGE(g, v, w)) { *p1 = w; p1++; } } /* Avoid unneccessary loops (next size == p1-newtable) */ if (p1-newtable < min_size-1) { continue; } SET_ADD_ELEMENT(current_clique,v); n=sub_unweighted_all(newtable,p1-newtable, min_size-1,max_size-1,maximal,g,opts); SET_DEL_ELEMENT(current_clique,v); if (n < 0) { /* Abort. */ count -= n; count = -count; break; } count+=n; } temp_list[temp_count++]=newtable; return count; } /***** Weighted clique searches *****/ /* * Weighted clique searches can use the same recursive routine, because * in both cases (single/all) they have to search through all potential * permutations searching for heavier cliques. */ /* * weighted_clique_search_single() * * Searches for a single clique of weight at least min_weight, and at * most max_weight. Stores maximum clique sizes into clique_size[] * (or min_weight-1, whichever is smaller). * * table - the order of the vertices in g to use * min_weight - minimum weight of clique to search for. If min_weight==0, * then searches for a maximum weight clique * max_weight - maximum weight of clique to search for. If no upper limit * is desired, use eg. INT_MAX * g - the graph * opts - time printing options * * opts->time_function is called after each base-level recursion, if * non-NULL. * * Returns 0 if a clique of requested weight was not found (also if * time_function requested an abort), otherwise returns >= 1. * If min_weight==0 (search for maximum-weight clique), then the return * value is the weight of the clique found. The found clique is stored * in best_clique. * * Note: Does NOT use opts->user_function of opts->clique_list. */ static int weighted_clique_search_single(int *table, int min_weight, int max_weight, graph_t *g, clique_options *opts) { /* struct timeval timeval; struct tms tms; */ int i,j; int v; int *newtable; int newsize; int newweight; int search_weight; int min_w; clique_options localopts; if (min_weight==0) min_w=INT_MAX; else min_w=min_weight; if (min_weight==1) { /* min_weight==1 may cause trouble in the routine, and * it's trivial to check as it's own case. * We write nothing to clique_size[]. */ for (i=0; i < g->n; i++) { if (g->weights[table[i]] <= max_weight) { set_empty(best_clique); SET_ADD_ELEMENT(best_clique,table[i]); return g->weights[table[i]]; } } return 0; } localopts.time_function=NULL; localopts.reorder_function=NULL; localopts.reorder_map=NULL; localopts.user_function=false_function; localopts.user_data=NULL; localopts.clique_list=&best_clique; localopts.clique_list_length=1; clique_list_count=0; v=table[0]; set_empty(best_clique); SET_ADD_ELEMENT(best_clique,v); search_weight=g->weights[v]; if (min_weight && (search_weight >= min_weight)) { if (search_weight <= max_weight) { /* Found suitable clique. */ return search_weight; } search_weight=min_weight-1; } clique_size[v]=search_weight; set_empty(current_clique); if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } for (i = 1; i < g->n; i++) { v=table[i]; newsize=0; newweight=0; for (j=0; jweights[table[j]]; newtable[newsize]=table[j]; newsize++; } } SET_ADD_ELEMENT(current_clique,v); search_weight=sub_weighted_all(newtable,newsize,newweight, g->weights[v],search_weight, clique_size[table[i-1]] + g->weights[v], min_w,max_weight,FALSE, g,&localopts); SET_DEL_ELEMENT(current_clique,v); if (search_weight < 0) { break; } clique_size[v]=search_weight; /* if (opts->time_function) { gettimeofday(&timeval,NULL); times(&tms); if (!opts->time_function(entrance_level, i+1,g->n,clique_size[v] * weight_multiplier, (double)(tms.tms_utime- cputimer.tms_utime)/ clocks_per_sec, timeval.tv_sec- realtimer.tv_sec+ (double)(timeval.tv_usec- realtimer.tv_usec)/ 1000000,opts)) { set_free(current_clique); current_clique=NULL; break; } } */ } temp_list[temp_count++]=newtable; if (min_weight && (search_weight > 0)) { /* Requested clique has not been found. */ return 0; } return clique_size[table[i-1]]; } /* * weighted_clique_search_all() * * Searches for all cliques with weight at least min_weight and at most * max_weight. Stores the cliques as opts declares. * * table - the order of the vertices in g to search * start - first index where the subgraph table[0], ..., table[start] * might include a requested kind of clique * min_weight - minimum weight of clique to search for. min_weight > 0 ! * max_weight - maximum weight of clique to search for. If no upper limit * is desired, use eg. INT_MAX * maximal - search only for maximal cliques * g - the graph * opts - time printing and clique storage options * * Cliques found are stored as defined by opts->user_function and * opts->clique_list. opts->time_function is called after each * base-level recursion, if non-NULL. * * clique_size[] must be defined and correct for all values of * table[0], ..., table[start-1]. * * Returns the number of cliques stored (not neccessarily number of cliques * in graph, if user/time_function aborts). */ static int weighted_clique_search_all(int *table, int start, int min_weight, int max_weight, boolean maximal, graph_t *g, clique_options *opts) { /* struct timeval timeval; struct tms tms; */ int i,j; int v; int *newtable; int newsize; int newweight; if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } clique_list_count=0; set_empty(current_clique); for (i=start; i < g->n; i++) { v=table[i]; clique_size[v]=min_weight; /* Do not prune here. */ newsize=0; newweight=0; for (j=0; jweights[table[j]]; newsize++; } } SET_ADD_ELEMENT(current_clique,v); j=sub_weighted_all(newtable,newsize,newweight, g->weights[v],min_weight-1,INT_MAX, min_weight,max_weight,maximal,g,opts); SET_DEL_ELEMENT(current_clique,v); if (j<0) { /* Abort. */ break; } /* if (opts->time_function) { gettimeofday(&timeval,NULL); times(&tms); if (!opts->time_function(entrance_level, i+1,g->n,clique_size[v] * weight_multiplier, (double)(tms.tms_utime- cputimer.tms_utime)/ clocks_per_sec, timeval.tv_sec- realtimer.tv_sec+ (double)(timeval.tv_usec- realtimer.tv_usec)/ 1000000,opts)) { set_free(current_clique); current_clique=NULL; break; } } */ } temp_list[temp_count++]=newtable; return clique_list_count; } /* * sub_weighted_all() * * Recursion function for searching for all cliques of given weight. * * table - subset of vertices of graph g * size - size of table * weight - total weight of vertices in table * current_weight - weight of clique found so far * prune_low - ignore all cliques with weight less or equal to this value * (often heaviest clique found so far) (passed through) * prune_high - maximum weight possible for clique in this subgraph * (passed through) * min_size - minimum weight of cliques to search for (passed through) * Must be greater than 0. * max_size - maximum weight of cliques to search for (passed through) * If no upper limit is desired, use eg. INT_MAX * maximal - search only for maximal cliques * g - the graph * opts - storage options * * All cliques of suitable weight found are stored according to opts. * * Returns weight of heaviest clique found (prune_low if a heavier clique * hasn't been found); if a clique with weight at least min_size is found * then min_size-1 is returned. If clique storage failed, -1 is returned. * * The largest clique found smaller than max_weight is stored in * best_clique, if non-NULL. * * Uses current_clique to store the currently-being-searched clique. * clique_size[] for all values in table must be defined and correct, * otherwise inaccurate results may occur. * * To search for a single maximum clique, use min_weight==max_weight==INT_MAX, * with best_clique non-NULL. To search for a single given-weight clique, * use opts->clique_list and opts->user_function=false_function. When * searching for all cliques, min_weight should be given the minimum weight * desired. */ static int sub_weighted_all(int *table, int size, int weight, int current_weight, int prune_low, int prune_high, int min_weight, int max_weight, boolean maximal, graph_t *g, clique_options *opts) { int i; int v,w; int *newtable; int *p1, *p2; int newweight; if (current_weight >= min_weight) { if ((current_weight <= max_weight) && ((!maximal) || is_maximal(current_clique,g))) { /* We've found one. Store it. */ if (!store_clique(current_clique,g,opts)) { return -1; } } if (current_weight >= max_weight) { /* Clique too heavy. */ return min_weight-1; } } if (size <= 0) { /* current_weight < min_weight, prune_low < min_weight, * so return value is always < min_weight. */ if (current_weight>prune_low) { if (best_clique) set_copy(best_clique,current_clique); if (current_weight < min_weight) return current_weight; else return min_weight-1; } else { return prune_low; } } /* Dynamic memory allocation with cache */ if (temp_count) { temp_count--; newtable=temp_list[temp_count]; } else { newtable=malloc(g->n * sizeof(int)); } for (i = size-1; i >= 0; i--) { v = table[i]; if (current_weight+clique_size[v] <= prune_low) { /* Dealing with subset without heavy enough clique. */ break; } if (current_weight+weight <= prune_low) { /* Even if all elements are added, won't do. */ break; } /* Very ugly code, but works faster than "for (i=...)" */ p1 = newtable; newweight = 0; for (p2=table; p2 < table+i; p2++) { w = *p2; if (GRAPH_IS_EDGE(g, v, w)) { *p1 = w; newweight += g->weights[w]; p1++; } } w=g->weights[v]; weight-=w; /* Avoid a few unneccessary loops */ if (current_weight+w+newweight <= prune_low) { continue; } SET_ADD_ELEMENT(current_clique,v); prune_low=sub_weighted_all(newtable,p1-newtable, newweight, current_weight+w, prune_low,prune_high, min_weight,max_weight,maximal, g,opts); SET_DEL_ELEMENT(current_clique,v); if ((prune_low<0) || (prune_low>=prune_high)) { /* Impossible to find larger clique. */ break; } } temp_list[temp_count++]=newtable; return prune_low; } /***** Helper functions *****/ /* * store_clique() * * Stores a clique according to given user options. * * clique - the clique to store * opts - storage options * * Returns FALSE if opts->user_function() returned FALSE; otherwise * returns TRUE. */ static boolean store_clique(set_t clique, graph_t *g, clique_options *opts) { clique_list_count++; /* clique_list[] */ if (opts->clique_list) { /* * This has been a major source of bugs: * Has clique_list_count been set to 0 before calling * the recursions? */ if (clique_list_count <= 0) { #ifdef USING_R error("CLIQUER INTERNAL ERROR: ", "clique_list_count has negative value!"); #else fprintf(stderr,"CLIQUER INTERNAL ERROR: " "clique_list_count has negative value!\n"); fprintf(stderr,"Please report as a bug.\n"); abort(); #endif } if (clique_list_count <= opts->clique_list_length) opts->clique_list[clique_list_count-1] = set_duplicate(clique); } /* user_function() */ if (opts->user_function) { if (!opts->user_function(clique,g,opts)) { /* User function requested abort. */ return FALSE; } } return TRUE; } /* * maximalize_clique() * * Adds greedily all possible vertices in g to set s to make it a maximal * clique. * * s - clique of vertices to make maximal * g - graph * * Note: Not very optimized (uses a simple O(n^2) routine), but is called * at maximum once per clique_xxx() call, so it shouldn't matter. */ static void maximalize_clique(set_t s,graph_t *g) { int i,j; boolean add; for (i=0; i < g->n; i++) { add=TRUE; for (j=0; j < g->n; j++) { if (SET_CONTAINS_FAST(s,j) && !GRAPH_IS_EDGE(g,i,j)) { add=FALSE; break; } } if (add) { SET_ADD_ELEMENT(s,i); } } return; } /* * is_maximal() * * Check whether a clique is maximal or not. * * clique - set of vertices in clique * g - graph * * Returns TRUE is clique is a maximal clique of g, otherwise FALSE. */ static boolean is_maximal(set_t clique, graph_t *g) { int i,j; int *table; int len; boolean addable; if (temp_count) { temp_count--; table=temp_list[temp_count]; } else { table=malloc(g->n * sizeof(int)); } len=0; for (i=0; i < g->n; i++) if (SET_CONTAINS_FAST(clique,i)) table[len++]=i; for (i=0; i < g->n; i++) { addable=TRUE; for (j=0; jtime_function() requests abort). * * The returned clique is newly allocated and can be freed by set_free(). * * Note: Does NOT use opts->user_function() or opts->clique_list[]. */ set_t clique_unweighted_find_single(graph_t *g,int min_size,int max_size, boolean maximal, clique_options *opts) { int i; int *table; set_t s; ENTRANCE_SAVE(); entrance_level++; if (opts==NULL) opts=&clique_default_options; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(g!=NULL); ASSERT(min_size>=0); ASSERT(max_size>=0); ASSERT((max_size==0) || (min_size <= max_size)); ASSERT(!((min_size==0) && (max_size>0))); ASSERT((opts->reorder_function==NULL) || (opts->reorder_map==NULL)); if ((max_size>0) && (min_size>max_size)) { /* state was not changed */ entrance_level--; return NULL; } /* if (clocks_per_sec==0) clocks_per_sec=sysconf(_SC_CLK_TCK); ASSERT(clocks_per_sec>0); */ /* Dynamic allocation */ current_clique=set_new(g->n); clique_size=malloc(g->n * sizeof(int)); /* table allocated later */ temp_list=malloc((g->n+2)*sizeof(int *)); temp_count=0; /* "start clock" */ /* gettimeofday(&realtimer,NULL); times(&cputimer); */ /* reorder */ if (opts->reorder_function) { table=opts->reorder_function(g,FALSE); } else if (opts->reorder_map) { table=reorder_duplicate(opts->reorder_map,g->n); } else { table=reorder_ident(g->n); } ASSERT(reorder_is_bijection(table,g->n)); if (unweighted_clique_search_single(table,min_size,g,opts)==0) { set_free(current_clique); current_clique=NULL; goto cleanreturn; } if (maximal && (min_size>0)) { maximalize_clique(current_clique,g); if ((max_size > 0) && (set_size(current_clique) > max_size)) { clique_options localopts; s = set_new(g->n); localopts.time_function = opts->time_function; localopts.output = opts->output; localopts.user_function = false_function; localopts.clique_list = &s; localopts.clique_list_length = 1; for (i=0; i < g->n-1; i++) if (clique_size[table[i]]>=min_size) break; if (unweighted_clique_search_all(table,i,min_size, max_size,maximal, g,&localopts)) { set_free(current_clique); current_clique=s; } else { set_free(current_clique); current_clique=NULL; } } } cleanreturn: s=current_clique; /* Free resources */ for (i=0; i < temp_count; i++) free(temp_list[i]); free(temp_list); free(table); free(clique_size); ENTRANCE_RESTORE(); entrance_level--; return s; } /* * clique_unweighted_find_all() * * Find all cliques with size at least min_size and at most max_size. * * g - the graph * min_size - minimum size of cliques to search for. If min_size==0, * searches for maximum cliques. * max_size - maximum size of cliques to search for. If max_size==0, no * upper limit is used. If min_size==0, this must also be 0. * maximal - require cliques to be maximal cliques * opts - time printing and clique storage options * * Returns the number of cliques found. This can be less than the number * of cliques in the graph iff opts->time_function() or opts->user_function() * returns FALSE (request abort). * * The cliques found are stored in opts->clique_list[] and * opts->user_function() is called with them (if non-NULL). The cliques * stored in opts->clique_list[] are newly allocated, and can be freed * by set_free(). */ int clique_unweighted_find_all(graph_t *g, int min_size, int max_size, boolean maximal, clique_options *opts) { int i; int *table; int count; ENTRANCE_SAVE(); entrance_level++; if (opts==NULL) opts=&clique_default_options; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(g!=NULL); ASSERT(min_size>=0); ASSERT(max_size>=0); ASSERT((max_size==0) || (min_size <= max_size)); ASSERT(!((min_size==0) && (max_size>0))); ASSERT((opts->reorder_function==NULL) || (opts->reorder_map==NULL)); if ((max_size>0) && (min_size>max_size)) { /* state was not changed */ entrance_level--; return 0; } /* if (clocks_per_sec==0) clocks_per_sec=sysconf(_SC_CLK_TCK); ASSERT(clocks_per_sec>0); */ /* Dynamic allocation */ current_clique=set_new(g->n); clique_size=malloc(g->n * sizeof(int)); /* table allocated later */ temp_list=malloc((g->n+2)*sizeof(int *)); temp_count=0; clique_list_count=0; memset(clique_size,0,g->n * sizeof(int)); /* "start clock" */ /* gettimeofday(&realtimer,NULL); times(&cputimer); */ /* reorder */ if (opts->reorder_function) { table=opts->reorder_function(g,FALSE); } else if (opts->reorder_map) { table=reorder_duplicate(opts->reorder_map,g->n); } else { table=reorder_ident(g->n); } ASSERT(reorder_is_bijection(table,g->n)); /* Search as normal until there is a chance to find a suitable * clique. */ if (unweighted_clique_search_single(table,min_size,g,opts)==0) { count=0; goto cleanreturn; } if (min_size==0 && max_size==0) { min_size=max_size=clique_size[table[g->n-1]]; maximal=FALSE; /* No need to test, since we're searching * for maximum cliques. */ } if (max_size==0) { max_size=INT_MAX; } for (i=0; i < g->n-1; i++) if (clique_size[table[i]] >= min_size) break; count=unweighted_clique_search_all(table,i,min_size,max_size, maximal,g,opts); cleanreturn: /* Free resources */ for (i=0; itime_function() requests abort). * * The returned clique is newly allocated and can be freed by set_free(). * * Note: Does NOT use opts->user_function() or opts->clique_list[]. * Note: Automatically uses clique_unweighted_find_single if all vertex * weights are the same. */ set_t clique_find_single(graph_t *g,int min_weight,int max_weight, boolean maximal, clique_options *opts) { int i; int *table; set_t s; ENTRANCE_SAVE(); entrance_level++; if (opts==NULL) opts=&clique_default_options; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(g!=NULL); ASSERT(min_weight>=0); ASSERT(max_weight>=0); ASSERT((max_weight==0) || (min_weight <= max_weight)); ASSERT(!((min_weight==0) && (max_weight>0))); ASSERT((opts->reorder_function==NULL) || (opts->reorder_map==NULL)); if ((max_weight>0) && (min_weight>max_weight)) { /* state was not changed */ entrance_level--; return NULL; } /* if (clocks_per_sec==0) clocks_per_sec=sysconf(_SC_CLK_TCK); ASSERT(clocks_per_sec>0); */ /* Check whether we can use unweighted routines. */ if (!graph_weighted(g)) { min_weight=DIV_UP(min_weight,g->weights[0]); if (max_weight) { max_weight=DIV_DOWN(max_weight,g->weights[0]); if (max_weight < min_weight) { /* state was not changed */ entrance_level--; return NULL; } } weight_multiplier = g->weights[0]; entrance_level--; s=clique_unweighted_find_single(g,min_weight,max_weight, maximal,opts); ENTRANCE_RESTORE(); return s; } /* Dynamic allocation */ current_clique=set_new(g->n); best_clique=set_new(g->n); clique_size=malloc(g->n * sizeof(int)); memset(clique_size, 0, g->n * sizeof(int)); /* table allocated later */ temp_list=malloc((g->n+2)*sizeof(int *)); temp_count=0; clique_list_count=0; /* "start clock" */ /* gettimeofday(&realtimer,NULL); times(&cputimer); */ /* reorder */ if (opts->reorder_function) { table=opts->reorder_function(g,TRUE); } else if (opts->reorder_map) { table=reorder_duplicate(opts->reorder_map,g->n); } else { table=reorder_ident(g->n); } ASSERT(reorder_is_bijection(table,g->n)); if (max_weight==0) max_weight=INT_MAX; if (weighted_clique_search_single(table,min_weight,max_weight, g,opts)==0) { /* Requested clique has not been found. */ set_free(best_clique); best_clique=NULL; goto cleanreturn; } if (maximal && (min_weight>0)) { maximalize_clique(best_clique,g); if (graph_subgraph_weight(g,best_clique) > max_weight) { clique_options localopts; localopts.time_function = opts->time_function; localopts.output = opts->output; localopts.user_function = false_function; localopts.clique_list = &best_clique; localopts.clique_list_length = 1; for (i=0; i < g->n-1; i++) if ((clique_size[table[i]] >= min_weight) || (clique_size[table[i]] == 0)) break; if (!weighted_clique_search_all(table,i,min_weight, max_weight,maximal, g,&localopts)) { set_free(best_clique); best_clique=NULL; } } } cleanreturn: s=best_clique; /* Free resources */ for (i=0; i < temp_count; i++) free(temp_list[i]); free(temp_list); temp_list=NULL; temp_count=0; free(table); set_free(current_clique); current_clique=NULL; free(clique_size); clique_size=NULL; ENTRANCE_RESTORE(); entrance_level--; return s; } /* * clique_find_all() * * Find all cliques with weight at least min_weight and at most max_weight. * * g - the graph * min_weight - minimum weight of cliques to search for. If min_weight==0, * searches for maximum weight cliques. * max_weight - maximum weight of cliques to search for. If max_weight==0, * no upper limit is used. If min_weight==0, max_weight must * also be 0. * maximal - require cliques to be maximal cliques * opts - time printing and clique storage options * * Returns the number of cliques found. This can be less than the number * of cliques in the graph iff opts->time_function() or opts->user_function() * returns FALSE (request abort). * * The cliques found are stored in opts->clique_list[] and * opts->user_function() is called with them (if non-NULL). The cliques * stored in opts->clique_list[] are newly allocated, and can be freed * by set_free(). * * Note: Automatically uses clique_unweighted_find_all if all vertex * weights are the same. */ int clique_find_all(graph_t *g, int min_weight, int max_weight, boolean maximal, clique_options *opts) { int i,n; int *table; ENTRANCE_SAVE(); entrance_level++; if (opts==NULL) opts=&clique_default_options; ASSERT((sizeof(setelement)*8)==ELEMENTSIZE); ASSERT(g!=NULL); ASSERT(min_weight>=0); ASSERT(max_weight>=0); ASSERT((max_weight==0) || (min_weight <= max_weight)); ASSERT(!((min_weight==0) && (max_weight>0))); ASSERT((opts->reorder_function==NULL) || (opts->reorder_map==NULL)); if ((max_weight>0) && (min_weight>max_weight)) { /* state was not changed */ entrance_level--; return 0; } /* if (clocks_per_sec==0) clocks_per_sec=sysconf(_SC_CLK_TCK); ASSERT(clocks_per_sec>0); */ if (!graph_weighted(g)) { min_weight=DIV_UP(min_weight,g->weights[0]); if (max_weight) { max_weight=DIV_DOWN(max_weight,g->weights[0]); if (max_weight < min_weight) { /* state was not changed */ entrance_level--; return 0; } } weight_multiplier = g->weights[0]; entrance_level--; i=clique_unweighted_find_all(g,min_weight,max_weight,maximal, opts); ENTRANCE_RESTORE(); return i; } /* Dynamic allocation */ current_clique=set_new(g->n); best_clique=set_new(g->n); clique_size=malloc(g->n * sizeof(int)); memset(clique_size, 0, g->n * sizeof(int)); /* table allocated later */ temp_list=malloc((g->n+2)*sizeof(int *)); temp_count=0; /* "start clock" */ /* gettimeofday(&realtimer,NULL); times(&cputimer); */ /* reorder */ if (opts->reorder_function) { table=opts->reorder_function(g,TRUE); } else if (opts->reorder_map) { table=reorder_duplicate(opts->reorder_map,g->n); } else { table=reorder_ident(g->n); } ASSERT(reorder_is_bijection(table,g->n)); /* First phase */ n=weighted_clique_search_single(table,min_weight,INT_MAX,g,opts); if (n==0) { /* Requested clique has not been found. */ goto cleanreturn; } if (min_weight==0) { min_weight=n; max_weight=n; maximal=FALSE; /* They're maximum cliques already. */ } if (max_weight==0) max_weight=INT_MAX; for (i=0; i < g->n; i++) if ((clique_size[table[i]] >= min_weight) || (clique_size[table[i]] == 0)) break; /* Second phase */ n=weighted_clique_search_all(table,i,min_weight,max_weight,maximal, g,opts); cleanreturn: /* Free resources */ for (i=0; i < temp_count; i++) free(temp_list[i]); free(temp_list); free(table); set_free(current_clique); set_free(best_clique); free(clique_size); ENTRANCE_RESTORE(); entrance_level--; return n; } #if 0 /* * clique_print_time() * * Reports current running information every 0.1 seconds or when values * change. * * level - re-entrance level * i - current recursion level * n - maximum recursion level * max - weight of heaviest clique found * cputime - CPU time used in algorithm so far * realtime - real time used in algorithm so far * opts - prints information to (FILE *)opts->output (or stdout if NULL) * * Returns always TRUE (ie. never requests abort). */ boolean clique_print_time(int level, int i, int n, int max, double cputime, double realtime, clique_options *opts) { static float prev_time=100; static int prev_i=100; static int prev_max=100; static int prev_level=0; FILE *fp=opts->output; int j; if (fp==NULL) fp=stdout; if (ABS(prev_time-realtime)>0.1 || i==n || ioutput (or stdout if NULL) * * Returns always TRUE (ie. never requests abort). */ boolean clique_print_time_always(int level, int i, int n, int max, double cputime, double realtime, clique_options *opts) { static float prev_time=100; static int prev_i=100; FILE *fp=opts->output; int j; if (fp==NULL) fp=stdout; for (j=1; j #include "set.h" #include "graph.h" #include "reorder.h" typedef struct _clique_options clique_options; struct _clique_options { int *(*reorder_function)(graph_t *, boolean); int *reorder_map; /* arguments: level, n, max, user_time, system_time, opts */ boolean (*time_function)(int,int,int,int,double,double, clique_options *); FILE *output; boolean (*user_function)(set_t,graph_t *,clique_options *); void *user_data; set_t *clique_list; int clique_list_length; }; /* Weighted clique functions */ extern int clique_max_weight(graph_t *g,clique_options *opts); extern set_t clique_find_single(graph_t *g,int min_weight,int max_weight, boolean maximal, clique_options *opts); extern int clique_find_all(graph_t *g, int req_weight, boolean exact, boolean maximal, clique_options *opts); /* Unweighted clique functions */ #define clique_unweighted_max_size clique_unweighted_max_weight extern int clique_unweighted_max_weight(graph_t *g, clique_options *opts); extern set_t clique_unweighted_find_single(graph_t *g,int min_size, int max_size,boolean maximal, clique_options *opts); extern int clique_unweighted_find_all(graph_t *g, int min_size, int max_size, boolean maximal, clique_options *opts); /* Time printing functions */ /* extern boolean clique_print_time(int level, int i, int n, int max, double cputime, double realtime, clique_options *opts); extern boolean clique_print_time_always(int level, int i, int n, int max, double cputime, double realtime, clique_options *opts); */ /* Alternate spelling (let's be a little forgiving): */ #define cliquer_options clique_options #define cliquer_default_options clique_default_options #endif /* !CLIQUER_H */ igraph/src/gml_tree.c0000644000175100001440000001572413431000472014276 0ustar hornikusers/* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_gml_tree.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include #include int igraph_gml_tree_init_integer(igraph_gml_tree_t *t, const char *name, int namelen, igraph_integer_t value) { igraph_integer_t *p; IGRAPH_UNUSED(namelen); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->names, 1); IGRAPH_CHECK(igraph_vector_char_init(&t->types, 1)); IGRAPH_FINALLY(igraph_vector_char_destroy, &t->types); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->children, 1); /* names */ VECTOR(t->names)[0] = (void*)name; /* types */ VECTOR(t->types)[0] = IGRAPH_I_GML_TREE_INTEGER; /* children */ p=igraph_Calloc(1, igraph_integer_t); if (!p) { IGRAPH_ERROR("Cannot create integer GML tree node", IGRAPH_ENOMEM); } *p=value; VECTOR(t->children)[0]=p; IGRAPH_FINALLY_CLEAN(3); return 0; } int igraph_gml_tree_init_real(igraph_gml_tree_t *t, const char *name, int namelen, igraph_real_t value) { igraph_real_t *p; IGRAPH_UNUSED(namelen); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->names, 1); IGRAPH_CHECK(igraph_vector_char_init(&t->types, 1)); IGRAPH_FINALLY(igraph_vector_char_destroy, &t->types); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->children, 1); /* names */ VECTOR(t->names)[0] = (void*) name; /* types */ VECTOR(t->types)[0] = IGRAPH_I_GML_TREE_REAL; /* children */ p=igraph_Calloc(1, igraph_real_t); if (!p) { IGRAPH_ERROR("Cannot create real GML tree node", IGRAPH_ENOMEM); } *p=value; VECTOR(t->children)[0]=p; IGRAPH_FINALLY_CLEAN(3); return 0; } int igraph_gml_tree_init_string(igraph_gml_tree_t *t, const char *name, int namelen, const char *value, int valuelen) { IGRAPH_UNUSED(namelen); IGRAPH_UNUSED(valuelen); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->names, 1); IGRAPH_CHECK(igraph_vector_char_init(&t->types, 1)); IGRAPH_FINALLY(igraph_vector_char_destroy, &t->types); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->children, 1); /* names */ VECTOR(t->names)[0] = (void*) name; /* types */ VECTOR(t->types)[0] = IGRAPH_I_GML_TREE_STRING; /* children */ VECTOR(t->children)[0]=(void*)value; IGRAPH_FINALLY_CLEAN(3); return 0; } int igraph_gml_tree_init_tree(igraph_gml_tree_t *t, const char *name, int namelen, igraph_gml_tree_t *value) { IGRAPH_UNUSED(namelen); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->names, 1); IGRAPH_CHECK(igraph_vector_char_init(&t->types, 1)); IGRAPH_FINALLY(igraph_vector_char_destroy, &t->types); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->children, 1); /* names */ VECTOR(t->names)[0] = (void*)name; /* types */ VECTOR(t->types)[0] = IGRAPH_I_GML_TREE_TREE; /* children */ VECTOR(t->children)[0]=value; IGRAPH_FINALLY_CLEAN(3); return 0; } /* merge is destructive, the _second_ tree is destroyed */ int igraph_gml_tree_mergedest(igraph_gml_tree_t *t1, igraph_gml_tree_t *t2) { long int i, n=igraph_vector_ptr_size(&t2->children); for (i=0; inames, VECTOR(t2->names)[i])); IGRAPH_CHECK(igraph_vector_char_push_back(&t1->types, VECTOR(t2->types)[i])); IGRAPH_CHECK(igraph_vector_ptr_push_back(&t1->children, VECTOR(t2->children)[i])); } igraph_vector_ptr_destroy(&t2->names); igraph_vector_char_destroy(&t2->types); igraph_vector_ptr_destroy(&t2->children); return 0; } void igraph_gml_tree_destroy(igraph_gml_tree_t *t) { long int i, n=igraph_vector_ptr_size(&t->children); for (i=0; itypes)[i]; switch (type) { case IGRAPH_I_GML_TREE_TREE: igraph_gml_tree_destroy(VECTOR(t->children)[i]); igraph_Free(VECTOR(t->names)[i]); break; case IGRAPH_I_GML_TREE_INTEGER: igraph_Free(VECTOR(t->children)[i]); igraph_Free(VECTOR(t->names)[i]); break; case IGRAPH_I_GML_TREE_REAL: igraph_Free(VECTOR(t->children)[i]); igraph_Free(VECTOR(t->names)[i]); break; case IGRAPH_I_GML_TREE_STRING: igraph_Free(VECTOR(t->children)[i]); igraph_Free(VECTOR(t->names)[i]); break; case IGRAPH_I_GML_TREE_DELETED: break; } } igraph_vector_ptr_destroy(&t->names); igraph_vector_char_destroy(&t->types); igraph_vector_ptr_destroy(&t->children); igraph_Free(t); } long int igraph_gml_tree_length(const igraph_gml_tree_t *t) { return igraph_vector_ptr_size(&t->names); } long int igraph_gml_tree_find(const igraph_gml_tree_t *t, const char *name, long int from) { long int size=igraph_vector_ptr_size(&t->names); while ( from < size && (! VECTOR(t->names)[from] || strcmp(VECTOR(t->names)[from], name)) ) { from++; } if (from==size) { from=-1; } return from; } long int igraph_gml_tree_findback(const igraph_gml_tree_t *t, const char *name, long int from) { while ( from >= 0 && (! VECTOR(t->names)[from] || strcmp(VECTOR(t->names)[from], name)) ) { from--; } return from; } int igraph_gml_tree_type(const igraph_gml_tree_t *t, long int pos) { return VECTOR(t->types)[pos]; } const char *igraph_gml_tree_name(const igraph_gml_tree_t *t, long int pos) { return VECTOR(t->names)[pos]; } igraph_integer_t igraph_gml_tree_get_integer(const igraph_gml_tree_t *t, long int pos) { igraph_integer_t *i=VECTOR(t->children)[pos]; return *i; } igraph_real_t igraph_gml_tree_get_real(const igraph_gml_tree_t *t, long int pos) { igraph_real_t *d=VECTOR(t->children)[pos]; return *d; } const char *igraph_gml_tree_get_string(const igraph_gml_tree_t *t, long int pos) { const char *s=VECTOR(t->children)[pos]; return s; } igraph_gml_tree_t *igraph_gml_tree_get_tree(const igraph_gml_tree_t *t, long int pos) { igraph_gml_tree_t *tree=VECTOR(t->children)[pos]; return tree; } void igraph_gml_tree_delete(igraph_gml_tree_t *t, long int pos) { if (VECTOR(t->types)[pos] == IGRAPH_I_GML_TREE_TREE) { igraph_gml_tree_destroy(VECTOR(t->children)[pos]); } igraph_Free(VECTOR(t->names)[pos]); igraph_Free(VECTOR(t->children)[pos]); VECTOR(t->children)[pos]=0; VECTOR(t->names)[pos]=0; VECTOR(t->types)[pos]=IGRAPH_I_GML_TREE_DELETED; } igraph/src/fortran_intrinsics.c0000644000175100001440000000242713431000472016414 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-12 Gabor Csardi 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include double digitsdbl_(double x) { return (double) DBL_MANT_DIG; } double epsilondbl_(double x) { return DBL_EPSILON; } double hugedbl_(double x) { return DBL_MAX; } double tinydbl_(double x) { return DBL_MIN; } int maxexponentdbl_(double x) { return DBL_MAX_EXP; } int minexponentdbl_(double x) { return DBL_MIN_EXP; } double radixdbl_(double x) { return (double) FLT_RADIX; } igraph/src/clustertool.cpp0000644000175100001440000005636013431000472015420 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Joerg Reichardt The original copyright notice follows here */ /*************************************************************************** main.cpp - description ------------------- begin : Tue Jul 13 11:26:47 CEST 2004 copyright : (C) 2004 by email : ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include "NetDataTypes.h" #include "NetRoutines.h" #include "pottsmodel_2.h" #include "igraph_community.h" #include "igraph_error.h" #include "igraph_random.h" #include "igraph_math.h" #include "igraph_interface.h" #include "igraph_components.h" #include "igraph_interrupt_internal.h" int igraph_i_community_spinglass_orig(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma); int igraph_i_community_spinglass_negative(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma, /* igraph_matrix_t *adhesion, */ /* igraph_matrix_t *normalised_adhesion, */ /* igraph_real_t *polarization, */ igraph_real_t gamma_minus); /** * \function igraph_community_spinglass * \brief Community detection based on statistical mechanics * * This function implements the community structure detection * algorithm proposed by Joerg Reichardt and Stefan Bornholdt. * The algorithm is described in their paper: Statistical Mechanics of * Community Detection, http://arxiv.org/abs/cond-mat/0603718 . * * From version 0.6 igraph also supports an extension to * the algorithm that allows negative edge weights. This is described * in V.A. Traag and Jeroen Bruggeman: Community detection in networks * with positive and negative links, http://arxiv.org/abs/0811.2329 . * \param graph The input graph, it may be directed but the direction * of the edge is not used in the algorithm. * \param weights The vector giving the edge weights, it may be \c NULL, * in which case all edges are weighted equally. Edge weights * should be positive, altough this is not tested. * \param modularity Pointer to a real number, if not \c NULL then the * modularity score of the solution will be stored here. This is the * gereralized modularity that simplifies to the one defined in * M. E. J. Newman and M. Girvan, Phys. Rev. E 69, 026113 (2004), * if the gamma parameter is one. * \param temperature Pointer to a real number, if not \c NULL then * the temperature at the end of the algorithm will be stored * here. * \param membership Pointer to an initialized vector or \c NULL. If * not \c NULL then the result of the clustering will be stored * here, for each vertex the number of its cluster is given, the * first cluster is numbered zero. The vector will be resized as * needed. * \param csize Pointer to an initialized vector or \c NULL. If not \c * NULL then the sizes of the clusters will stored here in cluster * number order. The vector will be resized as needed. * \param spins Integer giving the number of spins, ie. the maximum * number of clusters. Usually it is not a program to give a high * number here, the default was 25 in the original code. Even if * the number of spins is high the number of clusters in the * result might small. * \param parupdate A logical constant, whether to update all spins in * parallel. The default for this argument was \c FALSE (ie. 0) in * the original code. It is not implemented in the \c * IGRAPH_SPINCOMM_INP_NEG implementation. * \param starttemp Real number, the temperature at the start. The * value of this argument was 1.0 in the original code. * \param stoptemp Real number, the algorithm stops at this * temperature. The default was 0.01 in the original code. * \param coolfact Real number, the coolinf factor for the simulated * annealing. The default was 0.99 in the original code. * \param update_rule The type of the update rule. Possible values: \c * IGRAPH_SPINCOMM_UPDATE_SIMPLE and \c * IGRAPH_SPINCOMM_UPDATE_CONFIG. Basically this parameter defined * the null model based on which the actual clustering is done. If * this is \c IGRAPH_SPINCOMM_UPDATE_SIMPLE then the random graph * (ie. G(n,p)), if it is \c IGRAPH_SPINCOMM_UPDATE then the * configuration model is used. The configuration means that the * baseline for the clustering is a random graph with the same * degree distribution as the input graph. * \param gamma Real number. The gamma parameter of the * algorithm. This defined the weight of the missing and existing * links in the quality function for the clustering. The default * value in the original code was 1.0, which is equal weight to * missing and existing edges. Smaller values make the existing * links contibute more to the energy function which is minimized * in the algorithm. Bigger values make the missing links more * important. (If my understanding is correct.) * \param implementation Constant, chooses between the two * implementations of the spin-glass algorithm that are included * in igraph. \c IGRAPH_SPINCOMM_IMP_ORIG selects the original * implementation, this is faster, \c IGRAPH_SPINCOMM_INP_NEG selects * a new implementation by Vincent Traag that allows negative edge * weights. * \param gamma_minus Real number. Parameter for the \c * IGRAPH_SPINCOMM_IMP_NEG implementation. This * specifies the balance between the importance of present and * non-present negative weighted edges in a community. Smaller values of * \p gamma_minus lead to communities with lesser * negative intra-connectivity. * If this argument is set to zero, the algorithm reduces to a graph * coloring algorithm, using the number of spins as the number of * colors. * \return Error code. * * \sa igraph_community_spinglass_single() for calculating the community * of a single vertex. * * Time complexity: TODO. * * \example examples/simple/spinglass.c */ int igraph_community_spinglass(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma, /* the rest is for the NegSpin implementation */ igraph_spinglass_implementation_t implementation, /* igraph_matrix_t *adhesion, */ /* igraph_matrix_t *normalised_adhesion, */ /* igraph_real_t *polarization, */ igraph_real_t gamma_minus) { switch (implementation) { case IGRAPH_SPINCOMM_IMP_ORIG: return igraph_i_community_spinglass_orig(graph, weights, modularity, temperature, membership, csize, spins, parupdate, starttemp, stoptemp, coolfact, update_rule, gamma); break; case IGRAPH_SPINCOMM_IMP_NEG: return igraph_i_community_spinglass_negative(graph, weights, modularity, temperature, membership, csize, spins, parupdate, starttemp, stoptemp, coolfact, update_rule, gamma, /* adhesion, normalised_adhesion, */ /* polarization, */ gamma_minus); break; default: IGRAPH_ERROR("Unknown `implementation' in spinglass community finding", IGRAPH_EINVAL); } return 0; } int igraph_i_community_spinglass_orig(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma) { unsigned long changes, runs; igraph_bool_t use_weights=0; bool zeroT; double kT, acc, prob; ClusterList *cl_cur; network *net; PottsModel *pm; /* Check arguments */ if (spins < 2 || spins > 500) { IGRAPH_ERROR("Invalid number of spins", IGRAPH_EINVAL); } if (update_rule != IGRAPH_SPINCOMM_UPDATE_SIMPLE && update_rule != IGRAPH_SPINCOMM_UPDATE_CONFIG) { IGRAPH_ERROR("Invalid update rule", IGRAPH_EINVAL); } if (weights) { if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } use_weights=1; } if (coolfact < 0 || coolfact>=1.0) { IGRAPH_ERROR("Invalid cooling factor", IGRAPH_EINVAL); } if (gamma < 0.0) { IGRAPH_ERROR("Invalid gamma value", IGRAPH_EINVAL); } if (starttemp/stoptemp<1.0) { IGRAPH_ERROR("starttemp should be larger in absolute value than stoptemp", IGRAPH_EINVAL); } /* Check whether we have a single component */ igraph_bool_t conn; IGRAPH_CHECK(igraph_is_connected(graph, &conn, IGRAPH_WEAK)); if (!conn) { IGRAPH_ERROR("Cannot work with unconnected graph", IGRAPH_EINVAL); } net = new network; net->node_list =new DL_Indexed_List(); net->link_list =new DL_Indexed_List(); net->cluster_list=new DL_Indexed_List*>(); /* Transform the igraph_t */ IGRAPH_CHECK(igraph_i_read_network(graph, weights, net, use_weights, 0)); prob=2.0*net->sum_weights/double(net->node_list->Size()) /double(net->node_list->Size()-1); pm=new PottsModel(net,(unsigned int)spins,update_rule); /* initialize the random number generator */ RNG_BEGIN(); if ((stoptemp==0.0) && (starttemp==0.0)) zeroT=true; else zeroT=false; if (!zeroT) kT=pm->FindStartTemp(gamma, prob, starttemp); else kT=stoptemp; /* assign random initial configuration */ pm->assign_initial_conf(-1); runs=0; changes=1; while (changes>0 && (kT/stoptemp>1.0 || (zeroT && runs<150))) { IGRAPH_ALLOW_INTERRUPTION(); /* This is not clean.... */ runs++; if (!zeroT) { kT*=coolfact; if (parupdate) { changes=pm->HeatBathParallelLookup(gamma, prob, kT, 50); } else { acc=pm->HeatBathLookup(gamma, prob, kT, 50); if (acc<(1.0-1.0/double(spins))*0.01) { changes=0; } else { changes=1; } } } else { if (parupdate) { changes=pm->HeatBathParallelLookupZeroTemp(gamma, prob, 50); } else { acc=pm->HeatBathLookupZeroTemp(gamma, prob, 50); /* less than 1 percent acceptance ratio */ if (acc<(1.0-1.0/double(spins))*0.01) { changes=0; } else { changes=1; } } } } /* while loop */ pm->WriteClusters(modularity, temperature, csize, membership, kT, gamma); while (net->link_list->Size()) delete net->link_list->Pop(); while (net->node_list->Size()) delete net->node_list->Pop(); while (net->cluster_list->Size()) { cl_cur=net->cluster_list->Pop(); while (cl_cur->Size()) cl_cur->Pop(); delete cl_cur; } delete net->link_list; delete net->node_list; delete net->cluster_list; RNG_END(); delete net; delete pm; return 0; } /** * \function igraph_community_spinglass_single * \brief Community of a single node based on statistical mechanics * * This function implements the community structure detection * algorithm proposed by Joerg Reichardt and Stefan Bornholdt. It is * described in their paper: Statistical Mechanics of * Community Detection, http://arxiv.org/abs/cond-mat/0603718 . * * * This function calculates the community of a single vertex without * calculating all the communities in the graph. * * \param graph The input graph, it may be directed but the direction * of the edges is not used in the algorithm. * \param weights Pointer to a vector with the weights of the edges. * Alternatively \c NULL can be supplied to have the same weight * for every edge. * \param vertex The vertex id of the vertex of which ths community is * calculated. * \param community Pointer to an initialized vector, the result, the * ids of the vertices in the community of the input vertex will be * stored here. The vector will be resized as needed. * \param cohesion Pointer to a real variable, if not \c NULL the * cohesion index of the community will be stored here. * \param adhesion Pointer to a real variable, if not \c NULL the * adhesion index of the community will be stored here. * \param inner_links Pointer to an integer, if not \c NULL the * number of edges within the community is stored here. * \param outer_links Pointer to an integer, if not \c NULL the * number of edges between the community and the rest of the graph * will be stored here. * \param spins The number of spins to use, this can be higher than * the actual number of clusters in the network, in which case some * clusters will contain zero vertices. * \param update_rule The type of the update rule. Possible values: \c * IGRAPH_SPINCOMM_UPDATE_SIMPLE and \c * IGRAPH_SPINCOMM_UPDATE_CONFIG. Basically this parameter defined * the null model based on which the actual clustering is done. If * this is \c IGRAPH_SPINCOMM_UPDATE_SIMPLE then the random graph * (ie. G(n,p)), if it is \c IGRAPH_SPINCOMM_UPDATE then the * configuration model is used. The configuration means that the * baseline for the clustering is a random graph with the same * degree distribution as the input graph. * \param gamma Real number. The gamma parameter of the * algorithm. This defined the weight of the missing and existing * links in the quality function for the clustering. The default * value in the original code was 1.0, which is equal weight to * missing and existing edges. Smaller values make the existing * links contibute more to the energy function which is minimized * in the algorithm. Bigger values make the missing links more * important. (If my understanding is correct.) * \return Error code. * * \sa igraph_community_spinglass() for the traditional version of the * algorithm. * * Time complexity: TODO. */ int igraph_community_spinglass_single(const igraph_t *graph, const igraph_vector_t *weights, igraph_integer_t vertex, igraph_vector_t *community, igraph_real_t *cohesion, igraph_real_t *adhesion, igraph_integer_t *inner_links, igraph_integer_t *outer_links, igraph_integer_t spins, igraph_spincomm_update_t update_rule, igraph_real_t gamma) { igraph_bool_t use_weights=0; double prob; ClusterList *cl_cur; network *net; PottsModel *pm; char startnode[255]; /* Check arguments */ if (spins < 2 || spins > 500) { IGRAPH_ERROR("Invalid number of spins", IGRAPH_EINVAL); } if (update_rule != IGRAPH_SPINCOMM_UPDATE_SIMPLE && update_rule != IGRAPH_SPINCOMM_UPDATE_CONFIG) { IGRAPH_ERROR("Invalid update rule", IGRAPH_EINVAL); } if (weights) { if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } use_weights=1; } if (gamma < 0.0) { IGRAPH_ERROR("Invalid gamme value", IGRAPH_EINVAL); } if (vertex < 0 || vertex > igraph_vcount(graph)) { IGRAPH_ERROR("Invalid vertex id", IGRAPH_EINVAL); } /* Check whether we have a single component */ igraph_bool_t conn; IGRAPH_CHECK(igraph_is_connected(graph, &conn, IGRAPH_WEAK)); if (!conn) { IGRAPH_ERROR("Cannot work with unconnected graph", IGRAPH_EINVAL); } net = new network; net->node_list =new DL_Indexed_List(); net->link_list =new DL_Indexed_List(); net->cluster_list=new DL_Indexed_List*>(); /* Transform the igraph_t */ IGRAPH_CHECK(igraph_i_read_network(graph, weights, net, use_weights, 0)); prob=2.0*net->sum_weights/double(net->node_list->Size()) /double(net->node_list->Size()-1); pm=new PottsModel(net,(unsigned int)spins,update_rule); /* initialize the random number generator */ RNG_BEGIN(); /* to be exected, if we want to find the community around a particular node*/ /* the initial conf is needed, because otherwise, the degree of the nodes is not in the weight property, stupid!!! */ pm->assign_initial_conf(-1); snprintf(startnode, 255, "%li", (long int)vertex+1); pm->FindCommunityFromStart(gamma, prob, startnode, community, cohesion, adhesion, inner_links, outer_links); while (net->link_list->Size()) delete net->link_list->Pop(); while (net->node_list->Size()) delete net->node_list->Pop(); while (net->cluster_list->Size()) { cl_cur=net->cluster_list->Pop(); while (cl_cur->Size()) cl_cur->Pop(); delete cl_cur; } delete net->link_list; delete net->node_list; delete net->cluster_list; RNG_END(); delete net; delete pm; return 0; } int igraph_i_community_spinglass_negative(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma, /* igraph_matrix_t *adhesion, */ /* igraph_matrix_t *normalised_adhesion, */ /* igraph_real_t *polarization, */ igraph_real_t gamma_minus) { unsigned long changes, runs; igraph_bool_t use_weights=0; bool zeroT; double kT, acc; ClusterList *cl_cur; network *net; PottsModelN *pm; igraph_real_t d_n; igraph_real_t d_p; /* Check arguments */ if (parupdate) { IGRAPH_ERROR("Parallel spin update not implemented with " "negative gamma", IGRAPH_UNIMPLEMENTED); } if (spins < 2 || spins > 500) { IGRAPH_ERROR("Invalid number of spins", IGRAPH_EINVAL); } if (update_rule != IGRAPH_SPINCOMM_UPDATE_SIMPLE && update_rule != IGRAPH_SPINCOMM_UPDATE_CONFIG) { IGRAPH_ERROR("Invalid update rule", IGRAPH_EINVAL); } if (weights) { if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } use_weights=1; } if (coolfact < 0 || coolfact>=1.0) { IGRAPH_ERROR("Invalid cooling factor", IGRAPH_EINVAL); } if (gamma < 0.0) { IGRAPH_ERROR("Invalid gamma value", IGRAPH_EINVAL); } if (starttemp/stoptemp<1.0) { IGRAPH_ERROR("starttemp should be larger in absolute value than stoptemp", IGRAPH_EINVAL); } /* Check whether we have a single component */ igraph_bool_t conn; IGRAPH_CHECK(igraph_is_connected(graph, &conn, IGRAPH_WEAK)); if (!conn) { IGRAPH_ERROR("Cannot work with unconnected graph", IGRAPH_EINVAL); } if (weights) { igraph_vector_minmax(weights, &d_n, &d_p); } else { d_n = d_p = 1; } if (d_n > 0) { d_n=0; } if (d_p < 0) { d_p=0; } d_n = -d_n; net = new network; net->node_list =new DL_Indexed_List(); net->link_list =new DL_Indexed_List(); net->cluster_list=new DL_Indexed_List*>(); /* Transform the igraph_t */ IGRAPH_CHECK(igraph_i_read_network(graph, weights, net, use_weights, 0)); bool directed = igraph_is_directed(graph); pm=new PottsModelN(net,(unsigned int)spins, directed); /* initialize the random number generator */ RNG_BEGIN(); if ((stoptemp==0.0) && (starttemp==0.0)) zeroT=true; else zeroT=false; //Begin at a high enough temperature kT=pm->FindStartTemp(gamma, gamma_minus, starttemp); /* assign random initial configuration */ pm->assign_initial_conf(true); runs=0; changes=1; acc = 0; while (changes>0 && (kT/stoptemp>1.0 || (zeroT && runs<150))) { IGRAPH_ALLOW_INTERRUPTION(); /* This is not clean.... */ runs++; kT = kT*coolfact; acc=pm->HeatBathLookup(gamma, gamma_minus, kT, 50); if (acc<(1.0-1.0/double(spins))*0.001) changes=0; else changes=1; } /* while loop */ /* These are needed, otherwise 'modularity' is not calculated */ igraph_matrix_t adhesion, normalized_adhesion; igraph_real_t polarization; IGRAPH_MATRIX_INIT_FINALLY(&adhesion, 0, 0); IGRAPH_MATRIX_INIT_FINALLY(&normalized_adhesion, 0, 0); pm->WriteClusters(modularity, temperature, csize, membership, &adhesion, &normalized_adhesion, &polarization, kT, d_p, d_n, gamma, gamma_minus); igraph_matrix_destroy(&normalized_adhesion); igraph_matrix_destroy(&adhesion); IGRAPH_FINALLY_CLEAN(2); while (net->link_list->Size()) delete net->link_list->Pop(); while (net->node_list->Size()) delete net->node_list->Pop(); while (net->cluster_list->Size()) { cl_cur=net->cluster_list->Pop(); while (cl_cur->Size()) cl_cur->Pop(); delete cl_cur; } RNG_END(); return 0; } igraph/src/dmout.f0000644000175100001440000001357513431000472013635 0ustar hornikusers*----------------------------------------------------------------------- * Routine: DMOUT * * Purpose: Real matrix output routine. * * Usage: CALL DMOUT (LOUT, M, N, A, LDA, IDIGIT, IFMT) * * Arguments * M - Number of rows of A. (Input) * N - Number of columns of A. (Input) * A - Real M by N matrix to be printed. (Input) * LDA - Leading dimension of A exactly as specified in the * dimension statement of the calling program. (Input) * IFMT - Format to be used in printing matrix A. (Input) * IDIGIT - Print up to IABS(IDIGIT) decimal digits per number. (In) * If IDIGIT .LT. 0, printing is done with 72 columns. * If IDIGIT .GT. 0, printing is done with 132 columns. * *----------------------------------------------------------------------- * SUBROUTINE IGRAPHDMOUT( LOUT, M, N, A, LDA, IDIGIT, IFMT ) * ... * ... SPECIFICATIONS FOR ARGUMENTS * ... * ... SPECIFICATIONS FOR LOCAL VARIABLES * .. Scalar Arguments .. CHARACTER*( * ) IFMT INTEGER IDIGIT, LDA, LOUT, M, N * .. * .. Array Arguments .. DOUBLE PRECISION A( LDA, * ) * .. * .. Local Scalars .. CHARACTER*80 LINE INTEGER I, J, K1, K2, LLL, NDIGIT * .. * .. Local Arrays .. CHARACTER ICOL( 3 ) * .. * .. Intrinsic Functions .. INTRINSIC LEN, MIN, MIN0 * .. * .. Data statements .. DATA ICOL( 1 ), ICOL( 2 ), ICOL( 3 ) / 'C', 'o', $ 'l' / * .. * .. Executable Statements .. * ... * ... FIRST EXECUTABLE STATEMENT * c$$$ LLL = MIN( LEN( IFMT ), 80 ) c$$$ DO 10 I = 1, LLL c$$$ LINE( I: I ) = '-' c$$$ 10 CONTINUE c$$$* c$$$ DO 20 I = LLL + 1, 80 c$$$ LINE( I: I ) = ' ' c$$$ 20 CONTINUE c$$$* c$$$ WRITE( LOUT, FMT = 9999 )IFMT, LINE( 1: LLL ) c$$$ 9999 FORMAT( / 1X, A, / 1X, A ) c$$$* c$$$ IF( M.LE.0 .OR. N.LE.0 .OR. LDA.LE.0 ) c$$$ $ RETURN c$$$ NDIGIT = IDIGIT c$$$ IF( IDIGIT.EQ.0 ) c$$$ $ NDIGIT = 4 c$$$* c$$$*======================================================================= c$$$* CODE FOR OUTPUT USING 72 COLUMNS FORMAT c$$$*======================================================================= c$$$* c$$$ IF( IDIGIT.LT.0 ) THEN c$$$ NDIGIT = -IDIGIT c$$$ IF( NDIGIT.LE.4 ) THEN c$$$ DO 40 K1 = 1, N, 5 c$$$ K2 = MIN0( N, K1+4 ) c$$$ WRITE( LOUT, FMT = 9998 )( ICOL, I, I = K1, K2 ) c$$$ DO 30 I = 1, M c$$$ WRITE( LOUT, FMT = 9994 )I, ( A( I, J ), J = K1, K2 ) c$$$ 30 CONTINUE c$$$ 40 CONTINUE c$$$* c$$$ ELSE IF( NDIGIT.LE.6 ) THEN c$$$ DO 60 K1 = 1, N, 4 c$$$ K2 = MIN0( N, K1+3 ) c$$$ WRITE( LOUT, FMT = 9997 )( ICOL, I, I = K1, K2 ) c$$$ DO 50 I = 1, M c$$$ WRITE( LOUT, FMT = 9993 )I, ( A( I, J ), J = K1, K2 ) c$$$ 50 CONTINUE c$$$ 60 CONTINUE c$$$* c$$$ ELSE IF( NDIGIT.LE.10 ) THEN c$$$ DO 80 K1 = 1, N, 3 c$$$ K2 = MIN0( N, K1+2 ) c$$$ WRITE( LOUT, FMT = 9996 )( ICOL, I, I = K1, K2 ) c$$$ DO 70 I = 1, M c$$$ WRITE( LOUT, FMT = 9992 )I, ( A( I, J ), J = K1, K2 ) c$$$ 70 CONTINUE c$$$ 80 CONTINUE c$$$* c$$$ ELSE c$$$ DO 100 K1 = 1, N, 2 c$$$ K2 = MIN0( N, K1+1 ) c$$$ WRITE( LOUT, FMT = 9995 )( ICOL, I, I = K1, K2 ) c$$$ DO 90 I = 1, M c$$$ WRITE( LOUT, FMT = 9991 )I, ( A( I, J ), J = K1, K2 ) c$$$ 90 CONTINUE c$$$ 100 CONTINUE c$$$ END IF c$$$* c$$$*======================================================================= c$$$* CODE FOR OUTPUT USING 132 COLUMNS FORMAT c$$$*======================================================================= c$$$* c$$$ ELSE c$$$ IF( NDIGIT.LE.4 ) THEN c$$$ DO 120 K1 = 1, N, 10 c$$$ K2 = MIN0( N, K1+9 ) c$$$ WRITE( LOUT, FMT = 9998 )( ICOL, I, I = K1, K2 ) c$$$ DO 110 I = 1, M c$$$ WRITE( LOUT, FMT = 9994 )I, ( A( I, J ), J = K1, K2 ) c$$$ 110 CONTINUE c$$$ 120 CONTINUE c$$$* c$$$ ELSE IF( NDIGIT.LE.6 ) THEN c$$$ DO 140 K1 = 1, N, 8 c$$$ K2 = MIN0( N, K1+7 ) c$$$ WRITE( LOUT, FMT = 9997 )( ICOL, I, I = K1, K2 ) c$$$ DO 130 I = 1, M c$$$ WRITE( LOUT, FMT = 9993 )I, ( A( I, J ), J = K1, K2 ) c$$$ 130 CONTINUE c$$$ 140 CONTINUE c$$$* c$$$ ELSE IF( NDIGIT.LE.10 ) THEN c$$$ DO 160 K1 = 1, N, 6 c$$$ K2 = MIN0( N, K1+5 ) c$$$ WRITE( LOUT, FMT = 9996 )( ICOL, I, I = K1, K2 ) c$$$ DO 150 I = 1, M c$$$ WRITE( LOUT, FMT = 9992 )I, ( A( I, J ), J = K1, K2 ) c$$$ 150 CONTINUE c$$$ 160 CONTINUE c$$$* c$$$ ELSE c$$$ DO 180 K1 = 1, N, 5 c$$$ K2 = MIN0( N, K1+4 ) c$$$ WRITE( LOUT, FMT = 9995 )( ICOL, I, I = K1, K2 ) c$$$ DO 170 I = 1, M c$$$ WRITE( LOUT, FMT = 9991 )I, ( A( I, J ), J = K1, K2 ) c$$$ 170 CONTINUE c$$$ 180 CONTINUE c$$$ END IF c$$$ END IF c$$$ WRITE( LOUT, FMT = 9990 ) c$$$* c$$$ 9998 FORMAT( 10X, 10( 4X, 3A1, I4, 1X ) ) c$$$ 9997 FORMAT( 10X, 8( 5X, 3A1, I4, 2X ) ) c$$$ 9996 FORMAT( 10X, 6( 7X, 3A1, I4, 4X ) ) c$$$ 9995 FORMAT( 10X, 5( 9X, 3A1, I4, 6X ) ) c$$$ 9994 FORMAT( 1X, ' Row', I4, ':', 1X, 1P, 10D12.3 ) c$$$ 9993 FORMAT( 1X, ' Row', I4, ':', 1X, 1P, 8D14.5 ) c$$$ 9992 FORMAT( 1X, ' Row', I4, ':', 1X, 1P, 6D18.9 ) c$$$ 9991 FORMAT( 1X, ' Row', I4, ':', 1X, 1P, 5D22.13 ) c$$$ 9990 FORMAT( 1X, ' ' ) * RETURN END igraph/src/types.c0000644000175100001440000000764513431000472013647 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include #ifdef _MSC_VER # define snprintf _snprintf #endif #ifdef DBL_DIG /* Use DBL_DIG to determine the maximum precision used for %g */ # define STRINGIFY_HELPER(x) #x # define STRINGIFY(x) STRINGIFY_HELPER(x) # define IGRAPH_REAL_PRINTF_PRECISE_FORMAT "%." STRINGIFY(DBL_DIG) "g" #else /* Assume a precision of 10 digits for %g */ # define IGRAPH_REAL_PRINTF_PRECISE_FORMAT "%.10g" #endif #ifndef USING_R int igraph_real_printf(igraph_real_t val) { if (igraph_finite(val)) { return printf("%g", val); } else if (igraph_is_nan(val)) { return printf("NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return printf("-Inf"); } else { return printf("Inf"); } } else { /* fallback */ return printf("%g", val); } } #endif int igraph_real_fprintf(FILE *file, igraph_real_t val) { if (igraph_finite(val)) { return fprintf(file, "%g", val); } else if (igraph_is_nan(val)) { return fprintf(file, "NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return fprintf(file, "-Inf"); } else { return fprintf(file, "Inf"); } } else { /* fallback */ return fprintf(file, "%g", val); } } int igraph_real_snprintf(char* str, size_t size, igraph_real_t val) { if (igraph_finite(val)) { return snprintf(str, size, "%g", val); } else if (igraph_is_nan(val)) { return snprintf(str, size, "NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return snprintf(str, size, "-Inf"); } else { return snprintf(str, size, "Inf"); } } else { /* fallback */ return snprintf(str, size, "%g", val); } } #ifndef USING_R int igraph_real_printf_precise(igraph_real_t val) { if (igraph_finite(val)) { return printf(IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } else if (igraph_is_nan(val)) { return printf("NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return printf("-Inf"); } else { return printf("Inf"); } } else { /* fallback */ return printf(IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } } #endif int igraph_real_fprintf_precise(FILE *file, igraph_real_t val) { if (igraph_finite(val)) { return fprintf(file, IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } else if (igraph_is_nan(val)) { return fprintf(file, "NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return fprintf(file, "-Inf"); } else { return fprintf(file, "Inf"); } } else { /* fallback */ return fprintf(file, IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } } int igraph_real_snprintf_precise(char* str, size_t size, igraph_real_t val) { if (igraph_finite(val)) { return snprintf(str, size, IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } else if (igraph_is_nan(val)) { return snprintf(str, size, "NaN"); } else if (igraph_is_inf(val)) { if (val < 0) { return snprintf(str, size, "-Inf"); } else { return snprintf(str, size, "Inf"); } } else { /* fallback */ return snprintf(str, size, IGRAPH_REAL_PRINTF_PRECISE_FORMAT, val); } } igraph/src/foreign-dl-lexer.l0000644000175100001440000001066613430770201015657 0ustar hornikusers/* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include #include "foreign-dl-header.h" #include "foreign-dl-parser.h" #define YY_EXTRA_TYPE igraph_i_dl_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); %} %option noyywrap %option prefix="igraph_dl_yy" %option outfile="lex.yy.c" %option nounput %option noinput %option nodefault %option reentrant %option bison-bridge %option bison-locations digit [0-9] whitespace [ \t\v\f] %x LABELM FULLMATRIX EDGELIST NODELIST %% <*>\n\r|\r\n|\r|\n { return NEWLINE; } [dD][lL]{whitespace}+ { return DL; } [nN]{whitespace}*[=]{whitespace}* { return NEQ; } {digit}+ { return NUM; } [dD][aA][tT][aA][:] { switch (yyextra->mode) { case 0: BEGIN(FULLMATRIX); break; case 1: BEGIN(EDGELIST); break; case 2: BEGIN(NODELIST); break; } return DATA; } [lL][aA][bB][eE][lL][sS]: { BEGIN(LABELM); return LABELS; } [lL][aA][bB][eE][lL][sS]{whitespace}+[eE][mM][bB][eE][dD][dD][eE][dD]:?{whitespace}* { return LABELSEMBEDDED; } [fF][oO][rR][mM][aA][tT]{whitespace}*[=]{whitespace}*[fF][uU][lL][lL][mM][aA][tT][rR][iI][xX]{whitespace}* { yyextra->mode=0; return FORMATFULLMATRIX; } [fF][oO][rR][mM][aA][tT]{whitespace}*[=]{whitespace}*[eE][dD][gG][eE][lL][iI][sS][tT][1]{whitespace}* { yyextra->mode=1; return FORMATEDGELIST1; } [fF][oO][rR][mM][aA][tT]{whitespace}*[=]{whitespace}*[nN][oO][dD][eE][lL][iI][sS][tT][1]{whitespace}* { yyextra->mode=2; return FORMATNODELIST1; } [, ] { /* eaten up */ } [^, \t\n\r\f\v]+{whitespace}* { return LABEL; } {digit}{whitespace}* { return DIGIT; } [^ \t\n\r\v\f,]+ { return LABEL; } {whitespace} { } \-?{digit}+(\.{digit}+)?([eE](\+|\-)?{digit}+)? { return NUM; } [^ \t\n\r\v\f,]+ { return LABEL; } {whitespace}* { } {digit}+ { return NUM; } [^ \t\r\n\v\f,]+ { return LABEL; } {whitespace}* { } {whitespace}+ { /* eaten up */ } <> { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; BEGIN(INITIAL); return EOFF; } } <*>. { return 0; } . { return ERROR; } igraph/src/foreign-dl-parser.h0000644000175100001440000000574713431000472016031 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { NUM = 258, NEWLINE = 259, DL = 260, NEQ = 261, DATA = 262, LABELS = 263, LABELSEMBEDDED = 264, FORMATFULLMATRIX = 265, FORMATEDGELIST1 = 266, FORMATNODELIST1 = 267, DIGIT = 268, LABEL = 269, EOFF = 270, ERROR = 271 }; #endif /* Tokens. */ #define NUM 258 #define NEWLINE 259 #define DL 260 #define NEQ 261 #define DATA 262 #define LABELS 263 #define LABELSEMBEDDED 264 #define FORMATFULLMATRIX 265 #define FORMATEDGELIST1 266 #define FORMATNODELIST1 267 #define DIGIT 268 #define LABEL 269 #define EOFF 270 #define ERROR 271 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 86 "src/foreign-dl-parser.y" { long int integer; igraph_real_t real; } /* Line 1529 of yacc.c. */ #line 86 "y.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif igraph/src/walktrap_communities.h0000644000175100001440000001507713431000472016747 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: communities.h //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #ifndef COMMUNITIES_H #define COMMUNITIES_H #include "walktrap_graph.h" #include "walktrap_heap.h" #include "igraph_community.h" #include "config.h" namespace igraph { namespace walktrap { class Communities; class Probabilities { public: static IGRAPH_THREAD_LOCAL float* tmp_vector1; // static IGRAPH_THREAD_LOCAL float* tmp_vector2; // static IGRAPH_THREAD_LOCAL int* id; // static IGRAPH_THREAD_LOCAL int* vertices1; // static IGRAPH_THREAD_LOCAL int* vertices2; // static IGRAPH_THREAD_LOCAL int current_id; // static IGRAPH_THREAD_LOCAL Communities* C; // pointer to all the communities static IGRAPH_THREAD_LOCAL int length; // length of the random walks int size; // number of probabilities stored int* vertices; // the vertices corresponding to the stored probabilities, 0 if all the probabilities are stored float* P; // the probabilities long memory(); // the memory (in Bytes) used by the object double compute_distance(const Probabilities* P2) const; // compute the squared distance r^2 between this probability vector and P2 Probabilities(int community); // compute the probability vector of a community Probabilities(int community1, int community2); // merge the probability vectors of two communities in a new one // the two communities must have their probability vectors stored ~Probabilities(); // destructor }; class Community { public: Neighbor* first_neighbor; // first item of the list of adjacent communities Neighbor* last_neighbor; // last item of the list of adjacent communities int this_community; // number of this community int first_member; // number of the first vertex of the community int last_member; // number of the last vertex of the community int size; // number of members of the community Probabilities* P; // the probability vector, 0 if not stored. float sigma; // sigma(C) of the community float internal_weight; // sum of the weight of the internal edges float total_weight; // sum of the weight of all the edges of the community (an edge between two communities is a half-edge for each community) int sub_communities[2]; // the two sub sommunities, -1 if no sub communities; int sub_community_of; // number of the community in which this community has been merged // 0 if the community is active // -1 if the community is not used void merge(Community &C1, Community &C2); // create a new community by merging C1 an C2 void add_neighbor(Neighbor* N); void remove_neighbor(Neighbor* N); float min_delta_sigma(); // compute the minimal delta sigma among all the neighbors of this community Community(); // create an empty community ~Community(); // destructor }; class Communities { private: long max_memory; // size in Byte of maximal memory usage, -1 for no limit igraph_matrix_t *merges; long int mergeidx; igraph_vector_t *modularity; public: long memory_used; // in bytes Min_delta_sigma_heap* min_delta_sigma; // the min delta_sigma of the community with a saved probability vector (for memory management) Graph* G; // the graph int* members; // the members of each community represented as a chained list. // a community points to the first_member the array which contains // the next member (-1 = end of the community) Neighbor_heap* H; // the distances between adjacent communities. Community* communities; // array of the communities int nb_communities; // number of valid communities int nb_active_communities; // number of active communities Communities(Graph* G, int random_walks_length = 3, long max_memory = -1, igraph_matrix_t *merges=0, igraph_vector_t *modularity=0); // Constructor ~Communities(); // Destructor void merge_communities(Neighbor* N); // create a community by merging two existing communities double merge_nearest_communities(); double compute_delta_sigma(int c1, int c2); // compute delta_sigma(c1,c2) void remove_neighbor(Neighbor* N); void add_neighbor(Neighbor* N); void update_neighbor(Neighbor* N, float new_delta_sigma); void manage_memory(); }; } } /* end of namespaces */ #endif igraph/src/second.f0000644000175100001440000000142013431000472013742 0ustar hornikusers SUBROUTINE IGRAPHSECOND( T ) * REAL T * * -- LAPACK auxiliary routine (preliminary version) -- * Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., * Courant Institute, Argonne National Lab, and Rice University * July 26, 1991 * * Purpose * ======= * * SECOND returns the user time for a process in igraphseconds. * This version gets the time from the system function ETIME. * * .. Local Scalars .. REAL T1 * .. * .. Local Arrays .. REAL TARRAY( 2 ) * .. * .. External Functions .. REAL ETIME * .. * .. Executable Statements .. * TARRAY( 1 ) = 0.0 T1 = ETIME( TARRAY ) T = TARRAY( 1 ) RETURN * * End of SECOND * END igraph/src/foreign-gml-lexer.l0000644000175100001440000000601413430770201016027 0ustar hornikusers/* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-gml-header.h" #include "foreign-gml-parser.h" #define YY_EXTRA_TYPE igraph_i_gml_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); %} %option noyywrap %option prefix="igraph_gml_yy" %option outfile="lex.yy.c" %option nounput %option noinput %option nodefault %option reentrant %option bison-bridge %option bison-locations digit [0-9] whitespace [ \r\n\t] %% ^#[^\n\r]*[\n]|[\r] { /* comments ignored */ } \"[^\"]*\" { return STRING; } \-?{digit}+(\.{digit}+)?([eE](\+|\-)?{digit}+)? { return NUM; } [a-zA-Z_][a-zA-Z_0-9]* { return KEYWORD; } \[ { return LISTOPEN; } \] { return LISTCLOSE; } \n\r|\r\n|\r|\n { } {whitespace} { /* other whitespace ignored */ } <> { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return EOFF; } } . { return ERROR; } %% igraph/src/walktrap_graph.cpp0000644000175100001440000001423613431000472016043 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: graph.cpp //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #include #include #include #include #include // strlen #include "walktrap_graph.h" #include "igraph_interface.h" using namespace std; namespace igraph { namespace walktrap { bool operator<(const Edge& E1, const Edge& E2) { return(E1.neighbor < E2.neighbor); } Vertex::Vertex() { degree = 0; edges = 0; total_weight = 0.; } Vertex::~Vertex() { if(edges) delete[] edges; } Graph::Graph() { nb_vertices = 0; nb_edges = 0; vertices = 0; index = 0; total_weight = 0.; } Graph::~Graph () { if (vertices) delete[] vertices; } class Edge_list { public: int* V1; int* V2; float* W; int size; int size_max; void add(int v1, int v2, float w); Edge_list() { size = 0; size_max = 1024; V1 = new int[1024]; V2 = new int[1024]; W = new float[1024]; } ~Edge_list() { if(V1) delete[] V1; if(V2) delete[] V2; if(W) delete[] W; } }; void Edge_list::add(int v1, int v2, float w) { if(size == size_max) { int* tmp1 = new int[2*size_max]; int* tmp2 = new int[2*size_max]; float* tmp3 = new float[2*size_max]; for(int i = 0; i < size_max; i++) { tmp1[i] = V1[i]; tmp2[i] = V2[i]; tmp3[i] = W[i]; } delete[] V1; delete[] V2; delete[] W; V1 = tmp1; V2 = tmp2; W = tmp3; size_max *= 2; } V1[size] = v1; V2[size] = v2; W[size] = w; size++; } int Graph::convert_from_igraph(const igraph_t *graph, const igraph_vector_t *weights) { Graph &G=*this; int max_vertex=(int)igraph_vcount(graph)-1; long int no_of_edges=(long int)igraph_ecount(graph); long int i; long int deg; double w; Edge_list EL; for (i=0; i= lbfgs_parameter_t::wolfe * g(x)^T d, * * where x is the current point, d is the current search direction, and * a is the step length. */ LBFGS_LINESEARCH_BACKTRACKING_WOLFE = 2, /** * Backtracking method with strong Wolfe condition. * The backtracking method finds the step length such that it satisfies * both the Armijo condition (LBFGS_LINESEARCH_BACKTRACKING_ARMIJO) * and the following condition, * - |g(x + a * d)^T d| <= lbfgs_parameter_t::wolfe * |g(x)^T d|, * * where x is the current point, d is the current search direction, and * a is the step length. */ LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE = 3, }; /** * L-BFGS optimization parameters. * Call lbfgs_parameter_init() function to initialize parameters to the * default values. */ typedef struct { /** * The number of corrections to approximate the inverse hessian matrix. * The L-BFGS routine stores the computation results of previous \ref m * iterations to approximate the inverse hessian matrix of the current * iteration. This parameter controls the size of the limited memories * (corrections). The default value is \c 6. Values less than \c 3 are * not recommended. Large values will result in excessive computing time. */ int m; /** * Epsilon for convergence test. * This parameter determines the accuracy with which the solution is to * be found. A minimization terminates when * ||g|| < \ref epsilon * max(1, ||x||), * where ||.|| denotes the Euclidean (L2) norm. The default value is * \c 1e-5. */ lbfgsfloatval_t epsilon; /** * Distance for delta-based convergence test. * This parameter determines the distance, in iterations, to compute * the rate of decrease of the objective function. If the value of this * parameter is zero, the library does not perform the delta-based * convergence test. The default value is \c 0. */ int past; /** * Delta for convergence test. * This parameter determines the minimum rate of decrease of the * objective function. The library stops iterations when the * following condition is met: * (f' - f) / f < \ref delta, * where f' is the objective value of \ref past iterations ago, and f is * the objective value of the current iteration. * The default value is \c 0. */ lbfgsfloatval_t delta; /** * The maximum number of iterations. * The lbfgs() function terminates an optimization process with * ::LBFGSERR_MAXIMUMITERATION status code when the iteration count * exceedes this parameter. Setting this parameter to zero continues an * optimization process until a convergence or error. The default value * is \c 0. */ int max_iterations; /** * The line search algorithm. * This parameter specifies a line search algorithm to be used by the * L-BFGS routine. */ int linesearch; /** * The maximum number of trials for the line search. * This parameter controls the number of function and gradients evaluations * per iteration for the line search routine. The default value is \c 20. */ int max_linesearch; /** * The minimum step of the line search routine. * The default value is \c 1e-20. This value need not be modified unless * the exponents are too large for the machine being used, or unless the * problem is extremely badly scaled (in which case the exponents should * be increased). */ lbfgsfloatval_t min_step; /** * The maximum step of the line search. * The default value is \c 1e+20. This value need not be modified unless * the exponents are too large for the machine being used, or unless the * problem is extremely badly scaled (in which case the exponents should * be increased). */ lbfgsfloatval_t max_step; /** * A parameter to control the accuracy of the line search routine. * The default value is \c 1e-4. This parameter should be greater * than zero and smaller than \c 0.5. */ lbfgsfloatval_t ftol; /** * A coefficient for the Wolfe condition. * This parameter is valid only when the backtracking line-search * algorithm is used with the Wolfe condition, * ::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE or * ::LBFGS_LINESEARCH_BACKTRACKING_WOLFE . * The default value is \c 0.9. This parameter should be greater * the \ref ftol parameter and smaller than \c 1.0. */ lbfgsfloatval_t wolfe; /** * A parameter to control the accuracy of the line search routine. * The default value is \c 0.9. If the function and gradient * evaluations are inexpensive with respect to the cost of the * iteration (which is sometimes the case when solving very large * problems) it may be advantageous to set this parameter to a small * value. A typical small value is \c 0.1. This parameter shuold be * greater than the \ref ftol parameter (\c 1e-4) and smaller than * \c 1.0. */ lbfgsfloatval_t gtol; /** * The machine precision for floating-point values. * This parameter must be a positive value set by a client program to * estimate the machine precision. The line search routine will terminate * with the status code (::LBFGSERR_ROUNDING_ERROR) if the relative width * of the interval of uncertainty is less than this parameter. */ lbfgsfloatval_t xtol; /** * Coeefficient for the L1 norm of variables. * This parameter should be set to zero for standard minimization * problems. Setting this parameter to a positive value activates * Orthant-Wise Limited-memory Quasi-Newton (OWL-QN) method, which * minimizes the objective function F(x) combined with the L1 norm |x| * of the variables, {F(x) + C |x|}. This parameter is the coeefficient * for the |x|, i.e., C. As the L1 norm |x| is not differentiable at * zero, the library modifies function and gradient evaluations from * a client program suitably; a client program thus have only to return * the function value F(x) and gradients G(x) as usual. The default value * is zero. */ lbfgsfloatval_t orthantwise_c; /** * Start index for computing L1 norm of the variables. * This parameter is valid only for OWL-QN method * (i.e., \ref orthantwise_c != 0). This parameter b (0 <= b < N) * specifies the index number from which the library computes the * L1 norm of the variables x, * |x| := |x_{b}| + |x_{b+1}| + ... + |x_{N}| . * In other words, variables x_1, ..., x_{b-1} are not used for * computing the L1 norm. Setting b (0 < b < N), one can protect * variables, x_1, ..., x_{b-1} (e.g., a bias term of logistic * regression) from being regularized. The default value is zero. */ int orthantwise_start; /** * End index for computing L1 norm of the variables. * This parameter is valid only for OWL-QN method * (i.e., \ref orthantwise_c != 0). This parameter e (0 < e <= N) * specifies the index number at which the library stops computing the * L1 norm of the variables x, */ int orthantwise_end; } lbfgs_parameter_t; /** * Callback interface to provide objective function and gradient evaluations. * * The lbfgs() function call this function to obtain the values of objective * function and its gradients when needed. A client program must implement * this function to evaluate the values of the objective function and its * gradients, given current values of variables. * * @param instance The user data sent for lbfgs() function by the client. * @param x The current values of variables. * @param g The gradient vector. The callback function must compute * the gradient values for the current variables. * @param n The number of variables. * @param step The current step of the line search routine. * @retval lbfgsfloatval_t The value of the objective function for the current * variables. */ typedef lbfgsfloatval_t (*lbfgs_evaluate_t)( void *instance, const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n, const lbfgsfloatval_t step ); /** * Callback interface to receive the progress of the optimization process. * * The lbfgs() function call this function for each iteration. Implementing * this function, a client program can store or display the current progress * of the optimization process. * * @param instance The user data sent for lbfgs() function by the client. * @param x The current values of variables. * @param g The current gradient values of variables. * @param fx The current value of the objective function. * @param xnorm The Euclidean norm of the variables. * @param gnorm The Euclidean norm of the gradients. * @param step The line-search step used for this iteration. * @param n The number of variables. * @param k The iteration count. * @param ls The number of evaluations called for this iteration. * @retval int Zero to continue the optimization process. Returning a * non-zero value will cancel the optimization process. */ typedef int (*lbfgs_progress_t)( void *instance, const lbfgsfloatval_t *x, const lbfgsfloatval_t *g, const lbfgsfloatval_t fx, const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm, const lbfgsfloatval_t step, int n, int k, int ls ); /* A user must implement a function compatible with ::lbfgs_evaluate_t (evaluation callback) and pass the pointer to the callback function to lbfgs() arguments. Similarly, a user can implement a function compatible with ::lbfgs_progress_t (progress callback) to obtain the current progress (e.g., variables, function value, ||G||, etc) and to cancel the iteration process if necessary. Implementation of a progress callback is optional: a user can pass \c NULL if progress notification is not necessary. In addition, a user must preserve two requirements: - The number of variables must be multiples of 16 (this is not 4). - The memory block of variable array ::x must be aligned to 16. This algorithm terminates an optimization when: ||G|| < \epsilon \cdot \max(1, ||x||) . In this formula, ||.|| denotes the Euclidean norm. */ /** * Start a L-BFGS optimization. * * @param n The number of variables. * @param x The array of variables. A client program can set * default values for the optimization and receive the * optimization result through this array. This array * must be allocated by ::lbfgs_malloc function * for libLBFGS built with SSE/SSE2 optimization routine * enabled. The library built without SSE/SSE2 * optimization does not have such a requirement. * @param ptr_fx The pointer to the variable that receives the final * value of the objective function for the variables. * This argument can be set to \c NULL if the final * value of the objective function is unnecessary. * @param proc_evaluate The callback function to provide function and * gradient evaluations given a current values of * variables. A client program must implement a * callback function compatible with \ref * lbfgs_evaluate_t and pass the pointer to the * callback function. * @param proc_progress The callback function to receive the progress * (the number of iterations, the current value of * the objective function) of the minimization * process. This argument can be set to \c NULL if * a progress report is unnecessary. * @param instance A user data for the client program. The callback * functions will receive the value of this argument. * @param param The pointer to a structure representing parameters for * L-BFGS optimization. A client program can set this * parameter to \c NULL to use the default parameters. * Call lbfgs_parameter_init() function to fill a * structure with the default values. * @retval int The status code. This function returns zero if the * minimization process terminates without an error. A * non-zero value indicates an error. */ int lbfgs( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *ptr_fx, lbfgs_evaluate_t proc_evaluate, lbfgs_progress_t proc_progress, void *instance, lbfgs_parameter_t *param ); /** * Initialize L-BFGS parameters to the default values. * * Call this function to fill a parameter structure with the default values * and overwrite parameter values if necessary. * * @param param The pointer to the parameter structure. */ void lbfgs_parameter_init(lbfgs_parameter_t *param); /** * Allocate an array for variables. * * This function allocates an array of variables for the convenience of * ::lbfgs function; the function has a requreiemt for a variable array * when libLBFGS is built with SSE/SSE2 optimization routines. A user does * not have to use this function for libLBFGS built without SSE/SSE2 * optimization. * * @param n The number of variables. */ lbfgsfloatval_t* lbfgs_malloc(int n); /** * Free an array of variables. * * @param x The array of variables allocated by ::lbfgs_malloc * function. */ void lbfgs_free(lbfgsfloatval_t *x); /** @} */ #ifdef __cplusplus } #endif/*__cplusplus*/ /** @mainpage libLBFGS: a library of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) @section intro Introduction This library is a C port of the implementation of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) method written by Jorge Nocedal. The original FORTRAN source code is available at: http://www.ece.northwestern.edu/~nocedal/lbfgs.html The L-BFGS method solves the unconstrainted minimization problem,
    minimize F(x), x = (x1, x2, ..., xN),
only if the objective function F(x) and its gradient G(x) are computable. The well-known Newton's method requires computation of the inverse of the hessian matrix of the objective function. However, the computational cost for the inverse hessian matrix is expensive especially when the objective function takes a large number of variables. The L-BFGS method iteratively finds a minimizer by approximating the inverse hessian matrix by information from last m iterations. This innovation saves the memory storage and computational time drastically for large-scaled problems. Among the various ports of L-BFGS, this library provides several features: - Optimization with L1-norm (Orthant-Wise Limited-memory Quasi-Newton (OWL-QN) method): In addition to standard minimization problems, the library can minimize a function F(x) combined with L1-norm |x| of the variables, {F(x) + C |x|}, where C is a constant scalar parameter. This feature is useful for estimating parameters of sparse log-linear models (e.g., logistic regression and maximum entropy) with L1-regularization (or Laplacian prior). - Clean C code: Unlike C codes generated automatically by f2c (Fortran 77 into C converter), this port includes changes based on my interpretations, improvements, optimizations, and clean-ups so that the ported code would be well-suited for a C code. In addition to comments inherited from the original code, a number of comments were added through my interpretations. - Callback interface: The library receives function and gradient values via a callback interface. The library also notifies the progress of the optimization by invoking a callback function. In the original implementation, a user had to set function and gradient values every time the function returns for obtaining updated values. - Thread safe: The library is thread-safe, which is the secondary gain from the callback interface. - Cross platform. The source code can be compiled on Microsoft Visual Studio 2005, GNU C Compiler (gcc), etc. - Configurable precision: A user can choose single-precision (float) or double-precision (double) accuracy by changing ::LBFGS_FLOAT macro. - SSE/SSE2 optimization: This library includes SSE/SSE2 optimization (written in compiler intrinsics) for vector arithmetic operations on Intel/AMD processors. The library uses SSE for float values and SSE2 for double values. The SSE/SSE2 optimization routine is disabled by default. This library is used by: - CRFsuite: A fast implementation of Conditional Random Fields (CRFs) - Classias: A collection of machine-learning algorithms for classification - mlegp: an R package for maximum likelihood estimates for Gaussian processes - imaging2: the imaging2 class library - Algorithm::LBFGS - Perl extension for L-BFGS - YAP-LBFGS (an interface to call libLBFGS from YAP Prolog) @section download Download - Source code libLBFGS is distributed under the term of the MIT license. @section changelog History - Version 1.9 (2010-01-29): - Fixed a mistake in checking the validity of the parameters "ftol" and "wolfe"; this was discovered by Kevin S. Van Horn. - Version 1.8 (2009-07-13): - Accepted the patch submitted by Takashi Imamichi; the backtracking method now has three criteria for choosing the step length: - ::LBFGS_LINESEARCH_BACKTRACKING_ARMIJO: sufficient decrease (Armijo) condition only - ::LBFGS_LINESEARCH_BACKTRACKING_WOLFE: regular Wolfe condition (sufficient decrease condition + curvature condition) - ::LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE: strong Wolfe condition - Updated the documentation to explain the above three criteria. - Version 1.7 (2009-02-28): - Improved OWL-QN routines for stability. - Removed the support of OWL-QN method in MoreThuente algorithm because it accidentally fails in early stages of iterations for some objectives. Because of this change, the OW-LQN method must be used with the backtracking algorithm (::LBFGS_LINESEARCH_BACKTRACKING), or the library returns ::LBFGSERR_INVALID_LINESEARCH. - Renamed line search algorithms as follows: - ::LBFGS_LINESEARCH_BACKTRACKING: regular Wolfe condition. - ::LBFGS_LINESEARCH_BACKTRACKING_LOOSE: regular Wolfe condition. - ::LBFGS_LINESEARCH_BACKTRACKING_STRONG: strong Wolfe condition. - Source code clean-up. - Version 1.6 (2008-11-02): - Improved line-search algorithm with strong Wolfe condition, which was contributed by Takashi Imamichi. This routine is now default for ::LBFGS_LINESEARCH_BACKTRACKING. The previous line search algorithm with regular Wolfe condition is still available as ::LBFGS_LINESEARCH_BACKTRACKING_LOOSE. - Configurable stop index for L1-norm computation. A member variable ::lbfgs_parameter_t::orthantwise_end was added to specify the index number at which the library stops computing the L1 norm of the variables. This is useful to prevent some variables from being regularized by the OW-LQN method. - A sample program written in C++ (sample/sample.cpp). - Version 1.5 (2008-07-10): - Configurable starting index for L1-norm computation. A member variable ::lbfgs_parameter_t::orthantwise_start was added to specify the index number from which the library computes the L1 norm of the variables. This is useful to prevent some variables from being regularized by the OWL-QN method. - Fixed a zero-division error when the initial variables have already been a minimizer (reported by Takashi Imamichi). In this case, the library returns ::LBFGS_ALREADY_MINIMIZED status code. - Defined ::LBFGS_SUCCESS status code as zero; removed unused constants, LBFGSFALSE and LBFGSTRUE. - Fixed a compile error in an implicit down-cast. - Version 1.4 (2008-04-25): - Configurable line search algorithms. A member variable ::lbfgs_parameter_t::linesearch was added to choose either MoreThuente method (::LBFGS_LINESEARCH_MORETHUENTE) or backtracking algorithm (::LBFGS_LINESEARCH_BACKTRACKING). - Fixed a bug: the previous version did not compute psuedo-gradients properly in the line search routines for OWL-QN. This bug might quit an iteration process too early when the OWL-QN routine was activated (0 < ::lbfgs_parameter_t::orthantwise_c). - Configure script for POSIX environments. - SSE/SSE2 optimizations with GCC. - New functions ::lbfgs_malloc and ::lbfgs_free to use SSE/SSE2 routines transparently. It is uncessary to use these functions for libLBFGS built without SSE/SSE2 routines; you can still use any memory allocators if SSE/SSE2 routines are disabled in libLBFGS. - Version 1.3 (2007-12-16): - An API change. An argument was added to lbfgs() function to receive the final value of the objective function. This argument can be set to \c NULL if the final value is unnecessary. - Fixed a null-pointer bug in the sample code (reported by Takashi Imamichi). - Added build scripts for Microsoft Visual Studio 2005 and GCC. - Added README file. - Version 1.2 (2007-12-13): - Fixed a serious bug in orthant-wise L-BFGS. An important variable was used without initialization. - Version 1.1 (2007-12-01): - Implemented orthant-wise L-BFGS. - Implemented lbfgs_parameter_init() function. - Fixed several bugs. - API documentation. - Version 1.0 (2007-09-20): - Initial release. @section api Documentation - @ref liblbfgs_api "libLBFGS API" @section sample Sample code @include sample.c @section ack Acknowledgements The L-BFGS algorithm is described in: - Jorge Nocedal. Updating Quasi-Newton Matrices with Limited Storage. Mathematics of Computation, Vol. 35, No. 151, pp. 773--782, 1980. - Dong C. Liu and Jorge Nocedal. On the limited memory BFGS method for large scale optimization. Mathematical Programming B, Vol. 45, No. 3, pp. 503-528, 1989. The line search algorithms used in this implementation are described in: - John E. Dennis and Robert B. Schnabel. Numerical Methods for Unconstrained Optimization and Nonlinear Equations, Englewood Cliffs, 1983. - Jorge J. More and David J. Thuente. Line search algorithm with guaranteed sufficient decrease. ACM Transactions on Mathematical Software (TOMS), Vol. 20, No. 3, pp. 286-307, 1994. This library also implements Orthant-Wise Limited-memory Quasi-Newton (OWL-QN) method presented in: - Galen Andrew and Jianfeng Gao. Scalable training of L1-regularized log-linear models. In Proceedings of the 24th International Conference on Machine Learning (ICML 2007), pp. 33-40, 2007. Special thanks go to: - Yoshimasa Tsuruoka and Daisuke Okanohara for technical information about OWL-QN - Takashi Imamichi for the useful enhancements of the backtracking method Finally I would like to thank the original author, Jorge Nocedal, who has been distributing the effieicnt and explanatory implementation in an open source licence. @section reference Reference - L-BFGS by Jorge Nocedal. - Orthant-Wise Limited-memory Quasi-Newton Optimizer for L1-regularized Objectives by Galen Andrew. - C port (via f2c) by Taku Kudo. - C#/C++/Delphi/VisualBasic6 port in ALGLIB. - Computational Crystallography Toolbox includes scitbx::lbfgs. */ #endif/*__LBFGS_H__*/ igraph/src/plfit/error.c0000644000175100001440000000437113431000472014743 0ustar hornikusers/* error.c * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include "error.h" static char *plfit_i_error_strings[] = { "No error", "Failed", "Invalid value", "Underflow", "Overflow", "Not enough memory" }; #ifndef USING_R static plfit_error_handler_t* plfit_error_handler = plfit_error_handler_abort; #else /* This is overwritten, anyway */ static plfit_error_handler_t* plfit_error_handler = plfit_error_handler_ignore; #endif const char* plfit_strerror(const int plfit_errno) { return plfit_i_error_strings[plfit_errno]; } plfit_error_handler_t* plfit_set_error_handler(plfit_error_handler_t* new_handler) { plfit_error_handler_t* old_handler = plfit_error_handler; plfit_error_handler = new_handler; return old_handler; } void plfit_error(const char *reason, const char *file, int line, int plfit_errno) { plfit_error_handler(reason, file, line, plfit_errno); } #ifndef USING_R void plfit_error_handler_abort(const char *reason, const char *file, int line, int plfit_errno) { fprintf(stderr, "Error at %s:%i : %s, %s\n", file, line, reason, plfit_strerror(plfit_errno)); abort(); } #endif #ifndef USING_R void plfit_error_handler_printignore(const char *reason, const char *file, int line, int plfit_errno) { fprintf(stderr, "Error at %s:%i : %s, %s\n", file, line, reason, plfit_strerror(plfit_errno)); } #endif void plfit_error_handler_ignore(const char *reason, const char *file, int line, int plfit_errno) { } igraph/src/plfit/plfit.inc0000644000175100001440000000056613430770204015267 0ustar hornikusersPLFIT = plfit/error.c plfit/gss.c plfit/kolmogorov.c \ plfit/lbfgs.c plfit/options.c plfit/plfit.c \ plfit/zeta.c \ plfit/arithmetic_ansi.h plfit/arithmetic_sse_double.h plfit/arithmetic_sse_float.h \ plfit/error.h plfit/gss.h plfit/kolmogorov.h \ plfit/lbfgs.h plfit/platform.h plfit/plfit.h \ plfit/zeta.h igraph/src/plfit/zeta.h0000644000175100001440000000265013431000472014560 0ustar hornikusers/* specfunc/gsl_sf_zeta.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* This file was taken from the GNU Scientific Library. Some modifications * were done in order to make it independent from the rest of GSL */ #ifndef __ZETA_H__ #define __ZETA_H__ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* Hurwitz Zeta Function * zeta(s,q) = Sum[ (k+q)^(-s), {k,0,Infinity} ] * * s > 1.0, q > 0.0 */ double gsl_sf_hzeta(const double s, const double q); __END_DECLS #endif /* __ZETA_H__ */ igraph/src/plfit/gss.c0000644000175100001440000000661713431000472014413 0ustar hornikusers/* gss.c * * Copyright (C) 2012 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include "error.h" #include "gss.h" #include "platform.h" /** * \def PHI * * The golden ratio, i.e. 1+sqrt(5)/2 */ #define PHI 1.618033988749895 /** * \def RESPHI * * Constant defined as 2 - \c PHI */ #define RESPHI 0.3819660112501051 /** * \const _defparam * * Default parameters for the GSS algorithm. */ static const gss_parameter_t _defparam = { /* .epsilon = */ DBL_MIN, /* .on_error = */ GSS_ERROR_STOP }; /** * Stores whether the last optimization run triggered a warning or not. */ static unsigned short int gss_i_warning_flag = 0; void gss_parameter_init(gss_parameter_t *param) { memcpy(param, &_defparam, sizeof(*param)); } unsigned short int gss_get_warning_flag() { return gss_i_warning_flag; } #define TERMINATE { \ if (_min) { \ *(_min) = min; \ } \ if (_fmin) { \ *(_fmin) = fmin; \ } \ } #define EVALUATE(x, fx) { \ fx = proc_evaluate(instance, x); \ if (fmin > fx) { \ min = x; \ fmin = fx; \ } \ if (proc_progress) { \ retval = proc_progress(instance, x, fx, min, fmin, \ (a < b) ? a : b, (a < b) ? b : a, k); \ if (retval) { \ TERMINATE; \ return PLFIT_SUCCESS; \ } \ } \ } int gss(double a, double b, double *_min, double *_fmin, gss_evaluate_t proc_evaluate, gss_progress_t proc_progress, void* instance, const gss_parameter_t *_param) { double c, d, min; double fa, fb, fc, fd, fmin; int k = 0; int retval; unsigned short int successful = 1; gss_parameter_t param = _param ? (*_param) : _defparam; gss_i_warning_flag = 0; if (a > b) { c = a; a = b; b = c; } min = a; fmin = proc_evaluate(instance, a); c = a + RESPHI*(b-a); EVALUATE(a, fa); EVALUATE(b, fb); EVALUATE(c, fc); if (fc >= fa || fc >= fb) { if (param.on_error == GSS_ERROR_STOP) { return PLFIT_FAILURE; } else { gss_i_warning_flag = 1; } } while (fabs(a-b) > param.epsilon) { k++; d = c + RESPHI*(b-c); EVALUATE(d, fd); if (fd >= fa || fd >= fb) { if (param.on_error == GSS_ERROR_STOP) { successful = 0; break; } else { gss_i_warning_flag = 1; } } if (fc <= fd) { b = a; a = d; } else { a = c; c = d; fc = fd; } } if (successful) { c = (a+b) / 2.0; k++; EVALUATE(c, fc); TERMINATE; } return successful ? PLFIT_SUCCESS : PLFIT_FAILURE; } igraph/src/plfit/kolmogorov.c0000644000175100001440000000355213431000472016010 0ustar hornikusers/* kolmogorov.c * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include "kolmogorov.h" double plfit_kolmogorov(double z) { const double fj[4] = { -2, -8, -18, -32 }; const double w = 2.50662827; const double c1 = -1.2337005501361697; /* -pi^2 / 8 */ const double c2 = -11.103304951225528; /* 9*c1 */ const double c3 = -30.842513753404244; /* 25*c1 */ double u = fabs(z); double v; if (u < 0.2) return 1; if (u < 0.755) { v = 1.0 / (u*u); return 1 - w * (exp(c1*v) + exp(c2*v) + exp(c3*v)) / u; } if (u < 6.8116) { double r[4] = { 0, 0, 0, 0 }; long int maxj = (long int)(3.0 / u + 0.5); long int j; if (maxj < 1) maxj = 1; v = u*u; for (j = 0; j < maxj; j++) { r[j] = exp(fj[j] * v); } return 2*(r[0] - r[1] + r[2] - r[3]); } return 0; } double plfit_ks_test_one_sample_p(double d, size_t n) { return plfit_kolmogorov(d * sqrt(n)); } double plfit_ks_test_two_sample_p(double d, size_t n1, size_t n2) { return plfit_kolmogorov(d * sqrt(n1*n2 / ((double)(n1+n2)))); } igraph/src/plfit/error.h0000644000175100001440000000473013431000472014747 0ustar hornikusers/* error.h * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __ERROR_H__ #define __ERROR_H__ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS enum { PLFIT_SUCCESS = 0, PLFIT_FAILURE = 1, PLFIT_EINVAL = 2, PLFIT_UNDRFLOW = 3, PLFIT_OVERFLOW = 4, PLFIT_ENOMEM = 5 }; #if (defined(__GNUC__) && GCC_VERSION_MAJOR >= 3) # define PLFIT_UNLIKELY(a) __builtin_expect((a), 0) # define PLFIT_LIKELY(a) __builtin_expect((a), 1) #else # define PLFIT_UNLIKELY(a) a # define PLFIT_LIKELY(a) a #endif #define PLFIT_CHECK(a) \ do {\ int plfit_i_ret=(a); \ if (PLFIT_UNLIKELY(plfit_i_ret != PLFIT_SUCCESS)) {\ return plfit_i_ret; \ } \ } while(0) #define PLFIT_ERROR(reason,plfit_errno) \ do {\ plfit_error (reason, __FILE__, __LINE__, plfit_errno) ; \ return plfit_errno ; \ } while (0) typedef void plfit_error_handler_t(const char*, const char*, int, int); extern plfit_error_handler_t plfit_error_handler_abort; extern plfit_error_handler_t plfit_error_handler_ignore; extern plfit_error_handler_t plfit_error_handler_printignore; plfit_error_handler_t* plfit_set_error_handler(plfit_error_handler_t* new_handler); void plfit_error(const char *reason, const char *file, int line, int plfit_errno); const char* plfit_strerror(const int plfit_errno); void plfit_error_handler_abort(const char *reason, const char *file, int line, int plfit_errno); void plfit_error_handler_ignore(const char *reason, const char *file, int line, int plfit_errno); void plfit_error_handler_printignore(const char *reason, const char *file, int line, int plfit_errno); __END_DECLS #endif /* __ERROR_H__ */ igraph/src/plfit/zeta.c0000644000175100001440000001101013431000472014541 0ustar hornikusers/* specfunc/zeta.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ /* This file was taken from the GNU Scientific Library. Some modifications * were done in order to make it independent from the rest of GSL */ /* #include #include #include #include #include #include #include #include #include "error.h" #include "chebyshev.h" #include "cheb_eval.c" */ #include #include #include "error.h" /*-*-*-*-*-*-*-*-*-*- From gsl_machine.h -*-*-*-*-*-*-*-*-*-*-*-*-*/ #define GSL_LOG_DBL_MIN (-7.0839641853226408e+02) #define GSL_LOG_DBL_MAX 7.0978271289338397e+02 #define GSL_DBL_EPSILON 2.2204460492503131e-16 /*-*-*-*-*-*-*-*-*-* From gsl_sf_result.h *-*-*-*-*-*-*-*-*-*-*-*/ struct gsl_sf_result_struct { double val; double err; }; typedef struct gsl_sf_result_struct gsl_sf_result; /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* coefficients for Maclaurin summation in hzeta() * B_{2j}/(2j)! */ static double hzeta_c[15] = { 1.00000000000000000000000000000, 0.083333333333333333333333333333, -0.00138888888888888888888888888889, 0.000033068783068783068783068783069, -8.2671957671957671957671957672e-07, 2.0876756987868098979210090321e-08, -5.2841901386874931848476822022e-10, 1.3382536530684678832826980975e-11, -3.3896802963225828668301953912e-13, 8.5860620562778445641359054504e-15, -2.1748686985580618730415164239e-16, 5.5090028283602295152026526089e-18, -1.3954464685812523340707686264e-19, 3.5347070396294674716932299778e-21, -8.9535174270375468504026113181e-23 }; /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ static int gsl_sf_hzeta_e(const double s, const double q, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(s <= 1.0 || q <= 0.0) { PLFIT_ERROR("s must be larger than 1.0 and q must be larger than zero", PLFIT_EINVAL); } else { const double max_bits = 54.0; const double ln_term0 = -s * log(q); if(ln_term0 < GSL_LOG_DBL_MIN + 1.0) { PLFIT_ERROR("underflow", PLFIT_UNDRFLOW); } else if(ln_term0 > GSL_LOG_DBL_MAX - 1.0) { PLFIT_ERROR("overflow", PLFIT_OVERFLOW); } else if((s > max_bits && q < 1.0) || (s > 0.5*max_bits && q < 0.25)) { result->val = pow(q, -s); result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return PLFIT_SUCCESS; } else if(s > 0.5*max_bits && q < 1.0) { const double p1 = pow(q, -s); const double p2 = pow(q/(1.0+q), s); const double p3 = pow(q/(2.0+q), s); result->val = p1 * (1.0 + p2 + p3); result->err = GSL_DBL_EPSILON * (0.5*s + 2.0) * fabs(result->val); return PLFIT_SUCCESS; } else { /* Euler-Maclaurin summation formula * [Moshier, p. 400, with several typo corrections] */ const int jmax = 12; const int kmax = 10; int j, k; const double pmax = pow(kmax + q, -s); double scp = s; double pcp = pmax / (kmax + q); double ans = pmax*((kmax+q)/(s-1.0) + 0.5); for(k=0; kval = ans; result->err = 2.0 * (jmax + 1.0) * GSL_DBL_EPSILON * fabs(ans); return PLFIT_SUCCESS; } } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ double gsl_sf_hzeta(const double s, const double a) { gsl_sf_result result; gsl_sf_hzeta_e(s, a, &result); return result.val; } igraph/src/plfit/options.c0000644000175100001440000000272113431000472015302 0ustar hornikusers/* options.c * * Copyright (C) 2012 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "error.h" #include "plfit.h" const plfit_continuous_options_t plfit_continuous_default_options = { /* .finite_size_correction = */ 0, /* .xmin_method = */ PLFIT_GSS_OR_LINEAR }; const plfit_discrete_options_t plfit_discrete_default_options = { /* .finite_size_correction = */ 0, /* .alpha_method = */ PLFIT_LBFGS, /* .alpha = */ { /* .min = */ 1.01, /* .max = */ 5, /* .step = */ 0.01 } }; int plfit_continuous_options_init(plfit_continuous_options_t* options) { *options = plfit_continuous_default_options; return PLFIT_SUCCESS; } int plfit_discrete_options_init(plfit_discrete_options_t* options) { *options = plfit_discrete_default_options; return PLFIT_SUCCESS; } igraph/src/plfit/arithmetic_ansi.h0000644000175100001440000000654713431000472016771 0ustar hornikusers/* * ANSI C implementation of vector operations. * * Copyright (c) 2007-2010 Naoaki Okazaki * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* $Id: arithmetic_ansi.h 65 2010-01-29 12:19:16Z naoaki $ */ #include #include #if LBFGS_FLOAT == 32 && LBFGS_IEEE_FLOAT #define fsigndiff(x, y) (((*(uint32_t*)(x)) ^ (*(uint32_t*)(y))) & 0x80000000U) #else #define fsigndiff(x, y) (*(x) * (*(y) / fabs(*(y))) < 0.) #endif/*LBFGS_IEEE_FLOAT*/ inline static void* vecalloc(size_t size) { void *memblock = malloc(size); if (memblock) { memset(memblock, 0, size); } return memblock; } inline static void vecfree(void *memblock) { free(memblock); } inline static void vecset(lbfgsfloatval_t *x, const lbfgsfloatval_t c, const int n) { int i; for (i = 0;i < n;++i) { x[i] = c; } } inline static void veccpy(lbfgsfloatval_t *y, const lbfgsfloatval_t *x, const int n) { int i; for (i = 0;i < n;++i) { y[i] = x[i]; } } inline static void vecncpy(lbfgsfloatval_t *y, const lbfgsfloatval_t *x, const int n) { int i; for (i = 0;i < n;++i) { y[i] = -x[i]; } } inline static void vecadd(lbfgsfloatval_t *y, const lbfgsfloatval_t *x, const lbfgsfloatval_t c, const int n) { int i; for (i = 0;i < n;++i) { y[i] += c * x[i]; } } inline static void vecdiff(lbfgsfloatval_t *z, const lbfgsfloatval_t *x, const lbfgsfloatval_t *y, const int n) { int i; for (i = 0;i < n;++i) { z[i] = x[i] - y[i]; } } inline static void vecscale(lbfgsfloatval_t *y, const lbfgsfloatval_t c, const int n) { int i; for (i = 0;i < n;++i) { y[i] *= c; } } inline static void vecmul(lbfgsfloatval_t *y, const lbfgsfloatval_t *x, const int n) { int i; for (i = 0;i < n;++i) { y[i] *= x[i]; } } inline static void vecdot(lbfgsfloatval_t* s, const lbfgsfloatval_t *x, const lbfgsfloatval_t *y, const int n) { int i; *s = 0.; for (i = 0;i < n;++i) { *s += x[i] * y[i]; } } inline static void vec2norm(lbfgsfloatval_t* s, const lbfgsfloatval_t *x, const int n) { vecdot(s, x, x, n); *s = (lbfgsfloatval_t)sqrt(*s); } inline static void vec2norminv(lbfgsfloatval_t* s, const lbfgsfloatval_t *x, const int n) { vec2norm(s, x, n); *s = (lbfgsfloatval_t)(1.0 / *s); } igraph/src/plfit/platform.h0000644000175100001440000000250613431000472015441 0ustar hornikusers/* platform.h * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __PLATFORM_H__ #define __PLATFORM_H__ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #include __BEGIN_DECLS #ifdef _MSC_VER #define snprintf sprintf_s #define inline __inline #define isnan(x) _isnan(x) #define isfinite(x) _finite(x) #endif #ifndef INFINITY # define INFINITY (1.0/0.0) #endif #ifndef NAN # define NAN (INFINITY-INFINITY) #endif __END_DECLS #endif /* __PLATFORM_H__ */ igraph/src/plfit/arithmetic_sse_double.h0000644000175100001440000002113613431000472020152 0ustar hornikusers/* * SSE2 implementation of vector oprations (64bit double). * * Copyright (c) 2007-2010 Naoaki Okazaki * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* $Id: arithmetic_sse_double.h 65 2010-01-29 12:19:16Z naoaki $ */ #include #if !defined(__APPLE__) #include #endif #include #if 1400 <= _MSC_VER #include #endif/*1400 <= _MSC_VER*/ #if HAVE_EMMINTRIN_H #include #endif/*HAVE_EMMINTRIN_H*/ inline static void* vecalloc(size_t size) { #ifdef _MSC_VER void *memblock = _aligned_malloc(size, 16); #elif defined(__APPLE__) /* Memory on Mac OS X is already aligned to 16 bytes */ void *memblock = malloc(size); #else void *memblock = memalign(16, size); #endif if (memblock != NULL) { memset(memblock, 0, size); } return memblock; } inline static void vecfree(void *memblock) { #ifdef _MSC_VER _aligned_free(memblock); #else free(memblock); #endif } #define fsigndiff(x, y) \ ((_mm_movemask_pd(_mm_set_pd(*(x), *(y))) + 1) & 0x002) #define vecset(x, c, n) \ { \ int i; \ __m128d XMM0 = _mm_set1_pd(c); \ for (i = 0;i < (n);i += 8) { \ _mm_store_pd((x)+i , XMM0); \ _mm_store_pd((x)+i+2, XMM0); \ _mm_store_pd((x)+i+4, XMM0); \ _mm_store_pd((x)+i+6, XMM0); \ } \ } #define veccpy(y, x, n) \ { \ int i; \ for (i = 0;i < (n);i += 8) { \ __m128d XMM0 = _mm_load_pd((x)+i ); \ __m128d XMM1 = _mm_load_pd((x)+i+2); \ __m128d XMM2 = _mm_load_pd((x)+i+4); \ __m128d XMM3 = _mm_load_pd((x)+i+6); \ _mm_store_pd((y)+i , XMM0); \ _mm_store_pd((y)+i+2, XMM1); \ _mm_store_pd((y)+i+4, XMM2); \ _mm_store_pd((y)+i+6, XMM3); \ } \ } #define vecncpy(y, x, n) \ { \ int i; \ for (i = 0;i < (n);i += 8) { \ __m128d XMM0 = _mm_setzero_pd(); \ __m128d XMM1 = _mm_setzero_pd(); \ __m128d XMM2 = _mm_setzero_pd(); \ __m128d XMM3 = _mm_setzero_pd(); \ __m128d XMM4 = _mm_load_pd((x)+i ); \ __m128d XMM5 = _mm_load_pd((x)+i+2); \ __m128d XMM6 = _mm_load_pd((x)+i+4); \ __m128d XMM7 = _mm_load_pd((x)+i+6); \ XMM0 = _mm_sub_pd(XMM0, XMM4); \ XMM1 = _mm_sub_pd(XMM1, XMM5); \ XMM2 = _mm_sub_pd(XMM2, XMM6); \ XMM3 = _mm_sub_pd(XMM3, XMM7); \ _mm_store_pd((y)+i , XMM0); \ _mm_store_pd((y)+i+2, XMM1); \ _mm_store_pd((y)+i+4, XMM2); \ _mm_store_pd((y)+i+6, XMM3); \ } \ } #define vecadd(y, x, c, n) \ { \ int i; \ __m128d XMM7 = _mm_set1_pd(c); \ for (i = 0;i < (n);i += 4) { \ __m128d XMM0 = _mm_load_pd((x)+i ); \ __m128d XMM1 = _mm_load_pd((x)+i+2); \ __m128d XMM2 = _mm_load_pd((y)+i ); \ __m128d XMM3 = _mm_load_pd((y)+i+2); \ XMM0 = _mm_mul_pd(XMM0, XMM7); \ XMM1 = _mm_mul_pd(XMM1, XMM7); \ XMM2 = _mm_add_pd(XMM2, XMM0); \ XMM3 = _mm_add_pd(XMM3, XMM1); \ _mm_store_pd((y)+i , XMM2); \ _mm_store_pd((y)+i+2, XMM3); \ } \ } #define vecdiff(z, x, y, n) \ { \ int i; \ for (i = 0;i < (n);i += 8) { \ __m128d XMM0 = _mm_load_pd((x)+i ); \ __m128d XMM1 = _mm_load_pd((x)+i+2); \ __m128d XMM2 = _mm_load_pd((x)+i+4); \ __m128d XMM3 = _mm_load_pd((x)+i+6); \ __m128d XMM4 = _mm_load_pd((y)+i ); \ __m128d XMM5 = _mm_load_pd((y)+i+2); \ __m128d XMM6 = _mm_load_pd((y)+i+4); \ __m128d XMM7 = _mm_load_pd((y)+i+6); \ XMM0 = _mm_sub_pd(XMM0, XMM4); \ XMM1 = _mm_sub_pd(XMM1, XMM5); \ XMM2 = _mm_sub_pd(XMM2, XMM6); \ XMM3 = _mm_sub_pd(XMM3, XMM7); \ _mm_store_pd((z)+i , XMM0); \ _mm_store_pd((z)+i+2, XMM1); \ _mm_store_pd((z)+i+4, XMM2); \ _mm_store_pd((z)+i+6, XMM3); \ } \ } #define vecscale(y, c, n) \ { \ int i; \ __m128d XMM7 = _mm_set1_pd(c); \ for (i = 0;i < (n);i += 4) { \ __m128d XMM0 = _mm_load_pd((y)+i ); \ __m128d XMM1 = _mm_load_pd((y)+i+2); \ XMM0 = _mm_mul_pd(XMM0, XMM7); \ XMM1 = _mm_mul_pd(XMM1, XMM7); \ _mm_store_pd((y)+i , XMM0); \ _mm_store_pd((y)+i+2, XMM1); \ } \ } #define vecmul(y, x, n) \ { \ int i; \ for (i = 0;i < (n);i += 8) { \ __m128d XMM0 = _mm_load_pd((x)+i ); \ __m128d XMM1 = _mm_load_pd((x)+i+2); \ __m128d XMM2 = _mm_load_pd((x)+i+4); \ __m128d XMM3 = _mm_load_pd((x)+i+6); \ __m128d XMM4 = _mm_load_pd((y)+i ); \ __m128d XMM5 = _mm_load_pd((y)+i+2); \ __m128d XMM6 = _mm_load_pd((y)+i+4); \ __m128d XMM7 = _mm_load_pd((y)+i+6); \ XMM4 = _mm_mul_pd(XMM4, XMM0); \ XMM5 = _mm_mul_pd(XMM5, XMM1); \ XMM6 = _mm_mul_pd(XMM6, XMM2); \ XMM7 = _mm_mul_pd(XMM7, XMM3); \ _mm_store_pd((y)+i , XMM4); \ _mm_store_pd((y)+i+2, XMM5); \ _mm_store_pd((y)+i+4, XMM6); \ _mm_store_pd((y)+i+6, XMM7); \ } \ } #if 3 <= __SSE__ /* Horizontal add with haddps SSE3 instruction. The work register (rw) is unused. */ #define __horizontal_sum(r, rw) \ r = _mm_hadd_ps(r, r); \ r = _mm_hadd_ps(r, r); #else /* Horizontal add with SSE instruction. The work register (rw) is used. */ #define __horizontal_sum(r, rw) \ rw = r; \ r = _mm_shuffle_ps(r, rw, _MM_SHUFFLE(1, 0, 3, 2)); \ r = _mm_add_ps(r, rw); \ rw = r; \ r = _mm_shuffle_ps(r, rw, _MM_SHUFFLE(2, 3, 0, 1)); \ r = _mm_add_ps(r, rw); #endif #define vecdot(s, x, y, n) \ { \ int i; \ __m128d XMM0 = _mm_setzero_pd(); \ __m128d XMM1 = _mm_setzero_pd(); \ __m128d XMM2, XMM3, XMM4, XMM5; \ for (i = 0;i < (n);i += 4) { \ XMM2 = _mm_load_pd((x)+i ); \ XMM3 = _mm_load_pd((x)+i+2); \ XMM4 = _mm_load_pd((y)+i ); \ XMM5 = _mm_load_pd((y)+i+2); \ XMM2 = _mm_mul_pd(XMM2, XMM4); \ XMM3 = _mm_mul_pd(XMM3, XMM5); \ XMM0 = _mm_add_pd(XMM0, XMM2); \ XMM1 = _mm_add_pd(XMM1, XMM3); \ } \ XMM0 = _mm_add_pd(XMM0, XMM1); \ XMM1 = _mm_shuffle_pd(XMM0, XMM0, _MM_SHUFFLE2(1, 1)); \ XMM0 = _mm_add_pd(XMM0, XMM1); \ _mm_store_sd((s), XMM0); \ } #define vec2norm(s, x, n) \ { \ int i; \ __m128d XMM0 = _mm_setzero_pd(); \ __m128d XMM1 = _mm_setzero_pd(); \ __m128d XMM2, XMM3, XMM4, XMM5; \ for (i = 0;i < (n);i += 4) { \ XMM2 = _mm_load_pd((x)+i ); \ XMM3 = _mm_load_pd((x)+i+2); \ XMM4 = XMM2; \ XMM5 = XMM3; \ XMM2 = _mm_mul_pd(XMM2, XMM4); \ XMM3 = _mm_mul_pd(XMM3, XMM5); \ XMM0 = _mm_add_pd(XMM0, XMM2); \ XMM1 = _mm_add_pd(XMM1, XMM3); \ } \ XMM0 = _mm_add_pd(XMM0, XMM1); \ XMM1 = _mm_shuffle_pd(XMM0, XMM0, _MM_SHUFFLE2(1, 1)); \ XMM0 = _mm_add_pd(XMM0, XMM1); \ XMM0 = _mm_sqrt_pd(XMM0); \ _mm_store_sd((s), XMM0); \ } #define vec2norminv(s, x, n) \ { \ int i; \ __m128d XMM0 = _mm_setzero_pd(); \ __m128d XMM1 = _mm_setzero_pd(); \ __m128d XMM2, XMM3, XMM4, XMM5; \ for (i = 0;i < (n);i += 4) { \ XMM2 = _mm_load_pd((x)+i ); \ XMM3 = _mm_load_pd((x)+i+2); \ XMM4 = XMM2; \ XMM5 = XMM3; \ XMM2 = _mm_mul_pd(XMM2, XMM4); \ XMM3 = _mm_mul_pd(XMM3, XMM5); \ XMM0 = _mm_add_pd(XMM0, XMM2); \ XMM1 = _mm_add_pd(XMM1, XMM3); \ } \ XMM2 = _mm_set1_pd(1.0); \ XMM0 = _mm_add_pd(XMM0, XMM1); \ XMM1 = _mm_shuffle_pd(XMM0, XMM0, _MM_SHUFFLE2(1, 1)); \ XMM0 = _mm_add_pd(XMM0, XMM1); \ XMM0 = _mm_sqrt_pd(XMM0); \ XMM2 = _mm_div_pd(XMM2, XMM0); \ _mm_store_sd((s), XMM2); \ } igraph/src/plfit/plfit.h0000644000175100001440000000676613431000472014747 0ustar hornikusers/* plfit.h * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __PLFIT_H__ #define __PLFIT_H__ #include #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS #define PLFIT_VERSION_MAJOR 0 #define PLFIT_VERSION_MINOR 6 #define PLFIT_VERSION_STRING "0.6" typedef unsigned short int plfit_bool_t; typedef enum { PLFIT_GSS_OR_LINEAR, PLFIT_LINEAR_ONLY, PLFIT_DEFAULT_CONTINUOUS_METHOD = PLFIT_GSS_OR_LINEAR } plfit_continuous_method_t; typedef enum { PLFIT_LBFGS, PLFIT_LINEAR_SCAN, PLFIT_PRETEND_CONTINUOUS, PLFIT_DEFAULT_DISCRETE_METHOD = PLFIT_LBFGS } plfit_discrete_method_t; typedef struct _plfit_result_t { double alpha; /* fitted power-law exponent */ double xmin; /* cutoff where the power-law behaviour kicks in */ double L; /* log-likelihood of the sample */ double D; /* test statistic for the KS test */ double p; /* p-value of the KS test */ } plfit_result_t; /********** structure that holds the options of plfit **********/ typedef struct _plfit_continuous_options_t { plfit_bool_t finite_size_correction; plfit_continuous_method_t xmin_method; } plfit_continuous_options_t; typedef struct _plfit_discrete_options_t { plfit_bool_t finite_size_correction; plfit_discrete_method_t alpha_method; struct { double min; double max; double step; } alpha; } plfit_discrete_options_t; int plfit_continuous_options_init(plfit_continuous_options_t* options); int plfit_discrete_options_init(plfit_discrete_options_t* options); extern const plfit_continuous_options_t plfit_continuous_default_options; extern const plfit_discrete_options_t plfit_discrete_default_options; /********** continuous power law distribution fitting **********/ int plfit_log_likelihood_continuous(double* xs, size_t n, double alpha, double xmin, double* l); int plfit_estimate_alpha_continuous(double* xs, size_t n, double xmin, const plfit_continuous_options_t* options, plfit_result_t* result); int plfit_estimate_alpha_continuous_sorted(double* xs, size_t n, double xmin, const plfit_continuous_options_t* options, plfit_result_t* result); int plfit_continuous(double* xs, size_t n, const plfit_continuous_options_t* options, plfit_result_t* result); /********** discrete power law distribution fitting **********/ int plfit_estimate_alpha_discrete(double* xs, size_t n, double xmin, const plfit_discrete_options_t* options, plfit_result_t *result); int plfit_log_likelihood_discrete(double* xs, size_t n, double alpha, double xmin, double* l); int plfit_discrete(double* xs, size_t n, const plfit_discrete_options_t* options, plfit_result_t* result); __END_DECLS #endif /* __PLFIT_H__ */ igraph/src/plfit/gss.h0000644000175100001440000001366013431000472014414 0ustar hornikusers/* gss.h * * Copyright (C) 2012 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSS_H__ #define __GSS_H__ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /** * Enum specifying what the search should do when the function is not U-shaped. */ typedef enum { GSS_ERROR_STOP, /**< Stop and return an error code */ GSS_ERROR_WARN /**< Continue and set the warning flag */ } gss_error_handling_t; /** * Parameter settings for a golden section search. */ typedef struct { double epsilon; gss_error_handling_t on_error; } gss_parameter_t; /** * Callback interface to provide objective function evaluations for the golden * section search. * * The gss() function calls this function to obtain the values of the objective * function when needed. A client program must implement this function to evaluate * the value of the objective function, given the location. * * @param instance The user data sent for the gss() function by the client. * @param x The current value of the variable. * @retval double The value of the objective function for the current * variable. */ typedef double (*gss_evaluate_t)(void *instance, double x); /** * Callback interface to receive the progress of the optimization process for * the golden section search. * * The gss() function calls this function for each iteration. Implementing * this function, a client program can store or display the current progress * of the optimization process. * * @param instance The user data sent for the gss() function by the client. * @param x The current value of the variable. * @param fx The value of the objective function at x. * @param min The location of the minimum value of the objective * function found so far. * @param fmin The minimum value of the objective function found so far. * @param left The left side of the current bracket. * @param right The right side of the current bracket. * @param k The index of the current iteration. * @retval int Zero to continue the optimization process. Returning a * non-zero value will cancel the optimization process. */ typedef int (*gss_progress_t)(void *instance, double x, double fx, double min, double fmin, double left, double right, int k); /** * Start a golden section search optimization. * * @param a The left side of the bracket to start from * @param b The right side of the bracket to start from * @param min The pointer to the variable that receives the location of the * final value of the objective function. This argument can be set to * \c NULL if the location of the final value of the objective * function is unnecessary. * @param fmin The pointer to the variable that receives the final value of * the objective function. This argument can be st to \c NULL if the * final value of the objective function is unnecessary. * @param proc_evaluate The callback function to evaluate the objective * function at a given location. * @param proc_progress The callback function to receive the progress (the * last evaluated location, the value of the objective * function at that location, the width of the current * bracket, the minimum found so far and the step * count). This argument can be set to \c NULL if * a progress report is unnecessary. * @param instance A user data for the client program. The callback * functions will receive the value of this argument. * @param param The pointer to a structure representing parameters for * GSS algorithm. A client program can set this parameter * to \c NULL to use the default parameters. * Call the \ref gss_parameter_init() function to fill a * structure with the default values. * @retval int The status code. This function returns zero if the * minimization process terminates without an error. A * non-zero value indicates an error; in particular, * \c PLFIT_FAILURE means that the function is not * U-shaped. */ int gss(double a, double b, double *min, double *fmin, gss_evaluate_t proc_evaluate, gss_progress_t proc_progress, void* instance, const gss_parameter_t *_param); /** * Return the state of the warning flag. * * The warning flag is 1 if the last optimization was run on a function that * was not U-shaped. */ unsigned short int gss_get_warning_flag(); /** * Initialize GSS parameters to the default values. * * Call this function to fill a parameter structure with the default values * and overwrite parameter values if necessary. * * @param param The pointer to the parameter structure. */ void gss_parameter_init(gss_parameter_t *param); __END_DECLS #endif /* __GSS_H__ */ igraph/src/plfit/arithmetic_sse_float.h0000644000175100001440000002122513431000472020004 0ustar hornikusers/* * SSE/SSE3 implementation of vector oprations (32bit float). * * Copyright (c) 2007-2010 Naoaki Okazaki * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* $Id: arithmetic_sse_float.h 65 2010-01-29 12:19:16Z naoaki $ */ #include #if !defined(__APPLE__) #include #endif #include #if 1400 <= _MSC_VER #include #endif/*_MSC_VER*/ #if HAVE_XMMINTRIN_H #include #endif/*HAVE_XMMINTRIN_H*/ #if LBFGS_FLOAT == 32 && LBFGS_IEEE_FLOAT #define fsigndiff(x, y) (((*(uint32_t*)(x)) ^ (*(uint32_t*)(y))) & 0x80000000U) #else #define fsigndiff(x, y) (*(x) * (*(y) / fabs(*(y))) < 0.) #endif/*LBFGS_IEEE_FLOAT*/ inline static void* vecalloc(size_t size) { void *memblock = _aligned_malloc(size, 16); if (memblock != NULL) { memset(memblock, 0, size); } return memblock; } inline static void vecfree(void *memblock) { _aligned_free(memblock); } #define vecset(x, c, n) \ { \ int i; \ __m128 XMM0 = _mm_set_ps1(c); \ for (i = 0;i < (n);i += 16) { \ _mm_store_ps((x)+i , XMM0); \ _mm_store_ps((x)+i+ 4, XMM0); \ _mm_store_ps((x)+i+ 8, XMM0); \ _mm_store_ps((x)+i+12, XMM0); \ } \ } #define veccpy(y, x, n) \ { \ int i; \ for (i = 0;i < (n);i += 16) { \ __m128 XMM0 = _mm_load_ps((x)+i ); \ __m128 XMM1 = _mm_load_ps((x)+i+ 4); \ __m128 XMM2 = _mm_load_ps((x)+i+ 8); \ __m128 XMM3 = _mm_load_ps((x)+i+12); \ _mm_store_ps((y)+i , XMM0); \ _mm_store_ps((y)+i+ 4, XMM1); \ _mm_store_ps((y)+i+ 8, XMM2); \ _mm_store_ps((y)+i+12, XMM3); \ } \ } #define vecncpy(y, x, n) \ { \ int i; \ const uint32_t mask = 0x80000000; \ __m128 XMM4 = _mm_load_ps1((float*)&mask); \ for (i = 0;i < (n);i += 16) { \ __m128 XMM0 = _mm_load_ps((x)+i ); \ __m128 XMM1 = _mm_load_ps((x)+i+ 4); \ __m128 XMM2 = _mm_load_ps((x)+i+ 8); \ __m128 XMM3 = _mm_load_ps((x)+i+12); \ XMM0 = _mm_xor_ps(XMM0, XMM4); \ XMM1 = _mm_xor_ps(XMM1, XMM4); \ XMM2 = _mm_xor_ps(XMM2, XMM4); \ XMM3 = _mm_xor_ps(XMM3, XMM4); \ _mm_store_ps((y)+i , XMM0); \ _mm_store_ps((y)+i+ 4, XMM1); \ _mm_store_ps((y)+i+ 8, XMM2); \ _mm_store_ps((y)+i+12, XMM3); \ } \ } #define vecadd(y, x, c, n) \ { \ int i; \ __m128 XMM7 = _mm_set_ps1(c); \ for (i = 0;i < (n);i += 8) { \ __m128 XMM0 = _mm_load_ps((x)+i ); \ __m128 XMM1 = _mm_load_ps((x)+i+4); \ __m128 XMM2 = _mm_load_ps((y)+i ); \ __m128 XMM3 = _mm_load_ps((y)+i+4); \ XMM0 = _mm_mul_ps(XMM0, XMM7); \ XMM1 = _mm_mul_ps(XMM1, XMM7); \ XMM2 = _mm_add_ps(XMM2, XMM0); \ XMM3 = _mm_add_ps(XMM3, XMM1); \ _mm_store_ps((y)+i , XMM2); \ _mm_store_ps((y)+i+4, XMM3); \ } \ } #define vecdiff(z, x, y, n) \ { \ int i; \ for (i = 0;i < (n);i += 16) { \ __m128 XMM0 = _mm_load_ps((x)+i ); \ __m128 XMM1 = _mm_load_ps((x)+i+ 4); \ __m128 XMM2 = _mm_load_ps((x)+i+ 8); \ __m128 XMM3 = _mm_load_ps((x)+i+12); \ __m128 XMM4 = _mm_load_ps((y)+i ); \ __m128 XMM5 = _mm_load_ps((y)+i+ 4); \ __m128 XMM6 = _mm_load_ps((y)+i+ 8); \ __m128 XMM7 = _mm_load_ps((y)+i+12); \ XMM0 = _mm_sub_ps(XMM0, XMM4); \ XMM1 = _mm_sub_ps(XMM1, XMM5); \ XMM2 = _mm_sub_ps(XMM2, XMM6); \ XMM3 = _mm_sub_ps(XMM3, XMM7); \ _mm_store_ps((z)+i , XMM0); \ _mm_store_ps((z)+i+ 4, XMM1); \ _mm_store_ps((z)+i+ 8, XMM2); \ _mm_store_ps((z)+i+12, XMM3); \ } \ } #define vecscale(y, c, n) \ { \ int i; \ __m128 XMM7 = _mm_set_ps1(c); \ for (i = 0;i < (n);i += 8) { \ __m128 XMM0 = _mm_load_ps((y)+i ); \ __m128 XMM1 = _mm_load_ps((y)+i+4); \ XMM0 = _mm_mul_ps(XMM0, XMM7); \ XMM1 = _mm_mul_ps(XMM1, XMM7); \ _mm_store_ps((y)+i , XMM0); \ _mm_store_ps((y)+i+4, XMM1); \ } \ } #define vecmul(y, x, n) \ { \ int i; \ for (i = 0;i < (n);i += 16) { \ __m128 XMM0 = _mm_load_ps((x)+i ); \ __m128 XMM1 = _mm_load_ps((x)+i+ 4); \ __m128 XMM2 = _mm_load_ps((x)+i+ 8); \ __m128 XMM3 = _mm_load_ps((x)+i+12); \ __m128 XMM4 = _mm_load_ps((y)+i ); \ __m128 XMM5 = _mm_load_ps((y)+i+ 4); \ __m128 XMM6 = _mm_load_ps((y)+i+ 8); \ __m128 XMM7 = _mm_load_ps((y)+i+12); \ XMM4 = _mm_mul_ps(XMM4, XMM0); \ XMM5 = _mm_mul_ps(XMM5, XMM1); \ XMM6 = _mm_mul_ps(XMM6, XMM2); \ XMM7 = _mm_mul_ps(XMM7, XMM3); \ _mm_store_ps((y)+i , XMM4); \ _mm_store_ps((y)+i+ 4, XMM5); \ _mm_store_ps((y)+i+ 8, XMM6); \ _mm_store_ps((y)+i+12, XMM7); \ } \ } #if 3 <= __SSE__ /* Horizontal add with haddps SSE3 instruction. The work register (rw) is unused. */ #define __horizontal_sum(r, rw) \ r = _mm_hadd_ps(r, r); \ r = _mm_hadd_ps(r, r); #else /* Horizontal add with SSE instruction. The work register (rw) is used. */ #define __horizontal_sum(r, rw) \ rw = r; \ r = _mm_shuffle_ps(r, rw, _MM_SHUFFLE(1, 0, 3, 2)); \ r = _mm_add_ps(r, rw); \ rw = r; \ r = _mm_shuffle_ps(r, rw, _MM_SHUFFLE(2, 3, 0, 1)); \ r = _mm_add_ps(r, rw); #endif #define vecdot(s, x, y, n) \ { \ int i; \ __m128 XMM0 = _mm_setzero_ps(); \ __m128 XMM1 = _mm_setzero_ps(); \ __m128 XMM2, XMM3, XMM4, XMM5; \ for (i = 0;i < (n);i += 8) { \ XMM2 = _mm_load_ps((x)+i ); \ XMM3 = _mm_load_ps((x)+i+4); \ XMM4 = _mm_load_ps((y)+i ); \ XMM5 = _mm_load_ps((y)+i+4); \ XMM2 = _mm_mul_ps(XMM2, XMM4); \ XMM3 = _mm_mul_ps(XMM3, XMM5); \ XMM0 = _mm_add_ps(XMM0, XMM2); \ XMM1 = _mm_add_ps(XMM1, XMM3); \ } \ XMM0 = _mm_add_ps(XMM0, XMM1); \ __horizontal_sum(XMM0, XMM1); \ _mm_store_ss((s), XMM0); \ } #define vec2norm(s, x, n) \ { \ int i; \ __m128 XMM0 = _mm_setzero_ps(); \ __m128 XMM1 = _mm_setzero_ps(); \ __m128 XMM2, XMM3; \ for (i = 0;i < (n);i += 8) { \ XMM2 = _mm_load_ps((x)+i ); \ XMM3 = _mm_load_ps((x)+i+4); \ XMM2 = _mm_mul_ps(XMM2, XMM2); \ XMM3 = _mm_mul_ps(XMM3, XMM3); \ XMM0 = _mm_add_ps(XMM0, XMM2); \ XMM1 = _mm_add_ps(XMM1, XMM3); \ } \ XMM0 = _mm_add_ps(XMM0, XMM1); \ __horizontal_sum(XMM0, XMM1); \ XMM2 = XMM0; \ XMM1 = _mm_rsqrt_ss(XMM0); \ XMM3 = XMM1; \ XMM1 = _mm_mul_ss(XMM1, XMM1); \ XMM1 = _mm_mul_ss(XMM1, XMM3); \ XMM1 = _mm_mul_ss(XMM1, XMM0); \ XMM1 = _mm_mul_ss(XMM1, _mm_set_ss(-0.5f)); \ XMM3 = _mm_mul_ss(XMM3, _mm_set_ss(1.5f)); \ XMM3 = _mm_add_ss(XMM3, XMM1); \ XMM3 = _mm_mul_ss(XMM3, XMM2); \ _mm_store_ss((s), XMM3); \ } #define vec2norminv(s, x, n) \ { \ int i; \ __m128 XMM0 = _mm_setzero_ps(); \ __m128 XMM1 = _mm_setzero_ps(); \ __m128 XMM2, XMM3; \ for (i = 0;i < (n);i += 16) { \ XMM2 = _mm_load_ps((x)+i ); \ XMM3 = _mm_load_ps((x)+i+4); \ XMM2 = _mm_mul_ps(XMM2, XMM2); \ XMM3 = _mm_mul_ps(XMM3, XMM3); \ XMM0 = _mm_add_ps(XMM0, XMM2); \ XMM1 = _mm_add_ps(XMM1, XMM3); \ } \ XMM0 = _mm_add_ps(XMM0, XMM1); \ __horizontal_sum(XMM0, XMM1); \ XMM2 = XMM0; \ XMM1 = _mm_rsqrt_ss(XMM0); \ XMM3 = XMM1; \ XMM1 = _mm_mul_ss(XMM1, XMM1); \ XMM1 = _mm_mul_ss(XMM1, XMM3); \ XMM1 = _mm_mul_ss(XMM1, XMM0); \ XMM1 = _mm_mul_ss(XMM1, _mm_set_ss(-0.5f)); \ XMM3 = _mm_mul_ss(XMM3, _mm_set_ss(1.5f)); \ XMM3 = _mm_add_ss(XMM3, XMM1); \ _mm_store_ss((s), XMM3); \ } igraph/src/plfit/plfit.c0000644000175100001440000005416013431000472014731 0ustar hornikusers/* plfit.c * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include "error.h" #include "gss.h" #include "lbfgs.h" #include "platform.h" #include "plfit.h" #include "kolmogorov.h" #include "zeta.h" /* #define PLFIT_DEBUG */ #define DATA_POINTS_CHECK \ if (n <= 0) { \ PLFIT_ERROR("no data points", PLFIT_EINVAL); \ } #define XMIN_CHECK_ZERO \ if (xmin <= 0) { \ PLFIT_ERROR("xmin must be greater than zero", PLFIT_EINVAL); \ } #define XMIN_CHECK_ONE \ if (xmin < 1) { \ PLFIT_ERROR("xmin must be at least 1", PLFIT_EINVAL); \ } static int double_comparator(const void *a, const void *b) { const double *da = (const double*)a; const double *db = (const double*)b; return (*da > *db) - (*da < *db); } /** * Given a sorted array of doubles, return another array that contains pointers * into the array for the start of each block of identical elements. * * \param begin pointer to the beginning of the array * \param end pointer to the first element after the end of the array * \param result_length if not \c NULL, the number of unique elements in the * given array is returned here */ static double** unique_element_pointers(double* begin, double* end, size_t* result_length) { double* ptr = begin; double** result; double prev_x; size_t num_elts = 15; size_t used_elts = 0; /* Special case: empty array */ if (begin == end) { result = calloc(1, sizeof(double*)); if (result != 0) { result[0] = 0; } return result; } /* Allocate initial result array, including the guard element */ result = calloc(num_elts+1, sizeof(double*)); if (result == 0) return 0; prev_x = *begin; result[used_elts++] = begin; /* Process the input array */ for (ptr = begin+1; ptr < end; ptr++) { if (*ptr == prev_x) continue; /* New block found */ if (used_elts >= num_elts) { /* Array full; allocate a new chunk */ num_elts = num_elts*2 + 1; result = realloc(result, sizeof(double*) * (num_elts+1)); if (result == 0) return 0; } /* Store the new element */ result[used_elts++] = ptr; prev_x = *ptr; } /* Calculate the result length */ if (result_length != 0) { *result_length = used_elts; } /* Add the guard entry to the end of the result */ result[used_elts++] = 0; return result; } static void plfit_i_perform_finite_size_correction(plfit_result_t* result, size_t n) { result->alpha = result->alpha * (n-1) / n + 1.0 / n; } /********** Continuous power law distribution fitting **********/ void plfit_i_logsum_less_than_continuous(double* begin, double* end, double xmin, double* result, size_t* m) { double logsum = 0.0; size_t count = 0; for (; begin != end; begin++) { if (*begin >= xmin) { count++; logsum += log(*begin / xmin); } } *m = count; *result = logsum; } double plfit_i_logsum_continuous(double* begin, double* end, double xmin) { double logsum = 0.0; for (; begin != end; begin++) logsum += log(*begin / xmin); return logsum; } int plfit_i_estimate_alpha_continuous(double* xs, size_t n, double xmin, double* alpha) { double result; size_t m; XMIN_CHECK_ZERO; plfit_i_logsum_less_than_continuous(xs, xs+n, xmin, &result, &m); if (m == 0) { PLFIT_ERROR("no data point was larger than xmin", PLFIT_EINVAL); } *alpha = 1 + m / result; return PLFIT_SUCCESS; } int plfit_i_estimate_alpha_continuous_sorted(double* xs, size_t n, double xmin, double* alpha) { double* end = xs+n; XMIN_CHECK_ZERO; for (; xs != end && *xs < xmin; xs++); if (xs == end) { PLFIT_ERROR("no data point was larger than xmin", PLFIT_EINVAL); } *alpha = 1 + (end-xs) / plfit_i_logsum_continuous(xs, end, xmin); return PLFIT_SUCCESS; } static int plfit_i_ks_test_continuous(double* xs, double* xs_end, const double alpha, const double xmin, double* D) { /* Assumption: xs is sorted and cut off at xmin so the first element is * always larger than or equal to xmin. */ double result = 0, n; int m = 0; n = xs_end - xs; while (xs < xs_end) { double d = fabs(1-pow(xmin / *xs, alpha-1) - m / n); if (d > result) result = d; xs++; m++; } *D = result; return PLFIT_SUCCESS; } int plfit_log_likelihood_continuous(double* xs, size_t n, double alpha, double xmin, double* L) { double logsum, c; size_t m; if (alpha <= 1) { PLFIT_ERROR("alpha must be greater than one", PLFIT_EINVAL); } XMIN_CHECK_ZERO; c = (alpha - 1) / xmin; plfit_i_logsum_less_than_continuous(xs, xs+n, xmin, &logsum, &m); *L = -alpha * logsum + log(c) * m; return PLFIT_SUCCESS; } int plfit_estimate_alpha_continuous(double* xs, size_t n, double xmin, const plfit_continuous_options_t* options, plfit_result_t *result) { double *xs_copy; if (!options) options = &plfit_continuous_default_options; /* Make a copy of xs and sort it */ xs_copy = (double*)malloc(sizeof(double) * n); memcpy(xs_copy, xs, sizeof(double) * n); qsort(xs_copy, n, sizeof(double), double_comparator); PLFIT_CHECK(plfit_estimate_alpha_continuous_sorted(xs_copy, n, xmin, options, result)); free(xs_copy); return PLFIT_SUCCESS; } int plfit_estimate_alpha_continuous_sorted(double* xs, size_t n, double xmin, const plfit_continuous_options_t* options, plfit_result_t *result) { double* end; if (!options) options = &plfit_continuous_default_options; end = xs + n; while (xs < end && *xs < xmin) xs++; n = (size_t) (end - xs); PLFIT_CHECK(plfit_i_estimate_alpha_continuous_sorted(xs, n, xmin, &result->alpha)); PLFIT_CHECK(plfit_i_ks_test_continuous(xs, end, result->alpha, xmin, &result->D)); if (options->finite_size_correction) plfit_i_perform_finite_size_correction(result, n); result->xmin = xmin; result->p = plfit_ks_test_one_sample_p(result->D, n); plfit_log_likelihood_continuous(xs, n, result->alpha, result->xmin, &result->L); return PLFIT_SUCCESS; } typedef struct { double *begin; /**< Pointer to the beginning of the array holding the data */ double *end; /**< Pointer to after the end of the array holding the data */ double **uniques; /**< Pointers to unique elements of the input array */ plfit_result_t last; /**< Result of the last evaluation */ } plfit_continuous_xmin_opt_data_t; double plfit_i_continuous_xmin_opt_evaluate(void* instance, double x) { plfit_continuous_xmin_opt_data_t* data = (plfit_continuous_xmin_opt_data_t*)instance; double* begin = data->uniques[(int)x]; data->last.xmin = *begin; #ifdef PLFIT_DEBUG printf("Trying with xmin = %.4f\n", *begin); #endif plfit_i_estimate_alpha_continuous_sorted(begin, (size_t) (data->end-begin), *begin, &data->last.alpha); plfit_i_ks_test_continuous(begin, data->end, data->last.alpha, *begin, &data->last.D); return data->last.D; } int plfit_i_continuous_xmin_opt_progress(void* instance, double x, double fx, double min, double fmin, double left, double right, int k) { #ifdef PLFIT_DEBUG printf("Iteration #%d: [%.4f; %.4f), x=%.4f, fx=%.4f, min=%.4f, fmin=%.4f\n", k, left, right, x, fx, min, fmin); #endif /* Continue only if `left' and `right' point to different integers */ return (int)left == (int)right; } int plfit_continuous(double* xs, size_t n, const plfit_continuous_options_t* options, plfit_result_t* result) { gss_parameter_t gss_param; plfit_continuous_xmin_opt_data_t opt_data; plfit_result_t best_result; int success; size_t i, best_n, num_uniques; double x, *px; DATA_POINTS_CHECK; if (!options) options = &plfit_continuous_default_options; /* Make a copy of xs and sort it */ opt_data.begin = (double*)malloc(sizeof(double) * n); memcpy(opt_data.begin, xs, sizeof(double) * n); qsort(opt_data.begin, n, sizeof(double), double_comparator); opt_data.end = opt_data.begin + n; /* Create an array containing pointers to the unique elements of the input. From * each block of unique elements, we add the pointer to the first one. */ opt_data.uniques = unique_element_pointers(opt_data.begin, opt_data.end, &num_uniques); if (opt_data.uniques == 0) return PLFIT_ENOMEM; /* We will now determine the best xmin that yields the lowest D-score. * First we try a golden section search if needed. If that fails, we try * a linear search. */ if (options->xmin_method == PLFIT_GSS_OR_LINEAR && num_uniques > 5) { gss_parameter_init(&gss_param); success = (gss(0, num_uniques-5, &x, 0, plfit_i_continuous_xmin_opt_evaluate, plfit_i_continuous_xmin_opt_progress, &opt_data, &gss_param) == 0); best_result = opt_data.last; /* plfit_i_continuous_xmin_opt_evaluate will set opt_data.last to * indicate the location of the optimum and the value of D */ } else { success = 0; } if (success) { /* calculate best_n because we'll need it later. Luckily x indicates * the index in opt_data.uniques that we have to look up in order to * find the first element in the array that is included */ px = opt_data.uniques[(int)x]; best_n = (size_t) (opt_data.end-px+1); } else { /* GSS failed or skipped; try linear search */ /* Prepare some variables */ best_n = 0; best_result.D = DBL_MAX; best_result.xmin = 0; best_result.alpha = 0; for (i = 0; i < num_uniques-1; i++) { plfit_i_continuous_xmin_opt_evaluate(&opt_data, i); if (opt_data.last.D < best_result.D) { best_result = opt_data.last; best_n = (size_t) (opt_data.end - opt_data.uniques[i] + 1); } } } /* Get rid of the uniques array, we don't need it any more */ free(opt_data.uniques); /* Sort out the result */ *result = best_result; if (options->finite_size_correction) plfit_i_perform_finite_size_correction(result, best_n); result->p = plfit_ks_test_one_sample_p(result->D, best_n); plfit_log_likelihood_continuous(opt_data.begin + n - best_n, best_n, result->alpha, result->xmin, &result->L); /* Get rid of the copied data as well */ free(opt_data.begin); return PLFIT_SUCCESS; } /********** Discrete power law distribution fitting **********/ typedef struct { size_t m; double logsum; double xmin; } plfit_i_estimate_alpha_discrete_data_t; double plfit_i_logsum_discrete(double* begin, double* end, double xmin) { double logsum = 0.0; for (; begin != end; begin++) logsum += log(*begin); return logsum; } void plfit_i_logsum_less_than_discrete(double* begin, double* end, double xmin, double* logsum, size_t* m) { double result = 0.0; size_t count = 0; for (; begin != end; begin++) { if (*begin < xmin) continue; result += log(*begin); count++; } *logsum = result; *m = count; } lbfgsfloatval_t plfit_i_estimate_alpha_discrete_lbfgs_evaluate( void* instance, const lbfgsfloatval_t* x, lbfgsfloatval_t* g, const int n, const lbfgsfloatval_t step) { plfit_i_estimate_alpha_discrete_data_t* data; lbfgsfloatval_t result; double dx = step; double huge = 1e10; /* pseudo-infinity; apparently DBL_MAX does not work */ data = (plfit_i_estimate_alpha_discrete_data_t*)instance; #ifdef PLFIT_DEBUG printf("- Evaluating at %.4f (step = %.4f, xmin = %.4f)\n", *x, step, data->xmin); #endif if (isnan(*x)) { g[0] = huge; return huge; } /* Find the delta X value to estimate the gradient */ if (dx > 0.001 || dx == 0) dx = 0.001; else if (dx < -0.001) dx = -0.001; /* Is x[0] in its valid range? */ if (x[0] <= 1.0) { /* The Hurwitz zeta function is infinite in this case */ g[0] = (dx > 0) ? -huge : huge; return huge; } if (x[0] + dx <= 1.0) g[0] = huge; else g[0] = data->logsum + data->m * (log(gsl_sf_hzeta(x[0] + dx, data->xmin)) - log(gsl_sf_hzeta(x[0], data->xmin))) / dx; result = x[0] * data->logsum + data->m * log(gsl_sf_hzeta(x[0], data->xmin)); #ifdef PLFIT_DEBUG printf(" - Gradient: %.4f\n", g[0]); printf(" - Result: %.4f\n", result); #endif return result; } int plfit_i_estimate_alpha_discrete_lbfgs_progress(void* instance, const lbfgsfloatval_t* x, const lbfgsfloatval_t* g, const lbfgsfloatval_t fx, const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm, const lbfgsfloatval_t step, int n, int k, int ls) { return 0; } int plfit_i_estimate_alpha_discrete_linear_scan(double* xs, size_t n, double xmin, double* alpha, const plfit_discrete_options_t* options, plfit_bool_t sorted) { double curr_alpha, best_alpha, L, L_max; double logsum; size_t m; XMIN_CHECK_ONE; if (options->alpha.min <= 1.0) { PLFIT_ERROR("alpha.min must be greater than 1.0", PLFIT_EINVAL); } if (options->alpha.max < options->alpha.min) { PLFIT_ERROR("alpha.max must be greater than alpha.min", PLFIT_EINVAL); } if (options->alpha.step <= 0) { PLFIT_ERROR("alpha.step must be positive", PLFIT_EINVAL); } if (sorted) { logsum = plfit_i_logsum_discrete(xs, xs+n, xmin); m = n; } else { plfit_i_logsum_less_than_discrete(xs, xs+n, xmin, &logsum, &m); } best_alpha = options->alpha.min; L_max = -DBL_MAX; for (curr_alpha = options->alpha.min; curr_alpha <= options->alpha.max; curr_alpha += options->alpha.step) { L = -curr_alpha * logsum - m * log(gsl_sf_hzeta(curr_alpha, xmin)); if (L > L_max) { L_max = L; best_alpha = curr_alpha; } } *alpha = best_alpha; return PLFIT_SUCCESS; } int plfit_i_estimate_alpha_discrete_lbfgs(double* xs, size_t n, double xmin, double* alpha, const plfit_discrete_options_t* options, plfit_bool_t sorted) { lbfgs_parameter_t param; lbfgsfloatval_t* variables; plfit_i_estimate_alpha_discrete_data_t data; int ret; XMIN_CHECK_ONE; /* Initialize algorithm parameters */ lbfgs_parameter_init(¶m); param.max_iterations = 0; /* proceed until infinity */ /* Set up context for optimization */ data.xmin = xmin; if (sorted) { data.logsum = plfit_i_logsum_discrete(xs, xs+n, xmin); data.m = n; } else { plfit_i_logsum_less_than_discrete(xs, xs+n, xmin, &data.logsum, &data.m); } /* Allocate space for the single alpha variable */ variables = lbfgs_malloc(1); variables[0] = 3.0; /* initial guess */ /* Optimization */ ret = lbfgs(1, variables, /* ptr_fx = */ 0, plfit_i_estimate_alpha_discrete_lbfgs_evaluate, plfit_i_estimate_alpha_discrete_lbfgs_progress, &data, ¶m); if (ret < 0 && ret != LBFGSERR_ROUNDING_ERROR && ret != LBFGSERR_MAXIMUMLINESEARCH && ret != LBFGSERR_CANCELED) { char buf[4096]; snprintf(buf, 4096, "L-BFGS optimization signaled an error (error code = %d)", ret); lbfgs_free(variables); PLFIT_ERROR(buf, PLFIT_FAILURE); } *alpha = variables[0]; /* Deallocate the variable array */ lbfgs_free(variables); return PLFIT_SUCCESS; } int plfit_i_estimate_alpha_discrete_fast(double* xs, size_t n, double xmin, double* alpha, const plfit_discrete_options_t* options, plfit_bool_t sorted) { plfit_continuous_options_t cont_options; if (!options) options = &plfit_discrete_default_options; plfit_continuous_options_init(&cont_options); cont_options.finite_size_correction = options->finite_size_correction; XMIN_CHECK_ONE; if (sorted) { return plfit_i_estimate_alpha_continuous_sorted(xs, n, xmin-0.5, alpha); } else { return plfit_i_estimate_alpha_continuous(xs, n, xmin-0.5, alpha); } } int plfit_i_estimate_alpha_discrete(double* xs, size_t n, double xmin, double* alpha, const plfit_discrete_options_t* options, plfit_bool_t sorted) { switch (options->alpha_method) { case PLFIT_LBFGS: PLFIT_CHECK(plfit_i_estimate_alpha_discrete_lbfgs(xs, n, xmin, alpha, options, sorted)); break; case PLFIT_LINEAR_SCAN: PLFIT_CHECK(plfit_i_estimate_alpha_discrete_linear_scan(xs, n, xmin, alpha, options, sorted)); break; case PLFIT_PRETEND_CONTINUOUS: PLFIT_CHECK(plfit_i_estimate_alpha_discrete_fast(xs, n, xmin, alpha, options, sorted)); break; default: PLFIT_ERROR("unknown optimization method specified", PLFIT_EINVAL); } return PLFIT_SUCCESS; } static int plfit_i_ks_test_discrete(double* xs, double* xs_end, const double alpha, const double xmin, double* D) { /* Assumption: xs is sorted and cut off at xmin so the first element is * always larger than or equal to xmin. */ double result = 0, n, hzeta, x; int m = 0; n = xs_end - xs; hzeta = gsl_sf_hzeta(alpha, xmin); while (xs < xs_end) { double d; x = *xs; d = fabs(1-(gsl_sf_hzeta(alpha, x) / hzeta) - m / n); if (d > result) result = d; do { xs++; m++; } while (xs < xs_end && *xs == x); } *D = result; return PLFIT_SUCCESS; } int plfit_log_likelihood_discrete(double* xs, size_t n, double alpha, double xmin, double* L) { double result; size_t m; if (alpha <= 1) { PLFIT_ERROR("alpha must be greater than one", PLFIT_EINVAL); } XMIN_CHECK_ONE; plfit_i_logsum_less_than_discrete(xs, xs+n, xmin, &result, &m); result = - alpha * result - m * log(gsl_sf_hzeta(alpha, xmin)); *L = result; return PLFIT_SUCCESS; } int plfit_estimate_alpha_discrete(double* xs, size_t n, double xmin, const plfit_discrete_options_t* options, plfit_result_t *result) { double *xs_copy, *end; if (!options) options = &plfit_discrete_default_options; /* Check the validity of the input parameters */ DATA_POINTS_CHECK; if (options->alpha_method == PLFIT_LINEAR_SCAN) { if (options->alpha.min <= 1.0) { PLFIT_ERROR("alpha.min must be greater than 1.0", PLFIT_EINVAL); } if (options->alpha.max < options->alpha.min) { PLFIT_ERROR("alpha.max must be greater than alpha.min", PLFIT_EINVAL); } if (options->alpha.step <= 0) { PLFIT_ERROR("alpha.step must be positive", PLFIT_EINVAL); } } /* Make a copy of xs and sort it */ xs_copy = (double*)malloc(sizeof(double) * n); memcpy(xs_copy, xs, sizeof(double) * n); qsort(xs_copy, n, sizeof(double), double_comparator); xs = xs_copy; end = xs_copy + n; while (xs < end && *xs < xmin) xs++; n = (size_t) (end - xs); PLFIT_CHECK(plfit_i_estimate_alpha_discrete(xs, n, xmin, &result->alpha, options, /* sorted = */ 1)); PLFIT_CHECK(plfit_i_ks_test_discrete(xs, end, result->alpha, xmin, &result->D)); result->xmin = xmin; if (options->finite_size_correction) plfit_i_perform_finite_size_correction(result, n); result->p = plfit_ks_test_one_sample_p(result->D, n); plfit_log_likelihood_discrete(xs, n, result->alpha, result->xmin, &result->L); free(xs_copy); return PLFIT_SUCCESS; } int plfit_discrete(double* xs, size_t n, const plfit_discrete_options_t* options, plfit_result_t* result) { double curr_D, curr_alpha; plfit_result_t best_result; double *xs_copy, *px, *end, *end_xmin, prev_x; size_t best_n; size_t m; if (!options) options = &plfit_discrete_default_options; /* Check the validity of the input parameters */ DATA_POINTS_CHECK; if (options->alpha_method == PLFIT_LINEAR_SCAN) { if (options->alpha.min <= 1.0) { PLFIT_ERROR("alpha.min must be greater than 1.0", PLFIT_EINVAL); } if (options->alpha.max < options->alpha.min) { PLFIT_ERROR("alpha.max must be greater than alpha.min", PLFIT_EINVAL); } if (options->alpha.step <= 0) { PLFIT_ERROR("alpha.step must be positive", PLFIT_EINVAL); } } /* Make a copy of xs and sort it */ xs_copy = (double*)malloc(sizeof(double) * n); memcpy(xs_copy, xs, sizeof(double) * n); qsort(xs_copy, n, sizeof(double), double_comparator); best_result.D = DBL_MAX; best_result.xmin = 1; best_result.alpha = 1; best_n = 0; /* Make sure there are at least three distinct values if possible */ px = xs_copy; end = px + n; end_xmin = end - 1; m = 0; prev_x = *end_xmin; while (*end_xmin == prev_x && end_xmin > px) end_xmin--; prev_x = *end_xmin; while (*end_xmin == prev_x && end_xmin > px) end_xmin--; prev_x = 0; while (px < end_xmin) { while (px < end_xmin && *px == prev_x) { px++; m++; } plfit_i_estimate_alpha_discrete(px, n - m, *px, &curr_alpha, options, /* sorted = */ 1); plfit_i_ks_test_discrete(px, end, curr_alpha, *px, &curr_D); if (curr_D < best_result.D) { best_result.alpha = curr_alpha; best_result.xmin = *px; best_result.D = curr_D; best_n = n - m; } prev_x = *px; px++; m++; } *result = best_result; if (options->finite_size_correction) plfit_i_perform_finite_size_correction(result, best_n); result->p = plfit_ks_test_one_sample_p(result->D, best_n); plfit_log_likelihood_discrete(xs_copy+(n-best_n), best_n, result->alpha, result->xmin, &result->L); free(xs_copy); return PLFIT_SUCCESS; } igraph/src/plfit/kolmogorov.h0000644000175100001440000000234613431000472016015 0ustar hornikusers/* kolmogorov.h * * Copyright (C) 2010-2011 Tamas Nepusz * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __KOLMOGOROV_H__ #define __KOLMOGOROV_H__ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #include __BEGIN_DECLS double plfit_kolmogorov(double z); double plfit_ks_test_one_sample_p(double d, size_t n); double plfit_ks_test_two_sample_p(double d, size_t n1, size_t n2); __END_DECLS #endif igraph/src/plfit/lbfgs.c0000644000175100001440000012036013431000472014704 0ustar hornikusers/* * Limited memory BFGS (L-BFGS). * * Copyright (c) 1990, Jorge Nocedal * Copyright (c) 2007-2010 Naoaki Okazaki * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* $Id: lbfgs.c 65 2010-01-29 12:19:16Z naoaki $ */ /* This library is a C port of the FORTRAN implementation of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) method written by Jorge Nocedal. The original FORTRAN source code is available at: http://www.ece.northwestern.edu/~nocedal/lbfgs.html The L-BFGS algorithm is described in: - Jorge Nocedal. Updating Quasi-Newton Matrices with Limited Storage. Mathematics of Computation, Vol. 35, No. 151, pp. 773--782, 1980. - Dong C. Liu and Jorge Nocedal. On the limited memory BFGS method for large scale optimization. Mathematical Programming B, Vol. 45, No. 3, pp. 503-528, 1989. The line search algorithms used in this implementation are described in: - John E. Dennis and Robert B. Schnabel. Numerical Methods for Unconstrained Optimization and Nonlinear Equations, Englewood Cliffs, 1983. - Jorge J. More and David J. Thuente. Line search algorithm with guaranteed sufficient decrease. ACM Transactions on Mathematical Software (TOMS), Vol. 20, No. 3, pp. 286-307, 1994. This library also implements Orthant-Wise Limited-memory Quasi-Newton (OWL-QN) method presented in: - Galen Andrew and Jianfeng Gao. Scalable training of L1-regularized log-linear models. In Proceedings of the 24th International Conference on Machine Learning (ICML 2007), pp. 33-40, 2007. I would like to thank the original author, Jorge Nocedal, who has been distributing the effieicnt and explanatory implementation in an open source licence. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif/*HAVE_CONFIG_H*/ #ifndef _MSC_VER #include #endif #include #include #include #include "lbfgs.h" #ifdef _MSC_VER #define inline __inline typedef unsigned int uint32_t; #endif/*_MSC_VER*/ #if defined(USE_SSE) && defined(__SSE2__) && LBFGS_FLOAT == 64 /* Use SSE2 optimization for 64bit double precision. */ #include "arithmetic_sse_double.h" #elif defined(USE_SSE) && defined(__SSE__) && LBFGS_FLOAT == 32 /* Use SSE optimization for 32bit float precision. */ #include "arithmetic_sse_float.h" #else /* No CPU specific optimization. */ #include "arithmetic_ansi.h" #endif #define min2(a, b) ((a) <= (b) ? (a) : (b)) #define max2(a, b) ((a) >= (b) ? (a) : (b)) #define max3(a, b, c) max2(max2((a), (b)), (c)); #define is_aligned(p, bytes) \ (((uintptr_t)(const void*)(p)) % (bytes) == 0) struct tag_callback_data { int n; void *instance; lbfgs_evaluate_t proc_evaluate; lbfgs_progress_t proc_progress; }; typedef struct tag_callback_data callback_data_t; struct tag_iteration_data { lbfgsfloatval_t alpha; lbfgsfloatval_t *s; /* [n] */ lbfgsfloatval_t *y; /* [n] */ lbfgsfloatval_t ys; /* vecdot(y, s) */ }; typedef struct tag_iteration_data iteration_data_t; static const lbfgs_parameter_t _defparam = { 6, 1e-5, 0, 1e-5, 0, LBFGS_LINESEARCH_DEFAULT, 40, 1e-20, 1e20, 1e-4, 0.9, 0.9, 1.0e-16, 0.0, 0, -1, }; /* Forward function declarations. */ typedef int (*line_search_proc)( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wa, callback_data_t *cd, const lbfgs_parameter_t *param ); static int line_search_backtracking( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wa, callback_data_t *cd, const lbfgs_parameter_t *param ); static int line_search_backtracking_owlqn( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wp, callback_data_t *cd, const lbfgs_parameter_t *param ); static int line_search_morethuente( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wa, callback_data_t *cd, const lbfgs_parameter_t *param ); static int update_trial_interval( lbfgsfloatval_t *x, lbfgsfloatval_t *fx, lbfgsfloatval_t *dx, lbfgsfloatval_t *y, lbfgsfloatval_t *fy, lbfgsfloatval_t *dy, lbfgsfloatval_t *t, lbfgsfloatval_t *ft, lbfgsfloatval_t *dt, const lbfgsfloatval_t tmin, const lbfgsfloatval_t tmax, int *brackt ); static lbfgsfloatval_t owlqn_x1norm( const lbfgsfloatval_t* x, const int start, const int n ); static void owlqn_pseudo_gradient( lbfgsfloatval_t* pg, const lbfgsfloatval_t* x, const lbfgsfloatval_t* g, const int n, const lbfgsfloatval_t c, const int start, const int end ); static void owlqn_project( lbfgsfloatval_t* d, const lbfgsfloatval_t* sign, const int start, const int end ); #if defined(USE_SSE) && (defined(__SSE__) || defined(__SSE2__)) static int round_out_variables(int n) { n += 7; n /= 8; n *= 8; return n; } #endif/*defined(USE_SSE)*/ lbfgsfloatval_t* lbfgs_malloc(int n) { #if defined(USE_SSE) && (defined(__SSE__) || defined(__SSE2__)) n = round_out_variables(n); #endif/*defined(USE_SSE)*/ return (lbfgsfloatval_t*)vecalloc(sizeof(lbfgsfloatval_t) * (size_t) n); } void lbfgs_free(lbfgsfloatval_t *x) { vecfree(x); } void lbfgs_parameter_init(lbfgs_parameter_t *param) { memcpy(param, &_defparam, sizeof(*param)); } int lbfgs( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *ptr_fx, lbfgs_evaluate_t proc_evaluate, lbfgs_progress_t proc_progress, void *instance, lbfgs_parameter_t *_param ) { int ret; int i, j, k, ls, end, bound; lbfgsfloatval_t step; /* Constant parameters and their default values. */ lbfgs_parameter_t param = (_param != NULL) ? (*_param) : _defparam; const int m = param.m; lbfgsfloatval_t *xp = NULL; lbfgsfloatval_t *g = NULL, *gp = NULL, *pg = NULL; lbfgsfloatval_t *d = NULL, *w = NULL, *pf = NULL; iteration_data_t *lm = NULL, *it = NULL; lbfgsfloatval_t ys, yy; lbfgsfloatval_t xnorm, gnorm, beta; lbfgsfloatval_t fx = 0.; lbfgsfloatval_t rate = 0.; line_search_proc linesearch = line_search_morethuente; /* Construct a callback data. */ callback_data_t cd; cd.n = n; cd.instance = instance; cd.proc_evaluate = proc_evaluate; cd.proc_progress = proc_progress; #if defined(USE_SSE) && (defined(__SSE__) || defined(__SSE2__)) /* Round out the number of variables. */ n = round_out_variables(n); #endif/*defined(USE_SSE)*/ /* Check the input parameters for errors. */ if (n <= 0) { return LBFGSERR_INVALID_N; } #if defined(USE_SSE) && (defined(__SSE__) || defined(__SSE2__)) if (n % 8 != 0) { return LBFGSERR_INVALID_N_SSE; } if (!is_aligned(x, 16)) { return LBFGSERR_INVALID_X_SSE; } #endif/*defined(USE_SSE)*/ if (param.epsilon < 0.) { return LBFGSERR_INVALID_EPSILON; } if (param.past < 0) { return LBFGSERR_INVALID_TESTPERIOD; } if (param.delta < 0.) { return LBFGSERR_INVALID_DELTA; } if (param.min_step < 0.) { return LBFGSERR_INVALID_MINSTEP; } if (param.max_step < param.min_step) { return LBFGSERR_INVALID_MAXSTEP; } if (param.ftol < 0.) { return LBFGSERR_INVALID_FTOL; } if (param.linesearch == LBFGS_LINESEARCH_BACKTRACKING_WOLFE || param.linesearch == LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE) { if (param.wolfe <= param.ftol || 1. <= param.wolfe) { return LBFGSERR_INVALID_WOLFE; } } if (param.gtol < 0.) { return LBFGSERR_INVALID_GTOL; } if (param.xtol < 0.) { return LBFGSERR_INVALID_XTOL; } if (param.max_linesearch <= 0) { return LBFGSERR_INVALID_MAXLINESEARCH; } if (param.orthantwise_c < 0.) { return LBFGSERR_INVALID_ORTHANTWISE; } if (param.orthantwise_start < 0 || n < param.orthantwise_start) { return LBFGSERR_INVALID_ORTHANTWISE_START; } if (param.orthantwise_end < 0) { param.orthantwise_end = n; } if (n < param.orthantwise_end) { return LBFGSERR_INVALID_ORTHANTWISE_END; } if (param.orthantwise_c != 0.) { switch (param.linesearch) { case LBFGS_LINESEARCH_BACKTRACKING: linesearch = line_search_backtracking_owlqn; break; default: /* Only the backtracking method is available. */ return LBFGSERR_INVALID_LINESEARCH; } } else { switch (param.linesearch) { case LBFGS_LINESEARCH_MORETHUENTE: linesearch = line_search_morethuente; break; case LBFGS_LINESEARCH_BACKTRACKING_ARMIJO: case LBFGS_LINESEARCH_BACKTRACKING_WOLFE: case LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE: linesearch = line_search_backtracking; break; default: return LBFGSERR_INVALID_LINESEARCH; } } /* Allocate working space. */ xp = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); g = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); gp = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); d = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); w = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); if (xp == NULL || g == NULL || gp == NULL || d == NULL || w == NULL) { ret = LBFGSERR_OUTOFMEMORY; goto lbfgs_exit; } if (param.orthantwise_c != 0.) { /* Allocate working space for OW-LQN. */ pg = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); if (pg == NULL) { ret = LBFGSERR_OUTOFMEMORY; goto lbfgs_exit; } } /* Allocate limited memory storage. */ lm = (iteration_data_t*)vecalloc((size_t) m * sizeof(iteration_data_t)); if (lm == NULL) { ret = LBFGSERR_OUTOFMEMORY; goto lbfgs_exit; } /* Initialize the limited memory. */ for (i = 0;i < m;++i) { it = &lm[i]; it->alpha = 0; it->ys = 0; it->s = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); it->y = (lbfgsfloatval_t*)vecalloc((size_t) n * sizeof(lbfgsfloatval_t)); if (it->s == NULL || it->y == NULL) { ret = LBFGSERR_OUTOFMEMORY; goto lbfgs_exit; } } /* Allocate an array for storing previous values of the objective function. */ if (0 < param.past) { pf = (lbfgsfloatval_t*)vecalloc((size_t) param.past * sizeof(lbfgsfloatval_t)); } /* Evaluate the function value and its gradient. */ fx = cd.proc_evaluate(cd.instance, x, g, cd.n, 0); if (0. != param.orthantwise_c) { /* Compute the L1 norm of the variable and add it to the object value. */ xnorm = owlqn_x1norm(x, param.orthantwise_start, param.orthantwise_end); fx += xnorm * param.orthantwise_c; owlqn_pseudo_gradient( pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end ); } /* Store the initial value of the objective function. */ if (pf != NULL) { pf[0] = fx; } /* Compute the direction; we assume the initial hessian matrix H_0 as the identity matrix. */ if (param.orthantwise_c == 0.) { vecncpy(d, g, n); } else { vecncpy(d, pg, n); } /* Make sure that the initial variables are not a minimizer. */ vec2norm(&xnorm, x, n); if (param.orthantwise_c == 0.) { vec2norm(&gnorm, g, n); } else { vec2norm(&gnorm, pg, n); } if (xnorm < 1.0) xnorm = 1.0; if (gnorm / xnorm <= param.epsilon) { ret = LBFGS_ALREADY_MINIMIZED; goto lbfgs_exit; } /* Compute the initial step: step = 1.0 / sqrt(vecdot(d, d, n)) */ vec2norminv(&step, d, n); k = 1; end = 0; for (;;) { /* Store the current position and gradient vectors. */ veccpy(xp, x, n); veccpy(gp, g, n); /* Search for an optimal step. */ if (param.orthantwise_c == 0.) { ls = linesearch(n, x, &fx, g, d, &step, xp, gp, w, &cd, ¶m); } else { ls = linesearch(n, x, &fx, g, d, &step, xp, pg, w, &cd, ¶m); owlqn_pseudo_gradient( pg, x, g, n, param.orthantwise_c, param.orthantwise_start, param.orthantwise_end ); } if (ls < 0) { /* Revert to the previous point. */ veccpy(x, xp, n); veccpy(g, gp, n); ret = ls; goto lbfgs_exit; } /* Compute x and g norms. */ vec2norm(&xnorm, x, n); if (param.orthantwise_c == 0.) { vec2norm(&gnorm, g, n); } else { vec2norm(&gnorm, pg, n); } /* Report the progress. */ if (cd.proc_progress) { if ((ret = cd.proc_progress(cd.instance, x, g, fx, xnorm, gnorm, step, cd.n, k, ls))) { goto lbfgs_exit; } } /* Convergence test. The criterion is given by the following formula: |g(x)| / \max(1, |x|) < \epsilon */ if (xnorm < 1.0) xnorm = 1.0; if (gnorm / xnorm <= param.epsilon) { /* Convergence. */ ret = LBFGS_SUCCESS; break; } /* Test for stopping criterion. The criterion is given by the following formula: (f(past_x) - f(x)) / f(x) < \delta */ if (pf != NULL) { /* We don't test the stopping criterion while k < past. */ if (param.past <= k) { /* Compute the relative improvement from the past. */ rate = (pf[k % param.past] - fx) / fx; /* The stopping criterion. */ if (rate < param.delta) { ret = LBFGS_STOP; break; } } /* Store the current value of the objective function. */ pf[k % param.past] = fx; } if (param.max_iterations != 0 && param.max_iterations < k+1) { /* Maximum number of iterations. */ ret = LBFGSERR_MAXIMUMITERATION; break; } /* Update vectors s and y: s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}. y_{k+1} = g_{k+1} - g_{k}. */ it = &lm[end]; vecdiff(it->s, x, xp, n); vecdiff(it->y, g, gp, n); /* Compute scalars ys and yy: ys = y^t \cdot s = 1 / \rho. yy = y^t \cdot y. Notice that yy is used for scaling the hessian matrix H_0 (Cholesky factor). */ vecdot(&ys, it->y, it->s, n); vecdot(&yy, it->y, it->y, n); it->ys = ys; /* Recursive formula to compute dir = -(H \cdot g). This is described in page 779 of: Jorge Nocedal. Updating Quasi-Newton Matrices with Limited Storage. Mathematics of Computation, Vol. 35, No. 151, pp. 773--782, 1980. */ bound = (m <= k) ? m : k; ++k; end = (end + 1) % m; /* Compute the steepest direction. */ if (param.orthantwise_c == 0.) { /* Compute the negative of gradients. */ vecncpy(d, g, n); } else { vecncpy(d, pg, n); } j = end; for (i = 0;i < bound;++i) { j = (j + m - 1) % m; /* if (--j == -1) j = m-1; */ it = &lm[j]; /* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */ vecdot(&it->alpha, it->s, d, n); it->alpha /= it->ys; /* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */ vecadd(d, it->y, -it->alpha, n); } vecscale(d, ys / yy, n); for (i = 0;i < bound;++i) { it = &lm[j]; /* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}. */ vecdot(&beta, it->y, d, n); beta /= it->ys; /* \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */ vecadd(d, it->s, it->alpha - beta, n); j = (j + 1) % m; /* if (++j == m) j = 0; */ } /* Constrain the search direction for orthant-wise updates. */ if (param.orthantwise_c != 0.) { for (i = param.orthantwise_start;i < param.orthantwise_end;++i) { if (d[i] * pg[i] >= 0) { d[i] = 0; } } } /* Now the search direction d is ready. We try step = 1 first. */ step = 1.0; } lbfgs_exit: /* Return the final value of the objective function. */ if (ptr_fx != NULL) { *ptr_fx = fx; } vecfree(pf); /* Free memory blocks used by this function. */ if (lm != NULL) { for (i = 0;i < m;++i) { vecfree(lm[i].s); vecfree(lm[i].y); } vecfree(lm); } vecfree(pg); vecfree(w); vecfree(d); vecfree(gp); vecfree(g); vecfree(xp); return ret; } static int line_search_backtracking( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wp, callback_data_t *cd, const lbfgs_parameter_t *param ) { int count = 0; lbfgsfloatval_t width, dg; lbfgsfloatval_t finit, dginit = 0., dgtest; const lbfgsfloatval_t dec = 0.5, inc = 2.1; /* Check the input parameters for errors. */ if (*stp <= 0.) { return LBFGSERR_INVALIDPARAMETERS; } /* Compute the initial gradient in the search direction. */ vecdot(&dginit, g, s, n); /* Make sure that s points to a descent direction. */ if (0 < dginit) { return LBFGSERR_INCREASEGRADIENT; } /* The initial value of the objective function. */ finit = *f; dgtest = param->ftol * dginit; for (;;) { veccpy(x, xp, n); vecadd(x, s, *stp, n); /* Evaluate the function and gradient values. */ *f = cd->proc_evaluate(cd->instance, x, g, cd->n, *stp); ++count; if (*f > finit + *stp * dgtest) { width = dec; } else { /* The sufficient decrease condition (Armijo condition). */ if (param->linesearch == LBFGS_LINESEARCH_BACKTRACKING_ARMIJO) { /* Exit with the Armijo condition. */ return count; } /* Check the Wolfe condition. */ vecdot(&dg, g, s, n); if (dg < param->wolfe * dginit) { width = inc; } else { if(param->linesearch == LBFGS_LINESEARCH_BACKTRACKING_WOLFE) { /* Exit with the regular Wolfe condition. */ return count; } /* Check the strong Wolfe condition. */ if(dg > -param->wolfe * dginit) { width = dec; } else { /* Exit with the strong Wolfe condition. */ return count; } } } if (*stp < param->min_step) { /* The step is the minimum value. */ return LBFGSERR_MINIMUMSTEP; } if (*stp > param->max_step) { /* The step is the maximum value. */ return LBFGSERR_MAXIMUMSTEP; } if (param->max_linesearch <= count) { /* Maximum number of iteration. */ return LBFGSERR_MAXIMUMLINESEARCH; } (*stp) *= width; } } static int line_search_backtracking_owlqn( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wp, callback_data_t *cd, const lbfgs_parameter_t *param ) { int i, count = 0; lbfgsfloatval_t width = 0.5, norm = 0.; lbfgsfloatval_t finit = *f, dgtest; /* Check the input parameters for errors. */ if (*stp <= 0.) { return LBFGSERR_INVALIDPARAMETERS; } /* Choose the orthant for the new point. */ for (i = 0;i < n;++i) { wp[i] = (xp[i] == 0.) ? -gp[i] : xp[i]; } for (;;) { /* Update the current point. */ veccpy(x, xp, n); vecadd(x, s, *stp, n); /* The current point is projected onto the orthant. */ owlqn_project(x, wp, param->orthantwise_start, param->orthantwise_end); /* Evaluate the function and gradient values. */ *f = cd->proc_evaluate(cd->instance, x, g, cd->n, *stp); /* Compute the L1 norm of the variables and add it to the object value. */ norm = owlqn_x1norm(x, param->orthantwise_start, param->orthantwise_end); *f += norm * param->orthantwise_c; ++count; dgtest = 0.; for (i = 0;i < n;++i) { dgtest += (x[i] - xp[i]) * gp[i]; } if (*f <= finit + param->ftol * dgtest) { /* The sufficient decrease condition. */ return count; } if (*stp < param->min_step) { /* The step is the minimum value. */ return LBFGSERR_MINIMUMSTEP; } if (*stp > param->max_step) { /* The step is the maximum value. */ return LBFGSERR_MAXIMUMSTEP; } if (param->max_linesearch <= count) { /* Maximum number of iteration. */ return LBFGSERR_MAXIMUMLINESEARCH; } (*stp) *= width; } } static int line_search_morethuente( int n, lbfgsfloatval_t *x, lbfgsfloatval_t *f, lbfgsfloatval_t *g, lbfgsfloatval_t *s, lbfgsfloatval_t *stp, const lbfgsfloatval_t* xp, const lbfgsfloatval_t* gp, lbfgsfloatval_t *wa, callback_data_t *cd, const lbfgs_parameter_t *param ) { int count = 0; int brackt, stage1, uinfo = 0; lbfgsfloatval_t dg; lbfgsfloatval_t stx, fx, dgx; lbfgsfloatval_t sty, fy, dgy; lbfgsfloatval_t fxm, dgxm, fym, dgym, fm, dgm; lbfgsfloatval_t finit, ftest1, dginit, dgtest; lbfgsfloatval_t width, prev_width; lbfgsfloatval_t stmin, stmax; /* Check the input parameters for errors. */ if (*stp <= 0.) { return LBFGSERR_INVALIDPARAMETERS; } /* Compute the initial gradient in the search direction. */ vecdot(&dginit, g, s, n); /* Make sure that s points to a descent direction. */ if (0 < dginit) { return LBFGSERR_INCREASEGRADIENT; } /* Initialize local variables. */ brackt = 0; stage1 = 1; finit = *f; dgtest = param->ftol * dginit; width = param->max_step - param->min_step; prev_width = 2.0 * width; /* The variables stx, fx, dgx contain the values of the step, function, and directional derivative at the best step. The variables sty, fy, dgy contain the value of the step, function, and derivative at the other endpoint of the interval of uncertainty. The variables stp, f, dg contain the values of the step, function, and derivative at the current step. */ stx = sty = 0.; fx = fy = finit; dgx = dgy = dginit; for (;;) { /* Set the minimum and maximum steps to correspond to the present interval of uncertainty. */ if (brackt) { stmin = min2(stx, sty); stmax = max2(stx, sty); } else { stmin = stx; stmax = *stp + 4.0 * (*stp - stx); } /* Clip the step in the range of [stpmin, stpmax]. */ if (*stp < param->min_step) *stp = param->min_step; if (param->max_step < *stp) *stp = param->max_step; /* If an unusual termination is to occur then let stp be the lowest point obtained so far. */ if ((brackt && ((*stp <= stmin || stmax <= *stp) || param->max_linesearch <= count + 1 || uinfo != 0)) || (brackt && (stmax - stmin <= param->xtol * stmax))) { *stp = stx; } /* Compute the current value of x: x <- x + (*stp) * s. */ veccpy(x, xp, n); vecadd(x, s, *stp, n); /* Evaluate the function and gradient values. */ *f = cd->proc_evaluate(cd->instance, x, g, cd->n, *stp); vecdot(&dg, g, s, n); ftest1 = finit + *stp * dgtest; ++count; /* Test for errors and convergence. */ if (brackt && ((*stp <= stmin || stmax <= *stp) || uinfo != 0)) { /* Rounding errors prevent further progress. */ return LBFGSERR_ROUNDING_ERROR; } if (*stp == param->max_step && *f <= ftest1 && dg <= dgtest) { /* The step is the maximum value. */ return LBFGSERR_MAXIMUMSTEP; } if (*stp == param->min_step && (ftest1 < *f || dgtest <= dg)) { /* The step is the minimum value. */ return LBFGSERR_MINIMUMSTEP; } if (brackt && (stmax - stmin) <= param->xtol * stmax) { /* Relative width of the interval of uncertainty is at most xtol. */ return LBFGSERR_WIDTHTOOSMALL; } if (param->max_linesearch <= count) { /* Maximum number of iteration. */ return LBFGSERR_MAXIMUMLINESEARCH; } if (*f <= ftest1 && fabs(dg) <= param->gtol * (-dginit)) { /* The sufficient decrease condition and the directional derivative condition hold. */ return count; } /* In the first stage we seek a step for which the modified function has a nonpositive value and nonnegative derivative. */ if (stage1 && *f <= ftest1 && min2(param->ftol, param->gtol) * dginit <= dg) { stage1 = 0; } /* A modified function is used to predict the step only if we have not obtained a step for which the modified function has a nonpositive function value and nonnegative derivative, and if a lower function value has been obtained but the decrease is not sufficient. */ if (stage1 && ftest1 < *f && *f <= fx) { /* Define the modified function and derivative values. */ fm = *f - *stp * dgtest; fxm = fx - stx * dgtest; fym = fy - sty * dgtest; dgm = dg - dgtest; dgxm = dgx - dgtest; dgym = dgy - dgtest; /* Call update_trial_interval() to update the interval of uncertainty and to compute the new step. */ uinfo = update_trial_interval( &stx, &fxm, &dgxm, &sty, &fym, &dgym, stp, &fm, &dgm, stmin, stmax, &brackt ); /* Reset the function and gradient values for f. */ fx = fxm + stx * dgtest; fy = fym + sty * dgtest; dgx = dgxm + dgtest; dgy = dgym + dgtest; } else { /* Call update_trial_interval() to update the interval of uncertainty and to compute the new step. */ uinfo = update_trial_interval( &stx, &fx, &dgx, &sty, &fy, &dgy, stp, f, &dg, stmin, stmax, &brackt ); } /* Force a sufficient decrease in the interval of uncertainty. */ if (brackt) { if (0.66 * prev_width <= fabs(sty - stx)) { *stp = stx + 0.5 * (sty - stx); } prev_width = width; width = fabs(sty - stx); } } return LBFGSERR_LOGICERROR; } /** * Define the local variables for computing minimizers. */ #define USES_MINIMIZER \ lbfgsfloatval_t a, d, gamma, theta, p, q, r, s; /** * Find a minimizer of an interpolated cubic function. * @param cm The minimizer of the interpolated cubic. * @param u The value of one point, u. * @param fu The value of f(u). * @param du The value of f'(u). * @param v The value of another point, v. * @param fv The value of f(v). * @param du The value of f'(v). */ #define CUBIC_MINIMIZER(cm, u, fu, du, v, fv, dv) \ d = (v) - (u); \ theta = ((fu) - (fv)) * 3 / d + (du) + (dv); \ p = fabs(theta); \ q = fabs(du); \ r = fabs(dv); \ s = max3(p, q, r); \ /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ \ a = theta / s; \ gamma = s * sqrt(a * a - ((du) / s) * ((dv) / s)); \ if ((v) < (u)) gamma = -gamma; \ p = gamma - (du) + theta; \ q = gamma - (du) + gamma + (dv); \ r = p / q; \ (cm) = (u) + r * d; /** * Find a minimizer of an interpolated cubic function. * @param cm The minimizer of the interpolated cubic. * @param u The value of one point, u. * @param fu The value of f(u). * @param du The value of f'(u). * @param v The value of another point, v. * @param fv The value of f(v). * @param du The value of f'(v). * @param xmin The maximum value. * @param xmin The minimum value. */ #define CUBIC_MINIMIZER2(cm, u, fu, du, v, fv, dv, xmin, xmax) \ d = (v) - (u); \ theta = ((fu) - (fv)) * 3 / d + (du) + (dv); \ p = fabs(theta); \ q = fabs(du); \ r = fabs(dv); \ s = max3(p, q, r); \ /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ \ a = theta / s; \ gamma = s * sqrt(max2(0, a * a - ((du) / s) * ((dv) / s))); \ if ((u) < (v)) gamma = -gamma; \ p = gamma - (dv) + theta; \ q = gamma - (dv) + gamma + (du); \ r = p / q; \ if (r < 0. && gamma != 0.) { \ (cm) = (v) - r * d; \ } else if (a < 0) { \ (cm) = (xmax); \ } else { \ (cm) = (xmin); \ } /** * Find a minimizer of an interpolated quadratic function. * @param qm The minimizer of the interpolated quadratic. * @param u The value of one point, u. * @param fu The value of f(u). * @param du The value of f'(u). * @param v The value of another point, v. * @param fv The value of f(v). */ #define QUARD_MINIMIZER(qm, u, fu, du, v, fv) \ a = (v) - (u); \ (qm) = (u) + (du) / (((fu) - (fv)) / a + (du)) / 2 * a; /** * Find a minimizer of an interpolated quadratic function. * @param qm The minimizer of the interpolated quadratic. * @param u The value of one point, u. * @param du The value of f'(u). * @param v The value of another point, v. * @param dv The value of f'(v). */ #define QUARD_MINIMIZER2(qm, u, du, v, dv) \ a = (u) - (v); \ (qm) = (v) + (dv) / ((dv) - (du)) * a; /** * Update a safeguarded trial value and interval for line search. * * The parameter x represents the step with the least function value. * The parameter t represents the current step. This function assumes * that the derivative at the point of x in the direction of the step. * If the bracket is set to true, the minimizer has been bracketed in * an interval of uncertainty with endpoints between x and y. * * @param x The pointer to the value of one endpoint. * @param fx The pointer to the value of f(x). * @param dx The pointer to the value of f'(x). * @param y The pointer to the value of another endpoint. * @param fy The pointer to the value of f(y). * @param dy The pointer to the value of f'(y). * @param t The pointer to the value of the trial value, t. * @param ft The pointer to the value of f(t). * @param dt The pointer to the value of f'(t). * @param tmin The minimum value for the trial value, t. * @param tmax The maximum value for the trial value, t. * @param brackt The pointer to the predicate if the trial value is * bracketed. * @retval int Status value. Zero indicates a normal termination. * * @see * Jorge J. More and David J. Thuente. Line search algorithm with * guaranteed sufficient decrease. ACM Transactions on Mathematical * Software (TOMS), Vol 20, No 3, pp. 286-307, 1994. */ static int update_trial_interval( lbfgsfloatval_t *x, lbfgsfloatval_t *fx, lbfgsfloatval_t *dx, lbfgsfloatval_t *y, lbfgsfloatval_t *fy, lbfgsfloatval_t *dy, lbfgsfloatval_t *t, lbfgsfloatval_t *ft, lbfgsfloatval_t *dt, const lbfgsfloatval_t tmin, const lbfgsfloatval_t tmax, int *brackt ) { int bound; int dsign = fsigndiff(dt, dx); lbfgsfloatval_t mc; /* minimizer of an interpolated cubic. */ lbfgsfloatval_t mq; /* minimizer of an interpolated quadratic. */ lbfgsfloatval_t newt; /* new trial value. */ USES_MINIMIZER; /* for CUBIC_MINIMIZER and QUARD_MINIMIZER. */ /* Check the input parameters for errors. */ if (*brackt) { if (*t <= min2(*x, *y) || max2(*x, *y) <= *t) { /* The trival value t is out of the interval. */ return LBFGSERR_OUTOFINTERVAL; } if (0. <= *dx * (*t - *x)) { /* The function must decrease from x. */ return LBFGSERR_INCREASEGRADIENT; } if (tmax < tmin) { /* Incorrect tmin and tmax specified. */ return LBFGSERR_INCORRECT_TMINMAX; } } /* Trial value selection. */ if (*fx < *ft) { /* Case 1: a higher function value. The minimum is brackt. If the cubic minimizer is closer to x than the quadratic one, the cubic one is taken, else the average of the minimizers is taken. */ *brackt = 1; bound = 1; CUBIC_MINIMIZER(mc, *x, *fx, *dx, *t, *ft, *dt); QUARD_MINIMIZER(mq, *x, *fx, *dx, *t, *ft); if (fabs(mc - *x) < fabs(mq - *x)) { newt = mc; } else { newt = mc + 0.5 * (mq - mc); } } else if (dsign) { /* Case 2: a lower function value and derivatives of opposite sign. The minimum is brackt. If the cubic minimizer is closer to x than the quadratic (secant) one, the cubic one is taken, else the quadratic one is taken. */ *brackt = 1; bound = 0; CUBIC_MINIMIZER(mc, *x, *fx, *dx, *t, *ft, *dt); QUARD_MINIMIZER2(mq, *x, *dx, *t, *dt); if (fabs(mc - *t) > fabs(mq - *t)) { newt = mc; } else { newt = mq; } } else if (fabs(*dt) < fabs(*dx)) { /* Case 3: a lower function value, derivatives of the same sign, and the magnitude of the derivative decreases. The cubic minimizer is only used if the cubic tends to infinity in the direction of the minimizer or if the minimum of the cubic is beyond t. Otherwise the cubic minimizer is defined to be either tmin or tmax. The quadratic (secant) minimizer is also computed and if the minimum is brackt then the the minimizer closest to x is taken, else the one farthest away is taken. */ bound = 1; CUBIC_MINIMIZER2(mc, *x, *fx, *dx, *t, *ft, *dt, tmin, tmax); QUARD_MINIMIZER2(mq, *x, *dx, *t, *dt); if (*brackt) { if (fabs(*t - mc) < fabs(*t - mq)) { newt = mc; } else { newt = mq; } } else { if (fabs(*t - mc) > fabs(*t - mq)) { newt = mc; } else { newt = mq; } } } else { /* Case 4: a lower function value, derivatives of the same sign, and the magnitude of the derivative does not decrease. If the minimum is not brackt, the step is either tmin or tmax, else the cubic minimizer is taken. */ bound = 0; if (*brackt) { CUBIC_MINIMIZER(newt, *t, *ft, *dt, *y, *fy, *dy); } else if (*x < *t) { newt = tmax; } else { newt = tmin; } } /* Update the interval of uncertainty. This update does not depend on the new step or the case analysis above. - Case a: if f(x) < f(t), x <- x, y <- t. - Case b: if f(t) <= f(x) && f'(t)*f'(x) > 0, x <- t, y <- y. - Case c: if f(t) <= f(x) && f'(t)*f'(x) < 0, x <- t, y <- x. */ if (*fx < *ft) { /* Case a */ *y = *t; *fy = *ft; *dy = *dt; } else { /* Case c */ if (dsign) { *y = *x; *fy = *fx; *dy = *dx; } /* Cases b and c */ *x = *t; *fx = *ft; *dx = *dt; } /* Clip the new trial value in [tmin, tmax]. */ if (tmax < newt) newt = tmax; if (newt < tmin) newt = tmin; /* Redefine the new trial value if it is close to the upper bound of the interval. */ if (*brackt && bound) { mq = *x + 0.66 * (*y - *x); if (*x < *y) { if (mq < newt) newt = mq; } else { if (newt < mq) newt = mq; } } /* Return the new trial value. */ *t = newt; return 0; } static lbfgsfloatval_t owlqn_x1norm( const lbfgsfloatval_t* x, const int start, const int n ) { int i; lbfgsfloatval_t norm = 0.; for (i = start;i < n;++i) { norm += fabs(x[i]); } return norm; } static void owlqn_pseudo_gradient( lbfgsfloatval_t* pg, const lbfgsfloatval_t* x, const lbfgsfloatval_t* g, const int n, const lbfgsfloatval_t c, const int start, const int end ) { int i; /* Compute the negative of gradients. */ for (i = 0;i < start;++i) { pg[i] = g[i]; } /* Compute the psuedo-gradients. */ for (i = start;i < end;++i) { if (x[i] < 0.) { /* Differentiable. */ pg[i] = g[i] - c; } else if (0. < x[i]) { /* Differentiable. */ pg[i] = g[i] + c; } else { if (g[i] < -c) { /* Take the right partial derivative. */ pg[i] = g[i] + c; } else if (c < g[i]) { /* Take the left partial derivative. */ pg[i] = g[i] - c; } else { pg[i] = 0.; } } } for (i = end;i < n;++i) { pg[i] = g[i]; } } static void owlqn_project( lbfgsfloatval_t* d, const lbfgsfloatval_t* sign, const int start, const int end ) { int i; for (i = start;i < end;++i) { if (d[i] * sign[i] <= 0) { d[i] = 0; } } } igraph/src/fast_community.c0000644000175100001440000011361513431000472015537 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_community.h" #include "igraph_memory.h" #include "igraph_iterators.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #include "igraph_structural.h" #include "igraph_vector_ptr.h" #include "config.h" /* #define IGRAPH_FASTCOMM_DEBUG */ #ifdef _MSC_VER /* MSVC does not support variadic macros */ #include void debug(const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef IGRAPH_FASTCOMM_DEBUG vfprintf(stderr, fmt, args); #endif va_end(args); } #else # ifdef IGRAPH_FASTCOMM_DEBUG # define debug(...) fprintf(stderr, __VA_ARGS__) # else # define debug(...) # endif #endif /* * Implementation of the community structure algorithm originally published * by Clauset et al in: * * A. Clauset, M.E.J. Newman and C. Moore, "Finding community structure in * very large networks.". Phys. Rev. E 70, 066111 (2004). * * The data structures being used are slightly different and they are described * most closely in: * * K. Wakita, T. Tsurumi, "Finding community structure in mega-scale social * networks.". arXiv:cs/0702048v1. * * We maintain a vector of communities, each of which containing a list of * pointers to their neighboring communities along with the increase in the * modularity score that could be achieved by joining the two communities. * Each community has a pointer to one of its neighbors - the one which would * result in the highest increase in modularity after a join. The local * (community-level) maximums are also stored in an indexed max-heap. The * max-heap itself stores its elements in an array which satisfies the heap * property, but to allow us to access any of the elements in the array based * on the community index (and not based on the array index - which depends on * the element's actual position in the heap), we also maintain an index * vector in the heap: the ith element of the index vector contains the * position of community i in the array of the max-heap. When we perform * sifting operations on the heap to restore the heap property, we also maintain * the index vector. */ /* Structure storing a pair of communities along with their dQ values */ typedef struct s_igraph_i_fastgreedy_commpair { long int first; /* first member of the community pair */ long int second; /* second member of the community pair */ igraph_real_t *dq; /* pointer to a member of the dq vector storing the */ /* increase in modularity achieved when joining */ struct s_igraph_i_fastgreedy_commpair *opposite; } igraph_i_fastgreedy_commpair; /* Structure storing a community */ typedef struct { igraph_integer_t id; /* Identifier of the community (for merges matrix) */ igraph_integer_t size; /* Size of the community */ igraph_vector_ptr_t neis; /* references to neighboring communities */ igraph_i_fastgreedy_commpair* maxdq; /* community pair with maximal dq */ } igraph_i_fastgreedy_community; /* Global community list structure */ typedef struct { long int no_of_communities, n; /* number of communities, number of vertices */ igraph_i_fastgreedy_community* e; /* list of communities */ igraph_i_fastgreedy_community** heap; /* heap of communities */ igraph_integer_t *heapindex; /* heap index to speed up lookup by community idx */ } igraph_i_fastgreedy_community_list; /* Scans the community neighborhood list for the new maximal dq value. * Returns 1 if the maximum is different from the previous one, * 0 otherwise. */ int igraph_i_fastgreedy_community_rescan_max( igraph_i_fastgreedy_community* comm) { long int i, n; igraph_i_fastgreedy_commpair *p, *best; igraph_real_t bestdq, currdq; n = igraph_vector_ptr_size(&comm->neis); if (n == 0) { comm->maxdq = 0; return 1; } best = (igraph_i_fastgreedy_commpair*)VECTOR(comm->neis)[0]; bestdq = *best->dq; for (i = 1; i < n; i++) { p = (igraph_i_fastgreedy_commpair*)VECTOR(comm->neis)[i]; currdq = *p->dq; if (currdq > bestdq) { best = p; bestdq = currdq; } } if (best != comm->maxdq) { comm->maxdq = best; return 1; } else { return 0; } } /* Destroys the global community list object */ void igraph_i_fastgreedy_community_list_destroy( igraph_i_fastgreedy_community_list* list) { long int i; for (i=0; in; i++) { igraph_vector_ptr_destroy(&list->e[i].neis); } free(list->e); if (list->heapindex != 0) free(list->heapindex); if (list->heap != 0) free(list->heap); } /* Community list heap maintenance: sift down */ void igraph_i_fastgreedy_community_list_sift_down( igraph_i_fastgreedy_community_list* list, long int idx) { long int root, child, c1, c2; igraph_i_fastgreedy_community* dummy; igraph_integer_t dummy2; igraph_i_fastgreedy_community** heap = list->heap; igraph_integer_t* heapindex = list->heapindex; root = idx; while (root*2+1 < list->no_of_communities) { child = root*2+1; if (child+1 < list->no_of_communities && *heap[child]->maxdq->dq < *heap[child+1]->maxdq->dq) child++; if (*heap[root]->maxdq->dq < *heap[child]->maxdq->dq) { c1 = heap[root]->maxdq->first; c2 = heap[child]->maxdq->first; dummy = heap[root]; heap[root] = heap[child]; heap[child] = dummy; dummy2 = heapindex[c1]; heapindex[c1] = heapindex[c2]; heapindex[c2] = dummy2; root = child; } else break; } } /* Community list heap maintenance: sift up */ void igraph_i_fastgreedy_community_list_sift_up( igraph_i_fastgreedy_community_list* list, long int idx) { long int root, parent, c1, c2; igraph_i_fastgreedy_community* dummy; igraph_integer_t dummy2; igraph_i_fastgreedy_community** heap = list->heap; igraph_integer_t* heapindex = list->heapindex; root = idx; while (root>0) { parent = (root-1)/2; if (*heap[parent]->maxdq->dq < *heap[root]->maxdq->dq) { c1 = heap[root]->maxdq->first; c2 = heap[parent]->maxdq->first; dummy = heap[parent]; heap[parent] = heap[root]; heap[root] = dummy; dummy2 = heapindex[c1]; heapindex[c1] = heapindex[c2]; heapindex[c2] = dummy2; root = parent; } else break; } } /* Builds the community heap for the first time */ void igraph_i_fastgreedy_community_list_build_heap( igraph_i_fastgreedy_community_list* list) { long int i; for (i=list->no_of_communities/2-1; i>=0; i--) igraph_i_fastgreedy_community_list_sift_down(list, i); } /* Finds the element belonging to a given community in the heap and return its * index in the heap array */ #define igraph_i_fastgreedy_community_list_find_in_heap(list, idx) (list)->heapindex[idx] /* Dumps the heap - for debugging purposes */ void igraph_i_fastgreedy_community_list_dump_heap( igraph_i_fastgreedy_community_list* list) { long int i; debug("Heap:\n"); for (i=0; ino_of_communities; i++) { debug("(%ld, %p, %p)", i, list->heap[i], list->heap[i]->maxdq); if (list->heap[i]->maxdq) { debug(" (%ld, %ld, %.7f)", list->heap[i]->maxdq->first, list->heap[i]->maxdq->second, *list->heap[i]->maxdq->dq); } debug("\n"); } debug("Heap index:\n"); for (i=0; ino_of_communities; i++) debug("%ld ", (long)list->heapindex[i]); debug("\nEND\n"); } /* Checks if the community heap satisfies the heap property. * Only useful for debugging. */ void igraph_i_fastgreedy_community_list_check_heap( igraph_i_fastgreedy_community_list* list) { long int i; for (i=0; ino_of_communities/2; i++) { if ((2*i+1no_of_communities && *list->heap[i]->maxdq->dq < *list->heap[2*i+1]->maxdq->dq) || (2*i+2no_of_communities && *list->heap[i]->maxdq->dq < *list->heap[2*i+2]->maxdq->dq)) { IGRAPH_WARNING("Heap property violated"); debug("Position: %ld, %ld and %ld\n", i, 2*i+1, 2*i+2); igraph_i_fastgreedy_community_list_dump_heap(list); } } } /* Removes a given element from the heap */ void igraph_i_fastgreedy_community_list_remove( igraph_i_fastgreedy_community_list* list, long int idx) { igraph_real_t old; long int commidx; /* First adjust the index */ commidx=list->heap[list->no_of_communities-1]->maxdq->first; list->heapindex[commidx] = (igraph_integer_t) idx; commidx=list->heap[idx]->maxdq->first; list->heapindex[commidx] = -1; /* Now remove the element */ old=*list->heap[idx]->maxdq->dq; list->heap[idx] = list->heap[list->no_of_communities-1]; list->no_of_communities--; /* Recover heap property */ if (old > *list->heap[idx]->maxdq->dq) igraph_i_fastgreedy_community_list_sift_down(list, idx); else igraph_i_fastgreedy_community_list_sift_up(list, idx); } /* Removes a given element from the heap when there are no more neighbors * for it (comm->maxdq is NULL) */ void igraph_i_fastgreedy_community_list_remove2( igraph_i_fastgreedy_community_list* list, long int idx, long int comm) { long int i; if (idx == list->no_of_communities-1) { /* We removed the rightmost element on the bottom level, no problem, * there's nothing to be done */ list->heapindex[comm] = -1; list->no_of_communities--; return; } /* First adjust the index */ i=list->heap[list->no_of_communities-1]->maxdq->first; list->heapindex[i] = (igraph_integer_t) idx; list->heapindex[comm] = -1; /* Now remove the element */ list->heap[idx] = list->heap[list->no_of_communities-1]; list->no_of_communities--; /* Recover heap property */ for (i=list->no_of_communities/2-1; i>=0; i--) igraph_i_fastgreedy_community_list_sift_down(list, i); } /* Removes the pair belonging to community k from the neighborhood list * of community c (that is, clist[c]) and recalculates maxdq */ void igraph_i_fastgreedy_community_remove_nei( igraph_i_fastgreedy_community_list* list, long int c, long int k) { long int i, n; igraph_bool_t rescan=0; igraph_i_fastgreedy_commpair *p; igraph_i_fastgreedy_community *comm; igraph_real_t olddq; comm=&list->e[c]; n=igraph_vector_ptr_size(&comm->neis); for (i=0; ineis)[i]; if (p->second == k) { /* Check current maxdq */ if (comm->maxdq == p) rescan=1; break; } } if (imaxdq->dq; igraph_vector_ptr_remove(&comm->neis, i); if (rescan) { igraph_i_fastgreedy_community_rescan_max(comm); i=igraph_i_fastgreedy_community_list_find_in_heap(list, c); if (comm->maxdq) { if (*comm->maxdq->dq > olddq) igraph_i_fastgreedy_community_list_sift_up(list, i); else igraph_i_fastgreedy_community_list_sift_down(list, i); } else { /* no more neighbors for this community. we should remove this * community from the heap and restore the heap property */ debug("REMOVING (NO MORE NEIS): %ld\n", i); igraph_i_fastgreedy_community_list_remove2(list, i, c); } } } } /* Auxiliary function to sort a community pair list with respect to the * `second` field */ int igraph_i_fastgreedy_commpair_cmp(const void* p1, const void* p2) { igraph_i_fastgreedy_commpair *cp1, *cp2; cp1=*(igraph_i_fastgreedy_commpair**)p1; cp2=*(igraph_i_fastgreedy_commpair**)p2; return (int) (cp1->second - cp2->second); } /* Sorts the neighbor list of the community with the given index, optionally * optimizing the process if we know that the list is nearly sorted and only * a given pair is in the wrong place. */ void igraph_i_fastgreedy_community_sort_neighbors_of( igraph_i_fastgreedy_community_list* list, long int index, igraph_i_fastgreedy_commpair* changed_pair) { igraph_vector_ptr_t* vec; long int i, n; igraph_bool_t can_skip_sort = 0; igraph_i_fastgreedy_commpair *other_pair; vec = &list->e[index].neis; if (changed_pair != 0) { /* Optimized sorting */ /* First we look for changed_pair in vec */ n = igraph_vector_ptr_size(vec); for (i = 0; i < n; i++) { if (VECTOR(*vec)[i] == changed_pair) { break; } } /* Did we find it? We should have -- otherwise it's a bug */ if (i >= n) { IGRAPH_WARNING("changed_pair not found in neighbor vector while re-sorting " "the neighbors of a community; this is probably a bug. Falling back to " "full sort instead." ); } else { /* Okay, the pair that changed is at index i. We need to figure out where * its new place should be. We can simply try moving the item all the way * to the left as long as the comparison function tells so (since the * rest of the vector is sorted), and then move all the way to the right * as long as the comparison function tells so, and we will be okay. */ /* Shifting to the left */ while (i > 0) { other_pair = VECTOR(*vec)[i-1]; if (other_pair->second > changed_pair->second) { VECTOR(*vec)[i] = other_pair; i--; } else { break; } } VECTOR(*vec)[i] = changed_pair; /* Shifting to the right */ while (i < n-1) { other_pair = VECTOR(*vec)[i+1]; if (other_pair->second < changed_pair->second) { VECTOR(*vec)[i] = other_pair; i++; } else { break; } } VECTOR(*vec)[i] = changed_pair; /* Mark that we don't need a full sort */ can_skip_sort = 1; } } if (!can_skip_sort) { /* Fallback to full sorting */ igraph_vector_ptr_sort(vec, igraph_i_fastgreedy_commpair_cmp); } } /* Updates the dq value of community pair p in the community with index p->first * of the community list clist to newdq and restores the heap property * in community c if necessary. Returns 1 if the maximum in the row had * to be updated, zero otherwise */ int igraph_i_fastgreedy_community_update_dq( igraph_i_fastgreedy_community_list* list, igraph_i_fastgreedy_commpair* p, igraph_real_t newdq) { long int i,j,to,from; igraph_real_t olddq; igraph_i_fastgreedy_community *comm_to, *comm_from; to=p->first; from=p->second; comm_to=&list->e[to]; comm_from=&list->e[from]; if (comm_to->maxdq == p && newdq >= *p->dq) { /* If we are adjusting the current maximum and it is increased, we don't * have to re-scan for the new maximum */ *p->dq = newdq; /* The maximum was increased, so perform a sift-up in the heap */ i = igraph_i_fastgreedy_community_list_find_in_heap(list, to); igraph_i_fastgreedy_community_list_sift_up(list, i); /* Let's check the opposite side. If the pair was not the maximal in * the opposite side (the other community list)... */ if (comm_from->maxdq != p->opposite) { if (*comm_from->maxdq->dq < newdq) { /* ...and it will become the maximal, we need to adjust and sift up */ comm_from->maxdq = p->opposite; j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_up(list, j); } else { /* The pair was not the maximal in the opposite side and it will * NOT become the maximal, there's nothing to do there */ } } else { /* The pair was maximal in the opposite side, so we need to sift it up * with the new value */ j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_up(list, j); } return 1; } else if (comm_to->maxdq != p && (newdq <= *comm_to->maxdq->dq)) { /* If we are modifying an item which is not the current maximum, and the * new value is less than the current maximum, we don't * have to re-scan for the new maximum */ olddq = *p->dq; *p->dq = newdq; /* However, if the item was the maximum on the opposite side, we'd better * re-scan it */ if (comm_from->maxdq == p->opposite) { if (olddq>newdq) { /* Decreased the maximum on the other side, we have to re-scan for the * new maximum */ igraph_i_fastgreedy_community_rescan_max(comm_from); j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_down(list, j); } else { /* Increased the maximum on the other side, we don't have to re-scan * but we might have to sift up */ j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_up(list, j); } } return 0; } else { /* We got here in two cases: (1) the pair we are modifying right now is the maximum in the given community and we are decreasing it (2) the pair we are modifying right now is NOT the maximum in the given community, but we increase it so much that it will become the new maximum */ *p->dq = newdq; if (comm_to->maxdq != p) { /* case (2) */ comm_to->maxdq = p; /* The maximum was increased, so perform a sift-up in the heap */ i = igraph_i_fastgreedy_community_list_find_in_heap(list, to); igraph_i_fastgreedy_community_list_sift_up(list, i); /* Opposite side. Chances are that the new value became the maximum * in the opposite side, but check it first */ if (comm_from->maxdq != p->opposite) { if (*comm_from->maxdq->dq < newdq) { /* Yes, it will become the new maximum */ comm_from->maxdq = p->opposite; j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_up(list, j); } else { /* No, nothing to do there */ } } else { /* Already increased the maximum on the opposite side, so sift it up */ j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_up(list, j); } } else { /* case (1) */ /* This is the worst, we have to re-scan the whole community to find * the new maximum and update the global maximum as well if necessary */ igraph_i_fastgreedy_community_rescan_max(comm_to); /* The maximum was decreased, so perform a sift-down in the heap */ i = igraph_i_fastgreedy_community_list_find_in_heap(list, to); igraph_i_fastgreedy_community_list_sift_down(list, i); if (comm_from->maxdq != p->opposite) { /* The one that we decreased on the opposite side is not the * maximal one. Nothing to do. */ } else { /* We decreased the maximal on the opposite side as well. Re-scan * and sift down */ igraph_i_fastgreedy_community_rescan_max(comm_from); j = igraph_i_fastgreedy_community_list_find_in_heap(list, from); igraph_i_fastgreedy_community_list_sift_down(list, j); } } } return 1; } /** * \function igraph_community_fastgreedy * \brief Finding community structure by greedy optimization of modularity * * This function implements the fast greedy modularity optimization * algorithm for finding community structure, see * A Clauset, MEJ Newman, C Moore: Finding community structure in very * large networks, http://www.arxiv.org/abs/cond-mat/0408187 for the * details. * *
* Some improvements proposed in K Wakita, T Tsurumi: Finding community * structure in mega-scale social networks, * http://www.arxiv.org/abs/cs.CY/0702048v1 have also been implemented. * * \param graph The input graph. It must be a graph without multiple edges. * This is checked and an error message is given for graphs with multiple * edges. * \param weights Potentially a numeric vector containing edge * weights. Supply a null pointer here for unweighted graphs. The * weights are expected to be non-negative. * \param merges Pointer to an initialized matrix or NULL, the result of the * computation is stored here. The matrix has two columns and each * merge corresponds to one merge, the ids of the two merged * components are stored. The component ids are numbered from zero and * the first \c n components are the individual vertices, \c n is * the number of vertices in the graph. Component \c n is created * in the first merge, component \c n+1 in the second merge, etc. * The matrix will be resized as needed. If this argument is NULL * then it is ignored completely. * \param modularity Pointer to an initialized vector or NULL pointer, * in the former case the modularity scores along the stages of the * computation are recorded here. The vector will be resized as * needed. * \param membership Pointer to a vector. If not a null pointer, then * the membership vector corresponding to the best split (in terms * of modularity) is stored here. * \return Error code. * * \sa \ref igraph_community_walktrap(), \ref * igraph_community_edge_betweenness() for other community detection * algorithms, \ref igraph_community_to_membership() to convert the * dendrogram to a membership vector. * * Time complexity: O(|E||V|log|V|) in the worst case, * O(|E|+|V|log^2|V|) typically, |V| is the number of vertices, |E| is * the number of edges. * * \example examples/simple/igraph_community_fastgreedy.c */ int igraph_community_fastgreedy(const igraph_t *graph, const igraph_vector_t *weights, igraph_matrix_t *merges, igraph_vector_t *modularity, igraph_vector_t *membership) { long int no_of_edges, no_of_nodes, no_of_joins, total_joins; long int i, j, k, n, m, from, to, dummy, best_no_of_joins; igraph_integer_t ffrom, fto; igraph_eit_t edgeit; igraph_i_fastgreedy_commpair *pairs, *p1, *p2; igraph_i_fastgreedy_community_list communities; igraph_vector_t a; igraph_real_t q, *dq, bestq, weight_sum, loop_weight_sum; igraph_bool_t has_multiple; igraph_matrix_t merges_local; /*long int join_order[] = { 16,5, 5,6, 6,0, 4,0, 10,0, 26,29, 29,33, 23,33, 27,33, 25,24, 24,31, 12,3, 21,1, 30,8, 8,32, 9,2, 17,1, 11,0, 7,3, 3,2, 13,2, 1,2, 28,31, 31,33, 22,32, 18,32, 20,32, 32,33, 15,33, 14,33, 0,19, 19,2, -1,-1 };*/ /*long int join_order[] = { 43,42, 42,41, 44,41, 41,36, 35,36, 37,36, 36,29, 38,29, 34,29, 39,29, 33,29, 40,29, 32,29, 14,29, 30,29, 31,29, 6,18, 18,4, 23,4, 21,4, 19,4, 27,4, 20,4, 22,4, 26,4, 25,4, 24,4, 17,4, 0,13, 13,2, 1,2, 11,2, 8,2, 5,2, 3,2, 10,2, 9,2, 7,2, 2,28, 28,15, 12,15, 29,16, 4,15, -1,-1 };*/ no_of_nodes = igraph_vcount(graph); no_of_edges = igraph_ecount(graph); if (igraph_is_directed(graph)) { IGRAPH_ERROR("fast greedy community detection works for undirected graphs only", IGRAPH_UNIMPLEMENTED); } total_joins=no_of_nodes-1; if (weights != 0) { if (igraph_vector_size(weights) < igraph_ecount(graph)) IGRAPH_ERROR("fast greedy community detection: weight vector too short", IGRAPH_EINVAL); if (igraph_vector_any_smaller(weights, 0)) IGRAPH_ERROR("weights must be positive", IGRAPH_EINVAL); weight_sum = igraph_vector_sum(weights); } else weight_sum = no_of_edges; IGRAPH_CHECK(igraph_has_multiple(graph, &has_multiple)); if (has_multiple) { IGRAPH_ERROR("fast-greedy community finding works only on graphs without multiple edges", IGRAPH_EINVAL); } if (membership != 0 && merges == 0) { /* We need the merge matrix because the user wants the membership * vector, so we allocate one on our own */ IGRAPH_CHECK(igraph_matrix_init(&merges_local, total_joins, 2)); IGRAPH_FINALLY(igraph_matrix_destroy, &merges_local); merges = &merges_local; } if (merges != 0) { IGRAPH_CHECK(igraph_matrix_resize(merges, total_joins, 2)); igraph_matrix_null(merges); } if (modularity != 0) { IGRAPH_CHECK(igraph_vector_resize(modularity, total_joins+1)); } /* Create degree vector */ IGRAPH_VECTOR_INIT_FINALLY(&a, no_of_nodes); if (weights) { debug("Calculating weighted degrees\n"); for (i=0; i < no_of_edges; i++) { VECTOR(a)[(long int)IGRAPH_FROM(graph, i)] += VECTOR(*weights)[i]; VECTOR(a)[(long int)IGRAPH_TO(graph, i)] += VECTOR(*weights)[i]; } } else { debug("Calculating degrees\n"); IGRAPH_CHECK(igraph_degree(graph, &a, igraph_vss_all(), IGRAPH_ALL, 1)); } /* Create list of communities */ debug("Creating community list\n"); communities.n = no_of_nodes; communities.no_of_communities = no_of_nodes; communities.e = (igraph_i_fastgreedy_community*)calloc((size_t) no_of_nodes, sizeof(igraph_i_fastgreedy_community)); if (communities.e == 0) { IGRAPH_ERROR("can't run fast greedy community detection", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, communities.e); communities.heap = (igraph_i_fastgreedy_community**)calloc((size_t) no_of_nodes, sizeof(igraph_i_fastgreedy_community*)); if (communities.heap == 0) { IGRAPH_ERROR("can't run fast greedy community detection", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, communities.heap); communities.heapindex = (igraph_integer_t*)calloc((size_t)no_of_nodes, sizeof(igraph_integer_t)); if (communities.heapindex == 0) { IGRAPH_ERROR("can't run fast greedy community detection", IGRAPH_ENOMEM); } IGRAPH_FINALLY_CLEAN(2); IGRAPH_FINALLY(igraph_i_fastgreedy_community_list_destroy, &communities); for (i=0; ito) { dummy=from; from=to; to=dummy; } if (weights) { dq[j]=2*(VECTOR(*weights)[eidx]/(weight_sum*2.0) - VECTOR(a)[from]*VECTOR(a)[to]/(4.0*weight_sum*weight_sum)); } else { dq[j]=2*(1.0/(no_of_edges*2.0) - VECTOR(a)[from]*VECTOR(a)[to]/(4.0*no_of_edges*no_of_edges)); } pairs[i].first = from; pairs[i].second = to; pairs[i].dq = &dq[j]; pairs[i].opposite = &pairs[i+1]; pairs[i+1].first = to; pairs[i+1].second = from; pairs[i+1].dq = pairs[i].dq; pairs[i+1].opposite = &pairs[i]; /* Link the pair to the communities */ igraph_vector_ptr_push_back(&communities.e[from].neis, &pairs[i]); igraph_vector_ptr_push_back(&communities.e[to].neis, &pairs[i+1]); /* Update maximums */ if (communities.e[from].maxdq==0 || *communities.e[from].maxdq->dq < *pairs[i].dq) communities.e[from].maxdq = &pairs[i]; if (communities.e[to].maxdq==0 || *communities.e[to].maxdq->dq < *pairs[i+1].dq) communities.e[to].maxdq = &pairs[i+1]; } igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(1); /* Sorting community neighbor lists by community IDs */ debug("Sorting community neighbor lists\n"); for (i=0, j=0; i= bestq) { bestq = q; best_no_of_joins = no_of_joins; } /* Some debug info if needed */ /* igraph_i_fastgreedy_community_list_check_heap(&communities); */ #ifdef DEBUG debug("===========================================\n"); for (i=0; ifirst, p1->second, *p1->dq); } p1=communities.e[i].maxdq; debug("\n Maxdq: (%ld,%ld,%.4f)\n", p1->first, p1->second, *p1->dq); } debug("Global maxdq is: (%ld,%ld,%.4f)\n", communities.heap[0]->maxdq->first, communities.heap[0]->maxdq->second, *communities.heap[0]->maxdq->dq); for (i=0; imaxdq->first, communities.heap[i]->maxdq->second, *communities.heap[0]->maxdq->dq); debug("\n"); #endif if (communities.heap[0] == 0) break; /* no more communities */ if (communities.heap[0]->maxdq == 0) break; /* there are only isolated comms */ to=communities.heap[0]->maxdq->second; from=communities.heap[0]->maxdq->first; debug("Q[%ld] = %.7f\tdQ = %.7f\t |H| = %ld\n", no_of_joins, q, *communities.heap[0]->maxdq->dq, no_of_nodes-no_of_joins-1); /* DEBUG */ /* from=join_order[no_of_joins*2]; to=join_order[no_of_joins*2+1]; if (to == -1) break; for (i=0; isecond == from) communities.maxdq = p1; } */ n = igraph_vector_ptr_size(&communities.e[to].neis); m = igraph_vector_ptr_size(&communities.e[from].neis); /*if (n>m) { dummy=n; n=m; m=dummy; dummy=to; to=from; from=dummy; }*/ debug(" joining: %ld <- %ld\n", to, from); q += *communities.heap[0]->maxdq->dq; /* Merge the second community into the first */ i = j = 0; while (ifirst, p1->second, p2->first, p2->second); if (p1->second < p2->second) { /* Considering p1 from now on */ debug(" Considering: %ld-%ld\n", p1->first, p1->second); if (p1->second == from) { debug(" WILL REMOVE: %ld-%ld\n", to, from); } else { /* chain, case 1 */ debug(" CHAIN(1): %ld-%ld %ld, now=%.7f, adding=%.7f, newdq(%ld,%ld)=%.7f\n", to, p1->second, from, *p1->dq, -2*VECTOR(a)[from]*VECTOR(a)[p1->second], p1->first, p1->second, *p1->dq-2*VECTOR(a)[from]*VECTOR(a)[p1->second]); igraph_i_fastgreedy_community_update_dq(&communities, p1, *p1->dq - 2*VECTOR(a)[from]*VECTOR(a)[p1->second]); } i++; } else if (p1->second == p2->second) { /* p1->first, p1->second and p2->first form a triangle */ debug(" Considering: %ld-%ld and %ld-%ld\n", p1->first, p1->second, p2->first, p2->second); /* Update dq value */ debug(" TRIANGLE: %ld-%ld-%ld, now=%.7f, adding=%.7f, newdq(%ld,%ld)=%.7f\n", to, p1->second, from, *p1->dq, *p2->dq, p1->first, p1->second, *p1->dq+*p2->dq); igraph_i_fastgreedy_community_update_dq(&communities, p1, *p1->dq + *p2->dq); igraph_i_fastgreedy_community_remove_nei(&communities, p1->second, from); i++; j++; } else { debug(" Considering: %ld-%ld\n", p2->first, p2->second); if (p2->second == to) { debug(" WILL REMOVE: %ld-%ld\n", p2->second, p2->first); } else { /* chain, case 2 */ debug(" CHAIN(2): %ld %ld-%ld, newdq(%ld,%ld)=%.7f\n", to, p2->second, from, to, p2->second, *p2->dq-2*VECTOR(a)[to]*VECTOR(a)[p2->second]); p2->opposite->second=to; /* p2->opposite->second changed, so it means that * communities.e[p2->second].neis (which contains p2->opposite) is * not sorted any more. We have to find the index of p2->opposite in * this vector and move it to the correct place. Moving should be an * O(n) operation; re-sorting would be O(n*logn) or even worse, * depending on the pivoting strategy used by qsort() since the * vector is nearly sorted */ igraph_i_fastgreedy_community_sort_neighbors_of( &communities, p2->second, p2->opposite); /* link from.neis[j] to the current place in to.neis if * from.neis[j] != to */ p2->first=to; IGRAPH_CHECK(igraph_vector_ptr_insert(&communities.e[to].neis,i,p2)); n++; i++; if (*p2->dq > *communities.e[to].maxdq->dq) { communities.e[to].maxdq = p2; k=igraph_i_fastgreedy_community_list_find_in_heap(&communities, to); igraph_i_fastgreedy_community_list_sift_up(&communities, k); } igraph_i_fastgreedy_community_update_dq(&communities, p2, *p2->dq - 2*VECTOR(a)[to]*VECTOR(a)[p2->second]); } j++; } } while (isecond == from) { debug(" WILL REMOVE: %ld-%ld\n", p1->first, from); } else { /* chain, case 1 */ debug(" CHAIN(1): %ld-%ld %ld, now=%.7f, adding=%.7f, newdq(%ld,%ld)=%.7f\n", to, p1->second, from, *p1->dq, -2*VECTOR(a)[from]*VECTOR(a)[p1->second], p1->first, p1->second, *p1->dq-2*VECTOR(a)[from]*VECTOR(a)[p1->second]); igraph_i_fastgreedy_community_update_dq(&communities, p1, *p1->dq - 2*VECTOR(a)[from]*VECTOR(a)[p1->second]); } i++; } while (jsecond) { j++; continue; } /* chain, case 2 */ debug(" CHAIN(2): %ld %ld-%ld, newdq(%ld,%ld)=%.7f\n", to, p2->second, from, p1->first, p2->second, *p2->dq-2*VECTOR(a)[to]*VECTOR(a)[p2->second]); p2->opposite->second=to; /* need to re-sort community nei list `p2->second` */ igraph_i_fastgreedy_community_sort_neighbors_of(&communities, p2->second, p2->opposite); /* link from.neis[j] to the current place in to.neis if * from.neis[j] != to */ p2->first=to; IGRAPH_CHECK(igraph_vector_ptr_push_back(&communities.e[to].neis,p2)); if (*p2->dq > *communities.e[to].maxdq->dq) { communities.e[to].maxdq = p2; k=igraph_i_fastgreedy_community_list_find_in_heap(&communities, to); igraph_i_fastgreedy_community_list_sift_up(&communities, k); } igraph_i_fastgreedy_community_update_dq(&communities, p2, *p2->dq-2*VECTOR(a)[to]*VECTOR(a)[p2->second]); j++; } /* Now, remove community `from` from the neighbors of community `to` */ if (communities.no_of_communities > 2) { debug(" REMOVING: %ld-%ld\n", to, from); igraph_i_fastgreedy_community_remove_nei(&communities, to, from); i=igraph_i_fastgreedy_community_list_find_in_heap(&communities, from); igraph_i_fastgreedy_community_list_remove(&communities, i); } communities.e[from].maxdq=0; /* Update community sizes */ communities.e[to].size += communities.e[from].size; communities.e[from].size = 0; /* record what has been merged */ /* igraph_vector_ptr_clear is not enough here as it won't free * the memory consumed by communities.e[from].neis. Thanks * to Tom Gregorovic for pointing that out. */ igraph_vector_ptr_destroy(&communities.e[from].neis); if (merges) { MATRIX(*merges, no_of_joins, 0) = communities.e[to].id; MATRIX(*merges, no_of_joins, 1) = communities.e[from].id; communities.e[to].id = (igraph_integer_t) (no_of_nodes+no_of_joins); } /* Update vector a */ VECTOR(a)[to] += VECTOR(a)[from]; VECTOR(a)[from] = 0.0; no_of_joins++; } /* TODO: continue merging when some isolated communities remained. Always * joining the communities with the least number of nodes results in the * smallest decrease in modularity every step. Now we're simply deleting * the excess rows from the merge matrix */ if (no_of_joins < total_joins) { long int *ivec; ivec=igraph_Calloc(igraph_matrix_nrow(merges), long int); if (ivec == 0) IGRAPH_ERROR("can't run fast greedy community detection", IGRAPH_ENOMEM); IGRAPH_FINALLY(free, ivec); for (i=0; i 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * The grouping function takes as argument 'nev' eigenvectors and * and tries to minimize the eigenpair shifts induced by the coarse * graining (Section 5 of the above reference). The eigenvectors are * stored in a 'nev'x'n' matrix 'v'. * The 'algo' parameter can take the following values * 1 -> Optimal method (sec. 5.3.1) * 2 -> Intervals+k-means (sec. 5.3.3) * 3 -> Intervals (sec. 5.3.2) * 4 -> Exact SCG (sec. 5.4.1--last paragraph) * 'nt' is a vector of length 'nev' giving either the size of the * partitions (if algo = 1) or the number of intervals to cut the * eigenvectors if algo = 2 or algo = 3. When algo = 4 this parameter * is ignored. 'maxiter' fixes the maximum number of iterations of * the k-means algorithm, and is only considered when algo = 2. * All the algorithms try to find a minimizing partition of * ||v_i-Pv_i|| where P is a problem-specific projector and v_i denotes * the eigenvectors stored in v. The final partition is worked out * as decribed in Method 1 of Section 5.4.2. * 'matrix' provides the type of SCG (i.e. the form of P). So far, * the options are those described in section 6, that is: * 1 -> Symmetric (sec. 6.1) * 2 -> Laplacian (sec. 6.2) * 3 -> Stochastic (sec. 6.3) * In the stochastic case, a valid distribution probability 'p' must be * provided. In all other cases, 'p' is ignored and can be set to NULL. * The group labels in the final partition are given in 'gr' as positive * consecutive integers starting from 0. */ #include "igraph_scg.h" #include "igraph_eigen.h" #include "igraph_interface.h" #include "igraph_structural.h" #include "igraph_constructors.h" #include "igraph_conversion.h" #include "igraph_memory.h" #include "scg_headers.h" #include "math.h" /** * \section about_scg * * * The SCG functions provide a framework, called Spectral Coarse Graining * (SCG), for reducing large graphs while preserving their * spectral-related features, that is features * closely related with the eigenvalues and eigenvectors of a graph * matrix (which for now can be the adjacency, the stochastic, or the * Laplacian matrix). * * * * Common examples of such features comprise the first-passage-time of * random walkers on Markovian graphs, thermodynamic properties of * lattice models in statistical physics (e.g. Ising model), and the * epidemic threshold of epidemic network models (SIR and SIS models). * * * * SCG differs from traditional clustering schemes by producing a * coarse-grained graph (not just a partition of * the vertices), representative of the original one. As shown in [1], * Principal Component Analysis can be viewed as a particular SCG, * called exact SCG, where the matrix to be * coarse-grained is the covariance matrix of some data set. * * * * SCG should be of interest to practitioners of various * fields dealing with problems where matrix eigenpairs play an important * role, as for instance is the case of dynamical processes on networks. * * *
SCG in brief * * The main idea of SCG is to operate on a matrix a shrinkage operation * specifically designed to preserve some of the matrix eigenpairs while * not altering other important matrix features (such as its structure). * Mathematically, this idea was expressed as follows. Consider a * (complex) n x n matrix M and form the product *
* M'=LMR*, *
* where n' < n and L, R are from C[n'xn]} and are such * that LR*=I[n'] (R* denotes the conjugate transpose of R). Under * these assumptions, it can be shown that P=R*L is an n'-rank * projector and that, if (lambda, v) is a (right) * eigenpair of M (i.e. Mv=lambda v} and P is orthogonal, there exists * an eigenvalue lambda' of M' such that *
* |lambda-lambda'| <= const ||e[P](v)|| * [1+O(||e[P](v)||2)], *
* where ||e[P](v)||=||v-Pv||. Hence, if P (or equivalently * L, R) is chosen so as to make ||e[P](v)|| as small as possible, one * can preserve to any desired level the original eigenvalue * lambda in the coarse-grained matrix M'; * under extra assumptions on M, this result can be generalized to * eigenvectors [1]. This leads to the following generic definition of a * SCG problem. *
* * * Given M (C[nxn]) and (lambda, v), a (right) eigenpair of M to be * preserved by the coarse graining, the problem is to find a projector * P' solving *
* min(||e[P](v)||, p in Omega), *
* where Omega is a set of projectors in C[nxn] described by some * ad hoc constraints c[1], ..., c[r] * (e.g. c[1]: P in R[nxn], c[2]: P=t(P), c[3]: P[i,j] >= 0}, etc). *
* * * Choosing pertinent constraints to solve the SCG problem is of great * importance in applications. For instance, in the absence of * constraints the SCG problem is solved trivially by * P'=vv* (v is assumed normalized). We have designed a particular * constraint, called homogeneous mixing, which * ensures that vertices belonging to the same group are merged * consistently from a physical point of view (see [1] for * details). Under this constraint the SCG problem reduces to finding * the partition of 1, ..., n (labeling the original vertices) * minimizing *
* ||e[P](v)||2 = * sum([v(i)-(Pv)(i)]2; * alpha=1,...,n', i in alpha), *
* where alpha denotes a group (i.e. a block) in a partition of * {1, ..., n}, and |alpha| is the number of elements in alpha. *
* * * If M is symmetric or stochastic, for instance, then it may be * desirable (or mandatory) to choose L, R so that M' is symmetric or * stochastic as well. This structural constraint * has led to the construction of particular semi-projectors for * symmetric [1], stochastic [3] and Laplacian [2] matrices, that are * made available. * * * * In short, the coarse graining of matrices and graphs involves: * \olist * \oli Retrieving a matrix or a graph matrix M from the * problem. * \oli Computing the eigenpairs of M to be preserved in the * coarse-grained graph or matrix. * \oli Setting some problem-specific constraints (e.g. dimension of * the coarse-grained object). * \oli Solving the constrained SCG problem, that is finding P'. * \oli Computing from P' two semi-projectors L' and R' * (e.g. following the method proposed in [1]). * \oli Working out the product M'=L'MR'* and, if needed, defining * from M' a coarse-grained graph. * \endolist * *
* *
Functions for performing SCG * * The main functions are \ref igraph_scg_adjacency(), \ref * igraph_scg_laplacian() and \ref igraph_scg_stochastic(). * These functions handle all the steps involved in the * Spectral Coarse Graining (SCG) of some particular matrices and graphs * as described above and in reference [1]. In more details, * they compute some prescribed eigenpairs of a matrix or a * graph matrix, (for now adjacency, Laplacian and stochastic matrices are * available), work out an optimal partition to preserve the eigenpairs, * and finally output a coarse-grained matrix or graph along with other * useful information. * * * * These steps can also be carried out independently: (1) Use * \ref igraph_get_adjacency(), \ref igraph_get_sparsemat(), * \ref igraph_laplacian(), \ref igraph_get_stochastic() or \ref * igraph_get_stochastic_sparsemat() to compute a matrix M. * (2) Work out some prescribed eigenpairs of M e.g. by * means of \ref igraph_arpack_rssolve() or \ref * igraph_arpack_rnsolve(). (3) Invoke one the four * algorithms of the function \ref igraph_scg_grouping() to get a * partition that will preserve the eigenpairs in the coarse-grained * matrix. (4) Compute the semi-projectors L and R using * \ref igraph_scg_semiprojectors() and from there the coarse-grained * matrix M'=LMR*. If necessary, construct a coarse-grained graph from * M' (e.g. as in [1]). * *
* *
References * * [1] D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, * Shrinking Matrices while Preserving their Eigenpairs with Application * to the Spectral Coarse Graining of Graphs. Submitted to * SIAM Journal on Matrix Analysis and * Applications, 2008. * http://people.epfl.ch/david.morton * * * [2] D. Gfeller, and P. De Los Rios, Spectral Coarse Graining and * Synchronization in Oscillator Networks. * Physical Review Letters, * 100(17), 2008. * http://arxiv.org/abs/0708.2055 * * * [3] D. Gfeller, and P. De Los Rios, Spectral Coarse Graining of Complex * Networks, Physical Review Letters, * 99(3), 2007. * http://arxiv.org/abs/0706.0812 * *
*/ /** * \function igraph_scg_grouping * \brief SCG problem solver * * This function solves the Spectral Coarse Graining (SCG) problem; * either exactly, or approximately but faster. * *
* The algorithm \c IGRAPH_SCG_OPTIMUM solves exactly the SCG problem * for each eigenvector in \p V. The running time of this algorithm is * O(max(nt) m^2) for the symmetric and laplacian matrix problems * It is O(m^3) for the stochastic problem. Here m is the number * of rows in \p V. In all three cases, the memory usage is O(m^2). * * * The algorithms \c IGRAPH_SCG_INTERV and \c IGRAPH_SCG_INTERV_KM solve * approximately the SCG problem by performing a (for now) constant * binning of the components of the eigenvectors, that is \p nt * VECTOR(nt_vec)[i]) constant-size bins are used to * partition V[,i]. When \p algo is \c * IGRAPH_SCG_INTERV_KM, the (Lloyd) k-means algorithm is * run on each partition obtained by \c IGRAPH_SCG_INTERV to improve * accuracy. * * * Once a minimizing partition (either exact or approximate) has been * found for each eigenvector, the final grouping is worked out as * follows: two vertices are grouped together in the final partition if * they are grouped together in each minimizing partition. In general the * size of the final partition is not known in advance when the number * of columns in \p V is larger than one. * * * Finally, the algorithm \c IGRAPH_SCG_EXACT groups the vertices with * equal components in each eigenvector. The last three algorithms * essentially have linear running time and memory load. * * \param V The matrix of eigenvectors to be preserved by coarse * graining, each column is an eigenvector. * \param groups Pointer to an initialized vector, the result of the * SCG is stored here. * \param nt Positive integer. When \p algo is \c IGRAPH_SCG_OPTIMUM, * it gives the number of groups to partition each eigenvector * separately. When \p algo is \c IGRAPH_SCG_INTERV or \c * IGRAPH_SCG_INTERV_KM, it gives the number of intervals to * partition each eigenvector. This is ignored when \p algo is \c * IGRAPH_SCG_EXACT. * \param nt_vec A numeric vector of length one or the length must * match the number of eigenvectors given in \p V, or a \c NULL * pointer. If not \c NULL, then this argument gives the number of * groups or intervals, and \p nt is ignored. Different number of * groups or intervals can be specified for each eigenvector. * \param mtype The type of semi-projectors used in the SCG. Possible * values are \c IGRAPH_SCG_SYMMETRIC, \c IGRAPH_SCG_STOCHASTIC and * \c IGRAPH_SCG_LAPLACIAN. * \param algo The algorithm to solve the SCG problem. Possible * values: \c IGRAPH_SCG_OPTIMUM, \c IGRAPH_SCG_INTERV_KM, \c * IGRAPH_SCG_INTERV and \c IGRAPH_SCG_EXACT. Please see the * details about them above. * \param p A probability vector, or \c NULL. This argument must be * given if \p mtype is \c IGRAPH_SCG_STOCHASTIC, but it is ignored * otherwise. For the stochastic case it gives the stationary * probability distribution of a Markov chain, the one specified by * the graph/matrix under study. * \param maxiter A positive integer giving the number of iterations * of the k-means algorithm when \p algo is \c * IGRAPH_SCG_INTERV_KM. It is ignored in other cases. A reasonable * (initial) value for this argument is 100. * \return Error code. * * Time complexity: see description above. * * \sa \ref igraph_scg_adjacency(), \ref igraph_scg_laplacian(), \ref * igraph_scg_stochastic(). * * \example examples/simple/igraph_scg_grouping.c * \example examples/simple/igraph_scg_grouping2.c * \example examples/simple/igraph_scg_grouping3.c * \example examples/simple/igraph_scg_grouping4.c */ int igraph_scg_grouping(const igraph_matrix_t *V, igraph_vector_t *groups, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_matrix_t mtype, igraph_scg_algorithm_t algo, const igraph_vector_t *p, igraph_integer_t maxiter) { int no_of_nodes=(int) igraph_matrix_nrow(V); int nev=(int) igraph_matrix_ncol(V); igraph_matrix_int_t gr_mat; int i; if (nt_vec && igraph_vector_size(nt_vec) != 1 && igraph_vector_size(nt_vec) != nev) { IGRAPH_ERROR("Invalid length for interval specification", IGRAPH_EINVAL); } if (nt_vec && igraph_vector_size(nt_vec) == 1) { nt=(igraph_integer_t) VECTOR(*nt_vec)[0]; nt_vec=0; } if (!nt_vec && algo != IGRAPH_SCG_EXACT) { if (nt <= 1 || nt >= no_of_nodes) { IGRAPH_ERROR("Invalid interval specification", IGRAPH_EINVAL); } } else if (algo != IGRAPH_SCG_EXACT) { igraph_real_t min, max; igraph_vector_minmax(nt_vec, &min, &max); if (min <= 1 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid interval specification", IGRAPH_EINVAL); } } if (mtype == IGRAPH_SCG_STOCHASTIC && !p) { IGRAPH_ERROR("`p' must be given for the stochastic matrix case", IGRAPH_EINVAL); } if (p && igraph_vector_size(p) != no_of_nodes) { IGRAPH_ERROR("Invalid `p' vector size", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_resize(groups, no_of_nodes)); #define INVEC(i) (nt_vec ? VECTOR(*nt_vec)[i] : nt) IGRAPH_CHECK(igraph_matrix_int_init(&gr_mat, no_of_nodes, nev)); IGRAPH_FINALLY(igraph_matrix_int_destroy, &gr_mat); switch (algo) { case IGRAPH_SCG_OPTIMUM: for (i=0; i * The symmetric semi-projectors are defined as *
* L[alpha,j] = R[alpha,j] = 1/sqrt(|alpha|) delta[alpha,gamma(j)], *
* the (row) Laplacian semi-projectors as *
* L[alpha,j] = 1/|alpha| delta[alpha,gamma(j)] *
* and *
* R[alpha,j] = delta[alpha,gamma(j)], *
* and the (row) stochastic semi-projectors as *
* L[alpha,j] = p[1][j] / sum(p[1][k]; k in gamma(j)) * delta[alpha,gamma(j)] *
* and *
* R[alpha,j] = delta[alpha,gamma(j)], *
* where p[1] is the (left) eigenvector associated with the * one-eigenvalue of the stochastic matrix. L and R are * defined in a symmetric way when \p norm is \c * IGRAPH_SCG_NORM_COL. All these semi-projectors verify various * properties described in the reference. * \param groups A vector of integers, giving the group label of every * vertex in the partition. Group labels should start at zero and * should be sequential. * \param mtype The type of semi-projectors. For now \c * IGRAPH_SCG_SYMMETRIC, \c IGRAPH_SCG_STOCHASTIC and \c * IGRAP_SCG_LAPLACIAN are supported. * \param L If not a \c NULL pointer, then it must be a pointer to * an initialized matrix. The left semi-projector is stored here. * \param R If not a \c NULL pointer, then it must be a pointer to * an initialized matrix. The right semi-projector is stored here. * \param Lsparse If not a \c NULL pointer, then it must be a pointer * to an uninitialized sparse matrix. The left semi-projector is * stored here. * \param Rsparse If not a \c NULL pointer, then it must be a pointer * to an uninitialized sparse matrix. The right semi-projector is * stored here. * \param p \c NULL, or a probability vector of the same length as \p * groups. \p p is the stationary probability distribution of a * Markov chain when \p mtype is \c IGRAPH_SCG_STOCHASTIC. This * argument is ignored in all other cases. * \param norm Either \c IGRAPH_SCG_NORM_ROW or \c IGRAPH_SCG_NORM_COL. * Specifies whether the rows or the columns of the Laplacian * matrix sum up to zero, or whether the rows or the columns of the * stochastic matrix sum up to one. * \return Error code. * * Time complexity: TODO. * * \sa \ref igraph_scg_adjacency(), \ref igraph_scg_stochastic() and * \ref igraph_scg_laplacian(), \ref igraph_scg_grouping(). * * \example examples/simple/igraph_scg_semiprojectors.c * \example examples/simple/igraph_scg_semiprojectors2.c * \example examples/simple/igraph_scg_semiprojectors3.c */ int igraph_scg_semiprojectors(const igraph_vector_t *groups, igraph_scg_matrix_t mtype, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse, const igraph_vector_t *p, igraph_scg_norm_t norm) { int no_of_nodes=(int) igraph_vector_size(groups); int no_of_groups; igraph_real_t min, max; igraph_vector_minmax(groups, &min, &max); no_of_groups=(int) max+1; if (min < 0 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid membership vector", IGRAPH_EINVAL); } if (mtype == IGRAPH_SCG_STOCHASTIC && !p) { IGRAPH_ERROR("`p' must be given for the stochastic matrix case", IGRAPH_EINVAL); } if (p && igraph_vector_size(p) != no_of_nodes) { IGRAPH_ERROR("Invalid `p' vector length, should match number of vertices", IGRAPH_EINVAL); } switch (mtype) { case IGRAPH_SCG_SYMMETRIC: IGRAPH_CHECK(igraph_i_scg_semiprojectors_sym(groups, L, R, Lsparse, Rsparse, no_of_groups, no_of_nodes)); break; case IGRAPH_SCG_LAPLACIAN: IGRAPH_CHECK(igraph_i_scg_semiprojectors_lap(groups, L, R, Lsparse, Rsparse, no_of_groups, no_of_nodes, norm)); break; case IGRAPH_SCG_STOCHASTIC: IGRAPH_CHECK(igraph_i_scg_semiprojectors_sto(groups, L, R, Lsparse, Rsparse, no_of_groups, no_of_nodes, p, norm)); break; } return 0; } /** * \function igraph_scg_norm_eps * Calculate SCG residuals * * Computes |v[i]-Pv[i]|, where v[i] is the i-th eigenvector in \p V * and P is the projector corresponding to the \p mtype argument. * * \param V The matrix of eigenvectors to be preserved by coarse * graining, each column is an eigenvector. * \param groups A vector of integers, giving the group label of every * vertex in the partition. Group labels should start at zero and * should be sequential. * \param eps Pointer to a real value, the result is stored here. * \param mtype The type of semi-projectors. For now \c * IGRAPH_SCG_SYMMETRIC, \c IGRAPH_SCG_STOCHASTIC and \c * IGRAP_SCG_LAPLACIAN are supported. * \param p \c NULL, or a probability vector of the same length as \p * groups. \p p is the stationary probability distribution of a * Markov chain when \p mtype is \c IGRAPH_SCG_STOCHASTIC. This * argument is ignored in all other cases. * \param norm Either \c IGRAPH_SCG_NORM_ROW or \c IGRAPH_SCG_NORM_COL. * Specifies whether the rows or the columns of the Laplacian * matrix sum up to zero, or whether the rows or the columns of the * stochastic matrix sum up to one. * \return Error code. * * Time complexity: TODO. * * \sa \ref igraph_scg_adjacency(), \ref igraph_scg_stochastic() and * \ref igraph_scg_laplacian(), \ref igraph_scg_grouping(), \ref * igraph_scg_semiprojectors(). */ int igraph_scg_norm_eps(const igraph_matrix_t *V, const igraph_vector_t *groups, igraph_vector_t *eps, igraph_scg_matrix_t mtype, const igraph_vector_t *p, igraph_scg_norm_t norm) { int no_of_nodes=(int) igraph_vector_size(groups); int no_of_groups; int no_of_vectors=(int) igraph_matrix_ncol(V); igraph_real_t min, max; igraph_sparsemat_t Lsparse, Rsparse, Lsparse2, Rsparse2, Rsparse3, proj; igraph_vector_t x, res; int k, i; if (igraph_matrix_nrow(V) != no_of_nodes) { IGRAPH_ERROR("Eigenvector length and group vector length do not match", IGRAPH_EINVAL); } igraph_vector_minmax(groups, &min, &max); no_of_groups=(int) max+1; if (min < 0 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid membership vector", IGRAPH_EINVAL); } if (mtype == IGRAPH_SCG_STOCHASTIC && !p) { IGRAPH_ERROR("`p' must be given for the stochastic matrix case", IGRAPH_EINVAL); } if (p && igraph_vector_size(p) != no_of_nodes) { IGRAPH_ERROR("Invalid `p' vector length, should match number of vertices", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_scg_semiprojectors(groups, mtype, /* L= */ 0, /* R= */ 0, &Lsparse, &Rsparse, p, norm)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &Lsparse); IGRAPH_FINALLY(igraph_sparsemat_destroy, &Rsparse); IGRAPH_CHECK(igraph_sparsemat_compress(&Lsparse, &Lsparse2)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &Lsparse2); IGRAPH_CHECK(igraph_sparsemat_compress(&Rsparse, &Rsparse2)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &Rsparse2); IGRAPH_CHECK(igraph_sparsemat_transpose(&Rsparse2, &Rsparse3, /*values=*/ 1)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &Rsparse3); IGRAPH_CHECK(igraph_sparsemat_multiply(&Rsparse3, &Lsparse2, &proj)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &proj); IGRAPH_VECTOR_INIT_FINALLY(&res, no_of_nodes); IGRAPH_CHECK(igraph_vector_resize(eps, no_of_vectors)); for (k = 0; k < no_of_vectors; k++) { igraph_vector_view(&x, &MATRIX(*V, 0, k), no_of_nodes); igraph_vector_null(&res); IGRAPH_CHECK(igraph_sparsemat_gaxpy(&proj, &x, &res)); VECTOR(*eps)[k] = 0.0; for (i = 0; i < no_of_nodes; i++) { igraph_real_t di=MATRIX(*V, i, k) - VECTOR(res)[i]; VECTOR(*eps)[k] += di * di; } VECTOR(*eps)[k] = sqrt(VECTOR(*eps)[k]); } igraph_vector_destroy(&res); igraph_sparsemat_destroy(&proj); igraph_sparsemat_destroy(&Rsparse3); igraph_sparsemat_destroy(&Rsparse2); igraph_sparsemat_destroy(&Lsparse2); igraph_sparsemat_destroy(&Rsparse); igraph_sparsemat_destroy(&Lsparse); IGRAPH_FINALLY_CLEAN(7); return 0; } int igraph_i_matrix_laplacian(const igraph_matrix_t *matrix, igraph_matrix_t *mymatrix, igraph_scg_norm_t norm) { igraph_vector_t degree; int i, j, n=(int) igraph_matrix_nrow(matrix); IGRAPH_CHECK(igraph_matrix_resize(mymatrix, n, n)); IGRAPH_VECTOR_INIT_FINALLY(°ree, n); if (norm==IGRAPH_SCG_NORM_ROW) { IGRAPH_CHECK(igraph_matrix_rowsum(matrix, °ree)); } else { IGRAPH_CHECK(igraph_matrix_colsum(matrix, °ree)); } for (i=0; i= no_of_nodes) { IGRAPH_ERROR("Invalid eigenvectors given", IGRAPH_EINVAL); } if (!nt_vec && (nt <= 1 || nt >= no_of_nodes)) { IGRAPH_ERROR("Invalid interval specification", IGRAPH_EINVAL); } if (nt_vec) { if (igraph_vector_size(nt_vec) != 1 && igraph_vector_size(nt_vec) != no_of_ev) { IGRAPH_ERROR("Invalid length for interval specification", IGRAPH_EINVAL); } igraph_vector_minmax(nt_vec, &min, &max); if (min <= 1 || max >= no_of_nodes) { IGRAPH_ERROR("Invalid interval specification", IGRAPH_EINVAL); } } if (vectors && igraph_matrix_size(vectors) != 0 && (igraph_matrix_ncol(vectors) != no_of_ev || igraph_matrix_nrow(vectors) != no_of_nodes)) { IGRAPH_ERROR("Invalid eigenvector matrix size", IGRAPH_EINVAL); } if (vectors_cmplx && igraph_matrix_complex_size(vectors_cmplx) != 0 && (igraph_matrix_complex_ncol(vectors_cmplx) != no_of_ev || igraph_matrix_complex_nrow(vectors_cmplx) != no_of_nodes)) { IGRAPH_ERROR("Invalid eigenvector matrix size", IGRAPH_EINVAL); } if (groups && igraph_vector_size(groups) != 0 && igraph_vector_size(groups) != no_of_nodes) { IGRAPH_ERROR("Invalid `groups' vector size", IGRAPH_EINVAL); } if ( (scg_graph!=0) + (scg_matrix!=0) + (scg_sparsemat!=0) == 0 ) { IGRAPH_ERROR("No output is requested, please give at least one of " "`scg_graph', `scg_matrix' and `scg_sparsemat'", IGRAPH_EINVAL); } if (p && igraph_vector_size(p) != 0 && igraph_vector_size(p) != no_of_nodes) { IGRAPH_ERROR("Invalid `p' vector size", IGRAPH_EINVAL); } return 0; } /** * \function igraph_scg_adjacency * Spectral coarse graining, symmetric case. * * This function handles all the steps involved in the Spectral Coarse * Graining (SCG) of some matrices and graphs as described in the * reference below. * * \param graph The input graph. Exactly one of \p graph, \p matrix * and \p sparsemat must be given, the other two must be \c NULL * pointers. * \param matrix The input matrix. Exactly one of \p graph, \p matrix * and \p sparsemat must be given, the other two must be \c NULL * pointers. * \param sparsemat The input sparse matrix. Exactly one of \p graph, * \p matrix and \p sparsemat must be given, the other two must be * \c NULL pointers. * \param ev A vector of positive integers giving the indexes of the * eigenpairs to be preserved. 1 designates the eigenvalue with * largest algebraic value, 2 the one with second largest algebraic * value, etc. * \param nt Positive integer. When \p algo is \c IGRAPH_SCG_OPTIMUM, * it gives the number of groups to partition each eigenvector * separately. When \p algo is \c IGRAPH_SCG_INTERV or \c * IGRAPH_SCG_INTERV_KM, it gives the number of intervals to * partition each eigenvector. This is ignored when \p algo is \c * IGRAPH_SCG_EXACT. * \param nt_vec A numeric vector of length one or the length must * match the number of eigenvectors given in \p V, or a \c NULL * pointer. If not \c NULL, then this argument gives the number of * groups or intervals, and \p nt is ignored. Different number of * groups or intervals can be specified for each eigenvector. * \param algo The algorithm to solve the SCG problem. Possible * values: \c IGRAPH_SCG_OPTIMUM, \c IGRAPH_SCG_INTERV_KM, \c * IGRAPH_SCG_INTERV and \c IGRAPH_SCG_EXACT. Please see the * details about them above. * \param values If this is not \c NULL and the eigenvectors are * re-calculated, then the eigenvalues are stored here. * \param vectors If this is not \c NULL, and not a zero-length * matrix, then it is interpreted as the eigenvectors to use for * the coarse-graining. Otherwise the eigenvectors are * re-calculated, and they are stored here. (If this is not \c NULL.) * \param groups If this is not \c NULL, and not a zero-length vector, * then it is interpreted as the vector of group labels. (Group * labels are integers from zero and are sequential.) Otherwise * group labels are re-calculated and stored here, if this argument * is not a null pointer. * \param use_arpack Whether to use ARPACK for solving the * eigenproblem. Currently ARPACK is not implemented. * \param maxiter A positive integer giving the number of iterations * of the k-means algorithm when \p algo is \c * IGRAPH_SCG_INTERV_KM. It is ignored in other cases. A reasonable * (initial) value for this argument is 100. * \param scg_graph If not a \c NULL pointer, then the coarse-grained * graph is returned here. * \param scg_matrix If not a \c NULL pointer, then it must be an * initialied matrix, and the coarse-grained matrix is returned * here. * \param scg_sparsemat If not a \c NULL pointer, then the coarse * grained matrix is returned here, in sparse matrix form. * \param L If not a \c NULL pointer, then it must be an initialized * matrix and the left semi-projector is returned here. * \param R If not a \c NULL pointer, then it must be an initialized * matrix and the right semi-projector is returned here. * \param Lsparse If not a \c NULL pointer, then the left * semi-projector is returned here. * \param Rsparse If not a \c NULL pointer, then the right * semi-projector is returned here. * \return Error code. * * Time complexity: TODO. * * \sa \ref igraph_scg_grouping(), \ref igraph_scg_semiprojectors(), * \ref igraph_scg_stochastic() and \ref igraph_scg_laplacian(). * * \example examples/simple/scg.c */ int igraph_scg_adjacency(const igraph_t *graph, const igraph_matrix_t *matrix, const igraph_sparsemat_t *sparsemat, const igraph_vector_t *ev, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_algorithm_t algo, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_t *groups, igraph_bool_t use_arpack, igraph_integer_t maxiter, igraph_t *scg_graph, igraph_matrix_t *scg_matrix, igraph_sparsemat_t *scg_sparsemat, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse) { igraph_sparsemat_t *mysparsemat=(igraph_sparsemat_t*) sparsemat, real_sparsemat; int no_of_ev=(int) igraph_vector_size(ev); /* eigenvectors are calculated and returned */ igraph_bool_t do_vectors= vectors && igraph_matrix_size(vectors)==0; /* groups are calculated */ igraph_bool_t do_groups= !groups || igraph_vector_size(groups)==0; /* eigenvectors are not returned but must be calculated for groups */ igraph_bool_t tmp_vectors= !do_vectors && do_groups; /* need temporary vector for groups */ igraph_bool_t tmp_groups= !groups; igraph_matrix_t myvectors; igraph_vector_t mygroups; igraph_bool_t tmp_lsparse=!Lsparse, tmp_rsparse=!Rsparse; igraph_sparsemat_t myLsparse, myRsparse, tmpsparse, Rsparse_t; int no_of_nodes; igraph_real_t evmin, evmax; igraph_bool_t directed; /* --------------------------------------------------------------------*/ /* Argument checks */ IGRAPH_CHECK(igraph_i_scg_common_checks(graph, matrix, sparsemat, ev, nt, nt_vec, vectors, 0, groups, scg_graph, scg_matrix, scg_sparsemat, /*p=*/ 0, &evmin, &evmax)); if (graph) { no_of_nodes=igraph_vcount(graph); directed=igraph_is_directed(graph); } else if (matrix) { no_of_nodes=(int) igraph_matrix_nrow(matrix); directed=!igraph_matrix_is_symmetric(matrix); } else { no_of_nodes=(int) igraph_sparsemat_nrow(sparsemat); directed=!igraph_sparsemat_is_symmetric(sparsemat); } /* -------------------------------------------------------------------- */ /* Convert graph, if needed */ if (graph) { mysparsemat=&real_sparsemat; IGRAPH_CHECK(igraph_get_sparsemat(graph, mysparsemat)); IGRAPH_FINALLY(igraph_sparsemat_destroy, mysparsemat); } /* -------------------------------------------------------------------- */ /* Compute eigenpairs, if needed */ if (tmp_vectors) { vectors=&myvectors; IGRAPH_MATRIX_INIT_FINALLY(vectors, no_of_nodes, no_of_ev); } if (do_vectors || tmp_vectors) { igraph_arpack_options_t options; igraph_eigen_which_t which; igraph_matrix_t tmp; igraph_vector_t tmpev; igraph_vector_t tmpeval; int i; which.pos = IGRAPH_EIGEN_SELECT; which.il = (int) (no_of_nodes-evmax+1); which.iu = (int) (no_of_nodes-evmin+1); if (values) { IGRAPH_VECTOR_INIT_FINALLY(&tmpeval, 0); } IGRAPH_CHECK(igraph_matrix_init(&tmp, no_of_nodes, which.iu-which.il+1)); IGRAPH_FINALLY(igraph_matrix_destroy, &tmp); IGRAPH_CHECK(igraph_eigen_matrix_symmetric(matrix, mysparsemat, /* fun= */ 0, no_of_nodes, /* extra= */ 0, /* algorithm= */ use_arpack ? IGRAPH_EIGEN_ARPACK : IGRAPH_EIGEN_LAPACK, &which, &options, /*storage=*/ 0, values ? &tmpeval : 0, &tmp)); IGRAPH_VECTOR_INIT_FINALLY(&tmpev, no_of_ev); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_cliques.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_constants.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_stack.h" #include "igraph_types_internal.h" #include "igraph_cliquer.h" #include "config.h" #include #include /* memset */ void igraph_i_cliques_free_res(igraph_vector_ptr_t *res) { long i, n; n = igraph_vector_ptr_size(res); for (i=0; i(*new_member_storage)[m-1]) { (*new_member_storage)[m++]=v2; n=m; } else { m=n; } } else { m=n; } } /* See if new_member_storage is full. If so, reallocate */ if (m == new_member_storage_size) { IGRAPH_FINALLY_CLEAN(1); *new_member_storage = igraph_Realloc(*new_member_storage, (size_t) new_member_storage_size*2, igraph_real_t); if (*new_member_storage == 0) IGRAPH_ERROR("cliques failed", IGRAPH_ENOMEM); new_member_storage_size *= 2; IGRAPH_FINALLY(igraph_free, *new_member_storage); } } } } /* Calculate how many cliques have we found */ *clique_count = n/size; IGRAPH_FINALLY_CLEAN(1); return 0; } /* Internal function for calculating cliques or independent vertex sets. * They are practically the same except that the complementer of the graph * should be used in the latter case. */ int igraph_i_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size, igraph_bool_t independent_vertices) { igraph_integer_t no_of_nodes; igraph_vector_t neis; igraph_real_t *member_storage=0, *new_member_storage, *c1; long int i, j, k, clique_count, old_clique_count; if (igraph_is_directed(graph)) IGRAPH_WARNING("directionality of edges is ignored for directed graphs"); no_of_nodes = igraph_vcount(graph); if (min_size < 0) { min_size = 0; } if (max_size > no_of_nodes || max_size <= 0) { max_size = no_of_nodes; } igraph_vector_ptr_clear(res); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_FINALLY(igraph_i_cliques_free_res, res); /* Will be resized later, if needed. */ member_storage=igraph_Calloc(1, igraph_real_t); if (member_storage==0) { IGRAPH_ERROR("cliques failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, member_storage); /* Find all 1-cliques: every vertex will be a clique */ new_member_storage=igraph_Calloc(no_of_nodes, igraph_real_t); if (new_member_storage==0) { IGRAPH_ERROR("cliques failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, new_member_storage); for (i=0; i 1; i++) { /* Here new_member_storage contains the cliques found in the previous iteration. Save this into member_storage, might be needed later */ c1=member_storage; member_storage=new_member_storage; new_member_storage=c1; old_clique_count=clique_count; IGRAPH_ALLOW_INTERRUPTION(); /* Calculate the cliques */ IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_i_find_k_cliques(graph, i, member_storage, &new_member_storage, old_clique_count, &clique_count, &neis, independent_vertices)); IGRAPH_FINALLY(igraph_free, member_storage); IGRAPH_FINALLY(igraph_free, new_member_storage); /* Add the cliques just found to the result if requested */ if (i>=min_size && i<=max_size) { for (j=0, k=0; j * Cliques are fully connected subgraphs of a graph. * * * If you are only interested in the size of the largest clique in the graph, * use \ref igraph_clique_number() instead. * * The current implementation of this function searches * for maximal independent vertex sets (see \ref * igraph_maximal_independent_vertex_sets()) in the complementer graph * using the algorithm published in: * S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm * for generating all the maximal independent sets. SIAM J Computing, * 6:505--517, 1977. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in a clique. * The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. * \param min_size Integer giving the minimum size of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the cliques to be * returned. If negative or zero, no upper bound will be used. * \return Error code. * * \sa \ref igraph_largest_cliques() and \ref igraph_clique_number(). * * Time complexity: TODO * * \example examples/simple/igraph_cliques.c */ int igraph_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size) { return igraph_i_cliquer_cliques(graph, res, min_size, max_size); } /** * \function igraph_clique_size_hist * \brief Count cliques of each size in the graph * * * Cliques are fully connected subgraphs of a graph. * * The current implementation of this function * uses version 1.21 of the Cliquer library by Sampo Niskanen and * Patric R. J. ÖstergÃ¥rd, http://users.aalto.fi/~pat/cliquer.html * * \param graph The input graph. * \param hist Pointer to an initialized vector. The result will be stored * here. The first element will store the number of size-1 cliques, the second * element the number of size-2 cliques, etc. For cliques smaller than \c min_size, * zero counts will be returned. * \param min_size Integer giving the minimum size of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the cliques to be * returned. If negative or zero, no upper bound will be used. * \return Error code. * * \sa \ref igraph_cliques() and \ref igraph_cliques_callback() * * Time complexity: Exponential * */ int igraph_clique_size_hist(const igraph_t *graph, igraph_vector_t *hist, igraph_integer_t min_size, igraph_integer_t max_size) { return igraph_i_cliquer_histogram(graph, hist, min_size, max_size); } /** * \function igraph_cliques_callback * \brief Calls a function for each clique in the graph. * * * Cliques are fully connected subgraphs of a graph. This function * enumerates all cliques within the given size range and calls * \p cliquehandler_fn for each of them. The cliques are passed to the * callback function as an igraph_vector_t *. Destroying and * freeing this vector is left up to the user. Use \ref igraph_vector_destroy() * to destroy it first, then free it using \ref igraph_free(). * * The current implementation of this function * uses version 1.21 of the Cliquer library by Sampo Niskanen and * Patric R. J. ÖstergÃ¥rd, http://users.aalto.fi/~pat/cliquer.html * * \param graph The input graph. * \param min_size Integer giving the minimum size of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the cliques to be * returned. If negative or zero, no upper bound will be used. * \param cliquehandler_fn Callback function to be called for each clique. * See also igraph_clique_handler_t. * \param arg Extra argument to supply to \p cliquehandler_fn. * \return Error code. * * \sa \ref igraph_cliques() * * Time complexity: Exponential * */ int igraph_cliques_callback(const igraph_t *graph, igraph_integer_t min_size, igraph_integer_t max_size, igraph_clique_handler_t *cliquehandler_fn, void *arg) { return igraph_i_cliquer_callback(graph, min_size, max_size, cliquehandler_fn, arg); } /** * \function igraph_weighted_cliques * \brief Find all cliques in a given weight range in a vertex weighted graph * * * Cliques are fully connected subgraphs of a graph. * The weight of a clique is the sum of the weights * of individual vertices within the clique. * * The current implementation of this function * uses version 1.21 of the Cliquer library by Sampo Niskanen and * Patric R. J. ÖstergÃ¥rd, http://users.aalto.fi/~pat/cliquer.html * * Only positive integer vertex weights are supported. * * \param graph The input graph. * \param vertex_weights A vector of vertex weights. The current implementation * will truncate all weights to their integer parts. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in a clique. * The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. * \param min_weight Integer giving the minimum weight of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_weight Integer giving the maximum weight of the cliques to be * returned. If negative or zero, no upper bound will be used. * \param maximal If true, only maximal cliques will be returned * \return Error code. * * \sa \ref igraph_cliques(), \ref igraph_maximal_cliques() * * Time complexity: Exponential * */ int igraph_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res, igraph_real_t min_weight, igraph_real_t max_weight, igraph_bool_t maximal) { return igraph_i_weighted_cliques(graph, vertex_weights, res, min_weight, max_weight, maximal); } /** * \function igraph_largest_weighted_cliques * \brief Finds the largest weight clique(s) in a graph. * * * Finds the clique(s) having the largest weight in the graph. * * The current implementation of this function * uses version 1.21 of the Cliquer library by Sampo Niskanen and * Patric R. J. ÖstergÃ¥rd, http://users.aalto.fi/~pat/cliquer.html * * Only positive integer vertex weights are supported. * * \param graph The input graph. * \param vertex_weights A vector of vertex weights. The current implementation * will truncate all weights to their integer parts. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in a clique. * The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. * \return Error code. * * \sa \ref igraph_weighted_cliques(), \ref igraph_weighted_clique_number(), \ref igraph_largest_cliques() * * Time complexity: TODO */ int igraph_largest_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res) { return igraph_i_largest_weighted_cliques(graph, vertex_weights, res); } /** * \function igraph_weighted_clique_number * \brief Find the weight of the largest weight clique in the graph * * The current implementation of this function * uses version 1.21 of the Cliquer library by Sampo Niskanen and * Patric R. J. ÖstergÃ¥rd, http://users.aalto.fi/~pat/cliquer.html * * Only positive integer vertex weights are supported. * * \param graph The input graph. * \param vertex_weights A vector of vertex weights. The current implementation * will truncate all weights to their integer parts. * \param res The largest weight will be returned to the \c igraph_real_t * pointed to by this variable. * \return Error code. * * \sa \ref igraph_weighted_cliques(), \ref igraph_largest_weighted_cliques(), \ref igraph_clique_number() * * Time complexity: TODO * */ int igraph_weighted_clique_number(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_real_t *res) { return igraph_i_weighted_clique_number(graph, vertex_weights, res); } typedef int(*igraph_i_maximal_clique_func_t)(const igraph_vector_t*, void*, igraph_bool_t*); typedef struct { igraph_vector_ptr_t* result; igraph_integer_t min_size; igraph_integer_t max_size; } igraph_i_maximal_clique_data_t; int igraph_i_maximal_cliques(const igraph_t *graph, igraph_i_maximal_clique_func_t func, void* data); int igraph_i_maximal_or_largest_cliques_or_indsets(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t *clique_number, igraph_bool_t keep_only_largest, igraph_bool_t complementer); /** * \function igraph_independent_vertex_sets * \brief Find all independent vertex sets in a graph * * * A vertex set is considered independent if there are no edges between * them. * * * If you are interested in the size of the largest independent vertex set, * use \ref igraph_independence_number() instead. * * * The current implementation was ported to igraph from the Very Nauty Graph * Library by Keith Briggs and uses the algorithm from the paper * S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm * for generating all the maximal independent sets. SIAM J Computing, * 6:505--517, 1977. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in an independent * vertex set. The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. * \param min_size Integer giving the minimum size of the sets to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the sets to be * returned. If negative or zero, no upper bound will be used. * \return Error code. * * \sa \ref igraph_largest_independent_vertex_sets(), * \ref igraph_independence_number(). * * Time complexity: TODO * * \example examples/simple/igraph_independent_sets.c */ int igraph_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size) { return igraph_i_cliques(graph, res, min_size, max_size, 1); } /** * \function igraph_largest_independent_vertex_sets * \brief Finds the largest independent vertex set(s) in a graph. * * * An independent vertex set is largest if there is no other * independent vertex set with more vertices in the graph. * * * The current implementation was ported to igraph from the Very Nauty Graph * Library by Keith Briggs and uses the algorithm from the paper * S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm * for generating all the maximal independent sets. SIAM J Computing, * 6:505--517, 1977. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here. It will be resized as needed. * \return Error code. * * \sa \ref igraph_independent_vertex_sets(), \ref * igraph_maximal_independent_vertex_sets(). * * Time complexity: TODO */ int igraph_largest_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res) { return igraph_i_maximal_or_largest_cliques_or_indsets(graph, res, 0, 1, 0); } typedef struct igraph_i_max_ind_vsets_data_t { igraph_integer_t matrix_size; igraph_adjlist_t adj_list; /* Adjacency list of the graph */ igraph_vector_t deg; /* Degrees of individual nodes */ igraph_set_t* buckets; /* Bucket array */ /* The IS value for each node. Still to be explained :) */ igraph_integer_t* IS; igraph_integer_t largest_set_size; /* Size of the largest set encountered */ igraph_bool_t keep_only_largest; /* True if we keep only the largest sets */ } igraph_i_max_ind_vsets_data_t; int igraph_i_maximal_independent_vertex_sets_backtrack(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_i_max_ind_vsets_data_t *clqdata, igraph_integer_t level) { long int v1, v2, v3, c, j, k; igraph_vector_int_t *neis1, *neis2; igraph_bool_t f; igraph_integer_t j1; long int it_state; IGRAPH_ALLOW_INTERRUPTION(); if (level >= clqdata->matrix_size-1) { igraph_integer_t size=0; if (res) { igraph_vector_t *vec; vec = igraph_Calloc(1, igraph_vector_t); if (vec == 0) IGRAPH_ERROR("igraph_i_maximal_independent_vertex_sets failed", IGRAPH_ENOMEM); IGRAPH_VECTOR_INIT_FINALLY(vec, 0); for (v1=0; v1matrix_size; v1++) if (clqdata->IS[v1] == 0) { IGRAPH_CHECK(igraph_vector_push_back(vec, v1)); } size=(igraph_integer_t) igraph_vector_size(vec); if (!clqdata->keep_only_largest) IGRAPH_CHECK(igraph_vector_ptr_push_back(res, vec)); else { if (size > clqdata->largest_set_size) { /* We are keeping only the largest sets, and we've found one that's * larger than all previous sets, so we have to clear the list */ j=igraph_vector_ptr_size(res); for (v1=0; v1largest_set_size) { IGRAPH_CHECK(igraph_vector_ptr_push_back(res, vec)); } else { igraph_vector_destroy(vec); free(vec); } } IGRAPH_FINALLY_CLEAN(1); } else { for (v1=0, size=0; v1matrix_size; v1++) if (clqdata->IS[v1] == 0) size++; } if (size>clqdata->largest_set_size) clqdata->largest_set_size=size; } else { v1 = level+1; /* Count the number of vertices with an index less than v1 that have * an IS value of zero */ neis1 = igraph_adjlist_get(&clqdata->adj_list, v1); c = 0; j = 0; while (jdeg)[v1] && (v2=(long int) VECTOR(*neis1)[j]) <= level) { if (clqdata->IS[v2] == 0) c++; j++; } if (c == 0) { /* If there are no such nodes... */ j = 0; while (jdeg)[v1] && (v2=(long int) VECTOR(*neis1)[j]) <= level) { clqdata->IS[v2]++; j++; } IGRAPH_CHECK(igraph_i_maximal_independent_vertex_sets_backtrack(graph,res,clqdata, (igraph_integer_t) v1)); j = 0; while (jdeg)[v1] && (v2=(long int) VECTOR(*neis1)[j]) <= level) { clqdata->IS[v2]--; j++; } } else { /* If there are such nodes, store the count in the IS value of v1 */ clqdata->IS[v1] = (igraph_integer_t) c; IGRAPH_CHECK(igraph_i_maximal_independent_vertex_sets_backtrack(graph,res,clqdata, (igraph_integer_t) v1)); clqdata->IS[v1] = 0; f=1; j=0; while (jdeg)[v1] && (v2=(long int) VECTOR(*neis1)[j]) <= level) { if (clqdata->IS[v2] == 0) { IGRAPH_CHECK(igraph_set_add(&clqdata->buckets[v1], (igraph_integer_t) j)); neis2 = igraph_adjlist_get(&clqdata->adj_list, v2); k = 0; while (kdeg)[v2] && (v3=(long int) VECTOR(*neis2)[k])<=level) { clqdata->IS[v3]--; if (clqdata->IS[v3] == 0) f=0; k++; } } clqdata->IS[v2]++; j++; } if (f) IGRAPH_CHECK(igraph_i_maximal_independent_vertex_sets_backtrack(graph,res,clqdata, (igraph_integer_t) v1)); j=0; while (jdeg)[v1] && (v2=(long int) VECTOR(*neis1)[j]) <= level) { clqdata->IS[v2]--; j++; } it_state=0; while (igraph_set_iterate(&clqdata->buckets[v1], &it_state, &j1)) { j=(long)j1; v2=(long int) VECTOR(*neis1)[j]; neis2 = igraph_adjlist_get(&clqdata->adj_list, v2); k = 0; while (kdeg)[v2] && (v3=(long int) VECTOR(*neis2)[k])<=level) { clqdata->IS[v3]++; k++; } } igraph_set_clear(&clqdata->buckets[v1]); } } return 0; } void igraph_i_free_set_array(igraph_set_t* array) { long int i = 0; while (igraph_set_inited(array+i)) { igraph_set_destroy(array+i); i++; } igraph_Free(array); } /** * \function igraph_maximal_independent_vertex_sets * \brief Find all maximal independent vertex sets of a graph * * * A maximal independent vertex set is an independent vertex set which * can't be extended any more by adding a new vertex to it. * * * The algorithm used here is based on the following paper: * S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm for * generating all the maximal independent sets. SIAM J Computing, * 6:505--517, 1977. * * * The implementation was originally written by Kevin O'Neill and modified * by K M Briggs in the Very Nauty Graph Library. I simply re-wrote it to * use igraph's data structures. * * * If you are interested in the size of the largest independent vertex set, * use \ref igraph_independence_number() instead. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in an independent * vertex set. The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. * \return Error code. * * \sa \ref igraph_maximal_cliques(), \ref * igraph_independence_number() * * Time complexity: TODO. */ int igraph_maximal_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res) { igraph_i_max_ind_vsets_data_t clqdata; igraph_integer_t no_of_nodes = (igraph_integer_t) igraph_vcount(graph), i; if (igraph_is_directed(graph)) IGRAPH_WARNING("directionality of edges is ignored for directed graphs"); clqdata.matrix_size=no_of_nodes; clqdata.keep_only_largest=0; IGRAPH_CHECK(igraph_adjlist_init(graph, &clqdata.adj_list, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &clqdata.adj_list); clqdata.IS = igraph_Calloc(no_of_nodes, igraph_integer_t); if (clqdata.IS == 0) IGRAPH_ERROR("igraph_maximal_independent_vertex_sets failed", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, clqdata.IS); IGRAPH_VECTOR_INIT_FINALLY(&clqdata.deg, no_of_nodes); for (i=0; i * The independence number of a graph is the cardinality of the largest * independent vertex set. * * * The current implementation was ported to igraph from the Very Nauty Graph * Library by Keith Briggs and uses the algorithm from the paper * S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm * for generating all the maximal independent sets. SIAM J Computing, * 6:505--517, 1977. * * \param graph The input graph. * \param no The independence number will be returned to the \c * igraph_integer_t pointed by this variable. * \return Error code. * * \sa \ref igraph_independent_vertex_sets(). * * Time complexity: TODO. */ int igraph_independence_number(const igraph_t *graph, igraph_integer_t *no) { igraph_i_max_ind_vsets_data_t clqdata; igraph_integer_t no_of_nodes = (igraph_integer_t) igraph_vcount(graph), i; if (igraph_is_directed(graph)) IGRAPH_WARNING("directionality of edges is ignored for directed graphs"); clqdata.matrix_size=no_of_nodes; clqdata.keep_only_largest=0; IGRAPH_CHECK(igraph_adjlist_init(graph, &clqdata.adj_list, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &clqdata.adj_list); clqdata.IS = igraph_Calloc(no_of_nodes, igraph_integer_t); if (clqdata.IS == 0) IGRAPH_ERROR("igraph_independence_number failed", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, clqdata.IS); IGRAPH_VECTOR_INIT_FINALLY(&clqdata.deg, no_of_nodes); for (i=0; imin_size || size > data->max_size) return IGRAPH_SUCCESS; vec = igraph_Calloc(1, igraph_vector_t); if (vec == 0) IGRAPH_ERROR("cannot allocate memory for storing next clique", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_copy(vec, clique)); IGRAPH_CHECK(igraph_vector_ptr_push_back(data->result, vec)); return IGRAPH_SUCCESS; } int igraph_i_largest_cliques_store(const igraph_vector_t* clique, void* data, igraph_bool_t* cont) { igraph_vector_ptr_t* result = (igraph_vector_ptr_t*)data; igraph_vector_t* vec; long int i, n; IGRAPH_UNUSED(cont); /* Is the current clique at least as large as the others that we have found? */ if (!igraph_vector_ptr_empty(result)) { n = igraph_vector_size(clique); if (n < igraph_vector_size(VECTOR(*result)[0])) return IGRAPH_SUCCESS; if (n > igraph_vector_size(VECTOR(*result)[0])) { for (i = 0; i < igraph_vector_ptr_size(result); i++) igraph_vector_destroy(VECTOR(*result)[i]); igraph_vector_ptr_free_all(result); igraph_vector_ptr_resize(result, 0); } } vec = igraph_Calloc(1, igraph_vector_t); if (vec == 0) IGRAPH_ERROR("cannot allocate memory for storing next clique", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_copy(vec, clique)); IGRAPH_CHECK(igraph_vector_ptr_push_back(result, vec)); return IGRAPH_SUCCESS; } /** * \function igraph_largest_cliques * \brief Finds the largest clique(s) in a graph. * * * A clique is largest (quite intuitively) if there is no other clique * in the graph which contains more vertices. * * * Note that this is not necessarily the same as a maximal clique, * ie. the largest cliques are always maximal but a maximal clique is * not always largest. * * The current implementation of this function searches * for maximal cliques using \ref igraph_maximal_cliques() and drops * those that are not the largest. * * The implementation of this function changed between * igraph 0.5 and 0.6, so the order of the cliques and the order of * vertices within the cliques will almost surely be different between * these two versions. * * \param graph The input graph. * \param res Pointer to an initialized pointer vector, the result * will be stored here. It will be resized as needed. Note that * vertices of a clique may be returned in arbitrary order. * \return Error code. * * \sa \ref igraph_cliques(), \ref igraph_maximal_cliques() * * Time complexity: O(3^(|V|/3)) worst case. */ int igraph_largest_cliques(const igraph_t *graph, igraph_vector_ptr_t *res) { igraph_vector_ptr_clear(res); IGRAPH_FINALLY(igraph_i_cliques_free_res, res); IGRAPH_CHECK(igraph_i_maximal_cliques(graph, &igraph_i_largest_cliques_store, (void*)res)); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \function igraph_clique_number * \brief Find the clique number of the graph * * * The clique number of a graph is the size of the largest clique. * * \param graph The input graph. * \param no The clique number will be returned to the \c igraph_integer_t * pointed by this variable. * \return Error code. * * \sa \ref igraph_cliques(), \ref igraph_largest_cliques(). * * Time complexity: O(3^(|V|/3)) worst case. */ int igraph_clique_number(const igraph_t *graph, igraph_integer_t *no) { *no = 0; return igraph_i_maximal_cliques(graph, &igraph_i_maximal_cliques_store_max_size, (void*)no); } typedef struct { igraph_vector_int_t cand; igraph_vector_int_t fini; igraph_vector_int_t cand_filtered; } igraph_i_maximal_cliques_stack_frame; void igraph_i_maximal_cliques_stack_frame_destroy(igraph_i_maximal_cliques_stack_frame *frame) { igraph_vector_int_destroy(&frame->cand); igraph_vector_int_destroy(&frame->fini); igraph_vector_int_destroy(&frame->cand_filtered); } void igraph_i_maximal_cliques_stack_destroy(igraph_stack_ptr_t *stack) { igraph_i_maximal_cliques_stack_frame *frame; while (!igraph_stack_ptr_empty(stack)) { frame = (igraph_i_maximal_cliques_stack_frame*)igraph_stack_ptr_pop(stack); igraph_i_maximal_cliques_stack_frame_destroy(frame); free(frame); } igraph_stack_ptr_destroy(stack); } int igraph_i_maximal_cliques(const igraph_t *graph, igraph_i_maximal_clique_func_t func, void* data) { int directed=igraph_is_directed(graph); long int i, j, k, l; igraph_integer_t no_of_nodes, nodes_to_check, nodes_done; igraph_integer_t best_cand = 0, best_cand_degree = 0, best_fini_cand_degree; igraph_adjlist_t adj_list; igraph_stack_ptr_t stack; igraph_i_maximal_cliques_stack_frame frame, *new_frame_ptr; igraph_vector_t clique; igraph_vector_int_t new_cand, new_fini, cn, best_cand_nbrs, best_fini_cand_nbrs; igraph_bool_t cont = 1; int assret; if (directed) IGRAPH_WARNING("directionality of edges is ignored for directed graphs"); no_of_nodes = igraph_vcount(graph); if (no_of_nodes == 0) return IGRAPH_SUCCESS; /* Construct an adjacency list representation */ IGRAPH_CHECK(igraph_adjlist_init(graph, &adj_list, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adj_list); IGRAPH_CHECK(igraph_adjlist_simplify(&adj_list)); igraph_adjlist_sort(&adj_list); /* Initialize stack */ IGRAPH_CHECK(igraph_stack_ptr_init(&stack, 0)); IGRAPH_FINALLY(igraph_i_maximal_cliques_stack_destroy, &stack); /* Create the initial (empty) clique */ IGRAPH_VECTOR_INIT_FINALLY(&clique, 0); /* Initialize new_cand, new_fini, cn, best_cand_nbrs and best_fini_cand_nbrs (will be used later) */ igraph_vector_int_init(&new_cand, 0); IGRAPH_FINALLY(igraph_vector_int_destroy, &new_cand); igraph_vector_int_init(&new_fini, 0); IGRAPH_FINALLY(igraph_vector_int_destroy, &new_fini); igraph_vector_int_init(&cn, 0); IGRAPH_FINALLY(igraph_vector_int_destroy, &cn); igraph_vector_int_init(&best_cand_nbrs, 0); IGRAPH_FINALLY(igraph_vector_int_destroy, &best_cand_nbrs); igraph_vector_int_init(&best_fini_cand_nbrs, 0); IGRAPH_FINALLY(igraph_vector_int_destroy, &best_fini_cand_nbrs); /* Find the vertex with the highest degree */ best_cand = 0; best_cand_degree = (igraph_integer_t) igraph_vector_int_size(igraph_adjlist_get(&adj_list, 0)); for (i = 1; i < no_of_nodes; i++) { j = igraph_vector_int_size(igraph_adjlist_get(&adj_list, i)); if (j > best_cand_degree) { best_cand = (igraph_integer_t) i; best_cand_degree = (igraph_integer_t) j; } } /* Create the initial stack frame */ IGRAPH_CHECK(igraph_vector_int_init_seq(&frame.cand, 0, no_of_nodes-1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &frame.cand); IGRAPH_CHECK(igraph_vector_int_init(&frame.fini, 0)); IGRAPH_FINALLY(igraph_vector_int_destroy, &frame.fini); IGRAPH_CHECK(igraph_vector_int_init(&frame.cand_filtered, 0)); IGRAPH_FINALLY(igraph_vector_int_destroy, &frame.cand_filtered); IGRAPH_CHECK(igraph_vector_int_difference_sorted(&frame.cand, igraph_adjlist_get(&adj_list, best_cand), &frame.cand_filtered)); IGRAPH_FINALLY_CLEAN(3); IGRAPH_FINALLY(igraph_i_maximal_cliques_stack_frame_destroy, &frame); /* TODO: frame.cand and frame.fini should be a set instead of a vector */ /* Main loop starts here */ nodes_to_check = (igraph_integer_t) igraph_vector_int_size(&frame.cand_filtered); nodes_done = 0; while (!igraph_vector_int_empty(&frame.cand_filtered) || !igraph_stack_ptr_empty(&stack)) { if (igraph_vector_int_empty(&frame.cand_filtered)) { /* No candidates left to check in this stack frame, pop out the previous stack frame */ igraph_i_maximal_cliques_stack_frame *newframe = igraph_stack_ptr_pop(&stack); igraph_i_maximal_cliques_stack_frame_destroy(&frame); frame = *newframe; free(newframe); if (igraph_stack_ptr_size(&stack) == 1) { /* We will be using the next candidate node in the next iteration, so we can increase * nodes_done by 1 */ nodes_done++; } /* For efficiency reasons, we only check for interruption and show progress here */ IGRAPH_PROGRESS("Maximal cliques: ", 100.0 * nodes_done / nodes_to_check, NULL); IGRAPH_ALLOW_INTERRUPTION(); igraph_vector_pop_back(&clique); continue; } /* Try the next node in the clique */ i = (long int) igraph_vector_int_pop_back(&frame.cand_filtered); IGRAPH_CHECK(igraph_vector_push_back(&clique, i)); /* Remove the node from the candidate list */ assret=igraph_vector_int_binsearch(&frame.cand, i, &j); assert(assret); igraph_vector_int_remove(&frame.cand, j); /* Add the node to the finished list */ assret = !igraph_vector_int_binsearch(&frame.fini, i, &j); assert(assret); IGRAPH_CHECK(igraph_vector_int_insert(&frame.fini, j, i)); /* Create new_cand and new_fini */ IGRAPH_CHECK(igraph_vector_int_intersect_sorted(&frame.cand, igraph_adjlist_get(&adj_list, i), &new_cand)); IGRAPH_CHECK(igraph_vector_int_intersect_sorted(&frame.fini, igraph_adjlist_get(&adj_list, i), &new_fini)); /* Do we have anything more to search? */ if (igraph_vector_int_empty(&new_cand)) { if (igraph_vector_int_empty(&new_fini)) { /* We have a maximal clique here */ IGRAPH_CHECK(func(&clique, data, &cont)); if (!cont) { /* The callback function requested to stop the search */ break; } } igraph_vector_pop_back(&clique); continue; } if (igraph_vector_int_empty(&new_fini) && igraph_vector_int_size(&new_cand) == 1) { /* Shortcut: only one node left */ IGRAPH_CHECK(igraph_vector_push_back(&clique, VECTOR(new_cand)[0])); IGRAPH_CHECK(func(&clique, data, &cont)); if (!cont) { /* The callback function requested to stop the search */ break; } igraph_vector_pop_back(&clique); igraph_vector_pop_back(&clique); continue; } /* Find the next best candidate node in new_fini */ l = igraph_vector_int_size(&new_cand); best_cand_degree = -1; j = igraph_vector_int_size(&new_fini); for (i = 0; i < j; i++) { k = (long int)VECTOR(new_fini)[i]; IGRAPH_CHECK(igraph_vector_int_intersect_sorted(&new_cand, igraph_adjlist_get(&adj_list, k), &cn)); if (igraph_vector_int_size(&cn) > best_cand_degree) { best_cand_degree = (igraph_integer_t) igraph_vector_int_size(&cn); IGRAPH_CHECK(igraph_vector_int_update(&best_fini_cand_nbrs, &cn)); if (best_cand_degree == l) { /* Cool, we surely have the best candidate node here as best_cand_degree can't get any better */ break; } } } /* Shortcut here: we don't have to examine new_cand */ if (best_cand_degree == l) { igraph_vector_pop_back(&clique); continue; } /* Still finding best candidate node */ best_fini_cand_degree = best_cand_degree; best_cand_degree = -1; j = igraph_vector_int_size(&new_cand); l = l - 1; for (i = 0; i < j; i++) { k = (long int)VECTOR(new_cand)[i]; IGRAPH_CHECK(igraph_vector_int_intersect_sorted(&new_cand, igraph_adjlist_get(&adj_list, k), &cn)); if (igraph_vector_int_size(&cn) > best_cand_degree) { best_cand_degree = (igraph_integer_t) igraph_vector_int_size(&cn); IGRAPH_CHECK(igraph_vector_int_update(&best_cand_nbrs, &cn)); if (best_cand_degree == l) { /* Cool, we surely have the best candidate node here as best_cand_degree can't get any better */ break; } } } /* Create a new stack frame in case we back out later */ new_frame_ptr = igraph_Calloc(1, igraph_i_maximal_cliques_stack_frame); if (new_frame_ptr == 0) { IGRAPH_ERROR("cannot allocate new stack frame", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, new_frame_ptr); *new_frame_ptr = frame; memset(&frame, 0, sizeof(frame)); IGRAPH_CHECK(igraph_stack_ptr_push(&stack, new_frame_ptr)); IGRAPH_FINALLY_CLEAN(1); /* ownership of new_frame_ptr taken by the stack */ /* Ownership of the current frame and its vectors (frame.cand, frame.done, frame.cand_filtered) * is taken by the stack from now on. Vectors in frame must be re-initialized with new_cand, * new_fini and stuff. The old frame.cand and frame.fini won't be leaked because they are * managed by the stack now. */ frame.cand = new_cand; frame.fini = new_fini; IGRAPH_CHECK(igraph_vector_int_init(&new_cand, 0)); IGRAPH_CHECK(igraph_vector_int_init(&new_fini, 0)); IGRAPH_CHECK(igraph_vector_int_init(&frame.cand_filtered, 0)); /* Adjust frame.cand_filtered */ if (best_cand_degree < best_fini_cand_degree) { IGRAPH_CHECK(igraph_vector_int_difference_sorted(&frame.cand, &best_fini_cand_nbrs, &frame.cand_filtered)); } else { IGRAPH_CHECK(igraph_vector_int_difference_sorted(&frame.cand, &best_cand_nbrs, &frame.cand_filtered)); } } IGRAPH_PROGRESS("Maximal cliques: ", 100.0, NULL); igraph_adjlist_destroy(&adj_list); igraph_vector_destroy(&clique); igraph_vector_int_destroy(&new_cand); igraph_vector_int_destroy(&new_fini); igraph_vector_int_destroy(&cn); igraph_vector_int_destroy(&best_cand_nbrs); igraph_vector_int_destroy(&best_fini_cand_nbrs); igraph_i_maximal_cliques_stack_frame_destroy(&frame); igraph_i_maximal_cliques_stack_destroy(&stack); IGRAPH_FINALLY_CLEAN(9); return IGRAPH_SUCCESS; } int igraph_i_maximal_or_largest_cliques_or_indsets(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t *clique_number, igraph_bool_t keep_only_largest, igraph_bool_t complementer) { igraph_i_max_ind_vsets_data_t clqdata; igraph_integer_t no_of_nodes = (igraph_integer_t) igraph_vcount(graph), i; if (igraph_is_directed(graph)) IGRAPH_WARNING("directionality of edges is ignored for directed graphs"); clqdata.matrix_size=no_of_nodes; clqdata.keep_only_largest=keep_only_largest; if (complementer) IGRAPH_CHECK(igraph_adjlist_init_complementer(graph, &clqdata.adj_list, IGRAPH_ALL, 0)); else IGRAPH_CHECK(igraph_adjlist_init(graph, &clqdata.adj_list, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &clqdata.adj_list); clqdata.IS = igraph_Calloc(no_of_nodes, igraph_integer_t); if (clqdata.IS == 0) IGRAPH_ERROR("igraph_i_maximal_or_largest_cliques_or_indsets failed", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, clqdata.IS); IGRAPH_VECTOR_INIT_FINALLY(&clqdata.deg, no_of_nodes); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // **************************************************************************************************** // *** COPYRIGHT NOTICE ******************************************************************************* // dendro_eq.h - hierarchical random graph (hrg) data structure // Copyright (C) 2006-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // **************************************************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science AND Santa Fe Institute // Created : 19 April 2006 // Modified : 19 May 2007 // : 19 May 2008 (cleaned up for public consumption) // // **************************************************************************************************** // // Maximum likelihood dendrogram data structure. This is the heart of the HRG algorithm: all // manipulations are done here and all data is stored here. The data structure uses the separate // graph data structure to store the basic adjacency information (in a dangerously mutable way). // // Note: This version (dendro_eq.h) differs from other versions because it includes methods for // doing the consensus dendrogram calculation. // // **************************************************************************************************** #ifndef IGRAPH_HRG_DENDRO #define IGRAPH_HRG_DENDRO #include #include #include #include #include "hrg_graph.h" #include "hrg_rbtree.h" #include "hrg_splittree_eq.h" #include "igraph_hrg.h" using namespace std; using namespace fitHRG; namespace fitHRG { // *********************************************************************** // ******** Basic Structures ********************************************* #ifndef IGRAPH_HRG_LIST #define IGRAPH_HRG_LIST class list { public: int x; // stored elementd in linked-list list* next; // pointer to next elementd list::list(): x(-1), next(0) { } list::~list() { } }; #endif enum {DENDRO, GRAPH, LEFT, RIGHT}; struct block { double x; int y; }; struct ipair { int x; int y; short int t; string sp; }; struct child { int index; short int type; child* next; }; // *********************************************************************** // ******** Cnode Class ************************************************** #ifndef IGRAPH_HRG_CNODE #define IGRAPH_HRG_CNODE class cnode { public: int index; // array index of this node int degree; // number of children in list int parent; // index of parent node double weight; // sampled posterior weight child* children; // list of children (and their types) child* lastChild; // pointer to last child in list cnode(): index(-1), degree(0), parent(-1), weight(0.0), children(0), lastChild(0) { } ~cnode() { child *curr, *prev; curr = children; while (curr != NULL) { prev = curr; curr = curr->next; delete prev; prev = NULL; } lastChild = NULL; } }; #endif // *********************************************************************** // ******** Split Class ************************************************** class split { public: string s; // partition assignment of leaf vertices split(): s("") { } ~split() { } void initializeSplit(const int n) { s = ""; for (int i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include /* memset */ #include #include "igraph_centrality.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #include "igraph_topology.h" #include "igraph_types_internal.h" #include "igraph_stack.h" #include "igraph_dqueue.h" #include "config.h" #include "bigint.h" #include "prpack.h" int igraph_personalized_pagerank_arpack(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights, igraph_arpack_options_t *options); igraph_bool_t igraph_i_vector_mostly_negative(const igraph_vector_t *vector) { /* Many of the centrality measures correspond to the eigenvector of some * matrix. When v is an eigenvector, c*v is also an eigenvector, therefore * it may happen that all the scores in the eigenvector are negative, in which * case we want to negate them since the centrality scores should be positive. * However, since ARPACK is not always stable, sometimes it happens that * *some* of the centrality scores are small negative numbers. This function * helps distinguish between the two cases; it should return true if most of * the values are relatively large negative numbers, in which case we should * negate the eigenvector. */ long int i, n = igraph_vector_size(vector); igraph_real_t mi, ma; if (n == 0) return 0; mi = ma = VECTOR(*vector)[0]; for (i = 1; i < n; i++) { if (VECTOR(*vector)[i] < mi) mi = VECTOR(*vector)[i]; if (VECTOR(*vector)[i] > ma) ma = VECTOR(*vector)[i]; } if (mi >= 0) return 0; if (ma <= 0) return 1; mi /= ma; return (mi < 1e-5) ? 1 : 0; } int igraph_i_eigenvector_centrality(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_adjlist_t *adjlist=extra; igraph_vector_int_t *neis; long int i, j, nlen; for (i=0; igraph; const igraph_inclist_t *inclist=data->inclist; const igraph_vector_t *weights=data->weights; igraph_vector_int_t *edges; long int i, j, nlen; for (i=0; in=igraph_vcount(graph); options->start=1; /* no random start vector */ if (igraph_ecount(graph) == 0) { /* special case: empty graph */ if (value) *value = 0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 1); } return IGRAPH_SUCCESS; } if (weights) { igraph_real_t min, max; if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid length of weights vector when calculating " "eigenvector centrality", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_minmax(weights, &min, &max)); if (min == 0 && max == 0) { /* special case: all weights are zeros */ if (value) *value = 0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 1); } return IGRAPH_SUCCESS; } } IGRAPH_VECTOR_INIT_FINALLY(&values, 0); IGRAPH_MATRIX_INIT_FINALLY(&vectors, options->n, 1); IGRAPH_VECTOR_INIT_FINALLY(°ree, options->n); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, /*loops=*/ 0)); RNG_BEGIN(); for (i=0; in; i++) { if (VECTOR(degree)[i]) { MATRIX(vectors, i, 0) = VECTOR(degree)[i] + RNG_UNIF(-1e-4, 1e-4); } else { MATRIX(vectors, i, 0) = 1.0; } } RNG_END(); igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(1); options->n = igraph_vcount(graph); options->nev = 1; options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rssolve */ options->which[0]='L'; options->which[1]='A'; options->start=1; /* no random start vector */ if (!weights) { igraph_adjlist_t adjlist; IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_i_eigenvector_centrality_loop(&adjlist)); IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_eigenvector_centrality, &adjlist, options, 0, &values, &vectors)); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); } else { igraph_inclist_t inclist; igraph_i_eigenvector_centrality_t data = { graph, &inclist, weights }; IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_inclist_remove_duplicate(graph, &inclist)); IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_eigenvector_centrality2, &data, options, 0, &values, &vectors)); igraph_inclist_destroy(&inclist); IGRAPH_FINALLY_CLEAN(1); } if (value) { *value=VECTOR(values)[0]; } if (vector) { igraph_real_t amax=0; long int which=0; long int i; IGRAPH_CHECK(igraph_vector_resize(vector, options->n)); if (VECTOR(values)[0] <= 0) { /* Pathological case: largest eigenvalue is zero, therefore all the * scores can also be zeros, this will be a valid eigenvector. * This usually happens with graphs that have lots of sinks and * sources only. */ igraph_vector_fill(vector, 0); } else { for (i=0; in; i++) { igraph_real_t tmp; VECTOR(*vector)[i] = MATRIX(vectors, i, 0); tmp=fabs(VECTOR(*vector)[i]); if (tmp>amax) { amax=tmp; which=i; } } if (scale && amax!=0) { igraph_vector_scale(vector, 1/VECTOR(*vector)[which]); } else if (igraph_i_vector_mostly_negative(vector)) { igraph_vector_scale(vector, -1.0); } /* Correction for numeric inaccuracies (eliminating -0.0) */ for (i=0; in; i++) { if (VECTOR(*vector)[i] < 0) VECTOR(*vector)[i] = 0; } } } if (options->info) { IGRAPH_WARNING("Non-zero return code from ARPACK routine!"); } igraph_matrix_destroy(&vectors); igraph_vector_destroy(&values); IGRAPH_FINALLY_CLEAN(2); return 0; } /* int igraph_i_evcent_dir(igraph_real_t *to, const igraph_real_t *from, */ /* long int n, void *extra) { */ /* /\* TODO *\/ */ /* return 0; */ /* } */ /* int igraph_i_evcent_dir2(igraph_real_t *to, const igraph_real_t *from, */ /* long int n, void *extra) { */ /* /\* TODO *\/ */ /* return 0; */ /* } */ int igraph_eigenvector_centrality_directed(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options) { igraph_matrix_t values; igraph_matrix_t vectors; igraph_vector_t indegree; igraph_bool_t dag; long int i; if (igraph_ecount(graph) == 0) { /* special case: empty graph */ if (value) *value = 0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 1); } return IGRAPH_SUCCESS; } /* Quick check: if the graph is a DAG, all the eigenvector centralities are * zeros, and so is the eigenvalue */ IGRAPH_CHECK(igraph_is_dag(graph, &dag)); if (dag) { /* special case: graph is a DAG */ IGRAPH_WARNING("graph is directed and acyclic; eigenvector centralities " "will be zeros"); if (value) *value = 0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 0); } return IGRAPH_SUCCESS; } if (weights) { igraph_real_t min, max; if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid length of weights vector when calculating " "eigenvector centrality", IGRAPH_EINVAL); } if (igraph_is_directed(graph)) { IGRAPH_WARNING("Weighted directed graph in eigenvector centrality"); } IGRAPH_CHECK(igraph_vector_minmax(weights, &min, &max)); if (min < 0.0) { IGRAPH_WARNING("Negative weights, eigenpair might be complex"); } if (min == 0.0 && max == 0.0) { /* special case: all weights are zeros */ if (value) *value = 0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 1); } return IGRAPH_SUCCESS; } } options->n=igraph_vcount(graph); options->start=1; options->nev=1; options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rnsolve */ /* LM mode is not OK here because +1 and -1 can be eigenvalues at the * same time, e.g.: a -> b -> a, c -> a */ options->which[0]='L' ; options->which[1]='R'; IGRAPH_MATRIX_INIT_FINALLY(&values, 0, 0); IGRAPH_MATRIX_INIT_FINALLY(&vectors, options->n, 1); IGRAPH_VECTOR_INIT_FINALLY(&indegree, options->n); IGRAPH_CHECK(igraph_strength(graph, &indegree, igraph_vss_all(), IGRAPH_IN, /*loops=*/ 1, weights)); RNG_BEGIN(); for (i=0; in; i++) { if (VECTOR(indegree)[i]) { MATRIX(vectors, i, 0) = VECTOR(indegree)[i] + RNG_UNIF(-1e-4, 1e-4); } else { MATRIX(vectors, i, 0) = 1.0; } } RNG_END(); igraph_vector_destroy(&indegree); IGRAPH_FINALLY_CLEAN(1); if (!weights) { igraph_adjlist_t adjlist; IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_arpack_rnsolve(igraph_i_eigenvector_centrality, &adjlist, options, 0, &values, &vectors)); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); } else { igraph_inclist_t inclist; igraph_i_eigenvector_centrality_t data={ graph, &inclist, weights }; IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_arpack_rnsolve(igraph_i_eigenvector_centrality2, &data, options, 0, &values, &vectors)); igraph_inclist_destroy(&inclist); IGRAPH_FINALLY_CLEAN(1); } if (value) { *value=MATRIX(values, 0, 0); } if (vector) { igraph_real_t amax=0; long int which=0; long int i; IGRAPH_CHECK(igraph_vector_resize(vector, options->n)); if (MATRIX(values, 0, 0) <= 0) { /* Pathological case: largest eigenvalue is zero, therefore all the * scores can also be zeros, this will be a valid eigenvector. * This usually happens with graphs that have lots of sinks and * sources only. */ igraph_vector_fill(vector, 0); MATRIX(values, 0, 0) = 0; } else { for (i=0; in; i++) { igraph_real_t tmp; VECTOR(*vector)[i] = MATRIX(vectors, i, 0); tmp=fabs(VECTOR(*vector)[i]); if (tmp>amax) { amax=tmp; which=i; } } if (scale && amax!=0) { igraph_vector_scale(vector, 1/VECTOR(*vector)[which]); } else if (igraph_i_vector_mostly_negative(vector)) { igraph_vector_scale(vector, -1.0); } } /* Correction for numeric inaccuracies (eliminating -0.0) */ for (i=0; in; i++) { if (VECTOR(*vector)[i] < 0) VECTOR(*vector)[i] = 0; } } if (options->info) { IGRAPH_WARNING("Non-zero return code from ARPACK routine!"); } igraph_matrix_destroy(&vectors); igraph_matrix_destroy(&values); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_eigenvector_centrality * Eigenvector centrality of the vertices * * Eigenvector centrality is a measure of the importance of a node in a * network. It assigns relative scores to all nodes in the network based * on the principle that connections to high-scoring nodes contribute * more to the score of the node in question than equal connections to * low-scoring nodes. In practice, this is determined by calculating the * eigenvector corresponding to the largest positive eigenvalue of the * adjacency matrix. The centrality scores returned by igraph are always * normalized such that the largest eigenvector centrality score is one * (with one exception, see below). * * * Since the eigenvector centrality scores of nodes in different components * do not affect each other, it may be beneficial for large graphs to * decompose it first into weakly connected components and calculate the * centrality scores individually for each component. * * * Also note that the adjacency matrix of a directed acyclic graph or the * adjacency matrix of an empty graph does not possess positive eigenvalues, * therefore the eigenvector centrality is not defined for these graphs. * igraph will return an eigenvalue of zero in such cases. The eigenvector * centralities will all be equal for an empty graph and will all be zeros * for a directed acyclic graph. Such pathological cases can be detected * by asking igraph to calculate the eigenvalue as well (using the \p value * parameter, see below) and checking whether the eigenvalue is very close * to zero. * * \param graph The input graph. It might be directed. * \param vector Pointer to an initialized vector, it will be resized * as needed. The result of the computation is stored here. It can * be a null pointer, then it is ignored. * \param value If not a null pointer, then the eigenvalue * corresponding to the found eigenvector is stored here. * \param directed Boolean scalar, whether to consider edge directions * in a directed graph. It is ignored for undirected graphs. * \param scale If not zero then the result will be scaled such that * the absolute value of the maximum centrality is one. * \param weights A null pointer (=no edge weights), or a vector * giving the weights of the edges. The algorithm might result * complex numbers is some weights are negative. In this case only * the real part is reported. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices) parameter and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code. * * Time complexity: depends on the input graph, usually it is O(|V|+|E|). * * \sa \ref igraph_pagerank and \ref igraph_personalized_pagerank for * modifications of eigenvector centrality. * * \example examples/simple/eigenvector_centrality.c */ int igraph_eigenvector_centrality(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t directed, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options) { if (directed && igraph_is_directed(graph)) { return igraph_eigenvector_centrality_directed(graph, vector, value, scale, weights, options); } else { return igraph_eigenvector_centrality_undirected(graph, vector, value, scale, weights, options); } } /* struct for the unweighted variant of the HITS algorithm */ typedef struct igraph_i_kleinberg_data_t { igraph_adjlist_t *in; igraph_adjlist_t *out; igraph_vector_t *tmp; } igraph_i_kleinberg_data_t; /* struct for the weighted variant of the HITS algorithm */ typedef struct igraph_i_kleinberg_data2_t { const igraph_t *graph; igraph_inclist_t *in; igraph_inclist_t *out; igraph_vector_t *tmp; const igraph_vector_t *weights; } igraph_i_kleinberg_data2_t; /* ARPACK auxiliary routine for the unweighted HITS algorithm */ int igraph_i_kleinberg_unweighted(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_kleinberg_data_t *data = (igraph_i_kleinberg_data_t*)extra; igraph_adjlist_t *in = data->in; igraph_adjlist_t *out = data->out; igraph_vector_t *tmp = data->tmp; igraph_vector_int_t *neis; long int i, j, nlen; for (i=0; iin; igraph_inclist_t *out = data->out; igraph_vector_t *tmp = data->tmp; const igraph_vector_t *weights = data->weights; const igraph_t *g = data->graph; igraph_vector_int_t *neis; long int i, j, nlen; for (i=0; in=igraph_vcount(graph); options->start=1; /* no random start vector */ IGRAPH_VECTOR_INIT_FINALLY(&values, 0); IGRAPH_MATRIX_INIT_FINALLY(&vectors, options->n, 1); IGRAPH_VECTOR_INIT_FINALLY(&tmp, options->n); if (inout==0) { inadjlist=&myinadjlist; outadjlist=&myoutadjlist; ininclist=&myininclist; outinclist=&myoutinclist; } else if (inout==1) { inadjlist=&myoutadjlist; outadjlist=&myinadjlist; ininclist=&myoutinclist; outinclist=&myininclist; } else { /* This should not happen */ IGRAPH_ERROR("Invalid 'inout' argument, please do not call " "this function directly", IGRAPH_FAILURE); } if (weights == 0) { IGRAPH_CHECK(igraph_adjlist_init(graph, &myinadjlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &myinadjlist); IGRAPH_CHECK(igraph_adjlist_init(graph, &myoutadjlist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &myoutadjlist); } else { IGRAPH_CHECK(igraph_inclist_init(graph, &myininclist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_inclist_destroy, &myininclist); IGRAPH_CHECK(igraph_inclist_init(graph, &myoutinclist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &myoutinclist); } IGRAPH_CHECK(igraph_degree(graph, &tmp, igraph_vss_all(), IGRAPH_ALL, 0)); for (i=0; in; i++) { if (VECTOR(tmp)[i] != 0) { MATRIX(vectors, i, 0) = VECTOR(tmp)[i]; } else { MATRIX(vectors, i, 0) = 1.0; } } extra.in=inadjlist; extra.out=outadjlist; extra.tmp=&tmp; extra2.in=ininclist; extra2.out=outinclist; extra2.tmp=&tmp; extra2.graph=graph; extra2.weights=weights; options->nev = 1; options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rssolve */ options->which[0]='L'; options->which[1]='M'; if (weights == 0) { IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_kleinberg_unweighted, &extra, options, 0, &values, &vectors)); igraph_adjlist_destroy(&myoutadjlist); igraph_adjlist_destroy(&myinadjlist); IGRAPH_FINALLY_CLEAN(2); } else { IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_kleinberg_weighted, &extra2, options, 0, &values, &vectors)); igraph_inclist_destroy(&myoutinclist); igraph_inclist_destroy(&myininclist); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); if (value) { *value = VECTOR(values)[0]; } if (vector) { igraph_real_t amax=0; long int which=0; long int i; IGRAPH_CHECK(igraph_vector_resize(vector, options->n)); for (i=0; in; i++) { igraph_real_t tmp; VECTOR(*vector)[i] = MATRIX(vectors, i, 0); tmp=fabs(VECTOR(*vector)[i]); if (tmp>amax) { amax=tmp; which=i; } } if (scale && amax!=0) { igraph_vector_scale(vector, 1/VECTOR(*vector)[which]); } else if (igraph_i_vector_mostly_negative(vector)) { igraph_vector_scale(vector, -1.0); } /* Correction for numeric inaccuracies (eliminating -0.0) */ for (i=0; in; i++) { if (VECTOR(*vector)[i] < 0) VECTOR(*vector)[i] = 0; } } if (options->info) { IGRAPH_WARNING("Non-zero return code from ARPACK routine!"); } igraph_matrix_destroy(&vectors); igraph_vector_destroy(&values); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_hub_score * Kleinberg's hub scores * * The hub scores of the vertices are defined as the principal * eigenvector of A*A^T, where A is the adjacency * matrix of the graph, A^T is its transposed. * * See the following reference on the meaning of this score: * J. Kleinberg. Authoritative sources in a hyperlinked * environment. \emb Proc. 9th ACM-SIAM Symposium on Discrete * Algorithms, \eme 1998. Extended version in \emb Journal of the * ACM \eme 46(1999). Also appears as IBM Research Report RJ 10076, May * 1997. * \param graph The input graph. Can be directed and undirected. * \param vector Pointer to an initialized vector, the result is * stored here. If a null pointer then it is ignored. * \param value If not a null pointer then the eigenvalue * corresponding to the calculated eigenvector is stored here. * \param scale If not zero then the result will be scaled such that * the absolute value of the maximum centrality is one. * \param weights A null pointer (=no edge weights), or a vector * giving the weights of the edges. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices) parameter and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code. * * Time complexity: depends on the input graph, usually it is O(|V|), * the number of vertices. * * \sa \ref igraph_authority_score() for the companion measure, * \ref igraph_pagerank(), \ref igraph_personalized_pagerank(), * \ref igraph_eigenvector_centrality() for similar measures. */ int igraph_hub_score(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options) { return igraph_i_kleinberg(graph, vector, value, scale, weights, options, 0); } /** * \function igraph_authority_score * Kleinerg's authority scores * * The authority scores of the vertices are defined as the principal * eigenvector of A^T*A, where A is the adjacency * matrix of the graph, A^T is its transposed. * * See the following reference on the meaning of this score: * J. Kleinberg. Authoritative sources in a hyperlinked * environment. \emb Proc. 9th ACM-SIAM Symposium on Discrete * Algorithms, \eme 1998. Extended version in \emb Journal of the * ACM \eme 46(1999). Also appears as IBM Research Report RJ 10076, May * 1997. * \param graph The input graph. Can be directed and undirected. * \param vector Pointer to an initialized vector, the result is * stored here. If a null pointer then it is ignored. * \param value If not a null pointer then the eigenvalue * corresponding to the calculated eigenvector is stored here. * \param scale If not zero then the result will be scaled such that * the absolute value of the maximum centrality is one. * \param weights A null pointer (=no edge weights), or a vector * giving the weights of the edges. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices) parameter and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code. * * Time complexity: depends on the input graph, usually it is O(|V|), * the number of vertices. * * \sa \ref igraph_hub_score() for the companion measure, * \ref igraph_pagerank(), \ref igraph_personalized_pagerank(), * \ref igraph_eigenvector_centrality() for similar measures. */ int igraph_authority_score(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options) { return igraph_i_kleinberg(graph, vector, value, scale, weights, options, 1); } typedef struct igraph_i_pagerank_data_t { const igraph_t *graph; igraph_adjlist_t *adjlist; igraph_real_t damping; igraph_vector_t *outdegree; igraph_vector_t *tmp; igraph_vector_t *reset; } igraph_i_pagerank_data_t; typedef struct igraph_i_pagerank_data2_t { const igraph_t *graph; igraph_inclist_t *inclist; const igraph_vector_t *weights; igraph_real_t damping; igraph_vector_t *outdegree; igraph_vector_t *tmp; igraph_vector_t *reset; } igraph_i_pagerank_data2_t; int igraph_i_pagerank(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_pagerank_data_t *data=extra; igraph_adjlist_t *adjlist=data->adjlist; igraph_vector_t *outdegree=data->outdegree; igraph_vector_t *tmp=data->tmp; igraph_vector_t *reset=data->reset; igraph_vector_int_t *neis; long int i, j, nlen; igraph_real_t sumfrom=0.0; igraph_real_t fact=1-data->damping; /* Calculate p(x) / outdegree(x) in advance for all the vertices. * Note that we may divide by zero here; this is intentional since * we won't use those values and we save a comparison this way. * At the same time, we calculate the global probability of a * random jump in `sumfrom`. For vertices with no outgoing edges, * we will surely jump from there if we are there, hence those * vertices contribute p(x) to the teleportation probability. * For vertices with some outgoing edges, we jump from there with * probability `fact` if we are there, hence they contribute * p(x)*fact */ for (i=0; idamping; } /* Now we add the contribution from random jumps. `reset` is a vector * that defines the probability of ending up in vertex i after a jump. * `sumfrom` is the global probability of jumping as mentioned above. */ /* printf("sumfrom = %.6f\n", (float)sumfrom); */ if (reset) { /* Running personalized PageRank */ for (i=0; igraph; igraph_inclist_t *inclist=data->inclist; const igraph_vector_t *weights=data->weights; igraph_vector_t *outdegree=data->outdegree; igraph_vector_t *tmp=data->tmp; igraph_vector_t *reset=data->reset; long int i, j, nlen; igraph_real_t sumfrom=0.0; igraph_vector_int_t *neis; igraph_real_t fact=1-data->damping; /* printf("PageRank weighted: multiplying vector: "); for (i=0; idamping; } /* printf("sumfrom = %.6f\n", (float)sumfrom); */ if (reset) { /* Running personalized PageRank */ for (i=0; i * Please note that the PageRank of a given vertex depends on the PageRank * of all other vertices, so even if you want to calculate the PageRank for * only some of the vertices, all of them must be calculated. Requesting * the PageRank for only some of the vertices does not result in any * performance increase at all. * * * * For the explanation of the PageRank algorithm, see the following * webpage: * http://infolab.stanford.edu/~backrub/google.html , or the * following reference: * * * * Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual * Web Search Engine. Proceedings of the 7th World-Wide Web Conference, * Brisbane, Australia, April 1998. * * * \param graph The graph object. * \param algo The PageRank implementation to use. Possible values: * \c IGRAPH_PAGERANK_ALGO_POWER, \c IGRAPH_PAGERANK_ALGO_ARPACK, * \c IGRAPH_PAGERANK_ALGO_PRPACK. * \param vector Pointer to an initialized vector, the result is * stored here. It is resized as needed. * \param value Pointer to a real variable, the eigenvalue * corresponding to the PageRank vector is stored here. It should * be always exactly one. * \param vids The vertex ids for which the PageRank is returned. * \param directed Boolean, whether to consider the directedness of * the edges. This is ignored for undirected graphs. * \param damping The damping factor ("d" in the original paper) * \param weights Optional edge weights, it is either a null pointer, * then the edges are not weighted, or a vector of the same length * as the number of edges. * \param options Options to the power method or ARPACK. For the power * method, \c IGRAPH_PAGERANK_ALGO_POWER it must be a pointer to * a \ref igraph_pagerank_power_options_t object. * For \c IGRAPH_PAGERANK_ALGO_ARPACK it must be a pointer to an * \ref igraph_arpack_options_t object. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices), nev (1), * ncv (3) and which (LM) parameters and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids. * * Time complexity: depends on the input graph, usually it is O(|E|), * the number of edges. * * \sa \ref igraph_pagerank_old() for the old implementation, * \ref igraph_personalized_pagerank() and \ref igraph_personalized_pagerank_vs() * for the personalized PageRank measure, \ref igraph_arpack_rssolve() and * \ref igraph_arpack_rnsolve() for the underlying machinery. * * \example examples/simple/igraph_pagerank.c */ int igraph_pagerank(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, const igraph_vector_t *weights, void *options) { return igraph_personalized_pagerank(graph, algo, vector, value, vids, directed, damping, 0, weights, options); } /** * \function igraph_personalized_pagerank_vs * \brief Calculates the personalized Google PageRank for the specified vertices. * * The personalized PageRank is similar to the original PageRank measure, but the * random walk is reset in every step with probability 1-damping to a non-uniform * distribution (instead of the uniform distribution in the original PageRank measure. * * * This simplified interface takes a vertex sequence and resets the random walk to * one of the vertices in the specified vertex sequence, chosen uniformly. A typical * application of personalized PageRank is when the random walk is reset to the same * vertex every time - this can easily be achieved using \ref igraph_vss_1() which * generates a vertex sequence containing only a single vertex. * * * Please note that the personalized PageRank of a given vertex depends on the * personalized PageRank of all other vertices, so even if you want to calculate * the personalized PageRank for only some of the vertices, all of them must be * calculated. Requesting the personalized PageRank for only some of the vertices * does not result in any performance increase at all. * * * * \param graph The graph object. * \param algo The PageRank implementation to use. Possible values: * \c IGRAPH_PAGERANK_ALGO_POWER, \c IGRAPH_PAGERANK_ALGO_ARPACK, * \c IGRAPH_PAGERANK_ALGO_PRPACK. * \param vector Pointer to an initialized vector, the result is * stored here. It is resized as needed. * \param value Pointer to a real variable, the eigenvalue * corresponding to the PageRank vector is stored here. It should * be always exactly one. * \param vids The vertex ids for which the PageRank is returned. * \param directed Boolean, whether to consider the directedness of * the edges. This is ignored for undirected graphs. * \param damping The damping factor ("d" in the original paper) * \param reset_vids IDs of the vertices used when resetting the random walk. * \param weights Optional edge weights, it is either a null pointer, * then the edges are not weighted, or a vector of the same length * as the number of edges. * \param options Options to the power method or ARPACK. For the power * method, \c IGRAPH_PAGERANK_ALGO_POWER it must be a pointer to * a \ref igraph_pagerank_power_options_t object. * For \c IGRAPH_PAGERANK_ALGO_ARPACK it must be a pointer to an * \ref igraph_arpack_options_t object. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices), nev (1), * ncv (3) and which (LM) parameters and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids or an empty reset vertex sequence in * \p vids_reset. * * Time complexity: depends on the input graph, usually it is O(|E|), * the number of edges. * * \sa \ref igraph_pagerank() for the non-personalized implementation, * \ref igraph_arpack_rssolve() and \ref igraph_arpack_rnsolve() for * the underlying machinery. */ int igraph_personalized_pagerank_vs(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vs_t reset_vids, const igraph_vector_t *weights, void *options) { igraph_vector_t reset; igraph_vit_t vit; IGRAPH_VECTOR_INIT_FINALLY(&reset, igraph_vcount(graph)); IGRAPH_CHECK(igraph_vit_create(graph, reset_vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); while (!IGRAPH_VIT_END(vit)) { VECTOR(reset)[(long int)IGRAPH_VIT_GET(vit)]++; IGRAPH_VIT_NEXT(vit); } igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); IGRAPH_CHECK(igraph_personalized_pagerank(graph, algo, vector, value, vids, directed, damping, &reset, weights, options)); igraph_vector_destroy(&reset); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_personalized_pagerank * \brief Calculates the personalized Google PageRank for the specified vertices. * * The personalized PageRank is similar to the original PageRank measure, but the * random walk is reset in every step with probability 1-damping to a non-uniform * distribution (instead of the uniform distribution in the original PageRank measure. * * * Please note that the personalized PageRank of a given vertex depends on the * personalized PageRank of all other vertices, so even if you want to calculate * the personalized PageRank for only some of the vertices, all of them must be * calculated. Requesting the personalized PageRank for only some of the vertices * does not result in any performance increase at all. * * * * \param graph The graph object. * \param algo The PageRank implementation to use. Possible values: * \c IGRAPH_PAGERANK_ALGO_POWER, \c IGRAPH_PAGERANK_ALGO_ARPACK, * \c IGRAPH_PAGERANK_ALGO_PRPACK. * \param vector Pointer to an initialized vector, the result is * stored here. It is resized as needed. * \param value Pointer to a real variable, the eigenvalue * corresponding to the PageRank vector is stored here. It should * be always exactly one. * \param vids The vertex ids for which the PageRank is returned. * \param directed Boolean, whether to consider the directedness of * the edges. This is ignored for undirected graphs. * \param damping The damping factor ("d" in the original paper) * \param reset The probability distribution over the vertices used when * resetting the random walk. It is either a null pointer (denoting * a uniform choice that results in the original PageRank measure) * or a vector of the same length as the number of vertices. * \param weights Optional edge weights, it is either a null pointer, * then the edges are not weighted, or a vector of the same length * as the number of edges. * \param options Options to the power method or ARPACK. For the power * method, \c IGRAPH_PAGERANK_ALGO_POWER it must be a pointer to * a \ref igraph_pagerank_power_options_t object. * For \c IGRAPH_PAGERANK_ALGO_ARPACK it must be a pointer to an * \ref igraph_arpack_options_t object. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices), nev (1), * ncv (3) and which (LM) parameters and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids or an invalid reset vector in \p reset. * * Time complexity: depends on the input graph, usually it is O(|E|), * the number of edges. * * \sa \ref igraph_pagerank() for the non-personalized implementation, * \ref igraph_arpack_rssolve() and \ref igraph_arpack_rnsolve() for * the underlying machinery. */ int igraph_personalized_pagerank(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights, void *options) { if (algo == IGRAPH_PAGERANK_ALGO_POWER) { igraph_pagerank_power_options_t *o = (igraph_pagerank_power_options_t *) options; if (reset) { IGRAPH_WARNING("Cannot use weights with power method, " "weights will be ignored"); } return igraph_pagerank_old(graph, vector, vids, directed, o->niter, o->eps, damping, /*old=*/ 0); } else if (algo == IGRAPH_PAGERANK_ALGO_ARPACK) { igraph_arpack_options_t *o= (igraph_arpack_options_t*) options; return igraph_personalized_pagerank_arpack(graph, vector, value, vids, directed, damping, reset, weights, o); } else if (algo == IGRAPH_PAGERANK_ALGO_PRPACK) { return igraph_personalized_pagerank_prpack(graph, vector, value, vids, directed, damping, reset, weights); } else { IGRAPH_ERROR("Unknown PageRank algorithm", IGRAPH_EINVAL); } return 0; } /* * ARPACK-based implementation of \c igraph_personalized_pagerank. * * See \c igraph_personalized_pagerank for the documentation of the parameters. */ int igraph_personalized_pagerank_arpack(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights, igraph_arpack_options_t *options) { igraph_matrix_t values; igraph_matrix_t vectors; igraph_neimode_t dirmode; igraph_vector_t outdegree; igraph_vector_t indegree; igraph_vector_t tmp; long int i; long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); if (no_of_edges == 0) { /* special case: empty graph */ if (value) *value = 1.0; if (vector) { igraph_vector_resize(vector, no_of_nodes); igraph_vector_fill(vector, 1.0 / no_of_nodes); } return IGRAPH_SUCCESS; } options->n = (int) no_of_nodes; options->nev = 1; options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rnsolve */ options->which[0]='L'; options->which[1]='M'; options->start = 1; /* no random start vector */ directed = directed && igraph_is_directed(graph); if (weights) { igraph_real_t min, max; if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid length of weights vector when calculating " "PageRank scores", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_minmax(weights, &min, &max)); if (min == 0 && max == 0) { /* special case: all weights are zeros */ if (value) *value = 1.0; if (vector) { igraph_vector_resize(vector, igraph_vcount(graph)); igraph_vector_fill(vector, 1.0 / no_of_nodes); } return IGRAPH_SUCCESS; } } if (reset && igraph_vector_size(reset) != no_of_nodes) { IGRAPH_ERROR("Invalid length of reset vector when calculating " "personalized PageRank scores", IGRAPH_EINVAL); } IGRAPH_MATRIX_INIT_FINALLY(&values, 0, 0); IGRAPH_MATRIX_INIT_FINALLY(&vectors, options->n, 1); if (directed) { dirmode=IGRAPH_IN; } else { dirmode=IGRAPH_ALL; } IGRAPH_VECTOR_INIT_FINALLY(&indegree, options->n); IGRAPH_VECTOR_INIT_FINALLY(&outdegree, options->n); IGRAPH_VECTOR_INIT_FINALLY(&tmp, options->n); RNG_BEGIN(); if (reset) { /* Normalize reset vector so the sum is 1 */ double reset_sum; if (igraph_vector_min(reset) < 0) IGRAPH_ERROR("the reset vector must not contain negative elements", IGRAPH_EINVAL); reset_sum = igraph_vector_sum(reset); if (reset_sum == 0) IGRAPH_ERROR("the sum of the elements in the reset vector must not be zero", IGRAPH_EINVAL); igraph_vector_scale(reset, 1.0/reset_sum); } if (!weights) { igraph_adjlist_t adjlist; igraph_i_pagerank_data_t data = { graph, &adjlist, damping, &outdegree, &tmp, reset }; IGRAPH_CHECK(igraph_degree(graph, &outdegree, igraph_vss_all(), directed ? IGRAPH_OUT : IGRAPH_ALL, /*loops=*/ 0)); IGRAPH_CHECK(igraph_degree(graph, &indegree, igraph_vss_all(), directed ? IGRAPH_IN : IGRAPH_ALL, /*loops=*/ 0)); /* Set up an appropriate starting vector. We start from the in-degrees * plus some small random noise to avoid convergence problems */ for (i=0; in; i++) { if (VECTOR(indegree)[i]) MATRIX(vectors, i, 0) = VECTOR(indegree)[i] + RNG_UNIF(-1e-4, 1e-4); else MATRIX(vectors, i, 0) = 1; } IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, dirmode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_arpack_rnsolve(igraph_i_pagerank, &data, options, 0, &values, &vectors)); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); } else { igraph_inclist_t inclist; igraph_bool_t negative_weight_warned = 0; igraph_i_pagerank_data2_t data = { graph, &inclist, weights, damping, &outdegree, &tmp, reset }; IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, dirmode)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); /* Weighted degree */ for (i=0; in; i++) { if (VECTOR(indegree)[i]) MATRIX(vectors, i, 0) = VECTOR(indegree)[i] + RNG_UNIF(-1e-4, 1e-4); else MATRIX(vectors, i, 0) = 1; } IGRAPH_CHECK(igraph_arpack_rnsolve(igraph_i_pagerank2, &data, options, 0, &values, &vectors)); igraph_inclist_destroy(&inclist); IGRAPH_FINALLY_CLEAN(1); } RNG_END(); igraph_vector_destroy(&tmp); igraph_vector_destroy(&outdegree); igraph_vector_destroy(&indegree); IGRAPH_FINALLY_CLEAN(3); if (value) { *value=MATRIX(values, 0, 0); } if (vector) { long int i; igraph_vit_t vit; long int nodes_to_calc; igraph_real_t sum=0; for (i=0; iinfo) { IGRAPH_WARNING("Non-zero return code from ARPACK routine!"); } igraph_matrix_destroy(&vectors); igraph_matrix_destroy(&values); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \ingroup structural * \function igraph_betweenness * \brief Betweenness centrality of some vertices. * * * The betweenness centrality of a vertex is the number of geodesics * going through it. If there are more than one geodesic between two * vertices, the value of these geodesics are weighted by one over the * number of geodesics. * \param graph The graph object. * \param res The result of the computation, a vector containing the * betweenness scores for the specified vertices. * \param vids The vertices of which the betweenness centrality scores * will be calculated. * \param directed Logical, if true directed paths will be considered * for directed graphs. It is ignored for undirected graphs. * \param weights An optional vector containing edge weights for * calculating weighted betweenness. Supply a null pointer here * for unweighted betweenness. * \param nobigint Logical, if true, then we don't use big integers * for the calculation, setting this to 1 (=true) should * work for most graphs. It is currently ignored for weighted * graphs. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id passed in * \p vids. * * Time complexity: O(|V||E|), * |V| and * |E| are the number of vertices and * edges in the graph. * Note that the time complexity is independent of the number of * vertices for which the score is calculated. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_closeness(). * See \ref igraph_edge_betweenness() for calculating the betweenness score * of the edges in a graph. See \ref igraph_betweenness_estimate() to * estimate the betweenness score of the vertices in a graph. * * \example examples/simple/igraph_betweenness.c */ int igraph_betweenness(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, const igraph_vector_t* weights, igraph_bool_t nobigint) { return igraph_betweenness_estimate(graph, res, vids, directed, -1, weights, nobigint); } int igraph_i_betweenness_estimate_weighted(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t nobigint) { igraph_integer_t no_of_nodes=(igraph_integer_t) igraph_vcount(graph); igraph_integer_t no_of_edges=(igraph_integer_t) igraph_ecount(graph); igraph_2wheap_t Q; igraph_inclist_t inclist; igraph_adjlist_t fathers; long int source, j; igraph_stack_t S; igraph_neimode_t mode= directed ? IGRAPH_OUT : IGRAPH_ALL; igraph_vector_t dist, nrgeo, tmpscore; igraph_vector_t v_tmpres, *tmpres=&v_tmpres; igraph_vit_t vit; int cmp_result; const double eps = IGRAPH_SHORTEST_PATH_EPSILON; IGRAPH_UNUSED(nobigint); if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Weight vector length does not match", IGRAPH_EINVAL); } if (igraph_vector_min(weights) <= 0) { IGRAPH_ERROR("Weight vector must be positive", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_2wheap_init(&Q, no_of_nodes)); IGRAPH_FINALLY(igraph_2wheap_destroy, &Q); IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, mode)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_adjlist_init_empty(&fathers, no_of_nodes)); IGRAPH_FINALLY(igraph_adjlist_destroy, &fathers); IGRAPH_CHECK(igraph_stack_init(&S, no_of_nodes)); IGRAPH_FINALLY(igraph_stack_destroy, &S); IGRAPH_VECTOR_INIT_FINALLY(&dist, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&tmpscore, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&nrgeo, no_of_nodes); if (igraph_vs_is_all(&vids)) { IGRAPH_CHECK(igraph_vector_resize(res, no_of_nodes)); igraph_vector_null(res); tmpres=res; } else { IGRAPH_VECTOR_INIT_FINALLY(tmpres, no_of_nodes); } for (source=0; source=0 && VECTOR(dist)[minnei] >= cutoff+1.0) { continue; } /* Now check all neighbors of 'minnei' for a shorter path */ neis=igraph_inclist_get(&inclist, minnei); nlen=igraph_vector_int_size(neis); for (j=0; j * The betweenness centrality of a vertex is the number of geodesics * going through it. If there are more than one geodesic between two * vertices, the value of these geodesics are weighted by one over the * number of geodesics. When estimating betweenness centrality, igraph * takes into consideration only those paths that are shorter than or * equal to a prescribed length. Note that the estimated centrality * will always be less than the real one. * * \param graph The graph object. * \param res The result of the computation, a vector containing the * estimated betweenness scores for the specified vertices. * \param vids The vertices of which the betweenness centrality scores * will be estimated. * \param directed Logical, if true directed paths will be considered * for directed graphs. It is ignored for undirected graphs. * \param cutoff The maximal length of paths that will be considered. * If zero or negative, the exact betweenness will be calculated * (no upper limit on path lengths). * \param weights An optional vector containing edge weights for * calculating weighted betweenness. Supply a null pointer here * for unweighted betweenness. * \param nobigint Logical, if true, then we don't use big integers * for the calculation, setting this to 1 (=true) should * work for most graphs. It is currently ignored for weighted * graphs. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id passed in * \p vids. * * Time complexity: O(|V||E|), * |V| and * |E| are the number of vertices and * edges in the graph. * Note that the time complexity is independent of the number of * vertices for which the score is calculated. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_closeness(). * See \ref igraph_edge_betweenness() for calculating the betweenness score * of the edges in a graph. */ int igraph_betweenness_estimate(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t nobigint) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; long int *distance; unsigned long long int *nrgeo=0; /* must be long long; consider grid graphs for example */ igraph_biguint_t *big_nrgeo=0; double *tmpscore; igraph_stack_t stack=IGRAPH_STACK_NULL; long int source; long int j, k, nneis; igraph_vector_int_t *neis; igraph_vector_t v_tmpres, *tmpres=&v_tmpres; igraph_vit_t vit; igraph_adjlist_t adjlist_out, adjlist_in; igraph_adjlist_t *adjlist_out_p, *adjlist_in_p; igraph_biguint_t D, R, T; if (weights) { return igraph_i_betweenness_estimate_weighted(graph, res, vids, directed, cutoff, weights, nobigint); } if (!igraph_vs_is_all(&vids)) { /* subset */ IGRAPH_VECTOR_INIT_FINALLY(tmpres, no_of_nodes); } else { /* only */ IGRAPH_CHECK(igraph_vector_resize(res, no_of_nodes)); igraph_vector_null(res); tmpres=res; } directed=directed && igraph_is_directed(graph); if (directed) { IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist_out, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist_out); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist_in, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist_in); adjlist_out_p=&adjlist_out; adjlist_in_p=&adjlist_in; } else { IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist_out, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist_out); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist_in, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist_in); adjlist_out_p=&adjlist_out; adjlist_in_p=&adjlist_in; } for (j=0; j= 0 && distance[actnode] >= cutoff+1) { continue; } neis = igraph_adjlist_get(adjlist_out_p, actnode); nneis = igraph_vector_int_size(neis); for (j=0; j=0 && VECTOR(distance)[minnei] >= cutoff+1.0) { continue; } neis=igraph_inclist_get(&inclist, minnei); nlen=igraph_vector_int_size(neis); for (j=0; j * The betweenness centrality of an edge is the number of geodesics * going through it. If there are more than one geodesics between two * vertices, the value of these geodesics are weighted by one over the * number of geodesics. * \param graph The graph object. * \param result The result of the computation, vector containing the * betweenness scores for the edges. * \param directed Logical, if true directed paths will be considered * for directed graphs. It is ignored for undirected graphs. * \param weights An optional weight vector for weighted edge * betweenness. Supply a null pointer here for the unweighted * version. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * * Time complexity: O(|V||E|), * |V| and * |E| are the number of vertices and * edges in the graph. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_closeness(). * See \ref igraph_edge_betweenness() for calculating the betweenness score * of the edges in a graph. See \ref igraph_edge_betweenness_estimate() to * estimate the betweenness score of the edges in a graph. * * \example examples/simple/igraph_edge_betweenness.c */ int igraph_edge_betweenness(const igraph_t *graph, igraph_vector_t *result, igraph_bool_t directed, const igraph_vector_t *weights) { return igraph_edge_betweenness_estimate(graph, result, directed, -1, weights); } /** * \ingroup structural * \function igraph_edge_betweenness_estimate * \brief Estimated betweenness centrality of the edges. * * * The betweenness centrality of an edge is the number of geodesics * going through it. If there are more than one geodesics between two * vertices, the value of these geodesics are weighted by one over the * number of geodesics. When estimating betweenness centrality, igraph * takes into consideration only those paths that are shorter than or * equal to a prescribed length. Note that the estimated centrality * will always be less than the real one. * \param graph The graph object. * \param result The result of the computation, vector containing the * betweenness scores for the edges. * \param directed Logical, if true directed paths will be considered * for directed graphs. It is ignored for undirected graphs. * \param cutoff The maximal length of paths that will be considered. * If zero or negative, the exact betweenness will be calculated * (no upper limit on path lengths). * \param weights An optional weight vector for weighted * betweenness. Supply a null pointer here for unweighted * betweenness. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * * Time complexity: O(|V||E|), * |V| and * |E| are the number of vertices and * edges in the graph. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_closeness(). * See \ref igraph_betweenness() for calculating the betweenness score * of the vertices in a graph. */ int igraph_edge_betweenness_estimate(const igraph_t *graph, igraph_vector_t *result, igraph_bool_t directed, igraph_real_t cutoff, const igraph_vector_t *weights) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; long int *distance; unsigned long long int *nrgeo; double *tmpscore; igraph_stack_t stack=IGRAPH_STACK_NULL; long int source; long int j; igraph_inclist_t elist_out, elist_in; igraph_inclist_t *elist_out_p, *elist_in_p; igraph_vector_int_t *neip; long int neino; long int i; if (weights) { return igraph_i_edge_betweenness_estimate_weighted(graph, result, directed, cutoff, weights); } directed=directed && igraph_is_directed(graph); if (directed) { IGRAPH_CHECK(igraph_inclist_init(graph, &elist_out, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out); IGRAPH_CHECK(igraph_inclist_init(graph, &elist_in, IGRAPH_IN)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_in); elist_out_p=&elist_out; elist_in_p=&elist_in; } else { IGRAPH_CHECK(igraph_inclist_init(graph,&elist_out, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out); elist_out_p=elist_in_p=&elist_out; } distance=igraph_Calloc(no_of_nodes, long int); if (distance==0) { IGRAPH_ERROR("edge betweenness failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, distance); nrgeo=igraph_Calloc(no_of_nodes, unsigned long long int); if (nrgeo==0) { IGRAPH_ERROR("edge betweenness failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, nrgeo); tmpscore=igraph_Calloc(no_of_nodes, double); if (tmpscore==0) { IGRAPH_ERROR("edge betweenness failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, tmpscore); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_stack_init(&stack, no_of_nodes)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_CHECK(igraph_vector_resize(result, no_of_edges)); igraph_vector_null(result); /* here we go */ for (source=0; source 0 && distance[actnode] >= cutoff ) continue; neip=igraph_inclist_get(elist_out_p, actnode); neino=igraph_vector_int_size(neip); for (i=0; i * The closeness centrality of a vertex measures how easily other * vertices can be reached from it (or the other way: how easily it * can be reached from the other vertices). It is defined as * the number of vertices minus one divided by the sum of the * lengths of all geodesics from/to the given vertex. * * * If the graph is not connected, and there is no path between two * vertices, the number of vertices is used instead the length of the * geodesic. This is longer than the longest possible geodesic in case * of unweighted graphs, but may not be so in weighted graphs, so it is * best not to use this function on weighted graphs. * * * If the graph has a single vertex only, the closeness centrality of * that single vertex will be NaN (because we are essentially dividing * zero with zero). * * \param graph The graph object. * \param res The result of the computation, a vector containing the * closeness centrality scores for the given vertices. * \param vids Vector giving the vertices for which the closeness * centrality scores will be computed. * \param mode The type of shortest paths to be used for the * calculation in directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the lengths of the outgoing paths are calculated. * \cli IGRAPH_IN * the lengths of the incoming paths are calculated. * \cli IGRAPH_ALL * the directed graph is considered as an * undirected one for the computation. * \endclist * \param weights An optional vector containing edge weights for * weighted closeness. Supply a null pointer here for * traditional, unweighted closeness. * \param normalized Boolean, whether to normalize results by multiplying * by the number of vertices minus one. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(n|E|), * n is the number * of vertices for which the calculation is done and * |E| is the number * of edges in the graph. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_betweenness(). * See \ref igraph_closeness_estimate() to estimate closeness values. */ int igraph_closeness(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, const igraph_vector_t *weights, igraph_bool_t normalized) { return igraph_closeness_estimate(graph, res, vids, mode, -1, weights, normalized); } int igraph_i_closeness_estimate_weighted(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t normalized) { /* See igraph_shortest_paths_dijkstra() for the implementation details and the dirty tricks. */ long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_2wheap_t Q; igraph_vit_t vit; long int nodes_to_calc; igraph_lazy_inclist_t inclist; long int i, j; igraph_vector_t dist; igraph_vector_long_t which; long int nodes_reached; int cmp_result; const double eps = IGRAPH_SHORTEST_PATH_EPSILON; igraph_bool_t warning_shown = 0; if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (igraph_vector_min(weights) < 0) { IGRAPH_ERROR("Weight vector must be non-negative", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); IGRAPH_CHECK(igraph_2wheap_init(&Q, no_of_nodes)); IGRAPH_FINALLY(igraph_2wheap_destroy, &Q); IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, mode)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); IGRAPH_VECTOR_INIT_FINALLY(&dist, no_of_nodes); IGRAPH_CHECK(igraph_vector_long_init(&which, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &which); IGRAPH_CHECK(igraph_vector_resize(res, nodes_to_calc)); igraph_vector_null(res); for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int source=IGRAPH_VIT_GET(vit); igraph_2wheap_clear(&Q); igraph_2wheap_push_with_index(&Q, source, 0); VECTOR(which)[source] = i+1; VECTOR(dist)[source] = 1.0; /* actual distance is zero but we need to store distance + 1 */ nodes_reached=0; while (!igraph_2wheap_empty(&Q)) { igraph_integer_t minnei=(igraph_integer_t) igraph_2wheap_max_index(&Q); igraph_real_t mindist=-igraph_2wheap_delete_max(&Q); /* Now check all neighbors of minnei for a shorter path */ igraph_vector_t *neis=igraph_lazy_inclist_get(&inclist, minnei); long int nlen=igraph_vector_size(neis); VECTOR(*res)[i] += mindist; nodes_reached++; if (cutoff>0 && mindist>=cutoff) continue; /* NOT break!!! */ for (j=0; j nodes_reached && !warning_shown) { IGRAPH_WARNING("closeness centrality is not well-defined for disconnected graphs"); warning_shown = 1; } } /* !IGRAPH_VIT_END(vit) */ if (!normalized) { for (i=0; i * The closeness centrality of a vertex measures how easily other * vertices can be reached from it (or the other way: how easily it * can be reached from the other vertices). It is defined as * the number of vertices minus one divided by the sum of the * lengths of all geodesics from/to the given vertex. When estimating * closeness centrality, igraph considers paths having a length less than * or equal to a prescribed cutoff value. * * * If the graph is not connected, and there is no such path between two * vertices, the number of vertices is used instead the length of the * geodesic. This is always longer than the longest possible geodesic. * * * Since the estimation considers vertex pairs with a distance greater than * the given value as disconnected, the resulting estimation will always be * lower than the actual closeness centrality. * * \param graph The graph object. * \param res The result of the computation, a vector containing the * closeness centrality scores for the given vertices. * \param vids Vector giving the vertices for which the closeness * centrality scores will be computed. * \param mode The type of shortest paths to be used for the * calculation in directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the lengths of the outgoing paths are calculated. * \cli IGRAPH_IN * the lengths of the incoming paths are calculated. * \cli IGRAPH_ALL * the directed graph is considered as an * undirected one for the computation. * \endclist * \param cutoff The maximal length of paths that will be considered. * If zero or negative, the exact closeness will be calculated * (no upper limit on path lengths). * \param weights An optional vector containing edge weights for * weighted closeness. Supply a null pointer here for * traditional, unweighted closeness. * \param normalized Boolean, whether to normalize results by multiplying * by the number of vertices minus one. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(n|E|), * n is the number * of vertices for which the calculation is done and * |E| is the number * of edges in the graph. * * \sa Other centrality types: \ref igraph_degree(), \ref igraph_betweenness(). */ int igraph_closeness_estimate(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t normalized) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t already_counted; igraph_vector_int_t *neis; long int i, j; long int nodes_reached; igraph_adjlist_t allneis; igraph_dqueue_t q; long int nodes_to_calc; igraph_vit_t vit; igraph_bool_t warning_shown = 0; if (weights) { return igraph_i_closeness_estimate_weighted(graph, res, vids, mode, cutoff, weights, normalized); } IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("calculating closeness", IGRAPH_EINVMODE); } IGRAPH_VECTOR_INIT_FINALLY(&already_counted, no_of_nodes); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, mode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); IGRAPH_CHECK(igraph_vector_resize(res, nodes_to_calc)); igraph_vector_null(res); for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { igraph_dqueue_clear(&q); IGRAPH_CHECK(igraph_dqueue_push(&q, IGRAPH_VIT_GET(vit))); IGRAPH_CHECK(igraph_dqueue_push(&q, 0)); nodes_reached=1; VECTOR(already_counted)[(long int)IGRAPH_VIT_GET(vit)]=i+1; IGRAPH_PROGRESS("Closeness: ", 100.0*i/no_of_nodes, NULL); IGRAPH_ALLOW_INTERRUPTION(); while (!igraph_dqueue_empty(&q)) { long int act=(long int) igraph_dqueue_pop(&q); long int actdist=(long int) igraph_dqueue_pop(&q); VECTOR(*res)[i] += actdist; if (cutoff>0 && actdist>=cutoff) continue; /* NOT break!!! */ neis=igraph_adjlist_get(&allneis, act); for (j=0; j nodes_reached && !warning_shown) { IGRAPH_WARNING("closeness centrality is not well-defined for disconnected graphs"); warning_shown = 1; } } if (!normalized) { for (i=0; iIn order to make graphs of different sizes comparable, * the centralization index is usually normalized to a number between * zero and one, by dividing the (unnormalized) centralization score * of the most centralized structure with the same number of vertices. * * For most centrality indices the most centralized * structure is the star graph, a single center connected to all other * nodes in the network. There are some variation depending on whether * the graph is directed or not, whether loop edges are allowed, etc. * * * This function simply calculates the graph level index, if the node * level scores and the theoretical maximum are given. It is called by * all the measure-specific centralization functions. * * \param scores A vector containing the node-level centrality * scores. * \param theoretical_max The graph level centrality score of the most * centralized graph with the same number of vertices. Only used * if \c normalized set to true. * \param normalized Boolean, whether to normalize the centralization * by dividing the supplied theoretical maximum. * \return The graph level index. * * \sa \ref igraph_centralization_degree(), \ref * igraph_centralization_betweenness(), \ref * igraph_centralization_closeness(), and \ref * igraph_centralization_eigenvector_centrality() for specific * centralization functions. * * Time complexity: O(n), the length of the score vector. * * \example examples/simple/centralization.c */ igraph_real_t igraph_centralization(const igraph_vector_t *scores, igraph_real_t theoretical_max, igraph_bool_t normalized) { long int no_of_nodes=igraph_vector_size(scores); igraph_real_t maxscore=0.0; igraph_real_t cent=0.0; if (no_of_nodes != 0) { maxscore = igraph_vector_max(scores); cent = no_of_nodes * maxscore - igraph_vector_sum(scores); if (normalized) { cent = cent/theoretical_max; } } else { cent = IGRAPH_NAN; } return cent; } /** * \function igraph_centralization_degree * Calculate vertex degree and graph centralization * * This function calculates the degree of the vertices by passing its * arguments to \ref igraph_degree(); and it calculates the graph * level centralization index based on the results by calling \ref * igraph_centralization(). * \param graph The input graph. * \param res A vector if you need the node-level degree scores, or a * null pointer otherwise. * \param mode Constant the specifies the type of degree for directed * graphs. Possible values: \c IGRAPH_IN, \c IGRAPH_OUT and \c * IGRAPH_ALL. This argument is ignored for undirected graphs. * \param loops Boolean, whether to consider loop edges when * calculating the degree (and the centralization). * \param centralization Pointer to a real number, the centralization * score is placed here. * \param theoretical_max Pointer to real number or a null pointer. If * not a null pointer, then the theoretical maximum graph * centrality score for a graph with the same number vertices is * stored here. * \param normalized Boolean, whether to calculate a normalized * centralization score. See \ref igraph_centralization() for how * the normalization is done. * \return Error code. * * \sa \ref igraph_centralization(), \ref igraph_degree(). * * Time complexity: the complexity of \ref igraph_degree() plus O(n), * the number of vertices queried, for calculating the centralization * score. */ int igraph_centralization_degree(const igraph_t *graph, igraph_vector_t *res, igraph_neimode_t mode, igraph_bool_t loops, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized) { igraph_vector_t myscores; igraph_vector_t *scores=res; igraph_real_t *tmax=theoretical_max, mytmax; if (!tmax) { tmax=&mytmax; } if (!res) { scores=&myscores; IGRAPH_VECTOR_INIT_FINALLY(scores, 0); } IGRAPH_CHECK(igraph_degree(graph, scores, igraph_vss_all(), mode, loops)); IGRAPH_CHECK(igraph_centralization_degree_tmax(graph, 0, mode, loops, tmax)); *centralization = igraph_centralization(scores, *tmax, normalized); if (!res) { igraph_vector_destroy(scores); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_centralization_degree_tmax * Theoretical maximum for graph centralization based on degree * * This function returns the theoretical maximum graph centrality * based on vertex degree. * * * There are two ways to call this function, the first is to supply a * graph as the graph argument, and then the number of * vertices is taken from this object, and its directedness is * considered as well. The nodes argument is ignored in * this case. The mode argument is also ignored if the * supplied graph is undirected. * * * The other way is to supply a null pointer as the graph * argument. In this case the nodes and mode * arguments are considered. * * * The most centralized structure is the star. More specifically, for * undirected graphs it is the star, for directed graphs it is the * in-star or the out-star. * \param graph A graph object or a null pointer, see the description * above. * \param nodes The number of nodes. This is ignored if the * graph argument is not a null pointer. * \param mode Constant, whether the calculation is based on in-degree * (IGRAPH_IN), out-degree (IGRAPH_OUT) * or total degree (IGRAPH_ALL). This is ignored if * the graph argument is not a null pointer and the * given graph is undirected. * \param loops Boolean scalar, whether to consider loop edges in the * calculation. * \param res Pointer to a real variable, the result is stored here. * \return Error code. * * Time complexity: O(1). * * \sa \ref igraph_centralization_degree() and \ref * igraph_centralization(). */ int igraph_centralization_degree_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_neimode_t mode, igraph_bool_t loops, igraph_real_t *res) { igraph_bool_t directed=mode != IGRAPH_ALL; igraph_real_t real_nodes; if (graph) { directed=igraph_is_directed(graph); nodes=igraph_vcount(graph); } real_nodes = nodes; /* implicit cast to igraph_real_t */ if (directed) { switch (mode) { case IGRAPH_IN: case IGRAPH_OUT: if (!loops) { *res = (real_nodes-1) * (real_nodes-1); } else { *res = (real_nodes-1) * real_nodes; } break; case IGRAPH_ALL: if (!loops) { *res = 2 * (real_nodes-1) * (real_nodes-2); } else { *res = 2 * (real_nodes-1) * (real_nodes-1); } break; } } else { if (!loops) { *res = (real_nodes-1) * (real_nodes-2); } else { *res = (real_nodes-1) * real_nodes; } } return 0; } /** * \function igraph_centralization_betweenness * Calculate vertex betweenness and graph centralization * * This function calculates the betweenness centrality of the vertices * by passing its arguments to \ref igraph_betweenness(); and it * calculates the graph level centralization index based on the * results by calling \ref igraph_centralization(). * \param graph The input graph. * \param res A vector if you need the node-level betweenness scores, or a * null pointer otherwise. * \param directed Boolean, whether to consider directed paths when * calculating betweenness. * \param nobigint Logical, if true, then we don't use big integers * for the calculation, setting this to zero (=false) should * work for most graphs. It is currently ignored for weighted * graphs. * \param centralization Pointer to a real number, the centralization * score is placed here. * \param theoretical_max Pointer to real number or a null pointer. If * not a null pointer, then the theoretical maximum graph * centrality score for a graph with the same number vertices is * stored here. * \param normalized Boolean, whether to calculate a normalized * centralization score. See \ref igraph_centralization() for how * the normalization is done. * \return Error code. * * \sa \ref igraph_centralization(), \ref igraph_betweenness(). * * Time complexity: the complexity of \ref igraph_betweenness() plus * O(n), the number of vertices queried, for calculating the * centralization score. */ int igraph_centralization_betweenness(const igraph_t *graph, igraph_vector_t *res, igraph_bool_t directed, igraph_bool_t nobigint, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized) { igraph_vector_t myscores; igraph_vector_t *scores=res; igraph_real_t *tmax=theoretical_max, mytmax; if (!tmax) { tmax=&mytmax; } if (!res) { scores=&myscores; IGRAPH_VECTOR_INIT_FINALLY(scores, 0); } IGRAPH_CHECK(igraph_betweenness(graph, scores, igraph_vss_all(), directed, /*weights=*/ 0, nobigint)); IGRAPH_CHECK(igraph_centralization_betweenness_tmax(graph, 0, directed, tmax)); *centralization = igraph_centralization(scores, *tmax, normalized); if (!res) { igraph_vector_destroy(scores); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_centralization_betweenness_tmax * Theoretical maximum for graph centralization based on betweenness * * This function returns the theoretical maximum graph centrality * based on vertex betweenness. * * * There are two ways to call this function, the first is to supply a * graph as the graph argument, and then the number of * vertices is taken from this object, and its directedness is * considered as well. The nodes argument is ignored in * this case. The directed argument is also ignored if the * supplied graph is undirected. * * * The other way is to supply a null pointer as the graph * argument. In this case the nodes and directed * arguments are considered. * * * The most centralized structure is the star. * \param graph A graph object or a null pointer, see the description * above. * \param nodes The number of nodes. This is ignored if the * graph argument is not a null pointer. * \param directed Boolean scalar, whether to use directed paths in * the betweenness calculation. This argument is ignored if * graph is not a null pointer and it is undirected. * \param res Pointer to a real variable, the result is stored here. * \return Error code. * * Time complexity: O(1). * * \sa \ref igraph_centralization_betweenness() and \ref * igraph_centralization(). */ int igraph_centralization_betweenness_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_bool_t directed, igraph_real_t *res) { igraph_real_t real_nodes; if (graph) { directed=directed && igraph_is_directed(graph); nodes=igraph_vcount(graph); } real_nodes = nodes; /* implicit cast to igraph_real_t */ if (directed) { *res = (real_nodes-1) * (real_nodes-1) * (real_nodes-2); } else { *res = (real_nodes-1) * (real_nodes-1) * (real_nodes-2) / 2.0; } return 0; } /** * \function igraph_centralization_closeness * Calculate vertex closeness and graph centralization * * This function calculates the closeness centrality of the vertices * by passing its arguments to \ref igraph_closeness(); and it * calculates the graph level centralization index based on the * results by calling \ref igraph_centralization(). * \param graph The input graph. * \param res A vector if you need the node-level closeness scores, or a * null pointer otherwise. * \param mode Constant the specifies the type of closeness for directed * graphs. Possible values: \c IGRAPH_IN, \c IGRAPH_OUT and \c * IGRAPH_ALL. This argument is ignored for undirected graphs. See * \ref igraph_closeness() argument with the same name for more. * \param centralization Pointer to a real number, the centralization * score is placed here. * \param theoretical_max Pointer to real number or a null pointer. If * not a null pointer, then the theoretical maximum graph * centrality score for a graph with the same number vertices is * stored here. * \param normalized Boolean, whether to calculate a normalized * centralization score. See \ref igraph_centralization() for how * the normalization is done. * \return Error code. * * \sa \ref igraph_centralization(), \ref igraph_closeness(). * * Time complexity: the complexity of \ref igraph_closeness() plus * O(n), the number of vertices queried, for calculating the * centralization score. */ int igraph_centralization_closeness(const igraph_t *graph, igraph_vector_t *res, igraph_neimode_t mode, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized) { igraph_vector_t myscores; igraph_vector_t *scores=res; igraph_real_t *tmax=theoretical_max, mytmax; if (!tmax) { tmax=&mytmax; } if (!res) { scores=&myscores; IGRAPH_VECTOR_INIT_FINALLY(scores, 0); } IGRAPH_CHECK(igraph_closeness(graph, scores, igraph_vss_all(), mode, /*weights=*/ 0, /*normalize=*/ 1)); IGRAPH_CHECK(igraph_centralization_closeness_tmax(graph, 0, mode, tmax)); *centralization = igraph_centralization(scores, *tmax, normalized); if (!res) { igraph_vector_destroy(scores); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_centralization_closeness_tmax * Theoretical maximum for graph centralization based on closeness * * This function returns the theoretical maximum graph centrality * based on vertex closeness. * * * There are two ways to call this function, the first is to supply a * graph as the graph argument, and then the number of * vertices is taken from this object, and its directedness is * considered as well. The nodes argument is ignored in * this case. The mode argument is also ignored if the * supplied graph is undirected. * * * The other way is to supply a null pointer as the graph * argument. In this case the nodes and mode * arguments are considered. * * * The most centralized structure is the star. * \param graph A graph object or a null pointer, see the description * above. * \param nodes The number of nodes. This is ignored if the * graph argument is not a null pointer. * \param mode Constant, specifies what kinf of distances to consider * to calculate closeness. See the mode argument of * \ref igraph_closeness() for details. This argument is ignored * if graph is not a null pointer and it is * undirected. * \param res Pointer to a real variable, the result is stored here. * \return Error code. * * Time complexity: O(1). * * \sa \ref igraph_centralization_closeness() and \ref * igraph_centralization(). */ int igraph_centralization_closeness_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_neimode_t mode, igraph_real_t *res) { igraph_real_t real_nodes; if (graph) { nodes=igraph_vcount(graph); if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } } real_nodes = nodes; /* implicit cast to igraph_real_t */ if (mode != IGRAPH_ALL) { *res = (real_nodes-1) * (1.0-1.0/real_nodes); } else { *res = (real_nodes-1) * (real_nodes-2) / (2.0*real_nodes-3); } return 0; } /** * \function igraph_centralization_eigenvector_centrality * Calculate eigenvector centrality scores and graph centralization * * This function calculates the eigenvector centrality of the vertices * by passing its arguments to \ref igraph_eigenvector_centrality); * and it calculates the graph level centralization index based on the * results by calling \ref igraph_centralization(). * \param graph The input graph. * \param vector A vector if you need the node-level eigenvector * centrality scores, or a null pointer otherwise. * \param value If not a null pointer, then the leading eigenvalue is * stored here. * \param scale If not zero then the result will be scaled, such that * the absolute value of the maximum centrality is one. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices) parameter and * it always starts the calculation from a non-random vector * calculated based on the degree of the vertices. * \param centralization Pointer to a real number, the centralization * score is placed here. * \param theoretical_max Pointer to real number or a null pointer. If * not a null pointer, then the theoretical maximum graph * centrality score for a graph with the same number vertices is * stored here. * \param normalized Boolean, whether to calculate a normalized * centralization score. See \ref igraph_centralization() for how * the normalization is done. * \return Error code. * * \sa \ref igraph_centralization(), \ref igraph_eigenvector_centrality(). * * Time complexity: the complexity of \ref * igraph_eigenvector_centrality() plus O(|V|), the number of vertices * for the calculating the centralization. */ int igraph_centralization_eigenvector_centrality( const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t directed, igraph_bool_t scale, igraph_arpack_options_t *options, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized) { igraph_vector_t myscores; igraph_vector_t *scores=vector; igraph_real_t realvalue, *myvalue=value; igraph_real_t *tmax=theoretical_max, mytmax; if (!tmax) { tmax=&mytmax; } if (!vector) { scores=&myscores; IGRAPH_VECTOR_INIT_FINALLY(scores, 0); } if (!value) { myvalue=&realvalue; } IGRAPH_CHECK(igraph_eigenvector_centrality(graph, scores, myvalue, directed, scale, /*weights=*/ 0, options)); IGRAPH_CHECK(igraph_centralization_eigenvector_centrality_tmax( graph, 0, directed, scale, tmax)); *centralization = igraph_centralization(scores, *tmax, normalized); if (!vector) { igraph_vector_destroy(scores); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_centralization_eigenvector_centrality_tmax * Theoretical maximum centralization for eigenvector centrality * * This function returns the theoretical maximum graph centrality * based on vertex eigenvector centrality. * * * There are two ways to call this function, the first is to supply a * graph as the graph argument, and then the number of * vertices is taken from this object, and its directedness is * considered as well. The nodes argument is ignored in * this case. The directed argument is also ignored if the * supplied graph is undirected. * * * The other way is to supply a null pointer as the graph * argument. In this case the nodes and directed * arguments are considered. * * * The most centralized directed structure is the in-star. The most * centralized undirected structure is the graph with a single edge. * \param graph A graph object or a null pointer, see the description * above. * \param nodes The number of nodes. This is ignored if the * graph argument is not a null pointer. * \param directed Boolean scalar, whether to consider edge * directions. This argument is ignored if * graph is not a null pointer and it is undirected. * \param scale Whether to rescale the node-level centrality scores to * have a maximum of one. * \param res Pointer to a real variable, the result is stored here. * \return Error code. * * Time complexity: O(1). * * \sa \ref igraph_centralization_closeness() and \ref * igraph_centralization(). */ int igraph_centralization_eigenvector_centrality_tmax( const igraph_t *graph, igraph_integer_t nodes, igraph_bool_t directed, igraph_bool_t scale, igraph_real_t *res) { if (graph) { nodes=igraph_vcount(graph); directed=directed && igraph_is_directed(graph); } if (directed) { *res = nodes - 1; } else { if (scale) { *res = nodes - 2; } else { *res = (nodes-2.0) / M_SQRT2; } } return 0; } igraph/src/foreign-pajek-lexer.l0000644000175100001440000001522613430770201016347 0ustar hornikusers/* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-pajek-header.h" #include "foreign-pajek-parser.h" #define YY_EXTRA_TYPE igraph_i_pajek_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); %} %option noyywrap %option prefix="igraph_pajek_yy" %option outfile="lex.yy.c" %option nounput %option noinput %option nodefault %option reentrant %option bison-bridge %option bison-locations digit [0-9] word [^ \t\r\n] %% [ \t]* { } %[^\n]*\n[\r]* { } %[^\n]*\r[\n]* { } \*[Nn][eE][Tt] { return NETWORKLINE; } \*[Nn][Ee][Tt][Ww][Oo][Rr][Kk] { return NETWORKLINE; } \*[Vv][Ee][Rr][Tt][Ii][Cc][Ee][Ss] { return VERTICESLINE; } \*[Aa][Rr][Cc][Ss] { return ARCSLINE; } \*[Ee][Dd][Gg][Ee][Ss] { return EDGESLINE; } \*[Aa][Rr][Cc][Ss][Ll][Ii][Ss][Tt] { return ARCSLISTLINE; } \*[Ee][Dd][Gg][Ee][Ss][Ll][Ii][Ss][Tt] { return EDGESLISTLINE; } \*[Mm][Aa][Tt][Rr][Ii][Xx] { return MATRIXLINE; } \n\r|\r\n|\n|\r { yyextra->mode=0; return NEWLINE; } \"[^\"]*\" { return QSTR; } \([^\)]*\) { return PSTR; } \-?{digit}+(\.{digit}+)?([eE](\+|\-)?{digit}+)? { return NUM; } [Xx]_[Ff][Aa][Cc][Tt]/[ \t\n\r] { if (yyextra->mode==1) { return VP_X_FACT; } else { return ALNUM; } } [Yy]_[Ff][Aa][Cc][Tt]/[ \t\n\r] { if (yyextra->mode==1) { return VP_Y_FACT; } else { return ALNUM; } } [Ii][Cc]/[ \t\n\r] { if (yyextra->mode==1) { return VP_IC; } else { return ALNUM; } } [Bb][Cc]/[ \t\n\r] { if (yyextra->mode==1) { return VP_BC; } else { return ALNUM; } } [Bb][Ww]/[ \t\n\r] { if (yyextra->mode==1) { return VP_BW; } else { return ALNUM; } } [Pp][Hh][Ii]/[ \t\n\r] { if (yyextra->mode==1) { return VP_PHI; } else { return ALNUM; } } [Rr]/[ \t\n\r] { if (yyextra->mode==1) { return VP_R; } else { return ALNUM; } } [Qq]/[ \t\n\r] { if (yyextra->mode==1) { return VP_Q; } else { return ALNUM; } } [Ff][Oo][Nn][Tt]/[ \t\n\r] { if (yyextra->mode==1) { return VP_FONT; } else { return ALNUM; } } [Uu][Rr][Ll]/[ \t\n\r] { if (yyextra->mode==1) { return VP_URL; } else { return ALNUM; } } [Cc]/[ \t\n\r] { if (yyextra->mode==2) { return EP_C; } else { return ALNUM; } } [Pp]/[ \t\n\r] { if (yyextra->mode==2) { return EP_P; } else { return ALNUM; } } [Ss]/[ \t\n\r] { if (yyextra->mode==2) { return EP_S; } else { return ALNUM; } } [Aa]/[ \t\n\r] { if (yyextra->mode==2) { return EP_A; } else { return ALNUM; } } [Ww]/[ \t\n\r] { if (yyextra->mode==2) { return EP_W; } else { return ALNUM; } } [Hh]1/[ \t\n\r] { if (yyextra->mode==2) { return EP_H1; } else { return ALNUM; } } [Hh]2/[ \t\n\r] { if (yyextra->mode==2) { return EP_H2; } else { return ALNUM; } } [Aa]1/[ \t\n\r] { if (yyextra->mode==2) { return EP_A1; } else { return ALNUM; } } [Aa]2/[ \t\n\r] { if (yyextra->mode==2) { return EP_A2; } else { return ALNUM; } } [Kk]1/[ \t\n\r] { if (yyextra->mode==2) { return EP_K1; } else { return ALNUM; } } [Kk]2/[ \t\n\r] { if (yyextra->mode==2) { return EP_K2; } else { return ALNUM; } } [Aa][Pp]/[ \t\n\r] { if (yyextra->mode==2) { return EP_AP; } else { return ALNUM; } } [Ll]/[ \t\n\r] { if (yyextra->mode==2) { return EP_L; } else { return ALNUM; } } [Ll][Pp]/[ \t\n\r] { if (yyextra->mode==2) { return EP_LP; } else { return ALNUM; } } [Ll][Pp][Hh][Ii]/[ \t\n\r] { if (yyextra->mode==1) { return VP_LPHI; } else if (yyextra->mode==2) { return EP_LPHI; } else { return ALNUM; } } [Ll][Cc]/[ \t\n\r] { if (yyextra->mode==1) { return VP_LC; } else if (yyextra->mode==2) { return EP_LC; } else { return ALNUM; } } [Ll][Rr]/[ \t\n\r] { if (yyextra->mode==1) { return VP_LR; } else if (yyextra->mode==2) { return EP_LR; } else { return ALNUM; } } [Ll][Aa]/[ \t\n\r] { if (yyextra->mode==1) { return VP_LA; } else if (yyextra->mode==2) { return EP_LA; } else { return ALNUM; } } [Ss][Ii][Zz][Ee]/[ \t\n\r] { if (yyextra->mode==1) { return VP_SIZE; } else if (yyextra->mode==2) { return EP_SIZE; } else { return ALNUM; } } [Ff][Oo][Ss]/[ \t\n\r] { if (yyextra->mode==1) { return VP_FOS; } else if (yyextra->mode==2) { return EP_FOS; } else { return ALNUM; } } {word}+ { return ALNUM; } <> { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } . { return ERROR; } %% igraph/src/dstqrb.f0000644000175100001440000004065413431000472014002 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdstqrb c c\Description: c Computes all eigenvalues and the last component of the eigenvectors c of a symmetric tridiagonal matrix using the implicit QL or QR method. c c This is mostly a modification of the LAPACK routine dsteqr. c See Remarks. c c\Usage: c call igraphdstqrb c ( N, D, E, Z, WORK, INFO ) c c\Arguments c N Integer. (INPUT) c The number of rows and columns in the matrix. N >= 0. c c D Double precision array, dimension (N). (INPUT/OUTPUT) c On entry, D contains the diagonal elements of the c tridiagonal matrix. c On exit, D contains the eigenvalues, in ascending order. c If an error exit is made, the eigenvalues are correct c for indices 1,2,...,INFO-1, but they are unordered and c may not be the smallest eigenvalues of the matrix. c c E Double precision array, dimension (N-1). (INPUT/OUTPUT) c On entry, E contains the subdiagonal elements of the c tridiagonal matrix in positions 1 through N-1. c On exit, E has been destroyed. c c Z Double precision array, dimension (N). (OUTPUT) c On exit, Z contains the last row of the orthonormal c eigenvector matrix of the symmetric tridiagonal matrix. c If an error exit is made, Z contains the last row of the c eigenvector matrix associated with the stored eigenvalues. c c WORK Double precision array, dimension (max(1,2*N-2)). (WORKSPACE) c Workspace used in accumulating the transformation for c computing the last components of the eigenvectors. c c INFO Integer. (OUTPUT) c = 0: normal return. c < 0: if INFO = -i, the i-th argument had an illegal value. c > 0: if INFO = +i, the i-th eigenvalue has not converged c after a total of 30*N iterations. c c\Remarks c 1. None. c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c daxpy Level 1 BLAS that computes a vector triad. c dcopy Level 1 BLAS that copies one vector to another. c dswap Level 1 BLAS that swaps the contents of two vectors. c lsame LAPACK character comparison routine. c dlae2 LAPACK routine that computes the eigenvalues of a 2-by-2 c symmetric matrix. c dlaev2 LAPACK routine that eigendecomposition of a 2-by-2 symmetric c matrix. c dlamch LAPACK routine that determines machine constants. c dlanst LAPACK routine that computes the norm of a matrix. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c dlartg LAPACK Givens rotation construction routine. c dlascl LAPACK routine for careful scaling of a matrix. c dlaset LAPACK matrix initialization routine. c dlasr LAPACK routine that applies an orthogonal transformation to c a matrix. c dlasrt LAPACK sorting routine. c dsteqr LAPACK routine that computes eigenvalues and eigenvectors c of a symmetric tridiagonal matrix. c xerbla LAPACK error handler routine. c c\Authors c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: stqrb.F SID: 2.5 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c 1. Starting with version 2.5, this routine is a modified version c of LAPACK version 2.0 subroutine SSTEQR. No lines are deleted, c only commeted out and new lines inserted. c All lines commented out have "c$$$" at the beginning. c Note that the LAPACK version 1.0 subroutine SSTEQR contained c bugs. c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdstqrb ( n, d, e, z, work, info ) c c %------------------% c | Scalar Arguments | c %------------------% c integer info, n c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & d( n ), e( n-1 ), z( n ), work( 2*n-2 ) c c .. parameters .. Double precision & zero, one, two, three parameter ( zero = 0.0D+0, one = 1.0D+0, & two = 2.0D+0, three = 3.0D+0 ) integer maxit parameter ( maxit = 30 ) c .. c .. local scalars .. integer i, icompz, ii, iscale, j, jtot, k, l, l1, lend, & lendm1, lendp1, lendsv, lm1, lsv, m, mm, mm1, & nm1, nmaxit Double precision & anorm, b, c, eps, eps2, f, g, p, r, rt1, rt2, & s, safmax, safmin, ssfmax, ssfmin, tst c .. c .. external functions .. logical lsame Double precision & dlamch, dlanst, dlapy2 external lsame, dlamch, dlanst, dlapy2 c .. c .. external subroutines .. external dlae2, dlaev2, dlartg, dlascl, dlaset, dlasr, & dlasrt, dswap, xerbla c .. c .. intrinsic functions .. intrinsic abs, max, sign, sqrt c .. c .. executable statements .. c c test the input parameters. c info = 0 c c$$$ IF( LSAME( COMPZ, 'N' ) ) THEN c$$$ ICOMPZ = 0 c$$$ ELSE IF( LSAME( COMPZ, 'V' ) ) THEN c$$$ ICOMPZ = 1 c$$$ ELSE IF( LSAME( COMPZ, 'I' ) ) THEN c$$$ ICOMPZ = 2 c$$$ ELSE c$$$ ICOMPZ = -1 c$$$ END IF c$$$ IF( ICOMPZ.LT.0 ) THEN c$$$ INFO = -1 c$$$ ELSE IF( N.LT.0 ) THEN c$$$ INFO = -2 c$$$ ELSE IF( ( LDZ.LT.1 ) .OR. ( ICOMPZ.GT.0 .AND. LDZ.LT.MAX( 1, c$$$ $ N ) ) ) THEN c$$$ INFO = -6 c$$$ END IF c$$$ IF( INFO.NE.0 ) THEN c$$$ CALL XERBLA( 'SSTEQR', -INFO ) c$$$ RETURN c$$$ END IF c c *** New starting with version 2.5 *** c icompz = 2 c ************************************* c c quick return if possible c if( n.eq.0 ) $ return c if( n.eq.1 ) then if( icompz.eq.2 ) z( 1 ) = one return end if c c determine the unit roundoff and over/underflow thresholds. c eps = dlamch( 'e' ) eps2 = eps**2 safmin = dlamch( 's' ) safmax = one / safmin ssfmax = sqrt( safmax ) / three ssfmin = sqrt( safmin ) / eps2 c c compute the eigenvalues and eigenvectors of the tridiagonal c matrix. c c$$ if( icompz.eq.2 ) c$$$ $ call dlaset( 'full', n, n, zero, one, z, ldz ) c c *** New starting with version 2.5 *** c if ( icompz .eq. 2 ) then do 5 j = 1, n-1 z(j) = zero 5 continue z( n ) = one end if c ************************************* c nmaxit = n*maxit jtot = 0 c c determine where the matrix splits and choose ql or qr iteration c for each block, according to whether top or bottom diagonal c element is smaller. c l1 = 1 nm1 = n - 1 c 10 continue if( l1.gt.n ) $ go to 160 if( l1.gt.1 ) $ e( l1-1 ) = zero if( l1.le.nm1 ) then do 20 m = l1, nm1 tst = abs( e( m ) ) if( tst.eq.zero ) $ go to 30 if( tst.le.( sqrt( abs( d( m ) ) )*sqrt( abs( d( m+ $ 1 ) ) ) )*eps ) then e( m ) = zero go to 30 end if 20 continue end if m = n c 30 continue l = l1 lsv = l lend = m lendsv = lend l1 = m + 1 if( lend.eq.l ) $ go to 10 c c scale submatrix in rows and columns l to lend c anorm = dlanst( 'i', lend-l+1, d( l ), e( l ) ) iscale = 0 if( anorm.eq.zero ) $ go to 10 if( anorm.gt.ssfmax ) then iscale = 1 call dlascl( 'g', 0, 0, anorm, ssfmax, lend-l+1, 1, d( l ), n, $ info ) call dlascl( 'g', 0, 0, anorm, ssfmax, lend-l, 1, e( l ), n, $ info ) else if( anorm.lt.ssfmin ) then iscale = 2 call dlascl( 'g', 0, 0, anorm, ssfmin, lend-l+1, 1, d( l ), n, $ info ) call dlascl( 'g', 0, 0, anorm, ssfmin, lend-l, 1, e( l ), n, $ info ) end if c c choose between ql and qr iteration c if( abs( d( lend ) ).lt.abs( d( l ) ) ) then lend = lsv l = lendsv end if c if( lend.gt.l ) then c c ql iteration c c look for small subdiagonal element. c 40 continue if( l.ne.lend ) then lendm1 = lend - 1 do 50 m = l, lendm1 tst = abs( e( m ) )**2 if( tst.le.( eps2*abs( d( m ) ) )*abs( d( m+1 ) )+ $ safmin )go to 60 50 continue end if c m = lend c 60 continue if( m.lt.lend ) $ e( m ) = zero p = d( l ) if( m.eq.l ) $ go to 80 c c if remaining matrix is 2-by-2, use dlae2 or dlaev2 c to compute its eigensystem. c if( m.eq.l+1 ) then if( icompz.gt.0 ) then call dlaev2( d( l ), e( l ), d( l+1 ), rt1, rt2, c, s ) work( l ) = c work( n-1+l ) = s c$$$ call dlasr( 'r', 'v', 'b', n, 2, work( l ), c$$$ $ work( n-1+l ), z( 1, l ), ldz ) c c *** New starting with version 2.5 *** c tst = z(l+1) z(l+1) = c*tst - s*z(l) z(l) = s*tst + c*z(l) c ************************************* else call dlae2( d( l ), e( l ), d( l+1 ), rt1, rt2 ) end if d( l ) = rt1 d( l+1 ) = rt2 e( l ) = zero l = l + 2 if( l.le.lend ) $ go to 40 go to 140 end if c if( jtot.eq.nmaxit ) $ go to 140 jtot = jtot + 1 c c form shift. c g = ( d( l+1 )-p ) / ( two*e( l ) ) r = dlapy2( g, one ) g = d( m ) - p + ( e( l ) / ( g+sign( r, g ) ) ) c s = one c = one p = zero c c inner loop c mm1 = m - 1 do 70 i = mm1, l, -1 f = s*e( i ) b = c*e( i ) call dlartg( g, f, c, s, r ) if( i.ne.m-1 ) $ e( i+1 ) = r g = d( i+1 ) - p r = ( d( i )-g )*s + two*c*b p = s*r d( i+1 ) = g + p g = c*r - b c c if eigenvectors are desired, then save rotations. c if( icompz.gt.0 ) then work( i ) = c work( n-1+i ) = -s end if c 70 continue c c if eigenvectors are desired, then apply saved rotations. c if( icompz.gt.0 ) then mm = m - l + 1 c$$$ call dlasr( 'r', 'v', 'b', n, mm, work( l ), work( n-1+l ), c$$$ $ z( 1, l ), ldz ) c c *** New starting with version 2.5 *** c call dlasr( 'r', 'v', 'b', 1, mm, work( l ), & work( n-1+l ), z( l ), 1 ) c ************************************* end if c d( l ) = d( l ) - p e( l ) = g go to 40 c c eigenvalue found. c 80 continue d( l ) = p c l = l + 1 if( l.le.lend ) $ go to 40 go to 140 c else c c qr iteration c c look for small superdiagonal element. c 90 continue if( l.ne.lend ) then lendp1 = lend + 1 do 100 m = l, lendp1, -1 tst = abs( e( m-1 ) )**2 if( tst.le.( eps2*abs( d( m ) ) )*abs( d( m-1 ) )+ $ safmin )go to 110 100 continue end if c m = lend c 110 continue if( m.gt.lend ) $ e( m-1 ) = zero p = d( l ) if( m.eq.l ) $ go to 130 c c if remaining matrix is 2-by-2, use dlae2 or dlaev2 c to compute its eigensystem. c if( m.eq.l-1 ) then if( icompz.gt.0 ) then call dlaev2( d( l-1 ), e( l-1 ), d( l ), rt1, rt2, c, s ) c$$$ work( m ) = c c$$$ work( n-1+m ) = s c$$$ call dlasr( 'r', 'v', 'f', n, 2, work( m ), c$$$ $ work( n-1+m ), z( 1, l-1 ), ldz ) c c *** New starting with version 2.5 *** c tst = z(l) z(l) = c*tst - s*z(l-1) z(l-1) = s*tst + c*z(l-1) c ************************************* else call dlae2( d( l-1 ), e( l-1 ), d( l ), rt1, rt2 ) end if d( l-1 ) = rt1 d( l ) = rt2 e( l-1 ) = zero l = l - 2 if( l.ge.lend ) $ go to 90 go to 140 end if c if( jtot.eq.nmaxit ) $ go to 140 jtot = jtot + 1 c c form shift. c g = ( d( l-1 )-p ) / ( two*e( l-1 ) ) r = dlapy2( g, one ) g = d( m ) - p + ( e( l-1 ) / ( g+sign( r, g ) ) ) c s = one c = one p = zero c c inner loop c lm1 = l - 1 do 120 i = m, lm1 f = s*e( i ) b = c*e( i ) call dlartg( g, f, c, s, r ) if( i.ne.m ) $ e( i-1 ) = r g = d( i ) - p r = ( d( i+1 )-g )*s + two*c*b p = s*r d( i ) = g + p g = c*r - b c c if eigenvectors are desired, then save rotations. c if( icompz.gt.0 ) then work( i ) = c work( n-1+i ) = s end if c 120 continue c c if eigenvectors are desired, then apply saved rotations. c if( icompz.gt.0 ) then mm = l - m + 1 c$$$ call dlasr( 'r', 'v', 'f', n, mm, work( m ), work( n-1+m ), c$$$ $ z( 1, m ), ldz ) c c *** New starting with version 2.5 *** c call dlasr( 'r', 'v', 'f', 1, mm, work( m ), work( n-1+m ), & z( m ), 1 ) c ************************************* end if c d( l ) = d( l ) - p e( lm1 ) = g go to 90 c c eigenvalue found. c 130 continue d( l ) = p c l = l - 1 if( l.ge.lend ) $ go to 90 go to 140 c end if c c undo scaling if necessary c 140 continue if( iscale.eq.1 ) then call dlascl( 'g', 0, 0, ssfmax, anorm, lendsv-lsv+1, 1, $ d( lsv ), n, info ) call dlascl( 'g', 0, 0, ssfmax, anorm, lendsv-lsv, 1, e( lsv ), $ n, info ) else if( iscale.eq.2 ) then call dlascl( 'g', 0, 0, ssfmin, anorm, lendsv-lsv+1, 1, $ d( lsv ), n, info ) call dlascl( 'g', 0, 0, ssfmin, anorm, lendsv-lsv, 1, e( lsv ), $ n, info ) end if c c check for no convergence to an eigenvalue after a total c of n*maxit iterations. c if( jtot.lt.nmaxit ) $ go to 10 do 150 i = 1, n - 1 if( e( i ).ne.zero ) $ info = info + 1 150 continue go to 190 c c order eigenvalues and eigenvectors. c 160 continue if( icompz.eq.0 ) then c c use quick sort c call dlasrt( 'i', n, d, info ) c else c c use selection sort to minimize swaps of eigenvectors c do 180 ii = 2, n i = ii - 1 k = i p = d( i ) do 170 j = ii, n if( d( j ).lt.p ) then k = j p = d( j ) end if 170 continue if( k.ne.i ) then d( k ) = d( i ) d( i ) = p c$$$ call dswap( n, z( 1, i ), 1, z( 1, k ), 1 ) c *** New starting with version 2.5 *** c p = z(k) z(k) = z(i) z(i) = p c ************************************* end if 180 continue end if c 190 continue return c c %---------------% c | End of igraphdstqrb | c %---------------% c end igraph/src/iterators.c0000644000175100001440000015536313431000472014520 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_iterators.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_interface.h" #include "config.h" #include #include /** * \section about_iterators About selectors, iterators * * Everything about vertices and vertex selectors also applies * to edges and edge selectors unless explicitly noted otherwise. * * The vertex (and edge) selector notion was introduced in igraph 0.2. * It is a way to reference a sequence of vertices or edges * independently of the graph. * * While this might sound quite mysterious, it is actually very * simple. For example, all vertices of a graph can be selected by * \ref igraph_vs_all() and the graph independence means that * \ref igraph_vs_all() is not parametrized by a graph object. That is, * \ref igraph_vs_all() is the general \em concept of selecting all vertices * of a graph. A vertex selector is then a way to specify the class of vertices * to be visited. The selector might specify that all vertices of a graph or * all the neighbours of a vertex are to be visited. A vertex selector is a * way of saying that you want to visit a bunch of vertices, as opposed to a * vertex iterator which is a concrete plan for visiting each of the * chosen vertices of a specific graph. * * To determine the actual vertex IDs implied by a vertex selector, you * need to apply the concept of selecting vertices to a specific graph object. * This can be accomplished by instantiating a vertex iterator using a * specific vertex selection concept and a specific graph object. The notion * of vertex iterators can be thought of in the following way. Given a * specific graph object and the class of vertices to be visited, a vertex * iterator is a road map, plan or route for how to visit the chosen * vertices. * * Some vertex selectors have \em immediate versions. These have the * prefix \c igraph_vss instead of \c igraph_vs, e.g. \ref igraph_vss_all() * instead of \ref igraph_vs_all(). The immediate versions are to be used in * the parameter list of the igraph functions, such as \ref igraph_degree(). * These functions are not associated with any \type igraph_vs_t object, so * they have no separate constructors and destructors * (destroy functions). */ /** * \section about_vertex_selectors * * Vertex selectors are created by vertex selector constructors, * can be instantiated with \ref igraph_vit_create(), and are * destroyed with \ref igraph_vs_destroy(). */ /** * \function igraph_vs_all * \brief Vertex set, all vertices of a graph. * * \param vs Pointer to an uninitialized \type igraph_vs_t object. * \return Error code. * \sa \ref igraph_vss_all(), \ref igraph_vs_destroy() * * This selector includes all vertices of a given graph in * increasing vertex id order. * * * Time complexity: O(1). */ int igraph_vs_all(igraph_vs_t *vs) { vs->type=IGRAPH_VS_ALL; return 0; } /** * \function igraph_vss_all * \brief All vertices of a graph (immediate version). * * Immediate vertex selector for all vertices in a graph. It can * be used conveniently when some vertex property (eg. betweenness, * degree, etc.) should be calculated for all vertices. * * \return A vertex selector for all vertices in a graph. * \sa \ref igraph_vs_all() * * Time complexity: O(1). */ igraph_vs_t igraph_vss_all(void) { igraph_vs_t allvs; allvs.type=IGRAPH_VS_ALL; return allvs; } /** * \function igraph_vs_adj * \brief Adjacent vertices of a vertex. * * All neighboring vertices of a given vertex are selected by this * selector. The \c mode argument controls the type of the neighboring * vertices to be selected. The vertices are visited in increasing vertex * ID order, as of igraph version 0.4. * * \param vs Pointer to an uninitialized vertex selector object. * \param vid Vertex ID, the center of the neighborhood. * \param mode Decides the type of the neighborhood for directed * graphs. This parameter is ignored for undirected graphs. * Possible values: * \clist * \cli IGRAPH_OUT * All vertices to which there is a directed edge from \c vid. That * is, all the out-neighbors of \c vid. * \cli IGRAPH_IN * All vertices from which there is a directed edge to \c vid. In * other words, all the in-neighbors of \c vid. * \cli IGRAPH_ALL * All vertices to which or from which there is a directed edge * from/to \c vid. That is, all the neighbors of \c vid considered * as if the graph is undirected. * \endclist * \return Error code. * \sa \ref igraph_vs_destroy() * * Time complexity: O(1). */ int igraph_vs_adj(igraph_vs_t *vs, igraph_integer_t vid, igraph_neimode_t mode) { vs->type=IGRAPH_VS_ADJ; vs->data.adj.vid=vid; vs->data.adj.mode=mode; return 0; } /** * \function igraph_vs_nonadj * \brief Non-adjacent vertices of a vertex. * * All non-neighboring vertices of a given vertex. The \p mode * argument controls the type of neighboring vertices \em not to * select. Instead of selecting immediate neighbors of \c vid as is done by * \ref igraph_vs_adj(), the current function selects vertices that are \em not * immediate neighbors of \c vid. * * \param vs Pointer to an uninitialized vertex selector object. * \param vid Vertex ID, the \quote center \endquote of the * non-neighborhood. * \param mode The type of neighborhood not to select in directed * graphs. Possible values: * \clist * \cli IGRAPH_OUT * All vertices will be selected except those to which there is a * directed edge from \c vid. That is, we select all vertices * excluding the out-neighbors of \c vid. * \cli IGRAPH_IN * All vertices will be selected except those from which there is a * directed edge to \c vid. In other words, we select all vertices * but the in-neighbors of \c vid. * \cli IGRAPH_ALL * All vertices will be selected except those from or to which there * is a directed edge to or from \c vid. That is, we select all * vertices of \c vid except for its immediate neighbors. * \endclist * \return Error code. * \sa \ref igraph_vs_destroy() * * Time complexity: O(1). * * \example examples/simple/igraph_vs_nonadj.c */ int igraph_vs_nonadj(igraph_vs_t *vs, igraph_integer_t vid, igraph_neimode_t mode) { vs->type=IGRAPH_VS_NONADJ; vs->data.adj.vid=vid; vs->data.adj.mode=mode; return 0; } /** * \function igraph_vs_none * \brief Empty vertex set. * * Creates an empty vertex selector. * * \param vs Pointer to an uninitialized vertex selector object. * \return Error code. * \sa \ref igraph_vss_none(), \ref igraph_vs_destroy() * * Time complexity: O(1). */ int igraph_vs_none(igraph_vs_t *vs) { vs->type=IGRAPH_VS_NONE; return 0; } /** * \function igraph_vss_none * \brief Empty vertex set (immediate version). * * The immediate version of the empty vertex selector. * * \return An empty vertex selector. * \sa \ref igraph_vs_none() * * Time complexity: O(1). */ igraph_vs_t igraph_vss_none(void) { igraph_vs_t nonevs; nonevs.type=IGRAPH_VS_NONE; return nonevs; } /** * \function igraph_vs_1 * \brief Vertex set with a single vertex. * * This vertex selector selects a single vertex. * * \param vs Pointer to an uninitialized vertex selector object. * \param vid The vertex id to be selected. * \return Error Code. * \sa \ref igraph_vss_1(), \ref igraph_vs_destroy() * * Time complexity: O(1). */ int igraph_vs_1(igraph_vs_t *vs, igraph_integer_t vid) { vs->type=IGRAPH_VS_1; vs->data.vid=vid; return 0; } /** * \function igraph_vss_1 * \brief Vertex set with a single vertex (immediate version). * * The immediate version of the single-vertex selector. * * \param vid The vertex to be selected. * \return A vertex selector containing a single vertex. * \sa \ref igraph_vs_1() * * Time complexity: O(1). */ igraph_vs_t igraph_vss_1(igraph_integer_t vid) { igraph_vs_t onevs; onevs.type=IGRAPH_VS_1; onevs.data.vid=vid; return onevs; } /** * \function igraph_vs_vector * \brief Vertex set based on a vector. * * This function makes it possible to handle a \type vector_t * temporarily as a vertex selector. The vertex selector should be * thought of like a \em view to the vector. If you make changes to * the vector that also affects the vertex selector. Destroying the * vertex selector does not destroy the vector. (Of course.) Do not * destroy the vector before destroying the vertex selector, or you * might get strange behavior. * * \param vs Pointer to an uninitialized vertex selector. * \param v Pointer to a \type igraph_vector_t object. * \return Error code. * \sa \ref igraph_vss_vector(), \ref igraph_vs_destroy() * * Time complexity: O(1). * * \example examples/simple/igraph_vs_vector.c */ int igraph_vs_vector(igraph_vs_t *vs, const igraph_vector_t *v) { vs->type=IGRAPH_VS_VECTORPTR; vs->data.vecptr=v; return 0; } /** * \function igraph_vss_vector * \brief Vertex set based on a vector (immediate version). * * This is the immediate version of \ref igraph_vs_vector. * * \param v Pointer to a \type igraph_vector_t object. * \return A vertex selector object containing the vertices in the * vector. * \sa \ref igraph_vs_vector() * * Time complexity: O(1). */ igraph_vs_t igraph_vss_vector(const igraph_vector_t *v) { igraph_vs_t vecvs; vecvs.type=IGRAPH_VS_VECTORPTR; vecvs.data.vecptr=v; return vecvs; } /** * \function igraph_vs_vector_small * \brief Create a vertex set by giving its elements. * * This function can be used to create a vertex selector with a couple * of vertices. Do not forget to include a -1 after the * last vertex id. The behavior of the function is undefined if you * don't use a -1 properly. * * * Note that the vertex ids supplied will be parsed as * int's so you cannot supply arbitrarily large (too * large for int) vertex ids here. * * \param vs Pointer to an uninitialized vertex selector object. * \param ... Additional parameters, these will be the vertex ids to * be included in the vertex selector. Supply a -1 * after the last vertex id. * \return Error code. * \sa \ref igraph_vs_destroy() * * Time complexity: O(n), the number of vertex ids supplied. */ int igraph_vs_vector_small(igraph_vs_t *vs, ...) { va_list ap; long int i, n=0; vs->type=IGRAPH_VS_VECTOR; vs->data.vecptr=igraph_Calloc(1, igraph_vector_t); if (vs->data.vecptr==0) { IGRAPH_ERROR("Cannot create vertex selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)vs->data.vecptr); va_start(ap, vs); while (1) { int num = va_arg(ap, int); if (num == -1) { break; } n++; } va_end(ap); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t*)vs->data.vecptr, n); va_start(ap, vs); for (i=0; idata.vecptr)[i]=(igraph_real_t) va_arg(ap, int); } va_end(ap); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_vs_vector_copy * \brief Vertex set based on a vector, with copying. * * This function makes it possible to handle a \type vector_t * permanently as a vertex selector. The vertex selector creates a * copy of the original vector, so the vector can safely be destroyed * after creating the vertex selector. Changing the original vector * will not affect the vertex selector. The vertex selector is * responsible for deleting the copy made by itself. * * \param vs Pointer to an uninitialized vertex selector. * \param v Pointer to a \type igraph_vector_t object. * \return Error code. * \sa \ref igraph_vs_destroy() * * Time complexity: O(1). */ int igraph_vs_vector_copy(igraph_vs_t *vs, const igraph_vector_t *v) { vs->type=IGRAPH_VS_VECTOR; vs->data.vecptr=igraph_Calloc(1, igraph_vector_t); if (vs->data.vecptr==0) { IGRAPH_ERROR("Cannot create vertex selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)vs->data.vecptr); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*)vs->data.vecptr, v)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_vs_seq * \brief Vertex set, an interval of vertices. * * Creates a vertex selector containing all vertices with vertex id * equal to or bigger than \c from and equal to or smaller than \c * to. * * \param vs Pointer to an uninitialized vertex selector object. * \param from The first vertex id to be included in the vertex * selector. * \param to The last vertex id to be included in the vertex * selector. * \return Error code. * \sa \ref igraph_vss_seq(), \ref igraph_vs_destroy() * * Time complexity: O(1). * * \example examples/simple/igraph_vs_seq.c */ int igraph_vs_seq(igraph_vs_t *vs, igraph_integer_t from, igraph_integer_t to) { vs->type=IGRAPH_VS_SEQ; vs->data.seq.from=from; vs->data.seq.to=to+1; return 0; } /** * \function igraph_vss_seq * \brief An interval of vertices (immediate version). * * The immediate version of \ref igraph_vs_seq(). * * \param from The first vertex id to be included in the vertex * selector. * \param to The last vertex id to be included in the vertex * selector. * \return Error code. * \sa \ref igraph_vs_seq() * * Time complexity: O(1). */ igraph_vs_t igraph_vss_seq(igraph_integer_t from, igraph_integer_t to) { igraph_vs_t vs; vs.type=IGRAPH_VS_SEQ; vs.data.seq.from=from; vs.data.seq.to=to+1; return vs; } /** * \function igraph_vs_destroy * \brief Destroy a vertex set. * * This function should be called for all vertex selectors when they * are not needed. The memory allocated for the vertex selector will * be deallocated. Do not call this function on vertex selectors * created with the immediate versions of the vertex selector * constructors (starting with igraph_vss). * * \param vs Pointer to a vertex selector object. * * Time complexity: operating system dependent, usually O(1). */ void igraph_vs_destroy(igraph_vs_t *vs) { switch (vs->type) { case IGRAPH_VS_ALL: case IGRAPH_VS_ADJ: case IGRAPH_VS_NONE: case IGRAPH_VS_1: case IGRAPH_VS_VECTORPTR: case IGRAPH_VS_SEQ: case IGRAPH_VS_NONADJ: break; case IGRAPH_VS_VECTOR: igraph_vector_destroy((igraph_vector_t*)vs->data.vecptr); igraph_Free(vs->data.vecptr); break; default: break; } } /** * \function igraph_vs_is_all * \brief Check whether all vertices are included. * * This function checks whether the vertex selector object was created * by \ref igraph_vs_all() or \ref igraph_vss_all(). Note that the * vertex selector might contain all vertices in a given graph but if * it wasn't created by the two constructors mentioned here the return * value will be FALSE. * * \param vs Pointer to a vertex selector object. * \return TRUE (1) if the vertex selector contains all vertices and * FALSE (0) otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_vs_is_all(const igraph_vs_t *vs) { return vs->type == IGRAPH_VS_ALL; } int igraph_vs_as_vector(const igraph_t *graph, igraph_vs_t vs, igraph_vector_t *v) { igraph_vit_t vit; IGRAPH_CHECK(igraph_vit_create(graph, vs, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_CHECK(igraph_vit_as_vector(&vit, v)); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_vs_copy * \brief Creates a copy of a vertex selector. * \param src The selector being copied. * \param dest An uninitialized selector that will contain the copy. */ int igraph_vs_copy(igraph_vs_t* dest, const igraph_vs_t* src) { memcpy(dest, src, sizeof(igraph_vs_t)); switch (dest->type) { case IGRAPH_VS_VECTOR: dest->data.vecptr = igraph_Calloc(1,igraph_vector_t); if (!dest->data.vecptr) IGRAPH_ERROR("Cannot copy vertex selector", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*)dest->data.vecptr, (igraph_vector_t*)src->data.vecptr)); break; } return 0; } /** * \function igraph_vs_type * \brief Returns the type of the vertex selector. */ int igraph_vs_type(const igraph_vs_t *vs) { return vs->type; } /** * \function igraph_vs_size * \brief Returns the size of the vertex selector. * * The size of the vertex selector is the number of vertices it will * yield when it is iterated over. * * \param graph The graph over which we will iterate. * \param result The result will be returned here. */ int igraph_vs_size(const igraph_t *graph, const igraph_vs_t *vs, igraph_integer_t *result) { igraph_vector_t vec; igraph_bool_t *seen; long i; switch (vs->type) { case IGRAPH_VS_NONE: *result = 0; return 0; case IGRAPH_VS_1: *result = 0; if (vs->data.vid < igraph_vcount(graph) && vs->data.vid >= 0) *result=1; return 0; case IGRAPH_VS_SEQ: *result = vs->data.seq.to - vs->data.seq.from; return 0; case IGRAPH_VS_ALL: *result = igraph_vcount(graph); return 0; case IGRAPH_VS_ADJ: IGRAPH_VECTOR_INIT_FINALLY(&vec, 0); IGRAPH_CHECK(igraph_neighbors(graph,&vec,vs->data.adj.vid,vs->data.adj.mode)); *result=(igraph_integer_t) igraph_vector_size(&vec); igraph_vector_destroy(&vec); IGRAPH_FINALLY_CLEAN(1); return 0; case IGRAPH_VS_NONADJ: IGRAPH_VECTOR_INIT_FINALLY(&vec, 0); IGRAPH_CHECK(igraph_neighbors(graph,&vec,vs->data.adj.vid,vs->data.adj.mode)); *result=igraph_vcount(graph); seen=igraph_Calloc(*result, igraph_bool_t); if (seen==0) { IGRAPH_ERROR("Cannot calculate selector length", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, seen); for (i=0; idata.vecptr); return 0; } IGRAPH_ERROR("Cannot calculate selector length, invalid selector type", IGRAPH_EINVAL); } /***************************************************/ /** * \function igraph_vit_create * \brief Creates a vertex iterator from a vertex selector. * * This function instantiates a vertex selector object with a given * graph. This is the step when the actual vertex ids are created from * the \em logical notion of the vertex selector based on the graph. * Eg. a vertex selector created with \ref igraph_vs_all() contains * knowledge that \em all vertices are included in a (yet indefinite) * graph. When instantiating it a vertex iterator object is created, * this contains the actual vertex ids in the graph supplied as a * parameter. * * * The same vertex selector object can be used to instantiate any * number vertex iterators. * * \param graph An \type igraph_t object, a graph. * \param vs A vertex selector object. * \param vit Pointer to an uninitialized vertex iterator object. * \return Error code. * \sa \ref igraph_vit_destroy(). * * Time complexity: it depends on the vertex selector type. O(1) for * vertex selectors created with \ref igraph_vs_all(), \ref * igraph_vs_none(), \ref igraph_vs_1, \ref igraph_vs_vector, \ref * igraph_vs_seq(), \ref igraph_vs_vector(), \ref * igraph_vs_vector_small(). O(d) for \ref igraph_vs_adj(), d is the * number of vertex ids to be included in the iterator. O(|V|) for * \ref igraph_vs_nonadj(), |V| is the number of vertices in the graph. */ int igraph_vit_create(const igraph_t *graph, igraph_vs_t vs, igraph_vit_t *vit) { igraph_vector_t vec; igraph_bool_t *seen; long int i, j, n; switch (vs.type) { case IGRAPH_VS_ALL: vit->type=IGRAPH_VIT_SEQ; vit->pos=0; vit->start=0; vit->end=igraph_vcount(graph); break; case IGRAPH_VS_ADJ: vit->type=IGRAPH_VIT_VECTOR; vit->pos=0; vit->start=0; vit->vec=igraph_Calloc(1, igraph_vector_t); if (vit->vec == 0) { IGRAPH_ERROR("Cannot create iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) vit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t*)vit->vec, 0); IGRAPH_CHECK(igraph_neighbors(graph, (igraph_vector_t*)vit->vec, vs.data.adj.vid, vs.data.adj.mode)); vit->end=igraph_vector_size(vit->vec); IGRAPH_FINALLY_CLEAN(2); break; case IGRAPH_VS_NONADJ: vit->type=IGRAPH_VIT_VECTOR; vit->pos=0; vit->start=0; vit->vec=igraph_Calloc(1, igraph_vector_t); if (vit->vec == 0) { IGRAPH_ERROR("Cannot create iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) vit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t *) vit->vec, 0); IGRAPH_VECTOR_INIT_FINALLY(&vec, 0); IGRAPH_CHECK(igraph_neighbors(graph, &vec, vs.data.adj.vid, vs.data.adj.mode)); n=igraph_vcount(graph); seen=igraph_Calloc(n, igraph_bool_t); if (seen==0) { IGRAPH_ERROR("Cannot create iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, seen); for (i=0; ivec, n)); for (i=0, j=0; jvec)[j++] = i; } } igraph_Free(seen); igraph_vector_destroy(&vec); vit->end=n; IGRAPH_FINALLY_CLEAN(4); break; case IGRAPH_VS_NONE: vit->type=IGRAPH_VIT_SEQ; vit->pos=0; vit->start=0; vit->end=0; break; case IGRAPH_VS_1: vit->type=IGRAPH_VIT_SEQ; vit->pos=vs.data.vid; vit->start=vs.data.vid; vit->end=vs.data.vid+1; if (vit->pos >= igraph_vcount(graph)) { IGRAPH_ERROR("Cannot create iterator, invalid vertex id",IGRAPH_EINVVID); } break; case IGRAPH_VS_VECTORPTR: case IGRAPH_VS_VECTOR: vit->type=IGRAPH_VIT_VECTORPTR; vit->pos=0; vit->start=0; vit->vec=vs.data.vecptr; vit->end=igraph_vector_size(vit->vec); if (!igraph_vector_isininterval(vit->vec, 0, igraph_vcount(graph)-1)) { IGRAPH_ERROR("Cannot create iterator, invalid vertex id",IGRAPH_EINVVID); } break; case IGRAPH_VS_SEQ: vit->type=IGRAPH_VIT_SEQ; vit->pos=vs.data.seq.from; vit->start=vs.data.seq.from; vit->end=vs.data.seq.to; break; default: IGRAPH_ERROR("Cannot create iterator, invalid selector", IGRAPH_EINVAL); break; } return 0; } /** * \function igraph_vit_destroy * \brief Destroys a vertex iterator. * * * Deallocates memory allocated for a vertex iterator. * * \param vit Pointer to an initialized vertex iterator object. * \sa \ref igraph_vit_create() * * Time complexity: operating system dependent, usually O(1). */ void igraph_vit_destroy(const igraph_vit_t *vit) { switch (vit->type) { case IGRAPH_VIT_SEQ: case IGRAPH_VIT_VECTORPTR: break; case IGRAPH_VIT_VECTOR: igraph_vector_destroy((igraph_vector_t*)vit->vec); igraph_free((igraph_vector_t*)vit->vec); break; default: /* IGRAPH_ERROR("Cannot destroy iterator, unknown type", IGRAPH_EINVAL); */ break; } } int igraph_vit_as_vector(const igraph_vit_t *vit, igraph_vector_t *v) { long int i; IGRAPH_CHECK(igraph_vector_resize(v, IGRAPH_VIT_SIZE(*vit))); switch (vit->type) { case IGRAPH_VIT_SEQ: for (i=0; istart+i; } break; case IGRAPH_VIT_VECTOR: case IGRAPH_VIT_VECTORPTR: for (i=0; ivec)[i]; } break; default: IGRAPH_ERROR("Cannot convert to vector, unknown iterator type", IGRAPH_EINVAL); break; } return 0; } /*******************************************************/ /** * \function igraph_es_all * \brief Edge set, all edges. * * \param es Pointer to an uninitialized edge selector object. * \param order Constant giving the order in which the edges will be * included in the selector. Possible values: * \c IGRAPH_EDGEORDER_ID, edge id order. * \c IGRAPH_EDGEORDER_FROM, vertex id order, the id of the * \em source vertex counts for directed graphs. The order * of the incident edges of a given vertex is arbitrary. * \c IGRAPH_EDGEORDER_TO, vertex id order, the id of the \em * target vertex counts for directed graphs. The order * of the incident edges of a given vertex is arbitrary. * For undirected graph the latter two is the same. * \return Error code. * \sa \ref igraph_ess_all(), \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_all(igraph_es_t *es, igraph_edgeorder_type_t order) { switch (order) { case IGRAPH_EDGEORDER_ID: es->type=IGRAPH_ES_ALL; break; case IGRAPH_EDGEORDER_FROM: es->type=IGRAPH_ES_ALLFROM; break; case IGRAPH_EDGEORDER_TO: es->type=IGRAPH_ES_ALLTO; break; default: IGRAPH_ERROR("Invalid edge order, cannot create selector", IGRAPH_EINVAL); break; } return 0; } /** * \function igraph_ess_all * \brief Edge set, all edges (immediate version) * * The immediate version of the all-vertices selector. * * \param order Constant giving the order of the edges in the edge * selector. See \ref igraph_es_all() for the possible values. * \return The edge selector. * \sa \ref igraph_es_all() * * Time complexity: O(1). */ igraph_es_t igraph_ess_all(igraph_edgeorder_type_t order) { igraph_es_t es; igraph_es_all(&es, order); /* cannot fail */ return es; } /** * \function igraph_es_adj * \brief Adjacent edges of a vertex. * * This function was superseded by \ref igraph_es_incident() in igraph 0.6. * Please use \ref igraph_es_incident() instead of this function. * * * Deprecated in version 0.6. */ int igraph_es_adj(igraph_es_t *es, igraph_integer_t vid, igraph_neimode_t mode) { IGRAPH_WARNING("igraph_es_adj is deprecated, use igraph_es_incident"); return igraph_es_incident(es, vid, mode); } /** * \function igraph_es_incident * \brief Edges incident on a given vertex. * * \param es Pointer to an uninitialized edge selector object. * \param vid Vertex id, of which the incident edges will be * selected. * \param mode Constant giving the type of the incident edges to * select. This is ignored for undirected graphs. Possible values: * \c IGRAPH_OUT, outgoing edges; * \c IGRAPH_IN, incoming edges; * \c IGRAPH_ALL, all edges. * \return Error code. * \sa \ref igraph_es_destroy() * * Time complexity: O(1). * * \example examples/simple/igraph_es_adj.c */ int igraph_es_incident(igraph_es_t *es, igraph_integer_t vid, igraph_neimode_t mode) { es->type=IGRAPH_ES_INCIDENT; es->data.incident.vid=vid; es->data.incident.mode=mode; return 0; } /** * \function igraph_es_none * \brief Empty edge selector. * * \param es Pointer to an uninitialized edge selector object to * initialize. * \return Error code. * \sa \ref igraph_ess_none(), \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_none(igraph_es_t *es) { es->type=IGRAPH_ES_NONE; return 0; } /** * \function igraph_ess_none * \brief Immediate empty edge selector. * * * Immediate version of the empty edge selector. * * \return Initialized empty edge selector. * \sa \ref igraph_es_none() * * Time complexity: O(1). */ igraph_es_t igraph_ess_none(void) { igraph_es_t es; es.type=IGRAPH_ES_NONE; return es; } /** * \function igraph_es_1 * \brief Edge selector containing a single edge. * * \param es Pointer to an uninitialized edge selector object. * \param eid Edge id of the edge to select. * \return Error code. * \sa \ref igraph_ess_1(), \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_1(igraph_es_t *es, igraph_integer_t eid) { es->type=IGRAPH_ES_1; es->data.eid=eid; return 0; } /** * \function igraph_ess_1 * \brief Immediate version of the single edge edge selector. * * \param eid The id of the edge. * \return The edge selector. * \sa \ref igraph_es_1() * * Time complexity: O(1). */ igraph_es_t igraph_ess_1(igraph_integer_t eid) { igraph_es_t es; es.type=IGRAPH_ES_1; es.data.eid=eid; return es; } /** * \function igraph_es_vector * \brief Handle a vector as an edge selector. * * * Creates an edge selector which serves as a view to a vector * containing edge ids. Do not destroy the vector before destroying * the view. * * Many views can be created to the same vector. * * \param es Pointer to an uninitialized edge selector. * \param v Vector containing edge ids. * \return Error code. * \sa \ref igraph_ess_vector(), \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_vector(igraph_es_t *es, const igraph_vector_t *v) { es->type=IGRAPH_ES_VECTORPTR; es->data.vecptr=v; return 0; } /** * \function igraph_es_vector_copy * \brief Edge set, based on a vector, with copying. * * * This function makes it possible to handle a \type vector_t * permanently as an edge selector. The edge selector creates a * copy of the original vector, so the vector can safely be destroyed * after creating the edge selector. Changing the original vector * will not affect the edge selector. The edge selector is * responsible for deleting the copy made by itself. * * \param es Pointer to an uninitialized edge selector. * \param v Pointer to a \type igraph_vector_t object. * \return Error code. * \sa \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_vector_copy(igraph_es_t *es, const igraph_vector_t *v) { es->type=IGRAPH_ES_VECTOR; es->data.vecptr=igraph_Calloc(1, igraph_vector_t); if (es->data.vecptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)es->data.vecptr); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*)es->data.vecptr, v)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_ess_vector * \brief Immediate vector view edge selector. * * * This is the immediate version of the vector of edge ids edge * selector. * * \param v The vector of edge ids. * \return Edge selector, initialized. * \sa \ref igraph_es_vector() * * Time complexity: O(1). */ igraph_es_t igraph_ess_vector(const igraph_vector_t *v) { igraph_es_t es; es.type=IGRAPH_ES_VECTORPTR; es.data.vecptr=v; return es; } /** * \function igraph_es_fromto * \brief Edge selector, all edges between two vertex sets. * * * This function is not implemented yet. * * \param es Pointer to an uninitialized edge selector. * \param from Vertex selector, their outgoing edges will be * selected. * \param to Vertex selector, their incoming edges will be selected * from the previous selection. * \return Error code. * \sa \ref igraph_es_destroy() * * Time complexity: O(1). * * \example examples/simple/igraph_es_fromto.c */ int igraph_es_fromto(igraph_es_t *es, igraph_vs_t from, igraph_vs_t to) { IGRAPH_UNUSED(es); IGRAPH_UNUSED(from); IGRAPH_UNUSED(to); IGRAPH_ERROR("igraph_es_fromto not implemented yet", IGRAPH_UNIMPLEMENTED); /* TODO */ return 0; } /** * \function igraph_es_seq * \brief Edge selector, a sequence of edge ids. * * All edge ids between from and to will be * included in the edge selection. * * \param es Pointer to an uninitialized edge selector object. * \param from The first edge id to be included. * \param to The last edge id to be included. * \return Error code. * \sa \ref igraph_ess_seq(), \ref igraph_es_destroy() * * Time complexity: O(1). */ int igraph_es_seq(igraph_es_t *es, igraph_integer_t from, igraph_integer_t to) { es->type=IGRAPH_ES_SEQ; es->data.seq.from=from; es->data.seq.to=to; return 0; } /** * \function igraph_ess_seq * \brief Immediate version of the sequence edge selector. * * \param from The first edge id to include. * \param to The last edge id to include. * \return The initialized edge selector. * \sa \ref igraph_es_seq() * * Time complexity: O(1). */ igraph_es_t igraph_ess_seq(igraph_integer_t from, igraph_integer_t to) { igraph_es_t es; es.type=IGRAPH_ES_SEQ; es.data.seq.from=from; es.data.seq.to=to; return es; } /** * \function igraph_es_pairs * \brief Edge selector, multiple edges defined by their endpoints in a vector. * * The edges between the given pairs of vertices will be included in the * edge selection. The vertex pairs must be defined in the vector v, * the first element of the vector is the first vertex of the first edge * to be selected, the second element is the second vertex of the first * edge, the third element is the first vertex of the second edge and * so on. * * \param es Pointer to an uninitialized edge selector object. * \param v The vector containing the endpoints of the edges. * \param directed Whether the graph is directed or not. * \return Error code. * \sa \ref igraph_es_pairs_small(), \ref igraph_es_destroy() * * Time complexity: O(n), the number of edges being selected. * * \example examples/simple/igraph_es_pairs.c */ int igraph_es_pairs(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed) { es->type=IGRAPH_ES_PAIRS; es->data.path.mode=directed; es->data.path.ptr=igraph_Calloc(1, igraph_vector_t); if (es->data.path.ptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) es->data.path.ptr); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*) es->data.path.ptr, v)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_es_pairs_small * \brief Edge selector, multiple edges defined by their endpoints as arguments. * * The edges between the given pairs of vertices will be included in the * edge selection. The vertex pairs must be given as the arguments of the * function call, the third argument is the first vertex of the first edge, * the fourth argument is the second vertex of the first edge, the fifth * is the first vertex of the second edge and so on. The last element of the * argument list must be -1 to denote the end of the argument list. * * \param es Pointer to an uninitialized edge selector object. * \param directed Whether the graph is directed or not. * \return Error code. * \sa \ref igraph_es_pairs(), \ref igraph_es_destroy() * * Time complexity: O(n), the number of edges being selected. */ int igraph_es_pairs_small(igraph_es_t *es, igraph_bool_t directed, ...) { va_list ap; long int i, n=0; es->type=IGRAPH_ES_PAIRS; es->data.path.mode=directed; es->data.path.ptr=igraph_Calloc(1, igraph_vector_t); if (es->data.path.ptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)es->data.path.ptr); va_start(ap, directed); while (1) { int num = va_arg(ap, int); if (num == -1) { break; } n++; } va_end(ap); IGRAPH_VECTOR_INIT_FINALLY( (igraph_vector_t*) es->data.path.ptr, n); va_start(ap, directed); for (i=0; idata.path.ptr)[i]=(igraph_real_t) va_arg(ap, int); } va_end(ap); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_es_multipairs(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed) { es->type=IGRAPH_ES_MULTIPAIRS; es->data.path.mode=directed; es->data.path.ptr=igraph_Calloc(1, igraph_vector_t); if (es->data.path.ptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) es->data.path.ptr); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*) es->data.path.ptr, v)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \example examples/simple/igraph_es_path.c */ int igraph_es_path(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed) { es->type=IGRAPH_ES_PATH; es->data.path.mode=directed; es->data.path.ptr=igraph_Calloc(1, igraph_vector_t); if (es->data.path.ptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) es->data.path.ptr); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*) es->data.path.ptr, v)); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_es_path_small(igraph_es_t *es, igraph_bool_t directed, ...) { va_list ap; long int i, n=0; es->type=IGRAPH_ES_PATH; es->data.path.mode=directed; es->data.path.ptr=igraph_Calloc(1, igraph_vector_t); if (es->data.path.ptr==0) { IGRAPH_ERROR("Cannot create edge selector", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)es->data.path.ptr); va_start(ap, directed); while (1) { int num = va_arg(ap, int); if (num == -1) { break; } n++; } va_end(ap); IGRAPH_VECTOR_INIT_FINALLY( (igraph_vector_t*) es->data.path.ptr, n); va_start(ap, directed); for (i=0; idata.path.ptr)[i]=(igraph_real_t) va_arg(ap, int); } va_end(ap); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_es_destroy * \brief Destroys an edge selector object. * * * Call this function on an edge selector when it is not needed any * more. Do \em not call this function on edge selectors created by * immediate constructors, those don't need to be destroyed. * * \param es Pointer to an edge selector object. * * Time complexity: operating system dependent, usually O(1). */ void igraph_es_destroy(igraph_es_t *es) { switch (es->type) { case IGRAPH_ES_ALL: case IGRAPH_ES_ALLFROM: case IGRAPH_ES_ALLTO: case IGRAPH_ES_INCIDENT: case IGRAPH_ES_NONE: case IGRAPH_ES_1: case IGRAPH_ES_VECTORPTR: case IGRAPH_ES_SEQ: break; case IGRAPH_ES_VECTOR: igraph_vector_destroy((igraph_vector_t*)es->data.vecptr); igraph_Free(es->data.vecptr); break; case IGRAPH_ES_PAIRS: case IGRAPH_ES_PATH: case IGRAPH_ES_MULTIPAIRS: igraph_vector_destroy((igraph_vector_t*)es->data.path.ptr); igraph_Free(es->data.path.ptr); break; default: break; } } /** * \function igraph_es_is_all * \brief Check whether an edge selector includes all edges. * * \param es Pointer to an edge selector object. * \return TRUE (1) if es was created with \ref * igraph_es_all() or \ref igraph_ess_all(), and FALSE (0) otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_es_is_all(const igraph_es_t *es) { return es->type == IGRAPH_ES_ALL; } /** * \function igraph_es_copy * \brief Creates a copy of an edge selector. * \param src The selector being copied. * \param dest An uninitialized selector that will contain the copy. * \sa \ref igraph_es_destroy() */ int igraph_es_copy(igraph_es_t* dest, const igraph_es_t* src) { memcpy(dest, src, sizeof(igraph_es_t)); switch (dest->type) { case IGRAPH_ES_VECTOR: dest->data.vecptr = igraph_Calloc(1,igraph_vector_t); if (!dest->data.vecptr) IGRAPH_ERROR("Cannot copy edge selector", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*)dest->data.vecptr, (igraph_vector_t*)src->data.vecptr)); break; case IGRAPH_ES_PATH: case IGRAPH_ES_PAIRS: case IGRAPH_ES_MULTIPAIRS: dest->data.path.ptr = igraph_Calloc(1,igraph_vector_t); if (!dest->data.path.ptr) IGRAPH_ERROR("Cannot copy edge selector", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_copy((igraph_vector_t*)dest->data.path.ptr, (igraph_vector_t*)src->data.path.ptr)); break; } return 0; } int igraph_es_as_vector(const igraph_t *graph, igraph_es_t es, igraph_vector_t *v) { igraph_eit_t eit; IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_CHECK(igraph_eit_as_vector(&eit, v)); igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_es_type * \brief Returns the type of the edge selector. */ int igraph_es_type(const igraph_es_t *es) { return es->type; } int igraph_i_es_pairs_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result); int igraph_i_es_path_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result); int igraph_i_es_multipairs_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result); /** * \function igraph_es_size * \brief Returns the size of the edge selector. * * The size of the edge selector is the number of edges it will * yield when it is iterated over. * * \param graph The graph over which we will iterate. * \param result The result will be returned here. */ int igraph_es_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result) { igraph_vector_t v; switch (es->type) { case IGRAPH_ES_ALL: *result = igraph_ecount(graph); return 0; case IGRAPH_ES_ALLFROM: *result = igraph_ecount(graph); return 0; case IGRAPH_ES_ALLTO: *result = igraph_ecount(graph); return 0; case IGRAPH_ES_INCIDENT: IGRAPH_VECTOR_INIT_FINALLY(&v, 0); IGRAPH_CHECK(igraph_incident(graph, &v, es->data.incident.vid, es->data.incident.mode)); *result = (igraph_integer_t) igraph_vector_size(&v); igraph_vector_destroy(&v); IGRAPH_FINALLY_CLEAN(1); return 0; case IGRAPH_ES_NONE: *result = 0; return 0; case IGRAPH_ES_1: if (es->data.eid < igraph_ecount(graph) && es->data.eid >= 0) *result = 1; else *result = 0; return 0; case IGRAPH_ES_VECTOR: case IGRAPH_ES_VECTORPTR: *result = (igraph_integer_t) igraph_vector_size((igraph_vector_t*)es->data.vecptr); return 0; case IGRAPH_ES_SEQ: *result = es->data.seq.to - es->data.seq.from; return 0; case IGRAPH_ES_PAIRS: IGRAPH_CHECK(igraph_i_es_pairs_size(graph, es, result)); return 0; case IGRAPH_ES_PATH: IGRAPH_CHECK(igraph_i_es_path_size(graph, es, result)); return 0; case IGRAPH_ES_MULTIPAIRS: IGRAPH_CHECK(igraph_i_es_multipairs_size(graph, es, result)); return 0; default: IGRAPH_ERROR("Cannot calculate selector length, invalid selector type", IGRAPH_EINVAL); } return 0; } int igraph_i_es_pairs_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result) { long int n=igraph_vector_size(es->data.path.ptr); long int no_of_nodes=igraph_vcount(graph); long int i; if (n % 2 != 0) { IGRAPH_ERROR("Cannot calculate edge selector length from odd number of vertices", IGRAPH_EINVAL); } if (!igraph_vector_isininterval(es->data.path.ptr, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot calculate edge selector length", IGRAPH_EINVVID); } *result = (igraph_integer_t) (n/2); /* Check for the existence of all edges */ for (i=0; i<*result; i++) { long int from=(long int) VECTOR(*es->data.path.ptr)[2*i]; long int to=(long int) VECTOR(*es->data.path.ptr)[2*i+1]; igraph_integer_t eid; IGRAPH_CHECK(igraph_get_eid(graph, &eid, (igraph_integer_t) from, (igraph_integer_t) to, es->data.path.mode, /*error=*/ 1)); } return 0; } int igraph_i_es_path_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result) { long int n=igraph_vector_size(es->data.path.ptr); long int no_of_nodes=igraph_vcount(graph); long int i; if (!igraph_vector_isininterval(es->data.path.ptr, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot calculate selector length", IGRAPH_EINVVID); } if (n<=1) *result=0; else *result=(igraph_integer_t) (n-1); for (i=0; i<*result; i++) { long int from=(long int) VECTOR(*es->data.path.ptr)[i]; long int to=(long int) VECTOR(*es->data.path.ptr)[i+1]; igraph_integer_t eid; IGRAPH_CHECK(igraph_get_eid(graph, &eid, (igraph_integer_t) from, (igraph_integer_t) to, es->data.path.mode, /*error=*/ 1)); } return 0; } int igraph_i_es_multipairs_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result) { IGRAPH_UNUSED(graph); IGRAPH_UNUSED(es); IGRAPH_UNUSED(result); IGRAPH_ERROR("Cannot calculate edge selector length", IGRAPH_UNIMPLEMENTED); } /**************************************************/ int igraph_i_eit_create_allfromto(const igraph_t *graph, igraph_eit_t *eit, igraph_neimode_t mode); int igraph_i_eit_pairs(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit); int igraph_i_eit_multipairs(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit); int igraph_i_eit_path(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit); int igraph_i_eit_create_allfromto(const igraph_t *graph, igraph_eit_t *eit, igraph_neimode_t mode) { igraph_vector_t *vec; long int no_of_nodes=igraph_vcount(graph); long int i; vec=igraph_Calloc(1, igraph_vector_t); if (vec==0) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vec); IGRAPH_VECTOR_INIT_FINALLY(vec, 0); IGRAPH_CHECK(igraph_vector_reserve(vec, igraph_ecount(graph))); if (igraph_is_directed(graph)) { igraph_vector_t adj; IGRAPH_VECTOR_INIT_FINALLY(&adj, 0); for (i=0; itype=IGRAPH_EIT_VECTOR; eit->pos=0; eit->start=0; eit->vec=vec; eit->end=igraph_vector_size(eit->vec); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_eit_pairs(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit) { long int n=igraph_vector_size(es.data.path.ptr); long int no_of_nodes=igraph_vcount(graph); long int i; if (n % 2 != 0) { IGRAPH_ERROR("Cannot create edge iterator from odd number of vertices", IGRAPH_EINVAL); } if (!igraph_vector_isininterval(es.data.path.ptr, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_EINVVID); } eit->type=IGRAPH_EIT_VECTOR; eit->pos=0; eit->start=0; eit->end=n/2; eit->vec=igraph_Calloc(1, igraph_vector_t); if (eit->vec==0) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)eit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t*)eit->vec, n/2); for (i=0; ivec); i++) { long int from=(long int) VECTOR(*es.data.path.ptr)[2*i]; long int to=(long int) VECTOR(*es.data.path.ptr)[2*i+1]; igraph_integer_t eid; IGRAPH_CHECK(igraph_get_eid(graph, &eid, (igraph_integer_t) from, (igraph_integer_t) to, es.data.path.mode, /*error=*/ 1)); VECTOR(*eit->vec)[i]=eid; } IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_eit_multipairs(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit) { long int n=igraph_vector_size(es.data.path.ptr); long int no_of_nodes=igraph_vcount(graph); if (n % 2 != 0) { IGRAPH_ERROR("Cannot create edge iterator from odd number of vertices", IGRAPH_EINVAL); } if (!igraph_vector_isininterval(es.data.path.ptr, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_EINVVID); } eit->type=IGRAPH_EIT_VECTOR; eit->pos=0; eit->start=0; eit->end=n/2; eit->vec=igraph_Calloc(1, igraph_vector_t); if (eit->vec==0) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)eit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t*)eit->vec, n/2); IGRAPH_CHECK(igraph_get_eids_multi(graph, (igraph_vector_t *) eit->vec, /*pairs=*/ es.data.path.ptr, /*path=*/ 0, es.data.path.mode, /*error=*/ 1)); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_eit_path(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit) { long int n=igraph_vector_size(es.data.path.ptr); long int no_of_nodes=igraph_vcount(graph); long int i, len; if (!igraph_vector_isininterval(es.data.path.ptr, 0, no_of_nodes-1)) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_EINVVID); } if (n<=1) { len=0; } else { len=n-1; } eit->type=IGRAPH_EIT_VECTOR; eit->pos=0; eit->start=0; eit->end=len; eit->vec=igraph_Calloc(1, igraph_vector_t); if (eit->vec==0) { IGRAPH_ERROR("Cannot create edge iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*)eit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t *)eit->vec, len); for (i=0; ivec)[i]=eid; } IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_eit_create * \brief Creates an edge iterator from an edge selector. * * * This function creates an edge iterator based on an edge selector * and a graph. * * * The same edge selector can be used to create many edge iterators, * also for different graphs. * * \param graph An \type igraph_t object for which the edge selector * will be instantiated. * \param es The edge selector to instantiate. * \param eit Pointer to an uninitialized edge iterator. * \return Error code. * \sa \ref igraph_eit_destroy() * * Time complexity: depends on the type of the edge selector. For edge * selectors created by \ref igraph_es_all(), \ref igraph_es_none(), * \ref igraph_es_1(), igraph_es_vector(), igraph_es_seq() it is * O(1). For \ref igraph_es_incident() it is O(d) where d is the number of * incident edges of the vertex. */ int igraph_eit_create(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit) { switch (es.type) { case IGRAPH_ES_ALL: eit->type=IGRAPH_EIT_SEQ; eit->pos=0; eit->start=0; eit->end=igraph_ecount(graph); break; case IGRAPH_ES_ALLFROM: IGRAPH_CHECK(igraph_i_eit_create_allfromto(graph, eit, IGRAPH_OUT)); break; case IGRAPH_ES_ALLTO: IGRAPH_CHECK(igraph_i_eit_create_allfromto(graph, eit, IGRAPH_IN)); break; case IGRAPH_ES_INCIDENT: eit->type=IGRAPH_EIT_VECTOR; eit->pos=0; eit->start=0; eit->vec=igraph_Calloc(1, igraph_vector_t); if (eit->vec == 0) { IGRAPH_ERROR("Cannot create iterator", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (igraph_vector_t*) eit->vec); IGRAPH_VECTOR_INIT_FINALLY((igraph_vector_t*)eit->vec, 0); IGRAPH_CHECK(igraph_incident(graph, (igraph_vector_t*)eit->vec, es.data.incident.vid, es.data.incident.mode)); eit->end=igraph_vector_size(eit->vec); IGRAPH_FINALLY_CLEAN(2); break; case IGRAPH_ES_NONE: eit->type=IGRAPH_EIT_SEQ; eit->pos=0; eit->start=0; eit->end=0; break; case IGRAPH_ES_1: eit->type=IGRAPH_EIT_SEQ; eit->pos=es.data.eid; eit->start=es.data.eid; eit->end=es.data.eid+1; if (eit->pos >= igraph_ecount(graph)) { IGRAPH_ERROR("Cannot create iterator, invalid edge id", IGRAPH_EINVVID); } break; case IGRAPH_ES_VECTOR: case IGRAPH_ES_VECTORPTR: eit->type=IGRAPH_EIT_VECTORPTR; eit->pos=0; eit->start=0; eit->vec=es.data.vecptr; eit->end=igraph_vector_size(eit->vec); if (!igraph_vector_isininterval(eit->vec, 0, igraph_ecount(graph)-1)) { IGRAPH_ERROR("Cannot create iterator, invalid edge id",IGRAPH_EINVVID); } break; case IGRAPH_ES_SEQ: eit->type=IGRAPH_EIT_SEQ; eit->pos=es.data.seq.from; eit->start=es.data.seq.from; eit->end=es.data.seq.to; break; case IGRAPH_ES_PAIRS: IGRAPH_CHECK(igraph_i_eit_pairs(graph, es, eit)); break; case IGRAPH_ES_MULTIPAIRS: IGRAPH_CHECK(igraph_i_eit_multipairs(graph, es, eit)); break; case IGRAPH_ES_PATH: IGRAPH_CHECK(igraph_i_eit_path(graph, es, eit)); break; default: IGRAPH_ERROR("Cannot create iterator, invalid selector", IGRAPH_EINVAL); break; } return 0; } /** * \function igraph_eit_destroy * \brief Destroys an edge iterator. * * \param eit Pointer to an edge iterator to destroy. * \sa \ref igraph_eit_create() * * Time complexity: operating system dependent, usually O(1). */ void igraph_eit_destroy(const igraph_eit_t *eit) { switch (eit->type) { case IGRAPH_EIT_SEQ: case IGRAPH_EIT_VECTORPTR: break; case IGRAPH_EIT_VECTOR: igraph_vector_destroy((igraph_vector_t*)eit->vec); igraph_free((igraph_vector_t*)eit->vec); break; default: /* IGRAPH_ERROR("Cannot destroy iterator, unknown type", IGRAPH_EINVAL); */ break; } } int igraph_eit_as_vector(const igraph_eit_t *eit, igraph_vector_t *v) { long int i; IGRAPH_CHECK(igraph_vector_resize(v, IGRAPH_EIT_SIZE(*eit))); switch (eit->type) { case IGRAPH_EIT_SEQ: for (i=0; istart+i; } break; case IGRAPH_EIT_VECTOR: case IGRAPH_EIT_VECTORPTR: for (i=0; ivec)[i]; } break; default: IGRAPH_ERROR("Cannot convert to vector, unknown iterator type", IGRAPH_EINVAL); break; } return 0; } igraph/src/glpk_support.c0000644000175100001440000000451113431000472015221 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #ifdef HAVE_GLPK #include "igraph_types.h" #include "igraph_error.h" #include "igraph_interrupt_internal.h" #include #include #include void igraph_i_glpk_interruption_hook(glp_tree *tree, void *info) { IGRAPH_UNUSED(tree); IGRAPH_UNUSED(info); IGRAPH_ALLOW_INTERRUPTION_NORETURN(); } int igraph_i_glpk_check(int retval, const char* message) { char* code = "none"; char message_and_code[4096]; if (retval == IGRAPH_SUCCESS) return IGRAPH_SUCCESS; /* handle errors */ #define HANDLE_CODE(c) case c: code = #c; retval = IGRAPH_##c; break; #define HANDLE_CODE2(c) case c: code = #c; retval = IGRAPH_FAILURE; break; switch (retval) { HANDLE_CODE(GLP_EBOUND); HANDLE_CODE(GLP_EROOT); HANDLE_CODE(GLP_ENOPFS); HANDLE_CODE(GLP_ENODFS); HANDLE_CODE(GLP_EFAIL); HANDLE_CODE(GLP_EMIPGAP); HANDLE_CODE(GLP_ETMLIM); HANDLE_CODE(GLP_ESTOP); HANDLE_CODE2(GLP_EBADB); HANDLE_CODE2(GLP_ESING); HANDLE_CODE2(GLP_ECOND); HANDLE_CODE2(GLP_EOBJLL); HANDLE_CODE2(GLP_EOBJUL); HANDLE_CODE2(GLP_EITLIM); default: IGRAPH_ERROR("unknown GLPK error", IGRAPH_FAILURE); } #undef HANDLE_CODE sprintf(message_and_code, "%s (%s)", message, code); IGRAPH_ERROR(message_and_code, retval); } #endif #ifdef USING_R int igraph_glpk_dummy() { return 'b' + 'a' + 's' + 's' + 'z' + 'a' + 't' + 'o' + 'k' + 'm' + 'e' + 'g'; } #endif igraph/src/igraph_gml_tree.h0000644000175100001440000000577013431000472015635 0ustar hornikusers/* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REST_GML_TREE_H #define REST_GML_TREE_H #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" typedef enum { IGRAPH_I_GML_TREE_TREE=0, IGRAPH_I_GML_TREE_INTEGER, IGRAPH_I_GML_TREE_REAL, IGRAPH_I_GML_TREE_STRING, IGRAPH_I_GML_TREE_DELETED } igraph_i_gml_tree_type_t; typedef struct igraph_gml_tree_t { igraph_vector_ptr_t names; igraph_vector_char_t types; igraph_vector_ptr_t children; } igraph_gml_tree_t; int igraph_gml_tree_init_integer(igraph_gml_tree_t *t, const char *name, int namelen, igraph_integer_t value); int igraph_gml_tree_init_real(igraph_gml_tree_t *t, const char *name, int namelen, igraph_real_t value); int igraph_gml_tree_init_string(igraph_gml_tree_t *t, const char *name, int namelen, const char *value, int valuelen); int igraph_gml_tree_init_tree(igraph_gml_tree_t *t, const char *name, int namelen, igraph_gml_tree_t *value); void igraph_gml_tree_destroy(igraph_gml_tree_t *t); void igraph_gml_tree_delete(igraph_gml_tree_t *t, long int pos); int igraph_gml_tree_mergedest(igraph_gml_tree_t *t1, igraph_gml_tree_t *t2); long int igraph_gml_tree_length(const igraph_gml_tree_t *t); long int igraph_gml_tree_find(const igraph_gml_tree_t *t, const char *name, long int from); long int igraph_gml_tree_findback(const igraph_gml_tree_t *t, const char *name, long int from); int igraph_gml_tree_type(const igraph_gml_tree_t *t, long int pos); const char *igraph_gml_tree_name(const igraph_gml_tree_t *t, long int pos); igraph_integer_t igraph_gml_tree_get_integer(const igraph_gml_tree_t *t, long int pos); igraph_real_t igraph_gml_tree_get_real(const igraph_gml_tree_t *t, long int pos); const char *igraph_gml_tree_get_string(const igraph_gml_tree_t *t, long int pos); igraph_gml_tree_t *igraph_gml_tree_get_tree(const igraph_gml_tree_t *t, long int pos); #endif igraph/src/gengraph_random.cpp0000644000175100001440000001731413431000472016170 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define RNG_C #ifdef RCSID static const char rcsid[] = "$Id: random.cpp,v 1.15 2003/05/14 03:04:45 wilder Exp wilder $"; #endif //________________________________________________________________________ // See the header file random.h for a description of the contents of this // file as well as references and credits. #include #include "gengraph_random.h" using namespace std; using namespace KW_RNG; //________________________________________________________________________ // RNG::RNOR generates normal variates with rejection. // nfix() generates variates after rejection in RNOR. // Despite rejection, this method is much faster than Box-Muller. // double RNG::nfix(slong h, ulong i) // { // const double r = 3.442620f; // The starting of the right tail // static double x, y; // for(;;) { // x = h * wn[i]; // // If i == 0, handle the base strip // if (i==0){ // do { // x = -log(rand_open01()) * 0.2904764; // .2904764 is 1/r // y = -log(rand_open01()); // } while (y + y < x * x); // return ((h > 0) ? r + x : -r - x); // } // // If i > 0, handle the wedges of other strips // if (fn[i] + rand_open01() * (fn[i - 1] - fn[i]) < exp(-.5 * x * x) ) // return x; // // start all over // h = rand_int32(); // i = h & 127; // if ((ulong) abs((sint) h) < kn[i]) // return (h * wn[i]); // } // } // RNG::nfix // // __________________________________________________________________________ // // RNG::RNOR generates exponential variates with rejection. // // efix() generates variates after rejection in REXP. // double RNG::efix(ulong j, ulong i) // { // double x; // for (;;) // { // if (i == 0) // return (7.69711 - log(rand_open01())); // x = j * we[i]; // if (fe[i] + rand_open01() * (fe[i - 1] - fe[i]) < exp(-x)) // return (x); // j = rand_int32(); // i = (j & 255); // if (j < ke[i]) // return (j * we[i]); // } // } // RNG::efix // // __________________________________________________________________________ // // This procedure creates the tables used by RNOR and REXP // void RNG::zigset() // { // const double m1 = 2147483648.0; // 2^31 // const double m2 = 4294967296.0; // 2^32 // const double vn = 9.91256303526217e-3; // const double ve = 3.949659822581572e-3; // double dn = 3.442619855899, tn = dn; // double de = 7.697117470131487, te = de; // int i; // // Set up tables for RNOR // double q = vn / exp(-.5 * dn * dn); // kn[0] = (ulong) ((dn / q) * m1); // kn[1] = 0; // wn[0] = q / m1; // wn[127] = dn / m1; // fn[0]=1.; // fn[127] = exp(-.5 * dn * dn); // for(i = 126; i >= 1; i--) // { // dn = sqrt(-2 * log(vn / dn + exp(-.5 * dn * dn))); // kn[i + 1] = (ulong) ((dn / tn) * m1); // tn = dn; // fn[i] = exp(-.5 * dn * dn); // wn[i] = dn / m1; // } // // Set up tables for REXP // q = ve / exp(-de); // ke[0] = (ulong) ((de / q) * m2); // ke[1] = 0; // we[0] = q / m2; // we[255] = de / m2; // fe[0] = 1.; // fe[255] = exp(-de); // for (i = 254; i >= 1; i--) // { // de = -log(ve / de + exp(-de)); // ke[i+1] = (ulong) ((de / te) * m2); // te = de; // fe[i] = exp(-de); // we[i] = de / m2; // } // } // RNG::zigset // // __________________________________________________________________________ // // Generate a gamma variate with parameters 'shape' and 'scale' // double RNG::gamma(double shape, double scale) // { // if (shape < 1) // return gamma(shape + 1, scale) * pow(rand_open01(), 1.0 / shape); // const double d = shape - 1.0 / 3.0; // const double c = 1.0 / sqrt(9.0 * d); // double x, v, u; // for (;;) { // do { // x = RNOR(); // v = 1.0 + c * x; // } while (v <= 0.0); // v = v * v * v; // u = rand_open01(); // if (u < 1.0 - 0.0331 * x * x * x * x) // return (d * v / scale); // if (log(u) < 0.5 * x * x + d * (1.0 - v + log(v))) // return (d * v / scale); // } // } // RNG::gamma // // __________________________________________________________________________ // // gammalog returns the logarithm of the gamma function. From Numerical // // Recipes. // double gammalog(double xx) // { // static double cof[6]={ // 76.18009172947146, -86.50532032941677, 24.01409824083091, // -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5}; // double x = xx; // double y = xx; // double tmp = x + 5.5; // tmp -= (x + 0.5) * log(tmp); // double ser=1.000000000190015; // for (int j=0; j<=5; j++) // ser += cof[j] / ++y; // return -tmp + log(2.5066282746310005 * ser / x); // } // // __________________________________________________________________________ // // Generate a Poisson variate // // This is essentially the algorithm from Numerical Recipes // double RNG::poisson(double lambda) // { // static double sq, alxm, g, oldm = -1.0; // double em, t, y; // if (lambda < 12.0) { // if (lambda != oldm) { // oldm = lambda; // g = exp(-lambda); // } // em = -1; // t = 1.0; // do { // ++em; // t *= rand_open01(); // } while (t > g); // } else { // if (lambda != oldm) { // oldm = lambda; // sq = sqrt(2.0 * lambda); // alxm = log(lambda); // g = lambda * alxm - gammalog(lambda + 1.0); // } // do { // do { // y = tan(PI * rand_open01()); // em = sq * y + lambda; // } while (em < 0.0); // em = floor(em); // t = 0.9 * (1.0 + y * y) * exp(em * alxm - gammalog(em + 1.0)-g); // } while (rand_open01() > t); // } // return em; // } // RNG::poisson // // __________________________________________________________________________ // // Generate a binomial variate // // This is essentially the algorithm from Numerical Recipes // int RNG::binomial(double pp, int n) // { // if(n==0) return 0; // if(pp==0.0) return 0; // if(pp==1.0) return n; // double p = (pp<0.5 ? pp : 1.0-pp); // double am = n*p; // int bnl = 0; // if(n<25) { // for(int j=n; j--; ) if(rand_closed01()= en + 1.0); // em = floor(em); // t = 1.2 * sq * (1 + y * y) * exp(oldg - gammalog(em + 1.0) - // gammalog(en - em + 1.0) + em * log(p) + (en - em) * log(pc)); // } while (rand_closed01() > t); // bnl = int(em); // } // if (p!=pp) bnl=n-bnl; // return bnl; // } // RNG::binomial // __________________________________________________________________________ // rng.C igraph/src/dseigt.f0000644000175100001440000001227113431000472013754 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdseigt c c\Description: c Compute the eigenvalues of the current symmetric tridiagonal matrix c and the corresponding error bounds given the current residual norm. c c\Usage: c call igraphdseigt c ( RNORM, N, H, LDH, EIG, BOUNDS, WORKL, IERR ) c c\Arguments c RNORM Double precision scalar. (INPUT) c RNORM contains the residual norm corresponding to the current c symmetric tridiagonal matrix H. c c N Integer. (INPUT) c Size of the symmetric tridiagonal matrix H. c c H Double precision N by 2 array. (INPUT) c H contains the symmetric tridiagonal matrix with the c subdiagonal in the first column starting at H(2,1) and the c main diagonal in igraphsecond column. c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c EIG Double precision array of length N. (OUTPUT) c On output, EIG contains the N eigenvalues of H possibly c unsorted. The BOUNDS arrays are returned in the c same sorted order as EIG. c c BOUNDS Double precision array of length N. (OUTPUT) c On output, BOUNDS contains the error estimates corresponding c to the eigenvalues EIG. This is equal to RNORM times the c last components of the eigenvectors corresponding to the c eigenvalues in EIG. c c WORKL Double precision work array of length 3*N. (WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. c c IERR Integer. (OUTPUT) c Error exit flag from igraphdstqrb. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c igraphdstqrb ARPACK routine that computes the eigenvalues and the c last components of the eigenvectors of a symmetric c and tridiagonal matrix. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dcopy Level 1 BLAS that copies one vector to another. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.4' c c\SCCS Information: @(#) c FILE: seigt.F SID: 2.4 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c None c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdseigt & ( rnorm, n, h, ldh, eig, bounds, workl, ierr ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c integer ierr, ldh, n Double precision & rnorm c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & eig(n), bounds(n), h(ldh,2), workl(3*n) c c %------------% c | Parameters | c %------------% c Double precision & zero parameter (zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c integer i, k, msglvl c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, igraphdstqrb, igraphdvout, igraphsecond c c %-----------------------% c | Executable Statements | c %-----------------------% c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = mseigt c if (msglvl .gt. 0) then call igraphdvout (logfil, n, h(1,2), ndigit, & '_seigt: main diagonal of matrix H') if (n .gt. 1) then call igraphdvout (logfil, n-1, h(2,1), ndigit, & '_seigt: sub diagonal of matrix H') end if end if c call dcopy (n, h(1,2), 1, eig, 1) call dcopy (n-1, h(2,1), 1, workl, 1) call igraphdstqrb (n, eig, workl, bounds, workl(n+1), ierr) if (ierr .ne. 0) go to 9000 if (msglvl .gt. 1) then call igraphdvout (logfil, n, bounds, ndigit, & '_seigt: last row of the eigenvector matrix for H') end if c c %-----------------------------------------------% c | Finally determine the error bounds associated | c | with the n Ritz values of H. | c %-----------------------------------------------% c do 30 k = 1, n bounds(k) = rnorm*abs(bounds(k)) 30 continue c call igraphsecond (t1) tseigt = tseigt + (t1 - t0) c 9000 continue return c c %---------------% c | End of igraphdseigt | c %---------------% c end igraph/src/cohesive_blocks.c0000644000175100001440000004435513431000472015644 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_cohesive_blocks.h" #include "igraph_interface.h" #include "igraph_memory.h" #include "igraph_flow.h" #include "igraph_separators.h" #include "igraph_structural.h" #include "igraph_components.h" #include "igraph_dqueue.h" #include "igraph_constructors.h" #include "igraph_interrupt_internal.h" #include "igraph_statusbar.h" void igraph_i_cohesive_blocks_free(igraph_vector_ptr_t *ptr) { long int i, n=igraph_vector_ptr_size(ptr); for (i=0; ik. Thus a hiearchy of vertex subsets * is found, whith the entire graph G at its root. See the following * reference for details: J. Moody and D. R. White. Structural * cohesion and embeddedness: A hierarchical concept of social * groups. American Sociological Review, 68(1):103--127, Feb 2003. * * This function implements cohesive blocking and * calculates the complete cohesive block hierarchy of a graph. * * \param graph The input graph. It must be undirected and simple. See * \ref igraph_is_simple(). * \param blocks If not a null pointer, then it must be an initialized * vector of pointers and the cohesive blocks are stored here. * Each block is encoded with a numeric vector, that contains the * vertex ids of the block. * \param cohesion If not a null pointer, then it must be an initialized * vector and the cohesion of the blocks is stored here, in the same * order as the blocks in the \p blocks pointer vector. * \param parent If not a null pointer, then it must be an initialized * vector and the block hierarchy is stored here. For each block, the * id (i.e. the position in the \p blocks pointer vector) of its * parent block is stored. For the top block in the hierarchy, * -1 is stored. * \param block_tree If not a null pointer, then it must be a pointer * to an uninitialized graph, and the block hierarchy is stored * here as an igraph graph. The vertex ids correspond to the order * of the blocks in the \p blocks vector. * \return Error code. * * Time complexity: TODO. * * \example examples/simple/cohesive_blocks.c */ int igraph_cohesive_blocks(const igraph_t *graph, igraph_vector_ptr_t *blocks, igraph_vector_t *cohesion, igraph_vector_t *parent, igraph_t *block_tree) { /* Some implementation comments. Everything is relatively straightforward, except, that we need to follow the vertex ids of the various subgraphs, without having to store two-way mappings at each level. The subgraphs can overlap, this complicates things a bit. The 'Q' vector is used as a double ended queue and it contains the subgraphs to work on in the future. Some other vectors are associated with it. 'Qparent' gives the parent graph of a graph in Q. Qmapping gives the mapping of the vertices from the graph to the parent graph. Qcohesion is the vertex connectivity of the graph. Qptr is an integer and points to the next graph to work on. */ igraph_vector_ptr_t Q; igraph_vector_ptr_t Qmapping; igraph_vector_long_t Qparent; igraph_vector_long_t Qcohesion; igraph_vector_bool_t Qcheck; long int Qptr=0; igraph_integer_t conn; igraph_bool_t is_simple; igraph_t *graph_copy; igraph_vector_ptr_t separators; igraph_vector_t compvertices; igraph_vector_long_t components; igraph_vector_bool_t marked; igraph_vector_long_t compid; igraph_dqueue_t bfsQ; igraph_vector_t neis; if (igraph_is_directed(graph)) { IGRAPH_ERROR("Cohesive blocking only works on undirected graphs", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_is_simple(graph, &is_simple)); if (!is_simple) { IGRAPH_ERROR("Cohesive blocking only works on simple graphs", IGRAPH_EINVAL); } IGRAPH_STATUS("Starting cohesive block calculation.\n", 0); if (blocks) { igraph_vector_ptr_clear(blocks); } if (cohesion) { igraph_vector_clear(cohesion); } if (parent) { igraph_vector_clear(parent); } IGRAPH_CHECK(igraph_vector_ptr_init(&Q, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &Q); IGRAPH_FINALLY(igraph_i_cohesive_blocks_free, &Q); IGRAPH_CHECK(igraph_vector_ptr_init(&Qmapping, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &Qmapping); IGRAPH_FINALLY(igraph_i_cohesive_blocks_free2, &Qmapping); IGRAPH_CHECK(igraph_vector_long_init(&Qparent, 1)); IGRAPH_FINALLY(igraph_vector_long_destroy, &Qparent); IGRAPH_CHECK(igraph_vector_long_init(&Qcohesion, 1)); IGRAPH_FINALLY(igraph_vector_long_destroy, &Qcohesion); IGRAPH_CHECK(igraph_vector_bool_init(&Qcheck, 1)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &Qcheck); IGRAPH_CHECK(igraph_vector_ptr_init(&separators, 0)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &separators); IGRAPH_VECTOR_INIT_FINALLY(&compvertices, 0); IGRAPH_CHECK(igraph_vector_bool_init(&marked, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &marked); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_dqueue_init(&bfsQ, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &bfsQ); IGRAPH_CHECK(igraph_vector_long_init(&compid, 0)); IGRAPH_FINALLY(igraph_vector_long_destroy, &compid); IGRAPH_CHECK(igraph_vector_long_init(&components, 0)); IGRAPH_FINALLY(igraph_vector_long_destroy, &components); /* Put the input graph in the queue */ graph_copy=igraph_Calloc(1, igraph_t); if (!graph_copy) { IGRAPH_ERROR("Cannot do cohesive blocking", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_copy(graph_copy, graph)); VECTOR(Q)[0] = graph_copy; VECTOR(Qmapping)[0] = 0; /* Identity mapping */ VECTOR(Qparent)[0] = -1; /* Has no parent */ IGRAPH_CHECK(igraph_vertex_connectivity(graph, &conn, /*checks=*/ 1)); VECTOR(Qcohesion)[0] = conn; VECTOR(Qcheck)[0] = 0; /* Then work until the queue is empty */ while (Qptr < igraph_vector_ptr_size(&Q)) { igraph_t *mygraph=VECTOR(Q)[Qptr]; igraph_bool_t mycheck=VECTOR(Qcheck)[Qptr]; long int mynodes=igraph_vcount(mygraph); long int i, nsep; long int no, kept=0; long int cptr=0; long int nsepv=0; igraph_bool_t addedsep=0; IGRAPH_STATUSF(("Candidate %li: %li vertices,", 0, Qptr, mynodes)); IGRAPH_ALLOW_INTERRUPTION(); /* Get the separators */ IGRAPH_CHECK(igraph_minimum_size_separators(mygraph, &separators)); IGRAPH_FINALLY(igraph_i_cohesive_blocks_free3, &separators); nsep=igraph_vector_ptr_size(&separators); IGRAPH_STATUSF((" %li separators,", 0, nsep)); /* Remove them from the graph, also mark them */ IGRAPH_CHECK(igraph_vector_bool_resize(&marked, mynodes)); igraph_vector_bool_null(&marked); for (i=0; i VECTOR(Qcohesion)[Qptr]) { igraph_integer_t newconn; kept++; IGRAPH_CHECK(igraph_vector_ptr_push_back(&Q, newgraph)); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_vector_ptr_push_back(&Qmapping, newmapping)); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_vertex_connectivity(newgraph, &newconn, /*checks=*/ 1)); IGRAPH_CHECK(igraph_vector_long_push_back(&Qcohesion, newconn)); IGRAPH_CHECK(igraph_vector_long_push_back(&Qparent, Qptr)); IGRAPH_CHECK(igraph_vector_bool_push_back(&Qcheck, mycheck || addedsep)); } else { igraph_destroy(newgraph); igraph_free(newgraph); igraph_vector_destroy(newmapping); igraph_free(newmapping); IGRAPH_FINALLY_CLEAN(4); } } IGRAPH_STATUSF((" keeping %li.\n", 0, kept)); igraph_destroy(mygraph); igraph_free(mygraph); VECTOR(Q)[Qptr] = 0; igraph_i_cohesive_blocks_free3(&separators); IGRAPH_FINALLY_CLEAN(1); Qptr++; } igraph_vector_long_destroy(&components); igraph_vector_long_destroy(&compid); igraph_dqueue_destroy(&bfsQ); igraph_vector_destroy(&neis); igraph_vector_bool_destroy(&marked); igraph_vector_destroy(&compvertices); igraph_vector_ptr_destroy(&separators); IGRAPH_FINALLY_CLEAN(7); if (blocks || cohesion || parent || block_tree) { igraph_integer_t noblocks=(igraph_integer_t) Qptr, badblocks=0; igraph_vector_bool_t removed; long int i, resptr=0; igraph_vector_long_t rewritemap; IGRAPH_CHECK(igraph_vector_bool_init(&removed, noblocks)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &removed); IGRAPH_CHECK(igraph_vector_long_init(&rewritemap, noblocks)); IGRAPH_FINALLY(igraph_vector_long_destroy, &rewritemap); for (i=1; i= VECTOR(Qcohesion)[i]) { VECTOR(removed)[i]=1; badblocks++; } } /* Rewrite the mappings */ for (i=1; i= ic) { badblocks++; VECTOR(removed)[i]=1; break; } } } noblocks -= badblocks; if (blocks) { IGRAPH_CHECK(igraph_vector_ptr_resize(blocks, noblocks)); } if (cohesion) { IGRAPH_CHECK(igraph_vector_resize(cohesion, noblocks)); } if (parent) { IGRAPH_CHECK(igraph_vector_resize(parent, noblocks)); } for (i=0; i=0 && VECTOR(removed)[p]) { p=VECTOR(Qparent)[p]; } if (p>=0) { p=VECTOR(rewritemap)[p]; } VECTOR(Qparent)[i]=p; if (parent) { VECTOR(*parent)[resptr]=p; } } if (blocks) { VECTOR(*blocks)[resptr]=VECTOR(Qmapping)[i]; VECTOR(Qmapping)[i]=0; } resptr++; } /* Plus the original graph */ if (blocks) { igraph_vector_t *orig=igraph_Calloc(1, igraph_vector_t); if (!orig) { IGRAPH_ERROR("Cannot do cohesive blocking", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, orig); IGRAPH_CHECK(igraph_vector_init_seq(orig, 0, igraph_vcount(graph)-1)); VECTOR(*blocks)[0]=orig; IGRAPH_FINALLY_CLEAN(1); } if (block_tree) { igraph_vector_t edges; long int eptr=0; IGRAPH_VECTOR_INIT_FINALLY(&edges, noblocks*2-2); for (i=1; i KEV eigenvalues of largest magnitude are retained. c 'SM' -> KEV eigenvalues of smallest magnitude are retained. c 'LA' -> KEV eigenvalues of largest value are retained. c 'SA' -> KEV eigenvalues of smallest value are retained. c 'BE' -> KEV eigenvalues, half from each end of the spectrum. c If KEV is odd, compute one more from the high end. c c KEV Integer. (INPUT) c KEV+NP is the size of the matrix H. c c NP Integer. (INPUT) c Number of implicit shifts to be computed. c c RITZ Double precision array of length KEV+NP. (INPUT/OUTPUT) c On INPUT, RITZ contains the eigenvalues of H. c On OUTPUT, RITZ are sorted so that the unwanted eigenvalues c are in the first NP locations and the wanted part is in c the last KEV locations. When exact shifts are selected, the c unwanted part corresponds to the shifts to be applied. c c BOUNDS Double precision array of length KEV+NP. (INPUT/OUTPUT) c Error bounds corresponding to the ordering in RITZ. c c SHIFTS Double precision array of length NP. (INPUT/OUTPUT) c On INPUT: contains the user specified shifts if ISHIFT = 0. c On OUTPUT: contains the shifts sorted into decreasing order c of magnitude with respect to the Ritz estimates contained in c BOUNDS. If ISHIFT = 0, SHIFTS is not modified on exit. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c igraphdsortr ARPACK utility sorting routine. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dcopy Level 1 BLAS that copies one vector to another. c dswap Level 1 BLAS that swaps the contents of two vectors. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/93: Version ' 2.1' c c\SCCS Information: @(#) c FILE: sgets.F SID: 2.4 DATE OF SID: 4/19/96 RELEASE: 2 c c\Remarks c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsgets ( ishift, which, kev, np, ritz, bounds, & shifts ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character*2 which integer ishift, kev, np c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & bounds(kev+np), ritz(kev+np), shifts(np) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c integer kevd2, msglvl c c %----------------------% c | External Subroutines | c %----------------------% c external dswap, dcopy, igraphdsortr, igraphsecond c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic max, min c c %-----------------------% c | Executable Statements | c %-----------------------% c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = msgets c if (which .eq. 'BE') then c c %-----------------------------------------------------% c | Both ends of the spectrum are requested. | c | Sort the eigenvalues into algebraically increasing | c | order first then swap high end of the spectrum next | c | to low end in appropriate locations. | c | NOTE: when np < floor(kev/2) be careful not to swap | c | overlapping locations. | c %-----------------------------------------------------% c call igraphdsortr ('LA', .true., kev+np, ritz, bounds) kevd2 = kev / 2 if ( kev .gt. 1 ) then call dswap ( min(kevd2,np), ritz, 1, & ritz( max(kevd2,np)+1 ), 1) call dswap ( min(kevd2,np), bounds, 1, & bounds( max(kevd2,np)+1 ), 1) end if c else c c %----------------------------------------------------% c | LM, SM, LA, SA case. | c | Sort the eigenvalues of H into the desired order | c | and apply the resulting order to BOUNDS. | c | The eigenvalues are sorted so that the wanted part | c | are always in the last KEV locations. | c %----------------------------------------------------% c call igraphdsortr (which, .true., kev+np, ritz, bounds) end if c if (ishift .eq. 1 .and. np .gt. 0) then c c %-------------------------------------------------------% c | Sort the unwanted Ritz values used as shifts so that | c | the ones with largest Ritz estimates are first. | c | This will tend to minimize the effects of the | c | forward instability of the iteration when the shifts | c | are applied in subroutine igraphdsapps. | c %-------------------------------------------------------% c call igraphdsortr ('SM', .true., np, bounds, ritz) call dcopy (np, ritz, 1, shifts, 1) end if c call igraphsecond (t1) tsgets = tsgets + (t1 - t0) c if (msglvl .gt. 0) then call igraphivout (logfil, 1, kev, ndigit, '_sgets: KEV is') call igraphivout (logfil, 1, np, ndigit, '_sgets: NP is') call igraphdvout (logfil, kev+np, ritz, ndigit, & '_sgets: Eigenvalues of current H matrix') call igraphdvout (logfil, kev+np, bounds, ndigit, & '_sgets: Associated Ritz estimates') end if c return c c %---------------% c | End of igraphdsgets | c %---------------% c end igraph/src/cores.c0000644000175100001440000001115013431000472013600 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_community.h" #include "igraph_memory.h" #include "igraph_interface.h" #include "igraph_iterators.h" #include "config.h" /** * \function igraph_coreness * \brief Finding the coreness of the vertices in a network. * * The k-core of a graph is a maximal subgraph in which each vertex * has at least degree k. (Degree here means the degree in the * subgraph of course.). The coreness of a vertex is the highest order * of a k-core containing the vertex. * * * This function implements the algorithm presented in Vladimir * Batagelj, Matjaz Zaversnik: An O(m) Algorithm for Cores * Decomposition of Networks. * \param graph The input graph. * \param cores Pointer to an initialized vector, the result of the * computation will be stored here. It will be resized as * needed. For each vertex it contains the highest order of a * core containing the vertex. * \param mode For directed graph it specifies whether to calculate * in-cores, out-cores or the undirected version. It is ignored * for undirected graphs. Possible values: \c IGRAPH_ALL * undirected version, \c IGRAPH_IN in-cores, \c IGRAPH_OUT * out-cores. * \return Error code. * * Time complexity: O(|E|), the number of edges. */ int igraph_coreness(const igraph_t *graph, igraph_vector_t *cores, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); long int *bin, *vert, *pos; long int maxdeg; long int i, j=0; igraph_vector_t neis; igraph_neimode_t omode; if (mode != IGRAPH_ALL && mode != IGRAPH_OUT && mode != IGRAPH_IN) { IGRAPH_ERROR("Invalid mode in k-cores", IGRAPH_EINVAL); } if (!igraph_is_directed(graph) || mode==IGRAPH_ALL) { mode=omode=IGRAPH_ALL; } else if (mode==IGRAPH_IN) { omode=IGRAPH_OUT; } else { omode=IGRAPH_IN; } vert=igraph_Calloc(no_of_nodes, long int); if (vert==0) { IGRAPH_ERROR("Cannot calculate k-cores", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vert); pos=igraph_Calloc(no_of_nodes, long int); if (pos==0) { IGRAPH_ERROR("Cannot calculate k-cores", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, pos); /* maximum degree + degree of vertices */ IGRAPH_CHECK(igraph_degree(graph, cores, igraph_vss_all(), mode, IGRAPH_LOOPS)); maxdeg = (long int) igraph_vector_max(cores); bin=igraph_Calloc(maxdeg+1, long int); if (bin==0) { IGRAPH_ERROR("Cannot calculate k-cores", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, bin); /* degree histogram */ for (i=0; i0; i--) { bin[i] = bin[i-1]; } bin[0]=0; /* this is the main algorithm */ IGRAPH_VECTOR_INIT_FINALLY(&neis, maxdeg); for (i=0; i VECTOR(*cores)[v]) { long int du=(long int) VECTOR(*cores)[u]; long int pu=pos[u]; long int pw=bin[du]; long int w=vert[pw]; if (u != w) { pos[u]=pw; pos[w]=pu; vert[pu]=w; vert[pw]=u; } bin[du] += 1; VECTOR(*cores)[u] -= 1; } } } igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(1); igraph_free(bin); igraph_free(pos); igraph_free(vert); IGRAPH_FINALLY_CLEAN(3); return 0; } igraph/src/hrg_graph.h0000644000175100001440000001344013431000472014437 0ustar hornikusers/* -*- mode: C++ -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // **************************************************************************************************** // *** COPYRIGHT NOTICE ******************************************************************************* // graph.h - graph data structure for hierarchical random graphs // Copyright (C) 2005-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // **************************************************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science AND Santa Fe Institute // Created : 8 November 2005 // Modified : 23 December 2007 (cleaned up for public consumption) // // **************************************************************************************************** // // Graph data structure for hierarchical random graphs. The basic structure is an adjacency list of // edges; however, many additional pieces of metadata are stored as well. Each node stores its // external name, its degree and (if assigned) its group index. // // **************************************************************************************************** #ifndef IGRAPH_HRG_GRAPH #define IGRAPH_HRG_GRAPH #include #include #include #include "hrg_rbtree.h" using namespace std; namespace fitHRG { // ******** Basic Structures ********************************************* #ifndef IGRAPH_HRG_EDGE #define IGRAPH_HRG_EDGE class edge { public: int x; // stored integer value (edge terminator) double* h; // (histogram) weights of edge existence double total_weight; // (histogram) total weight observed int obs_count; // number of observations in histogram edge* next; // pointer to next elementd edge(): x(-1), h(0), total_weight(0.0), obs_count(0), next(0) { } ~edge() { if (h != NULL) { delete [] h; } h = NULL; } }; #endif #ifndef IGRAPH_HRG_VERT #define IGRAPH_HRG_VERT class vert { public: string name; // (external) name of vertex int degree; // degree of this vertex vert(): name(""), degree(0) { } ~vert() { } }; #endif // ******** Graph Class with Edge Statistics ***************************** class graph { public: graph(const int, bool predict=false); ~graph(); // add (i,j) to graph bool addLink(const int, const int); // add weight to (i,j)'s histogram bool addAdjacencyObs(const int, const int, const double, const double); // add to obs_count and total_weight void addAdjacencyEnd(); // true if (i,j) is already in graph bool doesLinkExist(const int, const int); // returns degree of vertex i int getDegree(const int); // returns name of vertex i string getName(const int); // returns edge list of vertex i edge* getNeighborList(const int); // return ptr to histogram of edge (i,j) double* getAdjacencyHist(const int, const int); // return average value of adjacency A(i,j) double getAdjacencyAverage(const int, const int); // returns bin_resolution double getBinResolution(); // returns num_bins int getNumBins(); // returns m int numLinks(); // returns n int numNodes(); // returns total_weight double getTotalWeight(); // reset edge (i,j)'s histogram void resetAdjacencyHistogram(const int, const int); // reset all edge histograms void resetAllAdjacencies(); // clear all links from graph void resetLinks(); // allocate edge histograms void setAdjacencyHistograms(const int); // set name of vertex i bool setName(const int, const string); private: bool predict; // do we need prediction? vert* nodes; // list of nodes edge** nodeLink; // linked list of neighbors to vertex edge** nodeLinkTail; // pointers to tail of neighbor list double*** A; // stochastic adjacency matrix for this graph int obs_count; // number of observations in A double total_weight; // total weight added to A int n; // number of vertices int m; // number of directed edges int num_bins; // number of bins in edge histograms double bin_resolution; // width of histogram bin }; } // namespace fitHRG #endif igraph/src/drl_graph.h0000644000175100001440000001074513431000472014445 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // The graph class contains the methods necessary to draw the // graph. It calls on the density server class to obtain // position and density information #include "DensityGrid.h" #include "igraph_layout.h" namespace drl { // layout schedule information struct layout_schedule { int iterations; float temperature; float attraction; float damping_mult; time_t time_elapsed; }; class graph { public: // Methods void init_parms ( int rand_seed, float edge_cut, float real_parm ); void init_parms ( const igraph_layout_drl_options_t *options ); void read_parms ( char *parms_file ); void read_real ( char *real_file ); int read_real ( const igraph_matrix_t *real_mat, const igraph_vector_bool_t *fixed); void scan_int ( char *filename ); void read_int ( char *file_name ); void draw_graph ( int int_out, char *coord_file ); int draw_graph (igraph_matrix_t *res); void write_coord ( const char *file_name ); void write_sim ( const char *file_name ); float get_tot_energy ( ); // Con/Decon graph( int proc_id, int tot_procs, char *int_file ); ~graph( ) { } graph( const igraph_t *igraph, const igraph_layout_drl_options_t *options, const igraph_vector_t *weights); private: // Methods int ReCompute ( ); void update_nodes ( ); float Compute_Node_Energy ( int node_ind ); void Solve_Analytic ( int node_ind, float &pos_x, float &pos_y ); void get_positions ( vector &node_indices, float return_positions[2*MAX_PROCS] ); void update_density ( vector &node_indices, float old_positions[2*MAX_PROCS], float new_positions[2*MAX_PROCS] ); void update_node_pos ( int node_ind, float old_positions[2*MAX_PROCS], float new_positions[2*MAX_PROCS] ); // MPI information int myid, num_procs; // graph decomposition information int num_nodes; // number of nodes in graph float highest_sim; // highest sim for normalization map id_catalog; // id_catalog[file id] = internal id map > neighbors; // neighbors of nodes on this proc. // graph layout information vector positions; DensityGrid density_server; // original VxOrd information int STAGE, iterations; float temperature, attraction, damping_mult; float min_edges, CUT_END, cut_length_end, cut_off_length, cut_rate; bool first_add, fine_first_add, fineDensity; // scheduling variables layout_schedule liquid; layout_schedule expansion; layout_schedule cooldown; layout_schedule crunch; layout_schedule simmer; // timing statistics time_t start_time, stop_time; // online clustering information int real_iterations; // number of iterations to hold .real input fixed int tot_iterations; int tot_expected_iterations; // for progress bar bool real_fixed; }; } // namespace drl igraph/src/bliss/0000755000175100001440000000000013567553110013453 5ustar hornikusersigraph/src/bliss/utils.cc0000644000175100001440000000521613431000472015112 0ustar hornikusers#include #include #include "utils.hh" /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { void print_permutation(FILE* const fp, const unsigned int N, const unsigned int* perm, const unsigned int offset) { assert(N > 0); assert(perm); for(unsigned int i = 0; i < N; i++) { unsigned int j = perm[i]; if(j == i) continue; bool is_first = true; while(j != i) { if(j < i) { is_first = false; break; } j = perm[j]; } if(!is_first) continue; fprintf(fp, "(%u,", i+offset); j = perm[i]; while(j != i) { fprintf(fp, "%u", j+offset); j = perm[j]; if(j != i) fprintf(fp, ","); } fprintf(fp, ")"); } } void print_permutation(FILE* const fp, const std::vector& perm, const unsigned int offset) { const unsigned int N = perm.size(); for(unsigned int i = 0; i < N; i++) { unsigned int j = perm[i]; if(j == i) continue; bool is_first = true; while(j != i) { if(j < i) { is_first = false; break; } j = perm[j]; } if(!is_first) continue; fprintf(fp, "(%u,", i+offset); j = perm[i]; while(j != i) { fprintf(fp, "%u", j+offset); j = perm[j]; if(j != i) fprintf(fp, ","); } fprintf(fp, ")"); } } bool is_permutation(const unsigned int N, const unsigned int* perm) { if(N == 0) return true; std::vector m(N, false); for(unsigned int i = 0; i < N; i++) { if(perm[i] >= N) return false; if(m[perm[i]]) return false; m[perm[i]] = true; } return true; } bool is_permutation(const std::vector& perm) { const unsigned int N = perm.size(); if(N == 0) return true; std::vector m(N, false); for(unsigned int i = 0; i < N; i++) { if(perm[i] >= N) return false; if(m[perm[i]]) return false; m[perm[i]] = true; } return true; } } // namespace bliss igraph/src/bliss/heap.hh0000644000175100001440000000370313430770175014715 0ustar hornikusers#ifndef BLISS_HEAP_HH #define BLISS_HEAP_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { /** \internal * \brief A capacity bounded heap data structure. */ class Heap { unsigned int N; unsigned int n; unsigned int *array; void upheap(unsigned int k); void downheap(unsigned int k); public: /** * Create a new heap. * init() must be called after this. */ Heap() {array = 0; n = 0; N = 0; } ~Heap(); /** * Initialize the heap to have the capacity to hold \e size elements. */ void init(const unsigned int size); /** * Is the heap empty? * Time complexity is O(1). */ bool is_empty() const {return(n==0); } /** * Remove all the elements in the heap. * Time complexity is O(1). */ void clear() {n = 0;} /** * Insert the element \a e in the heap. * Time complexity is O(log(N)), where N is the number of elements * currently in the heap. */ void insert(const unsigned int e); /** * Remove and return the smallest element in the heap. * Time complexity is O(log(N)), where N is the number of elements * currently in the heap. */ unsigned int remove(); /** * Get the number of elements in the heap. */ unsigned int size() const {return n; } }; } // namespace bliss #endif igraph/src/bliss/uintseqhash.hh0000644000175100001440000000372113430770176016335 0ustar hornikusers#ifndef BLISS_UINTSEQHASH_HH #define BLISS_UINTSEQHASH_HH #include /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { /** \internal * \brief A hash for sequences of unsigned ints. */ class UintSeqHash { protected: unsigned int h; public: UintSeqHash() {h = 0; } UintSeqHash(const UintSeqHash &other) {h = other.h; } UintSeqHash& operator=(const UintSeqHash &other) {h = other.h; return *this; } /** Reset the hash value. */ void reset() {h = 0; } /** Add the unsigned int \a n to the sequence. */ void update(unsigned int n); /** Get the hash value of the sequence seen so far. */ unsigned int get_value() const {return h; } /** Compare the hash values of this and \a other. * Return -1/0/1 if the value of this is smaller/equal/greater than * that of \a other. */ int cmp(const UintSeqHash &other) const { return (h < other.h)?-1:((h == other.h)?0:1); } /** An abbreviation for cmp(other) < 0 */ bool is_lt(const UintSeqHash &other) const {return(cmp(other) < 0); } /** An abbreviation for cmp(other) <= 0 */ bool is_le(const UintSeqHash &other) const {return(cmp(other) <= 0); } /** An abbreviation for cmp(other) == 0 */ bool is_equal(const UintSeqHash &other) const {return(cmp(other) == 0); } }; } // namespace bliss #endif igraph/src/bliss/kqueue.hh0000644000175100001440000000612313430770176015277 0ustar hornikusers#ifndef BLISS_KQUEUE_HH #define BLISS_KQUEUE_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ #include "defs.hh" namespace bliss { /** \internal * \brief A very simple implementation of queues with fixed capacity. */ template class KQueue { public: /** * Create a new queue with capacity zero. * The function init() should be called next. */ KQueue(); ~KQueue(); /** * Initialize the queue to have the capacity to hold at most \a N elements. */ void init(const unsigned int N); /** Is the queue empty? */ bool is_empty() const; /** Return the number of elements in the queue. */ unsigned int size() const; /** Remove all the elements in the queue. */ void clear(); /** Return (but don't remove) the first element in the queue. */ Type front() const; /** Remove and return the first element of the queue. */ Type pop_front(); /** Push the element \a e in the front of the queue. */ void push_front(Type e); /** Remove and return the last element of the queue. */ Type pop_back(); /** Push the element \a e in the back of the queue. */ void push_back(Type e); private: Type *entries, *end; Type *head, *tail; }; template KQueue::KQueue() { entries = 0; end = 0; head = 0; tail = 0; } template KQueue::~KQueue() { if(entries) free(entries); } template void KQueue::init(const unsigned int k) { assert(k > 0); if(entries) free(entries); entries = (Type*)malloc((k + 1) * sizeof(Type)); end = entries + k + 1; head = entries; tail = head; } template void KQueue::clear() { head = entries; tail = head; } template bool KQueue::is_empty() const { return(head == tail); } template unsigned int KQueue::size() const { if(tail >= head) return(tail - head); return((end - head) + (tail - entries)); } template Type KQueue::front() const { return *head; } template Type KQueue::pop_front() { Type *old_head = head; head++; if(head == end) head = entries; return *old_head; } template void KQueue::push_front(Type e) { if(head == entries) head = end - 1; else head--; *head = e; } template void KQueue::push_back(Type e) { *tail = e; tail++; if(tail == end) tail = entries; } } // namespace bliss #endif igraph/src/bliss/igraph-changes.md0000644000175100001440000000147013430770176016661 0ustar hornikusersThis file lists changes that were made to the original Bliss package (version 0.73) to integrate it into igraph. Remove `Makefile`, `Doxyfile` Removed `bliss.cc`, `bliss_C.cc`, `bliss_C.h` Remove references to `Timer` class in `graph.cc` Remove `timer.cc` and `timer.hh` Add to `defs.hh`: #include "config.h" #if HAVE_GMP == 1 # define BLISS_USE_GMP #endif In `bignum.hh`: Move `#if defined(BLISS_USE_GMP) ...` below `#include "defs.h"` Add: #include "igraph_memory.h" #include "igraph_error.h" Also add, for the `tostring` method without GMP: #include #include #include Add `tostring` member function to `BigNum` class for both cases (with or without GMP). In `graph.cc`, add IGRAPH_THREAD_LOCAL to the `PathInfo` global variable on line 612. igraph/src/bliss/graph.hh0000644000175100001440000010052013430770175015074 0ustar hornikusers#ifndef BLISS_GRAPH_HH #define BLISS_GRAPH_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ /** * \namespace bliss * The namespace bliss contains all the classes and functions of the bliss * tool except for the C programming language API. */ namespace bliss { class AbstractGraph; } #include #include #include "kstack.hh" #include "kqueue.hh" #include "heap.hh" #include "orbit.hh" #include "partition.hh" #include "bignum.hh" #include "uintseqhash.hh" namespace bliss { /** * \brief Statistics returned by the bliss search algorithm. */ class Stats { friend class AbstractGraph; public: /** \internal The size of the automorphism group. */ BigNum group_size; private: /** \internal An approximation (due to possible overflows) of * the size of the automorphism group. */ long double group_size_approx; /** \internal The number of nodes in the search tree. */ long unsigned int nof_nodes; /** \internal The number of leaf nodes in the search tree. */ long unsigned int nof_leaf_nodes; /** \internal The number of bad nodes in the search tree. */ long unsigned int nof_bad_nodes; /** \internal The number of canonical representative updates. */ long unsigned int nof_canupdates; /** \internal The number of generator permutations. */ long unsigned int nof_generators; /** \internal The maximal depth of the search tree. */ unsigned long int max_level; /** */ void reset() { group_size.assign(1); group_size_approx = 1.0; nof_nodes = 0; nof_leaf_nodes = 0; nof_bad_nodes = 0; nof_canupdates = 0; nof_generators = 0; max_level = 0; } public: Stats() { reset(); } /** Print the statistics. */ size_t print(FILE* const fp) const { size_t r = 0; r += fprintf(fp, "Nodes: %lu\n", nof_nodes); r += fprintf(fp, "Leaf nodes: %lu\n", nof_leaf_nodes); r += fprintf(fp, "Bad nodes: %lu\n", nof_bad_nodes); r += fprintf(fp, "Canrep updates: %lu\n", nof_canupdates); r += fprintf(fp, "Generators: %lu\n", nof_generators); r += fprintf(fp, "Max level: %lu\n", max_level); r += fprintf(fp, "|Aut|: ")+group_size.print(fp)+fprintf(fp, "\n"); fflush(fp); return r; } /** An approximation (due to possible overflows/rounding errors) of * the size of the automorphism group. */ long double get_group_size_approx() const {return group_size_approx;} /** The number of nodes in the search tree. */ long unsigned int get_nof_nodes() const {return nof_nodes;} /** The number of leaf nodes in the search tree. */ long unsigned int get_nof_leaf_nodes() const {return nof_leaf_nodes;} /** The number of bad nodes in the search tree. */ long unsigned int get_nof_bad_nodes() const {return nof_bad_nodes;} /** The number of canonical representative updates. */ long unsigned int get_nof_canupdates() const {return nof_canupdates;} /** The number of generator permutations. */ long unsigned int get_nof_generators() const {return nof_generators;} /** The maximal depth of the search tree. */ unsigned long int get_max_level() const {return max_level;} }; /** * \brief An abstract base class for different types of graphs. */ class AbstractGraph { friend class Partition; public: AbstractGraph(); virtual ~AbstractGraph(); /** * Set the verbose output level for the algorithms. * \param level the level of verbose output, 0 means no verbose output */ void set_verbose_level(const unsigned int level); /** * Set the file stream for the verbose output. * \param fp the file stream; if null, no verbose output is written */ void set_verbose_file(FILE * const fp); /** * Add a new vertex with color \a color in the graph and return its index. */ virtual unsigned int add_vertex(const unsigned int color = 0) = 0; /** * Add an edge between vertices \a source and \a target. * Duplicate edges between vertices are ignored but try to avoid introducing * them in the first place as they are not ignored immediately but will * consume memory and computation resources for a while. */ virtual void add_edge(const unsigned int source, const unsigned int target) = 0; /** * Change the color of the vertex \a vertex to \a color. */ virtual void change_color(const unsigned int vertex, const unsigned int color) = 0; /** * Check whether \a perm is an automorphism of this graph. * Unoptimized, mainly for debugging purposes. */ virtual bool is_automorphism(const std::vector& perm) const; /** Activate/deactivate failure recording. * May not be called during the search, i.e. from an automorphism reporting * hook function. * \param active if true, activate failure recording, deactivate otherwise */ void set_failure_recording(const bool active) {assert(!in_search); opt_use_failure_recording = active;} /** Activate/deactivate component recursion. * The choice affects the computed canonical labelings; * therefore, if you want to compare whether two graphs are isomorphic by * computing and comparing (for equality) their canonical versions, * be sure to use the same choice for both graphs. * May not be called during the search, i.e. from an automorphism reporting * hook function. * \param active if true, activate component recursion, deactivate otherwise */ void set_component_recursion(const bool active) {assert(!in_search); opt_use_comprec = active;} /** * Return the number of vertices in the graph. */ virtual unsigned int get_nof_vertices() const = 0; /** * Return a new graph that is the result of applying the permutation \a perm * to this graph. This graph is not modified. * \a perm must contain N=this.get_nof_vertices() elements and be a bijection * on {0,1,...,N-1}, otherwise the result is undefined or a segfault. */ virtual AbstractGraph* permute(const unsigned int* const perm) const = 0; virtual AbstractGraph* permute(const std::vector& perm) const = 0; /** * Find a set of generators for the automorphism group of the graph. * The function \a hook (if non-null) is called each time a new generator * for the automorphism group is found. * The first argument \a user_param for the hook is the * \a hook_user_param given below, * the second argument \a n is the length of the automorphism (equal to * get_nof_vertices()) and * the third argument \a aut is the automorphism * (a bijection on {0,...,get_nof_vertices()-1}). * The memory for the automorphism \a aut will be invalidated immediately * after the return from the hook function; * if you want to use the automorphism later, you have to take a copy of it. * Do not call any member functions in the hook. * The search statistics are copied in \a stats. */ void find_automorphisms(Stats& stats, void (*hook)(void* user_param, unsigned int n, const unsigned int* aut), void* hook_user_param); /** * Otherwise the same as find_automorphisms() except that * a canonical labeling of the graph (a bijection on * {0,...,get_nof_vertices()-1}) is returned. * The memory allocated for the returned canonical labeling will remain * valid only until the next call to a member function with the exception * that constant member functions (for example, bliss::Graph::permute()) can * be called without invalidating the labeling. * To compute the canonical version of an undirected graph, call this * function and then bliss::Graph::permute() with the returned canonical * labeling. * Note that the computed canonical version may depend on the applied version * of bliss as well as on some other options (for instance, the splitting * heuristic selected with bliss::Graph::set_splitting_heuristic()). */ const unsigned int* canonical_form(Stats& stats, void (*hook)(void* user_param, unsigned int n, const unsigned int* aut), void* hook_user_param); /** * Write the graph to a file in a variant of the DIMACS format. * See the bliss website * for the definition of the file format. * Note that in the DIMACS file the vertices are numbered from 1 to N while * in this C++ API they are from 0 to N-1. * Thus the vertex n in the file corresponds to the vertex n-1 in the API. * \param fp the file stream where the graph is written */ virtual void write_dimacs(FILE * const fp) = 0; /** * Write the graph to a file in the graphviz dotty format. * \param fp the file stream where the graph is written */ virtual void write_dot(FILE * const fp) = 0; /** * Write the graph in a file in the graphviz dotty format. * Do nothing if the file cannot be written. * \param file_name the name of the file to which the graph is written */ virtual void write_dot(const char * const file_name) = 0; /** * Get a hash value for the graph. * \return the hash value */ virtual unsigned int get_hash() = 0; /** * Disable/enable the "long prune" method. * The choice affects the computed canonical labelings; * therefore, if you want to compare whether two graphs are isomorphic by * computing and comparing (for equality) their canonical versions, * be sure to use the same choice for both graphs. * May not be called during the search, i.e. from an automorphism reporting * hook function. * \param active if true, activate "long prune", deactivate otherwise */ void set_long_prune_activity(const bool active) { assert(!in_search); opt_use_long_prune = active; } protected: /** \internal * How much verbose output is produced (0 means none) */ unsigned int verbose_level; /** \internal * The output stream for verbose output. */ FILE *verbstr; protected: /** \internal * The ordered partition used in the search algorithm. */ Partition p; /** \internal * Whether the search for automorphisms and a canonical labeling is * in progress. */ bool in_search; /** \internal * Is failure recording in use? */ bool opt_use_failure_recording; /* The "tree-specific" invariant value for the point when current path * got different from the first path */ unsigned int failure_recording_fp_deviation; /** \internal * Is component recursion in use? */ bool opt_use_comprec; unsigned int refine_current_path_certificate_index; bool refine_compare_certificate; bool refine_equal_to_first = false; unsigned int refine_first_path_subcertificate_end; int refine_cmp_to_best; unsigned int refine_best_path_subcertificate_end; static const unsigned int CERT_SPLIT = 0; //UINT_MAX; static const unsigned int CERT_EDGE = 1; //UINT_MAX-1; /** \internal * Add a triple (v1,v2,v3) in the certificate. * May modify refine_equal_to_first and refine_cmp_to_best. * May also update eqref_hash and failure_recording_fp_deviation. */ void cert_add(const unsigned int v1, const unsigned int v2, const unsigned int v3); /** \internal * Add a redundant triple (v1,v2,v3) in the certificate. * Can also just dicard the triple. * May modify refine_equal_to_first and refine_cmp_to_best. * May also update eqref_hash and failure_recording_fp_deviation. */ void cert_add_redundant(const unsigned int x, const unsigned int y, const unsigned int z); /**\internal * Is the long prune method in use? */ bool opt_use_long_prune; /**\internal * Maximum amount of memory (in megabytes) available for * the long prune method */ static const unsigned int long_prune_options_max_mem = 50; /**\internal * Maximum amount of automorphisms stored for the long prune method; * less than this is stored if the memory limit above is reached first */ static const unsigned int long_prune_options_max_stored_auts = 100; unsigned int long_prune_max_stored_autss; std::vector *> long_prune_fixed; std::vector *> long_prune_mcrs; std::vector long_prune_temp; unsigned int long_prune_begin; unsigned int long_prune_end; /** \internal * Initialize the "long prune" data structures. */ void long_prune_init(); /** \internal * Release the memory allocated for "long prune" data structures. */ void long_prune_deallocate(); void long_prune_add_automorphism(const unsigned int *aut); std::vector& long_prune_get_fixed(const unsigned int index); std::vector& long_prune_allocget_fixed(const unsigned int index); std::vector& long_prune_get_mcrs(const unsigned int index); std::vector& long_prune_allocget_mcrs(const unsigned int index); /** \internal * Swap the i:th and j:th stored automorphism information; * i and j must be "in window, i.e. in [long_prune_begin,long_prune_end[ */ void long_prune_swap(const unsigned int i, const unsigned int j); /* * Data structures and routines for refining the partition p into equitable */ Heap neighbour_heap; virtual bool split_neighbourhood_of_unit_cell(Partition::Cell *) = 0; virtual bool split_neighbourhood_of_cell(Partition::Cell * const) = 0; void refine_to_equitable(); void refine_to_equitable(Partition::Cell * const unit_cell); void refine_to_equitable(Partition::Cell * const unit_cell1, Partition::Cell * const unit_cell2); /** \internal * \return false if it was detected that the current certificate * is different from the first and/or best (whether this is checked * depends on in_search and refine_compare_certificate flags. */ bool do_refine_to_equitable(); unsigned int eqref_max_certificate_index; /** \internal * Whether eqref_hash is updated during equitable refinement process. */ bool compute_eqref_hash; UintSeqHash eqref_hash; /** \internal * Check whether the current partition p is equitable. * Performance: very slow, use only for debugging purposes. */ virtual bool is_equitable() const = 0; unsigned int *first_path_labeling; unsigned int *first_path_labeling_inv; Orbit first_path_orbits; unsigned int *first_path_automorphism; unsigned int *best_path_labeling; unsigned int *best_path_labeling_inv; Orbit best_path_orbits; unsigned int *best_path_automorphism; void update_labeling(unsigned int * const lab); void update_labeling_and_its_inverse(unsigned int * const lab, unsigned int * const lab_inv); void update_orbit_information(Orbit &o, const unsigned int *perm); void reset_permutation(unsigned int *perm); /* Mainly for debugging purposes */ virtual bool is_automorphism(unsigned int* const perm); std::vector certificate_current_path; std::vector certificate_first_path; std::vector certificate_best_path; unsigned int certificate_index; virtual void initialize_certificate() = 0; virtual void remove_duplicate_edges() = 0; virtual void make_initial_equitable_partition() = 0; virtual Partition::Cell* find_next_cell_to_be_splitted(Partition::Cell *cell) = 0; void search(const bool canonical, Stats &stats); void (*report_hook)(void *user_param, unsigned int n, const unsigned int *aut); void *report_user_param; /* * * Nonuniform component recursion (NUCR) * */ /** The currently traversed component */ unsigned int cr_level; /** \internal * The "Component End Point" data structure */ class CR_CEP { public: /** At which level in the search was this CEP created */ unsigned int creation_level; /** The current component has been fully traversed when the partition has * this many discrete cells left */ unsigned int discrete_cell_limit; /** The component to be traversed after the current one */ unsigned int next_cr_level; /** The next component end point */ unsigned int next_cep_index; bool first_checked; bool best_checked; }; /** \internal * A stack for storing Component End Points */ std::vector cr_cep_stack; /** \internal * Find the first non-uniformity component at the component recursion * level \a level. * The component is stored in \a cr_component. * If no component is found, \a cr_component is empty. * Returns false if all the cells in the component recursion level \a level * were discrete. * Modifies the max_ival and max_ival_count fields of Partition:Cell * (assumes that they are 0 when called and * quarantees that they are 0 when returned). */ virtual bool nucr_find_first_component(const unsigned int level) = 0; virtual bool nucr_find_first_component(const unsigned int level, std::vector& component, unsigned int& component_elements, Partition::Cell*& sh_return) = 0; /** \internal * The non-uniformity component found by nucr_find_first_component() * is stored here. */ std::vector cr_component; /** \internal * The number of vertices in the component \a cr_component */ unsigned int cr_component_elements; }; /** * \brief The class for undirected, vertex colored graphs. * * Multiple edges between vertices are not allowed (i.e., are ignored). */ class Graph : public AbstractGraph { public: /** * The possible splitting heuristics. * The selected splitting heuristics affects the computed canonical * labelings; therefore, if you want to compare whether two graphs * are isomorphic by computing and comparing (for equality) their * canonical versions, be sure to use the same splitting heuristics * for both graphs. */ typedef enum { /** First non-unit cell. * Very fast but may result in large search spaces on difficult graphs. * Use for large but easy graphs. */ shs_f = 0, /** First smallest non-unit cell. * Fast, should usually produce smaller search spaces than shs_f. */ shs_fs, /** First largest non-unit cell. * Fast, should usually produce smaller search spaces than shs_f. */ shs_fl, /** First maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_fm, /** First smallest maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_fsm, /** First largest maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_flm } SplittingHeuristic; protected: class Vertex { public: Vertex(); ~Vertex(); void add_edge(const unsigned int other_vertex); void remove_duplicate_edges(std::vector& tmp); void sort_edges(); unsigned int color; std::vector edges; unsigned int nof_edges() const {return edges.size(); } }; std::vector vertices; void sort_edges(); void remove_duplicate_edges(); /** \internal * Partition independent invariant. * Returns the color of the vertex. * Time complexity: O(1). */ static unsigned int vertex_color_invariant(const Graph* const g, const unsigned int v); /** \internal * Partition independent invariant. * Returns the degree of the vertex. * DUPLICATE EDGES MUST HAVE BEEN REMOVED BEFORE. * Time complexity: O(1). */ static unsigned int degree_invariant(const Graph* const g, const unsigned int v); /** \internal * Partition independent invariant. * Returns 1 if there is an edge from the vertex to itself, 0 if not. * Time complexity: O(k), where k is the number of edges leaving the vertex. */ static unsigned int selfloop_invariant(const Graph* const g, const unsigned int v); bool refine_according_to_invariant(unsigned int (*inv)(const Graph* const g, const unsigned int v)); /* * Routines needed when refining the partition p into equitable */ bool split_neighbourhood_of_unit_cell(Partition::Cell *); bool split_neighbourhood_of_cell(Partition::Cell * const); /** \internal * \copydoc AbstractGraph::is_equitable() const */ bool is_equitable() const; /* Splitting heuristics, documented in more detail in graph.cc */ SplittingHeuristic sh; Partition::Cell* find_next_cell_to_be_splitted(Partition::Cell *cell); Partition::Cell* sh_first(); Partition::Cell* sh_first_smallest(); Partition::Cell* sh_first_largest(); Partition::Cell* sh_first_max_neighbours(); Partition::Cell* sh_first_smallest_max_neighbours(); Partition::Cell* sh_first_largest_max_neighbours(); void make_initial_equitable_partition(); void initialize_certificate(); bool is_automorphism(unsigned int* const perm); bool nucr_find_first_component(const unsigned int level); bool nucr_find_first_component(const unsigned int level, std::vector& component, unsigned int& component_elements, Partition::Cell*& sh_return); public: /** * Create a new graph with \a N vertices and no edges. */ Graph(const unsigned int N = 0); /** * Destroy the graph. */ ~Graph(); /** * Read the graph from the file \a fp in a variant of the DIMACS format. * See the bliss website * for the definition of the file format. * Note that in the DIMACS file the vertices are numbered from 1 to N while * in this C++ API they are from 0 to N-1. * Thus the vertex n in the file corresponds to the vertex n-1 in the API. * * \param fp the file stream for the graph file * \param errstr if non-null, the possible error messages are printed * in this file stream * \return a new Graph object or 0 if reading failed for some * reason */ static Graph* read_dimacs(FILE* const fp, FILE* const errstr = stderr); /** * Write the graph to a file in a variant of the DIMACS format. * See the bliss website * for the definition of the file format. */ void write_dimacs(FILE* const fp); /** * \copydoc AbstractGraph::write_dot(FILE * const fp) */ void write_dot(FILE* const fp); /** * \copydoc AbstractGraph::write_dot(const char * const file_name) */ void write_dot(const char* const file_name); /** * \copydoc AbstractGraph::is_automorphism(const std::vector& perm) const */ bool is_automorphism(const std::vector& perm) const; /** * \copydoc AbstractGraph::get_hash() */ virtual unsigned int get_hash(); /** * Return the number of vertices in the graph. */ unsigned int get_nof_vertices() const {return vertices.size(); } /** * \copydoc AbstractGraph::permute(const unsigned int* const perm) const */ Graph* permute(const unsigned int* const perm) const; Graph* permute(const std::vector& perm) const; /** * Add a new vertex with color \a color in the graph and return its index. */ unsigned int add_vertex(const unsigned int color = 0); /** * Add an edge between vertices \a v1 and \a v2. * Duplicate edges between vertices are ignored but try to avoid introducing * them in the first place as they are not ignored immediately but will * consume memory and computation resources for a while. */ void add_edge(const unsigned int v1, const unsigned int v2); /** * Change the color of the vertex \a vertex to \a color. */ void change_color(const unsigned int vertex, const unsigned int color); /** * Compare this graph with the graph \a other. * Returns 0 if the graphs are equal, and a negative (positive) integer * if this graph is "smaller than" ("greater than", resp.) than \a other. */ int cmp(Graph& other); /** * Set the splitting heuristic used by the automorphism and canonical * labeling algorithm. * The selected splitting heuristics affects the computed canonical * labelings; therefore, if you want to compare whether two graphs * are isomorphic by computing and comparing (for equality) their * canonical versions, be sure to use the same splitting heuristics * for both graphs. */ void set_splitting_heuristic(const SplittingHeuristic shs) {sh = shs; } }; /** * \brief The class for directed, vertex colored graphs. * * Multiple edges between vertices are not allowed (i.e., are ignored). */ class Digraph : public AbstractGraph { public: /** * The possible splitting heuristics. * The selected splitting heuristics affects the computed canonical * labelings; therefore, if you want to compare whether two graphs * are isomorphic by computing and comparing (for equality) their * canonical versions, be sure to use the same splitting heuristics * for both graphs. */ typedef enum { /** First non-unit cell. * Very fast but may result in large search spaces on difficult graphs. * Use for large but easy graphs. */ shs_f = 0, /** First smallest non-unit cell. * Fast, should usually produce smaller search spaces than shs_f. */ shs_fs, /** First largest non-unit cell. * Fast, should usually produce smaller search spaces than shs_f. */ shs_fl, /** First maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_fm, /** First smallest maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_fsm, /** First largest maximally non-trivially connected non-unit cell. * Not so fast, should usually produce smaller search spaces than shs_f, * shs_fs, and shs_fl. */ shs_flm } SplittingHeuristic; protected: class Vertex { public: Vertex(); ~Vertex(); void add_edge_to(const unsigned int dest_vertex); void add_edge_from(const unsigned int source_vertex); void remove_duplicate_edges(std::vector& tmp); void sort_edges(); unsigned int color; std::vector edges_out; std::vector edges_in; unsigned int nof_edges_in() const {return edges_in.size(); } unsigned int nof_edges_out() const {return edges_out.size(); } }; std::vector vertices; void remove_duplicate_edges(); /** \internal * Partition independent invariant. * Returns the color of the vertex. * Time complexity: O(1). */ static unsigned int vertex_color_invariant(const Digraph* const g, const unsigned int v); /** \internal * Partition independent invariant. * Returns the indegree of the vertex. * DUPLICATE EDGES MUST HAVE BEEN REMOVED BEFORE. * Time complexity: O(1). */ static unsigned int indegree_invariant(const Digraph* const g, const unsigned int v); /** \internal * Partition independent invariant. * Returns the outdegree of the vertex. * DUPLICATE EDGES MUST HAVE BEEN REMOVED BEFORE. * Time complexity: O(1). */ static unsigned int outdegree_invariant(const Digraph* const g, const unsigned int v); /** \internal * Partition independent invariant. * Returns 1 if there is an edge from the vertex to itself, 0 if not. * Time complexity: O(k), where k is the number of edges leaving the vertex. */ static unsigned int selfloop_invariant(const Digraph* const g, const unsigned int v); /** \internal * Refine the partition \a p according to * the partition independent invariant \a inv. */ bool refine_according_to_invariant(unsigned int (*inv)(const Digraph* const g, const unsigned int v)); /* * Routines needed when refining the partition p into equitable */ bool split_neighbourhood_of_unit_cell(Partition::Cell* const); bool split_neighbourhood_of_cell(Partition::Cell* const); /** \internal * \copydoc AbstractGraph::is_equitable() const */ bool is_equitable() const; /* Splitting heuristics, documented in more detail in the cc-file. */ SplittingHeuristic sh; Partition::Cell* find_next_cell_to_be_splitted(Partition::Cell *cell); Partition::Cell* sh_first(); Partition::Cell* sh_first_smallest(); Partition::Cell* sh_first_largest(); Partition::Cell* sh_first_max_neighbours(); Partition::Cell* sh_first_smallest_max_neighbours(); Partition::Cell* sh_first_largest_max_neighbours(); void make_initial_equitable_partition(); void initialize_certificate(); bool is_automorphism(unsigned int* const perm); void sort_edges(); bool nucr_find_first_component(const unsigned int level); bool nucr_find_first_component(const unsigned int level, std::vector& component, unsigned int& component_elements, Partition::Cell*& sh_return); public: /** * Create a new directed graph with \a N vertices and no edges. */ Digraph(const unsigned int N = 0); /** * Destroy the graph. */ ~Digraph(); /** * Read the graph from the file \a fp in a variant of the DIMACS format. * See the bliss website * for the definition of the file format. * Note that in the DIMACS file the vertices are numbered from 1 to N while * in this C++ API they are from 0 to N-1. * Thus the vertex n in the file corresponds to the vertex n-1 in the API. * \param fp the file stream for the graph file * \param errstr if non-null, the possible error messages are printed * in this file stream * \return a new Digraph object or 0 if reading failed for some * reason */ static Digraph* read_dimacs(FILE* const fp, FILE* const errstr = stderr); /** * \copydoc AbstractGraph::write_dimacs(FILE * const fp) */ void write_dimacs(FILE* const fp); /** * \copydoc AbstractGraph::write_dot(FILE *fp) */ void write_dot(FILE * const fp); /** * \copydoc AbstractGraph::write_dot(const char * const file_name) */ void write_dot(const char * const file_name); /** * \copydoc AbstractGraph::is_automorphism(const std::vector& perm) const */ bool is_automorphism(const std::vector& perm) const; /** * \copydoc AbstractGraph::get_hash() */ virtual unsigned int get_hash(); /** * Return the number of vertices in the graph. */ unsigned int get_nof_vertices() const {return vertices.size(); } /** * Add a new vertex with color 'color' in the graph and return its index. */ unsigned int add_vertex(const unsigned int color = 0); /** * Add an edge from the vertex \a source to the vertex \a target. * Duplicate edges are ignored but try to avoid introducing * them in the first place as they are not ignored immediately but will * consume memory and computation resources for a while. */ void add_edge(const unsigned int source, const unsigned int target); /** * Change the color of the vertex 'vertex' to 'color'. */ void change_color(const unsigned int vertex, const unsigned int color); /** * Compare this graph with the graph \a other. * Returns 0 if the graphs are equal, and a negative (positive) integer * if this graph is "smaller than" ("greater than", resp.) than \a other. */ int cmp(Digraph& other); /** * Set the splitting heuristic used by the automorphism and canonical * labeling algorithm. * The selected splitting heuristics affects the computed canonical * labelings; therefore, if you want to compare whether two graphs * are isomorphic by computing and comparing (for equality) their * canonical versions, be sure to use the same splitting heuristics * for both graphs. */ void set_splitting_heuristic(SplittingHeuristic shs) {sh = shs; } /** * \copydoc AbstractGraph::permute(const unsigned int* const perm) const */ Digraph* permute(const unsigned int* const perm) const; Digraph* permute(const std::vector& perm) const; }; } #endif igraph/src/bliss/defs.hh0000644000175100001440000000700113430770175014714 0ustar hornikusers#ifndef BLISS_DEFS_HH #define BLISS_DEFS_HH #include #include #include "config.h" /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ #if HAVE_GMP == 1 # define BLISS_USE_GMP #endif #ifdef USING_R #include #define fatal_error(...) (error(__VA_ARGS__)) #endif namespace bliss { /** * The version number of bliss. */ static const char * const version = "0.73"; /* * If a fatal error (out of memory, internal error) is encountered, * this function is called. * There should not be a return from this function but exit or * a jump to code that deallocates the AbstractGraph instance that called this. */ #ifndef USING_R void fatal_error(const char* fmt, ...); #endif #if defined(BLISS_DEBUG) #define BLISS_CONSISTENCY_CHECKS #define BLISS_EXPENSIVE_CONSISTENCY_CHECKS #endif #if defined(BLISS_CONSISTENCY_CHECKS) /* Force a check that the found automorphisms are valid */ #define BLISS_VERIFY_AUTOMORPHISMS #endif #if defined(BLISS_CONSISTENCY_CHECKS) /* Force a check that the generated partitions are equitable */ #define BLISS_VERIFY_EQUITABLEDNESS #endif } // namespace bliss /*! \mainpage Bliss * * \section intro_sec Introduction * * This is the source code documentation of bliss, * produced by running doxygen in * the source directory. * The algorithms and data structures used in bliss are documented in * the papers found at the * bliss web site. * * * \section compile_sec Compiling * * Compiling bliss in Linux should be easy, just execute * \code * make * \endcode * in the bliss source directory. * This will produce the executable program \c bliss as well as * the library file \c libbliss.a that can be linked in other programs. * If you have the GNU Multiple Precision * Arithmetic Library (GMP) installed in your machine, you can also use * \code * make gmp * \endcode * to enable exact computation of automorphism group sizes. * * When linking the bliss library \c libbliss.a in other programs, * remember to include the standard c++ library * (and the GMP library if you compiled bliss to include it). * For instance, * \code gcc -o test test.c -lstdc++ -lgmp -lbliss\endcode * * \section cppapi_sec The C++ language API * * The C++ language API is the main API to bliss; * all other APIs are just more or less complete variants of it. * The C++ API consists basically of the public methods in * the classes bliss::AbstractGraph, bliss::Graph, and bliss::Digraph. * For an example of its use, * see the \ref executable "source of the bliss executable". * * * \section capi_sec The C language API * * The C language API is given in the file bliss_C.h. * It is currently more restricted than the C++ API so * consider using the C++ API whenever possible. */ #endif igraph/src/bliss/kstack.hh0000644000175100001440000000556413430770176015270 0ustar hornikusers#ifndef BLISS_KSTACK_H #define BLISS_KSTACK_H /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ #include #include "defs.hh" namespace bliss { /** \internal * \brief A very simple implementation of a stack with fixed capacity. */ template class KStack { public: /** * Create a new stack with zero capacity. * The function init() should be called next. */ KStack(); /** * Create a new stack with the capacity to hold at most \a N elements. */ KStack(int N); ~KStack(); /** * Initialize the stack to have the capacity to hold at most \a N elements. */ void init(int N); /** * Is the stack empty? */ bool is_empty() const {return(cursor == entries); } /** * Return (but don't remove) the top element of the stack. */ Type top() const {BLISS_ASSERT(cursor > entries); return *cursor; } /** * Pop (remove) the top element of the stack. */ Type pop() { return *cursor--; } /** * Push the element \a e in the stack. */ void push(Type e) { *(++cursor) = e; } /** Remove all the elements in the stack. */ void clean() {cursor = entries; } /** * Get the number of elements in the stack. */ unsigned int size() const {return(cursor - entries); } /** * Return the i:th element in the stack, where \a i is in the range * 0,...,this.size()-1; the 0:th element is the bottom element * in the stack. */ Type element_at(unsigned int i) { assert(i < size()); return entries[i+1]; } /** Return the capacity (NOT the number of elements) of the stack. */ int capacity() {return kapacity; } private: int kapacity; Type *entries; Type *cursor; }; template KStack::KStack() { kapacity = 0; entries = 0; cursor = 0; } template KStack::KStack(int k) { assert(k > 0); kapacity = k; entries = (Type*)malloc((k+1) * sizeof(Type)); cursor = entries; } template void KStack::init(int k) { assert(k > 0); if(entries) free(entries); kapacity = k; entries = (Type*)malloc((k+1) * sizeof(Type)); cursor = entries; } template KStack::~KStack() { free(entries); } } // namespace bliss #endif igraph/src/bliss/defs.cc0000644000175100001440000000202713431000472014670 0ustar hornikusers#include #include #include "defs.hh" /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { #ifndef USING_R void fatal_error(const char* fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr,"Bliss fatal error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\nAborting!\n"); va_end(ap); exit(1); } #endif } igraph/src/bliss/bignum.hh0000644000175100001440000000560313430770175015262 0ustar hornikusers#ifndef BLISS_BIGNUM_HH #define BLISS_BIGNUM_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ #include #include #include #include #include #include "defs.hh" #include "igraph_memory.h" #include "igraph_error.h" #if defined(BLISS_USE_GMP) #include #endif namespace bliss { /** * \brief A very simple class for big integers (or approximation of them). * * If the compile time flag BLISS_USE_GMP is set, * then the GNU Multiple Precision Arithmetic library (GMP) is used to * obtain arbitrary precision, otherwise "long double" is used to * approximate big integers. */ #if defined(BLISS_USE_GMP) class BigNum { mpz_t v; public: /** * Create a new big number and set it to zero. */ BigNum() {mpz_init(v); } /** * Destroy the number. */ ~BigNum() {mpz_clear(v); } /** * Set the number to \a n. */ void assign(const int n) {mpz_set_si(v, n); } /** * Multiply the number with \a n. */ void multiply(const int n) {mpz_mul_si(v, v, n); } /** * Print the number in the file stream \a fp. */ size_t print(FILE* const fp) const {return mpz_out_str(fp, 10, v); } int tostring(char **str) const { *str=igraph_Calloc(mpz_sizeinbase(v, 10)+2, char); if (! *str) { IGRAPH_ERROR("Cannot convert big number to string", IGRAPH_ENOMEM); } mpz_get_str(*str, 10, v); return 0; } }; #else class BigNum { long double v; public: /** * Create a new big number and set it to zero. */ BigNum(): v(0.0) {} /** * Set the number to \a n. */ void assign(const int n) {v = (long double)n; } /** * Multiply the number with \a n. */ void multiply(const int n) {v *= (long double)n; } /** * Print the number in the file stream \a fp. */ size_t print(FILE* const fp) const {return fprintf(fp, "%Lg", v); } int tostring(char **str) const { int size=static_cast( (std::log(std::abs(v))/std::log(10.0))+4 ); *str=igraph_Calloc(size, char ); if (! *str) { IGRAPH_ERROR("Cannot convert big number to string", IGRAPH_ENOMEM); } std::stringstream ss; ss << v; strncpy(*str, ss.str().c_str(), size); return 0; } }; #endif } //namespace bliss #endif igraph/src/bliss/graph.cc0000644000175100001440000042733513431000472015065 0ustar hornikusers#include #include #include #include #include #include #include "defs.hh" #include "graph.hh" #include "partition.hh" #include "utils.hh" /* use 'and' instead of '&&' */ #if _MSC_VER #include #endif #ifdef USING_R #undef stdout #define stdout NULL #endif /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { #define _INTERNAL_ERROR() fatal_error("%s:%d: internal error",__FILE__,__LINE__) #define _OUT_OF_MEMORY() fatal_error("%s:%d: out of memory",__FILE__,__LINE__) /*------------------------------------------------------------------------- * * Constructor and destructor routines for the abstract graph class * *-------------------------------------------------------------------------*/ AbstractGraph::AbstractGraph() { /* Initialize stuff */ first_path_labeling = 0; first_path_labeling_inv = 0; best_path_labeling = 0; best_path_labeling_inv = 0; first_path_automorphism = 0; best_path_automorphism = 0; in_search = false; /* Default value for using "long prune" */ opt_use_long_prune = true; /* Default value for using failure recording */ opt_use_failure_recording = true; /* Default value for using component recursion */ opt_use_comprec = true; verbose_level = 0; verbstr = stdout; report_hook = 0; report_user_param = 0; } AbstractGraph::~AbstractGraph() { if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(first_path_labeling_inv) { free(first_path_labeling_inv); first_path_labeling_inv = 0; } if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } if(best_path_labeling_inv) { free(best_path_labeling_inv); best_path_labeling_inv = 0; } if(first_path_automorphism) { free(first_path_automorphism); first_path_automorphism = 0; } if(best_path_automorphism) { free(best_path_automorphism); best_path_automorphism = 0; } report_hook = 0; report_user_param = 0; } /*------------------------------------------------------------------------- * * Verbose output management routines * *-------------------------------------------------------------------------*/ void AbstractGraph::set_verbose_level(const unsigned int level) { verbose_level = level; } void AbstractGraph::set_verbose_file(FILE* const fp) { verbstr = fp; } /*------------------------------------------------------------------------- * * Routines for refinement to equitable partition * *-------------------------------------------------------------------------*/ void AbstractGraph::refine_to_equitable() { /* Start refinement from all cells -> push 'em all in the splitting queue */ for(Partition::Cell* cell = p.first_cell; cell; cell = cell->next) p.splitting_queue_add(cell); do_refine_to_equitable(); } void AbstractGraph::refine_to_equitable(Partition::Cell* const unit_cell) { p.splitting_queue_add(unit_cell); do_refine_to_equitable(); } void AbstractGraph::refine_to_equitable(Partition::Cell* const unit_cell1, Partition::Cell* const unit_cell2) { p.splitting_queue_add(unit_cell1); p.splitting_queue_add(unit_cell2); do_refine_to_equitable(); } bool AbstractGraph::do_refine_to_equitable() { eqref_hash.reset(); while(!p.splitting_queue_is_empty()) { Partition::Cell* const cell = p.splitting_queue_pop(); if(cell->is_unit()) { if(in_search) { const unsigned int index = cell->first; if(first_path_automorphism) { /* Build the (potential) automorphism on-the-fly */ first_path_automorphism[first_path_labeling_inv[index]] = p.elements[index]; } if(best_path_automorphism) { /* Build the (potential) automorphism on-the-fly */ best_path_automorphism[best_path_labeling_inv[index]] = p.elements[index]; } } const bool worse = split_neighbourhood_of_unit_cell(cell); if(in_search and worse) goto worse_exit; } else { const bool worse = split_neighbourhood_of_cell(cell); if(in_search and worse) goto worse_exit; } } return true; worse_exit: /* Clear splitting_queue */ p.splitting_queue_clear(); return false; } /*------------------------------------------------------------------------- * * Routines for handling the canonical labeling * *-------------------------------------------------------------------------*/ /** \internal * Assign the labeling induced by the current partition 'this.p' to * \a labeling. * That is, if the partition is [[2,0],[1]], * then \a labeling will map 0 to 1, 1 to 2, and 2 to 0. */ void AbstractGraph::update_labeling(unsigned int* const labeling) { const unsigned int N = get_nof_vertices(); unsigned int* ep = p.elements; for(unsigned int i = 0; i < N; i++, ep++) labeling[*ep] = i; } /** \internal * The same as update_labeling() except that the inverse of the labeling * is also produced and assigned to \a labeling_inv. */ void AbstractGraph::update_labeling_and_its_inverse(unsigned int* const labeling, unsigned int* const labeling_inv) { const unsigned int N = get_nof_vertices(); unsigned int* ep = p.elements; unsigned int* clip = labeling_inv; for(unsigned int i = 0; i < N; ) { labeling[*ep] = i; i++; *clip = *ep; ep++; clip++; } } /*------------------------------------------------------------------------- * * Routines for handling automorphisms * *-------------------------------------------------------------------------*/ /** \internal * Reset the permutation \a perm to the identity permutation. */ void AbstractGraph::reset_permutation(unsigned int* perm) { const unsigned int N = get_nof_vertices(); for(unsigned int i = 0; i < N; i++, perm++) *perm = i; } bool AbstractGraph::is_automorphism(unsigned int* const perm) { _INTERNAL_ERROR(); return false; } bool AbstractGraph::is_automorphism(const std::vector& perm) const { _INTERNAL_ERROR(); return false; } /*------------------------------------------------------------------------- * * Certificate building * *-------------------------------------------------------------------------*/ void AbstractGraph::cert_add(const unsigned int v1, const unsigned int v2, const unsigned int v3) { if(refine_compare_certificate) { if(refine_equal_to_first) { /* So far equivalent to the first path... */ unsigned int index = certificate_current_path.size(); if(index >= refine_first_path_subcertificate_end) { refine_equal_to_first = false; } else if(certificate_first_path[index] != v1) { refine_equal_to_first = false; } else if(certificate_first_path[++index] != v2) { refine_equal_to_first = false; } else if(certificate_first_path[++index] != v3) { refine_equal_to_first = false; } if(opt_use_failure_recording and !refine_equal_to_first) { /* We just became different from the first path, * remember the deviation point tree-specific invariant * for the use of failure recording */ UintSeqHash h; h.update(v1); h.update(v2); h.update(v3); h.update(index); h.update(eqref_hash.get_value()); failure_recording_fp_deviation = h.get_value(); } } if(refine_cmp_to_best == 0) { /* So far equivalent to the current best path... */ unsigned int index = certificate_current_path.size(); if(index >= refine_best_path_subcertificate_end) { refine_cmp_to_best = 1; } else if(v1 > certificate_best_path[index]) { refine_cmp_to_best = 1; } else if(v1 < certificate_best_path[index]) { refine_cmp_to_best = -1; } else if(v2 > certificate_best_path[++index]) { refine_cmp_to_best = 1; } else if(v2 < certificate_best_path[index]) { refine_cmp_to_best = -1; } else if(v3 > certificate_best_path[++index]) { refine_cmp_to_best = 1; } else if(v3 < certificate_best_path[index]) { refine_cmp_to_best = -1; } } if((refine_equal_to_first == false) and (refine_cmp_to_best < 0)) return; } /* Update the current path certificate */ certificate_current_path.push_back(v1); certificate_current_path.push_back(v2); certificate_current_path.push_back(v3); } void AbstractGraph::cert_add_redundant(const unsigned int v1, const unsigned int v2, const unsigned int v3) { return cert_add(v1, v2, v3); } /*------------------------------------------------------------------------- * * Long prune code * *-------------------------------------------------------------------------*/ void AbstractGraph::long_prune_init() { const unsigned int N = get_nof_vertices(); long_prune_temp.clear(); long_prune_temp.resize(N); /* Of how many automorphisms we can store information in the predefined, fixed amount of memory? */ const unsigned int nof_fitting_in_max_mem = (long_prune_options_max_mem * 1024 * 1024) / (((N * 2) / 8)+1); long_prune_max_stored_autss = long_prune_options_max_stored_auts; /* Had some problems with g++ in using (a* tmp = long_prune_fixed[real_i]; long_prune_fixed[real_i] = long_prune_fixed[real_j]; long_prune_fixed[real_j] = tmp; tmp = long_prune_mcrs[real_i]; long_prune_mcrs[real_i] = long_prune_mcrs[real_j]; long_prune_mcrs[real_j] = tmp; } std::vector& AbstractGraph::long_prune_allocget_fixed(const unsigned int index) { const unsigned int i = index % long_prune_max_stored_autss; if(!long_prune_fixed[i]) long_prune_fixed[i] = new std::vector(get_nof_vertices()); return *long_prune_fixed[i]; } std::vector& AbstractGraph::long_prune_get_fixed(const unsigned int index) { return *long_prune_fixed[index % long_prune_max_stored_autss]; } std::vector& AbstractGraph::long_prune_allocget_mcrs(const unsigned int index) { const unsigned int i = index % long_prune_max_stored_autss; if(!long_prune_mcrs[i]) long_prune_mcrs[i] = new std::vector(get_nof_vertices()); return *long_prune_mcrs[i]; } std::vector& AbstractGraph::long_prune_get_mcrs(const unsigned int index) { return *long_prune_mcrs[index % long_prune_max_stored_autss]; } void AbstractGraph::long_prune_add_automorphism(const unsigned int* aut) { if(long_prune_max_stored_autss == 0) return; const unsigned int N = get_nof_vertices(); /* If the buffer of stored auts is full, remove the oldest aut */ if(long_prune_end - long_prune_begin == long_prune_max_stored_autss) { long_prune_begin++; } long_prune_end++; std::vector& fixed = long_prune_allocget_fixed(long_prune_end-1); std::vector& mcrs = long_prune_allocget_mcrs(long_prune_end-1); /* Mark nodes that are (i) fixed or (ii) minimal orbit representatives * under the automorphism 'aut' */ for(unsigned int i = 0; i < N; i++) { fixed[i] = (aut[i] == i); if(long_prune_temp[i] == false) { mcrs[i] = true; unsigned int j = aut[i]; while(j != i) { long_prune_temp[j] = true; j = aut[j]; } } else { mcrs[i] = false; } /* Clear the temp array on-the-fly... */ long_prune_temp[i] = false; } } /*------------------------------------------------------------------------- * * Routines for handling orbit information * *-------------------------------------------------------------------------*/ void AbstractGraph::update_orbit_information(Orbit& o, const unsigned int* perm) { const unsigned int N = get_nof_vertices(); for(unsigned int i = 0; i < N; i++) if(perm[i] != i) o.merge_orbits(i, perm[i]); } /*------------------------------------------------------------------------- * * The actual backtracking search * *-------------------------------------------------------------------------*/ class TreeNode { //friend class AbstractGraph; public: unsigned int split_cell_first; int split_element; static const int SPLIT_START = -1; static const int SPLIT_END = -2; Partition::BacktrackPoint partition_bt_point; unsigned int certificate_index; static const char NO = -1; static const char MAYBE = 0; static const char YES = 1; /* First path stuff */ bool fp_on; bool fp_cert_equal; char fp_extendable; /* Best path stuff */ bool in_best_path; int cmp_to_best_path; unsigned int failure_recording_ival; /* Component recursion related data */ unsigned int cr_cep_stack_size; unsigned int cr_cep_index; unsigned int cr_level; bool needs_long_prune = false; unsigned int long_prune_begin; std::set > long_prune_redundant; UintSeqHash eqref_hash; unsigned int subcertificate_length; }; typedef struct { unsigned int splitting_element; unsigned int certificate_index; unsigned int subcertificate_length; UintSeqHash eqref_hash; } PathInfo; void AbstractGraph::search(const bool canonical, Stats& stats) { const unsigned int N = get_nof_vertices(); unsigned int all_same_level = UINT_MAX; p.graph = this; /* * Must be done! */ remove_duplicate_edges(); /* * Reset search statistics */ stats.reset(); stats.nof_nodes = 1; stats.nof_leaf_nodes = 1; /* Free old first path data structures */ if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(first_path_labeling_inv) { free(first_path_labeling_inv); first_path_labeling_inv = 0; } if(first_path_automorphism) { free(first_path_automorphism); first_path_automorphism = 0; } /* Free old best path data structures */ if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } if(best_path_labeling_inv) { free(best_path_labeling_inv); best_path_labeling_inv = 0; } if(best_path_automorphism) { free(best_path_automorphism); best_path_automorphism = 0; } if(N == 0) { /* Nothing to do, return... */ return; } /* Initialize the partition ... */ p.init(N); /* ... and the component recursion data structures in the partition */ if(opt_use_comprec) p.cr_init(); neighbour_heap.init(N); in_search = false; /* Do not compute certificate when building the initial partition */ refine_compare_certificate = false; /* The 'eqref_hash' hash value is not computed when building * the initial partition as it is not used for anything at the moment. * This saves some cycles. */ compute_eqref_hash = false; make_initial_equitable_partition(); /* * Allocate space for the "first path" and "best path" labelings */ if(first_path_labeling) free(first_path_labeling); first_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int)); if(!first_path_labeling) _OUT_OF_MEMORY(); if(best_path_labeling) free(best_path_labeling); best_path_labeling = (unsigned int*)calloc(N, sizeof(unsigned int)); if(!best_path_labeling) _OUT_OF_MEMORY(); /* * Is the initial partition discrete? */ if(p.is_discrete()) { /* Make the best path labeling i.e. the canonical labeling */ update_labeling(best_path_labeling); /* Update statistics */ stats.nof_leaf_nodes = 1; /* Free component recursion data */ if(opt_use_comprec) p.cr_free(); return; } /* * Allocate the inverses of the "first path" and "best path" labelings */ if(first_path_labeling_inv) free(first_path_labeling_inv); first_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int)); if(!first_path_labeling_inv) _OUT_OF_MEMORY(); if(best_path_labeling_inv) free(best_path_labeling_inv); best_path_labeling_inv = (unsigned int*)calloc(N, sizeof(unsigned int)); if(!best_path_labeling_inv) _OUT_OF_MEMORY(); /* * Allocate space for the automorphisms */ if(first_path_automorphism) free(first_path_automorphism); first_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int)); if(!first_path_automorphism) _OUT_OF_MEMORY(); if(best_path_automorphism) free(best_path_automorphism); best_path_automorphism = (unsigned int*)malloc(N * sizeof(unsigned int)); if(!best_path_automorphism) _OUT_OF_MEMORY(); /* * Initialize orbit information so that all vertices are in their own orbits */ first_path_orbits.init(N); best_path_orbits.init(N); /* * Initialize certificate memory */ initialize_certificate(); std::vector search_stack; std::vector first_path_info; std::vector best_path_info; search_stack.clear(); /* Initialize "long prune" data structures */ if(opt_use_long_prune) long_prune_init(); /* * Initialize failure recording data structures */ typedef std::set > FailureRecordingSet; std::vector failure_recording_hashes; /* * Initialize component recursion data structures */ cr_cep_stack.clear(); unsigned int cr_cep_index = 0; { /* Inset a sentinel "component end point" */ CR_CEP sentinel; sentinel.creation_level = 0; sentinel.discrete_cell_limit = get_nof_vertices(); sentinel.next_cr_level = 0; sentinel.next_cep_index = 0; sentinel.first_checked = false; sentinel.best_checked = false; cr_cep_index = 0; cr_cep_stack.push_back(sentinel); } cr_level = 0; if(opt_use_comprec and nucr_find_first_component(cr_level) == true and p.nof_discrete_cells() + cr_component_elements < cr_cep_stack[cr_cep_index].discrete_cell_limit) { cr_level = p.cr_split_level(0, cr_component); CR_CEP cep; cep.creation_level = 0; cep.discrete_cell_limit = p.nof_discrete_cells() + cr_component_elements; cep.next_cr_level = 0; cep.next_cep_index = cr_cep_index; cep.first_checked = false; cep.best_checked = false; cr_cep_index = cr_cep_stack.size(); cr_cep_stack.push_back(cep); } /* * Build the root node of the search tree */ { TreeNode root; Partition::Cell* split_cell = find_next_cell_to_be_splitted(p.first_cell); root.split_cell_first = split_cell->first; root.split_element = TreeNode::SPLIT_START; root.partition_bt_point = p.set_backtrack_point(); root.certificate_index = 0; root.fp_on = true; root.fp_cert_equal = true; root.fp_extendable = TreeNode::MAYBE; root.in_best_path = false; root.cmp_to_best_path = 0; root.long_prune_begin = 0; root.failure_recording_ival = 0; /* Save component recursion info for backtracking */ root.cr_level = cr_level; root.cr_cep_stack_size = cr_cep_stack.size(); root.cr_cep_index = cr_cep_index; search_stack.push_back(root); } /* * Set status and global flags for search related procedures */ in_search = true; /* Do not compare certificates during refinement until the first path has been traversed to the leaf */ refine_compare_certificate = false; /* * The actual backtracking search */ while(!search_stack.empty()) { TreeNode& current_node = search_stack.back(); const unsigned int current_level = (unsigned int)search_stack.size()-1; if(opt_use_comprec) { CR_CEP& cep = cr_cep_stack[current_node.cr_cep_index]; if(cep.first_checked == true and current_node.fp_extendable == TreeNode::MAYBE and !search_stack[cep.creation_level].fp_on) { current_node.fp_extendable = TreeNode::NO; } } if(current_node.fp_on) { if(current_node.split_element == TreeNode::SPLIT_END) { search_stack.pop_back(); continue; } } else { if(current_node.fp_extendable == TreeNode::YES) { search_stack.pop_back(); continue; } if(current_node.split_element == TreeNode::SPLIT_END) { if(opt_use_failure_recording) { TreeNode& parent_node = search_stack[current_level-1]; if(parent_node.fp_on) failure_recording_hashes[current_level-1].insert(current_node.failure_recording_ival); } search_stack.pop_back(); continue; } if(current_node.fp_extendable == TreeNode::NO and (!canonical or current_node.cmp_to_best_path < 0)) { if(opt_use_failure_recording) { TreeNode& parent_node = search_stack[current_level-1]; if(parent_node.fp_on) failure_recording_hashes[current_level-1].insert(current_node.failure_recording_ival); } search_stack.pop_back(); continue; } } /* Restore partition ... */ p.goto_backtrack_point(current_node.partition_bt_point); /* ... and re-remember backtracking point */ current_node.partition_bt_point = p.set_backtrack_point(); /* Restore current path certificate */ certificate_index = current_node.certificate_index; refine_current_path_certificate_index = current_node.certificate_index; certificate_current_path.resize(certificate_index); /* Fetch split cell information */ Partition::Cell * const cell = p.get_cell(p.elements[current_node.split_cell_first]); /* Restore component recursion information */ cr_level = current_node.cr_level; cr_cep_stack.resize(current_node.cr_cep_stack_size); cr_cep_index = current_node.cr_cep_index; /* * Update long prune redundancy sets */ if(opt_use_long_prune and current_level >= 1 and !current_node.fp_on) { unsigned int begin = (current_node.long_prune_begin>long_prune_begin)?current_node.long_prune_begin:long_prune_begin; for(unsigned int i = begin; i < long_prune_end; i++) { const std::vector& fixed = long_prune_get_fixed(i); #if defined(BLISS_CONSISTENCY_CHECKS) for(unsigned int l = 0; l < search_stack.size()-2; l++) assert(fixed[search_stack[l].split_element]); #endif if(fixed[search_stack[search_stack.size()-1-1].split_element] == false) { long_prune_swap(begin, i); begin++; current_node.long_prune_begin = begin; continue; } } if(current_node.split_element == TreeNode::SPLIT_START) { current_node.needs_long_prune = true; } else if(current_node.needs_long_prune) { current_node.needs_long_prune = false; unsigned int begin = (current_node.long_prune_begin>long_prune_begin)?current_node.long_prune_begin:long_prune_begin; for(unsigned int i = begin; i < long_prune_end; i++) { const std::vector& fixed = long_prune_get_fixed(i); #if defined(BLISS_CONSISTENCY_CHECKS) for(unsigned int l = 0; l < search_stack.size()-2; l++) assert(fixed[search_stack[l].split_element]); #endif assert(fixed[search_stack[current_level-1].split_element] == true); if(fixed[search_stack[current_level-1].split_element] == false) { long_prune_swap(begin, i); begin++; current_node.long_prune_begin = begin; continue; } const std::vector& mcrs = long_prune_get_mcrs(i); unsigned int* ep = p.elements + cell->first; for(unsigned int j = cell->length; j > 0; j--, ep++) { if(mcrs[*ep] == false) current_node.long_prune_redundant.insert(*ep); } } } } /* * Find the next smallest, non-isomorphic element in the cell and * store it in current_node.split_element */ { unsigned int next_split_element = UINT_MAX; //unsigned int* next_split_element_pos = 0; unsigned int* ep = p.elements + cell->first; if(current_node.fp_on) { /* Find the next larger splitting element that is * a minimal orbit representative w.r.t. first_path_orbits */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > current_node.split_element and *ep < next_split_element and first_path_orbits.is_minimal_representative(*ep)) { next_split_element = *ep; //next_split_element_pos = ep; } } } else if(current_node.in_best_path) { /* Find the next larger splitting element that is * a minimal orbit representative w.r.t. best_path_orbits */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > current_node.split_element and *ep < next_split_element and best_path_orbits.is_minimal_representative(*ep) and (!opt_use_long_prune or current_node.long_prune_redundant.find(*ep) == current_node.long_prune_redundant.end())) { next_split_element = *ep; //next_split_element_pos = ep; } } } else { /* Find the next larger splitting element */ for(unsigned int i = cell->length; i > 0; i--, ep++) { if((int)(*ep) > current_node.split_element and *ep < next_split_element and (!opt_use_long_prune or current_node.long_prune_redundant.find(*ep) == current_node.long_prune_redundant.end())) { next_split_element = *ep; //next_split_element_pos = ep; } } } if(next_split_element == UINT_MAX) { /* No more (unexplored children) in the cell */ current_node.split_element = TreeNode::SPLIT_END; if(current_node.fp_on) { /* Update group size */ const unsigned int index = first_path_orbits.orbit_size(first_path_info[search_stack.size()-1].splitting_element); stats.group_size.multiply(index); stats.group_size_approx *= (long double)index; /* * Update all_same_level */ if(index == cell->length and all_same_level == current_level+1) all_same_level = current_level; if(verbstr and verbose_level >= 2) { fprintf(verbstr, "Level %u: orbits=%u, index=%u/%u, all_same_level=%u\n", current_level, first_path_orbits.nof_orbits(), index, cell->length, all_same_level); fflush(verbstr); } } continue; } /* Split on smallest */ current_node.split_element = next_split_element; } const unsigned int child_level = current_level+1; /* Update some statistics */ stats.nof_nodes++; if(search_stack.size() > stats.max_level) stats.max_level = search_stack.size(); /* Set flags and indices for the refiner certificate builder */ refine_equal_to_first = current_node.fp_cert_equal; refine_cmp_to_best = current_node.cmp_to_best_path; if(!first_path_info.empty()) { if(refine_equal_to_first) refine_first_path_subcertificate_end = first_path_info[search_stack.size()-1].certificate_index + first_path_info[search_stack.size()-1].subcertificate_length; if(canonical) { if(refine_cmp_to_best == 0) refine_best_path_subcertificate_end = best_path_info[search_stack.size()-1].certificate_index + best_path_info[search_stack.size()-1].subcertificate_length; } else refine_cmp_to_best = -1; } const bool was_fp_cert_equal = current_node.fp_cert_equal; /* Individualize, i.e. split the cell in two, the latter new cell * will be a unit one containing info.split_element */ Partition::Cell* const new_cell = p.individualize(cell, current_node.split_element); /* * Refine the new partition to equitable */ if(cell->is_unit()) refine_to_equitable(cell, new_cell); else refine_to_equitable(new_cell); /* Update statistics */ if(p.is_discrete()) stats.nof_leaf_nodes++; if(!first_path_info.empty()) { /* We are no longer on the first path */ const unsigned int subcertificate_length = certificate_current_path.size() - certificate_index; if(refine_equal_to_first) { /* Was equal to the first path so far */ PathInfo& first_pinfo = first_path_info[current_level]; assert(first_pinfo.certificate_index == certificate_index); if(subcertificate_length != first_pinfo.subcertificate_length) { refine_equal_to_first = false; if(opt_use_failure_recording) failure_recording_fp_deviation = subcertificate_length; } else if(first_pinfo.eqref_hash.cmp(eqref_hash) != 0) { refine_equal_to_first = false; if(opt_use_failure_recording) failure_recording_fp_deviation = eqref_hash.get_value(); } } if(canonical and (refine_cmp_to_best == 0)) { /* Was equal to the best path so far */ PathInfo& bestp_info = best_path_info[current_level]; assert(bestp_info.certificate_index == certificate_index); if(subcertificate_length < bestp_info.subcertificate_length) { refine_cmp_to_best = -1; } else if(subcertificate_length > bestp_info.subcertificate_length) { refine_cmp_to_best = 1; } else if(bestp_info.eqref_hash.cmp(eqref_hash) > 0) { refine_cmp_to_best = -1; } else if(bestp_info.eqref_hash.cmp(eqref_hash) < 0) { refine_cmp_to_best = 1; } } if(opt_use_failure_recording and was_fp_cert_equal and !refine_equal_to_first) { UintSeqHash k; k.update(failure_recording_fp_deviation); k.update(eqref_hash.get_value()); failure_recording_fp_deviation = k.get_value(); if(current_node.fp_on) failure_recording_hashes[current_level].insert(failure_recording_fp_deviation); else { for(unsigned int i = current_level; i > 0; i--) { if(search_stack[i].fp_on) break; const FailureRecordingSet& s = failure_recording_hashes[i]; if(i == current_level and s.find(failure_recording_fp_deviation) != s.end()) break; if(s.find(0) != s.end()) break; search_stack[i].fp_extendable = TreeNode::NO; } } } /* Check if no longer equal to the first path and, * if canonical labeling is desired, also worse than the * current best path */ if(refine_equal_to_first == false and (!canonical or (refine_cmp_to_best < 0))) { /* Yes, backtrack */ stats.nof_bad_nodes++; if(current_node.fp_cert_equal == true and current_level+1 > all_same_level) { assert(all_same_level >= 1); for(unsigned int i = all_same_level; i < search_stack.size(); i++) { search_stack[i].fp_extendable = TreeNode::NO; } } continue; } } #if defined(BLISS_VERIFY_EQUITABLEDNESS) /* The new partition should be equitable */ if(!is_equitable()) fatal_error("consistency check failed - partition after refinement is not equitable"); #endif /* * Next level search tree node info */ TreeNode child_node; /* No more in the first path */ child_node.fp_on = false; /* No more in the best path */ child_node.in_best_path = false; child_node.fp_cert_equal = refine_equal_to_first; if(current_node.fp_extendable == TreeNode::NO or (current_node.fp_extendable == TreeNode::MAYBE and child_node.fp_cert_equal == false)) child_node.fp_extendable = TreeNode::NO; else child_node.fp_extendable = TreeNode::MAYBE; child_node.cmp_to_best_path = refine_cmp_to_best; child_node.failure_recording_ival = 0; child_node.cr_cep_stack_size = current_node.cr_cep_stack_size; child_node.cr_cep_index = current_node.cr_cep_index; child_node.cr_level = current_node.cr_level; certificate_index = certificate_current_path.size(); current_node.eqref_hash = eqref_hash; current_node.subcertificate_length = certificate_index - current_node.certificate_index; /* * The first encountered leaf node at the end of the "first path"? */ if(p.is_discrete() and first_path_info.empty()) { //fprintf(stdout, "Level %u: FIRST\n", child_level); fflush(stdout); stats.nof_canupdates++; /* * Update labelings and their inverses */ update_labeling_and_its_inverse(first_path_labeling, first_path_labeling_inv); update_labeling_and_its_inverse(best_path_labeling, best_path_labeling_inv); /* * Reset automorphism array */ reset_permutation(first_path_automorphism); reset_permutation(best_path_automorphism); /* * Reset orbit information */ first_path_orbits.reset(); best_path_orbits.reset(); /* * Reset group size */ stats.group_size.assign(1); stats.group_size_approx = 1.0; /* * Reset all_same_level */ all_same_level = child_level; /* * Mark the current path to be the first and best one and save it */ const unsigned int base_size = search_stack.size(); best_path_info.clear(); //fprintf(stdout, " New base is: "); for(unsigned int i = 0; i < base_size; i++) { search_stack[i].fp_on = true; search_stack[i].fp_cert_equal = true; search_stack[i].fp_extendable = TreeNode::YES; search_stack[i].in_best_path = true; search_stack[i].cmp_to_best_path = 0; PathInfo path_info; path_info.splitting_element = search_stack[i].split_element; path_info.certificate_index = search_stack[i].certificate_index; path_info.eqref_hash = search_stack[i].eqref_hash; path_info.subcertificate_length = search_stack[i].subcertificate_length; first_path_info.push_back(path_info); best_path_info.push_back(path_info); //fprintf(stdout, "%u ", search_stack[i].split_element); } //fprintf(stdout, "\n"); fflush(stdout); /* Copy certificates */ certificate_first_path = certificate_current_path; certificate_best_path = certificate_current_path; /* From now on, compare certificates when refining */ refine_compare_certificate = true; if(opt_use_failure_recording) failure_recording_hashes.resize(base_size); /* for(unsigned int j = 0; j < search_stack.size(); j++) fprintf(stderr, "%u ", search_stack[j].split_element); fprintf(stderr, "\n"); p.print(stderr); fprintf(stderr, "\n"); */ /* * Backtrack to the previous level */ continue; } if(p.is_discrete() and child_node.fp_cert_equal) { /* * A leaf node that is equal to the first one. * An automorphism found: aut[i] = elements[first_path_labeling[i]] */ goto handle_first_path_automorphism; } if(!p.is_discrete()) { Partition::Cell* next_split_cell = 0; /* * An internal, non-leaf node */ if(opt_use_comprec) { assert(p.nof_discrete_cells() <= cr_cep_stack[cr_cep_index].discrete_cell_limit); assert(cr_level == child_node.cr_level); if(p.nof_discrete_cells() == cr_cep_stack[cr_cep_index].discrete_cell_limit) { /* We have reached the end of a component */ assert(cr_cep_index != 0); CR_CEP& cep = cr_cep_stack[cr_cep_index]; /* First, compare with respect to the first path */ if(first_path_info.empty() or child_node.fp_cert_equal) { if(cep.first_checked == false) { /* First time, go to the next component */ cep.first_checked = true; } else { assert(!first_path_info.empty()); assert(cep.creation_level < search_stack.size()); TreeNode& old_info = search_stack[cep.creation_level]; /* If the component was found when on the first path, * handle the found automorphism as the other * first path automorphisms */ if(old_info.fp_on) goto handle_first_path_automorphism; } } if(canonical and !first_path_info.empty() and child_node.cmp_to_best_path >= 0) { if(cep.best_checked == false) { /* First time, go to the next component */ cep.best_checked = true; } else { assert(cep.creation_level < search_stack.size()); TreeNode& old_info = search_stack[cep.creation_level]; if(child_node.cmp_to_best_path == 0) { /* If the component was found when on the best path, * handle the found automorphism as the other * best path automorphisms */ if(old_info.in_best_path) goto handle_best_path_automorphism; /* Otherwise, we do not remember the automorhism as * we didn't memorize the path that was invariant * equal to the best one and passed through the * component. * Thus we can only backtrack to the previous level */ child_node.cmp_to_best_path = -1; if(!child_node.fp_cert_equal) { continue; } } else { assert(child_node.cmp_to_best_path > 0); if(old_info.in_best_path) { stats.nof_canupdates++; /* * Update canonical labeling and its inverse */ for(unsigned int i = 0; i < N; i++) { if(p.get_cell(p.elements[i])->is_unit()) { best_path_labeling[p.elements[i]] = i; best_path_labeling_inv[i] = p.elements[i]; } } //update_labeling_and_its_inverse(best_path_labeling, best_path_labeling_inv); /* Reset best path automorphism */ reset_permutation(best_path_automorphism); /* Reset best path orbit structure */ best_path_orbits.reset(); /* Mark to be the best one and save prefix */ unsigned int postfix_start = cep.creation_level; assert(postfix_start < best_path_info.size()); while(p.get_cell(best_path_info[postfix_start].splitting_element)->is_unit()) { postfix_start++; assert(postfix_start < best_path_info.size()); } unsigned int postfix_start_cert = best_path_info[postfix_start].certificate_index; std::vector best_path_temp = best_path_info; best_path_info.clear(); for(unsigned int i = 0; i < search_stack.size(); i++) { TreeNode& ss_info = search_stack[i]; PathInfo bp_info; ss_info.cmp_to_best_path = 0; ss_info.in_best_path = true; bp_info.splitting_element = ss_info.split_element; bp_info.certificate_index = ss_info.certificate_index; bp_info.subcertificate_length = ss_info.subcertificate_length; bp_info.eqref_hash = ss_info.eqref_hash; best_path_info.push_back(bp_info); } /* Copy the postfix of the previous best path */ for(unsigned int i = postfix_start; i < best_path_temp.size(); i++) { best_path_info.push_back(best_path_temp[i]); best_path_info[best_path_info.size()-1].certificate_index = best_path_info[best_path_info.size()-2].certificate_index + best_path_info[best_path_info.size()-2].subcertificate_length; } std::vector certificate_best_path_old = certificate_best_path; certificate_best_path = certificate_current_path; for(unsigned int i = postfix_start_cert; i < certificate_best_path_old.size(); i++) certificate_best_path.push_back(certificate_best_path_old[i]); assert(certificate_best_path.size() == best_path_info.back().certificate_index + best_path_info.back().subcertificate_length); /* Backtrack to the previous level */ continue; } } } } /* No backtracking performed, go to next componenet */ cr_level = cep.next_cr_level; cr_cep_index = cep.next_cep_index; } /* Check if the current component has been split into * new non-uniformity subcomponents */ //if(nucr_find_first_component(cr_level) == true and // p.nof_discrete_cells() + cr_component_elements < // cr_cep_stack[cr_cep_index].discrete_cell_limit) if(nucr_find_first_component(cr_level, cr_component, cr_component_elements, next_split_cell) == true and p.nof_discrete_cells() + cr_component_elements < cr_cep_stack[cr_cep_index].discrete_cell_limit) { const unsigned int next_cr_level = p.cr_split_level(cr_level, cr_component); CR_CEP cep; cep.creation_level = search_stack.size(); cep.discrete_cell_limit = p.nof_discrete_cells() + cr_component_elements; cep.next_cr_level = cr_level; cep.next_cep_index = cr_cep_index; cep.first_checked = false; cep.best_checked = false; cr_cep_index = cr_cep_stack.size(); cr_cep_stack.push_back(cep); cr_level = next_cr_level; } } /* * Build the next node info */ /* Find the next cell to be splitted */ if(!next_split_cell) next_split_cell = find_next_cell_to_be_splitted(p.get_cell(p.elements[current_node.split_cell_first])); //Partition::Cell * const next_split_cell = find_next_cell_to_be_splitted(p.get_cell(p.elements[current_node.split_cell_first])); child_node.split_cell_first = next_split_cell->first; child_node.split_element = TreeNode::SPLIT_START; child_node.certificate_index = certificate_index; child_node.partition_bt_point = p.set_backtrack_point(); child_node.long_prune_redundant.clear(); child_node.long_prune_begin = current_node.long_prune_begin; /* Save component recursion info for backtracking */ child_node.cr_level = cr_level; child_node.cr_cep_stack_size = cr_cep_stack.size(); child_node.cr_cep_index = cr_cep_index; search_stack.push_back(child_node); continue; } /* * A leaf node not in the first path or equivalent to the first path */ if(child_node.cmp_to_best_path > 0) { /* * A new, better representative found */ //fprintf(stdout, "Level %u: NEW BEST\n", child_level); fflush(stdout); stats.nof_canupdates++; /* * Update canonical labeling and its inverse */ update_labeling_and_its_inverse(best_path_labeling, best_path_labeling_inv); /* Reset best path automorphism */ reset_permutation(best_path_automorphism); /* Reset best path orbit structure */ best_path_orbits.reset(); /* * Mark the current path to be the best one and save it */ const unsigned int base_size = search_stack.size(); assert(current_level+1 == base_size); best_path_info.clear(); for(unsigned int i = 0; i < base_size; i++) { search_stack[i].cmp_to_best_path = 0; search_stack[i].in_best_path = true; PathInfo path_info; path_info.splitting_element = search_stack[i].split_element; path_info.certificate_index = search_stack[i].certificate_index; path_info.subcertificate_length = search_stack[i].subcertificate_length; path_info.eqref_hash = search_stack[i].eqref_hash; best_path_info.push_back(path_info); } certificate_best_path = certificate_current_path; /* * Backtrack to the previous level */ continue; } handle_best_path_automorphism: /* * * Best path automorphism handling * */ { /* * Equal to the previous best path */ if(p.is_discrete()) { #if defined(BLISS_CONSISTENCY_CHECKS) /* Verify that the automorphism is correctly built */ for(unsigned int i = 0; i < N; i++) assert(best_path_automorphism[i] == p.elements[best_path_labeling[i]]); #endif } else { /* An automorphism that was found before the partition was discrete. * Set the image of all elements in non-disrete cells accordingly */ for(Partition::Cell* c = p.first_nonsingleton_cell; c; c = c->next_nonsingleton) { for(unsigned int i = c->first; i < c->first+c->length; i++) if(p.get_cell(p.elements[best_path_labeling[p.elements[i]]])->is_unit()) best_path_automorphism[p.elements[best_path_labeling[p.elements[i]]]] = p.elements[i]; else best_path_automorphism[p.elements[i]] = p.elements[i]; } } #if defined(BLISS_VERIFY_AUTOMORPHISMS) /* Verify that it really is an automorphism */ if(!is_automorphism(best_path_automorphism)) fatal_error("Best path automorhism validation check failed"); #endif unsigned int gca_level_with_first = 0; for(unsigned int i = search_stack.size(); i > 0; i--) { if((int)first_path_info[gca_level_with_first].splitting_element != search_stack[gca_level_with_first].split_element) break; gca_level_with_first++; } unsigned int gca_level_with_best = 0; for(unsigned int i = search_stack.size(); i > 0; i--) { if((int)best_path_info[gca_level_with_best].splitting_element != search_stack[gca_level_with_best].split_element) break; gca_level_with_best++; } if(opt_use_long_prune) { /* Record automorphism */ long_prune_add_automorphism(best_path_automorphism); } /* * Update orbit information */ update_orbit_information(best_path_orbits, best_path_automorphism); /* * Update orbit information */ const unsigned int nof_old_orbits = first_path_orbits.nof_orbits(); update_orbit_information(first_path_orbits, best_path_automorphism); if(nof_old_orbits != first_path_orbits.nof_orbits()) { /* Some orbits were merged */ /* Report automorphism */ if(report_hook) (*report_hook)(report_user_param, get_nof_vertices(), best_path_automorphism); /* Update statistics */ stats.nof_generators++; } /* * Compute backjumping level */ unsigned int backjumping_level = current_level+1-1; if(!first_path_orbits.is_minimal_representative(search_stack[gca_level_with_first].split_element)) { backjumping_level = gca_level_with_first; } else { assert(!best_path_orbits.is_minimal_representative(search_stack[gca_level_with_best].split_element)); backjumping_level = gca_level_with_best; } /* Backtrack */ search_stack.resize(backjumping_level + 1); continue; } _INTERNAL_ERROR(); handle_first_path_automorphism: /* * * A first-path automorphism: aut[i] = elements[first_path_labeling[i]] * */ if(p.is_discrete()) { #if defined(BLISS_CONSISTENCY_CHECKS) /* Verify that the complete automorphism is correctly built */ for(unsigned int i = 0; i < N; i++) assert(first_path_automorphism[i] == p.elements[first_path_labeling[i]]); #endif } else { /* An automorphism that was found before the partition was discrete. * Set the image of all elements in non-disrete cells accordingly */ for(Partition::Cell* c = p.first_nonsingleton_cell; c; c = c->next_nonsingleton) { for(unsigned int i = c->first; i < c->first+c->length; i++) if(p.get_cell(p.elements[first_path_labeling[p.elements[i]]])->is_unit()) first_path_automorphism[p.elements[first_path_labeling[p.elements[i]]]] = p.elements[i]; else first_path_automorphism[p.elements[i]] = p.elements[i]; } } #if defined(BLISS_VERIFY_AUTOMORPHISMS) /* Verify that it really is an automorphism */ if(!is_automorphism(first_path_automorphism)) fatal_error("First path automorphism validation check failed"); #endif if(opt_use_long_prune) { long_prune_add_automorphism(first_path_automorphism); } /* * Update orbit information */ update_orbit_information(first_path_orbits, first_path_automorphism); /* * Compute backjumping level */ for(unsigned int i = 0; i < search_stack.size(); i++) { TreeNode& n = search_stack[i]; if(n.fp_on) { ; } else { n.fp_extendable = TreeNode::YES; } } /* Report automorphism by calling the user defined hook function */ if(report_hook) (*report_hook)(report_user_param, get_nof_vertices(), first_path_automorphism); /* Update statistics */ stats.nof_generators++; continue; } /* while(!search_stack.empty()) */ /* Free "long prune" technique memory */ if(opt_use_long_prune) long_prune_deallocate(); /* Release component recursion data in partition */ if(opt_use_comprec) p.cr_free(); } void AbstractGraph::find_automorphisms(Stats& stats, void (*hook)(void *user_param, unsigned int n, const unsigned int *aut), void *user_param) { report_hook = hook; report_user_param = user_param; search(false, stats); if(first_path_labeling) { free(first_path_labeling); first_path_labeling = 0; } if(best_path_labeling) { free(best_path_labeling); best_path_labeling = 0; } } const unsigned int * AbstractGraph::canonical_form(Stats& stats, void (*hook)(void *user_param, unsigned int n, const unsigned int *aut), void *user_param) { report_hook = hook; report_user_param = user_param; search(true, stats); return best_path_labeling; } /*------------------------------------------------------------------------- * * Routines for directed graphs * *-------------------------------------------------------------------------*/ Digraph::Vertex::Vertex() { color = 0; } Digraph::Vertex::~Vertex() { ; } void Digraph::Vertex::add_edge_to(const unsigned int other_vertex) { edges_out.push_back(other_vertex); } void Digraph::Vertex::add_edge_from(const unsigned int other_vertex) { edges_in.push_back(other_vertex); } void Digraph::Vertex::remove_duplicate_edges(std::vector& tmp) { #if defined(BLISS_CONSISTENCY_CHECKS) /* Pre-conditions */ for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif for(std::vector::iterator iter = edges_out.begin(); iter != edges_out.end(); ) { const unsigned int dest_vertex = *iter; if(tmp[dest_vertex] == true) { /* A duplicate edge found! */ iter = edges_out.erase(iter); } else { /* Not seen earlier, mark as seen */ tmp[dest_vertex] = true; iter++; } } /* Clear tmp */ for(std::vector::iterator iter = edges_out.begin(); iter != edges_out.end(); iter++) { tmp[*iter] = false; } for(std::vector::iterator iter = edges_in.begin(); iter != edges_in.end(); ) { const unsigned int dest_vertex = *iter; if(tmp[dest_vertex] == true) { /* A duplicate edge found! */ iter = edges_in.erase(iter); } else { /* Not seen earlier, mark as seen */ tmp[dest_vertex] = true; iter++; } } /* Clear tmp */ for(std::vector::iterator iter = edges_in.begin(); iter != edges_in.end(); iter++) { tmp[*iter] = false; } #if defined(BLISS_CONSISTENCY_CHECKS) /* Post-conditions */ for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif } /** * Sort the edges entering and leaving the vertex according to * the vertex number of the other edge end. * Time complexity: O(e log(e)), where e is the number of edges * entering/leaving the vertex. */ void Digraph::Vertex::sort_edges() { std::sort(edges_in.begin(), edges_in.end()); std::sort(edges_out.begin(), edges_out.end()); } /*------------------------------------------------------------------------- * * Constructor and destructor for directed graphs * *-------------------------------------------------------------------------*/ Digraph::Digraph(const unsigned int nof_vertices) { vertices.resize(nof_vertices); sh = shs_flm; } Digraph::~Digraph() { ; } unsigned int Digraph::add_vertex(const unsigned int color) { const unsigned int new_vertex_num = vertices.size(); vertices.resize(new_vertex_num + 1); vertices.back().color = color; return new_vertex_num; } void Digraph::add_edge(const unsigned int vertex1, const unsigned int vertex2) { assert(vertex1 < get_nof_vertices()); assert(vertex2 < get_nof_vertices()); vertices[vertex1].add_edge_to(vertex2); vertices[vertex2].add_edge_from(vertex1); } void Digraph::change_color(const unsigned int vertex, const unsigned int new_color) { assert(vertex < get_nof_vertices()); vertices[vertex].color = new_color; } void Digraph::sort_edges() { for(unsigned int i = 0; i < get_nof_vertices(); i++) vertices[i].sort_edges(); } int Digraph::cmp(Digraph& other) { /* Compare the numbers of vertices */ if(get_nof_vertices() < other.get_nof_vertices()) return -1; if(get_nof_vertices() > other.get_nof_vertices()) return 1; /* Compare vertex colors */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { if(vertices[i].color < other.vertices[i].color) return -1; if(vertices[i].color > other.vertices[i].color) return 1; } /* Compare vertex degrees */ remove_duplicate_edges(); other.remove_duplicate_edges(); for(unsigned int i = 0; i < get_nof_vertices(); i++) { if(vertices[i].nof_edges_in() < other.vertices[i].nof_edges_in()) return -1; if(vertices[i].nof_edges_in() > other.vertices[i].nof_edges_in()) return 1; if(vertices[i].nof_edges_out() < other.vertices[i].nof_edges_out()) return -1; if(vertices[i].nof_edges_out() > other.vertices[i].nof_edges_out()) return 1; } /* Compare edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex& v1 = vertices[i]; Vertex& v2 = other.vertices[i]; v1.sort_edges(); v2.sort_edges(); std::vector::const_iterator ei1 = v1.edges_in.begin(); std::vector::const_iterator ei2 = v2.edges_in.begin(); while(ei1 != v1.edges_in.end()) { if(*ei1 < *ei2) return -1; if(*ei1 > *ei2) return 1; ei1++; ei2++; } ei1 = v1.edges_out.begin(); ei2 = v2.edges_out.begin(); while(ei1 != v1.edges_out.end()) { if(*ei1 < *ei2) return -1; if(*ei1 > *ei2) return 1; ei1++; ei2++; } } return 0; } Digraph* Digraph::permute(const std::vector& perm) const { Digraph* const g = new Digraph(get_nof_vertices()); for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex& v = vertices[i]; g->change_color(perm[i], v.color); for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { g->add_edge(perm[i], perm[*ei]); } } g->sort_edges(); return g; } Digraph* Digraph::permute(const unsigned int* const perm) const { Digraph* const g = new Digraph(get_nof_vertices()); for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex &v = vertices[i]; g->change_color(perm[i], v.color); for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { g->add_edge(perm[i], perm[*ei]); } } g->sort_edges(); return g; } /*------------------------------------------------------------------------- * * Print graph in graphviz format * *-------------------------------------------------------------------------*/ void Digraph::write_dot(const char* const filename) { FILE* const fp = fopen(filename, "w"); if(fp) { write_dot(fp); fclose(fp); } } void Digraph::write_dot(FILE* const fp) { remove_duplicate_edges(); fprintf(fp, "digraph g {\n"); unsigned int vnum = 0; for(std::vector::const_iterator vi = vertices.begin(); vi != vertices.end(); vi++, vnum++) { const Vertex& v = *vi; fprintf(fp, "v%u [label=\"%u:%u\"];\n", vnum, vnum, v.color); for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { fprintf(fp, "v%u -> v%u\n", vnum, *ei); } } fprintf(fp, "}\n"); } void Digraph::remove_duplicate_edges() { std::vector tmp(get_nof_vertices(), false); for(std::vector::iterator vi = vertices.begin(); vi != vertices.end(); vi++) { #if defined(BLISS_EXPENSIVE_CONSISTENCY_CHECKS) for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif (*vi).remove_duplicate_edges(tmp); } } /*------------------------------------------------------------------------- * * Get a hash value for the graph. * *-------------------------------------------------------------------------*/ unsigned int Digraph::get_hash() { remove_duplicate_edges(); sort_edges(); UintSeqHash h; h.update(get_nof_vertices()); /* Hash the color of each vertex */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { h.update(vertices[i].color); } /* Hash the edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { h.update(i); h.update(*ei); } } return h.get_value(); } /*------------------------------------------------------------------------- * * Read directed graph in the DIMACS format. * Returns 0 if an error occurred. * *-------------------------------------------------------------------------*/ Digraph* Digraph::read_dimacs(FILE* const fp, FILE* const errstr) { Digraph* g = 0; unsigned int nof_vertices; unsigned int nof_edges; unsigned int line_num = 1; const bool verbose = false; FILE* const verbstr = stdout; /* Read comments and the problem definition line */ while(1) { int c = getc(fp); if(c == 'c') { /* A comment, ignore the rest of the line */ while((c = getc(fp)) != '\n') { if(c == EOF) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } } line_num++; continue; } if(c == 'p') { /* The problem definition line */ if(fscanf(fp, " edge %u %u\n", &nof_vertices, &nof_edges) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } line_num++; break; } if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(nof_vertices <= 0) { if(errstr) fprintf(errstr, "error: no vertices\n"); goto error_exit; } if(verbose) { fprintf(verbstr, "Instance has %d vertices and %d edges\n", nof_vertices, nof_edges); fflush(verbstr); } g = new Digraph(nof_vertices); // // Read vertex colors // if(verbose) { fprintf(verbstr, "Reading vertex colors...\n"); fflush(verbstr); } while(1) { int c = getc(fp); if(c != 'n') { ungetc(c, fp); break; } ungetc(c, fp); unsigned int vertex; unsigned int color; if(fscanf(fp, "n %u %u\n", &vertex, &color) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(!((vertex >= 1) && (vertex <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...%u]\n", line_num, vertex, nof_vertices); goto error_exit; } line_num++; g->change_color(vertex - 1, color); } if(verbose) { fprintf(verbstr, "Done\n"); fflush(verbstr); } // // Read edges // if(verbose) { fprintf(verbstr, "Reading edges...\n"); fflush(verbstr); } for(unsigned i = 0; i < nof_edges; i++) { unsigned int from, to; if(fscanf(fp, "e %u %u\n", &from, &to) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(not((1 <= from) and (from <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...%u]\n", line_num, from, nof_vertices); goto error_exit; } if(not((1 <= to) and (to <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...%u]\n", line_num, to, nof_vertices); goto error_exit; } line_num++; g->add_edge(from-1, to-1); } if(verbose) { fprintf(verbstr, "Done\n"); fflush(verbstr); } return g; error_exit: if(g) delete g; return 0; } void Digraph::write_dimacs(FILE* const fp) { remove_duplicate_edges(); sort_edges(); /* First count the total number of edges */ unsigned int nof_edges = 0; for(unsigned int i = 0; i < get_nof_vertices(); i++) { nof_edges += vertices[i].edges_out.size(); } /* Output the "header" line */ fprintf(fp, "p edge %u %u\n", get_nof_vertices(), nof_edges); /* Print the color of each vertex */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex& v = vertices[i]; fprintf(fp, "n %u %u\n", i+1, v.color); /* if(v.color != 0) { fprintf(fp, "n %u %u\n", i+1, v.color); } */ } /* Print the edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex& v = vertices[i]; for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { fprintf(fp, "e %u %u\n", i+1, (*ei)+1); } } } /*------------------------------------------------------------------------- * * Partition independent invariants * *-------------------------------------------------------------------------*/ unsigned int Digraph::vertex_color_invariant(const Digraph* const g, const unsigned int vnum) { return g->vertices[vnum].color; } unsigned int Digraph::indegree_invariant(const Digraph* const g, const unsigned int vnum) { return g->vertices[vnum].nof_edges_in(); } unsigned int Digraph::outdegree_invariant(const Digraph* const g, const unsigned int vnum) { return g->vertices[vnum].nof_edges_out(); } unsigned int Digraph::selfloop_invariant(const Digraph* const g, const unsigned int vnum) { /* Quite inefficient but luckily not in the critical path */ const Vertex& v = g->vertices[vnum]; for(std::vector::const_iterator ei = v.edges_out.begin(); ei != v.edges_out.end(); ei++) { if(*ei == vnum) return 1; } return 0; } /*------------------------------------------------------------------------- * * Refine the partition p according to a partition independent invariant * *-------------------------------------------------------------------------*/ bool Digraph::refine_according_to_invariant(unsigned int (*inv)(const Digraph* const g, const unsigned int v)) { bool refined = false; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; ) { Partition::Cell* const next_cell = cell->next_nonsingleton; const unsigned int* ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) { unsigned int ival = inv(this, *ep); p.invariant_values[*ep] = ival; if(ival > cell->max_ival) { cell->max_ival = ival; cell->max_ival_count = 1; } else if(ival == cell->max_ival) { cell->max_ival_count++; } } Partition::Cell* const last_new_cell = p.zplit_cell(cell, true); refined |= (last_new_cell != cell); cell = next_cell; } return refined; } /*------------------------------------------------------------------------- * * Split the neighbourhood of a cell according to the equitable invariant * *-------------------------------------------------------------------------*/ bool Digraph::split_neighbourhood_of_cell(Partition::Cell* const cell) { const bool was_equal_to_first = refine_equal_to_first; if(compute_eqref_hash) { eqref_hash.update(cell->first); eqref_hash.update(cell->length); } const unsigned int* ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--) { const Vertex& v = vertices[*ep++]; std::vector::const_iterator ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j != 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) continue; const unsigned int ival = ++p.invariant_values[dest_vertex]; if(ival > neighbour_cell->max_ival) { neighbour_cell->max_ival = ival; neighbour_cell->max_ival_count = 1; if(ival == 1) neighbour_heap.insert(neighbour_cell->first); } else if(ival == neighbour_cell->max_ival) { neighbour_cell->max_ival_count++; } } } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival); eqref_hash.update(neighbour_cell->max_ival_count); } Partition::Cell* const last_new_cell = p.zplit_cell(neighbour_cell, true); /* Update certificate and hash if needed */ const Partition::Cell* c = neighbour_cell; while(1) { if(in_search) { /* Build certificate */ cert_add_redundant(CERT_SPLIT, c->first, c->length); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } if(compute_eqref_hash) { eqref_hash.update(c->first); eqref_hash.update(c->length); } if(c == last_new_cell) break; c = c->next; } } if(cell->is_in_splitting_queue()) { return false; } ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--) { const Vertex& v = vertices[*ep++]; std::vector::const_iterator ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) continue; const unsigned int ival = ++p.invariant_values[dest_vertex]; if(ival > neighbour_cell->max_ival) { neighbour_cell->max_ival = ival; neighbour_cell->max_ival_count = 1; if(ival == 1) neighbour_heap.insert(neighbour_cell->first); } else if(ival == neighbour_cell->max_ival) { neighbour_cell->max_ival_count++; } } } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival); eqref_hash.update(neighbour_cell->max_ival_count); } Partition::Cell* const last_new_cell = p.zplit_cell(neighbour_cell, true); /* Update certificate and hash if needed */ const Partition::Cell* c = neighbour_cell; while(1) { if(in_search) { /* Build certificate */ cert_add_redundant(CERT_SPLIT, c->first, c->length); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } if(compute_eqref_hash) { eqref_hash.update(c->first); eqref_hash.update(c->length); } if(c == last_new_cell) break; c = c->next; } } if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) return true; return false; worse_exit: /* Clear neighbour heap */ UintSeqHash rest; while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); if(opt_use_failure_recording and was_equal_to_first) { rest.update(neighbour_cell->first); rest.update(neighbour_cell->length); rest.update(neighbour_cell->max_ival); rest.update(neighbour_cell->max_ival_count); } neighbour_cell->max_ival = 0; neighbour_cell->max_ival_count = 0; p.clear_ivs(neighbour_cell); } if(opt_use_failure_recording and was_equal_to_first) { for(unsigned int i = p.splitting_queue.size(); i > 0; i--) { Partition::Cell* const cell = p.splitting_queue.pop_front(); rest.update(cell->first); rest.update(cell->length); p.splitting_queue.push_back(cell); } rest.update(failure_recording_fp_deviation); failure_recording_fp_deviation = rest.get_value(); } return true; } bool Digraph::split_neighbourhood_of_unit_cell(Partition::Cell* const unit_cell) { const bool was_equal_to_first = refine_equal_to_first; if(compute_eqref_hash) { eqref_hash.update(0x87654321); eqref_hash.update(unit_cell->first); eqref_hash.update(1); } const Vertex& v = vertices[p.elements[unit_cell->first]]; /* * Phase 1 * Refine neighbours according to the edges that leave the vertex v */ std::vector::const_iterator ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) { if(in_search) { /* Remember neighbour in order to generate certificate */ neighbour_heap.insert(neighbour_cell->first); } continue; } if(neighbour_cell->max_ival_count == 0) { neighbour_heap.insert(neighbour_cell->first); } neighbour_cell->max_ival_count++; unsigned int* const swap_position = p.elements + neighbour_cell->first + neighbour_cell->length - neighbour_cell->max_ival_count; *p.in_pos[dest_vertex] = *swap_position; p.in_pos[*swap_position] = p.in_pos[dest_vertex]; *swap_position = dest_vertex; p.in_pos[dest_vertex] = swap_position; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* neighbour_cell = p.get_cell(p.elements[start]); #if defined(BLISS_CONSISTENCY_CHECKS) assert(neighbour_cell->first == start); if(neighbour_cell->is_unit()) { assert(neighbour_cell->max_ival_count == 0); } else { assert(neighbour_cell->max_ival_count > 0); assert(neighbour_cell->max_ival_count <= neighbour_cell->length); } #endif if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival_count); } if(neighbour_cell->length > 1 and neighbour_cell->max_ival_count != neighbour_cell->length) { Partition::Cell* const new_cell = p.aux_split_in_two(neighbour_cell, neighbour_cell->length - neighbour_cell->max_ival_count); unsigned int* ep = p.elements + new_cell->first; unsigned int* const lp = p.elements+new_cell->first+new_cell->length; while(ep < lp) { p.element_to_cell_map[*ep] = new_cell; ep++; } neighbour_cell->max_ival_count = 0; if(compute_eqref_hash) { /* Update hash */ eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(0); eqref_hash.update(new_cell->first); eqref_hash.update(new_cell->length); eqref_hash.update(1); } /* Add cells in splitting_queue */ if(neighbour_cell->is_in_splitting_queue()) { /* Both cells must be included in splitting_queue in order to have refinement to equitable partition */ p.splitting_queue_add(new_cell); } else { Partition::Cell *min_cell, *max_cell; if(neighbour_cell->length <= new_cell->length) { min_cell = neighbour_cell; max_cell = new_cell; } else { min_cell = new_cell; max_cell = neighbour_cell; } /* Put the smaller cell in splitting_queue */ p.splitting_queue_add(min_cell); if(max_cell->is_unit()) { /* Put the "larger" cell also in splitting_queue */ p.splitting_queue_add(max_cell); } } /* Update pointer for certificate generation */ neighbour_cell = new_cell; } else { neighbour_cell->max_ival_count = 0; } /* * Build certificate if required */ if(in_search) { for(unsigned int i = neighbour_cell->first, j = neighbour_cell->length; j > 0; j--, i++) { /* Build certificate */ cert_add(CERT_EDGE, unit_cell->first, i); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } } /* if(in_search) */ } /* while(!neighbour_heap.is_empty()) */ /* * Phase 2 * Refine neighbours according to the edges that enter the vertex v */ ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) { if(in_search) { neighbour_heap.insert(neighbour_cell->first); } continue; } if(neighbour_cell->max_ival_count == 0) { neighbour_heap.insert(neighbour_cell->first); } neighbour_cell->max_ival_count++; unsigned int* const swap_position = p.elements + neighbour_cell->first + neighbour_cell->length - neighbour_cell->max_ival_count; *p.in_pos[dest_vertex] = *swap_position; p.in_pos[*swap_position] = p.in_pos[dest_vertex]; *swap_position = dest_vertex; p.in_pos[dest_vertex] = swap_position; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* neighbour_cell = p.get_cell(p.elements[start]); #if defined(BLISS_CONSISTENCY_CHECKS) assert(neighbour_cell->first == start); if(neighbour_cell->is_unit()) { assert(neighbour_cell->max_ival_count == 0); } else { assert(neighbour_cell->max_ival_count > 0); assert(neighbour_cell->max_ival_count <= neighbour_cell->length); } #endif if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival_count); } if(neighbour_cell->length > 1 and neighbour_cell->max_ival_count != neighbour_cell->length) { Partition::Cell* const new_cell = p.aux_split_in_two(neighbour_cell, neighbour_cell->length - neighbour_cell->max_ival_count); unsigned int* ep = p.elements + new_cell->first; unsigned int* const lp = p.elements+new_cell->first+new_cell->length; while(ep < lp) { p.element_to_cell_map[*ep] = new_cell; ep++; } neighbour_cell->max_ival_count = 0; if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(0); eqref_hash.update(new_cell->first); eqref_hash.update(new_cell->length); eqref_hash.update(1); } /* Add cells in splitting_queue */ if(neighbour_cell->is_in_splitting_queue()) { /* Both cells must be included in splitting_queue in order to have refinement to equitable partition */ p.splitting_queue_add(new_cell); } else { Partition::Cell *min_cell, *max_cell; if(neighbour_cell->length <= new_cell->length) { min_cell = neighbour_cell; max_cell = new_cell; } else { min_cell = new_cell; max_cell = neighbour_cell; } /* Put the smaller cell in splitting_queue */ p.splitting_queue_add(min_cell); if(max_cell->is_unit()) { /* Put the "larger" cell also in splitting_queue */ p.splitting_queue_add(max_cell); } } /* Update pointer for certificate generation */ neighbour_cell = new_cell; } else { neighbour_cell->max_ival_count = 0; } /* * Build certificate if required */ if(in_search) { for(unsigned int i = neighbour_cell->first, j = neighbour_cell->length; j > 0; j--, i++) { /* Build certificate */ cert_add(CERT_EDGE, i, unit_cell->first); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } } /* if(in_search) */ } /* while(!neighbour_heap.is_empty()) */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) return true; return false; worse_exit: /* Clear neighbour heap */ UintSeqHash rest; while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); if(opt_use_failure_recording and was_equal_to_first) { rest.update(neighbour_cell->first); rest.update(neighbour_cell->length); rest.update(neighbour_cell->max_ival_count); } neighbour_cell->max_ival_count = 0; } if(opt_use_failure_recording and was_equal_to_first) { rest.update(failure_recording_fp_deviation); failure_recording_fp_deviation = rest.get_value(); } return true; } /*------------------------------------------------------------------------- * * Check whether the current partition p is equitable. * Performance: very slow, use only for debugging purposes. * *-------------------------------------------------------------------------*/ bool Digraph::is_equitable() const { const unsigned int N = get_nof_vertices(); if(N == 0) return true; std::vector first_count = std::vector(N, 0); std::vector other_count = std::vector(N, 0); /* * Check equitabledness w.r.t. outgoing edges */ for(Partition::Cell* cell = p.first_cell; cell; cell = cell->next) { if(cell->is_unit()) continue; unsigned int* ep = p.elements + cell->first; const Vertex& first_vertex = vertices[*ep++]; /* Count outgoing edges of the first vertex for cells */ for(std::vector::const_iterator ei = first_vertex.edges_out.begin(); ei != first_vertex.edges_out.end(); ei++) { first_count[p.get_cell(*ei)->first]++; } /* Count and compare outgoing edges of the other vertices */ for(unsigned int i = cell->length; i > 1; i--) { const Vertex &vertex = vertices[*ep++]; for(std::vector::const_iterator ei = vertex.edges_out.begin(); ei != vertex.edges_out.end(); ei++) { other_count[p.get_cell(*ei)->first]++; } for(Partition::Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next) { if(first_count[cell2->first] != other_count[cell2->first]) { /* Not equitable */ return false; } other_count[cell2->first] = 0; } } /* Reset first_count */ for(unsigned int i = 0; i < N; i++) first_count[i] = 0; } /* * Check equitabledness w.r.t. incoming edges */ for(Partition::Cell* cell = p.first_cell; cell; cell = cell->next) { if(cell->is_unit()) continue; unsigned int* ep = p.elements + cell->first; const Vertex& first_vertex = vertices[*ep++]; /* Count incoming edges of the first vertex for cells */ for(std::vector::const_iterator ei = first_vertex.edges_in.begin(); ei != first_vertex.edges_in.end(); ei++) { first_count[p.get_cell(*ei)->first]++; } /* Count and compare incoming edges of the other vertices */ for(unsigned int i = cell->length; i > 1; i--) { const Vertex &vertex = vertices[*ep++]; for(std::vector::const_iterator ei = vertex.edges_in.begin(); ei != vertex.edges_in.end(); ei++) { other_count[p.get_cell(*ei)->first]++; } for(Partition::Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next) { if(first_count[cell2->first] != other_count[cell2->first]) { /* Not equitable */ return false; } other_count[cell2->first] = 0; } } /* Reset first_count */ for(unsigned int i = 0; i < N; i++) first_count[i] = 0; } return true; } /*------------------------------------------------------------------------- * * Build the initial equitable partition * *-------------------------------------------------------------------------*/ void Digraph::make_initial_equitable_partition() { refine_according_to_invariant(&vertex_color_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(&selfloop_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(&outdegree_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(&indegree_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_to_equitable(); //p.print_signature(stderr); fprintf(stderr, "\n"); } /*------------------------------------------------------------------------- * * Find the next cell to be splitted * *-------------------------------------------------------------------------*/ Partition::Cell* Digraph::find_next_cell_to_be_splitted(Partition::Cell* cell) { switch(sh) { case shs_f: return sh_first(); case shs_fs: return sh_first_smallest(); case shs_fl: return sh_first_largest(); case shs_fm: return sh_first_max_neighbours(); case shs_fsm: return sh_first_smallest_max_neighbours(); case shs_flm: return sh_first_largest_max_neighbours(); default: fatal_error("Internal error - unknown splitting heuristics"); return 0; } } /** \internal * A splitting heuristic. * Returns the first nonsingleton cell in the current partition. * The argument \a cell is ignored. */ Partition::Cell* Digraph::sh_first() { Partition::Cell* best_cell = 0; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; best_cell = cell; break; } return best_cell; } /** \internal * A splitting heuristic. * Returns the first smallest nonsingleton cell in the current partition. * The argument \a cell is ignored. */ Partition::Cell* Digraph::sh_first_smallest() { Partition::Cell* best_cell = 0; unsigned int best_size = UINT_MAX; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; if(cell->length < best_size) { best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first largest nonsingleton cell in the current partition. * The argument \a cell is ignored. */ Partition::Cell* Digraph::sh_first_largest() { Partition::Cell* best_cell = 0; unsigned int best_size = 0; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; if(cell->length > best_size) { best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Digraph::sh_first_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; int value = 0; const Vertex &v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei; ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { Partition::Cell * const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { Partition::Cell * const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if(value > best_value) { best_value = value; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first smallest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Digraph::sh_first_smallest_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; unsigned int best_size = UINT_MAX; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; int value = 0; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei; ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { Partition::Cell * const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell * const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { Partition::Cell * const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell * const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) or (value == best_value and cell->length < best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first largest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Digraph::sh_first_largest_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; unsigned int best_size = 0; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; int value = 0; const Vertex &v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei; ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { Partition::Cell* const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { Partition::Cell* const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) || (value == best_value && cell->length > best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } return best_cell; } /*------------------------------------------------------------------------ * * Initialize the certificate size and memory * *-------------------------------------------------------------------------*/ void Digraph::initialize_certificate() { certificate_index = 0; certificate_current_path.clear(); certificate_first_path.clear(); certificate_best_path.clear(); } /* * Check whether perm is an automorphism. * Slow, mainly for debugging and validation purposes. */ bool Digraph::is_automorphism(unsigned int* const perm) { std::set > edges1; std::set > edges2; #if defined(BLISS_CONSISTENCY_CHECKS) if(!is_permutation(get_nof_vertices(), perm)) _INTERNAL_ERROR(); #endif for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex& v1 = vertices[i]; Vertex& v2 = vertices[perm[i]]; edges1.clear(); for(std::vector::iterator ei = v1.edges_in.begin(); ei != v1.edges_in.end(); ei++) edges1.insert(perm[*ei]); edges2.clear(); for(std::vector::iterator ei = v2.edges_in.begin(); ei != v2.edges_in.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; edges1.clear(); for(std::vector::iterator ei = v1.edges_out.begin(); ei != v1.edges_out.end(); ei++) edges1.insert(perm[*ei]); edges2.clear(); for(std::vector::iterator ei = v2.edges_out.begin(); ei != v2.edges_out.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; } return true; } bool Digraph::is_automorphism(const std::vector& perm) const { if(!(perm.size() == get_nof_vertices() and is_permutation(perm))) return false; std::set > edges1; std::set > edges2; for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex& v1 = vertices[i]; const Vertex& v2 = vertices[perm[i]]; edges1.clear(); for(std::vector::const_iterator ei = v1.edges_in.begin(); ei != v1.edges_in.end(); ei++) edges1.insert(perm[*ei]); edges2.clear(); for(std::vector::const_iterator ei = v2.edges_in.begin(); ei != v2.edges_in.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; edges1.clear(); for(std::vector::const_iterator ei = v1.edges_out.begin(); ei != v1.edges_out.end(); ei++) edges1.insert(perm[*ei]); edges2.clear(); for(std::vector::const_iterator ei = v2.edges_out.begin(); ei != v2.edges_out.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; } return true; } bool Digraph::nucr_find_first_component(const unsigned int level) { cr_component.clear(); cr_component_elements = 0; /* Find first non-discrete cell in the component level */ Partition::Cell* first_cell = p.first_nonsingleton_cell; while(first_cell) { if(p.cr_get_level(first_cell->first) == level) break; first_cell = first_cell->next_nonsingleton; } /* The component is discrete, return false */ if(!first_cell) return false; std::vector component; first_cell->max_ival = 1; component.push_back(first_cell); for(unsigned int i = 0; i < component.size(); i++) { Partition::Cell* const cell = component[i]; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei; ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /* Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Already marked to be in the same component? */ if(neighbour_cell->max_ival == 1) continue; /* Is the neighbour at the same component recursion level? */ if(p.cr_get_level(neighbour_cell->first) != level) continue; if(neighbour_cell->max_ival_count == 0) neighbour_heap.insert(neighbour_cell->first); neighbour_cell->max_ival_count++; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } neighbour_cell->max_ival_count = 0; neighbour_cell->max_ival = 1; component.push_back(neighbour_cell); } ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /* Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Already marked to be in the same component? */ if(neighbour_cell->max_ival == 1) continue; /* Is the neighbour at the same component recursion level? */ if(p.cr_get_level(neighbour_cell->first) != level) continue; if(neighbour_cell->max_ival_count == 0) neighbour_heap.insert(neighbour_cell->first); neighbour_cell->max_ival_count++; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } neighbour_cell->max_ival_count = 0; neighbour_cell->max_ival = 1; component.push_back(neighbour_cell); } } for(unsigned int i = 0; i < component.size(); i++) { Partition::Cell* const cell = component[i]; cell->max_ival = 0; cr_component.push_back(cell->first); cr_component_elements += cell->length; } if(verbstr and verbose_level > 2) { fprintf(verbstr, "NU-component with %lu cells and %u vertices\n", (long unsigned)cr_component.size(), cr_component_elements); fflush(verbstr); } return true; } bool Digraph::nucr_find_first_component(const unsigned int level, std::vector& component, unsigned int& component_elements, Partition::Cell*& sh_return) { component.clear(); component_elements = 0; sh_return = 0; unsigned int sh_first = 0; unsigned int sh_size = 0; unsigned int sh_nuconn = 0; /* Find first non-discrete cell in the component level */ Partition::Cell* first_cell = p.first_nonsingleton_cell; while(first_cell) { if(p.cr_get_level(first_cell->first) == level) break; first_cell = first_cell->next_nonsingleton; } if(!first_cell) { /* The component is discrete, return false */ return false; } std::vector comp; KStack neighbours; neighbours.init(get_nof_vertices()); first_cell->max_ival = 1; comp.push_back(first_cell); for(unsigned int i = 0; i < comp.size(); i++) { Partition::Cell* const cell = comp[i]; unsigned int nuconn = 1; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei; /*| Phase 1: outgoing edges */ ei = v.edges_out.begin(); for(unsigned int j = v.nof_edges_out(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /* Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Is the neighbour at the same component recursion level? */ //if(p.cr_get_level(neighbour_cell->first) != level) // continue; if(neighbour_cell->max_ival_count == 0) neighbours.push(neighbour_cell); neighbour_cell->max_ival_count++; } while(!neighbours.is_empty()) { Partition::Cell* const neighbour_cell = neighbours.pop(); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } nuconn++; neighbour_cell->max_ival_count = 0; if(neighbour_cell->max_ival == 0) { comp.push_back(neighbour_cell); neighbour_cell->max_ival = 1; } } /*| Phase 2: incoming edges */ ei = v.edges_in.begin(); for(unsigned int j = v.nof_edges_in(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /*| Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Is the neighbour at the same component recursion level? */ //if(p.cr_get_level(neighbour_cell->first) != level) // continue; if(neighbour_cell->max_ival_count == 0) neighbours.push(neighbour_cell); neighbour_cell->max_ival_count++; } while(!neighbours.is_empty()) { Partition::Cell* const neighbour_cell = neighbours.pop(); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } nuconn++; neighbour_cell->max_ival_count = 0; if(neighbour_cell->max_ival == 0) { comp.push_back(neighbour_cell); neighbour_cell->max_ival = 1; } } /*| Phase 3: splitting heuristics */ switch(sh) { case shs_f: if(sh_return == 0 or cell->first <= sh_first) { sh_return = cell; sh_first = cell->first; } break; case shs_fs: if(sh_return == 0 or cell->length < sh_size or (cell->length == sh_size and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; } break; case shs_fl: if(sh_return == 0 or cell->length > sh_size or (cell->length == sh_size and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; } break; case shs_fm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_nuconn = nuconn; } break; case shs_fsm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and (cell->length < sh_size or (cell->length == sh_size and cell->first <= sh_first)))) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; sh_nuconn = nuconn; } break; case shs_flm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and (cell->length > sh_size or (cell->length == sh_size and cell->first <= sh_first)))) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; sh_nuconn = nuconn; } break; default: fatal_error("Internal error - unknown splitting heuristics"); return 0; } } assert(sh_return); for(unsigned int i = 0; i < comp.size(); i++) { Partition::Cell* const cell = comp[i]; cell->max_ival = 0; component.push_back(cell->first); component_elements += cell->length; } if(verbstr and verbose_level > 2) { fprintf(verbstr, "NU-component with %lu cells and %u vertices\n", (long unsigned)component.size(), component_elements); fflush(verbstr); } return true; } /*------------------------------------------------------------------------- * * Routines for undirected graphs * *-------------------------------------------------------------------------*/ Graph::Vertex::Vertex() { color = 0; } Graph::Vertex::~Vertex() { ; } void Graph::Vertex::add_edge(const unsigned int other_vertex) { edges.push_back(other_vertex); } void Graph::Vertex::remove_duplicate_edges(std::vector& tmp) { #if defined(BLISS_CONSISTENCY_CHECKS) /* Pre-conditions */ for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif for(std::vector::iterator iter = edges.begin(); iter != edges.end(); ) { const unsigned int dest_vertex = *iter; if(tmp[dest_vertex] == true) { /* A duplicate edge found! */ iter = edges.erase(iter); } else { /* Not seen earlier, mark as seen */ tmp[dest_vertex] = true; iter++; } } /* Clear tmp */ for(std::vector::iterator iter = edges.begin(); iter != edges.end(); iter++) { tmp[*iter] = false; } #if defined(BLISS_CONSISTENCY_CHECKS) /* Post-conditions */ for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif } /** * Sort the edges leaving the vertex according to * the vertex number of the other edge end. * Time complexity: O(e log(e)), where e is the number of edges * leaving the vertex. */ void Graph::Vertex::sort_edges() { std::sort(edges.begin(), edges.end()); } /*------------------------------------------------------------------------- * * Constructor and destructor for undirected graphs * *-------------------------------------------------------------------------*/ Graph::Graph(const unsigned int nof_vertices) { vertices.resize(nof_vertices); sh = shs_flm; } Graph::~Graph() { ; } unsigned int Graph::add_vertex(const unsigned int color) { const unsigned int vertex_num = vertices.size(); vertices.resize(vertex_num + 1); vertices.back().color = color; return vertex_num; } void Graph::add_edge(const unsigned int vertex1, const unsigned int vertex2) { //fprintf(stderr, "(%u,%u) ", vertex1, vertex2); vertices[vertex1].add_edge(vertex2); vertices[vertex2].add_edge(vertex1); } void Graph::change_color(const unsigned int vertex, const unsigned int color) { vertices[vertex].color = color; } /*------------------------------------------------------------------------- * * Read graph in the DIMACS format. * Returns 0 if an error occurred. * *-------------------------------------------------------------------------*/ Graph* Graph::read_dimacs(FILE* const fp, FILE* const errstr) { Graph *g = 0; unsigned int nof_vertices; unsigned int nof_edges; unsigned int line_num = 1; int c; const bool verbose = false; FILE* const verbstr = stdout; /* Read comments and the problem definition line */ while(1) { c = getc(fp); if(c == 'c') { /* A comment, ignore the rest of the line */ while((c = getc(fp)) != '\n') { if(c == EOF) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } } line_num++; continue; } if(c == 'p') { /* The problem definition line */ if(fscanf(fp, " edge %u %u\n", &nof_vertices, &nof_edges) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } line_num++; break; } if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(nof_vertices <= 0) { if(errstr) fprintf(errstr, "error: no vertices\n"); goto error_exit; } if(verbose) { fprintf(verbstr, "Instance has %d vertices and %d edges\n", nof_vertices, nof_edges); fflush(verbstr); } g = new Graph(nof_vertices); // // Read vertex colors // if(verbose) { fprintf(verbstr, "Reading vertex colors...\n"); fflush(verbstr); } while(1) { c = getc(fp); if(c != 'n') { ungetc(c, fp); break; } ungetc(c, fp); unsigned int vertex; unsigned int color; if(fscanf(fp, "n %u %u\n", &vertex, &color) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(!((vertex >= 1) && (vertex <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...,%u]\n", line_num, vertex, nof_vertices); goto error_exit; } line_num++; g->change_color(vertex - 1, color); } if(verbose) { fprintf(verbstr, "Done\n"); fflush(verbstr); } // // Read edges // if(verbose) { fprintf(verbstr, "Reading edges...\n"); fflush(verbstr); } for(unsigned i = 0; i < nof_edges; i++) { unsigned int from, to; if(fscanf(fp, "e %u %u\n", &from, &to) != 2) { if(errstr) fprintf(errstr, "error in line %u: not in DIMACS format\n", line_num); goto error_exit; } if(!((from >= 1) && (from <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...,%u]\n", line_num, from, nof_vertices); goto error_exit; } if(!((to >= 1) && (to <= nof_vertices))) { if(errstr) fprintf(errstr, "error in line %u: vertex %u not in range [1,...,%u]\n", line_num, to, nof_vertices); goto error_exit; } line_num++; g->add_edge(from-1, to-1); } if(verbose) { fprintf(verbstr, "Done\n"); fflush(verbstr); } return g; error_exit: if(g) delete g; return 0; } void Graph::write_dimacs(FILE* const fp) { remove_duplicate_edges(); sort_edges(); /* First count the total number of edges */ unsigned int nof_edges = 0; for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_i = *ei; if(dest_i < i) continue; nof_edges++; } } /* Output the "header" line */ fprintf(fp, "p edge %u %u\n", get_nof_vertices(), nof_edges); /* Print the color of each vertex */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; fprintf(fp, "n %u %u\n", i+1, v.color); /* if(v.color != 0) { fprintf(fp, "n %u %u\n", i+1, v.color); } */ } /* Print the edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_i = *ei; if(dest_i < i) continue; fprintf(fp, "e %u %u\n", i+1, dest_i+1); } } } void Graph::sort_edges() { for(unsigned int i = 0; i < get_nof_vertices(); i++) vertices[i].sort_edges(); } int Graph::cmp(Graph& other) { /* Compare the numbers of vertices */ if(get_nof_vertices() < other.get_nof_vertices()) return -1; if(get_nof_vertices() > other.get_nof_vertices()) return 1; /* Compare vertex colors */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { if(vertices[i].color < other.vertices[i].color) return -1; if(vertices[i].color > other.vertices[i].color) return 1; } /* Compare vertex degrees */ remove_duplicate_edges(); other.remove_duplicate_edges(); for(unsigned int i = 0; i < get_nof_vertices(); i++) { if(vertices[i].nof_edges() < other.vertices[i].nof_edges()) return -1; if(vertices[i].nof_edges() > other.vertices[i].nof_edges()) return 1; } /* Compare edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v1 = vertices[i]; Vertex &v2 = other.vertices[i]; v1.sort_edges(); v2.sort_edges(); std::vector::const_iterator ei1 = v1.edges.begin(); std::vector::const_iterator ei2 = v2.edges.begin(); while(ei1 != v1.edges.end()) { if(*ei1 < *ei2) return -1; if(*ei1 > *ei2) return 1; ei1++; ei2++; } } return 0; } Graph* Graph::permute(const std::vector& perm) const { #if defined(BLISS_CONSISTENCY_CHECKS) #endif Graph* const g = new Graph(get_nof_vertices()); for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex& v = vertices[i]; Vertex& permuted_v = g->vertices[perm[i]]; permuted_v.color = v.color; for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_v = *ei; permuted_v.add_edge(perm[dest_v]); } permuted_v.sort_edges(); } return g; } Graph* Graph::permute(const unsigned int* perm) const { #if defined(BLISS_CONSISTENCY_CHECKS) if(!is_permutation(get_nof_vertices(), perm)) _INTERNAL_ERROR(); #endif Graph* const g = new Graph(get_nof_vertices()); for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex& v = vertices[i]; Vertex& permuted_v = g->vertices[perm[i]]; permuted_v.color = v.color; for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_v = *ei; permuted_v.add_edge(perm[dest_v]); } permuted_v.sort_edges(); } return g; } /*------------------------------------------------------------------------- * * Print graph in graphviz format * *-------------------------------------------------------------------------*/ void Graph::write_dot(const char* const filename) { FILE *fp = fopen(filename, "w"); if(fp) { write_dot(fp); fclose(fp); } } void Graph::write_dot(FILE* const fp) { remove_duplicate_edges(); fprintf(fp, "graph g {\n"); unsigned int vnum = 0; for(std::vector::iterator vi = vertices.begin(); vi != vertices.end(); vi++, vnum++) { Vertex& v = *vi; fprintf(fp, "v%u [label=\"%u:%u\"];\n", vnum, vnum, v.color); for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int vnum2 = *ei; if(vnum2 > vnum) fprintf(fp, "v%u -- v%u\n", vnum, vnum2); } } fprintf(fp, "}\n"); } /*------------------------------------------------------------------------- * * Get a hash value for the graph. * *-------------------------------------------------------------------------*/ unsigned int Graph::get_hash() { remove_duplicate_edges(); sort_edges(); UintSeqHash h; h.update(get_nof_vertices()); /* Hash the color of each vertex */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { h.update(vertices[i].color); } /* Hash the edges */ for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex &v = vertices[i]; for(std::vector::const_iterator ei = v.edges.begin(); ei != v.edges.end(); ei++) { const unsigned int dest_i = *ei; if(dest_i < i) continue; h.update(i); h.update(dest_i); } } return h.get_value(); } void Graph::remove_duplicate_edges() { std::vector tmp(vertices.size(), false); for(std::vector::iterator vi = vertices.begin(); vi != vertices.end(); vi++) { #if defined(BLISS_EXPENSIVE_CONSISTENCY_CHECKS) for(unsigned int i = 0; i < tmp.size(); i++) assert(tmp[i] == false); #endif (*vi).remove_duplicate_edges(tmp); } } /*------------------------------------------------------------------------- * * Partition independent invariants * *-------------------------------------------------------------------------*/ /* * Return the color of the vertex. * Time complexity: O(1) */ unsigned int Graph::vertex_color_invariant(const Graph* const g, const unsigned int v) { return g->vertices[v].color; } /* * Return the degree of the vertex. * Time complexity: O(1) */ unsigned int Graph::degree_invariant(const Graph* const g, const unsigned int v) { return g->vertices[v].nof_edges(); } /* * Return 1 if the vertex v has a self-loop, 0 otherwise * Time complexity: O(E_v), where E_v is the number of edges leaving v */ unsigned int Graph::selfloop_invariant(const Graph* const g, const unsigned int v) { const Vertex& vertex = g->vertices[v]; for(std::vector::const_iterator ei = vertex.edges.begin(); ei != vertex.edges.end(); ei++) { if(*ei == v) return 1; } return 0; } /*------------------------------------------------------------------------- * * Refine the partition p according to a partition independent invariant * *-------------------------------------------------------------------------*/ bool Graph::refine_according_to_invariant(unsigned int (*inv)(const Graph* const g, const unsigned int v)) { bool refined = false; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; ) { Partition::Cell* const next_cell = cell->next_nonsingleton; const unsigned int* ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) { const unsigned int ival = inv(this, *ep); p.invariant_values[*ep] = ival; if(ival > cell->max_ival) { cell->max_ival = ival; cell->max_ival_count = 1; } else if(ival == cell->max_ival) { cell->max_ival_count++; } } Partition::Cell* const last_new_cell = p.zplit_cell(cell, true); refined |= (last_new_cell != cell); cell = next_cell; } return refined; } /*------------------------------------------------------------------------- * * Split the neighbourhood of a cell according to the equitable invariant * *-------------------------------------------------------------------------*/ bool Graph::split_neighbourhood_of_cell(Partition::Cell* const cell) { const bool was_equal_to_first = refine_equal_to_first; if(compute_eqref_hash) { eqref_hash.update(cell->first); eqref_hash.update(cell->length); } const unsigned int* ep = p.elements + cell->first; for(unsigned int i = cell->length; i > 0; i--) { const Vertex& v = vertices[*ep++]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j != 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell * const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) continue; const unsigned int ival = ++p.invariant_values[dest_vertex]; if(ival > neighbour_cell->max_ival) { neighbour_cell->max_ival = ival; neighbour_cell->max_ival_count = 1; if(ival == 1) { neighbour_heap.insert(neighbour_cell->first); } } else if(ival == neighbour_cell->max_ival) { neighbour_cell->max_ival_count++; } } } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell * const neighbour_cell = p.get_cell(p.elements[start]); if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival); eqref_hash.update(neighbour_cell->max_ival_count); } Partition::Cell* const last_new_cell = p.zplit_cell(neighbour_cell, true); /* Update certificate and hash if needed */ const Partition::Cell* c = neighbour_cell; while(1) { if(in_search) { /* Build certificate */ cert_add_redundant(CERT_SPLIT, c->first, c->length); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } if(compute_eqref_hash) { eqref_hash.update(c->first); eqref_hash.update(c->length); } if(c == last_new_cell) break; c = c->next; } } if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) return true; return false; worse_exit: /* Clear neighbour heap */ UintSeqHash rest; while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell * const neighbour_cell = p.get_cell(p.elements[start]); if(opt_use_failure_recording and was_equal_to_first) { rest.update(neighbour_cell->first); rest.update(neighbour_cell->length); rest.update(neighbour_cell->max_ival); rest.update(neighbour_cell->max_ival_count); } neighbour_cell->max_ival = 0; neighbour_cell->max_ival_count = 0; p.clear_ivs(neighbour_cell); } if(opt_use_failure_recording and was_equal_to_first) { for(unsigned int i = p.splitting_queue.size(); i > 0; i--) { Partition::Cell* const cell = p.splitting_queue.pop_front(); rest.update(cell->first); rest.update(cell->length); p.splitting_queue.push_back(cell); } rest.update(failure_recording_fp_deviation); failure_recording_fp_deviation = rest.get_value(); } return true; } bool Graph::split_neighbourhood_of_unit_cell(Partition::Cell* const unit_cell) { const bool was_equal_to_first = refine_equal_to_first; if(compute_eqref_hash) { eqref_hash.update(0x87654321); eqref_hash.update(unit_cell->first); eqref_hash.update(1); } const Vertex& v = vertices[p.elements[unit_cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { const unsigned int dest_vertex = *ei++; Partition::Cell * const neighbour_cell = p.get_cell(dest_vertex); if(neighbour_cell->is_unit()) { if(in_search) { /* Remember neighbour in order to generate certificate */ neighbour_heap.insert(neighbour_cell->first); } continue; } if(neighbour_cell->max_ival_count == 0) { neighbour_heap.insert(neighbour_cell->first); } neighbour_cell->max_ival_count++; unsigned int * const swap_position = p.elements + neighbour_cell->first + neighbour_cell->length - neighbour_cell->max_ival_count; *p.in_pos[dest_vertex] = *swap_position; p.in_pos[*swap_position] = p.in_pos[dest_vertex]; *swap_position = dest_vertex; p.in_pos[dest_vertex] = swap_position; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* neighbour_cell = p.get_cell(p.elements[start]); #if defined(BLISS_CONSISTENCY_CHECKS) if(neighbour_cell->is_unit()) { } else { } #endif if(compute_eqref_hash) { eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(neighbour_cell->max_ival_count); } if(neighbour_cell->length > 1 and neighbour_cell->max_ival_count != neighbour_cell->length) { Partition::Cell * const new_cell = p.aux_split_in_two(neighbour_cell, neighbour_cell->length - neighbour_cell->max_ival_count); unsigned int *ep = p.elements + new_cell->first; unsigned int * const lp = p.elements+new_cell->first+new_cell->length; while(ep < lp) { p.element_to_cell_map[*ep] = new_cell; ep++; } neighbour_cell->max_ival_count = 0; if(compute_eqref_hash) { /* Update hash */ eqref_hash.update(neighbour_cell->first); eqref_hash.update(neighbour_cell->length); eqref_hash.update(0); eqref_hash.update(new_cell->first); eqref_hash.update(new_cell->length); eqref_hash.update(1); } /* Add cells in splitting_queue */ if(neighbour_cell->is_in_splitting_queue()) { /* Both cells must be included in splitting_queue in order to ensure refinement into equitable partition */ p.splitting_queue_add(new_cell); } else { Partition::Cell *min_cell, *max_cell; if(neighbour_cell->length <= new_cell->length) { min_cell = neighbour_cell; max_cell = new_cell; } else { min_cell = new_cell; max_cell = neighbour_cell; } /* Put the smaller cell in splitting_queue */ p.splitting_queue_add(min_cell); if(max_cell->is_unit()) { /* Put the "larger" cell also in splitting_queue */ p.splitting_queue_add(max_cell); } } /* Update pointer for certificate generation */ neighbour_cell = new_cell; } else { /* neighbour_cell->length == 1 || neighbour_cell->max_ival_count == neighbour_cell->length */ neighbour_cell->max_ival_count = 0; } /* * Build certificate if required */ if(in_search) { for(unsigned int i = neighbour_cell->first, j = neighbour_cell->length; j > 0; j--, i++) { /* Build certificate */ cert_add(CERT_EDGE, unit_cell->first, i); /* No need to continue? */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) goto worse_exit; } } /* if(in_search) */ } /* while(!neighbour_heap.is_empty()) */ if(refine_compare_certificate and (refine_equal_to_first == false) and (refine_cmp_to_best < 0)) return true; return false; worse_exit: /* Clear neighbour heap */ UintSeqHash rest; while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell * const neighbour_cell = p.get_cell(p.elements[start]); if(opt_use_failure_recording and was_equal_to_first) { rest.update(neighbour_cell->first); rest.update(neighbour_cell->length); rest.update(neighbour_cell->max_ival_count); } neighbour_cell->max_ival_count = 0; } if(opt_use_failure_recording and was_equal_to_first) { rest.update(failure_recording_fp_deviation); failure_recording_fp_deviation = rest.get_value(); } return true; } /*------------------------------------------------------------------------- * * Check whether the current partition p is equitable. * Performance: very slow, use only for debugging purposes. * *-------------------------------------------------------------------------*/ bool Graph::is_equitable() const { const unsigned int N = get_nof_vertices(); if(N == 0) return true; std::vector first_count = std::vector(N, 0); std::vector other_count = std::vector(N, 0); for(Partition::Cell *cell = p.first_cell; cell; cell = cell->next) { if(cell->is_unit()) continue; unsigned int *ep = p.elements + cell->first; const Vertex &first_vertex = vertices[*ep++]; /* Count how many edges lead from the first vertex to * the neighbouring cells */ for(std::vector::const_iterator ei = first_vertex.edges.begin(); ei != first_vertex.edges.end(); ei++) { first_count[p.get_cell(*ei)->first]++; } /* Count and compare to the edges of the other vertices */ for(unsigned int i = cell->length; i > 1; i--) { const Vertex &vertex = vertices[*ep++]; for(std::vector::const_iterator ei = vertex.edges.begin(); ei != vertex.edges.end(); ei++) { other_count[p.get_cell(*ei)->first]++; } for(Partition::Cell *cell2 = p.first_cell; cell2; cell2 = cell2->next) { if(first_count[cell2->first] != other_count[cell2->first]) { /* Not equitable */ return false; } other_count[cell2->first] = 0; } } /* Reset first_count */ for(unsigned int i = 0; i < N; i++) first_count[i] = 0; } return true; } /*------------------------------------------------------------------------- * * Build the initial equitable partition * *-------------------------------------------------------------------------*/ void Graph::make_initial_equitable_partition() { refine_according_to_invariant(&vertex_color_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(&selfloop_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_according_to_invariant(°ree_invariant); p.splitting_queue_clear(); //p.print_signature(stderr); fprintf(stderr, "\n"); refine_to_equitable(); //p.print_signature(stderr); fprintf(stderr, "\n"); } /*------------------------------------------------------------------------- * * Find the next cell to be splitted * *-------------------------------------------------------------------------*/ Partition::Cell* Graph::find_next_cell_to_be_splitted(Partition::Cell* cell) { switch(sh) { case shs_f: return sh_first(); case shs_fs: return sh_first_smallest(); case shs_fl: return sh_first_largest(); case shs_fm: return sh_first_max_neighbours(); case shs_fsm: return sh_first_smallest_max_neighbours(); case shs_flm: return sh_first_largest_max_neighbours(); default: fatal_error("Internal error - unknown splitting heuristics"); return 0; } } /** \internal * A splitting heuristic. * Returns the first nonsingleton cell in the current partition. */ Partition::Cell* Graph::sh_first() { Partition::Cell* best_cell = 0; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; best_cell = cell; break; } return best_cell; } /** \internal * A splitting heuristic. * Returns the first smallest nonsingleton cell in the current partition. */ Partition::Cell* Graph::sh_first_smallest() { Partition::Cell* best_cell = 0; unsigned int best_size = UINT_MAX; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; if(cell->length < best_size) { best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first largest nonsingleton cell in the current partition. */ Partition::Cell* Graph::sh_first_largest() { Partition::Cell* best_cell = 0; unsigned int best_size = 0; for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; if(cell->length > best_size) { best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Graph::sh_first_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { Partition::Cell * const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if(value > best_value) { best_value = value; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first smallest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Graph::sh_first_smallest_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; unsigned int best_size = UINT_MAX; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { Partition::Cell* const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) or (value == best_value and cell->length < best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } return best_cell; } /** \internal * A splitting heuristic. * Returns the first largest nonsingleton cell with max number of neighbouring * nonsingleton cells. * Assumes that the partition p is equitable. * Assumes that the max_ival fields of the cells are all 0. */ Partition::Cell* Graph::sh_first_largest_max_neighbours() { Partition::Cell* best_cell = 0; int best_value = -1; unsigned int best_size = 0; KStack neighbour_cells_visited; neighbour_cells_visited.init(get_nof_vertices()); for(Partition::Cell* cell = p.first_nonsingleton_cell; cell; cell = cell->next_nonsingleton) { if(opt_use_comprec and p.cr_get_level(cell->first) != cr_level) continue; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { Partition::Cell* const neighbour_cell = p.get_cell(*ei++); if(neighbour_cell->is_unit()) continue; neighbour_cell->max_ival++; if(neighbour_cell->max_ival == 1) neighbour_cells_visited.push(neighbour_cell); } int value = 0; while(!neighbour_cells_visited.is_empty()) { Partition::Cell* const neighbour_cell = neighbour_cells_visited.pop(); if(neighbour_cell->max_ival != neighbour_cell->length) value++; neighbour_cell->max_ival = 0; } if((value > best_value) or (value == best_value and cell->length > best_size)) { best_value = value; best_size = cell->length; best_cell = cell; } } return best_cell; } /*------------------------------------------------------------------------- * * Initialize the certificate size and memory * *-------------------------------------------------------------------------*/ void Graph::initialize_certificate() { certificate_index = 0; certificate_current_path.clear(); certificate_first_path.clear(); certificate_best_path.clear(); } /*------------------------------------------------------------------------- * * Check whether perm is an automorphism. * Slow, mainly for debugging and validation purposes. * *-------------------------------------------------------------------------*/ bool Graph::is_automorphism(unsigned int* const perm) { std::set > edges1; std::set > edges2; #if defined(BLISS_CONSISTENCY_CHECKS) if(!is_permutation(get_nof_vertices(), perm)) _INTERNAL_ERROR(); #endif for(unsigned int i = 0; i < get_nof_vertices(); i++) { Vertex& v1 = vertices[i]; edges1.clear(); for(std::vector::iterator ei = v1.edges.begin(); ei != v1.edges.end(); ei++) edges1.insert(perm[*ei]); Vertex& v2 = vertices[perm[i]]; edges2.clear(); for(std::vector::iterator ei = v2.edges.begin(); ei != v2.edges.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; } return true; } bool Graph::is_automorphism(const std::vector& perm) const { if(!(perm.size() == get_nof_vertices() and is_permutation(perm))) return false; std::set > edges1; std::set > edges2; for(unsigned int i = 0; i < get_nof_vertices(); i++) { const Vertex& v1 = vertices[i]; edges1.clear(); for(std::vector::const_iterator ei = v1.edges.begin(); ei != v1.edges.end(); ei++) edges1.insert(perm[*ei]); const Vertex& v2 = vertices[perm[i]]; edges2.clear(); for(std::vector::const_iterator ei = v2.edges.begin(); ei != v2.edges.end(); ei++) edges2.insert(*ei); if(!(edges1 == edges2)) return false; } return true; } bool Graph::nucr_find_first_component(const unsigned int level) { cr_component.clear(); cr_component_elements = 0; /* Find first non-discrete cell in the component level */ Partition::Cell* first_cell = p.first_nonsingleton_cell; while(first_cell) { if(p.cr_get_level(first_cell->first) == level) break; first_cell = first_cell->next_nonsingleton; } /* The component is discrete, return false */ if(!first_cell) return false; std::vector component; first_cell->max_ival = 1; component.push_back(first_cell); for(unsigned int i = 0; i < component.size(); i++) { Partition::Cell* const cell = component[i]; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /* Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Already marked to be in the same component? */ if(neighbour_cell->max_ival == 1) continue; /* Is the neighbour at the same component recursion level? */ if(p.cr_get_level(neighbour_cell->first) != level) continue; if(neighbour_cell->max_ival_count == 0) neighbour_heap.insert(neighbour_cell->first); neighbour_cell->max_ival_count++; } while(!neighbour_heap.is_empty()) { const unsigned int start = neighbour_heap.remove(); Partition::Cell* const neighbour_cell = p.get_cell(p.elements[start]); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } neighbour_cell->max_ival_count = 0; neighbour_cell->max_ival = 1; component.push_back(neighbour_cell); } } for(unsigned int i = 0; i < component.size(); i++) { Partition::Cell* const cell = component[i]; cell->max_ival = 0; cr_component.push_back(cell->first); cr_component_elements += cell->length; } if(verbstr and verbose_level > 2) { fprintf(verbstr, "NU-component with %lu cells and %u vertices\n", (long unsigned)cr_component.size(), cr_component_elements); fflush(verbstr); } return true; } bool Graph::nucr_find_first_component(const unsigned int level, std::vector& component, unsigned int& component_elements, Partition::Cell*& sh_return) { component.clear(); component_elements = 0; sh_return = 0; unsigned int sh_first = 0; unsigned int sh_size = 0; unsigned int sh_nuconn = 0; /* Find first non-discrete cell in the component level */ Partition::Cell* first_cell = p.first_nonsingleton_cell; while(first_cell) { if(p.cr_get_level(first_cell->first) == level) break; first_cell = first_cell->next_nonsingleton; } if(!first_cell) { /* The component is discrete, return false */ return false; } std::vector comp; KStack neighbours; neighbours.init(get_nof_vertices()); first_cell->max_ival = 1; comp.push_back(first_cell); for(unsigned int i = 0; i < comp.size(); i++) { Partition::Cell* const cell = comp[i]; const Vertex& v = vertices[p.elements[cell->first]]; std::vector::const_iterator ei = v.edges.begin(); for(unsigned int j = v.nof_edges(); j > 0; j--) { const unsigned int neighbour = *ei++; Partition::Cell* const neighbour_cell = p.get_cell(neighbour); /* Skip unit neighbours */ if(neighbour_cell->is_unit()) continue; /* Is the neighbour at the same component recursion level? */ //if(p.cr_get_level(neighbour_cell->first) != level) // continue; if(neighbour_cell->max_ival_count == 0) neighbours.push(neighbour_cell); neighbour_cell->max_ival_count++; } unsigned int nuconn = 1; while(!neighbours.is_empty()) { Partition::Cell* const neighbour_cell = neighbours.pop(); //neighbours.pop_back(); /* Skip saturated neighbour cells */ if(neighbour_cell->max_ival_count == neighbour_cell->length) { neighbour_cell->max_ival_count = 0; continue; } nuconn++; neighbour_cell->max_ival_count = 0; if(neighbour_cell->max_ival == 0) { comp.push_back(neighbour_cell); neighbour_cell->max_ival = 1; } } switch(sh) { case shs_f: if(sh_return == 0 or cell->first <= sh_first) { sh_return = cell; sh_first = cell->first; } break; case shs_fs: if(sh_return == 0 or cell->length < sh_size or (cell->length == sh_size and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; } break; case shs_fl: if(sh_return == 0 or cell->length > sh_size or (cell->length == sh_size and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; } break; case shs_fm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and cell->first <= sh_first)) { sh_return = cell; sh_first = cell->first; sh_nuconn = nuconn; } break; case shs_fsm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and (cell->length < sh_size or (cell->length == sh_size and cell->first <= sh_first)))) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; sh_nuconn = nuconn; } break; case shs_flm: if(sh_return == 0 or nuconn > sh_nuconn or (nuconn == sh_nuconn and (cell->length > sh_size or (cell->length == sh_size and cell->first <= sh_first)))) { sh_return = cell; sh_first = cell->first; sh_size = cell->length; sh_nuconn = nuconn; } break; default: fatal_error("Internal error - unknown splitting heuristics"); return 0; } } assert(sh_return); for(unsigned int i = 0; i < comp.size(); i++) { Partition::Cell* const cell = comp[i]; cell->max_ival = 0; component.push_back(cell->first); component_elements += cell->length; } if(verbstr and verbose_level > 2) { fprintf(verbstr, "NU-component with %lu cells and %u vertices\n", (long unsigned)component.size(), component_elements); fflush(verbstr); } return true; } } igraph/src/bliss/utils.hh0000644000175100001440000000400713430770176015137 0ustar hornikusers#ifndef BLISS_UTILS_HH #define BLISS_UTILS_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ /** * \file * \brief Some small utilities. * */ #include using namespace std; namespace bliss { /** * Print the permutation \a perm of {0,...,N-1} in the cycle format * in the file stream \a fp. * The amount \a offset is added to each element before printing, * e.g. the permutation (2 4) is printed as (3 5) when \a offset is 1. */ void print_permutation(FILE* fp, const unsigned int N, const unsigned int* perm, const unsigned int offset = 0); /** * Print the permutation \a perm of {0,...,N-1} in the cycle format * in the file stream \a fp. * The amount \a offset is added to each element before printing, * e.g. the permutation (2 4) is printed as (3 5) when \a offset is 1. */ void print_permutation(FILE* fp, const std::vector& perm, const unsigned int offset = 0); /** * Check whether \a perm is a valid permutation on {0,...,N-1}. * Slow, mainly for debugging and validation purposes. */ bool is_permutation(const unsigned int N, const unsigned int* perm); /** * Check whether \a perm is a valid permutation on {0,...,N-1}. * Slow, mainly for debugging and validation purposes. */ bool is_permutation(const std::vector& perm); } // namespace bliss #endif igraph/src/bliss/uintseqhash.cc0000644000175100001440000001052413431000472016304 0ustar hornikusers#include "uintseqhash.hh" /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { /* * Random bits generated by * http://www.fourmilab.ch/hotbits/ */ static unsigned int rtab[256] = { 0xAEAA35B8, 0x65632E16, 0x155EDBA9, 0x01349B39, 0x8EB8BD97, 0x8E4C5367, 0x8EA78B35, 0x2B1B4072, 0xC1163893, 0x269A8642, 0xC79D7F6D, 0x6A32DEA0, 0xD4D2DA56, 0xD96D4F47, 0x47B5F48A, 0x2587C6BF, 0x642B71D8, 0x5DBBAF58, 0x5C178169, 0xA16D9279, 0x75CDA063, 0x291BC48B, 0x01AC2F47, 0x5416DF7C, 0x45307514, 0xB3E1317B, 0xE1C7A8DE, 0x3ACDAC96, 0x11B96831, 0x32DE22DD, 0x6A1DA93B, 0x58B62381, 0x283810E2, 0xBC30E6A6, 0x8EE51705, 0xB06E8DFB, 0x729AB12A, 0xA9634922, 0x1A6E8525, 0x49DD4E19, 0xE5DB3D44, 0x8C5B3A02, 0xEBDE2864, 0xA9146D9F, 0x736D2CB4, 0xF5229F42, 0x712BA846, 0x20631593, 0x89C02603, 0xD5A5BF6A, 0x823F4E18, 0x5BE5DEFF, 0x1C4EBBFA, 0x5FAB8490, 0x6E559B0C, 0x1FE528D6, 0xB3198066, 0x4A965EB5, 0xFE8BB3D5, 0x4D2F6234, 0x5F125AA4, 0xBCC640FA, 0x4F8BC191, 0xA447E537, 0xAC474D3C, 0x703BFA2C, 0x617DC0E7, 0xF26299D7, 0xC90FD835, 0x33B71C7B, 0x6D83E138, 0xCBB1BB14, 0x029CF5FF, 0x7CBD093D, 0x4C9825EF, 0x845C4D6D, 0x124349A5, 0x53942D21, 0x800E60DA, 0x2BA6EB7F, 0xCEBF30D3, 0xEB18D449, 0xE281F724, 0x58B1CB09, 0xD469A13D, 0x9C7495C3, 0xE53A7810, 0xA866C08E, 0x832A038B, 0xDDDCA484, 0xD5FE0DDE, 0x0756002B, 0x2FF51342, 0x60FEC9C8, 0x061A53E3, 0x47B1884E, 0xDC17E461, 0xA17A6A37, 0x3158E7E2, 0xA40D873B, 0x45AE2140, 0xC8F36149, 0x63A4EE2D, 0xD7107447, 0x6F90994F, 0x5006770F, 0xC1F3CA9A, 0x91B317B2, 0xF61B4406, 0xA8C9EE8F, 0xC6939B75, 0xB28BBC3B, 0x36BF4AEF, 0x3B12118D, 0x4D536ECF, 0x9CF4B46B, 0xE8AB1E03, 0x8225A360, 0x7AE4A130, 0xC4EE8B50, 0x50651797, 0x5BB4C59F, 0xD120EE47, 0x24F3A386, 0xBE579B45, 0x3A378EFC, 0xC5AB007B, 0x3668942B, 0x2DBDCC3A, 0x6F37F64C, 0xC24F862A, 0xB6F97FCF, 0x9E4FA23D, 0x551AE769, 0x46A8A5A6, 0xDC1BCFDD, 0x8F684CF9, 0x501D811B, 0x84279F80, 0x2614E0AC, 0x86445276, 0xAEA0CE71, 0x0812250F, 0xB586D18A, 0xC68D721B, 0x44514E1D, 0x37CDB99A, 0x24731F89, 0xFA72E589, 0x81E6EBA2, 0x15452965, 0x55523D9D, 0x2DC47E14, 0x2E7FA107, 0xA7790F23, 0x40EBFDBB, 0x77E7906B, 0x6C1DB960, 0x1A8B9898, 0x65FA0D90, 0xED28B4D8, 0x34C3ED75, 0x768FD2EC, 0xFAB60BCB, 0x962C75F4, 0x304F0498, 0x0A41A36B, 0xF7DE2A4A, 0xF4770FE2, 0x73C93BBB, 0xD21C82C5, 0x6C387447, 0x8CDB4CB9, 0x2CC243E8, 0x41859E3D, 0xB667B9CB, 0x89681E8A, 0x61A0526C, 0x883EDDDC, 0x539DE9A4, 0xC29E1DEC, 0x97C71EC5, 0x4A560A66, 0xBD7ECACF, 0x576AE998, 0x31CE5616, 0x97172A6C, 0x83D047C4, 0x274EA9A8, 0xEB31A9DA, 0x327209B5, 0x14D1F2CB, 0x00FE1D96, 0x817DBE08, 0xD3E55AED, 0xF2D30AFC, 0xFB072660, 0x866687D6, 0x92552EB9, 0xEA8219CD, 0xF7927269, 0xF1948483, 0x694C1DF5, 0xB7D8B7BF, 0xFFBC5D2F, 0x2E88B849, 0x883FD32B, 0xA0331192, 0x8CB244DF, 0x41FAF895, 0x16902220, 0x97FB512A, 0x2BEA3CC4, 0xAF9CAE61, 0x41ACD0D5, 0xFD2F28FF, 0xE780ADFA, 0xB3A3A76E, 0x7112AD87, 0x7C3D6058, 0x69E64FFF, 0xE5F8617C, 0x8580727C, 0x41F54F04, 0xD72BE498, 0x653D1795, 0x1275A327, 0x14B499D4, 0x4E34D553, 0x4687AA39, 0x68B64292, 0x5C18ABC3, 0x41EABFCC, 0x92A85616, 0x82684CF8, 0x5B9F8A4E, 0x35382FFE, 0xFB936318, 0x52C08E15, 0x80918B2E, 0x199EDEE0, 0xA9470163, 0xEC44ACDD, 0x612D6735, 0x8F88EA7D, 0x759F5EA4, 0xE5CC7240, 0x68CFEB8B, 0x04725601, 0x0C22C23E, 0x5BC97174, 0x89965841, 0x5D939479, 0x690F338A, 0x3C2D4380, 0xDAE97F2B }; void UintSeqHash::update(unsigned int i) { i++; while(i > 0) { h ^= rtab[i & 0xff]; #if 1 const unsigned int b = (h & 0x80000000) >> 31; i = i >> 8; h = (h << 1) | b; #else const unsigned int b = h & 0x80000000; h = h << 1; if(b != 0) h++; i = i >> 8; #endif } } } // namespace bliss igraph/src/bliss/partition.cc0000644000175100001440000006655313431000472015776 0ustar hornikusers#include #include #include #include "graph.hh" #include "partition.hh" /* use 'and' instead of '&&' */ #if _MSC_VER #include #endif /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { Partition::Partition() { N = 0; elements = 0; in_pos = 0; invariant_values = 0; cells = 0; free_cells = 0; element_to_cell_map = 0; graph = 0; discrete_cell_count = 0; /* Initialize a distribution count sorting array. */ for(unsigned int i = 0; i < 256; i++) dcs_count[i] = 0; cr_enabled = false; cr_cells = 0; cr_levels = 0; } Partition::~Partition() { if(elements) {free(elements); elements = 0; } if(cells) {free(cells); cells = 0; } if(element_to_cell_map) {free(element_to_cell_map); element_to_cell_map = 0; } if(in_pos) {free(in_pos); in_pos = 0; } if(invariant_values) {free(invariant_values); invariant_values = 0; } N = 0; } void Partition::init(const unsigned int M) { assert(M > 0); N = M; if(elements) free(elements); elements = (unsigned int*)malloc(N * sizeof(unsigned int)); for(unsigned int i = 0; i < N; i++) elements[i] = i; if(in_pos) free(in_pos); in_pos = (unsigned int**)malloc(N * sizeof(unsigned int*)); for(unsigned int i = 0; i < N; i++) in_pos[i] = elements + i; if(invariant_values) free(invariant_values); invariant_values = (unsigned int*)malloc(N * sizeof(unsigned int)); for(unsigned int i = 0; i < N; i++) invariant_values[i] = 0; if(cells) free(cells); cells = (Cell*)malloc(N * sizeof(Cell)); cells[0].first = 0; cells[0].length = N; cells[0].max_ival = 0; cells[0].max_ival_count = 0; cells[0].in_splitting_queue = false; cells[0].in_neighbour_heap = false; cells[0].prev = 0; cells[0].next = 0; cells[0].next_nonsingleton = 0; cells[0].prev_nonsingleton = 0; cells[0].split_level = 0; first_cell = &cells[0]; if(N == 1) { first_nonsingleton_cell = 0; discrete_cell_count = 1; } else { first_nonsingleton_cell = &cells[0]; discrete_cell_count = 0; } for(unsigned int i = 1; i < N; i++) { cells[i].first = 0; cells[i].length = 0; cells[i].max_ival = 0; cells[i].max_ival_count = 0; cells[i].in_splitting_queue = false; cells[i].in_neighbour_heap = false; cells[i].prev = 0; cells[i].next = (i < N-1)?&cells[i+1]:0; cells[i].next_nonsingleton = 0; cells[i].prev_nonsingleton = 0; } if(N > 1) free_cells = &cells[1]; else free_cells = 0; if(element_to_cell_map) free(element_to_cell_map); element_to_cell_map = (Cell **)malloc(N * sizeof(Cell *)); for(unsigned int i = 0; i < N; i++) element_to_cell_map[i] = first_cell; splitting_queue.init(N); refinement_stack.init(N); /* Reset the main backtracking stack */ bt_stack.clear(); } Partition::BacktrackPoint Partition::set_backtrack_point() { BacktrackInfo info; info.refinement_stack_size = refinement_stack.size(); if(cr_enabled) info.cr_backtrack_point = cr_get_backtrack_point(); BacktrackPoint p = bt_stack.size(); bt_stack.push_back(info); return p; } void Partition::goto_backtrack_point(BacktrackPoint p) { BacktrackInfo info = bt_stack[p]; bt_stack.resize(p); if(cr_enabled) cr_goto_backtrack_point(info.cr_backtrack_point); const unsigned int dest_refinement_stack_size = info.refinement_stack_size; assert(refinement_stack.size() >= dest_refinement_stack_size); while(refinement_stack.size() > dest_refinement_stack_size) { RefInfo i = refinement_stack.pop(); const unsigned int first = i.split_cell_first; Cell* cell = get_cell(elements[first]); if(cell->first != first) { assert(cell->first < first); assert(cell->split_level <= dest_refinement_stack_size); goto done; } assert(cell->split_level > dest_refinement_stack_size); while(cell->split_level > dest_refinement_stack_size) { assert(cell->prev); cell = cell->prev; } while(cell->next and cell->next->split_level > dest_refinement_stack_size) { /* Merge next cell */ Cell* const next_cell = cell->next; if(cell->length == 1) discrete_cell_count--; if(next_cell->length == 1) discrete_cell_count--; /* Update element_to_cell_map values of elements added in cell */ unsigned int* ep = elements + next_cell->first; unsigned int* const lp = ep + next_cell->length; for( ; ep < lp; ep++) element_to_cell_map[*ep] = cell; /* Update cell parameters */ cell->length += next_cell->length; if(next_cell->next) next_cell->next->prev = cell; cell->next = next_cell->next; /* (Pseudo)free next_cell */ next_cell->first = 0; next_cell->length = 0; next_cell->prev = 0; next_cell->next = free_cells; free_cells = next_cell; } done: if(i.prev_nonsingleton_first >= 0) { Cell* const prev_cell = get_cell(elements[i.prev_nonsingleton_first]); cell->prev_nonsingleton = prev_cell; prev_cell->next_nonsingleton = cell; } else { //assert(cell->prev_nonsingleton == 0); cell->prev_nonsingleton = 0; first_nonsingleton_cell = cell; } if(i.next_nonsingleton_first >= 0) { Cell* const next_cell = get_cell(elements[i.next_nonsingleton_first]); cell->next_nonsingleton = next_cell; next_cell->prev_nonsingleton = cell; } else { //assert(cell->next_nonsingleton == 0); cell->next_nonsingleton = 0; } } } Partition::Cell* Partition::individualize(Partition::Cell * const cell, const unsigned int element) { unsigned int * const pos = in_pos[element]; const unsigned int last = cell->first + cell->length - 1; *pos = elements[last]; in_pos[*pos] = pos; elements[last] = element; in_pos[element] = elements + last; Partition::Cell * const new_cell = aux_split_in_two(cell, cell->length-1); element_to_cell_map[element] = new_cell; return new_cell; } Partition::Cell* Partition::aux_split_in_two(Partition::Cell* const cell, const unsigned int first_half_size) { RefInfo i; /* (Pseudo)allocate new cell */ Cell * const new_cell = free_cells; free_cells = new_cell->next; /* Update new cell parameters */ new_cell->first = cell->first + first_half_size; new_cell->length = cell->length - first_half_size; new_cell->next = cell->next; if(new_cell->next) new_cell->next->prev = new_cell; new_cell->prev = cell; new_cell->split_level = refinement_stack.size()+1; /* Update old, splitted cell parameters */ cell->length = first_half_size; cell->next = new_cell; /* CR */ if(cr_enabled) cr_create_at_level_trailed(new_cell->first, cr_get_level(cell->first)); /* Add cell in refinement_stack for backtracking */ i.split_cell_first = new_cell->first; if(cell->prev_nonsingleton) i.prev_nonsingleton_first = cell->prev_nonsingleton->first; else i.prev_nonsingleton_first = -1; if(cell->next_nonsingleton) i.next_nonsingleton_first = cell->next_nonsingleton->first; else i.next_nonsingleton_first = -1; refinement_stack.push(i); /* Modify nonsingleton cell list */ if(new_cell->length > 1) { new_cell->prev_nonsingleton = cell; new_cell->next_nonsingleton = cell->next_nonsingleton; if(new_cell->next_nonsingleton) new_cell->next_nonsingleton->prev_nonsingleton = new_cell; cell->next_nonsingleton = new_cell; } else { new_cell->next_nonsingleton = 0; new_cell->prev_nonsingleton = 0; discrete_cell_count++; } if(cell->is_unit()) { if(cell->prev_nonsingleton) cell->prev_nonsingleton->next_nonsingleton = cell->next_nonsingleton; else first_nonsingleton_cell = cell->next_nonsingleton; if(cell->next_nonsingleton) cell->next_nonsingleton->prev_nonsingleton = cell->prev_nonsingleton; cell->next_nonsingleton = 0; cell->prev_nonsingleton = 0; discrete_cell_count++; } return new_cell; } size_t Partition::print(FILE* const fp, const bool add_newline) const { size_t r = 0; const char* cell_sep = ""; r += fprintf(fp, "["); for(Cell* cell = first_cell; cell; cell = cell->next) { /* Print cell */ r += fprintf(fp, "%s{", cell_sep); cell_sep = ","; const char* elem_sep = ""; for(unsigned int i = 0; i < cell->length; i++) { r += fprintf(fp, "%s%u", elem_sep, elements[cell->first + i]); elem_sep = ","; } r += fprintf(fp, "}"); } r += fprintf(fp, "]"); if(add_newline) r += fprintf(fp, "\n"); return r; } size_t Partition::print_signature(FILE* const fp, const bool add_newline) const { size_t r = 0; const char* cell_sep = ""; r += fprintf(fp, "["); for(Cell* cell = first_cell; cell; cell = cell->next) { if(cell->is_unit()) continue; //fprintf(fp, "%s%u", cell_sep, cr_cells[cell->first].level); r += fprintf(fp, "%s%u", cell_sep, cell->length); cell_sep = ","; } r += fprintf(fp, "]"); if(add_newline) r += fprintf(fp, "\n"); return r; } void Partition::splitting_queue_add(Cell* const cell) { static const unsigned int smallish_cell_threshold = 1; cell->in_splitting_queue = true; if(cell->length <= smallish_cell_threshold) splitting_queue.push_front(cell); else splitting_queue.push_back(cell); } void Partition::splitting_queue_clear() { while(!splitting_queue_is_empty()) splitting_queue_pop(); } /* * Assumes that the invariant values are NOT the same * and that the cell contains more than one element */ Partition::Cell* Partition::sort_and_split_cell1(Partition::Cell* const cell) { #if defined(BLISS_EXPENSIVE_CONSISTENCY_CHECKS) assert(cell->length > 1); assert(cell->first + cell->length <= N); unsigned int nof_0_found = 0; unsigned int nof_1_found = 0; for(unsigned int i = cell->first; i < cell->first + cell->length; i++) { const unsigned int ival = invariant_values[elements[i]]; assert(ival == 0 or ival == 1); if(ival == 0) nof_0_found++; else nof_1_found++; } assert(nof_0_found > 0); assert(nof_1_found > 0); assert(nof_1_found == cell->max_ival_count); assert(nof_0_found + nof_1_found == cell->length); assert(cell->max_ival == 1); #endif /* (Pseudo)allocate new cell */ Cell* const new_cell = free_cells; free_cells = new_cell->next; #define NEW_SORT1 #ifdef NEW_SORT1 unsigned int *ep0 = elements + cell->first; unsigned int *ep1 = ep0 + cell->length - cell->max_ival_count; if(cell->max_ival_count > cell->length / 2) { /* There are more ones than zeros, only move zeros */ unsigned int * const end = ep0 + cell->length; while(ep1 < end) { while(invariant_values[*ep1] == 0) { const unsigned int tmp = *ep1; *ep1 = *ep0; *ep0 = tmp; in_pos[tmp] = ep0; in_pos[*ep1] = ep1; ep0++; } element_to_cell_map[*ep1] = new_cell; invariant_values[*ep1] = 0; ep1++; } } else { /* There are more zeros than ones, only move ones */ unsigned int * const end = ep1; while(ep0 < end) { while(invariant_values[*ep0] != 0) { const unsigned int tmp = *ep0; *ep0 = *ep1; *ep1 = tmp; in_pos[tmp] = ep1; in_pos[*ep0] = ep0; ep1++; } ep0++; } ep1 = end; while(ep1 < elements + cell->first + cell->length) { element_to_cell_map[*ep1] = new_cell; invariant_values[*ep1] = 0; ep1++; } } /* Update new cell parameters */ new_cell->first = cell->first + cell->length - cell->max_ival_count; new_cell->length = cell->length - (new_cell->first - cell->first); new_cell->next = cell->next; if(new_cell->next) new_cell->next->prev = new_cell; new_cell->prev = cell; new_cell->split_level = refinement_stack.size()+1; /* Update old, splitted cell parameters */ cell->length = new_cell->first - cell->first; cell->next = new_cell; /* CR */ if(cr_enabled) cr_create_at_level_trailed(new_cell->first, cr_get_level(cell->first)); #else /* Sort vertices in the cell according to the invariant values */ unsigned int *ep0 = elements + cell->first; unsigned int *ep1 = ep0 + cell->length; while(ep1 > ep0) { const unsigned int element = *ep0; const unsigned int ival = invariant_values[element]; invariant_values[element] = 0; if(ival == 0) { ep0++; } else { ep1--; *ep0 = *ep1; *ep1 = element; element_to_cell_map[element] = new_cell; in_pos[element] = ep1; in_pos[*ep0] = ep0; } } /* Update new cell parameters */ new_cell->first = ep1 - elements; new_cell->length = cell->length - (new_cell->first - cell->first); new_cell->next = cell->next; if(new_cell->next) new_cell->next->prev = new_cell; new_cell->prev = cell; new_cell->split_level = cell->split_level; /* Update old, splitted cell parameters */ cell->length = new_cell->first - cell->first; cell->next = new_cell; cell->split_level = refinement_stack.size()+1; /* CR */ if(cr_enabled) cr_create_at_level_trailed(new_cell->first, cr_get_level(cell->first)); #endif /* ifdef NEW_SORT1*/ /* Add cell in refinement stack for backtracking */ { RefInfo i; i.split_cell_first = new_cell->first; if(cell->prev_nonsingleton) i.prev_nonsingleton_first = cell->prev_nonsingleton->first; else i.prev_nonsingleton_first = -1; if(cell->next_nonsingleton) i.next_nonsingleton_first = cell->next_nonsingleton->first; else i.next_nonsingleton_first = -1; /* Modify nonsingleton cell list */ if(new_cell->length > 1) { new_cell->prev_nonsingleton = cell; new_cell->next_nonsingleton = cell->next_nonsingleton; if(new_cell->next_nonsingleton) new_cell->next_nonsingleton->prev_nonsingleton = new_cell; cell->next_nonsingleton = new_cell; } else { new_cell->next_nonsingleton = 0; new_cell->prev_nonsingleton = 0; discrete_cell_count++; } if(cell->is_unit()) { if(cell->prev_nonsingleton) cell->prev_nonsingleton->next_nonsingleton = cell->next_nonsingleton; else first_nonsingleton_cell = cell->next_nonsingleton; if(cell->next_nonsingleton) cell->next_nonsingleton->prev_nonsingleton = cell->prev_nonsingleton; cell->next_nonsingleton = 0; cell->prev_nonsingleton = 0; discrete_cell_count++; } refinement_stack.push(i); } /* Add cells in splitting queue */ if(cell->in_splitting_queue) { /* Both cells must be included in splitting_queue in order to have refinement to equitable partition */ splitting_queue_add(new_cell); } else { Cell *min_cell, *max_cell; if(cell->length <= new_cell->length) { min_cell = cell; max_cell = new_cell; } else { min_cell = new_cell; max_cell = cell; } /* Put the smaller cell in splitting_queue */ splitting_queue_add(min_cell); if(max_cell->is_unit()) { /* Put the "larger" cell also in splitting_queue */ splitting_queue_add(max_cell); } } return new_cell; } /** * An auxiliary function for distribution count sorting. * Build start array so that * dcs_start[0] = 0 and dcs_start[i+1] = dcs_start[i] + dcs_count[i]. */ void Partition::dcs_cumulate_count(const unsigned int max) { unsigned int* count_p = dcs_count; unsigned int* start_p = dcs_start; unsigned int sum = 0; for(unsigned int i = max+1; i > 0; i--) { *start_p = sum; start_p++; sum += *count_p; count_p++; } } /** * Distribution count sorting of cells with invariant values less than 256. */ Partition::Cell* Partition::sort_and_split_cell255(Partition::Cell* const cell, const unsigned int max_ival) { if(cell->is_unit()) { /* Reset invariant value */ invariant_values[elements[cell->first]] = 0; return cell; } #ifdef BLISS_CONSISTENCY_CHECKS for(unsigned int i = 0; i < 256; i++) assert(dcs_count[i] == 0); #endif /* * Compute the distribution of invariant values to the count array */ { const unsigned int *ep = elements + cell->first; const unsigned int ival = invariant_values[*ep]; dcs_count[ival]++; ep++; #if defined(BLISS_CONSISTENCY_CHECKS) bool equal_invariant_values = true; #endif for(unsigned int i = cell->length - 1; i != 0; i--) { const unsigned int ival2 = invariant_values[*ep]; dcs_count[ival2]++; #if defined(BLISS_CONSISTENCY_CHECKS) if(ival2 != ival) { equal_invariant_values = false; } #endif ep++; } #if defined(BLISS_CONSISTENCY_CHECKS) assert(!equal_invariant_values); if(equal_invariant_values) { assert(dcs_count[ival] == cell->length); dcs_count[ival] = 0; clear_ivs(cell); return cell; } #endif } /* Build start array */ dcs_cumulate_count(max_ival); /* Do the sorting */ for(unsigned int i = 0; i <= max_ival; i++) { unsigned int *ep = elements + cell->first + dcs_start[i]; for(unsigned int j = dcs_count[i]; j > 0; j--) { while(true) { const unsigned int element = *ep; const unsigned int ival = invariant_values[element]; if(ival == i) break; *ep = elements[cell->first + dcs_start[ival]]; elements[cell->first + dcs_start[ival]] = element; dcs_start[ival]++; dcs_count[ival]--; } ep++; } dcs_count[i] = 0; } #if defined(BLISS_CONSISTENCY_CHECKS) for(unsigned int i = 0; i < 256; i++) assert(dcs_count[i] == 0); #endif /* split cell */ Cell* const new_cell = split_cell(cell); return new_cell; } /* * Sort the elements in a cell according to their invariant values. * The invariant values are not cleared. * Warning: the in_pos array is left in incorrect state. */ bool Partition::shellsort_cell(Partition::Cell* const cell) { unsigned int h; unsigned int* ep; if(cell->is_unit()) return false; /* Check whether all the elements have the same invariant value */ bool equal_invariant_values = true; { ep = elements + cell->first; const unsigned int ival = invariant_values[*ep]; ep++; for(unsigned int i = cell->length - 1; i > 0; i--) { if(invariant_values[*ep] != ival) { equal_invariant_values = false; break; } ep++; } } if(equal_invariant_values) return false; ep = elements + cell->first; for(h = 1; h <= cell->length/9; h = 3*h + 1) ; for( ; h > 0; h = h/3) { for(unsigned int i = h; i < cell->length; i++) { const unsigned int element = ep[i]; const unsigned int ival = invariant_values[element]; unsigned int j = i; while(j >= h and invariant_values[ep[j-h]] > ival) { ep[j] = ep[j-h]; j -= h; } ep[j] = element; } } return true; } void Partition::clear_ivs(Cell* const cell) { unsigned int* ep = elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) invariant_values[*ep] = 0; } /* * Assumes that the elements in the cell are sorted according to their * invariant values. */ Partition::Cell* Partition::split_cell(Partition::Cell* const original_cell) { Cell* cell = original_cell; const bool original_cell_was_in_splitting_queue = original_cell->in_splitting_queue; Cell* largest_new_cell = 0; while(true) { unsigned int* ep = elements + cell->first; const unsigned int* const lp = ep + cell->length; const unsigned int ival = invariant_values[*ep]; invariant_values[*ep] = 0; element_to_cell_map[*ep] = cell; in_pos[*ep] = ep; ep++; while(ep < lp) { const unsigned int e = *ep; if(invariant_values[e] != ival) break; invariant_values[e] = 0; in_pos[e] = ep; ep++; element_to_cell_map[e] = cell; } if(ep == lp) break; Cell* const new_cell = aux_split_in_two(cell, (ep - elements) - cell->first); if(graph and graph->compute_eqref_hash) { graph->eqref_hash.update(new_cell->first); graph->eqref_hash.update(new_cell->length); graph->eqref_hash.update(ival); } /* Add cells in splitting_queue */ assert(!new_cell->is_in_splitting_queue()); if(original_cell_was_in_splitting_queue) { /* In this case, all new cells are inserted in splitting_queue */ assert(cell->is_in_splitting_queue()); splitting_queue_add(new_cell); } else { /* Otherwise, we can omit one new cell from splitting_queue */ assert(!cell->is_in_splitting_queue()); if(largest_new_cell == 0) { largest_new_cell = cell; } else { assert(!largest_new_cell->is_in_splitting_queue()); if(cell->length > largest_new_cell->length) { splitting_queue_add(largest_new_cell); largest_new_cell = cell; } else { splitting_queue_add(cell); } } } /* Process the rest of the cell */ cell = new_cell; } if(original_cell == cell) { /* All the elements in cell had the same invariant value */ return cell; } /* Add cells in splitting_queue */ if(!original_cell_was_in_splitting_queue) { /* Also consider the last new cell */ assert(largest_new_cell); if(cell->length > largest_new_cell->length) { splitting_queue_add(largest_new_cell); largest_new_cell = cell; } else { splitting_queue_add(cell); } if(largest_new_cell->is_unit()) { /* Needed in certificate computation */ splitting_queue_add(largest_new_cell); } } return cell; } Partition::Cell* Partition::zplit_cell(Partition::Cell* const cell, const bool max_ival_info_ok) { Cell* last_new_cell = cell; if(!max_ival_info_ok) { /* Compute max_ival info */ assert(cell->max_ival == 0); assert(cell->max_ival_count == 0); unsigned int *ep = elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) { const unsigned int ival = invariant_values[*ep]; if(ival > cell->max_ival) { cell->max_ival = ival; cell->max_ival_count = 1; } else if(ival == cell->max_ival) { cell->max_ival_count++; } } } #ifdef BLISS_CONSISTENCY_CHECKS /* Verify max_ival info */ { unsigned int nof_zeros = 0; unsigned int max_ival = 0; unsigned int max_ival_count = 0; unsigned int *ep = elements + cell->first; for(unsigned int i = cell->length; i > 0; i--, ep++) { const unsigned int ival = invariant_values[*ep]; if(ival == 0) nof_zeros++; if(ival > max_ival) { max_ival = ival; max_ival_count = 1; } else if(ival == max_ival) max_ival_count++; } assert(max_ival == cell->max_ival); assert(max_ival_count == cell->max_ival_count); } #endif /* max_ival info has been computed */ if(cell->max_ival_count == cell->length) { /* All invariant values are the same, clear 'em */ if(cell->max_ival > 0) clear_ivs(cell); } else { /* All invariant values are not the same */ if(cell->max_ival == 1) { /* Specialized splitting for cells with binary invariant values */ last_new_cell = sort_and_split_cell1(cell); } else if(cell->max_ival < 256) { /* Specialized splitting for cells with invariant values < 256 */ last_new_cell = sort_and_split_cell255(cell, cell->max_ival); } else { /* Generic sorting and splitting */ const bool sorted = shellsort_cell(cell); assert(sorted); last_new_cell = split_cell(cell); } } cell->max_ival = 0; cell->max_ival_count = 0; return last_new_cell; } /* * * Component recursion specific code * */ void Partition::cr_init() { assert(bt_stack.empty()); cr_enabled = true; if(cr_cells) free(cr_cells); cr_cells = (CRCell*)malloc(N * sizeof(CRCell)); if(!cr_cells) {assert(false && "Mem out"); } if(cr_levels) free(cr_levels); cr_levels = (CRCell**)malloc(N * sizeof(CRCell*)); if(!cr_levels) {assert(false && "Mem out"); } for(unsigned int i = 0; i < N; i++) { cr_levels[i] = 0; cr_cells[i].level = UINT_MAX; cr_cells[i].next = 0; cr_cells[i].prev_next_ptr = 0; } for(const Cell *cell = first_cell; cell; cell = cell->next) cr_create_at_level_trailed(cell->first, 0); cr_max_level = 0; } void Partition::cr_free() { if(cr_cells) {free(cr_cells); cr_cells = 0; } if(cr_levels) {free(cr_levels); cr_levels = 0; } cr_created_trail.clear(); cr_splitted_level_trail.clear(); cr_bt_info.clear(); cr_max_level = 0; cr_enabled = false; } unsigned int Partition::cr_split_level(const unsigned int level, const std::vector& splitted_cells) { assert(cr_enabled); assert(level <= cr_max_level); cr_levels[++cr_max_level] = 0; cr_splitted_level_trail.push_back(level); for(unsigned int i = 0; i < splitted_cells.size(); i++) { const unsigned int cell_index = splitted_cells[i]; assert(cell_index < N); CRCell& cr_cell = cr_cells[cell_index]; assert(cr_cell.level == level); cr_cell.detach(); cr_create_at_level(cell_index, cr_max_level); } return cr_max_level; } unsigned int Partition::cr_get_backtrack_point() { assert(cr_enabled); CR_BTInfo info; info.created_trail_index = cr_created_trail.size(); info.splitted_level_trail_index = cr_splitted_level_trail.size(); cr_bt_info.push_back(info); return cr_bt_info.size()-1; } void Partition::cr_goto_backtrack_point(const unsigned int btpoint) { assert(cr_enabled); assert(btpoint < cr_bt_info.size()); while(cr_created_trail.size() > cr_bt_info[btpoint].created_trail_index) { const unsigned int cell_index = cr_created_trail.back(); cr_created_trail.pop_back(); CRCell& cr_cell = cr_cells[cell_index]; assert(cr_cell.level != UINT_MAX); assert(cr_cell.prev_next_ptr); cr_cell.detach(); } while(cr_splitted_level_trail.size() > cr_bt_info[btpoint].splitted_level_trail_index) { const unsigned int dest_level = cr_splitted_level_trail.back(); cr_splitted_level_trail.pop_back(); assert(cr_max_level > 0); assert(dest_level < cr_max_level); while(cr_levels[cr_max_level]) { CRCell *cr_cell = cr_levels[cr_max_level]; cr_cell->detach(); cr_create_at_level(cr_cell - cr_cells, dest_level); } cr_max_level--; } cr_bt_info.resize(btpoint); } void Partition::cr_create_at_level(const unsigned int cell_index, const unsigned int level) { assert(cr_enabled); assert(cell_index < N); assert(level < N); CRCell& cr_cell = cr_cells[cell_index]; assert(cr_cell.level == UINT_MAX); assert(cr_cell.next == 0); assert(cr_cell.prev_next_ptr == 0); if(cr_levels[level]) cr_levels[level]->prev_next_ptr = &(cr_cell.next); cr_cell.next = cr_levels[level]; cr_levels[level] = &cr_cell; cr_cell.prev_next_ptr = &cr_levels[level]; cr_cell.level = level; } void Partition::cr_create_at_level_trailed(const unsigned int cell_index, const unsigned int level) { assert(cr_enabled); cr_create_at_level(cell_index, level); cr_created_trail.push_back(cell_index); } } // namespace bliss igraph/src/bliss/orbit.hh0000644000175100001440000000601513430770176015117 0ustar hornikusers#ifndef BLISS_ORBIT_HH #define BLISS_ORBIT_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { /** \internal * \brief A class for representing orbit information. * * Given a set {0,...,N-1} of N elements, represent equivalence * classes (that is, unordered partitions) of the elements. * Supports only equivalence class merging, not splitting. * Merging two classes requires time O(k), where k is the number of * the elements in the smaller of the merged classes. * Getting the smallest representative in a class (and thus testing * whether two elements belong to the same class) is a constant time operation. */ class Orbit { class OrbitEntry { public: unsigned int element; OrbitEntry *next; unsigned int size; }; OrbitEntry *orbits; OrbitEntry **in_orbit; unsigned int nof_elements; unsigned int _nof_orbits; void merge_orbits(OrbitEntry *o1, OrbitEntry *o2); public: /** * Create a new orbit information object. * The init() function must be called next to actually initialize * the object. */ Orbit(); ~Orbit(); /** * Initialize the orbit information to consider sets of \a N elements. * It is required that \a N > 0. * The orbit information is reset so that each element forms * an orbit of its own. * Time complexity is O(N). * \sa reset() */ void init(const unsigned int N); /** * Reset the orbits so that each element forms an orbit of its own. * Time complexity is O(N). */ void reset(); /** * Merge the orbits of the elements \a e1 and \a e2. * Time complexity is O(k), where k is the number of elements in * the smaller of the merged orbits. */ void merge_orbits(unsigned int e1, unsigned int e2); /** * Is the element \a e the smallest element in its orbit? * Time complexity is O(1). */ bool is_minimal_representative(unsigned int e) const; /** * Get the smallest element in the orbit of the element \a e. * Time complexity is O(1). */ unsigned int get_minimal_representative(unsigned int e) const; /** * Get the number of elements in the orbit of the element \a e. * Time complexity is O(1). */ unsigned int orbit_size(unsigned int e) const; /** * Get the number of orbits. * Time complexity is O(1). */ unsigned int nof_orbits() const {return _nof_orbits; } }; } // namespace bliss #endif igraph/src/bliss/orbit.cc0000644000175100001440000000564613431000472015100 0ustar hornikusers#include #include #include "defs.hh" #include "orbit.hh" /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { Orbit::Orbit() { orbits = 0; in_orbit = 0; nof_elements = 0; } Orbit::~Orbit() { if(orbits) { free(orbits); orbits = 0; } if(in_orbit) { free(in_orbit); in_orbit = 0; } nof_elements = 0; } void Orbit::init(const unsigned int n) { assert(n > 0); if(orbits) free(orbits); orbits = (OrbitEntry*)malloc(n * sizeof(OrbitEntry)); if(in_orbit) free(in_orbit); in_orbit = (OrbitEntry**)malloc(n * sizeof(OrbitEntry*)); nof_elements = n; reset(); } void Orbit::reset() { assert(orbits); assert(in_orbit); for(unsigned int i = 0; i < nof_elements; i++) { orbits[i].element = i; orbits[i].next = 0; orbits[i].size = 1; in_orbit[i] = &orbits[i]; } _nof_orbits = nof_elements; } void Orbit::merge_orbits(OrbitEntry *orbit1, OrbitEntry *orbit2) { if(orbit1 != orbit2) { _nof_orbits--; /* Only update the elements in the smaller orbit */ if(orbit1->size > orbit2->size) { OrbitEntry * const temp = orbit2; orbit2 = orbit1; orbit1 = temp; } /* Link the elements of orbit1 to the almost beginning of orbit2 */ OrbitEntry *e = orbit1; while(e->next) { in_orbit[e->element] = orbit2; e = e->next; } in_orbit[e->element] = orbit2; e->next = orbit2->next; orbit2->next = orbit1; /* Keep the minimal orbit representative in the beginning */ if(orbit1->element < orbit2->element) { const unsigned int temp = orbit1->element; orbit1->element = orbit2->element; orbit2->element = temp; } orbit2->size += orbit1->size; } } void Orbit::merge_orbits(unsigned int e1, unsigned int e2) { merge_orbits(in_orbit[e1], in_orbit[e2]); } bool Orbit::is_minimal_representative(unsigned int element) const { return(get_minimal_representative(element) == element); } unsigned int Orbit::get_minimal_representative(unsigned int element) const { OrbitEntry * const orbit = in_orbit[element]; return(orbit->element); } unsigned int Orbit::orbit_size(unsigned int element) const { return(in_orbit[element]->size); } } // namespace bliss igraph/src/bliss/bliss_heap.cc0000644000175100001440000000402313431000472016056 0ustar hornikusers#include #include #include #include "defs.hh" #include "heap.hh" /* use 'and' instead of '&&' */ #if _MSC_VER #include #endif /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { Heap::~Heap() { if(array) { free(array); array = 0; n = 0; N = 0; } } void Heap::upheap(unsigned int index) { const unsigned int v = array[index]; array[0] = 0; while(array[index/2] > v) { array[index] = array[index/2]; index = index/2; } array[index] = v; } void Heap::downheap(unsigned int index) { const unsigned int v = array[index]; const unsigned int lim = n/2; while(index <= lim) { unsigned int new_index = index + index; if((new_index < n) and (array[new_index] > array[new_index+1])) new_index++; if(v <= array[new_index]) break; array[index] = array[new_index]; index = new_index; } array[index] = v; } void Heap::init(const unsigned int size) { if(size > N) { if(array) free(array); array = (unsigned int*)malloc((size + 1) * sizeof(unsigned int)); N = size; } n = 0; } void Heap::insert(const unsigned int v) { array[++n] = v; upheap(n); } unsigned int Heap::remove() { const unsigned int v = array[1]; array[1] = array[n--]; downheap(1); return v; } } // namespace bliss igraph/src/bliss/partition.hh0000644000175100001440000002033313430770176016010 0ustar hornikusers#ifndef BLISS_PARTITION_HH #define BLISS_PARTITION_HH /* Copyright (c) 2003-2015 Tommi Junttila Released under the GNU Lesser General Public License version 3. This file is part of bliss. bliss is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3 of the License. bliss is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with bliss. If not, see . */ namespace bliss { class Partition; } #include #include #include #include "kstack.hh" #include "kqueue.hh" #include "heap.hh" #include "orbit.hh" #include "graph.hh" namespace bliss { /** \internal * \brief A class for refinable, backtrackable ordered partitions. * * This is rather a data structure with some helper functions than * a proper self-contained class. * That is, for efficiency reasons the fields of this class are directly * manipulated from bliss::AbstractGraph and its subclasses. * Conversely, some methods of this class modify the fields of * bliss::AbstractGraph, too. */ class Partition { public: /** * \brief Data structure for holding information about a cell in a Partition. */ class Cell { friend class Partition; public: unsigned int length; /* Index of the first element of the cell in the Partition::elements array */ unsigned int first; unsigned int max_ival; unsigned int max_ival_count; private: bool in_splitting_queue; public: bool in_neighbour_heap; /* Pointer to the next cell, null if this is the last one. */ Cell* next; Cell* prev; Cell* next_nonsingleton; Cell* prev_nonsingleton; unsigned int split_level; /** Is this a unit cell? */ bool is_unit() const {return(length == 1); } /** Is this cell in splitting queue? */ bool is_in_splitting_queue() const {return(in_splitting_queue); } }; private: /** \internal * Data structure for remembering information about splits in order to * perform efficient backtracking over the splits. */ class RefInfo { public: unsigned int split_cell_first; int prev_nonsingleton_first; int next_nonsingleton_first; }; /** \internal * A stack for remembering the splits, used for backtracking. */ KStack refinement_stack; class BacktrackInfo { public: unsigned int refinement_stack_size; unsigned int cr_backtrack_point; }; /** \internal * The main stack for enabling backtracking. */ std::vector bt_stack; public: AbstractGraph* graph; /* Used during equitable partition refinement */ KQueue splitting_queue; void splitting_queue_add(Cell* const cell); Cell* splitting_queue_pop(); bool splitting_queue_is_empty() const; void splitting_queue_clear(); /** Type for backtracking points. */ typedef unsigned int BacktrackPoint; /** * Get a new backtrack point for the current partition */ BacktrackPoint set_backtrack_point(); /** * Backtrack to the point \a p and remove it. */ void goto_backtrack_point(BacktrackPoint p); /** * Split the non-unit Cell \a cell = {\a element,e1,e2,...,en} containing * the element \a element in two: * \a cell = {e1,...,en} and \a newcell = {\a element}. * @param cell a non-unit Cell * @param element an element in \a cell * @return the new unit Cell \a newcell */ Cell* individualize(Cell* const cell, const unsigned int element); Cell* aux_split_in_two(Cell* const cell, const unsigned int first_half_size); private: unsigned int N; Cell* cells; Cell* free_cells; unsigned int discrete_cell_count; public: Cell* first_cell; Cell* first_nonsingleton_cell; unsigned int *elements; /* invariant_values[e] gives the invariant value of the element e */ unsigned int *invariant_values; /* element_to_cell_map[e] gives the cell of the element e */ Cell **element_to_cell_map; /** Get the cell of the element \a e */ Cell* get_cell(const unsigned int e) const { return element_to_cell_map[e]; } /* in_pos[e] points to the elements array s.t. *in_pos[e] = e */ unsigned int **in_pos; Partition(); ~Partition(); /** * Initialize the partition to the unit partition (all elements in one cell) * over the \a N > 0 elements {0,...,\a N-1}. */ void init(const unsigned int N); /** * Returns true iff the partition is discrete, meaning that all * the elements are in their own cells. */ bool is_discrete() const {return(free_cells == 0); } unsigned int nof_discrete_cells() const {return(discrete_cell_count); } /** * Print the partition into the file stream \a fp. */ size_t print(FILE* const fp, const bool add_newline = true) const; /** * Print the partition cell sizes into the file stream \a fp. */ size_t print_signature(FILE* const fp, const bool add_newline = true) const; /* * Splits the Cell \a cell into [cell_1,...,cell_n] * according to the invariant_values of the elements in \a cell. * After splitting, cell_1 == \a cell. * Returns the pointer to the Cell cell_n; * cell_n != cell iff the Cell \a cell was actually splitted. * The flag \a max_ival_info_ok indicates whether the max_ival and * max_ival_count fields of the Cell \a cell have consistent values * when the method is called. * Clears the invariant values of elements in the Cell \a cell as well as * the max_ival and max_ival_count fields of the Cell \a cell. */ Cell *zplit_cell(Cell * const cell, const bool max_ival_info_ok); /* * Routines for component recursion */ void cr_init(); void cr_free(); unsigned int cr_get_level(const unsigned int cell_index) const; unsigned int cr_split_level(const unsigned int level, const std::vector& cells); /** Clear the invariant_values of the elements in the Cell \a cell. */ void clear_ivs(Cell* const cell); private: /* * Component recursion data structures */ /* Is component recursion support in use? */ bool cr_enabled; class CRCell { public: unsigned int level; CRCell* next; CRCell** prev_next_ptr; void detach() { if(next) next->prev_next_ptr = prev_next_ptr; *(prev_next_ptr) = next; level = UINT_MAX; next = 0; prev_next_ptr = 0; } }; CRCell* cr_cells; CRCell** cr_levels; class CR_BTInfo { public: unsigned int created_trail_index; unsigned int splitted_level_trail_index; }; std::vector cr_created_trail; std::vector cr_splitted_level_trail; std::vector cr_bt_info; unsigned int cr_max_level; void cr_create_at_level(const unsigned int cell_index, unsigned int level); void cr_create_at_level_trailed(const unsigned int cell_index, unsigned int level); unsigned int cr_get_backtrack_point(); void cr_goto_backtrack_point(const unsigned int btpoint); /* * * Auxiliary routines for sorting and splitting cells * */ Cell* sort_and_split_cell1(Cell* cell); Cell* sort_and_split_cell255(Cell* const cell, const unsigned int max_ival); bool shellsort_cell(Cell* cell); Cell* split_cell(Cell* const cell); /* * Some auxiliary stuff needed for distribution count sorting. * To make the code thread-safe (modulo the requirement that each graph is * only accessed in one thread at a time), the arrays are owned by * the partition instance, not statically defined. */ unsigned int dcs_count[256]; unsigned int dcs_start[256]; void dcs_cumulate_count(const unsigned int max); }; inline Partition::Cell* Partition::splitting_queue_pop() { Cell* const cell = splitting_queue.pop_front(); cell->in_splitting_queue = false; return cell; } inline bool Partition::splitting_queue_is_empty() const { return splitting_queue.is_empty(); } inline unsigned int Partition::cr_get_level(const unsigned int cell_index) const { return(cr_cells[cell_index].level); } } // namespace bliss #endif igraph/src/scg_approximate_methods.c0000644000175100001440000001311213431000472017375 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-12 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * The intervals_method and intervals_plus_kmeans implements the * methods of sec. 5.3.2 and sec. 5.3.3 of the above reference. * They take an eigenvector 'v' as parameter and a vector 'breaks' * of length 'nb', which provide the intervals used to cut 'v'. * Then all components of 'v' that fall into the same interval are * assigned the same group label in 'gr'. The group labels are * positive consecutive integers starting from 0. * The intervals_method function is adapted from bincode of the R * base package. * The intervals_plus_kmeans is initialized with regularly-spaced * breaks, which rougly corresponds to the intervals_method. Then * kmeans minimizes iteratively the objective function until it gets * stuck in a (usually) local minimum, or until 'itermax' is reached. * So far, the breaks_computation function allows computation of * constant bins, as used in intervals_method, and of equidistant * centers as used in intervals_plus_kmeans. */ #include "igraph_error.h" #include "igraph_types.h" #include "scg_headers.h" #include "igraph_memory.h" #include "igraph_vector.h" int igraph_i_intervals_plus_kmeans(const igraph_vector_t *v, int *gr, int n, int n_interv, int maxiter) { int i; igraph_vector_t centers; IGRAPH_VECTOR_INIT_FINALLY(¢ers, n_interv); igraph_i_breaks_computation(v, ¢ers, n_interv, 2); IGRAPH_CHECK(igraph_i_kmeans_Lloyd(v, n, 1, ¢ers, n_interv, gr, maxiter)); /*renumber the groups*/ for (i=0; i= 2) { new = (hi + lo)/2; if (VECTOR(*v)[i] > VECTOR(breaks)[new] || (lft && VECTOR(*v)[i] == VECTOR(breaks)[new])) { lo = new; } else { hi = new; } } gr[i] = lo; } } igraph_vector_destroy(&breaks); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_breaks_computation(const igraph_vector_t *v, igraph_vector_t *breaks, int nb, int method) { int i; igraph_real_t eps, vmin, vmax; igraph_vector_minmax(v, &vmin, &vmax); if (vmax == vmin) { IGRAPH_ERROR("There is only one (repeated) value in argument 'v' " "of bin_size_computation()", IGRAPH_EINVAL); } if (nb < 2) { IGRAPH_ERROR("'nb' in bin_size_computation() must be >= 2", IGRAPH_EINVAL); } switch (method) { case 1: /* constant bins for fixed-size intervals method */ eps = (vmax - vmin) / (igraph_real_t)(nb-1); VECTOR(*breaks)[0] = vmin; for (i=1; i sort XREAL,XIMAG into increasing order of magnitude. c 'SM' -> sort XREAL,XIMAG into decreasing order of magnitude. c 'LR' -> sort XREAL into increasing order of algebraic. c 'SR' -> sort XREAL into decreasing order of algebraic. c 'LI' -> sort XIMAG into increasing order of magnitude. c 'SI' -> sort XIMAG into decreasing order of magnitude. c NOTE: If an element of XIMAG is non-zero, then its negative c is also an element. c c APPLY Logical. (Input) c APPLY = .TRUE. -> apply the sorted order to array Y. c APPLY = .FALSE. -> do not apply the sorted order to array Y. c c N Integer. (INPUT) c Size of the arrays. c c XREAL, Double precision array of length N. (INPUT/OUTPUT) c XIMAG Real and imaginary part of the array to be sorted. c c Y Double precision array of length N. (INPUT/OUTPUT) c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.1' c Adapted from the sort routine in LANSO. c c\SCCS Information: @(#) c FILE: sortc.F SID: 2.3 DATE OF SID: 4/20/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsortc (which, apply, n, xreal, ximag, y) c c %------------------% c | Scalar Arguments | c %------------------% c character*2 which logical apply integer n c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & xreal(0:n-1), ximag(0:n-1), y(0:n-1) c c %---------------% c | Local Scalars | c %---------------% c integer i, igap, j Double precision & temp, temp1, temp2 c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlapy2 external dlapy2 c c %-----------------------% c | Executable Statements | c %-----------------------% c igap = n / 2 c if (which .eq. 'LM') then c c %------------------------------------------------------% c | Sort XREAL,XIMAG into increasing order of magnitude. | c %------------------------------------------------------% c 10 continue if (igap .eq. 0) go to 9000 c do 30 i = igap, n-1 j = i-igap 20 continue c if (j.lt.0) go to 30 c temp1 = dlapy2(xreal(j),ximag(j)) temp2 = dlapy2(xreal(j+igap),ximag(j+igap)) c if (temp1.gt.temp2) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 30 end if j = j-igap go to 20 30 continue igap = igap / 2 go to 10 c else if (which .eq. 'SM') then c c %------------------------------------------------------% c | Sort XREAL,XIMAG into decreasing order of magnitude. | c %------------------------------------------------------% c 40 continue if (igap .eq. 0) go to 9000 c do 60 i = igap, n-1 j = i-igap 50 continue c if (j .lt. 0) go to 60 c temp1 = dlapy2(xreal(j),ximag(j)) temp2 = dlapy2(xreal(j+igap),ximag(j+igap)) c if (temp1.lt.temp2) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 60 endif j = j-igap go to 50 60 continue igap = igap / 2 go to 40 c else if (which .eq. 'LR') then c c %------------------------------------------------% c | Sort XREAL into increasing order of algebraic. | c %------------------------------------------------% c 70 continue if (igap .eq. 0) go to 9000 c do 90 i = igap, n-1 j = i-igap 80 continue c if (j.lt.0) go to 90 c if (xreal(j).gt.xreal(j+igap)) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 90 endif j = j-igap go to 80 90 continue igap = igap / 2 go to 70 c else if (which .eq. 'SR') then c c %------------------------------------------------% c | Sort XREAL into decreasing order of algebraic. | c %------------------------------------------------% c 100 continue if (igap .eq. 0) go to 9000 do 120 i = igap, n-1 j = i-igap 110 continue c if (j.lt.0) go to 120 c if (xreal(j).lt.xreal(j+igap)) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 120 endif j = j-igap go to 110 120 continue igap = igap / 2 go to 100 c else if (which .eq. 'LI') then c c %------------------------------------------------% c | Sort XIMAG into increasing order of magnitude. | c %------------------------------------------------% c 130 continue if (igap .eq. 0) go to 9000 do 150 i = igap, n-1 j = i-igap 140 continue c if (j.lt.0) go to 150 c if (abs(ximag(j)).gt.abs(ximag(j+igap))) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 150 endif j = j-igap go to 140 150 continue igap = igap / 2 go to 130 c else if (which .eq. 'SI') then c c %------------------------------------------------% c | Sort XIMAG into decreasing order of magnitude. | c %------------------------------------------------% c 160 continue if (igap .eq. 0) go to 9000 do 180 i = igap, n-1 j = i-igap 170 continue c if (j.lt.0) go to 180 c if (abs(ximag(j)).lt.abs(ximag(j+igap))) then temp = xreal(j) xreal(j) = xreal(j+igap) xreal(j+igap) = temp c temp = ximag(j) ximag(j) = ximag(j+igap) ximag(j+igap) = temp c if (apply) then temp = y(j) y(j) = y(j+igap) y(j+igap) = temp end if else go to 180 endif j = j-igap go to 170 180 continue igap = igap / 2 go to 160 end if c 9000 continue return c c %---------------% c | End of igraphdsortc | c %---------------% c end igraph/src/spmatrix.c0000644000175100001440000007235013431000472014345 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_spmatrix.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \section igraph_spmatrix_constructor_and_destructor Sparse matrix constructors * and destructors. */ /** * \ingroup matrix * \function igraph_spmatrix_init * \brief Initializes a sparse matrix. * * * Every sparse matrix needs to be initialized before using it, this is done * by calling this function. A matrix has to be destroyed if it is not * needed any more, see \ref igraph_spmatrix_destroy(). * \param m Pointer to a not yet initialized sparse matrix object to be * initialized. * \param nrow The number of rows in the matrix. * \param ncol The number of columns in the matrix. * \return Error code. * * Time complexity: operating system dependent. */ int igraph_spmatrix_init(igraph_spmatrix_t *m, long int nrow, long int ncol) { assert(m != NULL); IGRAPH_VECTOR_INIT_FINALLY(&m->ridx, 0); IGRAPH_VECTOR_INIT_FINALLY(&m->cidx, ncol+1); IGRAPH_VECTOR_INIT_FINALLY(&m->data, 0); IGRAPH_FINALLY_CLEAN(3); m->nrow=nrow; m->ncol=ncol; return 0; } /** * \ingroup matrix * \function igraph_spmatrix_destroy * \brief Destroys a sparse matrix object. * * * This function frees all the memory allocated for a sparse matrix * object. The destroyed object needs to be reinitialized before using * it again. * \param m The matrix to destroy. * * Time complexity: operating system dependent. */ void igraph_spmatrix_destroy(igraph_spmatrix_t *m) { assert(m != NULL); igraph_vector_destroy(&m->ridx); igraph_vector_destroy(&m->cidx); igraph_vector_destroy(&m->data); } /** * \ingroup matrix * \function igraph_spmatrix_copy * \brief Copies a sparse matrix. * * * Creates a sparse matrix object by copying another one. * \param to Pointer to an uninitialized sparse matrix object. * \param from The initialized sparse matrix object to copy. * \return Error code, \c IGRAPH_ENOMEM if there * isn't enough memory to allocate the new sparse matrix. * * Time complexity: O(n), the number * of elements in the matrix. */ int igraph_spmatrix_copy(igraph_spmatrix_t *to, const igraph_spmatrix_t *from) { assert(from != NULL); assert(to != NULL); to->nrow = from->nrow; to->ncol = from->ncol; IGRAPH_CHECK(igraph_vector_copy(&to->ridx, &from->ridx)); IGRAPH_CHECK(igraph_vector_copy(&to->cidx, &from->cidx)); IGRAPH_CHECK(igraph_vector_copy(&to->data, &from->data)); return 0; } /** * \section igraph_spmatrix_accessing_elements Accessing elements of a sparse matrix */ /** * \ingroup matrix * \function igraph_spmatrix_e * \brief Accessing an element of a sparse matrix. * * Note that there are no range checks right now. * \param m The matrix object. * \param row The index of the row, starting with zero. * \param col The index of the column, starting with zero. * * Time complexity: O(log n), where n is the number of nonzero elements in * the requested column. */ igraph_real_t igraph_spmatrix_e(const igraph_spmatrix_t *m, long int row, long int col) { long int start, end; assert(m != NULL); start = (long) VECTOR(m->cidx)[col]; end = (long) VECTOR(m->cidx)[col+1]-1; if (enddata[start] and * m->data[end], inclusive, ordered by row index */ while (start < end-1) { long int mid=(start+end)/2; if (VECTOR(m->ridx)[mid] > row) { end=mid; } else if (VECTOR(m->ridx)[mid] < row) { start=mid; } else { start=mid; break; } } if (VECTOR(m->ridx)[start] == row) return VECTOR(m->data)[start]; if (VECTOR(m->ridx)[start] != row && VECTOR(m->ridx)[end] == row) return VECTOR(m->data)[end]; return 0; } /** * \ingroup matrix * \function igraph_spmatrix_set * \brief Setting an element of a sparse matrix. * * Note that there are no range checks right now. * \param m The matrix object. * \param row The index of the row, starting with zero. * \param col The index of the column, starting with zero. * \param value The new value. * * Time complexity: O(log n), where n is the number of nonzero elements in * the requested column. */ int igraph_spmatrix_set(igraph_spmatrix_t *m, long int row, long int col, igraph_real_t value) { long int start, end; assert(m != NULL); start = (long) VECTOR(m->cidx)[col]; end = (long) VECTOR(m->cidx)[col+1]-1; if (endridx, start, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start, value)); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]++; return 0; } /* Elements residing in column col are between m->data[start] and * m->data[end], inclusive, ordered by row index */ while (start < end-1) { long int mid=(start+end)/2; if (VECTOR(m->ridx)[mid] > row) { end=mid; } else if (VECTOR(m->ridx)[mid] < row) { start=mid; } else { start=mid; break; } } if (VECTOR(m->ridx)[start] == row) { /* Overwriting a value - or deleting it if it has been overwritten by zero */ if (value == 0) { igraph_vector_remove(&m->ridx, start); igraph_vector_remove(&m->data, start); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]--; } else { VECTOR(m->data)[start] = value; } return 0; } else if (VECTOR(m->ridx)[end] == row) { /* Overwriting a value - or deleting it if it has been overwritten by zero */ if (value == 0) { igraph_vector_remove(&m->ridx, end); igraph_vector_remove(&m->data, end); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]--; } else { VECTOR(m->data)[end] = value; } return 0; } /* New element has to be inserted, but only if not a zero is * being written into the matrix */ if (value != 0.0) { if (VECTOR(m->ridx)[end] < row) { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, end+1, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, end+1, value)); } else if (VECTOR(m->ridx)[start] < row) { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, start+1, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start+1, value)); } else { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, start, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start, value)); } for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]++; } return 0; } /** * \ingroup matrix * \function igraph_spmatrix_add_e * \brief Adding a real value to an element of a sparse matrix. * * Note that there are no range checks right now. This is implemented to avoid * double lookup of a given element in the matrix by using \ref igraph_spmatrix_e() * and \ref igraph_spmatrix_set() consecutively. * * \param m The matrix object. * \param row The index of the row, starting with zero. * \param col The index of the column, starting with zero. * \param value The value to add. * * Time complexity: O(log n), where n is the number of nonzero elements in * the requested column. */ int igraph_spmatrix_add_e(igraph_spmatrix_t *m, long int row, long int col, igraph_real_t value) { long int start, end; assert(m != NULL); start = (long) VECTOR(m->cidx)[col]; end = (long) VECTOR(m->cidx)[col+1]-1; if (endridx, start, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start, value)); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]++; return 0; } /* Elements residing in column col are between m->data[start] and * m->data[end], inclusive, ordered by row index */ while (start < end-1) { long int mid=(start+end)/2; if (VECTOR(m->ridx)[mid] > row) { end=mid; } else if (VECTOR(m->ridx)[mid] < row) { start=mid; } else { start=mid; break; } } if (VECTOR(m->ridx)[start] == row) { /* Overwriting a value */ if (VECTOR(m->data)[start] == -1) { igraph_vector_remove(&m->ridx, start); igraph_vector_remove(&m->data, start); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]--; } else { VECTOR(m->data)[start] += value; } return 0; } else if (VECTOR(m->ridx)[end] == row) { /* Overwriting a value */ if (VECTOR(m->data)[end] == -1) { igraph_vector_remove(&m->ridx, end); igraph_vector_remove(&m->data, end); for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]--; } else { VECTOR(m->data)[end] += value; } return 0; } /* New element has to be inserted, but only if not a zero is * being added to a zero element of the matrix */ if (value != 0.0) { if (VECTOR(m->ridx)[end] < row) { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, end+1, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, end+1, value)); } else if (VECTOR(m->ridx)[start] < row) { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, start+1, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start+1, value)); } else { IGRAPH_CHECK(igraph_vector_insert(&m->ridx, start, row)); IGRAPH_CHECK(igraph_vector_insert(&m->data, start, value)); } for (start=col+1; start < m->ncol+1; start++) VECTOR(m->cidx)[start]++; } return 0; } /** * \function igraph_spmatrix_add_col_values * \brief Adds the values of a column to another column. * * \param to The index of the column to be added to * \param from The index of the column to be added * \return Error code. */ int igraph_spmatrix_add_col_values(igraph_spmatrix_t *m, long int to, long int from) { long int i; /* TODO: I think this implementation could be speeded up if I don't use * igraph_spmatrix_add_e directly -- but maybe it's not worth the fuss */ for (i=(long int) VECTOR(m->cidx)[from]; icidx)[from+1]; i++) { IGRAPH_CHECK(igraph_spmatrix_add_e(m, (long int) VECTOR(m->ridx)[i], to, VECTOR(m->data)[i])); } return 0; } /** * \ingroup matrix * \function igraph_spmatrix_resize * \brief Resizes a sparse matrix. * * * This function resizes a sparse matrix by adding more elements to it. * The matrix retains its data even after resizing it, except for the data * which lies outside the new boundaries (if the new size is smaller). * \param m Pointer to an already initialized sparse matrix object. * \param nrow The number of rows in the resized matrix. * \param ncol The number of columns in the resized matrix. * \return Error code. * * Time complexity: O(n). * n is the number of elements in the old matrix. */ int igraph_spmatrix_resize(igraph_spmatrix_t *m, long int nrow, long int ncol) { long int i, j, ci, ei, mincol; assert(m != NULL); /* Iterating through the matrix data and deleting unnecessary data. */ /* At the same time, we create the new indices as well */ if (nrow < m->nrow) { ei = j = 0; mincol = (m->ncol < ncol) ? m->ncol : ncol; for (ci=0; ci < mincol; ci++) { for (; eicidx)[ci+1]; ei++) { if (VECTOR(m->ridx)[ei] < nrow) { VECTOR(m->ridx)[j]=VECTOR(m->ridx)[ei]; VECTOR(m->data)[j]=VECTOR(m->data)[ei]; j++; } } VECTOR(m->cidx)[ci]=j; } /* Contract the row index and the data vector */ IGRAPH_CHECK(igraph_vector_resize(&m->ridx, j)); IGRAPH_CHECK(igraph_vector_resize(&m->cidx, j)); } /* Updating cidx */ IGRAPH_CHECK(igraph_vector_resize(&m->cidx, ncol+1)); for (i=m->ncol+1; icidx)[i] = VECTOR(m->cidx)[m->ncol]; m->nrow=nrow; m->ncol=ncol; return 0; } /** * \ingroup matrix * \function igraph_spmatrix_count_nonzero * \brief The number of non-zero elements in a sparse matrix. * * \param m Pointer to an initialized sparse matrix object. * \return The size of the matrix. * * Time complexity: O(1). */ long int igraph_spmatrix_count_nonzero(const igraph_spmatrix_t *m) { assert(m != NULL); return igraph_vector_size(&m->data); } /** * \ingroup matrix * \function igraph_spmatrix_size * \brief The number of elements in a sparse matrix. * * \param m Pointer to an initialized sparse matrix object. * \return The size of the matrix. * * Time complexity: O(1). */ long int igraph_spmatrix_size(const igraph_spmatrix_t *m) { assert(m != NULL); return (m->nrow) * (m->ncol); } /** * \ingroup matrix * \function igraph_spmatrix_nrow * \brief The number of rows in a sparse matrix. * * \param m Pointer to an initialized sparse matrix object. * \return The number of rows in the matrix. * * Time complexity: O(1). */ long int igraph_spmatrix_nrow(const igraph_spmatrix_t *m) { assert(m != NULL); return m->nrow; } /** * \ingroup matrix * \function igraph_spmatrix_ncol * \brief The number of columns in a sparse matrix. * * \param m Pointer to an initialized sparse matrix object. * \return The number of columns in the sparse matrix. * * Time complexity: O(1). */ long int igraph_spmatrix_ncol(const igraph_spmatrix_t *m) { assert(m != NULL); return m->ncol; } /** * \ingroup matrix * \brief Copies a sparse matrix to a regular C array. * * * The matrix is copied columnwise, as this is the format most * programs and languages use. * The C array should be of sufficient size, there are (of course) no * range checks done. * \param m Pointer to an initialized sparse matrix object. * \param to Pointer to a C array, the place to copy the data to. * \return Error code. * * Time complexity: O(n), * n is the number of * elements in the matrix. */ int igraph_spmatrix_copy_to(const igraph_spmatrix_t *m, igraph_real_t *to) { long int c, dest_idx, idx; memset(to, 0, sizeof(igraph_real_t) * (size_t) igraph_spmatrix_size(m)); for (c=0, dest_idx=0; c < m->ncol; c++, dest_idx+=m->nrow) { for (idx=(long int) VECTOR(m->cidx)[c]; idxcidx)[c+1]; idx++) { to[dest_idx+(long)VECTOR(m->ridx)[idx]]=VECTOR(m->data)[idx]; } } return 0; } /** * \ingroup matrix * \brief Sets all element in a sparse matrix to zero. * * \param m Pointer to an initialized matrix object. * \return Error code, always returns with success. * * Time complexity: O(n), * n is the number of columns in the matrix */ int igraph_spmatrix_null(igraph_spmatrix_t *m) { assert(m != NULL); igraph_vector_clear(&m->data); igraph_vector_clear(&m->ridx); igraph_vector_null(&m->cidx); return 0; } /** * \ingroup matrix * \function igraph_spmatrix_add_cols * \brief Adds columns to a sparse matrix. * \param m The sparse matrix object. * \param n The number of columns to add. * \return Error code. * * Time complexity: O(1). */ int igraph_spmatrix_add_cols(igraph_spmatrix_t *m, long int n) { igraph_spmatrix_resize(m, m->nrow, m->ncol+n); return 0; } /** * \ingroup matrix * \function igraph_spmatrix_add_rows * \brief Adds rows to a sparse matrix. * \param m The sparse matrix object. * \param n The number of rows to add. * \return Error code. * * Time complexity: O(1). */ int igraph_spmatrix_add_rows(igraph_spmatrix_t *m, long int n) { igraph_spmatrix_resize(m, m->nrow+n, m->ncol); return 0; } /** * \function igraph_spmatrix_clear_row * \brief Clears a row in the matrix (sets all of its elements to zero) * \param m The matrix. * \param row The index of the row to be cleared. * * Time complexity: O(n), the number of nonzero elements in the matrix. */ int igraph_spmatrix_clear_row(igraph_spmatrix_t *m, long int row) { long int ci, ei, i, j, nremove=0, nremove_old=0; igraph_vector_t permvec; assert(m != NULL); IGRAPH_VECTOR_INIT_FINALLY(&permvec, igraph_vector_size(&m->data)); for (ci=0, i=0, j=1; ci < m->ncol; ci++) { for (ei=(long int) VECTOR(m->cidx)[ci]; ei < VECTOR(m->cidx)[ci+1]; ei++) { if (VECTOR(m->ridx)[ei] == row) { /* this element will be deleted, so all elements in cidx from the * column index of this element will have to be decreased by one */ nremove++; } else { /* this element will be kept */ VECTOR(permvec)[i] = j; j++; } i++; } if (ci > 0) { VECTOR(m->cidx)[ci] -= nremove_old; } nremove_old = nremove; } VECTOR(m->cidx)[m->ncol] -= nremove; igraph_vector_permdelete(&m->ridx, &permvec, nremove); igraph_vector_permdelete(&m->data, &permvec, nremove); igraph_vector_destroy(&permvec); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_spmatrix_clear_row_fast(igraph_spmatrix_t *m, long int row) { long int ei, n; assert(m != NULL); n = igraph_vector_size(&m->data); for (ei=0; eiridx)[ei] == row) VECTOR(m->data)[ei]=0.0; } return 0; } int igraph_i_spmatrix_cleanup(igraph_spmatrix_t *m) { long int ci, ei, i, j, nremove=0, nremove_old=0; igraph_vector_t permvec; assert(m != NULL); IGRAPH_VECTOR_INIT_FINALLY(&permvec, igraph_vector_size(&m->data)); for (ci=0, i=0, j=1; ci < m->ncol; ci++) { for (ei=(long int) VECTOR(m->cidx)[ci]; ei < VECTOR(m->cidx)[ci+1]; ei++) { if (VECTOR(m->data)[ei] == 0.0) { /* this element will be deleted, so all elements in cidx from the * column index of this element will have to be decreased by one */ nremove++; } else { /* this element will be kept */ VECTOR(permvec)[i] = j; j++; } i++; } if (ci > 0) { VECTOR(m->cidx)[ci] -= nremove_old; } nremove_old = nremove; } VECTOR(m->cidx)[m->ncol] -= nremove; igraph_vector_permdelete(&m->ridx, &permvec, nremove); igraph_vector_permdelete(&m->data, &permvec, nremove); igraph_vector_destroy(&permvec); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_spmatrix_clear_col * \brief Clears a column in the matrix (sets all of its elements to zero) * \param m The matrix. * \param col The index of the column to be cleared. * \return Error code. The current implementation always succeeds. * * Time complexity: TODO */ int igraph_spmatrix_clear_col(igraph_spmatrix_t *m, long int col) { long int i, n; assert(m != NULL); n = (long)VECTOR(m->cidx)[col+1] - (long)VECTOR(m->cidx)[col]; if (n == 0) return 0; igraph_vector_remove_section(&m->ridx, (long int) VECTOR(m->cidx)[col], (long int) VECTOR(m->cidx)[col+1]); igraph_vector_remove_section(&m->data, (long int) VECTOR(m->cidx)[col], (long int) VECTOR(m->cidx)[col+1]); for (i=col+1; i <= m->ncol; i++) { VECTOR(m->cidx)[i] -= n; } return 0; } /** * \function igraph_spmatrix_scale * \brief Multiplies each element of the sparse matrix by a constant. * \param m The matrix. * \param by The constant. * * Time complexity: O(n), the number of elements in the matrix. */ void igraph_spmatrix_scale(igraph_spmatrix_t *m, igraph_real_t by) { assert(m != NULL); igraph_vector_scale(&m->data, by); } /** * \function igraph_spmatrix_colsums * \brief Calculates the column sums of the matrix. * \param m The matrix. * \param res An initialized \c igraph_vector_t, the result will be stored here. * The vector will be resized as needed. * * Time complexity: O(n), the number of nonzero elements in the matrix. */ int igraph_spmatrix_colsums(const igraph_spmatrix_t *m, igraph_vector_t *res) { long int i, c; assert(m != NULL); IGRAPH_CHECK(igraph_vector_resize(res, m->ncol)); igraph_vector_null(res); for (c=0; c < m->ncol; c++) { for (i=(long int) VECTOR(m->cidx)[c]; icidx)[c+1]; i++) { VECTOR(*res)[c] += VECTOR(m->data)[i]; } } return 0; } /** * \function igraph_spmatrix_rowsums * \brief Calculates the row sums of the matrix. * \param m The matrix. * \param res An initialized \c igraph_vector_t, the result will be stored here. * The vector will be resized as needed. * * Time complexity: O(n), the number of nonzero elements in the matrix. */ int igraph_spmatrix_rowsums(const igraph_spmatrix_t *m, igraph_vector_t *res) { long int i, n; assert(m != NULL); IGRAPH_CHECK(igraph_vector_resize(res, m->nrow)); n = igraph_vector_size(&m->data); igraph_vector_null(res); for (i=0; i < n; i++) { VECTOR(*res)[(long int)VECTOR(m->ridx)[i]] += VECTOR(m->data)[i]; } return 0; } /** * \function igraph_spmatrix_max_nonzero * \brief Returns the maximum nonzero element of a matrix. * If the matrix is empty, zero is returned. * * \param m the matrix object. * \param ridx the row index of the maximum element if not \c NULL. * \param cidx the column index of the maximum element if not \c NULL. * * Time complexity: O(n), the number of nonzero elements in the matrix. */ igraph_real_t igraph_spmatrix_max_nonzero(const igraph_spmatrix_t *m, igraph_real_t *ridx, igraph_real_t *cidx) { igraph_real_t res; long int i, n, maxidx; assert(m != NULL); n=igraph_vector_size(&m->data); if (n == 0) return 0.0; maxidx = -1; for (i=0; idata)[i] != 0.0 && (maxidx == -1 || VECTOR(m->data)[i] >= VECTOR(m->data)[maxidx])) maxidx = i; if (maxidx == -1) return 0.0; res=VECTOR(m->data)[maxidx]; if (ridx != 0) *ridx = VECTOR(m->ridx)[maxidx]; if (cidx != 0) { igraph_vector_binsearch(&m->cidx, maxidx, &i); while (VECTOR(m->cidx)[i+1] == VECTOR(m->cidx)[i]) i++; *cidx = (igraph_real_t)i; } return res; } /** * \function igraph_spmatrix_max * \brief Returns the maximum element of a matrix. * If the matrix is empty, zero is returned. * * \param m the matrix object. * \param ridx the row index of the maximum element if not \c NULL. * \param cidx the column index of the maximum element if not \c NULL. * * Time complexity: O(n), the number of nonzero elements in the matrix. */ igraph_real_t igraph_spmatrix_max(const igraph_spmatrix_t *m, igraph_real_t *ridx, igraph_real_t *cidx) { igraph_real_t res; long int i, j, k, maxidx; assert(m != NULL); i=igraph_vector_size(&m->data); if (i == 0) return 0.0; maxidx=(long)igraph_vector_which_max(&m->data); res=VECTOR(m->data)[maxidx]; if (res>=0.0 || i == m->nrow * m->ncol) { if (ridx != 0) *ridx = VECTOR(m->ridx)[maxidx]; if (cidx != 0) { igraph_vector_binsearch(&m->cidx, maxidx, &i); i--; while (i < m->ncol-1 && VECTOR(m->cidx)[i+1] == VECTOR(m->cidx)[i]) i++; *cidx = (igraph_real_t)i; } return res; } /* the maximal nonzero element is negative and there is at least a * single zero */ res=0.0; if (cidx != 0 || ridx != 0) { for (i=0; i < m->ncol; i++) { if (VECTOR(m->cidx)[i+1] - VECTOR(m->cidx)[i] < m->nrow) { if (cidx != 0) *cidx = i; if (ridx != 0) { for (j=(long int) VECTOR(m->cidx)[i], k=0; j < VECTOR(m->cidx)[i+1]; j++, k++) { if (VECTOR(m->ridx)[j] != k) { *ridx = k; break; } } } break; } } } return res; } int igraph_i_spmatrix_get_col_nonzero_indices(const igraph_spmatrix_t *m, igraph_vector_t *res, long int col) { long int i, n; assert(m != NULL); n = (long int) (VECTOR(m->cidx)[col+1]-VECTOR(m->cidx)[col]); IGRAPH_CHECK(igraph_vector_resize(res, n)); for (i=(long int) VECTOR(m->cidx)[col], n=0; icidx)[col+1]; i++, n++) if (VECTOR(m->data)[i] != 0.0) VECTOR(*res)[n] = VECTOR(m->ridx)[i]; return 0; } /** * \section igraph_spmatrix_iterating Iterating over the non-zero elements of a sparse matrix * * The \type igraph_spmatrix_iter_t type represents an iterator that can * be used to step over the non-zero elements of a sparse matrix in columnwise * order efficiently. In general, you shouldn't modify the elements of the matrix * while iterating over it; doing so will probably invalidate the iterator, but * there are no checks to prevent you from doing this. * * To access the row index of the current element of the iterator, use its * \c ri field. Similarly, the \c ci field stores the column index of the current * element and the \c value field stores the value of the element. */ /** * \function igraph_spmatrix_iter_create * \brief Creates a sparse matrix iterator corresponding to the given matrix. * * \param mit pointer to the matrix iterator being initialized * \param m pointer to the matrix we will be iterating over * \return Error code. The current implementation is always successful. * * Time complexity: O(1). */ int igraph_spmatrix_iter_create(igraph_spmatrix_iter_t *mit, const igraph_spmatrix_t *m) { mit->m = m; IGRAPH_CHECK(igraph_spmatrix_iter_reset(mit)); return 0; } /** * \function igraph_spmatrix_iter_reset * \brief Resets a sparse matrix iterator. * * * After resetting, the iterator will point to the first nonzero element (if any). * * \param mit pointer to the matrix iterator being reset * \return Error code. The current implementation is always successful. * * Time complexity: O(1). */ int igraph_spmatrix_iter_reset(igraph_spmatrix_iter_t *mit) { assert(mit->m); if (igraph_spmatrix_count_nonzero(mit->m) == 0) { mit->pos = mit->ri = mit->ci = -1L; mit->value = -1; return 0; } mit->ci = 0; mit->pos = -1; IGRAPH_CHECK(igraph_spmatrix_iter_next(mit)); return 0; } /** * \function igraph_spmatrix_iter_next * \brief Moves a sparse matrix iterator to the next nonzero element. * * * You should call this function only if \ref igraph_spmatrix_iter_end() * returns FALSE (0). * * \param mit pointer to the matrix iterator being moved * \return Error code. The current implementation is always successful. * * Time complexity: O(1). */ int igraph_spmatrix_iter_next(igraph_spmatrix_iter_t *mit) { mit->pos++; if (igraph_spmatrix_iter_end(mit)) return 0; mit->ri = (long int)VECTOR(mit->m->ridx)[mit->pos]; mit->value = VECTOR(mit->m->data)[mit->pos]; while (VECTOR(mit->m->cidx)[mit->ci+1] <= mit->pos) { mit->ci++; } return 0; } /** * \function igraph_spmatrix_iter_end * \brief Checks whether there are more elements in the iterator. * * * You should call this function before calling \ref igraph_spmatrix_iter_next() * to make sure you have more elements in the iterator. * * \param mit pointer to the matrix iterator being checked * \return TRUE (1) if there are more elements in the iterator, * FALSE (0) otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_spmatrix_iter_end(igraph_spmatrix_iter_t *mit) { return mit->pos >= igraph_spmatrix_count_nonzero(mit->m); } /** * \function igraph_spmatrix_iter_destroy * \brief Frees the memory used by the iterator. * * * The current implementation does not allocate any memory upon * creation, so this function does nothing. However, since there is * no guarantee that future implementations will not allocate any * memory in \ref igraph_spmatrix_iter_create(), you are still * required to call this function whenever you are done with the * iterator. * * \param mit pointer to the matrix iterator being destroyed * * Time complexity: O(1). */ void igraph_spmatrix_iter_destroy(igraph_spmatrix_iter_t *mit) { IGRAPH_UNUSED(mit); /* Nothing to do at the moment */ } #ifndef USING_R /** * \function igraph_spmatrix_print * \brief Prints a sparse matrix. * * Prints a sparse matrix to the standard output. Only the non-zero entries * are printed. * * \return Error code. * * Time complexity: O(n), the number of non-zero elements. */ int igraph_spmatrix_print(const igraph_spmatrix_t* matrix) { return igraph_spmatrix_fprint(matrix, stdout); } #endif /** * \function igraph_spmatrix_fprint * \brief Prints a sparse matrix to the given file. * * Prints a sparse matrix to the given file. Only the non-zero entries * are printed. * * \return Error code. * * Time complexity: O(n), the number of non-zero elements. */ int igraph_spmatrix_fprint(const igraph_spmatrix_t* matrix, FILE *file) { igraph_spmatrix_iter_t mit; IGRAPH_CHECK(igraph_spmatrix_iter_create(&mit, matrix)); IGRAPH_FINALLY(igraph_spmatrix_iter_destroy, &mit); while (!igraph_spmatrix_iter_end(&mit)) { fprintf(file, "[%ld, %ld] = %.4f\n", (long int)mit.ri, (long int)mit.ci, mit.value); igraph_spmatrix_iter_next(&mit); } igraph_spmatrix_iter_destroy(&mit); IGRAPH_FINALLY_CLEAN(1); return 0; } igraph/src/dsconv.f0000644000175100001440000000665413431000472014001 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsconv c c\Description: c Convergence testing for the symmetric Arnoldi eigenvalue routine. c c\Usage: c call igraphdsconv c ( N, RITZ, BOUNDS, TOL, NCONV ) c c\Arguments c N Integer. (INPUT) c Number of Ritz values to check for convergence. c c RITZ Double precision array of length N. (INPUT) c The Ritz values to be checked for convergence. c c BOUNDS Double precision array of length N. (INPUT) c Ritz estimates associated with the Ritz values in RITZ. c c TOL Double precision scalar. (INPUT) c Desired relative accuracy for a Ritz value to be considered c "converged". c c NCONV Integer scalar. (OUTPUT) c Number of "converged" Ritz values. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Routines called: c igraphsecond ARPACK utility routine for timing. c dlamch LAPACK routine that determines machine constants. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: sconv.F SID: 2.4 DATE OF SID: 4/19/96 RELEASE: 2 c c\Remarks c 1. Starting with version 2.4, this routine no longer uses the c Parlett strategy using the gap conditions. c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsconv (n, ritz, bounds, tol, nconv) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c integer n, nconv Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & ritz(n), bounds(n) c c %---------------% c | Local Scalars | c %---------------% c integer i Double precision & temp, eps23 c c %-------------------% c | External routines | c %-------------------% c Double precision & dlamch external dlamch c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic abs c c %-----------------------% c | Executable Statements | c %-----------------------% c call igraphsecond (t0) c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0 / 3.0D+0) c nconv = 0 do 10 i = 1, n c c %-----------------------------------------------------% c | The i-th Ritz value is considered "converged" | c | when: bounds(i) .le. TOL*max(eps23, abs(ritz(i))) | c %-----------------------------------------------------% c temp = max( eps23, abs(ritz(i)) ) if ( bounds(i) .le. tol*temp ) then nconv = nconv + 1 end if c 10 continue c call igraphsecond (t1) tsconv = tsconv + (t1 - t0) c return c c %---------------% c | End of igraphdsconv | c %---------------% c end igraph/src/scg_kmeans.c0000644000175100001440000000567413431000472014615 0ustar hornikusers/* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * The kmeans_Lloyd function is adapted from the R-stats package. * It perfoms Lloyd's k-means clustering on a p x n data matrix * stored row-wise in a vector 'x'. 'cen' contains k initial centers. * The group label to which each object belongs is stored in 'cl'. * Labels are positive consecutive integers starting from 0. * See also Section 5.3.3 of the above reference. */ #include "igraph_memory.h" #include "scg_headers.h" int igraph_i_kmeans_Lloyd(const igraph_vector_t *x, int n, int p, igraph_vector_t *cen, int k, int *cl, int maxiter) { int iter, i, j, c, it, inew = 0; igraph_real_t best, dd, tmp; int updated; igraph_vector_int_t nc; IGRAPH_CHECK(igraph_vector_int_init(&nc, k)); IGRAPH_FINALLY(igraph_vector_int_destroy, &nc); for (i = 0; i < n; i++) { cl[i] = -1; } for (iter = 0; iter < maxiter; iter++) { updated = 0; for (i = 0; i < n; i++) { /* find nearest centre for each point */ best = IGRAPH_INFINITY; for (j = 0; j < k; j++) { dd = 0.0; for (c = 0; c < p; c++) { tmp = VECTOR(*x)[i+n*c] - VECTOR(*cen)[j+k*c]; dd += tmp * tmp; } if (dd < best) { best = dd; inew = j+1; } } if (cl[i] != inew) { updated = 1; cl[i] = inew; } } if (!updated) { break; } /* update each centre */ for (j = 0; j < k*p; j++) { VECTOR(*cen)[j] = 0.0; } for (j = 0; j < k; j++) { VECTOR(nc)[j] = 0; } for (i = 0; i < n; i++) { it = cl[i] - 1; VECTOR(nc)[it]++; for (c = 0; c < p; c++) { VECTOR(*cen)[it+c*k] += VECTOR(*x)[i+c*n]; } } for (j = 0; j < k*p; j++) { VECTOR(*cen)[j] /= VECTOR(nc)[j % k]; } } igraph_vector_int_destroy(&nc); IGRAPH_FINALLY_CLEAN(1); /* convervenge check */ if (iter >= maxiter-1) { IGRAPH_ERROR("Lloyd k-means did not converge", IGRAPH_FAILURE); } return 0; } igraph/src/topology.c0000644000175100001440000036364613431000472014365 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_topology.h" #include "igraph_memory.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "igraph_constructors.h" #include "igraph_conversion.h" #include "igraph_stack.h" #include "igraph_attributes.h" #include "igraph_structural.h" #include "config.h" const unsigned int igraph_i_isoclass_3[] = { 0, 1, 1, 3, 1, 5, 6, 7, 1, 6,10,11, 3, 7,11,15, 1, 6, 5, 7,10,21,21,23, 6,25,21,27,11,27,30,31, 1,10, 6,11, 6,21,25,27, 5,21,21,30, 7,23,27,31, 3,11, 7,15,11,30,27,31, 7,27,23,31,15,31,31,63 }; const unsigned int igraph_i_isoclass_3_idx[] = { 0, 4, 16, 1, 0, 32, 2, 8, 0 }; const unsigned int igraph_i_isoclass_4[] = { 0, 1, 1, 3, 1, 3, 3, 7, 1, 9, 10, 11, 10, 11, 14, 15, 1, 10, 18, 19, 20, 21, 22, 23, 3, 11, 19, 27, 21, 29, 30, 31, 1, 10, 20, 21, 18, 19, 22, 23, 3, 11, 21, 29, 19, 27, 30, 31, 3, 14, 22, 30, 22, 30, 54, 55, 7, 15, 23, 31, 23, 31, 55, 63, 1, 10, 9, 11, 10, 14, 11, 15, 18, 73, 73, 75, 76, 77, 77, 79, 10, 81, 73, 83, 84, 85, 86, 87, 19, 83, 90, 91, 92, 93, 94, 95, 20, 84, 98, 99, 100, 101, 102, 103, 22, 86, 106, 107, 108, 109, 110, 111, 21, 85, 106, 115, 116, 117, 118, 119, 23, 87, 122, 123, 124, 125, 126, 127, 1, 18, 10, 19, 20, 22, 21, 23, 10, 73, 81, 83, 84, 86, 85, 87, 9, 73, 73, 90, 98, 106, 106, 122, 11, 75, 83, 91, 99, 107, 115, 123, 10, 76, 84, 92, 100, 108, 116, 124, 14, 77, 85, 93, 101, 109, 117, 125, 11, 77, 86, 94, 102, 110, 118, 126, 15, 79, 87, 95, 103, 111, 119, 127, 3, 19, 11, 27, 21, 30, 29, 31, 19, 90, 83, 91, 92, 94, 93, 95, 11, 83, 75, 91, 99, 115, 107, 123, 27, 91, 91, 219, 220, 221, 221, 223, 21, 92, 99, 220, 228, 229, 230, 231, 30, 94, 115, 221, 229, 237, 238, 239, 29, 93, 107, 221, 230, 238, 246, 247, 31, 95, 123, 223, 231, 239, 247, 255, 1, 20, 10, 21, 18, 22, 19, 23, 20, 98, 84, 99, 100, 102, 101, 103, 10, 84, 76, 92, 100, 116, 108, 124, 21, 99, 92, 220, 228, 230, 229, 231, 18, 100, 100, 228, 292, 293, 293, 295, 22, 102, 116, 230, 293, 301, 302, 303, 19, 101, 108, 229, 293, 302, 310, 311, 23, 103, 124, 231, 295, 303, 311, 319, 3, 21, 11, 29, 19, 30, 27, 31, 22, 106, 86, 107, 108, 110, 109, 111, 14, 85, 77, 93, 101, 117, 109, 125, 30, 115, 94, 221, 229, 238, 237, 239, 22, 116, 102, 230, 293, 302, 301, 303, 54, 118, 118, 246, 310, 365, 365, 367, 30, 117, 110, 238, 302, 373, 365, 375, 55, 119, 126, 247, 311, 375, 382, 383, 3, 22, 14, 30, 22, 54, 30, 55, 21, 106, 85, 115, 116, 118, 117, 119, 11, 86, 77, 94, 102, 118, 110, 126, 29, 107, 93, 221, 230, 246, 238, 247, 19, 108, 101, 229, 293, 310, 302, 311, 30, 110, 117, 238, 302, 365, 373, 375, 27, 109, 109, 237, 301, 365, 365, 382, 31, 111, 125, 239, 303, 367, 375, 383, 7, 23, 15, 31, 23, 55, 31, 63, 23, 122, 87, 123, 124, 126, 125, 127, 15, 87, 79, 95, 103, 119, 111, 127, 31, 123, 95, 223, 231, 247, 239, 255, 23, 124, 103, 231, 295, 311, 303, 319, 55, 126, 119, 247, 311, 382, 375, 383, 31, 125, 111, 239, 303, 375, 367, 383, 63, 127, 127, 255, 319, 383, 383, 511, 1, 10, 10, 14, 9, 11, 11, 15, 18, 73, 76, 77, 73, 75, 77, 79, 20, 84, 100, 101, 98, 99, 102, 103, 22, 86, 108, 109, 106, 107, 110, 111, 10, 81, 84, 85, 73, 83, 86, 87, 19, 83, 92, 93, 90, 91, 94, 95, 21, 85, 116, 117, 106, 115, 118, 119, 23, 87, 124, 125, 122, 123, 126, 127, 18, 76, 73, 77, 73, 77, 75, 79, 292, 585, 585, 587, 585, 587, 587, 591, 100, 593, 594, 595, 596, 597, 598, 599, 293, 601, 602, 603, 604, 605, 606, 607, 100, 593, 596, 597, 594, 595, 598, 599, 293, 601, 604, 605, 602, 603, 606, 607, 228, 625, 626, 627, 626, 627, 630, 631, 295, 633, 634, 635, 634, 635, 638, 639, 20, 100, 84, 101, 98, 102, 99, 103, 100, 594, 593, 595, 596, 598, 597, 599, 98, 596, 596, 659, 660, 661, 661, 663, 102, 598, 666, 667, 661, 669, 670, 671, 84, 593, 674, 675, 596, 666, 678, 679, 101, 595, 675, 683, 659, 667, 686, 687, 99, 597, 678, 686, 661, 670, 694, 695, 103, 599, 679, 687, 663, 671, 695, 703, 22, 108, 86, 109, 106, 110, 107, 111, 293, 602, 601, 603, 604, 606, 605, 607, 102, 666, 598, 667, 661, 670, 669, 671, 301, 729, 729, 731, 732, 733, 733, 735, 116, 737, 678, 739, 626, 741, 742, 743, 302, 745, 746, 747, 748, 749, 750, 751, 230, 753, 742, 755, 756, 757, 758, 759, 303, 761, 762, 763, 764, 765, 766, 767, 10, 84, 81, 85, 73, 86, 83, 87, 100, 596, 593, 597, 594, 598, 595, 599, 84, 674, 593, 675, 596, 678, 666, 679, 116, 678, 737, 739, 626, 742, 741, 743, 76, 593, 593, 625, 585, 601, 601, 633, 108, 666, 737, 753, 602, 729, 745, 761, 92, 675, 737, 819, 604, 746, 822, 823, 124, 679, 826, 827, 634, 762, 830, 831, 19, 92, 83, 93, 90, 94, 91, 95, 293, 604, 601, 605, 602, 606, 603, 607, 101, 675, 595, 683, 659, 686, 667, 687, 302, 746, 745, 747, 748, 750, 749, 751, 108, 737, 666, 753, 602, 745, 729, 761, 310, 822, 822, 875, 876, 877, 877, 879, 229, 819, 741, 883, 748, 885, 886, 887, 311, 823, 830, 891, 892, 893, 894, 895, 21, 116, 85, 117, 106, 118, 115, 119, 228, 626, 625, 627, 626, 630, 627, 631, 99, 678, 597, 686, 661, 694, 670, 695, 230, 742, 753, 755, 756, 758, 757, 759, 92, 737, 675, 819, 604, 822, 746, 823, 229, 741, 819, 883, 748, 886, 885, 887, 220, 739, 739, 947, 732, 949, 949, 951, 231, 743, 827, 955, 764, 957, 958, 959, 23, 124, 87, 125, 122, 126, 123, 127, 295, 634, 633, 635, 634, 638, 635, 639, 103, 679, 599, 687, 663, 695, 671, 703, 303, 762, 761, 763, 764, 766, 765, 767, 124, 826, 679, 827, 634, 830, 762, 831, 311, 830, 823, 891, 892, 894, 893, 895, 231, 827, 743, 955, 764, 958, 957, 959, 319, 831, 831,1019,1020,1021,1021,1023, 1, 18, 20, 22, 10, 19, 21, 23, 10, 73, 84, 86, 81, 83, 85, 87, 10, 76, 100, 108, 84, 92, 116, 124, 14, 77, 101, 109, 85, 93, 117, 125, 9, 73, 98, 106, 73, 90, 106, 122, 11, 75, 99, 107, 83, 91, 115, 123, 11, 77, 102, 110, 86, 94, 118, 126, 15, 79, 103, 111, 87, 95, 119, 127, 20, 100, 98, 102, 84, 101, 99, 103, 100, 594, 596, 598, 593, 595, 597, 599, 84, 593, 596, 666, 674, 675, 678, 679, 101, 595, 659, 667, 675, 683, 686, 687, 98, 596, 660, 661, 596, 659, 661, 663, 102, 598, 661, 669, 666, 667, 670, 671, 99, 597, 661, 670, 678, 686, 694, 695, 103, 599, 663, 671, 679, 687, 695, 703, 18, 292, 100, 293, 100, 293, 228, 295, 76, 585, 593, 601, 593, 601, 625, 633, 73, 585, 594, 602, 596, 604, 626, 634, 77, 587, 595, 603, 597, 605, 627, 635, 73, 585, 596, 604, 594, 602, 626, 634, 77, 587, 597, 605, 595, 603, 627, 635, 75, 587, 598, 606, 598, 606, 630, 638, 79, 591, 599, 607, 599, 607, 631, 639, 22, 293, 102, 301, 116, 302, 230, 303, 108, 602, 666, 729, 737, 745, 753, 761, 86, 601, 598, 729, 678, 746, 742, 762, 109, 603, 667, 731, 739, 747, 755, 763, 106, 604, 661, 732, 626, 748, 756, 764, 110, 606, 670, 733, 741, 749, 757, 765, 107, 605, 669, 733, 742, 750, 758, 766, 111, 607, 671, 735, 743, 751, 759, 767, 10, 100, 84, 116, 76, 108, 92, 124, 84, 596, 674, 678, 593, 666, 675, 679, 81, 593, 593, 737, 593, 737, 737, 826, 85, 597, 675, 739, 625, 753, 819, 827, 73, 594, 596, 626, 585, 602, 604, 634, 86, 598, 678, 742, 601, 729, 746, 762, 83, 595, 666, 741, 601, 745, 822, 830, 87, 599, 679, 743, 633, 761, 823, 831, 21, 228, 99, 230, 92, 229, 220, 231, 116, 626, 678, 742, 737, 741, 739, 743, 85, 625, 597, 753, 675, 819, 739, 827, 117, 627, 686, 755, 819, 883, 947, 955, 106, 626, 661, 756, 604, 748, 732, 764, 118, 630, 694, 758, 822, 886, 949, 957, 115, 627, 670, 757, 746, 885, 949, 958, 119, 631, 695, 759, 823, 887, 951, 959, 19, 293, 101, 302, 108, 310, 229, 311, 92, 604, 675, 746, 737, 822, 819, 823, 83, 601, 595, 745, 666, 822, 741, 830, 93, 605, 683, 747, 753, 875, 883, 891, 90, 602, 659, 748, 602, 876, 748, 892, 94, 606, 686, 750, 745, 877, 885, 893, 91, 603, 667, 749, 729, 877, 886, 894, 95, 607, 687, 751, 761, 879, 887, 895, 23, 295, 103, 303, 124, 311, 231, 319, 124, 634, 679, 762, 826, 830, 827, 831, 87, 633, 599, 761, 679, 823, 743, 831, 125, 635, 687, 763, 827, 891, 955,1019, 122, 634, 663, 764, 634, 892, 764,1020, 126, 638, 695, 766, 830, 894, 958,1021, 123, 635, 671, 765, 762, 893, 957,1021, 127, 639, 703, 767, 831, 895, 959,1023, 3, 19, 21, 30, 11, 27, 29, 31, 19, 90, 92, 94, 83, 91, 93, 95, 21, 92, 228, 229, 99, 220, 230, 231, 30, 94, 229, 237, 115, 221, 238, 239, 11, 83, 99, 115, 75, 91, 107, 123, 27, 91, 220, 221, 91, 219, 221, 223, 29, 93, 230, 238, 107, 221, 246, 247, 31, 95, 231, 239, 123, 223, 247, 255, 22, 108, 106, 110, 86, 109, 107, 111, 293, 602, 604, 606, 601, 603, 605, 607, 116, 737, 626, 741, 678, 739, 742, 743, 302, 745, 748, 749, 746, 747, 750, 751, 102, 666, 661, 670, 598, 667, 669, 671, 301, 729, 732, 733, 729, 731, 733, 735, 230, 753, 756, 757, 742, 755, 758, 759, 303, 761, 764, 765, 762, 763, 766, 767, 22, 293, 116, 302, 102, 301, 230, 303, 108, 602, 737, 745, 666, 729, 753, 761, 106, 604, 626, 748, 661, 732, 756, 764, 110, 606, 741, 749, 670, 733, 757, 765, 86, 601, 678, 746, 598, 729, 742, 762, 109, 603, 739, 747, 667, 731, 755, 763, 107, 605, 742, 750, 669, 733, 758, 766, 111, 607, 743, 751, 671, 735, 759, 767, 54, 310, 118, 365, 118, 365, 246, 367, 310, 876, 822, 877, 822, 877, 875, 879, 118, 822, 630, 886, 694, 949, 758, 957, 365, 877, 886, 1755, 949,1757,1758,1759, 118, 822, 694, 949, 630, 886, 758, 957, 365, 877, 949,1757, 886,1755,1758,1759, 246, 875, 758,1758, 758, 1758,1782,1783, 367, 879, 957,1759, 957,1759,1783,1791, 14, 101, 85, 117, 77, 109, 93, 125, 101, 659, 675, 686, 595, 667, 683, 687, 85, 675, 625, 819, 597, 739, 753, 827, 117, 686, 819, 947, 627, 755, 883, 955, 77, 595, 597, 627, 587, 603, 605, 635, 109, 667, 739, 755, 603, 731, 747, 763, 93, 683, 753, 883, 605, 747, 875, 891, 125, 687, 827, 955, 635, 763, 891,1019, 30, 229, 115, 238, 94, 237, 221, 239, 302, 748, 746, 750, 745, 749, 747, 751, 117, 819, 627, 883, 686, 947, 755, 955, 373, 885, 885,1883, 885, 1883,1883,1887, 110, 741, 670, 757, 606, 749, 733, 765, 365, 886, 949,1758, 877,1755,1757,1759, 238, 883, 757,1907, 750,1883,1758, 1911, 375, 887, 958,1911, 893,1917,1918,1919, 30, 302, 117, 373, 110, 365, 238, 375, 229, 748, 819, 885, 741, 886, 883, 887, 115, 746, 627, 885, 670, 949, 757, 958, 238, 750, 883,1883, 757,1758, 1907,1911, 94, 745, 686, 885, 606, 877, 750, 893, 237, 749, 947, 1883, 749,1755,1883,1917, 221, 747, 755,1883, 733,1757,1758,1918, 239, 751, 955,1887, 765,1759,1911,1919, 55, 311, 119, 375, 126, 382, 247, 383, 311, 892, 823, 893, 830, 894, 891, 895, 119, 823, 631, 887, 695, 951, 759, 959, 375, 893, 887,1917, 958,1918,1911, 1919, 126, 830, 695, 958, 638, 894, 766,1021, 382, 894, 951,1918, 894,2029,1918,2031, 247, 891, 759,1911, 766,1918,1783,2039, 383, 895, 959,1919,1021,2031,2039,2047, 1, 20, 18, 22, 10, 21, 19, 23, 20, 98, 100, 102, 84, 99, 101, 103, 18, 100, 292, 293, 100, 228, 293, 295, 22, 102, 293, 301, 116, 230, 302, 303, 10, 84, 100, 116, 76, 92, 108, 124, 21, 99, 228, 230, 92, 220, 229, 231, 19, 101, 293, 302, 108, 229, 310, 311, 23, 103, 295, 303, 124, 231, 311, 319, 10, 84, 73, 86, 81, 85, 83, 87, 100, 596, 594, 598, 593, 597, 595, 599, 76, 593, 585, 601, 593, 625, 601, 633, 108, 666, 602, 729, 737, 753, 745, 761, 84, 674, 596, 678, 593, 675, 666, 679, 116, 678, 626, 742, 737, 739, 741, 743, 92, 675, 604, 746, 737, 819, 822, 823, 124, 679, 634, 762, 826, 827, 830, 831, 10, 100, 76, 108, 84, 116, 92, 124, 84, 596, 593, 666, 674, 678, 675, 679, 73, 594, 585, 602, 596, 626, 604, 634, 86, 598, 601, 729, 678, 742, 746, 762, 81, 593, 593, 737, 593, 737, 737, 826, 85, 597, 625, 753, 675, 739, 819, 827, 83, 595, 601, 745, 666, 741, 822, 830, 87, 599, 633, 761, 679, 743, 823, 831, 14, 101, 77, 109, 85, 117, 93, 125, 101, 659, 595, 667, 675, 686, 683, 687, 77, 595, 587, 603, 597, 627, 605, 635, 109, 667, 603, 731, 739, 755, 747, 763, 85, 675, 597, 739, 625, 819, 753, 827, 117, 686, 627, 755, 819, 947, 883, 955, 93, 683, 605, 747, 753, 883, 875, 891, 125, 687, 635, 763, 827, 955, 891,1019, 9, 98, 73, 106, 73, 106, 90, 122, 98, 660, 596, 661, 596, 661, 659, 663, 73, 596, 585, 604, 594, 626, 602, 634, 106, 661, 604, 732, 626, 756, 748, 764, 73, 596, 594, 626, 585, 604, 602, 634, 106, 661, 626, 756, 604, 732, 748, 764, 90, 659, 602, 748, 602, 748, 876, 892, 122, 663, 634, 764, 634, 764, 892,1020, 11, 99, 75, 107, 83, 115, 91, 123, 102, 661, 598, 669, 666, 670, 667, 671, 77, 597, 587, 605, 595, 627, 603, 635, 110, 670, 606, 733, 741, 757, 749, 765, 86, 678, 598, 742, 601, 746, 729, 762, 118, 694, 630, 758, 822, 949, 886, 957, 94, 686, 606, 750, 745, 885, 877, 893, 126, 695, 638, 766, 830, 958, 894, 1021, 11, 102, 77, 110, 86, 118, 94, 126, 99, 661, 597, 670, 678, 694, 686, 695, 75, 598, 587, 606, 598, 630, 606, 638, 107, 669, 605, 733, 742, 758, 750, 766, 83, 666, 595, 741, 601, 822, 745, 830, 115, 670, 627, 757, 746, 949, 885, 958, 91, 667, 603, 749, 729, 886, 877, 894, 123, 671, 635, 765, 762, 957, 893,1021, 15, 103, 79, 111, 87, 119, 95, 127, 103, 663, 599, 671, 679, 695, 687, 703, 79, 599, 591, 607, 599, 631, 607, 639, 111, 671, 607, 735, 743, 759, 751, 767, 87, 679, 599, 743, 633, 823, 761, 831, 119, 695, 631, 759, 823, 951, 887, 959, 95, 687, 607, 751, 761, 887, 879, 895, 127, 703, 639, 767, 831, 959, 895,1023, 3, 21, 19, 30, 11, 29, 27, 31, 22, 106, 108, 110, 86, 107, 109, 111, 22, 116, 293, 302, 102, 230, 301, 303, 54, 118, 310, 365, 118, 246, 365, 367, 14, 85, 101, 117, 77, 93, 109, 125, 30, 115, 229, 238, 94, 221, 237, 239, 30, 117, 302, 373, 110, 238, 365, 375, 55, 119, 311, 375, 126, 247, 382, 383, 19, 92, 90, 94, 83, 93, 91, 95, 293, 604, 602, 606, 601, 605, 603, 607, 108, 737, 602, 745, 666, 753, 729, 761, 310, 822, 876, 877, 822, 875, 877, 879, 101, 675, 659, 686, 595, 683, 667, 687, 302, 746, 748, 750, 745, 747, 749, 751, 229, 819, 748, 885, 741, 883, 886, 887, 311, 823, 892, 893, 830, 891, 894, 895, 21, 228, 92, 229, 99, 230, 220, 231, 116, 626, 737, 741, 678, 742, 739, 743, 106, 626, 604, 748, 661, 756, 732, 764, 118, 630, 822, 886, 694, 758, 949, 957, 85, 625, 675, 819, 597, 753, 739, 827, 117, 627, 819, 883, 686, 755, 947, 955, 115, 627, 746, 885, 670, 757, 949, 958, 119, 631, 823, 887, 695, 759, 951, 959, 30, 229, 94, 237, 115, 238, 221, 239, 302, 748, 745, 749, 746, 750, 747, 751, 110, 741, 606, 749, 670, 757, 733, 765, 365, 886, 877,1755, 949,1758, 1757,1759, 117, 819, 686, 947, 627, 883, 755, 955, 373, 885, 885, 1883, 885,1883,1883,1887, 238, 883, 750,1883, 757,1907,1758,1911, 375, 887, 893,1917, 958,1911,1918,1919, 11, 99, 83, 115, 75, 107, 91, 123, 102, 661, 666, 670, 598, 669, 667, 671, 86, 678, 601, 746, 598, 742, 729, 762, 118, 694, 822, 949, 630, 758, 886, 957, 77, 597, 595, 627, 587, 605, 603, 635, 110, 670, 741, 757, 606, 733, 749, 765, 94, 686, 745, 885, 606, 750, 877, 893, 126, 695, 830, 958, 638, 766, 894,1021, 27, 220, 91, 221, 91, 221, 219, 223, 301, 732, 729, 733, 729, 733, 731, 735, 109, 739, 603, 747, 667, 755, 731, 763, 365, 949, 877,1757, 886,1758,1755,1759, 109, 739, 667, 755, 603, 747, 731, 763, 365, 949, 886,1758, 877, 1757,1755,1759, 237, 947, 749,1883, 749,1883,1755,1917, 382, 951, 894,1918, 894,1918,2029,2031, 29, 230, 93, 238, 107, 246, 221, 247, 230, 756, 753, 757, 742, 758, 755, 759, 107, 742, 605, 750, 669, 758, 733, 766, 246, 758, 875,1758, 758,1782,1758,1783, 93, 753, 683, 883, 605, 875, 747, 891, 238, 757, 883,1907, 750,1758, 1883,1911, 221, 755, 747,1883, 733,1758,1757,1918, 247, 759, 891, 1911, 766,1783,1918,2039, 31, 231, 95, 239, 123, 247, 223, 255, 303, 764, 761, 765, 762, 766, 763, 767, 111, 743, 607, 751, 671, 759, 735, 767, 367, 957, 879,1759, 957,1783,1759,1791, 125, 827, 687, 955, 635, 891, 763,1019, 375, 958, 887,1911, 893,1918,1917, 1919, 239, 955, 751,1887, 765,1911,1759,1919, 383, 959, 895,1919, 1021,2039,2031,2047, 3, 22, 22, 54, 14, 30, 30, 55, 21, 106, 116, 118, 85, 115, 117, 119, 19, 108, 293, 310, 101, 229, 302, 311, 30, 110, 302, 365, 117, 238, 373, 375, 11, 86, 102, 118, 77, 94, 110, 126, 29, 107, 230, 246, 93, 221, 238, 247, 27, 109, 301, 365, 109, 237, 365, 382, 31, 111, 303, 367, 125, 239, 375, 383, 21, 116, 106, 118, 85, 117, 115, 119, 228, 626, 626, 630, 625, 627, 627, 631, 92, 737, 604, 822, 675, 819, 746, 823, 229, 741, 748, 886, 819, 883, 885, 887, 99, 678, 661, 694, 597, 686, 670, 695, 230, 742, 756, 758, 753, 755, 757, 759, 220, 739, 732, 949, 739, 947, 949, 951, 231, 743, 764, 957, 827, 955, 958, 959, 19, 293, 108, 310, 101, 302, 229, 311, 92, 604, 737, 822, 675, 746, 819, 823, 90, 602, 602, 876, 659, 748, 748, 892, 94, 606, 745, 877, 686, 750, 885, 893, 83, 601, 666, 822, 595, 745, 741, 830, 93, 605, 753, 875, 683, 747, 883, 891, 91, 603, 729, 877, 667, 749, 886, 894, 95, 607, 761, 879, 687, 751, 887, 895, 30, 302, 110, 365, 117, 373, 238, 375, 229, 748, 741, 886, 819, 885, 883, 887, 94, 745, 606, 877, 686, 885, 750, 893, 237, 749, 749,1755, 947,1883,1883,1917, 115, 746, 670, 949, 627, 885, 757, 958, 238, 750, 757,1758, 883,1883,1907,1911, 221, 747, 733, 1757, 755,1883,1758,1918, 239, 751, 765,1759, 955,1887,1911,1919, 11, 102, 86, 118, 77, 110, 94, 126, 99, 661, 678, 694, 597, 670, 686, 695, 83, 666, 601, 822, 595, 741, 745, 830, 115, 670, 746, 949, 627, 757, 885, 958, 75, 598, 598, 630, 587, 606, 606, 638, 107, 669, 742, 758, 605, 733, 750, 766, 91, 667, 729, 886, 603, 749, 877, 894, 123, 671, 762, 957, 635, 765, 893,1021, 29, 230, 107, 246, 93, 238, 221, 247, 230, 756, 742, 758, 753, 757, 755, 759, 93, 753, 605, 875, 683, 883, 747, 891, 238, 757, 750, 1758, 883,1907,1883,1911, 107, 742, 669, 758, 605, 750, 733, 766, 246, 758, 758,1782, 875,1758,1758,1783, 221, 755, 733,1758, 747, 1883,1757,1918, 247, 759, 766,1783, 891,1911,1918,2039, 27, 301, 109, 365, 109, 365, 237, 382, 220, 732, 739, 949, 739, 949, 947, 951, 91, 729, 603, 877, 667, 886, 749, 894, 221, 733, 747,1757, 755,1758,1883,1918, 91, 729, 667, 886, 603, 877, 749, 894, 221, 733, 755,1758, 747,1757,1883,1918, 219, 731, 731,1755, 731,1755, 1755,2029, 223, 735, 763,1759, 763,1759,1917,2031, 31, 303, 111, 367, 125, 375, 239, 383, 231, 764, 743, 957, 827, 958, 955, 959, 95, 761, 607, 879, 687, 887, 751, 895, 239, 765, 751,1759, 955, 1911,1887,1919, 123, 762, 671, 957, 635, 893, 765,1021, 247, 766, 759,1783, 891,1918,1911,2039, 223, 763, 735,1759, 763,1917,1759, 2031, 255, 767, 767,1791,1019,1919,1919,2047, 7, 23, 23, 55, 15, 31, 31, 63, 23, 122, 124, 126, 87, 123, 125, 127, 23, 124, 295, 311, 103, 231, 303, 319, 55, 126, 311, 382, 119, 247, 375, 383, 15, 87, 103, 119, 79, 95, 111, 127, 31, 123, 231, 247, 95, 223, 239, 255, 31, 125, 303, 375, 111, 239, 367, 383, 63, 127, 319, 383, 127, 255, 383, 511, 23, 124, 122, 126, 87, 125, 123, 127, 295, 634, 634, 638, 633, 635, 635, 639, 124, 826, 634, 830, 679, 827, 762, 831, 311, 830, 892, 894, 823, 891, 893, 895, 103, 679, 663, 695, 599, 687, 671, 703, 303, 762, 764, 766, 761, 763, 765, 767, 231, 827, 764, 958, 743, 955, 957, 959, 319, 831,1020,1021, 831,1019,1021,1023, 23, 295, 124, 311, 103, 303, 231, 319, 124, 634, 826, 830, 679, 762, 827, 831, 122, 634, 634, 892, 663, 764, 764,1020, 126, 638, 830, 894, 695, 766, 958,1021, 87, 633, 679, 823, 599, 761, 743, 831, 125, 635, 827, 891, 687, 763, 955,1019, 123, 635, 762, 893, 671, 765, 957,1021, 127, 639, 831, 895, 703, 767, 959,1023, 55, 311, 126, 382, 119, 375, 247, 383, 311, 892, 830, 894, 823, 893, 891, 895, 126, 830, 638, 894, 695, 958, 766,1021, 382, 894, 894,2029, 951,1918,1918,2031, 119, 823, 695, 951, 631, 887, 759, 959, 375, 893, 958,1918, 887,1917, 1911,1919, 247, 891, 766,1918, 759,1911,1783,2039, 383, 895,1021, 2031, 959,1919,2039,2047, 15, 103, 87, 119, 79, 111, 95, 127, 103, 663, 679, 695, 599, 671, 687, 703, 87, 679, 633, 823, 599, 743, 761, 831, 119, 695, 823, 951, 631, 759, 887, 959, 79, 599, 599, 631, 591, 607, 607, 639, 111, 671, 743, 759, 607, 735, 751, 767, 95, 687, 761, 887, 607, 751, 879, 895, 127, 703, 831, 959, 639, 767, 895,1023, 31, 231, 123, 247, 95, 239, 223, 255, 303, 764, 762, 766, 761, 765, 763, 767, 125, 827, 635, 891, 687, 955, 763,1019, 375, 958, 893,1918, 887,1911,1917,1919, 111, 743, 671, 759, 607, 751, 735, 767, 367, 957, 957,1783, 879,1759,1759,1791, 239, 955, 765,1911, 751,1887,1759,1919, 383, 959,1021,2039, 895, 1919,2031,2047, 31, 303, 125, 375, 111, 367, 239, 383, 231, 764, 827, 958, 743, 957, 955, 959, 123, 762, 635, 893, 671, 957, 765, 1021, 247, 766, 891,1918, 759,1783,1911,2039, 95, 761, 687, 887, 607, 879, 751, 895, 239, 765, 955,1911, 751,1759,1887,1919, 223, 763, 763,1917, 735,1759,1759,2031, 255, 767,1019,1919, 767,1791, 1919,2047, 63, 319, 127, 383, 127, 383, 255, 511, 319,1020, 831, 1021, 831,1021,1019,1023, 127, 831, 639, 895, 703, 959, 767,1023, 383,1021, 895,2031, 959,2039,1919,2047, 127, 831, 703, 959, 639, 895, 767,1023, 383,1021, 959,2039, 895,2031,1919,2047, 255,1019, 767,1919, 767,1919,1791,2047, 511,1023,1023,2047,1023,2047,2047, 4095 }; const unsigned int igraph_i_isoclass_4_idx[] = { 0, 8, 64, 512, 1, 0, 128, 1024, 2, 16, 0, 2048, 4, 32, 256, 0 }; const unsigned int igraph_i_isoclass_3u[] = { 0,1,1,3,1,3,3,7 }; const unsigned int igraph_i_isoclass_3u_idx[] = { 0,1,2,1,0,4,2,4,0 }; const unsigned int igraph_i_isoclass_4u[] = { 0, 1, 1, 3, 1, 3, 3, 7, 1, 3, 3,11,12,13,13,15, 1, 3,12,13, 3,11,13,15, 3, 7, 13,15,13,15,30,31, 1,12, 3,13, 3,13,11,15, 3,13, 7,15,13,30,15,31, 3,13,13,30, 7,15,15,31,11,15,15,31,15,31,31,63 }; const unsigned int igraph_i_isoclass_4u_idx[] = { 0, 1, 2, 8, 1, 0, 4, 16, 2, 4, 0, 32, 8, 16, 32, 0 }; const unsigned int igraph_i_isoclass2_3[] = { 0, 1, 1, 2, 1, 3, 4, 5, 1, 4, 6, 7, 2, 5, 7, 8, 1, 4, 3, 5, 6, 9, 9,10, 4,11, 9,12, 7,12,13,14, 1, 6, 4, 7, 4, 9,11,12, 3, 9, 9,13, 5,10,12,14, 2, 7, 5, 8, 7,13,12,14, 5,12,10,14, 8,14,14,15 }; const unsigned int igraph_i_isoclass2_3u[] = { 0,1,1,2,1,2,2,3 }; const unsigned int igraph_i_isoclass2_4u[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 4, 5, 6, 6, 7, 1, 2, 5, 6, 2, 4, 6, 7, 2, 3, 6, 7, 6, 7, 8, 9, 1, 5, 2, 6, 2, 6, 4, 7, 2, 6, 3, 7, 6, 8, 7, 9, 2, 6, 6, 8, 3, 7, 7, 9, 4, 7, 7, 9, 7, 9, 9,10 }; const unsigned int igraph_i_isoclass2_4[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 4, 5, 6, 5, 6, 7, 8, 1, 5, 9, 10, 11, 12, 13, 14, 2, 6, 10, 15, 12, 16, 17, 18, 1, 5, 11, 12, 9, 10, 13, 14, 2, 6, 12, 16, 10, 15, 17, 18, 2, 7, 13, 17, 13, 17, 19, 20, 3, 8, 14, 18, 14, 18, 20, 21, 1, 5, 4, 6, 5, 7, 6, 8, 9, 22, 22, 23, 24, 25, 25, 26, 5, 27, 22, 28, 29, 30, 31, 32, 10, 28, 33, 34, 35, 36, 37, 38, 11, 29, 39, 40, 41, 42, 43, 44, 13, 31, 45, 46, 47, 48, 49, 50, 12, 30, 45, 51, 52, 53, 54, 55, 14, 32, 56, 57, 58, 59, 60, 61, 1, 9, 5, 10, 11, 13, 12, 14, 5, 22, 27, 28, 29, 31, 30, 32, 4, 22, 22, 33, 39, 45, 45, 56, 6, 23, 28, 34, 40, 46, 51, 57, 5, 24, 29, 35, 41, 47, 52, 58, 7, 25, 30, 36, 42, 48, 53, 59, 6, 25, 31, 37, 43, 49, 54, 60, 8, 26, 32, 38, 44, 50, 55, 61, 2, 10, 6, 15, 12, 17, 16, 18, 10, 33, 28, 34, 35, 37, 36, 38, 6, 28, 23, 34, 40, 51, 46, 57, 15, 34, 34, 62, 63, 64, 64, 65, 12, 35, 40, 63, 66, 67, 68, 69, 17, 37, 51, 64, 67, 70, 71, 72, 16, 36, 46, 64, 68, 71, 73, 74, 18, 38, 57, 65, 69, 72, 74, 75, 1, 11, 5, 12, 9, 13, 10, 14, 11, 39, 29, 40, 41, 43, 42, 44, 5, 29, 24, 35, 41, 52, 47, 58, 12, 40, 35, 63, 66, 68, 67, 69, 9, 41, 41, 66, 76, 77, 77, 78, 13, 43, 52, 68, 77, 79, 80, 81, 10, 42, 47, 67, 77, 80, 82, 83, 14, 44, 58, 69, 78, 81, 83, 84, 2, 12, 6, 16, 10, 17, 15, 18, 13, 45, 31, 46, 47, 49, 48, 50, 7, 30, 25, 36, 42, 53, 48, 59, 17, 51, 37, 64, 67, 71, 70, 72, 13, 52, 43, 68, 77, 80, 79, 81, 19, 54, 54, 73, 82, 85, 85, 86, 17, 53, 49, 71, 80, 87, 85, 88, 20, 55, 60, 74, 83, 88, 89, 90, 2, 13, 7, 17, 13, 19, 17, 20, 12, 45, 30, 51, 52, 54, 53, 55, 6, 31, 25, 37, 43, 54, 49, 60, 16, 46, 36, 64, 68, 73, 71, 74, 10, 47, 42, 67, 77, 82, 80, 83, 17, 49, 53, 71, 80, 85, 87, 88, 15, 48, 48, 70, 79, 85, 85, 89, 18, 50, 59, 72, 81, 86, 88, 90, 3, 14, 8, 18, 14, 20, 18, 21, 14, 56, 32, 57, 58, 60, 59, 61, 8, 32, 26, 38, 44, 55, 50, 61, 18, 57, 38, 65, 69, 74, 72, 75, 14, 58, 44, 69, 78, 83, 81, 84, 20, 60, 55, 74, 83, 89, 88, 90, 18, 59, 50, 72, 81, 88, 86, 90, 21, 61, 61, 75, 84, 90, 90, 91, 1, 5, 5, 7, 4, 6, 6, 8, 9, 22, 24, 25, 22, 23, 25, 26, 11, 29, 41, 42, 39, 40, 43, 44, 13, 31, 47, 48, 45, 46, 49, 50, 5, 27, 29, 30, 22, 28, 31, 32, 10, 28, 35, 36, 33, 34, 37, 38, 12, 30, 52, 53, 45, 51, 54, 55, 14, 32, 58, 59, 56, 57, 60, 61, 9, 24, 22, 25, 22, 25, 23, 26, 76, 92, 92, 93, 92, 93, 93, 94, 41, 95, 96, 97, 98, 99,100,101, 77,102,103,104,105,106,107,108, 41, 95, 98, 99, 96, 97,100,101, 77,102,105,106, 103,104,107,108, 66,109,110,111,110,111,112,113, 78,114,115,116,115,116,117,118, 11, 41, 29, 42, 39, 43, 40, 44, 41, 96, 95, 97, 98,100, 99,101, 39, 98, 98,119, 120,121,121,122, 43,100,123,124,121,125,126,127, 29, 95,128,129, 98,123,130,131, 42, 97,129,132,119,124,133,134, 40, 99,130,133,121,126,135,136, 44,101,131,134, 122,127,136,137, 13, 47, 31, 48, 45, 49, 46, 50, 77,103,102,104,105,107,106,108, 43,123,100,124,121,126,125,127, 79,138,138,139,140,141,141,142, 52,143,130,144, 110,145,146,147, 80,148,149,150,151,152,153,154, 68,155,146,156,157,158,159,160, 81,161,162,163,164,165,166,167, 5, 29, 27, 30, 22, 31, 28, 32, 41, 98, 95, 99, 96,100, 97,101, 29,128, 95,129, 98,130,123,131, 52,130,143,144,110,146,145,147, 24, 95, 95,109, 92,102,102,114, 47,123,143,155,103,138,148,161, 35,129,143,168, 105,149,169,170, 58,131,171,172,115,162,173,174, 10, 35, 28, 36, 33, 37, 34, 38, 77,105,102,106,103,107,104,108, 42,129, 97,132,119,133,124,134, 80,149,148,150, 151,153,152,154, 47,143,123,155,103,148,138,161, 82,169,169,175,176,177,177,178, 67,168,145,179,151,180,181,182, 83,170,173,183,184,185,186,187, 12, 52, 30, 53, 45, 54, 51, 55, 66,110,109,111,110,112,111,113, 40,130, 99,133,121,135,126,136, 68,146,155,156,157,159,158,160, 35,143,129,168,105,169,149,170, 67,145,168,179, 151,181,180,182, 63,144,144,188,140,189,189,190, 69,147,172,191,164,192,193,194, 14, 58, 32, 59, 56, 60, 57, 61, 78,115,114,116,115,117,116,118, 44,131,101,134, 122,136,127,137, 81,162,161,163,164,166,165,167, 58,171,131,172,115,173,162,174, 83,173,170,183,184,186,185,187, 69,172,147,191,164,193,192,194, 84,174,174,195, 196,197,197,198, 1, 9, 11, 13, 5, 10, 12, 14, 5, 22, 29, 31, 27, 28, 30, 32, 5, 24, 41, 47, 29, 35, 52, 58, 7, 25, 42, 48, 30, 36, 53, 59, 4, 22, 39, 45, 22, 33, 45, 56, 6, 23, 40, 46, 28, 34, 51, 57, 6, 25, 43, 49, 31, 37, 54, 60, 8, 26, 44, 50, 32, 38, 55, 61, 11, 41, 39, 43, 29, 42, 40, 44, 41, 96, 98,100, 95, 97, 99,101, 29, 95, 98,123,128,129,130,131, 42, 97,119,124,129,132,133,134, 39, 98,120,121, 98,119,121,122, 43,100,121,125,123,124,126,127, 40, 99,121,126, 130,133,135,136, 44,101,122,127,131,134,136,137, 9, 76, 41, 77, 41, 77, 66, 78, 24, 92, 95,102, 95,102,109,114, 22, 92, 96,103, 98,105,110,115, 25, 93, 97,104, 99,106,111,116, 22, 92, 98,105, 96,103,110,115, 25, 93, 99,106, 97,104,111,116, 23, 93,100,107,100,107,112,117, 26, 94,101,108,101,108,113,118, 13, 77, 43, 79, 52, 80, 68, 81, 47,103,123,138,143,148,155,161, 31,102,100,138,130,149,146,162, 48,104,124,139,144,150,156,163, 45,105,121,140,110,151,157,164, 49,107,126,141, 145,152,158,165, 46,106,125,141,146,153,159,166, 50,108,127,142,147,154,160,167, 5, 41, 29, 52, 24, 47, 35, 58, 29, 98,128,130, 95,123,129,131, 27, 95, 95,143, 95,143,143,171, 30, 99,129,144,109,155,168,172, 22, 96, 98,110, 92,103,105,115, 31,100,130,146,102,138,149,162, 28, 97,123,145,102,148,169,173, 32,101,131,147, 114,161,170,174, 12, 66, 40, 68, 35, 67, 63, 69, 52,110,130,146,143,145,144,147, 30,109, 99,155,129,168,144,172, 53,111,133,156,168,179,188,191, 45,110,121,157, 105,151,140,164, 54,112,135,159,169,181,189,192, 51,111,126,158,149,180,189,193, 55,113,136,160,170,182,190,194, 10, 77, 42, 80, 47, 82, 67, 83, 35,105,129,149, 143,169,168,170, 28,102, 97,148,123,169,145,173, 36,106,132,150,155,175,179,183, 33,103,119,151,103,176,151,184, 37,107,133,153,148,177,180,185, 34,104,124,152, 138,177,181,186, 38,108,134,154,161,178,182,187, 14, 78, 44, 81, 58, 83, 69, 84, 58,115,131,162,171,173,172,174, 32,114,101,161,131,170,147,174, 59,116,134,163, 172,183,191,195, 56,115,122,164,115,184,164,196, 60,117,136,166,173,186,193,197, 57,116,127,165,162,185,192,197, 61,118,137,167,174,187,194,198, 2, 10, 12, 17, 6, 15, 16, 18, 10, 33, 35, 37, 28, 34, 36, 38, 12, 35, 66, 67, 40, 63, 68, 69, 17, 37, 67, 70, 51, 64, 71, 72, 6, 28, 40, 51, 23, 34, 46, 57, 15, 34, 63, 64, 34, 62, 64, 65, 16, 36, 68, 71, 46, 64, 73, 74, 18, 38, 69, 72, 57, 65, 74, 75, 13, 47, 45, 49, 31, 48, 46, 50, 77,103,105,107,102,104,106,108, 52,143,110,145, 130,144,146,147, 80,148,151,152,149,150,153,154, 43,123,121,126,100,124,125,127, 79,138,140,141,138,139,141,142, 68,155,157,158,146,156,159,160, 81,161,164,165, 162,163,166,167, 13, 77, 52, 80, 43, 79, 68, 81, 47,103,143,148,123,138,155,161, 45,105,110,151,121,140,157,164, 49,107,145,152,126,141,158,165, 31,102,130,149, 100,138,146,162, 48,104,144,150,124,139,156,163, 46,106,146,153,125,141,159,166, 50,108,147,154,127,142,160,167, 19, 82, 54, 85, 54, 85, 73, 86, 82,176,169,177, 169,177,175,178, 54,169,112,181,135,189,159,192, 85,177,181,199,189,200,201,202, 54,169,135,189,112,181,159,192, 85,177,189,200,181,199,201,202, 73,175,159,201, 159,201,203,204, 86,178,192,202,192,202,204,205, 7, 42, 30, 53, 25, 48, 36, 59, 42,119,129,133, 97,124,132,134, 30,129,109,168, 99,144,155,172, 53,133,168,188, 111,156,179,191, 25, 97, 99,111, 93,104,106,116, 48,124,144,156,104,139,150,163, 36,132,155,179,106,150,175,183, 59,134,172,191,116,163,183,195, 17, 67, 51, 71, 37, 70, 64, 72, 80,151,149,153,148,152,150,154, 53,168,111,179,133,188,156,191, 87,180,180,206,180,206,206,207, 49,145,126,158,107,152,141,165, 85,181,189,201, 177,199,200,202, 71,179,158,208,153,206,201,209, 88,182,193,209,185,210,211,212, 17, 80, 53, 87, 49, 85, 71, 88, 67,151,168,180,145,181,179,182, 51,149,111,180, 126,189,158,193, 71,153,179,206,158,201,208,209, 37,148,133,180,107,177,153,185, 70,152,188,206,152,199,206,210, 64,150,156,206,141,200,201,211, 72,154,191,207, 165,202,209,212, 20, 83, 55, 88, 60, 89, 74, 90, 83,184,170,185,173,186,183,187, 55,170,113,182,136,190,160,194, 88,185,182,210,193,211,209,212, 60,173,136,193, 117,186,166,197, 89,186,190,211,186,213,211,214, 74,183,160,209,166,211,204,215, 90,187,194,212,197,214,215,216, 1, 11, 9, 13, 5, 12, 10, 14, 11, 39, 41, 43, 29, 40, 42, 44, 9, 41, 76, 77, 41, 66, 77, 78, 13, 43, 77, 79, 52, 68, 80, 81, 5, 29, 41, 52, 24, 35, 47, 58, 12, 40, 66, 68, 35, 63, 67, 69, 10, 42, 77, 80, 47, 67, 82, 83, 14, 44, 78, 81, 58, 69, 83, 84, 5, 29, 22, 31, 27, 30, 28, 32, 41, 98, 96,100, 95, 99, 97,101, 24, 95, 92,102, 95,109,102,114, 47,123,103,138, 143,155,148,161, 29,128, 98,130, 95,129,123,131, 52,130,110,146,143,144,145,147, 35,129,105,149,143,168,169,170, 58,131,115,162,171,172,173,174, 5, 41, 24, 47, 29, 52, 35, 58, 29, 98, 95,123,128,130,129,131, 22, 96, 92,103, 98,110,105,115, 31,100,102,138,130,146,149,162, 27, 95, 95,143, 95,143,143,171, 30, 99,109,155, 129,144,168,172, 28, 97,102,148,123,145,169,173, 32,101,114,161,131,147,170,174, 7, 42, 25, 48, 30, 53, 36, 59, 42,119, 97,124,129,133,132,134, 25, 97, 93,104, 99,111,106,116, 48,124,104,139,144,156,150,163, 30,129, 99,144,109,168,155,172, 53,133,111,156,168,188,179,191, 36,132,106,150,155,179,175,183, 59,134,116,163, 172,191,183,195, 4, 39, 22, 45, 22, 45, 33, 56, 39,120, 98,121, 98,121,119,122, 22, 98, 92,105, 96,110,103,115, 45,121,105,140,110,157,151,164, 22, 98, 96,110, 92,105,103,115, 45,121,110,157,105,140,151,164, 33,119,103,151,103,151,176,184, 56,122,115,164,115,164,184,196, 6, 40, 23, 46, 28, 51, 34, 57, 43,121,100,125, 123,126,124,127, 25, 99, 93,106, 97,111,104,116, 49,126,107,141,145,158,152,165, 31,130,100,146,102,149,138,162, 54,135,112,159,169,189,181,192, 37,133,107,153, 148,180,177,185, 60,136,117,166,173,193,186,197, 6, 43, 25, 49, 31, 54, 37, 60, 40,121, 99,126,130,135,133,136, 23,100, 93,107,100,112,107,117, 46,125,106,141, 146,159,153,166, 28,123, 97,145,102,169,148,173, 51,126,111,158,149,189,180,193, 34,124,104,152,138,181,177,186, 57,127,116,165,162,192,185,197, 8, 44, 26, 50, 32, 55, 38, 61, 44,122,101,127,131,136,134,137, 26,101, 94,108,101,113,108,118, 50,127,108,142,147,160,154,167, 32,131,101,147,114,170,161,174, 55,136,113,160, 170,190,182,194, 38,134,108,154,161,182,178,187, 61,137,118,167,174,194,187,198, 2, 12, 10, 17, 6, 16, 15, 18, 13, 45, 47, 49, 31, 46, 48, 50, 13, 52, 77, 80, 43, 68, 79, 81, 19, 54, 82, 85, 54, 73, 85, 86, 7, 30, 42, 53, 25, 36, 48, 59, 17, 51, 67, 71, 37, 64, 70, 72, 17, 53, 80, 87, 49, 71, 85, 88, 20, 55, 83, 88, 60, 74, 89, 90, 10, 35, 33, 37, 28, 36, 34, 38, 77,105,103,107,102,106,104,108, 47,143,103,148,123,155,138,161, 82,169,176,177,169,175,177,178, 42,129,119,133, 97,132,124,134, 80,149,151,153,148,150,152,154, 67,168,151,180,145,179,181,182, 83,170,184,185,173,183,186,187, 12, 66, 35, 67, 40, 68, 63, 69, 52,110,143,145, 130,146,144,147, 45,110,105,151,121,157,140,164, 54,112,169,181,135,159,189,192, 30,109,129,168, 99,155,144,172, 53,111,168,179,133,156,188,191, 51,111,149,180, 126,158,189,193, 55,113,170,182,136,160,190,194, 17, 67, 37, 70, 51, 71, 64, 72, 80,151,148,152,149,153,150,154, 49,145,107,152,126,158,141,165, 85,181,177,199, 189,201,200,202, 53,168,133,188,111,179,156,191, 87,180,180,206,180,206,206,207, 71,179,153,206,158,208,201,209, 88,182,185,210,193,209,211,212, 6, 40, 28, 51, 23, 46, 34, 57, 43,121,123,126,100,125,124,127, 31,130,102,149,100,146,138,162, 54,135,169,189,112,159,181,192, 25, 99, 97,111, 93,106,104,116, 49,126,145,158, 107,141,152,165, 37,133,148,180,107,153,177,185, 60,136,173,193,117,166,186,197, 15, 63, 34, 64, 34, 64, 62, 65, 79,140,138,141,138,141,139,142, 48,144,104,150, 124,156,139,163, 85,189,177,200,181,201,199,202, 48,144,124,156,104,150,139,163, 85,189,181,201,177,200,199,202, 70,188,152,206,152,206,199,210, 89,190,186,211, 186,211,213,214, 16, 68, 36, 71, 46, 73, 64, 74, 68,157,155,158,146,159,156,160, 46,146,106,153,125,159,141,166, 73,159,175,201,159,203,201,204, 36,155,132,179, 106,175,150,183, 71,158,179,208,153,201,206,209, 64,156,150,206,141,201,200,211, 74,160,183,209,166,204,211,215, 18, 69, 38, 72, 57, 74, 65, 75, 81,164,161,165, 162,166,163,167, 50,147,108,154,127,160,142,167, 86,192,178,202,192,204,202,205, 59,172,134,191,116,183,163,195, 88,193,182,209,185,211,210,212, 72,191,154,207, 165,209,202,212, 90,194,187,212,197,215,214,216, 2, 13, 13, 19, 7, 17, 17, 20, 12, 45, 52, 54, 30, 51, 53, 55, 10, 47, 77, 82, 42, 67, 80, 83, 17, 49, 80, 85, 53, 71, 87, 88, 6, 31, 43, 54, 25, 37, 49, 60, 16, 46, 68, 73, 36, 64, 71, 74, 15, 48, 79, 85, 48, 70, 85, 89, 18, 50, 81, 86, 59, 72, 88, 90, 12, 52, 45, 54, 30, 53, 51, 55, 66,110,110,112,109,111,111,113, 35,143,105,169,129,168,149,170, 67,145,151,181,168,179,180,182, 40,130,121,135, 99,133,126,136, 68,146,157,159, 155,156,158,160, 63,144,140,189,144,188,189,190, 69,147,164,192,172,191,193,194, 10, 77, 47, 82, 42, 80, 67, 83, 35,105,143,169,129,149,168,170, 33,103,103,176, 119,151,151,184, 37,107,148,177,133,153,180,185, 28,102,123,169, 97,148,145,173, 36,106,155,175,132,150,179,183, 34,104,138,177,124,152,181,186, 38,108,161,178, 134,154,182,187, 17, 80, 49, 85, 53, 87, 71, 88, 67,151,145,181,168,180,179,182, 37,148,107,177,133,180,153,185, 70,152,152,199,188,206,206,210, 51,149,126,189, 111,180,158,193, 71,153,158,201,179,206,208,209, 64,150,141,200,156,206,201,211, 72,154,165,202,191,207,209,212, 6, 43, 31, 54, 25, 49, 37, 60, 40,121,130,135, 99,126,133,136, 28,123,102,169, 97,145,148,173, 51,126,149,189,111,158,180,193, 23,100,100,112, 93,107,107,117, 46,125,146,159,106,141,153,166, 34,124,138,181, 104,152,177,186, 57,127,162,192,116,165,185,197, 16, 68, 46, 73, 36, 71, 64, 74, 68,157,146,159,155,158,156,160, 36,155,106,175,132,179,150,183, 71,158,153,201, 179,208,206,209, 46,146,125,159,106,153,141,166, 73,159,159,203,175,201,201,204, 64,156,141,201,150,206,200,211, 74,160,166,204,183,209,211,215, 15, 79, 48, 85, 48, 85, 70, 89, 63,140,144,189,144,189,188,190, 34,138,104,177,124,181,152,186, 64,141,150,200,156,201,206,211, 34,138,124,181,104,177,152,186, 64,141,156,201, 150,200,206,211, 62,139,139,199,139,199,199,213, 65,142,163,202,163,202,210,214, 18, 81, 50, 86, 59, 88, 72, 90, 69,164,147,192,172,193,191,194, 38,161,108,178, 134,182,154,187, 72,165,154,202,191,209,207,212, 57,162,127,192,116,185,165,197, 74,166,160,204,183,211,209,215, 65,163,142,202,163,210,202,214, 75,167,167,205, 195,212,212,216, 3, 14, 14, 20, 8, 18, 18, 21, 14, 56, 58, 60, 32, 57, 59, 61, 14, 58, 78, 83, 44, 69, 81, 84, 20, 60, 83, 89, 55, 74, 88, 90, 8, 32, 44, 55, 26, 38, 50, 61, 18, 57, 69, 74, 38, 65, 72, 75, 18, 59, 81, 88, 50, 72, 86, 90, 21, 61, 84, 90, 61, 75, 90, 91, 14, 58, 56, 60, 32, 59, 57, 61, 78,115,115,117, 114,116,116,118, 58,171,115,173,131,172,162,174, 83,173,184,186,170,183,185,187, 44,131,122,136,101,134,127,137, 81,162,164,166,161,163,165,167, 69,172,164,193, 147,191,192,194, 84,174,196,197,174,195,197,198, 14, 78, 58, 83, 44, 81, 69, 84, 58,115,171,173,131,162,172,174, 56,115,115,184,122,164,164,196, 60,117,173,186, 136,166,193,197, 32,114,131,170,101,161,147,174, 59,116,172,183,134,163,191,195, 57,116,162,185,127,165,192,197, 61,118,174,187,137,167,194,198, 20, 83, 60, 89, 55, 88, 74, 90, 83,184,173,186,170,185,183,187, 60,173,117,186,136,193,166,197, 89,186,186,213,190,211,211,214, 55,170,136,190,113,182,160,194, 88,185,193,211, 182,210,209,212, 74,183,166,211,160,209,204,215, 90,187,197,214,194,212,215,216, 8, 44, 32, 55, 26, 50, 38, 61, 44,122,131,136,101,127,134,137, 32,131,114,170, 101,147,161,174, 55,136,170,190,113,160,182,194, 26,101,101,113, 94,108,108,118, 50,127,147,160,108,142,154,167, 38,134,161,182,108,154,178,187, 61,137,174,194, 118,167,187,198, 18, 69, 57, 74, 38, 72, 65, 75, 81,164,162,166,161,165,163,167, 59,172,116,183,134,191,163,195, 88,193,185,211,182,209,210,212, 50,147,127,160, 108,154,142,167, 86,192,192,204,178,202,202,205, 72,191,165,209,154,207,202,212, 90,194,197,215,187,212,214,216, 18, 81, 59, 88, 50, 86, 72, 90, 69,164,172,193, 147,192,191,194, 57,162,116,185,127,192,165,197, 74,166,183,211,160,204,209,215, 38,161,134,182,108,178,154,187, 72,165,191,209,154,202,207,212, 65,163,163,210, 142,202,202,214, 75,167,195,212,167,205,212,216, 21, 84, 61, 90, 61, 90, 75, 91, 84,196,174,197,174,197,195,198, 61,174,118,187,137,194,167,198, 90,197,187,214, 194,215,212,216, 61,174,137,194,118,187,167,198, 90,197,194,215,187,214,212,216, 75,195,167,212,167,212,205,216, 91,198,198,216,198,216,216,217 }; const unsigned int igraph_i_isographs_3[] = { 0, 1, 3, 5, 6, 7, 10, 11, 15, 21, 23, 25, 27, 30, 31, 63 }; const unsigned int igraph_i_isographs_3u[] = { 0, 1, 3, 7 }; const unsigned int igraph_i_isographs_4[] = { 0, 1, 3, 7, 9, 10, 11, 14, 15, 18, 19, 20, 21, 22, 23, 27, 29, 30, 31, 54, 55, 63, 73, 75, 76, 77, 79, 81, 83, 84, 85, 86, 87, 90, 91, 92, 93, 94, 95, 98, 99, 100, 101, 102, 103, 106, 107, 108, 109, 110, 111, 115, 116, 117, 118, 119, 122, 123, 124, 125, 126, 127, 219, 220, 221, 223, 228, 229, 230, 231, 237, 238, 239, 246, 247, 255, 292, 293, 295, 301, 302, 303, 310, 311, 319, 365, 367, 373, 375, 382, 383, 511, 585, 587, 591, 593, 594, 595, 596, 597, 598, 599, 601, 602, 603, 604, 605, 606, 607, 625, 626, 627, 630, 631, 633, 634, 635, 638, 639, 659, 660, 661, 663, 666, 667, 669, 670, 671, 674, 675, 678, 679, 683, 686, 687, 694, 695, 703, 729, 731, 732, 733, 735, 737, 739, 741, 742, 743, 745, 746, 747, 748, 749, 750, 751, 753, 755, 756, 757, 758, 759, 761, 762, 763, 764, 765, 766, 767, 819, 822, 823, 826, 827, 830, 831, 875, 876, 877, 879, 883, 885, 886, 887, 891, 892, 893, 894, 895, 947, 949, 951, 955, 957, 958, 959, 1019, 1020, 1021, 1023, 1755, 1757, 1758, 1759, 1782, 1783, 1791, 1883, 1887, 1907, 1911, 1917, 1918, 1919, 2029, 2031, 2039, 2047, 4095}; const unsigned int igraph_i_isographs_4u[] = { 0, 1, 3, 7, 11, 12, 13, 15, 30, 31, 63}; const unsigned int igraph_i_classedges_3[] = { 1,2, 0,2, 2,1, 0,1, 2,0, 1,0 }; const unsigned int igraph_i_classedges_3u[] = { 1,2, 0,2, 0,1 }; const unsigned int igraph_i_classedges_4[] = { 2,3, 1,3, 0,3, 3,2, 1,2, 0,2, 3,1, 2,1, 0,1, 3,0, 2,0, 1,0 }; const unsigned int igraph_i_classedges_4u[] = { 2,3, 1,3, 0,3, 1,2, 0,2, 0,1 }; /** * \section about_graph_isomorphism * * igraph provides four set of functions to deal with graph * isomorphism problems. * * The \ref igraph_isomorphic() and \ref igraph_subisomorphic() * functions make up the first set (in addition with the \ref * igraph_permute_vertices() function). These functions choose the * algorithm which is best for the supplied input graph. (The choice is * not very sophisticated though, see their documentation for * details.) * * The VF2 graph (and subgraph) isomorphism algorithm is implemented in * igraph, these functions are the second set. See \ref * igraph_isomorphic_vf2() and \ref igraph_subisomorphic_vf2() for * starters. * * Functions for the BLISS algorithm constitute the third set, * see \ref igraph_isomorphic_bliss(). * * Finally, the isomorphism classes of all graphs with three and * four vertices are precomputed and stored in igraph, so for these * small graphs there is a very simple fast way to decide isomorphism. * See \ref igraph_isomorphic_34(). * */ /** * \function igraph_isoclass * \brief Determine the isomorphism class of a graph with 3 or 4 vertices * * * All graphs with a given number of vertices belong to a number of * isomorphism classes, with every graph in a given class being * isomorphic to each other. * * * This function gives the isomorphism class (a number) of a * graph. Two graphs have the same isomorphism class if and only if * they are isomorphic. * * * The first isomorphism class is numbered zero and it is the empty * graph, the last isomorphism class is the full graph. The number of * isomorphism class for directed graphs with three vertices is 16 * (between 0 and 15), for undirected graph it is only 4. For graphs * with four vertices it is 218 (directed) and 11 (undirected). * * \param graph The graph object. * \param isoclass Pointer to an integer, the isomorphism class will * be stored here. * \return Error code. * \sa \ref igraph_isomorphic(), \ref igraph_isoclass_subgraph(), * \ref igraph_isoclass_create(), \ref igraph_motifs_randesu(). * * Because of some limitations this function works only for graphs * with three of four vertices. * * * Time complexity: O(|E|), the number of edges in the graph. */ int igraph_isoclass(const igraph_t *graph, igraph_integer_t *isoclass) { long int e; long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_integer_t from, to; unsigned char idx, mul; const unsigned int *arr_idx, *arr_code; int code=0; if (no_of_nodes < 3 || no_of_nodes > 4) { IGRAPH_ERROR("Only implemented for graphs with 3 or 4 vertices", IGRAPH_UNIMPLEMENTED); } if (igraph_is_directed(graph)) { if (no_of_nodes==3) { arr_idx=igraph_i_isoclass_3_idx; arr_code=igraph_i_isoclass2_3; mul=3; } else { arr_idx=igraph_i_isoclass_4_idx; arr_code=igraph_i_isoclass2_4; mul=4; } } else { if (no_of_nodes==3) { arr_idx=igraph_i_isoclass_3u_idx; arr_code=igraph_i_isoclass2_3u; mul=3; } else { arr_idx=igraph_i_isoclass_4u_idx; arr_code=igraph_i_isoclass2_4u; mul=4; } } for (e=0; e * From Wikipedia: The graph isomorphism problem or GI problem is the * graph theory problem of determining whether, given two graphs G1 * and G2, it is possible to permute (or relabel) the vertices of one * graph so that it is equal to the other. Such a permutation is * called a graph isomorphism. * * This function decides which graph isomorphism algorithm to be * used based on the input graphs. Right now it does the following: * \olist * \oli If one graph is directed and the other undirected then an * error is triggered. * \oli If the two graphs does not have the same number of vertices * and edges it returns with \c FALSE. * \oli Otherwise, if the graphs have three or four vertices then an O(1) * algorithm is used with precomputed data. * \oli Otherwise BLISS is used, see \ref igraph_isomorphic_bliss(). * \endolist * * * Please call the VF2 and BLISS functions directly if you need * something more sophisticated, e.g. you need the isomorphic mapping. * * \param graph1 The first graph. * \param graph2 The second graph. * \param iso Pointer to a logical variable, will be set to TRUE (1) * if the two graphs are isomorphic, and FALSE (0) otherwise. * \return Error code. * \sa \ref igraph_isoclass(), \ref igraph_isoclass_subgraph(), * \ref igraph_isoclass_create(). * * Time complexity: exponential. */ int igraph_isomorphic(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso) { long int nodes1=igraph_vcount(graph1), nodes2=igraph_vcount(graph2); long int edges1=igraph_ecount(graph1), edges2=igraph_ecount(graph2); igraph_bool_t dir1=igraph_is_directed(graph1), dir2=igraph_is_directed(graph2); igraph_bool_t loop1, loop2; if (dir1 != dir2) { IGRAPH_ERROR("Cannot compare directed and undirected graphs", IGRAPH_EINVAL); } else if (nodes1 != nodes2 || edges1 != edges2) { *iso=0; } else if (nodes1==3 || nodes1==4) { IGRAPH_CHECK(igraph_has_loop(graph1, &loop1)); IGRAPH_CHECK(igraph_has_loop(graph2, &loop2)); if (!loop1 && !loop2) { IGRAPH_CHECK(igraph_isomorphic_34(graph1, graph2, iso)); } else { IGRAPH_CHECK(igraph_isomorphic_bliss(graph1, graph2, NULL, NULL, iso, 0, 0, /*sh=*/ IGRAPH_BLISS_F, 0, 0)); } } else { IGRAPH_CHECK(igraph_isomorphic_bliss(graph1, graph2, NULL, NULL, iso, 0, 0, /*sh=*/ IGRAPH_BLISS_F, 0, 0)); } return 0; } /** * \function igraph_isomorphic_34 * Graph isomorphism for 3-4 vertices * * This function uses precomputed indices to decide isomorphism * problems for graphs with only 3 or 4 vertices. * \param graph1 The first input graph. * \param graph2 The second input graph. Must have the same * directedness as \p graph1. * \param iso Pointer to a boolean, the result is stored here. * \return Error code. * * Time complexity: O(1). */ int igraph_isomorphic_34(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso) { igraph_integer_t class1, class2; IGRAPH_CHECK(igraph_isoclass(graph1, &class1)); IGRAPH_CHECK(igraph_isoclass(graph2, &class2)); *iso= (class1 == class2); return 0; } /** * \function igraph_isoclass_subgraph * \brief The isomorphism class of a subgraph of a graph. * * * This function is only implemented for subgraphs with three or four * vertices. * \param graph The graph object. * \param vids A vector containing the vertex ids to be considered as * a subgraph. Each vertex id should be included at most once. * \param isoclass Pointer to an integer, this will be set to the * isomorphism class. * \return Error code. * \sa \ref igraph_isoclass(), \ref igraph_isomorphic(), * \ref igraph_isoclass_create(). * * Time complexity: O((d+n)*n), d is the average degree in the network, * and n is the number of vertices in \c vids. */ int igraph_isoclass_subgraph(const igraph_t *graph, igraph_vector_t *vids, igraph_integer_t *isoclass) { int nodes=(int) igraph_vector_size(vids); igraph_bool_t directed=igraph_is_directed(graph); igraph_vector_t neis; unsigned char mul, idx; const unsigned int *arr_idx, *arr_code; int code=0; long int i, j, s; if (nodes < 3 || nodes > 4) { IGRAPH_ERROR("Only for three- or four-vertex subgraphs", IGRAPH_UNIMPLEMENTED); } IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); if (directed) { if (nodes==3) { arr_idx=igraph_i_isoclass_3_idx; arr_code=igraph_i_isoclass2_3; mul=3; } else { arr_idx=igraph_i_isoclass_4_idx; arr_code=igraph_i_isoclass2_4; mul=4; } } else { if (nodes==3) { arr_idx=igraph_i_isoclass_3u_idx; arr_code=igraph_i_isoclass2_3u; mul=3; } else { arr_idx=igraph_i_isoclass_4u_idx; arr_code=igraph_i_isoclass2_4u; mul=4; } } for (i=0; i * This function is implemented only for graphs with three or four * vertices. * \param graph Pointer to an uninitialized graph object. * \param size The number of vertices to add to the graph. * \param number The isomorphism class. * \param directed Logical constant, whether to create a directed * graph. * \return Error code. * \sa \ref igraph_isoclass(), * \ref igraph_isoclass_subgraph(), * \ref igraph_isomorphic(). * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges in the graph to create. */ int igraph_isoclass_create(igraph_t *graph, igraph_integer_t size, igraph_integer_t number, igraph_bool_t directed) { igraph_vector_t edges; const unsigned int *classedges; long int power; long int code; long int pos; if (size < 3 || size > 4) { IGRAPH_ERROR("Only for graphs with three of four vertices", IGRAPH_UNIMPLEMENTED); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); if (directed) { if (size==3) { classedges=igraph_i_classedges_3; if (number < 0 || number >= (int)(sizeof(igraph_i_isographs_3)/sizeof(unsigned int))){ IGRAPH_ERROR("`number' invalid, cannot create graph", IGRAPH_EINVAL); } code=igraph_i_isographs_3[ (long int) number]; power=32; } else { classedges=igraph_i_classedges_4; if (number < 0 || number >= (int)(sizeof(igraph_i_isographs_4)/sizeof(unsigned int))){ IGRAPH_ERROR("`number' invalid, cannot create graph", IGRAPH_EINVAL); } code=igraph_i_isographs_4[ (long int) number]; power=2048; } } else { if (size==3) { classedges=igraph_i_classedges_3u; if (number < 0 || number >= (int)(sizeof(igraph_i_isographs_3u)/ sizeof(unsigned int))){ IGRAPH_ERROR("`number' invalid, cannot create graph", IGRAPH_EINVAL); } code=igraph_i_isographs_3u[ (long int) number]; power=4; } else { classedges=igraph_i_classedges_4u; if (number < 0 || number >= (int)(sizeof(igraph_i_isographs_4u)/ sizeof(unsigned int))) { IGRAPH_ERROR("`number' invalid, cannot create graph", IGRAPH_EINVAL); } code=igraph_i_isographs_4u[ (long int) number]; power=32; } } pos=0; while (code > 0) { if (code >= power) { IGRAPH_CHECK(igraph_vector_push_back(&edges, classedges[2*pos])); IGRAPH_CHECK(igraph_vector_push_back(&edges, classedges[2*pos+1])); code -= power; } power /= 2; pos++; } IGRAPH_CHECK(igraph_create(graph, &edges, size, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_isomorphic_function_vf2 * The generic VF2 interface * * * This function is an implementation of the VF2 isomorphism algorithm, * see P. Foggia, C. Sansone, M. Vento, An Improved algorithm for * matching large graphs, Proc. of the 3rd IAPR-TC-15 International * Workshop on Graph-based Representations, Italy, 2001. * * For using it you need to define a callback function of type * \ref igraph_isohandler_t. This function will be called whenever VF2 * finds an isomorphism between the two graphs. The mapping between * the two graphs will be also provided to this function. If the * callback returns a nonzero value then the search is continued, * otherwise it stops. The callback function must not destroy the * mapping vectors that are passed to it. * \param graph1 The first input graph. * \param graph2 The second input graph. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param map12 Pointer to an initialized vector or \c NULL. If not \c * NULL and the supplied graphs are isomorphic then the permutation * taking \p graph1 to \p graph is stored here. If not \c NULL and the * graphs are not isomorphic then a zero-length vector is returned. * \param map21 This is the same as \p map12, but for the permutation * taking \p graph2 to \p graph1. * \param isohandler_fn The callback function to be called if an * isomorphism is found. See also \ref igraph_isohandler_t. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p isohandler_fn, \p * node_compat_fn and \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_isomorphic_function_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isohandler_t *isohandler_fn, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { long int no_of_nodes=igraph_vcount(graph1); long int no_of_edges=igraph_ecount(graph1); igraph_vector_t mycore_1, mycore_2, *core_1=&mycore_1, *core_2=&mycore_2; igraph_vector_t in_1, in_2, out_1, out_2; long int in_1_size=0, in_2_size=0, out_1_size=0, out_2_size=0; igraph_vector_t *inneis_1, *inneis_2, *outneis_1, *outneis_2; long int matched_nodes=0; long int depth; long int cand1, cand2; long int last1, last2; igraph_stack_t path; igraph_lazy_adjlist_t inadj1, inadj2, outadj1, outadj2; igraph_vector_t indeg1, indeg2, outdeg1, outdeg2; if (igraph_is_directed(graph1) != igraph_is_directed(graph2)) { IGRAPH_ERROR("Cannot compare directed and undirected graphs", IGRAPH_EINVAL); } if ( (vertex_color1 && !vertex_color2) || (!vertex_color1 && vertex_color2) ) { IGRAPH_WARNING("Only one graph is vertex-colored, vertex colors will be ignored"); vertex_color1=vertex_color2=0; } if ( (edge_color1 && !edge_color2) || (!edge_color1 && edge_color2)) { IGRAPH_WARNING("Only one graph is edge-colored, edge colors will be ignored"); edge_color1 = edge_color2 = 0; } if (no_of_nodes != igraph_vcount(graph2) || no_of_edges != igraph_ecount(graph2)) { return 0; } if (vertex_color1) { if (igraph_vector_int_size(vertex_color1) != no_of_nodes || igraph_vector_int_size(vertex_color2) != no_of_nodes) { IGRAPH_ERROR("Invalid vertex color vector length", IGRAPH_EINVAL); } } if (edge_color1) { if (igraph_vector_int_size(edge_color1) != no_of_edges || igraph_vector_int_size(edge_color2) != no_of_edges) { IGRAPH_ERROR("Invalid edge color vector length", IGRAPH_EINVAL); } } /* Check color distribution */ if (vertex_color1) { int ret=0; igraph_vector_int_t tmp1, tmp2; IGRAPH_CHECK(igraph_vector_int_copy(&tmp1, vertex_color1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &tmp1); IGRAPH_CHECK(igraph_vector_int_copy(&tmp2, vertex_color2)); IGRAPH_FINALLY(igraph_vector_int_destroy, &tmp2); igraph_vector_int_sort(&tmp1); igraph_vector_int_sort(&tmp2); ret= !igraph_vector_int_all_e(&tmp1, &tmp2); igraph_vector_int_destroy(&tmp1); igraph_vector_int_destroy(&tmp2); IGRAPH_FINALLY_CLEAN(2); if (ret) { return 0; } } /* Check edge color distribution */ if (edge_color1) { int ret=0; igraph_vector_int_t tmp1, tmp2; IGRAPH_CHECK(igraph_vector_int_copy(&tmp1, edge_color1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &tmp1); IGRAPH_CHECK(igraph_vector_int_copy(&tmp2, edge_color2)); IGRAPH_FINALLY(igraph_vector_int_destroy, &tmp2); igraph_vector_int_sort(&tmp1); igraph_vector_int_sort(&tmp2); ret= !igraph_vector_int_all_e(&tmp1, &tmp2); igraph_vector_int_destroy(&tmp1); igraph_vector_int_destroy(&tmp2); IGRAPH_FINALLY_CLEAN(2); if (ret) { return 0; } } if (map12) { core_1=map12; IGRAPH_CHECK(igraph_vector_resize(core_1, no_of_nodes)); } else { IGRAPH_VECTOR_INIT_FINALLY(core_1, no_of_nodes); } igraph_vector_fill(core_1, -1); if (map21) { core_2=map21; IGRAPH_CHECK(igraph_vector_resize(core_2, no_of_nodes)); igraph_vector_null(core_2); } else { IGRAPH_VECTOR_INIT_FINALLY(core_2, no_of_nodes); } igraph_vector_fill(core_2, -1); IGRAPH_VECTOR_INIT_FINALLY(&in_1, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&in_2, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&out_1, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&out_2, no_of_nodes); IGRAPH_CHECK(igraph_stack_init(&path, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &path); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph1, &inadj1, IGRAPH_IN, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &inadj1); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph1, &outadj1, IGRAPH_OUT, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &outadj1); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph2, &inadj2, IGRAPH_IN, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &inadj2); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph2, &outadj2, IGRAPH_OUT, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &outadj2); IGRAPH_VECTOR_INIT_FINALLY(&indeg1, 0); IGRAPH_VECTOR_INIT_FINALLY(&indeg2, 0); IGRAPH_VECTOR_INIT_FINALLY(&outdeg1, 0); IGRAPH_VECTOR_INIT_FINALLY(&outdeg2, 0); IGRAPH_CHECK(igraph_stack_reserve(&path, no_of_nodes*2)); IGRAPH_CHECK(igraph_degree(graph1, &indeg1, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph2, &indeg2, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph1, &outdeg1, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph2, &outdeg2, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS)); depth=0; last1=-1; last2=-1; while (depth >= 0) { long int i; IGRAPH_ALLOW_INTERRUPTION(); cand1=-1; cand2=-1; /* Search for the next pair to try */ if ((in_1_size != in_2_size) || (out_1_size != out_2_size)) { /* step back, nothing to do */ } else if (out_1_size > 0 && out_2_size > 0) { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i0 && VECTOR(*core_2)[i] < 0) { cand2=i; } i++; } } /* search for cand1 now, it should be bigger than last1 */ i=last1+1; while (cand1<0 && i0 && VECTOR(*core_1)[i] < 0) { cand1=i; } i++; } } else if (in_1_size > 0 && in_2_size > 0) { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i0 && VECTOR(*core_2)[i] < 0) { cand2=i; } i++; } } /* search for cand1 now, should be bigger than last1 */ i=last1+1; while (cand1<0 && i0 && VECTOR(*core_1)[i] < 0) { cand1=i; } i++; } } else { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i= 1) { last2=(long int) igraph_stack_pop(&path); last1=(long int) igraph_stack_pop(&path); matched_nodes -= 1; VECTOR(*core_1)[last1]=-1; VECTOR(*core_2)[last2]=-1; if (VECTOR(in_1)[last1] != 0) { in_1_size += 1; } if (VECTOR(out_1)[last1] != 0) { out_1_size += 1; } if (VECTOR(in_2)[last2] != 0) { in_2_size += 1; } if (VECTOR(out_2)[last2] != 0) { out_2_size += 1; } inneis_1=igraph_lazy_adjlist_get(&inadj1, (igraph_integer_t) last1); for (i=0; i=0) { long int node2=(long int) VECTOR(*core_1)[node]; /* check if there is a node2->cand2 edge */ if (!igraph_vector_binsearch2(inneis_2, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) node, (igraph_integer_t) cand1, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) node2, (igraph_integer_t) cand2, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_1)[node] != 0) { xin1++; } if (VECTOR(out_1)[node] != 0) { xout1++; } } } for (i=0; !end && i=0) { long int node2=(long int) VECTOR(*core_1)[node]; /* check if there is a cand2->node2 edge */ if (!igraph_vector_binsearch2(outneis_2, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) cand1, (igraph_integer_t) node, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) cand2, (igraph_integer_t) node2, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_1)[node] != 0) { xin1++; } if (VECTOR(out_1)[node] != 0) { xout1++; } } } for (i=0; !end && i=0) { long int node2=(long int) VECTOR(*core_2)[node]; /* check if there is a node2->cand1 edge */ if (!igraph_vector_binsearch2(inneis_1, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) node2, (igraph_integer_t) cand1, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) node, (igraph_integer_t) cand2, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_2)[node] != 0) { xin2++; } if (VECTOR(out_2)[node] != 0) { xout2++; } } } for (i=0; !end && i= 0) { long int node2=(long int) VECTOR(*core_2)[node]; /* check if there is a cand1->node2 edge */ if (!igraph_vector_binsearch2(outneis_1, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) cand1, (igraph_integer_t) node2, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) cand2, (igraph_integer_t) node, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_2)[node] != 0) { xin2++; } if (VECTOR(out_2)[node] != 0) { xout2++; } } } if (!end && (xin1==xin2 && xout1==xout2)) { /* Ok, we add the (cand1, cand2) pair to the mapping */ depth += 1; IGRAPH_CHECK(igraph_stack_push(&path, cand1)); IGRAPH_CHECK(igraph_stack_push(&path, cand2)); matched_nodes += 1; VECTOR(*core_1)[cand1]=cand2; VECTOR(*core_2)[cand2]=cand1; /* update in_*, out_* */ if (VECTOR(in_1)[cand1] != 0) { in_1_size -= 1; } if (VECTOR(out_1)[cand1] != 0) { out_1_size -= 1; } if (VECTOR(in_2)[cand2] != 0) { in_2_size -= 1; } if (VECTOR(out_2)[cand2] != 0) { out_2_size -= 1; } inneis_1=igraph_lazy_adjlist_get(&inadj1, (igraph_integer_t) cand1); for (i=0; inode_compat_fn(graph1, graph2, g1_num, g2_num, data->carg); } igraph_bool_t igraph_i_isocompat_edge_cb(const igraph_t *graph1, const igraph_t *graph2, const igraph_integer_t g1_num, const igraph_integer_t g2_num, void *arg) { igraph_i_iso_cb_data_t *data=arg; return data->edge_compat_fn(graph1, graph2, g1_num, g2_num, data->carg); } igraph_bool_t igraph_i_isomorphic_vf2(igraph_vector_t *map12, igraph_vector_t *map21, void *arg) { igraph_i_iso_cb_data_t *data = arg; igraph_bool_t *iso = data->arg; IGRAPH_UNUSED(map12); IGRAPH_UNUSED(map21); *iso = 1; return 0; /* don't need to continue */ } /** * \function igraph_isomorphic_vf2 * \brief Isomorphism via VF2 * * * This function performs the VF2 algorithm via calling \ref * igraph_isomorphic_function_vf2(). * * Note that this function cannot be used for * deciding subgraph isomorphism, use \ref igraph_subisomorphic_vf2() * for that. * \param graph1 The first graph, may be directed or undirected. * \param graph2 The second graph. It must have the same directedness * as \p graph1, otherwise an error is reported. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param iso Pointer to a logical constant, the result of the * algorithm will be placed here. * \param map12 Pointer to an initialized vector or a NULL pointer. If not * a NULL pointer then the mapping from \p graph1 to \p graph2 is * stored here. If the graphs are not isomorphic then the vector is * cleared (ie. has zero elements). * \param map21 Pointer to an initialized vector or a NULL pointer. If not * a NULL pointer then the mapping from \p graph2 to \p graph1 is * stored here. If the graphs are not isomorphic then the vector is * cleared (ie. has zero elements). * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn * and \p edge_compat_fn. * \return Error code. * * \sa \ref igraph_subisomorphic_vf2(), * \ref igraph_count_isomorphisms_vf2(), * \ref igraph_get_isomorphisms_vf2(), * * Time complexity: exponential, what did you expect? * * \example examples/simple/igraph_isomorphic_vf2.c */ int igraph_isomorphic_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, iso, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; *iso=0; IGRAPH_CHECK(igraph_isomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, map12, map21, (igraph_isohandler_t*) igraph_i_isomorphic_vf2, ncb, ecb, &data)); if (! *iso) { if (map12) { igraph_vector_clear(map12); } if (map21) { igraph_vector_clear(map21); } } return 0; } igraph_bool_t igraph_i_count_isomorphisms_vf2(const igraph_vector_t *map12, const igraph_vector_t *map21, void *arg) { igraph_i_iso_cb_data_t *data = arg; igraph_integer_t *count = data->arg; IGRAPH_UNUSED(map12); IGRAPH_UNUSED(map21); *count += 1; return 1; /* always continue */ } /** * \function igraph_count_isomorphisms_vf2 * Number of isomorphisms via VF2 * * This function counts the number of isomorphic mappings between two * graphs. It uses the generic \ref igraph_isomorphic_function_vf2() * function. * \param graph1 The first input graph, may be directed or undirected. * \param graph2 The second input graph, it must have the same * directedness as \p graph1, or an error will be reported. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param count Point to an integer, the result will be stored here. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn and * \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_count_isomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_integer_t *count, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, count, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; *count=0; IGRAPH_CHECK(igraph_isomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, 0, 0, (igraph_isohandler_t*) igraph_i_count_isomorphisms_vf2, ncb, ecb, &data)); return 0; } void igraph_i_get_isomorphisms_free(igraph_vector_ptr_t *data) { long int i, n=igraph_vector_ptr_size(data); for (i=0; iarg; igraph_vector_t *newvector=igraph_Calloc(1, igraph_vector_t); IGRAPH_UNUSED(map12); if (!newvector) { igraph_error("Out of memory", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; /* stop right here */ } IGRAPH_FINALLY(igraph_free, newvector); IGRAPH_CHECK(igraph_vector_copy(newvector, map21)); IGRAPH_FINALLY(igraph_vector_destroy, newvector); IGRAPH_CHECK(igraph_vector_ptr_push_back(ptrvector, newvector)); IGRAPH_FINALLY_CLEAN(2); return 1; /* continue finding subisomorphisms */ } /** * \function igraph_get_isomorphisms_vf2 * Collect the isomorphic mappings * * This function finds all the isomorphic mappings between two * graphs. It uses the \ref igraph_isomorphic_function_vf2() * function. Call the function with the same graph as \p graph1 and \p * graph2 to get automorphisms. * \param graph1 The first input graph, may be directed or undirected. * \param graph2 The second input graph, it must have the same * directedness as \p graph1, or an error will be reported. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param maps Pointer vector. On return it is empty if the input graphs * are no isomorphic. Otherwise it contains pointers to * igraph_vector_t objects, each vector is an * isomorphic mapping of \p graph2 to \p graph1. Please note that * you need to 1) Destroy the vectors via \ref * igraph_vector_destroy(), 2) free them via * free() and then 3) call \ref * igraph_vector_ptr_destroy() on the pointer vector to deallocate all * memory when \p maps is no longer needed. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn * and \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_get_isomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_ptr_t *maps, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, maps, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; igraph_vector_ptr_clear(maps); IGRAPH_FINALLY(igraph_i_get_isomorphisms_free, maps); IGRAPH_CHECK(igraph_isomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, 0, 0, (igraph_isohandler_t*) igraph_i_get_isomorphisms_vf2, ncb, ecb, &data)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_subisomorphic * Decide subgraph isomorphism * * Check whether \p graph2 is isomorphic to a subgraph of \p graph1. * Currently this function just calls \ref igraph_subisomorphic_vf2() * for all graphs. * \param graph1 The first input graph, may be directed or * undirected. This is supposed to be the bigger graph. * \param graph2 The second input graph, it must have the same * directedness as \p graph2, or an error is triggered. This is * supposed to be the smaller graph. * \param iso Pointer to a boolean, the result is stored here. * \return Error code. * * Time complexity: exponential. */ int igraph_subisomorphic(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso) { return igraph_subisomorphic_vf2(graph1, graph2, 0, 0, 0, 0, iso, 0, 0, 0, 0, 0); } /** * \function igraph_subisomorphic_function_vf2 * Generic VF2 function for subgraph isomorphism problems * * This function is the pair of \ref igraph_isomorphic_function_vf2(), * for subgraph isomorphism problems. It searches for subgraphs of \p * graph1 which are isomorphic to \p graph2. When it founds an * isomorphic mapping it calls the supplied callback \p isohandler_fn. * The mapping (and its inverse) and the additional \p arg argument * are supplied to the callback. * \param graph1 The first input graph, may be directed or * undirected. This is supposed to be the larger graph. * \param graph2 The second input graph, it must have the same * directedness as \p graph1. This is supposed to be the smaller * graph. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the subgraph isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param map12 Pointer to a vector or \c NULL. If not \c NULL, then an * isomorphic mapping from \p graph1 to \p graph2 is stored here. * \param map21 Pointer to a vector ot \c NULL. If not \c NULL, then * an isomorphic mapping from \p graph2 to \p graph1 is stored * here. * \param isohandler_fn A pointer to a function of type \ref * igraph_isohandler_t. This will be called whenever a subgraph * isomorphism is found. If the function returns with a non-zero value * then the search is continued, otherwise it stops and the function * returns. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p isohandler_fn, \p * node_compat_fn and \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_subisomorphic_function_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isohandler_t *isohandler_fn, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { long int no_of_nodes1=igraph_vcount(graph1), no_of_nodes2=igraph_vcount(graph2); long int no_of_edges1=igraph_ecount(graph1), no_of_edges2=igraph_ecount(graph2); igraph_vector_t mycore_1, mycore_2, *core_1=&mycore_1, *core_2=&mycore_2; igraph_vector_t in_1, in_2, out_1, out_2; long int in_1_size=0, in_2_size=0, out_1_size=0, out_2_size=0; igraph_vector_t *inneis_1, *inneis_2, *outneis_1, *outneis_2; long int matched_nodes=0; long int depth; long int cand1, cand2; long int last1, last2; igraph_stack_t path; igraph_lazy_adjlist_t inadj1, inadj2, outadj1, outadj2; igraph_vector_t indeg1, indeg2, outdeg1, outdeg2; if (igraph_is_directed(graph1) != igraph_is_directed(graph2)) { IGRAPH_ERROR("Cannot compare directed and undirected graphs", IGRAPH_EINVAL); } if (no_of_nodes1 < no_of_nodes2 || no_of_edges1 < no_of_edges2) { return 0; } if ( (vertex_color1 && !vertex_color2) || (!vertex_color1 && vertex_color2) ) { IGRAPH_WARNING("Only one graph is vertex colored, colors will be ignored"); vertex_color1=vertex_color2=0; } if ( (edge_color1 && !edge_color2) || (!edge_color1 && edge_color2) ) { IGRAPH_WARNING("Only one graph is edge colored, colors will be ignored"); edge_color1=edge_color2=0; } if (vertex_color1) { if (igraph_vector_int_size(vertex_color1) != no_of_nodes1 || igraph_vector_int_size(vertex_color2) != no_of_nodes2) { IGRAPH_ERROR("Invalid vertex color vector length", IGRAPH_EINVAL); } } if (edge_color1) { if (igraph_vector_int_size(edge_color1) != no_of_edges1 || igraph_vector_int_size(edge_color2) != no_of_edges2) { IGRAPH_ERROR("Invalid edge color vector length", IGRAPH_EINVAL); } } /* Check color distribution */ if (vertex_color1) { /* TODO */ } /* Check edge color distribution */ if (edge_color1) { /* TODO */ } if (map12) { core_1=map12; IGRAPH_CHECK(igraph_vector_resize(core_1, no_of_nodes1)); } else { IGRAPH_VECTOR_INIT_FINALLY(core_1, no_of_nodes1); } igraph_vector_fill(core_1, -1); if (map21) { core_2=map21; IGRAPH_CHECK(igraph_vector_resize(core_2, no_of_nodes2)); } else { IGRAPH_VECTOR_INIT_FINALLY(core_2, no_of_nodes2); } igraph_vector_fill(core_2, -1); IGRAPH_VECTOR_INIT_FINALLY(&in_1, no_of_nodes1); IGRAPH_VECTOR_INIT_FINALLY(&in_2, no_of_nodes2); IGRAPH_VECTOR_INIT_FINALLY(&out_1, no_of_nodes1); IGRAPH_VECTOR_INIT_FINALLY(&out_2, no_of_nodes2); IGRAPH_CHECK(igraph_stack_init(&path, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &path); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph1, &inadj1, IGRAPH_IN, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &inadj1); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph1, &outadj1, IGRAPH_OUT, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &outadj1); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph2, &inadj2, IGRAPH_IN, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &inadj2); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph2, &outadj2, IGRAPH_OUT, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &outadj2); IGRAPH_VECTOR_INIT_FINALLY(&indeg1, 0); IGRAPH_VECTOR_INIT_FINALLY(&indeg2, 0); IGRAPH_VECTOR_INIT_FINALLY(&outdeg1, 0); IGRAPH_VECTOR_INIT_FINALLY(&outdeg2, 0); IGRAPH_CHECK(igraph_stack_reserve(&path, no_of_nodes2*2)); IGRAPH_CHECK(igraph_degree(graph1, &indeg1, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph2, &indeg2, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph1, &outdeg1, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_degree(graph2, &outdeg2, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS)); depth=0; last1=-1; last2=-1; while (depth >= 0) { long int i; IGRAPH_ALLOW_INTERRUPTION(); cand1=-1; cand2=-1; /* Search for the next pair to try */ if ((in_1_size < in_2_size) || (out_1_size < out_2_size)) { /* step back, nothing to do */ } else if (out_1_size > 0 && out_2_size > 0) { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i0 && VECTOR(*core_2)[i] < 0) { cand2=i; } i++; } } /* search for cand1 now, it should be bigger than last1 */ i=last1+1; while (cand1<0 && i0 && VECTOR(*core_1)[i] < 0) { cand1=i; } i++; } } else if (in_1_size > 0 && in_2_size > 0) { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i0 && VECTOR(*core_2)[i] < 0) { cand2=i; } i++; } } /* search for cand1 now, should be bigger than last1 */ i=last1+1; while (cand1<0 && i0 && VECTOR(*core_1)[i] < 0) { cand1=i; } i++; } } else { /**************************************************************/ /* cand2, search not always needed */ if (last2 >= 0) { cand2=last2; } else { i=0; while (cand2<0 && i= 1) { last2=(long int) igraph_stack_pop(&path); last1=(long int) igraph_stack_pop(&path); matched_nodes -= 1; VECTOR(*core_1)[last1]=-1; VECTOR(*core_2)[last2]=-1; if (VECTOR(in_1)[last1] != 0) { in_1_size += 1; } if (VECTOR(out_1)[last1] != 0) { out_1_size += 1; } if (VECTOR(in_2)[last2] != 0) { in_2_size += 1; } if (VECTOR(out_2)[last2] != 0) { out_2_size += 1; } inneis_1=igraph_lazy_adjlist_get(&inadj1, (igraph_integer_t) last1); for (i=0; i= 0) { long int node2=(long int) VECTOR(*core_2)[node]; /* check if there is a node2->cand1 edge */ if (!igraph_vector_binsearch2(inneis_1, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) node2, (igraph_integer_t) cand1, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) node, (igraph_integer_t) cand2, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_2)[node] != 0) { xin2++; } if (VECTOR(out_2)[node] != 0) { xout2++; } } } for (i=0; !end && i= 0) { long int node2=(long int) VECTOR(*core_2)[node]; /* check if there is a cand1->node2 edge */ if (!igraph_vector_binsearch2(outneis_1, node2)) { end=1; } else if (edge_color1 || edge_compat_fn) { igraph_integer_t eid1, eid2; igraph_get_eid(graph1, &eid1, (igraph_integer_t) cand1, (igraph_integer_t) node2, /*directed=*/ 1, /*error=*/ 1); igraph_get_eid(graph2, &eid2, (igraph_integer_t) cand2, (igraph_integer_t) node, /*directed=*/ 1, /*error=*/ 1); if (edge_color1 && VECTOR(*edge_color1)[(long int)eid1] != VECTOR(*edge_color2)[(long int)eid2]) { end=1; } if (edge_compat_fn && !edge_compat_fn(graph1, graph2, eid1, eid2, arg)) { end=1; } } } else { if (VECTOR(in_2)[node] != 0) { xin2++; } if (VECTOR(out_2)[node] != 0) { xout2++; } } } if (!end && (xin1>=xin2 && xout1>=xout2)) { /* Ok, we add the (cand1, cand2) pair to the mapping */ depth += 1; IGRAPH_CHECK(igraph_stack_push(&path, cand1)); IGRAPH_CHECK(igraph_stack_push(&path, cand2)); matched_nodes += 1; VECTOR(*core_1)[cand1]=cand2; VECTOR(*core_2)[cand2]=cand1; /* update in_*, out_* */ if (VECTOR(in_1)[cand1] != 0) { in_1_size -= 1; } if (VECTOR(out_1)[cand1] != 0) { out_1_size -= 1; } if (VECTOR(in_2)[cand2] != 0) { in_2_size -= 1; } if (VECTOR(out_2)[cand2] != 0) { out_2_size -= 1; } inneis_1=igraph_lazy_adjlist_get(&inadj1, (igraph_integer_t) cand1); for (i=0; iarg; IGRAPH_UNUSED(map12); IGRAPH_UNUSED(map21); *iso=1; return 0; /* stop */ } /** * \function igraph_subisomorphic_vf2 * Decide subgraph isomorphism using VF2 * * Decides whether a subgraph of \p graph1 is isomorphic to \p * graph2. It uses \ref igraph_subisomorphic_function_vf2(). * \param graph1 The first input graph, may be directed or * undirected. This is supposed to be the larger graph. * \param graph2 The second input graph, it must have the same * directedness as \p graph1. This is supposed to be the smaller * graph. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the subgraph isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param iso Pointer to a boolean. The result of the decision problem * is stored here. * \param map12 Pointer to a vector or \c NULL. If not \c NULL, then an * isomorphic mapping from \p graph1 to \p graph2 is stored here. * \param map21 Pointer to a vector ot \c NULL. If not \c NULL, then * an isomorphic mapping from \p graph2 to \p graph1 is stored * here. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn * and \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_subisomorphic_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, iso, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; *iso=0; IGRAPH_CHECK(igraph_subisomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, map12, map21, (igraph_isohandler_t *) igraph_i_subisomorphic_vf2, ncb, ecb, &data)); if (! *iso) { if (map12) { igraph_vector_clear(map12); } if (map21) { igraph_vector_clear(map21); } } return 0; } igraph_bool_t igraph_i_count_subisomorphisms_vf2(const igraph_vector_t *map12, const igraph_vector_t *map21, void *arg) { igraph_i_iso_cb_data_t *data = arg; igraph_integer_t *count = data->arg; IGRAPH_UNUSED(map12); IGRAPH_UNUSED(map21); *count += 1; return 1; /* always continue */ } /** * \function igraph_count_subisomorphisms_vf2 * Number of subgraph isomorphisms using VF2 * * Count the number of isomorphisms between subgraphs of \p graph1 and * \p graph2. This function uses \ref * igraph_subisomorphic_function_vf2(). * \param graph1 The first input graph, may be directed or * undirected. This is supposed to be the larger graph. * \param graph2 The second input graph, it must have the same * directedness as \p graph1. This is supposed to be the smaller * graph. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the subgraph isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param count Pointer to an integer. The number of subgraph * isomorphisms is stored here. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn and * \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_count_subisomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_integer_t *count, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, count, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; *count=0; IGRAPH_CHECK(igraph_subisomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, 0, 0, (igraph_isohandler_t*) igraph_i_count_subisomorphisms_vf2, ncb, ecb, &data)); return 0; } void igraph_i_get_subisomorphisms_free(igraph_vector_ptr_t *data) { long int i, n=igraph_vector_ptr_size(data); for (i=0; iarg; igraph_vector_t *newvector=igraph_Calloc(1, igraph_vector_t); IGRAPH_UNUSED(map12); if (!newvector) { igraph_error("Out of memory", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; /* stop right here */ } IGRAPH_FINALLY(igraph_free, newvector); IGRAPH_CHECK(igraph_vector_copy(newvector, map21)); IGRAPH_FINALLY(igraph_vector_destroy, newvector); IGRAPH_CHECK(igraph_vector_ptr_push_back(vector, newvector)); IGRAPH_FINALLY_CLEAN(2); return 1; /* continue finding subisomorphisms */ } /** * \function igraph_get_subisomorphisms_vf2 * Return all subgraph isomorphic mappings * * This function collects all isomorphic mappings of \p graph2 to a * subgraph of \p graph1. It uses the \ref * igraph_subisomorphic_function_vf2() function. * \param graph1 The first input graph, may be directed or * undirected. This is supposed to be the larger graph. * \param graph2 The second input graph, it must have the same * directedness as \p graph1. This is supposed to be the smaller * graph. * \param vertex_color1 An optional color vector for the first graph. If * color vectors are given for both graphs, then the subgraph isomorphism is * calculated on the colored graphs; i.e. two vertices can match * only if their color also matches. Supply a null pointer here if * your graphs are not colored. * \param vertex_color2 An optional color vector for the second graph. See * the previous argument for explanation. * \param edge_color1 An optional edge color vector for the first * graph. The matching edges in the two graphs must have matching * colors as well. Supply a null pointer here if your graphs are not * edge-colored. * \param edge_color2 The edge color vector for the second graph. * \param maps Pointer vector. On return it contains pointers to * igraph_vector_t objects, each vector is an * isomorphic mapping of \p graph2 to a subgraph of \p graph1. Please note that * you need to 1) Destroy the vectors via \ref * igraph_vector_destroy(), 2) free them via * free() and then 3) call \ref * igraph_vector_ptr_destroy() on the pointer vector to deallocate all * memory when \p maps is no longer needed. * \param node_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two nodes are compatible. * \param edge_compat_fn A pointer to a function of type \ref * igraph_isocompat_t. This function will be called by the algorithm to * determine whether two edges are compatible. * \param arg Extra argument to supply to functions \p node_compat_fn * and \p edge_compat_fn. * \return Error code. * * Time complexity: exponential. */ int igraph_get_subisomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_ptr_t *maps, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg) { igraph_i_iso_cb_data_t data = { node_compat_fn, edge_compat_fn, maps, arg }; igraph_isocompat_t *ncb = node_compat_fn ? igraph_i_isocompat_node_cb : 0; igraph_isocompat_t *ecb = edge_compat_fn ? igraph_i_isocompat_edge_cb : 0; igraph_vector_ptr_clear(maps); IGRAPH_FINALLY(igraph_i_get_subisomorphisms_free, maps); IGRAPH_CHECK(igraph_subisomorphic_function_vf2(graph1, graph2, vertex_color1, vertex_color2, edge_color1, edge_color2, 0, 0, (igraph_isohandler_t*) igraph_i_get_subisomorphisms_vf2, ncb, ecb, &data)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_permute_vertices * Permute the vertices * * This function creates a new graph from the input graph by permuting * its vertices according to the specified mapping. Call this function * with the output of \ref igraph_canonical_permutation() to create * the canonical form of a graph. * \param graph The input graph. * \param res Pointer to an uninitialized graph object. The new graph * is created here. * \param permutation The permutation to apply. Vertex 0 is mapped to * the first element of the vector, vertex 1 to the second, * etc. Note that it is not checked that the vector contains every * element only once, and no range checking is performed either. * \return Error code. * * Time complexity: O(|V|+|E|), linear in terms of the number of * vertices and edges. */ int igraph_permute_vertices(const igraph_t *graph, igraph_t *res, const igraph_vector_t *permutation) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vector_t edges; long int i, p=0; if (igraph_vector_size(permutation) != no_of_nodes) { IGRAPH_ERROR("Permute vertices: invalid permutation vector size", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); for (i=0; iattr) { igraph_vector_t index; igraph_vector_t vtypes; IGRAPH_I_ATTRIBUTE_DESTROY(res); IGRAPH_I_ATTRIBUTE_COPY(res, graph, /*graph=*/1, /*vertex=*/0, /*edge=*/1); IGRAPH_VECTOR_INIT_FINALLY(&vtypes, 0); IGRAPH_CHECK(igraph_i_attribute_get_info(graph, 0, 0, 0, &vtypes, 0, 0)); if (igraph_vector_size(&vtypes) != 0) { IGRAPH_VECTOR_INIT_FINALLY(&index, no_of_nodes); for (i=0; i * BLISS is a successor of the famous NAUTY algorithm and * implementation. While using the same ideas in general, with better * heuristics and data structure BLISS outperforms NAUTY on most * graphs. * * * * BLISS was developed and implemented by Tommi Junttila and Petteri Kaski at * Helsinki University of Technology, Finland. See Tommi Juntilla's * homepage at http://www.tcs.hut.fi/~tjunttil/ and the publication at * http://www.siam.org/proceedings/alenex/2007/alx07_013junttilat.pdf * for more information. * * * * BLISS version 0.73 is included in igraph. * */ /** * \function igraph_isomorphic_bliss * Graph isomorphism via BLISS * * This function uses the BLISS graph isomorphism algorithm, a * successor of the famous NAUTY algorithm and implementation. BLISS * is open source and licensed according to the GNU GPL. See * http://www.tcs.hut.fi/Software/bliss/index.html for * details. Currently the 0.73 version of BLISS is included in igraph. * * * * \param graph1 The first input graph. Multiple edges between the same nodes * are not supported and will cause an incorrect result to be returned. * \param graph2 The second input graph. Multiple edges between the same nodes * are not supported and will cause an incorrect result to be returned. * \param colors1 An optional vertex color vector for the first graph. Supply a * null pointer if your graph is not colored. * \param colors2 An optional vertex color vector for the second graph. Supply a * null pointer if your graph is not colored. * \param iso Pointer to a boolean, the result is stored here. * \param map12 A vector or \c NULL pointer. If not \c NULL then an * isomorphic mapping from \p graph1 to \p graph2 is stored here. * If the input graphs are not isomorphic then this vector is * cleared, i.e. it will have length zero. * \param map21 Similar to \p map12, but for the mapping from \p * graph2 to \p graph1. * \param sh Splitting heuristics to be used for the graphs. See * \ref igraph_bliss_sh_t. * \param info1 If not \c NULL, information about the canonization of * the first input graph is stored here. See \ref igraph_bliss_info_t * for details. Note that if the two graphs have different number * of vertices or edges, then this is not filled. * \param info2 Same as \p info1, but for the second graph. * \return Error code. * * Time complexity: exponential, but in practice it is quite fast. */ int igraph_isomorphic_bliss(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *colors1, const igraph_vector_int_t *colors2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_bliss_sh_t sh, igraph_bliss_info_t *info1, igraph_bliss_info_t *info2) { long int no_of_nodes=igraph_vcount(graph1); long int no_of_edges=igraph_ecount(graph1); igraph_vector_t perm1, perm2; igraph_vector_t vmap12, *mymap12=&vmap12; igraph_vector_t from, to, index; igraph_vector_t from2, to2, index2; igraph_bool_t directed; long int i, j; *iso=0; if (info1) { info1->nof_nodes = info1->nof_leaf_nodes = info1->nof_bad_nodes = info1->nof_canupdates = info1->max_level = info1->nof_generators = -1; info1->group_size = 0; } if (info2) { info2->nof_nodes = info2->nof_leaf_nodes = info2->nof_bad_nodes = info2->nof_canupdates = info2->max_level = info2->nof_generators = -1; info2->group_size = 0; } directed = igraph_is_directed(graph1); if (igraph_is_directed(graph2) != directed) { IGRAPH_ERROR("Cannot compare directed and undirected graphs", IGRAPH_EINVAL); } if ((colors1 == NULL || colors2 == NULL) && colors1 != colors2) { IGRAPH_WARNING("Only one of the graphs is vertex colored, colors will be ignored"); colors1 = NULL; colors2 = NULL; } if (no_of_nodes != igraph_vcount(graph2) || no_of_edges != igraph_ecount(graph2)) { if (map12) { igraph_vector_clear(map12); } if (map21) { igraph_vector_clear(map21); } return 0; } if (map12) { mymap12=map12; } else { IGRAPH_VECTOR_INIT_FINALLY(mymap12, 0); } IGRAPH_VECTOR_INIT_FINALLY(&perm1, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&perm2, no_of_nodes); IGRAPH_CHECK(igraph_canonical_permutation(graph1, colors1, &perm1, sh, info1)); IGRAPH_CHECK(igraph_canonical_permutation(graph2, colors2, &perm2, sh, info2)); IGRAPH_CHECK(igraph_vector_resize(mymap12, no_of_nodes)); /* The inverse of perm2 is produced in mymap12 */ for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_interface.h" #include "igraph_structural.h" #include "config.h" /** * \ingroup structural * \function igraph_are_connected * \brief Decides whether two vertices are connected * * \param graph The graph object. * \param v1 The first vertex. * \param v2 The second vertex. * \param res Boolean, \c TRUE if there is an edge from * \p v1 to \p v2, \c FALSE otherwise. * \return The error code \c IGRAPH_EINVVID is returned if an invalid * vertex ID is given. * * The function is of course symmetric for undirected graphs. * * * Time complexity: O( min(log(d1), log(d2)) ), * d1 is the (out-)degree of \p v1 and d2 is the (in-)degree of \p v2. */ int igraph_are_connected(const igraph_t *graph, igraph_integer_t v1, igraph_integer_t v2, igraph_bool_t *res) { long int nov=igraph_vcount(graph); igraph_integer_t eid=-1; if (v1 < 0 || v2 < 0 || v1 > nov-1 || v2 > nov-1) { IGRAPH_ERROR("are connected", IGRAPH_EINVVID); } igraph_get_eid(graph, &eid, v1, v2, /*directed=*/1, /*error=*/ 0); *res = (eid >=0); return IGRAPH_SUCCESS; } igraph/src/foreign-ncol-parser.h0000644000175100001440000000503313431000472016351 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ALNUM = 258, NEWLINE = 259, ERROR = 260 }; #endif /* Tokens. */ #define ALNUM 258 #define NEWLINE 259 #define ERROR 260 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 82 "src/foreign-ncol-parser.y" { long int edgenum; double weightnum; } /* Line 1529 of yacc.c. */ #line 64 "y.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif igraph/src/NetRoutines.h0000644000175100001440000000465013431000472014760 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt The original copyright notice follows here */ /*************************************************************************** NetRoutines.h - description ------------------- begin : Tue Oct 28 2003 copyright : (C) 2003 by Joerg Reichardt email : reichardt@mitte ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef NETROUTINES_H #define NETROUTINES_H #include "NetDataTypes.h" #include "igraph_types.h" #include "igraph_datatype.h" int igraph_i_read_network(const igraph_t *graph, const igraph_vector_t *weights, network *net, igraph_bool_t use_weights, unsigned int states); void reduce_cliques(DLList*>*, FILE *file); void reduce_cliques2(network*, bool, long ); void clear_all_markers(network *net); #endif igraph/src/atlas.c0000644000175100001440000000526213431000472013600 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph R package. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_constructors.h" #include "atlas-edges.h" #include "config.h" /** * \function igraph_atlas * \brief Create a small graph from the \quote Graph Atlas \endquote. * * * The number of the graph is given as a parameter. * The graphs are listed: \olist * \oli in increasing order of number of nodes; * \oli for a fixed number of nodes, in increasing order of the * number of edges; * \oli for fixed numbers of nodes and edges, in increasing * order of the degree sequence, for example 111223 < 112222; * \oli for fixed degree sequence, in increasing number of * automorphisms. * \endolist * * * The data was converted from the NetworkX software package, * see http://networkx.github.io . * * * See \emb An Atlas of Graphs \eme by Ronald C. Read and Robin J. Wilson, * Oxford University Press, 1998. * * \param graph Pointer to an uninitialized graph object. * \param number The number of the graph to generate. * * Added in version 0.2. * * Time complexity: O(|V|+|E|), the number of vertices plus the number of * edges. * * \example examples/simple/igraph_atlas.c */ int igraph_atlas(igraph_t *graph, int number) { igraph_integer_t pos, n, e; igraph_vector_t v=IGRAPH_VECTOR_NULL; if (number < 0 || number >= (int) (sizeof(igraph_i_atlas_edges_pos)/sizeof(long int))) { IGRAPH_ERROR("No such graph in atlas", IGRAPH_EINVAL); } pos=(igraph_integer_t) igraph_i_atlas_edges_pos[number]; n=(igraph_integer_t) igraph_i_atlas_edges[pos]; e=(igraph_integer_t) igraph_i_atlas_edges[pos+1]; IGRAPH_CHECK(igraph_create(graph, igraph_vector_view(&v,igraph_i_atlas_edges+pos+2, e*2), n, IGRAPH_UNDIRECTED)); return 0; } igraph/src/init.c0000644000175100001440000020371413431000472013441 0ustar hornikusers#include #include #include // for NULL #include /* The following symbols/expresssions for .NAME have been omitted call Most likely possible values need to be added below. */ /* FIXME: Check these declarations against the C/Fortran source code. */ /* .C calls */ extern void igraphhcass2(void *, void *, void *, void *, void *, void *); /* .Call calls */ extern SEXP make_lazy(SEXP, SEXP, SEXP); extern SEXP make_lazy_dots(SEXP, SEXP); extern SEXP promise_env_(SEXP); extern SEXP promise_expr_(SEXP); extern SEXP R_igraph_add_edges(SEXP, SEXP); extern SEXP R_igraph_add_env(SEXP); extern SEXP R_igraph_add_version_to_env(SEXP); extern SEXP R_igraph_add_vertices(SEXP, SEXP); extern SEXP R_igraph_address(SEXP); extern SEXP R_igraph_adhesion(SEXP, SEXP); extern SEXP R_igraph_adjacency_spectral_embedding(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_adjacent_triangles(SEXP, SEXP); extern SEXP R_igraph_adjacent_vertices(SEXP, SEXP, SEXP); extern SEXP R_igraph_adjlist(SEXP, SEXP, SEXP); extern SEXP R_igraph_all_minimal_st_separators(SEXP); extern SEXP R_igraph_all_st_cuts(SEXP, SEXP, SEXP); extern SEXP R_igraph_all_st_mincuts(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_are_connected(SEXP, SEXP, SEXP); extern SEXP R_igraph_arpack(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_arpack_unpack_complex(SEXP, SEXP, SEXP); extern SEXP R_igraph_articulation_points(SEXP); extern SEXP R_igraph_assortativity(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_assortativity_degree(SEXP, SEXP); extern SEXP R_igraph_assortativity_nominal(SEXP, SEXP, SEXP); extern SEXP R_igraph_asymmetric_preference_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_atlas(SEXP); extern SEXP R_igraph_authority_score(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_automorphisms(SEXP, SEXP); extern SEXP R_igraph_average_path_length(SEXP, SEXP, SEXP); extern SEXP R_igraph_avg_nearest_neighbor_degree(SEXP, SEXP, SEXP); extern SEXP R_igraph_barabasi_aging_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_barabasi_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_betweenness(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_betweenness_estimate(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_bfs(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_bibcoupling(SEXP, SEXP); extern SEXP R_igraph_biconnected_components(SEXP); extern SEXP R_igraph_bipartite_game_gnm(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_bipartite_game_gnp(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_bipartite_projection(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_bipartite_projection_size(SEXP, SEXP); extern SEXP R_igraph_callaway_traits_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_canonical_permutation(SEXP, SEXP); extern SEXP R_igraph_centralization(SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_betweenness(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_betweenness_tmax(SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_closeness(SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_closeness_tmax(SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_degree(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_degree_tmax(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_eigenvector_centrality(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_centralization_eigenvector_centrality_tmax(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_cited_type_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_citing_cited_type_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_clique_number(SEXP); extern SEXP R_igraph_cliques(SEXP, SEXP, SEXP); extern SEXP R_igraph_closeness(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_closeness_estimate(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_clusters(SEXP, SEXP); extern SEXP R_igraph_cocitation(SEXP, SEXP); extern SEXP R_igraph_cohesion(SEXP, SEXP); extern SEXP R_igraph_cohesive_blocks(SEXP); extern SEXP R_igraph_community_edge_betweenness(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_community_fastgreedy(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_community_infomap(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_community_label_propagation(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_community_leading_eigenvector(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_community_multilevel(SEXP, SEXP); extern SEXP R_igraph_community_optimal_modularity(SEXP, SEXP); extern SEXP R_igraph_community_to_membership2(SEXP, SEXP, SEXP); extern SEXP R_igraph_compare_communities(SEXP, SEXP, SEXP); extern SEXP R_igraph_complementer(SEXP, SEXP); extern SEXP R_igraph_compose(SEXP, SEXP, SEXP); extern SEXP R_igraph_connect_neighborhood(SEXP, SEXP, SEXP); extern SEXP R_igraph_constraint(SEXP, SEXP, SEXP); extern SEXP R_igraph_contract_vertices(SEXP, SEXP, SEXP); extern SEXP R_igraph_convex_hull(SEXP); extern SEXP R_igraph_coreness(SEXP, SEXP); extern SEXP R_igraph_correlated_game(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_correlated_pair_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_count_isomorphisms_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_count_multiple(SEXP, SEXP); extern SEXP R_igraph_count_subisomorphisms_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_create(SEXP, SEXP, SEXP); extern SEXP R_igraph_create_bipartite(SEXP, SEXP, SEXP); extern SEXP R_igraph_de_bruijn(SEXP, SEXP); extern SEXP R_igraph_decompose(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_degree(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_degree_sequence_game(SEXP, SEXP, SEXP); extern SEXP R_igraph_delete_edges(SEXP, SEXP); extern SEXP R_igraph_delete_vertices(SEXP, SEXP); extern SEXP R_igraph_density(SEXP, SEXP); extern SEXP R_igraph_dfs(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_diameter(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_difference(SEXP, SEXP); extern SEXP R_igraph_dim_select(SEXP); extern SEXP R_igraph_disjoint_union(SEXP); extern SEXP R_igraph_diversity(SEXP, SEXP, SEXP); extern SEXP R_igraph_dominator_tree(SEXP, SEXP, SEXP); extern SEXP R_igraph_dot_product_game(SEXP, SEXP); extern SEXP R_igraph_dyad_census(SEXP); extern SEXP R_igraph_eccentricity(SEXP, SEXP, SEXP); extern SEXP R_igraph_ecount(SEXP); extern SEXP R_igraph_edge_betweenness(SEXP, SEXP, SEXP); extern SEXP R_igraph_edge_betweenness_estimate(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_edge_connectivity(SEXP, SEXP); extern SEXP R_igraph_edge_disjoint_paths(SEXP, SEXP, SEXP); extern SEXP R_igraph_edges(SEXP, SEXP); extern SEXP R_igraph_eigen_adjacency(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_eigenvector_centrality(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_empty(SEXP, SEXP); extern SEXP R_igraph_erdos_renyi_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_es_adj(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_es_pairs(SEXP, SEXP, SEXP); extern SEXP R_igraph_es_path(SEXP, SEXP, SEXP); extern SEXP R_igraph_establishment_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_extended_chordal_ring(SEXP, SEXP); extern SEXP R_igraph_famous(SEXP); extern SEXP R_igraph_farthest_points(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_finalizer(); extern SEXP R_igraph_forest_fire_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_full(SEXP, SEXP, SEXP); extern SEXP R_igraph_full_bipartite(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_full_citation(SEXP, SEXP); extern SEXP R_igraph_get_adjacency(SEXP, SEXP, SEXP); extern SEXP R_igraph_get_adjedgelist(SEXP, SEXP); extern SEXP R_igraph_get_adjlist(SEXP, SEXP); extern SEXP R_igraph_get_all_shortest_paths(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_all_shortest_paths_dijkstra(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_all_simple_paths(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_all_simple_paths_pp(SEXP); extern SEXP R_igraph_get_attr_mode(SEXP, SEXP); extern SEXP R_igraph_get_diameter(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_edge(SEXP, SEXP); extern SEXP R_igraph_get_edgelist(SEXP, SEXP); extern SEXP R_igraph_get_eids(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_graph_id(SEXP); extern SEXP R_igraph_get_incidence(SEXP, SEXP); extern SEXP R_igraph_get_isomorphisms_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_shortest_paths(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_get_stochastic(SEXP, SEXP); extern SEXP R_igraph_get_stochastic_sparsemat(SEXP, SEXP); extern SEXP R_igraph_get_subisomorphisms_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_getsphere(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_girth(SEXP, SEXP); extern SEXP R_igraph_graph_adjacency(SEXP, SEXP); extern SEXP R_igraph_graph_version(SEXP); extern SEXP R_igraph_graphlets(SEXP, SEXP, SEXP); extern SEXP R_igraph_graphlets_candidate_basis(SEXP, SEXP); extern SEXP R_igraph_graphlets_project(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_grg_game(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_growing_random_game(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_has_multiple(SEXP); extern SEXP R_igraph_hrg_consensus(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_hrg_create(SEXP, SEXP); extern SEXP R_igraph_hrg_dendrogram(SEXP); extern SEXP R_igraph_hrg_fit(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_hrg_game(SEXP); extern SEXP R_igraph_hrg_predict(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_hsbm_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_hsbm_list_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_hub_score(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_i_levc_arp(SEXP, SEXP, SEXP); extern SEXP R_igraph_identical_graphs(SEXP, SEXP); extern SEXP R_igraph_incidence(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_incident(SEXP, SEXP, SEXP); extern SEXP R_igraph_incident_edges(SEXP, SEXP, SEXP); extern SEXP R_igraph_independence_number(SEXP); extern SEXP R_igraph_independent_vertex_sets(SEXP, SEXP, SEXP); extern SEXP R_igraph_induced_subgraph(SEXP, SEXP, SEXP); extern SEXP R_igraph_intersection(SEXP, SEXP); extern SEXP R_igraph_is_bipartite(SEXP); extern SEXP R_igraph_is_chordal(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_is_connected(SEXP, SEXP); extern SEXP R_igraph_is_dag(SEXP); extern SEXP R_igraph_is_degree_sequence(SEXP, SEXP); extern SEXP R_igraph_is_directed(SEXP); extern SEXP R_igraph_is_graphical_degree_sequence(SEXP, SEXP); extern SEXP R_igraph_is_loop(SEXP, SEXP); extern SEXP R_igraph_is_matching(SEXP, SEXP, SEXP); extern SEXP R_igraph_is_maximal_matching(SEXP, SEXP, SEXP); extern SEXP R_igraph_is_minimal_separator(SEXP, SEXP); extern SEXP R_igraph_is_multiple(SEXP, SEXP); extern SEXP R_igraph_is_mutual(SEXP, SEXP); extern SEXP R_igraph_is_separator(SEXP, SEXP); extern SEXP R_igraph_is_simple(SEXP); extern SEXP R_igraph_isoclass(SEXP); extern SEXP R_igraph_isoclass_create(SEXP, SEXP, SEXP); extern SEXP R_igraph_isoclass_subgraph(SEXP, SEXP); extern SEXP R_igraph_isomorphic(SEXP, SEXP); extern SEXP R_igraph_isomorphic_34(SEXP, SEXP); extern SEXP R_igraph_isomorphic_bliss(SEXP, SEXP, SEXP); extern SEXP R_igraph_isomorphic_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_k_regular_game(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_kautz(SEXP, SEXP); extern SEXP R_igraph_laplacian(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_laplacian_spectral_embedding(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_largest_cliques(SEXP); extern SEXP R_igraph_largest_independent_vertex_sets(SEXP); extern SEXP R_igraph_lastcit_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_lattice(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_bipartite(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_circle(SEXP, SEXP); extern SEXP R_igraph_layout_davidson_harel(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_drl(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_drl_3d(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_fruchterman_reingold(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_fruchterman_reingold_3d(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_gem(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_graphopt(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_grid(SEXP, SEXP); extern SEXP R_igraph_layout_grid_3d(SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_kamada_kawai(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_kamada_kawai_3d(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_lgl(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_mds(SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_merge_dla(SEXP, SEXP); extern SEXP R_igraph_layout_random(SEXP); extern SEXP R_igraph_layout_random_3d(SEXP); extern SEXP R_igraph_layout_reingold_tilford(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_sphere(SEXP); extern SEXP R_igraph_layout_star(SEXP, SEXP, SEXP); extern SEXP R_igraph_layout_sugiyama(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_lcf_vector(SEXP, SEXP, SEXP); extern SEXP R_igraph_line_graph(SEXP); extern SEXP R_igraph_list_triangles(SEXP); extern SEXP R_igraph_local_scan_0(SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_0_them(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_1_ecount(SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_1_ecount_them(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_k_ecount(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_k_ecount_them(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_local_scan_neighborhood_ecount(SEXP, SEXP, SEXP); extern SEXP R_igraph_make_weak_ref(SEXP, SEXP, SEXP); extern SEXP R_igraph_maxflow(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_maximal_cliques(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_maximal_cliques_count(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_maximal_cliques_file(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_maximal_independent_vertex_sets(SEXP); extern SEXP R_igraph_maximum_bipartite_matching(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_maximum_cardinality_search(SEXP); extern SEXP R_igraph_mincut(SEXP, SEXP); extern SEXP R_igraph_mincut_value(SEXP, SEXP); extern SEXP R_igraph_minimum_size_separators(SEXP); extern SEXP R_igraph_minimum_spanning_tree_prim(SEXP, SEXP); extern SEXP R_igraph_minimum_spanning_tree_unweighted(SEXP); extern SEXP R_igraph_modularity(SEXP, SEXP, SEXP); extern SEXP R_igraph_modularity_matrix(SEXP, SEXP, SEXP); extern SEXP R_igraph_motifs_randesu(SEXP, SEXP, SEXP); extern SEXP R_igraph_motifs_randesu_estimate(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_motifs_randesu_no(SEXP, SEXP, SEXP); extern SEXP R_igraph_mybracket(SEXP, SEXP); extern SEXP R_igraph_mybracket2(SEXP, SEXP, SEXP); extern SEXP R_igraph_mybracket2_copy(SEXP, SEXP, SEXP); extern SEXP R_igraph_mybracket2_names(SEXP, SEXP, SEXP); extern SEXP R_igraph_mybracket2_set(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_mybracket3_set(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_neighborhood(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_neighborhood_graphs(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_neighborhood_size(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_neighbors(SEXP, SEXP, SEXP); extern SEXP R_igraph_no_clusters(SEXP, SEXP); extern SEXP R_igraph_pagerank_old(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_path_length_hist(SEXP, SEXP); extern SEXP R_igraph_permute_vertices(SEXP, SEXP); extern SEXP R_igraph_personalized_pagerank(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_power_law_fit(SEXP, SEXP, SEXP); extern SEXP R_igraph_preference_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_psumtree_draw(SEXP, SEXP, SEXP); extern SEXP R_igraph_radius(SEXP, SEXP); extern SEXP R_igraph_random_sample(SEXP, SEXP, SEXP); extern SEXP R_igraph_random_walk(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_read_graph_dimacs(SEXP, SEXP); extern SEXP R_igraph_read_graph_dl(SEXP, SEXP); extern SEXP R_igraph_read_graph_edgelist(SEXP, SEXP, SEXP); extern SEXP R_igraph_read_graph_gml(SEXP); extern SEXP R_igraph_read_graph_graphdb(SEXP, SEXP); extern SEXP R_igraph_read_graph_graphml(SEXP, SEXP); extern SEXP R_igraph_read_graph_lgl(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_read_graph_ncol(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_read_graph_pajek(SEXP); extern SEXP R_igraph_recent_degree_aging_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_reciprocity(SEXP, SEXP, SEXP); extern SEXP R_igraph_rewire(SEXP, SEXP, SEXP); extern SEXP R_igraph_rewire_edges(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_ring(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_running_mean(SEXP, SEXP); extern SEXP R_igraph_sample_dirichlet(SEXP, SEXP); extern SEXP R_igraph_sample_sphere_surface(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_sample_sphere_volume(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_sbm_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_adjacency(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_grouping(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_laplacian(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_norm_eps(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_semiprojectors(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_scg_stochastic(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_set_verbose(SEXP); extern SEXP R_igraph_shortest_paths(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_similarity_dice(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_similarity_inverse_log_weighted(SEXP, SEXP, SEXP); extern SEXP R_igraph_similarity_jaccard(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_simple_interconnected_islands_game(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_simplify(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_sir(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_solve_lsap(SEXP, SEXP); extern SEXP R_igraph_spinglass_community(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_spinglass_my_community(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_split_join_distance(SEXP, SEXP); extern SEXP R_igraph_st_edge_connectivity(SEXP, SEXP, SEXP); extern SEXP R_igraph_st_mincut_value(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_st_vertex_connectivity(SEXP, SEXP, SEXP); extern SEXP R_igraph_star(SEXP, SEXP, SEXP); extern SEXP R_igraph_static_fitness_game(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_static_power_law_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_strength(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_subcomponent(SEXP, SEXP, SEXP); extern SEXP R_igraph_subgraph(SEXP, SEXP); extern SEXP R_igraph_subgraph_edges(SEXP, SEXP, SEXP); extern SEXP R_igraph_subisomorphic_lad(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_subisomorphic_vf2(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_to_directed(SEXP, SEXP); extern SEXP R_igraph_to_undirected(SEXP, SEXP, SEXP); extern SEXP R_igraph_topological_sorting(SEXP, SEXP); extern SEXP R_igraph_transitivity_avglocal_undirected(SEXP, SEXP); extern SEXP R_igraph_transitivity_barrat(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_transitivity_local_undirected(SEXP, SEXP, SEXP); extern SEXP R_igraph_transitivity_local_undirected_all(SEXP, SEXP); extern SEXP R_igraph_transitivity_undirected(SEXP, SEXP); extern SEXP R_igraph_tree(SEXP, SEXP, SEXP); extern SEXP R_igraph_triad_census(SEXP); extern SEXP R_igraph_unfold_tree(SEXP, SEXP, SEXP); extern SEXP R_igraph_union(SEXP, SEXP); extern SEXP R_igraph_vcount(SEXP); extern SEXP R_igraph_version(); extern SEXP R_igraph_vertex_connectivity(SEXP, SEXP); extern SEXP R_igraph_vertex_disjoint_paths(SEXP, SEXP, SEXP); extern SEXP R_igraph_vs_adj(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_vs_nei(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_walktrap_community(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_watts_strogatz_game(SEXP, SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_weak_ref_key(SEXP); extern SEXP R_igraph_weak_ref_run_finalizer(SEXP); extern SEXP R_igraph_weak_ref_value(SEXP); extern SEXP R_igraph_weighted_adjacency(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_dimacs(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_dot(SEXP, SEXP); extern SEXP R_igraph_write_graph_edgelist(SEXP, SEXP); extern SEXP R_igraph_write_graph_gml(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_graphml(SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_leda(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_lgl(SEXP, SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_ncol(SEXP, SEXP, SEXP, SEXP); extern SEXP R_igraph_write_graph_pajek(SEXP, SEXP); extern SEXP UUID_gen(SEXP); static const R_CMethodDef CEntries[] = { {"igraphhcass2", (DL_FUNC) &igraphhcass2, 6}, {NULL, NULL, 0} }; static const R_CallMethodDef CallEntries[] = { {"make_lazy", (DL_FUNC) &make_lazy, 3}, {"make_lazy_dots", (DL_FUNC) &make_lazy_dots, 2}, {"promise_env_", (DL_FUNC) &promise_env_, 1}, {"promise_expr_", (DL_FUNC) &promise_expr_, 1}, {"R_igraph_add_edges", (DL_FUNC) &R_igraph_add_edges, 2}, {"R_igraph_add_env", (DL_FUNC) &R_igraph_add_env, 1}, {"R_igraph_add_version_to_env", (DL_FUNC) &R_igraph_add_version_to_env, 1}, {"R_igraph_add_vertices", (DL_FUNC) &R_igraph_add_vertices, 2}, {"R_igraph_address", (DL_FUNC) &R_igraph_address, 1}, {"R_igraph_adhesion", (DL_FUNC) &R_igraph_adhesion, 2}, {"R_igraph_adjacency_spectral_embedding", (DL_FUNC) &R_igraph_adjacency_spectral_embedding, 7}, {"R_igraph_adjacent_triangles", (DL_FUNC) &R_igraph_adjacent_triangles, 2}, {"R_igraph_adjacent_vertices", (DL_FUNC) &R_igraph_adjacent_vertices, 3}, {"R_igraph_adjlist", (DL_FUNC) &R_igraph_adjlist, 3}, {"R_igraph_all_minimal_st_separators", (DL_FUNC) &R_igraph_all_minimal_st_separators, 1}, {"R_igraph_all_st_cuts", (DL_FUNC) &R_igraph_all_st_cuts, 3}, {"R_igraph_all_st_mincuts", (DL_FUNC) &R_igraph_all_st_mincuts, 4}, {"R_igraph_are_connected", (DL_FUNC) &R_igraph_are_connected, 3}, {"R_igraph_arpack", (DL_FUNC) &R_igraph_arpack, 5}, {"R_igraph_arpack_unpack_complex", (DL_FUNC) &R_igraph_arpack_unpack_complex, 3}, {"R_igraph_articulation_points", (DL_FUNC) &R_igraph_articulation_points, 1}, {"R_igraph_assortativity", (DL_FUNC) &R_igraph_assortativity, 4}, {"R_igraph_assortativity_degree", (DL_FUNC) &R_igraph_assortativity_degree, 2}, {"R_igraph_assortativity_nominal", (DL_FUNC) &R_igraph_assortativity_nominal, 3}, {"R_igraph_asymmetric_preference_game", (DL_FUNC) &R_igraph_asymmetric_preference_game, 5}, {"R_igraph_atlas", (DL_FUNC) &R_igraph_atlas, 1}, {"R_igraph_authority_score", (DL_FUNC) &R_igraph_authority_score, 4}, {"R_igraph_automorphisms", (DL_FUNC) &R_igraph_automorphisms, 2}, {"R_igraph_average_path_length", (DL_FUNC) &R_igraph_average_path_length, 3}, {"R_igraph_avg_nearest_neighbor_degree", (DL_FUNC) &R_igraph_avg_nearest_neighbor_degree, 3}, {"R_igraph_barabasi_aging_game", (DL_FUNC) &R_igraph_barabasi_aging_game, 12}, {"R_igraph_barabasi_game", (DL_FUNC) &R_igraph_barabasi_game, 9}, {"R_igraph_betweenness", (DL_FUNC) &R_igraph_betweenness, 5}, {"R_igraph_betweenness_estimate", (DL_FUNC) &R_igraph_betweenness_estimate, 6}, {"R_igraph_bfs", (DL_FUNC) &R_igraph_bfs, 15}, {"R_igraph_bibcoupling", (DL_FUNC) &R_igraph_bibcoupling, 2}, {"R_igraph_biconnected_components", (DL_FUNC) &R_igraph_biconnected_components, 1}, {"R_igraph_bipartite_game_gnm", (DL_FUNC) &R_igraph_bipartite_game_gnm, 5}, {"R_igraph_bipartite_game_gnp", (DL_FUNC) &R_igraph_bipartite_game_gnp, 5}, {"R_igraph_bipartite_projection", (DL_FUNC) &R_igraph_bipartite_projection, 4}, {"R_igraph_bipartite_projection_size", (DL_FUNC) &R_igraph_bipartite_projection_size, 2}, {"R_igraph_callaway_traits_game", (DL_FUNC) &R_igraph_callaway_traits_game, 6}, {"R_igraph_canonical_permutation", (DL_FUNC) &R_igraph_canonical_permutation, 2}, {"R_igraph_centralization", (DL_FUNC) &R_igraph_centralization, 3}, {"R_igraph_centralization_betweenness", (DL_FUNC) &R_igraph_centralization_betweenness, 4}, {"R_igraph_centralization_betweenness_tmax", (DL_FUNC) &R_igraph_centralization_betweenness_tmax, 3}, {"R_igraph_centralization_closeness", (DL_FUNC) &R_igraph_centralization_closeness, 3}, {"R_igraph_centralization_closeness_tmax", (DL_FUNC) &R_igraph_centralization_closeness_tmax, 3}, {"R_igraph_centralization_degree", (DL_FUNC) &R_igraph_centralization_degree, 4}, {"R_igraph_centralization_degree_tmax", (DL_FUNC) &R_igraph_centralization_degree_tmax, 4}, {"R_igraph_centralization_eigenvector_centrality", (DL_FUNC) &R_igraph_centralization_eigenvector_centrality, 5}, {"R_igraph_centralization_eigenvector_centrality_tmax", (DL_FUNC) &R_igraph_centralization_eigenvector_centrality_tmax, 4}, {"R_igraph_cited_type_game", (DL_FUNC) &R_igraph_cited_type_game, 5}, {"R_igraph_citing_cited_type_game", (DL_FUNC) &R_igraph_citing_cited_type_game, 5}, {"R_igraph_clique_number", (DL_FUNC) &R_igraph_clique_number, 1}, {"R_igraph_cliques", (DL_FUNC) &R_igraph_cliques, 3}, {"R_igraph_closeness", (DL_FUNC) &R_igraph_closeness, 5}, {"R_igraph_closeness_estimate", (DL_FUNC) &R_igraph_closeness_estimate, 6}, {"R_igraph_clusters", (DL_FUNC) &R_igraph_clusters, 2}, {"R_igraph_cocitation", (DL_FUNC) &R_igraph_cocitation, 2}, {"R_igraph_cohesion", (DL_FUNC) &R_igraph_cohesion, 2}, {"R_igraph_cohesive_blocks", (DL_FUNC) &R_igraph_cohesive_blocks, 1}, {"R_igraph_community_edge_betweenness", (DL_FUNC) &R_igraph_community_edge_betweenness, 8}, {"R_igraph_community_fastgreedy", (DL_FUNC) &R_igraph_community_fastgreedy, 5}, {"R_igraph_community_infomap", (DL_FUNC) &R_igraph_community_infomap, 4}, {"R_igraph_community_label_propagation", (DL_FUNC) &R_igraph_community_label_propagation, 4}, {"R_igraph_community_leading_eigenvector", (DL_FUNC) &R_igraph_community_leading_eigenvector, 9}, {"R_igraph_community_multilevel", (DL_FUNC) &R_igraph_community_multilevel, 2}, {"R_igraph_community_optimal_modularity", (DL_FUNC) &R_igraph_community_optimal_modularity, 2}, {"R_igraph_community_to_membership2", (DL_FUNC) &R_igraph_community_to_membership2, 3}, {"R_igraph_compare_communities", (DL_FUNC) &R_igraph_compare_communities, 3}, {"R_igraph_complementer", (DL_FUNC) &R_igraph_complementer, 2}, {"R_igraph_compose", (DL_FUNC) &R_igraph_compose, 3}, {"R_igraph_connect_neighborhood", (DL_FUNC) &R_igraph_connect_neighborhood, 3}, {"R_igraph_constraint", (DL_FUNC) &R_igraph_constraint, 3}, {"R_igraph_contract_vertices", (DL_FUNC) &R_igraph_contract_vertices, 3}, {"R_igraph_convex_hull", (DL_FUNC) &R_igraph_convex_hull, 1}, {"R_igraph_coreness", (DL_FUNC) &R_igraph_coreness, 2}, {"R_igraph_correlated_game", (DL_FUNC) &R_igraph_correlated_game, 4}, {"R_igraph_correlated_pair_game", (DL_FUNC) &R_igraph_correlated_pair_game, 5}, {"R_igraph_count_isomorphisms_vf2", (DL_FUNC) &R_igraph_count_isomorphisms_vf2, 6}, {"R_igraph_count_multiple", (DL_FUNC) &R_igraph_count_multiple, 2}, {"R_igraph_count_subisomorphisms_vf2", (DL_FUNC) &R_igraph_count_subisomorphisms_vf2, 6}, {"R_igraph_create", (DL_FUNC) &R_igraph_create, 3}, {"R_igraph_create_bipartite", (DL_FUNC) &R_igraph_create_bipartite, 3}, {"R_igraph_de_bruijn", (DL_FUNC) &R_igraph_de_bruijn, 2}, {"R_igraph_decompose", (DL_FUNC) &R_igraph_decompose, 4}, {"R_igraph_degree", (DL_FUNC) &R_igraph_degree, 4}, {"R_igraph_degree_sequence_game", (DL_FUNC) &R_igraph_degree_sequence_game, 3}, {"R_igraph_delete_edges", (DL_FUNC) &R_igraph_delete_edges, 2}, {"R_igraph_delete_vertices", (DL_FUNC) &R_igraph_delete_vertices, 2}, {"R_igraph_density", (DL_FUNC) &R_igraph_density, 2}, {"R_igraph_dfs", (DL_FUNC) &R_igraph_dfs, 12}, {"R_igraph_diameter", (DL_FUNC) &R_igraph_diameter, 4}, {"R_igraph_difference", (DL_FUNC) &R_igraph_difference, 2}, {"R_igraph_dim_select", (DL_FUNC) &R_igraph_dim_select, 1}, {"R_igraph_disjoint_union", (DL_FUNC) &R_igraph_disjoint_union, 1}, {"R_igraph_diversity", (DL_FUNC) &R_igraph_diversity, 3}, {"R_igraph_dominator_tree", (DL_FUNC) &R_igraph_dominator_tree, 3}, {"R_igraph_dot_product_game", (DL_FUNC) &R_igraph_dot_product_game, 2}, {"R_igraph_dyad_census", (DL_FUNC) &R_igraph_dyad_census, 1}, {"R_igraph_eccentricity", (DL_FUNC) &R_igraph_eccentricity, 3}, {"R_igraph_ecount", (DL_FUNC) &R_igraph_ecount, 1}, {"R_igraph_edge_betweenness", (DL_FUNC) &R_igraph_edge_betweenness, 3}, {"R_igraph_edge_betweenness_estimate", (DL_FUNC) &R_igraph_edge_betweenness_estimate, 4}, {"R_igraph_edge_connectivity", (DL_FUNC) &R_igraph_edge_connectivity, 2}, {"R_igraph_edge_disjoint_paths", (DL_FUNC) &R_igraph_edge_disjoint_paths, 3}, {"R_igraph_edges", (DL_FUNC) &R_igraph_edges, 2}, {"R_igraph_eigen_adjacency", (DL_FUNC) &R_igraph_eigen_adjacency, 4}, {"R_igraph_eigenvector_centrality", (DL_FUNC) &R_igraph_eigenvector_centrality, 5}, {"R_igraph_empty", (DL_FUNC) &R_igraph_empty, 2}, {"R_igraph_erdos_renyi_game", (DL_FUNC) &R_igraph_erdos_renyi_game, 5}, {"R_igraph_es_adj", (DL_FUNC) &R_igraph_es_adj, 4}, {"R_igraph_es_pairs", (DL_FUNC) &R_igraph_es_pairs, 3}, {"R_igraph_es_path", (DL_FUNC) &R_igraph_es_path, 3}, {"R_igraph_establishment_game", (DL_FUNC) &R_igraph_establishment_game, 6}, {"R_igraph_extended_chordal_ring", (DL_FUNC) &R_igraph_extended_chordal_ring, 2}, {"R_igraph_famous", (DL_FUNC) &R_igraph_famous, 1}, {"R_igraph_farthest_points", (DL_FUNC) &R_igraph_farthest_points, 4}, {"R_igraph_finalizer", (DL_FUNC) &R_igraph_finalizer, 0}, {"R_igraph_forest_fire_game", (DL_FUNC) &R_igraph_forest_fire_game, 5}, {"R_igraph_full", (DL_FUNC) &R_igraph_full, 3}, {"R_igraph_full_bipartite", (DL_FUNC) &R_igraph_full_bipartite, 4}, {"R_igraph_full_citation", (DL_FUNC) &R_igraph_full_citation, 2}, {"R_igraph_get_adjacency", (DL_FUNC) &R_igraph_get_adjacency, 3}, {"R_igraph_get_adjedgelist", (DL_FUNC) &R_igraph_get_adjedgelist, 2}, {"R_igraph_get_adjlist", (DL_FUNC) &R_igraph_get_adjlist, 2}, {"R_igraph_get_all_shortest_paths", (DL_FUNC) &R_igraph_get_all_shortest_paths, 4}, {"R_igraph_get_all_shortest_paths_dijkstra", (DL_FUNC) &R_igraph_get_all_shortest_paths_dijkstra, 5}, {"R_igraph_get_all_simple_paths", (DL_FUNC) &R_igraph_get_all_simple_paths, 4}, {"R_igraph_get_all_simple_paths_pp", (DL_FUNC) &R_igraph_get_all_simple_paths_pp, 1}, {"R_igraph_get_attr_mode", (DL_FUNC) &R_igraph_get_attr_mode, 2}, {"R_igraph_get_diameter", (DL_FUNC) &R_igraph_get_diameter, 4}, {"R_igraph_get_edge", (DL_FUNC) &R_igraph_get_edge, 2}, {"R_igraph_get_edgelist", (DL_FUNC) &R_igraph_get_edgelist, 2}, {"R_igraph_get_eids", (DL_FUNC) &R_igraph_get_eids, 5}, {"R_igraph_get_graph_id", (DL_FUNC) &R_igraph_get_graph_id, 1}, {"R_igraph_get_incidence", (DL_FUNC) &R_igraph_get_incidence, 2}, {"R_igraph_get_isomorphisms_vf2", (DL_FUNC) &R_igraph_get_isomorphisms_vf2, 6}, {"R_igraph_get_shortest_paths", (DL_FUNC) &R_igraph_get_shortest_paths, 9}, {"R_igraph_get_stochastic", (DL_FUNC) &R_igraph_get_stochastic, 2}, {"R_igraph_get_stochastic_sparsemat", (DL_FUNC) &R_igraph_get_stochastic_sparsemat, 2}, {"R_igraph_get_subisomorphisms_vf2", (DL_FUNC) &R_igraph_get_subisomorphisms_vf2, 6}, {"R_igraph_getsphere", (DL_FUNC) &R_igraph_getsphere, 8}, {"R_igraph_girth", (DL_FUNC) &R_igraph_girth, 2}, {"R_igraph_graph_adjacency", (DL_FUNC) &R_igraph_graph_adjacency, 2}, {"R_igraph_graph_version", (DL_FUNC) &R_igraph_graph_version, 1}, {"R_igraph_graphlets", (DL_FUNC) &R_igraph_graphlets, 3}, {"R_igraph_graphlets_candidate_basis", (DL_FUNC) &R_igraph_graphlets_candidate_basis, 2}, {"R_igraph_graphlets_project", (DL_FUNC) &R_igraph_graphlets_project, 5}, {"R_igraph_grg_game", (DL_FUNC) &R_igraph_grg_game, 4}, {"R_igraph_growing_random_game", (DL_FUNC) &R_igraph_growing_random_game, 4}, {"R_igraph_has_multiple", (DL_FUNC) &R_igraph_has_multiple, 1}, {"R_igraph_hrg_consensus", (DL_FUNC) &R_igraph_hrg_consensus, 4}, {"R_igraph_hrg_create", (DL_FUNC) &R_igraph_hrg_create, 2}, {"R_igraph_hrg_dendrogram", (DL_FUNC) &R_igraph_hrg_dendrogram, 1}, {"R_igraph_hrg_fit", (DL_FUNC) &R_igraph_hrg_fit, 4}, {"R_igraph_hrg_game", (DL_FUNC) &R_igraph_hrg_game, 1}, {"R_igraph_hrg_predict", (DL_FUNC) &R_igraph_hrg_predict, 5}, {"R_igraph_hsbm_game", (DL_FUNC) &R_igraph_hsbm_game, 5}, {"R_igraph_hsbm_list_game", (DL_FUNC) &R_igraph_hsbm_list_game, 5}, {"R_igraph_hub_score", (DL_FUNC) &R_igraph_hub_score, 4}, {"R_igraph_i_levc_arp", (DL_FUNC) &R_igraph_i_levc_arp, 3}, {"R_igraph_identical_graphs", (DL_FUNC) &R_igraph_identical_graphs, 2}, {"R_igraph_incidence", (DL_FUNC) &R_igraph_incidence, 4}, {"R_igraph_incident", (DL_FUNC) &R_igraph_incident, 3}, {"R_igraph_incident_edges", (DL_FUNC) &R_igraph_incident_edges, 3}, {"R_igraph_independence_number", (DL_FUNC) &R_igraph_independence_number, 1}, {"R_igraph_independent_vertex_sets", (DL_FUNC) &R_igraph_independent_vertex_sets, 3}, {"R_igraph_induced_subgraph", (DL_FUNC) &R_igraph_induced_subgraph, 3}, {"R_igraph_intersection", (DL_FUNC) &R_igraph_intersection, 2}, {"R_igraph_is_bipartite", (DL_FUNC) &R_igraph_is_bipartite, 1}, {"R_igraph_is_chordal", (DL_FUNC) &R_igraph_is_chordal, 5}, {"R_igraph_is_connected", (DL_FUNC) &R_igraph_is_connected, 2}, {"R_igraph_is_dag", (DL_FUNC) &R_igraph_is_dag, 1}, {"R_igraph_is_degree_sequence", (DL_FUNC) &R_igraph_is_degree_sequence, 2}, {"R_igraph_is_directed", (DL_FUNC) &R_igraph_is_directed, 1}, {"R_igraph_is_graphical_degree_sequence", (DL_FUNC) &R_igraph_is_graphical_degree_sequence, 2}, {"R_igraph_is_loop", (DL_FUNC) &R_igraph_is_loop, 2}, {"R_igraph_is_matching", (DL_FUNC) &R_igraph_is_matching, 3}, {"R_igraph_is_maximal_matching", (DL_FUNC) &R_igraph_is_maximal_matching, 3}, {"R_igraph_is_minimal_separator", (DL_FUNC) &R_igraph_is_minimal_separator, 2}, {"R_igraph_is_multiple", (DL_FUNC) &R_igraph_is_multiple, 2}, {"R_igraph_is_mutual", (DL_FUNC) &R_igraph_is_mutual, 2}, {"R_igraph_is_separator", (DL_FUNC) &R_igraph_is_separator, 2}, {"R_igraph_is_simple", (DL_FUNC) &R_igraph_is_simple, 1}, {"R_igraph_isoclass", (DL_FUNC) &R_igraph_isoclass, 1}, {"R_igraph_isoclass_create", (DL_FUNC) &R_igraph_isoclass_create, 3}, {"R_igraph_isoclass_subgraph", (DL_FUNC) &R_igraph_isoclass_subgraph, 2}, {"R_igraph_isomorphic", (DL_FUNC) &R_igraph_isomorphic, 2}, {"R_igraph_isomorphic_34", (DL_FUNC) &R_igraph_isomorphic_34, 2}, {"R_igraph_isomorphic_bliss", (DL_FUNC) &R_igraph_isomorphic_bliss, 3}, {"R_igraph_isomorphic_vf2", (DL_FUNC) &R_igraph_isomorphic_vf2, 6}, {"R_igraph_k_regular_game", (DL_FUNC) &R_igraph_k_regular_game, 4}, {"R_igraph_kautz", (DL_FUNC) &R_igraph_kautz, 2}, {"R_igraph_laplacian", (DL_FUNC) &R_igraph_laplacian, 4}, {"R_igraph_laplacian_spectral_embedding", (DL_FUNC) &R_igraph_laplacian_spectral_embedding, 8}, {"R_igraph_largest_cliques", (DL_FUNC) &R_igraph_largest_cliques, 1}, {"R_igraph_largest_independent_vertex_sets", (DL_FUNC) &R_igraph_largest_independent_vertex_sets, 1}, {"R_igraph_lastcit_game", (DL_FUNC) &R_igraph_lastcit_game, 5}, {"R_igraph_lattice", (DL_FUNC) &R_igraph_lattice, 5}, {"R_igraph_layout_bipartite", (DL_FUNC) &R_igraph_layout_bipartite, 5}, {"R_igraph_layout_circle", (DL_FUNC) &R_igraph_layout_circle, 2}, {"R_igraph_layout_davidson_harel", (DL_FUNC) &R_igraph_layout_davidson_harel, 11}, {"R_igraph_layout_drl", (DL_FUNC) &R_igraph_layout_drl, 6}, {"R_igraph_layout_drl_3d", (DL_FUNC) &R_igraph_layout_drl_3d, 6}, {"R_igraph_layout_fruchterman_reingold", (DL_FUNC) &R_igraph_layout_fruchterman_reingold, 10}, {"R_igraph_layout_fruchterman_reingold_3d", (DL_FUNC) &R_igraph_layout_fruchterman_reingold_3d, 11}, {"R_igraph_layout_gem", (DL_FUNC) &R_igraph_layout_gem, 7}, {"R_igraph_layout_graphopt", (DL_FUNC) &R_igraph_layout_graphopt, 8}, {"R_igraph_layout_grid", (DL_FUNC) &R_igraph_layout_grid, 2}, {"R_igraph_layout_grid_3d", (DL_FUNC) &R_igraph_layout_grid_3d, 3}, {"R_igraph_layout_kamada_kawai", (DL_FUNC) &R_igraph_layout_kamada_kawai, 10}, {"R_igraph_layout_kamada_kawai_3d", (DL_FUNC) &R_igraph_layout_kamada_kawai_3d, 12}, {"R_igraph_layout_lgl", (DL_FUNC) &R_igraph_layout_lgl, 8}, {"R_igraph_layout_mds", (DL_FUNC) &R_igraph_layout_mds, 3}, {"R_igraph_layout_merge_dla", (DL_FUNC) &R_igraph_layout_merge_dla, 2}, {"R_igraph_layout_random", (DL_FUNC) &R_igraph_layout_random, 1}, {"R_igraph_layout_random_3d", (DL_FUNC) &R_igraph_layout_random_3d, 1}, {"R_igraph_layout_reingold_tilford", (DL_FUNC) &R_igraph_layout_reingold_tilford, 5}, {"R_igraph_layout_sphere", (DL_FUNC) &R_igraph_layout_sphere, 1}, {"R_igraph_layout_star", (DL_FUNC) &R_igraph_layout_star, 3}, {"R_igraph_layout_sugiyama", (DL_FUNC) &R_igraph_layout_sugiyama, 6}, {"R_igraph_lcf_vector", (DL_FUNC) &R_igraph_lcf_vector, 3}, {"R_igraph_line_graph", (DL_FUNC) &R_igraph_line_graph, 1}, {"R_igraph_list_triangles", (DL_FUNC) &R_igraph_list_triangles, 1}, {"R_igraph_local_scan_0", (DL_FUNC) &R_igraph_local_scan_0, 3}, {"R_igraph_local_scan_0_them", (DL_FUNC) &R_igraph_local_scan_0_them, 4}, {"R_igraph_local_scan_1_ecount", (DL_FUNC) &R_igraph_local_scan_1_ecount, 3}, {"R_igraph_local_scan_1_ecount_them", (DL_FUNC) &R_igraph_local_scan_1_ecount_them, 4}, {"R_igraph_local_scan_k_ecount", (DL_FUNC) &R_igraph_local_scan_k_ecount, 4}, {"R_igraph_local_scan_k_ecount_them", (DL_FUNC) &R_igraph_local_scan_k_ecount_them, 5}, {"R_igraph_local_scan_neighborhood_ecount", (DL_FUNC) &R_igraph_local_scan_neighborhood_ecount, 3}, {"R_igraph_make_weak_ref", (DL_FUNC) &R_igraph_make_weak_ref, 3}, {"R_igraph_maxflow", (DL_FUNC) &R_igraph_maxflow, 4}, {"R_igraph_maximal_cliques", (DL_FUNC) &R_igraph_maximal_cliques, 4}, {"R_igraph_maximal_cliques_count", (DL_FUNC) &R_igraph_maximal_cliques_count, 4}, {"R_igraph_maximal_cliques_file", (DL_FUNC) &R_igraph_maximal_cliques_file, 5}, {"R_igraph_maximal_independent_vertex_sets", (DL_FUNC) &R_igraph_maximal_independent_vertex_sets, 1}, {"R_igraph_maximum_bipartite_matching", (DL_FUNC) &R_igraph_maximum_bipartite_matching, 4}, {"R_igraph_maximum_cardinality_search", (DL_FUNC) &R_igraph_maximum_cardinality_search, 1}, {"R_igraph_mincut", (DL_FUNC) &R_igraph_mincut, 2}, {"R_igraph_mincut_value", (DL_FUNC) &R_igraph_mincut_value, 2}, {"R_igraph_minimum_size_separators", (DL_FUNC) &R_igraph_minimum_size_separators, 1}, {"R_igraph_minimum_spanning_tree_prim", (DL_FUNC) &R_igraph_minimum_spanning_tree_prim, 2}, {"R_igraph_minimum_spanning_tree_unweighted", (DL_FUNC) &R_igraph_minimum_spanning_tree_unweighted, 1}, {"R_igraph_modularity", (DL_FUNC) &R_igraph_modularity, 3}, {"R_igraph_modularity_matrix", (DL_FUNC) &R_igraph_modularity_matrix, 3}, {"R_igraph_motifs_randesu", (DL_FUNC) &R_igraph_motifs_randesu, 3}, {"R_igraph_motifs_randesu_estimate", (DL_FUNC) &R_igraph_motifs_randesu_estimate, 5}, {"R_igraph_motifs_randesu_no", (DL_FUNC) &R_igraph_motifs_randesu_no, 3}, {"R_igraph_mybracket", (DL_FUNC) &R_igraph_mybracket, 2}, {"R_igraph_mybracket2", (DL_FUNC) &R_igraph_mybracket2, 3}, {"R_igraph_mybracket2_copy", (DL_FUNC) &R_igraph_mybracket2_copy, 3}, {"R_igraph_mybracket2_names", (DL_FUNC) &R_igraph_mybracket2_names, 3}, {"R_igraph_mybracket2_set", (DL_FUNC) &R_igraph_mybracket2_set, 4}, {"R_igraph_mybracket3_set", (DL_FUNC) &R_igraph_mybracket3_set, 5}, {"R_igraph_neighborhood", (DL_FUNC) &R_igraph_neighborhood, 5}, {"R_igraph_neighborhood_graphs", (DL_FUNC) &R_igraph_neighborhood_graphs, 5}, {"R_igraph_neighborhood_size", (DL_FUNC) &R_igraph_neighborhood_size, 5}, {"R_igraph_neighbors", (DL_FUNC) &R_igraph_neighbors, 3}, {"R_igraph_no_clusters", (DL_FUNC) &R_igraph_no_clusters, 2}, {"R_igraph_pagerank_old", (DL_FUNC) &R_igraph_pagerank_old, 7}, {"R_igraph_path_length_hist", (DL_FUNC) &R_igraph_path_length_hist, 2}, {"R_igraph_permute_vertices", (DL_FUNC) &R_igraph_permute_vertices, 2}, {"R_igraph_personalized_pagerank", (DL_FUNC) &R_igraph_personalized_pagerank, 8}, {"R_igraph_power_law_fit", (DL_FUNC) &R_igraph_power_law_fit, 3}, {"R_igraph_preference_game", (DL_FUNC) &R_igraph_preference_game, 7}, {"R_igraph_psumtree_draw", (DL_FUNC) &R_igraph_psumtree_draw, 3}, {"R_igraph_radius", (DL_FUNC) &R_igraph_radius, 2}, {"R_igraph_random_sample", (DL_FUNC) &R_igraph_random_sample, 3}, {"R_igraph_random_walk", (DL_FUNC) &R_igraph_random_walk, 5}, {"R_igraph_read_graph_dimacs", (DL_FUNC) &R_igraph_read_graph_dimacs, 2}, {"R_igraph_read_graph_dl", (DL_FUNC) &R_igraph_read_graph_dl, 2}, {"R_igraph_read_graph_edgelist", (DL_FUNC) &R_igraph_read_graph_edgelist, 3}, {"R_igraph_read_graph_gml", (DL_FUNC) &R_igraph_read_graph_gml, 1}, {"R_igraph_read_graph_graphdb", (DL_FUNC) &R_igraph_read_graph_graphdb, 2}, {"R_igraph_read_graph_graphml", (DL_FUNC) &R_igraph_read_graph_graphml, 2}, {"R_igraph_read_graph_lgl", (DL_FUNC) &R_igraph_read_graph_lgl, 4}, {"R_igraph_read_graph_ncol", (DL_FUNC) &R_igraph_read_graph_ncol, 5}, {"R_igraph_read_graph_pajek", (DL_FUNC) &R_igraph_read_graph_pajek, 1}, {"R_igraph_recent_degree_aging_game", (DL_FUNC) &R_igraph_recent_degree_aging_game, 10}, {"R_igraph_reciprocity", (DL_FUNC) &R_igraph_reciprocity, 3}, {"R_igraph_rewire", (DL_FUNC) &R_igraph_rewire, 3}, {"R_igraph_rewire_edges", (DL_FUNC) &R_igraph_rewire_edges, 4}, {"R_igraph_ring", (DL_FUNC) &R_igraph_ring, 4}, {"R_igraph_running_mean", (DL_FUNC) &R_igraph_running_mean, 2}, {"R_igraph_sample_dirichlet", (DL_FUNC) &R_igraph_sample_dirichlet, 2}, {"R_igraph_sample_sphere_surface", (DL_FUNC) &R_igraph_sample_sphere_surface, 4}, {"R_igraph_sample_sphere_volume", (DL_FUNC) &R_igraph_sample_sphere_volume, 4}, {"R_igraph_sbm_game", (DL_FUNC) &R_igraph_sbm_game, 5}, {"R_igraph_scg_adjacency", (DL_FUNC) &R_igraph_scg_adjacency, 14}, {"R_igraph_scg_grouping", (DL_FUNC) &R_igraph_scg_grouping, 7}, {"R_igraph_scg_laplacian", (DL_FUNC) &R_igraph_scg_laplacian, 16}, {"R_igraph_scg_norm_eps", (DL_FUNC) &R_igraph_scg_norm_eps, 5}, {"R_igraph_scg_semiprojectors", (DL_FUNC) &R_igraph_scg_semiprojectors, 5}, {"R_igraph_scg_stochastic", (DL_FUNC) &R_igraph_scg_stochastic, 17}, {"R_igraph_set_verbose", (DL_FUNC) &R_igraph_set_verbose, 1}, {"R_igraph_shortest_paths", (DL_FUNC) &R_igraph_shortest_paths, 6}, {"R_igraph_similarity_dice", (DL_FUNC) &R_igraph_similarity_dice, 4}, {"R_igraph_similarity_inverse_log_weighted", (DL_FUNC) &R_igraph_similarity_inverse_log_weighted, 3}, {"R_igraph_similarity_jaccard", (DL_FUNC) &R_igraph_similarity_jaccard, 4}, {"R_igraph_simple_interconnected_islands_game", (DL_FUNC) &R_igraph_simple_interconnected_islands_game, 4}, {"R_igraph_simplify", (DL_FUNC) &R_igraph_simplify, 4}, {"R_igraph_sir", (DL_FUNC) &R_igraph_sir, 4}, {"R_igraph_solve_lsap", (DL_FUNC) &R_igraph_solve_lsap, 2}, {"R_igraph_spinglass_community", (DL_FUNC) &R_igraph_spinglass_community, 11}, {"R_igraph_spinglass_my_community", (DL_FUNC) &R_igraph_spinglass_my_community, 6}, {"R_igraph_split_join_distance", (DL_FUNC) &R_igraph_split_join_distance, 2}, {"R_igraph_st_edge_connectivity", (DL_FUNC) &R_igraph_st_edge_connectivity, 3}, {"R_igraph_st_mincut_value", (DL_FUNC) &R_igraph_st_mincut_value, 4}, {"R_igraph_st_vertex_connectivity", (DL_FUNC) &R_igraph_st_vertex_connectivity, 3}, {"R_igraph_star", (DL_FUNC) &R_igraph_star, 3}, {"R_igraph_static_fitness_game", (DL_FUNC) &R_igraph_static_fitness_game, 5}, {"R_igraph_static_power_law_game", (DL_FUNC) &R_igraph_static_power_law_game, 7}, {"R_igraph_strength", (DL_FUNC) &R_igraph_strength, 5}, {"R_igraph_subcomponent", (DL_FUNC) &R_igraph_subcomponent, 3}, {"R_igraph_subgraph", (DL_FUNC) &R_igraph_subgraph, 2}, {"R_igraph_subgraph_edges", (DL_FUNC) &R_igraph_subgraph_edges, 3}, {"R_igraph_subisomorphic_lad", (DL_FUNC) &R_igraph_subisomorphic_lad, 7}, {"R_igraph_subisomorphic_vf2", (DL_FUNC) &R_igraph_subisomorphic_vf2, 6}, {"R_igraph_to_directed", (DL_FUNC) &R_igraph_to_directed, 2}, {"R_igraph_to_undirected", (DL_FUNC) &R_igraph_to_undirected, 3}, {"R_igraph_topological_sorting", (DL_FUNC) &R_igraph_topological_sorting, 2}, {"R_igraph_transitivity_avglocal_undirected", (DL_FUNC) &R_igraph_transitivity_avglocal_undirected, 2}, {"R_igraph_transitivity_barrat", (DL_FUNC) &R_igraph_transitivity_barrat, 4}, {"R_igraph_transitivity_local_undirected", (DL_FUNC) &R_igraph_transitivity_local_undirected, 3}, {"R_igraph_transitivity_local_undirected_all", (DL_FUNC) &R_igraph_transitivity_local_undirected_all, 2}, {"R_igraph_transitivity_undirected", (DL_FUNC) &R_igraph_transitivity_undirected, 2}, {"R_igraph_tree", (DL_FUNC) &R_igraph_tree, 3}, {"R_igraph_triad_census", (DL_FUNC) &R_igraph_triad_census, 1}, {"R_igraph_unfold_tree", (DL_FUNC) &R_igraph_unfold_tree, 3}, {"R_igraph_union", (DL_FUNC) &R_igraph_union, 2}, {"R_igraph_vcount", (DL_FUNC) &R_igraph_vcount, 1}, {"R_igraph_version", (DL_FUNC) &R_igraph_version, 0}, {"R_igraph_vertex_connectivity", (DL_FUNC) &R_igraph_vertex_connectivity, 2}, {"R_igraph_vertex_disjoint_paths", (DL_FUNC) &R_igraph_vertex_disjoint_paths, 3}, {"R_igraph_vs_adj", (DL_FUNC) &R_igraph_vs_adj, 4}, {"R_igraph_vs_nei", (DL_FUNC) &R_igraph_vs_nei, 4}, {"R_igraph_walktrap_community", (DL_FUNC) &R_igraph_walktrap_community, 6}, {"R_igraph_watts_strogatz_game", (DL_FUNC) &R_igraph_watts_strogatz_game, 6}, {"R_igraph_weak_ref_key", (DL_FUNC) &R_igraph_weak_ref_key, 1}, {"R_igraph_weak_ref_run_finalizer", (DL_FUNC) &R_igraph_weak_ref_run_finalizer, 1}, {"R_igraph_weak_ref_value", (DL_FUNC) &R_igraph_weak_ref_value, 1}, {"R_igraph_weighted_adjacency", (DL_FUNC) &R_igraph_weighted_adjacency, 4}, {"R_igraph_write_graph_dimacs", (DL_FUNC) &R_igraph_write_graph_dimacs, 5}, {"R_igraph_write_graph_dot", (DL_FUNC) &R_igraph_write_graph_dot, 2}, {"R_igraph_write_graph_edgelist", (DL_FUNC) &R_igraph_write_graph_edgelist, 2}, {"R_igraph_write_graph_gml", (DL_FUNC) &R_igraph_write_graph_gml, 4}, {"R_igraph_write_graph_graphml", (DL_FUNC) &R_igraph_write_graph_graphml, 3}, {"R_igraph_write_graph_leda", (DL_FUNC) &R_igraph_write_graph_leda, 4}, {"R_igraph_write_graph_lgl", (DL_FUNC) &R_igraph_write_graph_lgl, 5}, {"R_igraph_write_graph_ncol", (DL_FUNC) &R_igraph_write_graph_ncol, 4}, {"R_igraph_write_graph_pajek", (DL_FUNC) &R_igraph_write_graph_pajek, 2}, {"UUID_gen", (DL_FUNC) &UUID_gen, 1}, {NULL, NULL, 0} }; igraph/src/memory.c0000644000175100001440000000576613431000472014015 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_memory.h" #include "config.h" /** * \function igraph_free * Deallocate memory that was allocated by igraph functions * * Some igraph functions return a pointer vector (igraph_vector_ptr_t) * containing pointers to other igraph or other data types. These data * types are dynamically allocated and have to be deallocated * manually, if the user does not need them any more. This can be done * by calling igraph_free on them. * * * Here is a complete example on how to use \c igraph_free properly. * * * * int main(void) * { * igraph_t graph; * igraph_vector_ptr_t seps; * long int i; * * igraph_famous(&graph, "tutte"); * igraph_vector_ptr_init(&seps, 0); * igraph_minimum_size_separators(&graph, &seps); * * for (i=0; i * * * * \param p Pointer to the piece of memory to be deallocated. * \return Error code, currently always zero, meaning success. * * Time complexity: platform dependent, ideally it should be O(1). * * \sa \ref igraph_malloc() */ int igraph_free(void *p) { igraph_Free(p); return 0; } /** * \function igraph_malloc * Allocate memory that can be safely deallocated by igraph functions * * Some igraph functions, such as \ref igraph_vector_ptr_free_all() and * \ref igraph_vector_ptr_destroy_all() can free memory that may have been * allocated by the user. \c igraph_malloc() works exactly like \c malloc() * from the C standard library, but it is guaranteed that it can be safely * paired with the \c free() function used by igraph internally (which is * also user-accessible through \ref igraph_free()). * * \param n Number of bytes to be allocated. * \return Pointer to the piece of allocated memory. * * \sa \ref igraph_free() */ void *igraph_malloc(size_t n) { return malloc(n); } igraph/src/walktrap.cpp0000644000175100001440000001464613431000472014667 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: walktrap.cpp //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #include "walktrap_graph.h" #include "walktrap_communities.h" #include #include #include #include #include #include "igraph_community.h" #include "igraph_components.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" using namespace std; using namespace igraph::walktrap; /** * \function igraph_community_walktrap * * This function is the implementation of the Walktrap community * finding algorithm, see Pascal Pons, Matthieu Latapy: Computing * communities in large networks using random walks, * http://arxiv.org/abs/physics/0512106 * * * Currently the original C++ implementation is used in igraph, * see http://www-rp.lip6.fr/~latapy/PP/walktrap.html * I'm grateful to Matthieu Latapy and Pascal Pons for providing this * source code. * * * In contrast to the original implementation, isolated vertices are allowed * in the graph and they are assumed to have a single incident loop edge with * weight 1. * * \param graph The input graph, edge directions are ignored. * \param weights Numeric vector giving the weights of the edges. * If it is a NULL pointer then all edges will have equal * weights. The weights are expected to be positive. * \param steps Integer constant, the length of the random walks. * \param merges Pointer to a matrix, the merges performed by the * algorithm will be stored here (if not NULL). Each merge is a * row in a two-column matrix and contains the ids of the merged * clusters. Clusters are numbered from zero and cluster numbers * smaller than the number of nodes in the network belong to the * individual vertices as singleton clusters. In each step a new * cluster is created from two other clusters and its id will be * one larger than the largest cluster id so far. This means that * before the first merge we have \c n clusters (the number of * vertices in the graph) numbered from zero to \c n-1. The first * merge creates cluster \c n, the second cluster \c n+1, etc. * \param modularity Pointer to a vector. If not NULL then the * modularity score of the current clustering is stored here after * each merge operation. * \param membership Pointer to a vector. If not a NULL pointer, then * the membership vector corresponding to the maximal modularity * score is stored here. If it is not a NULL pointer, then neither * \p modularity nor \p merges may be NULL. * \return Error code. * * \sa \ref igraph_community_spinglass(), \ref * igraph_community_edge_betweenness(). * * Time complexity: O(|E||V|^2) in the worst case, O(|V|^2 log|V|) typically, * |V| is the number of vertices, |E| is the number of edges. * * \example examples/simple/walktrap.c */ int igraph_community_walktrap(const igraph_t *graph, const igraph_vector_t *weights, int steps, igraph_matrix_t *merges, igraph_vector_t *modularity, igraph_vector_t *membership) { long int no_of_nodes=(long int)igraph_vcount(graph); int length=steps; long max_memory=-1; if (membership && !(modularity && merges)) { IGRAPH_ERROR("Cannot calculate membership without modularity or merges", IGRAPH_EINVAL); } Graph* G = new Graph; if (G->convert_from_igraph(graph, weights)) IGRAPH_ERROR("Cannot convert igraph graph into walktrap format", IGRAPH_EINVAL); if (merges) { igraph_integer_t no; IGRAPH_CHECK(igraph_clusters(graph, /*membership=*/ 0, /*csize=*/ 0, &no, IGRAPH_WEAK)); IGRAPH_CHECK(igraph_matrix_resize(merges, no_of_nodes-no, 2)); } if (modularity) { IGRAPH_CHECK(igraph_vector_resize(modularity, no_of_nodes)); igraph_vector_null(modularity); } Communities C(G, length, max_memory, merges, modularity); while (!C.H->is_empty()) { IGRAPH_ALLOW_INTERRUPTION(); C.merge_nearest_communities(); } delete G; if (membership) { long int m=igraph_vector_which_max(modularity); IGRAPH_CHECK(igraph_community_to_membership(merges, no_of_nodes, /*steps=*/ m, membership, /*csize=*/ 0)); } return 0; } igraph/src/array.pmt0000644000175100001440000000477513430770175014215 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" int FUNCTION(igraph_array3,init)(TYPE(igraph_array3) *a, long int n1, long int n2, long int n3) { int ret; ret=FUNCTION(igraph_vector,init)(&a->data, n1*n2*n3); a->n1=n1; a->n2=n2; a->n3=n3; a->n1n2=n1*n2; return ret; } void FUNCTION(igraph_array3,destroy)(TYPE(igraph_array3) *a) { FUNCTION(igraph_vector,destroy)(&a->data); } long int FUNCTION(igraph_array3,size)(const TYPE(igraph_array3) *a) { return (a->n1n2) * (a->n3); } long int FUNCTION(igraph_array3,n)(const TYPE(igraph_array3) *a, long int idx) { switch (idx) { case 1: return a->n1; break; case 2: return a->n2; break; case 3: return a->n3; break; } return 0; } int FUNCTION(igraph_array3,resize)(TYPE(igraph_array3) *a, long int n1, long int n2, long int n3) { int ret=FUNCTION(igraph_vector,resize)(&a->data, n1*n2*n3); a->n1=n1; a->n2=n2; a->n3=n3; a->n1n2=n1*n2; return ret; } void FUNCTION(igraph_array3,null)(TYPE(igraph_array3) *a) { FUNCTION(igraph_vector,null)(&a->data); } BASE FUNCTION(igraph_array3,sum)(const TYPE(igraph_array3) *a) { return FUNCTION(igraph_vector,sum)(&a->data); } void FUNCTION(igraph_array3,scale)(TYPE(igraph_array3) *a, BASE by) { FUNCTION(igraph_vector,scale)(&a->data, by); } void FUNCTION(igraph_array3,fill)(TYPE(igraph_array3) *a, BASE e) { FUNCTION(igraph_vector,fill)(&a->data, e); } int FUNCTION(igraph_array3,update)(TYPE(igraph_array3) *to, const TYPE(igraph_array3) *from) { IGRAPH_CHECK(FUNCTION(igraph_array3,resize)(to, from->n1, from->n2, from->n3)); FUNCTION(igraph_vector,update)(&to->data, &from->data); return 0; } igraph/src/sparsemat.c0000644000175100001440000024271313431000472014477 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "cs/cs.h" #include "igraph_sparsemat.h" #include "igraph_error.h" #include "igraph_interface.h" #include "igraph_constructors.h" #include "igraph_memory.h" #include "igraph_vector_ptr.h" #include "igraph_attributes.h" #include /** * \section about_sparsemat About sparse matrices * * * The igraph_sparsemat_t data type stores sparse matrices, * i.e. matrices in which the majority of the elements are zero. * * * The data type is essentially a wrapper to some of the * functions in the CXSparse library, by Tim Davis, see * http://www.cise.ufl.edu/research/sparse/CXSparse/ * * * * Matrices can be stored in two formats: triplet and * column-compressed. The triplet format is intended for sparse matrix * initialization, as it is easy to add new (non-zero) elements to * it. Most of the computations are done on sparse matrices in * column-compressed format, after the user has converted the triplet * matrix to column-compressed, via \ref igraph_sparsemat_compress(). * * * * Both formats are dynamic, in the sense that new elements can be * added to them, possibly resulting the allocation of more memory. * * * * Row and column indices follow the C convention and are zero-based. * * * * \example examples/simple/igraph_sparsemat.c * \example examples/simple/igraph_sparsemat2.c * \example examples/simple/igraph_sparsemat3.c * \example examples/simple/igraph_sparsemat4.c * \example examples/simple/igraph_sparsemat5.c * \example examples/simple/igraph_sparsemat6.c * \example examples/simple/igraph_sparsemat7.c * \example examples/simple/igraph_sparsemat8.c * */ /** * \function igraph_sparsemat_init * Initialize a sparse matrix, in triplet format * * This is the most common way to create a sparse matrix, together * with the \ref igraph_sparsemat_entry() function, which can be used to * add the non-zero elements one by one. Once done, the user can call * \ref igraph_sparsemat_compress() to convert the matrix to * column-compressed, to allow computations with it. * * The user must call \ref igraph_sparsemat_destroy() on * the matrix to deallocate the memory, once the matrix is no more * needed. * \param A Pointer to a not yet initialized sparse matrix. * \param rows The number of rows in the matrix. * \param cols The number of columns. * \param nzmax The maximum number of non-zero elements in the * matrix. It is not compulsory to get this right, but it is * useful for the allocation of the proper amount of memory. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_init(igraph_sparsemat_t *A, int rows, int cols, int nzmax) { if (rows < 0) { IGRAPH_ERROR("Negative number of rows", IGRAPH_EINVAL); } if (cols < 0) { IGRAPH_ERROR("Negative number of columns", IGRAPH_EINVAL); } A->cs=cs_spalloc( rows, cols, nzmax, /*values=*/ 1, /*triplet=*/ 1); if (!A->cs) { IGRAPH_ERROR("Cannot allocate memory for sparse matrix", IGRAPH_ENOMEM); } return 0; } /** * \function igraph_sparsemat_copy * Copy a sparse matrix * * Create a sparse matrix object, by copying another one. The source * matrix can be either in triplet or column-compressed format. * * * Exactly the same amount of memory will be allocated to the * copy matrix, as it is currently for the original one. * \param to Pointer to an uninitialized sparse matrix, the copy will * be created here. * \param from The sparse matrix to copy. * \return Error code. * * Time complexity: O(n+nzmax), the number of columns plus the maximum * number of non-zero elements. */ int igraph_sparsemat_copy(igraph_sparsemat_t *to, const igraph_sparsemat_t *from) { int ne=from->cs->nz == -1 ? from->cs->n+1 : from->cs->nzmax; to->cs = cs_spalloc(from->cs->m, from->cs->n, from->cs->nzmax, /*values=*/ 1, /*triplet=*/ igraph_sparsemat_is_triplet(from)); to->cs->nzmax = from->cs->nzmax; to->cs->m = from->cs->m; to->cs->n = from->cs->n; to->cs->nz = from->cs->nz; memcpy(to->cs->p, from->cs->p, sizeof(int) * (size_t) ne); memcpy(to->cs->i, from->cs->i, sizeof(int) * (size_t) (from->cs->nzmax)); memcpy(to->cs->x, from->cs->x, sizeof(double) * (size_t) (from->cs->nzmax)); return 0; } /** * \function igraph_sparsemat_destroy * Deallocate memory used by a sparse matrix * * One destroyed, the sparse matrix must be initialized again, before * calling any other operation on it. * \param A The sparse matrix to destroy. * * Time complexity: O(1). */ void igraph_sparsemat_destroy(igraph_sparsemat_t *A) { cs_spfree(A->cs); } /** * \function igraph_sparsemat_realloc * Allocate more (or less) memory for a sparse matrix * * Sparse matrices automatically allocate more memory, as needed. To * control memory allocation, the user can call this function, to * allocate memory for a given number of non-zero elements. * \param A The sparse matrix, it can be in triplet or * column-compressed format. * \param nzmax The new maximum number of non-zero elements. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_realloc(igraph_sparsemat_t *A, int nzmax) { return !cs_sprealloc(A->cs, nzmax); } /** * \function igraph_sparsemat_nrow * Number of rows * * \param A The input matrix, in triplet or column-compressed format. * \return The number of rows in the \p A matrix. * * Time complexity: O(1). */ long int igraph_sparsemat_nrow(const igraph_sparsemat_t *A) { return A->cs->m; } /** * \function igraph_sparsemat_ncol * Number of columns. * * \param A The input matrix, in triplet or column-compressed format. * \return The number of columns in the \p A matrix. * * Time complexity: O(1). */ long int igraph_sparsemat_ncol(const igraph_sparsemat_t *A) { return A->cs->n; } /** * \function igraph_sparsemat_type * Type of a sparse matrix (triplet or column-compressed) * * Gives whether a sparse matrix is stored in the triplet format or in * column-compressed format. * \param A The input matrix. * \return Either \c IGRAPH_SPARSEMAT_CC or \c * IGRAPH_SPARSEMAT_TRIPLET. * * Time complexity: O(1). */ igraph_sparsemat_type_t igraph_sparsemat_type(const igraph_sparsemat_t *A) { return A->cs->nz < 0 ? IGRAPH_SPARSEMAT_CC : IGRAPH_SPARSEMAT_TRIPLET; } /** * \function igraph_sparsemat_is_triplet * Is this sparse matrix in triplet format? * * Decides whether a sparse matrix is in triplet format. * \param A The input matrix. * \return One if the input matrix is in triplet format, zero * otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_sparsemat_is_triplet(const igraph_sparsemat_t *A) { return A->cs->nz >= 0; } /** * \function igraph_sparsemat_is_cc * Is this sparse matrix in column-compressed format? * * Decides whether a sparse matrix is in column-compressed format. * \param A The input matrix. * \return One if the input matrix is in column-compressed format, zero * otherwise. * * Time complexity: O(1). */ igraph_bool_t igraph_sparsemat_is_cc(const igraph_sparsemat_t *A) { return A->cs->nz < 0; } /** * \function igraph_sparsemat_permute * Permute the rows and columns of a sparse matrix * * \param A The input matrix, it must be in column-compressed format. * \param p Integer vector, giving the permutation of the rows. * \param q Integer vector, the permutation of the columns. * \param res Pointer to an uninitialized sparse matrix, the result is * stored here. * \return Error code. * * Time complexity: O(m+n+nz), the number of rows plus the number of * columns plus the number of non-zero elements in the matrix. */ int igraph_sparsemat_permute(const igraph_sparsemat_t *A, const igraph_vector_int_t *p, const igraph_vector_int_t *q, igraph_sparsemat_t *res) { long int nrow=A->cs->m, ncol=A->cs->n; igraph_vector_int_t pinv; long int i; if (nrow != igraph_vector_int_size(p)) { IGRAPH_ERROR("Invalid row permutation length", IGRAPH_FAILURE); } if (ncol != igraph_vector_int_size(q)) { IGRAPH_ERROR("Invalid column permutation length", IGRAPH_FAILURE); } /* We invert the permutation by hand */ IGRAPH_CHECK(igraph_vector_int_init(&pinv, nrow)); IGRAPH_FINALLY(igraph_vector_int_destroy, &pinv); for (i=0; ics = cs_permute(A->cs, VECTOR(pinv), VECTOR(*q), /*values=*/ 1))) { IGRAPH_ERROR("Cannot index sparse matrix", IGRAPH_FAILURE); } igraph_vector_int_destroy(&pinv); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_sparsemat_index_rows(const igraph_sparsemat_t *A, const igraph_vector_int_t *p, igraph_sparsemat_t *res, igraph_real_t *constres) { igraph_sparsemat_t II, II2; long int nrow=A->cs->m; long int idx_rows=igraph_vector_int_size(p); long int k; /* Create index matrix */ IGRAPH_CHECK(igraph_sparsemat_init(&II2, (int) idx_rows, (int) nrow, (int) idx_rows)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &II2); for (k=0; kcs->p[1] != 0) { *constres = res->cs->x[0]; } else { *constres = 0.0; } } return 0; } int igraph_i_sparsemat_index_cols(const igraph_sparsemat_t *A, const igraph_vector_int_t *q, igraph_sparsemat_t *res, igraph_real_t *constres) { igraph_sparsemat_t JJ, JJ2; long int ncol=A->cs->n; long int idx_cols=igraph_vector_int_size(q); long int k; /* Create index matrix */ IGRAPH_CHECK(igraph_sparsemat_init(&JJ2, (int) ncol, (int) idx_cols, (int) idx_cols)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &JJ2); for (k=0; kcs->p [1] != 0) { *constres = res->cs->x [0]; } else { *constres = 0.0; } } return 0; } /** * \function igraph_sparsemat_index * Index a sparse matrix, extract a submatrix, or a single element * * This function serves two purposes. First, it can extract * submatrices from a sparse matrix. Second, as a special case, it can * extract a single element from a sparse matrix. * \param A The input matrix, it must be in column-compressed format. * \param p An integer vector, or a null pointer. The selected row * index or indices. A null pointer selects all rows. * \param q An integer vector, or a null pointer. The selected column * index or indices. A null pointer selects all columns. * \param res Pointer to an uninitialized sparse matrix, or a null * pointer. If not a null pointer, then the selected submatrix is * stored here. * \param constres Pointer to a real variable or a null pointer. If * not a null pointer, then the first non-zero element in the * selected submatrix is stored here, if there is one. Otherwise * zero is stored here. This behavior is handy if one * wants to select a single entry from the matrix. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_index(const igraph_sparsemat_t *A, const igraph_vector_int_t *p, const igraph_vector_int_t *q, igraph_sparsemat_t *res, igraph_real_t *constres) { igraph_sparsemat_t II, JJ, II2, JJ2, tmp; long int nrow=A->cs->m; long int ncol=A->cs->n; long int idx_rows= p ? igraph_vector_int_size(p) : -1; long int idx_cols= q ? igraph_vector_int_size(q) : -1; long int k; igraph_sparsemat_t *myres=res, mres; if (!p && !q) { IGRAPH_ERROR("No index vectors", IGRAPH_EINVAL); } if (!res && (idx_rows != 1 || idx_cols != 1)) { IGRAPH_ERROR("Sparse matrix indexing: must give `res' if not a " "single element is selected", IGRAPH_EINVAL); } if (!q) { return igraph_i_sparsemat_index_rows(A, p, res, constres); } if (!p) { return igraph_i_sparsemat_index_cols(A, q, res, constres); } if (!res) { myres=&mres; } /* Create first index matrix */ IGRAPH_CHECK(igraph_sparsemat_init(&II2, (int) idx_rows, (int) nrow, (int) idx_rows)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &II2); for (k=0; kcs->p [1] != 0) { *constres = myres->cs->x [0]; } else { *constres = 0.0; } } if (!res) { igraph_sparsemat_destroy(myres); } return 0; } /** * \function igraph_sparsemat_entry * Add an element to a sparse matrix * * This function can be used to add the entries to a sparse matrix, * after initializing it with \ref igraph_sparsemat_init(). * \param A The input matrix, it must be in triplet format. * \param row The row index of the entry to add. * \param col The column index of the entry to add. * \param elem The value of the entry. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_entry(igraph_sparsemat_t *A, int row, int col, igraph_real_t elem) { if (!cs_entry(A->cs, row, col, elem)) { IGRAPH_ERROR("Cannot add entry to sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_compress * Compress a sparse matrix, i.e. convert it to column-compress format * * Almost all sparse matrix operations require that the matrix is in * column-compressed format. * \param A The input matrix, it must be in triplet format. * \param res Pointer to an uninitialized sparse matrix object, the * compressed version of \p A is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_compress(const igraph_sparsemat_t *A, igraph_sparsemat_t *res) { if (! (res->cs=cs_compress(A->cs)) ) { IGRAPH_ERROR("Cannot compress sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_transpose * Transpose a sparse matrix * * \param A The input matrix, column-compressed or triple format. * \param res Pointer to an uninitialized sparse matrix, the result is * stored here. * \param values If this is non-zero, the matrix transpose is * calculated the normal way. If it is zero, then only the pattern * of the input matrix is stored in the result, the values are not. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_transpose(const igraph_sparsemat_t *A, igraph_sparsemat_t *res, int values) { if (A->cs->nz < 0) { /* column-compressed */ if (! (res->cs=cs_transpose(A->cs, values)) ) { IGRAPH_ERROR("Cannot transpose sparse matrix", IGRAPH_FAILURE); } } else { /* triplets */ int *tmp; IGRAPH_CHECK(igraph_sparsemat_copy(res, A)); tmp = res->cs->p; res->cs->p = res->cs->i; res->cs->i = tmp; } return 0; } igraph_bool_t igraph_i_sparsemat_is_symmetric_cc(const igraph_sparsemat_t *A) { igraph_sparsemat_t t, tt; igraph_bool_t res; int nz; IGRAPH_CHECK(igraph_sparsemat_transpose(A, &t, /*values=*/ 1)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &t); IGRAPH_CHECK(igraph_sparsemat_dupl(&t)); IGRAPH_CHECK(igraph_sparsemat_transpose(&t, &tt, /*values=*/ 1)); igraph_sparsemat_destroy(&t); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_sparsemat_destroy, &tt); IGRAPH_CHECK(igraph_sparsemat_transpose(&tt, &t, /*values=*/ 1)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &t); nz=t.cs->p[t.cs->n]; res = memcmp(t.cs->i, tt.cs->i, sizeof(int) * (size_t) nz) == 0; res = res && memcmp(t.cs->p, tt.cs->p, sizeof(int) * (size_t)(t.cs->n+1)) == 0; res = res && memcmp(t.cs->x, tt.cs->x, sizeof(igraph_real_t) * (size_t)nz)==0; igraph_sparsemat_destroy(&t); igraph_sparsemat_destroy(&tt); IGRAPH_FINALLY_CLEAN(2); return res; } igraph_bool_t igraph_i_sparsemat_is_symmetric_triplet(const igraph_sparsemat_t *A) { igraph_sparsemat_t tmp; igraph_bool_t res; IGRAPH_CHECK(igraph_sparsemat_compress(A, &tmp)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &tmp); res=igraph_i_sparsemat_is_symmetric_cc(&tmp); igraph_sparsemat_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return res; } igraph_bool_t igraph_sparsemat_is_symmetric(const igraph_sparsemat_t *A) { if (A->cs->m != A->cs->n) { return 0; } if (A->cs->nz < 0) { return igraph_i_sparsemat_is_symmetric_cc(A); } else { return igraph_i_sparsemat_is_symmetric_triplet(A); } } /** * \function igraph_sparsemat_dupl * Remove duplicate elements from a sparse matrix * * It is possible that a column-compressed sparse matrix stores a * single matrix entry in multiple pieces. The entry is then the sum * of all its pieces. (Some functions create matrices like this.) This * function eliminates the multiple pieces. * \param A The input matrix, in column-compressed format. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_dupl(igraph_sparsemat_t *A) { if (!cs_dupl(A->cs)) { IGRAPH_ERROR("Cannot remove duplicates from sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_fkeep * Filter the elements of a sparse matrix * * This function can be used to filter the (non-zero) elements of a * sparse matrix. For all entries, it calls the supplied function and * depending on the return values either keeps, or deleted the element * from the matrix. * \param A The input matrix, in column-compressed format. * \param fkeep The filter function. It must take four arguments: the * first is an \c int, the row index of the entry, the second is * another \c int, the column index. The third is \c igraph_real_t, * the value of the entry. The fourth element is a \c void pointer, * the \p other argument is passed here. The function must return * an \c int. If this is zero, then the entry is deleted, otherwise * it is kept. * \param other A \c void pointer that is passed to the filtering * function. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_fkeep(igraph_sparsemat_t *A, int (*fkeep)(int, int, igraph_real_t, void*), void *other) { if (!cs_fkeep(A->cs, fkeep, other)) { IGRAPH_ERROR("Cannot filter sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_dropzeros * Drop the zero elements from a sparse matrix * * As a result of matrix operations, some of the entries in a sparse * matrix might be zero. This function removes these entries. * \param A The input matrix, it must be in column-compressed format. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_dropzeros(igraph_sparsemat_t *A) { if (!cs_dropzeros(A->cs)) { IGRAPH_ERROR("Cannot drop zeros from sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_droptol * Drop the almost zero elements of a sparse matrix * * This function is similar to \ref igraph_sparsemat_dropzeros(), but it * also drops entries that are closer to zero than the given tolerance * threshold. * \param A The input matrix, it must be in column-compressed format. * \param tol Real number, giving the tolerance threshold. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_droptol(igraph_sparsemat_t *A, igraph_real_t tol) { if (!cs_droptol(A->cs, tol)) { IGRAPH_ERROR("Cannot drop (almost) zeros from sparse matrix", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_multiply * Matrix multiplication * * Multiplies two sparse matrices. * \param A The first input matrix (left hand side), in * column-compressed format. * \param B The second input matrix (right hand side), in * column-compressed format. * \param res Pointer to an uninitialized sparse matrix, the result is * stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_multiply(const igraph_sparsemat_t *A, const igraph_sparsemat_t *B, igraph_sparsemat_t *res) { if (! (res->cs=cs_multiply(A->cs, B->cs))) { IGRAPH_ERROR("Cannot multiply matrices", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_add * Sum of two sparse matrices * * \param A The first input matrix, in column-compressed format. * \param B The second input matrix, in column-compressed format. * \param alpha Real scalar, \p A is multiplied by \p alpha before the * addition. * \param beta Real scalar, \p B is multiplied by \p beta before the * addition. * \param res Pointer to an uninitialized sparse matrix, the result * is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_add(const igraph_sparsemat_t *A, const igraph_sparsemat_t *B, igraph_real_t alpha, igraph_real_t beta, igraph_sparsemat_t *res) { if (! (res->cs=cs_add(A->cs, B->cs, alpha, beta))) { IGRAPH_ERROR("Cannot add matrices", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_gaxpy * Matrix-vector product, added to another vector. * * \param A The input matrix, in column-compressed format. * \param x The input vector, its size must match the number of * columns in \p A. * \param res This vector is added to the matrix-vector product * and it is overwritten by the result. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_gaxpy(const igraph_sparsemat_t *A, const igraph_vector_t *x, igraph_vector_t *res) { if (A->cs->n != igraph_vector_size(x) || A->cs->m != igraph_vector_size(res)) { IGRAPH_ERROR("Invalid matrix/vector size for multiplication", IGRAPH_EINVAL); } if (! (cs_gaxpy(A->cs, VECTOR(*x), VECTOR(*res)))) { IGRAPH_ERROR("Cannot perform sparse matrix vector multiplication", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_lsolve * Solve a lower-triangular linear system * * Solve the Lx=b linear equation system, where the L coefficient * matrix is square and lower-triangular, with a zero-free diagonal. * \param L The input matrix, in column-compressed format. * \param b The right hand side of the linear system. * \param res An initialized vector, the result is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_lsolve(const igraph_sparsemat_t *L, const igraph_vector_t *b, igraph_vector_t *res) { if (L->cs->m != L->cs->n) { IGRAPH_ERROR("Cannot perform lower triangular solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res, b)); } if (! cs_lsolve(L->cs, VECTOR(*res))) { IGRAPH_ERROR("Cannot perform lower triangular solve", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_ltsolve * Solve an upper-triangular linear system * * Solve the L'x=b linear equation system, where the L * matrix is square and lower-triangular, with a zero-free diagonal. * \param L The input matrix, in column-compressed format. * \param b The right hand side of the linear system. * \param res An initialized vector, the result is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_ltsolve(const igraph_sparsemat_t *L, const igraph_vector_t *b, igraph_vector_t *res) { if (L->cs->m != L->cs->n) { IGRAPH_ERROR("Cannot perform transposed lower triangular solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res,b)); } if (!cs_ltsolve(L->cs, VECTOR(*res))) { IGRAPH_ERROR("Cannot perform lower triangular solve", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_usolve * Solve an upper-triangular linear system * * Solves the Ux=b upper triangular system. * \param U The input matrix, in column-compressed format. * \param b The right hand side of the linear system. * \param res An initialized vector, the result is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_usolve(const igraph_sparsemat_t *U, const igraph_vector_t *b, igraph_vector_t *res) { if (U->cs->m != U->cs->n) { IGRAPH_ERROR("Cannot perform upper triangular solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res, b)); } if (! cs_usolve(U->cs, VECTOR(*res))) { IGRAPH_ERROR("Cannot perform upper triangular solve", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_utsolve * Solve a lower-triangular linear system * * This is the same as \ref igraph_sparsemat_usolve(), but U'x=b is * solved, where the apostrophe denotes the transpose. * \param U The input matrix, in column-compressed format. * \param b The right hand side of the linear system. * \param res An initialized vector, the result is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_utsolve(const igraph_sparsemat_t *U, const igraph_vector_t *b, igraph_vector_t *res) { if (U->cs->m != U->cs->n) { IGRAPH_ERROR("Cannot perform transposed upper triangular solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res,b)); } if (!cs_utsolve(U->cs, VECTOR(*res))) { IGRAPH_ERROR("Cannot perform transposed upper triangular solve", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_cholsol * Solve a symmetric linear system via Cholesky decomposition * * Solve Ax=b, where A is a symmetric positive definite matrix. * \param A The input matrix, in column-compressed format. * \param v The right hand side. * \param res An initialized vector, the result is stored here. * \param order An integer giving the ordering method to use for the * factorization. Zero is the natural ordering; if it is one, then * the fill-reducing minimum-degree ordering of A+A' is used. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_cholsol(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res, int order) { if (A->cs->m != A->cs->n) { IGRAPH_ERROR("Cannot perform sparse symmetric solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res,b)); } if (! cs_cholsol(order, A->cs, VECTOR(*res))) { IGRAPH_ERROR("Cannot perform sparse symmetric solve", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_lusol * Solve a linear system via LU decomposition * * Solve Ax=b, via LU factorization of A. * \param A The input matrix, in column-compressed format. * \param b The right hand side of the equation. * \param res An initialized vector, the result is stored here. * \param order The ordering method to use, zero means the natural * ordering, one means the fill-reducing minimum-degree ordering of * A+A', two means the ordering of A'*A, after removing the dense * rows from A. Three means the ordering of A'*A. * \param tol Real number, the tolerance limit to use for the numeric * LU factorization. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_lusol(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res, int order, igraph_real_t tol) { if (A->cs->m != A->cs->n) { IGRAPH_ERROR("Cannot perform LU solve", IGRAPH_NONSQUARE); } if (res != b) { IGRAPH_CHECK(igraph_vector_update(res,b)); } if (! cs_lusol(order, A->cs, VECTOR(*res), tol)) { IGRAPH_ERROR("Cannot perform LU solve", IGRAPH_FAILURE); } return 0; } int igraph_i_sparsemat_cc(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed) { igraph_vector_t edges; long int no_of_nodes=A->cs->m; long int no_of_edges=A->cs->p[A->cs->n]; int *p=A->cs->p; int *i=A->cs->i; long int from=0; long int to=0; long int e=0; if (no_of_nodes != A->cs->n) { IGRAPH_ERROR("Cannot create graph object", IGRAPH_NONSQUARE); } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); while (*p < no_of_edges) { while (to < *(p+1)) { if (directed || from >= *i) { VECTOR(edges)[e++] = from; VECTOR(edges)[e++] = (*i); } to++; i++; } from++; p++; } igraph_vector_resize(&edges, e); IGRAPH_CHECK(igraph_create(graph, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_sparsemat_triplet(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed) { igraph_vector_t edges; long int no_of_nodes=A->cs->m; long int no_of_edges=A->cs->nz; int *i=A->cs->p; int *j=A->cs->i; long int e; if (no_of_nodes != A->cs->n) { IGRAPH_ERROR("Cannot create graph object", IGRAPH_NONSQUARE); } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); for (e=0; e<2*no_of_edges; i++, j++) { if (directed || *i >= *j) { VECTOR(edges)[e++] = (*i); VECTOR(edges)[e++] = (*j); } } igraph_vector_resize(&edges, e); IGRAPH_CHECK(igraph_create(graph, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_sparsemat * Create an igraph graph from a sparse matrix * * One edge is created for each non-zero entry in the matrix. If you * have a symmetric matrix, and want to create an undirected graph, * then delete the entries in the upper diagonal first, or call \ref * igraph_simplify() on the result graph to eliminate the multiple * edges. * \param graph Pointer to an uninitialized igraph_t object, the * graphs is stored here. * \param A The input matrix, in triplet or column-compressed format. * \param directed Boolean scalar, whether to create a directed * graph. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed) { if (A->cs->nz < 0) { return(igraph_i_sparsemat_cc(graph, A, directed)); } else { return(igraph_i_sparsemat_triplet(graph, A, directed)); } } int igraph_i_weighted_sparsemat_cc(const igraph_sparsemat_t *A, igraph_bool_t directed, const char *attr, igraph_bool_t loops, igraph_vector_t *edges, igraph_vector_t *weights) { long int no_of_edges=A->cs->p[A->cs->n]; int *p=A->cs->p; int *i=A->cs->i; igraph_real_t *x=A->cs->x; long int from=0; long int to=0; long int e=0, w=0; IGRAPH_UNUSED(attr); igraph_vector_resize(edges, no_of_edges*2); igraph_vector_resize(weights, no_of_edges); while (*p < no_of_edges) { while (to < *(p+1)) { if ( (loops || from != *i) && (directed || from >= *i) && *x != 0) { VECTOR(*edges)[e++] = (*i); VECTOR(*edges)[e++] = from; VECTOR(*weights)[w++] = (*x); } to++; i++; x++; } from++; p++; } igraph_vector_resize(edges, e); igraph_vector_resize(weights, w); return 0; } int igraph_i_weighted_sparsemat_triplet(const igraph_sparsemat_t *A, igraph_bool_t directed, const char *attr, igraph_bool_t loops, igraph_vector_t *edges, igraph_vector_t *weights) { IGRAPH_UNUSED(A); IGRAPH_UNUSED(directed); IGRAPH_UNUSED(attr); IGRAPH_UNUSED(loops); IGRAPH_UNUSED(edges); IGRAPH_UNUSED(weights); /* TODO */ IGRAPH_ERROR("Triplet matrices are not implemented", IGRAPH_UNIMPLEMENTED); return 0; } int igraph_weighted_sparsemat(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed, const char *attr, igraph_bool_t loops) { igraph_vector_t edges, weights; int pot_edges= A->cs->nz < 0 ? A->cs->p[A->cs->n] : A->cs->nz; const char* default_attr = "weight"; igraph_vector_ptr_t attr_vec; igraph_attribute_record_t attr_rec; long int no_of_nodes=A->cs->m; if (no_of_nodes != A->cs->n) { IGRAPH_ERROR("Cannot create graph object", IGRAPH_NONSQUARE); } IGRAPH_VECTOR_INIT_FINALLY(&edges, pot_edges*2); IGRAPH_VECTOR_INIT_FINALLY(&weights, pot_edges); IGRAPH_VECTOR_PTR_INIT_FINALLY(&attr_vec, 1); if (A->cs->nz < 0) { IGRAPH_CHECK(igraph_i_weighted_sparsemat_cc(A, directed, attr, loops, &edges, &weights)); } else { IGRAPH_CHECK(igraph_i_weighted_sparsemat_triplet(A, directed, attr, loops, &edges, &weights)); } /* Prepare attribute record */ attr_rec.name = attr ? attr : default_attr; attr_rec.type = IGRAPH_ATTRIBUTE_NUMERIC; attr_rec.value = &weights; VECTOR(attr_vec)[0] = &attr_rec; /* Create graph */ IGRAPH_CHECK(igraph_empty(graph, (igraph_integer_t) no_of_nodes, directed)); IGRAPH_FINALLY(igraph_destroy, graph); if (igraph_vector_size(&edges)>0) { IGRAPH_CHECK(igraph_add_edges(graph, &edges, &attr_vec)); } IGRAPH_FINALLY_CLEAN(1); /* Cleanup */ igraph_vector_destroy(&edges); igraph_vector_destroy(&weights); igraph_vector_ptr_destroy(&attr_vec); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \function igraph_get_sparsemat * Convert an igraph graph to a sparse matrix * * If the graph is undirected, then a symmetric matrix is created. * \param graph The input graph. * \param res Pointer to an uninitialized sparse matrix. The result * will be stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_get_sparsemat(const igraph_t *graph, igraph_sparsemat_t *res) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); long int nzmax= directed ? no_of_edges : no_of_edges*2; long int i; IGRAPH_CHECK(igraph_sparsemat_init(res, (igraph_integer_t) no_of_nodes, (igraph_integer_t) no_of_nodes, (igraph_integer_t) nzmax)); for (i=0; ics->nz < 0) { /* CC */ int j, p; for (j=0; jcs->n; j++) { CHECK(fprintf(outstream, "col %i: locations %i to %i\n", j, A->cs->p[j], A->cs->p[j+1]-1)); for (p=A->cs->p[j]; p < A->cs->p[j+1]; p++) { CHECK(fprintf(outstream, "%i : %g\n", A->cs->i[p], A->cs->x[p])); } } } else { /* Triplet */ int p; for (p=0; pcs->nz; p++) { CHECK(fprintf(outstream, "%i %i : %g\n", A->cs->i[p], A->cs->p[p], A->cs->x[p])); } } return 0; } #undef CHECK int igraph_i_sparsemat_eye_triplet(igraph_sparsemat_t *A, int n, int nzmax, igraph_real_t value) { long int i; IGRAPH_CHECK(igraph_sparsemat_init(A, n, n, nzmax)); for (i=0; ics = cs_spalloc(n, n, n, /*values=*/ 1, /*triplet=*/ 0)) ) { IGRAPH_ERROR("Cannot create eye sparse matrix", IGRAPH_FAILURE); } for (i=0; ics->p [i] = (int) i; A->cs->i [i] = (int) i; A->cs->x [i] = value; } A->cs->p [n] = n; return 0; } /** * \function igraph_sparsemat_eye * Create a sparse identity matrix * * \param A An uninitialized sparse matrix, the result is stored * here. * \param n The number of rows and number of columns in the matrix. * \param nzmax The maximum number of non-zero elements, this * essentially gives the amount of memory that will be allocated for * matrix elements. * \param value The value to store in the diagonal. * \param compress Whether to create a column-compressed matrix. If * false, then a triplet matrix is created. * \return Error code. * * Time complexity: O(n). */ int igraph_sparsemat_eye(igraph_sparsemat_t *A, int n, int nzmax, igraph_real_t value, igraph_bool_t compress) { if (compress) { return(igraph_i_sparsemat_eye_cc(A, n, value)); } else { return(igraph_i_sparsemat_eye_triplet(A, n, nzmax, value)); } } int igraph_i_sparsemat_diag_triplet(igraph_sparsemat_t *A, int nzmax, const igraph_vector_t *values) { int i, n=(int) igraph_vector_size(values); IGRAPH_CHECK(igraph_sparsemat_init(A, n, n, nzmax)); for (i=0; ics = cs_spalloc(n, n, n, /*values=*/ 1, /*triplet=*/ 0)) ) { IGRAPH_ERROR("Cannot create eye sparse matrix", IGRAPH_FAILURE); } for (i=0; ics->p [i] = i; A->cs->i [i] = i; A->cs->x [i] = VECTOR(*values)[i]; } A->cs->p [n] = n; return 0; } /** * \function igraph_sparsemat_diag * Create a sparse diagonal matrix * * \param A An uninitialized sparse matrix, the result is stored * here. * \param nzmax The maximum number of non-zero elements, this * essentially gives the amount of memory that will be allocated for * matrix elements. * \param values The values to store in the diagonal, the size of the * matrix defined by the length of this vector. * \param compress Whether to create a column-compressed matrix. If * false, then a triplet matrix is created. * \return Error code. * * Time complexity: O(n), the length of the diagonal vector. */ int igraph_sparsemat_diag(igraph_sparsemat_t *A, int nzmax, const igraph_vector_t *values, igraph_bool_t compress) { if (compress) { return(igraph_i_sparsemat_diag_cc(A, values)); } else { return(igraph_i_sparsemat_diag_triplet(A, nzmax, values)); } } int igraph_i_sparsemat_arpack_multiply(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_sparsemat_t *A=extra; igraph_vector_t vto, vfrom; igraph_vector_view(&vto, to, n); igraph_vector_view(&vfrom, from, n); igraph_vector_null(&vto); IGRAPH_CHECK(igraph_sparsemat_gaxpy(A, &vfrom, &vto)); return 0; } typedef struct igraph_i_sparsemat_arpack_rssolve_data_t { igraph_sparsemat_symbolic_t *dis; igraph_sparsemat_numeric_t *din; igraph_real_t tol; igraph_sparsemat_solve_t method; } igraph_i_sparsemat_arpack_rssolve_data_t; int igraph_i_sparsemat_arpack_solve(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_sparsemat_arpack_rssolve_data_t *data=extra; igraph_vector_t vfrom, vto; igraph_vector_view(&vfrom, from, n); igraph_vector_view(&vto, to, n); if (data->method == IGRAPH_SPARSEMAT_SOLVE_LU) { IGRAPH_CHECK(igraph_sparsemat_luresol(data->dis, data->din, &vfrom, &vto)); } else if (data->method == IGRAPH_SPARSEMAT_SOLVE_QR) { IGRAPH_CHECK(igraph_sparsemat_qrresol(data->dis, data->din, &vfrom, &vto)); } return 0; } /** * \function igraph_sparsemat_arpack_rssolve * Eigenvalues and eigenvectors of a symmetric sparse matrix via ARPACK * * \param The input matrix, must be column-compressed. * \param options It is passed to \ref igraph_arpack_rssolve(). See * \ref igraph_arpack_options_t for the details. If \c mode is 1, * then ARPACK uses regular mode, if \c mode is 3, then shift and * invert mode is used and the \c sigma structure member defines * the shift. * \param storage Storage for ARPACK. See \ref * igraph_arpack_rssolve() and \ref igraph_arpack_storage_t for * details. * \param values An initialized vector or a null pointer, the * eigenvalues are stored here. * \param vectors An initialised matrix, or a null pointer, the * eigenvectors are stored here, in the columns. * \param solvemethod The method to solve the linear system, if \c * mode is 3, i.e. the shift and invert mode is used. * Possible values: * \clist * \cli IGRAPH_SPARSEMAT_SOLVE_LU * The linear system is solved using LU decomposition. * \cli IGRAPH_SPARSEMAT_SOLVE_QR * The linear system is solved using QR decomposition. * \endclist * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_arpack_rssolve(const igraph_sparsemat_t *A, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_sparsemat_solve_t solvemethod) { int n=(int) igraph_sparsemat_nrow(A); if (n != igraph_sparsemat_ncol(A)) { IGRAPH_ERROR("Non-square matrix for ARPACK", IGRAPH_NONSQUARE); } options->n=n; if (options->mode==1) { IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_sparsemat_arpack_multiply, (void*) A, options, storage, values, vectors)); } else if (options->mode==3) { igraph_real_t sigma=options->sigma; igraph_sparsemat_t OP, eye; igraph_sparsemat_symbolic_t symb; igraph_sparsemat_numeric_t num; igraph_i_sparsemat_arpack_rssolve_data_t data; /*-----------------------------------*/ /* We need to factor the (A-sigma*I) */ /*-----------------------------------*/ /* Create (A-sigma*I) */ IGRAPH_CHECK(igraph_sparsemat_eye(&eye, /*n=*/ n, /*nzmax=*/ n, /*value=*/ -sigma, /*compress=*/ 1)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &eye); IGRAPH_CHECK(igraph_sparsemat_add(/*A=*/ A, /*B=*/ &eye, /*alpha=*/ 1.0, /*beta=*/ 1.0, /*res=*/ &OP)); igraph_sparsemat_destroy(&eye); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_sparsemat_destroy, &OP); if (solvemethod==IGRAPH_SPARSEMAT_SOLVE_LU) { /* Symbolic analysis */ IGRAPH_CHECK(igraph_sparsemat_symblu(/*order=*/ 0, &OP, &symb)); IGRAPH_FINALLY(igraph_sparsemat_symbolic_destroy, &symb); /* Numeric LU factorization */ IGRAPH_CHECK(igraph_sparsemat_lu(&OP, &symb, &num, /*tol=*/ 0)); IGRAPH_FINALLY(igraph_sparsemat_numeric_destroy, &num); } else if (solvemethod==IGRAPH_SPARSEMAT_SOLVE_QR) { /* Symbolic analysis */ IGRAPH_CHECK(igraph_sparsemat_symbqr(/*order=*/ 0, &OP, &symb)); IGRAPH_FINALLY(igraph_sparsemat_symbolic_destroy, &symb); /* Numeric QR factorization */ IGRAPH_CHECK(igraph_sparsemat_qr(&OP, &symb, &num)); IGRAPH_FINALLY(igraph_sparsemat_numeric_destroy, &num); } data.dis=&symb; data.din=# data.tol=options->tol; data.method=solvemethod; IGRAPH_CHECK(igraph_arpack_rssolve(igraph_i_sparsemat_arpack_solve, (void*) &data, options, storage, values, vectors)); igraph_sparsemat_numeric_destroy(&num); igraph_sparsemat_symbolic_destroy(&symb); igraph_sparsemat_destroy(&OP); IGRAPH_FINALLY_CLEAN(3); } return 0; } /** * \function igraph_sparsemat_arpack_rnsolve * Eigenvalues and eigenvectors of a nonsymmetric sparse matrix via ARPACK * * Eigenvalues and/or eigenvectors of a nonsymmetric sparse matrix. * \param A The input matrix, in column-compressed mode. * \param options ARPACK options, it is passed to \ref * igraph_arpack_rnsolve(). See also \ref igraph_arpack_options_t * for details. * \param storage Storage for ARPACK, this is passed to \ref * igraph_arpack_rnsolve(). See \ref igraph_arpack_storage_t for * details. * \param values An initialized matrix, or a null pointer. If not a * null pointer, then the eigenvalues are stored here, the first * column is the real part, the second column is the imaginary * part. * \param vectors An initialized matrix, or a null pointer. If not a * null pointer, then the eigenvectors are stored here, please see * \ref igraph_arpack_rnsolve() for the format. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_arpack_rnsolve(const igraph_sparsemat_t *A, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_matrix_t *values, igraph_matrix_t *vectors) { int n=(int) igraph_sparsemat_nrow(A); if (n != igraph_sparsemat_ncol(A)) { IGRAPH_ERROR("Non-square matrix for ARPACK", IGRAPH_NONSQUARE); } options->n=n; return igraph_arpack_rnsolve(igraph_i_sparsemat_arpack_multiply, (void*) A, options, storage, values, vectors); } /** * \function igraph_sparsemat_symbqr * Symbolic QR decomposition * * QR decomposition of sparse matrices involves two steps, the first * is calling this function, and then \ref * igraph_sparsemat_qr(). * \param order The ordering to use: 0 means natural ordering, 1 means * minimum degree ordering of A+A', 2 is minimum degree ordering of * A'A after removing the dense rows from A, and 3 is the minimum * degree ordering of A'A. * \param A The input matrix, in column-compressed format. * \param dis The result of the symbolic analysis is stored here. Once * not needed anymore, it must be destroyed by calling \ref * igraph_sparsemat_symbolic_destroy(). * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_symbqr(long int order, const igraph_sparsemat_t *A, igraph_sparsemat_symbolic_t *dis) { dis->symbolic = cs_sqr((int) order, A->cs, /*qr=*/ 1); if (!dis->symbolic) { IGRAPH_ERROR("Cannot do symbolic QR decomposition", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_symblu * Symbolic LU decomposition * * LU decomposition of sparse matrices involves two steps, the first * is calling this function, and then \ref igraph_sparsemat_lu(). * \param order The ordering to use: 0 means natural ordering, 1 means * minimum degree ordering of A+A', 2 is minimum degree ordering of * A'A after removing the dense rows from A, and 3 is the minimum * degree ordering of A'A. * \param A The input matrix, in column-compressed format. * \param dis The result of the symbolic analysis is stored here. Once * not needed anymore, it must be destroyed by calling \ref * igraph_sparsemat_symbolic_destroy(). * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_symblu(long int order, const igraph_sparsemat_t *A, igraph_sparsemat_symbolic_t *dis) { dis->symbolic = cs_sqr((int) order, A->cs, /*qr=*/ 0); if (!dis->symbolic) { IGRAPH_ERROR("Cannot do symbolic LU decomposition", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_lu * LU decomposition of a sparse matrix * * Performs numeric sparse LU decomposition of a matrix. * \param A The input matrix, in column-compressed format. * \param dis The symbolic analysis for LU decomposition, coming from * a call to the \ref igraph_sparsemat_symblu() function. * \param din The numeric decomposition, the result is stored here. It * can be used to solve linear systems with changing right hand * side vectors, by calling \ref igraph_sparsemat_luresol(). Once * not needed any more, it must be destroyed by calling \ref * igraph_sparsemat_symbolic_destroy() on it. * \param tol The tolerance for the numeric LU decomposition. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_lu(const igraph_sparsemat_t *A, const igraph_sparsemat_symbolic_t *dis, igraph_sparsemat_numeric_t *din, double tol) { din->numeric=cs_lu(A->cs, dis->symbolic, tol); if (!din->numeric) { IGRAPH_ERROR("Cannot do LU decomposition", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_qr * QR decomposition of a sparse matrix * * Numeric QR decomposition of a sparse matrix. * \param A The input matrix, in column-compressed format. * \param dis The result of the symbolic QR analysis, from the * function \ref igraph_sparsemat_symbqr(). * \param din The result of the decomposition is stored here, it can * be used to solve many linear systems with the same coefficient * matrix and changing right hand sides, using the \ref * igraph_sparsemat_qrresol() function. Once not needed any more, * one should call \ref igraph_sparsemat_numeric_destroy() on it to * free the allocated memory. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_qr(const igraph_sparsemat_t *A, const igraph_sparsemat_symbolic_t *dis, igraph_sparsemat_numeric_t *din) { din->numeric=cs_qr(A->cs, dis->symbolic); if (!din->numeric) { IGRAPH_ERROR("Cannot do QR decomposition", IGRAPH_FAILURE); } return 0; } /** * \function igraph_sparsemat_luresol * Solve linear system using a precomputed LU decomposition * * Uses the LU decomposition of a matrix to solve linear systems. * \param dis The symbolic analysis of the coefficient matrix, the * result of \ref igraph_sparsemat_symblu(). * \param din The LU decomposition, the result of a call to \ref * igraph_sparsemat_lu(). * \param b A vector that defines the right hand side of the linear * equation system. * \param res An initialized vector, the solution of the linear system * is stored here. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_luresol(const igraph_sparsemat_symbolic_t *dis, const igraph_sparsemat_numeric_t *din, const igraph_vector_t *b, igraph_vector_t *res) { int n=din->numeric->L->n; igraph_real_t *workspace; if (res != b) { IGRAPH_CHECK(igraph_vector_update(res, b)); } workspace=igraph_Calloc(n, igraph_real_t); if (!workspace) { IGRAPH_ERROR("Cannot LU (re)solve sparse matrix", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, workspace); if (!cs_ipvec(din->numeric->pinv, VECTOR(*res), workspace, n)) { IGRAPH_ERROR("Cannot LU (re)solve sparse matrix", IGRAPH_FAILURE); } if (!cs_lsolve(din->numeric->L, workspace)) { IGRAPH_ERROR("Cannot LU (re)solve sparse matrix", IGRAPH_FAILURE); } if (!cs_usolve(din->numeric->U, workspace)) { IGRAPH_ERROR("Cannot LU (re)solve sparse matrix", IGRAPH_FAILURE); } if (!cs_ipvec(dis->symbolic->q, workspace, VECTOR(*res), n)) { IGRAPH_ERROR("Cannot LU (re)solve sparse matrix", IGRAPH_FAILURE); } igraph_Free(workspace); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_sparsemat_qrresol * Solve a linear system using a precomputed QR decomposition * * Solves a linear system using a QR decomposition of its coefficient * matrix. * \param dis Symbolic analysis of the coefficient matrix, the result * of \ref igraph_sparsemat_symbqr(). * \param din The QR decomposition of the coefficient matrix, the * result of \ref igraph_sparsemat_qr(). * \param b Vector, giving the right hand side of the linear equation * system. * \param res An initialized vector, the solution is stored here. It * is resized as needed. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_qrresol(const igraph_sparsemat_symbolic_t *dis, const igraph_sparsemat_numeric_t *din, const igraph_vector_t *b, igraph_vector_t *res) { int n=din->numeric->L->n; igraph_real_t *workspace; int k; if (res != b) { IGRAPH_CHECK(igraph_vector_update(res, b)); } workspace=igraph_Calloc(dis->symbolic ? dis->symbolic->m2 : 1, igraph_real_t); if (!workspace) { IGRAPH_ERROR("Cannot QR (re)solve sparse matrix", IGRAPH_FAILURE); } IGRAPH_FINALLY(igraph_free, workspace); if (!cs_ipvec(dis->symbolic->pinv, VECTOR(*res), workspace, n)) { IGRAPH_ERROR("Cannot QR (re)solve sparse matrix", IGRAPH_FAILURE); } for (k=0; knumeric->L, k, din->numeric->B[k], workspace)) { IGRAPH_ERROR("Cannot QR (re)solve sparse matrix", IGRAPH_FAILURE); } } if (!cs_usolve(din->numeric->U, workspace)) { IGRAPH_ERROR("Cannot QR (re)solve sparse matrix", IGRAPH_FAILURE); } if (!cs_ipvec(dis->symbolic->q, workspace, VECTOR(*res), n)) { IGRAPH_ERROR("Cannot QR (re)solve sparse matrix", IGRAPH_FAILURE); } igraph_Free(workspace); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_sparsemat_symbolic_destroy * Deallocate memory for a symbolic decomposition * * Frees the memory allocated by \ref igraph_sparsemat_symbqr() or * \ref igraph_sparsemat_symblu(). * \param dis The symbolic analysis. * * Time complexity: O(1). */ void igraph_sparsemat_symbolic_destroy(igraph_sparsemat_symbolic_t *dis) { cs_sfree(dis->symbolic); dis->symbolic=0; } /** * \function igraph_sparsemat_numeric_destroy * Deallocate memory for a numeric decomposition * * Frees the memoty allocated by \ref igraph_sparsemat_qr() or \ref * igraph_sparsemat_lu(). * \param din The LU or QR decomposition. * * Time complexity: O(1). */ void igraph_sparsemat_numeric_destroy(igraph_sparsemat_numeric_t *din) { cs_nfree(din->numeric); din->numeric=0; } /** * \function igraph_matrix_as_sparsemat * Convert a dense matrix to a sparse matrix * * \param res An uninitialized sparse matrix, the result is stored * here. * \param mat The dense input matrix. * \param tol Real scalar, the tolerance. Values closer than \p tol to * zero are considered as zero, and will not be included in the * sparse matrix. * \return Error code. * * Time complexity: O(mn), the number of elements in the dense * matrix. */ int igraph_matrix_as_sparsemat(igraph_sparsemat_t *res, const igraph_matrix_t *mat, igraph_real_t tol) { int nrow=(int) igraph_matrix_nrow(mat); int ncol=(int) igraph_matrix_ncol(mat); int i, j, nzmax=0; for (i=0; i tol) { nzmax++; } } } IGRAPH_CHECK(igraph_sparsemat_init(res, nrow, ncol, nzmax)); for (i=0; i tol) { IGRAPH_CHECK(igraph_sparsemat_entry(res, i, j, MATRIX(*mat, i, j))); } } } return 0; } int igraph_i_sparsemat_as_matrix_cc(igraph_matrix_t *res, const igraph_sparsemat_t *spmat) { int nrow=(int) igraph_sparsemat_nrow(spmat); int ncol=(int) igraph_sparsemat_ncol(spmat); int *p=spmat->cs->p; int *i=spmat->cs->i; igraph_real_t *x=spmat->cs->x; int nzmax=spmat->cs->nzmax; int from=0, to=0; IGRAPH_CHECK(igraph_matrix_resize(res, nrow, ncol)); igraph_matrix_null(res); while (*p < nzmax) { while (to < *(p+1)) { MATRIX(*res, *i, from) += *x; to++; i++; x++; } from++; p++; } return 0; } int igraph_i_sparsemat_as_matrix_triplet(igraph_matrix_t *res, const igraph_sparsemat_t *spmat) { int nrow=(int) igraph_sparsemat_nrow(spmat); int ncol=(int) igraph_sparsemat_ncol(spmat); int *i=spmat->cs->p; int *j=spmat->cs->i; igraph_real_t *x=spmat->cs->x; int nz=spmat->cs->nz; int e; IGRAPH_CHECK(igraph_matrix_resize(res, nrow, ncol)); igraph_matrix_null(res); for (e=0; ecs->nz < 0) { return(igraph_i_sparsemat_as_matrix_cc(res, spmat)); } else { return(igraph_i_sparsemat_as_matrix_triplet(res, spmat)); } } /** * \function igraph_sparsemat_max * Maximum of a sparse matrix * * \param A The input matrix, column-compressed. * \return The maximum in the input matrix, or \c IGRAPH_NEGINFINITY * if the matrix has zero elements. * * Time complexity: TODO. */ igraph_real_t igraph_sparsemat_max(igraph_sparsemat_t *A) { int i, n; igraph_real_t *ptr; igraph_real_t res; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); ptr=A->cs->x; n = A->cs->nz==-1 ? A->cs->p[A->cs->n] : A->cs->nz; if (n==0) { return IGRAPH_NEGINFINITY; } res = *ptr; for (i=1; i res) { res=*ptr; } } return res; } /* TODO: CC matrix don't actually need _dupl, because the elements are right beside each other. Same for max and minmax. */ /** * \function igraph_sparsemat_min * Minimum of a sparse matrix * * \param A The input matrix, column-compressed. * \return The minimum in the input matrix, or \c IGRAPH_POSINFINITY * if the matrix has zero elements. * * Time complexity: TODO. */ igraph_real_t igraph_sparsemat_min(igraph_sparsemat_t *A) { int i, n; igraph_real_t *ptr; igraph_real_t res; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); ptr=A->cs->x; n = A->cs->nz==-1 ? A->cs->p[A->cs->n] : A->cs->nz; if (n==0) { return IGRAPH_POSINFINITY; } res = *ptr; for (i=1; ics->x; n = A->cs->nz==-1 ? A->cs->p[A->cs->n] : A->cs->nz; if (n==0) { *min=IGRAPH_POSINFINITY; *max=IGRAPH_NEGINFINITY; return 0; } *min = *max = *ptr; for (i=1; i *max) { *max=*ptr; } else if (*ptr < *min) { *min=*ptr; } } return 0; } /** * \function igraph_sparsemat_count_nonzero * Count nonzero elements of a sparse matrix * * \param A The input matrix, column-compressed. * \return Error code. * * Time complexity: TODO. */ long int igraph_sparsemat_count_nonzero(igraph_sparsemat_t *A) { int i, n; int res=0; igraph_real_t *ptr; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); ptr=A->cs->x; n = A->cs->nz==-1 ? A->cs->p[A->cs->n] : A->cs->nz; if (n==0) { return 0; } for (i=0; ics->x; n = A->cs->nz==-1 ? A->cs->p[A->cs->n] : A->cs->nz; if (n==0) { return 0; } for (i=0; i tol) { res++; } } return res; } int igraph_i_sparsemat_rowsums_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pi=A->cs->i; double *px=A->cs->x; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_null(res); for (i=0; ics->nz; i++, pi++, px++) { VECTOR(*res)[ *pi ] += *px; } return 0; } int igraph_i_sparsemat_rowsums_cc(const igraph_sparsemat_t *A, igraph_vector_t *res) { int ne=A->cs->p[A->cs->n]; double *px=A->cs->x; int *pi=A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_null(res); for (; pi < A->cs->i+ne; pi++, px++) { VECTOR(*res)[ *pi ] += *px; } return 0; } /** * \function igraph_sparsemat_rowsums * Row-wise sums. * * \param A The input matrix, in triplet or column-compressed format. * \param res An initialized vector, the result is stored here. It * will be resized as needed. * \return Error code. * * Time complexity: O(nz), the number of non-zero elements. */ int igraph_sparsemat_rowsums(const igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_rowsums_triplet(A, res); } else { return igraph_i_sparsemat_rowsums_cc(A, res); } } int igraph_i_sparsemat_rowmins_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pi=A->cs->i; double *px=A->cs->x; double inf=IGRAPH_INFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_fill(res, inf); for (i=0; ics->nz; i++, pi++, px++) { if (*px < VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; } } return 0; } int igraph_i_sparsemat_rowmins_cc(igraph_sparsemat_t *A, igraph_vector_t *res) { int ne; double *px; int *pi; double inf=IGRAPH_INFINITY; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); ne = A->cs->p[A->cs->n]; px = A->cs->x; pi = A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_fill(res, inf); for (; pi < A->cs->i+ne; pi++, px++) { if (*px < VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; } } return 0; } int igraph_sparsemat_rowmins(igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_rowmins_triplet(A, res); } else { return igraph_i_sparsemat_rowmins_cc(A, res); } } int igraph_i_sparsemat_rowmaxs_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pi=A->cs->i; double *px=A->cs->x; double inf=IGRAPH_NEGINFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_fill(res, inf); for (i=0; ics->nz; i++, pi++, px++) { if (*px > VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; } } return 0; } int igraph_i_sparsemat_rowmaxs_cc(igraph_sparsemat_t *A, igraph_vector_t *res) { int ne; double *px; int *pi; double inf=IGRAPH_NEGINFINITY; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); ne = A->cs->p[A->cs->n]; px = A->cs->x; pi = A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); igraph_vector_fill(res, inf); for (; pi < A->cs->i+ne; pi++, px++) { if (*px > VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; } } return 0; } int igraph_sparsemat_rowmaxs(igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_rowmaxs_triplet(A, res); } else { return igraph_i_sparsemat_rowmaxs_cc(A, res); } } int igraph_i_sparsemat_colmins_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pp=A->cs->p; double *px=A->cs->x; double inf=IGRAPH_INFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->n)); igraph_vector_fill(res, inf); for (i=0; ics->nz; i++, pp++, px++) { if (*px < VECTOR(*res)[ *pp ]) { VECTOR(*res)[ *pp ] = *px; } } return 0; } int igraph_i_sparsemat_colmins_cc(igraph_sparsemat_t *A, igraph_vector_t *res) { int n; double *px; int *pp; int *pi; double *pr; double inf=IGRAPH_INFINITY; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); n = A->cs->n; px = A->cs->x; pp = A->cs->p; pi = A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, n)); igraph_vector_fill(res, inf); pr=VECTOR(*res); for (; pp < A->cs->p + n; pp++, pr++) { for (; pi < A->cs->i + *(pp+1); pi++, px++) { if (*px < *pr) { *pr = *px; } } } return 0; } int igraph_sparsemat_colmins(igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_colmins_triplet(A, res); } else { return igraph_i_sparsemat_colmins_cc(A, res); } } int igraph_i_sparsemat_colmaxs_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pp=A->cs->p; double *px=A->cs->x; double inf=IGRAPH_NEGINFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->n)); igraph_vector_fill(res, inf); for (i=0; ics->nz; i++, pp++, px++) { if (*px > VECTOR(*res)[ *pp ]) { VECTOR(*res)[ *pp ] = *px; } } return 0; } int igraph_i_sparsemat_colmaxs_cc(igraph_sparsemat_t *A, igraph_vector_t *res) { int n; double *px; int *pp; int *pi; double *pr; double inf=IGRAPH_NEGINFINITY; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); n = A->cs->n; px = A->cs->x; pp = A->cs->p; pi = A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, n)); igraph_vector_fill(res, inf); pr=VECTOR(*res); for (; pp < A->cs->p + n; pp++, pr++) { for (; pi < A->cs->i + *(pp+1); pi++, px++) { if (*px > *pr) { *pr = *px; } } } return 0; } int igraph_sparsemat_colmaxs(igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_colmaxs_triplet(A, res); } else { return igraph_i_sparsemat_colmaxs_cc(A, res); } } int igraph_i_sparsemat_which_min_rows_triplet(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { int i; int *pi = A->cs->i; int *pp = A->cs->p; double *px = A->cs->x; double inf = IGRAPH_INFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); IGRAPH_CHECK(igraph_vector_int_resize(pos, A->cs->m)); igraph_vector_fill(res, inf); igraph_vector_int_null(pos); for (i = 0; i < A->cs->nz; i++, pi++, px++, pp++) { if (*px < VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; VECTOR(*pos)[ *pi ] = *pp; } } return 0; } int igraph_i_sparsemat_which_min_rows_cc(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { int n; double *px; int *pp; int *pi; double inf = IGRAPH_INFINITY; int j; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); n = A->cs->n; px = A->cs->x; pp = A->cs->p; pi = A->cs->i; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->m)); IGRAPH_CHECK(igraph_vector_int_resize(pos, A->cs->m)); igraph_vector_fill(res, inf); igraph_vector_int_null(pos); for (j=0; pp < A->cs->p + n; pp++, j++) { for (; pi < A->cs->i + *(pp+1); pi++, px++) { if (*px < VECTOR(*res)[ *pi ]) { VECTOR(*res)[ *pi ] = *px; VECTOR(*pos)[ *pi ] = j; } } } return 0; } int igraph_sparsemat_which_min_rows(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_which_min_rows_triplet(A, res, pos); } else { return igraph_i_sparsemat_which_min_rows_cc(A, res, pos); } } int igraph_i_sparsemat_which_min_cols_triplet(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { int i; int *pi = A->cs->i; int *pp = A->cs->p; double *px = A->cs->x; double inf = IGRAPH_INFINITY; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->n)); IGRAPH_CHECK(igraph_vector_int_resize(pos, A->cs->n)); igraph_vector_fill(res, inf); igraph_vector_int_null(pos); for (i = 0; i < A->cs->nz; i++, pi++, pp++, px++) { if (*px < VECTOR(*res)[ *pp ]) { VECTOR(*res)[ *pp ] = *px; VECTOR(*pos)[ *pp ] = *pi; } } return 0; } int igraph_i_sparsemat_which_min_cols_cc(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { int n, j, p; double *px; double *pr; int *ppos; double inf=IGRAPH_INFINITY; IGRAPH_CHECK(igraph_sparsemat_dupl(A)); n = A->cs->n; px = A->cs->x; IGRAPH_CHECK(igraph_vector_resize(res, n)); igraph_vector_fill(res, inf); pr=VECTOR(*res); IGRAPH_CHECK(igraph_vector_int_resize(pos, n)); igraph_vector_int_null(pos); ppos=VECTOR(*pos); for (j = 0; j < A->cs->n; j++, pr++, ppos++) { for (p = A->cs->p[j]; p < A->cs->p[j+1]; p++, px++) { if (*px < *pr) { *pr = *px; *ppos = A->cs->i[p]; } } } return 0; } int igraph_sparsemat_which_min_cols(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_which_min_cols_triplet(A, res, pos); } else { return igraph_i_sparsemat_which_min_cols_cc(A, res, pos); } } int igraph_i_sparsemat_colsums_triplet(const igraph_sparsemat_t *A, igraph_vector_t *res) { int i; int *pp=A->cs->p; double *px=A->cs->x; IGRAPH_CHECK(igraph_vector_resize(res, A->cs->n)); igraph_vector_null(res); for (i=0; ics->nz; i++, pp++, px++) { VECTOR(*res)[ *pp ] += *px; } return 0; } int igraph_i_sparsemat_colsums_cc(const igraph_sparsemat_t *A, igraph_vector_t *res) { int n=A->cs->n; double *px=A->cs->x; int *pp=A->cs->p; int *pi=A->cs->i; double *pr; IGRAPH_CHECK(igraph_vector_resize(res, n)); igraph_vector_null(res); pr=VECTOR(*res); for (; pp < A->cs->p + n; pp++, pr++) { for (; pi < A->cs->i + *(pp+1); pi++, px++) { *pr += *px; } } return 0; } /** * \function igraph_sparsemat_colsums * Column-wise sums * * \param A The input matrix, in triplet or column-compressed format. * \param res An initialized vector, the result is stored here. It * will be resized as needed. * \return Error code. * * Time complexity: O(nz) for triplet matrices, O(nz+n) for * column-compressed ones, nz is the number of non-zero elements, n is * the number of columns. */ int igraph_sparsemat_colsums(const igraph_sparsemat_t *A, igraph_vector_t *res) { if (igraph_sparsemat_is_triplet(A)) { return igraph_i_sparsemat_colsums_triplet(A, res); } else { return igraph_i_sparsemat_colsums_cc(A, res); } } /** * \function igraph_sparsemat_scale * Scale a sparse matrix * * Multiplies all elements of a sparse matrix, by the given scalar. * \param A The input matrix. * \param by The scaling factor. * \return Error code. * * Time complexity: O(nz), the number of non-zero elements in the * matrix. */ int igraph_sparsemat_scale(igraph_sparsemat_t *A, igraph_real_t by) { double *px = A->cs->x; int n = A->cs->nz == -1 ? A->cs->p[A->cs->n] : A->cs->nz; double *stop=px+n; for (; px < stop; px++) { *px *= by; } return 0; } /** * \function igraph_sparsemat_add_rows * Add rows to a sparse matrix * * The current matrix elements are retained and all elements in the * new rows are zero. * \param A The input matrix, in triplet or column-compressed format. * \param n The number of rows to add. * \return Error code. * * Time complexity: O(1). */ int igraph_sparsemat_add_rows(igraph_sparsemat_t *A, long int n) { A->cs->m += n; return 0; } /** * \function igraph_sparsemat_add_cols * Add columns to a sparse matrix * * The current matrix elements are retained, and all elements in the * new columns are zero. * \param A The input matrix, in triplet or column-compressed format. * \param n The number of columns to add. * \return Error code. * * Time complexity: TODO. */ int igraph_sparsemat_add_cols(igraph_sparsemat_t *A, long int n) { if (igraph_sparsemat_is_triplet(A)) { A->cs->n += n; } else { int *newp=realloc(A->cs->p, sizeof(int) * (size_t) (A->cs->n + n + 1)); int i; if (!newp) { IGRAPH_ERROR("Cannot add columns to sparse matrix", IGRAPH_ENOMEM); } if (newp != A->cs->p) { A->cs->p=newp; } for (i=A->cs->n+1; ics->n + n + 1; i++) { A->cs->p[i]=A->cs->p[i-1]; } A->cs->n += n; } return 0; } /** * \function igraph_sparsemat_resize * Resize a sparse matrix * * This function resizes a sparse matrix. The resized sparse matrix * will be empty. * * \param A The initialized sparse matrix to resize. * \param nrow The new number of rows. * \param ncol The new number of columns. * \param nzmax The new maximum number of elements. * \return Error code. * * Time complexity: O(nzmax), the maximum number of non-zero elements. */ int igraph_sparsemat_resize(igraph_sparsemat_t *A, long int nrow, long int ncol, int nzmax) { if (A->cs->nz < 0) { igraph_sparsemat_t tmp; IGRAPH_CHECK(igraph_sparsemat_init(&tmp, (int) nrow, (int) ncol, nzmax)); igraph_sparsemat_destroy(A); *A = tmp; } else { IGRAPH_CHECK(igraph_sparsemat_realloc(A, nzmax)); A->cs->m = (int) nrow; A->cs->n = (int) ncol; A->cs->nz = 0; } return 0; } int igraph_sparsemat_nonzero_storage(const igraph_sparsemat_t *A) { if (A->cs->nz < 0) { return A->cs->p[A->cs->n]; } else { return A->cs->nz; } } int igraph_sparsemat_getelements(const igraph_sparsemat_t *A, igraph_vector_int_t *i, igraph_vector_int_t *j, igraph_vector_t *x) { int nz=A->cs->nz; if (nz < 0) { nz=A->cs->p[A->cs->n]; IGRAPH_CHECK(igraph_vector_int_resize(i, nz)); IGRAPH_CHECK(igraph_vector_int_resize(j, A->cs->n+1)); IGRAPH_CHECK(igraph_vector_resize(x, nz)); memcpy(VECTOR(*i), A->cs->i, (size_t) nz * sizeof(int)); memcpy(VECTOR(*j), A->cs->p, (size_t) (A->cs->n+1) * sizeof(int)); memcpy(VECTOR(*x), A->cs->x, (size_t) nz * sizeof(igraph_real_t)); } else { IGRAPH_CHECK(igraph_vector_int_resize(i, nz)); IGRAPH_CHECK(igraph_vector_int_resize(j, nz)); IGRAPH_CHECK(igraph_vector_resize(x, nz)); memcpy(VECTOR(*i), A->cs->i, (size_t) nz * sizeof(int)); memcpy(VECTOR(*j), A->cs->p, (size_t) nz * sizeof(int)); memcpy(VECTOR(*x), A->cs->x, (size_t) nz * sizeof(igraph_real_t)); } return 0; } int igraph_sparsemat_scale_rows(igraph_sparsemat_t *A, const igraph_vector_t *fact) { int *i=A->cs->i; igraph_real_t *x=A->cs->x; int no_of_edges=A->cs->nz < 0 ? A->cs->p[A->cs->n] : A->cs->nz; int e; for (e=0; ecs->i; igraph_real_t *x=A->cs->x; int no_of_edges=A->cs->p[A->cs->n]; int e; int c=0; /* actual column */ for (e=0; ecs->n && A->cs->p[c+1] == e) { c++; } f=VECTOR(*fact)[c]; (*x) *= f; } return 0; } int igraph_i_sparsemat_scale_cols_triplet(igraph_sparsemat_t *A, const igraph_vector_t *fact) { int *j=A->cs->p; igraph_real_t *x=A->cs->x; int no_of_edges=A->cs->nz; int e; for (e=0; ecs->nz < 0) { return igraph_i_sparsemat_scale_cols_cc(A, fact); } else { return igraph_i_sparsemat_scale_cols_triplet(A, fact); } } int igraph_sparsemat_multiply_by_dense(const igraph_sparsemat_t *A, const igraph_matrix_t *B, igraph_matrix_t *res) { int m=(int) igraph_sparsemat_nrow(A); int n=(int) igraph_sparsemat_ncol(A); int p=(int) igraph_matrix_ncol(B); int i; if (igraph_matrix_nrow(B) != n) { IGRAPH_ERROR("Invalid dimensions in sparse-dense matrix product", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(res, m, p)); igraph_matrix_null(res); for (i=0; ics, &MATRIX(*B, 0, i), &MATRIX(*res, 0, i)))) { IGRAPH_ERROR("Cannot perform sparse-dense matrix multiplication", IGRAPH_FAILURE); } } return 0; } int igraph_sparsemat_dense_multiply(const igraph_matrix_t *A, const igraph_sparsemat_t *B, igraph_matrix_t *res) { int m=(int) igraph_matrix_nrow(A); int n=(int) igraph_matrix_ncol(A); int p=(int) igraph_sparsemat_ncol(B); int r, c; int *Bp=B->cs->p; if (igraph_sparsemat_nrow(B) != n) { IGRAPH_ERROR("Invalid dimensions in dense-sparse matrix product", IGRAPH_EINVAL); } if (!igraph_sparsemat_is_cc(B)) { IGRAPH_ERROR("Dense-sparse product is only implemented for " "column-compressed sparse matrices", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(res, m, p)); igraph_matrix_null(res); for (c=0; ccs->i[idx]) * B->cs->x[idx]; idx++; } } Bp++; } return 0; } int igraph_i_sparsemat_view(igraph_sparsemat_t *A, int nzmax, int m, int n, int *p, int *i, double *x, int nz) { A->cs = cs_calloc(1, sizeof(cs_di)); A->cs->nzmax = nzmax; A->cs->m = m; A->cs->n = n; A->cs->p = p; A->cs->i = i; A->cs->x = x; A->cs->nz = nz; return 0; } int igraph_sparsemat_sort(const igraph_sparsemat_t *A, igraph_sparsemat_t *sorted) { igraph_sparsemat_t tmp; IGRAPH_CHECK(igraph_sparsemat_transpose(A, &tmp, /*values=*/ 1)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &tmp); IGRAPH_CHECK(igraph_sparsemat_transpose(&tmp, sorted, /*values=*/ 1)); igraph_sparsemat_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_sparsemat_getelements_sorted(const igraph_sparsemat_t *A, igraph_vector_int_t *i, igraph_vector_int_t *j, igraph_vector_t *x) { if (A->cs->nz < 0) { igraph_sparsemat_t tmp; IGRAPH_CHECK(igraph_sparsemat_sort(A, &tmp)); IGRAPH_FINALLY(igraph_sparsemat_destroy, &tmp); IGRAPH_CHECK(igraph_sparsemat_getelements(&tmp, i, j, x)); igraph_sparsemat_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); } else { IGRAPH_CHECK(igraph_sparsemat_getelements(A, i, j, x)); } return 0; } int igraph_sparsemat_nzmax(const igraph_sparsemat_t *A) { return A->cs->nzmax; } int igraph_sparsemat_neg(igraph_sparsemat_t *A) { int i, nz=A->cs->nz == -1 ? A->cs->p[A->cs->n] : A->cs->nz; igraph_real_t *px=A->cs->x; for (i=0; imat=sparsemat; igraph_sparsemat_iterator_reset(it); return 0; } int igraph_sparsemat_iterator_reset(igraph_sparsemat_iterator_t *it) { it->pos=0; if (!igraph_sparsemat_is_triplet(it->mat)) { it->col=0; while (it->col < it->mat->cs->n && it->mat->cs->p[it->col+1] == it->pos) { it->col ++; } } return 0; } igraph_bool_t igraph_sparsemat_iterator_end(const igraph_sparsemat_iterator_t *it) { int nz=it->mat->cs->nz == -1 ? it->mat->cs->p[it->mat->cs->n] : it->mat->cs->nz; return it->pos >= nz; } int igraph_sparsemat_iterator_row(const igraph_sparsemat_iterator_t *it) { return it->mat->cs->i[it->pos]; } int igraph_sparsemat_iterator_col(const igraph_sparsemat_iterator_t *it) { if (igraph_sparsemat_is_triplet(it->mat)) { return it->mat->cs->p[it->pos]; } else { return it->col; } } igraph_real_t igraph_sparsemat_iterator_get(const igraph_sparsemat_iterator_t *it) { return it->mat->cs->x[it->pos]; } int igraph_sparsemat_iterator_next(igraph_sparsemat_iterator_t *it) { it->pos += 1; while (it->col < it->mat->cs->n && it->mat->cs->p[it->col+1] == it->pos) { it->col++; } return it->pos; } int igraph_sparsemat_iterator_idx(const igraph_sparsemat_iterator_t *it) { return it->pos; } igraph/src/scg_headers.h0000644000175100001440000001113113431000472014740 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * This file contains the headers of the library SCGlib. * For use with R software define * the constant R_COMPIL and refer to the R documentation to compile * a dynamic library. The scg_r_wrapper function should be useful. */ #ifndef SCG_HEADERS_H #define SCG_HEADERS_H #include #include #include "igraph_types.h" #include "igraph_vector.h" typedef struct ind_val { int ind; igraph_real_t val; } igraph_i_scg_indval_t; int igraph_i_compare_ind_val(const void *a, const void *b); typedef struct groups{ int ind; int n; int* gr; } igraph_i_scg_groups_t; /*------------------------------------------------- ------------DEFINED IN scg_approximate_methods.c--- ---------------------------------------------------*/ int igraph_i_breaks_computation(const igraph_vector_t *v, igraph_vector_t *breaks, int nb, int method); int igraph_i_intervals_plus_kmeans(const igraph_vector_t *v, int *gr, int n, int n_interv, int maxiter); int igraph_i_intervals_method(const igraph_vector_t *v, int *gr, int n, int n_interv); /*------------------------------------------------- ------------DEFINED IN scg_optimal_method.c-------- ---------------------------------------------------*/ int igraph_i_cost_matrix(igraph_real_t *Cv, const igraph_i_scg_indval_t *vs, int n, int matrix, const igraph_vector_t *ps); int igraph_i_optimal_partition(const igraph_real_t *v, int *gr, int n, int nt, int matrix, const igraph_real_t *p, igraph_real_t *value); /*------------------------------------------------- ------------DEFINED IN scg_kmeans.c---------------- ---------------------------------------------------*/ int igraph_i_kmeans_Lloyd(const igraph_vector_t *x, int n, int p, igraph_vector_t *centers, int k, int *cl, int maxiter); /*------------------------------------------------- ------------DEFINED IN scg_exact_scg.c------------- ---------------------------------------------------*/ int igraph_i_exact_coarse_graining(const igraph_real_t *v, int *gr, int n); /*------------------------------------------------- ------------DEFINED IN scg_utils.c----------------- ---------------------------------------------------*/ int igraph_i_compare_groups(const void *a,const void *b); int igraph_i_compare_real(const void *a, const void *b); int igraph_i_compare_int(const void *a, const void *b); igraph_real_t *igraph_i_real_sym_matrix(int size); #define igraph_i_real_sym_mat_get(S,i,j) S[i+j*(j+1)/2] #define igraph_i_real_sym_mat_set(S,i,j,val) S[i+j*(j+1)/2] = val #define igraph_i_free_real_sym_matrix(S) igraph_Free(S) #endif igraph/src/gengraph_powerlaw.cpp0000644000175100001440000001475613431000472016557 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // Pascalou ... #ifdef pascalou #define my_random() random() #define MY_RAND_MAX 0x7FFFFFFF #else #include "gengraph_definitions.h" #endif #include "gengraph_powerlaw.h" #include #include #include #include "igraph_error.h" namespace gengraph { // Destructor powerlaw::~powerlaw() { delete[] table; if(dt!=NULL) delete[] dt; } // Constructor powerlaw::powerlaw(double _alpha, int _mini, int _maxi) { alpha = _alpha; mini = _mini; maxi = _maxi; if(alpha<=2.0 && maxi<0) igraph_warningf("powerlaw exponent %f should be > 2 when no " "Maximum is specified", __FILE__, __LINE__, -1, alpha); if(alpha<=1.0 && maxi>=0) igraph_warningf("powerlaw exponent %f should be > 1", __FILE__, __LINE__, -1, alpha); if(maxi>=0 && mini>maxi) igraph_warningf("powerlaw max %d should be greater than min %d", __FILE__, __LINE__, -1, maxi, mini); table = new int[POWERLAW_TABLE]; tabulated = 0; dt = NULL; } // Sample int powerlaw::sample() { if(proba_big!=0 && test_proba(proba_big)) return int(floor(0.5+big_sample(random_float()))); int r=my_random(); // table[] contains integer from MY_RAND_MAX downto 0, in blocks. Search block... if(r>(MY_RAND_MAX>>max_dt)) return mini; int k=0; while(k=0) { a=b+1; if(a==tabulated-1) break; r<<=1; r+=random_bit(); } } // Now that we found the good block, run a dichotomy on this block [a,b] while(a=0 && k>maxi)) return 0.0; if(k>=mini+tabulated) return proba_big*(big_inv_sample(double(k)-0.5)-big_inv_sample(double(k)+0.5)); else { double div = table_mul; int prev_pos_in_table = k-mini-1; if(prev_pos_in_table<0) return (double(MY_RAND_MAX)+1.0-double(table[0]>>max_dt))*div; // what block are we in ? int k=0; while(k=mini; ) sum+=double(i)*proba(i); // add proba_big * integral(big_sample(t),t=0..1) if(proba_big!=0) sum += proba_big*((pow(_a+_b,_exp+1.0)-pow(_b,_exp+1.0))/(_a*(_exp+1.0)) +double(mini)-offset-sum); return sum; } // Median. Returns integer Med such that P(X<=Med) >= 1/2 int powerlaw::median() { if(proba_big>0.5) return int(floor(0.5+big_sample(1.0-0.5/proba_big))); double sum = 0.0; int i=mini; while(sum<0.5) sum+=proba(i++); return i-1; } void powerlaw::init_to_offset(double _offset, int _tabulated) { offset = _offset; tabulated = _tabulated; if(maxi>=0 && tabulated > maxi-mini) tabulated=maxi-mini+1; double sum = 0.0; double item = double(tabulated)+offset; // Compute sum of tabulated probabilities for(int i=tabulated; i--; ) sum += pow(item-=1.0, -alpha); // Compute others parameters : proba_big, table_mul, _a, _b, _exp if(maxi>0 && maxi<=mini+tabulated-1) { proba_big = 0; table_mul = inv_RANDMAX; } else { if(maxi<0) _b = 0.0; else _b = pow(double(maxi-mini)+0.5+offset, 1.0-alpha); _a = pow(double(tabulated)-0.5+offset,1.0-alpha) - _b; _exp = 1.0 / (1.0 - alpha); double sum_big = _a*(-_exp); proba_big = sum_big / (sum + sum_big); table_mul = inv_RANDMAX * sum / (sum + sum_big); } // How many delimiters will be necessary for the table ? max_dt = max(0,int(floor(alpha*log(double(tabulated))/log(2.0)))-6); if(dt!=NULL) delete[] dt; dt = new int[max_dt+1]; // Create table as decreasing integers from MY_RAND_MAX+1 (in virtual position -1) down to 0 // Every time the index crosses a delimiter, numbers get doubled. double ssum = 0; double mul = (double(MY_RAND_MAX)+1.0)*pow(2.0,max_dt)/sum; item = double(tabulated)+offset; int k = max_dt; dt[k--]=tabulated-1; for(int i=tabulated; --i>0; ) { table[i] = int(floor(0.5+ssum)); ssum += mul * pow(item-=1.0,-alpha); if(ssum>double(MY_RAND_MAX/2) && k>=0) { while((ssum*=0.5)>double(MY_RAND_MAX/2)) { mul*=0.5; dt[k--]=-1; }; mul*=0.5; dt[k--]=i-1; } } table[0] = int(floor(0.5+ssum)); max_dt = k+1; } void powerlaw::adjust_offset_mean(double _mean, double err, double factor) { // Set two bounds for offset double ol = offset; double oh = offset; if(mean()<_mean) { do { ol = oh; oh *= factor; init_to_offset(oh, tabulated); } while(mean()<_mean); } else { do { oh = ol; ol /= factor; init_to_offset(ol, tabulated); } while(mean()>_mean); } // Now, dichotomy while(fabs(oh-ol) > err*ol) { double oc = sqrt(oh*ol); init_to_offset(oc, tabulated); if(mean()<_mean) ol = oc; else oh = oc; } init_to_offset(sqrt(ol*oh), tabulated); } double powerlaw::init_to_mean(double _mean) { if(maxi>=0 && _mean >= 0.5*double((mini+maxi))) { igraph_errorf("Fatal error in powerlaw::init_to_mean(%f): " "Mean must be in ]min, (min+max)/2[ = ]%d, %d[", __FILE__, __LINE__, IGRAPH_EINVAL, _mean, mini, (mini+maxi)/2); return(-1.0); } init_to_offset(_mean-double(mini), 100); adjust_offset_mean(_mean, 0.01, 2); init_to_offset(offset, POWERLAW_TABLE); double eps = 1.0/(double(POWERLAW_TABLE)); adjust_offset_mean(_mean, eps*eps, 1.01); return offset; } } // namespace gengraph igraph/src/DensityGrid_3d.h0000644000175100001440000000541113431000472015310 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __DENSITY_GRID_H__ #define __DENSITY_GRID_H__ // Compile time adjustable parameters #include using namespace std; #include "drl_layout_3d.h" #include "drl_Node_3d.h" #ifdef MUSE_MPI #include #endif namespace drl3d { class DensityGrid { public: // Methods void Init(); void Subtract(Node &n, bool first_add, bool fine_first_add, bool fineDensity); void Add(Node &n, bool fineDensity ); float GetDensity(float Nx, float Ny, float Nz, bool fineDensity); // Contructor/Destructor DensityGrid() {}; ~DensityGrid(); private: // Private Members void Subtract( Node &N ); void Add( Node &N ); void fineSubtract( Node &N ); void fineAdd( Node &N ); // new dynamic variables -- SBM float (*fall_off)[RADIUS*2+1][RADIUS*2+1]; float (*Density)[GRID_SIZE][GRID_SIZE]; deque* Bins; // old static variables //float fall_off[RADIUS*2+1][RADIUS*2+1]; //float Density[GRID_SIZE][GRID_SIZE]; //deque Bins[GRID_SIZE][GRID_SIZE]; }; } // namespace drl3d #endif // __DENSITY_GRID_H__ igraph/src/adjlist.c0000644000175100001440000006642313431000472014134 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_adjlist.h" #include "igraph_memory.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "config.h" #include /* memset */ #include /** * \section about_adjlists * Sometimes it is easier to work with a graph which is in * adjacency list format: a list of vectors; each vector contains the * neighbor vertices or incident edges of a given vertex. Typically, * this representation is good if we need to iterate over the neighbors * of all vertices many times. E.g. when finding the shortest paths * between every pairs of vertices or calculating closeness centrality * for all the vertices. * * The igraph_adjlist_t stores the adjacency lists * of a graph. After creation it is independent of the original graph, * it can be modified freely with the usual vector operations, the * graph is not affected. E.g. the adjacency list can be used to * rewire the edges of a graph efficiently. If one used the * straightforward \ref igraph_delete_edges() and \ref * igraph_add_edges() combination for this that needs O(|V|+|E|) time * for every single deletion and insertion operation, it is thus very * slow if many edges are rewired. Extracting the graph into an * adjacency list, do all the rewiring operations on the vectors of * the adjacency list and then creating a new graph needs (depending * on how exactly the rewiring is done) typically O(|V|+|E|) time for * the whole rewiring process. * * Lazy adjacency lists are a bit different. When creating a * lazy adjacency list, the neighbors of the vertices are not queried, * only some memory is allocated for the vectors. When \ref * igraph_lazy_adjlist_get() is called for vertex v the first time, * the neighbors of v are queried and stored in a vector of the * adjacency list, so they don't need to be queried again. Lazy * adjacency lists are handy if you have an at least linear operation * (because initialization is generally linear in terms of number of * vertices), but you don't know how many vertices you will visit * during the computation. * * * * \example examples/simple/adjlist.c * */ /** * \function igraph_adjlist_init * Initialize an adjacency list of vertices from a given graph * * Create a list of vectors containing the neighbors of all vertices * in a graph. The adjacency list is independent of the graph after * creation, e.g. the graph can be destroyed and modified, the * adjacency list contains the state of the graph at the time of its * initialization. * \param graph The input graph. * \param al Pointer to an uninitialized igraph_adjlist_t object. * \param mode Constant specifying whether outgoing * (IGRAPH_OUT), incoming (IGRAPH_IN), * or both (IGRAPH_ALL) types of neighbors to include * in the adjacency list. It is ignored for undirected networks. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. */ int igraph_adjlist_init(const igraph_t *graph, igraph_adjlist_t *al, igraph_neimode_t mode) { igraph_integer_t i; igraph_vector_t tmp; if (mode != IGRAPH_IN && mode != IGRAPH_OUT && mode != IGRAPH_ALL) { IGRAPH_ERROR("Cannot create adjlist view", IGRAPH_EINVMODE); } igraph_vector_init(&tmp, 0); IGRAPH_FINALLY(igraph_vector_destroy, &tmp); if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } al->length=igraph_vcount(graph); al->adjs=igraph_Calloc(al->length, igraph_vector_int_t); if (al->adjs == 0) { IGRAPH_ERROR("Cannot create adjlist view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_adjlist_destroy, al); for (i=0; ilength; i++) { int j, n; IGRAPH_ALLOW_INTERRUPTION(); IGRAPH_CHECK(igraph_neighbors(graph, &tmp, i, mode)); n=igraph_vector_size(&tmp); IGRAPH_CHECK(igraph_vector_int_init(&al->adjs[i], n)); for (j=0; jadjs[i])[j] = VECTOR(tmp)[j]; } } igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_adjlist_init_empty * Initialize an empty adjacency list * * Creates a list of vectors, one for each vertex. This is useful when you * are \em constructing a graph using an adjacency list representation as * it does not require your graph to exist yet. * \param no_of_nodes The number of vertices * \param al Pointer to an uninitialized igraph_adjlist_t object. * \return Error code. * * Time complexity: O(|V|), linear in the number of vertices. */ int igraph_adjlist_init_empty(igraph_adjlist_t *al, igraph_integer_t no_of_nodes) { long int i; al->length=no_of_nodes; al->adjs=igraph_Calloc(al->length, igraph_vector_int_t); if (al->adjs == 0) { IGRAPH_ERROR("Cannot create adjlist view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_adjlist_destroy, al); for (i=0; ilength; i++) { IGRAPH_CHECK(igraph_vector_int_init(&al->adjs[i], 0)); } IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_adjlist_init_complementer * Adjacency lists for the complementer graph * * This function creates adjacency lists for the complementer * of the input graph. In the complementer graph all edges are present * which are not present in the original graph. Multiple edges in the * input graph are ignored. * \param graph The input graph. * \param al Pointer to a not yet initialized adjacency list. * \param mode Constant specifying whether outgoing * (IGRAPH_OUT), incoming (IGRAPH_IN), * or both (IGRAPH_ALL) types of neighbors (in the * complementer graph) to include in the adjacency list. It is * ignored for undirected networks. * \param loops Whether to consider loop edges. * \return Error code. * * Time complexity: O(|V|^2+|E|), quadratic in the number of vertices. */ int igraph_adjlist_init_complementer(const igraph_t *graph, igraph_adjlist_t *al, igraph_neimode_t mode, igraph_bool_t loops) { igraph_integer_t i, j, k, n; igraph_bool_t* seen; igraph_vector_t vec; if (mode != IGRAPH_IN && mode != IGRAPH_OUT && mode != IGRAPH_ALL) { IGRAPH_ERROR("Cannot create complementer adjlist view", IGRAPH_EINVMODE); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } al->length=igraph_vcount(graph); al->adjs=igraph_Calloc(al->length, igraph_vector_int_t); if (al->adjs == 0) { IGRAPH_ERROR("Cannot create complementer adjlist view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_adjlist_destroy, al); n=al->length; seen=igraph_Calloc(n, igraph_bool_t); if (seen==0) { IGRAPH_ERROR("Cannot create complementer adjlist view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, seen); IGRAPH_VECTOR_INIT_FINALLY(&vec, 0); for (i=0; ilength; i++) { IGRAPH_ALLOW_INTERRUPTION(); igraph_neighbors(graph, &vec, i, mode); memset(seen, 0, sizeof(igraph_bool_t)*(unsigned) al->length); n=al->length; if (!loops) { seen[i] = 1; n--; } for (j=0; jadjs[i], n)); for (j=0, k=0; kadjs[i])[k++] = j; } } } igraph_Free(seen); igraph_vector_destroy(&vec); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \function igraph_adjlist_destroy * Deallocate memory * * Free all memory allocated for an adjacency list. * \param al The adjacency list to destroy. * * Time complexity: depends on memory management. */ void igraph_adjlist_destroy(igraph_adjlist_t *al) { long int i; for (i=0; ilength; i++) { if (&al->adjs[i]) { igraph_vector_int_destroy(&al->adjs[i]); } } igraph_Free(al->adjs); } /** * \function igraph_adjlist_clear * Removes all edges from an adjacency list. * * \param al The adjacency list. * Time complexity: depends on memory management, typically O(n), where n is * the total number of elements in the adjacency list. */ void igraph_adjlist_clear(igraph_adjlist_t *al) { long int i; for (i=0; ilength; i++) { igraph_vector_int_clear(&al->adjs[i]); } } /** * \function igraph_adjlist_size * Number of vertices in an adjacency list. * * \param al The adjacency list. * \return The number of elements. * * Time complexity: O(1). */ igraph_integer_t igraph_adjlist_size(const igraph_adjlist_t *al) { return al->length; } /* igraph_vector_int_t *igraph_adjlist_get(igraph_adjlist_t *al, igraph_integer_t no) { */ /* return &al->adjs[(long int)no]; */ /* } */ /** * \function igraph_adjlist_sort * Sort each vector in an adjacency list. * * Sorts every vector of the adjacency list. * \param al The adjacency list. * * Time complexity: O(n log n), n is the total number of elements in * the adjacency list. */ void igraph_adjlist_sort(igraph_adjlist_t *al) { long int i; for (i=0; ilength; i++) igraph_vector_int_sort(&al->adjs[i]); } /** * \function igraph_adjlist_simplify * Simplify * * Simplify an adjacency list, ie. remove loop and multiple edges. * \param al The adjacency list. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of edges and * vertices. */ int igraph_adjlist_simplify(igraph_adjlist_t *al) { long int i; long int n=al->length; igraph_vector_int_t mark; igraph_vector_int_init(&mark, n); IGRAPH_FINALLY(igraph_vector_int_destroy, &mark); for (i=0; iadjs[i]; long int j, l=igraph_vector_int_size(v); VECTOR(mark)[i] = i+1; for (j=0; jlength; IGRAPH_UNUSED(graph); for (i=0; iadjs[i]; long int j, p=1, l=igraph_vector_int_size(v); for (j=1; jlength; for (i=0; iadjs[i]; igraph_vector_int_print(v); } return 0; } #endif int igraph_adjlist_fprint(const igraph_adjlist_t *al, FILE *outfile) { long int i; long int n=al->length; for (i=0; iadjs[i]; igraph_vector_int_fprint(v, outfile); } return 0; } #define ADJLIST_CANON_EDGE(from, to, directed) \ do { \ igraph_integer_t temp; \ if((!directed) && from < to) { \ temp = to; \ to = from; \ from = temp; \ } \ } while(0); igraph_bool_t igraph_adjlist_has_edge(igraph_adjlist_t* al, igraph_integer_t from, igraph_integer_t to, igraph_bool_t directed) { igraph_vector_int_t* fromvec; ADJLIST_CANON_EDGE(from, to, directed); fromvec = igraph_adjlist_get(al, from); return igraph_vector_int_binsearch2(fromvec, to); } int igraph_adjlist_replace_edge(igraph_adjlist_t* al, igraph_integer_t from, igraph_integer_t oldto, igraph_integer_t newto, igraph_bool_t directed) { igraph_vector_int_t *oldfromvec, *newfromvec; int err1, err2; long int oldpos, newpos; igraph_integer_t oldfrom = from, newfrom = from; ADJLIST_CANON_EDGE(oldfrom, oldto, directed); ADJLIST_CANON_EDGE(newfrom, newto, directed); oldfromvec = igraph_adjlist_get(al, oldfrom); newfromvec = igraph_adjlist_get(al, newfrom); err1 = igraph_vector_int_binsearch(oldfromvec, oldto, &oldpos); err2 = igraph_vector_int_binsearch(newfromvec, newto, &newpos); /* oldfrom -> oldto should exist; newfrom -> newto should not. */ if((!err1) || err2) return 1; igraph_vector_int_remove(oldfromvec, oldpos); if(oldfromvec == newfromvec && oldpos < newpos) --newpos; IGRAPH_CHECK(igraph_vector_int_insert(newfromvec, newpos, newto)); return 0; } int igraph_adjedgelist_remove_duplicate(const igraph_t *graph, igraph_inclist_t *al) { IGRAPH_WARNING("igraph_adjedgelist_remove_duplicate() is deprecated, use " "igraph_inclist_remove_duplicate() instead"); return igraph_inclist_remove_duplicate(graph, al); } #ifndef USING_R int igraph_adjedgelist_print(const igraph_inclist_t *al, FILE *outfile) { IGRAPH_WARNING("igraph_adjedgelist_print() is deprecated, use " "igraph_inclist_print() instead"); return igraph_inclist_fprint(al, outfile); } #endif /** * \function igraph_adjedgelist_init * Initialize an incidence list of edges * * This function was superseded by \ref igraph_inclist_init() in igraph 0.6. * Please use \ref igraph_inclist_init() instead of this function. * * * Deprecated in version 0.6. */ int igraph_adjedgelist_init(const igraph_t *graph, igraph_inclist_t *il, igraph_neimode_t mode) { IGRAPH_WARNING("igraph_adjedgelist_init() is deprecated, use " "igraph_inclist_init() instead"); return igraph_inclist_init(graph, il, mode); } /** * \function igraph_adjedgelist_destroy * Frees all memory allocated for an incidence list. * * This function was superseded by \ref igraph_inclist_destroy() in igraph 0.6. * Please use \ref igraph_inclist_destroy() instead of this function. * * * Deprecated in version 0.6. */ void igraph_adjedgelist_destroy(igraph_inclist_t *il) { IGRAPH_WARNING("igraph_adjedgelist_destroy() is deprecated, use " "igraph_inclist_destroy() instead"); igraph_inclist_destroy(il); } int igraph_inclist_remove_duplicate(const igraph_t *graph, igraph_inclist_t *al) { long int i; long int n=al->length; for (i=0; iincs[i]; long int j, p=1, l=igraph_vector_int_size(v); for (j=1; jlength; for (i=0; iincs[i]; igraph_vector_int_print(v); } return 0; } #endif int igraph_inclist_fprint(const igraph_inclist_t *al, FILE *outfile) { long int i; long int n=al->length; for (i=0; iincs[i]; igraph_vector_int_fprint(v, outfile); } return 0; } /** * \function igraph_inclist_init * Initialize an incidence list of edges * * Create a list of vectors containing the incident edges for all * vertices. The incidence list is independent of the graph after * creation, subsequent changes of the graph object do not update the * incidence list, and changes to the incidence list do not update the * graph. * \param graph The input graph. * \param il Pointer to an uninitialized incidence list. * \param mode Constant specifying whether incoming edges * (IGRAPH_IN), outgoing edges (IGRAPH_OUT) or * both (IGRAPH_ALL) to include in the incidence lists * of directed graphs. It is ignored for undirected graphs. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. */ int igraph_inclist_init(const igraph_t *graph, igraph_inclist_t *il, igraph_neimode_t mode) { igraph_integer_t i; igraph_vector_t tmp; if (mode != IGRAPH_IN && mode != IGRAPH_OUT && mode != IGRAPH_ALL) { IGRAPH_ERROR("Cannot create incidence list view", IGRAPH_EINVMODE); } igraph_vector_init(&tmp, 0); IGRAPH_FINALLY(igraph_vector_destroy, &tmp); if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } il->length=igraph_vcount(graph); il->incs=igraph_Calloc(il->length, igraph_vector_int_t); if (il->incs == 0) { IGRAPH_ERROR("Cannot create incidence list view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_inclist_destroy, il); for (i=0; ilength; i++) { int j, n; IGRAPH_ALLOW_INTERRUPTION(); IGRAPH_CHECK(igraph_incident(graph, &tmp, i, mode)); n=igraph_vector_size(&tmp); IGRAPH_CHECK(igraph_vector_int_init(&il->incs[i], n)); for (j=0; jincs[i])[j] = VECTOR(tmp)[j]; } } igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_inclist_init_empty * \brief Initialize an incidence list corresponding to an empty graph. * * This function essentially creates a list of empty vectors that may * be treated as an incidence list for a graph with a given number of * vertices. * * \param il Pointer to an uninitialized incidence list. * \param n The number of vertices in the incidence list. * \return Error code. * * Time complexity: O(|V|), linear in the number of vertices. */ int igraph_inclist_init_empty(igraph_inclist_t *il, igraph_integer_t n) { long int i; il->length=n; il->incs=igraph_Calloc(il->length, igraph_vector_int_t); if (il->incs == 0) { IGRAPH_ERROR("Cannot create incidence list view", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_inclist_destroy, il); for (i=0; iincs[i], 0)); } IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_inclist_destroy * Frees all memory allocated for an incidence list. * * \param eal The incidence list to destroy. * * Time complexity: depends on memory management. */ void igraph_inclist_destroy(igraph_inclist_t *il) { long int i; for (i=0; ilength; i++) { /* This works if some igraph_vector_int_t's are 0, because igraph_vector_destroy can handle this. */ igraph_vector_int_destroy(&il->incs[i]); } igraph_Free(il->incs); } /** * \function igraph_inclist_clear * Removes all edges from an incidence list. * * \param il The incidence list. * Time complexity: depends on memory management, typically O(n), where n is * the total number of elements in the incidence list. */ void igraph_inclist_clear(igraph_inclist_t *il) { long int i; for (i=0; ilength; i++) { igraph_vector_int_clear(&il->incs[i]); } } /** * \function igraph_lazy_adjlist_init * Constructor * * Create a lazy adjacency list for vertices. This function only * allocates some memory for storing the vectors of an adjacency list, * but the neighbor vertices are not queried, only at the \ref * igraph_lazy_adjlist_get() calls. * \param graph The input graph. * \param al Pointer to an uninitialized adjacency list object. * \param mode Constant, it gives whether incoming edges * (IGRAPH_IN), outgoing edges * (IGRPAH_OUT) or both types of edges * (IGRAPH_ALL) are considered. It is ignored for * undirected graphs. * \param simplify Constant, it gives whether to simplify the vectors * in the adjacency list (IGRAPH_SIMPLIFY) or not * (IGRAPH_DONT_SIMPLIFY). * \return Error code. * * Time complexity: O(|V|), the number of vertices, possibly, but * depends on the underlying memory management too. */ int igraph_lazy_adjlist_init(const igraph_t *graph, igraph_lazy_adjlist_t *al, igraph_neimode_t mode, igraph_lazy_adlist_simplify_t simplify) { if (mode != IGRAPH_IN && mode != IGRAPH_OUT && mode != IGRAPH_ALL) { IGRAPH_ERROR("Cannor create adjlist view", IGRAPH_EINVMODE); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } al->mode=mode; al->simplify=simplify; al->graph=graph; al->length=igraph_vcount(graph); al->adjs=igraph_Calloc(al->length, igraph_vector_t*); if (al->adjs == 0) { IGRAPH_ERROR("Cannot create lazy adjlist view", IGRAPH_ENOMEM); } return 0; } /** * \function igraph_lazy_adjlist_destroy * Deallocate memory * * Free all allocated memory for a lazy adjacency list. * \param al The adjacency list to deallocate. * * Time complexity: depends on the memory management. */ void igraph_lazy_adjlist_destroy(igraph_lazy_adjlist_t *al) { igraph_lazy_adjlist_clear(al); igraph_Free(al->adjs); } /** * \function igraph_lazy_adjlist_clear * Removes all edges from a lazy adjacency list. * * \param al The lazy adjacency list. * Time complexity: depends on memory management, typically O(n), where n is * the total number of elements in the adjacency list. */ void igraph_lazy_adjlist_clear(igraph_lazy_adjlist_t *al) { long int i, n=al->length; for (i=0; iadjs[i] != 0) { igraph_vector_destroy(al->adjs[i]); igraph_Free(al->adjs[i]); } } } igraph_vector_t *igraph_lazy_adjlist_get_real(igraph_lazy_adjlist_t *al, igraph_integer_t pno) { igraph_integer_t no=pno; int ret; if (al->adjs[no] == 0) { al->adjs[no] = igraph_Calloc(1, igraph_vector_t); if (al->adjs[no] == 0) { igraph_error("Lazy adjlist failed", __FILE__, __LINE__, IGRAPH_ENOMEM); } ret=igraph_vector_init(al->adjs[no], 0); if (ret != 0) { igraph_error("", __FILE__, __LINE__, ret); } ret=igraph_neighbors(al->graph, al->adjs[no], no, al->mode); if (ret != 0) { igraph_error("", __FILE__, __LINE__, ret); } if (al->simplify == IGRAPH_SIMPLIFY) { igraph_vector_t *v=al->adjs[no]; long int i, p=0, n=igraph_vector_size(v); for (i=0; iadjs[no]; } /** * \function igraph_lazy_adjedgelist_init * Initializes a lazy incidence list of edges * * This function was superseded by \ref igraph_lazy_inclist_init() in igraph 0.6. * Please use \ref igraph_lazy_inclist_init() instead of this function. * * * Deprecated in version 0.6. */ int igraph_lazy_adjedgelist_init(const igraph_t *graph, igraph_lazy_inclist_t *il, igraph_neimode_t mode) { IGRAPH_WARNING("igraph_lazy_adjedgelist_init() is deprecated, use " "igraph_lazy_inclist_init() instead"); return igraph_lazy_inclist_init(graph, il, mode); } /** * \function igraph_lazy_adjedgelist_destroy * Frees all memory allocated for an incidence list. * * This function was superseded by \ref igraph_lazy_inclist_destroy() in igraph 0.6. * Please use \ref igraph_lazy_inclist_destroy() instead of this function. * * * Deprecated in version 0.6. */ void igraph_lazy_adjedgelist_destroy(igraph_lazy_inclist_t *il) { IGRAPH_WARNING("igraph_lazy_adjedgelist_destroy() is deprecated, use " "igraph_lazy_inclist_destroy() instead"); igraph_lazy_inclist_destroy(il); } igraph_vector_t *igraph_lazy_adjedgelist_get_real(igraph_lazy_adjedgelist_t *il, igraph_integer_t pno) { IGRAPH_WARNING("igraph_lazy_adjedgelist_get_real() is deprecated, use " "igraph_lazy_inclist_get_real() instead"); return igraph_lazy_inclist_get_real(il, pno); } /** * \function igraph_lazy_inclist_init * Initializes a lazy incidence list of edges * * Create a lazy incidence list for edges. This function only * allocates some memory for storing the vectors of an incidence list, * but the incident edges are not queried, only when \ref * igraph_lazy_inclist_get() is called. * \param graph The input graph. * \param al Pointer to an uninitialized incidence list. * \param mode Constant, it gives whether incoming edges * (IGRAPH_IN), outgoing edges * (IGRPAH_OUT) or both types of edges * (IGRAPH_ALL) are considered. It is ignored for * undirected graphs. * \return Error code. * * Time complexity: O(|V|), the number of vertices, possibly. But it * also depends on the underlying memory management. */ int igraph_lazy_inclist_init(const igraph_t *graph, igraph_lazy_inclist_t *al, igraph_neimode_t mode) { if (mode != IGRAPH_IN && mode != IGRAPH_OUT && mode != IGRAPH_ALL) { IGRAPH_ERROR("Cannot create lazy incidence list view", IGRAPH_EINVMODE); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } al->mode=mode; al->graph=graph; al->length=igraph_vcount(graph); al->incs=igraph_Calloc(al->length, igraph_vector_t*); if (al->incs == 0) { IGRAPH_ERROR("Cannot create lazy incidence list view", IGRAPH_ENOMEM); } return 0; } /** * \function igraph_lazy_inclist_destroy * Deallocates memory * * Frees all allocated memory for a lazy incidence list. * \param al The incidence list to deallocate. * * Time complexity: depends on memory management. */ void igraph_lazy_inclist_destroy(igraph_lazy_inclist_t *il) { igraph_lazy_inclist_clear(il); igraph_Free(il->incs); } /** * \function igraph_lazy_inclist_clear * Removes all edges from a lazy incidence list. * * \param il The lazy incidence list. * Time complexity: depends on memory management, typically O(n), where n is * the total number of elements in the incidence list. */ void igraph_lazy_inclist_clear(igraph_lazy_inclist_t *il) { long int i, n=il->length; for (i=0; iincs[i] != 0) { igraph_vector_destroy(il->incs[i]); igraph_Free(il->incs[i]); } } } igraph_vector_t *igraph_lazy_inclist_get_real(igraph_lazy_inclist_t *il, igraph_integer_t pno) { igraph_integer_t no=pno; int ret; if (il->incs[no] == 0) { il->incs[no] = igraph_Calloc(1, igraph_vector_t); if (il->incs[no] == 0) { igraph_error("Lazy incidence list query failed", __FILE__, __LINE__, IGRAPH_ENOMEM); } ret=igraph_vector_init(il->incs[no], 0); if (ret != 0) { igraph_error("", __FILE__, __LINE__, ret); } ret=igraph_incident(il->graph, il->incs[no], no, il->mode); if (ret != 0) { igraph_error("", __FILE__, __LINE__, ret); } } return il->incs[no]; } igraph/src/dseupd.f0000644000175100001440000011030613431000472013757 0ustar hornikusersc\BeginDoc c c\Name: igraphdseupd c c\Description: c c This subroutine returns the converged approximations to eigenvalues c of A*z = lambda*B*z and (optionally): c c (1) the corresponding approximate eigenvectors, c c (2) an orthonormal (Lanczos) basis for the associated approximate c invariant subspace, c c (3) Both. c c There is negligible additional cost to obtain eigenvectors. An orthonormal c (Lanczos) basis is always computed. There is an additional storage cost c of n*nev if both are requested (in this case a separate array Z must be c supplied). c c These quantities are obtained from the Lanczos factorization computed c by DSAUPD for the linear operator OP prescribed by the MODE selection c (see IPARAM(7) in DSAUPD documentation.) DSAUPD must be called before c this routine is called. These approximate eigenvalues and vectors are c commonly called Ritz values and Ritz vectors respectively. They are c referred to as such in the comments that follow. The computed orthonormal c basis for the invariant subspace corresponding to these Ritz values is c referred to as a Lanczos basis. c c See documentation in the header of the subroutine DSAUPD for a definition c of OP as well as other terms and the relation of computed Ritz values c and vectors of OP with respect to the given problem A*z = lambda*B*z. c c The approximate eigenvalues of the original problem are returned in c ascending algebraic order. The user may elect to call this routine c once for each desired Ritz vector and store it peripherally if desired. c There is also the option of computing a selected set of these vectors c with a single call. c c\Usage: c call igraphdseupd c ( RVEC, HOWMNY, SELECT, D, Z, LDZ, SIGMA, BMAT, N, WHICH, NEV, TOL, c RESID, NCV, V, LDV, IPARAM, IPNTR, WORKD, WORKL, LWORKL, INFO ) c c RVEC LOGICAL (INPUT) c Specifies whether Ritz vectors corresponding to the Ritz value c approximations to the eigenproblem A*z = lambda*B*z are computed. c c RVEC = .FALSE. Compute Ritz values only. c c RVEC = .TRUE. Compute Ritz vectors. c c HOWMNY Character*1 (INPUT) c Specifies how many Ritz vectors are wanted and the form of Z c the matrix of Ritz vectors. See remark 1 below. c = 'A': compute NEV Ritz vectors; c = 'S': compute some of the Ritz vectors, specified c by the logical array SELECT. c c SELECT Logical array of dimension NEV. (INPUT) c If HOWMNY = 'S', SELECT specifies the Ritz vectors to be c computed. To select the Ritz vector corresponding to a c Ritz value D(j), SELECT(j) must be set to .TRUE.. c If HOWMNY = 'A' , SELECT is not referenced. c c D Double precision array of dimension NEV. (OUTPUT) c On exit, D contains the Ritz value approximations to the c eigenvalues of A*z = lambda*B*z. The values are returned c in ascending order. If IPARAM(7) = 3,4,5 then D represents c the Ritz values of OP computed by igraphdsaupd transformed to c those of the original eigensystem A*z = lambda*B*z. If c IPARAM(7) = 1,2 then the Ritz values of OP are the same c as the those of A*z = lambda*B*z. c c Z Double precision N by NEV array if HOWMNY = 'A'. (OUTPUT) c On exit, Z contains the B-orthonormal Ritz vectors of the c eigensystem A*z = lambda*B*z corresponding to the Ritz c value approximations. c If RVEC = .FALSE. then Z is not referenced. c NOTE: The array Z may be set equal to first NEV columns of the c Arnoldi/Lanczos basis array V computed by DSAUPD. c c LDZ Integer. (INPUT) c The leading dimension of the array Z. If Ritz vectors are c desired, then LDZ .ge. max( 1, N ). In any case, LDZ .ge. 1. c c SIGMA Double precision (INPUT) c If IPARAM(7) = 3,4,5 represents the shift. Not referenced if c IPARAM(7) = 1 or 2. c c c **** The remaining arguments MUST be the same as for the **** c **** call to DNAUPD that was just completed. **** c c NOTE: The remaining arguments c c BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, IPNTR, c WORKD, WORKL, LWORKL, INFO c c must be passed directly to DSEUPD following the last call c to DSAUPD. These arguments MUST NOT BE MODIFIED between c the the last call to DSAUPD and the call to DSEUPD. c c Two of these parameters (WORKL, INFO) are also output parameters: c c WORKL Double precision work array of length LWORKL. (OUTPUT/WORKSPACE) c WORKL(1:4*ncv) contains information obtained in c igraphdsaupd. They are not changed by igraphdseupd. c WORKL(4*ncv+1:ncv*ncv+8*ncv) holds the c untransformed Ritz values, the computed error estimates, c and the associated eigenvector matrix of H. c c Note: IPNTR(8:10) contains the pointer into WORKL for addresses c of the above information computed by igraphdseupd. c ------------------------------------------------------------- c IPNTR(8): pointer to the NCV RITZ values of the original system. c IPNTR(9): pointer to the NCV corresponding error bounds. c IPNTR(10): pointer to the NCV by NCV matrix of eigenvectors c of the tridiagonal matrix T. Only referenced by c igraphdseupd if RVEC = .TRUE. See Remarks. c ------------------------------------------------------------- c c INFO Integer. (OUTPUT) c Error flag on output. c = 0: Normal exit. c = -1: N must be positive. c = -2: NEV must be positive. c = -3: NCV must be greater than NEV and less than or equal to N. c = -5: WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'. c = -6: BMAT must be one of 'I' or 'G'. c = -7: Length of private work WORKL array is not sufficient. c = -8: Error return from trid. eigenvalue calculation; c Information error from LAPACK routine dsteqr. c = -9: Starting vector is zero. c = -10: IPARAM(7) must be 1,2,3,4,5. c = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatible. c = -12: NEV and WHICH = 'BE' are incompatible. c = -14: DSAUPD did not find any eigenvalues to sufficient c accuracy. c = -15: HOWMNY must be one of 'A' or 'S' if RVEC = .true. c = -16: HOWMNY = 'S' not yet implemented c c\BeginLib c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett, "The Symmetric Eigenvalue Problem". Prentice-Hall, c 1980. c 4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", c Computer Physics Communications, 53 (1989), pp 169-179. c 5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to c Implement the Spectral Transformation", Math. Comp., 48 (1987), c pp 663-673. c 6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos c Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", c SIAM J. Matr. Anal. Apps., January (1993). c 7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines c for Updating the QR decomposition", ACM TOMS, December 1990, c Volume 16 Number 4, pp 369-377. c c\Remarks c 1. The converged Ritz values are always returned in increasing c (algebraic) order. c c 2. Currently only HOWMNY = 'A' is implemented. It is included at this c stage for the user who wants to incorporate it. c c\Routines called: c igraphdsesrt ARPACK routine that sorts an array X, and applies the c corresponding permutation to a matrix A. c igraphdsortr igraphdsortr ARPACK sorting routine. c igraphivout ARPACK utility routine that prints integers. c igraphdvout ARPACK utility routine that prints vectors. c dgeqr2 LAPACK routine that computes the QR factorization of c a matrix. c dlacpy LAPACK matrix copy routine. c dlamch LAPACK routine that determines machine constants. c dorm2r LAPACK routine that applies an orthogonal matrix in c factored form. c dsteqr LAPACK routine that computes eigenvalues and eigenvectors c of a tridiagonal matrix. c dger Level 2 BLAS rank one update to a matrix. c dcopy Level 1 BLAS that copies one vector to another . c dnrm2 Level 1 BLAS that computes the norm of a vector. c dscal Level 1 BLAS that scales a vector. c dswap Level 1 BLAS that swaps the contents of two vectors. c\Authors c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Chao Yang Houston, Texas c Dept. of Computational & c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/15/93: Version ' 2.1' c c\SCCS Information: @(#) c FILE: seupd.F SID: 2.7 DATE OF SID: 8/27/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- subroutine igraphdseupd (rvec, howmny, select, d, z, ldz, & sigma, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, & ipntr, workd, workl, lworkl, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat, howmny, which*2 logical rvec, select(ncv) integer info, ldz, ldv, lworkl, n, ncv, nev Double precision & sigma, tol c c %-----------------% c | Array Arguments | c %-----------------% c integer iparam(7), ipntr(11) Double precision & d(nev), resid(n), v(ldv,ncv), z(ldz, nev), & workd(2*n), workl(lworkl) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c character type*6 integer bounds, ierr, ih, ihb, ihd, iq, iw, j, k, & ldh, ldq, mode, msglvl, nconv, next, ritz, & irz, ibd, ktrord, leftptr, rghtptr, ism, ilg Double precision & bnorm2, rnorm, temp, thres1, thres2, tempbnd, eps23 logical reord c c %--------------% c | Local Arrays | c %--------------% c Double precision & kv(2) c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, dger, dgeqr2, dlacpy, dorm2r, dscal, & igraphdsesrt, dsteqr, dswap, igraphdvout, & igraphivout, igraphdsortr c c %--------------------% c | External Functions | c %--------------------% c Double precision & dnrm2, dlamch external dnrm2, dlamch c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic min c c %-----------------------% c | Executable Statements | c %-----------------------% c c %------------------------% c | Set default parameters | c %------------------------% c msglvl = mseupd mode = iparam(7) nconv = iparam(5) info = 0 c c %--------------% c | Quick return | c %--------------% c if (nconv .eq. 0) go to 9000 ierr = 0 c if (nconv .le. 0) ierr = -14 if (n .le. 0) ierr = -1 if (nev .le. 0) ierr = -2 if (ncv .le. nev .or. ncv .gt. n) ierr = -3 if (which .ne. 'LM' .and. & which .ne. 'SM' .and. & which .ne. 'LA' .and. & which .ne. 'SA' .and. & which .ne. 'BE') ierr = -5 if (bmat .ne. 'I' .and. bmat .ne. 'G') ierr = -6 if ( (howmny .ne. 'A' .and. & howmny .ne. 'P' .and. & howmny .ne. 'S') .and. rvec ) & ierr = -15 if (rvec .and. howmny .eq. 'S') ierr = -16 c if (rvec .and. lworkl .lt. ncv**2+8*ncv) ierr = -7 c if (mode .eq. 1 .or. mode .eq. 2) then type = 'REGULR' else if (mode .eq. 3 ) then type = 'SHIFTI' else if (mode .eq. 4 ) then type = 'BUCKLE' else if (mode .eq. 5 ) then type = 'CAYLEY' else ierr = -10 end if if (mode .eq. 1 .and. bmat .eq. 'G') ierr = -11 if (nev .eq. 1 .and. which .eq. 'BE') ierr = -12 c c %------------% c | Error Exit | c %------------% c if (ierr .ne. 0) then info = ierr go to 9000 end if c c %-------------------------------------------------------% c | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | c | etc... and the remaining workspace. | c | Also update pointer to be used on output. | c | Memory is laid out as follows: | c | workl(1:2*ncv) := generated tridiagonal matrix H | c | The subdiagonal is stored in workl(2:ncv). | c | The dead spot is workl(1) but upon exiting | c | igraphdsaupd stores the B-norm of the last residual | c | vector in workl(1). We use this !!! | c | workl(2*ncv+1:2*ncv+ncv) := ritz values | c | The wanted values are in the first NCONV spots. | c | workl(3*ncv+1:3*ncv+ncv) := computed Ritz estimates | c | The wanted values are in the first NCONV spots. | c | NOTE: workl(1:4*ncv) is set by igraphdsaupd and is not | c | modified by igraphdseupd. | c %-------------------------------------------------------% c c %-------------------------------------------------------% c | The following is used and set by igraphdseupd. | c | workl(4*ncv+1:4*ncv+ncv) := used as workspace during | c | computation of the eigenvectors of H. Stores | c | the diagonal of H. Upon EXIT contains the NCV | c | Ritz values of the original system. The first | c | NCONV spots have the wanted values. If MODE = | c | 1 or 2 then will equal workl(2*ncv+1:3*ncv). | c | workl(5*ncv+1:5*ncv+ncv) := used as workspace during | c | computation of the eigenvectors of H. Stores | c | the subdiagonal of H. Upon EXIT contains the | c | NCV corresponding Ritz estimates of the | c | original system. The first NCONV spots have the | c | wanted values. If MODE = 1,2 then will equal | c | workl(3*ncv+1:4*ncv). | c | workl(6*ncv+1:6*ncv+ncv*ncv) := orthogonal Q that is | c | the eigenvector matrix for H as returned by | c | dsteqr. Not referenced if RVEC = .False. | c | Ordering follows that of workl(4*ncv+1:5*ncv) | c | workl(6*ncv+ncv*ncv+1:6*ncv+ncv*ncv+2*ncv) := | c | Workspace. Needed by dsteqr and by igraphdseupd. | c | GRAND total of NCV*(NCV+8) locations. | c %-------------------------------------------------------% c c ih = ipntr(5) ritz = ipntr(6) bounds = ipntr(7) ldh = ncv ldq = ncv ihd = bounds + ldh ihb = ihd + ldh iq = ihb + ldh iw = iq + ldh*ncv next = iw + 2*ncv ipntr(4) = next ipntr(8) = ihd ipntr(9) = ihb ipntr(10) = iq c c %----------------------------------------% c | irz points to the Ritz values computed | c | by _seigt before exiting _saup2. | c | ibd points to the Ritz estimates | c | computed by _seigt before exiting | c | _saup2. | c %----------------------------------------% c irz = ipntr(11)+ncv ibd = irz+ncv c c c %---------------------------------% c | Set machine dependent constant. | c %---------------------------------% c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0 / 3.0D+0) c c %---------------------------------------% c | RNORM is B-norm of the RESID(1:N). | c | BNORM2 is the 2 norm of B*RESID(1:N). | c | Upon exit of igraphdsaupd WORKD(1:N) has | c | B*RESID(1:N). | c %---------------------------------------% c rnorm = workl(ih) if (bmat .eq. 'I') then bnorm2 = rnorm else if (bmat .eq. 'G') then bnorm2 = dnrm2(n, workd, 1) end if c if (rvec) then c c %------------------------------------------------% c | Get the converged Ritz value on the boundary. | c | This value will be used to dermine whether we | c | need to reorder the eigenvalues and | c | eigenvectors comupted by _steqr, and is | c | referred to as the "threshold" value. | c | | c | A Ritz value gamma is said to be a wanted | c | one, if | c | abs(gamma) .ge. threshold, when WHICH = 'LM'; | c | abs(gamma) .le. threshold, when WHICH = 'SM'; | c | gamma .ge. threshold, when WHICH = 'LA'; | c | gamma .le. threshold, when WHICH = 'SA'; | c | gamma .le. thres1 .or. gamma .ge. thres2 | c | when WHICH = 'BE'; | c | | c | Note: converged Ritz values and associated | c | Ritz estimates have been placed in the first | c | NCONV locations in workl(ritz) and | c | workl(bounds) respectively. They have been | c | sorted (in _saup2) according to the WHICH | c | selection criterion. (Except in the case | c | WHICH = 'BE', they are sorted in an increasing | c | order.) | c %------------------------------------------------% c if (which .eq. 'LM' .or. which .eq. 'SM' & .or. which .eq. 'LA' .or. which .eq. 'SA' ) then c thres1 = workl(ritz) c if (msglvl .gt. 2) then call igraphdvout(logfil, 1, thres1, ndigit, & '_seupd: Threshold eigenvalue used for re-ordering') end if c else if (which .eq. 'BE') then c c %------------------------------------------------% c | Ritz values returned from _saup2 have been | c | sorted in increasing order. Thus two | c | "threshold" values (one for the small end, one | c | for the large end) are in the middle. | c %------------------------------------------------% c ism = max(nev,nconv) / 2 ilg = ism + 1 thres1 = workl(ism) thres2 = workl(ilg) c if (msglvl .gt. 2) then kv(1) = thres1 kv(2) = thres2 call igraphdvout(logfil, 2, kv, ndigit, & '_seupd: Threshold eigenvalues used for re-ordering') end if c end if c c %----------------------------------------------------------% c | Check to see if all converged Ritz values appear within | c | the first NCONV diagonal elements returned from _seigt. | c | This is done in the following way: | c | | c | 1) For each Ritz value obtained from _seigt, compare it | c | with the threshold Ritz value computed above to | c | determine whether it is a wanted one. | c | | c | 2) If it is wanted, then check the corresponding Ritz | c | estimate to see if it has converged. If it has, set | c | correponding entry in the logical array SELECT to | c | .TRUE.. | c | | c | If SELECT(j) = .TRUE. and j > NCONV, then there is a | c | converged Ritz value that does not appear at the top of | c | the diagonal matrix computed by _seigt in _saup2. | c | Reordering is needed. | c %----------------------------------------------------------% c reord = .false. ktrord = 0 do 10 j = 0, ncv-1 select(j+1) = .false. if (which .eq. 'LM') then if (abs(workl(irz+j)) .ge. abs(thres1)) then tempbnd = max( eps23, abs(workl(irz+j)) ) if (workl(ibd+j) .le. tol*tempbnd) then select(j+1) = .true. end if end if else if (which .eq. 'SM') then if (abs(workl(irz+j)) .le. abs(thres1)) then tempbnd = max( eps23, abs(workl(irz+j)) ) if (workl(ibd+j) .le. tol*tempbnd) then select(j+1) = .true. end if end if else if (which .eq. 'LA') then if (workl(irz+j) .ge. thres1) then tempbnd = max( eps23, abs(workl(irz+j)) ) if (workl(ibd+j) .le. tol*tempbnd) then select(j+1) = .true. end if end if else if (which .eq. 'SA') then if (workl(irz+j) .le. thres1) then tempbnd = max( eps23, abs(workl(irz+j)) ) if (workl(ibd+j) .le. tol*tempbnd) then select(j+1) = .true. end if end if else if (which .eq. 'BE') then if ( workl(irz+j) .le. thres1 .or. & workl(irz+j) .ge. thres2 ) then tempbnd = max( eps23, abs(workl(irz+j)) ) if (workl(ibd+j) .le. tol*tempbnd) then select(j+1) = .true. end if end if end if if (j+1 .gt. nconv ) reord = select(j+1) .or. reord if (select(j+1)) ktrord = ktrord + 1 10 continue c %-------------------------------------------% c | If KTRORD .ne. NCONV, something is wrong. | c %-------------------------------------------% c if (msglvl .gt. 2) then call igraphivout(logfil, 1, ktrord, ndigit, & '_seupd: Number of specified eigenvalues') call igraphivout(logfil, 1, nconv, ndigit, & '_seupd: Number of "converged" eigenvalues') end if c c %-----------------------------------------------------------% c | Call LAPACK routine _steqr to compute the eigenvalues and | c | eigenvectors of the final symmetric tridiagonal matrix H. | c | Initialize the eigenvector matrix Q to the identity. | c %-----------------------------------------------------------% c call dcopy (ncv-1, workl(ih+1), 1, workl(ihb), 1) call dcopy (ncv, workl(ih+ldh), 1, workl(ihd), 1) c call dsteqr ('Identity', ncv, workl(ihd), workl(ihb), & workl(iq), ldq, workl(iw), ierr) c if (ierr .ne. 0) then info = -8 go to 9000 end if c if (msglvl .gt. 1) then call dcopy (ncv, workl(iq+ncv-1), ldq, workl(iw), 1) call igraphdvout (logfil, ncv, workl(ihd), ndigit, & '_seupd: NCV Ritz values of the final H matrix') call igraphdvout (logfil, ncv, workl(iw), ndigit, & '_seupd: last row of the eigenvector matrix for H') end if c if (reord) then c c %---------------------------------------------% c | Reordered the eigenvalues and eigenvectors | c | computed by _steqr so that the "converged" | c | eigenvalues appear in the first NCONV | c | positions of workl(ihd), and the associated | c | eigenvectors appear in the first NCONV | c | columns. | c %---------------------------------------------% c leftptr = 1 rghtptr = ncv c if (ncv .eq. 1) go to 30 c 20 if (select(leftptr)) then c c %-------------------------------------------% c | Search, from the left, for the first Ritz | c | value that has not converged. | c %-------------------------------------------% c leftptr = leftptr + 1 c else if ( .not. select(rghtptr)) then c c %----------------------------------------------% c | Search, from the right, the first Ritz value | c | that has converged. | c %----------------------------------------------% c rghtptr = rghtptr - 1 c else c c %----------------------------------------------% c | Swap the Ritz value on the left that has not | c | converged with the Ritz value on the right | c | that has converged. Swap the associated | c | eigenvector of the tridiagonal matrix H as | c | well. | c %----------------------------------------------% c temp = workl(ihd+leftptr-1) workl(ihd+leftptr-1) = workl(ihd+rghtptr-1) workl(ihd+rghtptr-1) = temp call dcopy(ncv, workl(iq+ncv*(leftptr-1)), 1, & workl(iw), 1) call dcopy(ncv, workl(iq+ncv*(rghtptr-1)), 1, & workl(iq+ncv*(leftptr-1)), 1) call dcopy(ncv, workl(iw), 1, & workl(iq+ncv*(rghtptr-1)), 1) leftptr = leftptr + 1 rghtptr = rghtptr - 1 c end if c if (leftptr .lt. rghtptr) go to 20 c 30 end if c if (msglvl .gt. 2) then call igraphdvout (logfil, ncv, workl(ihd), ndigit, & '_seupd: The eigenvalues of H--reordered') end if c c %----------------------------------------% c | Load the converged Ritz values into D. | c %----------------------------------------% c call dcopy(nconv, workl(ihd), 1, d, 1) c else c c %-----------------------------------------------------% c | Ritz vectors not required. Load Ritz values into D. | c %-----------------------------------------------------% c call dcopy (nconv, workl(ritz), 1, d, 1) call dcopy (ncv, workl(ritz), 1, workl(ihd), 1) c end if c c %------------------------------------------------------------------% c | Transform the Ritz values and possibly vectors and corresponding | c | Ritz estimates of OP to those of A*x=lambda*B*x. The Ritz values | c | (and corresponding data) are returned in ascending order. | c %------------------------------------------------------------------% c if (type .eq. 'REGULR') then c c %---------------------------------------------------------% c | Ascending sort of wanted Ritz values, vectors and error | c | bounds. Not necessary if only Ritz values are desired. | c %---------------------------------------------------------% c if (rvec) then call igraphdsesrt ('LA', rvec , nconv, d, ncv, workl(iq), & ldq) else call dcopy (ncv, workl(bounds), 1, workl(ihb), 1) end if c else c c %-------------------------------------------------------------% c | * Make a copy of all the Ritz values. | c | * Transform the Ritz values back to the original system. | c | For TYPE = 'SHIFTI' the transformation is | c | lambda = 1/theta + sigma | c | For TYPE = 'BUCKLE' the transformation is | c | lambda = sigma * theta / ( theta - 1 ) | c | For TYPE = 'CAYLEY' the transformation is | c | lambda = sigma * (theta + 1) / (theta - 1 ) | c | where the theta are the Ritz values returned by igraphdsaupd. | c | NOTES: | c | *The Ritz vectors are not affected by the transformation. | c | They are only reordered. | c %-------------------------------------------------------------% c call dcopy (ncv, workl(ihd), 1, workl(iw), 1) if (type .eq. 'SHIFTI') then do 40 k=1, ncv workl(ihd+k-1) = one / workl(ihd+k-1) + sigma 40 continue else if (type .eq. 'BUCKLE') then do 50 k=1, ncv workl(ihd+k-1) = sigma * workl(ihd+k-1) / & (workl(ihd+k-1) - one) 50 continue else if (type .eq. 'CAYLEY') then do 60 k=1, ncv workl(ihd+k-1) = sigma * (workl(ihd+k-1) + one) / & (workl(ihd+k-1) - one) 60 continue end if c c %-------------------------------------------------------------% c | * Store the wanted NCONV lambda values into D. | c | * Sort the NCONV wanted lambda in WORKL(IHD:IHD+NCONV-1) | c | into ascending order and apply sort to the NCONV theta | c | values in the transformed system. We'll need this to | c | compute Ritz estimates in the original system. | c | * Finally sort the lambda's into ascending order and apply | c | to Ritz vectors if wanted. Else just sort lambda's into | c | ascending order. | c | NOTES: | c | *workl(iw:iw+ncv-1) contain the theta ordered so that they | c | match the ordering of the lambda. We'll use them again for | c | Ritz vector purification. | c %-------------------------------------------------------------% c call dcopy (nconv, workl(ihd), 1, d, 1) call igraphdsortr ('LA', .true., nconv, workl(ihd), workl(iw)) if (rvec) then call igraphdsesrt ('LA', rvec , nconv, d, ncv, workl(iq), & ldq) else call dcopy (ncv, workl(bounds), 1, workl(ihb), 1) call dscal (ncv, bnorm2/rnorm, workl(ihb), 1) call igraphdsortr ('LA', .true., nconv, d, workl(ihb)) end if c end if c c %------------------------------------------------% c | Compute the Ritz vectors. Transform the wanted | c | eigenvectors of the symmetric tridiagonal H by | c | the Lanczos basis matrix V. | c %------------------------------------------------% c if (rvec .and. howmny .eq. 'A') then c c %----------------------------------------------------------% c | Compute the QR factorization of the matrix representing | c | the wanted invariant subspace located in the first NCONV | c | columns of workl(iq,ldq). | c %----------------------------------------------------------% c call dgeqr2 (ncv, nconv, workl(iq), ldq, workl(iw+ncv), & workl(ihb), ierr) c c c %--------------------------------------------------------% c | * Postmultiply V by Q. | c | * Copy the first NCONV columns of VQ into Z. | c | The N by NCONV matrix Z is now a matrix representation | c | of the approximate invariant subspace associated with | c | the Ritz values in workl(ihd). | c %--------------------------------------------------------% c call dorm2r ('Right', 'Notranspose', n, ncv, nconv, workl(iq), & ldq, workl(iw+ncv), v, ldv, workd(n+1), ierr) call dlacpy ('All', n, nconv, v, ldv, z, ldz) c c %-----------------------------------------------------% c | In order to compute the Ritz estimates for the Ritz | c | values in both systems, need the last row of the | c | eigenvector matrix. Remember, it's in factored form | c %-----------------------------------------------------% c do 65 j = 1, ncv-1 workl(ihb+j-1) = zero 65 continue workl(ihb+ncv-1) = one call dorm2r ('Left', 'Transpose', ncv, 1, nconv, workl(iq), & ldq, workl(iw+ncv), workl(ihb), ncv, temp, ierr) c else if (rvec .and. howmny .eq. 'S') then c c Not yet implemented. See remark 2 above. c end if c if (type .eq. 'REGULR' .and. rvec) then c do 70 j=1, ncv workl(ihb+j-1) = rnorm * abs( workl(ihb+j-1) ) 70 continue c else if (type .ne. 'REGULR' .and. rvec) then c c %-------------------------------------------------% c | * Determine Ritz estimates of the theta. | c | If RVEC = .true. then compute Ritz estimates | c | of the theta. | c | If RVEC = .false. then copy Ritz estimates | c | as computed by igraphdsaupd. | c | * Determine Ritz estimates of the lambda. | c %-------------------------------------------------% c call dscal (ncv, bnorm2, workl(ihb), 1) if (type .eq. 'SHIFTI') then c do 80 k=1, ncv workl(ihb+k-1) = abs( workl(ihb+k-1) ) / workl(iw+k-1)**2 80 continue c else if (type .eq. 'BUCKLE') then c do 90 k=1, ncv workl(ihb+k-1) = sigma * abs( workl(ihb+k-1) ) / & ( workl(iw+k-1)-one )**2 90 continue c else if (type .eq. 'CAYLEY') then c do 100 k=1, ncv workl(ihb+k-1) = abs( workl(ihb+k-1) / & workl(iw+k-1)*(workl(iw+k-1)-one) ) 100 continue c end if c end if c if (type .ne. 'REGULR' .and. msglvl .gt. 1) then call igraphdvout (logfil, nconv, d, ndigit, & '_seupd: Untransformed converged Ritz values') call igraphdvout (logfil, nconv, workl(ihb), ndigit, & '_seupd: Ritz estimates of the untransformed Ritz values') else if (msglvl .gt. 1) then call igraphdvout (logfil, nconv, d, ndigit, & '_seupd: Converged Ritz values') call igraphdvout (logfil, nconv, workl(ihb), ndigit, & '_seupd: Associated Ritz estimates') end if c c %-------------------------------------------------% c | Ritz vector purification step. Formally perform | c | one of inverse subspace iteration. Only used | c | for MODE = 3,4,5. See reference 7 | c %-------------------------------------------------% c if (rvec .and. (type .eq. 'SHIFTI' .or. type .eq. 'CAYLEY')) then c do 110 k=0, nconv-1 workl(iw+k) = workl(iq+k*ldq+ncv-1) / workl(iw+k) 110 continue c else if (rvec .and. type .eq. 'BUCKLE') then c do 120 k=0, nconv-1 workl(iw+k) = workl(iq+k*ldq+ncv-1) / (workl(iw+k)-one) 120 continue c end if c if (type .ne. 'REGULR') & call dger (n, nconv, one, resid, 1, workl(iw), 1, z, ldz) c 9000 continue c return c c %---------------% c | End of igraphdseupd | c %---------------% c end igraph/src/walktrap_communities.cpp0000644000175100001440000006623313431000472017302 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: communities.cpp //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #include "walktrap_communities.h" #include #include #include #include #include "config.h" namespace igraph { namespace walktrap { IGRAPH_THREAD_LOCAL int Probabilities::length = 0; IGRAPH_THREAD_LOCAL Communities* Probabilities::C = 0; IGRAPH_THREAD_LOCAL float* Probabilities::tmp_vector1 = 0; IGRAPH_THREAD_LOCAL float* Probabilities::tmp_vector2 = 0; IGRAPH_THREAD_LOCAL int* Probabilities::id = 0; IGRAPH_THREAD_LOCAL int* Probabilities::vertices1 = 0; IGRAPH_THREAD_LOCAL int* Probabilities::vertices2 = 0; IGRAPH_THREAD_LOCAL int Probabilities::current_id = 0; Neighbor::Neighbor() { next_community1 = 0; previous_community1 = 0; next_community2 = 0; previous_community2 = 0; heap_index = -1; } Probabilities::~Probabilities() { C->memory_used -= memory(); if(P) delete[] P; if(vertices) delete[] vertices; } Probabilities::Probabilities(int community) { Graph* G = C->G; int nb_vertices1 = 0; int nb_vertices2 = 0; float initial_proba = 1./float(C->communities[community].size); int last = C->members[C->communities[community].last_member]; for(int m = C->communities[community].first_member; m != last; m = C->members[m]) { tmp_vector1[m] = initial_proba; vertices1[nb_vertices1++] = m; } for(int t = 0; t < length; t++) { current_id++; if(nb_vertices1 > (G->nb_vertices/2)) { nb_vertices2 = G->nb_vertices; for(int i = 0; i < G->nb_vertices; i++) tmp_vector2[i] = 0.; if(nb_vertices1 == G->nb_vertices) { for(int i = 0; i < G->nb_vertices; i++) { float proba = tmp_vector1[i]/G->vertices[i].total_weight; for(int j = 0; j < G->vertices[i].degree; j++) tmp_vector2[G->vertices[i].edges[j].neighbor] += proba*G->vertices[i].edges[j].weight; } } else { for(int i = 0; i < nb_vertices1; i++) { int v1 = vertices1[i]; float proba = tmp_vector1[v1]/G->vertices[v1].total_weight; for(int j = 0; j < G->vertices[v1].degree; j++) tmp_vector2[G->vertices[v1].edges[j].neighbor] += proba*G->vertices[v1].edges[j].weight; } } } else { nb_vertices2 = 0; for(int i = 0; i < nb_vertices1; i++) { int v1 = vertices1[i]; float proba = tmp_vector1[v1]/G->vertices[v1].total_weight; for(int j = 0; j < G->vertices[v1].degree; j++) { int v2 = G->vertices[v1].edges[j].neighbor; if(id[v2] == current_id) tmp_vector2[v2] += proba*G->vertices[v1].edges[j].weight; else { tmp_vector2[v2] = proba*G->vertices[v1].edges[j].weight; id[v2] = current_id; vertices2[nb_vertices2++] = v2; } } } } float* tmp = tmp_vector2; tmp_vector2 = tmp_vector1; tmp_vector1 = tmp; int* tmp2 = vertices2; vertices2 = vertices1; vertices1 = tmp2; nb_vertices1 = nb_vertices2; } if(nb_vertices1 > (G->nb_vertices/2)) { P = new float[G->nb_vertices]; size = G->nb_vertices; vertices = 0; if(nb_vertices1 == G->nb_vertices) { for(int i = 0; i < G->nb_vertices; i++) P[i] = tmp_vector1[i]/sqrt(G->vertices[i].total_weight); } else { for(int i = 0; i < G->nb_vertices; i++) P[i] = 0.; for(int i = 0; i < nb_vertices1; i++) P[vertices1[i]] = tmp_vector1[vertices1[i]]/sqrt(G->vertices[vertices1[i]].total_weight); } } else { P = new float[nb_vertices1]; size = nb_vertices1; vertices = new int[nb_vertices1]; int j = 0; for(int i = 0; i < G->nb_vertices; i++) { if(id[i] == current_id) { P[j] = tmp_vector1[i]/sqrt(G->vertices[i].total_weight); vertices[j] = i; j++; } } } C->memory_used += memory(); } Probabilities::Probabilities(int community1, int community2) { // The two following probability vectors must exist. // Do not call this function if it is not the case. Probabilities* P1 = C->communities[community1].P; Probabilities* P2 = C->communities[community2].P; float w1 = float(C->communities[community1].size)/float(C->communities[community1].size + C->communities[community2].size); float w2 = float(C->communities[community2].size)/float(C->communities[community1].size + C->communities[community2].size); if(P1->size == C->G->nb_vertices) { P = new float[C->G->nb_vertices]; size = C->G->nb_vertices; vertices = 0; if(P2->size == C->G->nb_vertices) { // two full vectors for(int i = 0; i < C->G->nb_vertices; i++) P[i] = P1->P[i]*w1 + P2->P[i]*w2; } else { // P1 full vector, P2 partial vector int j = 0; for(int i = 0; i < P2->size; i++) { for(; j < P2->vertices[i]; j++) P[j] = P1->P[j]*w1; P[j] = P1->P[j]*w1 + P2->P[i]*w2; j++; } for(; j < C->G->nb_vertices; j++) P[j] = P1->P[j]*w1; } } else { if(P2->size == C->G->nb_vertices) { // P1 partial vector, P2 full vector P = new float[C->G->nb_vertices]; size = C->G->nb_vertices; vertices = 0; int j = 0; for(int i = 0; i < P1->size; i++) { for(; j < P1->vertices[i]; j++) P[j] = P2->P[j]*w2; P[j] = P1->P[i]*w1 + P2->P[j]*w2; j++; } for(; j < C->G->nb_vertices; j++) P[j] = P2->P[j]*w2; } else { // two partial vectors int i = 0; int j = 0; int nb_vertices1 = 0; while((i < P1->size) && (j < P2->size)) { if(P1->vertices[i] < P2->vertices[j]) { tmp_vector1[P1->vertices[i]] = P1->P[i]*w1; vertices1[nb_vertices1++] = P1->vertices[i]; i++; continue; } if(P1->vertices[i] > P2->vertices[j]) { tmp_vector1[P2->vertices[j]] = P2->P[j]*w2; vertices1[nb_vertices1++] = P2->vertices[j]; j++; continue; } tmp_vector1[P1->vertices[i]] = P1->P[i]*w1 + P2->P[j]*w2; vertices1[nb_vertices1++] = P1->vertices[i]; i++; j++; } if(i == P1->size) { for(; j < P2->size; j++) { tmp_vector1[P2->vertices[j]] = P2->P[j]*w2; vertices1[nb_vertices1++] = P2->vertices[j]; } } else { for(; i < P1->size; i++) { tmp_vector1[P1->vertices[i]] = P1->P[i]*w1; vertices1[nb_vertices1++] = P1->vertices[i]; } } if(nb_vertices1 > (C->G->nb_vertices/2)) { P = new float[C->G->nb_vertices]; size = C->G->nb_vertices; vertices = 0; for(int i = 0; i < C->G->nb_vertices; i++) P[i] = 0.; for(int i = 0; i < nb_vertices1; i++) P[vertices1[i]] = tmp_vector1[vertices1[i]]; } else { P = new float[nb_vertices1]; size = nb_vertices1; vertices = new int[nb_vertices1]; for(int i = 0; i < nb_vertices1; i++) { vertices[i] = vertices1[i]; P[i] = tmp_vector1[vertices1[i]]; } } } } C->memory_used += memory(); } double Probabilities::compute_distance(const Probabilities* P2) const { double r = 0.; if(vertices) { if(P2->vertices) { // two partial vectors int i = 0; int j = 0; while((i < size) && (j < P2->size)) { if(vertices[i] < P2->vertices[j]) { r += P[i]*P[i]; i++; continue; } if(vertices[i] > P2->vertices[j]) { r += P2->P[j]*P2->P[j]; j++; continue; } r += (P[i] - P2->P[j])*(P[i] - P2->P[j]); i++; j++; } if(i == size) { for(; j < P2->size; j++) r += P2->P[j]*P2->P[j]; } else { for(; i < size; i++) r += P[i]*P[i]; } } else { // P1 partial vector, P2 full vector int i = 0; for(int j = 0; j < size; j++) { for(; i < vertices[j]; i++) r += P2->P[i]*P2->P[i]; r += (P[j] - P2->P[i])*(P[j] - P2->P[i]); i++; } for(; i < P2->size; i++) r += P2->P[i]*P2->P[i]; } } else { if(P2->vertices) { // P1 full vector, P2 partial vector int i = 0; for(int j = 0; j < P2->size; j++) { for(; i < P2->vertices[j]; i++) r += P[i]*P[i]; r += (P[i] - P2->P[j])*(P[i] - P2->P[j]); i++; } for(; i < size; i++) r += P[i]*P[i]; } else { // two full vectors for(int i = 0; i < size; i++) r += (P[i] - P2->P[i])*(P[i] - P2->P[i]); } } return r; } long Probabilities::memory() { if(vertices) return (sizeof(Probabilities) + long(size)*(sizeof(float) + sizeof(int))); else return (sizeof(Probabilities) + long(size)*sizeof(float)); } Community::Community() { P = 0; first_neighbor = 0; last_neighbor = 0; sub_community_of = -1; sub_communities[0] = -1; sub_communities[1] = -1; sigma = 0.; internal_weight = 0.; total_weight = 0.; } Community::~Community() { if(P) delete P; } Communities::Communities(Graph* graph, int random_walks_length, long m, igraph_matrix_t *pmerges, igraph_vector_t *pmodularity) { max_memory = m; memory_used = 0; G = graph; merges=pmerges; mergeidx=0; modularity=pmodularity; Probabilities::C = this; Probabilities::length = random_walks_length; Probabilities::tmp_vector1 = new float[G->nb_vertices]; Probabilities::tmp_vector2 = new float[G->nb_vertices]; Probabilities::id = new int[G->nb_vertices]; for(int i = 0; i < G->nb_vertices; i++) Probabilities::id[i] = 0; Probabilities::vertices1 = new int[G->nb_vertices]; Probabilities::vertices2 = new int[G->nb_vertices]; Probabilities::current_id = 0; members = new int[G->nb_vertices]; for(int i = 0; i < G->nb_vertices; i++) members[i] = -1; H = new Neighbor_heap(G->nb_edges); communities = new Community[2*G->nb_vertices]; // init the n single vertex communities if(max_memory != -1) min_delta_sigma = new Min_delta_sigma_heap(G->nb_vertices*2); else min_delta_sigma = 0; for(int i = 0; i < G->nb_vertices; i++) { communities[i].this_community = i; communities[i].first_member = i; communities[i].last_member = i; communities[i].size = 1; communities[i].sub_community_of = 0; } nb_communities = G->nb_vertices; nb_active_communities = G->nb_vertices; for(int i = 0; i < G->nb_vertices; i++) for(int j = 0; j < G->vertices[i].degree; j++) if (i < G->vertices[i].edges[j].neighbor) { communities[i].total_weight += G->vertices[i].edges[j].weight/2.; communities[G->vertices[i].edges[j].neighbor].total_weight += G->vertices[i].edges[j].weight/2.; Neighbor* N = new Neighbor; N->community1 = i; N->community2 = G->vertices[i].edges[j].neighbor; N->delta_sigma = -1./double(min(G->vertices[i].degree, G->vertices[G->vertices[i].edges[j].neighbor].degree)); N->weight = G->vertices[i].edges[j].weight; N->exact = false; add_neighbor(N); } if(max_memory != -1) { memory_used += min_delta_sigma->memory(); memory_used += 2*long(G->nb_vertices)*sizeof(Community); memory_used += long(G->nb_vertices)*(2*sizeof(float) + 3*sizeof(int)); // the static data of Probabilities class memory_used += H->memory() + long(G->nb_edges)*sizeof(Neighbor); memory_used += G->memory(); } /* int c = 0; */ Neighbor* N = H->get_first(); if (N == 0) return; /* this can happen if there are no edges */ while(!N->exact) { update_neighbor(N, compute_delta_sigma(N->community1, N->community2)); N->exact = true; N = H->get_first(); if(max_memory != -1) manage_memory(); /* TODO: this could use igraph_progress */ /* if(!silent) { */ /* c++; */ /* for(int k = (500*(c-1))/G->nb_edges + 1; k <= (500*c)/G->nb_edges; k++) { */ /* if(k % 50 == 1) {cerr.width(2); cerr << endl << k/ 5 << "% ";} */ /* cerr << "."; */ /* } */ /* } */ } } Communities::~Communities() { delete[] members; delete[] communities; delete H; if(min_delta_sigma) delete min_delta_sigma; delete[] Probabilities::tmp_vector1; delete[] Probabilities::tmp_vector2; delete[] Probabilities::id; delete[] Probabilities::vertices1; delete[] Probabilities::vertices2; } float Community::min_delta_sigma() { float r = 1.; for(Neighbor* N = first_neighbor; N != 0;) { if(N->delta_sigma < r) r = N->delta_sigma; if(N->community1 == this_community) N = N->next_community1; else N = N->next_community2; } return r; } void Community::add_neighbor(Neighbor* N) { // add a new neighbor at the end of the list if (last_neighbor) { if(last_neighbor->community1 == this_community) last_neighbor->next_community1 = N; else last_neighbor->next_community2 = N; if(N->community1 == this_community) N->previous_community1 = last_neighbor; else N->previous_community2 = last_neighbor; } else { first_neighbor = N; if(N->community1 == this_community) N->previous_community1 = 0; else N->previous_community2 = 0; } last_neighbor = N; } void Community::remove_neighbor(Neighbor* N) { // remove a neighbor from the list if (N->community1 == this_community) { if(N->next_community1) { // if (N->next_community1->community1 == this_community) N->next_community1->previous_community1 = N->previous_community1; // else // N->next_community1->previous_community2 = N->previous_community1; } else last_neighbor = N->previous_community1; if(N->previous_community1) { if (N->previous_community1->community1 == this_community) N->previous_community1->next_community1 = N->next_community1; else N->previous_community1->next_community2 = N->next_community1; } else first_neighbor = N->next_community1; } else { if(N->next_community2) { if (N->next_community2->community1 == this_community) N->next_community2->previous_community1 = N->previous_community2; else N->next_community2->previous_community2 = N->previous_community2; } else last_neighbor = N->previous_community2; if(N->previous_community2) { // if (N->previous_community2->community1 == this_community) // N->previous_community2->next_community1 = N->next_community2; // else N->previous_community2->next_community2 = N->next_community2; } else first_neighbor = N->next_community2; } } void Communities::remove_neighbor(Neighbor* N) { communities[N->community1].remove_neighbor(N); communities[N->community2].remove_neighbor(N); H->remove(N); if(max_memory !=-1) { if(N->delta_sigma == min_delta_sigma->delta_sigma[N->community1]) { min_delta_sigma->delta_sigma[N->community1] = communities[N->community1].min_delta_sigma(); if(communities[N->community1].P) min_delta_sigma->update(N->community1); } if(N->delta_sigma == min_delta_sigma->delta_sigma[N->community2]) { min_delta_sigma->delta_sigma[N->community2] = communities[N->community2].min_delta_sigma(); if(communities[N->community2].P) min_delta_sigma->update(N->community2); } } } void Communities::add_neighbor(Neighbor* N) { communities[N->community1].add_neighbor(N); communities[N->community2].add_neighbor(N); H->add(N); if(max_memory !=-1) { if(N->delta_sigma < min_delta_sigma->delta_sigma[N->community1]) { min_delta_sigma->delta_sigma[N->community1] = N->delta_sigma; if(communities[N->community1].P) min_delta_sigma->update(N->community1); } if(N->delta_sigma < min_delta_sigma->delta_sigma[N->community2]) { min_delta_sigma->delta_sigma[N->community2] = N->delta_sigma; if(communities[N->community2].P) min_delta_sigma->update(N->community2); } } } void Communities::update_neighbor(Neighbor* N, float new_delta_sigma) { if(max_memory !=-1) { if(new_delta_sigma < min_delta_sigma->delta_sigma[N->community1]) { min_delta_sigma->delta_sigma[N->community1] = new_delta_sigma; if(communities[N->community1].P) min_delta_sigma->update(N->community1); } if(new_delta_sigma < min_delta_sigma->delta_sigma[N->community2]) { min_delta_sigma->delta_sigma[N->community2] = new_delta_sigma; if(communities[N->community2].P) min_delta_sigma->update(N->community2); } float old_delta_sigma = N->delta_sigma; N->delta_sigma = new_delta_sigma; H->update(N); if(old_delta_sigma == min_delta_sigma->delta_sigma[N->community1]) { min_delta_sigma->delta_sigma[N->community1] = communities[N->community1].min_delta_sigma(); if(communities[N->community1].P) min_delta_sigma->update(N->community1); } if(old_delta_sigma == min_delta_sigma->delta_sigma[N->community2]) { min_delta_sigma->delta_sigma[N->community2] = communities[N->community2].min_delta_sigma(); if(communities[N->community2].P) min_delta_sigma->update(N->community2); } } else { N->delta_sigma = new_delta_sigma; H->update(N); } } void Communities::manage_memory() { while((memory_used > max_memory) && !min_delta_sigma->is_empty()) { int c = min_delta_sigma->get_max_community(); delete communities[c].P; communities[c].P = 0; min_delta_sigma->remove_community(c); } } void Communities::merge_communities(Neighbor* merge_N) { int c1 = merge_N->community1; int c2 = merge_N->community2; communities[nb_communities].first_member = communities[c1].first_member; // merge the communities[nb_communities].last_member = communities[c2].last_member; // two lists members[communities[c1].last_member] = communities[c2].first_member; // of members communities[nb_communities].size = communities[c1].size + communities[c2].size; communities[nb_communities].this_community = nb_communities; communities[nb_communities].sub_community_of = 0; communities[nb_communities].sub_communities[0] = c1; communities[nb_communities].sub_communities[1] = c2; communities[nb_communities].total_weight = communities[c1].total_weight + communities[c2].total_weight; communities[nb_communities].internal_weight = communities[c1].internal_weight + communities[c2].internal_weight + merge_N->weight; communities[nb_communities].sigma = communities[c1].sigma + communities[c2].sigma + merge_N->delta_sigma; communities[c1].sub_community_of = nb_communities; communities[c2].sub_community_of = nb_communities; // update the new probability vector... if(communities[c1].P && communities[c2].P) communities[nb_communities].P = new Probabilities(c1, c2); if(communities[c1].P) { delete communities[c1].P; communities[c1].P = 0; if(max_memory != -1) min_delta_sigma->remove_community(c1); } if(communities[c2].P) { delete communities[c2].P; communities[c2].P = 0; if(max_memory != -1) min_delta_sigma->remove_community(c2); } if(max_memory != -1) { min_delta_sigma->delta_sigma[c1] = -1.; // to avoid to update the min_delta_sigma for these communities min_delta_sigma->delta_sigma[c2] = -1.; // min_delta_sigma->delta_sigma[nb_communities] = -1.; } // update the new neighbors // by enumerating all the neighbors of c1 and c2 Neighbor* N1 = communities[c1].first_neighbor; Neighbor* N2 = communities[c2].first_neighbor; while(N1 && N2) { int neighbor_community1; int neighbor_community2; if (N1->community1 == c1) neighbor_community1 = N1->community2; else neighbor_community1 = N1->community1; if (N2->community1 == c2) neighbor_community2 = N2->community2; else neighbor_community2 = N2->community1; if (neighbor_community1 < neighbor_community2) { Neighbor* tmp = N1; if (N1->community1 == c1) N1 = N1->next_community1; else N1 = N1->next_community2; remove_neighbor(tmp); Neighbor* N = new Neighbor; N->weight = tmp->weight; N->community1 = neighbor_community1; N->community2 = nb_communities; N->delta_sigma = (double(communities[c1].size+communities[neighbor_community1].size)*tmp->delta_sigma + double(communities[c2].size)*merge_N->delta_sigma)/(double(communities[c1].size+communities[c2].size+communities[neighbor_community1].size));//compute_delta_sigma(neighbor_community1, nb_communities); N->exact = false; delete tmp; add_neighbor(N); } if (neighbor_community2 < neighbor_community1) { Neighbor* tmp = N2; if (N2->community1 == c2) N2 = N2->next_community1; else N2 = N2->next_community2; remove_neighbor(tmp); Neighbor* N = new Neighbor; N->weight = tmp->weight; N->community1 = neighbor_community2; N->community2 = nb_communities; N->delta_sigma = (double(communities[c1].size)*merge_N->delta_sigma + double(communities[c2].size+communities[neighbor_community2].size)*tmp->delta_sigma)/(double(communities[c1].size+communities[c2].size+communities[neighbor_community2].size));//compute_delta_sigma(neighbor_community2, nb_communities); N->exact = false; delete tmp; add_neighbor(N); } if (neighbor_community1 == neighbor_community2) { Neighbor* tmp1 = N1; Neighbor* tmp2 = N2; bool exact = N1->exact && N2->exact; if (N1->community1 == c1) N1 = N1->next_community1; else N1 = N1->next_community2; if (N2->community1 == c2) N2 = N2->next_community1; else N2 = N2->next_community2; remove_neighbor(tmp1); remove_neighbor(tmp2); Neighbor* N = new Neighbor; N->weight = tmp1->weight + tmp2->weight; N->community1 = neighbor_community1; N->community2 = nb_communities; N->delta_sigma = (double(communities[c1].size+communities[neighbor_community1].size)*tmp1->delta_sigma + double(communities[c2].size+communities[neighbor_community1].size)*tmp2->delta_sigma - double(communities[neighbor_community1].size)*merge_N->delta_sigma)/(double(communities[c1].size+communities[c2].size+communities[neighbor_community1].size)); N->exact = exact; delete tmp1; delete tmp2; add_neighbor(N); } } if(!N1) { while(N2) { // double delta_sigma2 = N2->delta_sigma; int neighbor_community; if (N2->community1 == c2) neighbor_community = N2->community2; else neighbor_community = N2->community1; Neighbor* tmp = N2; if (N2->community1 == c2) N2 = N2->next_community1; else N2 = N2->next_community2; remove_neighbor(tmp); Neighbor* N = new Neighbor; N->weight = tmp->weight; N->community1 = neighbor_community; N->community2 = nb_communities; N->delta_sigma = (double(communities[c1].size)*merge_N->delta_sigma + double(communities[c2].size+communities[neighbor_community].size)*tmp->delta_sigma)/(double(communities[c1].size+communities[c2].size+communities[neighbor_community].size));//compute_delta_sigma(neighbor_community, nb_communities); N->exact = false; delete tmp; add_neighbor(N); } } if(!N2) { while(N1) { // double delta_sigma1 = N1->delta_sigma; int neighbor_community; if (N1->community1 == c1) neighbor_community = N1->community2; else neighbor_community = N1->community1; Neighbor* tmp = N1; if (N1->community1 == c1) N1 = N1->next_community1; else N1 = N1->next_community2; remove_neighbor(tmp); Neighbor* N = new Neighbor; N->weight = tmp->weight; N->community1 = neighbor_community; N->community2 = nb_communities; N->delta_sigma = (double(communities[c1].size+communities[neighbor_community].size)*tmp->delta_sigma + double(communities[c2].size)*merge_N->delta_sigma)/(double(communities[c1].size+communities[c2].size+communities[neighbor_community].size));//compute_delta_sigma(neighbor_community, nb_communities); N->exact = false; delete tmp; add_neighbor(N); } } if(max_memory != -1) { min_delta_sigma->delta_sigma[nb_communities] = communities[nb_communities].min_delta_sigma(); min_delta_sigma->update(nb_communities); } nb_communities++; nb_active_communities--; } double Communities::merge_nearest_communities() { Neighbor* N = H->get_first(); while(!N->exact) { update_neighbor(N, compute_delta_sigma(N->community1, N->community2)); N->exact = true; N = H->get_first(); if(max_memory != -1) manage_memory(); } double d = N->delta_sigma; remove_neighbor(N); merge_communities(N); if(max_memory != -1) manage_memory(); if (merges) { MATRIX(*merges, mergeidx, 0)=N->community1; MATRIX(*merges, mergeidx, 1)=N->community2; mergeidx++; } if (modularity) { float Q = 0.; for(int i = 0; i < nb_communities; i++) { if(communities[i].sub_community_of == 0) { Q += (communities[i].internal_weight - communities[i].total_weight*communities[i].total_weight/G->total_weight)/G->total_weight; } } VECTOR(*modularity)[mergeidx]=Q; } delete N; /* This could use igraph_progress */ /* if(!silent) { */ /* for(int k = (500*(G->nb_vertices - nb_active_communities - 1))/(G->nb_vertices-1) + 1; k <= (500*(G->nb_vertices - nb_active_communities))/(G->nb_vertices-1); k++) { */ /* if(k % 50 == 1) {cerr.width(2); cerr << endl << k/ 5 << "% ";} */ /* cerr << "."; */ /* } */ /* } */ return d; } double Communities::compute_delta_sigma(int community1, int community2) { if(!communities[community1].P) { communities[community1].P = new Probabilities(community1); if(max_memory != -1) min_delta_sigma->update(community1); } if(!communities[community2].P) { communities[community2].P = new Probabilities(community2); if(max_memory != -1) min_delta_sigma->update(community2); } return communities[community1].P->compute_distance(communities[community2].P)*double(communities[community1].size)*double(communities[community2].size)/double(communities[community1].size + communities[community2].size); } } } /* end of namespaces */ igraph/src/sugiyama.c0000644000175100001440000013663313431000472014322 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "igraph_centrality.h" #include "igraph_components.h" #include "igraph_constants.h" #include "igraph_constructors.h" #include "igraph_datatype.h" #include "igraph_error.h" #include "igraph_glpk_support.h" #include "igraph_interface.h" #include "igraph_memory.h" #include "igraph_structural.h" #include "igraph_types.h" #include /* #define SUGIYAMA_DEBUG */ #ifdef _MSC_VER /* MSVC does not support variadic macros */ #include static void debug(const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef SUGIYAMA_DEBUG vfprintf(stderr, fmt, args); #endif va_end(args); } #else # ifdef SUGIYAMA_DEBUG # define debug(...) fprintf(stderr, __VA_ARGS__) # else # define debug(...) # endif #endif /* MSVC uses __forceinline instead of inline */ #ifdef _MSC_VER # define INLINE __forceinline #else # define INLINE inline #endif /* * Implementation of the Sugiyama layout algorithm as described in: * * [1] K. Sugiyama, S. Tagawa and M. Toda, "Methods for Visual Understanding of * Hierarchical Systems". IEEE Transactions on Systems, Man and Cybernetics * 11(2):109-125, 1981. * * The layering (if not given in advance) is calculated by ... TODO * * [2] TODO * * The X coordinates of nodes within a layer are calculated using the method of * Brandes & Köpf: * * [3] U. Brandes and B. Köpf, "Fast and Simple Horizontal Coordinate * Assignment". In: Lecture Notes in Computer Science 2265:31-44, 2002. * * Layer compaction is done according to: * * [4] N.S. Nikolov and A. Tarassov, "Graph layering by promotion of nodes". * Journal of Discrete Applied Mathematics, special issue: IV ALIO/EURO * workshop on applied combinatorial optimization, 154(5). * * The steps of the algorithm are as follows: * * 1. Cycle removal by finding an approximately minimal feedback arc set * and reversing the direction of edges in the set. Algorithms for * finding minimal feedback arc sets are as follows: * * - Find a cycle and find its minimum weight edge. Decrease the weight * of all the edges by w. Remove those edges whose weight became zero. * Repeat until there are no cycles. Re-introduce removed edges in * decreasing order of weights, ensuring that no cycles are created. * * - Order the vertices somehow and remove edges which point backwards * in the ordering. Eades et al proposed the following procedure: * * 1. Iteratively remove sinks and prepend them to a vertex sequence * s2. * * 2. Iteratively remove sources and append them to a vertex sequence * s1. * * 3. Choose a vertex u s.t. the difference between the number of * rightward arcs and the number of leftward arcs is the largest, * remove u and append it to s1. Goto step 1 if there are still * more vertices. * * 4. Concatenate s1 with s2. * * This algorithm is known to produce feedback arc sets at most the * size of m/2 - n/6, where m is the number of edges. Further * improvements are possible in step 3 which bring down the size of * the set to at most m/4 for cubic directed graphs, see Eades (1995). * * - For undirected graphs, find a maximum weight spanning tree and * remove all the edges not in the spanning tree. For directed graphs, * find minimal cuts iteratively and remove edges pointing from A to * B or from B to A in the cut, depending on which one is smaller. Yes, * this is time-consuming. * * 2. Assigning vertices to layers according to [2]. * * 3. Extracting weakly connected components. The remaining steps are * executed for each component. * * 4. Compacting the layering using the method of [4]. TODO * Steps 2-4 are performed only when no layering is given in advance. * * 5. Adding dummy nodes to ensure that each edge spans at most one layer * only. * * 6. Finding an optimal ordering of vertices within a layer using the * Sugiyama framework [1]. * * 7. Assigning horizontal coordinates to each vertex using [3]. * * 8. ??? * * 9. Profit! */ /** * Data structure to store a layering of the graph. */ typedef struct { igraph_vector_ptr_t layers; } igraph_i_layering_t; /** * Initializes a layering. */ int igraph_i_layering_init(igraph_i_layering_t* layering, const igraph_vector_t* membership) { long int i, n, num_layers; if (igraph_vector_size(membership) == 0) num_layers = 0; else num_layers = (long int) igraph_vector_max(membership) + 1; IGRAPH_CHECK(igraph_vector_ptr_init(&layering->layers, num_layers)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &layering->layers); for (i = 0; i < num_layers; i++) { igraph_vector_t* vec = igraph_Calloc(1, igraph_vector_t); IGRAPH_VECTOR_INIT_FINALLY(vec, 0); VECTOR(layering->layers)[i] = vec; IGRAPH_FINALLY_CLEAN(1); } IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&layering->layers, igraph_vector_destroy); n = igraph_vector_size(membership); for (i = 0; i < n; i++) { long int l = (long int) VECTOR(*membership)[i]; igraph_vector_t* vec = VECTOR(layering->layers)[l]; IGRAPH_CHECK(igraph_vector_push_back(vec, i)); } IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * Destroys a layering. */ void igraph_i_layering_destroy(igraph_i_layering_t* layering) { igraph_vector_ptr_destroy_all(&layering->layers); } /** * Returns the number of layers in a layering. */ int igraph_i_layering_num_layers(const igraph_i_layering_t* layering) { return (int) igraph_vector_ptr_size(&layering->layers); } /** * Returns the list of vertices in a given layer */ igraph_vector_t* igraph_i_layering_get(const igraph_i_layering_t* layering, long int index) { return (igraph_vector_t*)VECTOR(layering->layers)[index]; } /** * Forward declarations */ static int igraph_i_layout_sugiyama_place_nodes_vertically(const igraph_t* graph, const igraph_vector_t* weights, igraph_vector_t* membership); static int igraph_i_layout_sugiyama_order_nodes_horizontally(const igraph_t* graph, igraph_matrix_t* layout, const igraph_i_layering_t* layering, long int maxiter); static int igraph_i_layout_sugiyama_place_nodes_horizontally(const igraph_t* graph, igraph_matrix_t* layout, const igraph_i_layering_t* layering, igraph_real_t hgap, igraph_integer_t no_of_real_nodes); /** * Calculated the median of four numbers (not necessarily sorted). */ static INLINE igraph_real_t igraph_i_median_4(igraph_real_t x1, igraph_real_t x2, igraph_real_t x3, igraph_real_t x4) { igraph_real_t arr[4] = { x1, x2, x3, x4 }; igraph_vector_t vec; igraph_vector_view(&vec, arr, 4); igraph_vector_sort(&vec); return (arr[1] + arr[2]) / 2.0; } /** * \ingroup layout * \function igraph_layout_sugiyama * \brief Sugiyama layout algorithm for layered directed acyclic graphs. * * * This layout algorithm is designed for directed acyclic graphs where each * vertex is assigned to a layer. Layers are indexed from zero, and vertices * of the same layer will be placed on the same horizontal line. The X coordinates * of vertices within each layer are decided by the heuristic proposed by * Sugiyama et al to minimize edge crossings. * * * You can also try to lay out undirected graphs, graphs containing cycles, or * graphs without an a priori layered assignment with this algorithm. igraph * will try to eliminate cycles and assign vertices to layers, but there is no * guarantee on the quality of the layout in such cases. * * * The Sugiyama layout may introduce "bends" on the edges in order to obtain a * visually more pleasing layout. This is achieved by adding dummy nodes to * edges spanning more than one layer. The resulting layout assigns coordinates * not only to the nodes of the original graph but also to the dummy nodes. * The layout algorithm will also return the extended graph with the dummy nodes. * An edge in the original graph may either be mapped to a single edge in the * extended graph or a \em path that starts and ends in the original * source and target vertex and passes through multiple dummy vertices. In * such cases, the user may also request the mapping of the edges of the extended * graph back to the edges of the original graph. * * * For more details, see K. Sugiyama, S. Tagawa and M. Toda, "Methods for Visual * Understanding of Hierarchical Systems". IEEE Transactions on Systems, Man and * Cybernetics 11(2):109-125, 1981. * * \param graph Pointer to an initialized graph object. * \param res Pointer to an initialized matrix object. This will contain * the result and will be resized as needed. The first |V| rows * of the layout will contain the coordinates of the original graph, * the remaining rows contain the positions of the dummy nodes. * Therefore, you can use the result both with \p graph or with * \p extended_graph. * \param extended_graph Pointer to an uninitialized graph object or \c NULL. * The extended graph with the added dummy nodes will be * returned here. In this graph, each edge points downwards * to lower layers, spans exactly one layer and the first * |V| vertices coincide with the vertices of the * original graph. * \param extd_to_orig_eids Pointer to a vector or \c NULL. If not \c NULL, the * mapping from the edge IDs of the extended graph back * to the edge IDs of the original graph will be stored * here. * \param layers The layer index for each vertex or \c NULL if the layers should * be determined automatically by igraph. * \param hgap The preferred minimum horizontal gap between vertices in the same * layer. * \param vgap The distance between layers. * \param maxiter Maximum number of iterations in the crossing minimization stage. * 100 is a reasonable default; if you feel that you have too * many edge crossings, increase this. * \param weights Weights of the edges. These are used only if the graph contains * cycles; igraph will tend to reverse edges with smaller * weights when breaking the cycles. */ int igraph_layout_sugiyama(const igraph_t *graph, igraph_matrix_t *res, igraph_t *extd_graph, igraph_vector_t *extd_to_orig_eids, const igraph_vector_t* layers, igraph_real_t hgap, igraph_real_t vgap, long int maxiter, const igraph_vector_t *weights) { long int i, j, k, l, m, nei; long int no_of_nodes = (long int)igraph_vcount(graph); long int comp_idx; long int next_extd_vertex_id = no_of_nodes; igraph_bool_t directed = igraph_is_directed(graph); igraph_integer_t no_of_components; /* number of components of the original graph */ igraph_vector_t membership; /* components of the original graph */ igraph_vector_t extd_edgelist; /* edge list of the extended graph */ igraph_vector_t layers_own; /* layer indices after having eliminated empty layers */ igraph_real_t dx=0, dx2=0; /* displacement of the current component on the X axis */ igraph_vector_t layer_to_y; /* mapping from layer indices to final Y coordinates */ if (layers && igraph_vector_size(layers) != no_of_nodes) { IGRAPH_ERROR("layer vector too short or too long", IGRAPH_EINVAL); } if (extd_graph != 0) { IGRAPH_VECTOR_INIT_FINALLY(&extd_edgelist, 0); if (extd_to_orig_eids != 0) igraph_vector_clear(extd_to_orig_eids); } IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 2)); IGRAPH_VECTOR_INIT_FINALLY(&membership, 0); IGRAPH_VECTOR_INIT_FINALLY(&layer_to_y, 0); /* 1. Find a feedback arc set if we don't have a layering yet. If we do have * a layering, we can leave all the edges as is as they will be re-oriented * to point downwards only anyway. */ if (layers == 0) { IGRAPH_VECTOR_INIT_FINALLY(&layers_own, no_of_nodes); IGRAPH_CHECK(igraph_i_layout_sugiyama_place_nodes_vertically( graph, weights, &layers_own)); } else { IGRAPH_CHECK(igraph_vector_copy(&layers_own, layers)); IGRAPH_FINALLY(igraph_vector_destroy, &layers_own); } /* Normalize layering, eliminate empty layers */ if (no_of_nodes > 0) { igraph_vector_t inds; IGRAPH_VECTOR_INIT_FINALLY(&inds, 0); IGRAPH_CHECK((int) igraph_vector_qsort_ind(&layers_own, &inds, 0)); j = -1; dx = VECTOR(layers_own)[(long int)VECTOR(inds)[0]] - 1; for (i = 0; i < no_of_nodes; i++) { k = (long int)VECTOR(inds)[i]; if (VECTOR(layers_own)[k] > dx) { /* New layer starts here */ dx = VECTOR(layers_own)[k]; j++; IGRAPH_CHECK(igraph_vector_push_back(&layer_to_y, dx * vgap)); } VECTOR(layers_own)[k] = j; } igraph_vector_destroy(&inds); IGRAPH_FINALLY_CLEAN(1); } /* 2. Find the connected components. */ IGRAPH_CHECK(igraph_clusters(graph, &membership, 0, &no_of_components, IGRAPH_WEAK)); /* 3. For each component... */ dx = 0; for (comp_idx = 0; comp_idx < no_of_components; comp_idx++) { /* Extract the edges of the comp_idx'th component and add dummy nodes for edges * spanning more than one layer. */ long int component_size, next_new_vertex_id; igraph_vector_t old2new_vertex_ids; igraph_vector_t new2old_vertex_ids; igraph_vector_t new_layers; igraph_vector_t edgelist; igraph_vector_t neis; IGRAPH_VECTOR_INIT_FINALLY(&edgelist, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&new2old_vertex_ids, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&old2new_vertex_ids, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&new_layers, 0); igraph_vector_fill(&old2new_vertex_ids, -1); /* Construct a mapping from the old vertex ids to the new ones */ for (i = 0, next_new_vertex_id = 0; i < no_of_nodes; i++) { if (VECTOR(membership)[i] == comp_idx) { IGRAPH_CHECK(igraph_vector_push_back(&new_layers, VECTOR(layers_own)[i])); VECTOR(new2old_vertex_ids)[next_new_vertex_id] = i; VECTOR(old2new_vertex_ids)[i] = next_new_vertex_id; next_new_vertex_id++; } } component_size = next_new_vertex_id; /* Construct a proper layering of the component in new_graph where each edge * points downwards and spans exactly one layer. */ for (i = 0; i < no_of_nodes; i++) { if (VECTOR(membership)[i] != comp_idx) continue; /* Okay, this vertex is in the component we are considering. * Add the neighbors of this vertex, excluding loops */ IGRAPH_CHECK(igraph_incident(graph, &neis, (igraph_integer_t) i, IGRAPH_OUT)); j = igraph_vector_size(&neis); for (k = 0; k < j; k++) { long int eid = (long int) VECTOR(neis)[k]; if (directed) { nei = IGRAPH_TO(graph, eid); } else { nei = IGRAPH_OTHER(graph, eid, i); if (nei < i) /* to avoid considering edges twice */ continue; } if (VECTOR(layers_own)[i] == VECTOR(layers_own)[nei]) { /* Edge goes within the same layer, we don't need this in the * layered graph, but we need it in the extended graph */ if (extd_graph != 0) { IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, i)); IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, nei)); if (extd_to_orig_eids != 0) IGRAPH_CHECK(igraph_vector_push_back(extd_to_orig_eids, eid)); } } else if (VECTOR(layers_own)[i] > VECTOR(layers_own)[nei]) { /* Edge goes upwards, we have to flip it */ IGRAPH_CHECK(igraph_vector_push_back(&edgelist, VECTOR(old2new_vertex_ids)[nei])); for (l = (long int) VECTOR(layers_own)[nei]+1; l < VECTOR(layers_own)[i]; l++) { IGRAPH_CHECK(igraph_vector_push_back(&new_layers, l)); IGRAPH_CHECK(igraph_vector_push_back(&edgelist, next_new_vertex_id)); IGRAPH_CHECK(igraph_vector_push_back(&edgelist, next_new_vertex_id++)); } IGRAPH_CHECK(igraph_vector_push_back(&edgelist, VECTOR(old2new_vertex_ids)[i])); /* Also add the edge to the extended graph if needed, but this time * with the proper orientation */ if (extd_graph != 0) { IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, i)); next_extd_vertex_id += VECTOR(layers_own)[i] - VECTOR(layers_own)[nei] - 1; for (l = (long int) VECTOR(layers_own)[i]-1, m = 1; l > VECTOR(layers_own)[nei]; l--, m++) { IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, next_extd_vertex_id-m)); IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, next_extd_vertex_id-m)); if (extd_to_orig_eids != 0) IGRAPH_CHECK(igraph_vector_push_back(extd_to_orig_eids, eid)); } IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, nei)); if (extd_to_orig_eids != 0) IGRAPH_CHECK(igraph_vector_push_back(extd_to_orig_eids, eid)); } } else { /* Edge goes downwards */ IGRAPH_CHECK(igraph_vector_push_back(&edgelist, VECTOR(old2new_vertex_ids)[i])); for (l = (long int) VECTOR(layers_own)[i]+1; l < VECTOR(layers_own)[nei]; l++) { IGRAPH_CHECK(igraph_vector_push_back(&new_layers, l)); IGRAPH_CHECK(igraph_vector_push_back(&edgelist, next_new_vertex_id)); IGRAPH_CHECK(igraph_vector_push_back(&edgelist, next_new_vertex_id++)); } IGRAPH_CHECK(igraph_vector_push_back(&edgelist, VECTOR(old2new_vertex_ids)[nei])); /* Also add the edge to the extended graph */ if (extd_graph != 0) { IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, i)); for (l = (long int) VECTOR(layers_own)[i]+1; l < VECTOR(layers_own)[nei]; l++) { IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, next_extd_vertex_id)); IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, next_extd_vertex_id++)); if (extd_to_orig_eids != 0) IGRAPH_CHECK(igraph_vector_push_back(extd_to_orig_eids, eid)); } IGRAPH_CHECK(igraph_vector_push_back(&extd_edgelist, nei)); if (extd_to_orig_eids != 0) IGRAPH_CHECK(igraph_vector_push_back(extd_to_orig_eids, eid)); } } } } /* At this point, we have the subgraph with the dummy nodes and * edges, so we can run Sugiyama's algorithm on it. */ { igraph_matrix_t layout; igraph_i_layering_t layering; igraph_t subgraph; IGRAPH_CHECK(igraph_matrix_init(&layout, next_new_vertex_id, 2)); IGRAPH_FINALLY(igraph_matrix_destroy, &layout); IGRAPH_CHECK(igraph_create(&subgraph, &edgelist, (igraph_integer_t) next_new_vertex_id, 1)); IGRAPH_FINALLY(igraph_destroy, &subgraph); /* igraph_vector_print(&edgelist); igraph_vector_print(&new_layers); */ /* Assign the vertical coordinates */ for (i = 0; i < next_new_vertex_id; i++) MATRIX(layout, i, 1) = VECTOR(new_layers)[i]; /* Create a layering */ IGRAPH_CHECK(igraph_i_layering_init(&layering, &new_layers)); IGRAPH_FINALLY(igraph_i_layering_destroy, &layering); /* Find the order in which the nodes within a layer should be placed */ IGRAPH_CHECK(igraph_i_layout_sugiyama_order_nodes_horizontally(&subgraph, &layout, &layering, maxiter)); /* Assign the horizontal coordinates. This is according to the algorithm * of Brandes & Köpf */ IGRAPH_CHECK(igraph_i_layout_sugiyama_place_nodes_horizontally(&subgraph, &layout, &layering, hgap, (igraph_integer_t) component_size)); /* Re-assign rows into the result matrix, and at the same time, */ /* adjust dx so that the next component does not overlap this one */ j = next_new_vertex_id - component_size; k = igraph_matrix_nrow(res); IGRAPH_CHECK(igraph_matrix_add_rows(res, j)); dx2 = dx; for (i = 0; i < component_size; i++) { l = (long int)VECTOR(new2old_vertex_ids)[i]; MATRIX(*res, l, 0) = MATRIX(layout, i, 0) + dx; MATRIX(*res, l, 1) = VECTOR(layer_to_y)[(long)MATRIX(layout, i, 1)]; if (dx2 < MATRIX(*res, l, 0)) dx2 = MATRIX(*res, l, 0); } for (i = component_size; i < next_new_vertex_id; i++) { MATRIX(*res, k, 0) = MATRIX(layout, i, 0) + dx; MATRIX(*res, k, 1) = VECTOR(layer_to_y)[(long)MATRIX(layout, i, 1)]; if (dx2 < MATRIX(*res, k, 0)) dx2 = MATRIX(*res, k, 0); k++; } dx = dx2 + hgap; igraph_destroy(&subgraph); igraph_i_layering_destroy(&layering); igraph_matrix_destroy(&layout); IGRAPH_FINALLY_CLEAN(3); } igraph_vector_destroy(&new_layers); igraph_vector_destroy(&old2new_vertex_ids); igraph_vector_destroy(&new2old_vertex_ids); igraph_vector_destroy(&edgelist); igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(5); } igraph_vector_destroy(&layers_own); igraph_vector_destroy(&layer_to_y); igraph_vector_destroy(&membership); IGRAPH_FINALLY_CLEAN(3); if (extd_graph != 0) { IGRAPH_CHECK(igraph_create(extd_graph, &extd_edgelist, (igraph_integer_t) next_extd_vertex_id, igraph_is_directed(graph))); igraph_vector_destroy(&extd_edgelist); IGRAPH_FINALLY_CLEAN(1); } return IGRAPH_SUCCESS; } static int igraph_i_layout_sugiyama_place_nodes_vertically(const igraph_t* graph, const igraph_vector_t* weights, igraph_vector_t* membership) { long int no_of_nodes = igraph_vcount(graph); long int no_of_edges = igraph_ecount(graph); IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); if (no_of_edges == 0) { igraph_vector_fill(membership, 0); return IGRAPH_SUCCESS; } #ifdef HAVE_GLPK if (igraph_is_directed(graph) && no_of_nodes <= 1000) { /* Network simplex algorithm of Gansner et al, using the original linear * programming formulation */ long int i, j; igraph_vector_t outdegs, indegs, feedback_edges; glp_prob *ip; glp_smcp parm; /* Allocate storage and create the problem */ ip = glp_create_prob(); IGRAPH_FINALLY(glp_delete_prob, ip); IGRAPH_VECTOR_INIT_FINALLY(&feedback_edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&outdegs, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&indegs, no_of_nodes); /* Find an approximate feedback edge set */ IGRAPH_CHECK(igraph_i_feedback_arc_set_eades(graph, &feedback_edges, weights, 0)); igraph_vector_sort(&feedback_edges); /* Calculate in- and out-strengths for the remaining edges */ IGRAPH_CHECK(igraph_strength(graph, &indegs, igraph_vss_all(), IGRAPH_IN, 1, weights)); IGRAPH_CHECK(igraph_strength(graph, &outdegs, igraph_vss_all(), IGRAPH_IN, 1, weights)); j = igraph_vector_size(&feedback_edges); for (i = 0; i < j; i++) { long int eid = (long int) VECTOR(feedback_edges)[i]; long int from = IGRAPH_FROM(graph, eid); long int to = IGRAPH_TO(graph, eid); VECTOR(outdegs)[from] -= weights ? VECTOR(*weights)[eid] : 1; VECTOR(indegs)[to] -= weights ? VECTOR(*weights)[eid] : 1; } /* Configure GLPK */ glp_term_out(GLP_OFF); glp_init_smcp(&parm); parm.msg_lev = GLP_MSG_OFF; parm.presolve = GLP_OFF; /* Set up variables and objective function coefficients */ glp_set_obj_dir(ip, GLP_MIN); glp_add_cols(ip, (int) no_of_nodes); IGRAPH_CHECK(igraph_vector_sub(&outdegs, &indegs)); for (i = 1; i <= no_of_nodes; i++) { glp_set_col_kind(ip, (int) i, GLP_IV); glp_set_col_bnds(ip, (int) i, GLP_LO, 0.0, 0.0); glp_set_obj_coef(ip, (int) i, VECTOR(outdegs)[i-1]); } igraph_vector_destroy(&indegs); igraph_vector_destroy(&outdegs); IGRAPH_FINALLY_CLEAN(2); /* Add constraints */ glp_add_rows(ip, (int) no_of_edges); IGRAPH_CHECK(igraph_vector_push_back(&feedback_edges, -1)); j = 0; for (i = 0; i < no_of_edges; i++) { int ind[3]; double val[3] = {0, -1, 1}; ind[1] = IGRAPH_FROM(graph, i)+1; ind[2] = IGRAPH_TO(graph, i)+1; if (ind[1] == ind[2]) { if (VECTOR(feedback_edges)[j] == i) j++; continue; } if (VECTOR(feedback_edges)[j] == i) { /* This is a feedback edge, add it reversed */ glp_set_row_bnds(ip, (int) i+1, GLP_UP, -1, -1); j++; } else { glp_set_row_bnds(ip, (int) i+1, GLP_LO, 1, 1); } glp_set_mat_row(ip, (int) i+1, 2, ind, val); } /* Solve the problem */ IGRAPH_GLPK_CHECK(glp_simplex(ip, &parm), "Vertical arrangement step using IP failed"); /* The problem is totally unimodular, therefore the output of the simplex * solver can be converted to an integer solution easily */ for (i = 0; i < no_of_nodes; i++) VECTOR(*membership)[i] = floor(glp_get_col_prim(ip, (int) i+1)); glp_delete_prob(ip); igraph_vector_destroy(&feedback_edges); IGRAPH_FINALLY_CLEAN(2); } else if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_feedback_arc_set_eades(graph, 0, weights, membership)); } else { IGRAPH_CHECK(igraph_i_feedback_arc_set_undirected(graph, 0, weights, membership)); } #else if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_feedback_arc_set_eades(graph, 0, weights, membership)); } else { IGRAPH_CHECK(igraph_i_feedback_arc_set_undirected(graph, 0, weights, membership)); } #endif return IGRAPH_SUCCESS; } static int igraph_i_layout_sugiyama_calculate_barycenters(const igraph_t* graph, const igraph_i_layering_t* layering, long int layer_index, igraph_neimode_t direction, const igraph_matrix_t* layout, igraph_vector_t* barycenters) { long int i, j, m, n; igraph_vector_t* layer_members = igraph_i_layering_get(layering, layer_index); igraph_vector_t neis; IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); n = igraph_vector_size(layer_members); IGRAPH_CHECK(igraph_vector_resize(barycenters, n)); igraph_vector_null(barycenters); for (i = 0; i < n; i++) { IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) VECTOR(*layer_members)[i], direction)); m = igraph_vector_size(&neis); if (m == 0) { /* No neighbors in this direction. Just use the current X coordinate */ VECTOR(*barycenters)[i] = MATRIX(*layout, i, 0); } else { for (j = 0; j < m; j++) { VECTOR(*barycenters)[i] += MATRIX(*layout, (long)VECTOR(neis)[j], 0); } VECTOR(*barycenters)[i] /= m; } } igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * Given a properly layered graph where each edge points downwards and spans * exactly one layer, arranges the nodes in each layer horizontally in a way * that strives to minimize edge crossings. */ static int igraph_i_layout_sugiyama_order_nodes_horizontally(const igraph_t* graph, igraph_matrix_t* layout, const igraph_i_layering_t* layering, long int maxiter) { long int i, n, nei; long int no_of_vertices = igraph_vcount(graph); long int no_of_layers = igraph_i_layering_num_layers(layering); long int iter, layer_index; igraph_vector_t* layer_members; igraph_vector_t neis, barycenters, sort_indices; igraph_bool_t changed; /* The first column of the matrix will serve as the ordering */ /* Start with a first-seen ordering within each layer */ { long int *xs = igraph_Calloc(no_of_layers, long int); if (xs == 0) IGRAPH_ERROR("cannot order nodes horizontally", IGRAPH_ENOMEM); for (i = 0; i < no_of_vertices; i++) MATRIX(*layout, i, 0) = xs[(long int)MATRIX(*layout, i, 1)]++; free(xs); } IGRAPH_VECTOR_INIT_FINALLY(&barycenters, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&sort_indices, 0); /* Start the effective part of the Sugiyama algorithm */ iter = 0; changed = 1; while (changed && iter < maxiter) { changed = 0; /* Phase 1 */ /* Moving downwards and sorting by upper barycenters */ for (layer_index = 1; layer_index < no_of_layers; layer_index++) { layer_members = igraph_i_layering_get(layering, layer_index); n = igraph_vector_size(layer_members); igraph_i_layout_sugiyama_calculate_barycenters(graph, layering, layer_index, IGRAPH_IN, layout, &barycenters); #ifdef SUGIYAMA_DEBUG printf("Layer %ld, aligning to upper barycenters\n", layer_index); printf("Vertices: "); igraph_vector_print(layer_members); printf("Barycenters: "); igraph_vector_print(&barycenters); #endif IGRAPH_CHECK((int) igraph_vector_qsort_ind(&barycenters, &sort_indices, 0)); for (i = 0; i < n; i++) { nei = (long)VECTOR(*layer_members)[(long)VECTOR(sort_indices)[i]]; VECTOR(barycenters)[i] = nei; MATRIX(*layout, nei, 0) = i; } if (!igraph_vector_all_e(layer_members, &barycenters)) { IGRAPH_CHECK(igraph_vector_update(layer_members, &barycenters)); #ifdef SUGIYAMA_DEBUG printf("New vertex order: "); igraph_vector_print(layer_members); #endif changed = 1; } else { #ifdef SUGIYAMA_DEBUG printf("Order did not change.\n"); #endif } } /* Moving upwards and sorting by lower barycenters */ for (layer_index = no_of_layers - 2; layer_index >= 0; layer_index--) { layer_members = igraph_i_layering_get(layering, layer_index); n = igraph_vector_size(layer_members); igraph_i_layout_sugiyama_calculate_barycenters(graph, layering, layer_index, IGRAPH_OUT, layout, &barycenters); #ifdef SUGIYAMA_DEBUG printf("Layer %ld, aligning to lower barycenters\n", layer_index); printf("Vertices: "); igraph_vector_print(layer_members); printf("Barycenters: "); igraph_vector_print(&barycenters); #endif IGRAPH_CHECK((int) igraph_vector_qsort_ind(&barycenters, &sort_indices, 0)); for (i = 0; i < n; i++) { nei = (long)VECTOR(*layer_members)[(long)VECTOR(sort_indices)[i]]; VECTOR(barycenters)[i] = nei; MATRIX(*layout, nei, 0) = i; } if (!igraph_vector_all_e(layer_members, &barycenters)) { IGRAPH_CHECK(igraph_vector_update(layer_members, &barycenters)); #ifdef SUGIYAMA_DEBUG printf("New vertex order: "); igraph_vector_print(layer_members); #endif changed = 1; } else { #ifdef SUGIYAMA_DEBUG printf("Order did not change.\n"); #endif } } #ifdef SUGIYAMA_DEBUG printf("==== Finished iteration %ld\n", iter); #endif iter++; } igraph_vector_destroy(&barycenters); igraph_vector_destroy(&neis); igraph_vector_destroy(&sort_indices); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } #define IS_DUMMY(v) ((v >= no_of_real_nodes)) #define IS_INNER_SEGMENT(u, v) (IS_DUMMY(u) && IS_DUMMY(v)) #define X_POS(v) (MATRIX(*layout, v, 0)) static int igraph_i_layout_sugiyama_vertical_alignment(const igraph_t* graph, const igraph_i_layering_t* layering, const igraph_matrix_t* layout, const igraph_vector_bool_t* ignored_edges, igraph_bool_t reverse, igraph_bool_t align_right, igraph_vector_t* roots, igraph_vector_t* align); static int igraph_i_layout_sugiyama_horizontal_compaction(const igraph_t* graph, const igraph_vector_t* vertex_to_the_left, const igraph_vector_t* roots, const igraph_vector_t* align, igraph_real_t hgap, igraph_vector_t* xs); static int igraph_i_layout_sugiyama_horizontal_compaction_place_block(long int v, const igraph_vector_t* vertex_to_the_left, const igraph_vector_t* roots, const igraph_vector_t* align, igraph_vector_t* sinks, igraph_vector_t* shifts, igraph_real_t hgap, igraph_vector_t* xs); static int igraph_i_layout_sugiyama_place_nodes_horizontally(const igraph_t* graph, igraph_matrix_t* layout, const igraph_i_layering_t* layering, igraph_real_t hgap, igraph_integer_t no_of_real_nodes) { long int i, j, k, l, n; long int no_of_layers = igraph_i_layering_num_layers(layering); long int no_of_nodes = igraph_vcount(graph); long int no_of_edges = igraph_ecount(graph); igraph_vector_t neis1, neis2; igraph_vector_t xs[4]; igraph_vector_t roots, align; igraph_vector_t vertex_to_the_left; igraph_vector_bool_t ignored_edges; /* { igraph_vector_t edgelist; IGRAPH_VECTOR_INIT_FINALLY(&edgelist, 0); IGRAPH_CHECK(igraph_get_edgelist(graph, &edgelist, 0)); igraph_vector_print(&edgelist); igraph_vector_destroy(&edgelist); IGRAPH_FINALLY_CLEAN(1); for (i = 0; i < no_of_layers; i++) { igraph_vector_t* layer = igraph_i_layering_get(layering, i); igraph_vector_print(layer); } } */ IGRAPH_CHECK(igraph_vector_bool_init(&ignored_edges, no_of_edges)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &ignored_edges); IGRAPH_VECTOR_INIT_FINALLY(&vertex_to_the_left, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis1, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis2, 0); /* First, find all type 1 conflicts and mark one of the edges participating * in the conflict as being ignored. If one of the edges in the conflict * is a non-inner segment and the other is an inner segment, we ignore the * non-inner segment as we want to keep inner segments vertical. */ for (i = 0; i < no_of_layers-1; i++) { igraph_vector_t* vertices = igraph_i_layering_get(layering, i); n = igraph_vector_size(vertices); /* Find all the edges from this layer to the next */ igraph_vector_clear(&neis1); for (j = 0; j < n; j++) { IGRAPH_CHECK(igraph_neighbors(graph, &neis2, (igraph_integer_t) VECTOR(*vertices)[j], IGRAPH_OUT)); IGRAPH_CHECK(igraph_vector_append(&neis1, &neis2)); } /* Consider all pairs of edges and check whether they are in a type 1 * conflict */ n = igraph_vector_size(&neis1); for (j = 0; j < n; j++) { long int u = IGRAPH_FROM(graph, j); long int v = IGRAPH_TO(graph, j); igraph_bool_t j_inner = IS_INNER_SEGMENT(u, v); igraph_bool_t crossing; for (k = j+1; k < n; k++) { long int w = IGRAPH_FROM(graph, k); long int x = IGRAPH_TO(graph, k); if (IS_INNER_SEGMENT(w, x) == j_inner) continue; /* Do the u --> v and w --> x edges cross? */ crossing = (u == w || v == x); if (!crossing) { if (X_POS(u) <= X_POS(w)) { crossing = X_POS(v) >= X_POS(x); } else { crossing = X_POS(v) <= X_POS(x); } } if (crossing) { if (j_inner) { VECTOR(ignored_edges)[k] = 1; } else { VECTOR(ignored_edges)[j] = 1; } } } } } igraph_vector_destroy(&neis1); igraph_vector_destroy(&neis2); IGRAPH_FINALLY_CLEAN(2); /* * Prepare vertex_to_the_left where the ith element stores * the index of the vertex to the left of vertex i, or i itself if the * vertex is the leftmost vertex in a layer. */ for (i = 0; i < no_of_layers; i++) { igraph_vector_t* vertices = igraph_i_layering_get(layering, i); n = igraph_vector_size(vertices); if (n == 0) continue; k = l = (long int)VECTOR(*vertices)[0]; VECTOR(vertex_to_the_left)[k] = k; for (j = 1; j < n; j++) { k = (long int)VECTOR(*vertices)[j]; VECTOR(vertex_to_the_left)[k] = l; l = k; } } /* Type 1 conflicts found, ignored edges chosen, vertex_to_the_left * prepared. Run vertical alignment for all four combinations */ for (i = 0; i < 4; i++) IGRAPH_VECTOR_INIT_FINALLY(&xs[i], no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&roots, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&align, no_of_nodes); for (i = 0; i < 4; i++) { IGRAPH_CHECK(igraph_i_layout_sugiyama_vertical_alignment(graph, layering, layout, &ignored_edges, /* reverse = */ (igraph_bool_t) i / 2, /* align_right = */ i % 2, &roots, &align)); IGRAPH_CHECK(igraph_i_layout_sugiyama_horizontal_compaction(graph, &vertex_to_the_left, &roots, &align, hgap, &xs[i])); } { igraph_real_t width, min_width, mins[4], maxs[4], diff; /* Find the alignment with the minimum width */ min_width = IGRAPH_INFINITY; j = 0; for (i = 0; i < 4; i++) { mins[i] = igraph_vector_min(&xs[i]); maxs[i] = igraph_vector_max(&xs[i]); width = maxs[i] - mins[i]; if (width < min_width) { min_width = width; j = i; } } /* Leftmost alignments: align them s.t. the min X coordinate is equal to * the minimum X coordinate of the alignment with the smallest width. * Rightmost alignments: align them s.t. the max X coordinate is equal to * the max X coordinate of the alignment with the smallest width. */ for (i = 0; i < 4; i++) { if (j == i) continue; if (i % 2 == 0) { /* Leftmost alignment */ diff = mins[j] - mins[i]; } else { /* Rightmost alignment */ diff = maxs[j] - maxs[i]; } igraph_vector_add_constant(&xs[i], diff); } } /* For every vertex, find the median of the X coordinates in the four * alignments */ for (i = 0; i < no_of_nodes; i++) { X_POS(i) = igraph_i_median_4(VECTOR(xs[0])[i], VECTOR(xs[1])[i], VECTOR(xs[2])[i], VECTOR(xs[3])[i]); } igraph_vector_destroy(&roots); igraph_vector_destroy(&align); IGRAPH_FINALLY_CLEAN(2); for (i = 0; i < 4; i++) igraph_vector_destroy(&xs[i]); IGRAPH_FINALLY_CLEAN(4); igraph_vector_destroy(&vertex_to_the_left); IGRAPH_FINALLY_CLEAN(1); igraph_vector_bool_destroy(&ignored_edges); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } static int igraph_i_layout_sugiyama_vertical_alignment(const igraph_t* graph, const igraph_i_layering_t* layering, const igraph_matrix_t* layout, const igraph_vector_bool_t* ignored_edges, igraph_bool_t reverse, igraph_bool_t align_right, igraph_vector_t* roots, igraph_vector_t* align) { long int i, j, k, n, di, dj, i_limit, j_limit, r; long int no_of_layers = igraph_i_layering_num_layers(layering); long int no_of_nodes = igraph_vcount(graph); igraph_neimode_t neimode = (reverse ? IGRAPH_OUT : IGRAPH_IN); igraph_vector_t neis, xs, inds; IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&xs, 0); IGRAPH_VECTOR_INIT_FINALLY(&inds, 0); IGRAPH_CHECK(igraph_vector_resize(roots, no_of_nodes)); IGRAPH_CHECK(igraph_vector_resize(align, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { VECTOR(*roots)[i] = VECTOR(*align)[i] = i; } /* When reverse = False, we are aligning "upwards" in the tree, hence we * have to loop i from 1 to no_of_layers-1 (inclusive) and use neimode=IGRAPH_IN. * When reverse = True, we are aligning "downwards", hence we have to loop * i from no_of_layers-2 to 0 (inclusive) and use neimode=IGRAPH_OUT. */ i = reverse ? (no_of_layers-2) : 1; di = reverse ? -1 : 1; i_limit = reverse ? -1 : no_of_layers; for (; i != i_limit; i += di) { igraph_vector_t *layer = igraph_i_layering_get(layering, i); /* r = 0 in the paper, but C arrays are indexed from 0 */ r = align_right ? LONG_MAX : -1; /* If align_right is 1, we have to process the layer in reverse order */ j = align_right ? (igraph_vector_size(layer)-1) : 0; dj = align_right ? -1 : 1; j_limit = align_right ? -1 : igraph_vector_size(layer); for (; j != j_limit; j += dj) { long int medians[2]; long int vertex = (long int) VECTOR(*layer)[j]; long int pos; if (VECTOR(*align)[vertex] != vertex) /* This vertex is already aligned with some other vertex, * so there's nothing to do */ continue; /* Find the neighbors of vertex j in layer i */ IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) vertex, neimode)); n = igraph_vector_size(&neis); if (n == 0) /* No neighbors in this direction, continue */ continue; if (n == 1) { /* Just one neighbor; the median is trivial */ medians[0] = (long int) VECTOR(neis)[0]; medians[1] = -1; } else { /* Sort the neighbors by their X coordinates */ IGRAPH_CHECK(igraph_vector_resize(&xs, n)); for (k = 0; k < n; k++) VECTOR(xs)[k] = X_POS((long int)VECTOR(neis)[k]); IGRAPH_CHECK((int) igraph_vector_qsort_ind(&xs, &inds, 0)); if (n % 2 == 1) { /* Odd number of neighbors, so the median is unique */ medians[0] = (long int) VECTOR(neis)[(long int)VECTOR(inds)[n / 2]]; medians[1] = -1; } else { /* Even number of neighbors, so we have two medians. The order * depends on whether we are processing the layer in leftmost * or rightmost fashion. */ if (align_right) { medians[0] = (long int) VECTOR(neis)[(long int)VECTOR(inds)[n / 2]]; medians[1] = (long int) VECTOR(neis)[(long int)VECTOR(inds)[n / 2 - 1]]; } else { medians[0] = (long int) VECTOR(neis)[(long int)VECTOR(inds)[n / 2 - 1]]; medians[1] = (long int) VECTOR(neis)[(long int)VECTOR(inds)[n / 2]]; } } } /* Try aligning with the medians */ for (k = 0; k < 2; k++) { igraph_integer_t eid; if (medians[k] < 0) continue; if (VECTOR(*align)[vertex] != vertex) { /* Vertex already aligned, continue */ continue; } /* Is the edge between medians[k] and vertex ignored * because of a type 1 conflict? */ IGRAPH_CHECK(igraph_get_eid(graph, &eid, (igraph_integer_t) vertex, (igraph_integer_t) medians[k], 0, 1)); if (VECTOR(*ignored_edges)[(long int)eid]) continue; /* Okay, align with the median if possible */ pos = (long int) X_POS(medians[k]); if ((align_right && r > pos) || (!align_right && r < pos)) { VECTOR(*align)[medians[k]] = vertex; VECTOR(*roots)[vertex] = VECTOR(*roots)[medians[k]]; VECTOR(*align)[vertex] = VECTOR(*roots)[medians[k]]; r = pos; } } } } igraph_vector_destroy(&inds); igraph_vector_destroy(&neis); igraph_vector_destroy(&xs); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /* * Runs a horizontal compaction given a vertical alignment (in `align`) * and the roots (in `roots`). These come out directly from * igraph_i_layout_sugiyama_vertical_alignment. * * Returns the X coordinates for each vertex in `xs`. * * `graph` is the input graph, `layering` is the layering on which we operate. * `hgap` is the preferred horizontal gap between vertices. */ static int igraph_i_layout_sugiyama_horizontal_compaction(const igraph_t* graph, const igraph_vector_t* vertex_to_the_left, const igraph_vector_t* roots, const igraph_vector_t* align, igraph_real_t hgap, igraph_vector_t* xs) { long int i; long int no_of_nodes = igraph_vcount(graph); igraph_vector_t sinks, shifts, old_xs; igraph_real_t shift; /* Initialization */ IGRAPH_VECTOR_INIT_FINALLY(&sinks, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&shifts, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&old_xs, no_of_nodes); IGRAPH_CHECK(igraph_vector_resize(xs, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { VECTOR(sinks)[i] = i; } igraph_vector_fill(&shifts, IGRAPH_INFINITY); igraph_vector_fill(xs, -1); /* Calculate the coordinates of the vertices relative to their sinks * in their own class. At the end of this for loop, xs will contain the * relative displacement of a vertex from its sink, while the shifts list * will contain the absolute displacement of the sinks. * (For the sinks only, of course, the rest is undefined and unused) */ for (i = 0; i < no_of_nodes; i++) { if (VECTOR(*roots)[i] == i) { IGRAPH_CHECK( igraph_i_layout_sugiyama_horizontal_compaction_place_block(i, vertex_to_the_left, roots, align, &sinks, &shifts, hgap, xs) ); } } /* In "sinks", only those indices `i` matter for which `i` is in `roots`. * All the other values will never be touched. */ /* Calculate the absolute coordinates */ IGRAPH_CHECK(igraph_vector_update(&old_xs, xs)); for (i = 0; i < no_of_nodes; i++) { long int root = (long int) VECTOR(*roots)[i]; VECTOR(*xs)[i] = VECTOR(old_xs)[root]; shift = VECTOR(shifts)[(long int)VECTOR(sinks)[root]]; if (shift < IGRAPH_INFINITY) VECTOR(*xs)[i] += shift; } igraph_vector_destroy(&sinks); igraph_vector_destroy(&shifts); igraph_vector_destroy(&old_xs); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } static int igraph_i_layout_sugiyama_horizontal_compaction_place_block(long int v, const igraph_vector_t* vertex_to_the_left, const igraph_vector_t* roots, const igraph_vector_t* align, igraph_vector_t* sinks, igraph_vector_t* shifts, igraph_real_t hgap, igraph_vector_t* xs) { long int u, w; long int u_sink, v_sink; if (VECTOR(*xs)[v] >= 0) return IGRAPH_SUCCESS; VECTOR(*xs)[v] = 0; w = v; do { /* Check whether vertex w is the leftmost in its own layer */ u = (long int) VECTOR(*vertex_to_the_left)[w]; if (u != w) { /* Get the root of u (proceeding all the way upwards in the block) */ u = (long int) VECTOR(*roots)[u]; /* Place the block of u recursively */ IGRAPH_CHECK( igraph_i_layout_sugiyama_horizontal_compaction_place_block(u, vertex_to_the_left, roots, align, sinks, shifts, hgap, xs) ); u_sink = (long int) VECTOR(*sinks)[u]; v_sink = (long int) VECTOR(*sinks)[v]; /* If v is its own sink yet, set its sink to the sink of u */ if (v_sink == v) { VECTOR(*sinks)[v] = v_sink = u_sink; } /* If v and u have different sinks (i.e. they are in different classes), * shift the sink of u so that the two blocks are separated by the * preferred gap */ if (v_sink != u_sink) { if (VECTOR(*shifts)[u_sink] > VECTOR(*xs)[v] - VECTOR(*xs)[u] - hgap) { VECTOR(*shifts)[u_sink] = VECTOR(*xs)[v] - VECTOR(*xs)[u] - hgap; } } else { /* v and u have the same sink, i.e. they are in the same class. Make sure * that v is separated from u by at least hgap. */ if (VECTOR(*xs)[v] < VECTOR(*xs)[u] + hgap) VECTOR(*xs)[v] = VECTOR(*xs)[u] + hgap; } } /* Follow the alignment */ w = (long int) VECTOR(*align)[w]; } while (w != v); return IGRAPH_SUCCESS; } #undef IS_INNER_SEGMENT #undef IS_DUMMY #undef X_POS #ifdef SUGIYAMA_DEBUG #undef SUGIYAMA_DEBUG #endif igraph/src/dotproduct.c0000644000175100001440000002027013431000472014657 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_games.h" #include "igraph_random.h" #include "igraph_constructors.h" #include "igraph_lapack.h" /** * \function igraph_dot_product_game * Generate a random dot product graph * * In this model, each vertex is represented by a latent * position vector. Probability of an edge between two vertices are given * by the dot product of their latent position vectors. * * * See also Christine Leigh Myers Nickel: Random dot product graphs, a * model for social networks. Dissertation, Johns Hopkins University, * Maryland, USA, 2006. * * \param graph The output graph is stored here. * \param vecs A matrix in which each latent position vector is a * column. The dot product of the latent position vectors should be * in the [0,1] interval, otherwise a warning is given. For * negative dot products, no edges are added; dot products that are * larger than one always add an edge. * \param directed Should the generated graph be directed? * \return Error code. * * Time complexity: O(n*n*m), where n is the number of vertices, * and m is the length of the latent vectors. * * \sa \ref igraph_sample_dirichlet(), \ref * igraph_sample_sphere_volume(), \ref igraph_sample_sphere_surface() * for functions to generate the latent vectors. */ int igraph_dot_product_game(igraph_t *graph, const igraph_matrix_t *vecs, igraph_bool_t directed) { igraph_integer_t nrow=igraph_matrix_nrow(vecs); igraph_integer_t ncol=igraph_matrix_ncol(vecs); int i, j; igraph_vector_t edges; igraph_bool_t warned_neg=0, warned_big=0; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); RNG_BEGIN(); for (i = 0; i < ncol; i++) { int from=directed ? 0 : i+1; igraph_vector_t v1; igraph_vector_view(&v1, &MATRIX(*vecs, 0, i), nrow); for (j = from; j < ncol; j++) { igraph_real_t prob; igraph_vector_t v2; if (i==j) { continue; } igraph_vector_view(&v2, &MATRIX(*vecs, 0, j), nrow); igraph_lapack_ddot(&v1, &v2, &prob); if (prob < 0 && ! warned_neg) { warned_neg=1; IGRAPH_WARNING("Negative connection probability in " "dot-product graph"); } else if (prob > 1 && ! warned_big) { warned_big=1; IGRAPH_WARNING("Greater than 1 connection probability in " "dot-product graph"); IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } else if (RNG_UNIF01() < prob) { IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } } } RNG_END(); igraph_create(graph, &edges, ncol, directed); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_sample_sphere_surface * Sample points uniformly from the surface of a sphere * * The center of the sphere is at the origin. * * \param dim The dimension of the random vectors. * \param n The number of vectors to sample. * \param radius Radius of the sphere, it must be positive. * \param positive Whether to restrict sampling to the positive * orthant.} * \param res Pointer to an initialized matrix, the result is * stored here, each column will be a sampled vector. The matrix is * resized, as needed.} * \return Error code. * * Time complexity: O(n*dim*g), where g is the time complexity of * generating a standard normal random number. * * \sa \ref igraph_sample_sphere_volume(), \ref * igraph_sample_dirichlet() for other similar samplers. */ int igraph_sample_sphere_surface(igraph_integer_t dim, igraph_integer_t n, igraph_real_t radius, igraph_bool_t positive, igraph_matrix_t *res) { igraph_integer_t i, j; if (dim < 2) { IGRAPH_ERROR("Sphere must be at least two dimensional to sample from " "surface", IGRAPH_EINVAL); } if (n < 0) { IGRAPH_ERROR("Number of samples must be non-negative", IGRAPH_EINVAL); } if (radius <= 0) { IGRAPH_ERROR("Sphere radius must be positive", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(res, dim, n)); RNG_BEGIN(); for (i = 0; i < n; i++) { igraph_real_t *col=&MATRIX(*res, 0, i); igraph_real_t sum=0.0; for (j = 0; j < dim; j++) { col[j] = RNG_NORMAL(0, 1); sum += col[j] * col[j]; } sum = sqrt(sum); for (j = 0; j < dim; j++) { col[j] = radius * col[j] / sum; } if (positive) { for (j = 0; j < dim; j++) { col[j] = fabs(col[j]); } } } RNG_END(); return 0; } /** * \function igraph_sample_sphere_volume * Sample points uniformly from the volume of a sphere * * The center of the sphere is at the origin. * * \param dim The dimension of the random vectors. * \param n The number of vectors to sample. * \param radius Radius of the sphere, it must be positive. * \param positive Whether to restrict sampling to the positive * orthant.} * \param res Pointer to an initialized matrix, the result is * stored here, each column will be a sampled vector. The matrix is * resized, as needed.} * \return Error code. * * Time complexity: O(n*dim*g), where g is the time complexity of * generating a standard normal random number. * * \sa \ref igraph_sample_sphere_surface(), \ref * igraph_sample_dirichlet() for other similar samplers. */ int igraph_sample_sphere_volume(igraph_integer_t dim, igraph_integer_t n, igraph_real_t radius, igraph_bool_t positive, igraph_matrix_t *res) { igraph_integer_t i, j; /* Arguments are checked by the following call */ IGRAPH_CHECK(igraph_sample_sphere_surface(dim, n, radius, positive, res)); RNG_BEGIN(); for (i = 0; i < n; i++) { igraph_real_t *col=&MATRIX(*res, 0, i); igraph_real_t U=pow(RNG_UNIF01(), 1.0/dim); for (j = 0; j < dim; j++) { col[j] *= U; } } RNG_END(); return 0; } /** * \function igraph_sample_dirichlet * Sample points from a Dirichlet distribution * * \param n The number of vectors to sample. * \param alpha The parameters of the Dirichlet distribution. They * must be positive. The length of this vector gives the dimension * of the generated samples. * \param res Pointer to an initialized matrix, the result is stored * here, one sample in each column. It will be resized, as needed. * \return Error code. * * Time complexity: O(n * dim * g), where dim is the dimension of the * sample vectors, set by the length of alpha, and g is the time * complexity of sampling from a Gamma distribution. * * \sa \ref igraph_sample_sphere_surface() and * \ref igraph_sample_sphere_volume() for other methods to sample * latent vectors. */ int igraph_sample_dirichlet(igraph_integer_t n, const igraph_vector_t *alpha, igraph_matrix_t *res) { igraph_integer_t len=igraph_vector_size(alpha); igraph_integer_t i; igraph_vector_t vec; if (n < 0) { IGRAPH_ERROR("Number of samples should be non-negative", IGRAPH_EINVAL); } if (len < 2) { IGRAPH_ERROR("Dirichlet parameter vector too short, must " "have at least two entries", IGRAPH_EINVAL); } if (igraph_vector_min(alpha) <= 0) { IGRAPH_ERROR("Dirichlet concentration parameters must be positive", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(res, len, n)); RNG_BEGIN(); for (i = 0; i < n; i++) { igraph_vector_view(&vec, &MATRIX(*res, 0, i), len); igraph_rng_get_dirichlet(igraph_rng_default(), alpha, &vec); } RNG_END(); return 0; } igraph/src/dstats.f0000644000175100001440000000223213431000472013773 0ustar hornikusersc c\SCCS Information: @(#) c FILE: stats.F SID: 2.1 DATE OF SID: 4/19/96 RELEASE: 2 c %---------------------------------------------% c | Initialize statistic and timing information | c | for symmetric Arnoldi code. | c %---------------------------------------------% subroutine igraphdstats c %--------------------------------% c | See stat.doc for documentation | c %--------------------------------% include 'stat.h' c %-----------------------% c | Executable Statements | c %-----------------------% nopx = 0 nbx = 0 nrorth = 0 nitref = 0 nrstrt = 0 tsaupd = 0.0D+0 tsaup2 = 0.0D+0 tsaitr = 0.0D+0 tseigt = 0.0D+0 tsgets = 0.0D+0 tsapps = 0.0D+0 tsconv = 0.0D+0 titref = 0.0D+0 tgetv0 = 0.0D+0 trvec = 0.0D+0 c %----------------------------------------------------% c | User time including reverse communication overhead | c %----------------------------------------------------% tmvopx = 0.0D+0 tmvbx = 0.0D+0 return c c End of igraphdstats c end igraph/src/maximal_cliques_template.h0000644000175100001440000002450213431000472017547 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef IGRAPH_MC_ORIG #define RESTYPE igraph_vector_ptr_t *res #define RESNAME res #define SUFFIX #define RECORD do { \ igraph_vector_t *cl=igraph_Calloc(1, igraph_vector_t); \ int j; \ if (!cl) { \ IGRAPH_ERROR("Cannot list maximal cliques", IGRAPH_ENOMEM); \ } \ igraph_vector_ptr_push_back(res, cl); \ igraph_vector_init(cl, clsize); \ for (j=0; j PE && XS > XE) { /* Found a maximum clique, report it */ int clsize=igraph_vector_int_size(R); if (min_size <= clsize && (clsize <= max_size || max_size <= 0)) { RECORD; } } else if (PS <= PE) { /* Select a pivot element */ int pivot, mynextv; igraph_i_maximal_cliques_select_pivot(PX, PS, PE, XS, XE, pos, adjlist, &pivot, nextv, oldPS, oldXE); while ((mynextv=igraph_vector_int_pop_back(nextv)) != -1) { int newPS, newXE; /* Going down, prepare */ igraph_i_maximal_cliques_down(PX, PS, PE, XS, XE, pos, adjlist, mynextv, R, &newPS, &newXE); /* Recursive call */ FUNCTION(igraph_i_maximal_cliques_bk,SUFFIX)( PX, newPS, PE, XS, newXE, PS, XE, R, pos, adjlist, RESNAME, nextv, H, min_size, max_size); /* Putting v from P to X */ if (igraph_vector_int_tail(nextv) != -1) { igraph_i_maximal_cliques_PX(PX, PS, &PE, &XS, XE, pos, adjlist, mynextv, H); } } } /* Putting back vertices from X to P, see notes in H */ igraph_i_maximal_cliques_up(PX, PS, PE, XS, XE, pos, adjlist, R, H); return 0; } int FUNCTION(igraph_maximal_cliques,SUFFIX)( const igraph_t *graph, RESTYPE, igraph_integer_t min_size, igraph_integer_t max_size) { /* Implementation details. TODO */ igraph_vector_int_t PX, R, H, pos, nextv; igraph_vector_t coreness, order; igraph_vector_int_t rank; /* TODO: this is not needed */ int i, ii, nn, no_of_nodes=igraph_vcount(graph); igraph_adjlist_t adjlist, fulladjlist; igraph_real_t pgreset=round(no_of_nodes / 100.0), pg=pgreset, pgc=0; IGRAPH_UNUSED(nn); if (igraph_is_directed(graph)) { IGRAPH_WARNING("Edge directions are ignored for maximal clique " "calculation"); } igraph_vector_init(&order, no_of_nodes); IGRAPH_FINALLY(igraph_vector_destroy, &order); igraph_vector_int_init(&rank, no_of_nodes); IGRAPH_FINALLY(igraph_vector_int_destroy, &rank); igraph_vector_init(&coreness, no_of_nodes); igraph_coreness(graph, &coreness, /*mode=*/ IGRAPH_ALL); IGRAPH_FINALLY(igraph_vector_destroy, &coreness); igraph_vector_qsort_ind(&coreness, &order, /*descending=*/ 0); for (ii=0; ii vrank) { VECTOR(PX)[Pptr] = vx; VECTOR(pos)[vx] = Pptr+1; Pptr++; } else if (VECTOR(rank)[vx] < vrank) { VECTOR(PX)[Xptr] = vx; VECTOR(pos)[vx] = Xptr+1; Xptr--; } } PE = Pptr-1; XS = Xptr+1; /* end of P, start of X in PX */ /* Create an adjacency list that is specific to the v vertex. It only contains 'v' and its neighbors. Moreover, we only deal with the vertices in P and X (and R). */ igraph_vector_int_update(igraph_adjlist_get(&adjlist, v), igraph_adjlist_get(&fulladjlist, v)); for (j=0; j<=vdeg-1; j++) { int vv=VECTOR(PX)[j]; igraph_vector_int_t *fadj=igraph_adjlist_get(&fulladjlist, vv); igraph_vector_int_t *radj=igraph_adjlist_get(&adjlist, vv); int k, fn=igraph_vector_int_size(fadj); igraph_vector_int_clear(radj); for (k=0; k= PS && neipos <= XE) { igraph_vector_int_push_back(radj, nei); } } } /* Reorder the adjacency lists, according to P and X. */ igraph_i_maximal_cliques_reorder_adjlists(&PX, PS, PE, XS, XE, &pos, &adjlist); FUNCTION(igraph_i_maximal_cliques_bk,SUFFIX)( &PX, PS, PE, XS, XE, PS, XE, &R, &pos, &adjlist, RESNAME, &nextv, &H, min_size, max_size); } IGRAPH_PROGRESS("Maximal cliques: ", 100.0, NULL); igraph_vector_int_destroy(&nextv); igraph_vector_int_destroy(&pos); igraph_vector_int_destroy(&H); igraph_vector_int_destroy(&R); igraph_vector_int_destroy(&PX); igraph_adjlist_destroy(&fulladjlist); igraph_adjlist_destroy(&adjlist); igraph_vector_int_destroy(&rank); igraph_vector_destroy(&order); IGRAPH_FINALLY_CLEAN(10); /* + res */ return 0; } #undef RESTYPE #undef RESNAME #undef SUFFIX #undef RECORD #undef FINALLY #undef FOR_LOOP_OVER_VERTICES #undef FOR_LOOP_OVER_VERTICES_PREPARE igraph/src/dneupd.f0000644000175100001440000012567713431000472013773 0ustar hornikusersc\BeginDoc c c\Name: igraphdneupd c c\Description: c c This subroutine returns the converged approximations to eigenvalues c of A*z = lambda*B*z and (optionally): c c (1) The corresponding approximate eigenvectors; c c (2) An orthonormal basis for the associated approximate c invariant subspace; c c (3) Both. c c There is negligible additional cost to obtain eigenvectors. An orthonormal c basis is always computed. There is an additional storage cost of n*nev c if both are requested (in this case a separate array Z must be supplied). c c The approximate eigenvalues and eigenvectors of A*z = lambda*B*z c are derived from approximate eigenvalues and eigenvectors of c of the linear operator OP prescribed by the MODE selection in the c call to DNAUPD. DNAUPD must be called before this routine is called. c These approximate eigenvalues and vectors are commonly called Ritz c values and Ritz vectors respectively. They are referred to as such c in the comments that follow. The computed orthonormal basis for the c invariant subspace corresponding to these Ritz values is referred to as a c Schur basis. c c See documentation in the header of the subroutine DNAUPD for c definition of OP as well as other terms and the relation of computed c Ritz values and Ritz vectors of OP with respect to the given problem c A*z = lambda*B*z. For a brief description, see definitions of c IPARAM(7), MODE and WHICH in the documentation of DNAUPD. c c\Usage: c call igraphdneupd c ( RVEC, HOWMNY, SELECT, DR, DI, Z, LDZ, SIGMAR, SIGMAI, WORKEV, BMAT, c N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, IPNTR, WORKD, WORKL, c LWORKL, INFO ) c c\Arguments: c RVEC LOGICAL (INPUT) c Specifies whether a basis for the invariant subspace corresponding c to the converged Ritz value approximations for the eigenproblem c A*z = lambda*B*z is computed. c c RVEC = .FALSE. Compute Ritz values only. c c RVEC = .TRUE. Compute the Ritz vectors or Schur vectors. c See Remarks below. c c HOWMNY Character*1 (INPUT) c Specifies the form of the basis for the invariant subspace c corresponding to the converged Ritz values that is to be computed. c c = 'A': Compute NEV Ritz vectors; c = 'P': Compute NEV Schur vectors; c = 'S': compute some of the Ritz vectors, specified c by the logical array SELECT. c c SELECT Logical array of dimension NCV. (INPUT) c If HOWMNY = 'S', SELECT specifies the Ritz vectors to be c computed. To select the Ritz vector corresponding to a c Ritz value (DR(j), DI(j)), SELECT(j) must be set to .TRUE.. c If HOWMNY = 'A' or 'P', SELECT is used as internal workspace. c c DR Double precision array of dimension NEV+1. (OUTPUT) c If IPARAM(7) = 1,2 or 3 and SIGMAI=0.0 then on exit: DR contains c the real part of the Ritz approximations to the eigenvalues of c A*z = lambda*B*z. c If IPARAM(7) = 3, 4 and SIGMAI is not equal to zero, then on exit: c DR contains the real part of the Ritz values of OP computed by c DNAUPD. A further computation must be performed by the user c to transform the Ritz values computed for OP by DNAUPD to those c of the original system A*z = lambda*B*z. See remark 3 below. c c DI Double precision array of dimension NEV+1. (OUTPUT) c On exit, DI contains the imaginary part of the Ritz value c approximations to the eigenvalues of A*z = lambda*B*z associated c with DR. c c NOTE: When Ritz values are complex, they will come in complex c conjugate pairs. If eigenvectors are requested, the c corresponding Ritz vectors will also come in conjugate c pairs and the real and imaginary parts of these are c represented in two consecutive columns of the array Z c (see below). c c Z Double precision N by NEV+1 array if RVEC = .TRUE. and HOWMNY = 'A'. (OUTPUT) c On exit, if RVEC = .TRUE. and HOWMNY = 'A', then the columns of c Z represent approximate eigenvectors (Ritz vectors) corresponding c to the NCONV=IPARAM(5) Ritz values for eigensystem c A*z = lambda*B*z. c c The complex Ritz vector associated with the Ritz value c with positive imaginary part is stored in two consecutive c columns. The first column holds the real part of the Ritz c vector and the igraphsecond column holds the imaginary part. The c Ritz vector associated with the Ritz value with negative c imaginary part is simply the complex conjugate of the Ritz vector c associated with the positive imaginary part. c c If RVEC = .FALSE. or HOWMNY = 'P', then Z is not referenced. c c NOTE: If if RVEC = .TRUE. and a Schur basis is not required, c the array Z may be set equal to first NEV+1 columns of the Arnoldi c basis array V computed by DNAUPD. In this case the Arnoldi basis c will be destroyed and overwritten with the eigenvector basis. c c LDZ Integer. (INPUT) c The leading dimension of the array Z. If Ritz vectors are c desired, then LDZ >= max( 1, N ). In any case, LDZ >= 1. c c SIGMAR Double precision (INPUT) c If IPARAM(7) = 3 or 4, represents the real part of the shift. c Not referenced if IPARAM(7) = 1 or 2. c c SIGMAI Double precision (INPUT) c If IPARAM(7) = 3 or 4, represents the imaginary part of the shift. c Not referenced if IPARAM(7) = 1 or 2. See remark 3 below. c c WORKEV Double precision work array of dimension 3*NCV. (WORKSPACE) c c **** The remaining arguments MUST be the same as for the **** c **** call to DNAUPD that was just completed. **** c c NOTE: The remaining arguments c c BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, IPNTR, c WORKD, WORKL, LWORKL, INFO c c must be passed directly to DNEUPD following the last call c to DNAUPD. These arguments MUST NOT BE MODIFIED between c the the last call to DNAUPD and the call to DNEUPD. c c Three of these parameters (V, WORKL, INFO) are also output parameters: c c V Double precision N by NCV array. (INPUT/OUTPUT) c c Upon INPUT: the NCV columns of V contain the Arnoldi basis c vectors for OP as constructed by DNAUPD . c c Upon OUTPUT: If RVEC = .TRUE. the first NCONV=IPARAM(5) columns c contain approximate Schur vectors that span the c desired invariant subspace. See Remark 2 below. c c NOTE: If the array Z has been set equal to first NEV+1 columns c of the array V and RVEC=.TRUE. and HOWMNY= 'A', then the c Arnoldi basis held by V has been overwritten by the desired c Ritz vectors. If a separate array Z has been passed then c the first NCONV=IPARAM(5) columns of V will contain approximate c Schur vectors that span the desired invariant subspace. c c WORKL Double precision work array of length LWORKL. (OUTPUT/WORKSPACE) c WORKL(1:ncv*ncv+3*ncv) contains information obtained in c igraphdnaupd. They are not changed by igraphdneupd. c WORKL(ncv*ncv+3*ncv+1:3*ncv*ncv+6*ncv) holds the c real and imaginary part of the untransformed Ritz values, c the upper quasi-triangular matrix for H, and the c associated matrix representation of the invariant subspace for H. c c Note: IPNTR(9:13) contains the pointer into WORKL for addresses c of the above information computed by igraphdneupd. c ------------------------------------------------------------- c IPNTR(9): pointer to the real part of the NCV RITZ values of the c original system. c IPNTR(10): pointer to the imaginary part of the NCV RITZ values of c the original system. c IPNTR(11): pointer to the NCV corresponding error bounds. c IPNTR(12): pointer to the NCV by NCV upper quasi-triangular c Schur matrix for H. c IPNTR(13): pointer to the NCV by NCV matrix of eigenvectors c of the upper Hessenberg matrix H. Only referenced by c igraphdneupd if RVEC = .TRUE. See Remark 2 below. c ------------------------------------------------------------- c c INFO Integer. (OUTPUT) c Error flag on output. c c = 0: Normal exit. c c = 1: The Schur form computed by LAPACK routine dlahqr c could not be reordered by LAPACK routine dtrsen. c Re-enter subroutine igraphdneupd with IPARAM(5)=NCV and c increase the size of the arrays DR and DI to have c dimension at least dimension NCV and allocate at least NCV c columns for Z. NOTE: Not necessary if Z and V share c the same space. Please notify the authors if this error c occurs. c c = -1: N must be positive. c = -2: NEV must be positive. c = -3: NCV-NEV >= 2 and less than or equal to N. c = -5: WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI' c = -6: BMAT must be one of 'I' or 'G'. c = -7: Length of private work WORKL array is not sufficient. c = -8: Error return from calculation of a real Schur form. c Informational error from LAPACK routine dlahqr. c = -9: Error return from calculation of eigenvectors. c Informational error from LAPACK routine dtrevc. c = -10: IPARAM(7) must be 1,2,3,4. c = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatible. c = -12: HOWMNY = 'S' not yet implemented c = -13: HOWMNY must be one of 'A' or 'P' if RVEC = .true. c = -14: DNAUPD did not find any eigenvalues to sufficient c accuracy. c c\BeginLib c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett & Y. Saad, "Complex Shift and Invert Strategies for c Real Matrices", Linear Algebra and its Applications, vol 88/89, c pp 575-595, (1987). c c\Routines called: c igraphivout ARPACK utility routine that prints integers. c igraphdmout ARPACK utility routine that prints matrices c igraphdvout ARPACK utility routine that prints vectors. c dgeqr2 LAPACK routine that computes the QR factorization of c a matrix. c dlacpy LAPACK matrix copy routine. c dlahqr LAPACK routine to compute the real Schur form of an c upper Hessenberg matrix. c dlamch LAPACK routine that determines machine constants. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c dlaset LAPACK matrix initialization routine. c dorm2r LAPACK routine that applies an orthogonal matrix in c factored form. c dtrevc LAPACK routine to compute the eigenvectors of a matrix c in upper quasi-triangular form. c dtrsen LAPACK routine that re-orders the Schur form. c dtrmm Level 3 BLAS matrix times an upper triangular matrix. c dger Level 2 BLAS rank one update to a matrix. c dcopy Level 1 BLAS that copies one vector to another . c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c dscal Level 1 BLAS that scales a vector. c c\Remarks c c 1. Currently only HOWMNY = 'A' and 'P' are implemented. c c Let X' denote the transpose of X. c c 2. Schur vectors are an orthogonal representation for the basis of c Ritz vectors. Thus, their numerical properties are often superior. c If RVEC = .TRUE. then the relationship c A * V(:,1:IPARAM(5)) = V(:,1:IPARAM(5)) * T, and c V(:,1:IPARAM(5))' * V(:,1:IPARAM(5)) = I are approximately satisfied. c Here T is the leading submatrix of order IPARAM(5) of the real c upper quasi-triangular matrix stored workl(ipntr(12)). That is, c T is block upper triangular with 1-by-1 and 2-by-2 diagonal blocks; c each 2-by-2 diagonal block has its diagonal elements equal and its c off-diagonal elements of opposite sign. Corresponding to each 2-by-2 c diagonal block is a complex conjugate pair of Ritz values. The real c Ritz values are stored on the diagonal of T. c c 3. If IPARAM(7) = 3 or 4 and SIGMAI is not equal zero, then the user must c form the IPARAM(5) Rayleigh quotients in order to transform the Ritz c values computed by DNAUPD for OP to those of A*z = lambda*B*z. c Set RVEC = .true. and HOWMNY = 'A', and c compute c Z(:,I)' * A * Z(:,I) if DI(I) = 0. c If DI(I) is not equal to zero and DI(I+1) = - D(I), c then the desired real and imaginary parts of the Ritz value are c Z(:,I)' * A * Z(:,I) + Z(:,I+1)' * A * Z(:,I+1), c Z(:,I)' * A * Z(:,I+1) - Z(:,I+1)' * A * Z(:,I), respectively. c Another possibility is to set RVEC = .true. and HOWMNY = 'P' and c compute V(:,1:IPARAM(5))' * A * V(:,1:IPARAM(5)) and then an upper c quasi-triangular matrix of order IPARAM(5) is computed. See remark c 2 above. c c\Authors c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Chao Yang Houston, Texas c Dept. of Computational & c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: neupd.F SID: 2.5 DATE OF SID: 7/31/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- subroutine igraphdneupd (rvec, howmny, select, dr, di, z, ldz, & sigmar, sigmai, workev, bmat, n, which, nev, tol, & resid, ncv, v, ldv, iparam, ipntr, workd, & workl, lworkl, info) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat, howmny, which*2 logical rvec integer info, ldz, ldv, lworkl, n, ncv, nev Double precision & sigmar, sigmai, tol c c %-----------------% c | Array Arguments | c %-----------------% c integer iparam(11), ipntr(14) logical select(ncv) Double precision & dr(nev+1), di(nev+1), resid(n), v(ldv,ncv), z(ldz,*), & workd(3*n), workl(lworkl), workev(3*ncv) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c character type*6 integer bounds, ierr, ih, ihbds, iheigr, iheigi, iconj, nconv, & invsub, iuptri, iwev, iwork(1), j, k, ktrord, & ldh, ldq, mode, msglvl, outncv, ritzr, ritzi, wri, wrr, & irr, iri, ibd logical reord Double precision & conds, rnorm, sep, temp, thres, vl(1,1), temp1, eps23 c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, dger, dgeqr2, dlacpy, dlahqr, dlaset, & igraphdmout, dorm2r, dtrevc, dtrmm, dtrsen, dscal, & igraphdvout, igraphivout c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlapy2, dnrm2, dlamch, ddot external dlapy2, dnrm2, dlamch, ddot c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic abs, min, sqrt c c %-----------------------% c | Executable Statements | c %-----------------------% c c %------------------------% c | Set default parameters | c %------------------------% c msglvl = mneupd mode = iparam(7) nconv = iparam(5) info = 0 c c %---------------------------------% c | Get machine dependent constant. | c %---------------------------------% c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0 / 3.0D+0) c c %--------------% c | Quick return | c %--------------% c ierr = 0 c if (nconv .le. 0) then ierr = -14 else if (n .le. 0) then ierr = -1 else if (nev .le. 0) then ierr = -2 else if (ncv .le. nev+1 .or. ncv .gt. n) then ierr = -3 else if (which .ne. 'LM' .and. & which .ne. 'SM' .and. & which .ne. 'LR' .and. & which .ne. 'SR' .and. & which .ne. 'LI' .and. & which .ne. 'SI') then ierr = -5 else if (bmat .ne. 'I' .and. bmat .ne. 'G') then ierr = -6 else if (lworkl .lt. 3*ncv**2 + 6*ncv) then ierr = -7 else if ( (howmny .ne. 'A' .and. & howmny .ne. 'P' .and. & howmny .ne. 'S') .and. rvec ) then ierr = -13 else if (howmny .eq. 'S' ) then ierr = -12 end if c if (mode .eq. 1 .or. mode .eq. 2) then type = 'REGULR' else if (mode .eq. 3 .and. sigmai .eq. zero) then type = 'SHIFTI' else if (mode .eq. 3 ) then type = 'REALPT' else if (mode .eq. 4 ) then type = 'IMAGPT' else ierr = -10 end if if (mode .eq. 1 .and. bmat .eq. 'G') ierr = -11 c c %------------% c | Error Exit | c %------------% c if (ierr .ne. 0) then info = ierr go to 9000 end if c c %--------------------------------------------------------% c | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | c | etc... and the remaining workspace. | c | Also update pointer to be used on output. | c | Memory is laid out as follows: | c | workl(1:ncv*ncv) := generated Hessenberg matrix | c | workl(ncv*ncv+1:ncv*ncv+2*ncv) := real and imaginary | c | parts of ritz values | c | workl(ncv*ncv+2*ncv+1:ncv*ncv+3*ncv) := error bounds | c %--------------------------------------------------------% c c %-----------------------------------------------------------% c | The following is used and set by DNEUPD. | c | workl(ncv*ncv+3*ncv+1:ncv*ncv+4*ncv) := The untransformed | c | real part of the Ritz values. | c | workl(ncv*ncv+4*ncv+1:ncv*ncv+5*ncv) := The untransformed | c | imaginary part of the Ritz values. | c | workl(ncv*ncv+5*ncv+1:ncv*ncv+6*ncv) := The untransformed | c | error bounds of the Ritz values | c | workl(ncv*ncv+6*ncv+1:2*ncv*ncv+6*ncv) := Holds the upper | c | quasi-triangular matrix for H | c | workl(2*ncv*ncv+6*ncv+1: 3*ncv*ncv+6*ncv) := Holds the | c | associated matrix representation of the invariant | c | subspace for H. | c | GRAND total of NCV * ( 3 * NCV + 6 ) locations. | c %-----------------------------------------------------------% c ih = ipntr(5) ritzr = ipntr(6) ritzi = ipntr(7) bounds = ipntr(8) ldh = ncv ldq = ncv iheigr = bounds + ldh iheigi = iheigr + ldh ihbds = iheigi + ldh iuptri = ihbds + ldh invsub = iuptri + ldh*ncv ipntr(9) = iheigr ipntr(10) = iheigi ipntr(11) = ihbds ipntr(12) = iuptri ipntr(13) = invsub wrr = 1 wri = ncv + 1 iwev = wri + ncv c c %-----------------------------------------% c | irr points to the REAL part of the Ritz | c | values computed by _neigh before | c | exiting _naup2. | c | iri points to the IMAGINARY part of the | c | Ritz values computed by _neigh | c | before exiting _naup2. | c | ibd points to the Ritz estimates | c | computed by _neigh before exiting | c | _naup2. | c %-----------------------------------------% c irr = ipntr(14)+ncv*ncv iri = irr+ncv ibd = iri+ncv c c %------------------------------------% c | RNORM is B-norm of the RESID(1:N). | c %------------------------------------% c rnorm = workl(ih+2) workl(ih+2) = zero c if (rvec) then c c %-------------------------------------------% c | Get converged Ritz value on the boundary. | c | Note: converged Ritz values have been | c | placed in the first NCONV locations in | c | workl(ritzr) and workl(ritzi). They have | c | been sorted (in _naup2) according to the | c | WHICH selection criterion. | c %-------------------------------------------% c if (which .eq. 'LM' .or. which .eq. 'SM') then thres = dlapy2( workl(ritzr), workl(ritzi) ) else if (which .eq. 'LR' .or. which .eq. 'SR') then thres = workl(ritzr) else if (which .eq. 'LI' .or. which .eq. 'SI') then thres = abs( workl(ritzi) ) end if c if (msglvl .gt. 2) then call igraphdvout(logfil, 1, thres, ndigit, & '_neupd: Threshold eigenvalue used for re-ordering') end if c c %----------------------------------------------------------% c | Check to see if all converged Ritz values appear at the | c | top of the upper quasi-triangular matrix computed by | c | _neigh in _naup2. This is done in the following way: | c | | c | 1) For each Ritz value obtained from _neigh, compare it | c | with the threshold Ritz value computed above to | c | determine whether it is a wanted one. | c | | c | 2) If it is wanted, then check the corresponding Ritz | c | estimate to see if it has converged. If it has, set | c | correponding entry in the logical array SELECT to | c | .TRUE.. | c | | c | If SELECT(j) = .TRUE. and j > NCONV, then there is a | c | converged Ritz value that does not appear at the top of | c | the upper quasi-triangular matrix computed by _neigh in | c | _naup2. Reordering is needed. | c %----------------------------------------------------------% c reord = .false. ktrord = 0 do 10 j = 0, ncv-1 select(j+1) = .false. if (which .eq. 'LM') then if (dlapy2(workl(irr+j), workl(iri+j)) & .ge. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if else if (which .eq. 'SM') then if (dlapy2(workl(irr+j), workl(iri+j)) & .le. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if else if (which .eq. 'LR') then if (workl(irr+j) .ge. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if else if (which .eq. 'SR') then if (workl(irr+j) .le. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if else if (which .eq. 'LI') then if (abs(workl(iri+j)) .ge. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if else if (which .eq. 'SI') then if (abs(workl(iri+j)) .le. thres) then temp1 = max( eps23, & dlapy2( workl(irr+j), workl(iri+j) ) ) if (workl(ibd+j) .le. tol*temp1) & select(j+1) = .true. end if end if if (j+1 .gt. nconv ) reord = ( select(j+1) .or. reord ) if (select(j+1)) ktrord = ktrord + 1 10 continue c if (msglvl .gt. 2) then call igraphivout(logfil, 1, ktrord, ndigit, & '_neupd: Number of specified eigenvalues') call igraphivout(logfil, 1, nconv, ndigit, & '_neupd: Number of "converged" eigenvalues') end if c c %-----------------------------------------------------------% c | Call LAPACK routine dlahqr to compute the real Schur form | c | of the upper Hessenberg matrix returned by DNAUPD. | c | Make a copy of the upper Hessenberg matrix. | c | Initialize the Schur vector matrix Q to the identity. | c %-----------------------------------------------------------% c call dcopy (ldh*ncv, workl(ih), 1, workl(iuptri), 1) call dlaset ('All', ncv, ncv, zero, one, workl(invsub), ldq) call dlahqr (.true., .true., ncv, 1, ncv, workl(iuptri), ldh, & workl(iheigr), workl(iheigi), 1, ncv, & workl(invsub), ldq, ierr) call dcopy (ncv, workl(invsub+ncv-1), ldq, workl(ihbds), 1) c if (ierr .ne. 0) then info = -8 go to 9000 end if c if (msglvl .gt. 1) then call igraphdvout (logfil, ncv, workl(iheigr), ndigit, & '_neupd: Real part of the eigenvalues of H') call igraphdvout (logfil, ncv, workl(iheigi), ndigit, & '_neupd: Imaginary part of the Eigenvalues of H') call igraphdvout (logfil, ncv, workl(ihbds), ndigit, & '_neupd: Last row of the Schur vector matrix') if (msglvl .gt. 3) then call igraphdmout (logfil, ncv, ncv, workl(iuptri), ldh, & ndigit, & '_neupd: The upper quasi-triangular matrix ') end if end if c if (reord) then c c %-----------------------------------------------------% c | Reorder the computed upper quasi-triangular matrix. | c %-----------------------------------------------------% c call dtrsen ('None', 'V', select, ncv, workl(iuptri), ldh, & workl(invsub), ldq, workl(iheigr), workl(iheigi), & nconv, conds, sep, workl(ihbds), ncv, iwork, 1, ierr) c if (ierr .eq. 1) then info = 1 go to 9000 end if c if (msglvl .gt. 2) then call igraphdvout (logfil, ncv, workl(iheigr), ndigit, & '_neupd: Real part of the eigenvalues of H--reordered') call igraphdvout (logfil, ncv, workl(iheigi), ndigit, & '_neupd: Imag part of the eigenvalues of H--reordered') if (msglvl .gt. 3) then call igraphdmout (logfil, ncv, ncv, workl(iuptri), & ldq, ndigit, & '_neupd: Quasi-triangular matrix after re-ordering') end if end if c end if c c %---------------------------------------% c | Copy the last row of the Schur vector | c | into workl(ihbds). This will be used | c | to compute the Ritz estimates of | c | converged Ritz values. | c %---------------------------------------% c call dcopy(ncv, workl(invsub+ncv-1), ldq, workl(ihbds), 1) c c %----------------------------------------------------% c | Place the computed eigenvalues of H into DR and DI | c | if a spectral transformation was not used. | c %----------------------------------------------------% c if (type .eq. 'REGULR') then call dcopy (nconv, workl(iheigr), 1, dr, 1) call dcopy (nconv, workl(iheigi), 1, di, 1) end if c c %----------------------------------------------------------% c | Compute the QR factorization of the matrix representing | c | the wanted invariant subspace located in the first NCONV | c | columns of workl(invsub,ldq). | c %----------------------------------------------------------% c call dgeqr2 (ncv, nconv, workl(invsub), ldq, workev, & workev(ncv+1), ierr) c c %---------------------------------------------------------% c | * Postmultiply V by Q using dorm2r. | c | * Copy the first NCONV columns of VQ into Z. | c | * Postmultiply Z by R. | c | The N by NCONV matrix Z is now a matrix representation | c | of the approximate invariant subspace associated with | c | the Ritz values in workl(iheigr) and workl(iheigi) | c | The first NCONV columns of V are now approximate Schur | c | vectors associated with the real upper quasi-triangular | c | matrix of order NCONV in workl(iuptri) | c %---------------------------------------------------------% c call dorm2r ('Right', 'Notranspose', n, ncv, nconv, & workl(invsub), ldq, workev, v, ldv, workd(n+1), ierr) call dlacpy ('All', n, nconv, v, ldv, z, ldz) c do 20 j=1, nconv c c %---------------------------------------------------% c | Perform both a column and row scaling if the | c | diagonal element of workl(invsub,ldq) is negative | c | I'm lazy and don't take advantage of the upper | c | quasi-triangular form of workl(iuptri,ldq) | c | Note that since Q is orthogonal, R is a diagonal | c | matrix consisting of plus or minus ones | c %---------------------------------------------------% c if (workl(invsub+(j-1)*ldq+j-1) .lt. zero) then call dscal (nconv, -one, workl(iuptri+j-1), ldq) call dscal (nconv, -one, workl(iuptri+(j-1)*ldq), 1) end if c 20 continue c if (howmny .eq. 'A') then c c %--------------------------------------------% c | Compute the NCONV wanted eigenvectors of T | c | located in workl(iuptri,ldq). | c %--------------------------------------------% c do 30 j=1, ncv if (j .le. nconv) then select(j) = .true. else select(j) = .false. end if 30 continue c call dtrevc ('Right', 'Select', select, ncv, workl(iuptri), & ldq, vl, 1, workl(invsub), ldq, ncv, outncv, workev, & ierr) c if (ierr .ne. 0) then info = -9 go to 9000 end if c c %------------------------------------------------% c | Scale the returning eigenvectors so that their | c | Euclidean norms are all one. LAPACK subroutine | c | dtrevc returns each eigenvector normalized so | c | that the element of largest magnitude has | c | magnitude 1; | c %------------------------------------------------% c iconj = 0 do 40 j=1, nconv c if ( workl(iheigi+j-1) .eq. zero ) then c c %----------------------% c | real eigenvalue case | c %----------------------% c temp = dnrm2( ncv, workl(invsub+(j-1)*ldq), 1 ) call dscal ( ncv, one / temp, & workl(invsub+(j-1)*ldq), 1 ) c else c c %-------------------------------------------% c | Complex conjugate pair case. Note that | c | since the real and imaginary part of | c | the eigenvector are stored in consecutive | c | columns, we further normalize by the | c | square root of two. | c %-------------------------------------------% c if (iconj .eq. 0) then temp = dlapy2( dnrm2( ncv, workl(invsub+(j-1)*ldq), & 1 ), dnrm2( ncv, workl(invsub+j*ldq), 1) ) call dscal ( ncv, one / temp, & workl(invsub+(j-1)*ldq), 1 ) call dscal ( ncv, one / temp, & workl(invsub+j*ldq), 1 ) iconj = 1 else iconj = 0 end if c end if c 40 continue c call dgemv('T', ncv, nconv, one, workl(invsub), & ldq, workl(ihbds), 1, zero, workev, 1) c iconj = 0 do 45 j=1, nconv if (workl(iheigi+j-1) .ne. zero) then c c %-------------------------------------------% c | Complex conjugate pair case. Note that | c | since the real and imaginary part of | c | the eigenvector are stored in consecutive | c %-------------------------------------------% c if (iconj .eq. 0) then workev(j) = dlapy2(workev(j), workev(j+1)) workev(j+1) = workev(j) iconj = 1 else iconj = 0 end if end if 45 continue c if (msglvl .gt. 2) then call dcopy(ncv, workl(invsub+ncv-1), ldq, & workl(ihbds), 1) call igraphdvout (logfil, ncv, workl(ihbds), ndigit, & '_neupd: Last row of the eigenvector matrix for T') if (msglvl .gt. 3) then call igraphdmout (logfil, ncv, ncv, workl(invsub), & ldq, ndigit, & '_neupd: The eigenvector matrix for T') end if end if c c %---------------------------------------% c | Copy Ritz estimates into workl(ihbds) | c %---------------------------------------% c call dcopy(nconv, workev, 1, workl(ihbds), 1) c c %---------------------------------------------------------% c | Compute the QR factorization of the eigenvector matrix | c | associated with leading portion of T in the first NCONV | c | columns of workl(invsub,ldq). | c %---------------------------------------------------------% c call dgeqr2 (ncv, nconv, workl(invsub), ldq, workev, & workev(ncv+1), ierr) c c %----------------------------------------------% c | * Postmultiply Z by Q. | c | * Postmultiply Z by R. | c | The N by NCONV matrix Z is now contains the | c | Ritz vectors associated with the Ritz values | c | in workl(iheigr) and workl(iheigi). | c %----------------------------------------------% c call dorm2r ('Right', 'Notranspose', n, ncv, nconv, & workl(invsub), ldq, workev, z, ldz, workd(n+1), ierr) c call dtrmm ('Right', 'Upper', 'No transpose', 'Non-unit', & n, nconv, one, workl(invsub), ldq, z, ldz) c end if c else c c %------------------------------------------------------% c | An approximate invariant subspace is not needed. | c | Place the Ritz values computed DNAUPD into DR and DI | c %------------------------------------------------------% c call dcopy (nconv, workl(ritzr), 1, dr, 1) call dcopy (nconv, workl(ritzi), 1, di, 1) call dcopy (nconv, workl(ritzr), 1, workl(iheigr), 1) call dcopy (nconv, workl(ritzi), 1, workl(iheigi), 1) call dcopy (nconv, workl(bounds), 1, workl(ihbds), 1) end if c c %------------------------------------------------% c | Transform the Ritz values and possibly vectors | c | and corresponding error bounds of OP to those | c | of A*x = lambda*B*x. | c %------------------------------------------------% c if (type .eq. 'REGULR') then c if (rvec) & call dscal (ncv, rnorm, workl(ihbds), 1) c else c c %---------------------------------------% c | A spectral transformation was used. | c | * Determine the Ritz estimates of the | c | Ritz values in the original system. | c %---------------------------------------% c if (type .eq. 'SHIFTI') then c if (rvec) & call dscal (ncv, rnorm, workl(ihbds), 1) c do 50 k=1, ncv temp = dlapy2( workl(iheigr+k-1), & workl(iheigi+k-1) ) workl(ihbds+k-1) = abs( workl(ihbds+k-1) ) & / temp / temp 50 continue c else if (type .eq. 'REALPT') then c do 60 k=1, ncv 60 continue c else if (type .eq. 'IMAGPT') then c do 70 k=1, ncv 70 continue c end if c c %-----------------------------------------------------------% c | * Transform the Ritz values back to the original system. | c | For TYPE = 'SHIFTI' the transformation is | c | lambda = 1/theta + sigma | c | For TYPE = 'REALPT' or 'IMAGPT' the user must from | c | Rayleigh quotients or a projection. See remark 3 above.| c | NOTES: | c | *The Ritz vectors are not affected by the transformation. | c %-----------------------------------------------------------% c if (type .eq. 'SHIFTI') then c do 80 k=1, ncv temp = dlapy2( workl(iheigr+k-1), & workl(iheigi+k-1) ) workl(iheigr+k-1) = workl(iheigr+k-1) / temp / temp & + sigmar workl(iheigi+k-1) = -workl(iheigi+k-1) / temp / temp & + sigmai 80 continue c call dcopy (nconv, workl(iheigr), 1, dr, 1) call dcopy (nconv, workl(iheigi), 1, di, 1) c else if (type .eq. 'REALPT' .or. type .eq. 'IMAGPT') then c call dcopy (nconv, workl(iheigr), 1, dr, 1) call dcopy (nconv, workl(iheigi), 1, di, 1) c end if c end if c if (type .eq. 'SHIFTI' .and. msglvl .gt. 1) then call igraphdvout (logfil, nconv, dr, ndigit, & '_neupd: Untransformed real part of the Ritz valuess.') call igraphdvout (logfil, nconv, di, ndigit, & '_neupd: Untransformed imag part of the Ritz valuess.') call igraphdvout (logfil, nconv, workl(ihbds), ndigit, & '_neupd: Ritz estimates of untransformed Ritz values.') else if (type .eq. 'REGULR' .and. msglvl .gt. 1) then call igraphdvout (logfil, nconv, dr, ndigit, & '_neupd: Real parts of converged Ritz values.') call igraphdvout (logfil, nconv, di, ndigit, & '_neupd: Imag parts of converged Ritz values.') call igraphdvout (logfil, nconv, workl(ihbds), ndigit, & '_neupd: Associated Ritz estimates.') end if c c %-------------------------------------------------% c | Eigenvector Purification step. Formally perform | c | one of inverse subspace iteration. Only used | c | for MODE = 2. | c %-------------------------------------------------% c if (rvec .and. howmny .eq. 'A' .and. type .eq. 'SHIFTI') then c c %------------------------------------------------% c | Purify the computed Ritz vectors by adding a | c | little bit of the residual vector: | c | T | c | resid(:)*( e s ) / theta | c | NCV | c | where H s = s theta. Remember that when theta | c | has nonzero imaginary part, the corresponding | c | Ritz vector is stored across two columns of Z. | c %------------------------------------------------% c iconj = 0 do 110 j=1, nconv if (workl(iheigi+j-1) .eq. zero) then workev(j) = workl(invsub+(j-1)*ldq+ncv-1) / & workl(iheigr+j-1) else if (iconj .eq. 0) then temp = dlapy2( workl(iheigr+j-1), workl(iheigi+j-1) ) workev(j) = ( workl(invsub+(j-1)*ldq+ncv-1) * & workl(iheigr+j-1) + & workl(invsub+j*ldq+ncv-1) * & workl(iheigi+j-1) ) / temp / temp workev(j+1) = ( workl(invsub+j*ldq+ncv-1) * & workl(iheigr+j-1) - & workl(invsub+(j-1)*ldq+ncv-1) * & workl(iheigi+j-1) ) / temp / temp iconj = 1 else iconj = 0 end if 110 continue c c %---------------------------------------% c | Perform a rank one update to Z and | c | purify all the Ritz vectors together. | c %---------------------------------------% c call dger (n, nconv, one, resid, 1, workev, 1, z, ldz) c end if c 9000 continue c return c c %---------------% c | End of DNEUPD | c %---------------% c end igraph/src/bfgs.c0000644000175100001440000001323513431000472013414 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_nongraph.h" #include "igraph_interrupt_internal.h" #include "igraph_statusbar.h" #include "memory.h" #include "config.h" #include /* This is from GNU R's optim.c, slightly adapted to igraph */ #define stepredn 0.2 #define acctol 0.0001 #define reltest 10.0 #define FALSE 0 #define TRUE 1 /* BFGS variable-metric method, based on Pascal code in J.C. Nash, `Compact Numerical Methods for Computers', 2nd edition, converted by p2c then re-crafted by B.D. Ripley */ int igraph_bfgs(igraph_vector_t *b, igraph_real_t *Fmin, igraph_scalar_function_t fminfn, igraph_vector_function_t fmingr, int maxit, int trace, igraph_real_t abstol, igraph_real_t reltol, int nREPORT, void *ex, igraph_integer_t *fncount, igraph_integer_t *grcount) { int n=(int) igraph_vector_size(b); igraph_bool_t accpoint, enough; igraph_vector_t g, t, X, c; igraph_matrix_t B; /* Lmatrix really */ int count, funcount, gradcount; igraph_real_t f, gradproj; int i, j, ilast, iter = 0; igraph_real_t s, steplength; igraph_real_t D1, D2; if (maxit <= 0) { *Fmin = fminfn(b, 0, ex); *fncount = 1; *grcount = 0; return 0; } if (nREPORT <= 0) IGRAPH_ERROR("REPORT must be > 0 (method = \"BFGS\")", IGRAPH_EINVAL); IGRAPH_VECTOR_INIT_FINALLY(&g, n); IGRAPH_VECTOR_INIT_FINALLY(&t, n); IGRAPH_VECTOR_INIT_FINALLY(&X, n); IGRAPH_VECTOR_INIT_FINALLY(&c, n); IGRAPH_MATRIX_INIT_FINALLY(&B, n, n); f = fminfn(b, 0, ex); if (!IGRAPH_FINITE(f)) IGRAPH_ERROR("initial value in 'BFGS' is not finite", IGRAPH_DIVERGED); if (trace) igraph_statusf("initial value %f ", 0, f); *Fmin = f; funcount = gradcount = 1; fmingr(b, 0, &g, ex); iter++; ilast = gradcount; do { IGRAPH_ALLOW_INTERRUPTION(); if (ilast == gradcount) { for (i = 0; i < n; i++) { for (j = 0; j < i; j++) MATRIX(B,i,j) = 0.0; MATRIX(B, i, i) = 1.0; } } for (i = 0; i < n; i++) { VECTOR(X)[i] = VECTOR(*b)[i]; VECTOR(c)[i] = VECTOR(g)[i]; } gradproj = 0.0; for (i = 0; i < n; i++) { s = 0.0; for (j = 0; j <= i; j++) s -= MATRIX(B,i,j) * VECTOR(g)[j]; for (j = i + 1; j < n; j++) s -= MATRIX(B,j,i) * VECTOR(g)[j]; VECTOR(t)[i] = s; gradproj += s * VECTOR(g)[i]; } if (gradproj < 0.0) { /* search direction is downhill */ steplength = 1.0; accpoint = FALSE; do { count = 0; for (i = 0; i < n; i++) { VECTOR(*b)[i] = VECTOR(X)[i] + steplength * VECTOR(t)[i]; if (reltest + VECTOR(X)[i] == reltest + VECTOR(*b)[i]) /* no change */ count++; } if (count < n) { f = fminfn(b, 0, ex); funcount++; accpoint = IGRAPH_FINITE(f) && (f <= *Fmin + gradproj * steplength * acctol); if (!accpoint) { steplength *= stepredn; } } } while (!(count == n || accpoint)); enough = (f > abstol) && fabs(f - *Fmin) > reltol * (fabs(*Fmin) + reltol); /* stop if value if small or if relative change is low */ if (!enough) { count = n; *Fmin = f; } if (count < n) {/* making progress */ *Fmin = f; fmingr(b, 0, &g, ex); gradcount++; iter++; D1 = 0.0; for (i = 0; i < n; i++) { VECTOR(t)[i] = steplength * VECTOR(t)[i]; VECTOR(c)[i] = VECTOR(g)[i] - VECTOR(c)[i]; D1 += VECTOR(t)[i] * VECTOR(c)[i]; } if (D1 > 0) { D2 = 0.0; for (i = 0; i < n; i++) { s = 0.0; for (j = 0; j <= i; j++) s += MATRIX(B,i,j) * VECTOR(c)[j]; for (j = i + 1; j < n; j++) s += MATRIX(B,j,i) * VECTOR(c)[j]; VECTOR(X)[i] = s; D2 += s * VECTOR(c)[i]; } D2 = 1.0 + D2 / D1; for (i = 0; i < n; i++) { for (j = 0; j <= i; j++) MATRIX(B,i,j) += (D2 * VECTOR(t)[i] * VECTOR(t)[j] - VECTOR(X)[i] * VECTOR(t)[j] - VECTOR(t)[i] * VECTOR(X)[j]) / D1; } } else { /* D1 < 0 */ ilast = gradcount; } } else { /* no progress */ if (ilast < gradcount) { count = 0; ilast = gradcount; } } } else { /* uphill search */ count = 0; if (ilast == gradcount) count = n; else ilast = gradcount; /* Resets unless has just been reset */ } if (trace && (iter % nREPORT == 0)) igraph_statusf("iter%4d value %f", 0, iter, f); if (iter >= maxit) break; if (gradcount - ilast > 2 * n) ilast = gradcount; /* periodic restart */ } while (count != n || ilast != gradcount); if (trace) { igraph_statusf("final value %f ", 0, *Fmin); if (iter < maxit) igraph_status("converged", 0); else igraph_statusf("stopped after %i iterations", 0, iter); } *fncount = funcount; *grcount = gradcount; igraph_matrix_destroy(&B); igraph_vector_destroy(&c); igraph_vector_destroy(&X); igraph_vector_destroy(&t); igraph_vector_destroy(&g); IGRAPH_FINALLY_CLEAN(5); return (iter 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MATH_H #define IGRAPH_MATH_H #include "config.h" #include #include #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /** * \def IGRAPH_SHORTEST_PATH_EPSILON * * Relative error threshold used in weighted shortest path calculations * to decide whether two shortest paths are of equal length. */ #define IGRAPH_SHORTEST_PATH_EPSILON 1e-10 /* * Compiler-related hacks, mostly because of Microsoft Visual C++ */ double igraph_i_round(double X); int igraph_i_snprintf(char *buffer, size_t count, const char *format, ...); double igraph_log2(const double a); double igraph_log1p(double a); long double igraph_fabsl(long double a); double igraph_fmin(double a, double b); #ifndef HAVE_LOG2 #define log2(a) igraph_log2(a) #endif #ifndef HAVE_LOG1P #define log1p(a) igraph_log1p(a) #endif #ifndef HAVE_FABSL #define fabsl(a) igraph_fabsl(a) #endif #ifndef HAVE_FMIN #define fmin(a,b) igraph_fmin((a),(b)) #endif #ifndef HAVE_ROUND #define round igraph_i_round #endif #ifndef M_PI # define M_PI 3.14159265358979323846 #endif #ifndef M_PI_2 # define M_PI_2 1.57079632679489661923 #endif #ifndef M_LN2 # define M_LN2 0.69314718055994530942 #endif #ifndef M_SQRT2 # define M_SQRT2 1.4142135623730950488016887 #endif #ifndef M_LN_SQRT_2PI #define M_LN_SQRT_2PI 0.918938533204672741780329736406 /* log(sqrt(2*pi)) == log(2*pi)/2 */ #endif int igraph_almost_equals(double a, double b, double eps); int igraph_cmp_epsilon(double a, double b, double eps); __END_DECLS #endif igraph/src/foreign-lgl-lexer.c0000644000175100001440000016060113431000472016015 0ustar hornikusers#line 2 "lex.yy.c" #line 4 "lex.yy.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE igraph_lgl_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via igraph_lgl_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void igraph_lgl_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void igraph_lgl_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_lgl_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void igraph_lgl_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_lgl_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_lgl_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void igraph_lgl_yypop_buffer_state (yyscan_t yyscanner ); static void igraph_lgl_yyensure_buffer_stack (yyscan_t yyscanner ); static void igraph_lgl_yy_load_buffer_state (yyscan_t yyscanner ); static void igraph_lgl_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER igraph_lgl_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE igraph_lgl_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_lgl_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_lgl_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *igraph_lgl_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *igraph_lgl_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void igraph_lgl_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer igraph_lgl_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ igraph_lgl_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_lgl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ igraph_lgl_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_lgl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define igraph_lgl_yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 6 #define YY_END_OF_BUFFER 7 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[13] = { 0, 2, 2, 7, 4, 2, 3, 3, 1, 4, 2, 3, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[6] = { 0, 1, 2, 3, 4, 5 } ; static yyconst flex_int16_t yy_base[17] = { 0, 0, 0, 10, 0, 0, 0, 0, 11, 0, 0, 11, 11, 8, 6, 3, 3 } ; static yyconst flex_int16_t yy_def[17] = { 0, 12, 1, 12, 13, 14, 15, 16, 12, 13, 14, 12, 0, 12, 12, 12, 12 } ; static yyconst flex_int16_t yy_nxt[17] = { 0, 4, 5, 6, 7, 8, 11, 11, 10, 9, 12, 3, 12, 12, 12, 12, 12 } ; static yyconst flex_int16_t yy_chk[17] = { 0, 1, 1, 1, 1, 1, 16, 15, 14, 13, 3, 12, 12, 12, 12, 12, 12 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "src/foreign-lgl-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #line 24 "src/foreign-lgl-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-lgl-header.h" #include "foreign-lgl-parser.h" #define YY_EXTRA_TYPE igraph_i_lgl_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); #define YY_NO_INPUT 1 #line 500 "lex.yy.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int igraph_lgl_yylex_init (yyscan_t* scanner); int igraph_lgl_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int igraph_lgl_yylex_destroy (yyscan_t yyscanner ); int igraph_lgl_yyget_debug (yyscan_t yyscanner ); void igraph_lgl_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE igraph_lgl_yyget_extra (yyscan_t yyscanner ); void igraph_lgl_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *igraph_lgl_yyget_in (yyscan_t yyscanner ); void igraph_lgl_yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *igraph_lgl_yyget_out (yyscan_t yyscanner ); void igraph_lgl_yyset_out (FILE * out_str ,yyscan_t yyscanner ); yy_size_t igraph_lgl_yyget_leng (yyscan_t yyscanner ); char *igraph_lgl_yyget_text (yyscan_t yyscanner ); int igraph_lgl_yyget_lineno (yyscan_t yyscanner ); void igraph_lgl_yyset_lineno (int line_number ,yyscan_t yyscanner ); YYSTYPE * igraph_lgl_yyget_lval (yyscan_t yyscanner ); void igraph_lgl_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); YYLTYPE *igraph_lgl_yyget_lloc (yyscan_t yyscanner ); void igraph_lgl_yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int igraph_lgl_yywrap (yyscan_t yyscanner ); #else extern int igraph_lgl_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int igraph_lgl_yylex \ (YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner); #define YY_DECL int igraph_lgl_yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; #line 77 "src/foreign-lgl-lexer.l" /* --------------------------------------------------hashmark------*/ #line 743 "lex.yy.c" yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { igraph_lgl_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_lgl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_lgl_yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 13 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 11 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 80 "src/foreign-lgl-lexer.l" { return HASH; } YY_BREAK /* ------------------------------------------------whitespace------*/ case 2: YY_RULE_SETUP #line 83 "src/foreign-lgl-lexer.l" { } YY_BREAK /* ---------------------------------------------------newline------*/ case 3: /* rule 3 can match eol */ YY_RULE_SETUP #line 86 "src/foreign-lgl-lexer.l" { return NEWLINE; } YY_BREAK /* ----------------------------------------------alphanumeric------*/ case 4: YY_RULE_SETUP #line 89 "src/foreign-lgl-lexer.l" { return ALNUM; } YY_BREAK case YY_STATE_EOF(INITIAL): #line 91 "src/foreign-lgl-lexer.l" { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } YY_BREAK case 5: YY_RULE_SETUP #line 99 "src/foreign-lgl-lexer.l" { return ERROR; } YY_BREAK case 6: YY_RULE_SETUP #line 101 "src/foreign-lgl-lexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 874 "lex.yy.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * igraph_lgl_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( igraph_lgl_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of igraph_lgl_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ igraph_lgl_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; igraph_lgl_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) igraph_lgl_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 13 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 13 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 12); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ igraph_lgl_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( igraph_lgl_yywrap(yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void igraph_lgl_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ igraph_lgl_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_lgl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_lgl_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); igraph_lgl_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void igraph_lgl_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * igraph_lgl_yypop_buffer_state(); * igraph_lgl_yypush_buffer_state(new_buffer); */ igraph_lgl_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; igraph_lgl_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (igraph_lgl_yywrap()) processing, but the only time this flag * is looked at is after igraph_lgl_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void igraph_lgl_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE igraph_lgl_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) igraph_lgl_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) igraph_lgl_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yy_create_buffer()" ); b->yy_is_our_buffer = 1; igraph_lgl_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with igraph_lgl_yy_create_buffer() * @param yyscanner The scanner object. */ void igraph_lgl_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) igraph_lgl_yyfree((void *) b->yy_ch_buf ,yyscanner ); igraph_lgl_yyfree((void *) b ,yyscanner ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a igraph_lgl_yyrestart() or at EOF. */ static void igraph_lgl_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; igraph_lgl_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then igraph_lgl_yy_init_buffer was _probably_ * called from igraph_lgl_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void igraph_lgl_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) igraph_lgl_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void igraph_lgl_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; igraph_lgl_yyensure_buffer_stack(yyscanner); /* This block is copied from igraph_lgl_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from igraph_lgl_yy_switch_to_buffer. */ igraph_lgl_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void igraph_lgl_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; igraph_lgl_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { igraph_lgl_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void igraph_lgl_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_lgl_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_lgl_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_lgl_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) igraph_lgl_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; igraph_lgl_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to igraph_lgl_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * igraph_lgl_yy_scan_bytes() instead. */ YY_BUFFER_STATE igraph_lgl_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return igraph_lgl_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to igraph_lgl_yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_lgl_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) igraph_lgl_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_lgl_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = igraph_lgl_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in igraph_lgl_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE igraph_lgl_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int igraph_lgl_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int igraph_lgl_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *igraph_lgl_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *igraph_lgl_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t igraph_lgl_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *igraph_lgl_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void igraph_lgl_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void igraph_lgl_yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_lgl_yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void igraph_lgl_yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_lgl_yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see igraph_lgl_yy_switch_to_buffer */ void igraph_lgl_yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void igraph_lgl_yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int igraph_lgl_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void igraph_lgl_yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * igraph_lgl_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void igraph_lgl_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *igraph_lgl_yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void igraph_lgl_yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* igraph_lgl_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int igraph_lgl_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_lgl_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* igraph_lgl_yylex_init_extra has the same functionality as igraph_lgl_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to igraph_lgl_yyalloc in * the yyextra field. */ int igraph_lgl_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; igraph_lgl_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_lgl_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); igraph_lgl_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from igraph_lgl_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * igraph_lgl_yylex_init() */ return 0; } /* igraph_lgl_yylex_destroy is for both reentrant and non-reentrant scanners. */ int igraph_lgl_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ igraph_lgl_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; igraph_lgl_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ igraph_lgl_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ igraph_lgl_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * igraph_lgl_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ igraph_lgl_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *igraph_lgl_yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *igraph_lgl_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void igraph_lgl_yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see igraph_lgl_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 101 "src/foreign-lgl-lexer.l" igraph/src/gengraph_header.h0000644000175100001440000000576013431000472015607 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_definitions.h" #include #include #include "gengraph_random.h" namespace gengraph { static KW_RNG::RNG _my_random; int my_random() { return _my_random.rand_int31(); } void my_srandom(int x) { _my_random.init(x,!x*13,x*x+1,(x>>16)+(x<<16)); } int my_binomial(double pp, int n) { return _my_random.binomial(pp,n); } double my_random01() { return _my_random.rand_halfopen01(); } } #ifdef _WIN32 #include #include void set_priority_low() { HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,TRUE,_getpid()); SetPriorityClass(hProcess,IDLE_PRIORITY_CLASS); } #else #include #endif namespace gengraph { static int VERB; int VERBOSE() { return VERB; } void SET_VERBOSE(int v) { VERB = v; } //Hash profiling static unsigned long _hash_rm_i = 0; static unsigned long _hash_rm_c = 0; static unsigned long _hash_add_i = 0; static unsigned long _hash_add_c = 0; static unsigned long _hash_put_i = 0; static unsigned long _hash_put_c = 0; static unsigned long _hash_find_i = 0; static unsigned long _hash_find_c = 0; static unsigned long _hash_rand_i = 0; static unsigned long _hash_rand_c = 0; static unsigned long _hash_expand = 0; inline void _hash_add_iter() { _hash_add_i++; } inline void _hash_add_call() { _hash_add_c++; } inline void _hash_put_iter() { _hash_put_i++; } inline void _hash_put_call() { _hash_put_c++; } inline void _hash_rm_iter() { _hash_rm_i++; } inline void _hash_rm_call() { _hash_rm_c++; } inline void _hash_find_iter() { _hash_find_i++; } inline void _hash_find_call() { _hash_find_c++; } inline void _hash_rand_iter() { _hash_rand_i++; } inline void _hash_rand_call() { _hash_rand_c++; } inline void _hash_expand_call() { _hash_expand++; } // void _hash_prof() { // fprintf(stderr,"HASH_ADD : %lu / %lu\n", _hash_add_c , _hash_add_i); // fprintf(stderr,"HASH_PUT : %lu / %lu\n", _hash_put_c , _hash_put_i); // fprintf(stderr,"HASH_FIND: %lu / %lu\n", _hash_find_c, _hash_find_i); // fprintf(stderr,"HASH_RM : %lu / %lu\n", _hash_rm_c , _hash_rm_i); // fprintf(stderr,"HASH_RAND: %lu / %lu\n", _hash_rand_c, _hash_rand_i); // fprintf(stderr,"HASH_EXPAND : %lu calls\n", _hash_expand); // } } // namespace gengraph igraph/src/heap.c0000644000175100001440000006675713431000472013431 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include "igraph_math.h" #include #include /* memcpy & co. */ #include #define PARENT(x) (((x)+1)/2-1) #define LEFTCHILD(x) (((x)+1)*2-1) #define RIGHTCHILD(x) (((x)+1)*2) /** * \ingroup indheap * \brief Initializes an indexed heap (constructor). * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_indheap_init (igraph_indheap_t* h, long int alloc_size) { if (alloc_size <= 0 ) { alloc_size=1; } h->stor_begin=igraph_Calloc(alloc_size, igraph_real_t); if (h->stor_begin==0) { h->index_begin=0; IGRAPH_ERROR("indheap init failed", IGRAPH_ENOMEM); } h->index_begin=igraph_Calloc(alloc_size, long int); if (h->index_begin==0) { igraph_Free(h->stor_begin); h->stor_begin=0; IGRAPH_ERROR("indheap init failed", IGRAPH_ENOMEM); } h->stor_end=h->stor_begin + alloc_size; h->end=h->stor_begin; h->destroy=1; return 0; } int igraph_indheap_clear(igraph_indheap_t *h) { h->end=h->stor_begin; return 0; } /** * \ingroup indheap * \brief Initializes and build an indexed heap from a C array (constructor). * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_indheap_init_array (igraph_indheap_t *h, igraph_real_t* data, long int len) { long int i; h->stor_begin=igraph_Calloc(len, igraph_real_t); if (h->stor_begin==0) { h->index_begin=0; IGRAPH_ERROR("indheap init from array failed", IGRAPH_ENOMEM); } h->index_begin=igraph_Calloc(len, long int); if (h->index_begin==0) { igraph_Free(h->stor_begin); h->stor_begin=0; IGRAPH_ERROR("indheap init from array failed", IGRAPH_ENOMEM); } h->stor_end=h->stor_begin+len; h->end=h->stor_end; h->destroy=1; memcpy(h->stor_begin, data, (size_t) len*sizeof(igraph_real_t)); for (i=0; iindex_begin[i]=i+1; } igraph_indheap_i_build (h, 0); return 0; } /** * \ingroup indheap * \brief Destroys an initialized indexed heap. */ void igraph_indheap_destroy (igraph_indheap_t* h) { assert(h != 0); if (h->destroy) { if (h->stor_begin != 0) { igraph_Free(h->stor_begin); h->stor_begin=0; } if (h->index_begin != 0) { igraph_Free(h->index_begin); h->index_begin=0; } } } /** * \ingroup indheap * \brief Checks whether a heap is empty. */ igraph_bool_t igraph_indheap_empty (igraph_indheap_t* h) { assert(h != 0); assert(h->stor_begin != 0); return h->stor_begin == h->end; } /** * \ingroup indheap * \brief Adds an element to an indexed heap. */ int igraph_indheap_push (igraph_indheap_t* h, igraph_real_t elem) { assert(h != 0); assert(h->stor_begin != 0); /* full, allocate more storage */ if (h->stor_end == h->end) { long int new_size = igraph_indheap_size(h) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(igraph_indheap_reserve(h, new_size)); } *(h->end) = elem; h->end += 1; *(h->index_begin+igraph_indheap_size(h)-1)=igraph_indheap_size(h)-1; /* maintain indheap */ igraph_indheap_i_shift_up(h, igraph_indheap_size(h)-1); return 0; } /** * \ingroup indheap * \brief Adds an element to an indexed heap with a given index. */ int igraph_indheap_push_with_index(igraph_indheap_t* h, long int idx, igraph_real_t elem) { assert(h != 0); assert(h->stor_begin != 0); /* full, allocate more storage */ if (h->stor_end == h->end) { long int new_size = igraph_indheap_size(h) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(igraph_indheap_reserve(h, new_size)); } *(h->end) = elem; h->end += 1; *(h->index_begin+igraph_indheap_size(h)-1)=idx; /* maintain indheap */ igraph_indheap_i_shift_up(h, igraph_indheap_size(h)-1); return 0; } /** * \ingroup indheap * \brief Modifies an element in an indexed heap. */ int igraph_indheap_modify(igraph_indheap_t* h, long int idx, igraph_real_t elem) { long int i, n; assert(h != 0); assert(h->stor_begin != 0); n = igraph_indheap_size(h); for (i=0; iindex_begin[i] == idx) { h->stor_begin[i] = elem; break; } if (i == n) return 0; /* maintain indheap */ igraph_indheap_i_build(h, 0); return 0; } /** * \ingroup indheap * \brief Returns the largest element in an indexed heap. */ igraph_real_t igraph_indheap_max (igraph_indheap_t* h) { assert(h != NULL); assert(h->stor_begin != NULL); assert(h->stor_begin != h->end); return h->stor_begin[0]; } /** * \ingroup indheap * \brief Removes the largest element from an indexed heap. */ igraph_real_t igraph_indheap_delete_max(igraph_indheap_t* h) { igraph_real_t tmp; assert(h != NULL); assert(h->stor_begin != NULL); tmp=h->stor_begin[0]; igraph_indheap_i_switch(h, 0, igraph_indheap_size(h)-1); h->end -= 1; igraph_indheap_i_sink(h, 0); return tmp; } /** * \ingroup indheap * \brief Gives the number of elements in an indexed heap. */ long int igraph_indheap_size (igraph_indheap_t* h) { assert(h != 0); assert(h->stor_begin != 0); return h->end - h->stor_begin; } /** * \ingroup indheap * \brief Reserves more memory for an indexed heap. * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_indheap_reserve (igraph_indheap_t* h, long int size) { long int actual_size=igraph_indheap_size(h); igraph_real_t *tmp1; long int *tmp2; assert(h != 0); assert(h->stor_begin != 0); if (size <= actual_size) { return 0; } tmp1=igraph_Calloc(size, igraph_real_t); if (tmp1==0) { IGRAPH_ERROR("indheap reserve failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp1); /* TODO: hack */ tmp2=igraph_Calloc(size, long int); if (tmp2==0) { IGRAPH_ERROR("indheap reserve failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp2); memcpy(tmp1, h->stor_begin, (size_t) actual_size*sizeof(igraph_real_t)); memcpy(tmp2, h->index_begin, (size_t) actual_size*sizeof(long int)); igraph_Free(h->stor_begin); igraph_Free(h->index_begin); h->stor_begin=tmp1; h->index_begin=tmp2; h->stor_end=h->stor_begin + size; h->end=h->stor_begin+actual_size; IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \ingroup indheap * \brief Returns the index of the largest element in an indexed heap. */ long int igraph_indheap_max_index(igraph_indheap_t *h) { assert(h != 0); assert(h->stor_begin != 0); return h->index_begin[0]; } /** * \ingroup indheap * \brief Builds an indexed heap, this function should not be called * directly. */ void igraph_indheap_i_build(igraph_indheap_t* h, long int head) { long int size=igraph_indheap_size(h); if (RIGHTCHILD(head) < size) { /* both subtrees */ igraph_indheap_i_build(h, LEFTCHILD(head) ); igraph_indheap_i_build(h, RIGHTCHILD(head)); igraph_indheap_i_sink(h, head); } else if (LEFTCHILD(head) < size) { /* only left */ igraph_indheap_i_build(h, LEFTCHILD(head)); igraph_indheap_i_sink(h, head); } else { /* none */ } } /** * \ingroup indheap * \brief Moves an element up in the heap, don't call this function * directly. */ void igraph_indheap_i_shift_up(igraph_indheap_t *h, long int elem) { if (elem==0 || h->stor_begin[elem] < h->stor_begin[PARENT(elem)]) { /* at the top */ } else { igraph_indheap_i_switch(h, elem, PARENT(elem)); igraph_indheap_i_shift_up(h, PARENT(elem)); } } /** * \ingroup indheap * \brief Moves an element down in the heap, don't call this function * directly. */ void igraph_indheap_i_sink(igraph_indheap_t* h, long int head) { long int size=igraph_indheap_size(h); if (LEFTCHILD(head) >= size) { /* no subtrees */ } else if (RIGHTCHILD(head) == size || h->stor_begin[LEFTCHILD(head)]>=h->stor_begin[RIGHTCHILD(head)]) { /* sink to the left if needed */ if (h->stor_begin[head] < h->stor_begin[LEFTCHILD(head)]) { igraph_indheap_i_switch(h, head, LEFTCHILD(head)); igraph_indheap_i_sink(h, LEFTCHILD(head)); } } else { /* sink to the right */ if (h->stor_begin[head] < h->stor_begin[RIGHTCHILD(head)]) { igraph_indheap_i_switch(h, head, RIGHTCHILD(head)); igraph_indheap_i_sink(h, RIGHTCHILD(head)); } } } /** * \ingroup indheap * \brief Switches two elements in a heap, don't call this function * directly. */ void igraph_indheap_i_switch(igraph_indheap_t* h, long int e1, long int e2) { if (e1!=e2) { igraph_real_t tmp=h->stor_begin[e1]; h->stor_begin[e1]=h->stor_begin[e2]; h->stor_begin[e2]=tmp; tmp=h->index_begin[e1]; h->index_begin[e1]=h->index_begin[e2]; h->index_begin[e2]=(long int) tmp; } } /** * \ingroup doubleindheap * \brief Initializes an empty doubly indexed heap object (constructor). * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_d_indheap_init (igraph_d_indheap_t* h, long int alloc_size) { if (alloc_size <= 0 ) { alloc_size=1; } h->stor_begin=igraph_Calloc(alloc_size, igraph_real_t); if (h->stor_begin==0) { h->index_begin=0; h->index2_begin=0; IGRAPH_ERROR("d_indheap init failed", IGRAPH_ENOMEM); } h->stor_end=h->stor_begin + alloc_size; h->end=h->stor_begin; h->destroy=1; h->index_begin=igraph_Calloc(alloc_size, long int); if (h->index_begin==0) { igraph_Free(h->stor_begin); h->stor_begin=0; h->index2_begin=0; IGRAPH_ERROR("d_indheap init failed", IGRAPH_ENOMEM); } h->index2_begin=igraph_Calloc(alloc_size, long int); if (h->index2_begin==0) { igraph_Free(h->stor_begin); igraph_Free(h->index_begin); h->stor_begin=0; h->index_begin=0; IGRAPH_ERROR("d_indheap init failed", IGRAPH_ENOMEM); } return 0; } /** * \ingroup doubleindheap * \brief Destroys an initialized doubly indexed heap object. */ void igraph_d_indheap_destroy (igraph_d_indheap_t* h) { assert(h != 0); if (h->destroy) { if (h->stor_begin != 0) { igraph_Free(h->stor_begin); h->stor_begin=0; } if (h->index_begin != 0) { igraph_Free(h->index_begin); h->index_begin=0; } if (h->index2_begin != 0) { igraph_Free(h->index2_begin); h->index2_begin=0; } } } /** * \ingroup doubleindheap * \brief Decides whether a heap is empty. */ igraph_bool_t igraph_d_indheap_empty (igraph_d_indheap_t* h) { assert(h != 0); assert(h->stor_begin != 0); return h->stor_begin == h->end; } /** * \ingroup doubleindheap * \brief Adds an element to the heap. */ int igraph_d_indheap_push (igraph_d_indheap_t* h, igraph_real_t elem, long int idx, long int idx2) { assert(h != 0); assert(h->stor_begin != 0); /* full, allocate more storage */ if (h->stor_end == h->end) { long int new_size = igraph_d_indheap_size(h) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(igraph_d_indheap_reserve(h, new_size)); } *(h->end) = elem; h->end += 1; *(h->index_begin+igraph_d_indheap_size(h)-1)=idx ; *(h->index2_begin+igraph_d_indheap_size(h)-1)=idx2 ; /* maintain d_indheap */ igraph_d_indheap_i_shift_up(h, igraph_d_indheap_size(h)-1); return 0; } /** * \ingroup doubleindheap * \brief Returns the largest element in the heap. */ igraph_real_t igraph_d_indheap_max (igraph_d_indheap_t* h) { assert(h != NULL); assert(h->stor_begin != NULL); assert(h->stor_begin != h->end); return h->stor_begin[0]; } /** * \ingroup doubleindheap * \brief Removes the largest element from the heap. */ igraph_real_t igraph_d_indheap_delete_max(igraph_d_indheap_t* h) { igraph_real_t tmp; assert(h != NULL); assert(h->stor_begin != NULL); tmp=h->stor_begin[0]; igraph_d_indheap_i_switch(h, 0, igraph_d_indheap_size(h)-1); h->end -= 1; igraph_d_indheap_i_sink(h, 0); return tmp; } /** * \ingroup doubleindheap * \brief Gives the number of elements in the heap. */ long int igraph_d_indheap_size (igraph_d_indheap_t* h) { assert(h != 0); assert(h->stor_begin != 0); return h->end - h->stor_begin; } /** * \ingroup doubleindheap * \brief Allocates memory for a heap. * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_d_indheap_reserve (igraph_d_indheap_t* h, long int size) { long int actual_size=igraph_d_indheap_size(h); igraph_real_t *tmp1; long int *tmp2, *tmp3; assert(h != 0); assert(h->stor_begin != 0); if (size <= actual_size) { return 0; } tmp1=igraph_Calloc(size, igraph_real_t); if (tmp1==0) { IGRAPH_ERROR("d_indheap reserve failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp1); /* TODO: hack */ tmp2=igraph_Calloc(size, long int); if (tmp2==0) { IGRAPH_ERROR("d_indheap reserve failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp2); /* TODO: hack */ tmp3=igraph_Calloc(size, long int); if (tmp3==0) { IGRAPH_ERROR("d_indheap reserve failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp3); /* TODO: hack */ memcpy(tmp1, h->stor_begin, (size_t) actual_size*sizeof(igraph_real_t)); memcpy(tmp2, h->index_begin, (size_t) actual_size*sizeof(long int)); memcpy(tmp3, h->index2_begin, (size_t) actual_size*sizeof(long int)); igraph_Free(h->stor_begin); igraph_Free(h->index_begin); igraph_Free(h->index2_begin); h->stor_begin=tmp1; h->stor_end=h->stor_begin + size; h->end=h->stor_begin+actual_size; h->index_begin=tmp2; h->index2_begin=tmp3; IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup doubleindheap * \brief Gives the indices of the maximal element in the heap. */ void igraph_d_indheap_max_index(igraph_d_indheap_t *h, long int *idx, long int *idx2) { assert(h != 0); assert(h->stor_begin != 0); (*idx)=h->index_begin[0]; (*idx2)=h->index2_begin[0]; } /** * \ingroup doubleindheap * \brief Builds the heap, don't call it directly. */ void igraph_d_indheap_i_build(igraph_d_indheap_t* h, long int head) { long int size=igraph_d_indheap_size(h); if (RIGHTCHILD(head) < size) { /* both subtrees */ igraph_d_indheap_i_build(h, LEFTCHILD(head) ); igraph_d_indheap_i_build(h, RIGHTCHILD(head)); igraph_d_indheap_i_sink(h, head); } else if (LEFTCHILD(head) < size) { /* only left */ igraph_d_indheap_i_build(h, LEFTCHILD(head)); igraph_d_indheap_i_sink(h, head); } else { /* none */ } } /** * \ingroup doubleindheap * \brief Moves an element up in the heap, don't call it directly. */ void igraph_d_indheap_i_shift_up(igraph_d_indheap_t *h, long int elem) { if (elem==0 || h->stor_begin[elem] < h->stor_begin[PARENT(elem)]) { /* at the top */ } else { igraph_d_indheap_i_switch(h, elem, PARENT(elem)); igraph_d_indheap_i_shift_up(h, PARENT(elem)); } } /** * \ingroup doubleindheap * \brief Moves an element down in the heap, don't call it directly. */ void igraph_d_indheap_i_sink(igraph_d_indheap_t* h, long int head) { long int size=igraph_d_indheap_size(h); if (LEFTCHILD(head) >= size) { /* no subtrees */ } else if (RIGHTCHILD(head) == size || h->stor_begin[LEFTCHILD(head)]>=h->stor_begin[RIGHTCHILD(head)]) { /* sink to the left if needed */ if (h->stor_begin[head] < h->stor_begin[LEFTCHILD(head)]) { igraph_d_indheap_i_switch(h, head, LEFTCHILD(head)); igraph_d_indheap_i_sink(h, LEFTCHILD(head)); } } else { /* sink to the right */ if (h->stor_begin[head] < h->stor_begin[RIGHTCHILD(head)]) { igraph_d_indheap_i_switch(h, head, RIGHTCHILD(head)); igraph_d_indheap_i_sink(h, RIGHTCHILD(head)); } } } /** * \ingroup doubleindheap * \brief Switches two elements in the heap, don't call it directly. */ void igraph_d_indheap_i_switch(igraph_d_indheap_t* h, long int e1, long int e2) { if (e1!=e2) { long int tmpi; igraph_real_t tmp=h->stor_begin[e1]; h->stor_begin[e1]=h->stor_begin[e2]; h->stor_begin[e2]=tmp; tmpi=h->index_begin[e1]; h->index_begin[e1]=h->index_begin[e2]; h->index_begin[e2]=tmpi; tmpi=h->index2_begin[e1]; h->index2_begin[e1]=h->index2_begin[e2]; h->index2_begin[e2]=tmpi; } } /*************************************************/ #undef PARENT #undef LEFTCHILD #undef RIGHTCHILD #define PARENT(x) ((x)/2) #define LEFTCHILD(x) ((x)*2+1) #define RIGHTCHILD(x) ((x)*2) #define INACTIVE IGRAPH_INFINITY #define UNDEFINED 0.0 #define INDEXINC 1 void igraph_i_cutheap_switch(igraph_i_cutheap_t *ch, long int hidx1, long int hidx2) { if (hidx1 != hidx2) { long int idx1=(long int) VECTOR(ch->index)[hidx1]; long int idx2=(long int) VECTOR(ch->index)[hidx2]; igraph_real_t tmp=VECTOR(ch->heap)[hidx1]; VECTOR(ch->heap)[hidx1]=VECTOR(ch->heap)[hidx2]; VECTOR(ch->heap)[hidx2]=tmp; VECTOR(ch->index)[hidx1]=idx2; VECTOR(ch->index)[hidx2]=idx1; VECTOR(ch->hptr)[idx1] = hidx2+INDEXINC; VECTOR(ch->hptr)[idx2] = hidx1+INDEXINC; } } void igraph_i_cutheap_sink(igraph_i_cutheap_t *ch, long int hidx) { long int size=igraph_vector_size(&ch->heap); if (LEFTCHILD(hidx) >= size) { /* leaf node */ } else if (RIGHTCHILD(hidx) == size || VECTOR(ch->heap)[LEFTCHILD(hidx)] >= VECTOR(ch->heap)[RIGHTCHILD(hidx)]) { /* sink to the left if needed */ if (VECTOR(ch->heap)[hidx] < VECTOR(ch->heap)[LEFTCHILD(hidx)]) { igraph_i_cutheap_switch(ch, hidx, LEFTCHILD(hidx)); igraph_i_cutheap_sink(ch, LEFTCHILD(hidx)); } } else { /* sink to the right */ if (VECTOR(ch->heap)[hidx] < VECTOR(ch->heap)[RIGHTCHILD(hidx)]) { igraph_i_cutheap_switch(ch, hidx, RIGHTCHILD(hidx)); igraph_i_cutheap_sink(ch, RIGHTCHILD(hidx)); } } } void igraph_i_cutheap_shift_up(igraph_i_cutheap_t *ch, long int hidx) { if (hidx==0 || VECTOR(ch->heap)[hidx] < VECTOR(ch->heap)[PARENT(hidx)]) { /* at the top */ } else { igraph_i_cutheap_switch(ch, hidx, PARENT(hidx)); igraph_i_cutheap_shift_up(ch, PARENT(hidx)); } } int igraph_i_cutheap_init(igraph_i_cutheap_t *ch, igraph_integer_t nodes) { ch->dnodes=nodes; IGRAPH_VECTOR_INIT_FINALLY(&ch->heap, nodes); /* all zero */ IGRAPH_CHECK(igraph_vector_init_seq(&ch->index, 0, nodes-1)); IGRAPH_FINALLY(igraph_vector_destroy, &ch->index); IGRAPH_CHECK(igraph_vector_init_seq(&ch->hptr, INDEXINC, nodes+INDEXINC-1)); IGRAPH_FINALLY_CLEAN(2); return 0; } void igraph_i_cutheap_destroy(igraph_i_cutheap_t *ch) { igraph_vector_destroy(&ch->hptr); igraph_vector_destroy(&ch->index); igraph_vector_destroy(&ch->heap); } igraph_bool_t igraph_i_cutheap_empty(igraph_i_cutheap_t *ch) { return igraph_vector_empty(&ch->heap); } /* Number of active vertices */ igraph_integer_t igraph_i_cutheap_active_size(igraph_i_cutheap_t *ch) { return (igraph_integer_t) igraph_vector_size(&ch->heap); } /* Number of all (defined) vertices */ igraph_integer_t igraph_i_cutheap_size(igraph_i_cutheap_t *ch) { return (igraph_integer_t) (ch->dnodes); } igraph_real_t igraph_i_cutheap_maxvalue(igraph_i_cutheap_t *ch) { return VECTOR(ch->heap)[0]; } igraph_integer_t igraph_i_cutheap_popmax(igraph_i_cutheap_t *ch) { long int size=igraph_vector_size(&ch->heap); igraph_integer_t maxindex=(igraph_integer_t) VECTOR(ch->index)[0]; /* put the last element to the top */ igraph_i_cutheap_switch(ch, 0, size-1); /* remove the last element */ VECTOR(ch->hptr)[(long int) igraph_vector_tail(&ch->index)] = INACTIVE; igraph_vector_pop_back(&ch->heap); igraph_vector_pop_back(&ch->index); igraph_i_cutheap_sink(ch, 0); return maxindex; } /* Update the value of an active vertex, if not active it will be ignored */ int igraph_i_cutheap_update(igraph_i_cutheap_t *ch, igraph_integer_t index, igraph_real_t add) { igraph_real_t hidx=VECTOR(ch->hptr)[(long int)index]; if (hidx != INACTIVE && hidx != UNDEFINED) { long int hidx2=(long int) (hidx-INDEXINC); /* printf("updating vertex %li, heap index %li\n", (long int) index, hidx2); */ VECTOR(ch->heap)[hidx2] += add; igraph_i_cutheap_sink(ch, hidx2); igraph_i_cutheap_shift_up(ch, hidx2); } return 0; } /* Reset the value of all vertices to zero and make them active */ int igraph_i_cutheap_reset_undefine(igraph_i_cutheap_t *ch, long int vertex) { long int i, j, n=igraph_vector_size(&ch->hptr); /* undefine */ VECTOR(ch->hptr)[vertex] = UNDEFINED; ch->dnodes -= 1; IGRAPH_CHECK(igraph_vector_resize(&ch->heap, ch->dnodes)); igraph_vector_null(&ch->heap); IGRAPH_CHECK(igraph_vector_resize(&ch->index, ch->dnodes)); j=0; for (i=0; ihptr)[i] != UNDEFINED) { VECTOR(ch->index)[j]=i; VECTOR(ch->hptr)[i]=j+INDEXINC; j++; } } return 0; } /* -------------------------------------------------- */ /* Two-way indexed heap */ /* -------------------------------------------------- */ #undef PARENT #undef LEFTCHILD #undef RIGHTCHILD #define PARENT(x) (((x)+1)/2-1) #define LEFTCHILD(x) (((x)+1)*2-1) #define RIGHTCHILD(x) (((x)+1)*2) /* This is a smart indexed heap. In addition to the "normal" indexed heap it allows to access every element through its index in O(1) time. In other words, for this heap the indexing operation is O(1), the normal heap does this in O(n) time.... */ void igraph_i_2wheap_switch(igraph_2wheap_t *h, long int e1, long int e2) { if (e1 != e2) { long int tmp1, tmp2; igraph_real_t tmp3=VECTOR(h->data)[e1]; VECTOR(h->data)[e1]=VECTOR(h->data)[e2]; VECTOR(h->data)[e2]=tmp3; tmp1=VECTOR(h->index)[e1]; tmp2=VECTOR(h->index)[e2]; VECTOR(h->index2)[tmp1]=e2+2; VECTOR(h->index2)[tmp2]=e1+2; VECTOR(h->index)[e1]=tmp2; VECTOR(h->index)[e2]=tmp1; } } void igraph_i_2wheap_shift_up(igraph_2wheap_t *h, long int elem) { if (elem==0 || VECTOR(h->data)[elem] < VECTOR(h->data)[PARENT(elem)]) { /* at the top */ } else { igraph_i_2wheap_switch(h, elem, PARENT(elem)); igraph_i_2wheap_shift_up(h, PARENT(elem)); } } void igraph_i_2wheap_sink(igraph_2wheap_t *h, long int head) { long int size=igraph_2wheap_size(h); if (LEFTCHILD(head) >= size) { /* no subtrees */ } else if (RIGHTCHILD(head) == size || VECTOR(h->data)[LEFTCHILD(head)]>=VECTOR(h->data)[RIGHTCHILD(head)]) { /* sink to the left if needed */ if (VECTOR(h->data)[head] < VECTOR(h->data)[LEFTCHILD(head)]) { igraph_i_2wheap_switch(h, head, LEFTCHILD(head)); igraph_i_2wheap_sink(h, LEFTCHILD(head)); } } else { /* sink to the right */ if (VECTOR(h->data)[head] < VECTOR(h->data)[RIGHTCHILD(head)]) { igraph_i_2wheap_switch(h, head, RIGHTCHILD(head)); igraph_i_2wheap_sink(h, RIGHTCHILD(head)); } } } /* ------------------ */ /* These are public */ /* ------------------ */ int igraph_2wheap_init(igraph_2wheap_t *h, long int size) { h->size=size; /* We start with the biggest */ IGRAPH_CHECK(igraph_vector_long_init(&h->index2, size)); IGRAPH_FINALLY(igraph_vector_long_destroy, &h->index2); IGRAPH_VECTOR_INIT_FINALLY(&h->data, 0); IGRAPH_CHECK(igraph_vector_long_init(&h->index, 0)); /* IGRAPH_FINALLY(igraph_vector_long_destroy, &h->index); */ IGRAPH_FINALLY_CLEAN(2); return 0; } void igraph_2wheap_destroy(igraph_2wheap_t *h) { igraph_vector_destroy(&h->data); igraph_vector_long_destroy(&h->index); igraph_vector_long_destroy(&h->index2); } int igraph_2wheap_clear(igraph_2wheap_t *h) { igraph_vector_clear(&h->data); igraph_vector_long_clear(&h->index); igraph_vector_long_null(&h->index2); return 0; } igraph_bool_t igraph_2wheap_empty(const igraph_2wheap_t *h) { return igraph_vector_empty(&h->data); } int igraph_2wheap_push_with_index(igraph_2wheap_t *h, long int idx, igraph_real_t elem) { /* printf("-> %.2g [%li]\n", elem, idx); */ long int size=igraph_vector_size(&h->data); IGRAPH_CHECK(igraph_vector_push_back(&h->data, elem)); IGRAPH_CHECK(igraph_vector_long_push_back(&h->index, idx)); VECTOR(h->index2)[idx] = size+2; /* maintain heap */ igraph_i_2wheap_shift_up(h, size); return 0; } long int igraph_2wheap_size(const igraph_2wheap_t *h) { return igraph_vector_size(&h->data); } long int igraph_2wheap_max_size(const igraph_2wheap_t *h) { return h->size; } igraph_real_t igraph_2wheap_max(const igraph_2wheap_t *h) { return VECTOR(h->data)[0]; } long int igraph_2wheap_max_index(const igraph_2wheap_t *h) { return VECTOR(h->index)[0]; } igraph_bool_t igraph_2wheap_has_elem(const igraph_2wheap_t *h, long int idx) { return VECTOR(h->index2)[idx] != 0; } igraph_bool_t igraph_2wheap_has_active(const igraph_2wheap_t *h, long int idx) { return VECTOR(h->index2)[idx] > 1; } igraph_real_t igraph_2wheap_get(const igraph_2wheap_t *h, long int idx) { long int i=VECTOR(h->index2)[idx]-2; return VECTOR(h->data)[i]; } igraph_real_t igraph_2wheap_delete_max(igraph_2wheap_t *h) { igraph_real_t tmp=VECTOR(h->data)[0]; long int tmpidx=VECTOR(h->index)[0]; igraph_i_2wheap_switch(h, 0, igraph_2wheap_size(h)-1); igraph_vector_pop_back(&h->data); igraph_vector_long_pop_back(&h->index); VECTOR(h->index2)[tmpidx] = 0; igraph_i_2wheap_sink(h, 0); /* printf("<-max %.2g\n", tmp); */ return tmp; } igraph_real_t igraph_2wheap_deactivate_max(igraph_2wheap_t *h) { igraph_real_t tmp=VECTOR(h->data)[0]; long int tmpidx=VECTOR(h->index)[0]; igraph_i_2wheap_switch(h, 0, igraph_2wheap_size(h)-1); igraph_vector_pop_back(&h->data); igraph_vector_long_pop_back(&h->index); VECTOR(h->index2)[tmpidx] = 1; igraph_i_2wheap_sink(h, 0); return tmp; } igraph_real_t igraph_2wheap_delete_max_index(igraph_2wheap_t *h, long int *idx) { igraph_real_t tmp=VECTOR(h->data)[0]; long int tmpidx=VECTOR(h->index)[0]; igraph_i_2wheap_switch(h, 0, igraph_2wheap_size(h)-1); igraph_vector_pop_back(&h->data); igraph_vector_long_pop_back(&h->index); VECTOR(h->index2)[tmpidx] = 0; igraph_i_2wheap_sink(h, 0); if (idx) { *idx=tmpidx; } return tmp; } int igraph_2wheap_modify(igraph_2wheap_t *h, long int idx, igraph_real_t elem) { long int pos=VECTOR(h->index2)[idx]-2; /* printf("-- %.2g -> %.2g\n", VECTOR(h->data)[pos], elem); */ VECTOR(h->data)[pos] = elem; igraph_i_2wheap_sink(h, pos); igraph_i_2wheap_shift_up(h, pos); return 0; } /* Check that the heap is in a consistent state */ int igraph_2wheap_check(igraph_2wheap_t *h) { long int size=igraph_2wheap_size(h); long int i; igraph_bool_t error=0; /* Check the heap property */ for (i=0; i= size) { break; } if (VECTOR(h->data)[LEFTCHILD(i)] > VECTOR(h->data)[i]) { error=1; break; } if (RIGHTCHILD(i) >= size) { break; } if (VECTOR(h->data)[RIGHTCHILD(i)] > VECTOR(h->data)[i]) { error=1; break; } } if (error) { IGRAPH_ERROR("Inconsistent heap", IGRAPH_EINTERNAL); } return 0; } igraph/src/vector.c0000644000175100001440000002672413431000472014004 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_complex.h" #include "bigint.h" #include "config.h" #include #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_FLOAT #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_FLOAT #define BASE_LONG #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_INT #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_COMPLEX #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_COMPLEX #define BASE_LIMB #include "igraph_pmt.h" #include "vector.pmt" #include "igraph_pmt_off.h" #undef BASE_LIMB #include "igraph_math.h" int igraph_vector_floor(const igraph_vector_t *from, igraph_vector_long_t *to) { long int i, n=igraph_vector_size(from); IGRAPH_CHECK(igraph_vector_long_resize(to, n)); for (i=0; i * The smallest element will have order zero, the second smallest * order one, etc. * \param v The original \type igraph_vector_t object. * \param v2 A secondary key, another \type igraph_vector_t object. * \param res An initialized \type igraph_vector_t object, it will be * resized to match the size of \p v. The * result of the computation will be stored here. * \param nodes Hint, the largest element in \p v. * \return Error code: * \c IGRAPH_ENOMEM: out of memory * * Time complexity: O() */ int igraph_vector_order(const igraph_vector_t* v, const igraph_vector_t *v2, igraph_vector_t* res, igraph_real_t nodes) { long int edges=igraph_vector_size(v); igraph_vector_t ptr; igraph_vector_t rad; long int i, j; assert(v!=NULL); assert(v->stor_begin != NULL); IGRAPH_VECTOR_INIT_FINALLY(&ptr, (long int) nodes+1); IGRAPH_VECTOR_INIT_FINALLY(&rad, edges); IGRAPH_CHECK(igraph_vector_resize(res, edges)); for (i=0; istor_begin[i]; if (VECTOR(ptr)[radix]!=0) { VECTOR(rad)[i]=VECTOR(ptr)[radix]; } VECTOR(ptr)[radix]=i+1; } j=0; for (i=0; istor_begin[j++]=next; while (VECTOR(rad)[next] != 0) { next=(long int) VECTOR(rad)[next]-1; res->stor_begin[j++]=next; } } } igraph_vector_null(&ptr); igraph_vector_null(&rad); for (i=0; istor_begin[j++]=next; while (VECTOR(rad)[next] != 0) { next=(long int) VECTOR(rad)[next]-1; res->stor_begin[j++]=next; } } } igraph_vector_destroy(&ptr); igraph_vector_destroy(&rad); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_vector_order1(const igraph_vector_t* v, igraph_vector_t* res, igraph_real_t nodes) { long int edges=igraph_vector_size(v); igraph_vector_t ptr; igraph_vector_t rad; long int i, j; assert(v!=NULL); assert(v->stor_begin != NULL); IGRAPH_VECTOR_INIT_FINALLY(&ptr, (long int) nodes+1); IGRAPH_VECTOR_INIT_FINALLY(&rad, edges); IGRAPH_CHECK(igraph_vector_resize(res, edges)); for (i=0; istor_begin[i]; if (VECTOR(ptr)[radix]!=0) { VECTOR(rad)[i]=VECTOR(ptr)[radix]; } VECTOR(ptr)[radix]=i+1; } j=0; for (i=0; istor_begin[j++]=next; while (VECTOR(rad)[next] != 0) { next=(long int) VECTOR(rad)[next]-1; res->stor_begin[j++]=next; } } } igraph_vector_destroy(&ptr); igraph_vector_destroy(&rad); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_vector_order1_int(const igraph_vector_t* v, igraph_vector_int_t* res, igraph_real_t nodes) { long int edges=igraph_vector_size(v); igraph_vector_t ptr; igraph_vector_t rad; long int i, j; assert(v!=NULL); assert(v->stor_begin != NULL); IGRAPH_VECTOR_INIT_FINALLY(&ptr, (long int) nodes+1); IGRAPH_VECTOR_INIT_FINALLY(&rad, edges); IGRAPH_CHECK(igraph_vector_int_resize(res, edges)); for (i=0; istor_begin[i]; if (VECTOR(ptr)[radix]!=0) { VECTOR(rad)[i]=VECTOR(ptr)[radix]; } VECTOR(ptr)[radix]=i+1; } j=0; for (i=0; istor_begin[j++]=next; while (VECTOR(rad)[next] != 0) { next=(long int) VECTOR(rad)[next]-1; res->stor_begin[j++]=next; } } } igraph_vector_destroy(&ptr); igraph_vector_destroy(&rad); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_vector_rank(const igraph_vector_t *v, igraph_vector_t *res, long int nodes) { igraph_vector_t rad; igraph_vector_t ptr; long int edges = igraph_vector_size(v); long int i, c=0; IGRAPH_VECTOR_INIT_FINALLY(&rad, nodes); IGRAPH_VECTOR_INIT_FINALLY(&ptr, edges); IGRAPH_CHECK(igraph_vector_resize(res, edges)); for (i=0; istor_begin != 0); assert(rhs->stor_begin != 0); s=igraph_vector_size(lhs); if (s != igraph_vector_size(rhs)) { return 0; } else { if (tol==0) { tol=DBL_EPSILON; } for (i=0; i r+tol) { return 0; } } return 1; } } int igraph_vector_zapsmall(igraph_vector_t *v, igraph_real_t tol) { int i, n=igraph_vector_size(v); if (tol < 0.0) { IGRAPH_ERROR("`tol' tolerance must be non-negative", IGRAPH_EINVAL); } if (tol == 0.0) { tol = sqrt(DBL_EPSILON); } for (i = 0; i < n; i++) { igraph_real_t val=VECTOR(*v)[i]; if (val < tol && val > -tol) { VECTOR(*v)[i] = 0.0; } } return 0; } igraph/src/scg_utils.c0000644000175100001440000000556213431000472014473 0ustar hornikusers/* * SCGlib : A C library for the spectral coarse graining of matrices * as described in the paper: Shrinking Matrices while preserving their * eigenpairs with Application to the Spectral Coarse Graining of Graphs. * Preprint available at * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * This files contains the data structures and error handing * functions used throughout the SCGlib. */ #include "igraph_error.h" #include "igraph_memory.h" #include "scg_headers.h" /*to be used with qsort and struct ind_val arrays */ int igraph_i_compare_ind_val(const void *a, const void *b) { igraph_i_scg_indval_t *arg1 = (igraph_i_scg_indval_t *) a; igraph_i_scg_indval_t *arg2 = (igraph_i_scg_indval_t *) b; if ( arg1->val < arg2->val ) { return -1; } else if ( arg1->val == arg2->val ) { return 0; } else { return 1; } } /*to be used with qsort and struct groups*/ int igraph_i_compare_groups(const void *a, const void *b) { igraph_i_scg_groups_t *arg1 = (igraph_i_scg_groups_t *) a; igraph_i_scg_groups_t *arg2 = (igraph_i_scg_groups_t *) b; int i; for (i=0; in; i++) { if (arg1->gr[i]>arg2->gr[i]) return 1; else if (arg1->gr[i]gr[i]) return -1; } return 0; } /*to be used with qsort and real_vectors */ int igraph_i_compare_real(const void *a, const void *b) { igraph_real_t arg1 = * (igraph_real_t *) a; igraph_real_t arg2 = * (igraph_real_t *) b; if (arg1 < arg2) { return -1; } else if (arg1 == arg2) { return 0; } else { return 1; } } /*to be used with qsort and integer vectors */ int igraph_i_compare_int(const void *a, const void *b) { int arg1 = * (int *) a; int arg2 = * (int *) b; return (arg1 -arg2); } /* allocate a igraph_real_t symmetrix matrix with dimension size x size in vector format*/ igraph_real_t *igraph_i_real_sym_matrix(const int size) { igraph_real_t *S = igraph_Calloc(size*(size+1)/2, igraph_real_t); if (!S) { igraph_error("allocation failure in real_sym_matrix()", __FILE__, __LINE__, IGRAPH_ENOMEM); } return S; } igraph/src/community.c0000644000175100001440000035733213431000472014530 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_community.h" #include "igraph_constructors.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_arpack.h" #include "igraph_arpack_internal.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "igraph_components.h" #include "igraph_dqueue.h" #include "igraph_progress.h" #include "igraph_stack.h" #include "igraph_spmatrix.h" #include "igraph_statusbar.h" #include "igraph_types_internal.h" #include "igraph_conversion.h" #include "igraph_centrality.h" #include "config.h" #include #include #ifdef USING_R #include #endif int igraph_i_rewrite_membership_vector(igraph_vector_t *membership) { long int no=(long int) igraph_vector_max(membership)+1; igraph_vector_t idx; long int realno=0; long int i; long int len=igraph_vector_size(membership); IGRAPH_VECTOR_INIT_FINALLY(&idx, no); for (i=0; i=0; i--) { long int edge=(long int) VECTOR(*edges)[i]; long int from=IGRAPH_FROM(graph, edge); long int to=IGRAPH_TO(graph, edge); long int c1=(long int) VECTOR(mymembership)[from]; long int c2=(long int) VECTOR(mymembership)[to]; igraph_real_t actmod; long int j; if (c1 != c2) { /* this is a merge */ if (res) { MATRIX(*res, midx, 0)=c1; MATRIX(*res, midx, 1)=c2; } if (bridges) { VECTOR(*bridges)[midx]=i+1; } /* The new cluster has id no_of_nodes+midx+1 */ for (j=0; j maxmod) { maxmod=actmod; if (membership) { igraph_vector_update(membership, &mymembership); } } } midx++; } } if (membership) { IGRAPH_CHECK(igraph_i_rewrite_membership_vector(membership)); } igraph_vector_destroy(&mymembership); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_community_eb_get_merges * \brief Calculating the merges, ie. the dendrogram for an edge betweenness community structure * * * This function is handy if you have a sequence of edge which are * gradually removed from the network and you would like to know how * the network falls apart into separate components. The edge sequence * may come from the \ref igraph_community_edge_betweenness() * function, but this is not necessary. Note that \ref * igraph_community_edge_betweenness can also calculate the * dendrogram, via its \p merges argument. * * \param graph The input graph. * \param edges Vector containing the edges to be removed from the * network, all edges are expected to appear exactly once in the * vector. * \param weights An optional vector containing edge weights. If null, * the unweighted modularity scores will be calculated. If not null, * the weighted modularity scores will be calculated. Ignored if both * \p modularity and \p membership are nulls. * \param res Pointer to an initialized matrix, if not NULL then the * dendrogram will be stored here, in the same form as for the \ref * igraph_community_walktrap() function: the matrix has two columns * and each line is a merge given by the ids of the merged * components. The component ids are number from zero and * component ids smaller than the number of vertices in the graph * belong to individual vertices. The non-trivial components * containing at least two vertices are numbered from \c n, \c n is * the number of vertices in the graph. So if the first line * contains \c a and \c b that means that components \c a and \c b * are merged into component \c n, the second line creates * component \c n+1, etc. The matrix will be resized as needed. * \param bridges Pointer to an initialized vector or NULL. If not * null then the index of the edge removals which split the network * will be stored here. The vector will be resized as needed. * \param modularity If not a null pointer, then the modularity values * for the different divisions, corresponding to the merges matrix, * will be stored here. * \param membership If not a null pointer, then the membership vector * for the best division (in terms of modularity) will be stored * here. * \return Error code. * * \sa \ref igraph_community_edge_betweenness(). * * Time complexity: O(|E|+|V|log|V|), |V| is the number of vertices, * |E| is the number of edges. */ int igraph_community_eb_get_merges(const igraph_t *graph, const igraph_vector_t *edges, const igraph_vector_t *weights, igraph_matrix_t *res, igraph_vector_t *bridges, igraph_vector_t *modularity, igraph_vector_t *membership) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t ptr; long int i, midx=0; igraph_integer_t no_comps; if (membership || modularity) { return igraph_i_community_eb_get_merges2(graph, edges, weights, res, bridges, modularity, membership); } IGRAPH_CHECK(igraph_clusters(graph, 0, 0, &no_comps, IGRAPH_WEAK)); IGRAPH_VECTOR_INIT_FINALLY(&ptr, no_of_nodes*2-1); if (res) { IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes-no_comps, 2)); } if (bridges) { IGRAPH_CHECK(igraph_vector_resize(bridges, no_of_nodes-no_comps)); } for (i=igraph_vector_size(edges)-1; i>=0; i--) { igraph_integer_t edge=(igraph_integer_t) VECTOR(*edges)[i]; igraph_integer_t from, to, c1, c2, idx; igraph_edge(graph, edge, &from, &to); idx=from+1; while (VECTOR(ptr)[idx-1] != 0) { idx=(igraph_integer_t) VECTOR(ptr)[idx-1]; } c1=idx-1; idx=to+1; while (VECTOR(ptr)[idx-1] != 0) { idx=(igraph_integer_t) VECTOR(ptr)[idx-1]; } c2=idx-1; if (c1 != c2) { /* this is a merge */ if (res) { MATRIX(*res, midx, 0)=c1; MATRIX(*res, midx, 1)=c2; } if (bridges) { VECTOR(*bridges)[midx]=i+1; } VECTOR(ptr)[c1]=no_of_nodes+midx+1; VECTOR(ptr)[c2]=no_of_nodes+midx+1; VECTOR(ptr)[from]=no_of_nodes+midx+1; VECTOR(ptr)[to]=no_of_nodes+midx+1; midx++; } } igraph_vector_destroy(&ptr); IGRAPH_FINALLY_CLEAN(1); return 0; } /* Find the smallest active element in the vector */ long int igraph_i_vector_which_max_not_null(const igraph_vector_t *v, const char *passive) { long int which, i=0, size=igraph_vector_size(v); igraph_real_t max; while (passive[i]) { i++; } which=i; max=VECTOR(*v)[which]; for (i++; i max) { max=elem; which=i; } } return which; } /** * \function igraph_community_edge_betweenness * \brief Community finding based on edge betweenness * * Community structure detection based on the betweenness of the edges * in the network. The algorithm was invented by M. Girvan and * M. Newman, see: M. Girvan and M. E. J. Newman: Community structure in * social and biological networks, Proc. Nat. Acad. Sci. USA 99, 7821-7826 * (2002). * * * The idea is that the betweenness of the edges connecting two * communities is typically high, as many of the shortest paths * between nodes in separate communities go through them. So we * gradually remove the edge with highest betweenness from the * network, and recalculate edge betweenness after every removal. * This way sooner or later the network falls off to two components, * then after a while one of these components falls off to two smaller * components, etc. until all edges are removed. This is a divisive * hierarchical approach, the result is a dendrogram. * \param graph The input graph. * \param result Pointer to an initialized vector, the result will be * stored here, the ids of the removed edges in the order of their * removal. It will be resized as needed. It may be NULL if * the edge IDs are not needed by the caller. * \param edge_betweenness Pointer to an initialized vector or * NULL. In the former case the edge betweenness of the removed * edge is stored here. The vector will be resized as needed. * \param merges Pointer to an initialized matrix or NULL. If not NULL * then merges performed by the algorithm are stored here. Even if * this is a divisive algorithm, we can replay it backwards and * note which two clusters were merged. Clusters are numbered from * zero, see the \p merges argument of \ref * igraph_community_walktrap() for details. The matrix will be * resized as needed. * \param bridges Pointer to an initialized vector of NULL. If not * NULL then all edge removals which separated the network into * more components are marked here. * \param modularity If not a null pointer, then the modularity values * of the different divisions are stored here, in the order * corresponding to the merge matrix. The modularity values will * take weights into account if \p weights is not null. * \param membership If not a null pointer, then the membership vector, * corresponding to the highest modularity value, is stored here. * \param directed Logical constant, whether to calculate directed * betweenness (ie. directed paths) for directed graphs. It is * ignored for undirected graphs. * \param weights An optional vector containing edge weights. If null, * the unweighted edge betweenness scores will be calculated and * used. If not null, the weighted edge betweenness scores will be * calculated and used. * \return Error code. * * \sa \ref igraph_community_eb_get_merges(), \ref * igraph_community_spinglass(), \ref igraph_community_walktrap(). * * Time complexity: O(|V||E|^2), as the betweenness calculation requires * O(|V||E|) and we do it |E|-1 times. * * \example examples/simple/igraph_community_edge_betweenness.c */ int igraph_community_edge_betweenness(const igraph_t *graph, igraph_vector_t *result, igraph_vector_t *edge_betweenness, igraph_matrix_t *merges, igraph_vector_t *bridges, igraph_vector_t *modularity, igraph_vector_t *membership, igraph_bool_t directed, const igraph_vector_t *weights) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); double *distance, *tmpscore; unsigned long long int *nrgeo; long int source, i, e; igraph_inclist_t elist_out, elist_in, fathers; igraph_inclist_t *elist_out_p, *elist_in_p; igraph_vector_int_t *neip; long int neino; igraph_vector_t eb; long int maxedge, pos; igraph_integer_t from, to; igraph_bool_t result_owned = 0; igraph_stack_t stack=IGRAPH_STACK_NULL; igraph_real_t steps, steps_done; char *passive; /* Needed only for the unweighted case */ igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; /* Needed only for the weighted case */ igraph_2wheap_t heap; if (result == 0) { result = igraph_Calloc(1, igraph_vector_t); if (result == 0) IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, result); IGRAPH_VECTOR_INIT_FINALLY(result, 0); result_owned = 1; } directed=directed && igraph_is_directed(graph); if (directed) { IGRAPH_CHECK(igraph_inclist_init(graph, &elist_out, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out); IGRAPH_CHECK(igraph_inclist_init(graph, &elist_in, IGRAPH_IN)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_in); elist_out_p=&elist_out; elist_in_p=&elist_in; } else { IGRAPH_CHECK(igraph_inclist_init(graph, &elist_out, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out); elist_out_p=elist_in_p=&elist_out; } distance=igraph_Calloc(no_of_nodes, double); if (distance==0) { IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, distance); nrgeo=igraph_Calloc(no_of_nodes, unsigned long long int); if (nrgeo==0) { IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, nrgeo); tmpscore=igraph_Calloc(no_of_nodes, double); if (tmpscore==0) { IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, tmpscore); if (weights == 0) { IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); } else { if (igraph_vector_min(weights) <= 0) { IGRAPH_ERROR("weights must be strictly positive", IGRAPH_EINVAL); } if (membership != 0) { IGRAPH_WARNING("Membership vector will be selected based on the lowest "\ "modularity score."); } if (modularity != 0 || membership != 0) { IGRAPH_WARNING("Modularity calculation with weighted edge betweenness "\ "community detection might not make sense -- modularity treats edge "\ "weights as similarities while edge betwenness treats them as "\ "distances"); } IGRAPH_CHECK(igraph_2wheap_init(&heap, no_of_nodes)); IGRAPH_FINALLY(igraph_2wheap_destroy, &heap); IGRAPH_CHECK(igraph_inclist_init_empty(&fathers, (igraph_integer_t) no_of_nodes)); IGRAPH_FINALLY(igraph_inclist_destroy, &fathers); } IGRAPH_CHECK(igraph_stack_init(&stack, no_of_nodes)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_CHECK(igraph_vector_resize(result, no_of_edges)); if (edge_betweenness) { IGRAPH_CHECK(igraph_vector_resize(edge_betweenness, no_of_edges)); VECTOR(*edge_betweenness)[no_of_edges-1]=0; } IGRAPH_VECTOR_INIT_FINALLY(&eb, no_of_edges); passive=igraph_Calloc(no_of_edges, char); if (!passive) { IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, passive); /* Estimate the number of steps to be taken. * It is assumed that one iteration is O(|E||V|), but |V| is constant * anyway, so we will have approximately |E|^2 / 2 steps, and one * iteration of the outer loop advances the step counter by the number * of remaining edges at that iteration. */ steps = no_of_edges / 2.0 * (no_of_edges+1); steps_done = 0; for (e=0; e * Many community detection algorithms return with a \em merges * matrix, \ref igraph_community_walktrap() and \ref * igraph_community_edge_betweenness() are two examples. The matrix * contains the merge operations performed while mapping the * hierarchical structure of a network. If the matrix has \c n-1 rows, * where \c n is the number of vertices in the graph, then it contains * the hierarchical structure of the whole network and it is called a * dendrogram. * * * This function performs \p steps merge operations as prescribed by * the \p merges matrix and returns the current state of the network. * * * If \p merges is not a complete dendrogram, it is possible to * take \p steps steps if \p steps is not bigger than the number * lines in \p merges. * \param merges The two-column matrix containing the merge * operations. See \ref igraph_community_walktrap() for the * detailed syntax. * \param nodes The number of leaf nodes in the dendrogram * \param steps Integer constant, the number of steps to take. * \param membership Pointer to an initialized vector, the membership * results will be stored here, if not NULL. The vector will be * resized as needed. * \param csize Pointer to an initialized vector, or NULL. If not NULL * then the sizes of the components will be stored here, the vector * will be resized as needed. * * \sa \ref igraph_community_walktrap(), \ref * igraph_community_edge_betweenness(), \ref * igraph_community_fastgreedy() for community structure detection * algorithms. * * Time complexity: O(|V|), the number of vertices in the graph. */ int igraph_community_to_membership(const igraph_matrix_t *merges, igraph_integer_t nodes, igraph_integer_t steps, igraph_vector_t *membership, igraph_vector_t *csize) { long int no_of_nodes=nodes; long int components=no_of_nodes-steps; long int i, found=0; igraph_vector_t tmp; if (steps > igraph_matrix_nrow(merges)) { IGRAPH_ERROR("`steps' to big or `merges' matrix too short", IGRAPH_EINVAL); } if (membership) { IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); igraph_vector_null(membership); } if (csize) { IGRAPH_CHECK(igraph_vector_resize(csize, components)); igraph_vector_null(csize); } IGRAPH_VECTOR_INIT_FINALLY(&tmp, steps); for (i=steps-1; i>=0; i--) { long int c1=(long int) MATRIX(*merges, i, 0); long int c2=(long int) MATRIX(*merges, i, 1); /* new component? */ if (VECTOR(tmp)[i]==0) { found++; VECTOR(tmp)[i]=found; } if (c1 * Modularity on weighted graphs is also meaningful. When taking edge * weights into account, `Aij' becomes the weight of the corresponding * edge (or 0 if there is no edge), `ki' is the total weight of edges * incident on vertex `i', `kj' is the total weight of edges incident * on vertex `j' and `m' is the total weight of all edges. * * * See also Clauset, A.; Newman, M. E. J.; Moore, C. Finding * community structure in very large networks, Physical Review E, * 2004, 70, 066111. * \param graph The input graph. It must be undirected; directed graphs are * not supported yet. * \param membership Numeric vector which gives the type of each * vertex, ie. the component to which it belongs. * It does not have to be consecutive, i.e. empty communities are * allowed. * \param modularity Pointer to a real number, the result will be * stored here. * \param weights Weight vector or NULL if no weights are specified. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. */ int igraph_modularity(const igraph_t *graph, const igraph_vector_t *membership, igraph_real_t *modularity, const igraph_vector_t *weights) { igraph_vector_t e, a; long int types=(long int) igraph_vector_max(membership)+1; long int no_of_edges=igraph_ecount(graph); long int i; igraph_integer_t from, to; igraph_real_t m; long int c1, c2; if (igraph_is_directed(graph)) { #ifndef USING_R IGRAPH_ERROR("modularity is implemented for undirected graphs", IGRAPH_EINVAL); #else REprintf("Modularity is implemented for undirected graphs only.\n"); #endif } if (igraph_vector_size(membership) < igraph_vcount(graph)) { IGRAPH_ERROR("cannot calculate modularity, membership vector too short", IGRAPH_EINVAL); } if (igraph_vector_min(membership) < 0) { IGRAPH_ERROR("Invalid membership vector", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&e, types); IGRAPH_VECTOR_INIT_FINALLY(&a, types); if (weights) { if (igraph_vector_size(weights) < no_of_edges) IGRAPH_ERROR("cannot calculate modularity, weight vector too short", IGRAPH_EINVAL); m=igraph_vector_sum(weights); for (i=0; i 0) { for (i=0; i * The function documented in these section implements the * leading eigenvector method developed by Mark Newman and * published in MEJ Newman: Finding community structure using the * eigenvectors of matrices, Phys Rev E 74:036104 (2006). * * * The heart of the method is the definition of the modularity matrix, * B, which is B=A-P, A being the adjacency matrix of the (undirected) * network, and P contains the probability that certain edges are * present according to the configuration model In * other words, a Pij element of P is the probability that there is an * edge between vertices i and j in a random network in which the * degrees of all vertices are the same as in the input graph. * * * The leading eigenvector method works by calculating the eigenvector * of the modularity matrix for the largest positive eigenvalue and * then separating vertices into two community based on the sign of * the corresponding element in the eigenvector. If all elements in * the eigenvector are of the same sign that means that the network * has no underlying community structure. * Check Newman's paper to understand why this is a good method for * detecting community structure. * * * The leading eigenvector community structure detection method is * implemented in \ref igraph_community_leading_eigenvector(). * After the initial split, the following splits are done in a * way to optimize modularity regarding to the original network. * * * * \example examples/simple/igraph_community_leading_eigenvector.c * */ typedef struct igraph_i_community_leading_eigenvector_data_t { igraph_vector_t *idx; igraph_vector_t *idx2; igraph_adjlist_t *adjlist; igraph_inclist_t *inclist; igraph_vector_t *tmp; long int no_of_edges; igraph_vector_t *mymembership; long int comm; const igraph_vector_t *weights; const igraph_t *graph; igraph_vector_t *strength; igraph_real_t sumweights; } igraph_i_community_leading_eigenvector_data_t; int igraph_i_community_leading_eigenvector(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_community_leading_eigenvector_data_t *data=extra; long int j, k, nlen, size=n; igraph_vector_t *idx=data->idx; igraph_vector_t *idx2=data->idx2; igraph_vector_t *tmp=data->tmp; igraph_adjlist_t *adjlist=data->adjlist; igraph_real_t ktx, ktx2; long int no_of_edges=data->no_of_edges; igraph_vector_t *mymembership=data->mymembership; long int comm=data->comm; /* Ax */ for (j=0; jidx; igraph_vector_t *idx2=data->idx2; igraph_vector_t *tmp=data->tmp; igraph_adjlist_t *adjlist=data->adjlist; igraph_real_t ktx, ktx2; long int no_of_edges=data->no_of_edges; igraph_vector_t *mymembership=data->mymembership; long int comm=data->comm; /* Ax */ for (j=0; jidx; igraph_vector_t *idx2=data->idx2; igraph_vector_t *tmp=data->tmp; igraph_inclist_t *inclist=data->inclist; igraph_real_t ktx, ktx2; igraph_vector_t *mymembership=data->mymembership; long int comm=data->comm; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *strength=data->strength; igraph_real_t sw=data->sumweights; /* Ax */ for (j=0; jidx; igraph_vector_t *idx2=data->idx2; igraph_vector_t *tmp=data->tmp; igraph_inclist_t *inclist=data->inclist; igraph_real_t ktx, ktx2; igraph_vector_t *mymembership=data->mymembership; long int comm=data->comm; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *strength=data->strength; igraph_real_t sw=data->sumweights; /* Ax */ for (j=0; jp communities, * then these are numbered from zero to p-1. The * first line of the matrix contains the first merge * (which is in reality the last split) of two communities into * community p, the merge in the second line forms * community p+1, etc. The matrix should be * initialized before calling and will be resized as needed. * This argument is ignored of it is \c NULL. * \param membership The membership of the vertices after all the * splits were performed will be stored here. The vector must be * initialized before calling and will be resized as needed. * This argument is ignored if it is \c NULL. This argument can * also be used to supply a starting configuration for the community * finding, in the format of a membership vector. In this case the * \p start argument must be set to 1. * \param steps The maximum number of steps to perform. It might * happen that some component (or the whole network) has no * underlying community structure and no further steps can be * done. If you want as many steps as possible then supply the * number of vertices in the network here. * \param options The options for ARPACK. \c n is always * overwritten. \c ncv is set to at least 4. * \param modularity If not a null pointer, then it must be a pointer * to a real number and the modularity score of the final division * is stored here. * \param start Boolean, whether to use the community structure given * in the \p membership argument as a starting point. * \param eigenvalues Pointer to an initialized vector or a null * pointer. If not a null pointer, then the eigenvalues calculated * along the community structure detection are stored here. The * non-positive eigenvalues, that do not result a split, are stored * as well. * \param eigenvectors If not a null pointer, then the eigenvectors * that are calculated in each step of the algorithm, are stored here, * in a pointer vector. Each eigenvector is stored in an * \ref igraph_vector_t object. The user is responsible of * deallocating the memory that belongs to the individual vectors, * by calling first \ref igraph_vector_destroy(), and then * free() on them. * \param history Pointer to an initialized vector or a null pointer. * If not a null pointer, then a trace of the algorithm is stored * here, encoded numerically. The various operations: * \clist * \cli IGRAPH_LEVC_HIST_START_FULL * Start the algorithm from an initial state where each connected * component is a separate community. * \cli IGRAPH_LEVC_HIST_START_GIVEN * Start the algorithm from a given community structure. The next * value in the vector contains the initial number of * communities. * \cli IGRAPH_LEVC_HIST_SPLIT * Split a community into two communities. The id of the splitted * community is given in the next element of the history vector. * The id of the first new community is the same as the id of the * splitted community. The id of the second community equals to * the number of communities before the split. * \cli IGRAPH_LEVC_HIST_FAILED * Tried to split a community, but it was not worth it, as it * does not result in a bigger modularity value. The id of the * community is given in the next element of the vector. * \endclist * \param callback A null pointer or a function of type \ref * igraph_community_leading_eigenvector_callback_t. If given, this * callback function is called after each eigenvector/eigenvalue * calculation. If the callback returns a non-zero value, then the * community finding algorithm stops. See the arguments passed to * the callback at the documentation of \ref * igraph_community_leading_eigenvector_callback_t. * \param callback_extra Extra argument to pass to the callback * function. * \return Error code. * * \sa \ref igraph_community_walktrap() and \ref * igraph_community_spinglass() for other community structure * detection methods. * * Time complexity: O(|E|+|V|^2*steps), |V| is the number of vertices, * |E| the number of edges, steps the number of splits * performed. */ int igraph_community_leading_eigenvector(const igraph_t *graph, const igraph_vector_t *weights, igraph_matrix_t *merges, igraph_vector_t *membership, igraph_integer_t steps, igraph_arpack_options_t *options, igraph_real_t *modularity, igraph_bool_t start, igraph_vector_t *eigenvalues, igraph_vector_ptr_t *eigenvectors, igraph_vector_t *history, igraph_community_leading_eigenvector_callback_t *callback, void *callback_extra) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_dqueue_t tosplit; igraph_vector_t idx, idx2, mymerges; igraph_vector_t strength, tmp; long int staken=0; igraph_adjlist_t adjlist; igraph_inclist_t inclist; long int i, j, k, l; long int communities; igraph_vector_t vmembership, *mymembership=membership; igraph_i_community_leading_eigenvector_data_t extra; igraph_arpack_storage_t storage; igraph_real_t mod=0; igraph_arpack_function_t *arpcb1 = weights ? igraph_i_community_leading_eigenvector_weighted : igraph_i_community_leading_eigenvector; igraph_arpack_function_t *arpcb2 = weights ? igraph_i_community_leading_eigenvector2_weighted : igraph_i_community_leading_eigenvector2; igraph_real_t sumweights=0.0; if (weights && no_of_edges != igraph_vector_size(weights)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (start && !membership) { IGRAPH_ERROR("Cannot start from given configuration if memberships " "missing", IGRAPH_EINVAL); } if (start && membership && igraph_vector_size(membership) != no_of_nodes) { IGRAPH_ERROR("Wrong length for vector of predefined memberships", IGRAPH_EINVAL); } if (start && membership && igraph_vector_max(membership) >= no_of_nodes) { IGRAPH_WARNING("Too many communities in membership start vector"); } if (igraph_is_directed(graph)) { IGRAPH_WARNING("This method was developed for undirected graphs"); } if (steps < 0 || steps > no_of_nodes-1) { steps=(igraph_integer_t) no_of_nodes-1; } if (!membership) { mymembership=&vmembership; IGRAPH_VECTOR_INIT_FINALLY(mymembership, 0); } IGRAPH_VECTOR_INIT_FINALLY(&mymerges, 0); IGRAPH_CHECK(igraph_vector_reserve(&mymerges, steps*2)); IGRAPH_VECTOR_INIT_FINALLY(&idx, 0); if (eigenvalues) { igraph_vector_clear(eigenvalues); } if (eigenvectors) { igraph_vector_ptr_clear(eigenvectors); IGRAPH_FINALLY(igraph_i_levc_free, eigenvectors); } IGRAPH_STATUS("Starting leading eigenvector method.\n", 0); if (!start) { /* Calculate the weakly connected components in the graph and use them as * an initial split */ IGRAPH_CHECK(igraph_clusters(graph, mymembership, &idx, 0, IGRAPH_WEAK)); communities = igraph_vector_size(&idx); IGRAPH_STATUSF(("Starting from %li component(s).\n", 0, communities)); if (history) { IGRAPH_CHECK(igraph_vector_push_back(history, IGRAPH_LEVC_HIST_START_FULL)); } } else { /* Just create the idx vector for the given membership vector */ communities=(long int) igraph_vector_max(mymembership)+1; IGRAPH_STATUSF(("Starting from given membership vector with %li " "communities.\n", 0, communities)); if (history) { IGRAPH_CHECK(igraph_vector_push_back(history, IGRAPH_LEVC_HIST_START_GIVEN)); IGRAPH_CHECK(igraph_vector_push_back(history, communities)); } IGRAPH_CHECK(igraph_vector_resize(&idx, communities)); igraph_vector_null(&idx); for (i=0; i 2) { igraph_dqueue_push(&tosplit, i); } } for (i=1; incv = 0; /* 0 means "automatic" in igraph_arpack_rssolve */ options->start = 0; options->which[0]='L'; options->which[1]='A'; /* Memory for ARPACK */ /* We are allocating memory for 20 eigenvectors since options->ncv won't be * larger than 20 when using automatic mode in igraph_arpack_rssolve */ IGRAPH_CHECK(igraph_arpack_storage_init(&storage, (int) no_of_nodes, 20, (int) no_of_nodes, 1)); IGRAPH_FINALLY(igraph_arpack_storage_destroy, &storage); extra.idx=&idx; extra.idx2=&idx2; extra.tmp=&tmp; extra.adjlist=&adjlist; extra.inclist=&inclist; extra.weights=weights; extra.sumweights=sumweights; extra.graph=graph; extra.strength=&strength; extra.no_of_edges=no_of_edges; extra.mymembership=mymembership; while (!igraph_dqueue_empty(&tosplit) && staken < steps) { long int comm=(long int) igraph_dqueue_pop_back(&tosplit); /* depth first search */ long int size=0; igraph_real_t tmpev; IGRAPH_STATUSF(("Trying to split community %li... ", 0, comm)); IGRAPH_ALLOW_INTERRUPTION(); for (i=0; in=(int) size-1; options->info=0; options->nev=1; options->ldv=0; options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rssolve */ options->nconv = 0; options->lworkl = 0; /* we surely have enough space */ extra.comm=comm; /* We try calling the solver twice, once from a random starting point, once from a fixed one. This is because for some hard cases it tends to fail. We need to suppress error handling for the first call. */ { int i; igraph_error_handler_t *errh= igraph_set_error_handler(igraph_i_error_handler_none); igraph_warning_handler_t *warnh= igraph_set_warning_handler(igraph_warning_handler_ignore); igraph_arpack_rssolve(arpcb2, &extra, options, &storage, /*values=*/ 0, /*vectors=*/ 0); igraph_set_error_handler(errh); igraph_set_warning_handler(warnh); if (options->nconv < 1) { /* Call again, from a fixed starting point */ options->start=1; options->info=0; options->ncv=0; options->lworkl = 0; /* we surely have enough space */ for (i=0; i < options->n ; i++) { storage.resid[i] = 1; } IGRAPH_CHECK(igraph_arpack_rssolve(arpcb2, &extra, options, &storage, /*values=*/ 0, /*vectors=*/ 0)); options->start=0; } } if (options->nconv < 1) { IGRAPH_ERROR("ARPACK did not converge", IGRAPH_ARPACK_FAILED); } tmpev=storage.d[0]; /* Now we do the original eigenproblem, again, twice if needed */ options->n=(int) size; options->info=0; options->nev=1; options->ldv=0; options->nconv=0; options->lworkl = 0; /* we surely have enough space */ options->ncv = 0; /* 0 means "automatic" in igraph_arpack_rssolve */ { int i; igraph_error_handler_t *errh= igraph_set_error_handler(igraph_i_error_handler_none); igraph_arpack_rssolve(arpcb1, &extra, options, &storage, /*values=*/ 0, /*vectors=*/ 0); igraph_set_error_handler(errh); if (options->nconv < 1) { /* Call again from a fixed starting point */ options->start=1; options->info=0; options->ncv=0; options->lworkl = 0; /* we surely have enough space */ for (i=0; i < options->n; i++) { storage.resid[i] = 1; } IGRAPH_CHECK(igraph_arpack_rssolve(arpcb1, &extra, options, &storage, /*values=*/ 0, /*vectors=*/ 0)); options->start=0; } } if (options->nconv < 1) { IGRAPH_ERROR("ARPACK did not converge", IGRAPH_ARPACK_FAILED); } /* Ok, we have the leading eigenvector of the modularity matrix*/ /* ---------------------------------------------------------------*/ /* To avoid numeric errors */ if (fabs(storage.d[0]) < 1e-8) { storage.d[0] = 0; } /* We replace very small (in absolute value) elements of the leading eigenvector with zero, to get the same result, consistently.*/ for (i=0; i 1) { IGRAPH_CHECK(igraph_dqueue_push(&tosplit, communities-1)); } if (size-l > 1) { IGRAPH_CHECK(igraph_dqueue_push(&tosplit, comm)); } } igraph_arpack_storage_destroy(&storage); IGRAPH_FINALLY_CLEAN(1); if (!weights) { igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); } else { igraph_inclist_destroy(&inclist); igraph_vector_destroy(&strength); IGRAPH_FINALLY_CLEAN(2); } igraph_dqueue_destroy(&tosplit); igraph_vector_destroy(&tmp); igraph_vector_destroy(&idx2); IGRAPH_FINALLY_CLEAN(3); IGRAPH_STATUS("Done.\n", 0); /* reform the mymerges vector */ if (merges) { igraph_vector_null(&idx); l=igraph_vector_size(&mymerges); k=communities; j=0; IGRAPH_CHECK(igraph_matrix_resize(merges, l/2, 2)); for (i=l; i>0; i-=2) { long int from=(long int) VECTOR(mymerges)[i-1]; long int to=(long int) VECTOR(mymerges)[i-2]; MATRIX(*merges, j, 0)=VECTOR(mymerges)[i-2]; MATRIX(*merges, j, 1)=VECTOR(mymerges)[i-1]; if (VECTOR(idx)[from]!=0) { MATRIX(*merges, j, 1)=VECTOR(idx)[from]-1; } if (VECTOR(idx)[to]!=0) { MATRIX(*merges, j, 0)=VECTOR(idx)[to]-1; } VECTOR(idx)[to]=++k; j++; } } if (eigenvectors) { IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&idx); igraph_vector_destroy(&mymerges); IGRAPH_FINALLY_CLEAN(2); if (modularity) { IGRAPH_CHECK(igraph_modularity(graph, mymembership, modularity, weights)); } if (!membership) { igraph_vector_destroy(mymembership); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_le_community_to_membership * Vertex membership from the leading eigenvector community structure * * This function creates a membership vector from the * result of \ref igraph_community_leading_eigenvector(), * It takes \c membership * and performs \c steps merges, according to the supplied * \c merges matrix. * \param merges The matrix defining the merges to make. * This is usually from the output of the leading eigenvector community * structure detection routines. * \param steps The number of steps to make according to \c merges. * \param membership Initially the starting membership vector, * on output the resulting membership vector, after performing \c steps merges. * \param csize Optionally the sizes of the communities is stored here, * if this is not a null pointer, but an initialized vector. * \return Error code. * * Time complexity: O(|V|), the number of vertices. */ int igraph_le_community_to_membership(const igraph_matrix_t *merges, igraph_integer_t steps, igraph_vector_t *membership, igraph_vector_t *csize) { long int no_of_nodes=igraph_vector_size(membership); igraph_vector_t fake_memb; long int components, i; if (igraph_matrix_nrow(merges) < steps) { IGRAPH_ERROR("`steps' to big or `merges' matrix too short", IGRAPH_EINVAL); } components=(long int) igraph_vector_max(membership)+1; if (components > no_of_nodes) { IGRAPH_ERROR("Invalid membership vector, too many components", IGRAPH_EINVAL); } if (steps >= components) { IGRAPH_ERROR("Cannot make `steps' steps from supplied membership vector", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&fake_memb, components); /* Check membership vector */ for (i=0; i * Weights are taken into account as follows: when the new label of node * i is determined, the algorithm iterates over all edges incident on * node i and calculate the total weight of edges leading to other * nodes with label 0, 1, 2, ..., k-1 (where k is the number of possible * labels). The new label of node i will then be the label whose edges * (among the ones incident on node i) have the highest total weight. * * \param graph The input graph, should be undirected to make sense. * \param membership The membership vector, the result is returned here. * For each vertex it gives the ID of its community (label). * \param weights The weight vector, it should contain a positive * weight for all the edges. * \param initial The initial state. If NULL, every vertex will have * a different label at the beginning. Otherwise it must be a vector * with an entry for each vertex. Non-negative values denote different * labels, negative entries denote vertices without labels. * \param fixed Boolean vector denoting which labels are fixed. Of course * this makes sense only if you provided an initial state, otherwise * this element will be ignored. Also note that vertices without labels * cannot be fixed. * \param modularity If not a null pointer, then it must be a pointer * to a real number. The modularity score of the detected community * structure is stored here. * \return Error code. * * Time complexity: O(m+n) * * \example examples/simple/igraph_community_label_propagation.c */ int igraph_community_label_propagation(const igraph_t *graph, igraph_vector_t *membership, const igraph_vector_t *weights, const igraph_vector_t *initial, igraph_vector_bool_t *fixed, igraph_real_t *modularity) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); long int no_of_not_fixed_nodes=no_of_nodes; long int i, j, k; igraph_adjlist_t al; igraph_inclist_t il; igraph_bool_t running = 1; igraph_vector_t label_counters, dominant_labels, nonzero_labels, node_order; /* The implementation uses a trick to avoid negative array indexing: * elements of the membership vector are increased by 1 at the start * of the algorithm; this to allow us to denote unlabeled vertices * (if any) by zeroes. The membership vector is shifted back in the end */ /* Do some initial checks */ if (fixed && igraph_vector_bool_size(fixed) != no_of_nodes) { IGRAPH_ERROR("Invalid fixed labeling vector length", IGRAPH_EINVAL); } if (weights) { if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } else if (igraph_vector_min(weights) < 0) { IGRAPH_ERROR("Weights must be non-negative", IGRAPH_EINVAL); } } if (fixed && !initial) { IGRAPH_WARNING("Ignoring fixed vertices as no initial labeling given"); } IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); if (initial) { if (igraph_vector_size(initial) != no_of_nodes) { IGRAPH_ERROR("Invalid initial labeling vector length", IGRAPH_EINVAL); } /* Check if the labels used are valid, initialize membership vector */ for (i=0; i no_of_nodes) { IGRAPH_ERROR("elements of the initial labeling vector must be between 0 and |V|-1", IGRAPH_EINVAL); } if (i <= 0) { IGRAPH_ERROR("at least one vertex must be labeled in the initial labeling", IGRAPH_EINVAL); } } else { for (i=0; i 0) { /* Select randomly from the dominant labels */ k = RNG_INTEGER(0, igraph_vector_size(&dominant_labels)-1); k = (long int) VECTOR(dominant_labels)[k]; /* Check if the _current_ label of the node is also dominant */ if (VECTOR(label_counters)[(long)VECTOR(*membership)[v1]]!=max_count) { /* Nope, we need at least one more iteration */ running = 1; } VECTOR(*membership)[v1] = k; } /* Clear the nonzero elements in label_counters */ num_neis = igraph_vector_size(&nonzero_labels); for (j = 0; j < num_neis; j++) { VECTOR(label_counters)[(long int)VECTOR(nonzero_labels)[j]] = 0; } } } RNG_END(); /* Shift back the membership vector, permute labels in increasing order */ /* We recycle label_counters here :) */ igraph_vector_fill(&label_counters, -1); j = 0; for (i=0; i= 0) { if (VECTOR(label_counters)[k] == -1) { /* We have seen this label for the first time */ VECTOR(label_counters)[k] = j; k = j; j++; } else { k = (long int) VECTOR(label_counters)[k]; } } else { /* This is an unlabeled vertex */ } VECTOR(*membership)[i] = k; } if (weights) igraph_inclist_destroy(&il); else igraph_adjlist_destroy(&al); IGRAPH_FINALLY_CLEAN(1); if (modularity) { IGRAPH_CHECK(igraph_modularity(graph, membership, modularity, weights)); } igraph_vector_destroy(&node_order); igraph_vector_destroy(&label_counters); igraph_vector_destroy(&dominant_labels); igraph_vector_destroy(&nonzero_labels); IGRAPH_FINALLY_CLEAN(4); return 0; } /********************************************************************/ /* Structure storing a community */ typedef struct { igraph_integer_t size; /* Size of the community */ igraph_real_t weight_inside; /* Sum of edge weights inside community */ igraph_real_t weight_all; /* Sum of edge weights starting/ending in the community */ } igraph_i_multilevel_community; /* Global community list structure */ typedef struct { long int communities_no, vertices_no; /* Number of communities, number of vertices */ igraph_real_t weight_sum; /* Sum of edges weight in the whole graph */ igraph_i_multilevel_community *item; /* List of communities */ igraph_vector_t *membership; /* Community IDs */ igraph_vector_t *weights; /* Graph edge weights */ } igraph_i_multilevel_community_list; /* Computes the modularity of a community partitioning */ igraph_real_t igraph_i_multilevel_community_modularity( const igraph_i_multilevel_community_list *communities) { igraph_real_t result = 0; long int i; igraph_real_t m = communities->weight_sum; for (i = 0; i < communities->vertices_no; i++) { if (communities->item[i].size > 0) { result += (communities->item[i].weight_inside - communities->item[i].weight_all*communities->item[i].weight_all/m)/m; } } return result; } typedef struct { long int from; long int to; long int id; } igraph_i_multilevel_link; int igraph_i_multilevel_link_cmp(const void *a, const void *b) { long int r = (((igraph_i_multilevel_link*)a)->from - ((igraph_i_multilevel_link*)b)->from); if (r != 0) return (int) r; return (int) (((igraph_i_multilevel_link*)a)->to - ((igraph_i_multilevel_link*)b)->to); } /* removes multiple edges and returns new edge id's for each edge in |E|log|E| */ int igraph_i_multilevel_simplify_multiple(igraph_t *graph, igraph_vector_t *eids) { long int ecount = igraph_ecount(graph); long int i, l = -1, last_from = -1, last_to = -1; igraph_bool_t directed = igraph_is_directed(graph); igraph_integer_t from, to; igraph_vector_t edges; igraph_i_multilevel_link *links; /* Make sure there's enough space in eids to store the new edge IDs */ IGRAPH_CHECK(igraph_vector_resize(eids, ecount)); links = igraph_Calloc(ecount, igraph_i_multilevel_link); if (links == 0) { IGRAPH_ERROR("multi-level community structure detection failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, links); for (i = 0; i < ecount; i++) { igraph_edge(graph, (igraph_integer_t) i, &from, &to); links[i].from = from; links[i].to = to; links[i].id = i; } qsort((void*)links, (size_t) ecount, sizeof(igraph_i_multilevel_link), igraph_i_multilevel_link_cmp); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); for (i = 0; i < ecount; i++) { if (links[i].from == last_from && links[i].to == last_to) { VECTOR(*eids)[links[i].id] = l; continue; } last_from = links[i].from; last_to = links[i].to; igraph_vector_push_back(&edges, last_from); igraph_vector_push_back(&edges, last_to); l++; VECTOR(*eids)[links[i].id] = l; } free(links); IGRAPH_FINALLY_CLEAN(1); igraph_destroy(graph); IGRAPH_CHECK(igraph_create(graph, &edges, igraph_vcount(graph), directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } typedef struct { long int community; igraph_real_t weight; } igraph_i_multilevel_community_link; int igraph_i_multilevel_community_link_cmp(const void *a, const void *b) { return (int) (((igraph_i_multilevel_community_link*)a)->community - ((igraph_i_multilevel_community_link*)b)->community); } /** * Given a graph, a community structure and a vertex ID, this method * calculates: * * - edges: the list of edge IDs that are incident on the vertex * - weight_all: the total weight of these edges * - weight_inside: the total weight of edges that stay within the same * community where the given vertex is right now, excluding loop edges * - weight_loop: the total weight of loop edges * - links_community and links_weight: together these two vectors list the * communities incident on this vertex and the total weight of edges * pointing to these communities */ int igraph_i_multilevel_community_links(const igraph_t *graph, const igraph_i_multilevel_community_list *communities, igraph_integer_t vertex, igraph_vector_t *edges, igraph_real_t *weight_all, igraph_real_t *weight_inside, igraph_real_t *weight_loop, igraph_vector_t *links_community, igraph_vector_t *links_weight) { long int i, n, last = -1, c = -1; igraph_real_t weight = 1; long int to, to_community; long int community = (long int) VECTOR(*(communities->membership))[(long int)vertex]; igraph_i_multilevel_community_link *links; *weight_all = *weight_inside = *weight_loop = 0; igraph_vector_clear(links_community); igraph_vector_clear(links_weight); /* Get the list of incident edges */ igraph_incident(graph, edges, vertex, IGRAPH_ALL); n = igraph_vector_size(edges); links = igraph_Calloc(n, igraph_i_multilevel_community_link); if (links == 0) { IGRAPH_ERROR("multi-level community structure detection failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, links); for (i = 0; i < n; i++) { long int eidx = (long int) VECTOR(*edges)[i]; weight = VECTOR(*communities->weights)[eidx]; to = IGRAPH_OTHER(graph, eidx, vertex); *weight_all += weight; if (to == vertex) { *weight_loop += weight; links[i].community = community; links[i].weight = 0; continue; } to_community = (long int)VECTOR(*(communities->membership))[to]; if (community == to_community) *weight_inside += weight; /* debug("Link %ld (C: %ld) <-> %ld (C: %ld)\n", vertex, community, to, to_community); */ links[i].community = to_community; links[i].weight = weight; } /* Sort links by community ID and merge the same */ qsort((void*)links, (size_t) n, sizeof(igraph_i_multilevel_community_link), igraph_i_multilevel_community_link_cmp); for (i = 0; i < n; i++) { to_community = links[i].community; if (to_community != last) { igraph_vector_push_back(links_community, to_community); igraph_vector_push_back(links_weight, links[i].weight); last = to_community; c++; } else { VECTOR(*links_weight)[c] += links[i].weight; } } igraph_free(links); IGRAPH_FINALLY_CLEAN(1); return 0; } igraph_real_t igraph_i_multilevel_community_modularity_gain( const igraph_i_multilevel_community_list *communities, igraph_integer_t community, igraph_integer_t vertex, igraph_real_t weight_all, igraph_real_t weight_inside) { IGRAPH_UNUSED(vertex); return weight_inside - communities->item[(long int)community].weight_all*weight_all/communities->weight_sum; } /* Shrinks communities into single vertices, keeping all the edges. * This method is internal because it destroys the graph in-place and * creates a new one -- this is fine for the multilevel community * detection where a copy of the original graph is used anyway. * The membership vector will also be rewritten by the underlying * igraph_membership_reindex call */ int igraph_i_multilevel_shrink(igraph_t *graph, igraph_vector_t *membership) { igraph_vector_t edges; long int no_of_nodes = igraph_vcount(graph); long int no_of_edges = igraph_ecount(graph); igraph_bool_t directed = igraph_is_directed(graph); long int i; igraph_eit_t eit; if (no_of_nodes == 0) return 0; if (igraph_vector_size(membership) < no_of_nodes) { IGRAPH_ERROR("cannot shrink graph, membership vector too short", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges * 2); IGRAPH_CHECK(igraph_reindex_membership(membership, 0)); /* Create the new edgelist */ igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_ID), &eit); IGRAPH_FINALLY(igraph_eit_destroy, &eit); i = 0; while (!IGRAPH_EIT_END(eit)) { igraph_integer_t from, to; IGRAPH_CHECK(igraph_edge(graph, IGRAPH_EIT_GET(eit), &from, &to)); VECTOR(edges)[i++] = VECTOR(*membership)[(long int) from]; VECTOR(edges)[i++] = VECTOR(*membership)[(long int) to]; IGRAPH_EIT_NEXT(eit); } igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); /* Create the new graph */ igraph_destroy(graph); no_of_nodes = (long int) igraph_vector_max(membership)+1; IGRAPH_CHECK(igraph_create(graph, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup communities * \function igraph_i_community_multilevel_step * \brief Performs a single step of the multi-level modularity optimization method * * This function implements a single step of the multi-level modularity optimization * algorithm for finding community structure, see VD Blondel, J-L Guillaume, * R Lambiotte and E Lefebvre: Fast unfolding of community hierarchies in large * networks, http://arxiv.org/abs/0803.0476 for the details. * * This function was contributed by Tom Gregorovic. * * \param graph The input graph. It must be an undirected graph. * \param weights Numeric vector containing edge weights. If \c NULL, every edge * has equal weight. The weights are expected to be non-negative. * \param membership The membership vector, the result is returned here. * For each vertex it gives the ID of its community. * \param modularity The modularity of the partition is returned here. * \c NULL means that the modularity is not needed. * \return Error code. * * Time complexity: in average near linear on sparse graphs. */ int igraph_i_community_multilevel_step(igraph_t *graph, igraph_vector_t *weights, igraph_vector_t *membership, igraph_real_t *modularity) { long int i, j; long int vcount = igraph_vcount(graph); long int ecount = igraph_ecount(graph); igraph_integer_t ffrom, fto; igraph_real_t q, pass_q; int pass; igraph_bool_t changed = 0; igraph_vector_t links_community; igraph_vector_t links_weight; igraph_vector_t edges; igraph_vector_t temp_membership; igraph_i_multilevel_community_list communities; /* Initial sanity checks on the input parameters */ if (igraph_is_directed(graph)) { IGRAPH_ERROR("multi-level community detection works for undirected graphs only", IGRAPH_UNIMPLEMENTED); } if (igraph_vector_size(weights) < igraph_ecount(graph)) IGRAPH_ERROR("multi-level community detection: weight vector too short", IGRAPH_EINVAL); if (igraph_vector_any_smaller(weights, 0)) IGRAPH_ERROR("weights must be positive", IGRAPH_EINVAL); /* Initialize data structures */ IGRAPH_VECTOR_INIT_FINALLY(&links_community, 0); IGRAPH_VECTOR_INIT_FINALLY(&links_weight, 0); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&temp_membership, vcount); IGRAPH_CHECK(igraph_vector_resize(membership, vcount)); /* Initialize list of communities from graph vertices */ communities.vertices_no = vcount; communities.communities_no = vcount; communities.weights = weights; communities.weight_sum = 2 * igraph_vector_sum(weights); communities.membership = membership; communities.item = igraph_Calloc(vcount, igraph_i_multilevel_community); if (communities.item == 0) { IGRAPH_ERROR("multi-level community structure detection failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, communities.item); /* Still initializing the communities data structure */ for (i=0; i < vcount; i++) { VECTOR(*communities.membership)[i] = i; communities.item[i].size = 1; communities.item[i].weight_inside = 0; communities.item[i].weight_all = 0; } /* Some more initialization :) */ for (i = 0; i < ecount; i++) { igraph_real_t weight = 1; igraph_edge(graph, (igraph_integer_t) i, &ffrom, &fto); weight = VECTOR(*weights)[i]; communities.item[(long int) ffrom].weight_all += weight; communities.item[(long int) fto].weight_all += weight; if (ffrom == fto) communities.item[(long int) ffrom].weight_inside += 2*weight; } q = igraph_i_multilevel_community_modularity(&communities); pass = 1; do { /* Pass begin */ long int temp_communities_no = communities.communities_no; pass_q = q; changed = 0; /* Save the current membership, it will be restored in case of worse result */ IGRAPH_CHECK(igraph_vector_update(&temp_membership, communities.membership)); for (i = 0; i < vcount; i++) { /* Exclude vertex from its current community */ igraph_real_t weight_all = 0; igraph_real_t weight_inside = 0; igraph_real_t weight_loop = 0; igraph_real_t max_q_gain = 0; igraph_real_t max_weight; long int old_id, new_id, n; igraph_i_multilevel_community_links(graph, &communities, (igraph_integer_t) i, &edges, &weight_all, &weight_inside, &weight_loop, &links_community, &links_weight); old_id = (long int)VECTOR(*(communities.membership))[i]; new_id = old_id; /* Update old community */ igraph_vector_set(communities.membership, i, -1); communities.item[old_id].size--; if (communities.item[old_id].size == 0) {communities.communities_no--;} communities.item[old_id].weight_all -= weight_all; communities.item[old_id].weight_inside -= 2*weight_inside + weight_loop; /* debug("Remove %ld all: %lf Inside: %lf\n", i, -weight_all, -2*weight_inside + weight_loop); */ /* Find new community to join with the best modification gain */ max_q_gain = 0; max_weight = weight_inside; n = igraph_vector_size(&links_community); for (j = 0; j < n; j++) { long int c = (long int) VECTOR(links_community)[j]; igraph_real_t w = VECTOR(links_weight)[j]; igraph_real_t q_gain = igraph_i_multilevel_community_modularity_gain(&communities, (igraph_integer_t) c, (igraph_integer_t) i, weight_all, w); /* debug("Link %ld -> %ld weight: %lf gain: %lf\n", i, c, (double) w, (double) q_gain); */ if (q_gain > max_q_gain) { new_id = c; max_q_gain = q_gain; max_weight = w; } } /* debug("Added vertex %ld to community %ld (gain %lf).\n", i, new_id, (double) max_q_gain); */ /* Add vertex to "new" community and update it */ igraph_vector_set(communities.membership, i, new_id); if (communities.item[new_id].size == 0) {communities.communities_no++;} communities.item[new_id].size++; communities.item[new_id].weight_all += weight_all; communities.item[new_id].weight_inside += 2*max_weight + weight_loop; if (new_id != old_id) { changed++; } } q = igraph_i_multilevel_community_modularity(&communities); if (changed && (q > pass_q)) { /* debug("Pass %d (changed: %d) Communities: %ld Modularity from %lf to %lf\n", pass, changed, communities.communities_no, (double) pass_q, (double) q); */ pass++; } else { /* No changes or the modularity became worse, restore last membership */ IGRAPH_CHECK(igraph_vector_update(communities.membership, &temp_membership)); communities.communities_no = temp_communities_no; break; } IGRAPH_ALLOW_INTERRUPTION(); } while (changed && (q > pass_q)); /* Pass end */ if (modularity) { *modularity = q; } /* debug("Result Communities: %ld Modularity: %lf\n", communities.communities_no, (double) q); */ IGRAPH_CHECK(igraph_reindex_membership(membership, 0)); /* Shrink the nodes of the graph according to the present community structure * and simplify the resulting graph */ /* TODO: check if we really need to copy temp_membership */ IGRAPH_CHECK(igraph_vector_update(&temp_membership, membership)); IGRAPH_CHECK(igraph_i_multilevel_shrink(graph, &temp_membership)); igraph_vector_destroy(&temp_membership); IGRAPH_FINALLY_CLEAN(1); /* Update edge weights after shrinking and simplification */ /* Here we reuse the edges vector as we don't need the previous contents anymore */ /* TODO: can we use igraph_simplify here? */ IGRAPH_CHECK(igraph_i_multilevel_simplify_multiple(graph, &edges)); /* We reuse the links_weight vector to store the old edge weights */ IGRAPH_CHECK(igraph_vector_update(&links_weight, weights)); igraph_vector_fill(weights, 0); for (i = 0; i < ecount; i++) { VECTOR(*weights)[(long int)VECTOR(edges)[i]] += VECTOR(links_weight)[i]; } igraph_free(communities.item); igraph_vector_destroy(&links_community); igraph_vector_destroy(&links_weight); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(4); return 0; } /** * \ingroup communities * \function igraph_community_multilevel * \brief Finding community structure by multi-level optimization of modularity * * This function implements the multi-level modularity optimization * algorithm for finding community structure, see * VD Blondel, J-L Guillaume, R Lambiotte and E Lefebvre: Fast unfolding of * community hierarchies in large networks, J Stat Mech P10008 (2008) * for the details (preprint: http://arxiv.org/abs/arXiv:0803.0476). * * It is based on the modularity measure and a hierarchical approach. * Initially, each vertex is assigned to a community on its own. In every step, * vertices are re-assigned to communities in a local, greedy way: each vertex * is moved to the community with which it achieves the highest contribution to * modularity. When no vertices can be reassigned, each community is considered * a vertex on its own, and the process starts again with the merged communities. * The process stops when there is only a single vertex left or when the modularity * cannot be increased any more in a step. * * This function was contributed by Tom Gregorovic. * * \param graph The input graph. It must be an undirected graph. * \param weights Numeric vector containing edge weights. If \c NULL, every edge * has equal weight. The weights are expected to be non-negative. * \param membership The membership vector, the result is returned here. * For each vertex it gives the ID of its community. The vector * must be initialized and it will be resized accordingly. * \param memberships Numeric matrix that will contain the membership * vector after each level, if not \c NULL. It must be initialized and * it will be resized accordingly. * \param modularity Numeric vector that will contain the modularity score * after each level, if not \c NULL. It must be initialized and it * will be resized accordingly. * \return Error code. * * Time complexity: in average near linear on sparse graphs. * * \example examples/simple/igraph_community_multilevel.c */ int igraph_community_multilevel(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *membership, igraph_matrix_t *memberships, igraph_vector_t *modularity) { igraph_t g; igraph_vector_t w, m, level_membership; igraph_real_t prev_q = -1, q = -1; int i, level = 1; long int vcount = igraph_vcount(graph); /* Make a copy of the original graph, we will do the merges on the copy */ IGRAPH_CHECK(igraph_copy(&g, graph)); IGRAPH_FINALLY(igraph_destroy, &g); if (weights) { IGRAPH_CHECK(igraph_vector_copy(&w, weights)); IGRAPH_FINALLY(igraph_vector_destroy, &w); } else { IGRAPH_VECTOR_INIT_FINALLY(&w, igraph_ecount(&g)); igraph_vector_fill(&w, 1); } IGRAPH_VECTOR_INIT_FINALLY(&m, vcount); IGRAPH_VECTOR_INIT_FINALLY(&level_membership, vcount); if (memberships || membership) { /* Put each vertex in its own community */ for (i = 0; i < vcount; i++) { VECTOR(level_membership)[i] = i; } } if (memberships) { /* Resize the membership matrix to have vcount columns and no rows */ IGRAPH_CHECK(igraph_matrix_resize(memberships, 0, vcount)); } if (modularity) { /* Clear the modularity vector */ igraph_vector_clear(modularity); } while (1) { /* Remember the previous modularity and vertex count, do a single step */ igraph_integer_t step_vcount = igraph_vcount(&g); prev_q = q; IGRAPH_CHECK(igraph_i_community_multilevel_step(&g, &w, &m, &q)); /* Were there any merges? If not, we have to stop the process */ if (igraph_vcount(&g) == step_vcount || q < prev_q) break; if (memberships || membership) { for (i = 0; i < vcount; i++) { /* Readjust the membership vector */ VECTOR(level_membership)[i] = VECTOR(m)[(long int) VECTOR(level_membership)[i]]; } } if (modularity) { /* If we have to return the modularity scores, add it to the modularity vector */ IGRAPH_CHECK(igraph_vector_push_back(modularity, q)); } if (memberships) { /* If we have to return the membership vectors at each level, store the new * membership vector */ IGRAPH_CHECK(igraph_matrix_add_rows(memberships, 1)); IGRAPH_CHECK(igraph_matrix_set_row(memberships, &level_membership, level - 1)); } /* debug("Level: %d Communities: %ld Modularity: %f\n", level, (long int) igraph_vcount(&g), (double) q); */ /* Increase the level counter */ level++; } /* It might happen that there are no merges, so every vertex is in its own community. We still might want the modularity score for that. */ if (modularity && igraph_vector_size(modularity) == 0) { igraph_vector_t tmp; igraph_real_t mod; int i; IGRAPH_VECTOR_INIT_FINALLY(&tmp, vcount); for (i=0; i * References: * * * Meila M: Comparing clusterings by the variation of information. * In: Schölkopf B, Warmuth MK (eds.). Learning Theory and Kernel Machines: * 16th Annual Conference on Computational Learning Theory and 7th Kernel * Workshop, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes in Computer * Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1. * * * Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community structure * identification. J Stat Mech P09008, 2005. * * * van Dongen S: Performance criteria for graph clustering and Markov cluster * experiments. Technical Report INS-R0012, National Research Institute for * Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. * * * Rand WM: Objective criteria for the evaluation of clustering methods. * J Am Stat Assoc 66(336):846-850, 1971. * * * Hubert L and Arabie P: Comparing partitions. Journal of Classification * 2:193-218, 1985. * * \param comm1 the membership vector of the first community structure * \param comm2 the membership vector of the second community structure * \param result the result is stored here. * \param method the comparison method to use. \c IGRAPH_COMMCMP_VI * selects the variation of information (VI) metric of * Meila (2003), \c IGRAPH_COMMCMP_NMI selects the * normalized mutual information measure proposed by * Danon et al (2005), \c IGRAPH_COMMCMP_SPLIT_JOIN * selects the split-join distance of van Dongen (2000), * \c IGRAPH_COMMCMP_RAND selects the unadjusted Rand * index (1971) and \c IGRAPH_COMMCMP_ADJUSTED_RAND * selects the adjusted Rand index. * * \return Error code. * * Time complexity: O(n log(n)). */ int igraph_compare_communities(const igraph_vector_t *comm1, const igraph_vector_t *comm2, igraph_real_t* result, igraph_community_comparison_t method) { igraph_vector_t c1, c2; if (igraph_vector_size(comm1) != igraph_vector_size(comm2)) { IGRAPH_ERROR("community membership vectors have different lengths", IGRAPH_EINVAL); } /* Copy and reindex membership vectors to make sure they are continuous */ IGRAPH_CHECK(igraph_vector_copy(&c1, comm1)); IGRAPH_FINALLY(igraph_vector_destroy, &c1); IGRAPH_CHECK(igraph_vector_copy(&c2, comm2)); IGRAPH_FINALLY(igraph_vector_destroy, &c2); IGRAPH_CHECK(igraph_reindex_membership(&c1, 0)); IGRAPH_CHECK(igraph_reindex_membership(&c2, 0)); switch (method) { case IGRAPH_COMMCMP_VI: IGRAPH_CHECK(igraph_i_compare_communities_vi(&c1, &c2, result)); break; case IGRAPH_COMMCMP_NMI: IGRAPH_CHECK(igraph_i_compare_communities_nmi(&c1, &c2, result)); break; case IGRAPH_COMMCMP_SPLIT_JOIN: { igraph_integer_t d12, d21; IGRAPH_CHECK(igraph_i_split_join_distance(&c1, &c2, &d12, &d21)); *result = d12 + d21; } break; case IGRAPH_COMMCMP_RAND: case IGRAPH_COMMCMP_ADJUSTED_RAND: IGRAPH_CHECK(igraph_i_compare_communities_rand(&c1, &c2, result, method == IGRAPH_COMMCMP_ADJUSTED_RAND)); break; default: IGRAPH_ERROR("unknown community comparison method", IGRAPH_EINVAL); } /* Clean up everything */ igraph_vector_destroy(&c1); igraph_vector_destroy(&c2); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \ingroup communities * \function igraph_split_join_distance * \brief Calculates the split-join distance of two community structures * * The split-join distance between partitions A and B is the sum of the * projection distance of A from B and the projection distance of B from * A. The projection distance is an asymmetric measure and it is defined * as follows: * * * First, each set in partition A is evaluated against all sets in partition * B. For each set in partition A, the best matching set in partition B is * found and the overlap size is calculated. (Matching is quantified by the * size of the overlap between the two sets). Then, the maximal overlap sizes * for each set in A are summed together and subtracted from the number of * elements in A. * * * The split-join distance will be returned in two arguments, \c distance12 * will contain the projection distance of the first partition from the * second, while \c distance21 will be the projection distance of the second * partition from the first. This makes it easier to detect whether a * partition is a subpartition of the other, since in this case, the * corresponding distance will be zero. * * * Reference: * * * van Dongen S: Performance criteria for graph clustering and Markov cluster * experiments. Technical Report INS-R0012, National Research Institute for * Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. * * \param comm1 the membership vector of the first community structure * \param comm2 the membership vector of the second community structure * \param distance12 pointer to an \c igraph_integer_t, the projection distance * of the first community structure from the second one will be * returned here. * \param distance21 pointer to an \c igraph_integer_t, the projection distance * of the second community structure from the first one will be * returned here. * \return Error code. * * \see \ref igraph_compare_communities() with the \c IGRAPH_COMMCMP_SPLIT_JOIN * method if you are not interested in the individual distances but only the sum * of them. * * Time complexity: O(n log(n)). */ int igraph_split_join_distance(const igraph_vector_t *comm1, const igraph_vector_t *comm2, igraph_integer_t *distance12, igraph_integer_t *distance21) { igraph_vector_t c1, c2; if (igraph_vector_size(comm1) != igraph_vector_size(comm2)) { IGRAPH_ERROR("community membership vectors have different lengths", IGRAPH_EINVAL); } /* Copy and reindex membership vectors to make sure they are continuous */ IGRAPH_CHECK(igraph_vector_copy(&c1, comm1)); IGRAPH_FINALLY(igraph_vector_destroy, &c1); IGRAPH_CHECK(igraph_vector_copy(&c2, comm2)); IGRAPH_FINALLY(igraph_vector_destroy, &c2); IGRAPH_CHECK(igraph_reindex_membership(&c1, 0)); IGRAPH_CHECK(igraph_reindex_membership(&c2, 0)); IGRAPH_CHECK(igraph_i_split_join_distance(&c1, &c2, distance12, distance21)); /* Clean up everything */ igraph_vector_destroy(&c1); igraph_vector_destroy(&c2); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * Calculates the entropy and the mutual information for two reindexed community * membership vectors v1 and v2. This is needed by both Meila's and Danon's * community comparison measure. */ int igraph_i_entropy_and_mutual_information(const igraph_vector_t* v1, const igraph_vector_t* v2, double* h1, double* h2, double* mut_inf) { long int i, n = igraph_vector_size(v1); long int k1 = (long int)igraph_vector_max(v1)+1; long int k2 = (long int)igraph_vector_max(v2)+1; double *p1, *p2; igraph_spmatrix_t m; igraph_spmatrix_iter_t mit; p1 = igraph_Calloc(k1, double); if (p1 == 0) { IGRAPH_ERROR("igraph_i_entropy_and_mutual_information failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, p1); p2 = igraph_Calloc(k2, double); if (p2 == 0) { IGRAPH_ERROR("igraph_i_entropy_and_mutual_information failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, p2); /* Calculate the entropy of v1 */ *h1 = 0.0; for (i = 0; i < n; i++) p1[(long int)VECTOR(*v1)[i]]++; for (i = 0; i < k1; i++) { p1[i] /= n; *h1 -= p1[i] * log(p1[i]); } /* Calculate the entropy of v2 */ *h2 = 0.0; for (i = 0; i < n; i++) p2[(long int)VECTOR(*v2)[i]]++; for (i = 0; i < k2; i++) { p2[i] /= n; *h2 -= p2[i] * log(p2[i]); } /* We will only need the logs of p1 and p2 from now on */ for (i = 0; i < k1; i++) { p1[i] = log(p1[i]); } for (i = 0; i < k2; i++) { p2[i] = log(p2[i]); } /* Calculate the mutual information of v1 and v2 */ *mut_inf = 0.0; IGRAPH_CHECK(igraph_spmatrix_init(&m, k1, k2)); IGRAPH_FINALLY(igraph_spmatrix_destroy, &m); for (i = 0; i < n; i++) { IGRAPH_CHECK(igraph_spmatrix_add_e(&m, (int)VECTOR(*v1)[i], (int)VECTOR(*v2)[i], 1)); } IGRAPH_CHECK(igraph_spmatrix_iter_create(&mit, &m)); IGRAPH_FINALLY(igraph_spmatrix_iter_destroy, &mit); while (!igraph_spmatrix_iter_end(&mit)) { double p = mit.value / n; *mut_inf += p * (log(p) - p1[mit.ri] - p2[mit.ci]); igraph_spmatrix_iter_next(&mit); } igraph_spmatrix_iter_destroy(&mit); igraph_spmatrix_destroy(&m); free(p1); free(p2); IGRAPH_FINALLY_CLEAN(4); return 0; } /** * Implementation of the normalized mutual information (NMI) measure of * Danon et al. This function assumes that the community membership * vectors have already been normalized using igraph_reindex_communities(). * * * Reference: Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community * structure identification. J Stat Mech P09008, 2005. * * * Time complexity: O(n log(n)) */ int igraph_i_compare_communities_nmi(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_real_t* result) { double h1, h2, mut_inf; IGRAPH_CHECK(igraph_i_entropy_and_mutual_information(v1, v2, &h1, &h2, &mut_inf)); if (h1 == 0 && h2 == 0) *result = 1; else *result = 2 * mut_inf / (h1 + h2); return IGRAPH_SUCCESS; } /** * Implementation of the variation of information metric (VI) of * Meila et al. This function assumes that the community membership * vectors have already been normalized using igraph_reindex_communities(). * * * Reference: Meila M: Comparing clusterings by the variation of information. * In: Schölkopf B, Warmuth MK (eds.). Learning Theory and Kernel Machines: * 16th Annual Conference on Computational Learning Theory and 7th Kernel * Workshop, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes in Computer * Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1. * * * Time complexity: O(n log(n)) */ int igraph_i_compare_communities_vi(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_real_t* result) { double h1, h2, mut_inf; IGRAPH_CHECK(igraph_i_entropy_and_mutual_information(v1, v2, &h1, &h2, &mut_inf)); *result = h1 + h2 - 2*mut_inf; return IGRAPH_SUCCESS; } /** * \brief Calculates the confusion matrix for two clusterings. * * * This function assumes that the community membership vectors have already * been normalized using igraph_reindex_communities(). * * * Time complexity: O(n log(max(k1, k2))), where n is the number of vertices, k1 * and k2 are the number of clusters in each of the clusterings. */ int igraph_i_confusion_matrix(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_spmatrix_t *m) { long int k1 = (long int)igraph_vector_max(v1)+1; long int k2 = (long int)igraph_vector_max(v2)+1; long int i, n = igraph_vector_size(v1); IGRAPH_CHECK(igraph_spmatrix_resize(m, k1, k2)); for (i = 0; i < n; i++) { IGRAPH_CHECK(igraph_spmatrix_add_e(m, (int)VECTOR(*v1)[i], (int)VECTOR(*v2)[i], 1)); } return IGRAPH_SUCCESS; } /** * Implementation of the split-join distance of van Dongen. * * * This function assumes that the community membership vectors have already * been normalized using igraph_reindex_communities(). * * * Reference: van Dongen S: Performance criteria for graph clustering and Markov * cluster experiments. Technical Report INS-R0012, National Research Institute * for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. * * * Time complexity: O(n log(max(k1, k2))), where n is the number of vertices, k1 * and k2 are the number of clusters in each of the clusterings. */ int igraph_i_split_join_distance(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_integer_t* distance12, igraph_integer_t* distance21) { long int n = igraph_vector_size(v1); igraph_vector_t rowmax, colmax; igraph_spmatrix_t m; igraph_spmatrix_iter_t mit; /* Calculate the confusion matrix */ IGRAPH_CHECK(igraph_spmatrix_init(&m, 1, 1)); IGRAPH_FINALLY(igraph_spmatrix_destroy, &m); IGRAPH_CHECK(igraph_i_confusion_matrix(v1, v2, &m)); /* Initialize vectors that will store the row/columnwise maxima */ IGRAPH_VECTOR_INIT_FINALLY(&rowmax, igraph_spmatrix_nrow(&m)); IGRAPH_VECTOR_INIT_FINALLY(&colmax, igraph_spmatrix_ncol(&m)); /* Find the row/columnwise maxima */ IGRAPH_CHECK(igraph_spmatrix_iter_create(&mit, &m)); IGRAPH_FINALLY(igraph_spmatrix_iter_destroy, &mit); while (!igraph_spmatrix_iter_end(&mit)) { if (mit.value > VECTOR(rowmax)[mit.ri]) VECTOR(rowmax)[mit.ri] = mit.value; if (mit.value > VECTOR(colmax)[mit.ci]) VECTOR(colmax)[mit.ci] = mit.value; igraph_spmatrix_iter_next(&mit); } igraph_spmatrix_iter_destroy(&mit); IGRAPH_FINALLY_CLEAN(1); /* Calculate the distances */ *distance12 = (igraph_integer_t) (n - igraph_vector_sum(&rowmax)); *distance21 = (igraph_integer_t) (n - igraph_vector_sum(&colmax)); igraph_vector_destroy(&rowmax); igraph_vector_destroy(&colmax); igraph_spmatrix_destroy(&m); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /** * Implementation of the adjusted and unadjusted Rand indices. * * * This function assumes that the community membership vectors have already * been normalized using igraph_reindex_communities(). * * * References: * * * Rand WM: Objective criteria for the evaluation of clustering methods. J Am * Stat Assoc 66(336):846-850, 1971. * * * Hubert L and Arabie P: Comparing partitions. Journal of Classification * 2:193-218, 1985. * * * Time complexity: O(n log(max(k1, k2))), where n is the number of vertices, k1 * and k2 are the number of clusters in each of the clusterings. */ int igraph_i_compare_communities_rand(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_real_t *result, igraph_bool_t adjust) { igraph_spmatrix_t m; igraph_spmatrix_iter_t mit; igraph_vector_t rowsums, colsums; long int i, nrow, ncol; double rand, n; double frac_pairs_in_1, frac_pairs_in_2; /* Calculate the confusion matrix */ IGRAPH_CHECK(igraph_spmatrix_init(&m, 1, 1)); IGRAPH_FINALLY(igraph_spmatrix_destroy, &m); IGRAPH_CHECK(igraph_i_confusion_matrix(v1, v2, &m)); /* The unadjusted Rand index is defined as (a+d) / (a+b+c+d), where: * * - a is the number of pairs in the same cluster both in v1 and v2. This * equals the sum of n(i,j) choose 2 for all i and j. * * - b is the number of pairs in the same cluster in v1 and in different * clusters in v2. This is sum n(i,*) choose 2 for all i minus a. * n(i,*) is the number of elements in cluster i in v1. * * - c is the number of pairs in the same cluster in v2 and in different * clusters in v1. This is sum n(*,j) choose 2 for all j minus a. * n(*,j) is the number of elements in cluster j in v2. * * - d is (n choose 2) - a - b - c. * * Therefore, a+d = (n choose 2) - b - c * = (n choose 2) - sum (n(i,*) choose 2) * - sum (n(*,j) choose 2) * + 2 * sum (n(i,j) choose 2). * * Since a+b+c+d = (n choose 2) and this goes in the denominator, we can * just as well start dividing each term in a+d by (n choose 2), which * yields: * * 1 - sum( n(i,*)/n * (n(i,*)-1)/(n-1) ) * - sum( n(*,i)/n * (n(*,i)-1)/(n-1) ) * + sum( n(i,j)/n * (n(i,j)-1)/(n-1) ) * 2 */ /* Calculate row and column sums */ nrow = igraph_spmatrix_nrow(&m); ncol = igraph_spmatrix_ncol(&m); n = igraph_vector_size(v1) + 0.0; IGRAPH_VECTOR_INIT_FINALLY(&rowsums, nrow); IGRAPH_VECTOR_INIT_FINALLY(&colsums, ncol); IGRAPH_CHECK(igraph_spmatrix_rowsums(&m, &rowsums)); IGRAPH_CHECK(igraph_spmatrix_colsums(&m, &colsums)); /* Start calculating the unadjusted Rand index */ rand = 0.0; IGRAPH_CHECK(igraph_spmatrix_iter_create(&mit, &m)); IGRAPH_FINALLY(igraph_spmatrix_iter_destroy, &mit); while (!igraph_spmatrix_iter_end(&mit)) { rand += (mit.value / n) * (mit.value-1) / (n-1); igraph_spmatrix_iter_next(&mit); } igraph_spmatrix_iter_destroy(&mit); IGRAPH_FINALLY_CLEAN(1); frac_pairs_in_1 = frac_pairs_in_2 = 0.0; for (i = 0; i < nrow; i++) { frac_pairs_in_1 += (VECTOR(rowsums)[i] / n) * (VECTOR(rowsums)[i]-1) / (n-1); } for (i = 0; i < ncol; i++) { frac_pairs_in_2 += (VECTOR(colsums)[i] / n) * (VECTOR(colsums)[i]-1) / (n-1); } rand = 1.0 + 2 * rand - frac_pairs_in_1 - frac_pairs_in_2; if (adjust) { double expected = frac_pairs_in_1 * frac_pairs_in_2 + (1-frac_pairs_in_1) * (1-frac_pairs_in_2); rand = (rand - expected) / (1 - expected); } igraph_vector_destroy(&rowsums); igraph_vector_destroy(&colsums); igraph_spmatrix_destroy(&m); IGRAPH_FINALLY_CLEAN(3); *result = rand; return IGRAPH_SUCCESS; } igraph/src/include/0000755000175100001440000000000013430770210013751 5ustar hornikusersigraph/src/include/igraph_stack_pmt.h0000644000175100001440000000353013431000472017437 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include /** * Stack data type. * \ingroup internal */ typedef struct TYPE(igraph_stack) { BASE* stor_begin; BASE* stor_end; BASE* end; } TYPE(igraph_stack); DECLDIR int FUNCTION(igraph_stack,init)(TYPE(igraph_stack)* s, long int size); DECLDIR void FUNCTION(igraph_stack,destroy)(TYPE(igraph_stack)* s); DECLDIR int FUNCTION(igraph_stack,reserve)(TYPE(igraph_stack)* s, long int size); DECLDIR igraph_bool_t FUNCTION(igraph_stack,empty)(TYPE(igraph_stack)* s); DECLDIR long int FUNCTION(igraph_stack,size)(const TYPE(igraph_stack)* s); DECLDIR void FUNCTION(igraph_stack,clear)(TYPE(igraph_stack)* s); DECLDIR int FUNCTION(igraph_stack,push)(TYPE(igraph_stack)* s, BASE elem); DECLDIR BASE FUNCTION(igraph_stack,pop)(TYPE(igraph_stack)* s); DECLDIR BASE FUNCTION(igraph_stack,top)(const TYPE(igraph_stack)* s); DECLDIR int FUNCTION(igraph_stack,print)(const TYPE(igraph_stack)* s); DECLDIR int FUNCTION(igraph_stack,fprint)(const TYPE(igraph_stack)* s, FILE *file); igraph/src/include/igraph_scan.h0000644000175100001440000000470013431000472016376 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_SCAN_H #define IGRAPH_SCAN_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_arpack.h" #include "igraph_constants.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS DECLDIR int igraph_local_scan_0(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_local_scan_0_them(const igraph_t *us, const igraph_t *them, igraph_vector_t *res, const igraph_vector_t *weigths_them, igraph_neimode_t mode); DECLDIR int igraph_local_scan_1_ecount(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_local_scan_1_ecount_them(const igraph_t *us, const igraph_t *them, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_local_scan_k_ecount(const igraph_t *graph,int k, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_local_scan_k_ecount_them(const igraph_t *us, const igraph_t *them, int k, igraph_vector_t *res, const igraph_vector_t *weights_them, igraph_neimode_t mode); DECLDIR int igraph_local_scan_neighborhood_ecount(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, const igraph_vector_ptr_t *neighborhoods); __END_DECLS #endif igraph/src/include/igraph_decls.h0000644000175100001440000000103713431000472016544 0ustar hornikusers#undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #undef DECLDIR #if defined (_WIN32) || defined (WIN32) || defined (_WIN64) || defined (WIN64) # if defined (__MINGW32__) || defined (__CYGWIN32__) # define DECLDIR /**/ # else # ifdef IGRAPH_EXPORTS # define DECLDIR __declspec(dllexport) # else # define DECLDIR __declspec(dllimport) # endif # endif #else # define DECLDIR /**/ #endif igraph/src/include/igraph_lsap.h0000644000175100001440000000034213431000472016407 0ustar hornikusers #ifndef IGRAPH_LSAP #define IGRAPH_LSAP #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" int igraph_solve_lsap(igraph_matrix_t *c, igraph_integer_t n, igraph_vector_int_t *p); #endif igraph/src/include/igraph_separators.h0000644000175100001440000000325213431000472017636 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_SEPARATORS_H #define IGRAPH_SEPARATORS_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_datatype.h" #include "igraph_iterators.h" __BEGIN_DECLS DECLDIR int igraph_is_separator(const igraph_t *graph, const igraph_vs_t candidate, igraph_bool_t *res); DECLDIR int igraph_all_minimal_st_separators(const igraph_t *graph, igraph_vector_ptr_t *separators); DECLDIR int igraph_is_minimal_separator(const igraph_t *graph, const igraph_vs_t candidate, igraph_bool_t *res); DECLDIR int igraph_minimum_size_separators(const igraph_t *graph, igraph_vector_ptr_t *separators); __END_DECLS #endif igraph/src/include/igraph_pmt_off.h0000644000175100001440000000416313431000472017107 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef ATOMIC #undef ATOMIC #endif #ifdef ATOMIC_IO #undef ATOMIC_IO #endif #ifdef BASE #undef BASE #endif #ifdef BASE_EPSILON #undef BASE_EPSILON #endif #ifdef CONCAT2 #undef CONCAT2 #endif #ifdef CONCAT2x #undef CONCAT2x #endif #ifdef CONCAT3 #undef CONCAT3 #endif #ifdef CONCAT3x #undef CONCAT3x #endif #ifdef CONCAT4 #undef CONCAT4 #endif #ifdef CONCAT4x #undef CONCAT4x #endif #ifdef FP #undef FP #endif #ifdef FUNCTION #undef FUNCTION #endif #ifdef IN_FORMAT #undef IN_FORMAT #endif #ifdef MULTIPLICITY #undef MULTIPLICITY #endif #ifdef ONE #undef ONE #endif #ifdef OUT_FORMAT #undef OUT_FORMAT #endif #ifdef SHORT #undef SHORT #endif #ifdef TYPE #undef TYPE #endif #ifdef ZERO #undef ZERO #endif #ifdef HEAPMORE #undef HEAPMORE #endif #ifdef HEAPLESS #undef HEAPLESS #endif #ifdef HEAPMOREEQ #undef HEAPMOREEQ #endif #ifdef HEAPLESSEQ #undef HEAPLESSEQ #endif #ifdef SUM #undef SUM #endif #ifdef SQ #undef SQ #endif #ifdef PROD #undef PROD #endif #ifdef NOTORDERED #undef NOTORDERED #endif #ifdef EQ #undef EQ #endif #ifdef DIFF #undef DIFF #endif #ifdef DIV #undef DIV #endif #ifdef NOABS #undef NOABS #endif #ifdef PRINTFUNC #undef PRINTFUNC #endif #ifdef FPRINTFUNC #undef PRINTFUNC #endif #ifdef UNSIGNED #undef UNSIGNED #endif igraph/src/include/igraph_array_pmt.h0000644000175100001440000000406213431000472017451 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ typedef struct TYPE(igraph_array3) { TYPE(igraph_vector) data; long int n1, n2, n3, n1n2; } TYPE(igraph_array3); #ifndef IGRAPH_ARRAY3_INIT_FINALLY #define IGRAPH_ARRAY3_INIT_FINALLY(a, n1, n2, n3) \ do { IGRAPH_CHECK(igraph_array3_init(a, n1, n2, n3)); \ IGRAPH_FINALLY(igraph_array3_destroy, a); } while (0) #endif #ifndef ARRAY3 #define ARRAY3(m,i,j,k) ((m).data.stor_begin[(m).n1n2*(k)+(m).n1*(j)+(i)]) #endif int FUNCTION(igraph_array3,init)(TYPE(igraph_array3) *a, long int n1, long int n2, long int n3); void FUNCTION(igraph_array3,destroy)(TYPE(igraph_array3) *a); long int FUNCTION(igraph_array3,size)(const TYPE(igraph_array3) *a); long int FUNCTION(igraph_array3,n)(const TYPE(igraph_array3) *a, long int idx); int FUNCTION(igraph_array3,resize)(TYPE(igraph_array3) *a, long int n1, long int n2, long int n3); void FUNCTION(igraph_array3,null)(TYPE(igraph_array3) *a); BASE FUNCTION(igraph_array3,sum)(const TYPE(igraph_array3) *a); void FUNCTION(igraph_array3,scale)(TYPE(igraph_array3) *a, BASE by); void FUNCTION(igraph_array3,fill)(TYPE(igraph_array3) *a, BASE e); int FUNCTION(igraph_array3,update)(TYPE(igraph_array3) *to, const TYPE(igraph_array3) *from); igraph/src/include/igraph_embedding.h0000644000175100001440000000442413431000472017373 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_EMBEDDING_H #define IGRAPH_EMBEDDING_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_arpack.h" #include "igraph_eigen.h" #include "igraph_constants.h" __BEGIN_DECLS DECLDIR int igraph_adjacency_spectral_embedding(const igraph_t *graph, igraph_integer_t no, const igraph_vector_t *weights, igraph_eigen_which_position_t which, igraph_bool_t scaled, igraph_matrix_t *X, igraph_matrix_t *Y, igraph_vector_t *D, const igraph_vector_t *cvec, igraph_arpack_options_t *options); typedef enum { IGRAPH_EMBEDDING_D_A=0, IGRAPH_EMBEDDING_I_DAD, IGRAPH_EMBEDDING_DAD, IGRAPH_EMBEDDING_OAP } igraph_laplacian_spectral_embedding_type_t; DECLDIR int igraph_laplacian_spectral_embedding(const igraph_t *graph, igraph_integer_t no, const igraph_vector_t *weights, igraph_eigen_which_position_t which, igraph_neimode_t degmode, igraph_laplacian_spectral_embedding_type_t type, igraph_bool_t scaled, igraph_matrix_t *X, igraph_matrix_t *Y, igraph_vector_t *D, igraph_arpack_options_t *options); DECLDIR int igraph_dim_select(const igraph_vector_t *sv, igraph_integer_t *dim); __END_DECLS #endif igraph/src/include/igraph_neighborhood.h0000644000175100001440000000316713431000472020127 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_NEIGHBORHOOD_H #define IGRAPH_NEIGHBORHOOD_H #include "igraph_decls.h" __BEGIN_DECLS DECLDIR int igraph_neighborhood_size(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist); DECLDIR int igraph_neighborhood(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist); DECLDIR int igraph_neighborhood_graphs(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist); __END_DECLS #endif igraph/src/include/igraph_heap.h0000644000175100001440000000411113431000472016363 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_HEAP_H #define IGRAPH_HEAP_H #include "igraph_decls.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Heap */ /* -------------------------------------------------- */ /** * Heap data type. * \ingroup internal */ #define BASE_IGRAPH_REAL #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_IGRAPH_REAL #define BASE_LONG #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_LONG #define BASE_CHAR #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "igraph_heap_pmt.h" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_CHAR #define IGRAPH_HEAP_NULL { 0,0,0 } __END_DECLS #endif igraph/src/include/igraph_vector.h0000644000175100001440000001163313431000472016757 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_VECTOR_H #define IGRAPH_VECTOR_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_complex.h" #ifdef HAVE_STDINT_H # include #else # if HAVE_SYS_INT_TYPES_H # include /* for Solaris */ # endif #endif __BEGIN_DECLS /* -------------------------------------------------- */ /* Flexible vector */ /* -------------------------------------------------- */ #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_FLOAT #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_FLOAT #define BASE_LONG #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_INT #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_COMPLEX #include "igraph_pmt.h" #include "igraph_vector_type.h" #include "igraph_pmt_off.h" #undef BASE_COMPLEX #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_FLOAT #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_FLOAT #define BASE_LONG #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_INT #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_COMPLEX #include "igraph_pmt.h" #include "igraph_vector_pmt.h" #include "igraph_pmt_off.h" #undef BASE_COMPLEX /* -------------------------------------------------- */ /* Helper macros */ /* -------------------------------------------------- */ #ifndef IGRAPH_VECTOR_NULL #define IGRAPH_VECTOR_NULL { 0,0,0 } #endif #ifndef IGRAPH_VECTOR_INIT_FINALLY #define IGRAPH_VECTOR_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_vector_init(v, size)); \ IGRAPH_FINALLY(igraph_vector_destroy, v); } while (0) #endif #ifndef IGRAPH_VECTOR_BOOL_INIT_FINALLY #define IGRAPH_VECTOR_BOOL_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_vector_bool_init(v, size)); \ IGRAPH_FINALLY(igraph_vector_bool_destroy, v); } while (0) #endif #ifndef IGRAPH_VECTOR_LONG_INIT_FINALLY #define IGRAPH_VECTOR_LONG_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_vector_long_init(v, size)); \ IGRAPH_FINALLY(igraph_vector_long_destroy, v); } while (0) #endif /* -------------------------------------------------- */ /* Type-specific vector functions */ /* -------------------------------------------------- */ DECLDIR int igraph_vector_floor(const igraph_vector_t *from, igraph_vector_long_t *to); DECLDIR int igraph_vector_round(const igraph_vector_t *from, igraph_vector_long_t *to); DECLDIR igraph_bool_t igraph_vector_e_tol(const igraph_vector_t *lhs, const igraph_vector_t *rhs, igraph_real_t tol); DECLDIR int igraph_vector_zapsmall(igraph_vector_t *v, igraph_real_t tol); /* These are for internal use only */ int igraph_vector_order(const igraph_vector_t* v, const igraph_vector_t *v2, igraph_vector_t* res, igraph_real_t maxval); int igraph_vector_order1(const igraph_vector_t* v, igraph_vector_t* res, igraph_real_t maxval); int igraph_vector_order1_int(const igraph_vector_t* v, igraph_vector_int_t* res, igraph_real_t maxval); int igraph_vector_order2(igraph_vector_t *v); int igraph_vector_rank(const igraph_vector_t *v, igraph_vector_t *res, long int nodes); __END_DECLS #endif igraph/src/include/igraph_vector_type.h0000644000175100001440000000205613431000472020017 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Vector, dealing with arrays efficiently. * \ingroup types */ typedef struct TYPE(igraph_vector) { BASE* stor_begin; BASE* stor_end; BASE* end; } TYPE(igraph_vector); igraph/src/include/igraph_centrality.h0000644000175100001440000002157313431000472017637 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_CENTRALITY_H #define IGRAPH_CENTRALITY_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_iterators.h" #include "igraph_arpack.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Centrality */ /* -------------------------------------------------- */ DECLDIR int igraph_closeness(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, const igraph_vector_t *weights, igraph_bool_t normalized); DECLDIR int igraph_closeness_estimate(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t normalized); DECLDIR int igraph_betweenness(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, const igraph_vector_t *weights, igraph_bool_t nobigint); DECLDIR int igraph_betweenness_estimate(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t cutoff, const igraph_vector_t *weights, igraph_bool_t nobigint); DECLDIR int igraph_edge_betweenness(const igraph_t *graph, igraph_vector_t *result, igraph_bool_t directed, const igraph_vector_t *weigths); DECLDIR int igraph_edge_betweenness_estimate(const igraph_t *graph, igraph_vector_t *result, igraph_bool_t directed, igraph_real_t cutoff, const igraph_vector_t *weights); DECLDIR int igraph_pagerank_old(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, igraph_integer_t niter, igraph_real_t eps, igraph_real_t damping, igraph_bool_t old); /** * \typedef igraph_pagerank_algo_t * \brief PageRank algorithm implementation * * Algorithms to calculate PageRank. * \enumval IGRAPH_PAGERANK_ALGO_POWER Use a simple power iteration, * as it was implemented before igraph version 0.5. * \enumval IGRAPH_PAGERANK_ALGO_ARPACK Use the ARPACK library, this * was the PageRank implementation in igraph from version 0.5, until * version 0.7. * \enumval IGRAPH_PAGERANK_ALGO_PRPACK Use the PRPACK * library. Currently this implementation is recommended. */ typedef enum { IGRAPH_PAGERANK_ALGO_POWER=0, IGRAPH_PAGERANK_ALGO_ARPACK=1, IGRAPH_PAGERANK_ALGO_PRPACK=2 } igraph_pagerank_algo_t; /** * \struct igraph_pagerank_power_options_t * \brief Options for the power method * * \member niter The number of iterations to perform, integer. * \member eps The algorithm will consider the calculation as complete * if the difference of values between iterations change * less than this value for every vertex. */ typedef struct igraph_pagerank_power_options_t { igraph_integer_t niter; igraph_real_t eps; } igraph_pagerank_power_options_t; DECLDIR int igraph_pagerank(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, const igraph_vector_t *weights, void *options); DECLDIR int igraph_personalized_pagerank(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights, void *options); DECLDIR int igraph_personalized_pagerank_vs(const igraph_t *graph, igraph_pagerank_algo_t algo, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vs_t reset_vids, const igraph_vector_t *weights, void *options); DECLDIR int igraph_eigenvector_centrality(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t directed, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options); DECLDIR int igraph_hub_score(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options); DECLDIR int igraph_authority_score(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t scale, const igraph_vector_t *weights, igraph_arpack_options_t *options); DECLDIR int igraph_constraint(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, const igraph_vector_t *weights); DECLDIR int igraph_strength(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops, const igraph_vector_t *weights); DECLDIR int igraph_convergence_degree(const igraph_t *graph, igraph_vector_t *result, igraph_vector_t *ins, igraph_vector_t *outs); DECLDIR int igraph_sort_vertex_ids_by_degree(const igraph_t *graph, igraph_vector_t *outvids, igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops, igraph_order_t order, igraph_bool_t only_indices); DECLDIR igraph_real_t igraph_centralization(const igraph_vector_t *scores, igraph_real_t theoretical_max, igraph_bool_t normalized); DECLDIR int igraph_centralization_degree(const igraph_t *graph, igraph_vector_t *res, igraph_neimode_t mode, igraph_bool_t loops, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized); DECLDIR int igraph_centralization_degree_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_neimode_t mode, igraph_bool_t loops, igraph_real_t *res); DECLDIR int igraph_centralization_betweenness(const igraph_t *graph, igraph_vector_t *res, igraph_bool_t directed, igraph_bool_t nobigint, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized); DECLDIR int igraph_centralization_betweenness_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_bool_t directed, igraph_real_t *res); DECLDIR int igraph_centralization_closeness(const igraph_t *graph, igraph_vector_t *res, igraph_neimode_t mode, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized); DECLDIR int igraph_centralization_closeness_tmax(const igraph_t *graph, igraph_integer_t nodes, igraph_neimode_t mode, igraph_real_t *res); DECLDIR int igraph_centralization_eigenvector_centrality( const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, igraph_bool_t directed, igraph_bool_t scale, igraph_arpack_options_t *options, igraph_real_t *centralization, igraph_real_t *theoretical_max, igraph_bool_t normalized); DECLDIR int igraph_centralization_eigenvector_centrality_tmax( const igraph_t *graph, igraph_integer_t nodes, igraph_bool_t directed, igraph_bool_t scale, igraph_real_t *res); __END_DECLS #endif igraph/src/include/igraph_mixing.h0000644000175100001440000000315313431000472016746 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MIXING_H #define IGRAPH_MIXING_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_vector.h" __BEGIN_DECLS DECLDIR int igraph_assortativity_nominal(const igraph_t *graph, const igraph_vector_t *types, igraph_real_t *res, igraph_bool_t directed); DECLDIR int igraph_assortativity(const igraph_t *graph, const igraph_vector_t *types1, const igraph_vector_t *types2, igraph_real_t *res, igraph_bool_t directed); DECLDIR int igraph_assortativity_degree(const igraph_t *graph, igraph_real_t *res, igraph_bool_t directed); __END_DECLS #endif igraph/src/include/igraph_bipartite.h0000644000175100001440000000717713431000472017450 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_BIPARTITE_H #define IGRAPH_BIPARTITE_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_datatype.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Bipartite networks */ /* -------------------------------------------------- */ DECLDIR int igraph_full_bipartite(igraph_t *graph, igraph_vector_bool_t *types, igraph_integer_t n1, igraph_integer_t n2, igraph_bool_t directed, igraph_neimode_t mode); DECLDIR int igraph_create_bipartite(igraph_t *g, const igraph_vector_bool_t *types, const igraph_vector_t *edges, igraph_bool_t directed); DECLDIR int igraph_bipartite_projection_size(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_integer_t *vcount1, igraph_integer_t *ecount1, igraph_integer_t *vcount2, igraph_integer_t *ecount2); DECLDIR int igraph_bipartite_projection(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_t *proj1, igraph_t *proj2, igraph_vector_t *multiplicity1, igraph_vector_t *multiplicity2, igraph_integer_t probe1); DECLDIR int igraph_incidence(igraph_t *graph, igraph_vector_bool_t *types, const igraph_matrix_t *incidence, igraph_bool_t directed, igraph_neimode_t mode, igraph_bool_t multiple); DECLDIR int igraph_get_incidence(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_matrix_t *res, igraph_vector_t *row_ids, igraph_vector_t *col_ids); DECLDIR int igraph_is_bipartite(const igraph_t *graph, igraph_bool_t *res, igraph_vector_bool_t *type); DECLDIR int igraph_bipartite_game(igraph_t *graph, igraph_vector_bool_t *types, igraph_erdos_renyi_t type, igraph_integer_t n1, igraph_integer_t n2, igraph_real_t p, igraph_integer_t m, igraph_bool_t directed, igraph_neimode_t mode); DECLDIR int igraph_bipartite_game_gnp(igraph_t *graph, igraph_vector_bool_t *types, igraph_integer_t n1, igraph_integer_t n2, igraph_real_t p, igraph_bool_t directed, igraph_neimode_t mode); DECLDIR int igraph_bipartite_game_gnm(igraph_t *graph, igraph_vector_bool_t *types, igraph_integer_t n1, igraph_integer_t n2, igraph_integer_t m, igraph_bool_t directed, igraph_neimode_t mode); __END_DECLS #endif igraph/src/include/igraph_transitivity.h0000644000175100001440000000437613431000472020234 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_TRANSITIVITY_H #define IGRAPH_TRANSITIVITY_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_constants.h" #include "igraph_iterators.h" __BEGIN_DECLS DECLDIR int igraph_transitivity_undirected(const igraph_t *graph, igraph_real_t *res, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_local_undirected(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_local_undirected1(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_local_undirected2(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_local_undirected4(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_avglocal_undirected(const igraph_t *graph, igraph_real_t *res, igraph_transitivity_mode_t mode); DECLDIR int igraph_transitivity_barrat(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, const igraph_vector_t *weights, const igraph_transitivity_mode_t mode); __END_DECLS #endif igraph/src/include/igraph_scg.h0000644000175100001440000001030713431000472016226 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_SCG_H #define IGRAPH_SCG_H #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_sparsemat.h" typedef enum { IGRAPH_SCG_SYMMETRIC=1, IGRAPH_SCG_LAPLACIAN=2, IGRAPH_SCG_STOCHASTIC=3 } igraph_scg_matrix_t; typedef enum { IGRAPH_SCG_OPTIMUM=1, IGRAPH_SCG_INTERV_KM=2, IGRAPH_SCG_INTERV=3, IGRAPH_SCG_EXACT=4 } igraph_scg_algorithm_t; typedef enum { IGRAPH_SCG_NORM_ROW=1, IGRAPH_SCG_NORM_COL=2 } igraph_scg_norm_t; typedef enum { IGRAPH_SCG_DIRECTION_DEFAULT=1, IGRAPH_SCG_DIRECTION_LEFT=2, IGRAPH_SCG_DIRECTION_RIGHT=3 } igraph_scg_direction_t; int igraph_scg_grouping(const igraph_matrix_t *V, igraph_vector_t *groups, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_matrix_t mtype, igraph_scg_algorithm_t algo, const igraph_vector_t *p, igraph_integer_t maxiter); int igraph_scg_semiprojectors(const igraph_vector_t *groups, igraph_scg_matrix_t mtype, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse, const igraph_vector_t *p, igraph_scg_norm_t norm); int igraph_scg_norm_eps(const igraph_matrix_t *V, const igraph_vector_t *groups, igraph_vector_t *eps, igraph_scg_matrix_t mtype, const igraph_vector_t *p, igraph_scg_norm_t norm); int igraph_scg_adjacency(const igraph_t *graph, const igraph_matrix_t *matrix, const igraph_sparsemat_t *sparsemat, const igraph_vector_t *ev, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_algorithm_t algo, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_t *groups, igraph_bool_t use_arpack, igraph_integer_t maxiter, igraph_t *scg_graph, igraph_matrix_t *scg_matrix, igraph_sparsemat_t *scg_sparsemat, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse); int igraph_scg_stochastic(const igraph_t *graph, const igraph_matrix_t *matrix, const igraph_sparsemat_t *sparsemat, const igraph_vector_t *ev, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_algorithm_t algo, igraph_scg_norm_t norm, igraph_vector_complex_t *values, igraph_matrix_complex_t *vectors, igraph_vector_t *groups, igraph_vector_t *p, igraph_bool_t use_arpack, igraph_integer_t maxiter, igraph_t *scg_graph, igraph_matrix_t *scg_matrix, igraph_sparsemat_t *scg_sparsemat, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse); int igraph_scg_laplacian(const igraph_t *graph, const igraph_matrix_t *matrix, const igraph_sparsemat_t *sparsemat, const igraph_vector_t *ev, igraph_integer_t nt, const igraph_vector_t *nt_vec, igraph_scg_algorithm_t algo, igraph_scg_norm_t norm, igraph_scg_direction_t direction, igraph_vector_complex_t *values, igraph_matrix_complex_t *vectors, igraph_vector_t *groups, igraph_bool_t use_arpack, igraph_integer_t maxiter, igraph_t *scg_graph, igraph_matrix_t *scg_matrix, igraph_sparsemat_t *scg_sparsemat, igraph_matrix_t *L, igraph_matrix_t *R, igraph_sparsemat_t *Lsparse, igraph_sparsemat_t *Rsparse); #endif igraph/src/include/igraph_constants.h0000644000175100001440000001256113431000472017472 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_CONSTANTS_H #define IGRAPH_CONSTANTS_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_datatype.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Constants */ /* -------------------------------------------------- */ typedef enum { IGRAPH_UNDIRECTED=0, IGRAPH_DIRECTED=1 } igraph_i_directed_t; typedef enum { IGRAPH_NO_LOOPS=0, IGRAPH_LOOPS=1 } igraph_i_loops_t; typedef enum { IGRAPH_NO_MULTIPLE=0, IGRAPH_MULTIPLE=1 } igraph_i_multiple_t; typedef enum { IGRAPH_ASCENDING=0, IGRAPH_DESCENDING=1 } igraph_order_t; typedef enum { IGRAPH_MINIMUM=0, IGRAPH_MAXIMUM=1 } igraph_optimal_t; typedef enum { IGRAPH_OUT=1, IGRAPH_IN=2, IGRAPH_ALL=3, IGRAPH_TOTAL=3 } igraph_neimode_t; typedef enum { IGRAPH_WEAK=1, IGRAPH_STRONG=2 } igraph_connectedness_t; typedef enum { IGRAPH_RECIPROCITY_DEFAULT=0, IGRAPH_RECIPROCITY_RATIO=1 } igraph_reciprocity_t; typedef enum { IGRAPH_ADJ_DIRECTED=0, IGRAPH_ADJ_UNDIRECTED=1, IGRAPH_ADJ_MAX=1, IGRAPH_ADJ_UPPER, IGRAPH_ADJ_LOWER, IGRAPH_ADJ_MIN, IGRAPH_ADJ_PLUS } igraph_adjacency_t; typedef enum { IGRAPH_STAR_OUT=0, IGRAPH_STAR_IN, IGRAPH_STAR_UNDIRECTED, IGRAPH_STAR_MUTUAL } igraph_star_mode_t; typedef enum { IGRAPH_TREE_OUT=0, IGRAPH_TREE_IN, IGRAPH_TREE_UNDIRECTED } igraph_tree_mode_t; typedef enum { IGRAPH_ERDOS_RENYI_GNP=0, IGRAPH_ERDOS_RENYI_GNM } igraph_erdos_renyi_t; typedef enum { IGRAPH_GET_ADJACENCY_UPPER=0, IGRAPH_GET_ADJACENCY_LOWER, IGRAPH_GET_ADJACENCY_BOTH } igraph_get_adjacency_t; typedef enum { IGRAPH_DEGSEQ_SIMPLE=0, IGRAPH_DEGSEQ_VL, IGRAPH_DEGSEQ_SIMPLE_NO_MULTIPLE } igraph_degseq_t; typedef enum { IGRAPH_FILEFORMAT_EDGELIST=0, IGRAPH_FILEFORMAT_NCOL, IGRAPH_FILEFORMAT_PAJEK, IGRAPH_FILEFORMAT_LGL, IGRAPH_FILEFORMAT_GRAPHML } igraph_fileformat_type_t; typedef enum { IGRAPH_REWIRING_SIMPLE=0, IGRAPH_REWIRING_SIMPLE_LOOPS } igraph_rewiring_t; typedef enum { IGRAPH_EDGEORDER_ID=0, IGRAPH_EDGEORDER_FROM, IGRAPH_EDGEORDER_TO } igraph_edgeorder_type_t; typedef enum { IGRAPH_TO_DIRECTED_ARBITRARY=0, IGRAPH_TO_DIRECTED_MUTUAL } igraph_to_directed_t; typedef enum { IGRAPH_TO_UNDIRECTED_EACH=0, IGRAPH_TO_UNDIRECTED_COLLAPSE, IGRAPH_TO_UNDIRECTED_MUTUAL} igraph_to_undirected_t; typedef enum { IGRAPH_VCONN_NEI_ERROR=0, IGRAPH_VCONN_NEI_NUMBER_OF_NODES, IGRAPH_VCONN_NEI_IGNORE, IGRAPH_VCONN_NEI_NEGATIVE } igraph_vconn_nei_t; typedef enum { IGRAPH_SPINCOMM_UPDATE_SIMPLE=0, IGRAPH_SPINCOMM_UPDATE_CONFIG } igraph_spincomm_update_t; typedef enum { IGRAPH_DONT_SIMPLIFY=0, IGRAPH_SIMPLIFY } igraph_lazy_adlist_simplify_t; typedef enum { IGRAPH_TRANSITIVITY_NAN=0, IGRAPH_TRANSITIVITY_ZERO } igraph_transitivity_mode_t; typedef enum { IGRAPH_SPINCOMM_IMP_ORIG=0, IGRAPH_SPINCOMM_IMP_NEG } igraph_spinglass_implementation_t; typedef enum { IGRAPH_COMMCMP_VI = 0, IGRAPH_COMMCMP_NMI, IGRAPH_COMMCMP_SPLIT_JOIN, IGRAPH_COMMCMP_RAND, IGRAPH_COMMCMP_ADJUSTED_RAND } igraph_community_comparison_t; typedef enum { IGRAPH_ADD_WEIGHTS_NO = 0, IGRAPH_ADD_WEIGHTS_YES, IGRAPH_ADD_WEIGHTS_IF_PRESENT } igraph_add_weights_t; typedef enum { IGRAPH_BARABASI_BAG = 0, IGRAPH_BARABASI_PSUMTREE, IGRAPH_BARABASI_PSUMTREE_MULTIPLE} igraph_barabasi_algorithm_t; typedef enum { IGRAPH_FAS_EXACT_IP = 0, IGRAPH_FAS_APPROX_EADES } igraph_fas_algorithm_t; typedef enum { IGRAPH_SUBGRAPH_AUTO = 0, IGRAPH_SUBGRAPH_COPY_AND_DELETE, IGRAPH_SUBGRAPH_CREATE_FROM_SCRATCH } igraph_subgraph_implementation_t; typedef enum { IGRAPH_IMITATE_AUGMENTED = 0, IGRAPH_IMITATE_BLIND, IGRAPH_IMITATE_CONTRACTED } igraph_imitate_algorithm_t; typedef igraph_real_t igraph_scalar_function_t(const igraph_vector_t *var, const igraph_vector_t *par, void* extra); typedef void igraph_vector_function_t(const igraph_vector_t *var, const igraph_vector_t *par, igraph_vector_t* res, void* extra); typedef enum { IGRAPH_LAYOUT_GRID = 0, IGRAPH_LAYOUT_NOGRID, IGRAPH_LAYOUT_AUTOGRID } igraph_layout_grid_t; typedef enum { IGRAPH_RANDOM_WALK_STUCK_ERROR = 0, IGRAPH_RANDOM_WALK_STUCK_RETURN } igraph_random_walk_stuck_t; __END_DECLS #endif igraph/src/include/igraph_motifs.h0000644000175100001440000000745313431000472016763 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MOTIFS_H #define IGRAPH_MOTIFS_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_iterators.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Graph motifs */ /* -------------------------------------------------- */ /** * \typedef igraph_motifs_handler_t * Callback type for \c igraph_motifs_randesu_callback * * \ref igraph_motifs_randesu_callback() calls a specified callback * function whenever a new motif is found during a motif search. This * callback function must be of type \c igraph_motifs_handler_t. It has * the following arguments: * \param graph The graph that that algorithm is working on. Of course * this must not be modified. * \param vids The IDs of the vertices in the motif that has just been * found. This vector is owned by the motif search algorithm, so do not * modify or destroy it; make a copy of it if you need it later. * \param isoclass The isomorphism class of the motif that has just been * found. Use \ref igraph_isoclass or \ref igraph_isoclass_subgraph to find * out which isomorphism class belongs to a given motif. * \param extra The extra argument that was passed to \ref * igraph_motifs_randesu_callback(). * \return A logical value, if TRUE (=non-zero), that is interpreted * as a request to stop the motif search and return to the caller. * * \sa \ref igraph_motifs_randesu_callback() */ typedef igraph_bool_t igraph_motifs_handler_t(const igraph_t *graph, igraph_vector_t *vids, int isoclass, void* extra); DECLDIR int igraph_motifs_randesu(const igraph_t *graph, igraph_vector_t *hist, int size, const igraph_vector_t *cut_prob); DECLDIR int igraph_motifs_randesu_callback(const igraph_t *graph, int size, const igraph_vector_t *cut_prob, igraph_motifs_handler_t *callback, void* extra); DECLDIR int igraph_motifs_randesu_estimate(const igraph_t *graph, igraph_integer_t *est, int size, const igraph_vector_t *cut_prob, igraph_integer_t sample_size, const igraph_vector_t *sample); DECLDIR int igraph_motifs_randesu_no(const igraph_t *graph, igraph_integer_t *no, int size, const igraph_vector_t *cut_prob); DECLDIR int igraph_dyad_census(const igraph_t *graph, igraph_integer_t *mut, igraph_integer_t *asym, igraph_integer_t *null); DECLDIR int igraph_triad_census(const igraph_t *igraph, igraph_vector_t *res); DECLDIR int igraph_triad_census_24(const igraph_t *graph, igraph_real_t *res2, igraph_real_t *res4); DECLDIR int igraph_adjacent_triangles(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids); DECLDIR int igraph_list_triangles(const igraph_t *graph, igraph_vector_int_t *res); __END_DECLS #endif igraph/src/include/igraph_lapack.h0000644000175100001440000001012113431000472016677 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LAPACK_H #define LAPACK_H #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_decls.h" __BEGIN_DECLS /** * \section about_lapack LAPACK interface in igraph * * * LAPACK is written in Fortran90 and provides routines for solving * systems of simultaneous linear equations, least-squares solutions * of linear systems of equations, eigenvalue problems, and singular * value problems. The associated matrix factorizations (LU, Cholesky, * QR, SVD, Schur, generalized Schur) are also provided, as are * related computations such as reordering of the Schur factorizations * and estimating condition numbers. Dense and banded matrices are * handled, but not general sparse matrices. In all areas, similar * functionality is provided for real and complex matrices, in both * single and double precision. * * * * igraph provides an interface to a very limited set of LAPACK * functions, using the regular igraph data structures. * * * * See more about LAPACK at http://www.netlib.org/lapack/ * */ DECLDIR int igraph_lapack_dgetrf(igraph_matrix_t *a, igraph_vector_int_t *ipiv, int *info); DECLDIR int igraph_lapack_dgetrs(igraph_bool_t transpose, const igraph_matrix_t *a, igraph_vector_int_t *ipiv, igraph_matrix_t *b); DECLDIR int igraph_lapack_dgesv(igraph_matrix_t *a, igraph_vector_int_t *ipiv, igraph_matrix_t *b, int *info); typedef enum { IGRAPH_LAPACK_DSYEV_ALL, IGRAPH_LAPACK_DSYEV_INTERVAL, IGRAPH_LAPACK_DSYEV_SELECT } igraph_lapack_dsyev_which_t; DECLDIR int igraph_lapack_dsyevr(const igraph_matrix_t *A, igraph_lapack_dsyev_which_t which, igraph_real_t vl, igraph_real_t vu, int vestimate, int il, int iu, igraph_real_t abstol, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_int_t *support); /* TODO: should we use complex vectors/matrices? */ DECLDIR int igraph_lapack_dgeev(const igraph_matrix_t *A, igraph_vector_t *valuesreal, igraph_vector_t *valuesimag, igraph_matrix_t *vectorsleft, igraph_matrix_t *vectorsright, int *info); typedef enum { IGRAPH_LAPACK_DGEEVX_BALANCE_NONE=0, IGRAPH_LAPACK_DGEEVX_BALANCE_PERM, IGRAPH_LAPACK_DGEEVX_BALANCE_SCALE, IGRAPH_LAPACK_DGEEVX_BALANCE_BOTH } igraph_lapack_dgeevx_balance_t; DECLDIR int igraph_lapack_dgeevx(igraph_lapack_dgeevx_balance_t balance, const igraph_matrix_t *A, igraph_vector_t *valuesreal, igraph_vector_t *valuesimag, igraph_matrix_t *vectorsleft, igraph_matrix_t *vectorsright, int *ilo, int *ihi, igraph_vector_t *scale, igraph_real_t *abnrm, igraph_vector_t *rconde, igraph_vector_t *rcondv, int *info); DECLDIR int igraph_lapack_dgehrd(const igraph_matrix_t *A, int ilo, int ihi, igraph_matrix_t *result); DECLDIR int igraph_lapack_ddot(const igraph_vector_t *v1, const igraph_vector_t *v2, igraph_real_t *res); __END_DECLS #endif igraph/src/include/igraph_statusbar.h0000644000175100001440000001021413431000472017457 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_STATUSBAR #define IGRAPH_STATUSBAR #include "igraph_decls.h" __BEGIN_DECLS /** * \section about_status_handlers Status reporting * * * In addition to the possibility of reporting the progress of an * igraph computation via \ref igraph_progress(), it is also possible * to report simple status messages from within igraph functions, * without having to judge how much of the computation was performed * already. For this one needs to install a status handler function. * * * * Status handler functions must be of type \ref igraph_status_handler_t * and they can be install by a call to \ref igraph_set_status_handler(). * Currently there is a simple predefined status handler function, * called \ref igraph_status_handler_stderr(), but the user can define * new ones. * * * * Igraph functions report their status via a call to the * \ref IGRAPH_STATUS() or the \ref IGRAPH_STATUSF() macro. * */ /** * \typedef igraph_status_handler_t * * The type of the igraph status handler functions * \param message The status message. * \param data Additional context, with user-defined semantics. * Existing igraph functions pass a null pointer here. */ typedef int igraph_status_handler_t(const char *message, void *data); extern igraph_status_handler_t igraph_status_handler_stderr; DECLDIR igraph_status_handler_t * igraph_set_status_handler(igraph_status_handler_t new_handler); DECLDIR int igraph_status(const char *message, void *data); /** * \define IGRAPH_STATUS * Report the status of an igraph function. * * Typically this function is called only a handful of times from * an igraph function. E.g. if an algorithm has three major * steps, then it is logical to call it three times, to * signal the three major steps. * \param message The status message. * \param data Additional context, with user-defined semantics. * Existing igraph functions pass a null pointer here. * \return If the status handler returns with a value other than * \c IGRAPH_SUCCESS, then the function that called this * macro returns as well, with error code * \c IGRAPH_INTERRUPTED. */ #define IGRAPH_STATUS(message, data) \ do { \ if (igraph_status((message), (data)) != IGRAPH_SUCCESS) { \ IGRAPH_FINALLY_FREE(); \ return IGRAPH_INTERRUPTED; \ } \ } while (0) DECLDIR int igraph_statusf(const char *message, void *data, ...); /** * \define IGRAPH_STATUSF * Report the status from an igraph function * * This is the more flexible version of \ref IGRAPH_STATUS(), * having a printf-like syntax. As this macro takes variable * number of arguments, they must be all supplied as a single * argument, enclosed in parentheses. Then \ref igraph_statusf() * is called with the given arguments. * \param args The arguments to pass to \ref igraph_statusf(). * \return If the status handler returns with a value other than * \c IGRAPH_SUCCESS, then the function that called this * macro returns as well, with error code * \c IGRAPH_INTERRUPTED. */ #define IGRAPH_STATUSF(args) \ do { \ if (igraph_statusf args != IGRAPH_SUCCESS) { \ IGRAPH_FINALLY_FREE(); \ return IGRAPH_INTERRUPTED; \ } \ } while (0) __END_DECLS #endif igraph/src/include/igraph_interface.h0000644000175100001440000000774513431000472017426 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_INTERFACE_H #define IGRAPH_INTERFACE_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_iterators.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Interface */ /* -------------------------------------------------- */ DECLDIR int igraph_empty(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed); DECLDIR int igraph_empty_attrs(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, void *attr); DECLDIR int igraph_destroy(igraph_t *graph); DECLDIR int igraph_copy(igraph_t *to, const igraph_t *from); DECLDIR int igraph_add_edges(igraph_t *graph, const igraph_vector_t *edges, void *attr); DECLDIR int igraph_add_vertices(igraph_t *graph, igraph_integer_t nv, void *attr); DECLDIR int igraph_delete_edges(igraph_t *graph, igraph_es_t edges); DECLDIR int igraph_delete_vertices(igraph_t *graph, const igraph_vs_t vertices); DECLDIR int igraph_delete_vertices_idx(igraph_t *graph, const igraph_vs_t vertices, igraph_vector_t *idx, igraph_vector_t *invidx); DECLDIR igraph_integer_t igraph_vcount(const igraph_t *graph); DECLDIR igraph_integer_t igraph_ecount(const igraph_t *graph); DECLDIR int igraph_neighbors(const igraph_t *graph, igraph_vector_t *neis, igraph_integer_t vid, igraph_neimode_t mode); DECLDIR igraph_bool_t igraph_is_directed(const igraph_t *graph); DECLDIR int igraph_degree(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_edge(const igraph_t *graph, igraph_integer_t eid, igraph_integer_t *from, igraph_integer_t *to); DECLDIR int igraph_edges(const igraph_t *graph, igraph_es_t eids, igraph_vector_t *edges); DECLDIR int igraph_get_eid(const igraph_t *graph, igraph_integer_t *eid, igraph_integer_t from, igraph_integer_t to, igraph_bool_t directed, igraph_bool_t error); DECLDIR int igraph_get_eids(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error); DECLDIR int igraph_get_eids_multi(const igraph_t *graph, igraph_vector_t *eids, const igraph_vector_t *pairs, const igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t error); DECLDIR int igraph_adjacent(const igraph_t *graph, igraph_vector_t *eids, igraph_integer_t vid, igraph_neimode_t mode); /* deprecated */ DECLDIR int igraph_incident(const igraph_t *graph, igraph_vector_t *eids, igraph_integer_t vid, igraph_neimode_t mode); #define IGRAPH_FROM(g,e) ((igraph_integer_t)(VECTOR((g)->from)[(long int)(e)])) #define IGRAPH_TO(g,e) ((igraph_integer_t)(VECTOR((g)->to) [(long int)(e)])) #define IGRAPH_OTHER(g,e,v) \ ((igraph_integer_t)(IGRAPH_TO(g,(e))==(v) ? IGRAPH_FROM((g),(e)) : IGRAPH_TO((g),(e)))) __END_DECLS #endif igraph/src/include/igraph_matrix.h0000644000175100001440000000534113431000472016760 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MATRIX_H #define IGRAPH_MATRIX_H #include "igraph_decls.h" #include "igraph_vector.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Matrix, very similar to vector */ /* -------------------------------------------------- */ #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_INT #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_LONG #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_COMPLEX #include "igraph_pmt.h" #include "igraph_matrix_pmt.h" #include "igraph_pmt_off.h" #undef BASE_COMPLEX #define IGRAPH_MATRIX_NULL { IGRAPH_VECTOR_NULL, 0, 0 } #define IGRAPH_MATRIX_INIT_FINALLY(m, nr, nc) \ do { IGRAPH_CHECK(igraph_matrix_init(m, nr, nc)); \ IGRAPH_FINALLY(igraph_matrix_destroy, m); } while (0) /** * \ingroup matrix * \define MATRIX * \brief Accessing an element of a matrix. * * Note that there are no range checks right now. * This functionality might be redefined as a proper function later. * \param m The matrix object. * \param i The index of the row, starting with zero. * \param j The index of the column, starting with zero. * * Time complexity: O(1). */ #define MATRIX(m,i,j) ((m).data.stor_begin[(m).nrow*(j)+(i)]) igraph_bool_t igraph_matrix_all_e_tol(const igraph_matrix_t *lhs, const igraph_matrix_t *rhs, igraph_real_t tol); int igraph_matrix_zapsmall(igraph_matrix_t *m, igraph_real_t tol); __END_DECLS #endif igraph/src/include/igraph_cliques.h0000644000175100001440000001045613431000472017124 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_CLIQUES_H #define IGRAPH_CLIQUES_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Cliques, maximal independent vertex sets */ /* -------------------------------------------------- */ DECLDIR int igraph_maximal_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_maximal_cliques_file(const igraph_t *graph, FILE *outfile, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_maximal_cliques_count(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_maximal_cliques_subset(const igraph_t *graph, igraph_vector_int_t *subset, igraph_vector_ptr_t *res, igraph_integer_t *no, FILE *outfile, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_clique_size_hist(const igraph_t *graph, igraph_vector_t *hist, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_largest_cliques(const igraph_t *graph, igraph_vector_ptr_t *cliques); DECLDIR int igraph_clique_number(const igraph_t *graph, igraph_integer_t *no); DECLDIR int igraph_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res, igraph_real_t min_weight, igraph_real_t max_weight, igraph_bool_t maximal); DECLDIR int igraph_largest_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res); DECLDIR int igraph_weighted_clique_number(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_real_t *res); DECLDIR int igraph_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size); DECLDIR int igraph_largest_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res); DECLDIR int igraph_maximal_independent_vertex_sets(const igraph_t *graph, igraph_vector_ptr_t *res); DECLDIR int igraph_independence_number(const igraph_t *graph, igraph_integer_t *no); /** * \typedef igraph_clique_handler_t * \brief Type of clique handler functions * * Callback type, called when a clique was found. * * See the details at the documentation of \ref * igraph_cliques_callback(). * * \param clique The current clique. Destroying and freeing * this vector is left to the user. * \param arg This extra argument was passed to \ref * igraph_cliques_callback() when it was called. * \return Boolean, whether to continue with the clique search. */ typedef igraph_bool_t igraph_clique_handler_t(igraph_vector_t *clique, void *arg); DECLDIR int igraph_cliques_callback(const igraph_t *graph, igraph_integer_t min_size, igraph_integer_t max_size, igraph_clique_handler_t *cliquehandler_fn, void *arg); __END_DECLS #endif igraph/src/include/igraph_nongraph.h0000644000175100001440000000757113431000472017277 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_NONGRAPH_H #define IGRAPH_NONGRAPH_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_matrix.h" #include "igraph_types.h" #include "igraph_vector.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Other, not graph related */ /* -------------------------------------------------- */ /** * \struct igraph_plfit_result_t * \brief Result of fitting a power-law distribution to a vector * * This data structure contains the result of \ref igraph_power_law_fit(), * which tries to fit a power-law distribution to a vector of numbers. The * structure contains the following members: * * \member continuous Whether the fitted power-law distribution was continuous * or discrete. * \member alpha The exponent of the fitted power-law distribution. * \member xmin The minimum value from which the power-law distribution was * fitted. In other words, only the values larger than \c xmin * were used from the input vector. * \member L The log-likelihood of the fitted parameters; in other words, * the probability of observing the input vector given the * parameters. * \member D The test statistic of a Kolmogorov-Smirnov test that compares * the fitted distribution with the input vector. Smaller scores * denote better fit. * \member p The p-value of the Kolmogorov-Smirnov test. Small p-values * (less than 0.05) indicate that the test rejected the hypothesis * that the original data could have been drawn from the fitted * power-law distribution. */ typedef struct igraph_plfit_result_t { igraph_bool_t continuous; double alpha; double xmin; double L; double D; double p; } igraph_plfit_result_t; DECLDIR int igraph_running_mean(const igraph_vector_t *data, igraph_vector_t *res, igraph_integer_t binwidth); DECLDIR int igraph_fisher_yates_shuffle(igraph_vector_t *seq); DECLDIR int igraph_random_sample(igraph_vector_t *res, igraph_real_t l, igraph_real_t h, igraph_integer_t length); DECLDIR int igraph_convex_hull(const igraph_matrix_t *data, igraph_vector_t *resverts, igraph_matrix_t *rescoords); DECLDIR int igraph_zeroin(igraph_real_t *ax, igraph_real_t *bx, igraph_real_t (*f)(igraph_real_t x, void *info), void *info, igraph_real_t *Tol, int *Maxit, igraph_real_t *res); DECLDIR int igraph_bfgs(igraph_vector_t *b, igraph_real_t *Fmin, igraph_scalar_function_t fminfn, igraph_vector_function_t fmingr, int maxit, int trace, igraph_real_t abstol, igraph_real_t reltol, int nREPORT, void *ex, igraph_integer_t *fncount, igraph_integer_t *grcount); DECLDIR int igraph_power_law_fit(const igraph_vector_t* vector, igraph_plfit_result_t* result, igraph_real_t xmin, igraph_bool_t force_continuous); __END_DECLS #endif igraph/src/include/igraph_components.h0000644000175100001440000000440513431000472017641 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_COMPONENTS_H #define IGRAPH_COMPONENTS_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_datatype.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Components */ /* -------------------------------------------------- */ DECLDIR int igraph_clusters(const igraph_t *graph, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t *no, igraph_connectedness_t mode); DECLDIR int igraph_is_connected(const igraph_t *graph, igraph_bool_t *res, igraph_connectedness_t mode); DECLDIR void igraph_decompose_destroy(igraph_vector_ptr_t *complist); DECLDIR int igraph_decompose(const igraph_t *graph, igraph_vector_ptr_t *components, igraph_connectedness_t mode, long int maxcompno, long int minelements); DECLDIR int igraph_articulation_points(const igraph_t *graph, igraph_vector_t *res); DECLDIR int igraph_biconnected_components(const igraph_t *graph, igraph_integer_t *no, igraph_vector_ptr_t *tree_edges, igraph_vector_ptr_t *component_edges, igraph_vector_ptr_t *components, igraph_vector_t *articulation_points); __END_DECLS #endif igraph/src/include/igraph_graphlets.h0000644000175100001440000000332213431000472017442 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_GRAPHLETS_H #define IGRAPH_GRAPHLETS_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_vector_ptr.h" #include "igraph_interface.h" __BEGIN_DECLS DECLDIR int igraph_graphlets_candidate_basis(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_ptr_t *cliques, igraph_vector_t *thresholds); DECLDIR int igraph_graphlets_project(const igraph_t *graph, const igraph_vector_t *weights, const igraph_vector_ptr_t *cliques, igraph_vector_t *Mu, igraph_bool_t startMu, int niter); DECLDIR int igraph_graphlets(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_ptr_t *cliques, igraph_vector_t *Mu, int niter); __END_DECLS #endif igraph/src/include/igraph_pmt.h0000644000175100001440000000740013431000472016252 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define CONCAT2x(a,b) a ## _ ## b #define CONCAT2(a,b) CONCAT2x(a,b) #define CONCAT3x(a,b,c) a ## _ ## b ## _ ## c #define CONCAT3(a,b,c) CONCAT3x(a,b,c) #define CONCAT4x(a,b,c,d) a ## _ ## b ## _ ## c ## _ ## d #define CONCAT4(a,b,c,d) CONCAT4x(a,b,c,d) #if defined(BASE_IGRAPH_REAL) #define BASE igraph_real_t #define SHORT #define OUT_FORMAT "%G" #define PRINTFUNC(val) igraph_real_printf(val) #define FPRINTFUNC(file, val) igraph_real_fprintf(file, val) #define ZERO 0.0 #define ONE 1.0 #define MULTIPLICITY 1 #elif defined(BASE_FLOAT) #define BASE float #define SHORT float #define OUT_FORMAT "%f" #define ZERO 0.0F #define ONE 1.0F #define MULTIPLICITY 1 #elif defined(BASE_LONG) #define BASE long #define SHORT long #define OUT_FORMAT "%ld" #define ZERO 0L #define ONE 1L #define MULTIPLICITY 1 #elif defined(BASE_CHAR) #define BASE char #define SHORT char #define OUT_FORMAT "%d" #define ZERO 0 #define ONE 1 #define MULTIPLICITY 1 #elif defined(BASE_BOOL) #define BASE igraph_bool_t #define SHORT bool #define OUT_FORMAT "%d" #define ZERO 0 #define ONE 1 #define MULTIPLICITY 1 #elif defined(BASE_INT) #define BASE int #define SHORT int #define OUT_FORMAT "%d" #define ZERO 0 #define ONE 1 #define MULTIPLICITY 1 #elif defined(BASE_LIMB) #define BASE limb_t #define SHORT limb #define ZERO 0 #define ONE 1 #define MULTIPLICITY 1 #define UNSIGNED 1 #elif defined(BASE_PTR) #define BASE void* #define SHORT ptr #define ZERO 0 #define MULTIPLICITY 1 #elif defined(BASE_COMPLEX) #undef complex #define BASE igraph_complex_t #define SHORT complex #define ZERO igraph_complex(0,0) #define ONE {{1.0,0.0}} #define MULTIPLICITY 2 #define NOTORDERED 1 #define NOABS 1 #define SUM(a,b,c) ((a) = igraph_complex_add((b),(c))) #define DIFF(a,b,c) ((a) = igraph_complex_sub((b),(c))) #define PROD(a,b,c) ((a) = igraph_complex_mul((b),(c))) #define DIV(a,b,c) ((a) = igraph_complex_div((b),(c))) #define EQ(a,b) IGRAPH_COMPLEX_EQ((a),(b)) #define SQ(a) IGRAPH_REAL(igraph_complex_mul((a),(a))) #else #error unknown BASE_ directive #endif #if defined(BASE_IGRAPH_REAL) # define FUNCTION(dir,name) CONCAT2(dir,name) # define TYPE(dir) CONCAT2(dir,t) #elif defined(BASE_BOOL) /* Special case because stdbool.h defines bool as a macro to _Bool which would * screw things up */ # define FUNCTION(a,c) CONCAT3x(a,bool,c) # define TYPE(dir) CONCAT3x(dir,bool,t) #else # define FUNCTION(a,c) CONCAT3(a,SHORT,c) # define TYPE(dir) CONCAT3(dir,SHORT,t) #endif #if defined(HEAP_TYPE_MIN) #define HEAPMORE < #define HEAPMOREEQ <= #define HEAPLESS > #define HEAPLESSEQ >= #undef FUNCTION #undef TYPE #if defined(BASE_IGRAPH_REAL) #define FUNCTION(dir,name) CONCAT3(dir,min,name) #define TYPE(dir) CONCAT3(dir,min,t) #else #define FUNCTION(a,c) CONCAT4(a,min,SHORT,c) #define TYPE(dir) CONCAT4(dir,min,SHORT,t) #endif #endif #if defined(HEAP_TYPE_MAX) #define HEAPMORE > #define HEAPMOREEQ >= #define HEAPLESS < #define HEAPLESSEQ <= #endif igraph/src/include/igraph_sparsemat.h0000644000175100001440000002371513431000472017460 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_SPARSEMAT_H #define IGRAPH_SPARSEMAT_H #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_datatype.h" #include "igraph_arpack.h" #include struct cs_di_sparse; struct cs_di_symbolic; struct cs_di_numeric; typedef struct { struct cs_di_sparse *cs; } igraph_sparsemat_t; typedef struct { struct cs_di_symbolic *symbolic; } igraph_sparsemat_symbolic_t; typedef struct { struct cs_di_numeric *numeric; } igraph_sparsemat_numeric_t; typedef enum { IGRAPH_SPARSEMAT_TRIPLET, IGRAPH_SPARSEMAT_CC } igraph_sparsemat_type_t; typedef struct { igraph_sparsemat_t *mat; int pos; int col; } igraph_sparsemat_iterator_t; int igraph_sparsemat_init(igraph_sparsemat_t *A, int rows, int cols, int nzmax); int igraph_sparsemat_copy(igraph_sparsemat_t *to, const igraph_sparsemat_t *from); void igraph_sparsemat_destroy(igraph_sparsemat_t *A); int igraph_sparsemat_realloc(igraph_sparsemat_t *A, int nzmax); long int igraph_sparsemat_nrow(const igraph_sparsemat_t *A); long int igraph_sparsemat_ncol(const igraph_sparsemat_t *B); igraph_sparsemat_type_t igraph_sparsemat_type(const igraph_sparsemat_t *A); igraph_bool_t igraph_sparsemat_is_triplet(const igraph_sparsemat_t *A); igraph_bool_t igraph_sparsemat_is_cc(const igraph_sparsemat_t *A); int igraph_sparsemat_permute(const igraph_sparsemat_t *A, const igraph_vector_int_t *p, const igraph_vector_int_t *q, igraph_sparsemat_t *res); int igraph_sparsemat_index(const igraph_sparsemat_t *A, const igraph_vector_int_t *p, const igraph_vector_int_t *q, igraph_sparsemat_t *res, igraph_real_t *constres); int igraph_sparsemat_entry(igraph_sparsemat_t *A, int row, int col, igraph_real_t elem); int igraph_sparsemat_compress(const igraph_sparsemat_t *A, igraph_sparsemat_t *res); int igraph_sparsemat_transpose(const igraph_sparsemat_t *A, igraph_sparsemat_t *res, int values); igraph_bool_t igraph_sparsemat_is_symmetric(const igraph_sparsemat_t *A); int igraph_sparsemat_dupl(igraph_sparsemat_t *A); int igraph_sparsemat_fkeep(igraph_sparsemat_t *A, int (*fkeep)(int, int, igraph_real_t, void*), void *other); int igraph_sparsemat_dropzeros(igraph_sparsemat_t *A); int igraph_sparsemat_droptol(igraph_sparsemat_t *A, igraph_real_t tol); int igraph_sparsemat_multiply(const igraph_sparsemat_t *A, const igraph_sparsemat_t *B, igraph_sparsemat_t *res); int igraph_sparsemat_add(const igraph_sparsemat_t *A, const igraph_sparsemat_t *B, igraph_real_t alpha, igraph_real_t beta, igraph_sparsemat_t *res); int igraph_sparsemat_gaxpy(const igraph_sparsemat_t *A, const igraph_vector_t *x, igraph_vector_t *res); int igraph_sparsemat_lsolve(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_ltsolve(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_usolve(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_utsolve(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_cholsol(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res, int order); int igraph_sparsemat_lusol(const igraph_sparsemat_t *A, const igraph_vector_t *b, igraph_vector_t *res, int order, igraph_real_t tol); int igraph_sparsemat_print(const igraph_sparsemat_t *A, FILE *outstream); int igraph_sparsemat_eye(igraph_sparsemat_t *A, int n, int nzmax, igraph_real_t value, igraph_bool_t compress); int igraph_sparsemat_diag(igraph_sparsemat_t *A, int nzmax, const igraph_vector_t *values, igraph_bool_t compress); int igraph_sparsemat(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed); int igraph_weighted_sparsemat(igraph_t *graph, const igraph_sparsemat_t *A, igraph_bool_t directed, const char *attr, igraph_bool_t loops); int igraph_get_sparsemat(const igraph_t *graph, igraph_sparsemat_t *res); int igraph_matrix_as_sparsemat(igraph_sparsemat_t *res, const igraph_matrix_t *mat, igraph_real_t tol); int igraph_sparsemat_as_matrix(igraph_matrix_t *res, const igraph_sparsemat_t *spmat); typedef enum { IGRAPH_SPARSEMAT_SOLVE_LU, IGRAPH_SPARSEMAT_SOLVE_QR } igraph_sparsemat_solve_t; int igraph_sparsemat_arpack_rssolve(const igraph_sparsemat_t *A, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_sparsemat_solve_t solvemethod); int igraph_sparsemat_arpack_rnsolve(const igraph_sparsemat_t *A, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_matrix_t *values, igraph_matrix_t *vectors); int igraph_sparsemat_lu(const igraph_sparsemat_t *A, const igraph_sparsemat_symbolic_t *dis, igraph_sparsemat_numeric_t *din, double tol); int igraph_sparsemat_qr(const igraph_sparsemat_t *A, const igraph_sparsemat_symbolic_t *dis, igraph_sparsemat_numeric_t *din); int igraph_sparsemat_luresol(const igraph_sparsemat_symbolic_t *dis, const igraph_sparsemat_numeric_t *din, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_qrresol(const igraph_sparsemat_symbolic_t *dis, const igraph_sparsemat_numeric_t *din, const igraph_vector_t *b, igraph_vector_t *res); int igraph_sparsemat_symbqr(long int order, const igraph_sparsemat_t *A, igraph_sparsemat_symbolic_t *dis); int igraph_sparsemat_symblu(long int order, const igraph_sparsemat_t *A, igraph_sparsemat_symbolic_t *dis); void igraph_sparsemat_symbolic_destroy(igraph_sparsemat_symbolic_t *dis); void igraph_sparsemat_numeric_destroy(igraph_sparsemat_numeric_t *din); igraph_real_t igraph_sparsemat_max(igraph_sparsemat_t *A); igraph_real_t igraph_sparsemat_min(igraph_sparsemat_t *A); int igraph_sparsemat_minmax(igraph_sparsemat_t *A, igraph_real_t *min, igraph_real_t *max); long int igraph_sparsemat_count_nonzero(igraph_sparsemat_t *A); long int igraph_sparsemat_count_nonzerotol(igraph_sparsemat_t *A, igraph_real_t tol); int igraph_sparsemat_rowsums(const igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_colsums(const igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_rowmins(igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_colmins(igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_rowmaxs(igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_colmaxs(igraph_sparsemat_t *A, igraph_vector_t *res); int igraph_sparsemat_which_min_rows(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos); int igraph_sparsemat_which_min_cols(igraph_sparsemat_t *A, igraph_vector_t *res, igraph_vector_int_t *pos); int igraph_sparsemat_scale(igraph_sparsemat_t *A, igraph_real_t by); int igraph_sparsemat_add_rows(igraph_sparsemat_t *A, long int n); int igraph_sparsemat_add_cols(igraph_sparsemat_t *A, long int n); int igraph_sparsemat_resize(igraph_sparsemat_t *A, long int nrow, long int ncol, int nzmax); int igraph_sparsemat_nonzero_storage(const igraph_sparsemat_t *A); int igraph_sparsemat_getelements(const igraph_sparsemat_t *A, igraph_vector_int_t *i, igraph_vector_int_t *j, igraph_vector_t *x); int igraph_sparsemat_getelements_sorted(const igraph_sparsemat_t *A, igraph_vector_int_t *i, igraph_vector_int_t *j, igraph_vector_t *x); int igraph_sparsemat_scale_rows(igraph_sparsemat_t *A, const igraph_vector_t *fact); int igraph_sparsemat_scale_cols(igraph_sparsemat_t *A, const igraph_vector_t *fact); int igraph_sparsemat_multiply_by_dense(const igraph_sparsemat_t *A, const igraph_matrix_t *B, igraph_matrix_t *res); int igraph_sparsemat_dense_multiply(const igraph_matrix_t *A, const igraph_sparsemat_t *B, igraph_matrix_t *res); int igraph_i_sparsemat_view(igraph_sparsemat_t *A, int nzmax, int m, int n, int *p, int *i, double *x, int nz); int igraph_sparsemat_sort(const igraph_sparsemat_t *A, igraph_sparsemat_t *sorted); int igraph_sparsemat_nzmax(const igraph_sparsemat_t *A); int igraph_sparsemat_neg(igraph_sparsemat_t *A); int igraph_sparsemat_iterator_init(igraph_sparsemat_iterator_t *it, igraph_sparsemat_t *sparsemat); int igraph_sparsemat_iterator_reset(igraph_sparsemat_iterator_t *it); igraph_bool_t igraph_sparsemat_iterator_end(const igraph_sparsemat_iterator_t *it); int igraph_sparsemat_iterator_row(const igraph_sparsemat_iterator_t *it); int igraph_sparsemat_iterator_col(const igraph_sparsemat_iterator_t *it); int igraph_sparsemat_iterator_idx(const igraph_sparsemat_iterator_t *it); igraph_real_t igraph_sparsemat_iterator_get(const igraph_sparsemat_iterator_t *it); int igraph_sparsemat_iterator_next(igraph_sparsemat_iterator_t *it); #endif igraph/src/include/igraph_topology.h0000644000175100001440000002674413431000472017342 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_TOPOLOGY_H #define IGRAPH_TOPOLOGY_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Degree sequences */ /* -------------------------------------------------- */ DECLDIR int igraph_is_degree_sequence(const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res); DECLDIR int igraph_is_graphical_degree_sequence(const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res); /* -------------------------------------------------- */ /* Directed acyclic graphs */ /* -------------------------------------------------- */ DECLDIR int igraph_topological_sorting(const igraph_t *graph, igraph_vector_t *res, igraph_neimode_t mode); DECLDIR int igraph_is_dag(const igraph_t *graph, igraph_bool_t *res); DECLDIR int igraph_transitive_closure_dag(const igraph_t *graph, igraph_t *closure); /* -------------------------------------------------- */ /* Graph isomorphisms */ /* -------------------------------------------------- */ /* Common functions */ DECLDIR int igraph_permute_vertices(const igraph_t *graph, igraph_t *res, const igraph_vector_t *permutation); /* Generic interface */ DECLDIR int igraph_isomorphic(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso); DECLDIR int igraph_subisomorphic(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso); /* LAD */ DECLDIR int igraph_subisomorphic_lad(const igraph_t *pattern, const igraph_t *target, igraph_vector_ptr_t *domains, igraph_bool_t *iso, igraph_vector_t *map, igraph_vector_ptr_t *maps, igraph_bool_t induced, int time_limit); /* VF2 family*/ /** * \typedef igraph_isohandler_t * Callback type, called when an isomorphism was found * * See the details at the documentation of \ref * igraph_isomorphic_function_vf2(). * \param map12 The mapping from the first graph to the second. * \param map21 The mapping from the second graph to the first, the * inverse of \p map12 basically. * \param arg This extra argument was passed to \ref * igraph_isomorphic_function_vf2() when it was called. * \return Boolean, whether to continue with the isomorphism search. */ typedef igraph_bool_t igraph_isohandler_t(const igraph_vector_t *map12, const igraph_vector_t *map21, void *arg); /** * \typedef igraph_isocompat_t * Callback type, called to check whether two vertices or edges are compatible * * VF2 (subgraph) isomorphism functions can be restricted by defining * relations on the vertices and/or edges of the graphs, and then checking * whether the vertices (edges) match according to these relations. * * This feature is implemented by two callbacks, one for * vertices, one for edges. Every time igraph tries to match a vertex (edge) * of the first (sub)graph to a vertex of the second graph, the vertex * (edge) compatibility callback is called. The callback returns a * logical value, giving whether the two vertices match. * * Both callback functions are of type \c igraph_isocompat_t. * \param graph1 The first graph. * \param graph2 The second graph. * \param g1_num The id of a vertex or edge in the first graph. * \param g2_num The id of a vertex or edge in the second graph. * \param arg Extra argument to pass to the callback functions. * \return Logical scalar, whether vertex (or edge) \p g1_num in \p graph1 * is compatible with vertex (or edge) \p g2_num in \p graph2. */ typedef igraph_bool_t igraph_isocompat_t(const igraph_t *graph1, const igraph_t *graph2, const igraph_integer_t g1_num, const igraph_integer_t g2_num, void *arg); DECLDIR int igraph_isomorphic_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_isomorphic_function_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isohandler_t *isohandler_fn, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_count_isomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_integer_t *count, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_get_isomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_ptr_t *maps, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_subisomorphic_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_subisomorphic_function_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_t *map12, igraph_vector_t *map21, igraph_isohandler_t *isohandler_fn, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_count_subisomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_integer_t *count, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); DECLDIR int igraph_get_subisomorphisms_vf2(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *vertex_color1, const igraph_vector_int_t *vertex_color2, const igraph_vector_int_t *edge_color1, const igraph_vector_int_t *edge_color2, igraph_vector_ptr_t *maps, igraph_isocompat_t *node_compat_fn, igraph_isocompat_t *edge_compat_fn, void *arg); /* BLISS family */ /** * \struct igraph_bliss_info_t * Information about a BLISS run * * Some secondary information found by the BLISS algorithm is stored * here. It is useful if you wany to study the internal working of the * algorithm. * \member nof_nodes The number of nodes in the search tree. * \member nof_leaf_nodes The number of leaf nodes in the search tree. * \member nof_bad_nodes Number of bad nodes. * \member nof_canupdates Number of canrep updates. * \member nof_generators Number of generators of the automorphism group. * \member max_level Maximum level. * \member group_size The size of the automorphism group of the graph, * given as a string. It should be deallocated via * \ref igraph_free() if not needed any more. * * See http://www.tcs.hut.fi/Software/bliss/index.html * for details about the algorithm and these parameters. */ typedef struct igraph_bliss_info_t { unsigned long nof_nodes; unsigned long nof_leaf_nodes; unsigned long nof_bad_nodes; unsigned long nof_canupdates; unsigned long nof_generators; unsigned long max_level; char *group_size; } igraph_bliss_info_t; /** * \typedef igraph_bliss_sh_t * Splitting heuristics for BLISS * * \enumval IGRAPH_BLISS_F First non-singleton cell. * \enumval IGRAPH_BLISS_FL First largest non-singleton cell. * \enumval IGRAPH_BLISS_FS First smallest non-singleton cell. * \enumval IGRAPH_BLISS_FM First maximally non-trivially connected * non-singleton cell. * \enumval IGRAPH_BLISS_FLM Largest maximally non-trivially connected * non-singleton cell. * \enumval IGRAPH_BLISS_FSM Smallest maximally non-trivially * connected non-singletion cell. */ typedef enum { IGRAPH_BLISS_F=0, IGRAPH_BLISS_FL, IGRAPH_BLISS_FS, IGRAPH_BLISS_FM, IGRAPH_BLISS_FLM, IGRAPH_BLISS_FSM } igraph_bliss_sh_t; DECLDIR int igraph_canonical_permutation(const igraph_t *graph, const igraph_vector_int_t *colors, igraph_vector_t *labeling, igraph_bliss_sh_t sh, igraph_bliss_info_t *info); DECLDIR int igraph_isomorphic_bliss(const igraph_t *graph1, const igraph_t *graph2, const igraph_vector_int_t *colors1, const igraph_vector_int_t *colors2, igraph_bool_t *iso, igraph_vector_t *map12, igraph_vector_t *map21, igraph_bliss_sh_t sh, igraph_bliss_info_t *info1, igraph_bliss_info_t *info2); DECLDIR int igraph_automorphisms(const igraph_t *graph, const igraph_vector_int_t *colors, igraph_bliss_sh_t sh, igraph_bliss_info_t *info); DECLDIR int igraph_automorphism_group(const igraph_t *graph, const igraph_vector_int_t *colors, igraph_vector_ptr_t *generators, igraph_bliss_sh_t sh, igraph_bliss_info_t *info); /* Functions for 3-4 graphs */ DECLDIR int igraph_isomorphic_34(const igraph_t *graph1, const igraph_t *graph2, igraph_bool_t *iso); DECLDIR int igraph_isoclass(const igraph_t *graph, igraph_integer_t *isoclass); DECLDIR int igraph_isoclass_subgraph(const igraph_t *graph, igraph_vector_t *vids, igraph_integer_t *isoclass); DECLDIR int igraph_isoclass_create(igraph_t *graph, igraph_integer_t size, igraph_integer_t number, igraph_bool_t directed); __END_DECLS #endif igraph/src/include/igraph_stack.h0000644000175100001440000000402313431000472016555 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_STACK_H #define IGRAPH_STACK_H #include "igraph_decls.h" #include "igraph_types.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Plain stack */ /* -------------------------------------------------- */ #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_INT #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_PTR #include "igraph_pmt.h" #include "igraph_stack_pmt.h" #include "igraph_pmt_off.h" #undef BASE_PTR #define IGRAPH_STACK_NULL { 0,0,0 } void igraph_stack_ptr_free_all(igraph_stack_ptr_t* s); void igraph_stack_ptr_destroy_all(igraph_stack_ptr_t* s); __END_DECLS #endif igraph/src/include/igraph_adjlist.h0000644000175100001440000002156113431000472017110 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_ADJLIST_H #define IGRAPH_ADJLIST_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" __BEGIN_DECLS typedef struct igraph_adjlist_t { igraph_integer_t length; igraph_vector_int_t *adjs; } igraph_adjlist_t; DECLDIR int igraph_adjlist_init(const igraph_t *graph, igraph_adjlist_t *al, igraph_neimode_t mode); DECLDIR int igraph_adjlist_init_empty(igraph_adjlist_t *al, igraph_integer_t no_of_nodes); DECLDIR igraph_integer_t igraph_adjlist_size(const igraph_adjlist_t *al); DECLDIR int igraph_adjlist_init_complementer(const igraph_t *graph, igraph_adjlist_t *al, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR void igraph_adjlist_destroy(igraph_adjlist_t *al); DECLDIR void igraph_adjlist_clear(igraph_adjlist_t *al); DECLDIR void igraph_adjlist_sort(igraph_adjlist_t *al); DECLDIR int igraph_adjlist_simplify(igraph_adjlist_t *al); DECLDIR int igraph_adjlist_remove_duplicate(const igraph_t *graph, igraph_adjlist_t *al); DECLDIR int igraph_adjlist_print(const igraph_adjlist_t *al); DECLDIR int igraph_adjlist_fprint(const igraph_adjlist_t *al, FILE *outfile); DECLDIR igraph_bool_t igraph_adjlist_has_edge(igraph_adjlist_t* al, igraph_integer_t from, igraph_integer_t to, igraph_bool_t directed); DECLDIR int igraph_adjlist_replace_edge(igraph_adjlist_t* al, igraph_integer_t from, igraph_integer_t oldto, igraph_integer_t newto, igraph_bool_t directed); /* igraph_vector_int_t *igraph_adjlist_get(const igraph_adjlist_t *al, */ /* igraph_integer_t no); */ /** * \define igraph_adjlist_get * Query a vector in an adjlist * * Returns a pointer to an igraph_vector_int_t object from an * adjacency list. The vector can be modified as desired. * \param al The adjacency list object. * \param no The vertex of which the vertex of adjacent vertices are * returned. * \return Pointer to the igraph_vector_int_t object. * * Time complexity: O(1). */ #define igraph_adjlist_get(al,no) (&(al)->adjs[(long int)(no)]) DECLDIR int igraph_adjlist(igraph_t *graph, const igraph_adjlist_t *adjlist, igraph_neimode_t mode, igraph_bool_t duplicate); typedef struct igraph_inclist_t { igraph_integer_t length; igraph_vector_int_t *incs; } igraph_inclist_t; DECLDIR int igraph_inclist_init(const igraph_t *graph, igraph_inclist_t *il, igraph_neimode_t mode); DECLDIR int igraph_inclist_init_empty(igraph_inclist_t *il, igraph_integer_t n); DECLDIR void igraph_inclist_destroy(igraph_inclist_t *il); DECLDIR void igraph_inclist_clear(igraph_inclist_t *il); DECLDIR int igraph_inclist_remove_duplicate(const igraph_t *graph, igraph_inclist_t *il); DECLDIR int igraph_inclist_print(const igraph_inclist_t *il); DECLDIR int igraph_inclist_fprint(const igraph_inclist_t *il, FILE *outfile); /** * \define igraph_inclist_get * Query a vector in an incidence list * * Returns a pointer to an igraph_vector_int_t object from an * incidence list containing edge ids. The vector can be modified, * resized, etc. as desired. * \param il Pointer to the incidence list. * \param no The vertex for which the incident edges are returned. * \return Pointer to an igraph_vector_int_t object. * * Time complexity: O(1). */ #define igraph_inclist_get(il,no) (&(il)->incs[(long int)(no)]) typedef struct igraph_lazy_adjlist_t { const igraph_t *graph; igraph_integer_t length; igraph_vector_t **adjs; igraph_neimode_t mode; igraph_lazy_adlist_simplify_t simplify; } igraph_lazy_adjlist_t; DECLDIR int igraph_lazy_adjlist_init(const igraph_t *graph, igraph_lazy_adjlist_t *al, igraph_neimode_t mode, igraph_lazy_adlist_simplify_t simplify); DECLDIR void igraph_lazy_adjlist_destroy(igraph_lazy_adjlist_t *al); DECLDIR void igraph_lazy_adjlist_clear(igraph_lazy_adjlist_t *al); /* igraph_vector_t *igraph_lazy_adjlist_get(igraph_lazy_adjlist_t *al, */ /* igraph_integer_t no); */ /** * \define igraph_lazy_adjlist_get * Query neighbor vertices * * If the function is called for the first time for a vertex then the * result is stored in the adjacency list and no further query * operations are needed when the neighbors of the same vertex are * queried again. * \param al The lazy adjacency list. * \param no The vertex id to query. * \return Pointer to a vector. It is allowed to modify it and * modification does not affect the original graph. * * Time complexity: O(d), the number of neighbor vertices for the * first time, O(1) for subsequent calls. */ #define igraph_lazy_adjlist_get(al,no) \ ((al)->adjs[(long int)(no)] != 0 ? ((al)->adjs[(long int)(no)]) : \ (igraph_lazy_adjlist_get_real(al, no))) DECLDIR igraph_vector_t *igraph_lazy_adjlist_get_real(igraph_lazy_adjlist_t *al, igraph_integer_t no); typedef struct igraph_lazy_inclist_t { const igraph_t *graph; igraph_integer_t length; igraph_vector_t **incs; igraph_neimode_t mode; } igraph_lazy_inclist_t; DECLDIR int igraph_lazy_inclist_init(const igraph_t *graph, igraph_lazy_inclist_t *il, igraph_neimode_t mode); DECLDIR void igraph_lazy_inclist_destroy(igraph_lazy_inclist_t *il); DECLDIR void igraph_lazy_inclist_clear(igraph_lazy_inclist_t *il); /** * \define igraph_lazy_inclist_get * Query incident edges * * If the function is called for the first time for a vertex, then the * result is stored in the incidence list and no further query * operations are needed when the incident edges of the same vertex are * queried again. * \param al The lazy incidence list object. * \param no The vertex id to query. * \return Pointer to a vector. It is allowed to modify it and * modification does not affect the original graph. * * Time complexity: O(d), the number of incident edges for the first * time, O(1) for subsequent calls with the same \p no argument. */ #define igraph_lazy_inclist_get(al,no) \ ((al)->incs[(long int)(no)] != 0 ? ((al)->incs[(long int)(no)]) : \ (igraph_lazy_inclist_get_real(al, no))) DECLDIR igraph_vector_t *igraph_lazy_inclist_get_real(igraph_lazy_inclist_t *al, igraph_integer_t no); /************************************************************************* * DEPRECATED TYPES AND FUNCTIONS */ typedef igraph_inclist_t igraph_adjedgelist_t; DECLDIR int igraph_adjedgelist_init(const igraph_t *graph, igraph_inclist_t *il, igraph_neimode_t mode); DECLDIR void igraph_adjedgelist_destroy(igraph_inclist_t *il); DECLDIR int igraph_adjedgelist_remove_duplicate(const igraph_t *graph, igraph_inclist_t *il); DECLDIR int igraph_adjedgelist_print(const igraph_inclist_t *il, FILE *outfile); /** * \define igraph_adjedgelist_get * Query a vector in an incidence list * * This macro was superseded by \ref igraph_inclist_get() in igraph 0.6. * Please use \ref igraph_inclist_get() instead of this macro. * * * Deprecated in version 0.6. */ #define igraph_adjedgelist_get(ael,no) (&(ael)->incs[(long int)(no)]) typedef igraph_lazy_inclist_t igraph_lazy_adjedgelist_t; DECLDIR int igraph_lazy_adjedgelist_init(const igraph_t *graph, igraph_lazy_inclist_t *il, igraph_neimode_t mode); DECLDIR void igraph_lazy_adjedgelist_destroy(igraph_lazy_inclist_t *il); /** * \define igraph_lazy_adjedgelist_get * Query a vector in a lazy incidence list * * This macro was superseded by \ref igraph_lazy_inclist_get() in igraph 0.6. * Please use \ref igraph_lazy_inclist_get() instead of this macro. * * * Deprecated in version 0.6. */ #define igraph_lazy_adjedgelist_get(al,no) \ ((al)->incs[(long int)(no)] != 0 ? ((al)->incs[(long int)(no)]) : \ (igraph_lazy_adjedgelist_get_real(al, no))) DECLDIR igraph_vector_t *igraph_lazy_adjedgelist_get_real(igraph_lazy_inclist_t *al, igraph_integer_t no); __END_DECLS #endif igraph/src/include/igraph_constructors.h0000644000175100001440000000664113431000472020230 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_CONSTRUCTORS_H #define IGRAPH_CONSTRUCTORS_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_matrix.h" #include "igraph_datatype.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Constructors, deterministic */ /* -------------------------------------------------- */ DECLDIR int igraph_create(igraph_t *graph, const igraph_vector_t *edges, igraph_integer_t n, igraph_bool_t directed); DECLDIR int igraph_small(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, ...); DECLDIR int igraph_adjacency(igraph_t *graph, igraph_matrix_t *adjmatrix, igraph_adjacency_t mode); DECLDIR int igraph_weighted_adjacency(igraph_t *graph, igraph_matrix_t *adjmatrix, igraph_adjacency_t mode, const char* attr, igraph_bool_t loops); DECLDIR int igraph_star(igraph_t *graph, igraph_integer_t n, igraph_star_mode_t mode, igraph_integer_t center); DECLDIR int igraph_lattice(igraph_t *graph, const igraph_vector_t *dimvector, igraph_integer_t nei, igraph_bool_t directed, igraph_bool_t mutual, igraph_bool_t circular); DECLDIR int igraph_ring(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, igraph_bool_t mutual, igraph_bool_t circular); DECLDIR int igraph_tree(igraph_t *graph, igraph_integer_t n, igraph_integer_t children, igraph_tree_mode_t type); DECLDIR int igraph_full(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_full_citation(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed); DECLDIR int igraph_atlas(igraph_t *graph, int number); DECLDIR int igraph_extended_chordal_ring(igraph_t *graph, igraph_integer_t nodes, const igraph_matrix_t *W); DECLDIR int igraph_connect_neighborhood(igraph_t *graph, igraph_integer_t order, igraph_neimode_t mode); DECLDIR int igraph_linegraph(const igraph_t *graph, igraph_t *linegraph); DECLDIR int igraph_de_bruijn(igraph_t *graph, igraph_integer_t m, igraph_integer_t n); DECLDIR int igraph_kautz(igraph_t *graph, igraph_integer_t m, igraph_integer_t n); DECLDIR int igraph_famous(igraph_t *graph, const char *name); DECLDIR int igraph_lcf_vector(igraph_t *graph, igraph_integer_t n, const igraph_vector_t *shifts, igraph_integer_t repeats); DECLDIR int igraph_lcf(igraph_t *graph, igraph_integer_t n, ...); __END_DECLS #endif igraph/src/include/igraph_version.h.in0000644000175100001440000000254213430770210017551 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_VERSION_H #define IGRAPH_VERSION_H #include "igraph_decls.h" __BEGIN_DECLS #define IGRAPH_VERSION "@PACKAGE_VERSION@" #define IGRAPH_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@ #define IGRAPH_VERSION_MINOR @PACKAGE_VERSION_MINOR@ #define IGRAPH_VERSION_PATCH @PACKAGE_VERSION_PATCH@ #define IGRAPH_VERSION_PRERELEASE "@PACKAGE_VERSION_PRERELEASE@" int igraph_version(const char **version_string, int *major, int *minor, int *subminor); __END_DECLS #endif igraph/src/include/igraph_memory.h0000644000175100001440000000266313431000472016770 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REST_MEMORY_H #define REST_MEMORY_H #include #include "igraph_decls.h" __BEGIN_DECLS #define igraph_Calloc(n,t) (t*) calloc( (size_t)(n), sizeof(t) ) #define igraph_Realloc(p,n,t) (t*) realloc((void*)(p), (size_t)((n)*sizeof(t))) #define igraph_Free(p) (free( (void *)(p) ), (p) = NULL) /* #ifndef IGRAPH_NO_CALLOC */ /* # define Calloc igraph_Calloc */ /* # define Realloc igraph_Realloc */ /* # define Free igraph_Free */ /* #endif */ DECLDIR int igraph_free(void *p); DECLDIR void *igraph_malloc(size_t n); __END_DECLS #endif igraph/src/include/igraph_layout.h0000644000175100001440000002675513431000472017005 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_LAYOUT_H #define IGRAPH_LAYOUT_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_matrix.h" #include "igraph_datatype.h" #include "igraph_arpack.h" #include "igraph_iterators.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Layouts */ /* -------------------------------------------------- */ DECLDIR int igraph_layout_random(const igraph_t *graph, igraph_matrix_t *res); DECLDIR int igraph_layout_circle(const igraph_t *graph, igraph_matrix_t *res, igraph_vs_t order); DECLDIR int igraph_layout_star(const igraph_t *graph, igraph_matrix_t *res, igraph_integer_t center, const igraph_vector_t *order); DECLDIR int igraph_layout_grid(const igraph_t *graph, igraph_matrix_t *res, long int width); DECLDIR int igraph_layout_fruchterman_reingold(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, igraph_layout_grid_t grid, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy); DECLDIR int igraph_layout_kamada_kawai(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t epsilon, igraph_real_t kkconst, const igraph_vector_t *weights, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy); DECLDIR int igraph_layout_springs(const igraph_t *graph, igraph_matrix_t *res, igraph_real_t mass, igraph_real_t equil, igraph_real_t k, igraph_real_t repeqdis, igraph_real_t kfr, igraph_bool_t repulse); DECLDIR int igraph_layout_lgl(const igraph_t *graph, igraph_matrix_t *res, igraph_integer_t maxiter, igraph_real_t maxdelta, igraph_real_t area, igraph_real_t coolexp, igraph_real_t repulserad, igraph_real_t cellsize, igraph_integer_t root); DECLDIR int igraph_layout_reingold_tilford(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, const igraph_vector_t *roots, const igraph_vector_t *rootlevel); DECLDIR int igraph_layout_reingold_tilford_circular(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, const igraph_vector_t *roots, const igraph_vector_t *rootlevel); DECLDIR int igraph_layout_sugiyama(const igraph_t *graph, igraph_matrix_t *res, igraph_t *extd_graph, igraph_vector_t *extd_to_orig_eids, const igraph_vector_t* layers, igraph_real_t hgap, igraph_real_t vgap, long int maxiter, const igraph_vector_t *weights); DECLDIR int igraph_layout_random_3d(const igraph_t *graph, igraph_matrix_t *res); DECLDIR int igraph_layout_sphere(const igraph_t *graph, igraph_matrix_t *res); DECLDIR int igraph_layout_grid_3d(const igraph_t *graph, igraph_matrix_t *res, long int width, long int height); DECLDIR int igraph_layout_fruchterman_reingold_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy, const igraph_vector_t *minz, const igraph_vector_t *maxz); DECLDIR int igraph_layout_kamada_kawai_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t epsilon, igraph_real_t kkconst, const igraph_vector_t *weights, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy, const igraph_vector_t *minz, const igraph_vector_t *maxz); DECLDIR int igraph_layout_graphopt(const igraph_t *graph, igraph_matrix_t *res, igraph_integer_t niter, igraph_real_t node_charge, igraph_real_t node_mass, igraph_real_t spring_length, igraph_real_t spring_constant, igraph_real_t max_sa_movement, igraph_bool_t use_seed); DECLDIR int igraph_layout_mds(const igraph_t *graph, igraph_matrix_t *res, const igraph_matrix_t *dist, long int dim, igraph_arpack_options_t *options); DECLDIR int igraph_layout_bipartite(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_matrix_t *res, igraph_real_t hgap, igraph_real_t vgap, long int maxiter); /** * \struct igraph_layout_drl_options_t * Parameters for the DrL layout generator * * \member edge_cut The edge cutting parameter. * Edge cutting is done in the late stages of the * algorithm in order to achieve less dense layouts. Edges are cut * if there is a lot of stress on them (a large value in the * objective function sum). The edge cutting parameter is a value * between 0 and 1 with 0 representing no edge cutting and 1 * representing maximal edge cutting. The default value is 32/40. * \member init_iterations Number of iterations, initial phase. * \member init_temperature Start temperature, initial phase. * \member init_attraction Attraction, initial phase. * \member init_damping_mult Damping factor, initial phase. * \member liquid_iterations Number of iterations in the liquid phase. * \member liquid_temperature Start temperature in the liquid phase. * \member liquid_attraction Attraction in the liquid phase. * \member liquid_damping_mult Multiplicatie damping factor, liquid phase. * \member expansion_iterations Number of iterations in the expansion phase. * \member expansion_temperature Start temperature in the expansion phase. * \member expansion_attraction Attraction, expansion phase. * \member expansion_damping_mult Damping factor, expansion phase. * \member cooldown_iterations Number of iterations in the cooldown phase. * \member cooldown_temperature Start temperature in the cooldown phase. * \member cooldown_attraction Attraction in the cooldown phase. * \member cooldown_damping_mult Damping fact int the cooldown phase. * \member crunch_iterations Number of iterations in the crunch phase. * \member crunch_temperature Start temperature in the crunch phase. * \member crunch_attraction Attraction in the crunch phase. * \member crunch_damping_mult Damping factor in the crunch phase. * \member simmer_iterations Number of iterations in the simmer phase. * \member simmer_temperature Start temperature in te simmer phase. * \member simmer_attraction Attraction in the simmer phase. * \member simmer_damping_mult Multiplicative damping factor in the simmer phase. */ typedef struct igraph_layout_drl_options_t { igraph_real_t edge_cut; igraph_integer_t init_iterations; igraph_real_t init_temperature; igraph_real_t init_attraction; igraph_real_t init_damping_mult; igraph_integer_t liquid_iterations; igraph_real_t liquid_temperature; igraph_real_t liquid_attraction; igraph_real_t liquid_damping_mult; igraph_integer_t expansion_iterations; igraph_real_t expansion_temperature; igraph_real_t expansion_attraction; igraph_real_t expansion_damping_mult; igraph_integer_t cooldown_iterations; igraph_real_t cooldown_temperature; igraph_real_t cooldown_attraction; igraph_real_t cooldown_damping_mult; igraph_integer_t crunch_iterations; igraph_real_t crunch_temperature; igraph_real_t crunch_attraction; igraph_real_t crunch_damping_mult; igraph_integer_t simmer_iterations; igraph_real_t simmer_temperature; igraph_real_t simmer_attraction; igraph_real_t simmer_damping_mult; } igraph_layout_drl_options_t; /** * \typedef igraph_layout_drl_default_t * Predefined parameter templates for the DrL layout generator * * These constants can be used to initialize a set of DrL parameters. * These can then be modified according to the user's needs. * \enumval IGRAPH_LAYOUT_DRL_DEFAULT The deafult parameters. * \enumval IGRAPH_LAYOUT_DRL_COARSEN Slightly modified parameters to * get a coarser layout. * \enumval IGRAPH_LAYOUT_DRL_COARSEST An even coarser layout. * \enumval IGRAPH_LAYOUT_DRL_REFINE Refine an already calculated layout. * \enumval IGRAPH_LAYOUT_DRL_FINAL Finalize an already refined layout. */ typedef enum { IGRAPH_LAYOUT_DRL_DEFAULT=0, IGRAPH_LAYOUT_DRL_COARSEN, IGRAPH_LAYOUT_DRL_COARSEST, IGRAPH_LAYOUT_DRL_REFINE, IGRAPH_LAYOUT_DRL_FINAL } igraph_layout_drl_default_t; DECLDIR int igraph_layout_drl_options_init(igraph_layout_drl_options_t *options, igraph_layout_drl_default_t templ); DECLDIR int igraph_layout_drl(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_layout_drl_options_t *options, const igraph_vector_t *weights, const igraph_vector_bool_t *fixed); DECLDIR int igraph_layout_drl_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_layout_drl_options_t *options, const igraph_vector_t *weights, const igraph_vector_bool_t *fixed); DECLDIR int igraph_layout_merge_dla(igraph_vector_ptr_t *graphs, igraph_vector_ptr_t *coords, igraph_matrix_t *res); DECLDIR int igraph_layout_gem(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t temp_max, igraph_real_t temp_min, igraph_real_t temp_init); DECLDIR int igraph_layout_davidson_harel(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_integer_t fineiter, igraph_real_t cool_fact, igraph_real_t weight_node_dist, igraph_real_t weight_border, igraph_real_t weight_edge_lengths, igraph_real_t weight_edge_crossings, igraph_real_t weight_node_edge_dist); __END_DECLS #endif igraph/src/include/igraph_random.h0000644000175100001440000001140313431000472016730 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REST_RANDOM_H #define REST_RANDOM_H #include "igraph_decls.h" __BEGIN_DECLS #include #include #include "igraph_types.h" #include "igraph_vector.h" /* The new RNG interface is (somewhat) modelled based on the GSL */ typedef struct igraph_rng_type_t { const char *name; unsigned long int min; unsigned long int max; int (*init)(void **state); void (*destroy)(void *state); int (*seed)(void *state, unsigned long int seed); unsigned long int (*get)(void *state); igraph_real_t (*get_real)(void *state); igraph_real_t (*get_norm)(void *state); igraph_real_t (*get_geom)(void *state, igraph_real_t p); igraph_real_t (*get_binom)(void *state, long int n, igraph_real_t p); igraph_real_t (*get_exp)(void *state, igraph_real_t rate); igraph_real_t (*get_gamma)(void *state, igraph_real_t shape, igraph_real_t scale); } igraph_rng_type_t; typedef struct igraph_rng_t { const igraph_rng_type_t *type; void *state; int def; } igraph_rng_t; /* --------------------------------- */ DECLDIR int igraph_rng_init(igraph_rng_t *rng, const igraph_rng_type_t *type); DECLDIR void igraph_rng_destroy(igraph_rng_t *rng); DECLDIR int igraph_rng_seed(igraph_rng_t *rng, unsigned long int seed); DECLDIR unsigned long int igraph_rng_max(igraph_rng_t *rng); DECLDIR unsigned long int igraph_rng_min(igraph_rng_t *rng); DECLDIR const char *igraph_rng_name(igraph_rng_t *rng); DECLDIR long int igraph_rng_get_integer(igraph_rng_t *rng, long int l, long int h); DECLDIR igraph_real_t igraph_rng_get_normal(igraph_rng_t *rng, igraph_real_t m, igraph_real_t s); DECLDIR igraph_real_t igraph_rng_get_unif(igraph_rng_t *rng, igraph_real_t l, igraph_real_t h); DECLDIR igraph_real_t igraph_rng_get_unif01(igraph_rng_t *rng); DECLDIR igraph_real_t igraph_rng_get_geom(igraph_rng_t *rng, igraph_real_t p); DECLDIR igraph_real_t igraph_rng_get_binom(igraph_rng_t *rng, long int n, igraph_real_t p); DECLDIR igraph_real_t igraph_rng_get_exp(igraph_rng_t *rng, igraph_real_t rate); DECLDIR unsigned long int igraph_rng_get_int31(igraph_rng_t *rng); DECLDIR igraph_real_t igraph_rng_get_exp(igraph_rng_t *rng, igraph_real_t rate); DECLDIR igraph_real_t igraph_rng_get_gamma(igraph_rng_t *rng, igraph_real_t shape, igraph_real_t scale); DECLDIR int igraph_rng_get_dirichlet(igraph_rng_t *rng, const igraph_vector_t *alpha, igraph_vector_t *result); /* --------------------------------- */ extern const igraph_rng_type_t igraph_rngtype_glibc2; extern const igraph_rng_type_t igraph_rngtype_rand; extern const igraph_rng_type_t igraph_rngtype_mt19937; DECLDIR igraph_rng_t *igraph_rng_default(void); DECLDIR void igraph_rng_set_default(igraph_rng_t *rng); /* --------------------------------- */ #ifdef USING_R void GetRNGstate(void); void PutRNGstate(void); #define RNG_BEGIN() GetRNGstate() #define RNG_END() PutRNGstate() double Rf_dnorm4(double x, double mu, double sigma, int give_log); #define igraph_dnorm Rf_dnorm4 #else #define RNG_BEGIN() if (igraph_rng_default()->def==1) { \ igraph_rng_seed(igraph_rng_default(), time(0)); \ igraph_rng_default()->def=2; \ } #define RNG_END() /* do nothing */ DECLDIR double igraph_dnorm(double x, double mu, double sigma, int give_log); #endif #define RNG_INTEGER(l,h) (igraph_rng_get_integer(igraph_rng_default(),(l),(h))) #define RNG_NORMAL(m,s) (igraph_rng_get_normal(igraph_rng_default(),(m),(s))) #define RNG_UNIF(l,h) (igraph_rng_get_unif(igraph_rng_default(),(l),(h))) #define RNG_UNIF01() (igraph_rng_get_unif01(igraph_rng_default())) #define RNG_GEOM(p) (igraph_rng_get_geom(igraph_rng_default(),(p))) #define RNG_BINOM(n,p) (igraph_rng_get_binom(igraph_rng_default(),(n),(p))) #define RNG_INT31() (igraph_rng_get_int31(igraph_rng_default())) __END_DECLS #endif igraph/src/include/igraph_interrupt.h0000644000175100001440000001144113431000472017506 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_INTERRUPT_H #define IGRAPH_INTERRUPT_H #include "igraph_error.h" #include "igraph_decls.h" __BEGIN_DECLS /* This file contains the igraph interruption handling. */ /** * \section interrupthandlers Interruption handlers * * * \a igraph is designed to be embeddable into several higher level * languages (R and Python interfaces are included in the original * package). Since most higher level languages consider internal \a igraph * calls as atomic, interruption requests (like Ctrl-C in Python) must * be handled differently depending on the environment \a igraph embeds * into. * * An \emb interruption handler \eme is a function which is called regularly * by \a igraph during long calculations. A typical usage of the interruption * handler is to check whether the user tried to interrupt the calculation * and return an appropriate value to signal this condition. For example, * in R, one must call an internal R function regularly to check for * interruption requests, and the \a igraph interruption handler is the * perfect place to do that. * * If you are using the plain C interface of \a igraph or if you are * allowed to replace the operating system's interruption handler (like * SIGINT in Un*x systems), these calls are not of much use to you. * * The default interruption handler is empty. * The \ref igraph_set_interruption_handler() function can be used to set a * new interruption handler function of type * \ref igraph_interruption_handler_t, see the * documentation of this type for details. * */ /** * \section writing_interruption_handlers Writing interruption handlers * * * You can write and install interruption handlers simply by defining a * function of type \ref igraph_interruption_handler_t and calling * \ref igraph_set_interruption_handler(). This feature is useful for * interface writers, because usually this is the only way to allow handling * of Ctrl-C and similar keypresses properly. * * * Your interruption handler will be called regularly during long operations * (so it is not guaranteed to be called during operations which tend to be * short, like adding single edges). An interruption handler accepts no * parameters and must return \c IGRAPH_SUCCESS if the calculation should go on. All * other return values are considered to be a request for interruption, * and the caller function would return a special error code, \c IGRAPH_INTERRUPTED. * It is up to your error handler function to handle this error properly. * */ /** * \section writing_functions_interruption_handling Writing \a igraph functions with * proper interruption handling * * * There is practically a simple rule that should be obeyed when writing * \a igraph functions. If the calculation is expected to take a long time * in large graphs (a simple rule of thumb is to assume this for every * function with a time complexity of at least O(n^2)), call * \ref IGRAPH_ALLOW_INTERRUPTION in regular intervals like every 10th * iteration or so. * */ /** * \typedef igraph_interruption_handler_t * * This is the type of the interruption handler functions. * * \param data reserved for possible future use * \return \c IGRAPH_SUCCESS if the calculation should go on, anything else otherwise. */ typedef int igraph_interruption_handler_t (void* data); /** * \function igraph_allow_interruption * * This is the function which is called (usually via the * \ref IGRAPH_INTERRUPTION macro) if \a igraph is checking for interruption * requests. * * \param data reserved for possible future use, now it is always \c NULL * \return \c IGRAPH_SUCCESS if the calculation should go on, anything else otherwise. */ DECLDIR int igraph_allow_interruption(void* data); DECLDIR igraph_interruption_handler_t * igraph_set_interruption_handler (igraph_interruption_handler_t * new_handler); __END_DECLS #endif igraph/src/include/igraph_vector_pmt.h0000644000175100001440000002623413431000472017642 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*--------------------*/ /* Allocation */ /*--------------------*/ DECLDIR int FUNCTION(igraph_vector,init)(TYPE(igraph_vector)* v, long int size); DECLDIR int FUNCTION(igraph_vector,init_copy)(TYPE(igraph_vector)* v, BASE* data, long int length); DECLDIR int FUNCTION(igraph_vector,init_seq)(TYPE(igraph_vector)*v, BASE from, BASE to); DECLDIR int FUNCTION(igraph_vector,copy)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from); DECLDIR void FUNCTION(igraph_vector,destroy)(TYPE(igraph_vector)* v); DECLDIR long int FUNCTION(igraph_vector,capacity)(const TYPE(igraph_vector)*v); /*--------------------*/ /* Accessing elements */ /*--------------------*/ #ifndef VECTOR /** * \ingroup vector * \define VECTOR * \brief Accessing an element of a vector. * * Usage: * \verbatim VECTOR(v)[0] \endverbatim * to access the first element of the vector, you can also use this in * assignments, like: * \verbatim VECTOR(v)[10]=5; \endverbatim * * Note that there are no range checks right now. * This functionality might be redefined later as a real function * instead of a #define. * \param v The vector object. * * Time complexity: O(1). */ #define VECTOR(v) ((v).stor_begin) #endif DECLDIR BASE FUNCTION(igraph_vector,e)(const TYPE(igraph_vector)* v, long int pos); BASE* FUNCTION(igraph_vector,e_ptr)(const TYPE(igraph_vector)* v, long int pos); DECLDIR void FUNCTION(igraph_vector,set)(TYPE(igraph_vector)* v, long int pos, BASE value); DECLDIR BASE FUNCTION(igraph_vector,tail)(const TYPE(igraph_vector) *v); /*-----------------------*/ /* Initializing elements */ /*-----------------------*/ DECLDIR void FUNCTION(igraph_vector,null)(TYPE(igraph_vector)* v); DECLDIR void FUNCTION(igraph_vector,fill)(TYPE(igraph_vector)* v, BASE e); /*-----------------------*/ /* Vector views */ /*-----------------------*/ DECLDIR const TYPE(igraph_vector) *FUNCTION(igraph_vector,view)(const TYPE(igraph_vector) *v, const BASE *data, long int length); /*-----------------------*/ /* Copying vectors */ /*-----------------------*/ DECLDIR void FUNCTION(igraph_vector,copy_to)(const TYPE(igraph_vector) *v, BASE* to); DECLDIR int FUNCTION(igraph_vector,update)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from); DECLDIR int FUNCTION(igraph_vector,append)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from); DECLDIR int FUNCTION(igraph_vector,swap)(TYPE(igraph_vector) *v1, TYPE(igraph_vector) *v2); /*-----------------------*/ /* Exchanging elements */ /*-----------------------*/ DECLDIR int FUNCTION(igraph_vector,swap_elements)(TYPE(igraph_vector) *v, long int i, long int j); DECLDIR int FUNCTION(igraph_vector,reverse)(TYPE(igraph_vector) *v); DECLDIR int FUNCTION(igraph_vector,shuffle)(TYPE(igraph_vector) *v); /*-----------------------*/ /* Vector operations */ /*-----------------------*/ DECLDIR void FUNCTION(igraph_vector,add_constant)(TYPE(igraph_vector) *v, BASE plus); DECLDIR void FUNCTION(igraph_vector,scale)(TYPE(igraph_vector) *v, BASE by); DECLDIR int FUNCTION(igraph_vector,add)(TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2); DECLDIR int FUNCTION(igraph_vector,sub)(TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2); DECLDIR int FUNCTION(igraph_vector,mul)(TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2); DECLDIR int FUNCTION(igraph_vector,div)(TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2); DECLDIR int FUNCTION(igraph_vector,cumsum)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from); #ifndef NOABS DECLDIR int FUNCTION(igraph_vector,abs)(TYPE(igraph_vector) *v); #endif /*------------------------------*/ /* Comparison */ /*------------------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_vector,all_e)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_vector,all_l)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_vector,all_g)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_vector,all_le)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_vector,all_ge)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); /*------------------------------*/ /* Finding minimum and maximum */ /*------------------------------*/ DECLDIR BASE FUNCTION(igraph_vector,min)(const TYPE(igraph_vector)* v); DECLDIR BASE FUNCTION(igraph_vector,max)(const TYPE(igraph_vector)* v); DECLDIR long int FUNCTION(igraph_vector,which_min)(const TYPE(igraph_vector)* v); DECLDIR long int FUNCTION(igraph_vector,which_max)(const TYPE(igraph_vector)* v); DECLDIR int FUNCTION(igraph_vector,minmax)(const TYPE(igraph_vector) *v, BASE *min, BASE *max); DECLDIR int FUNCTION(igraph_vector,which_minmax)(const TYPE(igraph_vector) *v, long int *which_min, long int *which_max); /*-------------------*/ /* Vector properties */ /*-------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_vector,empty) (const TYPE(igraph_vector)* v); DECLDIR long int FUNCTION(igraph_vector,size) (const TYPE(igraph_vector)* v); DECLDIR igraph_bool_t FUNCTION(igraph_vector,isnull)(const TYPE(igraph_vector) *v); DECLDIR BASE FUNCTION(igraph_vector,sum)(const TYPE(igraph_vector) *v); DECLDIR igraph_real_t FUNCTION(igraph_vector,sumsq)(const TYPE(igraph_vector) *v); DECLDIR BASE FUNCTION(igraph_vector,prod)(const TYPE(igraph_vector) *v); DECLDIR igraph_bool_t FUNCTION(igraph_vector,isininterval)(const TYPE(igraph_vector) *v, BASE low, BASE high); DECLDIR igraph_bool_t FUNCTION(igraph_vector,any_smaller)(const TYPE(igraph_vector) *v, BASE limit); DECLDIR igraph_bool_t FUNCTION(igraph_vector,is_equal)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs); DECLDIR igraph_real_t FUNCTION(igraph_vector,maxdifference)(const TYPE(igraph_vector) *m1, const TYPE(igraph_vector) *m2); /*------------------------*/ /* Searching for elements */ /*------------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_vector,contains)(const TYPE(igraph_vector) *v, BASE e); DECLDIR igraph_bool_t FUNCTION(igraph_vector,search)(const TYPE(igraph_vector) *v, long int from, BASE what, long int *pos); DECLDIR igraph_bool_t FUNCTION(igraph_vector,binsearch)(const TYPE(igraph_vector) *v, BASE what, long int *pos); DECLDIR igraph_bool_t FUNCTION(igraph_vector,binsearch2)(const TYPE(igraph_vector) *v, BASE what); /*------------------------*/ /* Resizing operations */ /*------------------------*/ DECLDIR void FUNCTION(igraph_vector,clear)(TYPE(igraph_vector)* v); DECLDIR int FUNCTION(igraph_vector,resize)(TYPE(igraph_vector)* v, long int newsize); DECLDIR int FUNCTION(igraph_vector,resize_min)(TYPE(igraph_vector)*v); DECLDIR int FUNCTION(igraph_vector,reserve)(TYPE(igraph_vector)* v, long int size); DECLDIR int FUNCTION(igraph_vector,push_back)(TYPE(igraph_vector)* v, BASE e); DECLDIR BASE FUNCTION(igraph_vector,pop_back)(TYPE(igraph_vector)* v); DECLDIR int FUNCTION(igraph_vector,insert)(TYPE(igraph_vector) *v, long int pos, BASE value); DECLDIR void FUNCTION(igraph_vector,remove)(TYPE(igraph_vector) *v, long int elem); DECLDIR void FUNCTION(igraph_vector,remove_section)(TYPE(igraph_vector) *v, long int from, long int to); /*-----------*/ /* Sorting */ /*-----------*/ DECLDIR void FUNCTION(igraph_vector,sort)(TYPE(igraph_vector) *v); DECLDIR long int FUNCTION(igraph_vector,qsort_ind)(TYPE(igraph_vector) *v, igraph_vector_t *inds, igraph_bool_t descending); /*-----------*/ /* Printing */ /*-----------*/ int FUNCTION(igraph_vector,print)(const TYPE(igraph_vector) *v); int FUNCTION(igraph_vector,printf)(const TYPE(igraph_vector) *v, const char *format); int FUNCTION(igraph_vector,fprint)(const TYPE(igraph_vector) *v, FILE *file); #ifdef BASE_COMPLEX DECLDIR int igraph_vector_complex_real(const igraph_vector_complex_t *v, igraph_vector_t *real); DECLDIR int igraph_vector_complex_imag(const igraph_vector_complex_t *v, igraph_vector_t *imag); DECLDIR int igraph_vector_complex_realimag(const igraph_vector_complex_t *v, igraph_vector_t *real, igraph_vector_t *imag); DECLDIR int igraph_vector_complex_create(igraph_vector_complex_t *v, const igraph_vector_t *real, const igraph_vector_t *imag); DECLDIR int igraph_vector_complex_create_polar(igraph_vector_complex_t *v, const igraph_vector_t *r, const igraph_vector_t *theta); #endif /* ----------------------------------------------------------------------------*/ /* For internal use only, may be removed, rewritten ... */ /* ----------------------------------------------------------------------------*/ int FUNCTION(igraph_vector,init_real)(TYPE(igraph_vector)*v, int no, ...); int FUNCTION(igraph_vector,init_int)(TYPE(igraph_vector)*v, int no, ...); int FUNCTION(igraph_vector,init_real_end)(TYPE(igraph_vector)*v, BASE endmark, ...); int FUNCTION(igraph_vector,init_int_end)(TYPE(igraph_vector)*v, int endmark, ...); int FUNCTION(igraph_vector,move_interval)(TYPE(igraph_vector) *v, long int begin, long int end, long int to); int FUNCTION(igraph_vector,move_interval2)(TYPE(igraph_vector) *v, long int begin, long int end, long int to); void FUNCTION(igraph_vector,permdelete)(TYPE(igraph_vector) *v, const igraph_vector_t *index, long int nremove); int FUNCTION(igraph_vector,filter_smaller)(TYPE(igraph_vector) *v, BASE elem); int FUNCTION(igraph_vector,get_interval)(const TYPE(igraph_vector) *v, TYPE(igraph_vector) *res, long int from, long int to); int FUNCTION(igraph_vector,difference_sorted)(const TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2, TYPE(igraph_vector) *result); int FUNCTION(igraph_vector,intersect_sorted)(const TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2, TYPE(igraph_vector) *result); int FUNCTION(igraph_vector,index)(const TYPE(igraph_vector) *v, TYPE(igraph_vector) *newv, const igraph_vector_t *idx); int FUNCTION(igraph_vector,index_int)(TYPE(igraph_vector) *v, const igraph_vector_int_t *idx); igraph/src/include/igraph_dqueue.h0000644000175100001440000000372113431000472016744 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_DQUEUE_H #define IGRAPH_DQUEUE_H #include "igraph_types.h" #include "igraph_decls.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* double ended queue, very useful */ /* -------------------------------------------------- */ #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_dqueue_pmt.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "igraph_dqueue_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_dqueue_pmt.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_dqueue_pmt.h" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_INT #include "igraph_pmt.h" #include "igraph_dqueue_pmt.h" #include "igraph_pmt_off.h" #undef BASE_INT #define IGRAPH_DQUEUE_NULL { 0,0,0,0 } #define IGRAPH_DQUEUE_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_dqueue_init(v, size)); \ IGRAPH_FINALLY(igraph_dqueue_destroy, v); } while (0) __END_DECLS #endif igraph/src/include/igraph_vector_ptr.h0000644000175100001440000001062013431000472017637 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_VECTOR_PTR_H #define IGRAPH_VECTOR_PTR_H #include "igraph_decls.h" #include "igraph_vector.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Flexible vector, storing pointers */ /* -------------------------------------------------- */ /** * Vector, storing pointers efficiently * \ingroup internal * */ typedef struct s_vector_ptr { void** stor_begin; void** stor_end; void** end; igraph_finally_func_t* item_destructor; } igraph_vector_ptr_t; #define IGRAPH_VECTOR_PTR_NULL { 0,0,0,0 } #define IGRAPH_VECTOR_PTR_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_vector_ptr_init(v, size)); \ IGRAPH_FINALLY(igraph_vector_ptr_destroy, v); } while (0) DECLDIR int igraph_vector_ptr_init (igraph_vector_ptr_t* v, long int size); DECLDIR int igraph_vector_ptr_init_copy (igraph_vector_ptr_t* v, void** data, long int length); DECLDIR const igraph_vector_ptr_t *igraph_vector_ptr_view (const igraph_vector_ptr_t *v, void *const *data, long int length); DECLDIR void igraph_vector_ptr_destroy (igraph_vector_ptr_t* v); DECLDIR void igraph_vector_ptr_free_all (igraph_vector_ptr_t* v); DECLDIR void igraph_vector_ptr_destroy_all (igraph_vector_ptr_t* v); DECLDIR int igraph_vector_ptr_reserve (igraph_vector_ptr_t* v, long int size); DECLDIR igraph_bool_t igraph_vector_ptr_empty (const igraph_vector_ptr_t* v); DECLDIR long int igraph_vector_ptr_size (const igraph_vector_ptr_t* v); DECLDIR void igraph_vector_ptr_clear (igraph_vector_ptr_t* v); DECLDIR void igraph_vector_ptr_null (igraph_vector_ptr_t* v); DECLDIR int igraph_vector_ptr_push_back (igraph_vector_ptr_t* v, void* e); DECLDIR int igraph_vector_ptr_append (igraph_vector_ptr_t *to, const igraph_vector_ptr_t *from); DECLDIR void *igraph_vector_ptr_pop_back (igraph_vector_ptr_t *v); DECLDIR int igraph_vector_ptr_insert(igraph_vector_ptr_t *v, long int pos, void* e); DECLDIR void* igraph_vector_ptr_e (const igraph_vector_ptr_t* v, long int pos); DECLDIR void igraph_vector_ptr_set (igraph_vector_ptr_t* v, long int pos, void* value); DECLDIR int igraph_vector_ptr_resize(igraph_vector_ptr_t* v, long int newsize); DECLDIR void igraph_vector_ptr_copy_to(const igraph_vector_ptr_t *v, void** to); DECLDIR int igraph_vector_ptr_copy(igraph_vector_ptr_t *to, const igraph_vector_ptr_t *from); DECLDIR void igraph_vector_ptr_remove(igraph_vector_ptr_t *v, long int pos); DECLDIR void igraph_vector_ptr_sort(igraph_vector_ptr_t *v, int(*compar)(const void*, const void*)); DECLDIR int igraph_vector_ptr_index_int(igraph_vector_ptr_t *v, const igraph_vector_int_t *idx); DECLDIR igraph_finally_func_t* igraph_vector_ptr_get_item_destructor(const igraph_vector_ptr_t *v); DECLDIR igraph_finally_func_t* igraph_vector_ptr_set_item_destructor(igraph_vector_ptr_t *v, igraph_finally_func_t *func); /** * \define IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR * \brief Sets the item destructor for this pointer vector (macro version). * * This macro is expanded to \ref igraph_vector_ptr_set_item_destructor(), the * only difference is that the second argument is automatically cast to an * \c igraph_finally_func_t*. The cast is necessary in most cases as the * destructor functions we use (such as \ref igraph_vector_destroy()) take a * pointer to some concrete igraph data type, while \c igraph_finally_func_t * expects \c void* */ #define IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(v, func) \ igraph_vector_ptr_set_item_destructor((v), (igraph_finally_func_t*)(func)) __END_DECLS #endif igraph/src/include/igraph_complex.h0000644000175100001440000001063713431000472017127 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_COMPLEX_H #define IGRAPH_COMPLEX_H #include "igraph_decls.h" #include "igraph_types.h" __BEGIN_DECLS typedef struct igraph_complex_t { igraph_real_t dat[2]; } igraph_complex_t; #define IGRAPH_REAL(x) ((x).dat[0]) #define IGRAPH_IMAG(x) ((x).dat[1]) #define IGRAPH_COMPLEX_EQ(x,y) ((x).dat[0]==(y).dat[0] && (x).dat[1]==(y).dat[1]) DECLDIR igraph_complex_t igraph_complex(igraph_real_t x, igraph_real_t y); DECLDIR igraph_complex_t igraph_complex_polar(igraph_real_t r, igraph_real_t theta); DECLDIR igraph_bool_t igraph_complex_eq_tol(igraph_complex_t z1, igraph_complex_t z2, igraph_real_t tol); DECLDIR igraph_real_t igraph_complex_mod(igraph_complex_t z); DECLDIR igraph_real_t igraph_complex_arg(igraph_complex_t z); DECLDIR igraph_real_t igraph_complex_abs(igraph_complex_t z); DECLDIR igraph_real_t igraph_complex_logabs(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_add(igraph_complex_t z1, igraph_complex_t z2); DECLDIR igraph_complex_t igraph_complex_sub(igraph_complex_t z1, igraph_complex_t z2); DECLDIR igraph_complex_t igraph_complex_mul(igraph_complex_t z1, igraph_complex_t z2); DECLDIR igraph_complex_t igraph_complex_div(igraph_complex_t z1, igraph_complex_t z2); DECLDIR igraph_complex_t igraph_complex_add_real(igraph_complex_t z, igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_add_imag(igraph_complex_t z, igraph_real_t y); DECLDIR igraph_complex_t igraph_complex_sub_real(igraph_complex_t z, igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_sub_imag(igraph_complex_t z, igraph_real_t y); DECLDIR igraph_complex_t igraph_complex_mul_real(igraph_complex_t z, igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_mul_imag(igraph_complex_t z, igraph_real_t y); DECLDIR igraph_complex_t igraph_complex_div_real(igraph_complex_t z, igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_div_imag(igraph_complex_t z, igraph_real_t y); DECLDIR igraph_complex_t igraph_complex_conj(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_neg(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_inv(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_sqrt(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_sqrt_real(igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_exp(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_pow(igraph_complex_t z1, igraph_complex_t z2); DECLDIR igraph_complex_t igraph_complex_pow_real(igraph_complex_t z, igraph_real_t x); DECLDIR igraph_complex_t igraph_complex_log(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_log10(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_log_b(igraph_complex_t z, igraph_complex_t b); DECLDIR igraph_complex_t igraph_complex_sin(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_cos(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_tan(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_sec(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_csc(igraph_complex_t z); DECLDIR igraph_complex_t igraph_complex_cot(igraph_complex_t z); __END_DECLS #endif igraph/src/include/igraph_iterators.h0000644000175100001440000003055313431000472017473 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_ITERATORS_H #define IGRAPH_ITERATORS_H #include "igraph_decls.h" #include "igraph_constants.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Vertex selectors */ /* -------------------------------------------------- */ #define IGRAPH_VS_ALL 0 #define IGRAPH_VS_ADJ 1 #define IGRAPH_VS_NONE 2 #define IGRAPH_VS_1 3 #define IGRAPH_VS_VECTORPTR 4 #define IGRAPH_VS_VECTOR 5 #define IGRAPH_VS_SEQ 6 #define IGRAPH_VS_NONADJ 7 typedef struct igraph_vs_t { int type; union { igraph_integer_t vid; /* single vertex */ const igraph_vector_t *vecptr; /* vector of vertices */ struct { igraph_integer_t vid; igraph_neimode_t mode; } adj; /* adjacent vertices */ struct { igraph_integer_t from; igraph_integer_t to; } seq; /* sequence of vertices from:to */ } data; } igraph_vs_t; DECLDIR int igraph_vs_all(igraph_vs_t *vs); DECLDIR igraph_vs_t igraph_vss_all(void); DECLDIR int igraph_vs_adj(igraph_vs_t *vs, igraph_integer_t vid, igraph_neimode_t mode); DECLDIR igraph_vs_t igraph_vss_adj(igraph_integer_t vid, igraph_neimode_t mode); DECLDIR int igraph_vs_nonadj(igraph_vs_t *vs, igraph_integer_t vid, igraph_neimode_t mode); DECLDIR int igraph_vs_none(igraph_vs_t *vs); DECLDIR igraph_vs_t igraph_vss_none(void); DECLDIR int igraph_vs_1(igraph_vs_t *vs, igraph_integer_t vid); DECLDIR igraph_vs_t igraph_vss_1(igraph_integer_t vid); DECLDIR int igraph_vs_vector(igraph_vs_t *vs, const igraph_vector_t *v); DECLDIR igraph_vs_t igraph_vss_vector(const igraph_vector_t *v); DECLDIR int igraph_vs_vector_small(igraph_vs_t *vs, ...); DECLDIR int igraph_vs_vector_copy(igraph_vs_t *vs, const igraph_vector_t *v); DECLDIR int igraph_vs_seq(igraph_vs_t *vs, igraph_integer_t from, igraph_integer_t to); DECLDIR igraph_vs_t igraph_vss_seq(igraph_integer_t from, igraph_integer_t to); DECLDIR void igraph_vs_destroy(igraph_vs_t *vs); DECLDIR igraph_bool_t igraph_vs_is_all(const igraph_vs_t *vs); DECLDIR int igraph_vs_copy(igraph_vs_t* dest, const igraph_vs_t* src); DECLDIR int igraph_vs_as_vector(const igraph_t *graph, igraph_vs_t vs, igraph_vector_t *v); DECLDIR int igraph_vs_size(const igraph_t *graph, const igraph_vs_t *vs, igraph_integer_t *result); DECLDIR int igraph_vs_type(const igraph_vs_t *vs); /* -------------------------------------------------- */ /* Vertex iterators */ /* -------------------------------------------------- */ #define IGRAPH_VIT_SEQ 0 #define IGRAPH_VIT_VECTOR 1 #define IGRAPH_VIT_VECTORPTR 2 typedef struct igraph_vit_t { int type; long int pos; long int start; long int end; const igraph_vector_t *vec; } igraph_vit_t; /** * \section IGRAPH_VIT Stepping over the vertices * * After creating an iterator with \ref igraph_vit_create(), it * points to the first vertex in the vertex determined by the vertex * selector (if there is any). The \ref IGRAPH_VIT_NEXT() macro steps * to the next vertex, \ref IGRAPH_VIT_END() checks whether there are * more vertices to visit, \ref IGRAPH_VIT_SIZE() gives the total size * of the vertices visited so far and to be visited. \ref * IGRAPH_VIT_RESET() resets the iterator, it will point to the first * vertex again. Finally \ref IGRAPH_VIT_GET() gives the current vertex * pointed to by the iterator (call this only if \ref IGRAPH_VIT_END() * is false). * * * Here is an example on how to step over the neighbors of vertex 0: * * igraph_vs_t vs; * igraph_vit_t vit; * ... * igraph_vs_adj(&vs, 0, IGRAPH_ALL); * igraph_vit_create(&graph, vs, &vit); * while (!IGRAPH_VIT_END(vit)) { * printf(" %li", (long int) IGRAPH_VIT_GET(vit)); * IGRAPH_VIT_NEXT(vit); * } * printf("\n"); * ... * igraph_vit_destroy(&vit); * igraph_vs_destroy(&vs); * * */ /** * \define IGRAPH_VIT_NEXT * \brief Next vertex. * * Steps the iterator to the next vertex. Only call this function if * \ref IGRAPH_VIT_END() returns false. * \param vit The vertex iterator to step. * * Time complexity: O(1). */ #define IGRAPH_VIT_NEXT(vit) (++((vit).pos)) /** * \define IGRAPH_VIT_END * \brief Are we at the end? * * Checks whether there are more vertices to step to. * \param vit The vertex iterator to check. * \return Logical value, if true there are no more vertices to step * to. * * Time complexity: O(1). */ #define IGRAPH_VIT_END(vit) ((vit).pos >= (vit).end) /** * \define IGRAPH_VIT_SIZE * \brief Size of a vertex iterator. * * Gives the number of vertices in a vertex iterator. * \param vit The vertex iterator. * \return The number of vertices. * * Time complexity: O(1). */ #define IGRAPH_VIT_SIZE(vit) ((vit).end - (vit).start) /** * \define IGRAPH_VIT_RESET * \brief Reset a vertex iterator. * * Resets a vertex iterator. After calling this macro the iterator * will point to the first vertex. * \param vit The vertex iterator. * * Time complexity: O(1). */ #define IGRAPH_VIT_RESET(vit) ((vit).pos = (vit).start) /** * \define IGRAPH_VIT_GET * \brief Query the current position. * * Gives the vertex id of the current vertex pointed to by the * iterator. * \param vit The vertex iterator. * \return The vertex id of the current vertex. * * Time complexity: O(1). */ #define IGRAPH_VIT_GET(vit) \ ((igraph_integer_t)(((vit).type == IGRAPH_VIT_SEQ) ? (vit).pos : \ VECTOR(*(vit).vec)[(vit).pos])) DECLDIR int igraph_vit_create(const igraph_t *graph, igraph_vs_t vs, igraph_vit_t *vit); DECLDIR void igraph_vit_destroy(const igraph_vit_t *vit); DECLDIR int igraph_vit_as_vector(const igraph_vit_t *vit, igraph_vector_t *v); /* -------------------------------------------------- */ /* Edge Selectors */ /* -------------------------------------------------- */ #define IGRAPH_ES_ALL 0 #define IGRAPH_ES_ALLFROM 1 #define IGRAPH_ES_ALLTO 2 #define IGRAPH_ES_INCIDENT 3 #define IGRAPH_ES_NONE 4 #define IGRAPH_ES_1 5 #define IGRAPH_ES_VECTORPTR 6 #define IGRAPH_ES_VECTOR 7 #define IGRAPH_ES_SEQ 8 #define IGRAPH_ES_PAIRS 9 #define IGRAPH_ES_PATH 10 #define IGRAPH_ES_MULTIPAIRS 11 typedef struct igraph_es_t { int type; union { igraph_integer_t vid; igraph_integer_t eid; const igraph_vector_t *vecptr; struct { igraph_integer_t vid; igraph_neimode_t mode; } incident; struct { igraph_integer_t from; igraph_integer_t to; } seq; struct { const igraph_vector_t *ptr; igraph_bool_t mode; } path; } data; } igraph_es_t; DECLDIR int igraph_es_all(igraph_es_t *es, igraph_edgeorder_type_t order); DECLDIR igraph_es_t igraph_ess_all(igraph_edgeorder_type_t order); DECLDIR int igraph_es_adj(igraph_es_t *es, igraph_integer_t vid, igraph_neimode_t mode); /* deprecated */ DECLDIR int igraph_es_incident(igraph_es_t *es, igraph_integer_t vid, igraph_neimode_t mode); DECLDIR int igraph_es_none(igraph_es_t *es); DECLDIR igraph_es_t igraph_ess_none(void); DECLDIR int igraph_es_1(igraph_es_t *es, igraph_integer_t eid); DECLDIR igraph_es_t igraph_ess_1(igraph_integer_t eid); DECLDIR int igraph_es_vector(igraph_es_t *es, const igraph_vector_t *v); DECLDIR igraph_es_t igraph_ess_vector(const igraph_vector_t *v); DECLDIR int igraph_es_fromto(igraph_es_t *es, igraph_vs_t from, igraph_vs_t to); DECLDIR int igraph_es_seq(igraph_es_t *es, igraph_integer_t from, igraph_integer_t to); DECLDIR igraph_es_t igraph_ess_seq(igraph_integer_t from, igraph_integer_t to); DECLDIR int igraph_es_vector_copy(igraph_es_t *es, const igraph_vector_t *v); DECLDIR int igraph_es_pairs(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed); DECLDIR int igraph_es_pairs_small(igraph_es_t *es, igraph_bool_t directed, ...); DECLDIR int igraph_es_multipairs(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed); DECLDIR int igraph_es_path(igraph_es_t *es, const igraph_vector_t *v, igraph_bool_t directed); DECLDIR int igraph_es_path_small(igraph_es_t *es, igraph_bool_t directed, ...); DECLDIR void igraph_es_destroy(igraph_es_t *es); DECLDIR igraph_bool_t igraph_es_is_all(const igraph_es_t *es); DECLDIR int igraph_es_copy(igraph_es_t* dest, const igraph_es_t* src); DECLDIR int igraph_es_as_vector(const igraph_t *graph, igraph_es_t es, igraph_vector_t *v); DECLDIR int igraph_es_size(const igraph_t *graph, const igraph_es_t *es, igraph_integer_t *result); DECLDIR int igraph_es_type(const igraph_es_t *es); /* -------------------------------------------------- */ /* Edge Iterators */ /* -------------------------------------------------- */ #define IGRAPH_EIT_SEQ 0 #define IGRAPH_EIT_VECTOR 1 #define IGRAPH_EIT_VECTORPTR 2 typedef struct igraph_eit_t { int type; long int pos; long int start; long int end; const igraph_vector_t *vec; } igraph_eit_t; /** * \section IGRAPH_EIT Stepping over the edges * * Just like for vertex iterators, macros are provided for * stepping over a sequence of edges: \ref IGRAPH_EIT_NEXT() goes to * the next edge, \ref IGRAPH_EIT_END() checks whether there are more * edges to visit, \ref IGRAPH_EIT_SIZE() gives the number of edges in * the edge sequence, \ref IGRAPH_EIT_RESET() resets the iterator to * the first edge and \ref IGRAPH_EIT_GET() returns the id of the * current edge. */ /** * \define IGRAPH_EIT_NEXT * \brief Next edge. * * Steps the iterator to the next edge. Call this function only if * \ref IGRAPH_EIT_END() returns false. * \param eit The edge iterator to step. * * Time complexity: O(1). */ #define IGRAPH_EIT_NEXT(eit) (++((eit).pos)) /** * \define IGRAPH_EIT_END * \brief Are we at the end? * * Checks whether there are more edges to step to. * \param wit The edge iterator to check. * \return Logical value, if true there are no more edges * to step to. * * Time complexity: O(1). */ #define IGRAPH_EIT_END(eit) ((eit).pos >= (eit).end) /** * \define IGRAPH_EIT_SIZE * \brief Number of edges in the iterator. * * Gives the number of edges in an edge iterator. * \param eit The edge iterator. * \return The number of edges. * * Time complexity: O(1). */ #define IGRAPH_EIT_SIZE(eit) ((eit).end - (eit).start) /** * \define IGRAPH_EIT_RESET * \brief Reset an edge iterator. * * Resets an edge iterator. After calling this macro the iterator will * point to the first edge. * \param eit The edge iterator. * * Time complexity: O(1). */ #define IGRAPH_EIT_RESET(eit) ((eit).pos = (eit).start) /** * \define IGRAPH_EIT_GET * \brief Query an edge iterator. * * Gives the edge id of the current edge pointed to by an iterator. * \param eit The edge iterator. * \return The id of the current edge. * * Time complexity: O(1). */ #define IGRAPH_EIT_GET(eit) \ (igraph_integer_t)((((eit).type == IGRAPH_EIT_SEQ) ? (eit).pos : \ VECTOR(*(eit).vec)[(eit).pos])) DECLDIR int igraph_eit_create(const igraph_t *graph, igraph_es_t es, igraph_eit_t *eit); DECLDIR void igraph_eit_destroy(const igraph_eit_t *eit); DECLDIR int igraph_eit_as_vector(const igraph_eit_t *eit, igraph_vector_t *v); __END_DECLS #endif igraph/src/include/igraph_types.h0000644000175100001440000000546413431000472016626 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REST_TYPES_H #define REST_TYPES_H #include "igraph_decls.h" __BEGIN_DECLS #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #include "igraph_error.h" #include #include #include /* This is to eliminate gcc warnings about unused parameters */ #define IGRAPH_UNUSED(x) (void)(x) typedef int igraph_integer_t; typedef double igraph_real_t; typedef int igraph_bool_t; /* Replacements for printf that print doubles in the same way on all platforms * (even for NaN and infinities) */ DECLDIR int igraph_real_printf(igraph_real_t val); DECLDIR int igraph_real_fprintf(FILE *file, igraph_real_t val); DECLDIR int igraph_real_snprintf(char* str, size_t size, igraph_real_t val); /* Replacements for printf that print doubles in the same way on all platforms * (even for NaN and infinities) with the largest possible precision */ DECLDIR int igraph_real_printf_precise(igraph_real_t val); DECLDIR int igraph_real_fprintf_precise(FILE *file, igraph_real_t val); DECLDIR int igraph_real_snprintf_precise(char* str, size_t size, igraph_real_t val); /* igraph_i_fdiv is needed here instead of in igraph_math.h because * some constants use it */ double igraph_i_fdiv(const double a, const double b); #if defined(INFINITY) # define IGRAPH_INFINITY INFINITY # define IGRAPH_POSINFINITY INFINITY # define IGRAPH_NEGINFINITY (-INFINITY) #else # define IGRAPH_INFINITY (igraph_i_fdiv(1.0, 0.0)) # define IGRAPH_POSINFINITY (igraph_i_fdiv(1.0, 0.0)) # define IGRAPH_NEGINFINITY (igraph_i_fdiv(-1.0, 0.0)) #endif DECLDIR int igraph_finite(double x); #define IGRAPH_FINITE(x) igraph_finite(x) DECLDIR int igraph_is_nan(double x); DECLDIR int igraph_is_inf(double x); DECLDIR int igraph_is_posinf(double x); DECLDIR int igraph_is_neginf(double x); #if defined(NAN) # define IGRAPH_NAN NAN #elif defined(INFINITY) # define IGRAPH_NAN (INFINITY/INFINITY) #else # define IGRAPH_NAN (igraph_i_fdiv(0.0, 0.0)) #endif __END_DECLS #endif igraph/src/include/igraph_hrg.h0000644000175100001440000000777013431000472016244 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_HRG_H #define IGRAPH_HRG_H #include "igraph_decls.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_datatype.h" __BEGIN_DECLS /** * \struct igraph_hrg_t * Data structure to store a hierarchical random graph * * A hierarchical random graph (HRG) can be given as a binary tree, * where the internal vertices are labeled with real numbers. * * Note that you don't necessarily have to know this * internal representation for using the HRG functions, just pass the * HRG objects created by one igraph function, to another igraph * function. * * * It has the following members: * \member left Vector that contains the left children of the internal * tree vertices. The first vertex is always the root vertex, so * the first element of the vector is the left child of the root * vertex. Internal vertices are denoted with negative numbers, * starting from -1 and going down, i.e. the root vertex is * -1. Leaf vertices are denoted by non-negative number, starting * from zero and up. * \member right Vector that contains the right children of the * vertices, with the same encoding as the \c left vector. * \member prob The connection probabilities attached to the internal * vertices, the first number belongs to the root vertex * (i.e. internal vertex -1), the second to internal vertex -2, * etc. * \member edges The number of edges in the subtree below the given * internal vertex. * \member vertices The number of vertices in the subtree below the * given internal vertex, including itself. */ typedef struct igraph_hrg_t { igraph_vector_t left, right, prob, edges, vertices; } igraph_hrg_t; DECLDIR int igraph_hrg_init(igraph_hrg_t *hrg, int n); DECLDIR void igraph_hrg_destroy(igraph_hrg_t *hrg); DECLDIR int igraph_hrg_size(const igraph_hrg_t *hrg); DECLDIR int igraph_hrg_resize(igraph_hrg_t *hrg, int newsize); DECLDIR int igraph_hrg_fit(const igraph_t *graph, igraph_hrg_t *hrg, igraph_bool_t start, int steps); DECLDIR int igraph_hrg_sample(const igraph_t *graph, igraph_t *sample, igraph_vector_ptr_t *samples, igraph_hrg_t *hrg, igraph_bool_t start); DECLDIR int igraph_hrg_game(igraph_t *graph, const igraph_hrg_t *hrg); DECLDIR int igraph_hrg_dendrogram(igraph_t *graph, const igraph_hrg_t *hrg); DECLDIR int igraph_hrg_consensus(const igraph_t *graph, igraph_vector_t *parents, igraph_vector_t *weights, igraph_hrg_t *hrg, igraph_bool_t start, int num_samples); DECLDIR int igraph_hrg_predict(const igraph_t *graph, igraph_vector_t *edges, igraph_vector_t *prob, igraph_hrg_t *hrg, igraph_bool_t start, int num_samples, int num_bins); DECLDIR int igraph_hrg_create(igraph_hrg_t *hrg, const igraph_t *graph, const igraph_vector_t *prob); __END_DECLS #endif /* IGRAPH_HRG_H */ igraph/src/include/igraph_array.h0000644000175100001440000000317213431000472016572 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_ARRAY_H #define IGRAPH_ARRAY_H #include "igraph_decls.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* 3D array */ /* -------------------------------------------------- */ #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "igraph_array_pmt.h" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "igraph_array_pmt.h" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "igraph_array_pmt.h" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "igraph_array_pmt.h" #include "igraph_pmt_off.h" #undef BASE_BOOL __END_DECLS #endif igraph/src/include/igraph.h0000644000175100001440000000550013431000472015371 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_H #define IGRAPH_H #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif #include "igraph_version.h" #include "igraph_memory.h" #include "igraph_error.h" #include "igraph_random.h" #include "igraph_progress.h" #include "igraph_statusbar.h" #include "igraph_types.h" #include "igraph_complex.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_array.h" #include "igraph_dqueue.h" #include "igraph_stack.h" #include "igraph_heap.h" #include "igraph_psumtree.h" #include "igraph_strvector.h" #include "igraph_vector_ptr.h" #include "igraph_spmatrix.h" #include "igraph_sparsemat.h" #include "igraph_qsort.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_iterators.h" #include "igraph_interface.h" #include "igraph_constructors.h" #include "igraph_games.h" #include "igraph_microscopic_update.h" #include "igraph_centrality.h" #include "igraph_paths.h" #include "igraph_components.h" #include "igraph_structural.h" #include "igraph_transitivity.h" #include "igraph_neighborhood.h" #include "igraph_topology.h" #include "igraph_bipartite.h" #include "igraph_cliques.h" #include "igraph_layout.h" #include "igraph_visitor.h" #include "igraph_community.h" #include "igraph_conversion.h" #include "igraph_foreign.h" #include "igraph_motifs.h" #include "igraph_operators.h" #include "igraph_flow.h" #include "igraph_nongraph.h" #include "igraph_cocitation.h" #include "igraph_adjlist.h" #include "igraph_attributes.h" #include "igraph_blas.h" #include "igraph_lapack.h" #include "igraph_arpack.h" #include "igraph_mixing.h" #include "igraph_separators.h" #include "igraph_cohesive_blocks.h" #include "igraph_eigen.h" #include "igraph_hrg.h" #include "igraph_threading.h" #include "igraph_interrupt.h" #include "igraph_scg.h" #include "igraph_matching.h" #include "igraph_embedding.h" #include "igraph_scan.h" #include "igraph_graphlets.h" #include "igraph_epidemics.h" #include "igraph_lsap.h" #include "igraph_coloring.h" #endif igraph/src/include/igraph_qsort.h0000644000175100001440000000236613431000472016630 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard st, Cambridge, MA 02139, USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_QSORT_H #define IGRAPH_QSORT_H #include "igraph_decls.h" __BEGIN_DECLS DECLDIR void igraph_qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *)); DECLDIR void igraph_qsort_r(void *base, size_t nel, size_t width, void *thunk, int (*compar)(void *, const void *, const void *)); __END_DECLS #endif igraph/src/include/igraph_arpack.h0000644000175100001440000003274513431000472016725 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #ifndef ARPACK_H #define ARPACK_H #include "igraph_decls.h" __BEGIN_DECLS /** * \section about_arpack ARPACK interface in igraph * * * ARPACK is a library for solving large scale eigenvalue problems. * The package is designed to compute a few eigenvalues and corresponding * eigenvectors of a general \c n by \c n matrix \c A. It is * most appropriate for large sparse or structured matrices \c A where * structured means that a matrix-vector product w <- Av requires * order \c n rather than the usual order n^2 floating point * operations. Please see * http://www.caam.rice.edu/software/ARPACK/ for details. * * * * The eigenvalue calculation in ARPACK (in the simplest * case) involves the calculation of the \c Av product where \c A * is the matrix we work with and \c v is an arbitrary vector. A * user-defined function of type \ref igraph_arpack_function_t * is expected to perform this product. If the product can be done * efficiently, e.g. if the matrix is sparse, then ARPACK is usually * able to calculate the eigenvalues very quickly. * * * In igraph, eigenvalue/eigenvector calculations usually * involve the following steps: * \olist * \oli Initialization of an \ref igraph_arpack_options_t data * structure using \ref igraph_arpack_options_init. * \oli Setting some options in the initialized \ref * igraph_arpack_options_t object. * \oli Defining a function of type \ref igraph_arpack_function_t. * The input of this function is a vector, and the output * should be the output matrix multiplied by the input vector. * \oli Calling \ref igraph_arpack_rssolve() (is the matrix is * symmetric), or \ref igraph_arpack_rnsolve(). * \endolist * The \ref igraph_arpack_options_t object can be used multiple * times. * * * * If we have many eigenvalue problems to solve, then it might worth * to create an \ref igraph_arpack_storage_t object, and initialize it * via \ref igraph_arpack_storage_init(). This structure contains all * memory needed for ARPACK (with the given upper limit regerding to * the size of the eigenvalue problem). Then many problems can be * solved using the same \ref igraph_arpack_storage_t object, without * always reallocating the required memory. * The \ref igraph_arpack_storage_t object needs to be destroyed by * calling \ref igraph_arpack_storage_destroy() on it, when it is not * needed any more. * * * * igraph does not contain all * ARPACK routines, only the ones dealing with symmetric and * non-symmetric eigenvalue problems using double precision real * numbers. * * */ /** * \struct igraph_arpack_options_t * \brief Options for ARPACK * * This data structure contains the options of thee ARPACK eigenvalue * solver routines. It must be initialized by calling \ref * igraph_arpack_options_init() on it. Then it can be used for * multiple ARPACK calls, as the ARPACK solvers do not modify it. * * Input options: * \member bmat Character. Whether to solve a standard ('I') ot a * generalized problem ('B'). * \member n Dimension of the eigenproblem. * \member which Specifies which eigenvalues/vectors to * compute. Possible values for symmetric matrices: * \clist \cli LA * Compute \c nev largest (algebraic) eigenvalues. * \cli SA * Compute \c nev smallest (algebraic) eigenvalues. * \cli LM * Compute \c nev largest (in magnitude) eigenvalues. * \cli SM * Compute \c nev smallest (in magnitude) eigenvalues. * \cli BE * Compute \c nev eigenvalues, half from each end of * the spectrum. When \c nev is odd, compute one * more from the high en than from the low * end. \endclist * Possible values for non-symmetric matrices: * \clist \cli LM * Compute \c nev largest (in magnitude) eigenvalues. * \cli SM * Compute \c nev smallest (in magnitude) eigenvalues. * \cli LR * Compute \c nev eigenvalues of largest real part. * \cli SR * Compute \c nev eigenvalues of smallest real part. * \cli LI * Compute \c nev eigenvalues of largest imaginary part. * \cli SI * Compute \c nev eigenvalues of smallest imaginary * part. \endclist * \member nev The number of eigenvalues to be computed. * \member tol Stopping criterion: the relative accuracy * of the Ritz value is considered acceptable if its error is less * than \c tol times its estimated value. If this is set to zero * then machine precision is used. * \member ncv Number of Lanczos vectors to be generated. Setting this * to zero means that \ref igraph_arpack_rssolve and \ref igraph_arpack_rnsolve * will determine a suitable value for \c ncv automatically. * \member ldv Numberic scalar. It should be set to * zero in the current igraph implementation. * \member ishift Either zero or one. If zero then the shifts are * provided by the user via reverse communication. If one then exact * shifts with respect to the reduced tridiagonal matrix \c T. * Please always set this to one. * \member mxiter Maximum number of Arnoldi update iterations allowed. * \member nb Blocksize to be used in the recurrence. Please always * leave this on the default value, one. * \member mode The type of the eigenproblem to be solved. * Possible values if the input matrix is symmetric: * \olist * \oli A*x=lambda*x, A is symmetric. * \oli A*x=lambda*M*x, A is * symmetric, M is symmetric positive definite. * \oli K*x=lambda*M*x, K is * symmetric, M is symmetric positive semi-definite. * \oli K*x=lambda*KG*x, K is * symmetric positive semi-definite, KG is symmetric * indefinite. * \oli A*x=lambda*M*x, A is * symmetric, M is symmetric positive * semi-definite. (Cayley transformed mode.) \endolist * Please note that only \c mode ==1 was tested and other values * might not work properly. * Possible values if the input matrix is not symmetric: * \olist * \oli A*x=lambda*x. * \oli A*x=lambda*M*x, M is * symmetric positive definite. * \oli A*x=lambda*M*x, M is * symmetric semi-definite. * \oli A*x=lambda*M*x, M is * symmetric semi-definite. \endolist * Please note that only \c mode == 1 was tested and other values * might not work properly. * \member start Whether to use the supplied starting vector (1), or * use a random starting vector (0). The starting vector must be * supplied in the first column of the \c vectors argument of the * \ref igraph_arpack_rssolve() of \ref igraph_arpack_rnsolve() call. * * Output options: * \member info Error flag of ARPACK. Possible values: * \clist \cli 0 * Normal exit. * \cli 1 * Maximum number of iterations taken. * \cli 3 * No shifts could be applied during a cycle of the * Implicitly restarted Arnoldi iteration. One possibility * is to increase the size of \c ncv relative to \c * nev. \endclist * ARPACK can return other error flags as well, but these are * converted to igraph errors, see \ref igraph_error_type_t. * \member ierr Error flag of the second ARPACK call (one eigenvalue * computation usually involves two calls to ARPACK). This is * always zero, as other error codes are converted to igraph errors. * \member noiter Number of Arnoldi iterations taken. * \member nconv Number of converged Ritz values. This * represents the number of Ritz values that satisfy the * convergence critetion. * \member numop Total number of matrix-vector multiplications. * \member numopb Not used currently. * \member numreo Total number of steps of re-orthogonalization. * * Internal options: * \member lworkl Do not modify this option. * \member sigma The shift for the shift-invert mode. * \member sigmai The imaginary part of the shift, for the * non-symmetric or complex shift-invert mode. * \member iparam Do not modify this option. * \member ipntr Do not modify this option. * */ typedef struct igraph_arpack_options_t { /* INPUT */ char bmat[1]; /* I-standard problem, G-generalized */ int n; /* Dimension of the eigenproblem */ char which[2]; /* LA, SA, LM, SM, BE */ int nev; /* Number of eigenvalues to be computed */ igraph_real_t tol; /* Stopping criterion */ int ncv; /* Number of columns in V */ int ldv; /* Leading dimension of V */ int ishift; /* 0-reverse comm., 1-exact with tridiagonal */ int mxiter; /* Maximum number of update iterations to take */ int nb; /* Block size on the recurrence, only 1 works */ int mode; /* The kind of problem to be solved (1-5) 1: A*x=l*x, A symmetric 2: A*x=l*M*x, A symm. M pos. def. 3: K*x = l*M*x, K symm., M pos. semidef. 4: K*x = l*KG*x, K s. pos. semidef. KG s. indef. 5: A*x = l*M*x, A symm., M symm. pos. semidef. */ int start; /* 0: random, 1: use the supplied vector */ int lworkl; /* Size of temporary storage, default is fine */ igraph_real_t sigma; /* The shift for modes 3,4,5 */ igraph_real_t sigmai; /* The imaginary part of shift for rnsolve */ /* OUTPUT */ int info; /* What happened, see docs */ int ierr; /* What happened in the dseupd call */ int noiter; /* The number of iterations taken */ int nconv; int numop; /* Number of OP*x operations */ int numopb; /* Number of B*x operations if BMAT='G' */ int numreo; /* Number of steps of re-orthogonalizations */ /* INTERNAL */ int iparam[11]; int ipntr[14]; } igraph_arpack_options_t; /** * \struct igraph_arpack_storage_t * \brief Storage for ARPACK * * Public members, do not modify them directly, these are considered * to be read-only. * \member maxn Maximum rank of matrix. * \member maxncv Maximum NCV. * \member maxldv Maximum LDV. * * These members are considered to be private: * \member workl Working memory. * \member workd Working memory. * \member d Memory for eigenvalues. * \member resid Memory for residuals. * \member ax Working memory. * \member select Working memory. * \member di Memory for eigenvalues, non-symmetric case only. * \member workev Working memory, non-symmetric case only. */ typedef struct igraph_arpack_storage_t { int maxn, maxncv, maxldv; igraph_real_t *v; igraph_real_t *workl; igraph_real_t *workd; igraph_real_t *d; igraph_real_t *resid; igraph_real_t *ax; int *select; igraph_real_t *di; /* These two only for non-symmetric problems */ igraph_real_t *workev; } igraph_arpack_storage_t; DECLDIR void igraph_arpack_options_init(igraph_arpack_options_t *o); DECLDIR int igraph_arpack_storage_init(igraph_arpack_storage_t *s, long int maxn, long int maxncv, long int maxldv, igraph_bool_t symm); DECLDIR void igraph_arpack_storage_destroy(igraph_arpack_storage_t *s); /** * \typedef igraph_arpack_function_t * Type of the ARPACK callback function * * \param to Pointer to an \c igraph_real_t, the result of the * matrix-vector product is expected to be stored here. * \param from Pointer to an \c igraph_real_t, the input matrix should * be multiplied by the vector stored here. * \param n The length of the vector (which is the same as the order * of the input matrix). * \param extra Extra argument to the matrix-vector calculation * function. This is coming from the \ref igraph_arpack_rssolve() * or \ref igraph_arpack_rnsolve() function. * \return Error code, if not zero, then the ARPACK solver considers * this as an error, stops and calls the igraph error handler. */ typedef int igraph_arpack_function_t(igraph_real_t *to, const igraph_real_t *from, int n, void *extra); DECLDIR int igraph_arpack_rssolve(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors); DECLDIR int igraph_arpack_rnsolve(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_matrix_t *values, igraph_matrix_t *vectors); DECLDIR int igraph_arpack_unpack_complex(igraph_matrix_t *vectors, igraph_matrix_t *values, long int nev); __END_DECLS #endif igraph/src/include/igraph_epidemics.h0000644000175100001440000000417713431000472017424 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_EPIDEMICS_H #define IGRAPH_EPIDEMICS_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /** * \struct igraph_sir_t * * Data structure to store the results of one simulation * of the SIR (susceptible-infected-recovered) model on a graph. * * It has the following members. They are all (real or integer) * vectors, and they are of the same length. * * \member times A vector, the times of the events are stored here. * \member no_s An integer vector, the number of susceptibles in * each time step is stored here. * \member no_i An integer vector, the number of infected individuals * at each time step, is stored here. * \member no_r An integer vector, the number of recovered individuals * is stored here at each time step. */ typedef struct igraph_sir_t { igraph_vector_t times; igraph_vector_int_t no_s, no_i, no_r; } igraph_sir_t; DECLDIR int igraph_sir_init(igraph_sir_t *sir); DECLDIR void igraph_sir_destroy(igraph_sir_t *sir); DECLDIR int igraph_sir(const igraph_t *graph, igraph_real_t beta, igraph_real_t gamma, igraph_integer_t no_sim, igraph_vector_ptr_t *result); __END_DECLS #endif igraph/src/include/igraph_games.h0000644000175100001440000002354113431000472016552 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_GAMES_H #define IGRAPH_GAMES_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_matrix.h" #include "igraph_vector.h" #include "igraph_datatype.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Constructors, games (=stochastic) */ /* -------------------------------------------------- */ DECLDIR int igraph_barabasi_game(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t A, igraph_bool_t directed, igraph_barabasi_algorithm_t algo, const igraph_t *start_from); DECLDIR int igraph_nonlinear_barabasi_game(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t zeroappeal, igraph_bool_t directed); DECLDIR int igraph_erdos_renyi_game(igraph_t *graph, igraph_erdos_renyi_t type, igraph_integer_t n, igraph_real_t p, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_erdos_renyi_game_gnp(igraph_t *graph, igraph_integer_t n, igraph_real_t p, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_erdos_renyi_game_gnm(igraph_t *graph, igraph_integer_t n, igraph_real_t m, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_degree_sequence_game(igraph_t *graph, const igraph_vector_t *out_deg, const igraph_vector_t *in_deg, igraph_degseq_t method); DECLDIR int igraph_growing_random_game(igraph_t *graph, igraph_integer_t n, igraph_integer_t m, igraph_bool_t directed, igraph_bool_t citation); DECLDIR int igraph_barabasi_aging_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t pa_exp, igraph_real_t aging_exp, igraph_integer_t aging_bin, igraph_real_t zero_deg_appeal, igraph_real_t zero_age_appeal, igraph_real_t deg_coef, igraph_real_t age_coef, igraph_bool_t directed); DECLDIR int igraph_recent_degree_game(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t window, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t zero_appeal, igraph_bool_t directed); DECLDIR int igraph_recent_degree_aging_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t pa_exp, igraph_real_t aging_exp, igraph_integer_t aging_bin, igraph_integer_t window, igraph_real_t zero_appeal, igraph_bool_t directed); DECLDIR int igraph_callaway_traits_game (igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_integer_t edges_per_step, igraph_vector_t *type_dist, igraph_matrix_t *pref_matrix, igraph_bool_t directed); DECLDIR int igraph_establishment_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_integer_t k, igraph_vector_t *type_dist, igraph_matrix_t *pref_matrix, igraph_bool_t directed); DECLDIR int igraph_grg_game(igraph_t *graph, igraph_integer_t nodes, igraph_real_t radius, igraph_bool_t torus, igraph_vector_t *x, igraph_vector_t *y); DECLDIR int igraph_preference_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, const igraph_vector_t *type_dist, igraph_bool_t fixed_sizes, const igraph_matrix_t *pref_matrix, igraph_vector_t *node_type_vec, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_asymmetric_preference_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_matrix_t *type_dist_matrix, igraph_matrix_t *pref_matrix, igraph_vector_t *node_type_in_vec, igraph_vector_t *node_type_out_vec, igraph_bool_t loops); DECLDIR int igraph_rewire_edges(igraph_t *graph, igraph_real_t prob, igraph_bool_t loops, igraph_bool_t multiple); DECLDIR int igraph_watts_strogatz_game(igraph_t *graph, igraph_integer_t dim, igraph_integer_t size, igraph_integer_t nei, igraph_real_t p, igraph_bool_t loops, igraph_bool_t multiple); DECLDIR int igraph_lastcit_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t edges_per_node, igraph_integer_t agebins, const igraph_vector_t *preference, igraph_bool_t directed); DECLDIR int igraph_cited_type_game(igraph_t *graph, igraph_integer_t nodes, const igraph_vector_t *types, const igraph_vector_t *pref, igraph_integer_t edges_per_step, igraph_bool_t directed); DECLDIR int igraph_citing_cited_type_game(igraph_t *graph, igraph_integer_t nodes, const igraph_vector_t *types, const igraph_matrix_t *pref, igraph_integer_t edges_per_step, igraph_bool_t directed); DECLDIR int igraph_forest_fire_game(igraph_t *graph, igraph_integer_t nodes, igraph_real_t fw_prob, igraph_real_t bw_factor, igraph_integer_t ambs, igraph_bool_t directed); DECLDIR int igraph_simple_interconnected_islands_game( igraph_t *graph, igraph_integer_t islands_n, igraph_integer_t islands_size, igraph_real_t islands_pin, igraph_integer_t n_inter); DECLDIR int igraph_static_fitness_game(igraph_t *graph, igraph_integer_t no_of_edges, igraph_vector_t* fitness_out, igraph_vector_t* fitness_in, igraph_bool_t loops, igraph_bool_t multiple); DECLDIR int igraph_static_power_law_game(igraph_t *graph, igraph_integer_t no_of_nodes, igraph_integer_t no_of_edges, igraph_real_t exponent_out, igraph_real_t exponent_in, igraph_bool_t loops, igraph_bool_t multiple, igraph_bool_t finite_size_correction); DECLDIR int igraph_k_regular_game(igraph_t *graph, igraph_integer_t no_of_nodes, igraph_integer_t k, igraph_bool_t directed, igraph_bool_t multiple); DECLDIR int igraph_sbm_game(igraph_t *graph, igraph_integer_t n, const igraph_matrix_t *pref_matrix, const igraph_vector_int_t *block_sizes, igraph_bool_t directed, igraph_bool_t loops); DECLDIR int igraph_hsbm_game(igraph_t *graph, igraph_integer_t n, igraph_integer_t m, const igraph_vector_t *rho, const igraph_matrix_t *C, igraph_real_t p); DECLDIR int igraph_hsbm_list_game(igraph_t *graph, igraph_integer_t n, const igraph_vector_int_t *mlist, const igraph_vector_ptr_t *rholist, const igraph_vector_ptr_t *Clist, igraph_real_t p); DECLDIR int igraph_correlated_game(const igraph_t *old_graph, igraph_t *new_graph, igraph_real_t corr, igraph_real_t p, const igraph_vector_t *permutation); DECLDIR int igraph_correlated_pair_game(igraph_t *graph1, igraph_t *graph2, int n, igraph_real_t corr, igraph_real_t p, igraph_bool_t directed, const igraph_vector_t *permutation); DECLDIR int igraph_dot_product_game(igraph_t *graph, const igraph_matrix_t *vecs, igraph_bool_t directed); DECLDIR int igraph_sample_sphere_surface(igraph_integer_t dim, igraph_integer_t n, igraph_real_t radius, igraph_bool_t positive, igraph_matrix_t *res); DECLDIR int igraph_sample_sphere_volume(igraph_integer_t dim, igraph_integer_t n, igraph_real_t radius, igraph_bool_t positive, igraph_matrix_t *res); DECLDIR int igraph_sample_sphere_volume(igraph_integer_t dim, igraph_integer_t n, igraph_real_t radius, igraph_bool_t positive, igraph_matrix_t *res); DECLDIR int igraph_sample_dirichlet(igraph_integer_t n, const igraph_vector_t *alpha, igraph_matrix_t *res); __END_DECLS #endif igraph/src/include/igraph_matching.h0000644000175100001440000000412313431000472017243 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2012 Tamas Nepusz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MATCHING_H #define IGRAPH_MATCHING_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_vector.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Matchings in graphs */ /* -------------------------------------------------- */ DECLDIR int igraph_is_matching(const igraph_t* graph, const igraph_vector_bool_t* types, const igraph_vector_long_t* matching, igraph_bool_t* result); DECLDIR int igraph_is_maximal_matching(const igraph_t* graph, const igraph_vector_bool_t* types, const igraph_vector_long_t* matching, igraph_bool_t* result); DECLDIR int igraph_maximum_bipartite_matching(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights, igraph_real_t eps); DECLDIR int igraph_maximum_matching(const igraph_t* graph, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights); __END_DECLS #endif igraph/src/include/igraph_attributes.h0000644000175100001440000010253413431000472017644 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REST_ATTRIBUTES_H #define REST_ATTRIBUTES_H #include "igraph_decls.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_strvector.h" #include "igraph_vector_ptr.h" #include "igraph_iterators.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Attributes */ /* -------------------------------------------------- */ /** * \section about_attributes * * Attributes are numbers or strings (or basically any kind * of data) associated with the vertices or edges of a graph, or * with the graph itself. Eg. you may label vertices with symbolic names * or attach numeric weights to the edges of a graph. * * igraph attributes are designed to be flexible and extensible. * In igraph attributes are implemented via an interface abstraction: * any type implementing the functions in the interface, can be used * for storing vertex, edge and graph attributes. This means that * different attribute implementations can be used together with * igraph. This is reasonable: if igraph is used from Python attributes can be * of any Python type, from GNU R all R types are allowed. There is an * experimental attribute implementation to be used when programming * in C, but by default it is currently turned off. * * First we briefly look over how attribute handlers can be * implemented. This is not something a user does every day. It is * rather typically the job of the high level interface writers. (But * it is possible to write an interface without implementing * attributes.) Then we show the experimental C attribute handler. */ /** * \section about_attribute_table * It is possible to attach an attribute handling * interface to \a igraph. This is simply a table of functions, of * type \ref igraph_attribute_table_t. These functions are invoked to * notify the attribute handling code about the structural changes in * a graph. See the documentation of this type for details. * * By default there is no attribute interface attached to \a igraph, * to attach one, call \ref igraph_i_set_attribute_table with your new * table. * */ /** * \typedef igraph_attribute_type_t * The possible types of the attributes. * * Note that this is only the * type communicated by the attribute interface towards igraph * functions. Eg. in the GNU R attribute handler, it is safe to say * that all complex R object attributes are strings, as long as this * interface is able to serialize them into strings. See also \ref * igraph_attribute_table_t. * \enumval IGRAPH_ATTRIBUTE_DEFAULT Currently not used for anything. * \enumval IGRAPH_ATTRIBUTE_NUMERIC Numeric attribute. * \enumval IGRAPH_ATTRIBUTE_BOOLEAN Logical values, true or false. * \enumval IGRAPH_ATTRIBUTE_STRING Attribute that can be converted to * a string. * \enumval IGRAPH_ATTRIBUTE_R_OBJECT An R object. This is usually * ignored by the igraph functions. * \enumval IGRAPH_ATTRIBUTE_PY_OBJECT A Python object. Usually * ignored by the igraph functions. * */ typedef enum { IGRAPH_ATTRIBUTE_DEFAULT=0, IGRAPH_ATTRIBUTE_NUMERIC=1, IGRAPH_ATTRIBUTE_BOOLEAN=5, IGRAPH_ATTRIBUTE_STRING=2, IGRAPH_ATTRIBUTE_R_OBJECT=3, IGRAPH_ATTRIBUTE_PY_OBJECT=4 } igraph_attribute_type_t; typedef struct igraph_attribute_record_t { const char *name; igraph_attribute_type_t type; const void *value; } igraph_attribute_record_t; typedef enum { IGRAPH_ATTRIBUTE_GRAPH=0, IGRAPH_ATTRIBUTE_VERTEX, IGRAPH_ATTRIBUTE_EDGE } igraph_attribute_elemtype_t; typedef enum { IGRAPH_ATTRIBUTE_COMBINE_IGNORE=0, IGRAPH_ATTRIBUTE_COMBINE_DEFAULT=1, IGRAPH_ATTRIBUTE_COMBINE_FUNCTION=2, IGRAPH_ATTRIBUTE_COMBINE_SUM=3, IGRAPH_ATTRIBUTE_COMBINE_PROD=4, IGRAPH_ATTRIBUTE_COMBINE_MIN=5, IGRAPH_ATTRIBUTE_COMBINE_MAX=6, IGRAPH_ATTRIBUTE_COMBINE_RANDOM=7, IGRAPH_ATTRIBUTE_COMBINE_FIRST=8, IGRAPH_ATTRIBUTE_COMBINE_LAST=9, IGRAPH_ATTRIBUTE_COMBINE_MEAN=10, IGRAPH_ATTRIBUTE_COMBINE_MEDIAN=11, IGRAPH_ATTRIBUTE_COMBINE_CONCAT=12 } igraph_attribute_combination_type_t; typedef void (*igraph_function_pointer_t)(void); typedef struct igraph_attribute_combination_record_t { const char *name; /* can be NULL, meaning: the rest */ igraph_attribute_combination_type_t type; igraph_function_pointer_t func; } igraph_attribute_combination_record_t; typedef struct igraph_attribute_combination_t { igraph_vector_ptr_t list; } igraph_attribute_combination_t; #define IGRAPH_NO_MORE_ATTRIBUTES ((const char*)0) DECLDIR int igraph_attribute_combination_init(igraph_attribute_combination_t *comb); DECLDIR int igraph_attribute_combination(igraph_attribute_combination_t *comb, ...); DECLDIR void igraph_attribute_combination_destroy(igraph_attribute_combination_t *comb); DECLDIR int igraph_attribute_combination_add(igraph_attribute_combination_t *comb, const char *name, igraph_attribute_combination_type_t type, igraph_function_pointer_t func); DECLDIR int igraph_attribute_combination_remove(igraph_attribute_combination_t *comb, const char *name); DECLDIR int igraph_attribute_combination_query(const igraph_attribute_combination_t *comb, const char *name, igraph_attribute_combination_type_t *type, igraph_function_pointer_t *func); /** * \struct igraph_attribute_table_t * \brief Table of functions to perform operations on attributes * * This type collects the functions defining an attribute handler. * It has the following members: * \member init This function is called whenever a new graph object is * created, right after it is created but before any vertices or * edges are added. It is supposed to set the \c attr member of the \c * igraph_t object. It is expected to return an error code. * \member destroy This function is called whenever the graph object * is destroyed, right before freeing the allocated memory. * \member copy This function is called when copying a graph with \ref * igraph_copy, after the structure of the graph has been already * copied. It is expected to return an error code. * \member add_vertices Called when vertices are added to a * graph, before adding the vertices themselves. * The number of vertices to add is supplied as an * argument. Expected to return an error code. * \member permute_vertices Typically called when a new graph is * created based on an existing one, e.g. if vertices are removed * from a graph. The supplied index vector defines which old vertex * a new vertex corresponds to. Its length must be the same as the * number of vertices in the new graph. * \member combine_vertices This function is called when the creation * of a new graph involves a merge (contraction, etc.) of vertices * from another graph. The function is after the new graph was created. * An argument specifies how several vertices from the old graph map to a * single vertex in the new graph. * \member add_edges Called when new edges have been added. The number * of new edges are supplied as well. It is expected to return an * error code. * \member permute_edges Typically called when a new graph is created and * some of the new edges should carry the attributes of some of the * old edges. The idx vector shows the mapping between the old edges and * the new ones. Its length is the same as the number of edges in the new * graph, and for each edge it gives the id of the old edge (the edge in * the old graph). * \member combine_edges This function is called when the creation * of a new graph involves a merge (contraction, etc.) of edges * from another graph. The function is after the new graph was created. * An argument specifies how several edges from the old graph map to a * single edge in the new graph. * \member get_info Query the attributes of a graph, the names and * types should be returned. * \member has_attr Check whether a graph has the named * graph/vertex/edge attribute. * \member gettype Query the type of a graph/vertex/edge attribute. * \member get_numeric_graph_attr Query a numeric graph attribute. The * value should be placed as the first element of the \p value * vector. * \member get_string_graph_attr Query a string graph attribute. The * value should be placed as the first element of the \p value * string vector. * \member get_bool_graph_attr Query a boolean graph attribute. The * value should be placed as the first element of the \p value * boolean vector. * \member get_numeric_vertex_attr Query a numeric vertex attribute, * for the vertices included in \p vs. * \member get_string_vertex_attr Query a string vertex attribute, * for the vertices included in \p vs. * \member get_bool_vertex_attr Query a boolean vertex attribute, * for the vertices included in \p vs. * \member get_numeric_edge_attr Query a numeric edge attribute, for * the edges included in \p es. * \member get_string_edge_attr Query a string edge attribute, for the * edges included in \p es. * \member get_bool_edge_attr Query a boolean edge attribute, for the * edges included in \p es. * * Note that the get_*_*_attr are allowed to * convert the attributes to numeric or string. E.g. if a vertex attribute * is a GNU R complex data type, then * get_string_vertex_attribute may serialize it * into a string, but this probably makes sense only if * add_vertices is able to deserialize it. */ typedef struct igraph_attribute_table_t { int (*init)(igraph_t *graph, igraph_vector_ptr_t *attr); void (*destroy)(igraph_t *graph); int (*copy)(igraph_t *to, const igraph_t *from, igraph_bool_t ga, igraph_bool_t va, igraph_bool_t ea); int (*add_vertices)(igraph_t *graph, long int nv, igraph_vector_ptr_t *attr); int (*permute_vertices)(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx); int (*combine_vertices)(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb); int (*add_edges)(igraph_t *graph, const igraph_vector_t *edges, igraph_vector_ptr_t *attr); int (*permute_edges)(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx); int (*combine_edges)(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb); int (*get_info)(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes); igraph_bool_t (*has_attr)(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name); int (*gettype)(const igraph_t *graph, igraph_attribute_type_t *type, igraph_attribute_elemtype_t elemtype, const char *name); int (*get_numeric_graph_attr)(const igraph_t *graph, const char *name, igraph_vector_t *value); int (*get_string_graph_attr)(const igraph_t *graph, const char *name, igraph_strvector_t *value); int (*get_bool_graph_attr)(const igraph_t *igraph, const char *name, igraph_vector_bool_t *value); int (*get_numeric_vertex_attr)(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_t *value); int (*get_string_vertex_attr)(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_strvector_t *value); int (*get_bool_vertex_attr)(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_bool_t *value); int (*get_numeric_edge_attr)(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_t *value); int (*get_string_edge_attr)(const igraph_t *graph, const char *name, igraph_es_t es, igraph_strvector_t *value); int (*get_bool_edge_attr)(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_bool_t *value); } igraph_attribute_table_t; DECLDIR igraph_attribute_table_t * igraph_i_set_attribute_table(const igraph_attribute_table_t * table); DECLDIR igraph_bool_t igraph_has_attribute_table(void); #define IGRAPH_I_ATTRIBUTE_DESTROY(graph) \ do {if ((graph)->attr) igraph_i_attribute_destroy(graph);} while(0) #define IGRAPH_I_ATTRIBUTE_COPY(to,from,ga,va,ea) do { \ int igraph_i_ret2=0; \ if ((from)->attr) { \ IGRAPH_CHECK(igraph_i_ret2=igraph_i_attribute_copy((to),(from),(ga),(va),(ea))); \ } else { \ (to)->attr = 0; \ } \ if (igraph_i_ret2 != 0) { \ IGRAPH_ERROR("", igraph_i_ret2); \ } \ } while(0) int igraph_i_attribute_init(igraph_t *graph, void *attr); void igraph_i_attribute_destroy(igraph_t *graph); int igraph_i_attribute_copy(igraph_t *to, const igraph_t *from, igraph_bool_t ga, igraph_bool_t va, igraph_bool_t ea); int igraph_i_attribute_add_vertices(igraph_t *graph, long int nv, void *attr); int igraph_i_attribute_permute_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx); int igraph_i_attribute_combine_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb); int igraph_i_attribute_add_edges(igraph_t *graph, const igraph_vector_t *edges, void *attr); int igraph_i_attribute_permute_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx); int igraph_i_attribute_combine_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb); int igraph_i_attribute_get_info(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes); igraph_bool_t igraph_i_attribute_has_attr(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name); int igraph_i_attribute_gettype(const igraph_t *graph, igraph_attribute_type_t *type, igraph_attribute_elemtype_t elemtype, const char *name); int igraph_i_attribute_get_numeric_graph_attr(const igraph_t *graph, const char *name, igraph_vector_t *value); int igraph_i_attribute_get_numeric_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_t *value); int igraph_i_attribute_get_numeric_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_t *value); int igraph_i_attribute_get_string_graph_attr(const igraph_t *graph, const char *name, igraph_strvector_t *value); int igraph_i_attribute_get_string_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_strvector_t *value); int igraph_i_attribute_get_string_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_strvector_t *value); int igraph_i_attribute_get_bool_graph_attr(const igraph_t *graph, const char *name, igraph_vector_bool_t *value); int igraph_i_attribute_get_bool_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_bool_t *value); int igraph_i_attribute_get_bool_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_bool_t *value); /* Experimental attribute handler in C */ extern const igraph_attribute_table_t igraph_cattribute_table; DECLDIR igraph_real_t igraph_cattribute_GAN(const igraph_t *graph, const char *name); DECLDIR igraph_bool_t igraph_cattribute_GAB(const igraph_t *graph, const char *name); DECLDIR const char* igraph_cattribute_GAS(const igraph_t *graph, const char *name); DECLDIR igraph_real_t igraph_cattribute_VAN(const igraph_t *graph, const char *name, igraph_integer_t vid); DECLDIR igraph_bool_t igraph_cattribute_VAB(const igraph_t *graph, const char *name, igraph_integer_t vid); DECLDIR const char* igraph_cattribute_VAS(const igraph_t *graph, const char *name, igraph_integer_t vid); DECLDIR igraph_real_t igraph_cattribute_EAN(const igraph_t *graph, const char *name, igraph_integer_t eid); DECLDIR igraph_bool_t igraph_cattribute_EAB(const igraph_t *graph, const char *name, igraph_integer_t eid); DECLDIR const char* igraph_cattribute_EAS(const igraph_t *graph, const char *name, igraph_integer_t eid); DECLDIR int igraph_cattribute_VANV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_vector_t *result); DECLDIR int igraph_cattribute_EANV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_vector_t *result); DECLDIR int igraph_cattribute_VASV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_strvector_t *result); DECLDIR int igraph_cattribute_EASV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_strvector_t *result); DECLDIR int igraph_cattribute_VABV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_vector_bool_t *result); DECLDIR int igraph_cattribute_EABV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_vector_bool_t *result); DECLDIR int igraph_cattribute_list(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes); DECLDIR igraph_bool_t igraph_cattribute_has_attr(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name); DECLDIR int igraph_cattribute_GAN_set(igraph_t *graph, const char *name, igraph_real_t value); DECLDIR int igraph_cattribute_GAB_set(igraph_t *graph, const char *name, igraph_bool_t value); DECLDIR int igraph_cattribute_GAS_set(igraph_t *graph, const char *name, const char *value); DECLDIR int igraph_cattribute_VAN_set(igraph_t *graph, const char *name, igraph_integer_t vid, igraph_real_t value); DECLDIR int igraph_cattribute_VAB_set(igraph_t *graph, const char *name, igraph_integer_t vid, igraph_bool_t value); DECLDIR int igraph_cattribute_VAS_set(igraph_t *graph, const char *name, igraph_integer_t vid, const char *value); DECLDIR int igraph_cattribute_EAN_set(igraph_t *graph, const char *name, igraph_integer_t eid, igraph_real_t value); DECLDIR int igraph_cattribute_EAB_set(igraph_t *graph, const char *name, igraph_integer_t eid, igraph_bool_t value); DECLDIR int igraph_cattribute_EAS_set(igraph_t *graph, const char *name, igraph_integer_t eid, const char *value); DECLDIR int igraph_cattribute_VAN_setv(igraph_t *graph, const char *name, const igraph_vector_t *v); DECLDIR int igraph_cattribute_VAB_setv(igraph_t *graph, const char *name, const igraph_vector_bool_t *v); DECLDIR int igraph_cattribute_VAS_setv(igraph_t *graph, const char *name, const igraph_strvector_t *sv); DECLDIR int igraph_cattribute_EAN_setv(igraph_t *graph, const char *name, const igraph_vector_t *v); DECLDIR int igraph_cattribute_EAB_setv(igraph_t *graph, const char *name, const igraph_vector_bool_t *v); DECLDIR int igraph_cattribute_EAS_setv(igraph_t *graph, const char *name, const igraph_strvector_t *sv); DECLDIR void igraph_cattribute_remove_g(igraph_t *graph, const char *name); DECLDIR void igraph_cattribute_remove_v(igraph_t *graph, const char *name); DECLDIR void igraph_cattribute_remove_e(igraph_t *graph, const char *name); DECLDIR void igraph_cattribute_remove_all(igraph_t *graph, igraph_bool_t g, igraph_bool_t v, igraph_bool_t e); /** * \define GAN * Query a numeric graph attribute. * * This is shorthand for \ref igraph_cattribute_GAN(). * \param graph The graph. * \param n The name of the attribute. * \return The value of the attribute. */ #define GAN(graph,n) (igraph_cattribute_GAN((graph), (n))) /** * \define GAB * Query a boolean graph attribute. * * This is shorthand for \ref igraph_cattribute_GAB(). * \param graph The graph. * \param n The name of the attribute. * \return The value of the attribute. */ #define GAB(graph,n) (igraph_cattribute_GAB((graph), (n))) /** * \define GAS * Query a string graph attribute. * * This is shorthand for \ref igraph_cattribute_GAS(). * \param graph The graph. * \param n The name of the attribute. * \return The value of the attribute. */ #define GAS(graph,n) (igraph_cattribute_GAS((graph), (n))) /** * \define VAN * Query a numeric vertex attribute. * * This is shorthand for \ref igraph_cattribute_VAN(). * \param graph The graph. * \param n The name of the attribute. * \param v The id of the vertex. * \return The value of the attribute. */ #define VAN(graph,n,v) (igraph_cattribute_VAN((graph), (n), (v))) /** * \define VAB * Query a boolean vertex attribute. * * This is shorthand for \ref igraph_cattribute_VAB(). * \param graph The graph. * \param n The name of the attribute. * \param v The id of the vertex. * \return The value of the attribute. */ #define VAB(graph,n,v) (igraph_cattribute_VAB((graph), (n), (v))) /** * \define VAS * Query a string vertex attribute. * * This is shorthand for \ref igraph_cattribute_VAS(). * \param graph The graph. * \param n The name of the attribute. * \param v The id of the vertex. * \return The value of the attribute. */ #define VAS(graph,n,v) (igraph_cattribute_VAS((graph), (n), (v))) /** * \define VANV * Query a numeric vertex attribute for all vertices. * * This is a shorthand for \ref igraph_cattribute_VANV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define VANV(graph,n,vec) (igraph_cattribute_VANV((graph),(n), \ igraph_vss_all(), (vec))) /** * \define VABV * Query a boolean vertex attribute for all vertices. * * This is a shorthand for \ref igraph_cattribute_VABV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized boolean vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define VABV(graph,n,vec) (igraph_cattribute_VABV((graph),(n), \ igraph_vss_all(), (vec))) /** * \define VASV * Query a string vertex attribute for all vertices. * * This is a shorthand for \ref igraph_cattribute_VASV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized string vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define VASV(graph,n,vec) (igraph_cattribute_VASV((graph),(n), \ igraph_vss_all(), (vec))) /** * \define EAN * Query a numeric edge attribute. * * This is shorthand for \ref igraph_cattribute_EAN(). * \param graph The graph. * \param n The name of the attribute. * \param e The id of the edge. * \return The value of the attribute. */ #define EAN(graph,n,e) (igraph_cattribute_EAN((graph), (n), (e))) /** * \define EAB * Query a boolean edge attribute. * * This is shorthand for \ref igraph_cattribute_EAB(). * \param graph The graph. * \param n The name of the attribute. * \param e The id of the edge. * \return The value of the attribute. */ #define EAB(graph,n,e) (igraph_cattribute_EAB((graph), (n), (e))) /** * \define EAS * Query a string edge attribute. * * This is shorthand for \ref igraph_cattribute_EAS(). * \param graph The graph. * \param n The name of the attribute. * \param e The id of the edge. * \return The value of the attribute. */ #define EAS(graph,n,e) (igraph_cattribute_EAS((graph), (n), (e))) /** * \define EANV * Query a numeric edge attribute for all edges. * * This is a shorthand for \ref igraph_cattribute_EANV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define EANV(graph,n,vec) (igraph_cattribute_EANV((graph),(n), \ igraph_ess_all(IGRAPH_EDGEORDER_ID), (vec))) /** * \define EABV * Query a boolean edge attribute for all edges. * * This is a shorthand for \ref igraph_cattribute_EABV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define EABV(graph,n,vec) (igraph_cattribute_EABV((graph),(n), \ igraph_ess_all(IGRAPH_EDGEORDER_ID), (vec))) /** * \define EASV * Query a string edge attribute for all edges. * * This is a shorthand for \ref igraph_cattribute_EASV(). * \param graph The graph. * \param n The name of the attribute. * \param vec Pointer to an initialized string vector, the result is * stored here. It will be resized, if needed. * \return Error code. */ #define EASV(graph,n,vec) (igraph_cattribute_EASV((graph),(n), \ igraph_ess_all(IGRAPH_EDGEORDER_ID), (vec))) /** * \define SETGAN * Set a numeric graph attribute * * This is a shorthand for \ref igraph_cattribute_GAN_set(). * \param graph The graph. * \param n The name of the attribute. * \param value The new value of the attribute. * \return Error code. */ #define SETGAN(graph,n,value) (igraph_cattribute_GAN_set((graph),(n),(value))) /** * \define SETGAB * Set a boolean graph attribute * * This is a shorthand for \ref igraph_cattribute_GAB_set(). * \param graph The graph. * \param n The name of the attribute. * \param value The new value of the attribute. * \return Error code. */ #define SETGAB(graph,n,value) (igraph_cattribute_GAB_set((graph),(n),(value))) /** * \define SETGAS * Set a string graph attribute * * This is a shorthand for \ref igraph_cattribute_GAS_set(). * \param graph The graph. * \param n The name of the attribute. * \param value The new value of the attribute. * \return Error code. */ #define SETGAS(graph,n,value) (igraph_cattribute_GAS_set((graph),(n),(value))) /** * \define SETVAN * Set a numeric vertex attribute * * This is a shorthand for \ref igraph_cattribute_VAN_set(). * \param graph The graph. * \param n The name of the attribute. * \param vid Ids of the vertices to set. * \param value The new value of the attribute. * \return Error code. */ #define SETVAN(graph,n,vid,value) (igraph_cattribute_VAN_set((graph),(n),(vid),(value))) /** * \define SETVAB * Set a boolean vertex attribute * * This is a shorthand for \ref igraph_cattribute_VAB_set(). * \param graph The graph. * \param n The name of the attribute. * \param vid Ids of the vertices to set. * \param value The new value of the attribute. * \return Error code. */ #define SETVAB(graph,n,vid,value) (igraph_cattribute_VAB_set((graph),(n),(vid),(value))) /** * \define SETVAS * Set a string vertex attribute * * This is a shorthand for \ref igraph_cattribute_VAS_set(). * \param graph The graph. * \param n The name of the attribute. * \param vid Ids of the vertices to set. * \param value The new value of the attribute. * \return Error code. */ #define SETVAS(graph,n,vid,value) (igraph_cattribute_VAS_set((graph),(n),(vid),(value))) /** * \define SETEAN * Set a numeric edge attribute * * This is a shorthand for \ref igraph_cattribute_EAN_set(). * \param graph The graph. * \param n The name of the attribute. * \param eid Ids of the edges to set. * \param value The new value of the attribute. * \return Error code. */ #define SETEAN(graph,n,eid,value) (igraph_cattribute_EAN_set((graph),(n),(eid),(value))) /** * \define SETEAB * Set a boolean edge attribute * * This is a shorthand for \ref igraph_cattribute_EAB_set(). * \param graph The graph. * \param n The name of the attribute. * \param eid Ids of the edges to set. * \param value The new value of the attribute. * \return Error code. */ #define SETEAB(graph,n,eid,value) (igraph_cattribute_EAB_set((graph),(n),(eid),(value))) /** * \define SETEAS * Set a string edge attribute * * This is a shorthand for \ref igraph_cattribute_EAS_set(). * \param graph The graph. * \param n The name of the attribute. * \param eid Ids of the edges to set. * \param value The new value of the attribute. * \return Error code. */ #define SETEAS(graph,n,eid,value) (igraph_cattribute_EAS_set((graph),(n),(eid),(value))) /** * \define SETVANV * Set a numeric vertex attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_VAN_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. * \return Error code. */ #define SETVANV(graph,n,v) (igraph_cattribute_VAN_setv((graph),(n),(v))) /** * \define SETVABV * Set a boolean vertex attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_VAB_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. * \return Error code. */ #define SETVABV(graph,n,v) (igraph_cattribute_VAB_setv((graph),(n),(v))) /** * \define SETVASV * Set a string vertex attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_VAS_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. * \return Error code. */ #define SETVASV(graph,n,v) (igraph_cattribute_VAS_setv((graph),(n),(v))) /** * \define SETEANV * Set a numeric edge attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_EAN_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. */ #define SETEANV(graph,n,v) (igraph_cattribute_EAN_setv((graph),(n),(v))) /** * \define SETEABV * Set a boolean edge attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_EAB_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. */ #define SETEABV(graph,n,v) (igraph_cattribute_EAB_setv((graph),(n),(v))) /** * \define SETEASV * Set a string edge attribute for all vertices * * This is a shorthand for \ref igraph_cattribute_EAS_setv(). * \param graph The graph. * \param n The name of the attribute. * \param v Vector containing the new values of the attributes. */ #define SETEASV(graph,n,v) (igraph_cattribute_EAS_setv((graph),(n),(v))) /** * \define DELGA * Remove a graph attribute. * * A shorthand for \ref igraph_cattribute_remove_g(). * \param graph The graph. * \param n The name of the attribute to remove. */ #define DELGA(graph,n) (igraph_cattribute_remove_g((graph),(n))) /** * \define DELVA * Remove a vertex attribute. * * A shorthand for \ref igraph_cattribute_remove_v(). * \param graph The graph. * \param n The name of the attribute to remove. */ #define DELVA(graph,n) (igraph_cattribute_remove_v((graph),(n))) /** * \define DELEA * Remove an edge attribute. * * A shorthand for \ref igraph_cattribute_remove_e(). * \param graph The graph. * \param n The name of the attribute to remove. */ #define DELEA(graph,n) (igraph_cattribute_remove_e((graph),(n))) /** * \define DELGAS * Remove all graph attributes. * * Calls \ref igraph_cattribute_remove_all(). * \param graph The graph. */ #define DELGAS(graph) (igraph_cattribute_remove_all((graph),1,0,0)) /** * \define DELVAS * Remove all vertex attributes. * * Calls \ref igraph_cattribute_remove_all(). * \param graph The graph. */ #define DELVAS(graph) (igraph_cattribute_remove_all((graph),0,1,0)) /** * \define DELEAS * Remove all edge attributes. * * Calls \ref igraph_cattribute_remove_all(). * \param graph The graph. */ #define DELEAS(graph) (igraph_cattribute_remove_all((graph),0,0,1)) /** * \define DELALL * Remove all attributes. * * All graph, vertex and edges attributes will be removed. * Calls \ref igraph_cattribute_remove_all(). * \param graph The graph. */ #define DELALL(graph) (igraph_cattribute_remove_all((graph),1,1,1)) __END_DECLS #endif igraph/src/include/igraph_structural.h0000644000175100001440000001510213431000472017660 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_STRUCTURAL_H #define IGRAPH_STRUCTURAL_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_datatype.h" #include "igraph_iterators.h" #include "igraph_attributes.h" #include "igraph_sparsemat.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Basic query functions */ /* -------------------------------------------------- */ DECLDIR int igraph_are_connected(const igraph_t *graph, igraph_integer_t v1, igraph_integer_t v2, igraph_bool_t *res); /* -------------------------------------------------- */ /* Structural properties */ /* -------------------------------------------------- */ DECLDIR int igraph_minimum_spanning_tree(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights); DECLDIR int igraph_minimum_spanning_tree_unweighted(const igraph_t *graph, igraph_t *mst); DECLDIR int igraph_minimum_spanning_tree_prim(const igraph_t *graph, igraph_t *mst, const igraph_vector_t *weights); DECLDIR int igraph_subcomponent(const igraph_t *graph, igraph_vector_t *res, igraph_real_t vid, igraph_neimode_t mode); DECLDIR int igraph_rewire(igraph_t *graph, igraph_integer_t n, igraph_rewiring_t mode); DECLDIR int igraph_subgraph(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids); DECLDIR int igraph_induced_subgraph_map(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_subgraph_implementation_t impl, igraph_vector_t *map, igraph_vector_t *invmap); DECLDIR int igraph_induced_subgraph(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_subgraph_implementation_t impl); DECLDIR int igraph_subgraph_edges(const igraph_t *graph, igraph_t *res, const igraph_es_t eids, igraph_bool_t delete_vertices); DECLDIR int igraph_simplify(igraph_t *graph, igraph_bool_t multiple, igraph_bool_t loops, const igraph_attribute_combination_t *edge_comb); DECLDIR int igraph_reciprocity(const igraph_t *graph, igraph_real_t *res, igraph_bool_t ignore_loops, igraph_reciprocity_t mode); DECLDIR int igraph_maxdegree(const igraph_t *graph, igraph_integer_t *res, igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_density(const igraph_t *graph, igraph_real_t *res, igraph_bool_t loops); DECLDIR int igraph_has_loop(const igraph_t *graph, igraph_bool_t *res); DECLDIR int igraph_is_loop(const igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es); DECLDIR int igraph_is_simple(const igraph_t *graph, igraph_bool_t *res); DECLDIR int igraph_has_multiple(const igraph_t *graph, igraph_bool_t *res); DECLDIR int igraph_is_multiple(const igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es); DECLDIR int igraph_count_multiple(const igraph_t *graph, igraph_vector_t *res, igraph_es_t es); DECLDIR int igraph_girth(const igraph_t *graph, igraph_integer_t *girth, igraph_vector_t *circle); DECLDIR int igraph_add_edge(igraph_t *graph, igraph_integer_t from, igraph_integer_t to); DECLDIR int igraph_unfold_tree(const igraph_t *graph, igraph_t *tree, igraph_neimode_t mode, const igraph_vector_t *roots, igraph_vector_t *vertex_index); DECLDIR int igraph_is_mutual(igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es); DECLDIR int igraph_maximum_cardinality_search(const igraph_t *graph, igraph_vector_t *alpha, igraph_vector_t *alpham1); DECLDIR int igraph_is_chordal(const igraph_t *graph, const igraph_vector_t *alpha, const igraph_vector_t *alpham1, igraph_bool_t *chordal, igraph_vector_t *fill_in, igraph_t *newgraph); DECLDIR int igraph_avg_nearest_neighbor_degree(const igraph_t *graph, igraph_vs_t vids, igraph_vector_t *knn, igraph_vector_t *knnk, const igraph_vector_t *weights); DECLDIR int igraph_contract_vertices(igraph_t *graph, const igraph_vector_t *mapping, const igraph_attribute_combination_t *vertex_comb); DECLDIR int igraph_transitive_closure_dag(const igraph_t *graph, igraph_t *closure); DECLDIR int igraph_feedback_arc_set(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_fas_algorithm_t algo); DECLDIR int igraph_diversity(igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *res, const igraph_vs_t vs); /* -------------------------------------------------- */ /* Spectral Properties */ /* -------------------------------------------------- */ DECLDIR int igraph_laplacian(const igraph_t *graph, igraph_matrix_t *res, igraph_sparsemat_t *sparseres, igraph_bool_t normalized, const igraph_vector_t *weights); /* -------------------------------------------------- */ /* Internal functions, may change any time */ /* -------------------------------------------------- */ int igraph_i_feedback_arc_set_undirected(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_vector_t *layering); int igraph_i_feedback_arc_set_eades(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights, igraph_vector_t *layering); __END_DECLS #endif igraph/src/include/igraph_threading.h.in0000644000175100001440000000227013430770210020027 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_THREADING_H #define IGRAPH_THREADING_H #include "igraph_decls.h" __BEGIN_DECLS /** * \define IGRAPH_THREAD_SAFE * * Macro that is defined to be 1 if the current build of the * igraph library is thread-safe, and 0 if it is not. */ #define IGRAPH_THREAD_SAFE @HAVE_TLS@ __END_DECLS #endif igraph/src/include/igraph_coloring.h0000644000175100001440000000112113431000472017260 0ustar hornikusers#ifndef IGRAPH_COLORING_H #define IGRAPH_COLORING_H #include "igraph_datatype.h" __BEGIN_DECLS /** * \typedef igraph_coloring_greedy_t * Ordering heuristics for igraph_vertex_coloring_greedy * * \enumval IGRAPH_COLORING_GREEDY_COLORED_NEIGHBORS Choose vertex with largest number of already colored neighbors. * */ typedef enum { IGRAPH_COLORING_GREEDY_COLORED_NEIGHBORS = 0 } igraph_coloring_greedy_t; DECLDIR int igraph_vertex_coloring_greedy(const igraph_t *graph, igraph_vector_int_t *colors, igraph_coloring_greedy_t heuristic); __END_DECLS #endif /* IGRAPH_COLORING_H */ igraph/src/include/igraph_operators.h0000644000175100001440000000473313431000472017476 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_OPERATORS_H #define IGRAPH_OPERATORS_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Graph operators */ /* -------------------------------------------------- */ DECLDIR int igraph_disjoint_union(igraph_t *res, const igraph_t *left, const igraph_t *right); DECLDIR int igraph_disjoint_union_many(igraph_t *res, const igraph_vector_ptr_t *graphs); DECLDIR int igraph_union(igraph_t *res, const igraph_t *left, const igraph_t *right, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2); DECLDIR int igraph_union_many(igraph_t *res, const igraph_vector_ptr_t *graphs, igraph_vector_ptr_t *edgemaps); DECLDIR int igraph_intersection(igraph_t *res, const igraph_t *left, const igraph_t *right, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2); DECLDIR int igraph_intersection_many(igraph_t *res, const igraph_vector_ptr_t *graphs, igraph_vector_ptr_t *edgemaps); DECLDIR int igraph_difference(igraph_t *res, const igraph_t *orig, const igraph_t *sub); DECLDIR int igraph_complementer(igraph_t *res, const igraph_t *graph, igraph_bool_t loops); DECLDIR int igraph_compose(igraph_t *res, const igraph_t *g1, const igraph_t *g2, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2); __END_DECLS #endif igraph/src/include/igraph_dqueue_pmt.h0000644000175100001440000000415713431000472017630 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Double ended queue data type. * \ingroup internal */ typedef struct TYPE(igraph_dqueue) { BASE *begin; BASE *end; BASE *stor_begin; BASE *stor_end; } TYPE(igraph_dqueue); DECLDIR int FUNCTION(igraph_dqueue,init) (TYPE(igraph_dqueue)* q, long int size); DECLDIR void FUNCTION(igraph_dqueue,destroy) (TYPE(igraph_dqueue)* q); DECLDIR igraph_bool_t FUNCTION(igraph_dqueue,empty) (const TYPE(igraph_dqueue)* q); DECLDIR void FUNCTION(igraph_dqueue,clear) (TYPE(igraph_dqueue)* q); DECLDIR igraph_bool_t FUNCTION(igraph_dqueue,full) (TYPE(igraph_dqueue)* q); DECLDIR long int FUNCTION(igraph_dqueue,size) (const TYPE(igraph_dqueue)* q); DECLDIR BASE FUNCTION(igraph_dqueue,pop) (TYPE(igraph_dqueue)* q); DECLDIR BASE FUNCTION(igraph_dqueue,pop_back)(TYPE(igraph_dqueue)* q); DECLDIR BASE FUNCTION(igraph_dqueue,head) (const TYPE(igraph_dqueue)* q); DECLDIR BASE FUNCTION(igraph_dqueue,back) (const TYPE(igraph_dqueue)* q); DECLDIR int FUNCTION(igraph_dqueue,push) (TYPE(igraph_dqueue)* q, BASE elem); int FUNCTION(igraph_dqueue,print)(const TYPE(igraph_dqueue)* q); int FUNCTION(igraph_dqueue,fprint)(const TYPE(igraph_dqueue)* q, FILE *file); DECLDIR BASE FUNCTION(igraph_dqueue,e)(const TYPE(igraph_dqueue) *q, long int idx); igraph/src/include/igraph_cocitation.h0000644000175100001440000000531613431000472017612 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_COCITATION_H #define IGRAPH_COCITATION_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_matrix.h" #include "igraph_datatype.h" #include "igraph_iterators.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Cocitation and other similarity measures */ /* -------------------------------------------------- */ DECLDIR int igraph_cocitation(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids); DECLDIR int igraph_bibcoupling(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids); DECLDIR int igraph_similarity_jaccard(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_jaccard_pairs(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *pairs, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_jaccard_es(const igraph_t *graph, igraph_vector_t *res, const igraph_es_t es, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_dice(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_dice_pairs(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *pairs, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_dice_es(const igraph_t *graph, igraph_vector_t *res, const igraph_es_t es, igraph_neimode_t mode, igraph_bool_t loops); DECLDIR int igraph_similarity_inverse_log_weighted(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode); __END_DECLS #endif igraph/src/include/igraph_psumtree.h0000644000175100001440000000326113431000472017317 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_PSUMTREE_H #define IGRAPH_PSUMTREE_H #include "igraph_decls.h" #include "igraph_vector.h" __BEGIN_DECLS typedef struct { igraph_vector_t v; long int size; long int offset; } igraph_psumtree_t; DECLDIR int igraph_psumtree_init(igraph_psumtree_t *t, long int size); DECLDIR void igraph_psumtree_destroy(igraph_psumtree_t *t); DECLDIR igraph_real_t igraph_psumtree_get(const igraph_psumtree_t *t, long int idx); DECLDIR long int igraph_psumtree_size(const igraph_psumtree_t *t); DECLDIR int igraph_psumtree_search(const igraph_psumtree_t *t, long int *idx, igraph_real_t elem); DECLDIR int igraph_psumtree_update(igraph_psumtree_t *t, long int idx, igraph_real_t new_value); DECLDIR igraph_real_t igraph_psumtree_sum(const igraph_psumtree_t *t); __END_DECLS #endif igraph/src/include/igraph_paths.h0000644000175100001440000001350613431000472016575 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_PATHS_H #define IGRAPH_PATHS_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_matrix.h" #include "igraph_iterators.h" __BEGIN_DECLS DECLDIR int igraph_diameter(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t *from, igraph_integer_t *to, igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t unconn); DECLDIR int igraph_diameter_dijkstra(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *pres, igraph_integer_t *pfrom, igraph_integer_t *pto, igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t unconn); DECLDIR int igraph_shortest_paths(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, igraph_neimode_t mode); DECLDIR int igraph_get_shortest_paths(const igraph_t *graph, igraph_vector_ptr_t *vertices, igraph_vector_ptr_t *edges, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode, igraph_vector_long_t *predecessors, igraph_vector_long_t *inbound_edges); DECLDIR int igraph_get_shortest_path(const igraph_t *graph, igraph_vector_t *vertices, igraph_vector_t *edges, igraph_integer_t from, igraph_integer_t to, igraph_neimode_t mode); DECLDIR int igraph_get_all_shortest_paths(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vector_t *nrgeo, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode); DECLDIR int igraph_shortest_paths_dijkstra(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_shortest_paths_bellman_ford(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_get_shortest_paths_dijkstra(const igraph_t *graph, igraph_vector_ptr_t *vertices, igraph_vector_ptr_t *edges, igraph_integer_t from, igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode, igraph_vector_long_t *predecessors, igraph_vector_long_t *inbound_edges); DECLDIR int igraph_get_shortest_path_dijkstra(const igraph_t *graph, igraph_vector_t *vertices, igraph_vector_t *edges, igraph_integer_t from, igraph_integer_t to, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_get_all_shortest_paths_dijkstra(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vector_t *nrgeo, igraph_integer_t from, igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode); DECLDIR int igraph_shortest_paths_johnson(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, const igraph_vector_t *weights); DECLDIR int igraph_average_path_length(const igraph_t *graph, igraph_real_t *res, igraph_bool_t directed, igraph_bool_t unconn); DECLDIR int igraph_path_length_hist(const igraph_t *graph, igraph_vector_t *res, igraph_real_t *unconnected, igraph_bool_t directed); DECLDIR int igraph_eccentricity(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, igraph_neimode_t mode); DECLDIR int igraph_radius(const igraph_t *graph, igraph_real_t *radius, igraph_neimode_t mode); DECLDIR int igraph_get_all_simple_paths(const igraph_t *graph, igraph_vector_int_t *res, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode); DECLDIR int igraph_random_walk(const igraph_t *graph, igraph_vector_t *walk, igraph_integer_t start, igraph_neimode_t mode, igraph_integer_t steps, igraph_random_walk_stuck_t stuck); DECLDIR int igraph_random_edge_walk(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *edgewalk, igraph_integer_t start, igraph_neimode_t mode, igraph_integer_t steps, igraph_random_walk_stuck_t stuck); __END_DECLS #endif igraph/src/include/igraph_progress.h0000644000175100001440000001534413431000472017324 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_PROGRESS_H #define IGRAPH_PROGRESS_H #include "igraph_decls.h" #include "igraph_types.h" __BEGIN_DECLS /** * \section about_progress_handlers About progress handlers * * It is often useful to report the progress of some long * calculation, to allow the user to follow the computation and * guess the total running time. A couple of igraph functions * support this at the time of writing, hopefully more will support it * in the future. * * * * To see the progress of a computation, the user has to install a * progress handler, as there is none installed by default. * If an igraph function supports progress reporting, then it * calls the installed progress handler periodically, and passes a * percentage value to it, the percentage of computation already * performed. To install a progress handler, you need to call * \ref igraph_set_progress_handler(). Currently there is a single * pre-defined progress handler, called \ref * igraph_progress_handler_stderr(). * */ /** * \section writing_progress_handlers Writing progress handlers * * * To write a new progress handler, one needs to create a function of * type \ref igraph_progress_handler_t. The new progress handler * can then be installed with the \ref igraph_set_progress_handler() * function. * * * * One can assume that the first progress handler call from a * calculation will be call with zero as the \p percentage argument, * and the last call from a function will have 100 as the \p * percentage argument. Note, however, that if an error happens in the * middle of a computation, then the 100 percent call might be * omitted. * */ /** * \section igraph_functions_with_progress Writing igraph functions with progress reporting * * * If you want to write a function that uses igraph and supports * progress reporting, you need to include \ref igraph_progress() * calls in your function, usually via the \ref IGRAPH_PROGRESS() * macro. * * * * It is good practice to always include a call to \ref * igraph_progress() with a zero \p percentage argument, before the * computation; and another call with 100 \p percentage value * after the computation is completed. * * * * It is also good practice \em not to call \ref igraph_progress() too * often, as this would slow down the computation. It might not be * worth to support progress reporting in functions with linear or * log-linear time complexity, as these are fast, even with a large * amount of data. For functions with quadratic or higher time * complexity make sure that the time complexity of the progress * reporting is constant or at least linear. In practice this means * having at most O(n) progress checks and at most 100 \reg * igraph_progress() calls. * */ /** * \section progress_and_threads Multi-threaded programs * * * In multi-threaded programs, each thread has its own progress * handler, if thread-local storage is supported and igraph is * thread-safe. See the \ref IGRAPH_THREAD_SAFE macro for checking * whether an igraph build is thread-safe. * */ /* -------------------------------------------------- */ /* Progress handlers */ /* -------------------------------------------------- */ /** * \typedef igraph_progress_handler_t * \brief Type of progress handler functions * * This is the type of the igraph progress handler functions. * There is currently one such predefined function, * \ref igraph_progress_handler_stderr(), but the user can * write and set up more sophisticated ones. * \param message A string describing the function or algorithm * that is reporting the progress. Current igraph functions * always use the name \p message argument if reporting from the * same function. * \param percent Numeric, the percentage that was completed by the * algorithm or function. * \param data User-defined data. Current igraph functions that * report progress pass a null pointer here. Users can * write their own progress handlers and functions with progress * reporting, and then pass some meaningfull context here. * \return If the return value of the progress handler is not * IGRAPH_SUCCESS (=0), then \ref igraph_progress() returns the * error code \c IGRAPH_INTERRUPTED. The \ref IGRAPH_PROGRESS() * macro frees all memory and finishes the igraph function with * error code \c IGRAPH_INTERRUPTED in this case. */ typedef int igraph_progress_handler_t(const char *message, igraph_real_t percent, void *data); extern igraph_progress_handler_t igraph_progress_handler_stderr; DECLDIR igraph_progress_handler_t * igraph_set_progress_handler(igraph_progress_handler_t new_handler); DECLDIR int igraph_progress(const char *message, igraph_real_t percent, void *data); DECLDIR int igraph_progressf(const char *message, igraph_real_t percent, void *data, ...); /** * \define IGRAPH_PROGRESS * \brief Report progress. * * The standard way to report progress from an igraph function * \param message A string, a textual message that references the * calculation under progress. * \param percent Numeric scalar, the percentage that is complete. * \param data User-defined data, this can be used in user-defined * progress handler functions, from user-written igraph functions. * \return If the progress handler returns with \c IGRAPH_INTERRUPTED, * then this macro frees up the igraph allocated memory for * temporary data and returns to the caller with \c * IGRAPH_INTERRUPTED. */ #define IGRAPH_PROGRESS(message, percent, data) \ do { \ if (igraph_progress((message), (percent), (data)) != IGRAPH_SUCCESS) { \ IGRAPH_FINALLY_FREE(); \ return IGRAPH_INTERRUPTED; \ } \ } while (0) __END_DECLS #endif igraph/src/include/igraph_cohesive_blocks.h0000644000175100001440000000231713431000472020616 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_COHESIVE_BLOCKS_H #define IGRAPH_COHESIVE_BLOCKS_H #include "igraph_datatype.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" int igraph_cohesive_blocks(const igraph_t *graph, igraph_vector_ptr_t *blocks, igraph_vector_t *cohesion, igraph_vector_t *parent, igraph_t *block_tree); #endif igraph/src/include/igraph_eigen.h0000644000175100001440000000743413431000472016550 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_arpack.h" #include "igraph_lapack.h" #include "igraph_sparsemat.h" #ifndef IGRAPH_EIGEN_H #define IGRAPH_EIGEN_H #include "igraph_decls.h" __BEGIN_DECLS typedef enum { IGRAPH_EIGEN_AUTO=0, IGRAPH_EIGEN_LAPACK, IGRAPH_EIGEN_ARPACK, IGRAPH_EIGEN_COMP_AUTO, IGRAPH_EIGEN_COMP_LAPACK, IGRAPH_EIGEN_COMP_ARPACK } igraph_eigen_algorithm_t; typedef enum { IGRAPH_EIGEN_LM=0, IGRAPH_EIGEN_SM, /* 1 */ IGRAPH_EIGEN_LA, /* 2 */ IGRAPH_EIGEN_SA, /* 3 */ IGRAPH_EIGEN_BE, /* 4 */ IGRAPH_EIGEN_LR, /* 5 */ IGRAPH_EIGEN_SR, /* 6 */ IGRAPH_EIGEN_LI, /* 7 */ IGRAPH_EIGEN_SI, /* 8 */ IGRAPH_EIGEN_ALL, /* 9 */ IGRAPH_EIGEN_INTERVAL, /* 10 */ IGRAPH_EIGEN_SELECT } /* 11 */ igraph_eigen_which_position_t; typedef struct igraph_eigen_which_t { igraph_eigen_which_position_t pos; int howmany; int il, iu; igraph_real_t vl, vu; int vestimate; igraph_lapack_dgeevx_balance_t balance; } igraph_eigen_which_t; DECLDIR int igraph_eigen_matrix_symmetric(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors); DECLDIR int igraph_eigen_matrix(const igraph_matrix_t *A, const igraph_sparsemat_t *sA, igraph_arpack_function_t *fun, int n, void *extra, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_complex_t *values, igraph_matrix_complex_t *vectors); DECLDIR int igraph_eigen_adjacency(const igraph_t *graph, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_complex_t *cmplxvalues, igraph_matrix_complex_t *cmplxvectors); DECLDIR int igraph_eigen_laplacian(const igraph_t *graph, igraph_eigen_algorithm_t algorithm, const igraph_eigen_which_t *which, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_complex_t *cmplxvalues, igraph_matrix_complex_t *cmplxvectors); __END_DECLS #endif igraph/src/include/igraph_blas.h0000644000175100001440000000470513431000472016400 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef BLAS_H #define BLAS_H #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_decls.h" __BEGIN_DECLS /** * \section about_blas BLAS interface in igraph * * * BLAS is a highly optimized library for basic linear algebra operations * such as vector-vector, matrix-vector and matrix-matrix product. * Please see http://www.netlib.org/blas/ for details and a reference * implementation in Fortran. igraph contains some wrapper functions * that can be used to call BLAS routines in a somewhat more * user-friendly way. Not all BLAS routines are included in igraph, * and even those which are included might not have wrappers; * the extension of the set of wrapped functions will probably be driven * by igraph's internal requirements. The wrapper functions usually * substitute double-precision floating point arrays used by BLAS with * \type igraph_vector_t and \type igraph_matrix_t instances and also * remove those parameters (such as the number of rows/columns) that * can be inferred from the passed arguments directly. * */ DECLDIR void igraph_blas_dgemv(igraph_bool_t transpose, igraph_real_t alpha, const igraph_matrix_t* a, const igraph_vector_t* x, igraph_real_t beta, igraph_vector_t* y); DECLDIR void igraph_blas_dgemv_array(igraph_bool_t transpose, igraph_real_t alpha, const igraph_matrix_t* a, const igraph_real_t* x, igraph_real_t beta, igraph_real_t* y); DECLDIR igraph_real_t igraph_blas_dnrm2(const igraph_vector_t *v); __END_DECLS #endif igraph/src/include/igraph_datatype.h0000644000175100001440000000556113431000472017273 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_DATATYPE_H #define IGRAPH_DATATYPE_H #include "igraph_decls.h" #include "igraph_types.h" #include "igraph_vector.h" __BEGIN_DECLS /** * \ingroup internal * \struct igraph_t * \brief The internal data structure for storing graphs. * * It is simple and efficient. It has the following members: * - n The number of vertices, reduntant. * - directed Whether the graph is directed. * - from The first column of the edge list. * - to The second column of the edge list. * - oi The index of the edge list by the first column. Thus * the first edge according to this order goes from * \c from[oi[0]] to \c to[oi[0]]. The length of * this vector is the same as the number of edges in the graph. * - ii The index of the edge list by the second column. * The length of this vector is the same as the number of edges. * - os Contains pointers to the edgelist (\c from * and \c to for every vertex. The first edge \em from * vertex \c v is edge no. \c from[oi[os[v]]] if * \c os[v]is
This is basically the same as os, but this time * for the incoming edges. * * For undirected graph, the same edge list is stored, ie. an * undirected edge is stored only once, and for checking whether there * is an undirected edge from \c v1 to \c v2 one * should search for both \c from=v1, \c to=v2 and * \c from=v2, \c to=v1. * * The storage requirements for a graph with \c |V| vertices * and \c |E| edges is \c O(|E|+|V|). */ typedef struct igraph_s { igraph_integer_t n; igraph_bool_t directed; igraph_vector_t from; igraph_vector_t to; igraph_vector_t oi; igraph_vector_t ii; igraph_vector_t os; igraph_vector_t is; void *attr; } igraph_t; __END_DECLS #endif igraph/src/include/igraph_strvector.h0000644000175100001440000000713713431000472017514 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_STRVECTOR_H #define IGRAPH_STRVECTOR_H #include "igraph_decls.h" #include "igraph_vector.h" __BEGIN_DECLS /** * Vector of strings * \ingroup internal */ typedef struct s_igraph_strvector { char **data; long int len; } igraph_strvector_t; /** * \define STR * Indexing string vectors * * This is a macro which allows to query the elements of a string vector in * simpler way than \ref igraph_strvector_get(). Note this macro cannot be * used to set an element, for that use \ref igraph_strvector_set(). * \param sv The string vector * \param i The the index of the element. * \return The element at position \p i. * * Time complexity: O(1). */ #define STR(sv,i) ((const char *)((sv).data[(i)])) #define IGRAPH_STRVECTOR_NULL { 0,0 } #define IGRAPH_STRVECTOR_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_strvector_init(v, size)); \ IGRAPH_FINALLY( (igraph_finally_func_t*) igraph_strvector_destroy, v); } while (0) DECLDIR int igraph_strvector_init(igraph_strvector_t *sv, long int len); DECLDIR void igraph_strvector_destroy(igraph_strvector_t *sv); DECLDIR long int igraph_strvector_size(const igraph_strvector_t *sv); DECLDIR void igraph_strvector_get(const igraph_strvector_t *sv, long int idx, char **value); DECLDIR int igraph_strvector_set(igraph_strvector_t *sv, long int idx, const char *value); DECLDIR int igraph_strvector_set2(igraph_strvector_t *sv, long int idx, const char *value, int len); DECLDIR void igraph_strvector_clear(igraph_strvector_t *sv); DECLDIR void igraph_strvector_remove_section(igraph_strvector_t *v, long int from, long int to); DECLDIR void igraph_strvector_remove(igraph_strvector_t *v, long int elem); DECLDIR void igraph_strvector_move_interval(igraph_strvector_t *v, long int begin, long int end, long int to); DECLDIR int igraph_strvector_copy(igraph_strvector_t *to, const igraph_strvector_t *from); DECLDIR int igraph_strvector_append(igraph_strvector_t *to, const igraph_strvector_t *from); DECLDIR int igraph_strvector_resize(igraph_strvector_t* v, long int newsize); DECLDIR int igraph_strvector_add(igraph_strvector_t *v, const char *value); DECLDIR void igraph_strvector_permdelete(igraph_strvector_t *v, const igraph_vector_t *index, long int nremove); DECLDIR void igraph_strvector_remove_negidx(igraph_strvector_t *v, const igraph_vector_t *neg, long int nremove); DECLDIR int igraph_strvector_print(const igraph_strvector_t *v, FILE *file, const char *sep); DECLDIR int igraph_strvector_index(const igraph_strvector_t *v, igraph_strvector_t *newv, const igraph_vector_t *idx); __END_DECLS #endif igraph/src/include/igraph_microscopic_update.h0000644000175100001440000000430213431000472021324 0ustar hornikusers/* -*- mode: C -*- */ /* Microscopic update rules for dealing with agent-level strategy revision. Copyright (C) 2011 Minh Van Nguyen This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MICROSCOPIC_UPDATE_H #define IGRAPH_MICROSCOPIC_UPDATE_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_iterators.h" #include "igraph_types.h" #include "igraph_vector.h" __BEGIN_DECLS DECLDIR int igraph_deterministic_optimal_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_optimal_t optimality, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode); DECLDIR int igraph_moran_process(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode); DECLDIR int igraph_roulette_wheel_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_bool_t islocal, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode); DECLDIR int igraph_stochastic_imitation(const igraph_t *graph, igraph_integer_t vid, igraph_imitate_algorithm_t algo, const igraph_vector_t *quantities, igraph_vector_t *strategies, igraph_neimode_t mode); __END_DECLS #endif igraph/src/include/igraph_community.h0000644000175100001440000002225713431000472017505 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_COMMUNITY_H #define IGRAPH_COMMUNITY_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_arpack.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* K-Cores */ /* -------------------------------------------------- */ DECLDIR int igraph_coreness(const igraph_t *graph, igraph_vector_t *cores, igraph_neimode_t mode); /* -------------------------------------------------- */ /* Community Structure */ /* -------------------------------------------------- */ /* TODO: cut.community */ /* TODO: edge.type.matrix */ /* TODO: */ DECLDIR int igraph_community_optimal_modularity(const igraph_t *graph, igraph_real_t *modularity, igraph_vector_t *membership, const igraph_vector_t *weights); DECLDIR int igraph_community_spinglass(const igraph_t *graph, const igraph_vector_t *weights, igraph_real_t *modularity, igraph_real_t *temperature, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t spins, igraph_bool_t parupdate, igraph_real_t starttemp, igraph_real_t stoptemp, igraph_real_t coolfact, igraph_spincomm_update_t update_rule, igraph_real_t gamma, /* the rest is for the NegSpin implementation */ igraph_spinglass_implementation_t implementation, /* igraph_matrix_t *adhesion, */ /* igraph_matrix_t *normalised_adhesion, */ /* igraph_real_t *polarization, */ igraph_real_t lambda); DECLDIR int igraph_community_spinglass_single(const igraph_t *graph, const igraph_vector_t *weights, igraph_integer_t vertex, igraph_vector_t *community, igraph_real_t *cohesion, igraph_real_t *adhesion, igraph_integer_t *inner_links, igraph_integer_t *outer_links, igraph_integer_t spins, igraph_spincomm_update_t update_rule, igraph_real_t gamma); DECLDIR int igraph_community_walktrap(const igraph_t *graph, const igraph_vector_t *weights, int steps, igraph_matrix_t *merges, igraph_vector_t *modularity, igraph_vector_t *membership); DECLDIR int igraph_community_infomap(const igraph_t * graph, const igraph_vector_t *e_weights, const igraph_vector_t *v_weights, int nb_trials, igraph_vector_t *membership, igraph_real_t *codelength); DECLDIR int igraph_community_edge_betweenness(const igraph_t *graph, igraph_vector_t *result, igraph_vector_t *edge_betweenness, igraph_matrix_t *merges, igraph_vector_t *bridges, igraph_vector_t *modularity, igraph_vector_t *membership, igraph_bool_t directed, const igraph_vector_t *weights); DECLDIR int igraph_community_eb_get_merges(const igraph_t *graph, const igraph_vector_t *edges, const igraph_vector_t *weights, igraph_matrix_t *merges, igraph_vector_t *bridges, igraph_vector_t *modularity, igraph_vector_t *membership); DECLDIR int igraph_community_fastgreedy(const igraph_t *graph, const igraph_vector_t *weights, igraph_matrix_t *merges, igraph_vector_t *modularity, igraph_vector_t *membership); DECLDIR int igraph_community_to_membership(const igraph_matrix_t *merges, igraph_integer_t nodes, igraph_integer_t steps, igraph_vector_t *membership, igraph_vector_t *csize); DECLDIR int igraph_le_community_to_membership(const igraph_matrix_t *merges, igraph_integer_t steps, igraph_vector_t *membership, igraph_vector_t *csize); DECLDIR int igraph_modularity(const igraph_t *graph, const igraph_vector_t *membership, igraph_real_t *modularity, const igraph_vector_t *weights); DECLDIR int igraph_modularity_matrix(const igraph_t *graph, const igraph_vector_t *membership, igraph_matrix_t *modmat, const igraph_vector_t *weights); DECLDIR int igraph_reindex_membership(igraph_vector_t *membership, igraph_vector_t *new_to_old); typedef enum { IGRAPH_LEVC_HIST_SPLIT=1, IGRAPH_LEVC_HIST_FAILED, IGRAPH_LEVC_HIST_START_FULL, IGRAPH_LEVC_HIST_START_GIVEN } igraph_leading_eigenvector_community_history_t; /** * \typedef igraph_community_leading_eigenvector_callback_t * Callback for the leading eigenvector community finding method. * * The leading eigenvector community finding implementation in igraph * is able to call a callback function, after each eigenvalue * calculation. This callback function must be of \c * igraph_community_leading_eigenvector_callback_t type. * The following arguments are passed to the callback: * \param membership The actual membership vector, before recording * the potential change implied by the newly found eigenvalue. * \param comm The id of the community that the algorithm tried to * split in the last iteration. The community ids are indexed from * zero here! * \param eigenvalue The eigenvalue the algorithm has just found. * \param eigenvector The eigenvector corresponding to the eigenvalue * the algorithm just found. * \param arpack_multiplier A function that was passed to \ref * igraph_arpack_rssolve() to solve the last eigenproblem. * \param arpack_extra The extra argument that was passed to the * ARPACK solver. * \param extra Extra argument that as passed to \ref * igraph_community_leading_eigenvector(). * * \sa \ref igraph_community_leading_eigenvector(), \ref * igraph_arpack_function_t, \ref igraph_arpack_rssolve(). */ typedef int igraph_community_leading_eigenvector_callback_t( const igraph_vector_t *membership, long int comm, igraph_real_t eigenvalue, const igraph_vector_t *eigenvector, igraph_arpack_function_t *arpack_multiplier, void *arpack_extra, void *extra); DECLDIR int igraph_community_leading_eigenvector(const igraph_t *graph, const igraph_vector_t *weights, igraph_matrix_t *merges, igraph_vector_t *membership, igraph_integer_t steps, igraph_arpack_options_t *options, igraph_real_t *modularity, igraph_bool_t start, igraph_vector_t *eigenvalues, igraph_vector_ptr_t *eigenvectors, igraph_vector_t *history, igraph_community_leading_eigenvector_callback_t *callback, void *callback_extra); DECLDIR int igraph_community_label_propagation(const igraph_t *graph, igraph_vector_t *membership, const igraph_vector_t *weights, const igraph_vector_t *initial, igraph_vector_bool_t *fixed, igraph_real_t *modularity); DECLDIR int igraph_community_multilevel(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *membership, igraph_matrix_t *memberships, igraph_vector_t *modularity); /* -------------------------------------------------- */ /* Community Structure Comparison */ /* -------------------------------------------------- */ DECLDIR int igraph_compare_communities(const igraph_vector_t *comm1, const igraph_vector_t *comm2, igraph_real_t* result, igraph_community_comparison_t method); DECLDIR int igraph_split_join_distance(const igraph_vector_t *comm1, const igraph_vector_t *comm2, igraph_integer_t* distance12, igraph_integer_t* distance21); __END_DECLS #endif igraph/src/include/igraph_conversion.h0000644000175100001440000000442313431000472017641 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_CONVERSION_H #define IGRAPH_CONVERSION_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_spmatrix.h" #include "igraph_matrix.h" #include "igraph_sparsemat.h" #include "igraph_attributes.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Conversion */ /* -------------------------------------------------- */ DECLDIR int igraph_get_adjacency(const igraph_t *graph, igraph_matrix_t *res, igraph_get_adjacency_t type, igraph_bool_t eids); DECLDIR int igraph_get_adjacency_sparse(const igraph_t *graph, igraph_spmatrix_t *res, igraph_get_adjacency_t type); DECLDIR int igraph_get_stochastic(const igraph_t *graph, igraph_matrix_t *matrix, igraph_bool_t column_wise); DECLDIR int igraph_get_stochastic_sparsemat(const igraph_t *graph, igraph_sparsemat_t *sparsemat, igraph_bool_t column_wise); DECLDIR int igraph_get_edgelist(const igraph_t *graph, igraph_vector_t *res, igraph_bool_t bycol); DECLDIR int igraph_to_directed(igraph_t *graph, igraph_to_directed_t flags); DECLDIR int igraph_to_undirected(igraph_t *graph, igraph_to_undirected_t flags, const igraph_attribute_combination_t *edge_comb); __END_DECLS #endif igraph/src/include/igraph_visitor.h0000644000175100001440000001164313431000472017155 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_VISITOR_H #define IGRAPH_VISITOR_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Visitor-like functions */ /* -------------------------------------------------- */ /** * \typedef igraph_bfshandler_t * Callback type for BFS function * * \ref igraph_bfs() is able to call a callback function, whenever a * new vertex is found, while doing the breadth-first search. This * callback function must be of type \c igraph_bfshandler_t. It has * the following arguments: * \param graph The graph that that algorithm is working on. Of course * this must not be modified. * \param vid The id of the vertex just found by the breadth-first * search. * \param pred The id of the previous vertex visited. It is -1 if * there is no previous vertex, because the current vertex is the root * is a search tree. * \param succ The id of the next vertex that will be visited. It is * -1 if there is no next vertex, because the current vertex is the * last one in a search tree. * \param rank The rank of the current vertex, it starts with zero. * \param dist The distance (number of hops) of the current vertex * from the root of the current search tree. * \param extra The extra argument that was passed to \ref * igraph_bfs(). * \return A logical value, if TRUE (=non-zero), that is interpreted * as a request to stop the BFS and return to the caller. If a BFS * is terminated like this, then all elements of the result vectors * that were not yet calculated at the point of the termination * contain \c IGRAPH_NAN. * * \sa \ref igraph_bfs() */ typedef igraph_bool_t igraph_bfshandler_t(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t pred, igraph_integer_t succ, igraph_integer_t rank, igraph_integer_t dist, void *extra); int igraph_bfs(const igraph_t *graph, igraph_integer_t root, const igraph_vector_t *roots, igraph_neimode_t mode, igraph_bool_t unreachable, const igraph_vector_t *restricted, igraph_vector_t *order, igraph_vector_t *rank, igraph_vector_t *father, igraph_vector_t *pred, igraph_vector_t *succ, igraph_vector_t *dist, igraph_bfshandler_t *callback, void *extra); int igraph_i_bfs(igraph_t *graph, igraph_integer_t vid, igraph_neimode_t mode, igraph_vector_t *vids, igraph_vector_t *layers, igraph_vector_t *parents); /** * \function igraph_dfshandler_t * Callback type for the DFS function * * \ref igraph_dfs() is able to call a callback function, whenever a * new vertex is discovered, and/or whenever a subtree is * completed. These callbacks must be of type \c * igraph_dfshandler_t. They have the following arguments: * \param graph The graph that that algorithm is working on. Of course * this must not be modified. * \param vid The id of the vertex just found by the depth-first * search. * \param dist The distance (number of hops) of the current vertex * from the root of the current search tree. * \param extra The extra argument that was passed to \ref * igraph_dfs(). * \return A logical value, if TRUE (=non-zero), that is interpreted * as a request to stop the DFS and return to the caller. If a DFS * is terminated like this, then all elements of the result vectors * that were not yet calculated at the point of the termination * contain \c IGRAPH_NAN. * * \sa \ref igraph_dfs() */ typedef igraph_bool_t igraph_dfshandler_t(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t dist, void *extra); int igraph_dfs(const igraph_t *graph, igraph_integer_t root, igraph_neimode_t mode, igraph_bool_t unreachable, igraph_vector_t *order, igraph_vector_t *order_out, igraph_vector_t *father, igraph_vector_t *dist, igraph_dfshandler_t *in_callback, igraph_dfshandler_t *out_callback, void *extra); __END_DECLS #endif igraph/src/include/igraph_error.h0000644000175100001440000006511313431000472016610 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_ERROR_H #define IGRAPH_ERROR_H #include #include "igraph_decls.h" __BEGIN_DECLS /* This file contains the igraph error handling. * Most bits are taken literally from the GSL library (with the GSL_ * prefix renamed to IGRAPH_), as I couldn't find a better way to do * them. */ /** * \section errorhandlingbasics Error handling basics * * \a igraph functions can run into various problems preventing them * from normal operation. The user might have supplied invalid arguments, * e.g. a non-square matrix when a square-matrix was expected, or the program * has run out of memory while some more memory allocation is required, etc. * * * By default \a igraph aborts the program when it runs into an * error. While this behavior might be good enough for smaller programs, * it is without doubt avoidable in larger projects. Please read further * if your project requires more sophisticated error handling. You can * safely skip the rest of this chapter otherwise. * */ /** * \section errorhandlers Error handlers * * * If \a igraph runs into an error - an invalid argument was supplied * to a function, or we've ran out of memory - the control is * transferred to the \emb error handler \eme function. * * The default error handler is \ref igraph_error_handler_abort which * prints an error message and aborts the program. * * * The \ref igraph_set_error_handler() function can be used to set a new * error handler function of type \ref igraph_error_handler_t; see the * documentation of this type for details. * * * There are two other predefined error handler functions, * \ref igraph_error_handler_ignore and \ref igraph_error_handler_printignore. * These deallocate the temporarily allocated memory (more about this * later) and return with the error code. The latter also prints an * error message. If you use these error handlers you need to take * care about possible errors yourself by checking the return value of * (almost) every non-void \a igraph function. * * Independently of the error handler installed, all functions in the * library do their best to leave their arguments * \em semantically unchanged if an error * happens. By semantically we mean that the implementation of an * object supplied as an argument might change, but its * \quote meaning \endquote in most cases does not. The rare occasions * when this rule is violated are documented in this manual. * */ /** * \section errorcodes Error codes * * Every \a igraph function which can fail return a * single integer error code. Some functions are very simple and * cannot run into any error, these may return other types, or * \type void as well. The error codes are defined by the * \ref igraph_error_type_t enumeration. * */ /** * \section writing_error_handlers Writing error handlers * * * The contents of the rest of this chapter might be useful only * for those who want to create an interface to \a igraph from another * language. Most readers can safely skip to the next chapter. * * * * You can write and install error handlers simply by defining a * function of type \ref igraph_error_handler_t and calling * \ref igraph_set_error_handler(). This feature is useful for interface * writers, as \a igraph will have the chance to * signal errors the appropriate way, eg. the R interface defines an * error handler which calls the error() * function, as required by R, while the Python interface has an error * handler which raises an exception according to the Python way. * * * If you want to write an error handler, your error handler should * call \ref IGRAPH_FINALLY_FREE() to deallocate all temporary memory to * prevent memory leaks. * */ /** * \section error_handling_internals Error handling internals * * * If an error happens, the functions in the library call the * \ref IGRAPH_ERROR macro with a textual description of the error and an * \a igraph error code. This macro calls (through the \ref * igraph_error() function) the installed error handler. Another useful * macro is \ref IGRAPH_CHECK(). This checks the return value of its * argument, which is normally a function call, and calls \ref * IGRAPH_ERROR if it is not \c IGRAPH_SUCCESS. * */ /** * \section deallocating_memory Deallocating memory * * * If a function runs into an error (and the program is not aborted) * the error handler should deallocate all temporary memory. This is * done by storing the address and the destroy function of all temporary * objects in a stack. The \ref IGRAPH_FINALLY function declares an object as * temporary by placing its address in the stack. If an \a igraph function returns * with success it calls \ref IGRAPH_FINALLY_CLEAN() with the * number of objects to remove from the stack. If an error happens * however, the error handler should call \ref IGRAPH_FINALLY_FREE() to * deallocate each object added to the stack. This means that the * temporary objects allocated in the calling function (and etc.) will * be freed as well. * */ /** * \section writing_functions_error_handling Writing \a igraph functions with * proper error handling * * * There are some simple rules to keep in order to have functions * behaving well in erroneous situations. First, check the arguments * of the functions and call \ref IGRAPH_ERROR if they are invalid. Second, * call \ref IGRAPH_FINALLY on each dynamically allocated object and call * \ref IGRAPH_FINALLY_CLEAN() with the proper argument before returning. Third, use * \ref IGRAPH_CHECK on all \a igraph function calls which can generate errors. * * * The size of the stack used for this bookkeeping is fixed, and * small. If you want to allocate several objects, write a destroy * function which can deallocate all of these. See the * adjlist.c file in the * \a igraph source for an example. * * * For some functions these mechanisms are simply not flexible * enough. These functions should define their own error handlers and * restore the error handler before they return. * */ /** * \section error_handling_threads Error handling and threads * * * It is likely that the \a igraph error handling * method is \em not thread-safe, mainly because of * the static global stack which is used to store the address of the * temporarily allocated objects. This issue might be addressed in a * later version of \a igraph. * */ /** * \typedef igraph_error_handler_t * \brief Type of error handler functions. * * This is the type of the error handler functions. * \param reason Textual description of the error. * \param file The source file in which the error is noticed. * \param line The number of the line in the source file which triggered * the error * \param igraph_errno The \a igraph error code. */ typedef void igraph_error_handler_t (const char * reason, const char * file, int line, int igraph_errno); /** * \var igraph_error_handler_abort * \brief Abort program in case of error. * * The default error handler, prints an error message and aborts the * program. */ extern igraph_error_handler_t igraph_error_handler_abort; /** * \var igraph_error_handler_ignore * \brief Ignore errors. * * This error handler frees the temporarily allocated memory and returns * with the error code. */ extern igraph_error_handler_t igraph_error_handler_ignore; /** * \var igraph_error_handler_printignore * \brief Print and ignore errors. * * Frees temporarily allocated memory, prints an error message to the * standard error and returns with the error code. */ extern igraph_error_handler_t igraph_error_handler_printignore; /** * \function igraph_set_error_handler * \brief Set a new error handler. * * Installs a new error handler. If called with 0, it installs the * default error handler (which is currently * \ref igraph_error_handler_abort). * \param new_handler The error handler function to install. * \return The old error handler function. This should be saved and * restored if \p new_handler is not needed any * more. */ DECLDIR igraph_error_handler_t* igraph_set_error_handler(igraph_error_handler_t* new_handler); /** * \typedef igraph_error_type_t * \brief Error code type. * These are the possible values returned by \a igraph functions. * Note that these are interesting only if you defined an error handler * with \ref igraph_set_error_handler(). Otherwise the program is aborted * and the function causing the error never returns. * * \enumval IGRAPH_SUCCESS The function successfully completed its task. * \enumval IGRAPH_FAILURE Something went wrong. You'll almost never * meet this error as normally more specific error codes are used. * \enumval IGRAPH_ENOMEM There wasn't enough memory to allocate * on the heap. * \enumval IGRAPH_PARSEERROR A parse error was found in a file. * \enumval IGRAPH_EINVAL A parameter's value is invalid. Eg. negative * number was specified as the number of vertices. * \enumval IGRAPH_EXISTS A graph/vertex/edge attribute is already * installed with the given name. * \enumval IGRAPH_EINVEVECTOR Invalid vector of vertex ids. A vertex id * is either negative or bigger than the number of vertices minus one. * \enumval IGRAPH_EINVVID Invalid vertex id, negative or too big. * \enumval IGRAPH_NONSQUARE A non-square matrix was received while a * square matrix was expected. * \enumval IGRAPH_EINVMODE Invalid mode parameter. * \enumval IGRAPH_EFILE A file operation failed. Eg. a file doesn't exist, * or the user has no rights to open it. * \enumval IGRAPH_UNIMPLEMENTED Attempted to call an unimplemented or * disabled (at compile-time) function. * \enumval IGRAPH_DIVERGED A numeric algorithm failed to converge. * \enumval IGRAPH_ARPACK_PROD Matrix-vector product failed. * \enumval IGRAPH_ARPACK_NPOS N must be positive. * \enumval IGRAPH_ARPACK_NEVNPOS NEV must be positive. * \enumval IGRAPH_ARPACK_NCVSMALL NCV must be bigger. * \enumval IGRAPH_ARPACK_NONPOSI Maximum number of iterations should be positive. * \enumval IGRAPH_ARPACK_WHICHINV Invalid WHICH parameter. * \enumval IGRAPH_ARPACK_BMATINV Invalid BMAT parameter. * \enumval IGRAPH_ARPACK_WORKLSMALL WORKL is too small. * \enumval IGRAPH_ARPACK_TRIDERR LAPACK error in tridiagonal eigenvalue calculation. * \enumval IGRAPH_ARPACK_ZEROSTART Starting vector is zero. * \enumval IGRAPH_ARPACK_MODEINV MODE is invalid. * \enumval IGRAPH_ARPACK_MODEBMAT MODE and BMAT are not compatible. * \enumval IGRAPH_ARPACK_ISHIFT ISHIFT must be 0 or 1. * \enumval IGRAPH_ARPACK_NEVBE NEV and WHICH='BE' are incompatible. * \enumval IGRAPH_ARPACK_NOFACT Could not build an Arnoldi factorization. * \enumval IGRAPH_ARPACK_FAILED No eigenvalues to sufficient accuracy. * \enumval IGRAPH_ARPACK_HOWMNY HOWMNY is invalid. * \enumval IGRAPH_ARPACK_HOWMNYS HOWMNY='S' is not implemented. * \enumval IGRAPH_ARPACK_EVDIFF Different number of converged Ritz values. * \enumval IGRAPH_ARPACK_SHUR Error from calculation of a real Schur form. * \enumval IGRAPH_ARPACK_LAPACK LAPACK (dtrevc) error for calculating eigenvectors. * \enumval IGRAPH_ARPACK_UNKNOWN Unknown ARPACK error. * \enumval IGRAPH_ENEGLOOP Negative loop detected while calculating shortest paths. * \enumval IGRAPH_EINTERNAL Internal error, likely a bug in igraph. * \enumval IGRAPH_EDIVZERO Big integer division by zero. * \enumval IGARPH_GLP_EBOUND GLPK error (GLP_EBOUND). * \enumval IGARPH_GLP_EROOT GLPK error (GLP_EROOT). * \enumval IGARPH_GLP_ENOPFS GLPK error (GLP_ENOPFS). * \enumval IGARPH_GLP_ENODFS GLPK error (GLP_ENODFS). * \enumval IGARPH_GLP_EFAIL GLPK error (GLP_EFAIL). * \enumval IGARPH_GLP_EMIPGAP GLPK error (GLP_EMIPGAP). * \enumval IGARPH_GLP_ETMLIM GLPK error (GLP_ETMLIM). * \enumval IGARPH_GLP_ESTOP GLPK error (GLP_ESTOP). * \enumval IGRAPH_EATTRIBUTES Attribute handler error. The user is not * expected to find this; it is signalled if some igraph function is * not using the attribute handler interface properly. * \enumval IGRAPH_EATTRCOMBINE Unimplemented attribute combination * method for the given attribute type. * \enumval IGRAPH_ELAPACK A LAPACK call resulted an error. * \enumval IGRAPH_EDRL Internal error in the DrL layout generator. * \enumval IGRAPH_EOVERFLOW Integer or double overflow. * \enumval IGRAPH_EGLP Internal GLPK error. * \enumval IGRAPH_CPUTIME CPU time exceeded. * \enumval IGRAPH_EUNDERFLOW Integer or double underflow. * \enumval IGRAPH_ERWSTUCK Random walk got stuck. */ typedef enum { IGRAPH_SUCCESS = 0, IGRAPH_FAILURE = 1, IGRAPH_ENOMEM = 2, IGRAPH_PARSEERROR = 3, IGRAPH_EINVAL = 4, IGRAPH_EXISTS = 5, IGRAPH_EINVEVECTOR = 6, IGRAPH_EINVVID = 7, IGRAPH_NONSQUARE = 8, IGRAPH_EINVMODE = 9, IGRAPH_EFILE = 10, IGRAPH_UNIMPLEMENTED = 12, IGRAPH_INTERRUPTED = 13, IGRAPH_DIVERGED = 14, IGRAPH_ARPACK_PROD = 15, IGRAPH_ARPACK_NPOS = 16, IGRAPH_ARPACK_NEVNPOS = 17, IGRAPH_ARPACK_NCVSMALL = 18, IGRAPH_ARPACK_NONPOSI = 19, IGRAPH_ARPACK_WHICHINV = 20, IGRAPH_ARPACK_BMATINV = 21, IGRAPH_ARPACK_WORKLSMALL= 22, IGRAPH_ARPACK_TRIDERR = 23, IGRAPH_ARPACK_ZEROSTART = 24, IGRAPH_ARPACK_MODEINV = 25, IGRAPH_ARPACK_MODEBMAT = 26, IGRAPH_ARPACK_ISHIFT = 27, IGRAPH_ARPACK_NEVBE = 28, IGRAPH_ARPACK_NOFACT = 29, IGRAPH_ARPACK_FAILED = 30, IGRAPH_ARPACK_HOWMNY = 31, IGRAPH_ARPACK_HOWMNYS = 32, IGRAPH_ARPACK_EVDIFF = 33, IGRAPH_ARPACK_SHUR = 34, IGRAPH_ARPACK_LAPACK = 35, IGRAPH_ARPACK_UNKNOWN = 36, IGRAPH_ENEGLOOP = 37, IGRAPH_EINTERNAL = 38, IGRAPH_ARPACK_MAXIT = 39, IGRAPH_ARPACK_NOSHIFT = 40, IGRAPH_ARPACK_REORDER = 41, IGRAPH_EDIVZERO = 42, IGRAPH_GLP_EBOUND = 43, IGRAPH_GLP_EROOT = 44, IGRAPH_GLP_ENOPFS = 45, IGRAPH_GLP_ENODFS = 46, IGRAPH_GLP_EFAIL = 47, IGRAPH_GLP_EMIPGAP = 48, IGRAPH_GLP_ETMLIM = 49, IGRAPH_GLP_ESTOP = 50, IGRAPH_EATTRIBUTES = 51, IGRAPH_EATTRCOMBINE = 52, IGRAPH_ELAPACK = 53, IGRAPH_EDRL = 54, IGRAPH_EOVERFLOW = 55, IGRAPH_EGLP = 56, IGRAPH_CPUTIME = 57, IGRAPH_EUNDERFLOW = 58, IGRAPH_ERWSTUCK = 59 } igraph_error_type_t; /** * \define IGRAPH_ERROR * \brief Trigger an error. * * \a igraph functions usually use this macro when they notice an error. * It calls * \ref igraph_error() with the proper parameters and if that returns * the macro returns the "calling" function as well, with the error * code. If for some (suspicious) reason you want to call the error * handler without returning from the current function, call * \ref igraph_error() directly. * \param reason Textual description of the error. This should be * something more descriptive than the text associated with the error * code. Eg. if the error code is \c IGRAPH_EINVAL, * its associated text (see \ref igraph_strerror()) is "Invalid * value" and this string should explain which parameter was invalid * and maybe why. * \param igraph_errno The \a igraph error code. */ #define IGRAPH_ERROR(reason,igraph_errno) \ do { \ igraph_error (reason, __FILE__, __LINE__, igraph_errno) ; \ return igraph_errno ; \ } while (0) /** * \function igraph_error * \brief Trigger an error. * * \a igraph functions usually call this function (most often via the * \ref IGRAPH_ERROR macro) if they notice an error. * It calls the currently installed error handler function with the * supplied arguments. * * \param reason Textual description of the error. * \param file The source file in which the error was noticed. * \param line The number of line in the source file which triggered the * error. * \param igraph_errno The \a igraph error code. * \return the error code (if it returns) * * \sa igraph_errorf(). */ DECLDIR int igraph_error(const char *reason, const char *file, int line, int igraph_errno); /** * \function igraph_errorf * \brief Trigger an error, printf-like version. * * \param reason Textual description of the error, interpreted as * a printf format string. * \param file The source file in which the error was noticed. * \param line The line in the source file which triggered the error. * \param igraph_errno The \a igraph error code. * \param ... Additional parameters, the values to substitute into the * format string. * * \sa igraph_error(). */ DECLDIR int igraph_errorf(const char *reason, const char *file, int line, int igraph_errno, ...); DECLDIR int igraph_errorvf(const char *reason, const char *file, int line, int igraph_errno, va_list ap); /** * \function igraph_strerror * \brief Textual description of an error. * * This is a simple utility function, it gives a short general textual * description for an \a igraph error code. * * \param igraph_errno The \a igraph error code. * \return pointer to the textual description of the error code. */ DECLDIR const char* igraph_strerror(const int igraph_errno); #define IGRAPH_ERROR_SELECT_2(a,b) ((a) != IGRAPH_SUCCESS ? (a) : ((b) != IGRAPH_SUCCESS ? (b) : IGRAPH_SUCCESS)) #define IGRAPH_ERROR_SELECT_3(a,b,c) ((a) != IGRAPH_SUCCESS ? (a) : IGRAPH_ERROR_SELECT_2(b,c)) #define IGRAPH_ERROR_SELECT_4(a,b,c,d) ((a) != IGRAPH_SUCCESS ? (a) : IGRAPH_ERROR_SELECT_3(b,c,d)) #define IGRAPH_ERROR_SELECT_5(a,b,c,d,e) ((a) != IGRAPH_SUCCESS ? (a) : IGRAPH_ERROR_SELECT_4(b,c,d,e)) /* Now comes the more convenient error handling macro arsenal. * Ideas taken from exception.{h,c} by Laurent Deniau see * http://cern.ch/Laurent.Deniau/html/oopc/oopc.html#Exceptions for more * information. We don't use the exception handling code though. */ struct igraph_i_protectedPtr { int all; void *ptr; void (*func)(void*); }; typedef void igraph_finally_func_t (void*); DECLDIR void IGRAPH_FINALLY_REAL(void (*func)(void*), void* ptr); /** * \function IGRAPH_FINALLY_CLEAN * \brief Signal clean deallocation of objects. * * Removes the specified number of objects from the stack of * temporarily allocated objects. Most often this is called just * before returning from a function. * \param num The number of objects to remove from the bookkeeping * stack. */ DECLDIR void IGRAPH_FINALLY_CLEAN(int num); /** * \function IGRAPH_FINALLY_FREE * \brief Deallocate all registered objects. * * Calls the destroy function for all objects in the stack of * temporarily allocated objects. This is usually called only from an * error handler. It is \em not appropriate to use it * instead of destroying each unneeded object of a function, as it * destroys the temporary objects of the caller function (and so on) * as well. */ DECLDIR void IGRAPH_FINALLY_FREE(void); /** * \function IGRAPH_FINALLY_STACK_SIZE * \brief Returns the number of registered objects. * * Returns the number of objects in the stack of temporarily allocated * objects. This function is handy if you write an own igraph routine and * you want to make sure it handles errors properly. A properly written * igraph routine should not leave pointers to temporarily allocated objects * in the finally stack, because otherwise an \ref IGRAPH_FINALLY_FREE call * in another igraph function would result in freeing these objects as well * (and this is really hard to debug, since the error will be not in that * function that shows erroneous behaviour). Therefore, it is advised to * write your own test cases and examine \ref IGRAPH_FINALLY_STACK_SIZE * before and after your test cases - the numbers should be equal. */ DECLDIR int IGRAPH_FINALLY_STACK_SIZE(void); /** * \define IGRAPH_FINALLY_STACK_EMPTY * \brief Returns true if there are no registered objects, false otherwise. * * This is just a shorthand notation for checking that * \ref IGRAPH_FINALLY_STACK_SIZE is zero. */ #define IGRAPH_FINALLY_STACK_EMPTY (IGRAPH_FINALLY_STACK_SIZE() == 0) /** * \define IGRAPH_FINALLY * \brief Register an object for deallocation. * \param func The address of the function which is normally called to * destroy the object. * \param ptr Pointer to the object itself. * * This macro places the address of an object, together with the * address of its destructor in a stack. This stack is used if an * error happens to deallocate temporarily allocated objects to * prevent memory leaks. */ #define IGRAPH_FINALLY(func,ptr) \ IGRAPH_FINALLY_REAL((igraph_finally_func_t*)(func), (ptr)) #if (defined(__GNUC__) && GCC_VERSION_MAJOR >= 3) # define IGRAPH_UNLIKELY(a) __builtin_expect((a), 0) # define IGRAPH_LIKELY(a) __builtin_expect((a), 1) #else # define IGRAPH_UNLIKELY(a) a # define IGRAPH_LIKELY(a) a #endif /** * \define IGRAPH_CHECK * \brief Check the return value of a function call. * * \param a An expression, usually a function call. * * Executes the expression and checks its value. If this is not * \c IGRAPH_SUCCESS, it calls \ref IGRAPH_ERROR with * the value as the error code. Here is an example usage: * \verbatim IGRAPH_CHECK(vector_push_back(&v, 100)); \endverbatim * *
There is only one reason to use this macro when writing * \a igraph functions. If the user installs an error handler which * returns to the auxiliary calling code (like \ref * igraph_error_handler_ignore and \ref * igraph_error_handler_printignore), and the \a igraph function * signalling the error is called from another \a igraph function * then we need to make sure that the error is propagated back to * the auxiliary (ie. non-igraph) calling function. This is achieved * by using IGRAPH_CHECK on every \a igraph * call which can return an error code. */ #define IGRAPH_CHECK(a) do { \ int igraph_i_ret=(a); \ if (IGRAPH_UNLIKELY(igraph_i_ret != 0)) {\ IGRAPH_ERROR("", igraph_i_ret); \ } } while (0) /** * \section about_igraph_warnings Warning messages * * * Igraph also supports warning messages in addition to error * messages. Warning messages typically do not terminate the * program, but they are usually crucial to the user. * * * * Igraph warning are handled similarly to errors. There is a * separate warning handler function that is called whenever * an igraph function triggers a warning. This handler can be * set by the \ref igraph_set_warning_handler() function. There are * two predefined simple warning handlers, * \ref igraph_warning_handler_ignore() and * \ref igraph_warning_handler_print(), the latter being the default. * * * * To trigger a warning, igraph functions typically use the * \ref IGRAPH_WARNING() macro, the \ref igraph_warning() function, * or if more flexibility is needed, \ref igraph_warningf(). * */ /** * \typedef igraph_warning_handler_t * Type of igraph warning handler functions * * Currently it is defined to have the same type as * \ref igraph_error_handler_t, although the last (error code) * argument is not used. */ typedef igraph_error_handler_t igraph_warning_handler_t; /** * \function igraph_set_warning_handler * Install a warning handler * * Install the supplied warning handler function. * \param new_handler The new warning handler function to install. * Supply a null pointer here to uninstall the current * warning handler, without installing a new one. * \return The current warning handler function. */ DECLDIR igraph_warning_handler_t* igraph_set_warning_handler(igraph_warning_handler_t* new_handler); extern igraph_warning_handler_t igraph_warning_handler_ignore; extern igraph_warning_handler_t igraph_warning_handler_print; /** * \function igraph_warning * Trigger a warning * * Call this function if you want to trigger a warning from within * a function that uses igraph. * \param reason Textual description of the warning. * \param file The source file in which the warning was noticed. * \param line The number of line in the source file which triggered the * warning. * \param igraph_errno Warnings could have potentially error codes as well, * but this is currently not used in igraph. * \return The supplied error code. */ DECLDIR int igraph_warning(const char *reason, const char *file, int line, int igraph_errno); /** * \function igraph_warningf * Trigger a warning, more flexible printf-like syntax * * This function is similar to \ref igraph_warning(), but * uses a printf-like syntax. It substitutes the additional arguments * into the \p reason template string and calls \ref igraph_warning(). * \param reason Textual description of the warning, a template string * with the same syntax as the standard printf C library function. * \param file The source file in which the warning was noticed. * \param line The number of line in the source file which triggered the * warning. * \param igraph_errno Warnings could have potentially error codes as well, * but this is currently not used in igraph. * \param ... The additional arguments to be substituted into the * template string. * \return The supplied error code. */ DECLDIR int igraph_warningf(const char *reason, const char *file, int line, int igraph_errno, ...); /** * \define IGRAPH_WARNING * Trigger a warning. * * This is the usual way of triggering a warning from an igraph * function. It calls \ref igraph_warning(). * \param reason The warning message. */ #define IGRAPH_WARNING(reason) \ do { \ igraph_warning(reason, __FILE__, __LINE__, -1); \ } while (0) __END_DECLS #endif igraph/src/include/igraph_flow.h0000644000175100001440000001532313431000472016424 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_FLOW_H #define IGRAPH_FLOW_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* MAximum flows, minimum cuts & such */ /* -------------------------------------------------- */ /** * \typedef igraph_maxflow_stats_t * A simple data type to return some statistics from the * push-relabel maximum flow solver. * * \param nopush The number of push operations performed. * \param norelabel The number of relabel operarions performed. * \param nogap The number of times the gap heuristics was used. * \param nogapnodes The total number of vertices that were * omitted form further calculations because of the gap * heuristics. * \param nobfs The number of times the reverse BFS was run to * assign good values to the height function. This includes * an initial run before the whole algorithm, so it is always * at least one. */ typedef struct { int nopush, norelabel, nogap, nogapnodes, nobfs; } igraph_maxflow_stats_t; DECLDIR int igraph_maxflow(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *flow, igraph_vector_t *cut, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity, igraph_maxflow_stats_t *stats); DECLDIR int igraph_maxflow_value(const igraph_t *graph, igraph_real_t *value, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity, igraph_maxflow_stats_t *stats); DECLDIR int igraph_st_mincut(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *cut, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity); DECLDIR int igraph_st_mincut_value(const igraph_t *graph, igraph_real_t *res, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity); DECLDIR int igraph_mincut_value(const igraph_t *graph, igraph_real_t *res, const igraph_vector_t *capacity); DECLDIR int igraph_mincut(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_vector_t *cut, const igraph_vector_t *capacity); DECLDIR int igraph_st_vertex_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target, igraph_vconn_nei_t neighbors); DECLDIR int igraph_vertex_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks); DECLDIR int igraph_st_edge_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target); DECLDIR int igraph_edge_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks); DECLDIR int igraph_edge_disjoint_paths(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target); DECLDIR int igraph_vertex_disjoint_paths(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target); DECLDIR int igraph_adhesion(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks); DECLDIR int igraph_cohesion(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks); /* s-t cut listing related stuff */ DECLDIR int igraph_even_tarjan_reduction(const igraph_t *graph, igraph_t *graphbar, igraph_vector_t *capacity); DECLDIR int igraph_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, igraph_vector_t *residual_capacity, const igraph_vector_t *flow); int igraph_i_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, igraph_vector_t *residual_capacity, const igraph_vector_t *flow, igraph_vector_t *tmp); int igraph_i_reverse_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, const igraph_vector_t *flow, igraph_vector_t *tmp); DECLDIR int igraph_reverse_residual_graph(const igraph_t *graph, const igraph_vector_t *capacity, igraph_t *residual, const igraph_vector_t *flow); DECLDIR int igraph_dominator_tree(const igraph_t *graph, igraph_integer_t root, igraph_vector_t *dom, igraph_t *domtree, igraph_vector_t *leftout, igraph_neimode_t mode); DECLDIR int igraph_all_st_cuts(const igraph_t *graph, igraph_vector_ptr_t *cuts, igraph_vector_ptr_t *partition1s, igraph_integer_t source, igraph_integer_t target); DECLDIR int igraph_all_st_mincuts(const igraph_t *graph, igraph_real_t *value, igraph_vector_ptr_t *cuts, igraph_vector_ptr_t *partition1s, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity); DECLDIR int igraph_gomory_hu_tree(const igraph_t *graph, igraph_t *tree, igraph_vector_t *flows, const igraph_vector_t *capacity); __END_DECLS #endif igraph/src/include/igraph_foreign.h0000644000175100001440000000724513431000472017112 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_FOREIGN_H #define IGRAPH_FOREIGN_H #include "igraph_decls.h" #include "igraph_constants.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_strvector.h" #include __BEGIN_DECLS /* -------------------------------------------------- */ /* Read and write foreign formats */ /* -------------------------------------------------- */ DECLDIR int igraph_read_graph_edgelist(igraph_t *graph, FILE *instream, igraph_integer_t n, igraph_bool_t directed); DECLDIR int igraph_read_graph_ncol(igraph_t *graph, FILE *instream, igraph_strvector_t *predefnames, igraph_bool_t names, igraph_add_weights_t weights, igraph_bool_t directed); DECLDIR int igraph_read_graph_lgl(igraph_t *graph, FILE *instream, igraph_bool_t names, igraph_add_weights_t weights, igraph_bool_t directed); DECLDIR int igraph_read_graph_pajek(igraph_t *graph, FILE *instream); DECLDIR int igraph_read_graph_graphml(igraph_t *graph, FILE *instream, int index); DECLDIR int igraph_read_graph_dimacs(igraph_t *graph, FILE *instream, igraph_strvector_t *problem, igraph_vector_t *label, igraph_integer_t *source, igraph_integer_t *target, igraph_vector_t *capacity, igraph_bool_t directed); DECLDIR int igraph_read_graph_graphdb(igraph_t *graph, FILE *instream, igraph_bool_t directed); DECLDIR int igraph_read_graph_gml(igraph_t *graph, FILE *instream); DECLDIR int igraph_read_graph_dl(igraph_t *graph, FILE *instream, igraph_bool_t directed); DECLDIR int igraph_write_graph_edgelist(const igraph_t *graph, FILE *outstream); DECLDIR int igraph_write_graph_ncol(const igraph_t *graph, FILE *outstream, const char *names, const char *weights); DECLDIR int igraph_write_graph_lgl(const igraph_t *graph, FILE *outstream, const char *names, const char *weights, igraph_bool_t isolates); DECLDIR int igraph_write_graph_graphml(const igraph_t *graph, FILE *outstream, igraph_bool_t prefixattr); DECLDIR int igraph_write_graph_pajek(const igraph_t *graph, FILE *outstream); DECLDIR int igraph_write_graph_dimacs(const igraph_t *graph, FILE *outstream, long int source, long int target, const igraph_vector_t *capacity); DECLDIR int igraph_write_graph_gml(const igraph_t *graph, FILE *outstream, const igraph_vector_t *id, const char *creator); DECLDIR int igraph_write_graph_dot(const igraph_t *graph, FILE *outstream); DECLDIR int igraph_write_graph_leda(const igraph_t *graph, FILE *outstream, const char* vertex_attr_name, const char* edge_attr_name); __END_DECLS #endif igraph/src/include/igraph_heap_pmt.h0000644000175100001440000000370013431000472017246 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ typedef struct TYPE(igraph_heap) { BASE* stor_begin; BASE* stor_end; BASE* end; int destroy; } TYPE(igraph_heap); DECLDIR int FUNCTION(igraph_heap,init)(TYPE(igraph_heap)* h, long int size); DECLDIR int FUNCTION(igraph_heap,init_array)(TYPE(igraph_heap) *t, BASE* data, long int len); DECLDIR void FUNCTION(igraph_heap,destroy)(TYPE(igraph_heap)* h); DECLDIR igraph_bool_t FUNCTION(igraph_heap,empty)(TYPE(igraph_heap)* h); DECLDIR int FUNCTION(igraph_heap,push)(TYPE(igraph_heap)* h, BASE elem); DECLDIR BASE FUNCTION(igraph_heap,top)(TYPE(igraph_heap)* h); DECLDIR BASE FUNCTION(igraph_heap,delete_top)(TYPE(igraph_heap)* h); DECLDIR long int FUNCTION(igraph_heap,size)(TYPE(igraph_heap)* h); DECLDIR int FUNCTION(igraph_heap,reserve)(TYPE(igraph_heap)* h, long int size); void FUNCTION(igraph_heap,i_build)(BASE* arr, long int size, long int head); void FUNCTION(igraph_heap,i_shift_up)(BASE* arr, long int size, long int elem); void FUNCTION(igraph_heap,i_sink)(BASE* arr, long int size, long int head); void FUNCTION(igraph_heap,i_switch)(BASE* arr, long int e1, long int e2); igraph/src/include/igraph_matrix_pmt.h0000644000175100001440000002405413431000472017642 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ typedef struct TYPE(igraph_matrix) { TYPE(igraph_vector) data; long int nrow, ncol; } TYPE(igraph_matrix); /*---------------*/ /* Allocation */ /*---------------*/ DECLDIR int FUNCTION(igraph_matrix,init)(TYPE(igraph_matrix) *m, long int nrow, long int ncol); DECLDIR int FUNCTION(igraph_matrix,copy)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from); DECLDIR void FUNCTION(igraph_matrix,destroy)(TYPE(igraph_matrix) *m); DECLDIR long int FUNCTION(igraph_matrix,capacity)(const TYPE(igraph_matrix) *m); /*--------------------*/ /* Accessing elements */ /*--------------------*/ /* MATRIX */ DECLDIR BASE FUNCTION(igraph_matrix,e)(const TYPE(igraph_matrix) *m, long int row, long int col); BASE* FUNCTION(igraph_matrix,e_ptr)(const TYPE(igraph_matrix) *m, long int row, long int col); DECLDIR void FUNCTION(igraph_matrix,set)(TYPE(igraph_matrix)* m, long int row, long int col, BASE value); /*------------------------------*/ /* Initializing matrix elements */ /*------------------------------*/ DECLDIR void FUNCTION(igraph_matrix,null)(TYPE(igraph_matrix) *m); DECLDIR void FUNCTION(igraph_matrix,fill)(TYPE(igraph_matrix) *m, BASE e); /*-----------------------*/ /* Matrix views */ /*-----------------------*/ const TYPE(igraph_matrix) *FUNCTION(igraph_matrix,view)(const TYPE(igraph_matrix) *m, const BASE *data, long int nrow, long int ncol); /*------------------*/ /* Copying matrices */ /*------------------*/ DECLDIR void FUNCTION(igraph_matrix,copy_to)(const TYPE(igraph_matrix) *m, BASE *to); DECLDIR int FUNCTION(igraph_matrix,update)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from); DECLDIR int FUNCTION(igraph_matrix,rbind)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from); DECLDIR int FUNCTION(igraph_matrix,cbind)(TYPE(igraph_matrix) *to, const TYPE(igraph_matrix) *from); DECLDIR int FUNCTION(igraph_matrix,swap)(TYPE(igraph_matrix) *m1, TYPE(igraph_matrix) *m2); /*--------------------------*/ /* Copying rows and columns */ /*--------------------------*/ DECLDIR int FUNCTION(igraph_matrix,get_row)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res, long int index); DECLDIR int FUNCTION(igraph_matrix,get_col)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res, long int index); DECLDIR int FUNCTION(igraph_matrix,set_row)(TYPE(igraph_matrix) *m, const TYPE(igraph_vector) *v, long int index); DECLDIR int FUNCTION(igraph_matrix,set_col)(TYPE(igraph_matrix) *m, const TYPE(igraph_vector) *v, long int index); DECLDIR int FUNCTION(igraph_matrix,select_rows)(const TYPE(igraph_matrix) *m, TYPE(igraph_matrix) *res, const igraph_vector_t *rows); DECLDIR int FUNCTION(igraph_matrix,select_cols)(const TYPE(igraph_matrix) *m, TYPE(igraph_matrix) *res, const igraph_vector_t *cols); DECLDIR int FUNCTION(igraph_matrix,select_rows_cols)(const TYPE(igraph_matrix) *m, TYPE(igraph_matrix) *res, const igraph_vector_t *rows, const igraph_vector_t *cols); /*-----------------------------*/ /* Exchanging rows and columns */ /*-----------------------------*/ DECLDIR int FUNCTION(igraph_matrix,swap_rows)(TYPE(igraph_matrix) *m, long int i, long int j); DECLDIR int FUNCTION(igraph_matrix,swap_cols)(TYPE(igraph_matrix) *m, long int i, long int j); DECLDIR int FUNCTION(igraph_matrix,swap_rowcol)(TYPE(igraph_matrix) *m, long int i, long int j); DECLDIR int FUNCTION(igraph_matrix,transpose)(TYPE(igraph_matrix) *m); /*-----------------------------*/ /* Matrix operations */ /*-----------------------------*/ DECLDIR int FUNCTION(igraph_matrix,add)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); DECLDIR int FUNCTION(igraph_matrix,sub)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); DECLDIR int FUNCTION(igraph_matrix,mul_elements)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); DECLDIR int FUNCTION(igraph_matrix,div_elements)(TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); DECLDIR void FUNCTION(igraph_matrix,scale)(TYPE(igraph_matrix) *m, BASE by); DECLDIR void FUNCTION(igraph_matrix,add_constant)(TYPE(igraph_matrix) *m, BASE plus); /*-----------------------------*/ /* Finding minimum and maximum */ /*-----------------------------*/ DECLDIR igraph_real_t FUNCTION(igraph_matrix,min)(const TYPE(igraph_matrix) *m); DECLDIR igraph_real_t FUNCTION(igraph_matrix,max)(const TYPE(igraph_matrix) *m); DECLDIR int FUNCTION(igraph_matrix,which_min)(const TYPE(igraph_matrix) *m, long int *i, long int *j); DECLDIR int FUNCTION(igraph_matrix,which_max)(const TYPE(igraph_matrix) *m, long int *i, long int *j); DECLDIR int FUNCTION(igraph_matrix,minmax)(const TYPE(igraph_matrix) *m, BASE *min, BASE *max); DECLDIR int FUNCTION(igraph_matrix,which_minmax)(const TYPE(igraph_matrix) *m, long int *imin, long int *jmin, long int *imax, long int *jmax); /*------------------------------*/ /* Comparison */ /*------------------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_matrix,all_e)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,all_l)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,all_g)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,all_le)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,all_ge)(const TYPE(igraph_matrix) *lhs, const TYPE(igraph_matrix) *rhs); /*-------------------*/ /* Matrix properties */ /*-------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_matrix,isnull)(const TYPE(igraph_matrix) *m); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,empty)(const TYPE(igraph_matrix) *m); DECLDIR long int FUNCTION(igraph_matrix,size)(const TYPE(igraph_matrix) *m); DECLDIR long int FUNCTION(igraph_matrix,nrow)(const TYPE(igraph_matrix) *m); DECLDIR long int FUNCTION(igraph_matrix,ncol)(const TYPE(igraph_matrix) *m); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,is_symmetric)(const TYPE(igraph_matrix) *m); DECLDIR BASE FUNCTION(igraph_matrix,sum)(const TYPE(igraph_matrix) *m); DECLDIR BASE FUNCTION(igraph_matrix,prod)(const TYPE(igraph_matrix) *m); DECLDIR int FUNCTION(igraph_matrix,rowsum)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res); DECLDIR int FUNCTION(igraph_matrix,colsum)(const TYPE(igraph_matrix) *m, TYPE(igraph_vector) *res); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,is_equal)(const TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); DECLDIR igraph_real_t FUNCTION(igraph_matrix,maxdifference)(const TYPE(igraph_matrix) *m1, const TYPE(igraph_matrix) *m2); /*------------------------*/ /* Searching for elements */ /*------------------------*/ DECLDIR igraph_bool_t FUNCTION(igraph_matrix,contains)(const TYPE(igraph_matrix) *m, BASE e); DECLDIR igraph_bool_t FUNCTION(igraph_matrix,search)(const TYPE(igraph_matrix) *m, long int from, BASE what, long int *pos, long int *row, long int *col); /*------------------------*/ /* Resizing operations */ /*------------------------*/ DECLDIR int FUNCTION(igraph_matrix,resize)(TYPE(igraph_matrix) *m, long int nrow, long int ncol); DECLDIR int FUNCTION(igraph_matrix,resize_min)(TYPE(igraph_matrix) *m); DECLDIR int FUNCTION(igraph_matrix,add_cols)(TYPE(igraph_matrix) *m, long int n); DECLDIR int FUNCTION(igraph_matrix,add_rows)(TYPE(igraph_matrix) *m, long int n); DECLDIR int FUNCTION(igraph_matrix,remove_col)(TYPE(igraph_matrix) *m, long int col); DECLDIR int FUNCTION(igraph_matrix,remove_row)(TYPE(igraph_matrix) *m, long int row); /*------------------------*/ /* Print as text */ /*------------------------*/ int FUNCTION(igraph_matrix,print)(const TYPE(igraph_matrix) *m); int FUNCTION(igraph_matrix,printf)(const TYPE(igraph_matrix) *m, const char *format); int FUNCTION(igraph_matrix,fprint)(const TYPE(igraph_matrix) *m, FILE *file); #ifdef BASE_COMPLEX int igraph_matrix_complex_real(const igraph_matrix_complex_t *v, igraph_matrix_t *real); int igraph_matrix_complex_imag(const igraph_matrix_complex_t *v, igraph_matrix_t *imag); int igraph_matrix_complex_realimag(const igraph_matrix_complex_t *v, igraph_matrix_t *real, igraph_matrix_t *imag); int igraph_matrix_complex_create(igraph_matrix_complex_t *v, const igraph_matrix_t *real, const igraph_matrix_t *imag); int igraph_matrix_complex_create_polar(igraph_matrix_complex_t *v, const igraph_matrix_t *r, const igraph_matrix_t *theta); #endif /* ----------------------------------------------------------------------------*/ /* For internal use only, may be removed, rewritten ... */ /* ----------------------------------------------------------------------------*/ int FUNCTION(igraph_matrix,permdelete_rows)(TYPE(igraph_matrix) *m, long int *index, long int nremove); int FUNCTION(igraph_matrix,delete_rows_neg)(TYPE(igraph_matrix) *m, const igraph_vector_t *neg, long int nremove); igraph/src/include/igraph_spmatrix.h0000644000175100001440000001257513431000472017332 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_SPMATRIX_H #define IGRAPH_SPMATRIX_H #include "igraph_decls.h" #include "igraph_vector.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Sparse matrix */ /* -------------------------------------------------- */ /** * \section about_igraph_spmatrix_t_objects About \type igraph_spmatrix_t objects * * The \type igraph_spmatrix_t type stores a sparse matrix with the * assumption that the number of nonzero elements in the matrix scales * linearly with the row or column count of the matrix (so most of the * elements are zero). Of course it can store an arbitrary real matrix, * but if most of the elements are nonzero, one should use \type igraph_matrix_t * instead. * * The elements are stored in column compressed format, so the elements * in the same column are stored adjacent in the computer's memory. The storage * requirement for a sparse matrix is O(n) where n is the number of nonzero * elements. Actually it can be a bit larger, see the documentation of * the vector type for an explanation. */ typedef struct s_spmatrix { igraph_vector_t ridx, cidx, data; long int nrow, ncol; } igraph_spmatrix_t; #define IGRAPH_SPMATRIX_INIT_FINALLY(m, nr, nc) \ do { IGRAPH_CHECK(igraph_spmatrix_init(m, nr, nc)); \ IGRAPH_FINALLY(igraph_spmatrix_destroy, m); } while (0) DECLDIR int igraph_spmatrix_init(igraph_spmatrix_t *m, long int nrow, long int ncol); DECLDIR void igraph_spmatrix_destroy(igraph_spmatrix_t *m); DECLDIR int igraph_spmatrix_resize(igraph_spmatrix_t *m, long int nrow, long int ncol); DECLDIR igraph_real_t igraph_spmatrix_e(const igraph_spmatrix_t *m, long int row, long int col); DECLDIR int igraph_spmatrix_set(igraph_spmatrix_t *m, long int row, long int col, igraph_real_t value); DECLDIR int igraph_spmatrix_add_e(igraph_spmatrix_t *m, long int row, long int col, igraph_real_t value); DECLDIR int igraph_spmatrix_add_col_values(igraph_spmatrix_t *m, long int to, long int from); DECLDIR long int igraph_spmatrix_count_nonzero(const igraph_spmatrix_t *m); DECLDIR long int igraph_spmatrix_size(const igraph_spmatrix_t *m); DECLDIR long int igraph_spmatrix_nrow(const igraph_spmatrix_t *m); DECLDIR long int igraph_spmatrix_ncol(const igraph_spmatrix_t *m); DECLDIR int igraph_spmatrix_copy_to(const igraph_spmatrix_t *m, igraph_real_t *to); DECLDIR int igraph_spmatrix_null(igraph_spmatrix_t *m); DECLDIR int igraph_spmatrix_add_cols(igraph_spmatrix_t *m, long int n); DECLDIR int igraph_spmatrix_add_rows(igraph_spmatrix_t *m, long int n); DECLDIR int igraph_spmatrix_clear_col(igraph_spmatrix_t *m, long int col); DECLDIR int igraph_spmatrix_clear_row(igraph_spmatrix_t *m, long int row); DECLDIR int igraph_spmatrix_copy(igraph_spmatrix_t *to, const igraph_spmatrix_t *from); DECLDIR igraph_real_t igraph_spmatrix_max_nonzero(const igraph_spmatrix_t *m, igraph_real_t *ridx, igraph_real_t *cidx); DECLDIR igraph_real_t igraph_spmatrix_max(const igraph_spmatrix_t *m, igraph_real_t *ridx, igraph_real_t *cidx); DECLDIR void igraph_spmatrix_scale(igraph_spmatrix_t *m, igraph_real_t by); DECLDIR int igraph_spmatrix_colsums(const igraph_spmatrix_t *m, igraph_vector_t *res); DECLDIR int igraph_spmatrix_rowsums(const igraph_spmatrix_t *m, igraph_vector_t *res); DECLDIR int igraph_spmatrix_print(const igraph_spmatrix_t *matrix); DECLDIR int igraph_spmatrix_fprint(const igraph_spmatrix_t *matrix, FILE* file); DECLDIR int igraph_i_spmatrix_get_col_nonzero_indices(const igraph_spmatrix_t *m, igraph_vector_t *res, long int col); DECLDIR int igraph_i_spmatrix_clear_row_fast(igraph_spmatrix_t *m, long int row); DECLDIR int igraph_i_spmatrix_cleanup(igraph_spmatrix_t *m); typedef struct s_spmatrix_iter { const igraph_spmatrix_t *m; /* pointer to the matrix we are iterating over */ long int pos; /* internal index into the data vector */ long int ri; /* row index */ long int ci; /* column index */ igraph_real_t value; /* value at the given cell */ } igraph_spmatrix_iter_t; DECLDIR int igraph_spmatrix_iter_create(igraph_spmatrix_iter_t *mit, const igraph_spmatrix_t *m); DECLDIR int igraph_spmatrix_iter_reset(igraph_spmatrix_iter_t *mit); DECLDIR int igraph_spmatrix_iter_next(igraph_spmatrix_iter_t *mit); DECLDIR igraph_bool_t igraph_spmatrix_iter_end(igraph_spmatrix_iter_t *mit); DECLDIR void igraph_spmatrix_iter_destroy(igraph_spmatrix_iter_t *mit); __END_DECLS #endif igraph/src/gengraph_graph_molloy_optimized.cpp0000644000175100001440000015716513431000472021501 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_definitions.h" #include #include #include #include #include "gengraph_qsort.h" #include "gengraph_box_list.h" #include "gengraph_vertex_cover.h" #include "gengraph_degree_sequence.h" #include "gengraph_graph_molloy_optimized.h" #include "igraph_error.h" #include "igraph_statusbar.h" #include "igraph_progress.h" #ifndef register #define register #endif using namespace std; namespace gengraph { void graph_molloy_opt::breadth_search(int *dist, int v0, int *buff) { bool tmpbuff = (buff==NULL); if(tmpbuff) buff = new int[n]; for(int i=0; im) m=deg[k]; return m; } void graph_molloy_opt::compute_neigh() { int *p = links; for(int i=0; in) n=i; // n++; // // degrees ? // if(VERBOSE()) fprintf(stderr,"%d, #edges=",n); // int *degs = new int[n]; // for(i=0; i=i) *(c++)=*p; } } assert(c==b+(a/2)); return b; } int *graph_molloy_opt::hard_copy() { int *hc = new int[2+n+a/2]; // to store n,a,deg[] and links[] hc[0] = n; hc[1] = a; memcpy(hc+2,deg,sizeof(int)*n); int *c = hc+2+n; for(int i=0; i=i) *(c++)=*p; } } assert(c==hc+2+n+a/2); return hc; } void graph_molloy_opt::restore(int* b) { int i; for(i=0; i=0; i--) a+=(deg[i]=int(neigh[i+1]-neigh[i])); refresh_nbarcs(); } void graph_molloy_opt::clean() { int *b = hard_copy(); replace(b); delete[] b; } void graph_molloy_opt::replace(int *_hardcopy) { delete[] deg; n = *(_hardcopy++); a = *(_hardcopy++); deg = new int[a+n]; memcpy(deg,_hardcopy,sizeof(int)*n); links = deg+n; compute_neigh(); restore(_hardcopy+n); } int* graph_molloy_opt::components(int *comp) { int i; // breadth-first search buffer int *buff=new int[n]; // comp[i] will contain the index of the component that contains vertex i if(comp==NULL) comp=new int[n]; memset(comp,0,sizeof(int)*n); // current component index int curr_comp = 0; // loop over all non-visited vertices... for(int v0=0; v0 nb_comp) nb_comp=comp[i]; // box-sort sizes int offset = 0; int *box = pre_boxsort(buff,nb_comp,offset); for(i=nb_comp-1; i>=0; i--) buff[i] = --box[buff[i]-offset]; delete[] box; // reassign component indexes for(int *c=comp+n; comp!=c--; *c=buff[*c-1]) { } // clean.. at last! delete[] buff; return comp; } void graph_molloy_opt::giant_comp() { int *comp = components(); // Clear edges of all vertices that do not belong to comp 0 for(int i=0; i=0; i--) { c+=nb[i]; nb[i]=-nb[i]+c; } // sort for(i=0; i0; ) { // pick a vertex. we could pick any, but here we pick the one with biggest degree int v = sorted[first]; // look for current degree of v while(nb[d]<=first) d--; // store it in dv int dv = d; // bind it ! c -= dv; int dc = d; // residual degree of vertices we bind to int fc = ++first; // position of the first vertex with degree dc while(dv>0 && dc>0) { int lc = nb[dc]; if(lc!=fc) { while(dv>0 && lc>fc) { // binds v with sorted[--lc] dv--; int w = sorted[--lc]; *(neigh[v]++) = w; *(neigh[w]++) = v; } fc = nb[dc]; nb[dc] = lc; } dc--; } if(dv != 0) { // We couldn't bind entirely v delete[] nb; delete[] sorted; compute_neigh(); igraph_errorf("Error in graph_molloy_opt::havelhakimi():" " Couldn't bind vertex %d entirely " "(%d edges remaining)", __FILE__, __LINE__, IGRAPH_EINTERNAL, v, dv); return false; } } assert(c==0); compute_neigh(); delete[] nb; delete[] sorted; return true; } bool graph_molloy_opt::is_connected() { bool *visited = new bool[n]; for(int i=n; i>0; visited[--i]=false) { } int *to_visit = new int[n]; int *stop = to_visit; int left = n-1; *(to_visit++) = 0; visited[0] = true; while(left>0 && to_visit != stop) { int v = *(--to_visit); int *w = neigh[v]; for(int k = deg[v]; k--; w++) if(!visited[*w]) { visited[*w] = true; left--; *(to_visit++) = *w; } } delete[] visited; delete[] stop; assert(left>=0); return (left == 0); } bool graph_molloy_opt::make_connected() { //assert(verify()); if(a/2 < n-1) { // fprintf(stderr,"\ngraph::make_connected() failed : #edges < #vertices-1\n"); return false; } int i; // Data struct for the visit : // - buff[] contains vertices to visit // - dist[V] is V's distance modulo 4 to the root of its comp, or -1 if it hasn't been visited yet #define MC_BUFF_SIZE (n+2) int *buff = new int[MC_BUFF_SIZE]; unsigned char * dist = new unsigned char[n]; #define NOT_VISITED 255 #define FORBIDDEN 254 for(i=n; i>0; dist[--i]=NOT_VISITED) { } // Data struct to store components : either surplus trees or surplus edges are stored at buff[]'s end // - A Tree is coded by one of its vertices // - An edge (a,b) is coded by the TWO ints a and b int *ffub = buff+MC_BUFF_SIZE; edge *edges = (edge *) ffub; int *trees = ffub; int *min_ffub = buff+1+(MC_BUFF_SIZE%2 ? 0 : 1); // There will be only one "fatty" component, and trees. edge fatty_edge = { -1, -1 }; bool enough_edges = false; // start main loop for(int v0=0; v0min_ffub) min_ffub+=2; // update limit of ffub's storage //assert(verify()); } else if(dist[w]==next_dist || (w>=v && dist[w]==current_dist)) { // we found a removable edge if(trees!=ffub) { // some trees still.. Let's merge with them! assert(trees>=min_ffub); assert(edges==(edge *)ffub); swap_edges(v,w,*trees,neigh[*trees][0]); trees++; //assert(verify()); } else if(is_a_tree) { // we must merge with the fatty component is_a_tree = false; if(fatty_edge.from < 0) { // we ARE the first component! fatty is us fatty_edge.from = v; fatty_edge.to = w; } else { // we connect to fatty swap_edges(fatty_edge.from, fatty_edge.to, v, w); fatty_edge.to = w; //assert(verify()); } } else if(!enough_edges) { // Store the removable edge for future use if(edges<=(edge *)min_ffub+1) enough_edges = true; else { edges--; edges->from = v; edges->to = w; } } } } } // Mark component while(to_visit!=buff) dist[*(--to_visit)] = FORBIDDEN; // Check if it is a tree if(is_a_tree ) { assert(deg[v0]!=0); if(edges!=(edge *)ffub) { // let's bind the tree we found with a removable edge in stock assert(trees == ffub); if(edges<(edge *)min_ffub) edges=(edge *)min_ffub; swap_edges(v0,neigh[v0][0],edges->from,edges->to); edges++; assert(verify()); } else if(fatty_edge.from>=0) { // if there is a fatty component, let's merge with it ! and discard fatty :-/ assert(trees == ffub); swap_edges(v0,neigh[v0][0],fatty_edge.from,fatty_edge.to); fatty_edge.from = -1; fatty_edge.to = -1; assert(verify()); } else { // add the tree to the list of trees assert(trees>min_ffub); *(--trees) = v0; assert(verify()); } } } delete[] buff; delete[] dist; // Should ALWAYS return true : either we have no tree left, or we are a unique, big tree return(trees == ffub || ((trees+1)==ffub && fatty_edge.from<0)); } bool graph_molloy_opt::swap_edges_simple(int from1, int to1, int from2, int to2) { if(from1==to1 || from1==from2 || from1==to2 || to1==from2 || to1==to2 || from2==to2) return false; if (is_edge(from1,to2) || is_edge(from2,to1)) return false; swap_edges(from1, to1, from2, to2); return true; } long graph_molloy_opt::fab_connected_shuffle(long times) { //assert(verify()); long nb_swaps = 0; double T = double(min(a,times))/10.0; double q1 = 1.131; double q2 = 0.9237; while(times>0) { long iperiod = max(1,long(T)); // Backup graph int *save = backup(); //assert(verify()); // Swaps long swaps = 0; for(long i=iperiod; i>0; i--) { // Pick two random vertices int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; if(f1==f2) continue; // Pick two random neighbours int *f1t1 = neigh[f1]+my_random()%deg[f1]; int *f2t2 = neigh[f2]+my_random()%deg[f2]; int t1 = *f1t1; int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; fast_rpl(neigh[t1],f1,f2); fast_rpl(neigh[t2],f2,f1); swaps++; } } //assert(verify()); // test connectivity if(is_connected()) { nb_swaps += swaps; times -= iperiod; // adjust T T*=q1; } else { restore(save); //assert(verify()); T*=q2; } delete[] save; } return nb_swaps; } long graph_molloy_opt::opt_fab_connected_shuffle(long times) { //assert(verify()); long nb_swaps = 0; double T = double(min(a,times))/10.0; double q1 = 1.131; double q2 = 0.9237; while(times>0) { long iperiod = max(1,long(T)); // Backup graph int *save = backup(); //assert(verify()); // Swaps long swaps = 0; for(long i=iperiod; i>0; i--) { // Pick two random vertices int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; if(f1==f2) continue; // Pick two random neighbours int *f1t1 = neigh[f1]+my_random()%deg[f1]; int *f2t2 = neigh[f2]+my_random()%deg[f2]; int t1 = *f1t1; int t2 = *f2t2; if( // test simplicity t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1) && // test isolated pair (deg[f1]>1 || deg[t2]>1) && (deg[f2]>1 || deg[t1]>1) ) { // swap *f1t1 = t2; *f2t2 = t1; fast_rpl(neigh[t1],f1,f2); fast_rpl(neigh[t2],f2,f1); swaps++; } } //assert(verify()); // test connectivity if(is_connected()) { nb_swaps += swaps; times -= iperiod; // adjust T T*=q1; } else { restore(save); //assert(verify()); T*=q2; } delete[] save; } return nb_swaps; } long graph_molloy_opt::gkantsidis_connected_shuffle(long times) { //assert(verify()); long nb_swaps = 0; long T = min(a,times)/10; while(times>0) { // Backup graph int *save = backup(); //assert(verify()); // Swaps long swaps = 0; for(int i=T; i>0; i--) { // Pick two random vertices int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; if(f1==f2) continue; // Pick two random neighbours int *f1t1 = neigh[f1]+my_random()%deg[f1]; int *f2t2 = neigh[f2]+my_random()%deg[f2]; int t1 = *f1t1; int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; fast_rpl(neigh[t1],f1,f2); fast_rpl(neigh[t2],f2,f1); swaps++; } } //assert(verify()); // test connectivity if(is_connected()) { nb_swaps += swaps; times -= T; // adjust T T++; } else { restore(save); //assert(verify()); T/=2; if(T==0) T=1; } delete[] save; } return nb_swaps; } long graph_molloy_opt::slow_connected_shuffle(long times) { //assert(verify()); long nb_swaps = 0; while(times--) { // Pick two random vertices int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; if(f1==f2) continue; // Pick two random neighbours int *f1t1 = neigh[f1]+my_random()%deg[f1]; int *f2t2 = neigh[f2]+my_random()%deg[f2]; int t1 = *f1t1; int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; int *t1f1 = fast_rpl(neigh[t1],f1,f2); int *t2f2 = fast_rpl(neigh[t2],f2,f1); // test connectivity if(is_connected()) nb_swaps++; else { // undo swap *t1f1 = f1; *t2f2 = f2; *f1t1 = t1; *f2t2 = t2; } } } return nb_swaps; } void graph_molloy_opt::print(FILE *f, bool NOZERO) { int i,j; for(i=0; i0) { fprintf(f,"%d",i); for(j=0; j=dmax) { left_to_explore = 0; return; } *(Kbuff++) = v; visited[v] = true; calls++; int *w = neigh[v]; qsort(deg, w, deg[v]); w+=deg[v]; for(int i=deg[v]; i--; ) { if(visited[*--w]) calls++; else depth_isolated(*w, calls, left_to_explore, dmax, Kbuff, visited); if(left_to_explore==0) break; } } int graph_molloy_opt::depth_search(bool *visited, int *buff, int v0) { for(int i=0; i=0) for(int i=0; i=newdeg[v]) { int *p = neigh[v]+(newdeg[v]++); *ww = *p; *p = w; // Now, add the dual edge ww = neigh[w]; p = ww+(newdeg[w]); while(ww!=p && *ww != v) { ww++; k2++; } if(ww==p) { // dual edge was not discovered.. search it and add it. while(*ww != v) { ww++; k2++; } *ww = *p; *p = v; newdeg[w]++; } } // if edge redudancy is asked, look for dual edge else if(edge_redudancy!=NULL) for(int *ww = neigh[w]; *(ww++)!=v; k2++) { } // add edge redudancy if(edge_redudancy!=NULL) { edge_redudancy[v][k] += red; edge_redudancy[w][k2] += red; } assert(newdeg[v]<=deg[v]); } // dist[] MUST be full of zeros !!!! int graph_molloy_opt::breadth_path_search(int src, int *buff, double *paths, unsigned char *dist) { unsigned char last_dist = 0; unsigned char curr_dist = 1; int *to_visit = buff; int *visited = buff; *(to_visit++) = src; paths[src] = 1.0; dist[src] = curr_dist; int nb_visited = 1; while(visited != to_visit) { int v = *(visited++); if(last_dist==(curr_dist=dist[v])) break; unsigned char nd = next_dist(curr_dist); int *ww = neigh[v]; double p = paths[v]; for(int k=deg[v]; k--;) { int w=*(ww++); unsigned char d = dist[w]; if(d==0) { // not visited yet ! *(to_visit++) = w; dist[w] = nd; paths[w]= p; // is it the last one ? if(++nb_visited==n) last_dist=nd; } else if(d==nd) if((paths[w]+=p)==numeric_limits::infinity()) { IGRAPH_ERROR("Fatal error : too many (>MAX_DOUBLE) possible" " paths in graph", IGRAPH_EOVERFLOW); } } } assert(to_visit == buff+nb_visited); return nb_visited; } // dist[] MUST be full of zeros !!!! void graph_molloy_opt::explore_usp(double *target, int nb_vertices, int *buff, double *paths, unsigned char *dist, int *newdeg, double **edge_redudancy) { while(--nb_vertices) { int v = buff[nb_vertices]; if(target[v]>0.0) { unsigned char pd = prev_dist(dist[v]); int *ww = neigh[v]; int k=0; // pick ONE father at random double father_index = my_random01()*paths[v]; double f = 0.0; int father = -1; while(f0.0) { unsigned char pd = prev_dist(dist[v]); int *ww = neigh[v]; int dv = deg[v]; double f=target[v]/paths[v]; // pick ALL fathers register int father; for(int k=0; k0.0) { unsigned char pd = prev_dist(dist[v]); int *ww = neigh[v]; // for all fathers : do we take it ? int paths_left = int(target[v]); double father_index = paths[v]; int father; for(int k=0; k0) { paths_left -= to_add_to_father; // increase target[] of father target[father] += to_add_to_father; // add edge, if necessary if(newdeg!=NULL) add_traceroute_edge(v,k,newdeg,edge_redudancy,target[v]); } } } // clear dist[] dist[v] = 0; } dist[buff[0]] = 0; } double *graph_molloy_opt::vertex_betweenness(int mode, bool trivial_paths) { char MODES[3] = {'U','A','R'}; igraph_statusf("Computing vertex betweenness %cSP...", 0, MODES[mode]); // breadth-first search vertex fifo int *buff = new int[n]; // breadth-first search path count double *paths = new double[n]; // breadth-first search distance vector unsigned char *dist = new unsigned char[n]; // global betweenness double *b = new double[n]; // local betweenness (for one source) double *target = new double[n]; // init all int progress = 0; memset(dist,0,sizeof(unsigned char)*n); for(double *yo = target+n; (yo--)!=target; *yo=1.0) { } for(double *yo = b+n; (yo--)!=b; *yo=0.0) { } int progress_steps = max(1000,n/10); // Main loop for(int v0 = 0; v0(progress*n) / progress_steps) { progress++; igraph_progressf("Computing vertex betweenness %cSP", 100.0*double(progress)/double(progress_steps), 0, MODES[mode]); } // Breadth-first search int nb_vertices = breadth_path_search(v0, buff, paths, dist); // initialize target[vertices in component] to 1 //for(int *yo = buff+nb_vertices; (yo--)!=buff; target[*yo]=1.0); // backwards-cumulative exploration switch(mode) { case MODE_USP: explore_usp(target, nb_vertices, buff, paths, dist); break; case MODE_ASP: explore_asp(target, nb_vertices, buff, paths, dist); break; case MODE_RSP: explore_rsp(target, nb_vertices, buff, paths, dist); break; default: IGRAPH_WARNING("graph_molloy_opt::vertex_betweenness() " "called with Invalid Mode"); } // add targets[vertices in component] to global betweenness and reset targets[] if(nb_vertices==n) { // cache optimization if all vertices are in component double *bb=b; double *tt_end=target+n; if(trivial_paths) for(double *yo=target; yo!=tt_end; *(bb++)+=*(yo++)){} else { for(double *yo=target; yo!=tt_end; *(bb++)+=(*(yo++)-1.0)) { } b[*buff]-=(target[*buff]-1.0); } for(double *yo = target; yo!=tt_end; *(yo++)=1.0) { } } else { if(trivial_paths) for(int *yo = buff+nb_vertices; (yo--)!=buff; b[*yo]+=target[*yo]) { } else for(int *yo = buff+nb_vertices; (--yo)!=buff; b[*yo]+=(target[*yo]-1.0)) { } for(int *yo = buff+nb_vertices; (yo--)!=buff; target[*yo]=1.0) { } } } // Clean all & return delete[] target; delete[] dist; delete[] buff; delete[] paths; igraph_status("Done\n", 0); return b; } double graph_molloy_opt::traceroute_sample(int mode, int nb_src, int *src, int nb_dst, int* dst, double *redudancy, double **edge_redudancy) { // verify & verbose assert(verify()); char MODES[3] = {'U','A','R'}; igraph_statusf("traceroute %cSP on G(N=%d,M=%d) with %d src and %d dst...", 0, MODES[mode], nbvertices_real(), nbarcs(), nb_src,nb_dst); // create dst[] buffer if necessary bool newdist = dst==NULL; if(newdist) dst = new int[n]; // breadth-first search vertex fifo int *buff = new int[n]; // breadth-first search path count double *paths = new double[n]; // breadth-first search distance vector unsigned char *dist = new unsigned char[n]; // newdeg[] allows to tag discovered edges int *newdeg = new int[n]; // target[v] is > 0 if v is a destination double *target = new double[n]; // init all int i; memset(dist,0,sizeof(unsigned char)*n); memset(newdeg,0,sizeof(int)*n); for(double *yo = target+n; (yo--)!=target; *yo=0.0) { } if(redudancy!=NULL) for(double *yo = redudancy+n; (yo--)!=redudancy; *yo=0.0) { } // src_0 counts the number of sources having degree 0 int src_0 = 0; // nopath counts the number of pairs (src,dst) having no possible path int nopath = 0; // nb_paths & total_dist are for the average distance estimator int nb_paths = 0; double total_dist = 0; // s will be the current source int s; while(nb_src--) if(deg[s = *(src++)]==0) src_0++; else { // breadth-first search int nb_vertices = breadth_path_search(s,buff,paths,dist); // do we have to pick new destinations ? if(newdist) pick_random_dst(double(nb_dst),NULL,dst); // mark reachable destinations as "targets" for(i=0; i0.0) { total_dist += double(current_dist); nb_paths++; } } // substract target[] to redudancy if needed if(redudancy!=NULL) for(i=1; i0) { if(deg[s]==0) src_0++; else { if(s>next_step) { next_step = s+(n/1000)+1; igraph_progress("Sampling paths", double(s)/double(n), 0); } int v; // breadth-first search int *to_visit=buff; int *visited=buff; *(to_visit++)=s; dist[s]=1; nb_pos[s]=1; while(visited!=to_visit) { v=*(visited++); unsigned char n_dist = next_dist(dist[v]); int *w0 = neigh[v]; for(int *w = w0+deg[v]; w--!=w0; ) { unsigned char d2 = dist[*w]; if(d2==0) { dist[*w]=d2=n_dist; *(to_visit++) = *w; } if(d2==n_dist) nb_pos[*w] += nb_pos[v]; } } // for every target, pick a random path. int t_index = nb_dst[s]; // create dst[] if necessary if(NOMEM) pick_random_src(double(t_index),NULL,dst); while(t_index--) if(dist[v = *(dst++)]==0) nopath++; else { #ifdef _DEBUG igraph_statusf("Sampling path %d -> %d\n", 0, s, v); #endif //_DEBUG nb_paths++; // while we haven't reached the source.. while(v!=s) { // pick a random father int index = my_random()%nb_pos[v]; unsigned char p_dist = prev_dist(dist[v]); int *w = neigh[v]; int k=0; int new_father; while(dist[new_father=w[k]]!=p_dist || (index-=nb_pos[new_father])>=0) k++; // add edge add_traceroute_edge(v,k,newdeg,edge_redudancies,1.0); if(redudancies!=NULL && new_father!=s) redudancies[new_father]+=1.0; // step down to father v = new_father; // increase total distance total_dist++; if(total_dist==0) total_dist64++; } } // reset (int *)dst if necessary if(NOMEM) dst -= nb_dst[s]; // clear breadth-first search buffers while(visited!=buff) { v=*(--visited); dist[v]=0; nb_pos[v]=0; } } } // update degrees for(i=0; i0) tdist *= 4294967296.0; tdist += double(total_dist); return tdist / double(nb_paths); } int *graph_molloy_opt::vertices_real(int &nb_v) { int *yo; if(nb_v<0) { nb_v=0; for(yo=deg; yo!=deg+n; ) if(*(yo++)>0) nb_v++; } if(nb_v==0) { IGRAPH_WARNING("graph is empty"); return NULL; } int *buff=new int[nb_v]; yo=buff; for(int i=0; i0) *(yo++)=i; if(yo!=buff+nb_v){ igraph_warningf("wrong #vertices in graph_molloy_opt::vertices_real(%d)", __FILE__, __LINE__, -1, nb_v); delete[] buff; return NULL; } else return buff; } int *graph_molloy_opt::pick_random_vertices(int &k, int *output, int nb_v, int *among) { int i; bool CREATED_AMONG = false; if(among==NULL && k>0) { among=vertices_real(nb_v); CREATED_AMONG=true; } if(k>nb_v) { igraph_warningf("Warning : tried to pick %d among %d vertices. " "Picked only %d", __FILE__, __LINE__, -1, k, nb_v, nb_v); k = nb_v; } if(k>0) { if(output==NULL) output=new int[k]; for(i=0; i=1.0 ? k : k*double(nb_v)))); if(kk==0) kk=1; int *yo=pick_random_vertices(kk,buff,nb_v,among); if(nb!=NULL) *nb=kk; if(AMONG_CREATED) delete[] among; return yo; } int *graph_molloy_opt::pick_random_dst(double k, int *nb, int* buff, int nb_v, int* among) { bool AMONG_CREATED=false; if(among==NULL || nb_v<0) { AMONG_CREATED=true; among=vertices_real(nb_v); } int kk = int(floor(0.5 + (k>1.0 ? k : k*double(nb_v)))); if(kk==0) kk=1; int *yo=pick_random_vertices(kk,buff,nb_v,among); if(nb!=NULL) *nb=kk; if(AMONG_CREATED) delete[] among; return yo; } int graph_molloy_opt::core() { box_list b(n,deg); int v; int removed = 0; while((v=b.get_one())>=0) { b.pop_vertex(v,neigh); deg[v]=0; removed++; } refresh_nbarcs(); return removed; } int graph_molloy_opt::try_disconnect(int K, int max_tries) { bool *visited = new bool[n]; for(bool *p = visited+n; p!=visited; *(--p)=false) { } int *Kbuff = new int[K]; int tries = 0; int next_step = -1; if(VERBOSE()) next_step = 0; bool yo = true; while(yo && tries 0 if v is a destination double *target = new double[n]; // times_seen count the times we saw each vertex int *times_seen = new int[n]; // init all int i; memset(dist,0,sizeof(unsigned char)*n); memset(times_seen,0,sizeof(int)*n); for(double *yo = target+n; (yo--)!=target; *yo=0.0) { } // src_0 counts the number of sources having degree 0 int src_0 = 0; // nopath counts the number of pairs (src,dst) having no possible path int nopath = 0; // s will be the current source int s; for(int nsrc=0; nsrc=0 && links[i]0); } return true; } /*___________________________________________________________________________________ Not to use anymore : use graph_molloy_hash class instead void graph_molloy_opt::shuffle(long times) { while(times) { int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; int t1 = neigh[f1][my_random()%deg[f1]]; int t2 = neigh[f2][my_random()%deg[f2]]; if(swap_edges_simple(f1,t1,f2,t2)) times--; } } long graph_molloy_opt::connected_shuffle(long times) { //assert(verify()); #ifdef PERFORMANCE_MONITOR long failures = 0; long successes = 0; double avg_K = 0.0; long avg_T = 0; #endif //PERFORMANCE_MONITOR long nb_swaps = 0; long T = min(a,times)/10; double double_K = 1.0; int K = int(double_K); double Q1 = 1.35; double Q2 = 1.01; int *Kbuff = new int[K]; bool *visited = new bool[n]; for(int i=0; inb_swaps) { // Backup graph #ifdef PERFORMANCE_MONITOR avg_K+=double_K; avg_T+=T; #endif //PERFORMANCE_MONITOR int *save = backup(); //assert(verify()); // Swaps long swaps = 0; for(int i=T; i>0; i--) { // Pick two random vertices int f1 = pick_random_vertex(); int f2 = pick_random_vertex(); if(f1==f2) continue; // Pick two random neighbours int *f1t1 = random_neighbour(f1); int t1 = *f1t1; int *f2t2 = random_neighbour(f2); int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && !is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; int *t1f1 = fast_rpl(neigh[t1],f1,f2); int *t2f2 = fast_rpl(neigh[t2],f2,f1); // isolation test if(isolated(f1, K, Kbuff, visited) || isolated(f2, K, Kbuff, visited)) { // undo swap *t1f1 = f1; *t2f2 = f2; *f1t1 = t1; *f2t2 = t2; } else swaps++; } } //assert(verify()); // test connectivity bool ok = is_connected(); #ifdef PERFORMANCE_MONITOR if(ok) successes++; else failures++; #endif //PERFORMANCE_MONITOR if(ok) { nb_swaps += swaps; // adjust K and T if((K+10)*T>5*a) { double_K/=Q2; K = int(double_K); } else T*=2; } else { restore(save); //assert(verify()); double_K*=Q1; K = int(double_K); delete[] Kbuff; Kbuff = new int[K]; } delete[] save; } #ifdef PERFORMANCE_MONITOR fprintf(stderr,"\n*** Performance Monitor ***\n"); fprintf(stderr," - Connectivity test successes : %ld\n",successes); fprintf(stderr," - Connectivity test failures : %ld\n",failures); fprintf(stderr," - Average window : %ld\n",avg_T/long(successes+failures)); fprintf(stderr," - Average isolation test width : %f\n",avg_K/double(successes+failures)); #endif //PERFORMANCE_MONITOR return nb_swaps; } bool graph_molloy_opt::try_shuffle(int T, int K) { int i; int *Kbuff = NULL; if(K>0) Kbuff = new int[K]; bool *visited = new bool[n]; for(i=0; i0; i--) { // Pick two random vertices int f1 = pick_random_vertex(); int f2 = pick_random_vertex(); if(f1==f2) continue; // Pick two random neighbours int *f1t1 = random_neighbour(f1); int t1 = *f1t1; int *f2t2 = random_neighbour(f2); int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; int *t1f1 = fast_rpl(neigh[t1],f1,f2); int *t2f2 = fast_rpl(neigh[t2],f2,f1); // isolation test if(isolated(f1, K, Kbuff, visited) || isolated(f2, K, Kbuff, visited)) { // undo swap *t1f1 = f1; *t2f2 = f2; *f1t1 = t1; *f2t2 = t2; } } } delete[] visited; if(Kbuff != NULL) delete[] Kbuff; bool yo = is_connected(); restore(back); delete[] back; return yo; } double graph_molloy_opt::window(int K, double ratio) { int steps = 100; double T = double(a*10); double q2 = 0.1; double q1 = pow(q2,(ratio-1.0)/ratio); int failures = 0; int successes = 0; int *Kbuff = new int[K]; bool *visited = new bool[n]; while(successes<10*steps) { int *back=backup(); for(int i=int(T); i>0; i--) { // Pick two random vertices int f1 = links[my_random()%a]; int f2 = links[my_random()%a]; if(f1==f2) continue; // Pick two random neighbours int *f1t1 = neigh[f1]+my_random()%deg[f1]; int *f2t2 = neigh[f2]+my_random()%deg[f2]; int t1 = *f1t1; int t2 = *f2t2; // test simplicity if(t1!=t2 && f1!=t2 && f2!=t1 && is_edge(f1,t2) && !is_edge(f2,t1)) { // swap *f1t1 = t2; *f2t2 = t1; int *t1f1 = fast_rpl(neigh[t1],f1,f2); int *t2f2 = fast_rpl(neigh[t2],f2,f1); // isolation test if(isolated(f1, K, Kbuff, visited) || isolated(f2, K, Kbuff, visited)) { // undo swap *t1f1 = f1; *t2f2 = f2; *f1t1 = t1; *f2t2 = t2; } } } if(is_connected()) { T *= q1; if(T>double(5*a)) T=double(5*a); successes++; if((successes%steps)==0) { q2 = sqrt(q2); q1 = sqrt(q1); } } else { T*=q2; failures++; } if(VERBOSE()) fprintf(stderr,"."); restore(back); delete[] back; } delete[] Kbuff; delete[] visited; if(VERBOSE()) fprintf(stderr,"Failures:%d Successes:%d\n",failures, successes); return T; } double graph_molloy_opt::eval_K(int quality) { double K = 5.0; double avg_K = 1.0; for(int i=quality; i--; ) { int int_K = int(floor(K+0.5)); if(try_shuffle(a/(int_K+1),int_K)) { K*=0.8; fprintf(stderr,"+"); } else { K*=1.25; fprintf(stderr,"-"); } if(ideg[t2] ? f1 : t2, K, Kbuff, visited); sum_K += effective_isolated(deg[f2]>deg[t1] ? f2 : t1, K, Kbuff, visited); // undo swap swap_edges(f1,t2,f2,t1); // assert(verify()); } delete[] Kbuff; delete[] visited; return double(sum_K)/double(2*quality); } //___________________________________________________________________________________ //*/ /***** NOT USED ANYMORE (Modif 22/04/2005) ****** int64_t *graph_molloy_opt::vertex_betweenness_usp(bool trivial_paths) { if(VERBOSE()) fprintf(stderr,"Computing vertex betweenness USP..."); int i; unsigned char *dist = new unsigned char[n]; int *buff = new int[n]; int64_t *b = new int64_t[n]; int *bb = new int[n]; int *dd = new int[max_degree()]; for(i=0; i(progress*n)/1000) { progress++; fprintf(stderr,"\rComputing vertex betweenness USP : %d.%d%% ",progress/10,progress%10); } int nb_vertices = width_search(dist, buff, v0); int nv = nb_vertices; for(i=0; i(progress*n)/1000) { progress++; fprintf(stderr,"\rComputing vertex betweenness RSP : %d.%d%% ",progress/10,progress%10); } int nb_vertices = width_search(dist, buff, v0); int nv = nb_vertices; for(i=0; i1 && to_give>2*n_father) { int o = rng.binomial(1.0/n_father,to_give); to_give -= o; bb[dd[--n_father]]+=o; } if(n_father==1) bb[dd[0]]+=to_give; else { while(to_give--) bb[dd[my_random()%n_father]]++; } } if(trivial_paths) bb[v]++; } for(i=0; i0) { if(VERBOSE()==VERBOSE_LOTS && v0>(progress*n)/1000) { progress++; fprintf(stderr,"\rComputing vertex betweenness ASP : %d.%d%% ",progress/10,progress%10); } int nb_vertices = width_search(dist, buff, v0); if(!trivial_paths) dist[v0]=2; int nv = nb_vertices; for(i=0; iset_verbose_level(0); for (unsigned int i=0; iadd_edge((unsigned int)IGRAPH_FROM(graph, i), (unsigned int)IGRAPH_TO(graph, i)); } return g; } void bliss_free_graph(AbstractGraph *g) { delete g; } inline int bliss_set_sh(AbstractGraph *g, igraph_bliss_sh_t sh, bool directed) { if (directed) { Digraph::SplittingHeuristic gsh = Digraph::shs_fsm; switch (sh) { case IGRAPH_BLISS_F: gsh = Digraph::shs_f; break; case IGRAPH_BLISS_FL: gsh = Digraph::shs_fl; break; case IGRAPH_BLISS_FS: gsh = Digraph::shs_fs; break; case IGRAPH_BLISS_FM: gsh = Digraph::shs_fm; break; case IGRAPH_BLISS_FLM: gsh = Digraph::shs_flm; break; case IGRAPH_BLISS_FSM: gsh = Digraph::shs_fsm; break; default: IGRAPH_ERROR("Invalid splitting heuristic", IGRAPH_EINVAL); } static_cast(g)->set_splitting_heuristic(gsh); } else { Graph::SplittingHeuristic gsh = Graph::shs_fsm; switch (sh) { case IGRAPH_BLISS_F: gsh = Graph::shs_f; break; case IGRAPH_BLISS_FL: gsh = Graph::shs_fl; break; case IGRAPH_BLISS_FS: gsh = Graph::shs_fs; break; case IGRAPH_BLISS_FM: gsh = Graph::shs_fm; break; case IGRAPH_BLISS_FLM: gsh = Graph::shs_flm; break; case IGRAPH_BLISS_FSM: gsh = Graph::shs_fsm; break; default: IGRAPH_ERROR("Invalid splitting heuristic", IGRAPH_EINVAL); } static_cast(g)->set_splitting_heuristic(gsh); } return IGRAPH_SUCCESS; } inline int bliss_set_colors(AbstractGraph *g, const igraph_vector_int_t *colors) { if (colors == NULL) return IGRAPH_SUCCESS; const int n = g->get_nof_vertices(); if (n != igraph_vector_int_size(colors)) IGRAPH_ERROR("Invalid vertex color vector length", IGRAPH_EINVAL); for (int i=0; i < n; ++i) g->change_color(i, VECTOR(*colors)[i]); return IGRAPH_SUCCESS; } inline void bliss_info_to_igraph(igraph_bliss_info_t *info, const Stats &stats) { if (info) { info->max_level = stats.get_max_level(); info->nof_nodes = stats.get_nof_nodes(); info->nof_leaf_nodes = stats.get_nof_leaf_nodes(); info->nof_bad_nodes = stats.get_nof_bad_nodes(); info->nof_canupdates = stats.get_nof_canupdates(); info->nof_generators = stats.get_nof_generators(); stats.group_size.tostring(&info->group_size); } } // this is the callback function used with AbstractGraph::find_automorphisms() // it collects the group generators into a pointer vector void collect_generators(void *generators, unsigned int n, const unsigned int *aut) { igraph_vector_ptr_t *gen = static_cast(generators); igraph_vector_t *newvector = igraph_Calloc(1, igraph_vector_t); igraph_vector_init(newvector, n); copy(aut, aut+n, newvector->stor_begin); // takes care of unsigned int -> double conversion igraph_vector_ptr_push_back(gen, newvector); } } // end unnamed namespace /** * \function igraph_canonical_permutation * Canonical permutation using BLISS * * This function computes the canonical permutation which transforms * the graph into a canonical form by using the BLISS algorithm. * * \param graph The input graph. Multiple edges between the same nodes * are not supported and will cause an incorrect result to be returned. * \param colors An optional vertex color vector for the graph. Supply a * null pointer is the graph is not colored. * \param labeling Pointer to a vector, the result is stored here. The * permutation takes vertex 0 to the first element of the vector, * vertex 1 to the second, etc. The vector will be resized as * needed. * \param sh The splitting heuristics to be used in BLISS. See \ref * igraph_bliss_sh_t. * \param info If not \c NULL then information on BLISS internals is * stored here. See \ref igraph_bliss_info_t. * \return Error code. * * Time complexity: exponential, in practice it is fast for many graphs. */ int igraph_canonical_permutation(const igraph_t *graph, const igraph_vector_int_t *colors, igraph_vector_t *labeling, igraph_bliss_sh_t sh, igraph_bliss_info_t *info) { AbstractGraph *g = bliss_from_igraph(graph); IGRAPH_FINALLY(bliss_free_graph, g); const unsigned int N=g->get_nof_vertices(); IGRAPH_CHECK(bliss_set_sh(g, sh, igraph_is_directed(graph))); IGRAPH_CHECK(bliss_set_colors(g, colors)); Stats stats; const unsigned int *cl = g->canonical_form(stats, NULL, NULL); IGRAPH_CHECK(igraph_vector_resize(labeling, N)); for (unsigned int i=0; ilong double is used * and it is only approximate. See also \ref igraph_bliss_info_t. * * \param graph The input graph. Multiple edges between the same nodes * are not supported and will cause an incorrect result to be returned. * \param colors An optional vertex color vector for the graph. Supply a * null pointer is the graph is not colored. * \param sh The splitting heuristics to be used in BLISS. See \ref * igraph_bliss_sh_t. * \param info The result is stored here, in particular in the \c * group_size tag of \p info. * \return Error code. * * Time complexity: exponential, in practice it is fast for many graphs. */ int igraph_automorphisms(const igraph_t *graph, const igraph_vector_int_t *colors, igraph_bliss_sh_t sh, igraph_bliss_info_t *info) { AbstractGraph *g = bliss_from_igraph(graph); IGRAPH_FINALLY(bliss_free_graph, g); IGRAPH_CHECK(bliss_set_sh(g, sh, igraph_is_directed(graph))); IGRAPH_CHECK(bliss_set_colors(g, colors)); Stats stats; g->find_automorphisms(stats, NULL, NULL); bliss_info_to_igraph(info, stats); delete g; IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \function igraph_automorphism_group * Automorphism group generators using BLISS * * The generators of the automorphism group of a graph are computed * using BLISS. The generator set may not be minimal and may depend on * the splitting heuristics. * * \param graph The input graph. Multiple edges between the same nodes * are not supported and will cause an incorrect result to be returned. * \param colors An optional vertex color vector for the graph. Supply a * null pointer is the graph is not colored. * \param generators Must be an initialized pointer vector. It will * contain pointers to \ref igraph_vector_t objects * representing generators of the automorphism group. * \param sh The splitting heuristics to be used in BLISS. See \ref * igraph_bliss_sh_t. * \param info If not \c NULL then information on BLISS internals is * stored here. See \ref igraph_bliss_info_t. * \return Error code. * * Time complexity: exponential, in practice it is fast for many graphs. */ int igraph_automorphism_group( const igraph_t *graph, const igraph_vector_int_t *colors, igraph_vector_ptr_t *generators, igraph_bliss_sh_t sh, igraph_bliss_info_t *info) { AbstractGraph *g = bliss_from_igraph(graph); IGRAPH_FINALLY(bliss_free_graph, g); IGRAPH_CHECK(bliss_set_sh(g, sh, igraph_is_directed(graph))); IGRAPH_CHECK(bliss_set_colors(g, colors)); Stats stats; igraph_vector_ptr_resize(generators, 0); g->find_automorphisms(stats, collect_generators, generators); bliss_info_to_igraph(info, stats); delete g; IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } igraph/src/dnapps.f0000644000175100001440000005614113431000472013766 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdnapps c c\Description: c Given the Arnoldi factorization c c A*V_{k} - V_{k}*H_{k} = r_{k+p}*e_{k+p}^T, c c apply NP implicit shifts resulting in c c A*(V_{k}*Q) - (V_{k}*Q)*(Q^T* H_{k}*Q) = r_{k+p}*e_{k+p}^T * Q c c where Q is an orthogonal matrix which is the product of rotations c and reflections resulting from the NP bulge chage sweeps. c The updated Arnoldi factorization becomes: c c A*VNEW_{k} - VNEW_{k}*HNEW_{k} = rnew_{k}*e_{k}^T. c c\Usage: c call igraphdnapps c ( N, KEV, NP, SHIFTR, SHIFTI, V, LDV, H, LDH, RESID, Q, LDQ, c WORKL, WORKD ) c c\Arguments c N Integer. (INPUT) c Problem size, i.e. size of matrix A. c c KEV Integer. (INPUT/OUTPUT) c KEV+NP is the size of the input matrix H. c KEV is the size of the updated matrix HNEW. KEV is only c updated on ouput when fewer than NP shifts are applied in c order to keep the conjugate pair together. c c NP Integer. (INPUT) c Number of implicit shifts to be applied. c c SHIFTR, Double precision array of length NP. (INPUT) c SHIFTI Real and imaginary part of the shifts to be applied. c Upon, entry to igraphdnapps, the shifts must be sorted so that the c conjugate pairs are in consecutive locations. c c V Double precision N by (KEV+NP) array. (INPUT/OUTPUT) c On INPUT, V contains the current KEV+NP Arnoldi vectors. c On OUTPUT, V contains the updated KEV Arnoldi vectors c in the first KEV columns of V. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (KEV+NP) by (KEV+NP) array. (INPUT/OUTPUT) c On INPUT, H contains the current KEV+NP by KEV+NP upper c Hessenber matrix of the Arnoldi factorization. c On OUTPUT, H contains the updated KEV by KEV upper Hessenberg c matrix in the KEV leading submatrix. c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c RESID Double precision array of length N. (INPUT/OUTPUT) c On INPUT, RESID contains the the residual vector r_{k+p}. c On OUTPUT, RESID is the update residual vector rnew_{k} c in the first KEV locations. c c Q Double precision KEV+NP by KEV+NP work array. (WORKSPACE) c Work array used to accumulate the rotations and reflections c during the bulge chase sweep. c c LDQ Integer. (INPUT) c Leading dimension of Q exactly as declared in the calling c program. c c WORKL Double precision work array of length (KEV+NP). (WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. c c WORKD Double precision work array of length 2*N. (WORKSPACE) c Distributed array used in the application of the accumulated c orthogonal matrix Q. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c c\Routines called: c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdmout ARPACK utility routine that prints matrices. c igraphdvout ARPACK utility routine that prints vectors. c dlabad LAPACK routine that computes machine constants. c dlacpy LAPACK matrix copy routine. c dlamch LAPACK routine that determines machine constants. c dlanhs LAPACK routine that computes various norms of a matrix. c dlapy2 LAPACK routine to compute sqrt(x**2+y**2) carefully. c dlarf LAPACK routine that applies Householder reflection to c a matrix. c dlarfg LAPACK Householder reflection construction routine. c dlartg LAPACK Givens rotation construction routine. c dlaset LAPACK matrix initialization routine. c dgemv Level 2 BLAS routine for matrix vector multiplication. c daxpy Level 1 BLAS that computes a vector triad. c dcopy Level 1 BLAS that copies one vector to another . c dscal Level 1 BLAS that scales a vector. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.1' c c\SCCS Information: @(#) c FILE: napps.F SID: 2.3 DATE OF SID: 4/20/96 RELEASE: 2 c c\Remarks c 1. In this version, each shift is applied to all the sublocks of c the Hessenberg matrix H and not just to the submatrix that it c comes from. Deflation as in LAPACK routine dlahqr (QR algorithm c for upper Hessenberg matrices ) is used. c The subdiagonals of H are enforced to be non-negative. c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdnapps & ( n, kev, np, shiftr, shifti, v, ldv, h, ldh, resid, q, ldq, & workl, workd ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c integer kev, ldh, ldq, ldv, n, np c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & h(ldh,kev+np), resid(n), shifti(np), shiftr(np), & v(ldv,kev+np), q(ldq,kev+np), workd(2*n), workl(kev+np) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %------------------------% c | Local Scalars & Arrays | c %------------------------% c integer i, iend, ir, istart, j, jj, kplusp, msglvl, nr logical cconj, first Double precision & c, f, g, h11, h12, h21, h22, h32, ovfl, r, s, sigmai, & sigmar, smlnum, ulp, unfl, u(3), t, tau, tst1 save first, ovfl, smlnum, ulp, unfl c c %----------------------% c | External Subroutines | c %----------------------% c external daxpy, dcopy, dscal, dlacpy, dlarfg, dlarf, & dlaset, dlabad, igraphsecond, dlartg c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlamch, dlanhs, dlapy2 external dlamch, dlanhs, dlapy2 c c %----------------------% c | Intrinsics Functions | c %----------------------% c intrinsic abs, max, min c c %----------------% c | Data statments | c %----------------% c data first / .true. / c c %-----------------------% c | Executable Statements | c %-----------------------% c if (first) then c c %-----------------------------------------------% c | Set machine-dependent constants for the | c | stopping criterion. If norm(H) <= sqrt(OVFL), | c | overflow should not occur. | c | REFERENCE: LAPACK subroutine dlahqr | c %-----------------------------------------------% c unfl = dlamch( 'safe minimum' ) ovfl = one / unfl call dlabad( unfl, ovfl ) ulp = dlamch( 'precision' ) smlnum = unfl*( n / ulp ) first = .false. end if c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = mnapps kplusp = kev + np c c %--------------------------------------------% c | Initialize Q to the identity to accumulate | c | the rotations and reflections | c %--------------------------------------------% c call dlaset ('All', kplusp, kplusp, zero, one, q, ldq) c c %----------------------------------------------% c | Quick return if there are no shifts to apply | c %----------------------------------------------% c if (np .eq. 0) go to 9000 c c %----------------------------------------------% c | Chase the bulge with the application of each | c | implicit shift. Each shift is applied to the | c | whole matrix including each block. | c %----------------------------------------------% c cconj = .false. do 110 jj = 1, np sigmar = shiftr(jj) sigmai = shifti(jj) c if (msglvl .gt. 2 ) then call igraphivout (logfil, 1, jj, ndigit, & '_napps: shift number.') call igraphdvout (logfil, 1, sigmar, ndigit, & '_napps: The real part of the shift ') call igraphdvout (logfil, 1, sigmai, ndigit, & '_napps: The imaginary part of the shift ') end if c c %-------------------------------------------------% c | The following set of conditionals is necessary | c | in order that complex conjugate pairs of shifts | c | are applied together or not at all. | c %-------------------------------------------------% c if ( cconj ) then c c %-----------------------------------------% c | cconj = .true. means the previous shift | c | had non-zero imaginary part. | c %-----------------------------------------% c cconj = .false. go to 110 else if ( jj .lt. np .and. abs( sigmai ) .gt. zero ) then c c %------------------------------------% c | Start of a complex conjugate pair. | c %------------------------------------% c cconj = .true. else if ( jj .eq. np .and. abs( sigmai ) .gt. zero ) then c c %----------------------------------------------% c | The last shift has a nonzero imaginary part. | c | Don't apply it; thus the order of the | c | compressed H is order KEV+1 since only np-1 | c | were applied. | c %----------------------------------------------% c kev = kev + 1 go to 110 end if istart = 1 20 continue c c %--------------------------------------------------% c | if sigmai = 0 then | c | Apply the jj-th shift ... | c | else | c | Apply the jj-th and (jj+1)-th together ... | c | (Note that jj < np at this point in the code) | c | end | c | to the current block of H. The next do loop | c | determines the current block ; | c %--------------------------------------------------% c do 30 i = istart, kplusp-1 c c %----------------------------------------% c | Check for splitting and deflation. Use | c | a standard test as in the QR algorithm | c | REFERENCE: LAPACK subroutine dlahqr | c %----------------------------------------% c tst1 = abs( h( i, i ) ) + abs( h( i+1, i+1 ) ) if( tst1.eq.zero ) & tst1 = dlanhs( '1', kplusp-jj+1, h, ldh, workl ) if( abs( h( i+1,i ) ).le.max( ulp*tst1, smlnum ) ) then if (msglvl .gt. 0) then call igraphivout (logfil, 1, i, ndigit, & '_napps: matrix splitting at row/column no.') call igraphivout (logfil, 1, jj, ndigit, & '_napps: matrix splitting with shift number.') call igraphdvout (logfil, 1, h(i+1,i), ndigit, & '_napps: off diagonal element.') end if iend = i h(i+1,i) = zero go to 40 end if 30 continue iend = kplusp 40 continue c if (msglvl .gt. 2) then call igraphivout (logfil, 1, istart, ndigit, & '_napps: Start of current block ') call igraphivout (logfil, 1, iend, ndigit, & '_napps: End of current block ') end if c c %------------------------------------------------% c | No reason to apply a shift to block of order 1 | c %------------------------------------------------% c if ( istart .eq. iend ) go to 100 c c %------------------------------------------------------% c | If istart + 1 = iend then no reason to apply a | c | complex conjugate pair of shifts on a 2 by 2 matrix. | c %------------------------------------------------------% c if ( istart + 1 .eq. iend .and. abs( sigmai ) .gt. zero ) & go to 100 c h11 = h(istart,istart) h21 = h(istart+1,istart) if ( abs( sigmai ) .le. zero ) then c c %---------------------------------------------% c | Real-valued shift ==> apply single shift QR | c %---------------------------------------------% c f = h11 - sigmar g = h21 c do 80 i = istart, iend-1 c c %-----------------------------------------------------% c | Contruct the plane rotation G to zero out the bulge | c %-----------------------------------------------------% c call dlartg (f, g, c, s, r) if (i .gt. istart) then c c %-------------------------------------------% c | The following ensures that h(1:iend-1,1), | c | the first iend-2 off diagonal of elements | c | H, remain non negative. | c %-------------------------------------------% c if (r .lt. zero) then r = -r c = -c s = -s end if h(i,i-1) = r h(i+1,i-1) = zero end if c c %---------------------------------------------% c | Apply rotation to the left of H; H <- G'*H | c %---------------------------------------------% c do 50 j = i, kplusp t = c*h(i,j) + s*h(i+1,j) h(i+1,j) = -s*h(i,j) + c*h(i+1,j) h(i,j) = t 50 continue c c %---------------------------------------------% c | Apply rotation to the right of H; H <- H*G | c %---------------------------------------------% c do 60 j = 1, min(i+2,iend) t = c*h(j,i) + s*h(j,i+1) h(j,i+1) = -s*h(j,i) + c*h(j,i+1) h(j,i) = t 60 continue c c %----------------------------------------------------% c | Accumulate the rotation in the matrix Q; Q <- Q*G | c %----------------------------------------------------% c do 70 j = 1, min( j+jj, kplusp ) t = c*q(j,i) + s*q(j,i+1) q(j,i+1) = - s*q(j,i) + c*q(j,i+1) q(j,i) = t 70 continue c c %---------------------------% c | Prepare for next rotation | c %---------------------------% c if (i .lt. iend-1) then f = h(i+1,i) g = h(i+2,i) end if 80 continue c c %-----------------------------------% c | Finished applying the real shift. | c %-----------------------------------% c else c c %----------------------------------------------------% c | Complex conjugate shifts ==> apply double shift QR | c %----------------------------------------------------% c h12 = h(istart,istart+1) h22 = h(istart+1,istart+1) h32 = h(istart+2,istart+1) c c %---------------------------------------------------------% c | Compute 1st column of (H - shift*I)*(H - conj(shift)*I) | c %---------------------------------------------------------% c s = 2.0*sigmar t = dlapy2 ( sigmar, sigmai ) u(1) = ( h11 * (h11 - s) + t * t ) / h21 + h12 u(2) = h11 + h22 - s u(3) = h32 c do 90 i = istart, iend-1 c nr = min ( 3, iend-i+1 ) c c %-----------------------------------------------------% c | Construct Householder reflector G to zero out u(1). | c | G is of the form I - tau*( 1 u )' * ( 1 u' ). | c %-----------------------------------------------------% c call dlarfg ( nr, u(1), u(2), 1, tau ) c if (i .gt. istart) then h(i,i-1) = u(1) h(i+1,i-1) = zero if (i .lt. iend-1) h(i+2,i-1) = zero end if u(1) = one c c %--------------------------------------% c | Apply the reflector to the left of H | c %--------------------------------------% c call dlarf ('Left', nr, kplusp-i+1, u, 1, tau, & h(i,i), ldh, workl) c c %---------------------------------------% c | Apply the reflector to the right of H | c %---------------------------------------% c ir = min ( i+3, iend ) call dlarf ('Right', ir, nr, u, 1, tau, & h(1,i), ldh, workl) c c %-----------------------------------------------------% c | Accumulate the reflector in the matrix Q; Q <- Q*G | c %-----------------------------------------------------% c call dlarf ('Right', kplusp, nr, u, 1, tau, & q(1,i), ldq, workl) c c %----------------------------% c | Prepare for next reflector | c %----------------------------% c if (i .lt. iend-1) then u(1) = h(i+1,i) u(2) = h(i+2,i) if (i .lt. iend-2) u(3) = h(i+3,i) end if c 90 continue c c %--------------------------------------------% c | Finished applying a complex pair of shifts | c | to the current block | c %--------------------------------------------% c end if c 100 continue c c %---------------------------------------------------------% c | Apply the same shift to the next block if there is any. | c %---------------------------------------------------------% c istart = iend + 1 if (iend .lt. kplusp) go to 20 c c %---------------------------------------------% c | Loop back to the top to get the next shift. | c %---------------------------------------------% c 110 continue c c %--------------------------------------------------% c | Perform a similarity transformation that makes | c | sure that H will have non negative sub diagonals | c %--------------------------------------------------% c do 120 j=1,kev if ( h(j+1,j) .lt. zero ) then call dscal( kplusp-j+1, -one, h(j+1,j), ldh ) call dscal( min(j+2, kplusp), -one, h(1,j+1), 1 ) call dscal( min(j+np+1,kplusp), -one, q(1,j+1), 1 ) end if 120 continue c do 130 i = 1, kev c c %--------------------------------------------% c | Final check for splitting and deflation. | c | Use a standard test as in the QR algorithm | c | REFERENCE: LAPACK subroutine dlahqr | c %--------------------------------------------% c tst1 = abs( h( i, i ) ) + abs( h( i+1, i+1 ) ) if( tst1.eq.zero ) & tst1 = dlanhs( '1', kev, h, ldh, workl ) if( h( i+1,i ) .le. max( ulp*tst1, smlnum ) ) & h(i+1,i) = zero 130 continue c c %-------------------------------------------------% c | Compute the (kev+1)-st column of (V*Q) and | c | temporarily store the result in WORKD(N+1:2*N). | c | This is needed in the residual update since we | c | cannot GUARANTEE that the corresponding entry | c | of H would be zero as in exact arithmetic. | c %-------------------------------------------------% c if (h(kev+1,kev) .gt. zero) & call dgemv ('N', n, kplusp, one, v, ldv, q(1,kev+1), 1, zero, & workd(n+1), 1) c c %----------------------------------------------------------% c | Compute column 1 to kev of (V*Q) in backward order | c | taking advantage of the upper Hessenberg structure of Q. | c %----------------------------------------------------------% c do 140 i = 1, kev call dgemv ('N', n, kplusp-i+1, one, v, ldv, & q(1,kev-i+1), 1, zero, workd, 1) call dcopy (n, workd, 1, v(1,kplusp-i+1), 1) 140 continue c c %-------------------------------------------------% c | Move v(:,kplusp-kev+1:kplusp) into v(:,1:kev). | c %-------------------------------------------------% c call dlacpy ('A', n, kev, v(1,kplusp-kev+1), ldv, v, ldv) c c %--------------------------------------------------------------% c | Copy the (kev+1)-st column of (V*Q) in the appropriate place | c %--------------------------------------------------------------% c if (h(kev+1,kev) .gt. zero) & call dcopy (n, workd(n+1), 1, v(1,kev+1), 1) c c %-------------------------------------% c | Update the residual vector: | c | r <- sigmak*r + betak*v(:,kev+1) | c | where | c | sigmak = (e_{kplusp}'*Q)*e_{kev} | c | betak = e_{kev+1}'*H*e_{kev} | c %-------------------------------------% c call dscal (n, q(kplusp,kev), resid, 1) if (h(kev+1,kev) .gt. zero) & call daxpy (n, h(kev+1,kev), v(1,kev+1), 1, resid, 1) c if (msglvl .gt. 1) then call igraphdvout (logfil, 1, q(kplusp,kev), ndigit, & '_napps: sigmak = (e_{kev+p}^T*Q)*e_{kev}') call igraphdvout (logfil, 1, h(kev+1,kev), ndigit, & '_napps: betak = e_{kev+1}^T*H*e_{kev}') call igraphivout (logfil, 1, kev, ndigit, & '_napps: Order of the final Hessenberg matrix ') if (msglvl .gt. 2) then call igraphdmout (logfil, kev, kev, h, ldh, ndigit, & '_napps: updated Hessenberg matrix H for next iteration') end if c end if c 9000 continue call igraphsecond (t1) tnapps = tnapps + (t1 - t0) c return c c %---------------% c | End of igraphdnapps | c %---------------% c end igraph/src/rinterface.c0000644000175100001440000166222113431000472014623 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library R interface. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph.h" #include "igraph_error.h" #include "config.h" #include #include #include #include "rinterface.h" #include "init.c" /* registration table */ #include int igraph_free(void *p); SEXP R_igraph_vector_to_SEXP(const igraph_vector_t *v); SEXP R_igraph_vector_int_to_SEXP(const igraph_vector_int_t *v); SEXP R_igraph_vector_int_to_SEXPp1(const igraph_vector_int_t *v); SEXP R_igraph_vector_bool_to_SEXP(const igraph_vector_bool_t *v); SEXP R_igraph_vector_long_to_SEXP(const igraph_vector_long_t *v); SEXP R_igraph_vector_complex_to_SEXP(const igraph_vector_complex_t* v); SEXP R_igraph_0orvector_to_SEXP(const igraph_vector_t *v); SEXP R_igraph_0orvector_bool_to_SEXP(const igraph_vector_bool_t *v); SEXP R_igraph_0orvector_long_to_SEXP(const igraph_vector_long_t *v); SEXP R_igraph_0orvector_complex_to_SEXP(const igraph_vector_complex_t *v); SEXP R_igraph_matrix_to_SEXP(const igraph_matrix_t *m); SEXP R_igraph_matrix_complex_to_SEXP(const igraph_matrix_complex_t *m); SEXP R_igraph_0ormatrix_complex_to_SEXP(const igraph_matrix_complex_t *m); SEXP R_igraph_strvector_to_SEXP(const igraph_strvector_t *m); SEXP R_igraph_to_SEXP(const igraph_t *graph); SEXP R_igraph_vectorlist_to_SEXP(const igraph_vector_ptr_t *ptr); SEXP R_igraph_vectorlist_int_to_SEXP(const igraph_vector_ptr_t *ptr); void R_igraph_vectorlist_int_destroy(igraph_vector_ptr_t *ptr); SEXP R_igraph_0orvectorlist_to_SEXP(const igraph_vector_ptr_t *ptr); void R_igraph_vectorlist_destroy(igraph_vector_ptr_t *ptr); SEXP R_igraph_matrixlist_to_SEXP(const igraph_vector_ptr_t *ptr); void R_igraph_matrixlist_destroy(igraph_vector_ptr_t *ptr); SEXP R_igraph_graphlist_to_SEXP(const igraph_vector_ptr_t *ptr); void R_igraph_graphlist_destroy(igraph_vector_ptr_t *ptr); SEXP R_igraph_hrg_to_SEXP(const igraph_hrg_t *hrg); SEXP R_igraph_plfit_result_to_SEXP(const igraph_plfit_result_t *plfit); SEXP R_igraph_sparsemat_to_SEXP(const igraph_sparsemat_t *sp); SEXP R_igraph_0orsparsemat_to_SEXP(const igraph_sparsemat_t *sp); SEXP R_igraph_maxflow_stats_to_SEXP(const igraph_maxflow_stats_t *st); SEXP R_igraph_sirlist_to_SEXP(const igraph_vector_ptr_t *sl); void R_igraph_sirlist_destroy(igraph_vector_ptr_t *sl); int R_igraph_SEXP_to_strvector(SEXP rval, igraph_strvector_t *sv); int R_igraph_SEXP_to_strvector_copy(SEXP rval, igraph_strvector_t *sv); int R_SEXP_to_vector(SEXP sv, igraph_vector_t *v); int R_SEXP_to_vector_copy(SEXP sv, igraph_vector_t *v); int R_SEXP_to_matrix(SEXP pakl, igraph_matrix_t *akl); int R_SEXP_to_matrix_complex(SEXP pakl, igraph_matrix_complex_t *akl); int R_SEXP_to_igraph_matrix_copy(SEXP pakl, igraph_matrix_t *akl); int R_SEXP_to_igraph(SEXP graph, igraph_t *res); int R_SEXP_to_igraph_copy(SEXP graph, igraph_t *res); int R_SEXP_to_igraph_vs(SEXP rit, igraph_t *graph, igraph_vs_t *it); int R_SEXP_to_igraph_es(SEXP rit, igraph_t *graph, igraph_es_t *it); int R_SEXP_to_igraph_adjlist(SEXP vectorlist, igraph_adjlist_t *ptr); int R_igraph_SEXP_to_0orvectorlist(SEXP vectorlist, igraph_vector_ptr_t *ptr); int R_igraph_SEXP_to_vectorlist(SEXP vectorlist, igraph_vector_ptr_t *ptr); int R_igraph_SEXP_to_vectorlist_int(SEXP vectorlist, igraph_vector_ptr_t *ptr); int R_igraph_SEXP_to_matrixlist(SEXP matrixlist, igraph_vector_ptr_t *ptr); int R_SEXP_to_vector_bool(SEXP sv, igraph_vector_bool_t *v); int R_SEXP_to_vector_bool_copy(SEXP sv, igraph_vector_bool_t *v); int R_SEXP_to_vector_int(SEXP sv, igraph_vector_int_t *v); int R_SEXP_to_vector_long_copy(SEXP sv, igraph_vector_long_t *v); int R_SEXP_to_hrg(SEXP shrg, igraph_hrg_t *hrg); int R_SEXP_to_hrg_copy(SEXP shrg, igraph_hrg_t *hrg); int R_SEXP_to_sparsemat(SEXP pakl, igraph_sparsemat_t *akl); int R_SEXP_to_pagerank_power_options(SEXP popt, igraph_pagerank_power_options_t *opt); SEXP R_igraph_i_lang7(SEXP s, SEXP t, SEXP u, SEXP v, SEXP w, SEXP x, SEXP y) { PROTECT(s); PROTECT(t); PROTECT(u); s = LCONS(s, LCONS(t, LCONS(u, list4(v, w, x, y)))); UNPROTECT(3); return s; } /* get the list element named str, or return NULL */ /* from the R Manual */ SEXP R_igraph_getListElement(SEXP list, const char *str) { SEXP elmt = R_NilValue, names = getAttrib(list, R_NamesSymbol); int i; for (i = 0; i < length(list); i++) if(strcmp(CHAR(STRING_ELT(names, i)), str) == 0) { elmt = VECTOR_ELT(list, i); break; } return elmt; } SEXP R_igraph_c2(SEXP x1, SEXP x2) { SEXP cc = PROTECT(install("c")); SEXP lc = PROTECT(lang3(cc, x1, x2)); SEXP ret = EVAL(lc); UNPROTECT(2); return ret; } /****************************************************** * Attributes * *****************************************************/ SEXP R_igraph_get_attr_mode(SEXP graph, SEXP pwhich) { int which=INTEGER(pwhich)[0]-1; SEXP obj=VECTOR_ELT(VECTOR_ELT(graph, 8), which); int i, len=GET_LENGTH(obj); SEXP result; PROTECT(result=NEW_CHARACTER(len)); for (i=0; iattr=result; /* Add graph attributes */ attrno= attr==NULL ? 0 : igraph_vector_ptr_size(attr); SET_VECTOR_ELT(result, 1, NEW_LIST(attrno)); gal=VECTOR_ELT(result, 1); PROTECT(names=NEW_CHARACTER(attrno)); px++; for (i=0; iname)); SET_VECTOR_ELT(gal, i, R_NilValue); switch (rec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: vec=(igraph_vector_t*) rec->value; if (igraph_vector_size(vec) > 0) { SET_VECTOR_ELT(gal, i, NEW_NUMERIC(1)); REAL(VECTOR_ELT(gal, i))[0]=VECTOR(*vec)[0]; } break; case IGRAPH_ATTRIBUTE_BOOLEAN: log=(igraph_vector_bool_t*) rec->value; if (igraph_vector_bool_size(log) > 0) { SET_VECTOR_ELT(gal, i, NEW_LOGICAL(1)); LOGICAL(VECTOR_ELT(gal, i))[0]=VECTOR(*log)[0]; } break; case IGRAPH_ATTRIBUTE_STRING: strvec=(igraph_strvector_t*) rec->value; if (igraph_strvector_size(strvec) > 0) { SET_VECTOR_ELT(gal, i, NEW_CHARACTER(1)); SET_STRING_ELT(VECTOR_ELT(gal,i), 0, mkChar(STR(*strvec, 0))); } break; case IGRAPH_ATTRIBUTE_R_OBJECT: UNPROTECT(px); IGRAPH_ERROR("R_objects not implemented yet", IGRAPH_UNIMPLEMENTED); break; case IGRAPH_ATTRIBUTE_DEFAULT: case IGRAPH_ATTRIBUTE_PY_OBJECT: default: UNPROTECT(px); IGRAPH_ERROR("Unknown attribute type, this should not happen", IGRAPH_EINTERNAL); break; } } SET_NAMES(gal, names); UNPROTECT(px); return 0; } void R_igraph_attribute_destroy(igraph_t *graph) { SEXP attr=graph->attr; REAL(VECTOR_ELT(attr, 0))[1] -= 1; /* refcount for igraph_t */ if (!R_igraph_attribute_protected && REAL(VECTOR_ELT(attr, 0))[1]==0 && REAL(VECTOR_ELT(attr, 0))[2]==1) { R_ReleaseObject(attr); } graph->attr=0; } /* If not copying all three attribute kinds are requested, then we don't refcount, but really copy the requested ones, because 1) we can only refcount all three at the same time, and 2) the not-copied attributes will be set up by subsequent calls to permute_vertices and/or permute/edges anyway. */ int R_igraph_attribute_copy(igraph_t *to, const igraph_t *from, igraph_bool_t ga, igraph_bool_t va, igraph_bool_t ea) { SEXP fromattr=from->attr; if (ga && va && ea) { to->attr=from->attr; REAL(VECTOR_ELT(fromattr, 0))[1] += 1; /* refcount only */ if (!R_igraph_attribute_protected && REAL(VECTOR_ELT(fromattr, 0))[1] == 1) { R_PreserveObject(to->attr); } } else { R_igraph_attribute_init(to,0); /* Sets up many things */ SEXP toattr=to->attr; if (ga) { SET_VECTOR_ELT(toattr, 1, duplicate(VECTOR_ELT(fromattr, 1))); } if (va) { SET_VECTOR_ELT(toattr, 2, duplicate(VECTOR_ELT(fromattr, 2))); } if (ea) { SET_VECTOR_ELT(toattr, 3, duplicate(VECTOR_ELT(fromattr, 3))); } } return 0; } SEXP R_igraph_attribute_add_vertices_append1(igraph_vector_ptr_t *nattr, int j, int nv) { SEXP app = R_NilValue; igraph_attribute_record_t *tmprec=VECTOR(*nattr)[j-1]; long int len = 0; switch (tmprec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: len = igraph_vector_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_BOOLEAN: len = igraph_vector_bool_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_STRING: len = igraph_strvector_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_R_OBJECT: igraph_error("R objects not implemented yet", __FILE__, __LINE__, IGRAPH_UNIMPLEMENTED); return R_NilValue; break; default: igraph_error("Unknown attribute type, internal error", __FILE__, __LINE__, IGRAPH_EINVAL); return R_NilValue; break; } if (len != nv) { igraph_error("Invalid attribute length", __FILE__, __LINE__, IGRAPH_EINVAL); return R_NilValue; } switch (tmprec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: PROTECT(app=NEW_NUMERIC(nv)); igraph_vector_copy_to(tmprec->value, REAL(app)); break; case IGRAPH_ATTRIBUTE_BOOLEAN: PROTECT(app=R_igraph_vector_bool_to_SEXP(tmprec->value)); break; default: /* IGRAPH_ATTRIBUTE_STRING */ PROTECT(app=R_igraph_strvector_to_SEXP(tmprec->value)); break; } UNPROTECT(1); return app; } void R_igraph_attribute_add_vertices_append(SEXP val, long int nv, igraph_vector_ptr_t *nattr) { SEXP names; long int valno, i, nattrno; SEXP rep = R_NilValue; int px = 0; valno=GET_LENGTH(val); names=PROTECT(GET_NAMES(val)); px++; if (nattr==NULL) { nattrno=0; } else { nattrno=igraph_vector_ptr_size(nattr); } for (i=0; iname); } if (l) { /* This attribute is present in nattr */ SEXP app = PROTECT(R_igraph_attribute_add_vertices_append1(nattr, j, nv)); SEXP newva = PROTECT(R_igraph_c2(oldva, app)); SET_VECTOR_ELT(val, i, newva); UNPROTECT(2); } else { /* No such attribute, append NA's */ if (isNull(rep)) { SEXP l1 = PROTECT(install("rep")); px++; SEXP l2 = PROTECT(ScalarLogical(NA_LOGICAL)); px++; SEXP l3 = PROTECT(ScalarInteger((int) nv)); px++; SEXP l4 = PROTECT(lang3(l1, l2, l3)); px++; PROTECT(rep=EVAL(l4)); px++; } PROTECT(newva=R_igraph_c2(oldva, rep)); SET_VECTOR_ELT(val, i, newva); UNPROTECT(1); } } UNPROTECT(px); } SEXP R_igraph_attribute_add_vertices_dup(SEXP attr) { SEXP newattr=duplicate(attr); int px = 0; if (R_igraph_attribute_protected) { PROTECT(newattr); px++; } else { R_PreserveObject(newattr); } REAL(VECTOR_ELT(attr, 0))[1] -= 1; if (!R_igraph_attribute_protected && REAL(VECTOR_ELT(attr, 0))[1] == 0) { R_ReleaseObject(attr); } REAL(VECTOR_ELT(newattr, 0))[0] = 0; REAL(VECTOR_ELT(newattr, 0))[1] = 1; if (R_igraph_attribute_protected) { long int pos, alen=LENGTH(VECTOR_ELT(attr, 0)); if (alen == 4) { pos=REAL(VECTOR_ELT(attr, 0))[3]; SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } else { SEXP tmp=PROTECT(NEW_NUMERIC(4)); px++; REAL(tmp)[0] = REAL(VECTOR_ELT(attr, 0))[0]; REAL(tmp)[1] = REAL(VECTOR_ELT(attr, 0))[1]; REAL(tmp)[2] = REAL(VECTOR_ELT(attr, 0))[2]; pos = REAL(tmp)[3] = R_igraph_attribute_protected_size; R_igraph_attribute_protected_size += 1; SET_VECTOR_ELT(newattr, 0, tmp); } SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } UNPROTECT(px); return newattr; } int R_igraph_attribute_add_vertices(igraph_t *graph, long int nv, igraph_vector_ptr_t *nattr) { SEXP attr=graph->attr; SEXP val, rep=0, names, newnames; igraph_vector_t news; long int valno, i, origlen, nattrno, newattrs; int px = 0; if (REAL(VECTOR_ELT(attr, 0))[0]+REAL(VECTOR_ELT(attr, 0))[1] > 1) { SEXP newattr = PROTECT(R_igraph_attribute_add_vertices_dup(attr)); px++; attr=graph->attr=newattr; } val=VECTOR_ELT(attr, 2); valno=GET_LENGTH(val); names=PROTECT(GET_NAMES(val)); px++; if (nattr==NULL) { nattrno=0; } else { nattrno=igraph_vector_ptr_size(nattr); } origlen=igraph_vcount(graph)-nv; /* First add the new attributes, if any */ newattrs=0; if (igraph_vector_init(&news, 0)) error("Out of memory"); IGRAPH_FINALLY(igraph_vector_destroy, &news); for (i=0; iname; long int j; igraph_bool_t l=0; for (j=0; !l && jname)); } PROTECT(newval=R_igraph_c2(val, app)); PROTECT(newnames=R_igraph_c2(names, newnames)); SET_NAMES(newval, newnames); SET_VECTOR_ELT(attr, 2, newval); val=VECTOR_ELT(attr, 2); UNPROTECT(9); } igraph_vector_destroy(&news); IGRAPH_FINALLY_CLEAN(1); /* news */ /* Now append the new values */ R_igraph_attribute_add_vertices_append(val, nv, nattr); UNPROTECT(px); return 0; } /* void R_igraph_attribute_delete_vertices(igraph_t *graph, */ /* const igraph_vector_t *eidx, */ /* const igraph_vector_t *vidx) { */ /* SEXP attr=graph->attr; */ /* SEXP eal, val; */ /* long int valno, ealno, i; */ /* if (REAL(VECTOR_ELT(attr, 0))[0]+REAL(VECTOR_ELT(attr, 0))[1] > 1) { */ /* SEXP newattr; */ /* PROTECT(newattr=duplicate(attr)); */ /* REAL(VECTOR_ELT(attr, 0))[1] -= 1; */ /* if (REAL(VECTOR_ELT(attr, 0))[1] == 0) { */ /* R_ReleaseObject(attr); */ /* } */ /* REAL(VECTOR_ELT(newattr, 0))[0] = 0; */ /* REAL(VECTOR_ELT(newattr, 0))[1] = 1; */ /* attr=graph->attr=newattr; */ /* } */ /* /\* Vertices *\/ */ /* val=VECTOR_ELT(attr, 2); */ /* valno=GET_LENGTH(val); */ /* for (i=0; i 0) { */ /* newlen++; */ /* } */ /* } */ /* PROTECT(ss=NEW_NUMERIC(newlen)); */ /* for (j=0; j0) { */ /* REAL(ss)[(long int)VECTOR(*vidx)[j]-1]=j+1; */ /* } */ /* } */ /* PROTECT(newva=EVAL(lang3(install("["), oldva, ss))); */ /* SET_VECTOR_ELT(val, i, newva); */ /* UNPROTECT(2); */ /* } */ /* /\* Edges *\/ */ /* eal=VECTOR_ELT(attr, 3); */ /* ealno=GET_LENGTH(eal); */ /* for (i=0; i 0) { */ /* newlen++; */ /* } */ /* } */ /* PROTECT(ss=NEW_NUMERIC(newlen)); */ /* for (j=0; j0) { */ /* REAL(ss)[(long int)VECTOR(*eidx)[j]-1]=j+1; */ /* } */ /* } */ /* PROTECT(newea=EVAL(lang3(install("["), oldea, ss))); */ /* SET_VECTOR_ELT(eal, i, newea); */ /* UNPROTECT(2); */ /* } */ /* } */ int R_igraph_attribute_permute_vertices_same(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { SEXP attr=newgraph->attr; SEXP val; long int i, valno; long int idxlen=igraph_vector_size(idx); SEXP ss; int px = 0; /* We copy if we need to */ if (REAL(VECTOR_ELT(attr, 0))[0]+REAL(VECTOR_ELT(attr, 0))[1] > 1) { SEXP newattr = duplicate(attr); if (R_igraph_attribute_protected) { PROTECT(newattr); px++; } else { R_PreserveObject(newattr); } REAL(VECTOR_ELT(attr, 0))[1] -= 1; if (!R_igraph_attribute_protected && REAL(VECTOR_ELT(attr, 0))[1] == 0) { R_ReleaseObject(attr); } REAL(VECTOR_ELT(newattr, 0))[0] = 0; REAL(VECTOR_ELT(newattr, 0))[1] = 1; if (R_igraph_attribute_protected) { long int pos, alen=LENGTH(VECTOR_ELT(attr, 0)); if (alen == 4) { pos=REAL(VECTOR_ELT(attr, 0))[3]; SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } else { SEXP tmp=PROTECT(NEW_NUMERIC(4)); px++; REAL(tmp)[0] = REAL(VECTOR_ELT(attr, 0))[0]; REAL(tmp)[1] = REAL(VECTOR_ELT(attr, 0))[1]; REAL(tmp)[2] = REAL(VECTOR_ELT(attr, 0))[2]; pos = REAL(tmp)[3] = R_igraph_attribute_protected_size; R_igraph_attribute_protected_size += 1; SET_VECTOR_ELT(newattr, 0, tmp); } SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } attr=newgraph->attr=newattr; } val=VECTOR_ELT(attr,2); valno=GET_LENGTH(val); /* If we have no vertex attributes, then we don't need to do anything */ if (valno==0) { UNPROTECT(px); return 0; } /* Convert idx to an R object, we will use this for indexing */ PROTECT(ss=NEW_INTEGER(idxlen)); px++; for (i=0; iattr; SEXP toattr=newgraph->attr; SEXP val, toval; SEXP names; long int i, valno; long int idxlen=igraph_vector_size(idx); SEXP ss; int px = 0; val=VECTOR_ELT(attr,2); valno=GET_LENGTH(val); /* If we have no vertex attributes, then we don't need to do anything */ if (valno==0) { return 0; } /* Convert idx to an R object, we will use this for indexing */ PROTECT(ss=NEW_INTEGER(idxlen)); px++; for (i=0; itype) { case IGRAPH_ATTRIBUTE_NUMERIC: len = igraph_vector_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_BOOLEAN: len = igraph_vector_bool_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_STRING: len = igraph_strvector_size(tmprec->value); break; case IGRAPH_ATTRIBUTE_R_OBJECT: igraph_error("R objects not implemented yet", __FILE__, __LINE__, IGRAPH_UNIMPLEMENTED); return R_NilValue; break; default: igraph_error("Unknown attribute type, internal error", __FILE__, __LINE__, IGRAPH_EINVAL); return R_NilValue; break; } if (len != ne) { igraph_error("Invalid attribute length", __FILE__, __LINE__, IGRAPH_EINVAL); return R_NilValue; } switch (tmprec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: PROTECT(app=NEW_NUMERIC(ne)); igraph_vector_copy_to(tmprec->value, REAL(app)); break; case IGRAPH_ATTRIBUTE_BOOLEAN: PROTECT(app=R_igraph_vector_bool_to_SEXP(tmprec->value)); break; default: /* IGRAPH_ATTRIBUTE_STRING */ PROTECT(app=R_igraph_strvector_to_SEXP(tmprec->value)); break; } UNPROTECT(1); return app; } void R_igraph_attribute_add_edges_append(SEXP eal, const igraph_vector_t *edges, igraph_vector_ptr_t *nattr) { SEXP names; long int ealno, i; long int ne=igraph_vector_size(edges)/2, nattrno; SEXP rep = R_NilValue; int px = 0; ealno=GET_LENGTH(eal); names=PROTECT(GET_NAMES(eal)); px++; if (nattr==NULL) { nattrno=0; } else { nattrno=igraph_vector_ptr_size(nattr); } for (i=0; iname); } if (l) { /* This attribute is present in nattr */ SEXP app = PROTECT(R_igraph_attribute_add_edges_append1(nattr, j, ne)); SEXP newea = PROTECT(R_igraph_c2(oldea, app)); SET_VECTOR_ELT(eal, i, newea); UNPROTECT(2); } else { /* No such attribute, append NA's */ if (isNull(rep)) { SEXP l1 = PROTECT(install("rep")); px++; SEXP l2 = PROTECT(ScalarLogical(NA_LOGICAL)); px++; SEXP l3 = PROTECT(ScalarInteger((int) ne)); px++; SEXP l4 = PROTECT(lang3(l1, l2, l3)); px++; PROTECT(rep = EVAL(l4)); px++; } SEXP newea = PROTECT(R_igraph_c2(oldea, rep)); SET_VECTOR_ELT(eal, i, newea); UNPROTECT(1); } } UNPROTECT(px); } int R_igraph_attribute_add_edges(igraph_t *graph, const igraph_vector_t *edges, igraph_vector_ptr_t *nattr) { SEXP attr=graph->attr; SEXP eal, names, newnames; igraph_vector_t news; long int ealno, i, origlen, nattrno, newattrs; long int ne=igraph_vector_size(edges)/2; int px = 0; if (igraph_vector_init(&news, 0)) error("Out of memory"); IGRAPH_FINALLY(igraph_vector_destroy, &news); if (REAL(VECTOR_ELT(attr, 0))[0] + REAL(VECTOR_ELT(attr, 0))[1] > 1) { SEXP newattr = PROTECT(R_igraph_attribute_add_edges_dup(attr)); px++; attr=graph->attr=newattr; } eal=VECTOR_ELT(attr, 3); ealno=GET_LENGTH(eal); names=PROTECT(GET_NAMES(eal)); px++; if (nattr==NULL) { nattrno=0; } else { nattrno=igraph_vector_ptr_size(nattr); } origlen=igraph_ecount(graph)-ne; /* First add the new attributes, if any */ newattrs=0; for (i=0; iname; long int j; igraph_bool_t l=0; for (j=0; !l && jname)); } PROTECT(neweal=R_igraph_c2(eal, app)); PROTECT(newnames=R_igraph_c2(names, newnames)); SET_NAMES(neweal, newnames); SET_VECTOR_ELT(attr, 3, neweal); eal=VECTOR_ELT(attr, 3); UNPROTECT(9); } igraph_vector_destroy(&news); IGRAPH_FINALLY_CLEAN(1); /* Now append the new values */ R_igraph_attribute_add_edges_append(eal, edges, nattr); UNPROTECT(px); return 0; } /* void R_igraph_attribute_delete_edges(igraph_t *graph, */ /* const igraph_vector_t *idx) { */ /* SEXP attr=graph->attr; */ /* SEXP eal; */ /* long int ealno, i; */ /* if (REAL(VECTOR_ELT(attr, 0))[0]+REAL(VECTOR_ELT(attr, 0))[1] > 1) { */ /* SEXP newattr; */ /* PROTECT(newattr=duplicate(attr)); */ /* REAL(VECTOR_ELT(attr, 0))[1] -= 1; */ /* if (REAL(VECTOR_ELT(attr, 0))[1] == 0) { */ /* R_ReleaseObject(attr); */ /* } */ /* REAL(VECTOR_ELT(newattr, 0))[0] = 0; */ /* REAL(VECTOR_ELT(newattr, 0))[1] = 1; */ /* attr=graph->attr=newattr; */ /* } */ /* eal=VECTOR_ELT(attr, 3); */ /* ealno=GET_LENGTH(eal); */ /* for (i=0; i 0) { */ /* newlen++; */ /* } */ /* } */ /* PROTECT(ss=NEW_NUMERIC(newlen)); */ /* for (j=0; j 0) { */ /* REAL(ss)[(long int)VECTOR(*idx)[j]-1] = j+1; */ /* } */ /* } */ /* PROTECT(newea=EVAL(lang3(install("["), oldea, ss))); */ /* SET_VECTOR_ELT(eal, i, newea); */ /* UNPROTECT(2); */ /* } */ /* } */ int R_igraph_attribute_permute_edges_same(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { SEXP attr=newgraph->attr; SEXP eal; long int i, ealno; long int idxlen=igraph_vector_size(idx); SEXP ss; int px = 0; /* We copy if we need to */ if (REAL(VECTOR_ELT(attr, 0))[0]+REAL(VECTOR_ELT(attr, 0))[1] > 1) { SEXP newattr=duplicate(attr); if (R_igraph_attribute_protected) { PROTECT(newattr); px++; } else { R_PreserveObject(newattr); } REAL(VECTOR_ELT(attr, 0))[1] -= 1; if (!R_igraph_attribute_protected && REAL(VECTOR_ELT(attr, 0))[1] == 0) { R_ReleaseObject(attr); } REAL(VECTOR_ELT(newattr, 0))[0] = 0; REAL(VECTOR_ELT(newattr, 0))[1] = 1; if (R_igraph_attribute_protected) { long int pos, alen=LENGTH(VECTOR_ELT(attr, 0)); if (alen == 4) { pos=REAL(VECTOR_ELT(attr, 0))[3]; SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } else { SEXP tmp=PROTECT(NEW_NUMERIC(4)); px++; REAL(tmp)[0] = REAL(VECTOR_ELT(attr, 0))[0]; REAL(tmp)[1] = REAL(VECTOR_ELT(attr, 0))[1]; REAL(tmp)[2] = REAL(VECTOR_ELT(attr, 0))[2]; pos = REAL(tmp)[3] = R_igraph_attribute_protected_size; R_igraph_attribute_protected_size += 1; SET_VECTOR_ELT(newattr, 0, tmp); } SET_VECTOR_ELT(R_igraph_attribute_protected, pos, newattr); } attr=newgraph->attr=newattr; } eal=VECTOR_ELT(attr,3); ealno=GET_LENGTH(eal); /* If we have no edge attributes, then we don't need to do anything */ if (ealno==0) { UNPROTECT(px); return 0; } /* Convert idx to an R object, we will use this for indexing */ PROTECT(ss=NEW_INTEGER(idxlen)); px++; for (i=0; iattr; SEXP toattr=newgraph->attr; SEXP eal, toeal; SEXP names; long int i, ealno; long int idxlen=igraph_vector_size(idx); SEXP ss; eal=VECTOR_ELT(attr,3); ealno=GET_LENGTH(eal); /* If we have no vertex attributes, then we don't need to do anything */ if (ealno==0) { return 0; } /* Convert idx to an R object, we will use this for indexing */ PROTECT(ss=NEW_INTEGER(idxlen)); for (i=0; iattr; for (i=0; i<3; i++) { igraph_strvector_t *n=names[i]; igraph_vector_t *t=types[i]; SEXP al=VECTOR_ELT(attr, i+1); if (n) { /* return names */ SEXP names = PROTECT(GET_NAMES(al)); R_igraph_SEXP_to_strvector_copy(names, n); UNPROTECT(1); } if (t) { /* return types */ igraph_vector_resize(t, GET_LENGTH(al)); for (j=0; jattr, attrnum), name); return res != R_NilValue; } int R_igraph_attribute_gettype(const igraph_t *graph, igraph_attribute_type_t *type, igraph_attribute_elemtype_t elemtype, const char *name) { long int attrnum; SEXP res; switch (elemtype) { case IGRAPH_ATTRIBUTE_GRAPH: attrnum=1; break; case IGRAPH_ATTRIBUTE_VERTEX: attrnum=2; break; case IGRAPH_ATTRIBUTE_EDGE: attrnum=3; break; default: IGRAPH_ERROR("Unkwown attribute element type", IGRAPH_EINVAL); break; } res=R_igraph_getListElement(VECTOR_ELT(graph->attr, attrnum), name); if (IS_NUMERIC(res) || IS_INTEGER(res)) { *type=IGRAPH_ATTRIBUTE_NUMERIC; } else if (IS_LOGICAL(res)) { *type=IGRAPH_ATTRIBUTE_BOOLEAN; } else if (IS_CHARACTER(res)) { *type=IGRAPH_ATTRIBUTE_STRING; } else { *type=IGRAPH_ATTRIBUTE_R_OBJECT; } return 0; } int R_igraph_attribute_get_numeric_graph_attr(const igraph_t *graph, const char *name, igraph_vector_t *value) { SEXP gal=VECTOR_ELT(graph->attr, 1); SEXP ga=R_igraph_getListElement(gal, name); if (ga == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_NUMERIC(ga) && !IS_INTEGER(ga)) { IGRAPH_ERROR("Attribute not numeric", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_resize(value, 1)); if (IS_NUMERIC(ga)) { VECTOR(*value)[0]=REAL(ga)[0]; } else { /* INTEGER */ VECTOR(*value)[0]=INTEGER(ga)[0]; } return 0; } int R_igraph_attribute_get_bool_graph_attr(const igraph_t *graph, const char *name, igraph_vector_bool_t *value) { SEXP gal=VECTOR_ELT(graph->attr, 1); SEXP ga=R_igraph_getListElement(gal, name); if (ga == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_LOGICAL(ga)) { IGRAPH_ERROR("Attribute not logical", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_bool_resize(value, 1)); VECTOR(*value)[0]=LOGICAL(ga)[0]; return 0; } int R_igraph_attribute_get_string_graph_attr(const igraph_t *graph, const char *name, igraph_strvector_t *value) { /* TODO: serialization */ SEXP gal=VECTOR_ELT(graph->attr, 1); SEXP ga=R_igraph_getListElement(gal, name); if (ga == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_CHARACTER(ga)) { IGRAPH_ERROR("Attribute is not character", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_strvector_resize(value, 1)); IGRAPH_CHECK(igraph_strvector_set(value, 0, CHAR(STRING_ELT(ga, 0)))); return 0; } int R_igraph_attribute_get_numeric_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_t *value) { /* TODO: serialization */ SEXP val=VECTOR_ELT(graph->attr, 2); SEXP va=R_igraph_getListElement(val, name); igraph_vector_t newvalue; if (va == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_NUMERIC(va) && !IS_INTEGER(va)) { IGRAPH_ERROR("Attribute not numeric", IGRAPH_EINVAL); } if (igraph_vs_is_all(&vs)) { R_SEXP_to_vector_copy(AS_NUMERIC(va), &newvalue); igraph_vector_destroy(value); *value=newvalue; } else { igraph_vit_t it; long int i=0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_vector_resize(value, IGRAPH_VIT_SIZE(it))); if (IS_NUMERIC(va)) { while (!IGRAPH_VIT_END(it)) { long int v=IGRAPH_VIT_GET(it); VECTOR(*value)[i]=REAL(va)[v]; IGRAPH_VIT_NEXT(it); i++; } } else if (IS_INTEGER(va)) { while (!IGRAPH_VIT_END(it)) { long int v=IGRAPH_VIT_GET(it); VECTOR(*value)[i]=INTEGER(va)[v]; IGRAPH_VIT_NEXT(it); i++; } } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int R_igraph_attribute_get_bool_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_bool_t *value) { /* TODO: serialization */ SEXP val=VECTOR_ELT(graph->attr, 2); SEXP va=R_igraph_getListElement(val, name); igraph_vector_bool_t newvalue; if (va == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_LOGICAL(va)) { IGRAPH_ERROR("Attribute not logical", IGRAPH_EINVAL); } if (igraph_vs_is_all(&vs)) { R_SEXP_to_vector_bool_copy(va, &newvalue); igraph_vector_bool_destroy(value); *value=newvalue; } else { igraph_vit_t it; long int i=0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_vector_bool_resize(value, IGRAPH_VIT_SIZE(it))); while (!IGRAPH_VIT_END(it)) { long int v=IGRAPH_VIT_GET(it); VECTOR(*value)[i]=LOGICAL(va)[v]; IGRAPH_VIT_NEXT(it); i++; } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int R_igraph_attribute_get_string_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_strvector_t *value) { /* TODO: serialization */ SEXP val, va; val=VECTOR_ELT(graph->attr, 2); va=R_igraph_getListElement(val, name); if (va == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_CHARACTER(va)) { IGRAPH_ERROR("Attribute is not character", IGRAPH_EINVAL); } if (igraph_vs_is_all(&vs)) { R_igraph_SEXP_to_strvector_copy(va, value); } else { igraph_vit_t it; long int i=0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_strvector_resize(value, IGRAPH_VIT_SIZE(it))); while (!IGRAPH_VIT_END(it)) { long int v=IGRAPH_VIT_GET(it); const char *str=CHAR(STRING_ELT(va, v)); IGRAPH_CHECK(igraph_strvector_set(value, i, str)); IGRAPH_VIT_NEXT(it); i++; } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int R_igraph_attribute_get_numeric_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_t *value) { /* TODO: serialization */ SEXP eal=VECTOR_ELT(graph->attr, 3); SEXP ea=R_igraph_getListElement(eal, name); igraph_vector_t newvalue; if (ea == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_NUMERIC(ea) && !IS_INTEGER(ea)) { IGRAPH_ERROR("Attribute is not numeric", IGRAPH_EINVAL); } if (igraph_es_is_all(&es)) { R_SEXP_to_vector_copy(AS_NUMERIC(ea), &newvalue); igraph_vector_destroy(value); *value=newvalue; } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_vector_resize(value, IGRAPH_EIT_SIZE(it))); if (IS_NUMERIC(ea)) { while (!IGRAPH_EIT_END(it)) { long int e=IGRAPH_EIT_GET(it); VECTOR(*value)[i]=REAL(ea)[e]; IGRAPH_EIT_NEXT(it); i++; } } else { /* INTEGER */ while (!IGRAPH_EIT_END(it)) { long int e=IGRAPH_EIT_GET(it); VECTOR(*value)[i]=INTEGER(ea)[e]; IGRAPH_EIT_NEXT(it); i++; } } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int R_igraph_attribute_get_bool_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_bool_t *value) { /* TODO: serialization */ SEXP eal=VECTOR_ELT(graph->attr, 3); SEXP ea=R_igraph_getListElement(eal, name); igraph_vector_bool_t newvalue; if (ea == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_LOGICAL(ea)) { IGRAPH_ERROR("Attribute not logical", IGRAPH_EINVAL); } if (igraph_es_is_all(&es)) { R_SEXP_to_vector_bool_copy(ea, &newvalue); igraph_vector_bool_destroy(value); *value=newvalue; } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_vector_bool_resize(value, IGRAPH_EIT_SIZE(it))); while (!IGRAPH_EIT_END(it)) { long int e=IGRAPH_EIT_GET(it); VECTOR(*value)[i]=LOGICAL(ea)[e]; IGRAPH_EIT_NEXT(it); i++; } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int R_igraph_attribute_get_string_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_strvector_t *value) { /* TODO: serialization */ SEXP eal=VECTOR_ELT(graph->attr, 3); SEXP ea=R_igraph_getListElement(eal, name); if (ea == R_NilValue) { IGRAPH_ERROR("No such attribute", IGRAPH_EINVAL); } if (!IS_CHARACTER(ea)) { IGRAPH_ERROR("Attribute is not character", IGRAPH_EINVAL); } if (igraph_es_is_all(&es)) { R_igraph_SEXP_to_strvector_copy(ea, value); } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_strvector_resize(value, IGRAPH_EIT_SIZE(it))); while (!IGRAPH_EIT_END(it)) { long int e=IGRAPH_EIT_GET(it); const char *str=CHAR(STRING_ELT(ea, e)); IGRAPH_CHECK(igraph_strvector_set(value, i, str)); IGRAPH_EIT_NEXT(it); i++; } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } SEXP R_igraph_ac_sum_numeric(SEXP attr, const igraph_vector_ptr_t *merges) { SEXP res; SEXP attr2; long int i, len=igraph_vector_ptr_size(merges); PROTECT(attr2=AS_NUMERIC(attr)); PROTECT(res=NEW_NUMERIC(len)); for (i=0; i 0 ? REAL(attr2)[(long) VECTOR(*v)[0] ] : NA_REAL; for (j=1; j 0 ? REAL(attr2)[(long) VECTOR(*v)[0] ] : NA_REAL; for (j=1; j m) { m=val; } } REAL(res)[i] = m; } UNPROTECT(2); return res; } SEXP R_igraph_ac_random_numeric(SEXP attr, const igraph_vector_ptr_t *merges) { SEXP res; SEXP attr2; long int i, len=igraph_vector_ptr_size(merges); PROTECT(attr2=AS_NUMERIC(attr)); PROTECT(res=NEW_NUMERIC(len)); RNG_BEGIN(); for (i=0; i0 ? 0.0 : NA_REAL; for (j=0; j0) { s=s/n; } REAL(res)[i] = s; } UNPROTECT(2); return res; } SEXP R_igraph_ac_median_numeric(SEXP attr, const igraph_vector_ptr_t *merges) { SEXP res; SEXP attr2; long int i, len=igraph_vector_ptr_size(merges); PROTECT(attr2=AS_NUMERIC(attr)); PROTECT(res=NEW_NUMERIC(len)); for (i=0; iattr; SEXP toattr=newgraph->attr; SEXP val=VECTOR_ELT(attr, 2); long int i, j, valno=GET_LENGTH(val); SEXP names, newnames; SEXP res; int keepno=0; int *TODO; igraph_function_pointer_t *funcs; int px = 0; /* Create the TODO list first */ PROTECT(names=GET_NAMES(val)); px++; TODO=igraph_Calloc(valno, int); if (!TODO) { UNPROTECT(px); IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, TODO); funcs=igraph_Calloc(valno, igraph_function_pointer_t); if (!funcs) { UNPROTECT(px); IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, funcs); for (i=0; iattr; SEXP toattr=newgraph->attr; SEXP eal=VECTOR_ELT(attr, 3); long int i, j, ealno=GET_LENGTH(eal); SEXP names, newnames; SEXP res; int keepno=0; int *TODO; igraph_function_pointer_t *funcs; int px = 0; /* Create the TODO list first */ PROTECT(names=GET_NAMES(eal)); px++; TODO=igraph_Calloc(ealno, int); if (!TODO) { UNPROTECT(px); IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, TODO); funcs=igraph_Calloc(ealno, igraph_function_pointer_t); if (!funcs) { UNPROTECT(px); IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, funcs); for (i=0; idata, REAL(result)); PROTECT(dim=NEW_INTEGER(3)); INTEGER(dim)[0]=(int) igraph_array3_n(a, 1); INTEGER(dim)[1]=(int) igraph_array3_n(a, 2); INTEGER(dim)[2]=(int) igraph_array3_n(a, 3); SET_DIM(result, dim); UNPROTECT(2); return result; } SEXP R_igraph_0orarray3_to_SEXP(const igraph_array3_t *a) { SEXP result; if (a) { PROTECT(result=R_igraph_array3_to_SEXP(a)); } else { PROTECT(result=R_NilValue); } UNPROTECT(1); return result; } SEXP R_igraph_strvector_to_SEXP(const igraph_strvector_t *m) { SEXP result; long int i; char *str; long int len; len=igraph_strvector_size(m); PROTECT(result=NEW_CHARACTER(len)); for (i=0; idirected; memcpy(REAL(VECTOR_ELT(result, 2)), graph->from.stor_begin, sizeof(igraph_real_t)*(size_t) no_of_edges); memcpy(REAL(VECTOR_ELT(result, 3)), graph->to.stor_begin, sizeof(igraph_real_t)*(size_t) no_of_edges); memcpy(REAL(VECTOR_ELT(result, 4)), graph->oi.stor_begin, sizeof(igraph_real_t)*(size_t) no_of_edges); memcpy(REAL(VECTOR_ELT(result, 5)), graph->ii.stor_begin, sizeof(igraph_real_t)*(size_t) no_of_edges); memcpy(REAL(VECTOR_ELT(result, 6)), graph->os.stor_begin, sizeof(igraph_real_t)*(size_t) (no_of_nodes+1)); memcpy(REAL(VECTOR_ELT(result, 7)), graph->is.stor_begin, sizeof(igraph_real_t)*(size_t) (no_of_nodes+1)); SET_CLASS(result, ScalarString(CREATE_STRING_VECTOR("igraph"))); /* Attributes */ SET_VECTOR_ELT(result, 8, graph->attr); REAL(VECTOR_ELT(graph->attr, 0))[0] += 1; /* Environment for vertex/edge seqs */ SET_VECTOR_ELT(result, 9, R_NilValue); R_igraph_add_env(result); UNPROTECT(1); return result; } SEXP R_igraph_vectorlist_to_SEXP(const igraph_vector_ptr_t *ptr) { SEXP result; long int i, n=igraph_vector_ptr_size(ptr); PROTECT(result=NEW_LIST(n)); for (i=0; ileft)); SET_VECTOR_ELT(result, 1, R_igraph_vector_to_SEXP(&hrg->right)); SET_VECTOR_ELT(result, 2, R_igraph_vector_to_SEXP(&hrg->prob)); SET_VECTOR_ELT(result, 3, R_igraph_vector_to_SEXP(&hrg->edges)); SET_VECTOR_ELT(result, 4, R_igraph_vector_to_SEXP(&hrg->vertices)); PROTECT(names=NEW_CHARACTER(5)); SET_STRING_ELT(names, 0, mkChar("left")); SET_STRING_ELT(names, 1, mkChar("right")); SET_STRING_ELT(names, 2, mkChar("prob")); SET_STRING_ELT(names, 3, mkChar("edges")); SET_STRING_ELT(names, 4, mkChar("vertices")); SET_NAMES(result, names); UNPROTECT(2); return result; } int R_SEXP_to_hrg(SEXP shrg, igraph_hrg_t *hrg) { R_SEXP_to_vector(VECTOR_ELT(shrg, 0), &hrg->left); R_SEXP_to_vector(VECTOR_ELT(shrg, 1), &hrg->right); R_SEXP_to_vector(VECTOR_ELT(shrg, 2), &hrg->prob); R_SEXP_to_vector(VECTOR_ELT(shrg, 3), &hrg->edges); R_SEXP_to_vector(VECTOR_ELT(shrg, 4), &hrg->vertices); return 0; } int R_SEXP_to_hrg_copy(SEXP shrg, igraph_hrg_t *hrg) { R_SEXP_to_vector_copy(VECTOR_ELT(shrg, 0), &hrg->left); R_SEXP_to_vector_copy(VECTOR_ELT(shrg, 1), &hrg->right); R_SEXP_to_vector_copy(VECTOR_ELT(shrg, 2), &hrg->prob); R_SEXP_to_vector_copy(VECTOR_ELT(shrg, 3), &hrg->edges); R_SEXP_to_vector_copy(VECTOR_ELT(shrg, 4), &hrg->vertices); return 0; } SEXP R_igraph_plfit_result_to_SEXP(const igraph_plfit_result_t *plfit) { SEXP result, names; PROTECT(result=NEW_LIST(6)); SET_VECTOR_ELT(result, 0, ScalarLogical(plfit->continuous)); SET_VECTOR_ELT(result, 1, ScalarReal(plfit->alpha)); SET_VECTOR_ELT(result, 2, ScalarReal(plfit->xmin)); SET_VECTOR_ELT(result, 3, ScalarReal(plfit->L)); SET_VECTOR_ELT(result, 4, ScalarReal(plfit->D)); SET_VECTOR_ELT(result, 5, ScalarReal(plfit->p)); PROTECT(names=NEW_CHARACTER(6)); SET_STRING_ELT(names, 0, mkChar("continuous")); SET_STRING_ELT(names, 1, mkChar("alpha")); SET_STRING_ELT(names, 2, mkChar("xmin")); SET_STRING_ELT(names, 3, mkChar("logLik")); SET_STRING_ELT(names, 4, mkChar("KS.stat")); SET_STRING_ELT(names, 5, mkChar("KS.p")); SET_NAMES(result, names); UNPROTECT(2); return result; } SEXP R_igraph_maxflow_stats_to_SEXP(const igraph_maxflow_stats_t *st) { SEXP result, names; PROTECT(result=NEW_LIST(5)); SET_VECTOR_ELT(result, 0, ScalarInteger(st->nopush)); SET_VECTOR_ELT(result, 1, ScalarInteger(st->norelabel)); SET_VECTOR_ELT(result, 2, ScalarInteger(st->nogap)); SET_VECTOR_ELT(result, 3, ScalarInteger(st->nogapnodes)); SET_VECTOR_ELT(result, 4, ScalarInteger(st->nobfs)); PROTECT(names=NEW_CHARACTER(5)); SET_STRING_ELT(names, 0, mkChar("nopush")); SET_STRING_ELT(names, 1, mkChar("norelabel")); SET_STRING_ELT(names, 2, mkChar("nogap")); SET_STRING_ELT(names, 3, mkChar("nogapnodes")); SET_STRING_ELT(names, 4, mkChar("nobfs")); SET_NAMES(result, names); UNPROTECT(2); return result; } SEXP R_igraph_sirlist_to_SEXP(const igraph_vector_ptr_t *sl) { SEXP result, names; int i, n=igraph_vector_ptr_size(sl); PROTECT(result=NEW_LIST(n)); PROTECT(names=NEW_CHARACTER(4)); SET_STRING_ELT(names, 0, mkChar("times")); SET_STRING_ELT(names, 1, mkChar("NS")); SET_STRING_ELT(names, 2, mkChar("NI")); SET_STRING_ELT(names, 3, mkChar("NR")); for (i=0; itimes)); SET_VECTOR_ELT(tmp, 1, R_igraph_vector_int_to_SEXP(&sir->no_s)); SET_VECTOR_ELT(tmp, 2, R_igraph_vector_int_to_SEXP(&sir->no_i)); SET_VECTOR_ELT(tmp, 3, R_igraph_vector_int_to_SEXP(&sir->no_r)); SET_VECTOR_ELT(result, i, tmp); SET_NAMES(tmp, names); UNPROTECT(1); } UNPROTECT(2); return result; } void R_igraph_sirlist_destroy(igraph_vector_ptr_t *sl) { int i, n=igraph_vector_ptr_size(sl); for (i=0; itimes); igraph_vector_int_destroy(&sir->no_s); igraph_vector_int_destroy(&sir->no_i); igraph_vector_int_destroy(&sir->no_r); igraph_free(sir); } igraph_vector_ptr_destroy(sl); } int R_SEXP_to_sparsemat(SEXP pakl, igraph_sparsemat_t *akl) { SEXP Dim=GET_SLOT(pakl, install("Dim")); SEXP i=GET_SLOT(pakl, install("i")); SEXP p=GET_SLOT(pakl, install("p")); SEXP x=GET_SLOT(pakl, install("x")); igraph_i_sparsemat_view(akl, /*nzmax=*/ GET_LENGTH(x), /*m=*/ INTEGER(Dim)[0], /*n=*/ INTEGER(Dim)[1], /*p=*/ INTEGER(p), /*i=*/ INTEGER(i), /*x=*/ REAL(x), /*nz=*/ -1); return 0; } int R_SEXP_to_pagerank_power_options(SEXP popt, igraph_pagerank_power_options_t *opt) { opt->niter=INTEGER(AS_INTEGER(R_igraph_getListElement(popt, "niter")))[0]; opt->eps=REAL(R_igraph_getListElement(popt, "eps"))[0]; return 0; } SEXP R_igraph_sparsemat_to_SEXP_triplet(const igraph_sparsemat_t *sp) { SEXP res, names; int nz=igraph_sparsemat_nonzero_storage(sp); PROTECT(res=NEW_LIST(5)); SET_VECTOR_ELT(res, 0, ScalarString(CREATE_STRING_VECTOR("triplet"))); SET_VECTOR_ELT(res, 1, NEW_INTEGER(2)); INTEGER(VECTOR_ELT(res, 1))[0] = (int) igraph_sparsemat_nrow(sp); INTEGER(VECTOR_ELT(res, 1))[1] = (int) igraph_sparsemat_ncol(sp); SET_VECTOR_ELT(res, 2, NEW_INTEGER(nz)); SET_VECTOR_ELT(res, 3, NEW_INTEGER(nz)); SET_VECTOR_ELT(res, 4, NEW_NUMERIC(nz)); if (nz > 0) { igraph_vector_int_t i, j; igraph_vector_t x; igraph_vector_int_view(&i, INTEGER(VECTOR_ELT(res, 2)), nz); igraph_vector_int_view(&j, INTEGER(VECTOR_ELT(res, 3)), nz); igraph_vector_view(&x, REAL(VECTOR_ELT(res, 4)), nz); igraph_sparsemat_getelements(sp, &j, &i, &x); } PROTECT(names=NEW_CHARACTER(5)); SET_STRING_ELT(names, 0, mkChar("type")); SET_STRING_ELT(names, 1, mkChar("dim")); SET_STRING_ELT(names, 2, mkChar("p")); SET_STRING_ELT(names, 3, mkChar("i")); SET_STRING_ELT(names, 4, mkChar("x")); SET_NAMES(res, names); SET_CLASS(res, ScalarString(CREATE_STRING_VECTOR("igraph.tmp.sparse"))); UNPROTECT(2); return res; } SEXP R_igraph_sparsemat_to_SEXP_cc(const igraph_sparsemat_t *sp) { SEXP res, names; int nz=igraph_sparsemat_nonzero_storage(sp); int m=(int) igraph_sparsemat_nrow(sp); int n=(int) igraph_sparsemat_ncol(sp); PROTECT(res=NEW_LIST(5)); SET_VECTOR_ELT(res, 0, ScalarString(CREATE_STRING_VECTOR("cc"))); SET_VECTOR_ELT(res, 1, NEW_INTEGER(2)); INTEGER(VECTOR_ELT(res, 1))[0] = m; INTEGER(VECTOR_ELT(res, 1))[1] = n; SET_VECTOR_ELT(res, 2, NEW_INTEGER(n+1)); SET_VECTOR_ELT(res, 3, NEW_INTEGER(nz)); SET_VECTOR_ELT(res, 4, NEW_NUMERIC(nz)); if (nz > 0) { igraph_vector_int_t i, p; igraph_vector_t x; igraph_vector_int_view(&p, INTEGER(VECTOR_ELT(res, 2)), n+1); igraph_vector_int_view(&i, INTEGER(VECTOR_ELT(res, 3)), nz); igraph_vector_view(&x, REAL(VECTOR_ELT(res, 4)), nz); igraph_sparsemat_getelements_sorted(sp, &i, &p, &x); } PROTECT(names=NEW_CHARACTER(5)); SET_STRING_ELT(names, 0, mkChar("type")); SET_STRING_ELT(names, 1, mkChar("dim")); SET_STRING_ELT(names, 2, mkChar("p")); SET_STRING_ELT(names, 3, mkChar("i")); SET_STRING_ELT(names, 4, mkChar("x")); SET_NAMES(res, names); SET_CLASS(res, ScalarString(CREATE_STRING_VECTOR("igraph.tmp.sparse"))); UNPROTECT(2); return res; } SEXP R_igraph_sparsemat_to_SEXP(const igraph_sparsemat_t *sp) { if (igraph_sparsemat_is_triplet(sp)) { return R_igraph_sparsemat_to_SEXP_triplet(sp); } else { return R_igraph_sparsemat_to_SEXP_cc(sp); } } SEXP R_igraph_0orsparsemat_to_SEXP(const igraph_sparsemat_t *sp) { if (!sp) { return R_NilValue; } else { return R_igraph_sparsemat_to_SEXP(sp); } } int R_SEXP_to_igraph_adjlist(SEXP vectorlist, igraph_adjlist_t *ptr) { int length=GET_LENGTH(vectorlist); int i; ptr->length=length; ptr->adjs = (igraph_vector_int_t*) R_alloc((size_t) length, sizeof(igraph_vector_int_t)); for (i=0; iadjs[i], INTEGER(vec), GET_LENGTH(vec)); } return 0; } int R_igraph_SEXP_to_0orvectorlist(SEXP vectorlist, igraph_vector_ptr_t *ptr) { if (!isNull(vectorlist)) { return R_igraph_SEXP_to_vectorlist(vectorlist, ptr); } return 0; } int R_igraph_SEXP_to_vectorlist(SEXP vectorlist, igraph_vector_ptr_t *ptr) { int length=GET_LENGTH(vectorlist); int i; igraph_vector_t *vecs; igraph_vector_t **vecsptr; vecs = (igraph_vector_t *) R_alloc((size_t) length, sizeof(igraph_vector_t)); vecsptr = (igraph_vector_t **) R_alloc((size_t) length, sizeof(igraph_vector_t*)); igraph_vector_ptr_view(ptr, (void**) vecsptr, length); for (i=0; ilen=GET_LENGTH(rval); sv->data=(char**) R_alloc((size_t) (sv->len), sizeof(char*)); for (i=0; ilen; i++) { sv->data[i]=(char*) CHAR(STRING_ELT(rval, i)); } return 0; } int R_igraph_SEXP_to_strvector_copy(SEXP rval, igraph_strvector_t *sv) { long int i; igraph_strvector_init(sv, GET_LENGTH(rval)); for (i=0; ilen; i++) { igraph_strvector_set(sv, i, CHAR(STRING_ELT(rval, i))); } return 0; } int R_SEXP_to_vector(SEXP sv, igraph_vector_t *v) { v->stor_begin=REAL(sv); v->stor_end=v->stor_begin+GET_LENGTH(sv); v->end=v->stor_end; return 0; } int R_SEXP_to_vector_copy(SEXP sv, igraph_vector_t *v) { return igraph_vector_init_copy(v, REAL(sv), GET_LENGTH(sv)); } int R_SEXP_to_vector_bool(SEXP sv, igraph_vector_bool_t *v) { v->stor_begin=LOGICAL(sv); v->stor_end=v->stor_begin+GET_LENGTH(sv); v->end=v->stor_end; return 0; } int R_SEXP_to_vector_bool_copy(SEXP sv, igraph_vector_bool_t *v) { long int i, n=GET_LENGTH(sv); int *svv=LOGICAL(sv); igraph_vector_bool_init(v, n); for (i=0; istor_begin=(int*) INTEGER(sv); v->stor_end=v->stor_begin+GET_LENGTH(sv); v->end=v->stor_end; return 0; } int R_SEXP_to_vector_long_copy(SEXP sv, igraph_vector_long_t *v) { long int i, n=GET_LENGTH(sv); double *svv=REAL(sv); igraph_vector_long_init(v, n); for (i=0; idata); akl->nrow=INTEGER(GET_DIM(pakl))[0]; akl->ncol=INTEGER(GET_DIM(pakl))[1]; return 0; } int R_SEXP_to_igraph_matrix_copy(SEXP pakl, igraph_matrix_t *akl) { igraph_vector_init_copy(&akl->data, REAL(pakl), GET_LENGTH(pakl)); akl->nrow=INTEGER(GET_DIM(pakl))[0]; akl->ncol=INTEGER(GET_DIM(pakl))[1]; return 0; } int R_SEXP_to_vector_complex(SEXP pv, igraph_vector_complex_t *v) { v->stor_begin=(igraph_complex_t*) COMPLEX(pv); v->stor_end=v->stor_begin+GET_LENGTH(pv); v->end=v->stor_end; return 0; } int R_SEXP_to_vector_complex_copy(SEXP pv, igraph_vector_complex_t *v) { igraph_vector_complex_init_copy(v, (igraph_complex_t*) COMPLEX(pv), GET_LENGTH(pv)); return 0; } int R_SEXP_to_matrix_complex(SEXP pakl, igraph_matrix_complex_t *akl) { R_SEXP_to_vector_complex(pakl, &akl->data); akl->nrow=INTEGER(GET_DIM(pakl))[0]; akl->ncol=INTEGER(GET_DIM(pakl))[1]; return 0; } int R_SEXP_to_matrix_complex_copy(SEXP pakl, igraph_matrix_complex_t *akl) { igraph_vector_complex_init_copy(&akl->data, (igraph_complex_t*) COMPLEX(pakl), GET_LENGTH(pakl)); akl->nrow=INTEGER(GET_DIM(pakl))[0]; akl->ncol=INTEGER(GET_DIM(pakl))[1]; return 0; } int R_igraph_SEXP_to_array3(SEXP rval, igraph_array3_t *a) { R_SEXP_to_vector(rval, &a->data); a->n1=INTEGER(GET_DIM(rval))[0]; a->n2=INTEGER(GET_DIM(rval))[1]; a->n3=INTEGER(GET_DIM(rval))[2]; a->n1n2=(a->n1) * (a->n2); return 0; } int R_igraph_SEXP_to_array3_copy(SEXP rval, igraph_array3_t *a) { igraph_vector_init_copy(&a->data, REAL(rval), GET_LENGTH(rval)); a->n1=INTEGER(GET_DIM(rval))[0]; a->n2=INTEGER(GET_DIM(rval))[1]; a->n3=INTEGER(GET_DIM(rval))[2]; a->n1n2=(a->n1) * (a->n2); return 0; } int R_SEXP_to_igraph(SEXP graph, igraph_t *res) { res->n=(igraph_integer_t) REAL(VECTOR_ELT(graph, 0))[0]; res->directed=LOGICAL(VECTOR_ELT(graph, 1))[0]; R_SEXP_to_vector(VECTOR_ELT(graph, 2), &res->from); R_SEXP_to_vector(VECTOR_ELT(graph, 3), &res->to); R_SEXP_to_vector(VECTOR_ELT(graph, 4), &res->oi); R_SEXP_to_vector(VECTOR_ELT(graph, 5), &res->ii); R_SEXP_to_vector(VECTOR_ELT(graph, 6), &res->os); R_SEXP_to_vector(VECTOR_ELT(graph, 7), &res->is); /* attributes */ REAL(VECTOR_ELT(VECTOR_ELT(graph, 8), 0))[0] = 1; /* R objects refcount */ REAL(VECTOR_ELT(VECTOR_ELT(graph, 8), 0))[1] = 0; /* igraph_t objects */ res->attr=VECTOR_ELT(graph, 8); return 0; } int R_SEXP_to_igraph_copy(SEXP graph, igraph_t *res) { res->n=(igraph_integer_t) REAL(VECTOR_ELT(graph, 0))[0]; res->directed=LOGICAL(VECTOR_ELT(graph, 1))[0]; igraph_vector_init_copy(&res->from, REAL(VECTOR_ELT(graph, 2)), GET_LENGTH(VECTOR_ELT(graph, 2))); igraph_vector_init_copy(&res->to, REAL(VECTOR_ELT(graph, 3)), GET_LENGTH(VECTOR_ELT(graph, 3))); igraph_vector_init_copy(&res->oi, REAL(VECTOR_ELT(graph, 4)), GET_LENGTH(VECTOR_ELT(graph, 4))); igraph_vector_init_copy(&res->ii, REAL(VECTOR_ELT(graph, 5)), GET_LENGTH(VECTOR_ELT(graph, 5))); igraph_vector_init_copy(&res->os, REAL(VECTOR_ELT(graph, 6)), GET_LENGTH(VECTOR_ELT(graph, 6))); igraph_vector_init_copy(&res->is, REAL(VECTOR_ELT(graph, 7)), GET_LENGTH(VECTOR_ELT(graph, 7))); /* attributes */ REAL(VECTOR_ELT(VECTOR_ELT(graph, 8), 0))[0] = 1; /* R objects */ REAL(VECTOR_ELT(VECTOR_ELT(graph, 8), 0))[1] = 1; /* igraph_t objects */ R_PreserveObject(res->attr=VECTOR_ELT(graph, 8)); return 0; } /* * We have only vector type */ int R_SEXP_to_igraph_vs(SEXP rit, igraph_t *graph, igraph_vs_t *it) { igraph_vector_t *tmpv=(igraph_vector_t*)R_alloc(1,sizeof(igraph_vector_t)); igraph_vs_vector(it, igraph_vector_view(tmpv, REAL(rit), GET_LENGTH(rit))); return 0; } /* * We have only vector type */ int R_SEXP_to_igraph_es(SEXP rit, igraph_t *graph, igraph_es_t *it) { igraph_vector_t *tmpv=(igraph_vector_t*)R_alloc(1,sizeof(igraph_vector_t)); igraph_es_vector(it, igraph_vector_view(tmpv, REAL(rit), GET_LENGTH(rit))); return 0; } int R_SEXP_to_igraph_layout_drl_options(SEXP in, igraph_layout_drl_options_t *opt) { opt->edge_cut = REAL(AS_NUMERIC(R_igraph_getListElement(in, "edge.cut")))[0]; opt->init_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "init.iterations")))[0]; opt->init_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "init.temperature")))[0]; opt->init_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "init.attraction")))[0]; opt->init_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "init.damping.mult")))[0]; opt->liquid_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "liquid.iterations")))[0]; opt->liquid_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "liquid.temperature")))[0]; opt->liquid_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "liquid.attraction")))[0]; opt->liquid_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "liquid.damping.mult")))[0]; opt->expansion_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "expansion.iterations")))[0]; opt->expansion_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "expansion.temperature")))[0]; opt->expansion_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "expansion.attraction")))[0]; opt->expansion_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "expansion.damping.mult")))[0]; opt->cooldown_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "cooldown.iterations")))[0]; opt->cooldown_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "cooldown.temperature")))[0]; opt->cooldown_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "cooldown.attraction")))[0]; opt->cooldown_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "cooldown.damping.mult")))[0]; opt->crunch_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "crunch.iterations")))[0]; opt->crunch_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "crunch.temperature")))[0]; opt->crunch_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "crunch.attraction")))[0]; opt->crunch_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "crunch.damping.mult")))[0]; opt->simmer_iterations = (igraph_integer_t) REAL(AS_NUMERIC(R_igraph_getListElement(in, "simmer.iterations")))[0]; opt->simmer_temperature = REAL(AS_NUMERIC(R_igraph_getListElement(in, "simmer.temperature")))[0]; opt->simmer_attraction = REAL(AS_NUMERIC(R_igraph_getListElement(in, "simmer.attraction")))[0]; opt->simmer_damping_mult = REAL(AS_NUMERIC(R_igraph_getListElement(in, "simmer.damping.mult")))[0]; return 0; } int R_SEXP_to_igraph_arpack_options(SEXP in, igraph_arpack_options_t *opt) { const char *tmpstr; igraph_arpack_options_init(opt); opt -> bmat[0] = CHAR(STRING_ELT(AS_CHARACTER (R_igraph_getListElement(in, "bmat")), 0))[0]; opt -> n = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "n")))[0]; tmpstr=CHAR(STRING_ELT(AS_CHARACTER(R_igraph_getListElement(in, "which")), 0)); opt -> which[0]=tmpstr[0]; opt -> which[1]=tmpstr[1]; opt -> nev = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "nev")))[0]; opt -> tol = REAL(AS_NUMERIC(R_igraph_getListElement(in, "tol")))[0]; opt -> ncv = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "ncv")))[0]; opt -> ldv = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "ldv")))[0]; opt -> ishift = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "ishift")))[0]; opt -> mxiter = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "maxiter")))[0]; opt -> nb = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "nb")))[0]; opt -> mode = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "mode")))[0]; opt -> start = INTEGER(AS_INTEGER(R_igraph_getListElement(in, "start")))[0]; opt -> lworkl = 0; opt -> sigma = REAL(AS_NUMERIC(R_igraph_getListElement(in, "sigma")))[0]; opt -> sigmai = REAL(AS_NUMERIC(R_igraph_getListElement(in, "sigmai")))[0]; opt -> info = opt -> start; opt->iparam[0]=opt->ishift; opt->iparam[2]=opt->mxiter; opt->iparam[3]=opt->nb; opt->iparam[6]=opt->mode; return 0; } SEXP R_igraph_arpack_options_to_SEXP(const igraph_arpack_options_t *opt) { SEXP result, names; char bmat[2], which[3]; bmat[0]=opt->bmat[0]; bmat[1]='\0'; which[0]=opt->which[0]; which[1]=opt->which[1]; which[2]='\0'; PROTECT(result = NEW_LIST(20)); SET_VECTOR_ELT(result, 0, ScalarString(CREATE_STRING_VECTOR(bmat))); SET_VECTOR_ELT(result, 1, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 1))[0]=opt->n; SET_VECTOR_ELT(result, 2, ScalarString(CREATE_STRING_VECTOR(which))); SET_VECTOR_ELT(result, 3, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 3))[0]=opt->nev; SET_VECTOR_ELT(result, 4, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 4))[0]=opt->tol; SET_VECTOR_ELT(result, 5, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 5))[0]=opt->ncv; SET_VECTOR_ELT(result, 6, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 6))[0]=opt->ldv; SET_VECTOR_ELT(result, 7, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 7))[0]=opt->ishift; SET_VECTOR_ELT(result, 8, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 8))[0]=opt->mxiter; SET_VECTOR_ELT(result, 9, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 9))[0]=opt->nb; SET_VECTOR_ELT(result, 10, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 10))[0]=opt->mode; SET_VECTOR_ELT(result, 11, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 11))[0]=opt->start; SET_VECTOR_ELT(result, 12, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 12))[0]=opt->sigma; SET_VECTOR_ELT(result, 13, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 13))[0]=opt->sigmai; SET_VECTOR_ELT(result, 14, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 14))[0]=opt->info; SET_VECTOR_ELT(result, 15, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 15))[0]=opt->iparam[2];/* mxiter */ SET_VECTOR_ELT(result, 16, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 16))[0]=opt->iparam[4];/* nconv */ SET_VECTOR_ELT(result, 17, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 17))[0]=opt->iparam[8];/* numop */ SET_VECTOR_ELT(result, 18, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 18))[0]=opt->iparam[9];/* numopb */ SET_VECTOR_ELT(result, 19, NEW_INTEGER(1)); INTEGER(VECTOR_ELT(result, 19))[0]=opt->iparam[10];/* numreo */ PROTECT(names=NEW_CHARACTER(20)); SET_STRING_ELT(names, 0, mkChar("bmat")); SET_STRING_ELT(names, 1, mkChar("n")); SET_STRING_ELT(names, 2, mkChar("which")); SET_STRING_ELT(names, 3, mkChar("nev")); SET_STRING_ELT(names, 4, mkChar("tol")); SET_STRING_ELT(names, 5, mkChar("ncv")); SET_STRING_ELT(names, 6, mkChar("ldv")); SET_STRING_ELT(names, 7, mkChar("ishift")); SET_STRING_ELT(names, 8, mkChar("maxiter")); SET_STRING_ELT(names, 9, mkChar("nb")); SET_STRING_ELT(names, 10, mkChar("mode")); SET_STRING_ELT(names, 11, mkChar("start")); SET_STRING_ELT(names, 12, mkChar("sigma")); SET_STRING_ELT(names, 13, mkChar("sigmai")); SET_STRING_ELT(names, 14, mkChar("info")); SET_STRING_ELT(names, 15, mkChar("iter")); SET_STRING_ELT(names, 16, mkChar("nconv")); SET_STRING_ELT(names, 17, mkChar("numop")); SET_STRING_ELT(names, 18, mkChar("numopb")); SET_STRING_ELT(names, 19, mkChar("numreo")); SET_NAMES(result, names); UNPROTECT(2); return result; } int R_SEXP_to_igraph_eigen_which(SEXP in, igraph_eigen_which_t *out) { SEXP pos=PROTECT(AS_CHARACTER(R_igraph_getListElement(in, "pos"))); SEXP balance=PROTECT(AS_CHARACTER(R_igraph_getListElement (in, "balance"))); if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "lm")) { out->pos=IGRAPH_EIGEN_LM; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "sm")) { out->pos=IGRAPH_EIGEN_SM; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "la")) { out->pos=IGRAPH_EIGEN_LA; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "sa")) { out->pos=IGRAPH_EIGEN_SA; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "be")) { out->pos=IGRAPH_EIGEN_BE; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "lr")) { out->pos=IGRAPH_EIGEN_LR; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "sr")) { out->pos=IGRAPH_EIGEN_SR; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "li")) { out->pos=IGRAPH_EIGEN_LI; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "si")) { out->pos=IGRAPH_EIGEN_SI; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "all")) { out->pos=IGRAPH_EIGEN_ALL; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "interval")) { out->pos=IGRAPH_EIGEN_INTERVAL; } else if (!strcasecmp(CHAR(STRING_ELT(pos, 0)), "select")) { out->pos=IGRAPH_EIGEN_SELECT; } else { UNPROTECT(2); IGRAPH_ERROR("Unknown eigenvalue position specification", IGRAPH_EINVAL); } out->howmany=INTEGER(AS_INTEGER(R_igraph_getListElement (in, "howmany")))[0]; out->il=INTEGER(AS_INTEGER(R_igraph_getListElement(in, "il")))[0]; out->iu=INTEGER(AS_INTEGER(R_igraph_getListElement(in, "iu")))[0]; out->vl=REAL(AS_NUMERIC(R_igraph_getListElement(in, "vl")))[0]; out->vu=REAL(AS_NUMERIC(R_igraph_getListElement(in, "vu")))[0]; out->vestimate=INTEGER(AS_INTEGER(R_igraph_getListElement (in, "vestimate")))[0]; if (!strcasecmp(CHAR(STRING_ELT(balance, 0)), "none")) { out->balance=IGRAPH_LAPACK_DGEEVX_BALANCE_NONE; } else if (!strcasecmp(CHAR(STRING_ELT(balance, 0)), "perm")) { out->balance=IGRAPH_LAPACK_DGEEVX_BALANCE_PERM; } else if (!strcasecmp(CHAR(STRING_ELT(balance, 0)), "scale")) { out->balance=IGRAPH_LAPACK_DGEEVX_BALANCE_SCALE; } else if (!strcasecmp(CHAR(STRING_ELT(balance, 0)), "both")) { out->balance=IGRAPH_LAPACK_DGEEVX_BALANCE_BOTH; } else { UNPROTECT(2); IGRAPH_ERROR("Unknown balance specification", IGRAPH_EINVAL); } UNPROTECT(2); return 0; } SEXP R_igraph_bliss_info_to_SEXP(const igraph_bliss_info_t *info) { SEXP result, names; PROTECT(result=NEW_LIST(6)); SET_VECTOR_ELT(result, 0, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 0))[0]=info->nof_nodes; SET_VECTOR_ELT(result, 1, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 1))[0]=info->nof_leaf_nodes; SET_VECTOR_ELT(result, 2, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 2))[0]=info->nof_bad_nodes; SET_VECTOR_ELT(result, 3, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 3))[0]=info->nof_canupdates; SET_VECTOR_ELT(result, 4, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 4))[0]=info->max_level; if (info->group_size) { SET_VECTOR_ELT(result, 5, NEW_CHARACTER(1)); SET_STRING_ELT(VECTOR_ELT(result, 5), 0, mkChar(info->group_size)); } else { SET_VECTOR_ELT(result, 5, R_NilValue); } PROTECT(names=NEW_CHARACTER(6)); SET_STRING_ELT(names, 0, mkChar("nof_nodes")); SET_STRING_ELT(names, 1, mkChar("nof_leaf_nodes")); SET_STRING_ELT(names, 2, mkChar("nof_bad_nodes")); SET_STRING_ELT(names, 3, mkChar("nof_canupdates")); SET_STRING_ELT(names, 4, mkChar("max_level")); SET_STRING_ELT(names, 5, mkChar("group_size")); SET_NAMES(result, names); UNPROTECT(2); return result; } /*******************************************************************/ SEXP R_igraph_mybracket(SEXP graph, SEXP pidx) { int idx=INTEGER(pidx)[0]-1; return duplicate(VECTOR_ELT(graph, idx)); } SEXP R_igraph_mybracket2(SEXP graph, SEXP pidx1, SEXP pidx2) { int idx1=INTEGER(pidx1)[0]-1; int idx2=INTEGER(pidx2)[0]-1; return duplicate(VECTOR_ELT(VECTOR_ELT(graph, idx1), idx2)); } SEXP R_igraph_mybracket2_names(SEXP graph, SEXP pidx1, SEXP pidx2) { SEXP result; int idx1=INTEGER(pidx1)[0]-1; int idx2=INTEGER(pidx2)[0]-1; result=duplicate(GET_NAMES(VECTOR_ELT(VECTOR_ELT(graph, idx1), idx2))); return result; } SEXP R_igraph_mybracket2_copy(SEXP graph, SEXP pidx1, SEXP pidx2) { int idx1=INTEGER(pidx1)[0]-1; int idx2=INTEGER(pidx2)[0]-1; return duplicate(VECTOR_ELT(VECTOR_ELT(graph, idx1), idx2)); } SEXP R_igraph_mybracket2_set(SEXP graph, SEXP pidx1, SEXP pidx2, SEXP value) { SEXP newgraph; int idx1=INTEGER(pidx1)[0]-1; int idx2=INTEGER(pidx2)[0]-1; PROTECT(newgraph=duplicate(graph)); SET_VECTOR_ELT(VECTOR_ELT(newgraph, idx1), idx2, value); UNPROTECT(1); return newgraph; } SEXP R_igraph_mybracket3_set(SEXP graph, SEXP pidx1, SEXP pidx2, SEXP pname, SEXP value) { SEXP newgraph; int idx1=INTEGER(pidx1)[0]-1; int idx2=INTEGER(pidx2)[0]-1; const char *name=CHAR(STRING_ELT(pname, 0)); SEXP attrs, names; int i, n; PROTECT(newgraph=duplicate(graph)); attrs=VECTOR_ELT(VECTOR_ELT(newgraph, idx1), idx2); names=PROTECT(getAttrib(attrs, R_NamesSymbol)); n=length(attrs); for (i=0; i100) { igraph_shortest_paths_johnson(&g, &res, vs, to, pw); } else if (negw) { igraph_shortest_paths_bellman_ford(&g, &res, vs, to, pw, (igraph_neimode_t) mode); } else { /* This one chooses 'unweighted' if there are no weights */ igraph_shortest_paths_dijkstra(&g, &res, vs, to, pw, (igraph_neimode_t) mode); } break; case 1: /* unweighted */ igraph_shortest_paths(&g, &res, vs, to, (igraph_neimode_t) mode); break; case 2: /* dijkstra */ igraph_shortest_paths_dijkstra(&g, &res, vs, to, pw, (igraph_neimode_t) mode); break; case 3: /* bellman-ford */ igraph_shortest_paths_bellman_ford(&g, &res, vs, to, pw, (igraph_neimode_t) mode); break; case 4: /* johnson */ igraph_shortest_paths_johnson(&g, &res, vs, to, pw); break; } PROTECT(result=R_igraph_matrix_to_SEXP(&res)); igraph_matrix_destroy(&res); igraph_vs_destroy(&vs); UNPROTECT(1); return result; } SEXP R_igraph_lattice(SEXP pdimvector, SEXP pnei, SEXP pdirected, SEXP pmutual, SEXP pcircular) { igraph_t g; igraph_vector_t dimvector; igraph_integer_t nei=(igraph_integer_t) REAL(pnei)[0]; igraph_bool_t directed=LOGICAL(pdirected)[0]; igraph_bool_t mutual=LOGICAL(pmutual)[0]; igraph_bool_t circular=LOGICAL(pcircular)[0]; SEXP result; R_SEXP_to_vector(pdimvector, &dimvector); igraph_lattice(&g, &dimvector, nei, directed, mutual, circular); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_barabasi_game(SEXP pn, SEXP ppower, SEXP pm, SEXP poutseq, SEXP poutpref, SEXP pA, SEXP pdirected, SEXP palgo, SEXP pstart) { igraph_t g; igraph_integer_t n=(igraph_integer_t) REAL(pn)[0]; igraph_real_t power=REAL(ppower)[0]; igraph_integer_t m=isNull(pm) ? 0 : (igraph_integer_t) REAL(pm)[0]; igraph_vector_t outseq, *myoutseq=0; igraph_bool_t outpref=LOGICAL(poutpref)[0]; igraph_real_t A=REAL(pA)[0]; igraph_bool_t directed=LOGICAL(pdirected)[0]; igraph_barabasi_algorithm_t algo=(igraph_barabasi_algorithm_t) REAL(palgo)[0]; igraph_t start, *ppstart=0; SEXP result; if (!isNull(poutseq)) { R_SEXP_to_vector(poutseq, &outseq); myoutseq=&outseq; } if (!isNull(pstart)) { R_SEXP_to_igraph(pstart, &start); ppstart=&start; } igraph_barabasi_game(&g, n, power, m, myoutseq, outpref, A, directed, algo, ppstart); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_recent_degree_game(SEXP pn, SEXP ppower, SEXP pwindow, SEXP pm, SEXP poutseq, SEXP poutpref, SEXP pzero_appeal, SEXP pdirected) { igraph_t g; igraph_integer_t n=(igraph_integer_t) REAL(pn)[0]; igraph_real_t power=REAL(ppower)[0]; igraph_integer_t window=(igraph_integer_t) REAL(pwindow)[0]; igraph_integer_t m=(igraph_integer_t) REAL(pm)[0]; igraph_vector_t outseq; igraph_bool_t outpref=LOGICAL(poutpref)[0]; igraph_bool_t directed=LOGICAL(pdirected)[0]; igraph_real_t zero_appeal=REAL(pzero_appeal)[0]; SEXP result; R_SEXP_to_vector(poutseq, &outseq); igraph_recent_degree_game(&g, n, power, window, m, &outseq, outpref, zero_appeal, directed); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_layout_fruchterman_reingold(SEXP graph, SEXP coords, SEXP niter, SEXP start_temp, SEXP weights, SEXP minx, SEXP maxx, SEXP miny, SEXP maxy, SEXP grid) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_coords; igraph_integer_t c_niter; igraph_real_t c_start_temp; igraph_vector_t c_weights; igraph_vector_t c_minx; igraph_vector_t c_maxx; igraph_vector_t c_miny; igraph_vector_t c_maxy; igraph_layout_grid_t c_grid=INTEGER(grid)[0]; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(coords)) { if (0 != R_SEXP_to_igraph_matrix_copy(coords, &c_coords)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } } else { igraph_matrix_init(&c_coords, 0, 0); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_coords); c_niter=INTEGER(niter)[0]; c_start_temp=REAL(start_temp)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(minx)) { R_SEXP_to_vector(minx, &c_minx); } if (!isNull(maxx)) { R_SEXP_to_vector(maxx, &c_maxx); } if (!isNull(miny)) { R_SEXP_to_vector(miny, &c_miny); } if (!isNull(maxy)) { R_SEXP_to_vector(maxy, &c_maxy); } /* Call igraph */ igraph_layout_fruchterman_reingold(&c_graph, &c_coords, !isNull(coords), c_niter, c_start_temp, c_grid, (isNull(weights) ? 0 : &c_weights), (isNull(minx) ? 0 : &c_minx), (isNull(maxx) ? 0 : &c_maxx), (isNull(miny) ? 0 : &c_miny), (isNull(maxy) ? 0 : &c_maxy)); /* Convert output */ PROTECT(coords=R_igraph_matrix_to_SEXP(&c_coords)); igraph_matrix_destroy(&c_coords); IGRAPH_FINALLY_CLEAN(1); result=coords; UNPROTECT(1); return(result); } SEXP R_igraph_layout_fruchterman_reingold_3d(SEXP graph, SEXP coords, SEXP niter, SEXP start_temp, SEXP weights, SEXP minx, SEXP maxx, SEXP miny, SEXP maxy, SEXP minz, SEXP maxz) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_coords; igraph_integer_t c_niter; igraph_real_t c_start_temp; igraph_vector_t c_weights; igraph_vector_t c_minx; igraph_vector_t c_maxx; igraph_vector_t c_miny; igraph_vector_t c_maxy; igraph_vector_t c_minz; igraph_vector_t c_maxz; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(coords)) { if (0 != R_SEXP_to_igraph_matrix_copy(coords, &c_coords)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } } else { igraph_matrix_init(&c_coords, 0, 0); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_coords); c_niter=INTEGER(niter)[0]; c_start_temp=REAL(start_temp)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(minx)) { R_SEXP_to_vector(minx, &c_minx); } if (!isNull(maxx)) { R_SEXP_to_vector(maxx, &c_maxx); } if (!isNull(miny)) { R_SEXP_to_vector(miny, &c_miny); } if (!isNull(maxy)) { R_SEXP_to_vector(maxy, &c_maxy); } if (!isNull(minz)) { R_SEXP_to_vector(minz, &c_minz); } if (!isNull(maxz)) { R_SEXP_to_vector(maxz, &c_maxz); } /* Call igraph */ igraph_layout_fruchterman_reingold_3d(&c_graph, &c_coords, !isNull(coords), c_niter, c_start_temp, (isNull(weights) ? 0 : &c_weights), (isNull(minx) ? 0 : &c_minx), (isNull(maxx) ? 0 : &c_maxx), (isNull(miny) ? 0 : &c_miny), (isNull(maxy) ? 0 : &c_maxy), (isNull(minz) ? 0 : &c_minz), (isNull(maxz) ? 0 : &c_maxz)); /* Convert output */ PROTECT(coords=R_igraph_matrix_to_SEXP(&c_coords)); igraph_matrix_destroy(&c_coords); IGRAPH_FINALLY_CLEAN(1); result=coords; UNPROTECT(1); return(result); } SEXP R_igraph_layout_kamada_kawai(SEXP graph, SEXP coords, SEXP maxiter, SEXP epsilon, SEXP kkconst, SEXP weights, SEXP minx, SEXP maxx, SEXP miny, SEXP maxy) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_coords; igraph_integer_t c_maxiter; igraph_real_t c_epsilon; igraph_real_t c_kkconst; igraph_vector_t c_weights; igraph_vector_t c_minx; igraph_vector_t c_maxx; igraph_vector_t c_miny; igraph_vector_t c_maxy; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(coords)) { if (0 != R_SEXP_to_igraph_matrix_copy(coords, &c_coords)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } } else { igraph_matrix_init(&c_coords, 0, 0); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_coords); c_maxiter=INTEGER(maxiter)[0]; c_epsilon=REAL(epsilon)[0]; c_kkconst=REAL(kkconst)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(minx)) { R_SEXP_to_vector(minx, &c_minx); } if (!isNull(maxx)) { R_SEXP_to_vector(maxx, &c_maxx); } if (!isNull(miny)) { R_SEXP_to_vector(miny, &c_miny); } if (!isNull(maxy)) { R_SEXP_to_vector(maxy, &c_maxy); } /* Call igraph */ igraph_layout_kamada_kawai(&c_graph, &c_coords, !isNull(coords), c_maxiter, c_epsilon, c_kkconst, (isNull(weights) ? 0 : &c_weights), (isNull(minx) ? 0 : &c_minx), (isNull(maxx) ? 0 : &c_maxx), (isNull(miny) ? 0 : &c_miny), (isNull(maxy) ? 0 : &c_maxy)); /* Convert output */ PROTECT(coords=R_igraph_matrix_to_SEXP(&c_coords)); igraph_matrix_destroy(&c_coords); IGRAPH_FINALLY_CLEAN(1); result=coords; UNPROTECT(1); return(result); } SEXP R_igraph_layout_kamada_kawai_3d(SEXP graph, SEXP coords, SEXP maxiter, SEXP epsilon, SEXP kkconst, SEXP weights, SEXP minx, SEXP maxx, SEXP miny, SEXP maxy, SEXP minz, SEXP maxz) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_coords; igraph_integer_t c_maxiter; igraph_real_t c_epsilon; igraph_real_t c_kkconst; igraph_vector_t c_weights; igraph_vector_t c_minx; igraph_vector_t c_maxx; igraph_vector_t c_miny; igraph_vector_t c_maxy; igraph_vector_t c_minz; igraph_vector_t c_maxz; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(coords)) { if (0 != R_SEXP_to_igraph_matrix_copy(coords, &c_coords)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } } else { igraph_matrix_init(&c_coords, 0, 0); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_coords); c_maxiter=INTEGER(maxiter)[0]; c_epsilon=REAL(epsilon)[0]; c_kkconst=REAL(kkconst)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(minx)) { R_SEXP_to_vector(minx, &c_minx); } if (!isNull(maxx)) { R_SEXP_to_vector(maxx, &c_maxx); } if (!isNull(miny)) { R_SEXP_to_vector(miny, &c_miny); } if (!isNull(maxy)) { R_SEXP_to_vector(maxy, &c_maxy); } if (!isNull(minz)) { R_SEXP_to_vector(minz, &c_minz); } if (!isNull(maxz)) { R_SEXP_to_vector(maxz, &c_maxz); } /* Call igraph */ igraph_layout_kamada_kawai_3d(&c_graph, &c_coords, !isNull(coords), c_maxiter, c_epsilon, c_kkconst, (isNull(weights) ? 0 : &c_weights), (isNull(minx) ? 0 : &c_minx), (isNull(maxx) ? 0 : &c_maxx), (isNull(miny) ? 0 : &c_miny), (isNull(maxy) ? 0 : &c_maxy), (isNull(minz) ? 0 : &c_minz), (isNull(maxz) ? 0 : &c_maxz)); /* Convert output */ PROTECT(coords=R_igraph_matrix_to_SEXP(&c_coords)); igraph_matrix_destroy(&c_coords); IGRAPH_FINALLY_CLEAN(1); result=coords; UNPROTECT(1); return(result); } SEXP R_igraph_layout_graphopt(SEXP graph, SEXP pniter, SEXP pcharge, SEXP pmass, SEXP pspring_length, SEXP pspring_constant, SEXP pmax_sa_movement, SEXP start) { igraph_t g; igraph_integer_t niter=(igraph_integer_t) REAL(pniter)[0]; igraph_real_t charge=REAL(pcharge)[0]; igraph_real_t mass=REAL(pmass)[0]; igraph_real_t spring_length=REAL(pspring_length)[0]; igraph_real_t spring_constant=REAL(pspring_constant)[0]; igraph_real_t max_sa_movement=REAL(pmax_sa_movement)[0]; igraph_matrix_t res; SEXP result; R_SEXP_to_igraph(graph, &g); if (isNull(start)) { igraph_matrix_init(&res, 0, 0); } else { R_SEXP_to_igraph_matrix_copy(start, &res); } igraph_layout_graphopt(&g, &res, niter, charge, mass, spring_length, spring_constant, max_sa_movement, !isNull(start)); PROTECT(result=R_igraph_matrix_to_SEXP(&res)); igraph_matrix_destroy(&res); UNPROTECT(1); return result; } SEXP R_igraph_layout_lgl(SEXP graph, SEXP pmaxiter, SEXP pmaxdelta, SEXP parea, SEXP pcoolexp, SEXP prepulserad, SEXP pcellsize, SEXP proot) { igraph_t g; igraph_matrix_t res; igraph_integer_t maxiter=(igraph_integer_t) REAL(pmaxiter)[0]; igraph_real_t maxdelta=REAL(pmaxdelta)[0]; igraph_real_t area=REAL(parea)[0]; igraph_real_t coolexp=REAL(pcoolexp)[0]; igraph_real_t repulserad=REAL(prepulserad)[0]; igraph_real_t cellsize=REAL(pcellsize)[0]; igraph_integer_t root=(igraph_integer_t) REAL(proot)[0]; SEXP result; R_SEXP_to_igraph(graph, &g); igraph_matrix_init(&res, 0, 0); igraph_layout_lgl(&g, &res, maxiter, maxdelta, area, coolexp, repulserad, cellsize, root); PROTECT(result=R_igraph_matrix_to_SEXP(&res)); igraph_matrix_destroy(&res); UNPROTECT(1); return result; } SEXP R_igraph_minimum_spanning_tree_unweighted(SEXP graph) { igraph_t g; igraph_t mst; SEXP result; R_SEXP_to_igraph(graph, &g); igraph_minimum_spanning_tree_unweighted(&g, &mst); PROTECT(result=R_igraph_to_SEXP(&mst)); igraph_destroy(&mst); UNPROTECT(1); return result; } SEXP R_igraph_minimum_spanning_tree_prim(SEXP graph, SEXP pweights) { igraph_t g; igraph_t mst; igraph_vector_t weights; SEXP result; R_SEXP_to_vector(pweights, &weights); R_SEXP_to_igraph(graph, &g); igraph_minimum_spanning_tree_prim(&g, &mst, &weights); PROTECT(result=R_igraph_to_SEXP(&mst)); igraph_destroy(&mst); UNPROTECT(1); return result; } SEXP R_igraph_get_shortest_paths(SEXP graph, SEXP pfrom, SEXP pto, SEXP pmode, SEXP pno, SEXP weights, SEXP output, SEXP ppred, SEXP pinbound) { igraph_t g; igraph_integer_t from=(igraph_integer_t) REAL(pfrom)[0]; igraph_vs_t to; igraph_integer_t mode=(igraph_integer_t) REAL(pmode)[0]; igraph_vector_t *vects, *evects; long int i; igraph_vector_ptr_t ptrvec, ptrevec; igraph_vector_t w, *pw=&w; SEXP result, result1, result2, names; igraph_bool_t verts=REAL(output)[0]==0 || REAL(output)[0]==2; igraph_bool_t edges=REAL(output)[0]==1 || REAL(output)[0]==2; igraph_bool_t pred=LOGICAL(ppred)[0]; igraph_bool_t inbound=LOGICAL(pinbound)[0]; igraph_vector_long_t predvec, inboundvec; long int no=(long int) REAL(pno)[0]; R_SEXP_to_igraph(graph, &g); R_SEXP_to_igraph_vs(pto, &g, &to); if (verts) { igraph_vector_ptr_init(&ptrvec, no); vects=(igraph_vector_t*) R_alloc((size_t) GET_LENGTH(pto), sizeof(igraph_vector_t)); for (i=0; i0) { R_igraph_SEXP_to_strvector(ppredef, &predef); predefptr=&predef; } igraph_read_graph_ncol(&g, file, predefptr, names, weights, directed); fclose(file); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_write_graph_ncol(SEXP graph, SEXP file, SEXP pnames, SEXP pweights) { igraph_t g; FILE *stream; #if HAVE_OPEN_MEMSTREAM == 1 char *bp; size_t size; #endif const char *names, *weights; SEXP result; if (isNull(pnames)) { names=0; } else { names=CHAR(STRING_ELT(pnames, 0)); } if (isNull(pweights)) { weights=0; } else { weights=CHAR(STRING_ELT(pweights, 0)); } R_SEXP_to_igraph(graph, &g); #if HAVE_OPEN_MEMSTREAM == 1 stream=open_memstream(&bp, &size); #else stream=fopen(CHAR(STRING_ELT(file,0)), "w"); #endif if (stream==0) { igraph_error("Cannot write .ncol file", __FILE__, __LINE__, IGRAPH_EFILE); } igraph_write_graph_ncol(&g, stream, names, weights); fclose(stream); #if HAVE_OPEN_MEMSTREAM == 1 PROTECT(result=allocVector(RAWSXP, size)); memcpy(RAW(result), bp, sizeof(char)*size); free(bp); #else PROTECT(result=NEW_NUMERIC(0)); #endif UNPROTECT(1); return result; } SEXP R_igraph_read_graph_lgl(SEXP pvfile, SEXP pnames, SEXP pweights, SEXP pdirected) { igraph_t g; igraph_bool_t names=LOGICAL(pnames)[0]; igraph_add_weights_t weights=REAL(pweights)[0]; igraph_bool_t directed=LOGICAL(pdirected)[0]; FILE *file; SEXP result; #if HAVE_FMEMOPEN == 1 file=fmemopen(RAW(pvfile), GET_LENGTH(pvfile), "r"); #else file=fopen(CHAR(STRING_ELT(pvfile, 0)), "r"); #endif if (file==0) { igraph_error("Cannot read edgelist", __FILE__, __LINE__, IGRAPH_EFILE); } igraph_read_graph_lgl(&g, file, names, weights, directed); fclose(file); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_write_graph_lgl(SEXP graph, SEXP file, SEXP pnames, SEXP pweights, SEXP pisolates) { igraph_t g; FILE *stream; #if HAVE_OPEN_MEMSTREAM == 1 char *bp; size_t size; #endif const char *names, *weights; igraph_bool_t isolates=LOGICAL(pisolates)[0]; SEXP result; if (isNull(pnames)) { names=0; } else { names=CHAR(STRING_ELT(pnames, 0)); } if (isNull(pweights)) { weights=0; } else { weights=CHAR(STRING_ELT(pweights, 0)); } R_SEXP_to_igraph(graph, &g); #if HAVE_OPEN_MEMSTREAM == 1 stream=open_memstream(&bp, &size); #else stream=fopen(CHAR(STRING_ELT(file, 0)), "w"); #endif igraph_write_graph_lgl(&g, stream, names, weights, isolates); fclose(stream); #if HAVE_OPEN_MEMSTREAM == 1 PROTECT(result=allocVector(RAWSXP, size)); memcpy(RAW(result), bp, sizeof(char)*size); free(bp); #else PROTECT(result=NEW_NUMERIC(0)); #endif UNPROTECT(1); return result; } SEXP R_igraph_read_graph_pajek(SEXP pvfile) { igraph_t g; FILE *file; SEXP result; #if HAVE_FMEMOPEN == 1 file=fmemopen(RAW(pvfile), GET_LENGTH(pvfile), "r"); #else file=fopen(CHAR(STRING_ELT(pvfile, 0)), "r"); #endif if (file==0) { igraph_error("Cannot read Pajek file", __FILE__, __LINE__, IGRAPH_EFILE); } igraph_read_graph_pajek(&g, file); fclose(file); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_decompose(SEXP graph, SEXP pmode, SEXP pmaxcompno, SEXP pminelements) { igraph_t g; igraph_integer_t mode=(igraph_integer_t) REAL(pmode)[0]; igraph_integer_t maxcompno=(igraph_integer_t) REAL(pmaxcompno)[0]; igraph_integer_t minelements=(igraph_integer_t) REAL(pminelements)[0]; igraph_vector_ptr_t comps; SEXP result; long int i; R_PreserveObject(R_igraph_attribute_protected=NEW_LIST(100)); R_igraph_attribute_protected_size=0; IGRAPH_FINALLY(R_igraph_attribute_protected_destroy, 0); R_SEXP_to_igraph(graph, &g); igraph_vector_ptr_init(&comps, 0); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &comps); igraph_decompose(&g, &comps, (igraph_connectedness_t) mode, maxcompno, minelements); PROTECT(result=NEW_LIST(igraph_vector_ptr_size(&comps))); for (i=0; ifun, s_from, data->extra)); PROTECT(s_to = eval(R_fcall, data->rho)); memcpy(to, REAL(s_to), sizeof(igraph_real_t) * (size_t) n); UNPROTECT(3); return 0; } SEXP R_igraph_arpack(SEXP function, SEXP extra, SEXP options, SEXP rho, SEXP sym) { igraph_vector_t values; igraph_matrix_t vectors, values2; R_igraph_i_arpack_data_t data; igraph_arpack_options_t c_options; SEXP result, names; if (0 != igraph_matrix_init(&vectors, 0, 0)) { igraph_error("Cannot run ARPACK", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &vectors); if (LOGICAL(sym)[0]) { if (0 != igraph_vector_init(&values, 0)) { igraph_error("Cannot run ARPACK", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &values); } else { if (0 != igraph_matrix_init(&values2, 0, 0)) { igraph_error("Cannot run ARPACK", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &values2); } data.fun=function; data.extra=extra; data.rho=rho; R_SEXP_to_igraph_arpack_options(options, &c_options); if (LOGICAL(sym)[0]) { if (0 != igraph_arpack_rssolve(R_igraph_i_arpack_callback, &data, &c_options, 0, &values, &vectors)) { igraph_error("ARPACK failed", __FILE__, __LINE__, IGRAPH_FAILURE); } } else { if (0 != igraph_arpack_rnsolve(R_igraph_i_arpack_callback, &data, &c_options, 0, &values2, &vectors)) { igraph_error("ARPACK failed", __FILE__, __LINE__, IGRAPH_FAILURE); } } PROTECT(result=NEW_LIST(3)); if (LOGICAL(sym)[0]) { SET_VECTOR_ELT(result, 0, R_igraph_vector_to_SEXP(&values)); igraph_vector_destroy(&values); IGRAPH_FINALLY_CLEAN(1); } else { SET_VECTOR_ELT(result, 0, R_igraph_matrix_to_SEXP(&values2)); igraph_matrix_destroy(&values2); IGRAPH_FINALLY_CLEAN(1); } SET_VECTOR_ELT(result, 1, R_igraph_matrix_to_SEXP(&vectors)); igraph_matrix_destroy(&vectors); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 2, R_igraph_arpack_options_to_SEXP(&c_options)); PROTECT(names=NEW_CHARACTER(3)); SET_STRING_ELT(names, 0, mkChar("values")); SET_STRING_ELT(names, 1, mkChar("vectors")); SET_STRING_ELT(names, 2, mkChar("options")); SET_NAMES(result, names); UNPROTECT(2); return result; } SEXP R_igraph_is_chordal(SEXP graph, SEXP alpha, SEXP alpham1, SEXP pfillin, SEXP pnewgraph) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_alpha; igraph_vector_t c_alpham1; igraph_bool_t c_chordal; igraph_vector_t c_fillin; igraph_t c_newgraph; SEXP chordal; SEXP fillin; SEXP newgraph; int c_result; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(alpha)) { R_SEXP_to_vector(alpha, &c_alpha); } if (!isNull(alpham1)) { R_SEXP_to_vector(alpham1, &c_alpham1); } if (LOGICAL(pfillin)[0]) { if (0 != igraph_vector_init(&c_fillin, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_fillin); } c_result=igraph_is_chordal(&c_graph, (isNull(alpha) ? 0 : &c_alpha), (isNull(alpham1) ? 0 : &c_alpham1), &c_chordal, (LOGICAL(pfillin)[0] ? &c_fillin : 0), (LOGICAL(pnewgraph)[0] ? &c_newgraph : 0)); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(chordal=NEW_LOGICAL(1)); LOGICAL(chordal)[0]=c_chordal; if (LOGICAL(pfillin)[0]) { PROTECT(fillin=R_igraph_vector_to_SEXP(&c_fillin)); igraph_vector_destroy(&c_fillin); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(fillin=R_NilValue); } if (LOGICAL(pnewgraph)[0]) { IGRAPH_FINALLY(igraph_destroy, &c_newgraph); PROTECT(newgraph=R_igraph_to_SEXP(&c_newgraph)); igraph_destroy(&c_newgraph); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(newgraph=R_NilValue); } SET_VECTOR_ELT(result, 0, chordal); SET_VECTOR_ELT(result, 1, fillin); SET_VECTOR_ELT(result, 2, newgraph); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("chordal")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("fillin")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("newgraph")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } typedef struct { SEXP graph, fun, extra, rho; } R_igraph_i_bfs_data_t; igraph_bool_t R_igraph_bfshandler(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t pred, igraph_integer_t succ, igraph_integer_t rank, igraph_integer_t dist, void *extra) { R_igraph_i_bfs_data_t *data=extra; SEXP args, R_fcall, result, names; igraph_bool_t cres; PROTECT(args=NEW_NUMERIC(5)); PROTECT(names=NEW_CHARACTER(5)); SET_STRING_ELT(names, 0, mkChar("vid")); SET_STRING_ELT(names, 1, mkChar("pred")); SET_STRING_ELT(names, 2, mkChar("succ")); SET_STRING_ELT(names, 3, mkChar("rank")); SET_STRING_ELT(names, 4, mkChar("dist")); REAL(args)[0]=vid; REAL(args)[1]=pred; REAL(args)[2]=succ; REAL(args)[3]=rank; REAL(args)[4]=dist; SET_NAMES(args, names); PROTECT(R_fcall = lang4(data->fun, data->graph, args, data->extra)); PROTECT(result = eval(R_fcall, data->rho)); cres=LOGICAL(result)[0]; UNPROTECT(4); return cres; } SEXP R_igraph_bfs(SEXP graph, SEXP proot, SEXP proots, SEXP pneimode, SEXP punreachable, SEXP prestricted, SEXP porder, SEXP prank, SEXP pfather, SEXP ppred, SEXP psucc, SEXP pdist, SEXP pcallback, SEXP pextra, SEXP prho) { igraph_t g; SEXP result, names; igraph_integer_t root=(igraph_integer_t) REAL(proot)[0]; igraph_vector_t roots; igraph_bool_t unreachable=LOGICAL(punreachable)[0]; igraph_vector_t restricted; igraph_integer_t neimode=(igraph_integer_t) REAL(pneimode)[0]; igraph_vector_t order, rank, father, pred, succ, dist; igraph_vector_t *p_order=0, *p_rank=0, *p_father=0, *p_pred=0, *p_succ=0, *p_dist=0; igraph_bfshandler_t *callback=0; R_igraph_i_bfs_data_t cb_data, *p_cb_data=0; R_SEXP_to_igraph(graph, &g); if (!isNull(proots)) { R_SEXP_to_vector(proots, &roots); } if (!isNull(prestricted)) { R_SEXP_to_vector(prestricted, &restricted); } if (LOGICAL(porder)[0]) { igraph_vector_init(&order, 0); p_order=ℴ } if (LOGICAL(prank)[0]) { igraph_vector_init(&rank, 0); p_rank=&rank; } if (LOGICAL(pfather)[0]) { igraph_vector_init(&father, 0); p_father=&father; } if (LOGICAL(ppred)[0]) { igraph_vector_init(&pred, 0); p_pred=&pred; } if (LOGICAL(psucc)[0]) { igraph_vector_init(&succ, 0); p_succ=≻ } if (LOGICAL(pdist)[0]) { igraph_vector_init(&dist, 0); p_dist=&dist; } if (!isNull(pcallback)) { cb_data.graph=graph; cb_data.fun=pcallback; cb_data.extra=pextra; cb_data.rho=prho; callback=R_igraph_bfshandler; p_cb_data = &cb_data; } igraph_bfs(&g, root, isNull(proots) ? 0 : &roots, (igraph_neimode_t) neimode, unreachable, isNull(prestricted) ? 0 : &restricted, p_order, p_rank, p_father, p_pred, p_succ, p_dist, (igraph_bfshandler_t*) callback, p_cb_data); PROTECT(result=NEW_LIST(8)); PROTECT(names=NEW_CHARACTER(8)); SET_STRING_ELT(names, 0, mkChar("root")); SET_VECTOR_ELT(result, 0, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 0))[0] = root+1; SET_STRING_ELT(names, 1, mkChar("neimode")); SET_VECTOR_ELT(result, 1, NEW_CHARACTER(1)); if (neimode==1) { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("out")); } else if (neimode==2) { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("in")); } else { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("all")); } SET_STRING_ELT(names, 2, mkChar("order")); SET_VECTOR_ELT(result, 2, R_igraph_0orvector_to_SEXP_d(p_order)); SET_STRING_ELT(names, 3, mkChar("rank")); SET_VECTOR_ELT(result, 3, R_igraph_0orvector_to_SEXP_d(p_rank)); SET_STRING_ELT(names, 4, mkChar("father")); SET_VECTOR_ELT(result, 4, R_igraph_0orvector_to_SEXP_d(p_father)); SET_STRING_ELT(names, 5, mkChar("pred")); SET_VECTOR_ELT(result, 5, R_igraph_0orvector_to_SEXP_d(p_pred)); SET_STRING_ELT(names, 6, mkChar("succ")); SET_VECTOR_ELT(result, 6, R_igraph_0orvector_to_SEXP_d(p_succ)); SET_STRING_ELT(names, 7, mkChar("dist")); SET_VECTOR_ELT(result, 7, R_igraph_0orvector_to_SEXP_d(p_dist)); SET_NAMES(result, names); UNPROTECT(2); return result; } typedef struct { SEXP graph, fun_in, fun_out, extra, rho; } R_igraph_i_dfs_data_t; igraph_bool_t R_igraph_dfshandler(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t dist, void *extra, int which) { R_igraph_i_dfs_data_t *data=extra; SEXP args, R_fcall, result, names; igraph_bool_t cres; PROTECT(args=NEW_NUMERIC(2)); PROTECT(names=NEW_CHARACTER(2)); SET_STRING_ELT(names, 0, mkChar("vid")); SET_STRING_ELT(names, 1, mkChar("dist")); REAL(args)[0]=vid; REAL(args)[1]=dist; SET_NAMES(args, names); PROTECT(R_fcall = lang4(which==0 ? data->fun_in : data->fun_out, data->graph, args, data->extra)); PROTECT(result = eval(R_fcall, data->rho)); cres=LOGICAL(result)[0]; UNPROTECT(4); return cres; } igraph_bool_t R_igraph_dfshandler_in(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t dist, void *extra) { return R_igraph_dfshandler(graph, vid, dist, extra, 0); } igraph_bool_t R_igraph_dfshandler_out(const igraph_t *graph, igraph_integer_t vid, igraph_integer_t dist, void *extra) { return R_igraph_dfshandler(graph, vid, dist, extra, 1); } SEXP R_igraph_dfs(SEXP graph, SEXP proot, SEXP pneimode, SEXP punreachable, SEXP porder, SEXP porder_out, SEXP pfather, SEXP pdist, SEXP pin_callback, SEXP pout_callback, SEXP pextra, SEXP prho) { igraph_t g; SEXP result, names; igraph_integer_t root=(igraph_integer_t) REAL(proot)[0]; igraph_integer_t neimode=(igraph_integer_t) REAL(pneimode)[0]; igraph_bool_t unreachable=LOGICAL(punreachable)[0]; igraph_vector_t order, order_out, father, dist; igraph_vector_t *p_order=0, *p_order_out=0, *p_father=0, *p_dist=0; igraph_dfshandler_t *in_callback=0, *out_callback=0; R_igraph_i_dfs_data_t cb_data, *p_cb_data=0; R_SEXP_to_igraph(graph, &g); if (LOGICAL(porder)[0]) { igraph_vector_init(&order, 0); p_order=ℴ } if (LOGICAL(porder_out)[0]) { igraph_vector_init(&order_out, 0); p_order_out=&order_out; } if (LOGICAL(pfather)[0]) { igraph_vector_init(&father, 0); p_father=&father; } if (LOGICAL(pdist)[0]) { igraph_vector_init(&dist, 0); p_dist=&dist; } if (!isNull(pin_callback) || !isNull(pout_callback)) { cb_data.graph=graph; cb_data.fun_in=pin_callback; cb_data.fun_out=pout_callback; cb_data.extra=pextra; cb_data.rho=prho; p_cb_data = &cb_data; } if (!isNull(pin_callback)) { in_callback=R_igraph_dfshandler_in; } if (!isNull(pout_callback)) { out_callback=R_igraph_dfshandler_out; } igraph_dfs(&g, root, (igraph_neimode_t) neimode, unreachable, p_order, p_order_out, p_father, p_dist, (igraph_dfshandler_t*) in_callback, (igraph_dfshandler_t*) out_callback, p_cb_data); PROTECT(result=NEW_LIST(6)); PROTECT(names=NEW_CHARACTER(6)); SET_STRING_ELT(names, 0, mkChar("root")); SET_VECTOR_ELT(result, 0, NEW_NUMERIC(1)); REAL(VECTOR_ELT(result, 0))[0] = root; SET_STRING_ELT(names, 1, mkChar("neimode")); SET_VECTOR_ELT(result, 1, NEW_CHARACTER(1)); if (neimode==1) { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("out")); } else if (neimode==2) { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("in")); } else { SET_STRING_ELT(VECTOR_ELT(result, 1), 0, mkChar("all")); } SET_STRING_ELT(names, 2, mkChar("order")); SET_VECTOR_ELT(result, 2, R_igraph_0orvector_to_SEXP_d(p_order)); SET_STRING_ELT(names, 3, mkChar("order.out")); SET_VECTOR_ELT(result, 3, R_igraph_0orvector_to_SEXP_d(p_order_out)); SET_STRING_ELT(names, 4, mkChar("father")); SET_VECTOR_ELT(result, 4, R_igraph_0orvector_to_SEXP_d(p_father)); SET_STRING_ELT(names, 5, mkChar("dist")); SET_VECTOR_ELT(result, 5, R_igraph_0orvector_to_SEXP_d(p_dist)); SET_NAMES(result, names); UNPROTECT(2); return result; } SEXP R_igraph_cohesive_blocks(SEXP graph) { igraph_vector_ptr_t c_blocks; igraph_vector_t c_cohesion; igraph_vector_t c_parent; igraph_t c_blockTree; int c_result; igraph_t c_graph; SEXP blocks; SEXP cohesion; SEXP parent; SEXP blockTree; SEXP result; SEXP names; R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_blocks, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_blocks); if (0 != igraph_vector_init(&c_cohesion, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_cohesion); if (0 != igraph_vector_init(&c_parent, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_parent); c_result=igraph_cohesive_blocks(&c_graph, &c_blocks, &c_cohesion, &c_parent, &c_blockTree); PROTECT(result=NEW_LIST(4)); PROTECT(names=NEW_CHARACTER(4)); PROTECT(blocks=R_igraph_vectorlist_to_SEXP_p1(&c_blocks)); R_igraph_vectorlist_destroy(&c_blocks); IGRAPH_FINALLY_CLEAN(1); PROTECT(cohesion=R_igraph_vector_to_SEXP(&c_cohesion)); igraph_vector_destroy(&c_cohesion); IGRAPH_FINALLY_CLEAN(1); PROTECT(parent=R_igraph_vector_to_SEXPp1(&c_parent)); igraph_vector_destroy(&c_parent); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &c_blockTree); PROTECT(blockTree=R_igraph_to_SEXP(&c_blockTree)); igraph_destroy(&c_blockTree); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, blocks); SET_VECTOR_ELT(result, 1, cohesion); SET_VECTOR_ELT(result, 2, parent); SET_VECTOR_ELT(result, 3, blockTree); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("blocks")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("cohesion")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("parent")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("blockTree")); SET_NAMES(result, names); UNPROTECT(6); return result; } typedef struct { igraph_arpack_function_t *fun; } R_igraph_i_function_container_t; SEXP R_igraph_i_levc_arp(SEXP extP, SEXP extE, SEXP pv) { R_igraph_i_function_container_t *cont = R_ExternalPtrAddr(extP); igraph_arpack_function_t *fun= cont->fun; void *extra=R_ExternalPtrAddr(extE); SEXP res; PROTECT(res=NEW_NUMERIC(GET_LENGTH(pv))); fun(REAL(res), REAL(pv), GET_LENGTH(pv), extra); UNPROTECT(1); return res; } typedef struct R_igraph_i_levc_data_t { SEXP fun; SEXP extra; SEXP rho; SEXP rho2; } R_igraph_i_levc_data_t; int R_igraph_i_levc_callback(const igraph_vector_t *membership, long int comm, igraph_real_t eigenvalue, const igraph_vector_t *eigenvector, igraph_arpack_function_t *arpack_multiplier, void *arpack_extra, void *extra) { SEXP s_memb, s_comm, s_evalue, s_evector, s_multip; SEXP R_fcall, R_multip_call; SEXP res, l1, l2, l3; int result; R_igraph_i_levc_data_t *data=extra; R_igraph_i_function_container_t cont = { arpack_multiplier }; PROTECT(s_memb=R_igraph_vector_to_SEXP(membership)); PROTECT(s_comm=NEW_NUMERIC(1)); REAL(s_comm)[0]=comm; PROTECT(s_evalue=NEW_NUMERIC(1)); REAL(s_evalue)[0]=eigenvalue; PROTECT(s_evector=R_igraph_vector_to_SEXP(eigenvector)); PROTECT(l1 = install("igraph.i.levc.arp")); PROTECT(l2 = R_MakeExternalPtr((void*) &cont, R_NilValue, R_NilValue)); PROTECT(l3 = R_MakeExternalPtr(arpack_extra, R_NilValue, R_NilValue)); PROTECT(R_multip_call = lang3(l1, l2, l3)); PROTECT(s_multip = eval(R_multip_call, data->rho2)); PROTECT(R_fcall = R_igraph_i_lang7(data->fun, s_memb, s_comm, s_evalue, s_evector, s_multip, data->extra)); PROTECT(res = eval(R_fcall, data->rho)); result=(int) REAL(AS_NUMERIC(res))[0]; UNPROTECT(11); return result; } SEXP R_igraph_community_leading_eigenvector(SEXP graph, SEXP steps, SEXP weights, SEXP options, SEXP pstart, SEXP callback, SEXP callback_extra, SEXP callback_env, SEXP callback_env2) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_merges; igraph_vector_t c_membership; igraph_integer_t c_steps; igraph_vector_t v_weights, *pweights=0; igraph_bool_t c_start=!isNull(pstart); igraph_arpack_options_t c_options; igraph_real_t c_modularity; igraph_vector_t c_eigenvalues; igraph_vector_ptr_t c_eigenvectors; igraph_vector_t c_history; SEXP merges; SEXP membership; SEXP modularity; SEXP eigenvalues; SEXP eigenvectors; SEXP history; int c_result; SEXP result, names; R_igraph_i_levc_data_t callback_data = { callback, callback_extra, callback_env, callback_env2 }; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { pweights=&v_weights; R_SEXP_to_vector(weights, &v_weights); } if (0 != igraph_matrix_init(&c_merges, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_merges); if (c_start) { R_SEXP_to_vector_copy(pstart, &c_membership); } else { if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); c_steps=INTEGER(steps)[0]; R_SEXP_to_igraph_arpack_options(options, &c_options); if (0 != igraph_vector_init(&c_eigenvalues, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } if (0 != igraph_vector_ptr_init(&c_eigenvectors, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } if (0 != igraph_vector_init(&c_history, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } /* Call igraph */ c_result=igraph_community_leading_eigenvector(&c_graph, pweights, &c_merges, &c_membership, c_steps, &c_options, &c_modularity, c_start, &c_eigenvalues, &c_eigenvectors, &c_history, isNull(callback) ? 0 : R_igraph_i_levc_callback, &callback_data); /* Convert output */ PROTECT(result=NEW_LIST(7)); PROTECT(names=NEW_CHARACTER(7)); PROTECT(merges=R_igraph_matrix_to_SEXP(&c_merges)); igraph_matrix_destroy(&c_merges); IGRAPH_FINALLY_CLEAN(1); PROTECT(membership=R_igraph_vector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); PROTECT(modularity=NEW_NUMERIC(1)); REAL(modularity)[0]=c_modularity; PROTECT(eigenvalues=R_igraph_vector_to_SEXP(&c_eigenvalues)); igraph_vector_destroy(&c_eigenvalues); PROTECT(eigenvectors=R_igraph_vectorlist_to_SEXP(&c_eigenvectors)); R_igraph_vectorlist_destroy(&c_eigenvectors); PROTECT(history=R_igraph_vector_to_SEXP(&c_history)); igraph_vector_destroy(&c_history); SET_VECTOR_ELT(result, 0, merges); SET_VECTOR_ELT(result, 1, membership); SET_VECTOR_ELT(result, 2, options); SET_VECTOR_ELT(result, 3, modularity); SET_VECTOR_ELT(result, 4, eigenvalues); SET_VECTOR_ELT(result, 5, eigenvectors); SET_VECTOR_ELT(result, 6, history); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("merges")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("membership")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("modularity")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("eigenvalues")); SET_STRING_ELT(names, 5, CREATE_STRING_VECTOR("eigenvectors")); SET_STRING_ELT(names, 6, CREATE_STRING_VECTOR("history")); SET_NAMES(result, names); UNPROTECT(8); UNPROTECT(1); return(result); } SEXP R_igraph_get_eids(SEXP graph, SEXP pvp, SEXP pdirected, SEXP perror, SEXP pmulti) { igraph_t g; igraph_vector_t vp; igraph_vector_t res; igraph_bool_t directed=LOGICAL(pdirected)[0]; igraph_bool_t error=LOGICAL(perror)[0]; igraph_bool_t multi=LOGICAL(pmulti)[0]; SEXP result; R_SEXP_to_igraph(graph, &g); R_SEXP_to_vector(pvp, &vp); igraph_vector_init(&res, 0); if (multi) { igraph_get_eids_multi(&g, &res, /*pairs=*/ &vp, /*path=*/ 0, directed, error); } else { igraph_get_eids(&g, &res, /*pairs=*/ &vp, /*path=*/ 0, directed, error); } PROTECT(result=R_igraph_vector_to_SEXP(&res)); igraph_vector_destroy(&res); UNPROTECT(1); return result; } SEXP R_igraph_scg_semiprojectors(SEXP groups, SEXP matrix_type, SEXP p, SEXP norm, SEXP psparse) { /* Declarations */ igraph_vector_t c_groups; igraph_integer_t c_matrix_type; igraph_matrix_t c_L; igraph_matrix_t c_R; igraph_sparsemat_t c_Lsparse; igraph_sparsemat_t c_Rsparse; igraph_vector_t c_p; igraph_integer_t c_norm; SEXP L; SEXP R; SEXP Lsparse; SEXP Rsparse; igraph_bool_t sparse=LOGICAL(psparse)[0]; int c_result; SEXP result, names; /* Convert input */ R_SEXP_to_vector(groups, &c_groups); c_matrix_type=(igraph_integer_t) REAL(matrix_type)[0]; if (!sparse) { if (0 != igraph_matrix_init(&c_L, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_L); if (0 != igraph_matrix_init(&c_R, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_R); } else { /* Nothing to do, because igraph_scg_semiprojectors expect uninitialized sparse matrices */ } if (!isNull(p)) { R_SEXP_to_vector(p, &c_p); } c_norm=(igraph_integer_t) REAL(norm)[0]; /* Call igraph */ c_result=igraph_scg_semiprojectors(&c_groups, (igraph_scg_matrix_t) c_matrix_type, (sparse ? 0 : &c_L), (sparse ? 0 : &c_R), (sparse ? &c_Lsparse : 0), (sparse ? &c_Rsparse : 0), (isNull(p) ? 0 : &c_p), (igraph_scg_norm_t) c_norm); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); if (!sparse) { PROTECT(L=R_igraph_0ormatrix_to_SEXP(&c_L)); igraph_matrix_destroy(&c_L); IGRAPH_FINALLY_CLEAN(1); PROTECT(R=R_igraph_0ormatrix_to_SEXP(&c_R)); igraph_matrix_destroy(&c_R); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, L); SET_VECTOR_ELT(result, 1, R); } else { PROTECT(Lsparse=R_igraph_0orsparsemat_to_SEXP(&c_Lsparse)); igraph_sparsemat_destroy(&c_Lsparse); IGRAPH_FINALLY_CLEAN(1); PROTECT(Rsparse=R_igraph_0orsparsemat_to_SEXP(&c_Rsparse)); igraph_sparsemat_destroy(&c_Rsparse); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, Lsparse); SET_VECTOR_ELT(result, 1, Rsparse); } SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("L")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("R")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } SEXP R_igraph_laplacian(SEXP graph, SEXP normalized, SEXP weights, SEXP psparse) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_sparsemat_t c_sparseres; igraph_bool_t c_normalized; igraph_vector_t c_weights; igraph_bool_t c_sparse=LOGICAL(psparse)[0]; SEXP result; int c_result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!c_sparse) { if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); } if (c_sparse) { if (0 != igraph_sparsemat_init(&c_sparseres, 0, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_sparsemat_destroy, &c_sparseres); } c_normalized=LOGICAL(normalized)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ c_result=igraph_laplacian(&c_graph, (c_sparse ? 0 : &c_res), (c_sparse ? &c_sparseres : 0), c_normalized, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ if (!c_sparse) { PROTECT(result=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(result=R_igraph_sparsemat_to_SEXP(&c_sparseres)); igraph_sparsemat_destroy(&c_sparseres); IGRAPH_FINALLY_CLEAN(1); } UNPROTECT(1); return(result); } SEXP R_igraph_scg_adjacency(SEXP graph, SEXP matrix, SEXP sparsmat, SEXP ev, SEXP intervals_vector, SEXP algorithm, SEXP evec, SEXP groups, SEXP use_arpack, SEXP maxiter, SEXP sparse, SEXP output, SEXP semproj, SEXP epairs) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_matrix; igraph_sparsemat_t c_sparsmat; igraph_vector_t c_ev; igraph_vector_t c_intervals_vector; igraph_integer_t c_algorithm=(igraph_integer_t) REAL(algorithm)[0]; igraph_vector_t c_eval; igraph_matrix_t c_evec; igraph_vector_t c_groups; igraph_bool_t c_use_arpack=LOGICAL(use_arpack)[0]; igraph_integer_t c_maxiter=INTEGER(maxiter)[0]; igraph_bool_t c_sparse=LOGICAL(sparse)[0]; igraph_real_t c_output=REAL(output)[0]; igraph_bool_t c_semproj=LOGICAL(semproj)[0]; igraph_bool_t c_epairs=LOGICAL(epairs)[0]; igraph_t c_scg_graph; igraph_matrix_t c_scg_matrix; igraph_sparsemat_t c_scg_sparsemat; igraph_matrix_t c_L; igraph_matrix_t c_R; igraph_sparsemat_t c_Lsparse; igraph_sparsemat_t c_Rsparse; SEXP scg_graph; SEXP scg_matrix; SEXP scg_sparsemat; SEXP L; SEXP R; SEXP Lsparse; SEXP Rsparse; int c_result; SEXP result, names; SEXP eval; /* What to return */ igraph_bool_t do_scg_graph= (!isNull(graph) && c_output==1 /*default*/) || c_output==3 /*graph*/; igraph_bool_t do_scg_matrix=!c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_scg_sparsemat=c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_L=c_semproj && !c_sparse; igraph_bool_t do_R=c_semproj && !c_sparse; igraph_bool_t do_Lsparse=c_semproj && c_sparse; igraph_bool_t do_Rsparse=c_semproj && c_sparse; igraph_bool_t do_eval=c_epairs; igraph_bool_t do_evec=c_epairs; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } if (!isNull(matrix)) { R_SEXP_to_matrix(matrix, &c_matrix); } if (!isNull(sparsmat)) { R_SEXP_to_sparsemat(sparsmat, &c_sparsmat); } R_SEXP_to_vector(ev, &c_ev); R_SEXP_to_vector(intervals_vector, &c_intervals_vector); if (do_eval) { igraph_vector_init(&c_eval, 0); } if (!isNull(evec)) { R_SEXP_to_igraph_matrix_copy(evec, &c_evec); } else if (do_evec) { igraph_matrix_init(&c_evec, 0, 0); } if (!isNull(groups)) { R_SEXP_to_vector_copy(groups, &c_groups); } else { igraph_vector_init(&c_groups, 0); } if (do_scg_matrix) { igraph_matrix_init(&c_scg_matrix, 0, 0); } if (do_L) { igraph_matrix_init(&c_L, 0, 0); } if (do_R) { igraph_matrix_init(&c_R, 0, 0); } if (do_scg_sparsemat) { igraph_sparsemat_init(&c_scg_sparsemat, 0, 0, 0); } /* Call igraph */ c_result=igraph_scg_adjacency((isNull(graph) ? 0 : &c_graph), (isNull(matrix) ? 0 : &c_matrix), (isNull(sparsmat) ? 0 : &c_sparsmat), &c_ev, /*intervals=*/ 0, &c_intervals_vector, (igraph_scg_algorithm_t) c_algorithm, (do_eval ? &c_eval : 0), (!isNull(evec) || do_evec ? &c_evec : 0), &c_groups, c_use_arpack, c_maxiter, (do_scg_graph ? &c_scg_graph : 0), (do_scg_matrix ? &c_scg_matrix : 0), (do_scg_sparsemat ? &c_scg_sparsemat : 0), (do_L ? &c_L : 0), (do_R ? &c_R : 0), (do_Lsparse ? &c_Lsparse : 0), (do_Rsparse ? &c_Rsparse : 0)); if (!isNull(sparsmat)) { igraph_free(c_sparsmat.cs); } /* Convert output */ PROTECT(result=NEW_LIST(6)); PROTECT(names=NEW_CHARACTER(6)); if (do_eval) { eval=R_igraph_vector_to_SEXP(&c_eval); igraph_vector_destroy(&c_eval); } else { eval=R_NilValue; } PROTECT(eval); if (do_evec) { evec=R_igraph_matrix_to_SEXP(&c_evec); igraph_matrix_destroy(&c_evec); } else { evec=R_NilValue; } PROTECT(evec); PROTECT(groups=R_igraph_vector_to_SEXPp1(&c_groups)); igraph_vector_destroy(&c_groups); if (do_scg_graph) { PROTECT(scg_graph=R_igraph_to_SEXP(&c_scg_graph)); igraph_destroy(&c_scg_graph); UNPROTECT(1); } else { scg_graph=R_NilValue; } PROTECT(scg_graph); if (do_scg_matrix) { scg_matrix=R_igraph_matrix_to_SEXP(&c_scg_matrix); igraph_matrix_destroy(&c_scg_matrix); } else { scg_matrix=R_NilValue; } PROTECT(scg_matrix); if (do_scg_sparsemat) { scg_sparsemat=R_igraph_sparsemat_to_SEXP(&c_scg_sparsemat); igraph_sparsemat_destroy(&c_scg_sparsemat); } else { scg_sparsemat=R_NilValue; } PROTECT(scg_sparsemat); if (do_L) { L=R_igraph_matrix_to_SEXP(&c_L); igraph_matrix_destroy(&c_L); } else { L=R_NilValue; } PROTECT(L); if (do_R) { R=R_igraph_matrix_to_SEXP(&c_R); igraph_matrix_destroy(&c_R); } else { R=R_NilValue; } PROTECT(R); if (do_Lsparse) { Lsparse=R_igraph_sparsemat_to_SEXP(&c_Lsparse); igraph_sparsemat_destroy(&c_Lsparse); } else { Lsparse=R_NilValue; } PROTECT(Lsparse); if (do_Rsparse) { Rsparse=R_igraph_sparsemat_to_SEXP(&c_Rsparse); igraph_sparsemat_destroy(&c_Rsparse); } else { Rsparse=R_NilValue; } PROTECT(Rsparse); if (do_scg_graph) { SET_VECTOR_ELT(result, 0, scg_graph); } if (do_scg_matrix) { SET_VECTOR_ELT(result, 0, scg_matrix); } if (do_scg_sparsemat) { SET_VECTOR_ELT(result, 0, scg_sparsemat); } SET_VECTOR_ELT(result, 1, groups); if (do_L) { SET_VECTOR_ELT(result, 2, L); } if (do_Lsparse) { SET_VECTOR_ELT(result, 2, Lsparse); } if (do_R) { SET_VECTOR_ELT(result, 3, R); } if (do_Rsparse) { SET_VECTOR_ELT(result, 3, Rsparse); } SET_VECTOR_ELT(result, 4, eval); SET_VECTOR_ELT(result, 5, evec); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("Xt")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("groups")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("L")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("R")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("values")); SET_STRING_ELT(names, 5, CREATE_STRING_VECTOR("vectors")); SET_NAMES(result, names); UNPROTECT(12); return(result); } SEXP R_igraph_scg_stochastic(SEXP graph, SEXP matrix, SEXP sparsmat, SEXP ev, SEXP intervals_vector, SEXP algorithm, SEXP norm, SEXP evec, SEXP groups, SEXP p, SEXP use_arpack, SEXP maxiter, SEXP sparse, SEXP output, SEXP semproj, SEXP epairs, SEXP stat_prob) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_matrix; igraph_sparsemat_t c_sparsmat; igraph_vector_t c_ev; igraph_vector_t c_intervals_vector; igraph_integer_t c_algorithm=(igraph_integer_t) REAL(algorithm)[0]; igraph_integer_t c_norm=(igraph_integer_t) REAL(norm)[0]; igraph_vector_complex_t c_eval; igraph_matrix_complex_t c_evec; igraph_vector_t c_groups; igraph_vector_t c_p; igraph_bool_t c_use_arpack=LOGICAL(use_arpack)[0]; igraph_integer_t c_maxiter=INTEGER(maxiter)[0]; igraph_bool_t c_sparse=LOGICAL(sparse)[0]; igraph_real_t c_output=REAL(output)[0]; igraph_bool_t c_semproj=LOGICAL(semproj)[0]; igraph_bool_t c_epairs=LOGICAL(epairs)[0]; igraph_bool_t c_stat_prob=LOGICAL(stat_prob)[0]; igraph_t c_scg_graph; igraph_matrix_t c_scg_matrix; igraph_sparsemat_t c_scg_sparsemat; igraph_matrix_t c_L; igraph_matrix_t c_R; igraph_sparsemat_t c_Lsparse; igraph_sparsemat_t c_Rsparse; SEXP scg_graph; SEXP scg_matrix; SEXP scg_sparsemat; SEXP L; SEXP R; SEXP Lsparse; SEXP Rsparse; int c_result; SEXP result, names; SEXP eval; /* What to return */ igraph_bool_t do_scg_graph= (!isNull(graph) && c_output==1 /*default*/) || c_output==3 /*graph*/; igraph_bool_t do_scg_matrix=!c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_scg_sparsemat=c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_L=c_semproj && !c_sparse; igraph_bool_t do_R=c_semproj && !c_sparse; igraph_bool_t do_Lsparse=c_semproj && c_sparse; igraph_bool_t do_Rsparse=c_semproj && c_sparse; igraph_bool_t do_eval=c_epairs; igraph_bool_t do_evec=c_epairs; igraph_bool_t do_p=c_stat_prob; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } if (!isNull(matrix)) { R_SEXP_to_matrix(matrix, &c_matrix); } if (!isNull(sparsmat)) { R_SEXP_to_sparsemat(sparsmat, &c_sparsmat); } R_SEXP_to_vector(ev, &c_ev); R_SEXP_to_vector(intervals_vector, &c_intervals_vector); if (do_eval) { igraph_vector_complex_init(&c_eval, 0); } if (!isNull(evec)) { R_SEXP_to_matrix_complex_copy(evec, &c_evec); } else if (do_evec) { igraph_matrix_complex_init(&c_evec, 0, 0); } if (!isNull(groups)) { R_SEXP_to_vector_copy(groups, &c_groups); } else { igraph_vector_init(&c_groups, 0); } if (!isNull(p)) { R_SEXP_to_vector_copy(p, &c_p); } else if (do_p) { igraph_vector_init(&c_p, 0); } if (do_scg_matrix) { igraph_matrix_init(&c_scg_matrix, 0, 0); } if (do_L) { igraph_matrix_init(&c_L, 0, 0); } if (do_R) { igraph_matrix_init(&c_R, 0, 0); } /* Call igraph */ c_result=igraph_scg_stochastic((isNull(graph) ? 0 : &c_graph), (isNull(matrix) ? 0 : &c_matrix), (isNull(sparsmat) ? 0 : &c_sparsmat), &c_ev, /*intervals=*/ 0, &c_intervals_vector, (igraph_scg_algorithm_t) c_algorithm, (igraph_scg_norm_t) c_norm, (do_eval ? &c_eval : 0), (!isNull(evec) || do_evec ? &c_evec : 0), &c_groups, (!isNull(p) || do_p ? &c_p : 0), c_use_arpack, c_maxiter, (do_scg_graph ? &c_scg_graph : 0), (do_scg_matrix ? &c_scg_matrix : 0), (do_scg_sparsemat ? &c_scg_sparsemat : 0), (do_L ? &c_L : 0), (do_R ? &c_R : 0), (do_Lsparse ? &c_Lsparse : 0), (do_Rsparse ? &c_Rsparse : 0)); if (!isNull(sparsmat)) { igraph_free(c_sparsmat.cs); } /* Convert output */ PROTECT(result=NEW_LIST(7)); PROTECT(names=NEW_CHARACTER(7)); if (do_eval) { PROTECT(eval=R_igraph_vector_complex_to_SEXP(&c_eval)); igraph_vector_complex_destroy(&c_eval); } else { PROTECT(eval=R_NilValue); } if (do_evec) { PROTECT(evec=R_igraph_matrix_complex_to_SEXP(&c_evec)); igraph_matrix_complex_destroy(&c_evec); } else { PROTECT(evec=R_NilValue); } if (do_p) { PROTECT(p=R_igraph_vector_to_SEXP(&c_p)); igraph_vector_destroy(&c_p); } else { PROTECT(p=R_NilValue); } PROTECT(groups=R_igraph_vector_to_SEXPp1(&c_groups)); igraph_vector_destroy(&c_groups); if (do_scg_graph) { PROTECT(scg_graph=R_igraph_to_SEXP(&c_scg_graph)); igraph_destroy(&c_scg_graph); } else { PROTECT(scg_graph=R_NilValue); } if (do_scg_matrix) { PROTECT(scg_matrix=R_igraph_matrix_to_SEXP(&c_scg_matrix)); igraph_matrix_destroy(&c_scg_matrix); } else { PROTECT(scg_matrix=R_NilValue); } if (do_scg_sparsemat) { PROTECT(scg_sparsemat=R_igraph_sparsemat_to_SEXP(&c_scg_sparsemat)); igraph_sparsemat_destroy(&c_scg_sparsemat); } else { PROTECT(scg_sparsemat=R_NilValue); } if (do_L) { PROTECT(L=R_igraph_matrix_to_SEXP(&c_L)); igraph_matrix_destroy(&c_L); } else { PROTECT(L=R_NilValue); } if (do_R) { PROTECT(R=R_igraph_matrix_to_SEXP(&c_R)); igraph_matrix_destroy(&c_R); } else { PROTECT(R=R_NilValue); } if (do_Lsparse) { PROTECT(Lsparse=R_igraph_sparsemat_to_SEXP(&c_Lsparse)); igraph_sparsemat_destroy(&c_Lsparse); } else { PROTECT(Lsparse=R_NilValue); } if (do_Rsparse) { PROTECT(Rsparse=R_igraph_sparsemat_to_SEXP(&c_Rsparse)); igraph_sparsemat_destroy(&c_Rsparse); } else { PROTECT(Rsparse=R_NilValue); } if (do_scg_graph) { SET_VECTOR_ELT(result, 0, scg_graph); } if (do_scg_matrix) { SET_VECTOR_ELT(result, 0, scg_matrix); } if (do_scg_sparsemat) { SET_VECTOR_ELT(result, 0, scg_sparsemat); } SET_VECTOR_ELT(result, 1, groups); if (do_L) { SET_VECTOR_ELT(result, 2, L); } if (do_Lsparse) { SET_VECTOR_ELT(result, 2, Lsparse); } if (do_R) { SET_VECTOR_ELT(result, 3, R); } if (do_Rsparse) { SET_VECTOR_ELT(result, 3, Rsparse); } SET_VECTOR_ELT(result, 4, eval); SET_VECTOR_ELT(result, 5, evec); if (do_p) { SET_VECTOR_ELT(result, 6, p); } SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("Xt")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("groups")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("L")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("R")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("values")); SET_STRING_ELT(names, 5, CREATE_STRING_VECTOR("vectors")); SET_STRING_ELT(names, 6, CREATE_STRING_VECTOR("p")); SET_NAMES(result, names); UNPROTECT(12); UNPROTECT(1); return(result); } SEXP R_igraph_scg_laplacian(SEXP graph, SEXP matrix, SEXP sparsmat, SEXP ev, SEXP intervals_vector, SEXP algorithm, SEXP norm, SEXP direction, SEXP evec, SEXP groups, SEXP use_arpack, SEXP maxiter, SEXP sparse, SEXP output, SEXP semproj, SEXP epairs) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_matrix; igraph_sparsemat_t c_sparsmat; igraph_vector_t c_ev; igraph_vector_t c_intervals_vector; igraph_integer_t c_algorithm=(igraph_integer_t) REAL(algorithm)[0]; igraph_integer_t c_norm=(igraph_integer_t) REAL(norm)[0]; igraph_integer_t c_direction=(igraph_integer_t) REAL(direction)[0]; igraph_vector_complex_t c_eval; igraph_matrix_complex_t c_evec; igraph_vector_t c_groups; igraph_bool_t c_use_arpack=LOGICAL(use_arpack)[0]; igraph_integer_t c_maxiter=INTEGER(maxiter)[0]; igraph_bool_t c_sparse=LOGICAL(sparse)[0]; igraph_real_t c_output=REAL(output)[0]; igraph_bool_t c_semproj=LOGICAL(semproj)[0]; igraph_bool_t c_epairs=LOGICAL(epairs)[0]; igraph_t c_scg_graph; igraph_matrix_t c_scg_matrix; igraph_sparsemat_t c_scg_sparsemat; igraph_matrix_t c_L; igraph_matrix_t c_R; igraph_sparsemat_t c_Lsparse; igraph_sparsemat_t c_Rsparse; SEXP eval; SEXP scg_graph; SEXP scg_matrix; SEXP scg_sparsemat; SEXP L; SEXP R; SEXP Lsparse; SEXP Rsparse; int c_result; SEXP result, names; /* What to return */ igraph_bool_t do_scg_graph= (!isNull(graph) && c_output==1 /*default*/) || c_output==3 /*graph*/; igraph_bool_t do_scg_matrix=!c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_scg_sparsemat=c_sparse && ((isNull(graph) && c_output==1 /*default*/) || c_output==2 /*matrix*/); igraph_bool_t do_L=c_semproj && !c_sparse; igraph_bool_t do_R=c_semproj && !c_sparse; igraph_bool_t do_Lsparse=c_semproj && c_sparse; igraph_bool_t do_Rsparse=c_semproj && c_sparse; igraph_bool_t do_eval=c_epairs; igraph_bool_t do_evec=c_epairs; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } if (!isNull(matrix)) { R_SEXP_to_matrix(matrix, &c_matrix); } if (!isNull(sparsmat)) { R_SEXP_to_sparsemat(sparsmat, &c_sparsmat); } R_SEXP_to_vector(ev, &c_ev); R_SEXP_to_vector(intervals_vector, &c_intervals_vector); if (do_eval) { igraph_vector_complex_init(&c_eval, 0); } if (!isNull(evec)) { R_SEXP_to_matrix_complex_copy(evec, &c_evec); } else if (do_evec) { igraph_matrix_complex_init(&c_evec, 0, 0); } if (!isNull(groups)) { R_SEXP_to_vector_copy(groups, &c_groups); } else { igraph_vector_init(&c_groups, 0); } if (do_scg_matrix) { igraph_matrix_init(&c_scg_matrix, 0, 0); } if (do_L) { igraph_matrix_init(&c_L, 0, 0); } if (do_R) { igraph_matrix_init(&c_R, 0, 0); } /* Call igraph */ c_result=igraph_scg_laplacian((isNull(graph) ? 0 : &c_graph), (isNull(matrix) ? 0 : &c_matrix), (isNull(sparsmat) ? 0 : &c_sparsmat), &c_ev, /*intervals=*/ 0, &c_intervals_vector, (igraph_scg_algorithm_t) c_algorithm, (igraph_scg_norm_t) c_norm, (igraph_scg_direction_t) c_direction, (do_eval ? &c_eval : 0), (!isNull(evec) || do_evec ? &c_evec : 0), &c_groups, c_use_arpack, c_maxiter, (do_scg_graph ? &c_scg_graph : 0), (do_scg_matrix ? &c_scg_matrix : 0), (do_scg_sparsemat ? &c_scg_sparsemat : 0), (do_L ? &c_L : 0), (do_R ? &c_R : 0), (do_Lsparse ? &c_Lsparse : 0), (do_Rsparse ? &c_Rsparse : 0)); if (!isNull(sparsmat)) { igraph_free(c_sparsmat.cs); } /* Convert output */ PROTECT(result=NEW_LIST(6)); PROTECT(names=NEW_CHARACTER(6)); if (do_eval) { PROTECT(eval=R_igraph_vector_complex_to_SEXP(&c_eval)); igraph_vector_complex_destroy(&c_eval); } else { PROTECT(eval=R_NilValue); } if (do_evec) { PROTECT(evec=R_igraph_matrix_complex_to_SEXP(&c_evec)); igraph_matrix_complex_destroy(&c_evec); } else { PROTECT(evec=R_NilValue); } PROTECT(groups=R_igraph_vector_to_SEXPp1(&c_groups)); igraph_vector_destroy(&c_groups); if (do_scg_graph) { PROTECT(scg_graph=R_igraph_to_SEXP(&c_scg_graph)); igraph_destroy(&c_scg_graph); } else { PROTECT(scg_graph=R_NilValue); } if (do_scg_matrix) { PROTECT(scg_matrix=R_igraph_matrix_to_SEXP(&c_scg_matrix)); igraph_matrix_destroy(&c_scg_matrix); } else { PROTECT(scg_matrix=R_NilValue); } if (do_scg_sparsemat) { PROTECT(scg_sparsemat=R_igraph_sparsemat_to_SEXP(&c_scg_sparsemat)); igraph_sparsemat_destroy(&c_scg_sparsemat); } else { PROTECT(scg_sparsemat=R_NilValue); } if (do_L) { PROTECT(L=R_igraph_matrix_to_SEXP(&c_L)); igraph_matrix_destroy(&c_L); } else { PROTECT(L=R_NilValue); } if (do_R) { PROTECT(R=R_igraph_matrix_to_SEXP(&c_R)); igraph_matrix_destroy(&c_R); } else { PROTECT(R=R_NilValue); } if (do_Lsparse) { PROTECT(Lsparse=R_igraph_sparsemat_to_SEXP(&c_Lsparse)); igraph_sparsemat_destroy(&c_Lsparse); } else { PROTECT(Lsparse=R_NilValue); } if (do_Rsparse) { PROTECT(Rsparse=R_igraph_sparsemat_to_SEXP(&c_Rsparse)); igraph_sparsemat_destroy(&c_Rsparse); } else { PROTECT(Rsparse=R_NilValue); } if (do_scg_graph) { SET_VECTOR_ELT(result, 0, scg_graph); } if (do_scg_matrix) { SET_VECTOR_ELT(result, 0, scg_matrix); } if (do_scg_sparsemat) { SET_VECTOR_ELT(result, 0, scg_sparsemat); } SET_VECTOR_ELT(result, 1, groups); if (do_L) { SET_VECTOR_ELT(result, 2, L); } if (do_Lsparse) { SET_VECTOR_ELT(result, 2, Lsparse); } if (do_R) { SET_VECTOR_ELT(result, 3, R); } if (do_Rsparse) { SET_VECTOR_ELT(result, 3, Rsparse); } SET_VECTOR_ELT(result, 4, eval); SET_VECTOR_ELT(result, 5, evec); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("Xt")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("groups")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("L")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("R")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("values")); SET_STRING_ELT(names, 5, CREATE_STRING_VECTOR("vectors")); SET_NAMES(result, names); UNPROTECT(11); UNPROTECT(1); return(result); } SEXP R_igraph_subisomorphic_lad(SEXP pattern, SEXP target, SEXP domains, SEXP induced, SEXP time_limit, SEXP pqmap, SEXP pqall_maps) { /* Declarations */ igraph_t c_pattern; igraph_t c_target; igraph_vector_ptr_t c_domains; igraph_bool_t c_iso; igraph_vector_t c_map; igraph_vector_ptr_t c_maps; igraph_bool_t c_induced; int c_time_limit; igraph_bool_t c_qmap; igraph_bool_t c_qall_maps; SEXP iso; SEXP map; SEXP maps; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(pattern, &c_pattern); R_SEXP_to_igraph(target, &c_target); R_igraph_SEXP_to_0orvectorlist(domains, &c_domains); c_qmap=LOGICAL(pqmap)[0]; c_qall_maps=LOGICAL(pqall_maps)[0]; if (c_qmap) { if (0 != igraph_vector_init(&c_map, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map); map=R_GlobalEnv; /* hack to have a non-NULL value */ } else { map=R_NilValue; } if (c_qall_maps) { if (0 != igraph_vector_ptr_init(&c_maps, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_maps); maps=R_GlobalEnv; /* hack to have a non-NULL value */ } else { maps=R_NilValue; } c_induced=LOGICAL(induced)[0]; c_time_limit=INTEGER(time_limit)[0]; /* Call igraph */ igraph_subisomorphic_lad(&c_pattern, &c_target, (isNull(domains) ? 0 : &c_domains), &c_iso, (isNull(map) ? 0 : &c_map), (isNull(maps) ? 0 : &c_maps), c_induced, c_time_limit); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; if (!isNull(map)) { PROTECT(map=R_igraph_0orvector_to_SEXP(&c_map)); igraph_vector_destroy(&c_map); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(map=R_NilValue); } if (!isNull(maps)) { PROTECT(maps=R_igraph_0orvectorlist_to_SEXP(&c_maps)); R_igraph_vectorlist_destroy(&c_maps); } else { PROTECT(maps=R_NilValue); } IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, iso); SET_VECTOR_ELT(result, 1, map); SET_VECTOR_ELT(result, 2, maps); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("iso")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("map")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("maps")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_graphlets / /-------------------------------------------*/ SEXP R_igraph_graphlets(SEXP graph, SEXP weights, SEXP niter) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_weights; igraph_vector_ptr_t c_cliques; igraph_vector_t c_Mu; int c_niter; SEXP cliques; SEXP Mu; SEXP result, names; R_PreserveObject(R_igraph_attribute_protected=NEW_LIST(100)); R_igraph_attribute_protected_size=0; IGRAPH_FINALLY(R_igraph_attribute_protected_destroy, 0); /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (0 != igraph_vector_ptr_init(&c_cliques, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_cliques); if (0 != igraph_vector_init(&c_Mu, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_Mu); c_niter=INTEGER(niter)[0]; /* Call igraph */ igraph_graphlets(&c_graph, (isNull(weights) ? 0 : &c_weights), &c_cliques, &c_Mu, c_niter); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(cliques=R_igraph_vectorlist_to_SEXP_p1(&c_cliques)); R_igraph_vectorlist_destroy(&c_cliques); IGRAPH_FINALLY_CLEAN(1); PROTECT(Mu=R_igraph_vector_to_SEXP(&c_Mu)); igraph_vector_destroy(&c_Mu); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, cliques); SET_VECTOR_ELT(result, 1, Mu); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("cliques")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("Mu")); SET_NAMES(result, names); UNPROTECT(4); IGRAPH_FINALLY_CLEAN(1); R_igraph_attribute_protected_destroy(0); return(result); } /*-------------------------------------------/ / igraph_graphlets_candidate_basis / /-------------------------------------------*/ SEXP R_igraph_graphlets_candidate_basis(SEXP graph, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_weights; igraph_vector_ptr_t c_cliques; igraph_vector_t c_thresholds; SEXP cliques; SEXP thresholds; SEXP result, names; R_PreserveObject(R_igraph_attribute_protected=NEW_LIST(100)); R_igraph_attribute_protected_size=0; IGRAPH_FINALLY(R_igraph_attribute_protected_destroy, 0); /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (0 != igraph_vector_ptr_init(&c_cliques, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_cliques); if (0 != igraph_vector_init(&c_thresholds, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_thresholds); /* Call igraph */ igraph_graphlets_candidate_basis(&c_graph, (isNull(weights) ? 0 : &c_weights), &c_cliques, &c_thresholds); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(cliques=R_igraph_vectorlist_to_SEXP_p1(&c_cliques)); R_igraph_vectorlist_destroy(&c_cliques); IGRAPH_FINALLY_CLEAN(1); PROTECT(thresholds=R_igraph_vector_to_SEXP(&c_thresholds)); igraph_vector_destroy(&c_thresholds); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, cliques); SET_VECTOR_ELT(result, 1, thresholds); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("cliques")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("thresholds")); SET_NAMES(result, names); UNPROTECT(4); IGRAPH_FINALLY_CLEAN(1); R_igraph_attribute_protected_destroy(0); return(result); } int igraph_i_graphlets_project(const igraph_t *graph, const igraph_vector_t *weights, const igraph_vector_ptr_t *cliques, igraph_vector_t *Mu, igraph_bool_t startMu, int niter, int vid1); /*-------------------------------------------/ / igraph_graphlets_project / /-------------------------------------------*/ SEXP R_igraph_graphlets_project(SEXP graph, SEXP weights, SEXP cliques, SEXP Mu, SEXP niter) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_weights; igraph_vector_ptr_t c_cliques; igraph_vector_t c_Mu; int c_niter; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(cliques)) { R_igraph_SEXP_to_vectorlist(cliques, &c_cliques); } if (0 != R_SEXP_to_vector_copy(Mu, &c_Mu)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_Mu); c_niter=INTEGER(niter)[0]; /* Call igraph */ igraph_i_graphlets_project(&c_graph, (isNull(weights) ? 0 : &c_weights), &c_cliques, &c_Mu, /*startMu=*/ 1, c_niter, /*vid1=*/ 1); /* Convert output */ PROTECT(Mu=R_igraph_vector_to_SEXP(&c_Mu)); igraph_vector_destroy(&c_Mu); IGRAPH_FINALLY_CLEAN(1); result=Mu; UNPROTECT(1); return(result); } SEXP R_igraph_adjacency_spectral_embedding(SEXP graph, SEXP no, SEXP pweights, SEXP pwhich, SEXP scaled, SEXP cvec, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_vector_t weights; igraph_eigen_which_position_t c_which; igraph_integer_t c_no; igraph_bool_t c_scaled; igraph_matrix_t c_X; igraph_matrix_t c_Y; igraph_vector_t c_D; igraph_vector_t c_cvec; igraph_arpack_options_t c_options; SEXP X; SEXP Y; SEXP D; igraph_bool_t directed; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); directed=igraph_is_directed(&c_graph); if (!isNull(pweights)) { R_SEXP_to_vector(pweights, &weights); } c_which=INTEGER(pwhich)[0]; c_no=INTEGER(no)[0]; c_scaled=LOGICAL(scaled)[0]; if (0 != igraph_matrix_init(&c_X, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_X); if (directed) { if (0 != igraph_matrix_init(&c_Y, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_Y); } if (0 != igraph_vector_init(&c_D, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_D); R_SEXP_to_vector(cvec, &c_cvec); R_SEXP_to_igraph_arpack_options(options, &c_options); /* Call igraph */ igraph_adjacency_spectral_embedding(&c_graph, c_no, isNull(pweights) ? 0 : &weights, c_which, c_scaled, &c_X, directed ? &c_Y : 0, &c_D, &c_cvec, &c_options); /* Convert output */ PROTECT(result=NEW_LIST(4)); PROTECT(names=NEW_CHARACTER(4)); PROTECT(X=R_igraph_matrix_to_SEXP(&c_X)); igraph_matrix_destroy(&c_X); IGRAPH_FINALLY_CLEAN(1); if (directed) { PROTECT(Y=R_igraph_matrix_to_SEXP(&c_Y)); igraph_matrix_destroy(&c_Y); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(Y=R_NilValue); } PROTECT(D=R_igraph_vector_to_SEXP(&c_D)); igraph_vector_destroy(&c_D); IGRAPH_FINALLY_CLEAN(1); PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); SET_VECTOR_ELT(result, 0, X); SET_VECTOR_ELT(result, 1, Y); SET_VECTOR_ELT(result, 2, D); SET_VECTOR_ELT(result, 3, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("X")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("Y")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("D")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(5); UNPROTECT(1); return(result); } SEXP R_igraph_laplacian_spectral_embedding(SEXP graph, SEXP no, SEXP weights, SEXP which, SEXP degmode, SEXP type, SEXP scaled, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_no; igraph_vector_t c_weights; igraph_eigen_which_position_t c_which; igraph_neimode_t c_degmode; igraph_laplacian_spectral_embedding_type_t c_type; igraph_bool_t c_scaled; igraph_matrix_t c_X; igraph_matrix_t c_Y; igraph_vector_t c_D; igraph_arpack_options_t c_options; SEXP X; SEXP Y; SEXP D; igraph_bool_t directed; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); directed=igraph_is_directed(&c_graph); c_no=INTEGER(no)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_which=INTEGER(which)[0]; c_degmode=(igraph_neimode_t) REAL(degmode)[0]; c_type=(igraph_laplacian_spectral_embedding_type_t) INTEGER(type)[0]; c_scaled=LOGICAL(scaled)[0]; if (0 != igraph_matrix_init(&c_X, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_X); if (directed) { if (0 != igraph_matrix_init(&c_Y, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_Y); } if (0 != igraph_vector_init(&c_D, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_D); R_SEXP_to_igraph_arpack_options(options, &c_options); /* Call igraph */ igraph_laplacian_spectral_embedding(&c_graph, c_no, (isNull(weights) ? 0 : &c_weights), c_which, c_degmode, c_type, c_scaled, &c_X, directed ? &c_Y : 0, &c_D, &c_options); /* Convert output */ PROTECT(result=NEW_LIST(4)); PROTECT(names=NEW_CHARACTER(4)); PROTECT(X=R_igraph_matrix_to_SEXP(&c_X)); igraph_matrix_destroy(&c_X); IGRAPH_FINALLY_CLEAN(1); if (directed) { PROTECT(Y=R_igraph_matrix_to_SEXP(&c_Y)); igraph_matrix_destroy(&c_Y); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(Y=R_NilValue); } PROTECT(D=R_igraph_0orvector_to_SEXP(&c_D)); igraph_vector_destroy(&c_D); IGRAPH_FINALLY_CLEAN(1); PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); SET_VECTOR_ELT(result, 0, X); SET_VECTOR_ELT(result, 1, Y); SET_VECTOR_ELT(result, 2, D); SET_VECTOR_ELT(result, 3, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("X")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("Y")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("D")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(5); UNPROTECT(1); return(result); } SEXP R_igraph_simple_interconnected_islands_game(SEXP islands_n, SEXP islands_size, SEXP islands_pin, SEXP n_inter) { igraph_t g; igraph_integer_t a=INTEGER(islands_n)[0]; igraph_integer_t b=INTEGER(islands_size)[0]; igraph_real_t c=REAL(islands_pin)[0]; igraph_integer_t d=INTEGER(n_inter)[0]; SEXP result; igraph_simple_interconnected_islands_game(&g, a, b, c, d); PROTECT(result=R_igraph_to_SEXP(&g)); igraph_destroy(&g); UNPROTECT(1); return result; } SEXP R_igraph_version() { const char *version; SEXP result; igraph_version(&version, /*major=*/ 0, /*minor=*/ 0, /*patch=*/ 0); PROTECT(result=NEW_CHARACTER(1)); SET_STRING_ELT(result, 0, mkChar(version)); UNPROTECT(1); return result; } SEXP R_igraph_bipartite_projection(SEXP graph, SEXP types, SEXP probe1, SEXP pwhich) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_t c_proj1; igraph_t c_proj2; igraph_vector_t c_multiplicity1; igraph_vector_t c_multiplicity2; igraph_integer_t c_probe1; igraph_integer_t which=INTEGER(pwhich)[0]; igraph_bool_t do_1=(which == 0 || which == 1); igraph_bool_t do_2=(which == 0 || which == 2); SEXP proj1; SEXP proj2; SEXP multiplicity1; SEXP multiplicity2; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } if (0 != igraph_vector_init(&c_multiplicity1, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_multiplicity1); multiplicity1 = R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_multiplicity2, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_multiplicity2); multiplicity2=R_GlobalEnv; /* hack to have a non-NULL value */ c_probe1=INTEGER(probe1)[0]; /* Call igraph */ igraph_bipartite_projection(&c_graph, (isNull(types) ? 0 : &c_types), do_1 ? &c_proj1 : 0, do_2 ? &c_proj2 : 0, (isNull(multiplicity1) ? 0 : &c_multiplicity1), (isNull(multiplicity2) ? 0 : &c_multiplicity2), c_probe1); /* Convert output */ PROTECT(result=NEW_LIST(4)); PROTECT(names=NEW_CHARACTER(4)); if (do_1) { IGRAPH_FINALLY(igraph_destroy, &c_proj1); PROTECT(proj1=R_igraph_to_SEXP(&c_proj1)); igraph_destroy(&c_proj1); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(proj1=R_NilValue); } if (do_2) { IGRAPH_FINALLY(igraph_destroy, &c_proj2); PROTECT(proj2=R_igraph_to_SEXP(&c_proj2)); igraph_destroy(&c_proj2); IGRAPH_FINALLY_CLEAN(1); } else { PROTECT(proj2=R_NilValue); } PROTECT(multiplicity1=R_igraph_0orvector_to_SEXP(&c_multiplicity1)); igraph_vector_destroy(&c_multiplicity1); IGRAPH_FINALLY_CLEAN(1); PROTECT(multiplicity2=R_igraph_0orvector_to_SEXP(&c_multiplicity2)); igraph_vector_destroy(&c_multiplicity2); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, proj1); SET_VECTOR_ELT(result, 1, proj2); SET_VECTOR_ELT(result, 2, multiplicity1); SET_VECTOR_ELT(result, 3, multiplicity2); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("proj1")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("proj2")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("multiplicity1")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("multiplicity2")); SET_NAMES(result, names); UNPROTECT(5); UNPROTECT(1); return(result); } SEXP R_igraph_solve_lsap(SEXP px, SEXP pnc) { igraph_matrix_t x; igraph_integer_t nc = INTEGER(pnc)[0]; igraph_vector_int_t p; SEXP result; R_SEXP_to_matrix(px, &x); igraph_vector_int_init(&p, nc); IGRAPH_FINALLY(igraph_vector_int_destroy, &p); igraph_solve_lsap(&x, nc, &p); PROTECT(result = R_igraph_vector_int_to_SEXP(&p)); igraph_vector_int_destroy(&p); IGRAPH_FINALLY_CLEAN(1); UNPROTECT(1); return result; } SEXP R_igraph_adjacent_vertices(SEXP pgraph, SEXP pv, SEXP pmode) { igraph_t graph; igraph_vs_t vs; igraph_vit_t vit; igraph_integer_t mode = (igraph_integer_t) REAL(pmode)[0]; SEXP result; size_t i, n; igraph_lazy_adjlist_t adjlist; R_SEXP_to_igraph(pgraph, &graph); R_SEXP_to_igraph_vs(pv, &graph, &vs); IGRAPH_FINALLY(igraph_vs_destroy, &vs); igraph_vit_create(&graph, vs, &vit); IGRAPH_FINALLY(igraph_vit_destroy, &vit); n = IGRAPH_VIT_SIZE(vit); igraph_lazy_adjlist_init(&graph, &adjlist, mode, /* simplify= */ 0); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); PROTECT(result = NEW_LIST(n)); for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid = IGRAPH_VIT_GET(vit); igraph_vector_t *neis = igraph_lazy_adjlist_get(&adjlist, vid); SET_VECTOR_ELT(result, i, R_igraph_vector_to_SEXP(neis)); } igraph_lazy_adjlist_destroy(&adjlist); igraph_vit_destroy(&vit); igraph_vs_destroy(&vs); IGRAPH_FINALLY_CLEAN(3); UNPROTECT(1); return result; } SEXP R_igraph_incident_edges(SEXP pgraph, SEXP pe, SEXP pmode) { igraph_t graph; igraph_vs_t vs; igraph_vit_t vit; igraph_integer_t mode = (igraph_integer_t) REAL(pmode)[0]; SEXP result; size_t i, n; igraph_lazy_inclist_t adjlist; R_SEXP_to_igraph(pgraph, &graph); R_SEXP_to_igraph_vs(pe, &graph, &vs); IGRAPH_FINALLY(igraph_vs_destroy, &vs); igraph_vit_create(&graph, vs, &vit); IGRAPH_FINALLY(igraph_vit_destroy, &vit); n = IGRAPH_VIT_SIZE(vit); igraph_lazy_inclist_init(&graph, &adjlist, mode); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &adjlist); PROTECT(result = NEW_LIST(n)); for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int eid = IGRAPH_VIT_GET(vit); igraph_vector_t *neis = igraph_lazy_inclist_get(&adjlist, eid); SET_VECTOR_ELT(result, i, R_igraph_vector_to_SEXP(neis)); } igraph_lazy_inclist_destroy(&adjlist); igraph_vit_destroy(&vit); igraph_vs_destroy(&vs); IGRAPH_FINALLY_CLEAN(3); UNPROTECT(1); return result; } /***********************************************/ /* THE REST IS GENERATED BY inger.py */ /***********************************************/ /*-------------------------------------------/ / igraph_empty / /-------------------------------------------*/ SEXP R_igraph_empty(SEXP n, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_empty(&c_graph, c_n, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_vcount / /-------------------------------------------*/ SEXP R_igraph_vcount(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_result; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ c_result= igraph_vcount(&c_graph); /* Convert output */ PROTECT(result=NEW_INTEGER(1)); INTEGER(result)[0]=c_result; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_full_citation / /-------------------------------------------*/ SEXP R_igraph_full_citation(SEXP n, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_full_citation(&c_graph, c_n, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_lcf_vector / /-------------------------------------------*/ SEXP R_igraph_lcf_vector(SEXP n, SEXP shifts, SEXP repeats) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_vector_t c_shifts; igraph_integer_t c_repeats; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; R_SEXP_to_vector(shifts, &c_shifts); c_repeats=INTEGER(repeats)[0]; /* Call igraph */ igraph_lcf_vector(&c_graph, c_n, &c_shifts, c_repeats); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_adjlist / /-------------------------------------------*/ SEXP R_igraph_adjlist(SEXP adjlist, SEXP mode, SEXP duplicate) { /* Declarations */ igraph_t c_graph; igraph_adjlist_t c_adjlist; igraph_neimode_t c_mode; igraph_bool_t c_duplicate; SEXP graph; SEXP result; /* Convert input */ if (0 != R_SEXP_to_igraph_adjlist(adjlist, &c_adjlist)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } c_mode=(igraph_neimode_t) REAL(mode)[0]; c_duplicate=LOGICAL(duplicate)[0]; /* Call igraph */ igraph_adjlist(&c_graph, &c_adjlist, c_mode, c_duplicate); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_full_bipartite / /-------------------------------------------*/ SEXP R_igraph_full_bipartite(SEXP n1, SEXP n2, SEXP directed, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_integer_t c_n1; igraph_integer_t c_n2; igraph_bool_t c_directed; igraph_neimode_t c_mode; SEXP graph; SEXP types; SEXP result, names; /* Convert input */ if (0 != igraph_vector_bool_init(&c_types, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_types); types=R_GlobalEnv; /* hack to have a non-NULL value */ c_n1=INTEGER(n1)[0]; c_n2=INTEGER(n2)[0]; c_directed=LOGICAL(directed)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_full_bipartite(&c_graph, (isNull(types) ? 0 : &c_types), c_n1, c_n2, c_directed, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); PROTECT(types=R_igraph_0orvector_bool_to_SEXP(&c_types)); igraph_vector_bool_destroy(&c_types); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, graph); SET_VECTOR_ELT(result, 1, types); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("graph")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("types")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_forest_fire_game / /-------------------------------------------*/ SEXP R_igraph_forest_fire_game(SEXP nodes, SEXP fw_prob, SEXP bw_factor, SEXP ambs, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_nodes; igraph_real_t c_fw_prob; igraph_real_t c_bw_factor; igraph_integer_t c_ambs; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ c_nodes=INTEGER(nodes)[0]; c_fw_prob=REAL(fw_prob)[0]; c_bw_factor=REAL(bw_factor)[0]; c_ambs=INTEGER(ambs)[0]; c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_forest_fire_game(&c_graph, c_nodes, c_fw_prob, c_bw_factor, c_ambs, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_static_fitness_game / /-------------------------------------------*/ SEXP R_igraph_static_fitness_game(SEXP no_of_edges, SEXP fitness_out, SEXP fitness_in, SEXP loops, SEXP multiple) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_no_of_edges; igraph_vector_t c_fitness_out; igraph_vector_t c_fitness_in; igraph_bool_t c_loops; igraph_bool_t c_multiple; SEXP graph; SEXP result; /* Convert input */ c_no_of_edges=INTEGER(no_of_edges)[0]; R_SEXP_to_vector(fitness_out, &c_fitness_out); if (!isNull(fitness_in)) { R_SEXP_to_vector(fitness_in, &c_fitness_in); } c_loops=LOGICAL(loops)[0]; c_multiple=LOGICAL(multiple)[0]; /* Call igraph */ igraph_static_fitness_game(&c_graph, c_no_of_edges, &c_fitness_out, (isNull(fitness_in) ? 0 : &c_fitness_in), c_loops, c_multiple); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_static_power_law_game / /-------------------------------------------*/ SEXP R_igraph_static_power_law_game(SEXP no_of_nodes, SEXP no_of_edges, SEXP exponent_out, SEXP exponent_in, SEXP loops, SEXP multiple, SEXP finite_size_correction) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_no_of_nodes; igraph_integer_t c_no_of_edges; igraph_real_t c_exponent_out; igraph_real_t c_exponent_in; igraph_bool_t c_loops; igraph_bool_t c_multiple; igraph_bool_t c_finite_size_correction; SEXP graph; SEXP result; /* Convert input */ c_no_of_nodes=INTEGER(no_of_nodes)[0]; c_no_of_edges=INTEGER(no_of_edges)[0]; c_exponent_out=REAL(exponent_out)[0]; c_exponent_in=REAL(exponent_in)[0]; c_loops=LOGICAL(loops)[0]; c_multiple=LOGICAL(multiple)[0]; c_finite_size_correction=LOGICAL(finite_size_correction)[0]; /* Call igraph */ igraph_static_power_law_game(&c_graph, c_no_of_nodes, c_no_of_edges, c_exponent_out, c_exponent_in, c_loops, c_multiple, c_finite_size_correction); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_k_regular_game / /-------------------------------------------*/ SEXP R_igraph_k_regular_game(SEXP no_of_nodes, SEXP k, SEXP directed, SEXP multiple) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_no_of_nodes; igraph_integer_t c_k; igraph_bool_t c_directed; igraph_bool_t c_multiple; SEXP graph; SEXP result; /* Convert input */ c_no_of_nodes=INTEGER(no_of_nodes)[0]; c_k=INTEGER(k)[0]; c_directed=LOGICAL(directed)[0]; c_multiple=LOGICAL(multiple)[0]; /* Call igraph */ igraph_k_regular_game(&c_graph, c_no_of_nodes, c_k, c_directed, c_multiple); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_sbm_game / /-------------------------------------------*/ SEXP R_igraph_sbm_game(SEXP n, SEXP pref_matrix, SEXP block_sizes, SEXP directed, SEXP loops) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_matrix_t c_pref_matrix; igraph_vector_int_t c_block_sizes; igraph_bool_t c_directed; igraph_bool_t c_loops; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; R_SEXP_to_matrix(pref_matrix, &c_pref_matrix); R_SEXP_to_vector_int(block_sizes, &c_block_sizes); c_directed=LOGICAL(directed)[0]; c_loops=LOGICAL(loops)[0]; /* Call igraph */ igraph_sbm_game(&c_graph, c_n, &c_pref_matrix, &c_block_sizes, c_directed, c_loops); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hsbm_game / /-------------------------------------------*/ SEXP R_igraph_hsbm_game(SEXP n, SEXP m, SEXP rho, SEXP C, SEXP p) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_integer_t c_m; igraph_vector_t c_rho; igraph_matrix_t c_C; igraph_real_t c_p; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; c_m=INTEGER(m)[0]; R_SEXP_to_vector(rho, &c_rho); R_SEXP_to_matrix(C, &c_C); c_p=REAL(p)[0]; /* Call igraph */ igraph_hsbm_game(&c_graph, c_n, c_m, &c_rho, &c_C, c_p); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hsbm_list_game / /-------------------------------------------*/ SEXP R_igraph_hsbm_list_game(SEXP n, SEXP mlist, SEXP rholist, SEXP Clist, SEXP p) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_n; igraph_vector_int_t c_mlist; igraph_vector_ptr_t c_rholist; igraph_vector_ptr_t c_Clist; igraph_real_t c_p; SEXP graph; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; R_SEXP_to_vector_int(mlist, &c_mlist); R_igraph_SEXP_to_vectorlist(rholist, &c_rholist); R_igraph_SEXP_to_matrixlist(Clist, &c_Clist); c_p=REAL(p)[0]; /* Call igraph */ igraph_hsbm_list_game(&c_graph, c_n, &c_mlist, &c_rholist, &c_Clist, c_p); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_correlated_game / /-------------------------------------------*/ SEXP R_igraph_correlated_game(SEXP old_graph, SEXP corr, SEXP p, SEXP permutation) { /* Declarations */ igraph_t c_old_graph; igraph_t c_new_graph; igraph_real_t c_corr; igraph_real_t c_p; igraph_vector_t c_permutation; SEXP new_graph; SEXP result; /* Convert input */ R_SEXP_to_igraph(old_graph, &c_old_graph); c_corr=REAL(corr)[0]; c_p=REAL(p)[0]; if (!isNull(permutation)) { R_SEXP_to_vector(permutation, &c_permutation); } /* Call igraph */ igraph_correlated_game(&c_old_graph, &c_new_graph, c_corr, c_p, (isNull(permutation) ? 0 : &c_permutation)); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_new_graph); PROTECT(new_graph=R_igraph_to_SEXP(&c_new_graph)); igraph_destroy(&c_new_graph); IGRAPH_FINALLY_CLEAN(1); result=new_graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_correlated_pair_game / /-------------------------------------------*/ SEXP R_igraph_correlated_pair_game(SEXP n, SEXP corr, SEXP p, SEXP directed, SEXP permutation) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; int c_n; igraph_real_t c_corr; igraph_real_t c_p; igraph_bool_t c_directed; igraph_vector_t c_permutation; SEXP graph1; SEXP graph2; SEXP result, names; /* Convert input */ c_n=INTEGER(n)[0]; c_corr=REAL(corr)[0]; c_p=REAL(p)[0]; c_directed=LOGICAL(directed)[0]; if (!isNull(permutation)) { R_SEXP_to_vector(permutation, &c_permutation); } /* Call igraph */ igraph_correlated_pair_game(&c_graph1, &c_graph2, c_n, c_corr, c_p, c_directed, (isNull(permutation) ? 0 : &c_permutation)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_graph1); PROTECT(graph1=R_igraph_to_SEXP(&c_graph1)); igraph_destroy(&c_graph1); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &c_graph2); PROTECT(graph2=R_igraph_to_SEXP(&c_graph2)); igraph_destroy(&c_graph2); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, graph1); SET_VECTOR_ELT(result, 1, graph2); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("graph1")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("graph2")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_dot_product_game / /-------------------------------------------*/ SEXP R_igraph_dot_product_game(SEXP vecs, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_vecs; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ R_SEXP_to_matrix(vecs, &c_vecs); c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_dot_product_game(&c_graph, &c_vecs, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_sample_sphere_surface / /-------------------------------------------*/ SEXP R_igraph_sample_sphere_surface(SEXP dim, SEXP n, SEXP radius, SEXP positive) { /* Declarations */ igraph_integer_t c_dim; igraph_integer_t c_n; igraph_real_t c_radius; igraph_bool_t c_positive; igraph_matrix_t c_res; SEXP res; SEXP result; /* Convert input */ c_dim=INTEGER(dim)[0]; c_n=INTEGER(n)[0]; c_radius=REAL(radius)[0]; c_positive=LOGICAL(positive)[0]; if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); /* Call igraph */ igraph_sample_sphere_surface(c_dim, c_n, c_radius, c_positive, &c_res); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_sample_sphere_volume / /-------------------------------------------*/ SEXP R_igraph_sample_sphere_volume(SEXP dim, SEXP n, SEXP radius, SEXP positive) { /* Declarations */ igraph_integer_t c_dim; igraph_integer_t c_n; igraph_real_t c_radius; igraph_bool_t c_positive; igraph_matrix_t c_res; SEXP res; SEXP result; /* Convert input */ c_dim=INTEGER(dim)[0]; c_n=INTEGER(n)[0]; c_radius=REAL(radius)[0]; c_positive=LOGICAL(positive)[0]; if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); /* Call igraph */ igraph_sample_sphere_volume(c_dim, c_n, c_radius, c_positive, &c_res); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_sample_dirichlet / /-------------------------------------------*/ SEXP R_igraph_sample_dirichlet(SEXP n, SEXP alpha) { /* Declarations */ igraph_integer_t c_n; igraph_vector_t c_alpha; igraph_matrix_t c_res; SEXP res; SEXP result; /* Convert input */ c_n=INTEGER(n)[0]; R_SEXP_to_vector(alpha, &c_alpha); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); /* Call igraph */ igraph_sample_dirichlet(c_n, &c_alpha, &c_res); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_closeness / /-------------------------------------------*/ SEXP R_igraph_closeness(SEXP graph, SEXP vids, SEXP mode, SEXP weights, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; igraph_vector_t c_weights; igraph_bool_t c_normalized; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_closeness(&c_graph, &c_res, c_vids, c_mode, (isNull(weights) ? 0 : &c_weights), c_normalized); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_closeness_estimate / /-------------------------------------------*/ SEXP R_igraph_closeness_estimate(SEXP graph, SEXP vids, SEXP mode, SEXP cutoff, SEXP weights, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; igraph_real_t c_cutoff; igraph_vector_t c_weights; igraph_bool_t c_normalized; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_cutoff=REAL(cutoff)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_closeness_estimate(&c_graph, &c_res, c_vids, c_mode, c_cutoff, (isNull(weights) ? 0 : &c_weights), c_normalized); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_all_shortest_paths / /-------------------------------------------*/ SEXP R_igraph_get_all_shortest_paths(SEXP graph, SEXP from, SEXP to, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_ptr_t c_res; igraph_vector_t c_nrgeo; igraph_integer_t c_from; igraph_vs_t c_to; igraph_neimode_t c_mode; SEXP res; SEXP nrgeo; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_res); if (0 != igraph_vector_init(&c_nrgeo, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_nrgeo); c_from=(igraph_integer_t) REAL(from)[0]; R_SEXP_to_igraph_vs(to, &c_graph, &c_to); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_get_all_shortest_paths(&c_graph, &c_res, &c_nrgeo, c_from, c_to, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(res=R_igraph_vectorlist_to_SEXP_p1(&c_res)); R_igraph_vectorlist_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(nrgeo=R_igraph_vector_to_SEXP(&c_nrgeo)); igraph_vector_destroy(&c_nrgeo); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_to); SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, nrgeo); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("nrgeo")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_all_shortest_paths_dijkstra / /-------------------------------------------*/ SEXP R_igraph_get_all_shortest_paths_dijkstra(SEXP graph, SEXP from, SEXP to, SEXP weights, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_ptr_t c_res; igraph_vector_t c_nrgeo; igraph_integer_t c_from; igraph_vs_t c_to; igraph_vector_t c_weights; igraph_neimode_t c_mode; SEXP res; SEXP nrgeo; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_res); if (0 != igraph_vector_init(&c_nrgeo, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_nrgeo); c_from=(igraph_integer_t) REAL(from)[0]; R_SEXP_to_igraph_vs(to, &c_graph, &c_to); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_get_all_shortest_paths_dijkstra(&c_graph, &c_res, &c_nrgeo, c_from, c_to, (isNull(weights) ? 0 : &c_weights), c_mode); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(res=R_igraph_vectorlist_to_SEXP_p1(&c_res)); R_igraph_vectorlist_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(nrgeo=R_igraph_vector_to_SEXP(&c_nrgeo)); igraph_vector_destroy(&c_nrgeo); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_to); SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, nrgeo); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("nrgeo")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_all_simple_paths / /-------------------------------------------*/ SEXP R_igraph_get_all_simple_paths(SEXP graph, SEXP from, SEXP to, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_int_t c_res; igraph_integer_t c_from; igraph_vs_t c_to; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_int_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_int_destroy, &c_res); c_from=(igraph_integer_t) REAL(from)[0]; R_SEXP_to_igraph_vs(to, &c_graph, &c_to); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_get_all_simple_paths(&c_graph, &c_res, c_from, c_to, c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_int_to_SEXPp1(&c_res)); igraph_vector_int_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_to); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_betweenness_estimate / /-------------------------------------------*/ SEXP R_igraph_betweenness_estimate(SEXP graph, SEXP vids, SEXP directed, SEXP cutoff, SEXP weights, SEXP nobigint) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_bool_t c_directed; igraph_real_t c_cutoff; igraph_vector_t c_weights; igraph_bool_t c_nobigint; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_directed=LOGICAL(directed)[0]; c_cutoff=REAL(cutoff)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_nobigint=LOGICAL(nobigint)[0]; /* Call igraph */ igraph_betweenness_estimate(&c_graph, &c_res, c_vids, c_directed, c_cutoff, (isNull(weights) ? 0 : &c_weights), c_nobigint); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_edge_betweenness / /-------------------------------------------*/ SEXP R_igraph_edge_betweenness(SEXP graph, SEXP directed, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_bool_t c_directed; igraph_vector_t c_weights; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_directed=LOGICAL(directed)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_edge_betweenness(&c_graph, &c_res, c_directed, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_edge_betweenness_estimate / /-------------------------------------------*/ SEXP R_igraph_edge_betweenness_estimate(SEXP graph, SEXP directed, SEXP cutoff, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_bool_t c_directed; igraph_real_t c_cutoff; igraph_vector_t c_weights; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_directed=LOGICAL(directed)[0]; c_cutoff=REAL(cutoff)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_edge_betweenness_estimate(&c_graph, &c_res, c_directed, c_cutoff, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_pagerank_old / /-------------------------------------------*/ SEXP R_igraph_pagerank_old(SEXP graph, SEXP vids, SEXP directed, SEXP niter, SEXP eps, SEXP damping, SEXP old) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_bool_t c_directed; igraph_integer_t c_niter; igraph_real_t c_eps; igraph_real_t c_damping; igraph_bool_t c_old; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_directed=LOGICAL(directed)[0]; c_niter=INTEGER(niter)[0]; c_eps=REAL(eps)[0]; c_damping=REAL(damping)[0]; c_old=LOGICAL(old)[0]; /* Call igraph */ igraph_pagerank_old(&c_graph, &c_res, c_vids, c_directed, c_niter, c_eps, c_damping, c_old); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_personalized_pagerank / /-------------------------------------------*/ SEXP R_igraph_personalized_pagerank(SEXP graph, SEXP algo, SEXP vids, SEXP directed, SEXP damping, SEXP personalized, SEXP weights, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_pagerank_algo_t c_algo; igraph_vector_t c_vector; igraph_real_t c_value; igraph_vs_t c_vids; igraph_bool_t c_directed; igraph_real_t c_damping; igraph_vector_t c_personalized; igraph_vector_t c_weights; igraph_pagerank_power_options_t c_options1; igraph_arpack_options_t c_options2; void* c_options; SEXP vector; SEXP value; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_algo=(igraph_pagerank_algo_t) INTEGER(algo)[0]; if (0 != igraph_vector_init(&c_vector, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vector); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_directed=LOGICAL(directed)[0]; c_damping=REAL(damping)[0]; if (!isNull(personalized)) { R_SEXP_to_vector(personalized, &c_personalized); } if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (c_algo == IGRAPH_PAGERANK_ALGO_POWER) { R_SEXP_to_pagerank_power_options(options, &c_options1); c_options = &c_options1; } else if (c_algo == IGRAPH_PAGERANK_ALGO_ARPACK) { R_SEXP_to_igraph_arpack_options(options, &c_options2); c_options = &c_options2; } else { c_options = 0; } /* Call igraph */ igraph_personalized_pagerank(&c_graph, c_algo, &c_vector, &c_value, c_vids, c_directed, c_damping, (isNull(personalized) ? 0 : &c_personalized), (isNull(weights) ? 0 : &c_weights), c_options); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(vector=R_igraph_vector_to_SEXP(&c_vector)); igraph_vector_destroy(&c_vector); IGRAPH_FINALLY_CLEAN(1); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; igraph_vs_destroy(&c_vids); if (c_algo == IGRAPH_PAGERANK_ALGO_POWER) { PROTECT(options); } else if (c_algo == IGRAPH_PAGERANK_ALGO_ARPACK) { PROTECT(options = R_igraph_arpack_options_to_SEXP(&c_options2)); } else { PROTECT(options); } SET_VECTOR_ELT(result, 0, vector); SET_VECTOR_ELT(result, 1, value); SET_VECTOR_ELT(result, 2, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vector")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_induced_subgraph / /-------------------------------------------*/ SEXP R_igraph_induced_subgraph(SEXP graph, SEXP vids, SEXP impl) { /* Declarations */ igraph_t c_graph; igraph_t c_res; igraph_vs_t c_vids; igraph_subgraph_implementation_t c_impl; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_impl=(igraph_subgraph_implementation_t) REAL(impl)[0]; /* Call igraph */ igraph_induced_subgraph(&c_graph, &c_res, c_vids, c_impl); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_res); PROTECT(res=R_igraph_to_SEXP(&c_res)); igraph_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_subgraph_edges / /-------------------------------------------*/ SEXP R_igraph_subgraph_edges(SEXP graph, SEXP eids, SEXP delete_vertices) { /* Declarations */ igraph_t c_graph; igraph_t c_res; igraph_es_t c_eids; igraph_bool_t c_delete_vertices; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_igraph_es(eids, &c_graph, &c_eids); c_delete_vertices=LOGICAL(delete_vertices)[0]; /* Call igraph */ igraph_subgraph_edges(&c_graph, &c_res, c_eids, c_delete_vertices); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_res); PROTECT(res=R_igraph_to_SEXP(&c_res)); igraph_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_es_destroy(&c_eids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_path_length_hist / /-------------------------------------------*/ SEXP R_igraph_path_length_hist(SEXP graph, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_real_t c_unconnected; igraph_bool_t c_directed; SEXP res; SEXP unconnected; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_path_length_hist(&c_graph, &c_res, &c_unconnected, c_directed); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(unconnected=NEW_NUMERIC(1)); REAL(unconnected)[0]=c_unconnected; SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, unconnected); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("unconnected")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_simplify / /-------------------------------------------*/ SEXP R_igraph_simplify(SEXP graph, SEXP remove_multiple, SEXP remove_loops, SEXP edge_attr_comb) { /* Declarations */ igraph_t c_graph; igraph_bool_t c_remove_multiple; igraph_bool_t c_remove_loops; igraph_attribute_combination_t c_edge_attr_comb; SEXP result; /* Convert input */ R_SEXP_to_igraph_copy(graph, &c_graph); IGRAPH_FINALLY(igraph_destroy, &c_graph); c_remove_multiple=LOGICAL(remove_multiple)[0]; c_remove_loops=LOGICAL(remove_loops)[0]; R_SEXP_to_attr_comb(edge_attr_comb, &c_edge_attr_comb); /* Call igraph */ igraph_simplify(&c_graph, c_remove_multiple, c_remove_loops, &c_edge_attr_comb); /* Convert output */ PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); igraph_attribute_combination_destroy(&c_edge_attr_comb); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_dag / /-------------------------------------------*/ SEXP R_igraph_is_dag(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ igraph_is_dag(&c_graph, &c_res); /* Convert output */ PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_simple / /-------------------------------------------*/ SEXP R_igraph_is_simple(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ igraph_is_simple(&c_graph, &c_res); /* Convert output */ PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_has_multiple / /-------------------------------------------*/ SEXP R_igraph_has_multiple(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ igraph_has_multiple(&c_graph, &c_res); /* Convert output */ PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_eigenvector_centrality / /-------------------------------------------*/ SEXP R_igraph_eigenvector_centrality(SEXP graph, SEXP directed, SEXP scale, SEXP weights, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_vector; igraph_real_t c_value; igraph_bool_t c_directed; igraph_bool_t c_scale; igraph_vector_t c_weights; igraph_arpack_options_t c_options; SEXP vector; SEXP value; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_vector, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vector); c_directed=LOGICAL(directed)[0]; c_scale=LOGICAL(scale)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } R_SEXP_to_igraph_arpack_options(options, &c_options); /* Call igraph */ igraph_eigenvector_centrality(&c_graph, &c_vector, &c_value, c_directed, c_scale, (isNull(weights) ? 0 : &c_weights), &c_options); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(vector=R_igraph_vector_to_SEXP(&c_vector)); igraph_vector_destroy(&c_vector); IGRAPH_FINALLY_CLEAN(1); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); SET_VECTOR_ELT(result, 0, vector); SET_VECTOR_ELT(result, 1, value); SET_VECTOR_ELT(result, 2, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vector")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hub_score / /-------------------------------------------*/ SEXP R_igraph_hub_score(SEXP graph, SEXP scale, SEXP weights, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_vector; igraph_real_t c_value; igraph_bool_t c_scale; igraph_vector_t c_weights; igraph_arpack_options_t c_options; SEXP vector; SEXP value; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_vector, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vector); c_scale=LOGICAL(scale)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } R_SEXP_to_igraph_arpack_options(options, &c_options); /* Call igraph */ igraph_hub_score(&c_graph, &c_vector, &c_value, c_scale, (isNull(weights) ? 0 : &c_weights), &c_options); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(vector=R_igraph_vector_to_SEXP(&c_vector)); igraph_vector_destroy(&c_vector); IGRAPH_FINALLY_CLEAN(1); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); SET_VECTOR_ELT(result, 0, vector); SET_VECTOR_ELT(result, 1, value); SET_VECTOR_ELT(result, 2, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vector")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_authority_score / /-------------------------------------------*/ SEXP R_igraph_authority_score(SEXP graph, SEXP scale, SEXP weights, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_vector; igraph_real_t c_value; igraph_bool_t c_scale; igraph_vector_t c_weights; igraph_arpack_options_t c_options; SEXP vector; SEXP value; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_vector, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vector); c_scale=LOGICAL(scale)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } R_SEXP_to_igraph_arpack_options(options, &c_options); /* Call igraph */ igraph_authority_score(&c_graph, &c_vector, &c_value, c_scale, (isNull(weights) ? 0 : &c_weights), &c_options); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(vector=R_igraph_vector_to_SEXP(&c_vector)); igraph_vector_destroy(&c_vector); IGRAPH_FINALLY_CLEAN(1); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); SET_VECTOR_ELT(result, 0, vector); SET_VECTOR_ELT(result, 1, value); SET_VECTOR_ELT(result, 2, options); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vector")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_arpack_unpack_complex / /-------------------------------------------*/ SEXP R_igraph_arpack_unpack_complex(SEXP vectors, SEXP values, SEXP nev) { /* Declarations */ igraph_matrix_t c_vectors; igraph_matrix_t c_values; igraph_integer_t c_nev; SEXP result, names; /* Convert input */ if (0 != R_SEXP_to_igraph_matrix_copy(vectors, &c_vectors)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_vectors); if (0 != R_SEXP_to_igraph_matrix_copy(values, &c_values)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_values); c_nev=INTEGER(nev)[0]; /* Call igraph */ igraph_arpack_unpack_complex(&c_vectors, &c_values, c_nev); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(vectors=R_igraph_matrix_to_SEXP(&c_vectors)); igraph_matrix_destroy(&c_vectors); IGRAPH_FINALLY_CLEAN(1); PROTECT(values=R_igraph_matrix_to_SEXP(&c_values)); igraph_matrix_destroy(&c_values); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, vectors); SET_VECTOR_ELT(result, 1, values); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vectors")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("values")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_unfold_tree / /-------------------------------------------*/ SEXP R_igraph_unfold_tree(SEXP graph, SEXP mode, SEXP roots) { /* Declarations */ igraph_t c_graph; igraph_t c_tree; igraph_neimode_t c_mode; igraph_vector_t c_roots; igraph_vector_t c_vertex_index; SEXP tree; SEXP vertex_index; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_mode=(igraph_neimode_t) REAL(mode)[0]; R_SEXP_to_vector(roots, &c_roots); if (0 != igraph_vector_init(&c_vertex_index, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vertex_index); vertex_index=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_unfold_tree(&c_graph, &c_tree, c_mode, &c_roots, (isNull(vertex_index) ? 0 : &c_vertex_index)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_tree); PROTECT(tree=R_igraph_to_SEXP(&c_tree)); igraph_destroy(&c_tree); IGRAPH_FINALLY_CLEAN(1); PROTECT(vertex_index=R_igraph_0orvector_to_SEXPp1(&c_vertex_index)); igraph_vector_destroy(&c_vertex_index); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, tree); SET_VECTOR_ELT(result, 1, vertex_index); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("tree")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("vertex_index")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_mutual / /-------------------------------------------*/ SEXP R_igraph_is_mutual(SEXP graph, SEXP es) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_res; igraph_es_t c_es; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_bool_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_res); R_SEXP_to_igraph_es(es, &c_graph, &c_es); /* Call igraph */ igraph_is_mutual(&c_graph, &c_res, c_es); /* Convert output */ PROTECT(res=R_igraph_vector_bool_to_SEXP(&c_res)); igraph_vector_bool_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_es_destroy(&c_es); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_maximum_cardinality_search / /-------------------------------------------*/ SEXP R_igraph_maximum_cardinality_search(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_alpha; igraph_vector_t c_alpham1; SEXP alpha; SEXP alpham1; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_alpha, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_alpha); if (0 != igraph_vector_init(&c_alpham1, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_alpham1); alpham1=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_maximum_cardinality_search(&c_graph, &c_alpha, (isNull(alpham1) ? 0 : &c_alpham1)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(alpha=R_igraph_vector_to_SEXPp1(&c_alpha)); igraph_vector_destroy(&c_alpha); IGRAPH_FINALLY_CLEAN(1); PROTECT(alpham1=R_igraph_0orvector_to_SEXPp1(&c_alpham1)); igraph_vector_destroy(&c_alpham1); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, alpha); SET_VECTOR_ELT(result, 1, alpham1); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("alpha")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("alpham1")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_avg_nearest_neighbor_degree / /-------------------------------------------*/ SEXP R_igraph_avg_nearest_neighbor_degree(SEXP graph, SEXP vids, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vs_t c_vids; igraph_vector_t c_knn; igraph_vector_t c_knnk; igraph_vector_t c_weights; SEXP knn; SEXP knnk; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); if (0 != igraph_vector_init(&c_knn, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_knn); if (0 != igraph_vector_init(&c_knnk, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_knnk); knnk=R_GlobalEnv; /* hack to have a non-NULL value */ if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_avg_nearest_neighbor_degree(&c_graph, c_vids, &c_knn, (isNull(knnk) ? 0 : &c_knnk), (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); igraph_vs_destroy(&c_vids); PROTECT(knn=R_igraph_vector_to_SEXP(&c_knn)); igraph_vector_destroy(&c_knn); IGRAPH_FINALLY_CLEAN(1); PROTECT(knnk=R_igraph_0orvector_to_SEXP(&c_knnk)); igraph_vector_destroy(&c_knnk); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, knn); SET_VECTOR_ELT(result, 1, knnk); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("knn")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("knnk")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_strength / /-------------------------------------------*/ SEXP R_igraph_strength(SEXP graph, SEXP vids, SEXP mode, SEXP loops, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; igraph_bool_t c_loops; igraph_vector_t c_weights; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_loops=LOGICAL(loops)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_strength(&c_graph, &c_res, c_vids, c_mode, c_loops, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization / /-------------------------------------------*/ SEXP R_igraph_centralization(SEXP scores, SEXP theoretical_max, SEXP normalized) { /* Declarations */ igraph_vector_t c_scores; igraph_real_t c_theoretical_max; igraph_bool_t c_normalized; igraph_real_t c_result; SEXP result; /* Convert input */ R_SEXP_to_vector(scores, &c_scores); c_theoretical_max=REAL(theoretical_max)[0]; c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ c_result= igraph_centralization(&c_scores, c_theoretical_max, c_normalized); /* Convert output */ PROTECT(result=NEW_NUMERIC(1)); REAL(result)[0]=c_result; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_degree / /-------------------------------------------*/ SEXP R_igraph_centralization_degree(SEXP graph, SEXP mode, SEXP loops, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_neimode_t c_mode; igraph_bool_t c_loops; igraph_real_t c_centralization; igraph_real_t c_theoretical_max; igraph_bool_t c_normalized; SEXP res; SEXP centralization; SEXP theoretical_max; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_loops=LOGICAL(loops)[0]; c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_centralization_degree(&c_graph, &c_res, c_mode, c_loops, &c_centralization, &c_theoretical_max, c_normalized); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(centralization=NEW_NUMERIC(1)); REAL(centralization)[0]=c_centralization; PROTECT(theoretical_max=NEW_NUMERIC(1)); REAL(theoretical_max)[0]=c_theoretical_max; SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, centralization); SET_VECTOR_ELT(result, 2, theoretical_max); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("centralization")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("theoretical_max")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_degree_tmax / /-------------------------------------------*/ SEXP R_igraph_centralization_degree_tmax(SEXP graph, SEXP nodes, SEXP mode, SEXP loops) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_nodes; igraph_neimode_t c_mode; igraph_bool_t c_loops; igraph_real_t c_res; SEXP res; SEXP result; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } c_nodes=INTEGER(nodes)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; c_loops=LOGICAL(loops)[0]; /* Call igraph */ igraph_centralization_degree_tmax((isNull(graph) ? 0 : &c_graph), c_nodes, c_mode, c_loops, &c_res); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_betweenness / /-------------------------------------------*/ SEXP R_igraph_centralization_betweenness(SEXP graph, SEXP directed, SEXP nobigint, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_bool_t c_directed; igraph_bool_t c_nobigint; igraph_real_t c_centralization; igraph_real_t c_theoretical_max; igraph_bool_t c_normalized; SEXP res; SEXP centralization; SEXP theoretical_max; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_directed=LOGICAL(directed)[0]; c_nobigint=LOGICAL(nobigint)[0]; c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_centralization_betweenness(&c_graph, &c_res, c_directed, c_nobigint, &c_centralization, &c_theoretical_max, c_normalized); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(centralization=NEW_NUMERIC(1)); REAL(centralization)[0]=c_centralization; PROTECT(theoretical_max=NEW_NUMERIC(1)); REAL(theoretical_max)[0]=c_theoretical_max; SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, centralization); SET_VECTOR_ELT(result, 2, theoretical_max); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("centralization")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("theoretical_max")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_betweenness_tmax / /-------------------------------------------*/ SEXP R_igraph_centralization_betweenness_tmax(SEXP graph, SEXP nodes, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_nodes; igraph_bool_t c_directed; igraph_real_t c_res; SEXP res; SEXP result; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } c_nodes=INTEGER(nodes)[0]; c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_centralization_betweenness_tmax((isNull(graph) ? 0 : &c_graph), c_nodes, c_directed, &c_res); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_closeness / /-------------------------------------------*/ SEXP R_igraph_centralization_closeness(SEXP graph, SEXP mode, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_neimode_t c_mode; igraph_real_t c_centralization; igraph_real_t c_theoretical_max; igraph_bool_t c_normalized; SEXP res; SEXP centralization; SEXP theoretical_max; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_centralization_closeness(&c_graph, &c_res, c_mode, &c_centralization, &c_theoretical_max, c_normalized); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(centralization=NEW_NUMERIC(1)); REAL(centralization)[0]=c_centralization; PROTECT(theoretical_max=NEW_NUMERIC(1)); REAL(theoretical_max)[0]=c_theoretical_max; SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, centralization); SET_VECTOR_ELT(result, 2, theoretical_max); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("centralization")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("theoretical_max")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_closeness_tmax / /-------------------------------------------*/ SEXP R_igraph_centralization_closeness_tmax(SEXP graph, SEXP nodes, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_nodes; igraph_neimode_t c_mode; igraph_real_t c_res; SEXP res; SEXP result; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } c_nodes=INTEGER(nodes)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_centralization_closeness_tmax((isNull(graph) ? 0 : &c_graph), c_nodes, c_mode, &c_res); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_eigenvector_centrality / /-------------------------------------------*/ SEXP R_igraph_centralization_eigenvector_centrality(SEXP graph, SEXP directed, SEXP scale, SEXP options, SEXP normalized) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_vector; igraph_real_t c_value; igraph_bool_t c_directed; igraph_bool_t c_scale; igraph_arpack_options_t c_options; igraph_real_t c_centralization; igraph_real_t c_theoretical_max; igraph_bool_t c_normalized; SEXP vector; SEXP value; SEXP centralization; SEXP theoretical_max; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_vector, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_vector); c_directed=LOGICAL(directed)[0]; c_scale=LOGICAL(scale)[0]; R_SEXP_to_igraph_arpack_options(options, &c_options); c_normalized=LOGICAL(normalized)[0]; /* Call igraph */ igraph_centralization_eigenvector_centrality(&c_graph, &c_vector, &c_value, c_directed, c_scale, &c_options, &c_centralization, &c_theoretical_max, c_normalized); /* Convert output */ PROTECT(result=NEW_LIST(5)); PROTECT(names=NEW_CHARACTER(5)); PROTECT(vector=R_igraph_vector_to_SEXP(&c_vector)); igraph_vector_destroy(&c_vector); IGRAPH_FINALLY_CLEAN(1); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); PROTECT(centralization=NEW_NUMERIC(1)); REAL(centralization)[0]=c_centralization; PROTECT(theoretical_max=NEW_NUMERIC(1)); REAL(theoretical_max)[0]=c_theoretical_max; SET_VECTOR_ELT(result, 0, vector); SET_VECTOR_ELT(result, 1, value); SET_VECTOR_ELT(result, 2, options); SET_VECTOR_ELT(result, 3, centralization); SET_VECTOR_ELT(result, 4, theoretical_max); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vector")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("options")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("centralization")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("theoretical_max")); SET_NAMES(result, names); UNPROTECT(6); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_centralization_eigenvector_centrality_tmax / /-------------------------------------------*/ SEXP R_igraph_centralization_eigenvector_centrality_tmax(SEXP graph, SEXP nodes, SEXP directed, SEXP scale) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_nodes; igraph_bool_t c_directed; igraph_bool_t c_scale; igraph_real_t c_res; SEXP res; SEXP result; /* Convert input */ if (!isNull(graph)) { R_SEXP_to_igraph(graph, &c_graph); } c_nodes=INTEGER(nodes)[0]; c_directed=LOGICAL(directed)[0]; c_scale=LOGICAL(scale)[0]; /* Call igraph */ igraph_centralization_eigenvector_centrality_tmax((isNull(graph) ? 0 : &c_graph), c_nodes, c_directed, c_scale, &c_res); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_assortativity_nominal / /-------------------------------------------*/ SEXP R_igraph_assortativity_nominal(SEXP graph, SEXP types, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_types; igraph_real_t c_res; igraph_bool_t c_directed; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(types, &c_types); c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_assortativity_nominal(&c_graph, &c_types, &c_res, c_directed); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_assortativity / /-------------------------------------------*/ SEXP R_igraph_assortativity(SEXP graph, SEXP types1, SEXP types2, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_types1; igraph_vector_t c_types2; igraph_real_t c_res; igraph_bool_t c_directed; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(types1, &c_types1); if (!isNull(types2)) { R_SEXP_to_vector(types2, &c_types2); } c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_assortativity(&c_graph, &c_types1, (isNull(types2) ? 0 : &c_types2), &c_res, c_directed); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_assortativity_degree / /-------------------------------------------*/ SEXP R_igraph_assortativity_degree(SEXP graph, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_real_t c_res; igraph_bool_t c_directed; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_assortativity_degree(&c_graph, &c_res, c_directed); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_contract_vertices / /-------------------------------------------*/ SEXP R_igraph_contract_vertices(SEXP graph, SEXP mapping, SEXP vertex_attr_comb) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_mapping; igraph_attribute_combination_t c_vertex_attr_comb; SEXP result; /* Convert input */ R_SEXP_to_igraph_copy(graph, &c_graph); IGRAPH_FINALLY(igraph_destroy, &c_graph); R_SEXP_to_vector(mapping, &c_mapping); R_SEXP_to_attr_comb(vertex_attr_comb, &c_vertex_attr_comb); /* Call igraph */ igraph_contract_vertices(&c_graph, &c_mapping, &c_vertex_attr_comb); /* Convert output */ PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); igraph_attribute_combination_destroy(&c_vertex_attr_comb); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_eccentricity / /-------------------------------------------*/ SEXP R_igraph_eccentricity(SEXP graph, SEXP vids, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_eccentricity(&c_graph, &c_res, c_vids, c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_radius / /-------------------------------------------*/ SEXP R_igraph_radius(SEXP graph, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_real_t c_radius; igraph_neimode_t c_mode; SEXP radius; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_radius(&c_graph, &c_radius, c_mode); /* Convert output */ PROTECT(radius=NEW_NUMERIC(1)); REAL(radius)[0]=c_radius; result=radius; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_diversity / /-------------------------------------------*/ SEXP R_igraph_diversity(SEXP graph, SEXP weights, SEXP vids) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_weights; igraph_vector_t c_res; igraph_vs_t c_vids; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); /* Call igraph */ igraph_diversity(&c_graph, (isNull(weights) ? 0 : &c_weights), &c_res, c_vids); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_random_walk / /-------------------------------------------*/ SEXP R_igraph_random_walk(SEXP graph, SEXP start, SEXP mode, SEXP steps, SEXP stuck) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_walk; igraph_integer_t c_start; igraph_neimode_t c_mode; igraph_integer_t c_steps; igraph_random_walk_stuck_t c_stuck; SEXP walk; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_walk, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_walk); c_start=(igraph_integer_t) REAL(start)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; c_steps=INTEGER(steps)[0]; c_stuck=(igraph_random_walk_stuck_t) INTEGER(stuck)[0]; /* Call igraph */ igraph_random_walk(&c_graph, &c_walk, c_start, c_mode, c_steps, c_stuck); /* Convert output */ PROTECT(walk=R_igraph_vector_to_SEXPp1(&c_walk)); igraph_vector_destroy(&c_walk); IGRAPH_FINALLY_CLEAN(1); result=walk; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_degree_sequence / /-------------------------------------------*/ SEXP R_igraph_is_degree_sequence(SEXP out_deg, SEXP in_deg) { /* Declarations */ igraph_vector_t c_out_deg; igraph_vector_t c_in_deg; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_vector(out_deg, &c_out_deg); if (!isNull(in_deg)) { R_SEXP_to_vector(in_deg, &c_in_deg); } /* Call igraph */ igraph_is_degree_sequence(&c_out_deg, (isNull(in_deg) ? 0 : &c_in_deg), &c_res); /* Convert output */ PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_graphical_degree_sequence / /-------------------------------------------*/ SEXP R_igraph_is_graphical_degree_sequence(SEXP out_deg, SEXP in_deg) { /* Declarations */ igraph_vector_t c_out_deg; igraph_vector_t c_in_deg; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_vector(out_deg, &c_out_deg); if (!isNull(in_deg)) { R_SEXP_to_vector(in_deg, &c_in_deg); } /* Call igraph */ igraph_is_graphical_degree_sequence(&c_out_deg, (isNull(in_deg) ? 0 : &c_in_deg), &c_res); /* Convert output */ PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_bipartite_projection_size / /-------------------------------------------*/ SEXP R_igraph_bipartite_projection_size(SEXP graph, SEXP types) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_integer_t c_vcount1; igraph_integer_t c_ecount1; igraph_integer_t c_vcount2; igraph_integer_t c_ecount2; SEXP vcount1; SEXP ecount1; SEXP vcount2; SEXP ecount2; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } /* Call igraph */ igraph_bipartite_projection_size(&c_graph, (isNull(types) ? 0 : &c_types), &c_vcount1, &c_ecount1, &c_vcount2, &c_ecount2); /* Convert output */ PROTECT(result=NEW_LIST(4)); PROTECT(names=NEW_CHARACTER(4)); PROTECT(vcount1=NEW_INTEGER(1)); INTEGER(vcount1)[0]=c_vcount1; PROTECT(ecount1=NEW_INTEGER(1)); INTEGER(ecount1)[0]=c_ecount1; PROTECT(vcount2=NEW_INTEGER(1)); INTEGER(vcount2)[0]=c_vcount2; PROTECT(ecount2=NEW_INTEGER(1)); INTEGER(ecount2)[0]=c_ecount2; SET_VECTOR_ELT(result, 0, vcount1); SET_VECTOR_ELT(result, 1, ecount1); SET_VECTOR_ELT(result, 2, vcount2); SET_VECTOR_ELT(result, 3, ecount2); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("vcount1")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("ecount1")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("vcount2")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("ecount2")); SET_NAMES(result, names); UNPROTECT(5); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_create_bipartite / /-------------------------------------------*/ SEXP R_igraph_create_bipartite(SEXP types, SEXP edges, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_vector_t c_edges; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ R_SEXP_to_vector_bool(types, &c_types); R_SEXP_to_vector(edges, &c_edges); c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_create_bipartite(&c_graph, &c_types, &c_edges, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_incidence / /-------------------------------------------*/ SEXP R_igraph_incidence(SEXP incidence, SEXP directed, SEXP mode, SEXP multiple) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_matrix_t c_incidence; igraph_bool_t c_directed; igraph_neimode_t c_mode; igraph_bool_t c_multiple; SEXP graph; SEXP types; SEXP result, names; /* Convert input */ if (0 != igraph_vector_bool_init(&c_types, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_types); R_SEXP_to_matrix(incidence, &c_incidence); c_directed=LOGICAL(directed)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; c_multiple=LOGICAL(multiple)[0]; /* Call igraph */ igraph_incidence(&c_graph, &c_types, &c_incidence, c_directed, c_mode, c_multiple); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); PROTECT(types=R_igraph_vector_bool_to_SEXP(&c_types)); igraph_vector_bool_destroy(&c_types); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, graph); SET_VECTOR_ELT(result, 1, types); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("graph")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("types")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_incidence / /-------------------------------------------*/ SEXP R_igraph_get_incidence(SEXP graph, SEXP types) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_matrix_t c_res; igraph_vector_t c_row_ids; igraph_vector_t c_col_ids; SEXP res; SEXP row_ids; SEXP col_ids; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); if (0 != igraph_vector_init(&c_row_ids, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_row_ids); row_ids=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_col_ids, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_col_ids); col_ids=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_get_incidence(&c_graph, (isNull(types) ? 0 : &c_types), &c_res, (isNull(row_ids) ? 0 : &c_row_ids), (isNull(col_ids) ? 0 : &c_col_ids)); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); PROTECT(row_ids=R_igraph_0orvector_to_SEXP(&c_row_ids)); igraph_vector_destroy(&c_row_ids); IGRAPH_FINALLY_CLEAN(1); PROTECT(col_ids=R_igraph_0orvector_to_SEXP(&c_col_ids)); igraph_vector_destroy(&c_col_ids); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, row_ids); SET_VECTOR_ELT(result, 2, col_ids); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("row_ids")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("col_ids")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_bipartite / /-------------------------------------------*/ SEXP R_igraph_is_bipartite(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_bool_t c_res; igraph_vector_bool_t c_type; SEXP res; SEXP type; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_bool_init(&c_type, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_type); type=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_is_bipartite(&c_graph, &c_res, (isNull(type) ? 0 : &c_type)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; PROTECT(type=R_igraph_0orvector_bool_to_SEXP(&c_type)); igraph_vector_bool_destroy(&c_type); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, type); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("type")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_bipartite_game_gnp / /-------------------------------------------*/ SEXP R_igraph_bipartite_game_gnp(SEXP n1, SEXP n2, SEXP p, SEXP directed, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_integer_t c_n1; igraph_integer_t c_n2; igraph_real_t c_p; igraph_bool_t c_directed; igraph_neimode_t c_mode; SEXP graph; SEXP types; SEXP result, names; /* Convert input */ if (0 != igraph_vector_bool_init(&c_types, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_types); types=R_GlobalEnv; /* hack to have a non-NULL value */ c_n1=INTEGER(n1)[0]; c_n2=INTEGER(n2)[0]; c_p=REAL(p)[0]; c_directed=LOGICAL(directed)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_bipartite_game_gnp(&c_graph, (isNull(types) ? 0 : &c_types), c_n1, c_n2, c_p, c_directed, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); PROTECT(types=R_igraph_0orvector_bool_to_SEXP(&c_types)); igraph_vector_bool_destroy(&c_types); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, graph); SET_VECTOR_ELT(result, 1, types); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("graph")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("types")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_bipartite_game_gnm / /-------------------------------------------*/ SEXP R_igraph_bipartite_game_gnm(SEXP n1, SEXP n2, SEXP m, SEXP directed, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_integer_t c_n1; igraph_integer_t c_n2; igraph_integer_t c_m; igraph_bool_t c_directed; igraph_neimode_t c_mode; SEXP graph; SEXP types; SEXP result, names; /* Convert input */ if (0 != igraph_vector_bool_init(&c_types, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_bool_destroy, &c_types); types=R_GlobalEnv; /* hack to have a non-NULL value */ c_n1=INTEGER(n1)[0]; c_n2=INTEGER(n2)[0]; c_m=INTEGER(m)[0]; c_directed=LOGICAL(directed)[0]; c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_bipartite_game_gnm(&c_graph, (isNull(types) ? 0 : &c_types), c_n1, c_n2, c_m, c_directed, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); PROTECT(types=R_igraph_0orvector_bool_to_SEXP(&c_types)); igraph_vector_bool_destroy(&c_types); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, graph); SET_VECTOR_ELT(result, 1, types); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("graph")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("types")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_clusters / /-------------------------------------------*/ SEXP R_igraph_clusters(SEXP graph, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_membership; igraph_vector_t c_csize; igraph_integer_t c_no; igraph_connectedness_t c_mode; SEXP membership; SEXP csize; SEXP no; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); if (0 != igraph_vector_init(&c_csize, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_csize); c_mode=REAL(mode)[0]; /* Call igraph */ igraph_clusters(&c_graph, &c_membership, &c_csize, &c_no, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(membership=R_igraph_vector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); PROTECT(csize=R_igraph_vector_to_SEXP(&c_csize)); igraph_vector_destroy(&c_csize); IGRAPH_FINALLY_CLEAN(1); PROTECT(no=NEW_INTEGER(1)); INTEGER(no)[0]=c_no; SET_VECTOR_ELT(result, 0, membership); SET_VECTOR_ELT(result, 1, csize); SET_VECTOR_ELT(result, 2, no); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("membership")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("csize")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("no")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_articulation_points / /-------------------------------------------*/ SEXP R_igraph_articulation_points(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); /* Call igraph */ igraph_articulation_points(&c_graph, &c_res); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXPp1(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_biconnected_components / /-------------------------------------------*/ SEXP R_igraph_biconnected_components(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_no; igraph_vector_ptr_t c_tree_edges; igraph_vector_ptr_t c_component_edges; igraph_vector_ptr_t c_components; igraph_vector_t c_articulation_points; SEXP no; SEXP tree_edges; SEXP component_edges; SEXP components; SEXP articulation_points; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_tree_edges, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_tree_edges); if (0 != igraph_vector_ptr_init(&c_component_edges, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_component_edges); if (0 != igraph_vector_ptr_init(&c_components, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_components); if (0 != igraph_vector_init(&c_articulation_points, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_articulation_points); /* Call igraph */ igraph_biconnected_components(&c_graph, &c_no, &c_tree_edges, &c_component_edges, &c_components, &c_articulation_points); /* Convert output */ PROTECT(result=NEW_LIST(5)); PROTECT(names=NEW_CHARACTER(5)); PROTECT(no=NEW_INTEGER(1)); INTEGER(no)[0]=c_no; PROTECT(tree_edges=R_igraph_vectorlist_to_SEXP_p1(&c_tree_edges)); R_igraph_vectorlist_destroy(&c_tree_edges); IGRAPH_FINALLY_CLEAN(1); PROTECT(component_edges=R_igraph_vectorlist_to_SEXP_p1(&c_component_edges)); R_igraph_vectorlist_destroy(&c_component_edges); IGRAPH_FINALLY_CLEAN(1); PROTECT(components=R_igraph_vectorlist_to_SEXP_p1(&c_components)); R_igraph_vectorlist_destroy(&c_components); IGRAPH_FINALLY_CLEAN(1); PROTECT(articulation_points=R_igraph_vector_to_SEXPp1(&c_articulation_points)); igraph_vector_destroy(&c_articulation_points); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, no); SET_VECTOR_ELT(result, 1, tree_edges); SET_VECTOR_ELT(result, 2, component_edges); SET_VECTOR_ELT(result, 3, components); SET_VECTOR_ELT(result, 4, articulation_points); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("no")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("tree_edges")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("component_edges")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("components")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("articulation_points")); SET_NAMES(result, names); UNPROTECT(6); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_star / /-------------------------------------------*/ SEXP R_igraph_layout_star(SEXP graph, SEXP center, SEXP order) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_integer_t c_center; igraph_vector_t c_order; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_center=(igraph_integer_t) REAL(center)[0]; if (!isNull(order)) { R_SEXP_to_vector(order, &c_order); } /* Call igraph */ igraph_layout_star(&c_graph, &c_res, c_center, (isNull(order) ? 0 : &c_order)); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_grid / /-------------------------------------------*/ SEXP R_igraph_layout_grid(SEXP graph, SEXP width) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_integer_t c_width; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_width=INTEGER(width)[0]; /* Call igraph */ igraph_layout_grid(&c_graph, &c_res, c_width); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_grid_3d / /-------------------------------------------*/ SEXP R_igraph_layout_grid_3d(SEXP graph, SEXP width, SEXP height) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_integer_t c_width; igraph_integer_t c_height; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_width=INTEGER(width)[0]; c_height=INTEGER(height)[0]; /* Call igraph */ igraph_layout_grid_3d(&c_graph, &c_res, c_width, c_height); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_drl / /-------------------------------------------*/ SEXP R_igraph_layout_drl(SEXP graph, SEXP res, SEXP use_seed, SEXP options, SEXP weights, SEXP fixed) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_bool_t c_use_seed; igraph_layout_drl_options_t c_options; igraph_vector_t c_weights; igraph_vector_bool_t c_fixed; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != R_SEXP_to_igraph_matrix_copy(res, &c_res)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_use_seed=LOGICAL(use_seed)[0]; R_SEXP_to_igraph_layout_drl_options(options, &c_options); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(fixed)) { R_SEXP_to_vector_bool(fixed, &c_fixed); } /* Call igraph */ igraph_layout_drl(&c_graph, &c_res, c_use_seed, &c_options, (isNull(weights) ? 0 : &c_weights), (isNull(fixed) ? 0 : &c_fixed)); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_drl_3d / /-------------------------------------------*/ SEXP R_igraph_layout_drl_3d(SEXP graph, SEXP res, SEXP use_seed, SEXP options, SEXP weights, SEXP fixed) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_bool_t c_use_seed; igraph_layout_drl_options_t c_options; igraph_vector_t c_weights; igraph_vector_bool_t c_fixed; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != R_SEXP_to_igraph_matrix_copy(res, &c_res)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_use_seed=LOGICAL(use_seed)[0]; R_SEXP_to_igraph_layout_drl_options(options, &c_options); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(fixed)) { R_SEXP_to_vector_bool(fixed, &c_fixed); } /* Call igraph */ igraph_layout_drl_3d(&c_graph, &c_res, c_use_seed, &c_options, (isNull(weights) ? 0 : &c_weights), (isNull(fixed) ? 0 : &c_fixed)); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_sugiyama / /-------------------------------------------*/ SEXP R_igraph_layout_sugiyama(SEXP graph, SEXP layers, SEXP hgap, SEXP vgap, SEXP maxiter, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_t c_extd_graph; igraph_vector_t c_extd_to_orig_eids; igraph_vector_t c_layers; igraph_real_t c_hgap; igraph_real_t c_vgap; igraph_integer_t c_maxiter; igraph_vector_t c_weights; SEXP res; SEXP extd_graph; SEXP extd_to_orig_eids; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); extd_graph=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_extd_to_orig_eids, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_extd_to_orig_eids); extd_to_orig_eids=R_GlobalEnv; /* hack to have a non-NULL value */ if (!isNull(layers)) { R_SEXP_to_vector(layers, &c_layers); } c_hgap=REAL(hgap)[0]; c_vgap=REAL(vgap)[0]; c_maxiter=INTEGER(maxiter)[0]; if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_layout_sugiyama(&c_graph, &c_res, (isNull(extd_graph) ? 0 : &c_extd_graph), (isNull(extd_to_orig_eids) ? 0 : &c_extd_to_orig_eids), (isNull(layers) ? 0 : &c_layers), c_hgap, c_vgap, c_maxiter, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &c_extd_graph); PROTECT(extd_graph=R_igraph_to_SEXP(&c_extd_graph)); igraph_destroy(&c_extd_graph); IGRAPH_FINALLY_CLEAN(1); PROTECT(extd_to_orig_eids=R_igraph_0orvector_to_SEXPp1(&c_extd_to_orig_eids)); igraph_vector_destroy(&c_extd_to_orig_eids); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, res); SET_VECTOR_ELT(result, 1, extd_graph); SET_VECTOR_ELT(result, 2, extd_to_orig_eids); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("res")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("extd_graph")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("extd_to_orig_eids")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_mds / /-------------------------------------------*/ SEXP R_igraph_layout_mds(SEXP graph, SEXP dist, SEXP dim) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_matrix_t c_dist; igraph_integer_t c_dim; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); if (!isNull(dist)) { R_SEXP_to_matrix(dist, &c_dist); } c_dim=INTEGER(dim)[0]; /* Call igraph */ igraph_layout_mds(&c_graph, &c_res, (isNull(dist) ? 0 : &c_dist), c_dim, 0); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_bipartite / /-------------------------------------------*/ SEXP R_igraph_layout_bipartite(SEXP graph, SEXP types, SEXP hgap, SEXP vgap, SEXP maxiter) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_matrix_t c_res; igraph_real_t c_hgap; igraph_real_t c_vgap; igraph_integer_t c_maxiter; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_hgap=REAL(hgap)[0]; c_vgap=REAL(vgap)[0]; c_maxiter=INTEGER(maxiter)[0]; /* Call igraph */ igraph_layout_bipartite(&c_graph, (isNull(types) ? 0 : &c_types), &c_res, c_hgap, c_vgap, c_maxiter); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_gem / /-------------------------------------------*/ SEXP R_igraph_layout_gem(SEXP graph, SEXP res, SEXP use_seed, SEXP maxiter, SEXP temp_max, SEXP temp_min, SEXP temp_init) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_bool_t c_use_seed; igraph_integer_t c_maxiter; igraph_real_t c_temp_max; igraph_real_t c_temp_min; igraph_real_t c_temp_init; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != R_SEXP_to_igraph_matrix_copy(res, &c_res)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_use_seed=LOGICAL(use_seed)[0]; c_maxiter=INTEGER(maxiter)[0]; c_temp_max=REAL(temp_max)[0]; c_temp_min=REAL(temp_min)[0]; c_temp_init=REAL(temp_init)[0]; /* Call igraph */ igraph_layout_gem(&c_graph, &c_res, c_use_seed, c_maxiter, c_temp_max, c_temp_min, c_temp_init); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_layout_davidson_harel / /-------------------------------------------*/ SEXP R_igraph_layout_davidson_harel(SEXP graph, SEXP res, SEXP use_seed, SEXP maxiter, SEXP fineiter, SEXP cool_fact, SEXP weight_node_dist, SEXP weight_border, SEXP weight_edge_lengths, SEXP weight_edge_crossings, SEXP weight_node_edge_dist) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_bool_t c_use_seed; igraph_integer_t c_maxiter; igraph_integer_t c_fineiter; igraph_real_t c_cool_fact; igraph_real_t c_weight_node_dist; igraph_real_t c_weight_border; igraph_real_t c_weight_edge_lengths; igraph_real_t c_weight_edge_crossings; igraph_real_t c_weight_node_edge_dist; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != R_SEXP_to_igraph_matrix_copy(res, &c_res)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_use_seed=LOGICAL(use_seed)[0]; c_maxiter=INTEGER(maxiter)[0]; c_fineiter=INTEGER(fineiter)[0]; c_cool_fact=REAL(cool_fact)[0]; c_weight_node_dist=REAL(weight_node_dist)[0]; c_weight_border=REAL(weight_border)[0]; c_weight_edge_lengths=REAL(weight_edge_lengths)[0]; c_weight_edge_crossings=REAL(weight_edge_crossings)[0]; c_weight_node_edge_dist=REAL(weight_node_edge_dist)[0]; /* Call igraph */ igraph_layout_davidson_harel(&c_graph, &c_res, c_use_seed, c_maxiter, c_fineiter, c_cool_fact, c_weight_node_dist, c_weight_border, c_weight_edge_lengths, c_weight_edge_crossings, c_weight_node_edge_dist); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_similarity_jaccard / /-------------------------------------------*/ SEXP R_igraph_similarity_jaccard(SEXP graph, SEXP vids, SEXP mode, SEXP loops) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; igraph_bool_t c_loops; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_loops=LOGICAL(loops)[0]; /* Call igraph */ igraph_similarity_jaccard(&c_graph, &c_res, c_vids, c_mode, c_loops); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_similarity_dice / /-------------------------------------------*/ SEXP R_igraph_similarity_dice(SEXP graph, SEXP vids, SEXP mode, SEXP loops) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; igraph_bool_t c_loops; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; c_loops=LOGICAL(loops)[0]; /* Call igraph */ igraph_similarity_dice(&c_graph, &c_res, c_vids, c_mode, c_loops); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_similarity_inverse_log_weighted / /-------------------------------------------*/ SEXP R_igraph_similarity_inverse_log_weighted(SEXP graph, SEXP vids, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_vs_t c_vids; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_similarity_inverse_log_weighted(&c_graph, &c_res, c_vids, c_mode); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_compare_communities / /-------------------------------------------*/ SEXP R_igraph_compare_communities(SEXP comm1, SEXP comm2, SEXP method) { /* Declarations */ igraph_vector_t c_comm1; igraph_vector_t c_comm2; igraph_real_t c_res; igraph_community_comparison_t c_method; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_vector(comm1, &c_comm1); R_SEXP_to_vector(comm2, &c_comm2); c_method=(igraph_community_comparison_t) REAL(method)[0]; /* Call igraph */ igraph_compare_communities(&c_comm1, &c_comm2, &c_res, c_method); /* Convert output */ PROTECT(res=NEW_NUMERIC(1)); REAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_modularity / /-------------------------------------------*/ SEXP R_igraph_modularity(SEXP graph, SEXP membership, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_membership; igraph_real_t c_modularity; igraph_vector_t c_weights; SEXP modularity; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(membership, &c_membership); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_modularity(&c_graph, &c_membership, &c_modularity, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(modularity=NEW_NUMERIC(1)); REAL(modularity)[0]=c_modularity; result=modularity; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_modularity_matrix / /-------------------------------------------*/ SEXP R_igraph_modularity_matrix(SEXP graph, SEXP membership, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_membership; igraph_matrix_t c_modmat; igraph_vector_t c_weights; SEXP modmat; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(membership, &c_membership); if (0 != igraph_matrix_init(&c_modmat, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_modmat); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_modularity_matrix(&c_graph, &c_membership, &c_modmat, (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(modmat=R_igraph_matrix_to_SEXP(&c_modmat)); igraph_matrix_destroy(&c_modmat); IGRAPH_FINALLY_CLEAN(1); result=modmat; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_community_label_propagation / /-------------------------------------------*/ SEXP R_igraph_community_label_propagation(SEXP graph, SEXP weights, SEXP initial, SEXP fixed) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_membership; igraph_vector_t c_weights; igraph_vector_t c_initial; igraph_vector_bool_t c_fixed; igraph_real_t c_modularity; SEXP membership; SEXP modularity; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(initial)) { R_SEXP_to_vector(initial, &c_initial); } if (!isNull(fixed)) { R_SEXP_to_vector_bool(fixed, &c_fixed); } /* Call igraph */ igraph_community_label_propagation(&c_graph, &c_membership, (isNull(weights) ? 0 : &c_weights), (isNull(initial) ? 0 : &c_initial), (isNull(fixed) ? 0 : &c_fixed), &c_modularity); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(membership=R_igraph_vector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); PROTECT(modularity=NEW_NUMERIC(1)); REAL(modularity)[0]=c_modularity; SET_VECTOR_ELT(result, 0, membership); SET_VECTOR_ELT(result, 1, modularity); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("membership")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("modularity")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_community_multilevel / /-------------------------------------------*/ SEXP R_igraph_community_multilevel(SEXP graph, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_weights; igraph_vector_t c_membership; igraph_matrix_t c_memberships; igraph_vector_t c_modularity; SEXP membership; SEXP memberships; SEXP modularity; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); if (0 != igraph_matrix_init(&c_memberships, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_memberships); memberships=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_modularity, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_modularity); modularity=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_community_multilevel(&c_graph, (isNull(weights) ? 0 : &c_weights), &c_membership, (isNull(memberships) ? 0 : &c_memberships), (isNull(modularity) ? 0 : &c_modularity)); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(membership=R_igraph_vector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); PROTECT(memberships=R_igraph_0ormatrix_to_SEXP(&c_memberships)); igraph_matrix_destroy(&c_memberships); IGRAPH_FINALLY_CLEAN(1); PROTECT(modularity=R_igraph_0orvector_to_SEXP(&c_modularity)); igraph_vector_destroy(&c_modularity); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, membership); SET_VECTOR_ELT(result, 1, memberships); SET_VECTOR_ELT(result, 2, modularity); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("membership")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("memberships")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("modularity")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_community_optimal_modularity / /-------------------------------------------*/ SEXP R_igraph_community_optimal_modularity(SEXP graph, SEXP weights) { /* Declarations */ igraph_t c_graph; igraph_real_t c_modularity; igraph_vector_t c_membership; igraph_vector_t c_weights; SEXP modularity; SEXP membership; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); membership=R_GlobalEnv; /* hack to have a non-NULL value */ if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } /* Call igraph */ igraph_community_optimal_modularity(&c_graph, &c_modularity, (isNull(membership) ? 0 : &c_membership), (isNull(weights) ? 0 : &c_weights)); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(modularity=NEW_NUMERIC(1)); REAL(modularity)[0]=c_modularity; PROTECT(membership=R_igraph_0orvector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, modularity); SET_VECTOR_ELT(result, 1, membership); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("modularity")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("membership")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_split_join_distance / /-------------------------------------------*/ SEXP R_igraph_split_join_distance(SEXP comm1, SEXP comm2) { /* Declarations */ igraph_vector_t c_comm1; igraph_vector_t c_comm2; igraph_integer_t c_distance12; igraph_integer_t c_distance21; SEXP distance12; SEXP distance21; SEXP result, names; /* Convert input */ R_SEXP_to_vector(comm1, &c_comm1); R_SEXP_to_vector(comm2, &c_comm2); /* Call igraph */ igraph_split_join_distance(&c_comm1, &c_comm2, &c_distance12, &c_distance21); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(distance12=NEW_INTEGER(1)); INTEGER(distance12)[0]=c_distance12; PROTECT(distance21=NEW_INTEGER(1)); INTEGER(distance21)[0]=c_distance21; SET_VECTOR_ELT(result, 0, distance12); SET_VECTOR_ELT(result, 1, distance21); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("distance12")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("distance21")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_fit / /-------------------------------------------*/ SEXP R_igraph_hrg_fit(SEXP graph, SEXP hrg, SEXP start, SEXP steps) { /* Declarations */ igraph_t c_graph; igraph_hrg_t c_hrg; igraph_bool_t c_start; int c_steps; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != R_SEXP_to_hrg_copy(hrg, &c_hrg)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_hrg_destroy, &c_hrg); c_start=LOGICAL(start)[0]; c_steps=INTEGER(steps)[0]; /* Call igraph */ igraph_hrg_fit(&c_graph, &c_hrg, c_start, c_steps); /* Convert output */ PROTECT(hrg=R_igraph_hrg_to_SEXP(&c_hrg)); igraph_hrg_destroy(&c_hrg); IGRAPH_FINALLY_CLEAN(1); result=hrg; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_game / /-------------------------------------------*/ SEXP R_igraph_hrg_game(SEXP hrg) { /* Declarations */ igraph_t c_graph; igraph_hrg_t c_hrg; SEXP graph; SEXP result; /* Convert input */ R_SEXP_to_hrg(hrg, &c_hrg); /* Call igraph */ igraph_hrg_game(&c_graph, &c_hrg); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_dendrogram / /-------------------------------------------*/ SEXP R_igraph_hrg_dendrogram(SEXP hrg) { /* Declarations */ igraph_t c_graph; igraph_hrg_t c_hrg; SEXP graph; SEXP result; /* Convert input */ R_SEXP_to_hrg(hrg, &c_hrg); /* Call igraph */ igraph_hrg_dendrogram(&c_graph, &c_hrg); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_consensus / /-------------------------------------------*/ SEXP R_igraph_hrg_consensus(SEXP graph, SEXP hrg, SEXP start, SEXP num_samples) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_parents; igraph_vector_t c_weights; igraph_hrg_t c_hrg; igraph_bool_t c_start; int c_num_samples; SEXP parents; SEXP weights; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_parents, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_parents); if (0 != igraph_vector_init(&c_weights, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_weights); if (0 != R_SEXP_to_hrg_copy(hrg, &c_hrg)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_hrg_destroy, &c_hrg); c_start=LOGICAL(start)[0]; c_num_samples=INTEGER(num_samples)[0]; /* Call igraph */ igraph_hrg_consensus(&c_graph, &c_parents, &c_weights, &c_hrg, c_start, c_num_samples); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(parents=R_igraph_vector_to_SEXP(&c_parents)); igraph_vector_destroy(&c_parents); IGRAPH_FINALLY_CLEAN(1); PROTECT(weights=R_igraph_vector_to_SEXP(&c_weights)); igraph_vector_destroy(&c_weights); IGRAPH_FINALLY_CLEAN(1); PROTECT(hrg=R_igraph_hrg_to_SEXP(&c_hrg)); igraph_hrg_destroy(&c_hrg); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, parents); SET_VECTOR_ELT(result, 1, weights); SET_VECTOR_ELT(result, 2, hrg); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("parents")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("weights")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("hrg")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_predict / /-------------------------------------------*/ SEXP R_igraph_hrg_predict(SEXP graph, SEXP hrg, SEXP start, SEXP num_samples, SEXP num_bins) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_edges; igraph_vector_t c_prob; igraph_hrg_t c_hrg; igraph_bool_t c_start; int c_num_samples; int c_num_bins; SEXP edges; SEXP prob; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_edges, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_edges); if (0 != igraph_vector_init(&c_prob, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_prob); if (0 != R_SEXP_to_hrg_copy(hrg, &c_hrg)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_hrg_destroy, &c_hrg); c_start=LOGICAL(start)[0]; c_num_samples=INTEGER(num_samples)[0]; c_num_bins=INTEGER(num_bins)[0]; /* Call igraph */ igraph_hrg_predict(&c_graph, &c_edges, &c_prob, &c_hrg, c_start, c_num_samples, c_num_bins); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(edges=R_igraph_vector_to_SEXPp1(&c_edges)); igraph_vector_destroy(&c_edges); IGRAPH_FINALLY_CLEAN(1); PROTECT(prob=R_igraph_vector_to_SEXP(&c_prob)); igraph_vector_destroy(&c_prob); IGRAPH_FINALLY_CLEAN(1); PROTECT(hrg=R_igraph_hrg_to_SEXP(&c_hrg)); igraph_hrg_destroy(&c_hrg); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, edges); SET_VECTOR_ELT(result, 1, prob); SET_VECTOR_ELT(result, 2, hrg); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("edges")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("prob")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("hrg")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_hrg_create / /-------------------------------------------*/ SEXP R_igraph_hrg_create(SEXP graph, SEXP prob) { /* Declarations */ igraph_hrg_t c_hrg; igraph_t c_graph; igraph_vector_t c_prob; SEXP hrg; SEXP result; /* Convert input */ if (0 != igraph_hrg_init(&c_hrg, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_hrg_destroy, &c_hrg); R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(prob, &c_prob); /* Call igraph */ igraph_hrg_create(&c_hrg, &c_graph, &c_prob); /* Convert output */ PROTECT(hrg=R_igraph_hrg_to_SEXP(&c_hrg)); igraph_hrg_destroy(&c_hrg); IGRAPH_FINALLY_CLEAN(1); result=hrg; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_community_infomap / /-------------------------------------------*/ SEXP R_igraph_community_infomap(SEXP graph, SEXP e_weights, SEXP v_weights, SEXP nb_trials) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_e_weights; igraph_vector_t c_v_weights; int c_nb_trials; igraph_vector_t c_membership; igraph_real_t c_codelength; SEXP membership; SEXP codelength; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(e_weights)) { R_SEXP_to_vector(e_weights, &c_e_weights); } if (!isNull(v_weights)) { R_SEXP_to_vector(v_weights, &c_v_weights); } c_nb_trials=INTEGER(nb_trials)[0]; if (0 != igraph_vector_init(&c_membership, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_membership); /* Call igraph */ igraph_community_infomap(&c_graph, (isNull(e_weights) ? 0 : &c_e_weights), (isNull(v_weights) ? 0 : &c_v_weights), c_nb_trials, &c_membership, &c_codelength); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(membership=R_igraph_vector_to_SEXP(&c_membership)); igraph_vector_destroy(&c_membership); IGRAPH_FINALLY_CLEAN(1); PROTECT(codelength=NEW_NUMERIC(1)); REAL(codelength)[0]=c_codelength; SET_VECTOR_ELT(result, 0, membership); SET_VECTOR_ELT(result, 1, codelength); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("membership")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("codelength")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_to_undirected / /-------------------------------------------*/ SEXP R_igraph_to_undirected(SEXP graph, SEXP mode, SEXP edge_attr_comb) { /* Declarations */ igraph_t c_graph; igraph_to_undirected_t c_mode; igraph_attribute_combination_t c_edge_attr_comb; SEXP result; /* Convert input */ R_SEXP_to_igraph_copy(graph, &c_graph); IGRAPH_FINALLY(igraph_destroy, &c_graph); c_mode=(igraph_to_undirected_t) REAL(mode)[0]; R_SEXP_to_attr_comb(edge_attr_comb, &c_edge_attr_comb); /* Call igraph */ igraph_to_undirected(&c_graph, c_mode, &c_edge_attr_comb); /* Convert output */ PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); igraph_attribute_combination_destroy(&c_edge_attr_comb); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_stochastic / /-------------------------------------------*/ SEXP R_igraph_get_stochastic(SEXP graph, SEXP column_wise) { /* Declarations */ igraph_t c_graph; igraph_matrix_t c_res; igraph_bool_t c_column_wise; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_matrix_init(&c_res, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_res); c_column_wise=LOGICAL(column_wise)[0]; /* Call igraph */ igraph_get_stochastic(&c_graph, &c_res, c_column_wise); /* Convert output */ PROTECT(res=R_igraph_matrix_to_SEXP(&c_res)); igraph_matrix_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_stochastic_sparsemat / /-------------------------------------------*/ SEXP R_igraph_get_stochastic_sparsemat(SEXP graph, SEXP column_wise) { /* Declarations */ igraph_t c_graph; igraph_sparsemat_t c_sparsemat; igraph_bool_t c_column_wise; SEXP sparsemat; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Don't need to init. */ c_column_wise=LOGICAL(column_wise)[0]; /* Call igraph */ igraph_get_stochastic_sparsemat(&c_graph, &c_sparsemat, c_column_wise); /* Convert output */ PROTECT(sparsemat=R_igraph_sparsemat_to_SEXP(&c_sparsemat)); igraph_sparsemat_destroy(&c_sparsemat); IGRAPH_FINALLY_CLEAN(1); result=sparsemat; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_dyad_census / /-------------------------------------------*/ SEXP R_igraph_dyad_census(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_mut; igraph_integer_t c_asym; igraph_integer_t c_null; SEXP mut; SEXP asym; SEXP null; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ igraph_dyad_census(&c_graph, &c_mut, &c_asym, &c_null); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(mut=NEW_INTEGER(1)); INTEGER(mut)[0]=c_mut; PROTECT(asym=NEW_INTEGER(1)); INTEGER(asym)[0]=c_asym; PROTECT(null=NEW_INTEGER(1)); INTEGER(null)[0]=c_null; SET_VECTOR_ELT(result, 0, mut); SET_VECTOR_ELT(result, 1, asym); SET_VECTOR_ELT(result, 2, null); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("mut")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("asym")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("null")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_triad_census / /-------------------------------------------*/ SEXP R_igraph_triad_census(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); /* Call igraph */ igraph_triad_census(&c_graph, &c_res); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_adjacent_triangles / /-------------------------------------------*/ SEXP R_igraph_adjacent_triangles(SEXP graph, SEXP vids) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vs_t c_vids; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); R_SEXP_to_igraph_vs(vids, &c_graph, &c_vids); /* Call igraph */ igraph_adjacent_triangles(&c_graph, &c_res, c_vids); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); igraph_vs_destroy(&c_vids); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_0 / /-------------------------------------------*/ SEXP R_igraph_local_scan_0(SEXP graph, SEXP weights, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vector_t c_weights; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_0(&c_graph, &c_res, (isNull(weights) ? 0 : &c_weights), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_0_them / /-------------------------------------------*/ SEXP R_igraph_local_scan_0_them(SEXP us, SEXP them, SEXP weights_them, SEXP mode) { /* Declarations */ igraph_t c_us; igraph_t c_them; igraph_vector_t c_res; igraph_vector_t c_weights_them; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(us, &c_us); R_SEXP_to_igraph(them, &c_them); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights_them)) { R_SEXP_to_vector(weights_them, &c_weights_them); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_0_them(&c_us, &c_them, &c_res, (isNull(weights_them) ? 0 : &c_weights_them), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_1_ecount / /-------------------------------------------*/ SEXP R_igraph_local_scan_1_ecount(SEXP graph, SEXP weights, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vector_t c_weights; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_1_ecount(&c_graph, &c_res, (isNull(weights) ? 0 : &c_weights), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_1_ecount_them / /-------------------------------------------*/ SEXP R_igraph_local_scan_1_ecount_them(SEXP us, SEXP them, SEXP weights_them, SEXP mode) { /* Declarations */ igraph_t c_us; igraph_t c_them; igraph_vector_t c_res; igraph_vector_t c_weights_them; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(us, &c_us); R_SEXP_to_igraph(them, &c_them); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights_them)) { R_SEXP_to_vector(weights_them, &c_weights_them); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_1_ecount_them(&c_us, &c_them, &c_res, (isNull(weights_them) ? 0 : &c_weights_them), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_k_ecount / /-------------------------------------------*/ SEXP R_igraph_local_scan_k_ecount(SEXP graph, SEXP k, SEXP weights, SEXP mode) { /* Declarations */ igraph_t c_graph; int c_k; igraph_vector_t c_res; igraph_vector_t c_weights; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_k=INTEGER(k)[0]; if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_k_ecount(&c_graph, c_k, &c_res, (isNull(weights) ? 0 : &c_weights), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_k_ecount_them / /-------------------------------------------*/ SEXP R_igraph_local_scan_k_ecount_them(SEXP us, SEXP them, SEXP k, SEXP weights_them, SEXP mode) { /* Declarations */ igraph_t c_us; igraph_t c_them; int c_k; igraph_vector_t c_res; igraph_vector_t c_weights_them; igraph_neimode_t c_mode; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(us, &c_us); R_SEXP_to_igraph(them, &c_them); c_k=INTEGER(k)[0]; if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights_them)) { R_SEXP_to_vector(weights_them, &c_weights_them); } c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_local_scan_k_ecount_them(&c_us, &c_them, c_k, &c_res, (isNull(weights_them) ? 0 : &c_weights_them), c_mode); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_local_scan_neighborhood_ecount / /-------------------------------------------*/ SEXP R_igraph_local_scan_neighborhood_ecount(SEXP graph, SEXP weights, SEXP neighborhoods) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_res; igraph_vector_t c_weights; igraph_vector_ptr_t c_neighborhoods; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_res); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } if (!isNull(neighborhoods)) { R_igraph_SEXP_to_vectorlist_int(neighborhoods, &c_neighborhoods); } /* Call igraph */ igraph_local_scan_neighborhood_ecount(&c_graph, &c_res, (isNull(weights) ? 0 : &c_weights), &c_neighborhoods); /* Convert output */ PROTECT(res=R_igraph_vector_to_SEXP(&c_res)); igraph_vector_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_list_triangles / /-------------------------------------------*/ SEXP R_igraph_list_triangles(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_int_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_int_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_int_destroy, &c_res); /* Call igraph */ igraph_list_triangles(&c_graph, &c_res); /* Convert output */ PROTECT(res=R_igraph_vector_int_to_SEXPp1(&c_res)); igraph_vector_int_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_maxflow / /-------------------------------------------*/ SEXP R_igraph_maxflow(SEXP graph, SEXP source, SEXP target, SEXP capacity) { /* Declarations */ igraph_t c_graph; igraph_real_t c_value; igraph_vector_t c_flow; igraph_vector_t c_cut; igraph_vector_t c_partition1; igraph_vector_t c_partition2; igraph_integer_t c_source; igraph_integer_t c_target; igraph_vector_t c_capacity; igraph_maxflow_stats_t c_stats; SEXP value; SEXP flow; SEXP cut; SEXP partition1; SEXP partition2; SEXP stats; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_flow, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_flow); flow=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_cut, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_cut); cut=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_partition1, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_partition1); if (0 != igraph_vector_init(&c_partition2, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_partition2); c_source=(igraph_integer_t) REAL(source)[0]; c_target=(igraph_integer_t) REAL(target)[0]; if (!isNull(capacity)) { R_SEXP_to_vector(capacity, &c_capacity); } /* Call igraph */ igraph_maxflow(&c_graph, &c_value, (isNull(flow) ? 0 : &c_flow), (isNull(cut) ? 0 : &c_cut), &c_partition1, &c_partition2, c_source, c_target, (isNull(capacity) ? 0 : &c_capacity), &c_stats); /* Convert output */ PROTECT(result=NEW_LIST(6)); PROTECT(names=NEW_CHARACTER(6)); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(flow=R_igraph_0orvector_to_SEXP(&c_flow)); igraph_vector_destroy(&c_flow); IGRAPH_FINALLY_CLEAN(1); PROTECT(cut=R_igraph_0orvector_to_SEXPp1(&c_cut)); igraph_vector_destroy(&c_cut); IGRAPH_FINALLY_CLEAN(1); PROTECT(partition1=R_igraph_vector_to_SEXPp1(&c_partition1)); igraph_vector_destroy(&c_partition1); IGRAPH_FINALLY_CLEAN(1); PROTECT(partition2=R_igraph_vector_to_SEXPp1(&c_partition2)); igraph_vector_destroy(&c_partition2); IGRAPH_FINALLY_CLEAN(1); PROTECT(stats=R_igraph_maxflow_stats_to_SEXP(&c_stats)); SET_VECTOR_ELT(result, 0, value); SET_VECTOR_ELT(result, 1, flow); SET_VECTOR_ELT(result, 2, cut); SET_VECTOR_ELT(result, 3, partition1); SET_VECTOR_ELT(result, 4, partition2); SET_VECTOR_ELT(result, 5, stats); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("flow")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("cut")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("partition1")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("partition2")); SET_STRING_ELT(names, 5, CREATE_STRING_VECTOR("stats")); SET_NAMES(result, names); UNPROTECT(7); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_dominator_tree / /-------------------------------------------*/ SEXP R_igraph_dominator_tree(SEXP graph, SEXP root, SEXP mode) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_root; igraph_vector_t c_dom; igraph_t c_domtree; igraph_vector_t c_leftout; igraph_neimode_t c_mode; SEXP dom; SEXP domtree; SEXP leftout; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_root=(igraph_integer_t) REAL(root)[0]; if (0 != igraph_vector_init(&c_dom, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_dom); domtree=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_leftout, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_leftout); c_mode=(igraph_neimode_t) REAL(mode)[0]; /* Call igraph */ igraph_dominator_tree(&c_graph, c_root, &c_dom, (isNull(domtree) ? 0 : &c_domtree), &c_leftout, c_mode); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(dom=R_igraph_vector_to_SEXPp1(&c_dom)); igraph_vector_destroy(&c_dom); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &c_domtree); PROTECT(domtree=R_igraph_to_SEXP(&c_domtree)); igraph_destroy(&c_domtree); IGRAPH_FINALLY_CLEAN(1); PROTECT(leftout=R_igraph_vector_to_SEXPp1(&c_leftout)); igraph_vector_destroy(&c_leftout); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, dom); SET_VECTOR_ELT(result, 1, domtree); SET_VECTOR_ELT(result, 2, leftout); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("dom")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("domtree")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("leftout")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_all_st_cuts / /-------------------------------------------*/ SEXP R_igraph_all_st_cuts(SEXP graph, SEXP source, SEXP target) { /* Declarations */ igraph_t c_graph; igraph_vector_ptr_t c_cuts; igraph_vector_ptr_t c_partition1s; igraph_integer_t c_source; igraph_integer_t c_target; SEXP cuts; SEXP partition1s; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_cuts, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_cuts); if (0 != igraph_vector_ptr_init(&c_partition1s, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_partition1s); c_source=(igraph_integer_t) REAL(source)[0]; c_target=(igraph_integer_t) REAL(target)[0]; /* Call igraph */ igraph_all_st_cuts(&c_graph, &c_cuts, &c_partition1s, c_source, c_target); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(cuts=R_igraph_vectorlist_to_SEXP_p1(&c_cuts)); R_igraph_vectorlist_destroy(&c_cuts); IGRAPH_FINALLY_CLEAN(1); PROTECT(partition1s=R_igraph_vectorlist_to_SEXP_p1(&c_partition1s)); R_igraph_vectorlist_destroy(&c_partition1s); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, cuts); SET_VECTOR_ELT(result, 1, partition1s); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("cuts")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("partition1s")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_all_st_mincuts / /-------------------------------------------*/ SEXP R_igraph_all_st_mincuts(SEXP graph, SEXP source, SEXP target, SEXP capacity) { /* Declarations */ igraph_t c_graph; igraph_real_t c_value; igraph_vector_ptr_t c_cuts; igraph_vector_ptr_t c_partition1s; igraph_integer_t c_source; igraph_integer_t c_target; igraph_vector_t c_capacity; SEXP value; SEXP cuts; SEXP partition1s; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_cuts, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_cuts); if (0 != igraph_vector_ptr_init(&c_partition1s, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_partition1s); c_source=(igraph_integer_t) REAL(source)[0]; c_target=(igraph_integer_t) REAL(target)[0]; if (!isNull(capacity)) { R_SEXP_to_vector(capacity, &c_capacity); } /* Call igraph */ igraph_all_st_mincuts(&c_graph, &c_value, &c_cuts, &c_partition1s, c_source, c_target, (isNull(capacity) ? 0 : &c_capacity)); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(value=NEW_NUMERIC(1)); REAL(value)[0]=c_value; PROTECT(cuts=R_igraph_vectorlist_to_SEXP_p1(&c_cuts)); R_igraph_vectorlist_destroy(&c_cuts); IGRAPH_FINALLY_CLEAN(1); PROTECT(partition1s=R_igraph_vectorlist_to_SEXP_p1(&c_partition1s)); R_igraph_vectorlist_destroy(&c_partition1s); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, value); SET_VECTOR_ELT(result, 1, cuts); SET_VECTOR_ELT(result, 2, partition1s); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("value")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("cuts")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("partition1s")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_separator / /-------------------------------------------*/ SEXP R_igraph_is_separator(SEXP graph, SEXP candidate) { /* Declarations */ igraph_t c_graph; igraph_vs_t c_candidate; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_igraph_vs(candidate, &c_graph, &c_candidate); /* Call igraph */ igraph_is_separator(&c_graph, c_candidate, &c_res); /* Convert output */ igraph_vs_destroy(&c_candidate); PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_minimal_separator / /-------------------------------------------*/ SEXP R_igraph_is_minimal_separator(SEXP graph, SEXP candidate) { /* Declarations */ igraph_t c_graph; igraph_vs_t c_candidate; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_igraph_vs(candidate, &c_graph, &c_candidate); /* Call igraph */ igraph_is_minimal_separator(&c_graph, c_candidate, &c_res); /* Convert output */ igraph_vs_destroy(&c_candidate); PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_all_minimal_st_separators / /-------------------------------------------*/ SEXP R_igraph_all_minimal_st_separators(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_ptr_t c_separators; SEXP separators; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_separators, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_separators); /* Call igraph */ igraph_all_minimal_st_separators(&c_graph, &c_separators); /* Convert output */ PROTECT(separators=R_igraph_vectorlist_to_SEXP_p1(&c_separators)); R_igraph_vectorlist_destroy(&c_separators); IGRAPH_FINALLY_CLEAN(1); result=separators; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_minimum_size_separators / /-------------------------------------------*/ SEXP R_igraph_minimum_size_separators(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_vector_ptr_t c_separators; SEXP separators; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_ptr_init(&c_separators, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_separators); /* Call igraph */ igraph_minimum_size_separators(&c_graph, &c_separators); /* Convert output */ PROTECT(separators=R_igraph_vectorlist_to_SEXP_p1(&c_separators)); R_igraph_vectorlist_destroy(&c_separators); IGRAPH_FINALLY_CLEAN(1); result=separators; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isoclass / /-------------------------------------------*/ SEXP R_igraph_isoclass(SEXP graph) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_isoclass; SEXP isoclass; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); /* Call igraph */ igraph_isoclass(&c_graph, &c_isoclass); /* Convert output */ PROTECT(isoclass=NEW_INTEGER(1)); INTEGER(isoclass)[0]=c_isoclass; result=isoclass; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isomorphic / /-------------------------------------------*/ SEXP R_igraph_isomorphic(SEXP graph1, SEXP graph2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_bool_t c_iso; SEXP iso; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); /* Call igraph */ igraph_isomorphic(&c_graph1, &c_graph2, &c_iso); /* Convert output */ PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; result=iso; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isoclass_subgraph / /-------------------------------------------*/ SEXP R_igraph_isoclass_subgraph(SEXP graph, SEXP vids) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_vids; igraph_integer_t c_isoclass; SEXP isoclass; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(vids, &c_vids); /* Call igraph */ igraph_isoclass_subgraph(&c_graph, &c_vids, &c_isoclass); /* Convert output */ PROTECT(isoclass=NEW_INTEGER(1)); INTEGER(isoclass)[0]=c_isoclass; result=isoclass; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isoclass_create / /-------------------------------------------*/ SEXP R_igraph_isoclass_create(SEXP size, SEXP number, SEXP directed) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_size; igraph_integer_t c_number; igraph_bool_t c_directed; SEXP graph; SEXP result; /* Convert input */ c_size=INTEGER(size)[0]; c_number=INTEGER(number)[0]; c_directed=LOGICAL(directed)[0]; /* Call igraph */ igraph_isoclass_create(&c_graph, c_size, c_number, c_directed); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_graph); PROTECT(graph=R_igraph_to_SEXP(&c_graph)); igraph_destroy(&c_graph); IGRAPH_FINALLY_CLEAN(1); result=graph; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isomorphic_vf2 / /-------------------------------------------*/ SEXP R_igraph_isomorphic_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_bool_t c_iso; igraph_vector_t c_map12; igraph_vector_t c_map21; SEXP iso; SEXP map12; SEXP map21; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } if (0 != igraph_vector_init(&c_map12, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map12); map12=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_map21, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map21); map21=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_isomorphic_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_iso, (isNull(map12) ? 0 : &c_map12), (isNull(map21) ? 0 : &c_map21), 0, 0, 0); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; PROTECT(map12=R_igraph_0orvector_to_SEXPp1(&c_map12)); igraph_vector_destroy(&c_map12); IGRAPH_FINALLY_CLEAN(1); PROTECT(map21=R_igraph_0orvector_to_SEXPp1(&c_map21)); igraph_vector_destroy(&c_map21); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, iso); SET_VECTOR_ELT(result, 1, map12); SET_VECTOR_ELT(result, 2, map21); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("iso")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("map12")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("map21")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_count_isomorphisms_vf2 / /-------------------------------------------*/ SEXP R_igraph_count_isomorphisms_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_integer_t c_count; SEXP count; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } /* Call igraph */ igraph_count_isomorphisms_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_count, 0, 0, 0); /* Convert output */ PROTECT(count=NEW_INTEGER(1)); INTEGER(count)[0]=c_count; result=count; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_isomorphisms_vf2 / /-------------------------------------------*/ SEXP R_igraph_get_isomorphisms_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_vector_ptr_t c_maps; SEXP maps; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } if (0 != igraph_vector_ptr_init(&c_maps, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_maps); /* Call igraph */ igraph_get_isomorphisms_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_maps, 0, 0, 0); /* Convert output */ PROTECT(maps=R_igraph_vectorlist_to_SEXP(&c_maps)); R_igraph_vectorlist_destroy(&c_maps); IGRAPH_FINALLY_CLEAN(1); result=maps; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_subisomorphic_vf2 / /-------------------------------------------*/ SEXP R_igraph_subisomorphic_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_bool_t c_iso; igraph_vector_t c_map12; igraph_vector_t c_map21; SEXP iso; SEXP map12; SEXP map21; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } if (0 != igraph_vector_init(&c_map12, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map12); map12=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_map21, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map21); map21=R_GlobalEnv; /* hack to have a non-NULL value */ /* Call igraph */ igraph_subisomorphic_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_iso, (isNull(map12) ? 0 : &c_map12), (isNull(map21) ? 0 : &c_map21), 0, 0, 0); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; PROTECT(map12=R_igraph_0orvector_to_SEXPp1(&c_map12)); igraph_vector_destroy(&c_map12); IGRAPH_FINALLY_CLEAN(1); PROTECT(map21=R_igraph_0orvector_to_SEXPp1(&c_map21)); igraph_vector_destroy(&c_map21); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, iso); SET_VECTOR_ELT(result, 1, map12); SET_VECTOR_ELT(result, 2, map21); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("iso")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("map12")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("map21")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_count_subisomorphisms_vf2 / /-------------------------------------------*/ SEXP R_igraph_count_subisomorphisms_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_integer_t c_count; SEXP count; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } /* Call igraph */ igraph_count_subisomorphisms_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_count, 0, 0, 0); /* Convert output */ PROTECT(count=NEW_INTEGER(1)); INTEGER(count)[0]=c_count; result=count; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_get_subisomorphisms_vf2 / /-------------------------------------------*/ SEXP R_igraph_get_subisomorphisms_vf2(SEXP graph1, SEXP graph2, SEXP vertex_color1, SEXP vertex_color2, SEXP edge_color1, SEXP edge_color2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_vector_int_t c_vertex_color1; igraph_vector_int_t c_vertex_color2; igraph_vector_int_t c_edge_color1; igraph_vector_int_t c_edge_color2; igraph_vector_ptr_t c_maps; SEXP maps; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (!isNull(vertex_color1)) { R_SEXP_to_vector_int(vertex_color1, &c_vertex_color1); } if (!isNull(vertex_color2)) { R_SEXP_to_vector_int(vertex_color2, &c_vertex_color2); } if (!isNull(edge_color1)) { R_SEXP_to_vector_int(edge_color1, &c_edge_color1); } if (!isNull(edge_color2)) { R_SEXP_to_vector_int(edge_color2, &c_edge_color2); } if (0 != igraph_vector_ptr_init(&c_maps, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_vectorlist_destroy, &c_maps); /* Call igraph */ igraph_get_subisomorphisms_vf2(&c_graph1, &c_graph2, (isNull(vertex_color1) ? 0 : &c_vertex_color1), (isNull(vertex_color2) ? 0 : &c_vertex_color2), (isNull(edge_color1) ? 0 : &c_edge_color1), (isNull(edge_color2) ? 0 : &c_edge_color2), &c_maps, 0, 0, 0); /* Convert output */ PROTECT(maps=R_igraph_vectorlist_to_SEXP(&c_maps)); R_igraph_vectorlist_destroy(&c_maps); IGRAPH_FINALLY_CLEAN(1); result=maps; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isomorphic_34 / /-------------------------------------------*/ SEXP R_igraph_isomorphic_34(SEXP graph1, SEXP graph2) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_bool_t c_iso; SEXP iso; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); /* Call igraph */ igraph_isomorphic_34(&c_graph1, &c_graph2, &c_iso); /* Convert output */ PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; result=iso; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_canonical_permutation / /-------------------------------------------*/ SEXP R_igraph_canonical_permutation(SEXP graph, SEXP sh) { /* Declarations */ igraph_t c_graph; igraph_vector_t c_labeling; igraph_bliss_sh_t c_sh; igraph_bliss_info_t c_info; SEXP labeling; SEXP info; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (0 != igraph_vector_init(&c_labeling, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_labeling); c_sh=REAL(sh)[0]; /* Call igraph */ igraph_canonical_permutation(&c_graph, 0, &c_labeling, c_sh, &c_info); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(labeling=R_igraph_vector_to_SEXPp1(&c_labeling)); igraph_vector_destroy(&c_labeling); IGRAPH_FINALLY_CLEAN(1); PROTECT(info=R_igraph_bliss_info_to_SEXP(&c_info)); if (c_info.group_size) { free(c_info.group_size); } SET_VECTOR_ELT(result, 0, labeling); SET_VECTOR_ELT(result, 1, info); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("labeling")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("info")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_permute_vertices / /-------------------------------------------*/ SEXP R_igraph_permute_vertices(SEXP graph, SEXP permutation) { /* Declarations */ igraph_t c_graph; igraph_t c_res; igraph_vector_t c_permutation; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); R_SEXP_to_vector(permutation, &c_permutation); /* Call igraph */ igraph_permute_vertices(&c_graph, &c_res, &c_permutation); /* Convert output */ IGRAPH_FINALLY(igraph_destroy, &c_res); PROTECT(res=R_igraph_to_SEXP(&c_res)); igraph_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_isomorphic_bliss / /-------------------------------------------*/ SEXP R_igraph_isomorphic_bliss(SEXP graph1, SEXP graph2, SEXP sh) { /* Declarations */ igraph_t c_graph1; igraph_t c_graph2; igraph_bool_t c_iso; igraph_vector_t c_map12; igraph_vector_t c_map21; igraph_bliss_sh_t c_sh; igraph_bliss_info_t c_info1; igraph_bliss_info_t c_info2; SEXP iso; SEXP map12; SEXP map21; SEXP info1; SEXP info2; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph1, &c_graph1); R_SEXP_to_igraph(graph2, &c_graph2); if (0 != igraph_vector_init(&c_map12, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map12); map12=R_GlobalEnv; /* hack to have a non-NULL value */ if (0 != igraph_vector_init(&c_map21, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_map21); map21=R_GlobalEnv; /* hack to have a non-NULL value */ c_sh=REAL(sh)[0]; /* Call igraph */ igraph_isomorphic_bliss(&c_graph1, &c_graph2, 0, 0, &c_iso, (isNull(map12) ? 0 : &c_map12), (isNull(map21) ? 0 : &c_map21), c_sh, &c_info1, &c_info2); /* Convert output */ PROTECT(result=NEW_LIST(5)); PROTECT(names=NEW_CHARACTER(5)); PROTECT(iso=NEW_LOGICAL(1)); LOGICAL(iso)[0]=c_iso; PROTECT(map12=R_igraph_0orvector_to_SEXPp1(&c_map12)); igraph_vector_destroy(&c_map12); IGRAPH_FINALLY_CLEAN(1); PROTECT(map21=R_igraph_0orvector_to_SEXPp1(&c_map21)); igraph_vector_destroy(&c_map21); IGRAPH_FINALLY_CLEAN(1); PROTECT(info1=R_igraph_bliss_info_to_SEXP(&c_info1)); if (c_info1.group_size) { free(c_info1.group_size); } PROTECT(info2=R_igraph_bliss_info_to_SEXP(&c_info2)); if (c_info2.group_size) { free(c_info2.group_size); } SET_VECTOR_ELT(result, 0, iso); SET_VECTOR_ELT(result, 1, map12); SET_VECTOR_ELT(result, 2, map21); SET_VECTOR_ELT(result, 3, info1); SET_VECTOR_ELT(result, 4, info2); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("iso")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("map12")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("map21")); SET_STRING_ELT(names, 3, CREATE_STRING_VECTOR("info1")); SET_STRING_ELT(names, 4, CREATE_STRING_VECTOR("info2")); SET_NAMES(result, names); UNPROTECT(6); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_automorphisms / /-------------------------------------------*/ SEXP R_igraph_automorphisms(SEXP graph, SEXP sh) { /* Declarations */ igraph_t c_graph; igraph_bliss_sh_t c_sh; igraph_bliss_info_t c_info; SEXP info; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_sh=REAL(sh)[0]; /* Call igraph */ igraph_automorphisms(&c_graph, 0, c_sh, &c_info); /* Convert output */ PROTECT(info=R_igraph_bliss_info_to_SEXP(&c_info)); if (c_info.group_size) { free(c_info.group_size); } result=info; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_scg_grouping / /-------------------------------------------*/ SEXP R_igraph_scg_grouping(SEXP V, SEXP nt, SEXP nt_vec, SEXP mtype, SEXP algo, SEXP p, SEXP maxiter) { /* Declarations */ igraph_matrix_t c_V; igraph_vector_t c_groups; igraph_integer_t c_nt; igraph_vector_t c_nt_vec; igraph_scg_matrix_t c_mtype; igraph_scg_algorithm_t c_algo; igraph_vector_t c_p; igraph_integer_t c_maxiter; SEXP groups; SEXP result; /* Convert input */ R_SEXP_to_matrix(V, &c_V); if (0 != igraph_vector_init(&c_groups, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_groups); c_nt=INTEGER(nt)[0]; if (!isNull(nt_vec)) { R_SEXP_to_vector(nt_vec, &c_nt_vec); } c_mtype=(igraph_scg_matrix_t) REAL(mtype)[0]; c_algo=(igraph_scg_algorithm_t) REAL(algo)[0]; if (!isNull(p)) { R_SEXP_to_vector(p, &c_p); } c_maxiter=INTEGER(maxiter)[0]; /* Call igraph */ igraph_scg_grouping(&c_V, &c_groups, c_nt, (isNull(nt_vec) ? 0 : &c_nt_vec), c_mtype, c_algo, (isNull(p) ? 0 : &c_p), c_maxiter); /* Convert output */ PROTECT(groups=R_igraph_vector_to_SEXPp1(&c_groups)); igraph_vector_destroy(&c_groups); IGRAPH_FINALLY_CLEAN(1); result=groups; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_scg_norm_eps / /-------------------------------------------*/ SEXP R_igraph_scg_norm_eps(SEXP V, SEXP groups, SEXP mtype, SEXP p, SEXP norm) { /* Declarations */ igraph_matrix_t c_V; igraph_vector_t c_groups; igraph_vector_t c_eps; igraph_scg_matrix_t c_mtype; igraph_vector_t c_p; igraph_scg_norm_t c_norm; SEXP eps; SEXP result; /* Convert input */ R_SEXP_to_matrix(V, &c_V); R_SEXP_to_vector(groups, &c_groups); if (0 != igraph_vector_init(&c_eps, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_eps); c_mtype=(igraph_scg_matrix_t) REAL(mtype)[0]; if (!isNull(p)) { R_SEXP_to_vector(p, &c_p); } c_norm=(igraph_scg_norm_t) REAL(norm)[0]; /* Call igraph */ igraph_scg_norm_eps(&c_V, &c_groups, &c_eps, c_mtype, (isNull(p) ? 0 : &c_p), c_norm); /* Convert output */ PROTECT(eps=R_igraph_vector_to_SEXP(&c_eps)); igraph_vector_destroy(&c_eps); IGRAPH_FINALLY_CLEAN(1); result=eps; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_matching / /-------------------------------------------*/ SEXP R_igraph_is_matching(SEXP graph, SEXP types, SEXP matching) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_vector_long_t c_matching; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } R_SEXP_to_vector_long_copy(matching, &c_matching); /* Call igraph */ igraph_is_matching(&c_graph, (isNull(types) ? 0 : &c_types), &c_matching, &c_res); /* Convert output */ igraph_vector_long_destroy(&c_matching); PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_is_maximal_matching / /-------------------------------------------*/ SEXP R_igraph_is_maximal_matching(SEXP graph, SEXP types, SEXP matching) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_vector_long_t c_matching; igraph_bool_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } R_SEXP_to_vector_long_copy(matching, &c_matching); /* Call igraph */ igraph_is_maximal_matching(&c_graph, (isNull(types) ? 0 : &c_types), &c_matching, &c_res); /* Convert output */ igraph_vector_long_destroy(&c_matching); PROTECT(res=NEW_LOGICAL(1)); LOGICAL(res)[0]=c_res; result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_maximum_bipartite_matching / /-------------------------------------------*/ SEXP R_igraph_maximum_bipartite_matching(SEXP graph, SEXP types, SEXP weights, SEXP eps) { /* Declarations */ igraph_t c_graph; igraph_vector_bool_t c_types; igraph_integer_t c_matching_size; igraph_real_t c_matching_weight; igraph_vector_long_t c_matching; igraph_vector_t c_weights; igraph_real_t c_eps; SEXP matching_size; SEXP matching_weight; SEXP matching; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); if (!isNull(types)) { R_SEXP_to_vector_bool(types, &c_types); } if (0 != igraph_vector_long_init(&c_matching, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_long_destroy, &c_matching); if (!isNull(weights)) { R_SEXP_to_vector(weights, &c_weights); } c_eps=REAL(eps)[0]; /* Call igraph */ igraph_maximum_bipartite_matching(&c_graph, (isNull(types) ? 0 : &c_types), &c_matching_size, &c_matching_weight, &c_matching, (isNull(weights) ? 0 : &c_weights), c_eps); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(matching_size=NEW_INTEGER(1)); INTEGER(matching_size)[0]=c_matching_size; PROTECT(matching_weight=NEW_NUMERIC(1)); REAL(matching_weight)[0]=c_matching_weight; PROTECT(matching=R_igraph_vector_long_to_SEXPp1(&c_matching)); igraph_vector_long_destroy(&c_matching); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, matching_size); SET_VECTOR_ELT(result, 1, matching_weight); SET_VECTOR_ELT(result, 2, matching); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("matching_size")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("matching_weight")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("matching")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_eigen_adjacency / /-------------------------------------------*/ SEXP R_igraph_eigen_adjacency(SEXP graph, SEXP algorithm, SEXP which, SEXP options) { /* Declarations */ igraph_t c_graph; igraph_integer_t c_algorithm; igraph_eigen_which_t c_which; igraph_arpack_options_t c_options; igraph_vector_t c_values; igraph_matrix_t c_vectors; SEXP values; SEXP vectors; SEXP result, names; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_algorithm=REAL(algorithm)[0]; R_SEXP_to_igraph_eigen_which(which, &c_which); R_SEXP_to_igraph_arpack_options(options, &c_options); if (0 != igraph_vector_init(&c_values, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_values); if (0 != igraph_matrix_init(&c_vectors, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_vectors); /* Call igraph */ igraph_eigen_adjacency(&c_graph, c_algorithm, &c_which, &c_options, 0, &c_values, &c_vectors, 0, 0); /* Convert output */ PROTECT(result=NEW_LIST(3)); PROTECT(names=NEW_CHARACTER(3)); PROTECT(options=R_igraph_arpack_options_to_SEXP(&c_options)); PROTECT(values=R_igraph_vector_to_SEXP(&c_values)); igraph_vector_destroy(&c_values); IGRAPH_FINALLY_CLEAN(1); PROTECT(vectors=R_igraph_matrix_to_SEXP(&c_vectors)); igraph_matrix_destroy(&c_vectors); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, options); SET_VECTOR_ELT(result, 1, values); SET_VECTOR_ELT(result, 2, vectors); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("options")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("values")); SET_STRING_ELT(names, 2, CREATE_STRING_VECTOR("vectors")); SET_NAMES(result, names); UNPROTECT(4); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_power_law_fit / /-------------------------------------------*/ SEXP R_igraph_power_law_fit(SEXP data, SEXP xmin, SEXP force_continuous) { /* Declarations */ igraph_vector_t c_data; igraph_plfit_result_t c_res; igraph_real_t c_xmin; igraph_bool_t c_force_continuous; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_vector(data, &c_data); c_xmin=REAL(xmin)[0]; c_force_continuous=LOGICAL(force_continuous)[0]; /* Call igraph */ igraph_power_law_fit(&c_data, &c_res, c_xmin, c_force_continuous); /* Convert output */ PROTECT(res=R_igraph_plfit_result_to_SEXP(&c_res)); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_sir / /-------------------------------------------*/ SEXP R_igraph_sir(SEXP graph, SEXP beta, SEXP gamma, SEXP no_sim) { /* Declarations */ igraph_t c_graph; igraph_real_t c_beta; igraph_real_t c_gamma; igraph_integer_t c_no_sim; igraph_vector_ptr_t c_res; SEXP res; SEXP result; /* Convert input */ R_SEXP_to_igraph(graph, &c_graph); c_beta=REAL(beta)[0]; c_gamma=REAL(gamma)[0]; c_no_sim=INTEGER(no_sim)[0]; if (0 != igraph_vector_ptr_init(&c_res, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(R_igraph_sirlist_destroy, &c_res); /* Call igraph */ igraph_sir(&c_graph, c_beta, c_gamma, c_no_sim, &c_res); /* Convert output */ PROTECT(res=R_igraph_sirlist_to_SEXP(&c_res)); R_igraph_sirlist_destroy(&c_res); IGRAPH_FINALLY_CLEAN(1); result=res; UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_convex_hull / /-------------------------------------------*/ SEXP R_igraph_convex_hull(SEXP data) { /* Declarations */ igraph_matrix_t c_data; igraph_vector_t c_resverts; igraph_matrix_t c_rescoords; SEXP resverts; SEXP rescoords; SEXP result, names; /* Convert input */ R_SEXP_to_matrix(data, &c_data); if (0 != igraph_vector_init(&c_resverts, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_vector_destroy, &c_resverts); if (0 != igraph_matrix_init(&c_rescoords, 0, 0)) { igraph_error("", __FILE__, __LINE__, IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_matrix_destroy, &c_rescoords); /* Call igraph */ igraph_convex_hull(&c_data, &c_resverts, &c_rescoords); /* Convert output */ PROTECT(result=NEW_LIST(2)); PROTECT(names=NEW_CHARACTER(2)); PROTECT(resverts=R_igraph_vector_to_SEXP(&c_resverts)); igraph_vector_destroy(&c_resverts); IGRAPH_FINALLY_CLEAN(1); PROTECT(rescoords=R_igraph_matrix_to_SEXP(&c_rescoords)); igraph_matrix_destroy(&c_rescoords); IGRAPH_FINALLY_CLEAN(1); SET_VECTOR_ELT(result, 0, resverts); SET_VECTOR_ELT(result, 1, rescoords); SET_STRING_ELT(names, 0, CREATE_STRING_VECTOR("resverts")); SET_STRING_ELT(names, 1, CREATE_STRING_VECTOR("rescoords")); SET_NAMES(result, names); UNPROTECT(3); UNPROTECT(1); return(result); } /*-------------------------------------------/ / igraph_dim_select / /-------------------------------------------*/ SEXP R_igraph_dim_select(SEXP sv) { /* Declarations */ igraph_vector_t c_sv; igraph_integer_t c_dim; SEXP dim; SEXP result; /* Convert input */ R_SEXP_to_vector(sv, &c_sv); /* Call igraph */ igraph_dim_select(&c_sv, &c_dim); /* Convert output */ PROTECT(dim=NEW_INTEGER(1)); INTEGER(dim)[0]=c_dim; result=dim; UNPROTECT(1); return(result); } igraph/src/igraph_estack.h0000644000175100001440000000302713431000472015302 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_ESTACK_H #define IGRAPH_ESTACK_H #include "igraph_stack.h" #include "igraph_vector.h" typedef struct igraph_estack_t { igraph_stack_long_t stack; igraph_vector_bool_t isin; } igraph_estack_t; int igraph_estack_init(igraph_estack_t *s, long int setsize, long int stacksize); void igraph_estack_destroy(igraph_estack_t *s); int igraph_estack_push(igraph_estack_t *s, long int elem); long int igraph_estack_pop(igraph_estack_t *s); igraph_bool_t igraph_estack_iselement(const igraph_estack_t *s, long int elem); long int igraph_estack_size(const igraph_estack_t *s); int igraph_estack_print(const igraph_estack_t *s); #endif igraph/src/conversion.c0000644000175100001440000006237513431000472014671 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_conversion.h" #include "igraph_iterators.h" #include "igraph_interface.h" #include "igraph_attributes.h" #include "igraph_constructors.h" #include "igraph_types_internal.h" #include "igraph_sparsemat.h" #include "config.h" /** * \ingroup conversion * \function igraph_get_adjacency * \brief Returns the adjacency matrix of a graph * * * The result is an incidence matrix, it contains numbers greater * than one if there are multiple edges in the graph. * \param graph Pointer to the graph to convert * \param res Pointer to an initialized matrix object, it will be * resized if needed. * \param type Constant giving the type of the adjacency matrix to * create for undirected graphs. It is ignored for directed * graphs. Possible values: * \clist * \cli IGRAPH_GET_ADJACENCY_UPPER * the upper right triangle of the matrix is used. * \cli IGRAPH_GET_ADJACENCY_LOWER * the lower left triangle of the matrix is used. * \cli IGRAPH_GET_ADJACENCY_BOTH * the whole matrix is used, a symmetric matrix is returned. * \endclist * \param type eids Logical, if true, then the edges ids plus one * are stored in the adjacency matrix, instead of the number of * edges between the two vertices. (The plus one is needed, since * edge ids start from zero, and zero means no edge in this case.) * \return Error code: * \c IGRAPH_EINVAL invalid type argument. * * \sa igraph_get_adjacency_sparse if you want a sparse matrix representation * * Time complexity: O(|V||V|), * |V| is the * number of vertices in the graph. */ int igraph_get_adjacency(const igraph_t *graph, igraph_matrix_t *res, igraph_get_adjacency_t type, igraph_bool_t eids) { igraph_eit_t edgeit; long int no_of_nodes=igraph_vcount(graph); igraph_bool_t directed=igraph_is_directed(graph); int retval=0; long int from, to; igraph_integer_t ffrom, fto; IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, no_of_nodes)); igraph_matrix_null(res); IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &edgeit)); IGRAPH_FINALLY(igraph_eit_destroy, &edgeit); if (directed) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); igraph_edge(graph, (igraph_integer_t) edge, &ffrom, &fto); from=ffrom; to=fto; if (eids) { MATRIX(*res, from, to) = edge+1; } else { MATRIX(*res, from, to) += 1; } IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_UPPER) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); igraph_edge(graph, (igraph_integer_t) edge, &ffrom, &fto); from=ffrom; to=fto; if (to < from) { if (eids) { MATRIX(*res, to, from) = edge+1; } else { MATRIX(*res, to, from) += 1; } } else { if (eids) { MATRIX(*res, from, to) = edge+1; } else { MATRIX(*res, from, to) += 1; } } IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_LOWER) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); igraph_edge(graph, (igraph_integer_t) edge, &ffrom, &fto); from=ffrom; to=fto; if (to < from) { if (eids) { MATRIX(*res, from, to) = edge+1; } else { MATRIX(*res, from, to) += 1; } } else { if (eids) { MATRIX(*res, to, from) = edge+1; } else { MATRIX(*res, to, from) += 1; } } IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_BOTH) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); igraph_edge(graph, (igraph_integer_t) edge, &ffrom, &fto); from=ffrom; to=fto; if (eids) { MATRIX(*res, from, to) = edge+1; } else { MATRIX(*res, from, to) += 1; } if (from != to) { if (eids) { MATRIX(*res, to, from) = edge+1; } else { MATRIX(*res, to, from) += 1; } } IGRAPH_EIT_NEXT(edgeit); } } else { IGRAPH_ERROR("Invalid type argument", IGRAPH_EINVAL); } igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(1); return retval; } /** * \ingroup conversion * \function igraph_get_adjacency_sparse * \brief Returns the adjacency matrix of a graph in sparse matrix format * * * The result is an incidence matrix, it contains numbers greater * than one if there are multiple edges in the graph. * \param graph Pointer to the graph to convert * \param res Pointer to an initialized sparse matrix object, it will be * resized if needed. * \param type Constant giving the type of the adjacency matrix to * create for undirected graphs. It is ignored for directed * graphs. Possible values: * \clist * \cli IGRAPH_GET_ADJACENCY_UPPER * the upper right triangle of the matrix is used. * \cli IGRAPH_GET_ADJACENCY_LOWER * the lower left triangle of the matrix is used. * \cli IGRAPH_GET_ADJACENCY_BOTH * the whole matrix is used, a symmetric matrix is returned. * \endclist * \return Error code: * \c IGRAPH_EINVAL invalid type argument. * * \sa igraph_get_adjacency if you would like to get a normal matrix * ( \type igraph_matrix_t ) * * Time complexity: O(|V||V|), * |V| is the * number of vertices in the graph. */ int igraph_get_adjacency_sparse(const igraph_t *graph, igraph_spmatrix_t *res, igraph_get_adjacency_t type) { igraph_eit_t edgeit; long int no_of_nodes=igraph_vcount(graph); igraph_bool_t directed=igraph_is_directed(graph); int retval=0; long int from, to; igraph_integer_t ffrom, fto; igraph_spmatrix_null(res); IGRAPH_CHECK(igraph_spmatrix_resize(res, no_of_nodes, no_of_nodes)); IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &edgeit)); IGRAPH_FINALLY(igraph_eit_destroy, &edgeit); if (directed) { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; igraph_spmatrix_add_e(res, from, to, 1); IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_UPPER) { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; if (to < from) { igraph_spmatrix_add_e(res, to, from, 1); } else { igraph_spmatrix_add_e(res, from, to, 1); } IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_LOWER) { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; if (to > from) { igraph_spmatrix_add_e(res, to, from, 1); } else { igraph_spmatrix_add_e(res, from, to, 1); } IGRAPH_EIT_NEXT(edgeit); } } else if (type==IGRAPH_GET_ADJACENCY_BOTH) { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; igraph_spmatrix_add_e(res, from, to, 1); if (from != to) { igraph_spmatrix_add_e(res, to, from, 1); } IGRAPH_EIT_NEXT(edgeit); } } else { IGRAPH_ERROR("Invalid type argument", IGRAPH_EINVAL); } igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(1); return retval; } /** * \ingroup conversion * \function igraph_get_edgelist * \brief Returns the list of edges in a graph * * The order of the edges is given by the edge ids. * \param graph Pointer to the graph object * \param res Pointer to an initialized vector object, it will be * resized. * \param bycol Logical, if true, the edges will be returned * columnwise, eg. the first edge is * res[0]->res[|E|], the second is * res[1]->res[|E|+1], etc. * \return Error code. * * Time complexity: O(|E|), the * number of edges in the graph. */ int igraph_get_edgelist(const igraph_t *graph, igraph_vector_t *res, igraph_bool_t bycol) { igraph_eit_t edgeit; long int no_of_edges=igraph_ecount(graph); long int vptr=0; igraph_integer_t from, to; IGRAPH_CHECK(igraph_vector_resize(res, no_of_edges*2)); IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_ID), &edgeit)); IGRAPH_FINALLY(igraph_eit_destroy, &edgeit); if (bycol) { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &from, &to); VECTOR(*res)[vptr]=from; VECTOR(*res)[vptr+no_of_edges]=to; vptr++; IGRAPH_EIT_NEXT(edgeit); } } else { while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &from, &to); VECTOR(*res)[vptr++]=from; VECTOR(*res)[vptr++]=to; IGRAPH_EIT_NEXT(edgeit); } } igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_to_directed * \brief Convert an undirected graph to a directed one * * * If the supplied graph is directed, this function does nothing. * \param graph The graph object to convert. * \param mode Constant, specifies the details of how exactly the * conversion is done. Possible values: \c * IGRAPH_TO_DIRECTED_ARBITRARY: the number of edges in the * graph stays the same, an arbitrarily directed edge is * created for each undirected edge; * \c IGRAPH_TO_DIRECTED_MUTUAL: two directed edges are * created for each undirected edge, one in each direction. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. */ int igraph_to_directed(igraph_t *graph, igraph_to_directed_t mode) { if (mode != IGRAPH_TO_DIRECTED_ARBITRARY && mode != IGRAPH_TO_DIRECTED_MUTUAL) { IGRAPH_ERROR("Cannot directed graph, invalid mode", IGRAPH_EINVAL); } if (igraph_is_directed(graph)) { return 0; } if (mode==IGRAPH_TO_DIRECTED_ARBITRARY) { igraph_t newgraph; igraph_vector_t edges; long int no_of_edges=igraph_ecount(graph); long int no_of_nodes=igraph_vcount(graph); long int size=no_of_edges*2; IGRAPH_VECTOR_INIT_FINALLY(&edges, size); IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); IGRAPH_CHECK(igraph_create(&newgraph, &edges, (igraph_integer_t) no_of_nodes, IGRAPH_DIRECTED)); IGRAPH_FINALLY(igraph_destroy, &newgraph); igraph_vector_destroy(&edges); IGRAPH_I_ATTRIBUTE_DESTROY(&newgraph); IGRAPH_I_ATTRIBUTE_COPY(&newgraph, graph, 1,1,1); IGRAPH_FINALLY_CLEAN(2); igraph_destroy(graph); *graph=newgraph; } else if (mode==IGRAPH_TO_DIRECTED_MUTUAL) { igraph_t newgraph; igraph_vector_t edges; igraph_vector_t index; long int no_of_edges=igraph_ecount(graph); long int no_of_nodes=igraph_vcount(graph); long int size=no_of_edges*4; long int i; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, size)); IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); IGRAPH_CHECK(igraph_vector_resize(&edges, no_of_edges*4)); IGRAPH_VECTOR_INIT_FINALLY(&index, no_of_edges*2); for (i=0; i * If the supplied graph is undirected, this function does nothing. * \param graph The graph object to convert. * \param mode Constant, specifies the details of how exactly the * conversion is done. Possible values: \c * IGRAPH_TO_UNDIRECTED_EACH: the number of edges remains * constant, an undirected edge is created for each directed * one, this version might create graphs with multiple edges; * \c IGRAPH_TO_UNDIRECTED_COLLAPSE: one undirected edge will * be created for each pair of vertices which are connected * with at least one directed edge, no multiple edges will be * created. \c IGRAPH_TO_UNDIRECTED_MUTUAL creates an undirected * edge for each pair of mutual edges in the directed graph. * Non-mutual edges are lost. This mode might create multiple * edges. * \param edge_comb What to do with the edge attributes. See the igraph * manual section about attributes for details. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. * * \example examples/simple/igraph_to_undirected.c */ int igraph_to_undirected(igraph_t *graph, igraph_to_undirected_t mode, const igraph_attribute_combination_t *edge_comb) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vector_t edges; igraph_t newgraph; igraph_bool_t attr=edge_comb && igraph_has_attribute_table(); if (mode != IGRAPH_TO_UNDIRECTED_EACH && mode != IGRAPH_TO_UNDIRECTED_COLLAPSE && mode != IGRAPH_TO_UNDIRECTED_MUTUAL) { IGRAPH_ERROR("Cannot undirect graph, invalid mode", IGRAPH_EINVAL); } if (!igraph_is_directed(graph)) { return 0; } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); if (mode==IGRAPH_TO_UNDIRECTED_EACH) { igraph_es_t es; igraph_eit_t eit; IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); IGRAPH_CHECK(igraph_es_all(&es, IGRAPH_EDGEORDER_ID)); IGRAPH_FINALLY(igraph_es_destroy, &es); IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); while (!IGRAPH_EIT_END(eit)) { long int edge=IGRAPH_EIT_GET(eit); igraph_integer_t from, to; igraph_edge(graph, (igraph_integer_t) edge, &from, &to); IGRAPH_CHECK(igraph_vector_push_back(&edges, from)); IGRAPH_CHECK(igraph_vector_push_back(&edges, to)); IGRAPH_EIT_NEXT(eit); } igraph_eit_destroy(&eit); igraph_es_destroy(&es); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_create(&newgraph, &edges, (igraph_integer_t) no_of_nodes, IGRAPH_UNDIRECTED)); IGRAPH_FINALLY(igraph_destroy, &newgraph); igraph_vector_destroy(&edges); IGRAPH_I_ATTRIBUTE_DESTROY(&newgraph); IGRAPH_I_ATTRIBUTE_COPY(&newgraph, graph, 1,1,1); IGRAPH_FINALLY_CLEAN(2); igraph_destroy(graph); *graph=newgraph; } else if (mode==IGRAPH_TO_UNDIRECTED_COLLAPSE) { igraph_vector_t inadj, outadj; long int i; igraph_vector_t mergeinto; long int actedge=0; if (attr) { IGRAPH_VECTOR_INIT_FINALLY(&mergeinto, no_of_edges); } IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); IGRAPH_VECTOR_INIT_FINALLY(&inadj, 0); IGRAPH_VECTOR_INIT_FINALLY(&outadj, 0); for (i=0; i 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-ncol-header.h" #include "foreign-ncol-parser.h" #define YY_EXTRA_TYPE igraph_i_ncol_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); %} %option noyywrap %option prefix="igraph_ncol_yy" %option outfile="lex.yy.c" %option nounput %option noinput %option nodefault %option reentrant %option bison-bridge %option bison-locations alnum [^ \t\n\r] %% /* ------------------------------------------------whitespace------*/ [ \t]* { } /* ---------------------------------------------------newline------*/ \n\r|\r\n|\n|\r { return NEWLINE; } /* ----------------------------------------------alphanumeric------*/ {alnum}+ { return ALNUM; } <> { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } /* ---------------------------------------------anything else------*/ . { return ERROR; } %% igraph/src/bignum.h0000644000175100001440000001127613431000472013764 0ustar hornikusers/***************************************************************************** * Entropy - Emerging Network To Reduce Orwellian Potency Yield * * Copyright (C) 2005 Juergen Buchmueller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * $Id: bignum.h,v 1.6 2005/08/11 17:57:39 pullmoll Exp $ *****************************************************************************/ #ifndef _bignum_h_ #define _bignum_h_ #include "config.h" #ifdef HAVE_STDINT_H # include #else # ifdef HAVE_SYS_INT_TYPES_H # include # else # include "pstdint.h" # endif #endif #include #include #include #ifndef NULL #define NULL 0 #endif #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef HAVE_U64 #define HAVE_U64 1 #endif /* up to 512 limbs (512 * 32 = 16384 bits) numbers */ /* BN_MAXSIZE used to be 512 here, allowing us to go up to 512*32 = 16384 bits. * However, this has caused compilation problems with clang 7.3 (unless * compiling with -O2 -g). Since it is unlikely that we'll need that many bits, * I have changed this to 128, which still yields 4096 bits of precision but * does not cause problems with clang -- TN, 2016-04-18 */ #define BN_MAXSIZE 128 #define LIMBBITS 32 #define LIMBMASK 0xfffffffful #define HALFMASK 0x0000fffful #define DIGMSB 0x80000000ul #define DIGLSB 0x00000001ul typedef uint32_t count_t; typedef uint16_t half_t; typedef uint32_t limb_t; #if HAVE_U64 typedef uint64_t dlimb_t; #endif /* less significant half limb */ #define LSH(d) ((half_t)(d)) /* more significant half limb */ #define MSH(d) ((limb_t)(d)>>16) /* shift left half limb */ #define SHL(d) ((limb_t)(d)<<16) /* single limb functions */ limb_t sl_div(limb_t *q, limb_t *r, limb_t u[2], limb_t v); limb_t sl_gcd(limb_t x, limb_t y); int sl_modexp(limb_t *exp, limb_t x, limb_t n, limb_t d); int sl_modinv(limb_t *inv, limb_t u, limb_t v); int sl_modmul(limb_t *a, limb_t x, limb_t y, limb_t m); int sl_mul(limb_t p[2], limb_t x, limb_t y); /* big number functions (max. MAXSIZE limbs) */ void bn_zero(limb_t a[], count_t nlimb); void bn_limb(limb_t a[], limb_t d, count_t nlimb); void bn_copy(limb_t a[], limb_t b[], count_t nlimb); count_t bn_sizeof(limb_t a[], count_t nlimb); int bn_cmp_limb(limb_t a[], limb_t b, count_t nlimb); int bn_cmp(limb_t a[], limb_t b[], count_t nlimb); /* big number to hex, decimal, binary */ const char *bn2x(limb_t a[], count_t nlimb); const char *bn2d(limb_t a[], count_t nlimb); const char *bn2f(limb_t a[], count_t alimb, limb_t b[], count_t blimb); const char *bn2b(limb_t a[], count_t nlimb); /* big number with single limb operations */ limb_t bn_add_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb); limb_t bn_sub_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb); limb_t bn_div_limb(limb_t q[], limb_t u[], limb_t v, count_t nlimb); limb_t bn_mod_limb(limb_t u[], limb_t d, count_t nlimb); limb_t bn_mul_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb); /* big number with single limb <= HALFMASK operations */ limb_t bn_div_half(limb_t q[], limb_t u[], limb_t v, count_t nlimb); limb_t bn_mod_half(limb_t a[], limb_t d, count_t nlimb); /* big number operations */ limb_t bn_add(limb_t w[], limb_t u[], limb_t v[], count_t nlimb); limb_t bn_sub(limb_t w[], limb_t u[], limb_t v[], count_t nlimb); limb_t bn_shl(limb_t a[], limb_t b[], count_t x, count_t nlimb); limb_t bn_shr(limb_t a[], limb_t b[], count_t x, count_t nlimb); int bn_mul(limb_t w[], limb_t u[], limb_t v[], count_t nlimb); int bn_div(limb_t q[], limb_t r[], limb_t u[], limb_t v[], count_t ulimb, count_t vlimb); limb_t bn_mod(limb_t r[], limb_t u[], count_t ulimb, limb_t v[], count_t vlimb); int bn_gcd(limb_t g[], limb_t x[], limb_t y[], count_t nlimb); int bn_sqrt(limb_t g[], limb_t x[], limb_t y[], count_t rlimb, count_t nlimb); int bn_modexp(limb_t y[], limb_t x[], limb_t e[], limb_t m[], count_t nlimb); int bn_modinv(limb_t inv[], limb_t u[], limb_t v[], count_t nlimb); limb_t bn_modmul(limb_t a[], limb_t x[], limb_t y[], limb_t m[], count_t nlimb); #endif /* !defined(_bignum_h_) */ igraph/src/igraph_fixed_vectorlist.c0000644000175100001440000000446013431000472017402 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types_internal.h" #include "igraph_memory.h" void igraph_fixed_vectorlist_destroy(igraph_fixed_vectorlist_t *l) { long int i, n=igraph_vector_ptr_size(&l->v); for (i=0; iv)[i]; if (v) { igraph_vector_destroy(v); } } igraph_vector_ptr_destroy(&l->v); igraph_free(l->vecs); } int igraph_fixed_vectorlist_convert(igraph_fixed_vectorlist_t *l, const igraph_vector_t *from, long int size) { igraph_vector_t sizes; long int i, no=igraph_vector_size(from); l->vecs=igraph_Calloc(size, igraph_vector_t); if (!l->vecs) { IGRAPH_ERROR("Cannot merge attributes for simplify", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, l->vecs); IGRAPH_CHECK(igraph_vector_ptr_init(&l->v, size)); IGRAPH_FINALLY(igraph_fixed_vectorlist_destroy, &l->v); IGRAPH_VECTOR_INIT_FINALLY(&sizes, size); for (i=0; i= 0) { VECTOR(sizes)[to] += 1; } } for (i=0; ivecs[i]); IGRAPH_CHECK(igraph_vector_init(v, (long int) VECTOR(sizes)[i])); igraph_vector_clear(v); VECTOR(l->v)[i]=v; } for (i=0; i= 0) { igraph_vector_t *v=&(l->vecs[to]); igraph_vector_push_back(v, i); } } igraph_vector_destroy(&sizes); IGRAPH_FINALLY_CLEAN(3); return 0; } igraph/src/complex.c0000644000175100001440000002555513431000472014152 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_complex.h" #include "igraph_math.h" #include /** * \example igraph_complex.c */ igraph_complex_t igraph_complex(igraph_real_t x, igraph_real_t y) { igraph_complex_t res; IGRAPH_REAL(res) = x; IGRAPH_IMAG(res) = y; return res; } igraph_complex_t igraph_complex_polar(igraph_real_t r, igraph_real_t theta) { igraph_complex_t res; IGRAPH_REAL(res) = r * cos(theta); IGRAPH_IMAG(res) = r * sin(theta); return res; } igraph_bool_t igraph_complex_eq_tol(igraph_complex_t z1, igraph_complex_t z2, igraph_real_t tol) { if (fabs(IGRAPH_REAL(z1) - IGRAPH_REAL(z2)) > tol || fabs(IGRAPH_IMAG(z1) - IGRAPH_IMAG(z2)) > tol) { return 0; } return 1; } igraph_real_t igraph_complex_mod(igraph_complex_t z) { igraph_real_t x=IGRAPH_REAL(z); igraph_real_t y=IGRAPH_IMAG(z); return hypot(x,y); } igraph_real_t igraph_complex_arg(igraph_complex_t z) { igraph_real_t x=IGRAPH_REAL(z); igraph_real_t y=IGRAPH_IMAG(z); if (x==0.0 && y==0.0) { return 0.0; } return atan2(y,x); } igraph_complex_t igraph_complex_add(igraph_complex_t z1, igraph_complex_t z2) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z1) + IGRAPH_REAL(z2); IGRAPH_IMAG(res) = IGRAPH_IMAG(z1) + IGRAPH_IMAG(z2); return res; } igraph_complex_t igraph_complex_sub(igraph_complex_t z1, igraph_complex_t z2) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z1) - IGRAPH_REAL(z2); IGRAPH_IMAG(res) = IGRAPH_IMAG(z1) - IGRAPH_IMAG(z2); return res; } igraph_complex_t igraph_complex_mul(igraph_complex_t z1, igraph_complex_t z2) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z1) * IGRAPH_REAL(z2) - IGRAPH_IMAG(z1) * IGRAPH_IMAG(z2); IGRAPH_IMAG(res) = IGRAPH_REAL(z1) * IGRAPH_IMAG(z2) + IGRAPH_IMAG(z1) * IGRAPH_REAL(z2); return res; } igraph_complex_t igraph_complex_div(igraph_complex_t z1, igraph_complex_t z2) { igraph_complex_t res; igraph_real_t z1r = IGRAPH_REAL(z1), z1i = IGRAPH_IMAG(z1); igraph_real_t z2r = IGRAPH_REAL(z2), z2i = IGRAPH_IMAG(z2); igraph_real_t s = 1.0 / igraph_complex_abs(z2); igraph_real_t sz2r = s * z2r; igraph_real_t sz2i = s * z2i; IGRAPH_REAL(res) = (z1r * sz2r + z1i * sz2i) * s; IGRAPH_IMAG(res) = (z1i * sz2r - z1r * sz2i) * s; return res; } igraph_complex_t igraph_complex_add_real(igraph_complex_t z, igraph_real_t x) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z) + x; IGRAPH_IMAG(res) = IGRAPH_IMAG(z); return res; } igraph_complex_t igraph_complex_add_imag(igraph_complex_t z, igraph_real_t y) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z); IGRAPH_IMAG(res) = IGRAPH_IMAG(z) + y; return res; } igraph_complex_t igraph_complex_sub_real(igraph_complex_t z, igraph_real_t x) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z) - x; IGRAPH_IMAG(res) = IGRAPH_IMAG(z); return res; } igraph_complex_t igraph_complex_sub_imag(igraph_complex_t z, igraph_real_t y) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z); IGRAPH_IMAG(res) = IGRAPH_IMAG(z) - y; return res; } igraph_complex_t igraph_complex_mul_real(igraph_complex_t z, igraph_real_t x) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z) * x; IGRAPH_IMAG(res) = IGRAPH_IMAG(z) * x; return res; } igraph_complex_t igraph_complex_mul_imag(igraph_complex_t z, igraph_real_t y) { igraph_complex_t res; IGRAPH_REAL(res) = - IGRAPH_IMAG(z) * y; IGRAPH_IMAG(res) = IGRAPH_REAL(z) * y; return res; } igraph_complex_t igraph_complex_div_real(igraph_complex_t z, igraph_real_t x) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z) / x; IGRAPH_IMAG(res) = IGRAPH_IMAG(z) / x; return res; } igraph_complex_t igraph_complex_div_imag(igraph_complex_t z, igraph_real_t y) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_IMAG(z) / y; IGRAPH_IMAG(res) = - IGRAPH_REAL(z) / y; return res; } igraph_complex_t igraph_complex_conj(igraph_complex_t z) { igraph_complex_t res; IGRAPH_REAL(res) = IGRAPH_REAL(z); IGRAPH_IMAG(res) = - IGRAPH_IMAG(z); return res; } igraph_complex_t igraph_complex_neg(igraph_complex_t z) { igraph_complex_t res; IGRAPH_REAL(res) = - IGRAPH_REAL(z); IGRAPH_IMAG(res) = - IGRAPH_IMAG(z); return res; } igraph_complex_t igraph_complex_inv(igraph_complex_t z) { igraph_complex_t res; igraph_real_t s = 1.0 / igraph_complex_abs(z); IGRAPH_REAL(res) = (IGRAPH_REAL(z) * s) * s; IGRAPH_IMAG(res) = - (IGRAPH_IMAG(z) * s) * s; return res; } igraph_real_t igraph_complex_abs(igraph_complex_t z) { return hypot(IGRAPH_REAL(z), IGRAPH_IMAG(z)); } igraph_real_t igraph_complex_logabs(igraph_complex_t z) { igraph_real_t xabs = fabs(IGRAPH_REAL(z)); igraph_real_t yabs = fabs(IGRAPH_IMAG(z)); igraph_real_t max, u; if (xabs >= yabs) { max = xabs; u = yabs / xabs; } else { max = yabs; u = xabs / yabs; } return log (max) + 0.5 * log1p (u * u); } igraph_complex_t igraph_complex_sqrt(igraph_complex_t z) { igraph_complex_t res; if (IGRAPH_REAL(z)==0.0 && IGRAPH_IMAG(z) == 0.0) { IGRAPH_REAL(res) = IGRAPH_IMAG(res) = 0.0; } else { igraph_real_t x = fabs (IGRAPH_REAL(z)); igraph_real_t y = fabs (IGRAPH_IMAG(z)); igraph_real_t w; if (x >= y) { igraph_real_t t = y / x; w = sqrt (x) * sqrt (0.5 * (1.0 + sqrt (1.0 + t * t))); } else { igraph_real_t t = x / y; w = sqrt (y) * sqrt (0.5 * (t + sqrt (1.0 + t * t))); } if (IGRAPH_REAL(z) >= 0.0) { igraph_real_t ai = IGRAPH_IMAG(z); IGRAPH_REAL(res) = w; IGRAPH_IMAG(res) = ai / (2.0 * w); } else { igraph_real_t ai = IGRAPH_IMAG(z); igraph_real_t vi = (ai >= 0) ? w : -w; IGRAPH_REAL(res) = ai / (2.0 * vi); IGRAPH_IMAG(res) = vi; } } return res; } igraph_complex_t igraph_complex_sqrt_real(igraph_real_t x) { igraph_complex_t res; if (x >= 0) { IGRAPH_REAL(res) = sqrt(x); IGRAPH_IMAG(res) = 0.0; } else { IGRAPH_REAL(res) = 0.0; IGRAPH_IMAG(res) = sqrt(-x); } return res; } igraph_complex_t igraph_complex_exp(igraph_complex_t z) { igraph_real_t rho = exp(IGRAPH_REAL(z)); igraph_real_t theta = IGRAPH_IMAG(z); igraph_complex_t res; IGRAPH_REAL(res) = rho * cos(theta); IGRAPH_IMAG(res) = rho * sin(theta); return res; } igraph_complex_t igraph_complex_pow(igraph_complex_t z1, igraph_complex_t z2) { igraph_complex_t res; if (IGRAPH_REAL(z1) == 0 && IGRAPH_IMAG(z1) == 0.0) { if (IGRAPH_REAL(z2) == 0 && IGRAPH_IMAG(z2) == 0.0) { IGRAPH_REAL(res) = 1.0; IGRAPH_IMAG(res) = 0.0; } else { IGRAPH_REAL(res) = IGRAPH_IMAG(res) = 0.0; } } else if (IGRAPH_REAL(z2) == 1.0 && IGRAPH_IMAG(z2) == 0.0) { IGRAPH_REAL(res) = IGRAPH_REAL(z1); IGRAPH_IMAG(res) = IGRAPH_IMAG(z1); } else if (IGRAPH_REAL(z2) == -1.0 && IGRAPH_IMAG(z2) == 0.0) { res = igraph_complex_inv(z1); } else { igraph_real_t logr = igraph_complex_logabs (z1); igraph_real_t theta = igraph_complex_arg (z1); igraph_real_t z2r = IGRAPH_REAL(z2), z2i = IGRAPH_IMAG(z2); igraph_real_t rho = exp (logr * z2r - z2i * theta); igraph_real_t beta = theta * z2r + z2i * logr; IGRAPH_REAL(res) = rho * cos(beta); IGRAPH_IMAG(res) = rho * sin(beta); } return res; } igraph_complex_t igraph_complex_pow_real(igraph_complex_t z, igraph_real_t x) { igraph_complex_t res; if (IGRAPH_REAL(z) == 0.0 && IGRAPH_IMAG(z) == 0.0) { if (x==0) { IGRAPH_REAL(res) = 1.0; IGRAPH_IMAG(res) = 0.0; } else { IGRAPH_REAL(res) = IGRAPH_IMAG(res) = 0.0; } } else { igraph_real_t logr = igraph_complex_logabs(z); igraph_real_t theta = igraph_complex_arg(z); igraph_real_t rho = exp (logr * x); igraph_real_t beta = theta * x; IGRAPH_REAL(res) = rho * cos(beta); IGRAPH_IMAG(res) = rho * sin(beta); } return res; } igraph_complex_t igraph_complex_log(igraph_complex_t z) { igraph_complex_t res; IGRAPH_REAL(res) = igraph_complex_logabs(z); IGRAPH_IMAG(res) = igraph_complex_arg(z); return res; } igraph_complex_t igraph_complex_log10(igraph_complex_t z) { return igraph_complex_mul_real(igraph_complex_log(z), 1/log(10.0)); } igraph_complex_t igraph_complex_log_b(igraph_complex_t z, igraph_complex_t b) { return igraph_complex_div (igraph_complex_log(z), igraph_complex_log(b)); } igraph_complex_t igraph_complex_sin(igraph_complex_t z) { igraph_real_t zr = IGRAPH_REAL(z); igraph_real_t zi = IGRAPH_IMAG(z); igraph_complex_t res; if (zi == 0.0) { IGRAPH_REAL(res) = sin(zr); IGRAPH_IMAG(res) = 0.0; } else { IGRAPH_REAL(res) = sin(zr) * cosh(zi); IGRAPH_IMAG(res) = cos(zr) * sinh(zi); } return res; } igraph_complex_t igraph_complex_cos(igraph_complex_t z) { igraph_real_t zr=IGRAPH_REAL(z); igraph_real_t zi=IGRAPH_IMAG(z); igraph_complex_t res; if (zi == 0.0) { IGRAPH_REAL(res) = cos(zr); IGRAPH_IMAG(res) = 0.0; } else { IGRAPH_REAL(res) = cos(zr) * cosh(zi); IGRAPH_IMAG(res) = sin(zr) * sinh(-zi); } return res; } igraph_complex_t igraph_complex_tan(igraph_complex_t z) { igraph_real_t zr=IGRAPH_REAL(z); igraph_real_t zi=IGRAPH_IMAG(z); igraph_complex_t res; if (fabs (zi) < 1) { igraph_real_t D = pow (cos (zr), 2.0) + pow (sinh (zi), 2.0); IGRAPH_REAL(res) = 0.5 * sin (2 * zr) / D; IGRAPH_IMAG(res) = 0.5 * sinh (2 * zi) / D; } else { igraph_real_t u = exp (-zi); igraph_real_t C = 2 * u / (1 - pow (u, 2.0)); igraph_real_t D = 1 + pow (cos (zr), 2.0) * pow (C, 2.0); igraph_real_t S = pow (C, 2.0); igraph_real_t T = 1.0 / tanh (zi); IGRAPH_REAL(res) = 0.5 * sin (2 * zr) * S / D; IGRAPH_IMAG(res) = T / D; } return res; } igraph_complex_t igraph_complex_sec(igraph_complex_t z) { return igraph_complex_inv(igraph_complex_cos(z)); } igraph_complex_t igraph_complex_csc(igraph_complex_t z) { return igraph_complex_inv(igraph_complex_sin(z)); } igraph_complex_t igraph_complex_cot(igraph_complex_t z) { return igraph_complex_inv(igraph_complex_tan(z)); } igraph/src/prpack.h0000644000175100001440000000302013431000472013747 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_PRPACK #define IGRAPH_PRPACK #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #include "igraph_types.h" #include "igraph_datatype.h" #include "igraph_iterators.h" #include "igraph_interface.h" __BEGIN_DECLS int igraph_personalized_pagerank_prpack(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights); __END_DECLS #endif igraph/src/dsesrt.f0000644000175100001440000001242613431000472014003 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsesrt c c\Description: c Sort the array X in the order specified by WHICH and optionally c apply the permutation to the columns of the matrix A. c c\Usage: c call igraphdsesrt c ( WHICH, APPLY, N, X, NA, A, LDA) c c\Arguments c WHICH Character*2. (Input) c 'LM' -> X is sorted into increasing order of magnitude. c 'SM' -> X is sorted into decreasing order of magnitude. c 'LA' -> X is sorted into increasing order of algebraic. c 'SA' -> X is sorted into decreasing order of algebraic. c c APPLY Logical. (Input) c APPLY = .TRUE. -> apply the sorted order to A. c APPLY = .FALSE. -> do not apply the sorted order to A. c c N Integer. (INPUT) c Dimension of the array X. c c X Double precision array of length N. (INPUT/OUTPUT) c The array to be sorted. c c NA Integer. (INPUT) c Number of rows of the matrix A. c c A Double precision array of length NA by N. (INPUT/OUTPUT) c c LDA Integer. (INPUT) c Leading dimension of A. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Routines c dswap Level 1 BLAS that swaps the contents of two vectors. c c\Authors c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/15/93: Version ' 2.1'. c Adapted from the sort routine in LANSO and c the ARPACK code igraphdsortr c c\SCCS Information: @(#) c FILE: sesrt.F SID: 2.3 DATE OF SID: 4/19/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsesrt (which, apply, n, x, na, a, lda) c c %------------------% c | Scalar Arguments | c %------------------% c character*2 which logical apply integer lda, n, na c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & x(0:n-1), a(lda, 0:n-1) c c %---------------% c | Local Scalars | c %---------------% c integer i, igap, j Double precision & temp c c %----------------------% c | External Subroutines | c %----------------------% c external dswap c c %-----------------------% c | Executable Statements | c %-----------------------% c igap = n / 2 c if (which .eq. 'SA') then c c X is sorted into decreasing order of algebraic. c 10 continue if (igap .eq. 0) go to 9000 do 30 i = igap, n-1 j = i-igap 20 continue c if (j.lt.0) go to 30 c if (x(j).lt.x(j+igap)) then temp = x(j) x(j) = x(j+igap) x(j+igap) = temp if (apply) call dswap( na, a(1, j), 1, a(1,j+igap), 1) else go to 30 endif j = j-igap go to 20 30 continue igap = igap / 2 go to 10 c else if (which .eq. 'SM') then c c X is sorted into decreasing order of magnitude. c 40 continue if (igap .eq. 0) go to 9000 do 60 i = igap, n-1 j = i-igap 50 continue c if (j.lt.0) go to 60 c if (abs(x(j)).lt.abs(x(j+igap))) then temp = x(j) x(j) = x(j+igap) x(j+igap) = temp if (apply) call dswap( na, a(1, j), 1, a(1,j+igap), 1) else go to 60 endif j = j-igap go to 50 60 continue igap = igap / 2 go to 40 c else if (which .eq. 'LA') then c c X is sorted into increasing order of algebraic. c 70 continue if (igap .eq. 0) go to 9000 do 90 i = igap, n-1 j = i-igap 80 continue c if (j.lt.0) go to 90 c if (x(j).gt.x(j+igap)) then temp = x(j) x(j) = x(j+igap) x(j+igap) = temp if (apply) call dswap( na, a(1, j), 1, a(1,j+igap), 1) else go to 90 endif j = j-igap go to 80 90 continue igap = igap / 2 go to 70 c else if (which .eq. 'LM') then c c X is sorted into increasing order of magnitude. c 100 continue if (igap .eq. 0) go to 9000 do 120 i = igap, n-1 j = i-igap 110 continue c if (j.lt.0) go to 120 c if (abs(x(j)).gt.abs(x(j+igap))) then temp = x(j) x(j) = x(j+igap) x(j+igap) = temp if (apply) call dswap( na, a(1, j), 1, a(1,j+igap), 1) else go to 120 endif j = j-igap go to 110 120 continue igap = igap / 2 go to 100 end if c 9000 continue return c c %---------------% c | End of igraphdsesrt | c %---------------% c end igraph/src/DensityGrid_3d.cpp0000644000175100001440000002156413431000472015652 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the member definitions of the DensityGrid.h class // This code is modified from the original code by B.N. Wylie #include #include #include #include #include using namespace std; #include "drl_Node_3d.h" #include "DensityGrid_3d.h" #include "igraph_error.h" #define GET_BIN(z, y, x) (Bins[(z*GRID_SIZE+y)*GRID_SIZE+x]) namespace drl3d { //******************************************************* // Density Grid Destructor -- deallocates memory used // for Density matrix, fall_off matrix, and node deque. DensityGrid::~DensityGrid () { delete[] Density; delete[] fall_off; delete[] Bins; } /********************************************* * Function: Density_Grid::Reset * * Description: Reset the density grid * *********************************************/ // changed from reset to init since we will only // call this once in the parallel version of layout void DensityGrid::Init() { Density = new float[GRID_SIZE][GRID_SIZE][GRID_SIZE]; fall_off = new float[RADIUS*2+1][RADIUS*2+1][RADIUS*2+1]; Bins = new deque[GRID_SIZE*GRID_SIZE*GRID_SIZE]; // Clear Grid int i; for (i=0; i< GRID_SIZE; i++) for (int j=0; j< GRID_SIZE; j++) for (int k=0; k < GRID_SIZE; k++) { Density[i][j][k] = 0; GET_BIN(i,j,k).erase(GET_BIN(i,j,k).begin(),GET_BIN(i,j,k).end()); } // Compute fall off for(i=-RADIUS; i<=RADIUS; i++) for(int j=-RADIUS; j<=RADIUS; j++) for (int k=-RADIUS; k<=RADIUS; k++) { fall_off[i+RADIUS][j+RADIUS][k+RADIUS] = (float)((RADIUS-fabs((float)i))/RADIUS) * (float)((RADIUS-fabs((float)j))/RADIUS) * (float)((RADIUS-fabs((float)k))/RADIUS); } } /*************************************************** * Function: DensityGrid::GetDensity * * Description: Get_Density from density grid * **************************************************/ float DensityGrid::GetDensity(float Nx, float Ny, float Nz,bool fineDensity) { deque::iterator BI; int x_grid, y_grid, z_grid; float x_dist, y_dist, z_dist, distance, density=0; int boundary=10; // boundary around plane /* Where to look */ x_grid = (int)((Nx+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((Ny+HALF_VIEW+.5)*VIEW_TO_GRID); z_grid = (int)((Nz+HALF_VIEW+.5)*VIEW_TO_GRID); // Check for edges of density grid (10000 is arbitrary high density) if (x_grid > GRID_SIZE-boundary || x_grid < boundary) return 10000; if (y_grid > GRID_SIZE-boundary || y_grid < boundary) return 10000; if (z_grid > GRID_SIZE-boundary || z_grid < boundary) return 10000; // Fine density? if (fineDensity) { // Go through nearest bins for (int k=z_grid-1; k<=z_grid+1; k++) for(int i=y_grid-1; i<=y_grid+1; i++) for(int j=x_grid-1; j<=x_grid+1; j++) { // Look through bin and add fine repulsions for(BI = GET_BIN(k,i,j).begin(); BI < GET_BIN(k,i,j).end(); ++BI) { x_dist = Nx-(BI->x); y_dist = Ny-(BI->y); z_dist = Nz-(BI->z); distance = x_dist*x_dist+y_dist*y_dist+z_dist*z_dist; density += 1e-4/(distance + 1e-50); } } // Course density } else { // Add rough estimate density = Density[z_grid][y_grid][x_grid]; density *= density; } return density; } /// Wrapper functions for the Add and subtract methods /// Nodes should all be passed by constant ref void DensityGrid::Add(Node &n, bool fineDensity) { if(fineDensity) fineAdd(n); else Add(n); } void DensityGrid::Subtract( Node &n, bool first_add, bool fine_first_add, bool fineDensity) { if ( fineDensity && !fine_first_add ) fineSubtract (n); else if ( !first_add ) Subtract(n); } /*************************************************** * Function: DensityGrid::Subtract * * Description: Subtract a node from density grid * **************************************************/ void DensityGrid::Subtract(Node &N) { int x_grid, y_grid, z_grid, diam; float *den_ptr, *fall_ptr; /* Where to subtract */ x_grid = (int)((N.sub_x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.sub_y+HALF_VIEW+.5)*VIEW_TO_GRID); z_grid = (int)((N.sub_z+HALF_VIEW+.5)*VIEW_TO_GRID); x_grid -= RADIUS; y_grid -= RADIUS; z_grid -= RADIUS; diam = 2*RADIUS; // check to see that we are inside grid if ( (x_grid >= GRID_SIZE) || (x_grid < 0) || (y_grid >= GRID_SIZE) || (y_grid < 0) || (z_grid >= GRID_SIZE) || (z_grid < 0) ) { #ifdef MUSE_MPI MPI_Abort ( MPI_COMM_WORLD, 1 ); #else igraph_error("Exceeded density grid in DrL", __FILE__, __LINE__, IGRAPH_EDRL); return; #endif } /* Subtract density values */ den_ptr = &Density[z_grid][y_grid][x_grid]; fall_ptr = &fall_off[0][0][0]; for(int i = 0; i <= diam; i++) { for(int j = 0; j <= diam; j++) for (int k=0; k <= diam; k++) *den_ptr++ -= *fall_ptr++; den_ptr += GRID_SIZE - (diam+1); } } /*************************************************** * Function: DensityGrid::Add * * Description: Add a node to the density grid * **************************************************/ void DensityGrid::Add(Node &N) { int x_grid, y_grid, z_grid, diam; float *den_ptr, *fall_ptr; /* Where to add */ x_grid = (int)((N.x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.y+HALF_VIEW+.5)*VIEW_TO_GRID); z_grid = (int)((N.z+HALF_VIEW+.5)*VIEW_TO_GRID); N.sub_x = N.x; N.sub_y = N.y; N.sub_z = N.z; x_grid -= RADIUS; y_grid -= RADIUS; z_grid -= RADIUS; diam = 2*RADIUS; // check to see that we are inside grid if ( (x_grid >= GRID_SIZE) || (x_grid < 0) || (y_grid >= GRID_SIZE) || (y_grid < 0) || (z_grid >= GRID_SIZE) || (z_grid < 0) ) { #ifdef MUSE_MPI MPI_Abort ( MPI_COMM_WORLD, 1 ); #else igraph_error("Exceeded density grid in DrL", __FILE__, __LINE__, IGRAPH_EDRL); return; #endif } /* Add density values */ den_ptr = &Density[z_grid][y_grid][x_grid]; fall_ptr = &fall_off[0][0][0]; for(int i = 0; i <= diam; i++) { for(int j = 0; j <= diam; j++) for (int k = 0; k <= diam; k++) *den_ptr++ += *fall_ptr++; den_ptr += GRID_SIZE - (diam+1); } } /*************************************************** * Function: DensityGrid::fineSubtract * * Description: Subtract a node from bins * **************************************************/ void DensityGrid::fineSubtract(Node &N) { int x_grid, y_grid, z_grid; /* Where to subtract */ x_grid = (int)((N.sub_x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.sub_y+HALF_VIEW+.5)*VIEW_TO_GRID); z_grid = (int)((N.sub_z+HALF_VIEW+.5)*VIEW_TO_GRID); GET_BIN(z_grid,y_grid,x_grid).pop_front(); } /*************************************************** * Function: DensityGrid::fineAdd * * Description: Add a node to the bins * **************************************************/ void DensityGrid::fineAdd(Node &N) { int x_grid, y_grid, z_grid; /* Where to add */ x_grid = (int)((N.x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.y+HALF_VIEW+.5)*VIEW_TO_GRID); z_grid = (int)((N.z+HALF_VIEW+.5)*VIEW_TO_GRID); N.sub_x = N.x; N.sub_y = N.y; N.sub_z = N.z; GET_BIN(z_grid,y_grid,x_grid).push_back(N); } } // namespace drl3d igraph/src/igraph_trie.c0000644000175100001440000002506013431000472014767 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \ingroup igraphtrie * \brief Creates a trie node (not to be called directly) * \return Error code: errors by igraph_strvector_init(), * igraph_vector_ptr_init() and igraph_vector_init() might be returned. */ int igraph_i_trie_init_node(igraph_trie_node_t *t) { IGRAPH_STRVECTOR_INIT_FINALLY(&t->strs, 0); IGRAPH_VECTOR_PTR_INIT_FINALLY(&t->children, 0); IGRAPH_VECTOR_INIT_FINALLY(&t->values, 0); IGRAPH_FINALLY_CLEAN(3); return 0; } void igraph_i_trie_destroy_node(igraph_trie_node_t *t, igraph_bool_t sfree); /** * \ingroup igraphtrie * \brief Creates a trie. * \return Error code: errors by igraph_strvector_init(), * igraph_vector_ptr_init() and igraph_vector_init() might be returned. */ int igraph_trie_init(igraph_trie_t *t, igraph_bool_t storekeys) { t->maxvalue=-1; t->storekeys=storekeys; IGRAPH_CHECK(igraph_i_trie_init_node( (igraph_trie_node_t *)t )); IGRAPH_FINALLY(igraph_i_trie_destroy_node, t); if (storekeys) { IGRAPH_CHECK(igraph_strvector_init(&t->keys, 0)); } IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup igraphtrie * \brief Destroys a node of a trie (not to be called directly). */ void igraph_i_trie_destroy_node(igraph_trie_node_t *t, igraph_bool_t sfree) { long int i; igraph_strvector_destroy(&t->strs); for (i=0; ichildren); i++) { igraph_trie_node_t *child=VECTOR(t->children)[i]; if (child != 0) { igraph_i_trie_destroy_node(child, 1); } } igraph_vector_ptr_destroy(&t->children); igraph_vector_destroy(&t->values); if (sfree) { igraph_Free(t); } } /** * \ingroup igraphtrie * \brief Destroys a trie (frees allocated memory). */ void igraph_trie_destroy(igraph_trie_t *t) { if (t->storekeys) { igraph_strvector_destroy(&t->keys); } igraph_i_trie_destroy_node( (igraph_trie_node_t*) t, 0); } /** * \ingroup igraphtrie * \brief Internal helping function for igraph_trie_t */ long int igraph_i_strdiff(const char *str, const char *key) { long int diff=0; while (key[diff] != '\0' && str[diff] != '\0' && str[diff]==key[diff]) { diff++; } return diff; } /** * \ingroup igraphtrie * \brief Search/insert in a trie (not to be called directly). * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_trie_get_node(igraph_trie_node_t *t, const char *key, igraph_real_t newvalue, long int *id) { char *str; long int i; igraph_bool_t add; /* If newvalue is negative, we don't add the node if nonexistent, only check * for its existence */ add = (newvalue>=0); for (i=0; istrs); i++) { long int diff; igraph_strvector_get(&t->strs, i, &str); diff=igraph_i_strdiff(str, key); if (diff == 0) { /* ------------------------------------ */ /* No match, next */ } else if (str[diff]=='\0' && key[diff]=='\0') { /* ------------------------------------ */ /* They are exactly the same */ if (VECTOR(t->values)[i] != -1) { *id=(long int) VECTOR(t->values)[i]; return 0; } else { VECTOR(t->values)[i]=newvalue; *id=(long int) newvalue; return 0; } } else if (str[diff]=='\0') { /* ------------------------------------ */ /* str is prefix of key, follow its link if there is one */ igraph_trie_node_t *node=VECTOR(t->children)[i]; if (node != 0) { return igraph_trie_get_node(node, key+diff, newvalue, id); } else if (add) { igraph_trie_node_t *node=igraph_Calloc(1, igraph_trie_node_t); if (node==0) { IGRAPH_ERROR("cannot add to trie", IGRAPH_ENOMEM); } IGRAPH_STRVECTOR_INIT_FINALLY(&node->strs, 1); IGRAPH_VECTOR_PTR_INIT_FINALLY(&node->children, 1); IGRAPH_VECTOR_INIT_FINALLY(&node->values, 1); IGRAPH_CHECK(igraph_strvector_set(&node->strs, 0, key+diff)); VECTOR(node->children)[0]=0; VECTOR(node->values)[0]=newvalue; VECTOR(t->children)[i]=node; *id=(long int) newvalue; IGRAPH_FINALLY_CLEAN(3); return 0; } else { *id=-1; return 0; } } else if (key[diff]=='\0' && add) { /* ------------------------------------ */ /* key is prefix of str, the node has to be cut */ char *str2; igraph_trie_node_t *node=igraph_Calloc(1, igraph_trie_node_t); if (node==0) { IGRAPH_ERROR("cannot add to trie", IGRAPH_ENOMEM); } IGRAPH_STRVECTOR_INIT_FINALLY(&node->strs, 1); IGRAPH_VECTOR_PTR_INIT_FINALLY(&node->children, 1); IGRAPH_VECTOR_INIT_FINALLY(&node->values, 1); IGRAPH_CHECK(igraph_strvector_set(&node->strs, 0, str+diff)); VECTOR(node->children)[0]=VECTOR(t->children)[i]; VECTOR(node->values)[0]=VECTOR(t->values)[i]; str2=strdup(str); if (str2 == 0) { IGRAPH_ERROR("cannot add to trie", IGRAPH_ENOMEM); } str2[diff]='\0'; IGRAPH_FINALLY(free, str2); IGRAPH_CHECK(igraph_strvector_set(&t->strs, i, str2)); free(str2); IGRAPH_FINALLY_CLEAN(4); VECTOR(t->values)[i]=newvalue; VECTOR(t->children)[i]=node; *id=(long int) newvalue; return 0; } else if (add) { /* ------------------------------------ */ /* the first diff characters match */ char *str2; igraph_trie_node_t *node=igraph_Calloc(1, igraph_trie_node_t); if (node==0) { IGRAPH_ERROR("cannot add to trie", IGRAPH_ENOMEM); } IGRAPH_STRVECTOR_INIT_FINALLY(&node->strs, 2); IGRAPH_VECTOR_PTR_INIT_FINALLY(&node->children, 2); IGRAPH_VECTOR_INIT_FINALLY(&node->values, 2); IGRAPH_CHECK(igraph_strvector_set(&node->strs, 0, str+diff)); IGRAPH_CHECK(igraph_strvector_set(&node->strs, 1, key+diff)); VECTOR(node->children)[0]=VECTOR(t->children)[i]; VECTOR(node->children)[1]=0; VECTOR(node->values)[0]=VECTOR(t->values)[i]; VECTOR(node->values)[1]=newvalue; str2=strdup(str); if (str2 == 0) { IGRAPH_ERROR("cannot add to trie", IGRAPH_ENOMEM); } str2[diff]='\0'; IGRAPH_FINALLY(free, str2); IGRAPH_CHECK(igraph_strvector_set(&t->strs, i, str2)); free(str2); IGRAPH_FINALLY_CLEAN(4); VECTOR(t->values)[i]=-1; VECTOR(t->children)[i]=node; *id=(long int) newvalue; return 0; } else { /* ------------------------------------------------- */ /* No match, but we requested not to add the new key */ *id=-1; return 0; } } /* ------------------------------------ */ /* Nothing matches */ if (add) { IGRAPH_CHECK(igraph_vector_ptr_reserve(&t->children, igraph_vector_ptr_size(&t->children)+1)); IGRAPH_CHECK(igraph_vector_reserve(&t->values, igraph_vector_size(&t->values)+1)); IGRAPH_CHECK(igraph_strvector_add(&t->strs, key)); igraph_vector_ptr_push_back(&t->children, 0); /* allocated */ igraph_vector_push_back(&t->values, newvalue); /* allocated */ *id=(long int) newvalue; } else { *id=-1; } return 0; } /** * \ingroup igraphtrie * \brief Search/insert in a trie. */ int igraph_trie_get(igraph_trie_t *t, const char *key, long int *id) { if (!t->storekeys) { IGRAPH_CHECK(igraph_trie_get_node( (igraph_trie_node_t*) t, key, t->maxvalue+1, id)); if (*id > t->maxvalue) { t->maxvalue=*id; } return 0; } else { int ret; igraph_error_handler_t *oldhandler; oldhandler=igraph_set_error_handler(igraph_error_handler_ignore); /* Add it to the string vector first, we can undo this later */ ret=igraph_strvector_add(&t->keys, key); if (ret != 0) { igraph_set_error_handler(oldhandler); IGRAPH_ERROR("cannot get element from trie", ret); } ret = igraph_trie_get_node( (igraph_trie_node_t*) t, key, t->maxvalue+1, id); if (ret != 0) { igraph_strvector_resize(&t->keys, igraph_strvector_size(&t->keys)-1); igraph_set_error_handler(oldhandler); IGRAPH_ERROR("cannot get element from trie", ret); } /* everything is fine */ if (*id > t->maxvalue) { t->maxvalue=*id; } else { igraph_strvector_resize(&t->keys, igraph_strvector_size(&t->keys)-1); } igraph_set_error_handler(oldhandler); } return 0; } /** * \ingroup igraphtrie * \brief Search/insert in a trie (for internal use). * * @return Error code: * - IGRAPH_ENOMEM: out of memory */ int igraph_trie_get2(igraph_trie_t *t, const char *key, long int length, long int *id) { char *tmp=igraph_Calloc(length+1, char); if (tmp==0) { IGRAPH_ERROR("Cannot get from trie", IGRAPH_ENOMEM); } strncpy(tmp, key, length); tmp[length]='\0'; IGRAPH_FINALLY(free, tmp); IGRAPH_CHECK(igraph_trie_get(t, tmp, id)); igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup igraphtrie * \brief Search in a trie. * This variant does not add \c key to the trie if it does not exist. * In this case, a negative id is returned. */ int igraph_trie_check(igraph_trie_t *t, const char *key, long int *id) { IGRAPH_CHECK(igraph_trie_get_node( (igraph_trie_node_t*) t, key, -1, id)); return 0; } /** * \ingroup igraphtrie * \brief Get an element of a trie based on its index. */ void igraph_trie_idx(igraph_trie_t *t, long int idx, char **str) { igraph_strvector_get(&t->keys, idx, str); } /** * \ingroup igraphtrie * \brief Returns the size of a trie. */ long int igraph_trie_size(igraph_trie_t *t) { return t->maxvalue+1; } /* Hmmm, very dirty.... */ int igraph_trie_getkeys(igraph_trie_t *t, const igraph_strvector_t **strv) { *strv=&t->keys; return 0; } igraph/src/igraph_blas_internal.h0000644000175100001440000000400313431000472016640 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef BLAS_INTERNAL_H #define BLAS_INTERNAL_H /* Note: only files calling the BLAS routines directly need to include this header. */ #include "igraph_types.h" #include "config.h" #ifndef INTERNAL_BLAS #define igraphdaxpy_ daxpy_ #define igraphdger_ dger_ #define igraphdcopy_ dcopy_ #define igraphdscal_ dscal_ #define igraphdswap_ dswap_ #define igraphdgemm_ dgemm_ #define igraphdgemv_ dgemv_ #define igraphddot_ ddot_ #define igraphdnrm2_ dnrm2_ #define igraphlsame_ lsame_ #define igraphdrot_ drot_ #define igraphidamax_ idamax_ #define igraphdtrmm_ dtrmm_ #define igraphdasum_ dasum_ #define igraphdtrsm_ dtrsm_ #define igraphdtrsv_ dtrsv_ #define igraphdnrm2_ dnrm2_ #endif int igraphdgemv_(char *trans, int *m, int *n, igraph_real_t *alpha, igraph_real_t *a, int *lda, igraph_real_t *x, int *incx, igraph_real_t *beta, igraph_real_t *y, int *incy); int igraphdgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c__, int *ldc); double igraphdnrm2_(int *n, double *x, int *incx); #endif igraph/src/blas.c0000644000175100001440000000736313431000472013421 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_blas.h" #include "igraph_blas_internal.h" #include /** * \function igraph_blas_dgemv * \brief Matrix-vector multiplication using BLAS, vector version. * * This function is a somewhat more user-friendly interface to * the \c dgemv function in BLAS. \c dgemv performs the operation * y = alpha*A*x + beta*y, where x and y are vectors and A is an * appropriately sized matrix (symmetric or unsymmetric). * * \param transpose whether to transpose the matrix \p A * \param alpha the constant \p alpha * \param a the matrix \p A * \param x the vector \p x * \param beta the constant \p beta * \param y the vector \p y (which will be modified in-place) * * Time complexity: O(nk) if the matrix is of size n x k * * \sa \ref igraph_blas_dgemv_array if you have arrays instead of * vectors. * * \example examples/simple/blas.c */ void igraph_blas_dgemv(igraph_bool_t transpose, igraph_real_t alpha, const igraph_matrix_t* a, const igraph_vector_t* x, igraph_real_t beta, igraph_vector_t* y) { char trans = transpose ? 'T' : 'N'; int m, n; int inc = 1; m = (int) igraph_matrix_nrow(a); n = (int) igraph_matrix_ncol(a); assert(igraph_vector_size(x) == transpose ? m : n); assert(igraph_vector_size(y) == transpose ? n : m); igraphdgemv_(&trans, &m, &n, &alpha, VECTOR(a->data), &m, VECTOR(*x), &inc, &beta, VECTOR(*y), &inc); } /** * \function igraph_blas_dgemv_array * \brief Matrix-vector multiplication using BLAS, array version. * * This function is a somewhat more user-friendly interface to * the \c dgemv function in BLAS. \c dgemv performs the operation * y = alpha*A*x + beta*y, where x and y are vectors and A is an * appropriately sized matrix (symmetric or unsymmetric). * * \param transpose whether to transpose the matrix \p A * \param alpha the constant \p alpha * \param a the matrix \p A * \param x the vector \p x as a regular C array * \param beta the constant \p beta * \param y the vector \p y as a regular C array * (which will be modified in-place) * * Time complexity: O(nk) if the matrix is of size n x k * * \sa \ref igraph_blas_dgemv if you have vectors instead of * arrays. */ void igraph_blas_dgemv_array(igraph_bool_t transpose, igraph_real_t alpha, const igraph_matrix_t* a, const igraph_real_t* x, igraph_real_t beta, igraph_real_t* y) { char trans = transpose ? 'T' : 'N'; int m, n; int inc = 1; m = (int) igraph_matrix_nrow(a); n = (int) igraph_matrix_ncol(a); igraphdgemv_(&trans, &m, &n, &alpha, VECTOR(a->data), &m, (igraph_real_t*)x, &inc, &beta, y, &inc); } igraph_real_t igraph_blas_dnrm2(const igraph_vector_t *v) { int n =igraph_vector_size(v); int one = 1; return igraphdnrm2_(&n, VECTOR(*v), &one); } igraph/src/stack.pmt0000644000175100001440000001575213430770205014173 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \ingroup stack * \function igraph_stack_init * \brief Initializes a stack. * * The initialized stack is always empty. * \param s Pointer to an uninitialized stack. * \param size The number of elements to allocate memory for. * \return Error code. * * Time complexity: O(\p size). */ int FUNCTION(igraph_stack,init) (TYPE(igraph_stack)* s, long int size) { long int alloc_size= size > 0 ? size : 1; assert (s != NULL); if (size < 0) { size=0; } s->stor_begin=igraph_Calloc(alloc_size, BASE); if (s->stor_begin==0) { IGRAPH_ERROR("stack init failed", IGRAPH_ENOMEM); } s->stor_end=s->stor_begin + alloc_size; s->end=s->stor_begin; return 0; } /** * \ingroup stack * \function igraph_stack_destroy * \brief Destroys a stack object. * * Deallocate the memory used for a stack. * It is possible to reinitialize a destroyed stack again by * \ref igraph_stack_init(). * \param s The stack to destroy. * * Time complexity: O(1). */ void FUNCTION(igraph_stack,destroy) (TYPE(igraph_stack)* s) { assert( s != NULL); if (s->stor_begin != 0) { igraph_Free(s->stor_begin); s->stor_begin=NULL; } } /** * \ingroup stack * \function igraph_stack_reserve * \brief Reserve memory. * * Reverse memory for future use. The actual size of the stack is * unchanged. * \param s The stack object. * \param size The number of elements to reserve memory for. If it is * not bigger than the current size then nothing happens. * \return Error code. * * Time complexity: should be around O(n), the new allocated size of * the stack. */ int FUNCTION(igraph_stack,reserve) (TYPE(igraph_stack)* s, long int size) { long int actual_size=FUNCTION(igraph_stack,size)(s); BASE *tmp; assert(s != NULL); assert(s->stor_begin != NULL); if (size <= actual_size) { return 0; } tmp=igraph_Realloc(s->stor_begin, (size_t) size, BASE); if (tmp==0) { IGRAPH_ERROR("stack reserve failed", IGRAPH_ENOMEM); } s->stor_begin=tmp; s->stor_end=s->stor_begin + size; s->end=s->stor_begin+actual_size; return 0; } /** * \ingroup stack * \function igraph_stack_empty * \brief Decides whether a stack object is empty. * * \param s The stack object. * \return Boolean, \c TRUE if the stack is empty, \c FALSE * otherwise. * * Time complexity: O(1). */ igraph_bool_t FUNCTION(igraph_stack,empty) (TYPE(igraph_stack)* s) { assert (s != NULL); assert (s->stor_begin != NULL); assert (s->end != NULL); return s->stor_begin == s->end; } /** * \ingroup stack * \function igraph_stack_size * \brief Returns the number of elements in a stack. * * \param s The stack object. * \return The number of elements in the stack. * * Time complexity: O(1). */ long int FUNCTION(igraph_stack,size) (const TYPE(igraph_stack)* s) { assert (s != NULL); assert (s->stor_begin != NULL); return s->end - s->stor_begin; } /** * \ingroup stack * \function igraph_stack_clear * \brief Removes all elements from a stack. * * \param s The stack object. * * Time complexity: O(1). */ void FUNCTION(igraph_stack,clear) (TYPE(igraph_stack)* s) { assert (s != NULL); assert (s->stor_begin != NULL); s->end = s->stor_begin; } /** * \ingroup stack * \function igraph_stack_push * \brief Places an element on the top of a stack. * * The capacity of the stack is increased, if needed. * \param s The stack object. * \param elem The element to push. * \return Error code. * * Time complexity: O(1) is no reallocation is needed, O(n) * otherwise, but it is ensured that n push operations are performed * in O(n) time. */ int FUNCTION(igraph_stack,push)(TYPE(igraph_stack)* s, BASE elem) { assert (s != NULL); assert (s->stor_begin != NULL); if (s->end == s->stor_end) { /* full, allocate more storage */ BASE *bigger=NULL, *old=s->stor_begin; bigger = igraph_Calloc(2*FUNCTION(igraph_stack,size)(s)+1, BASE); if (bigger==0) { IGRAPH_ERROR("stack push failed", IGRAPH_ENOMEM); } memcpy(bigger, s->stor_begin, (size_t) FUNCTION(igraph_stack,size)(s)*sizeof(BASE)); s->end = bigger + (s->stor_end - s->stor_begin); s->stor_end = bigger + 2*(s->stor_end - s->stor_begin)+1; s->stor_begin = bigger; *(s->end) = elem; (s->end) += 1; igraph_Free(old); } else { *(s->end) = elem; (s->end) += 1; } return 0; } /** * \ingroup stack * \function igraph_stack_pop * \brief Removes and returns an element from the top of a stack. * * The stack must contain at least one element, call \ref * igraph_stack_empty() to make sure of this. * \param s The stack object. * \return The removed top element. * * Time complexity: O(1). */ BASE FUNCTION(igraph_stack,pop) (TYPE(igraph_stack)* s) { assert (s != NULL); assert (s->stor_begin != NULL); assert (s->end != NULL); assert (s->end != s->stor_begin); (s->end)--; return *(s->end); } /** * \ingroup stack * \function igraph_stack_top * \brief Query top element. * * Returns the top element of the stack, without removing it. * The stack must be non-empty. * \param s The stack. * \return The top element. * * Time complexity: O(1). */ BASE FUNCTION(igraph_stack,top) (const TYPE(igraph_stack)* s) { assert (s != NULL); assert (s->stor_begin != NULL); assert (s->end != NULL); assert (s->end != s->stor_begin); return *(s->end-1); } #if defined (OUT_FORMAT) #ifndef USING_R int FUNCTION(igraph_stack,print)(const TYPE(igraph_stack) *s) { long int i, n=FUNCTION(igraph_stack,size)(s); if (n!=0) { printf(OUT_FORMAT, s->stor_begin[0]); } for (i=1; istor_begin[i]); } printf("\n"); return 0; } #endif int FUNCTION(igraph_stack,fprint)(const TYPE(igraph_stack) *s, FILE *file) { long int i, n=FUNCTION(igraph_stack,size)(s); if (n!=0) { fprintf(file, OUT_FORMAT, s->stor_begin[0]); } for (i=1; istor_begin[i]); } fprintf(file, "\n"); return 0; } #endif igraph/src/glet.c0000644000175100001440000006505413431000472013434 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_graphlets.h" #include "igraph_memory.h" #include "igraph_constructors.h" #include "igraph_cliques.h" #include "igraph_structural.h" #include "igraph_qsort.h" #include "igraph_conversion.h" /** * \section graphlets_intro Introduction * * * Graphlet decomposition models a weighted undirected graph * via the union of potentially overlapping dense social groups. * This is done by a two-step algorithm. In the first step a candidate * set of groups (a candidate basis) is created by finding cliques * if the thresholded input graph. In the second step these * the graph is projected on the candidate basis, resulting a * weight coefficient for each clique in the candidate basis. * * * * igraph contains three functions for performing the graph * decomponsition of a graph. The first is \ref igraph_graphlets(), which * performed both steps on the method and returns a list of subgraphs, * with their corresponding weights. The second and third functions * correspond to the first and second steps of the algorithm, and they are * useful if the user wishes to perform them individually: * \ref igraph_graphlets_candidate_basis() and * \ref igraph_graphlets_project(). * */ typedef struct { igraph_vector_int_t *resultids; igraph_t *result; igraph_vector_t *resultweights; int nc; } igraph_i_subclique_next_free_t; void igraph_i_subclique_next_free(void *ptr) { igraph_i_subclique_next_free_t *data=ptr; int i; if (data->resultids) { for (i=0; inc; i++) { if (data->resultids+i) { igraph_vector_int_destroy(data->resultids+i); } } igraph_Free(data->resultids); } if (data->result) { for (i=0; inc; i++) { if (data->result+i) { igraph_destroy(data->result+i); } } igraph_Free(data->result); } if (data->resultweights) { for (i=0; inc; i++) { if (data->resultweights+i) { igraph_vector_destroy(data->resultweights+i); } } igraph_Free(data->resultweights); } } /** * \function igraph_subclique_next * Calculate subcliques of the cliques found at the previous level * * \param graph Input graph. * \param weight Edge weights. * \param ids The ids of the vertices in the input graph. * \param cliques A list of vectors, vertex ids for cliques. * \param result The result is stored here, a list of graphs is stored * here. * \param resultids The ids of the vertices in the result graphs is * stored here. * \param clique_thr The thresholds for the cliques are stored here, * if not a null pointer. * \param next_thr The next thresholds for the cliques are stored * here, if not a null pointer. * */ int igraph_i_subclique_next(const igraph_t *graph, const igraph_vector_t *weights, const igraph_vector_int_t *ids, const igraph_vector_ptr_t *cliques, igraph_t **result, igraph_vector_t **resultweights, igraph_vector_int_t **resultids, igraph_vector_t *clique_thr, igraph_vector_t *next_thr) { /* The input is a set of cliques, that were found at a previous level. For each clique, we calculate the next threshold, drop the isolate vertices, and create a new graph from them. */ igraph_vector_int_t mark, map; igraph_vector_int_t edges; igraph_vector_t neis, newedges; igraph_integer_t c, nc=igraph_vector_ptr_size(cliques); igraph_integer_t no_of_nodes=igraph_vcount(graph); igraph_integer_t no_of_edges=igraph_ecount(graph); igraph_i_subclique_next_free_t freedata={ 0, 0, 0, nc }; if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid length of weight vector", IGRAPH_EINVAL); } if (igraph_vector_int_size(ids) != no_of_nodes) { IGRAPH_ERROR("Invalid length of ID vector", IGRAPH_EINVAL); } IGRAPH_FINALLY(igraph_i_subclique_next_free, &freedata); *resultids=igraph_Calloc(nc, igraph_vector_int_t); if (!*resultids) { IGRAPH_ERROR("Cannot calculate next cliques", IGRAPH_ENOMEM); } freedata.resultids = *resultids; *resultweights=igraph_Calloc(nc, igraph_vector_t); if (!*resultweights) { IGRAPH_ERROR("Cannot calculate next cliques", IGRAPH_ENOMEM); } freedata.resultweights = *resultweights; *result=igraph_Calloc(nc, igraph_t); if (!*result) { IGRAPH_ERROR("Cannot calculate next cliques", IGRAPH_ENOMEM); } freedata.result = *result; igraph_vector_init(&newedges, 100); IGRAPH_FINALLY(igraph_vector_destroy, &newedges); igraph_vector_int_init(&mark, no_of_nodes); IGRAPH_FINALLY(igraph_vector_destroy, &mark); igraph_vector_int_init(&map, no_of_nodes); IGRAPH_FINALLY(igraph_vector_destroy, &map); igraph_vector_int_init(&edges, 100); IGRAPH_FINALLY(igraph_vector_int_destroy, &edges); igraph_vector_init(&neis, 10); IGRAPH_FINALLY(igraph_vector_destroy, &neis); if (clique_thr) { igraph_vector_resize(clique_thr, nc); } if (next_thr) { igraph_vector_resize(next_thr, nc); } /* Iterate over all cliques. We will create graphs for all subgraphs defined by the cliques. */ for (c=0; c minweight && w < nextweight) { nextweight=w; } } } } /* v < clsize */ /* --------------------------------------------------- */ /* OK, we have stored the edges and found the weight of the clique and the next weight to consider */ if (clique_thr) { VECTOR(*clique_thr)[c] = minweight; } if (next_thr) { VECTOR(*next_thr )[c] = nextweight; } /* --------------------------------------------------- */ /* Now we create the subgraph from the edges above the next threshold, and their incident vertices. */ igraph_vector_int_init(newids, 0); igraph_vector_init(neww, 0); /* We use mark[] to denote the vertices already mapped to the new graph. If this is -(c+1), then the vertex was mapped, otherwise it was not. The mapping itself is in map[]. */ noe=igraph_vector_int_size(&edges); for (e=0; e= nextweight) { if (VECTOR(mark)[from] == c+1) { VECTOR(map)[from] = nov++; VECTOR(mark)[from] = -(c+1); igraph_vector_int_push_back(newids, VECTOR(*ids)[from]); } if (VECTOR(mark)[to] == c+1) { VECTOR(map)[to] = nov++; VECTOR(mark)[to] = -(c+1); igraph_vector_int_push_back(newids, VECTOR(*ids)[to]); } igraph_vector_push_back(neww, w); igraph_vector_push_back(&newedges, VECTOR(map)[from]); igraph_vector_push_back(&newedges, VECTOR(map)[to]); } } igraph_create(newgraph, &newedges, nov, IGRAPH_UNDIRECTED); /* --------------------------------------------------- */ } /* c < nc */ igraph_vector_destroy(&neis); igraph_vector_int_destroy(&edges); igraph_vector_int_destroy(&mark); igraph_vector_int_destroy(&map); igraph_vector_destroy(&newedges); IGRAPH_FINALLY_CLEAN(6); /* + freedata */ return 0; } void igraph_i_graphlets_destroy_vectorlist(igraph_vector_ptr_t *vl) { int i, n=igraph_vector_ptr_size(vl); for (i=0; i= startthr) { IGRAPH_CHECK(igraph_vector_push_back(&subv, i)); } } igraph_subgraph_edges(graph, &subg, igraph_ess_vector(&subv), /*delete_vertices=*/ 0); IGRAPH_FINALLY(igraph_destroy, &subg); igraph_maximal_cliques(&subg, &mycliques, /*min_size=*/ 0, /*max_size=*/ 0); igraph_destroy(&subg); IGRAPH_FINALLY_CLEAN(1); nocliques=igraph_vector_ptr_size(&mycliques); igraph_vector_destroy(&subv); IGRAPH_FINALLY_CLEAN(1); /* Get the next cliques and thresholds */ IGRAPH_VECTOR_INIT_FINALLY(&next_thr, 0); IGRAPH_VECTOR_INIT_FINALLY(&clique_thr, 0); igraph_i_subclique_next(graph, weights, ids, &mycliques, &newgraphs, &newweights, &newids, &clique_thr, &next_thr); freedata.result = newgraphs; freedata.resultids = newids; freedata.resultweights = newweights; freedata.nc = nocliques; IGRAPH_FINALLY(igraph_i_subclique_next_free, &freedata); /* Store cliques at the current level */ igraph_vector_append(thresholds, &clique_thr); for (i=0; i 1) { igraph_vector_t *w=newweights + i; igraph_vector_int_t *ids=newids +i; igraph_i_graphlets(g, w, cliques, thresholds, ids, VECTOR(next_thr)[i]); } } igraph_vector_destroy(&clique_thr); igraph_vector_destroy(&next_thr); igraph_i_subclique_next_free(&freedata); igraph_vector_ptr_destroy(&mycliques); /* contents was copied over */ IGRAPH_FINALLY_CLEAN(4); return 0; } typedef struct { const igraph_vector_ptr_t *cliques; const igraph_vector_t *thresholds; } igraph_i_graphlets_filter_t; int igraph_i_graphlets_filter_cmp(void *data, const void *a, const void *b) { igraph_i_graphlets_filter_t *ddata=(igraph_i_graphlets_filter_t *) data; int *aa=(int*) a; int *bb=(int*) b; igraph_real_t t_a=VECTOR(*ddata->thresholds)[*aa]; igraph_real_t t_b=VECTOR(*ddata->thresholds)[*bb]; igraph_vector_t *v_a, *v_b; int s_a, s_b; if (t_a < t_b) { return -1; } else if (t_a > t_b) { return 1; } v_a=(igraph_vector_t*) VECTOR(*ddata->cliques)[*aa]; v_b=(igraph_vector_t*) VECTOR(*ddata->cliques)[*bb]; s_a=igraph_vector_size(v_a); s_b=igraph_vector_size(v_b); if (s_a < s_b) { return -1; } else if (s_a > s_b) { return 1; } else { return 0; } } int igraph_i_graphlets_filter(igraph_vector_ptr_t *cliques, igraph_vector_t *thresholds) { /* Filter out non-maximal cliques. Every non-maximal clique is part of a maximal clique, at the same threshold. First we order the cliques, according to their threshold, and then according to their size. So when we look for a candidate superset, we only need to check the cliques next in the list, until their threshold is different. */ int i, iptr, nocliques=igraph_vector_ptr_size(cliques); igraph_vector_int_t order; igraph_i_graphlets_filter_t sortdata = { cliques, thresholds }; igraph_vector_int_init(&order, nocliques); IGRAPH_FINALLY(igraph_vector_int_destroy, &order); for (i=0; i n_j) { continue; } /* Check if hay is a superset */ while (pi < n_i && pj < n_j && n_i-pi <= n_j-pj) { int ei=VECTOR(*needle)[pi]; int ej=VECTOR(*hay)[pj]; if (ei < ej) { break; } else if (ei > ej) { pj++; } else { pi++; pj++; } } if (pi == n_i) { /* Found, delete immediately */ igraph_vector_destroy(needle); igraph_free(needle); VECTOR(*cliques)[ri]=0; break; } } } /* Remove null pointers from the list of cliques */ for (i=0, iptr=0; iMu)[*aa]; igraph_real_t Mu_b = VECTOR(*ddata->Mu)[*bb]; if (Mu_a < Mu_b) { return 1; } else if (Mu_a > Mu_b) { return -1; } else { return 0; } } /** * \function igraph_graphlets * Calculate graphlets basis and project the graph on it * * This function simply calls \ref igraph_graphlets_candidate_basis() * and \ref igraph_graphlets_project(), and then orders the graphlets * according to decreasing weights. * \param graph The input graph, it must be a simple graph, edge directions are * ignored. * \param weights Weights of the edges, a vector. * \param cliques An initialized vector of pointers. * The graphlet basis is stored here. Each element of the pointer * vector will be a vector of vertex ids. * \param Mu An initialized vector, the weights of the graphlets will * be stored here. * \param niter Integer scalar, the number of iterations to perform * for the projection step. * \return Error code. * * See also: \ref igraph_graphlets_candidate_basis() and * \ref igraph_graphlets_project(). */ int igraph_graphlets(const igraph_t *graph, const igraph_vector_t *weights, igraph_vector_ptr_t *cliques, igraph_vector_t *Mu, int niter) { int i, nocliques; igraph_vector_t thresholds; igraph_vector_int_t order; igraph_i_graphlets_order_t sortdata={ cliques, Mu }; igraph_vector_init(&thresholds, 0); IGRAPH_FINALLY(igraph_vector_destroy, &thresholds); igraph_graphlets_candidate_basis(graph, weights, cliques, &thresholds); igraph_vector_destroy(&thresholds); IGRAPH_FINALLY_CLEAN(1); igraph_graphlets_project(graph, weights, cliques, Mu, /*startMu=*/ 0, niter); nocliques=igraph_vector_ptr_size(cliques); igraph_vector_int_init(&order, nocliques); IGRAPH_FINALLY(igraph_vector_int_destroy, &order); for (i=0; i 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "igraph_hacks_internal.h" #include "igraph_math.h" #include "igraph_types_internal.h" #include "foreign-dl-header.h" #include "foreign-dl-parser.h" #include #define yyscan_t void* int igraph_dl_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_dl_yyerror(YYLTYPE* locp, igraph_i_dl_parsedata_t* context, const char *s); char *igraph_dl_yyget_text (yyscan_t yyscanner ); int igraph_dl_yyget_leng (yyscan_t yyscanner ); int igraph_i_dl_add_str(char *newstr, int length, igraph_i_dl_parsedata_t *context); int igraph_i_dl_add_edge(long int from, long int to, igraph_i_dl_parsedata_t *context); int igraph_i_dl_add_edge_w(long int from, long int to, igraph_real_t weight, igraph_i_dl_parsedata_t *context); extern igraph_real_t igraph_pajek_get_number(const char *str, long int len); #define scanner context->scanner /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 86 "src/foreign-dl-parser.y" { long int integer; igraph_real_t real; } /* Line 193 of yacc.c. */ #line 195 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 220 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 4 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 118 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 17 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 37 /* YYNRULES -- Number of rules. */ #define YYNRULES 66 /* YYNRULES -- Number of states. */ #define YYNSTATES 138 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 271 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 11, 12, 15, 16, 18, 20, 22, 24, 28, 30, 31, 33, 37, 45, 51, 52, 56, 57, 61, 62, 65, 67, 69, 73, 74, 78, 80, 82, 85, 89, 93, 97, 105, 111, 121, 131, 132, 135, 140, 144, 146, 147, 150, 155, 159, 161, 163, 167, 170, 178, 184, 194, 204, 205, 208, 212, 214, 215, 218, 219, 222, 226, 228, 229 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 18, 0, -1, 5, 6, 39, 4, 21, 19, 20, -1, -1, 19, 23, -1, -1, 15, -1, 22, -1, 35, -1, 44, -1, 10, 23, 24, -1, 24, -1, -1, 4, -1, 7, 23, 26, -1, 8, 23, 25, 23, 7, 23, 26, -1, 9, 23, 7, 23, 29, -1, -1, 25, 23, 14, -1, -1, 26, 27, 4, -1, -1, 27, 28, -1, 13, -1, 30, -1, 31, 4, 33, -1, -1, 31, 23, 32, -1, 14, -1, 34, -1, 33, 34, -1, 14, 27, 4, -1, 11, 23, 36, -1, 7, 23, 37, -1, 8, 23, 25, 23, 7, 23, 37, -1, 9, 23, 7, 23, 40, -1, 8, 23, 25, 23, 9, 23, 7, 23, 40, -1, 9, 23, 8, 23, 25, 23, 7, 23, 40, -1, -1, 37, 38, -1, 39, 39, 42, 4, -1, 39, 39, 4, -1, 3, -1, -1, 40, 41, -1, 43, 43, 42, 4, -1, 43, 43, 4, -1, 3, -1, 14, -1, 12, 23, 45, -1, 7, 46, -1, 8, 23, 25, 23, 7, 23, 46, -1, 9, 23, 7, 23, 50, -1, 8, 23, 25, 23, 9, 23, 7, 23, 50, -1, 9, 23, 8, 23, 25, 23, 7, 23, 50, -1, -1, 46, 47, -1, 48, 49, 4, -1, 3, -1, -1, 49, 39, -1, -1, 50, 51, -1, 52, 53, 4, -1, 43, -1, -1, 53, 43, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 111, 111, 113, 113, 115, 115, 117, 118, 119, 122, 122, 124, 124, 126, 127, 128, 131, 132, 138, 138, 143, 143, 145, 155, 157, 159, 159, 161, 165, 169, 174, 178, 180, 181, 182, 183, 184, 187, 188, 191, 193, 197, 200, 201, 204, 206, 210, 213, 229, 231, 232, 233, 234, 235, 238, 239, 242, 244, 247, 247, 253, 254, 257, 259, 263, 263 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "NUM", "NEWLINE", "DL", "NEQ", "DATA", "LABELS", "LABELSEMBEDDED", "FORMATFULLMATRIX", "FORMATEDGELIST1", "FORMATNODELIST1", "DIGIT", "LABEL", "EOFF", "ERROR", "$accept", "input", "trail", "eof", "rest", "formfullmatrix", "newline", "fullmatrix", "labels", "fullmatrixdata", "zerooneseq", "zeroone", "labeledfullmatrixdata", "reallabeledfullmatrixdata", "labelseq", "label", "labeledmatrixlines", "labeledmatrixline", "edgelist1", "edgelist1rest", "edgelist1data", "edgelist1dataline", "integer", "labelededgelist1data", "labelededgelist1dataline", "weight", "elabel", "nodelist1", "nodelist1rest", "nodelist1data", "nodelist1dataline", "from", "tolist", "labelednodelist1data", "labelednodelist1dataline", "fromelabel", "labeltolist", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 17, 18, 19, 19, 20, 20, 21, 21, 21, 22, 22, 23, 23, 24, 24, 24, 25, 25, 26, 26, 27, 27, 28, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 36, 36, 36, 37, 37, 38, 38, 39, 40, 40, 41, 41, 42, 43, 44, 45, 45, 45, 45, 45, 46, 46, 47, 48, 49, 49, 50, 50, 51, 52, 53, 53 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 7, 0, 2, 0, 1, 1, 1, 1, 3, 1, 0, 1, 3, 7, 5, 0, 3, 0, 3, 0, 2, 1, 1, 3, 0, 3, 1, 1, 2, 3, 3, 3, 7, 5, 9, 9, 0, 2, 4, 3, 1, 0, 2, 4, 3, 1, 1, 3, 2, 7, 5, 9, 9, 0, 2, 3, 1, 0, 2, 0, 2, 3, 1, 0, 2 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 0, 0, 0, 1, 42, 0, 0, 12, 12, 12, 12, 12, 12, 3, 7, 11, 8, 9, 13, 19, 17, 0, 0, 0, 0, 5, 14, 12, 12, 10, 12, 12, 12, 32, 55, 12, 12, 49, 6, 2, 4, 0, 0, 26, 38, 17, 0, 50, 17, 0, 20, 23, 22, 12, 18, 16, 24, 12, 33, 12, 12, 12, 58, 56, 59, 12, 12, 12, 19, 0, 0, 39, 0, 0, 43, 17, 0, 0, 61, 17, 15, 21, 25, 29, 28, 27, 0, 12, 12, 35, 12, 57, 60, 12, 12, 52, 12, 0, 30, 47, 41, 0, 38, 0, 48, 44, 0, 0, 55, 0, 64, 62, 65, 0, 31, 40, 34, 12, 0, 12, 51, 12, 0, 12, 43, 46, 0, 43, 61, 63, 66, 61, 36, 45, 37, 53, 54 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 2, 26, 40, 14, 15, 20, 16, 28, 27, 42, 53, 56, 57, 58, 86, 83, 84, 17, 34, 59, 72, 73, 90, 106, 102, 107, 18, 38, 48, 64, 65, 77, 96, 112, 113, 123 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -114 static const yytype_int8 yypact[] = { 8, 38, 11, 43, -114, -114, 44, 57, 46, 46, 46, 46, 46, 46, -114, -114, -114, -114, -114, -114, -114, -114, 69, 53, 63, 66, 6, 65, 46, 46, -114, 46, 46, 46, -114, -114, 46, 46, -114, -114, -114, -114, 5, 19, -114, -114, -114, 76, 84, -114, 82, -114, -114, -114, 46, -114, -114, -114, 93, 43, 46, 46, 46, -114, -114, -114, 46, 46, 46, -114, 85, 86, -114, 43, 23, -114, -114, 88, 33, -114, -114, 65, -114, 85, -114, -114, -114, 90, 46, 46, 87, 46, -114, -114, 46, 46, 87, 46, 25, -114, -114, -114, 94, -114, 95, -114, -114, 87, 29, -114, 96, -114, -114, -114, 49, -114, -114, 43, 46, 92, 46, 84, 46, 2, 46, -114, -114, 100, -114, -114, -114, -114, -114, 87, -114, 87, 87, 87 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -114, -114, -114, -114, -114, -114, -9, 83, -41, 36, 26, -114, -114, -114, -114, -114, -114, 24, -114, -114, 7, -114, 4, -113, -114, -7, -82, -114, -114, 9, -114, -114, -114, -98, -114, -114, -114 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -22 static const yytype_int16 yytable[] = { 21, 22, 23, 24, 25, 60, 130, 6, 66, 51, 19, 4, 133, 1, 111, 135, 105, 41, 52, 43, 44, 39, 45, 46, 47, 119, 54, 49, 50, 115, 88, 136, 89, 55, 137, 91, 120, 55, 52, 97, 94, 131, 95, 55, 3, 69, 5, 55, 7, 71, 19, 74, 75, 76, 111, 111, 124, 78, 79, 80, 8, 9, 10, 55, 8, 9, 10, 11, 12, 13, 31, 32, 33, 35, 36, 37, 29, 87, -21, 103, 104, 93, 108, 61, 62, 109, 110, 63, 114, 67, 68, 5, 92, 100, 101, 100, 126, 70, 116, 82, 85, 105, 118, 122, 134, 81, 30, 99, 98, 125, 117, 128, 127, 129, 0, 132, 0, 0, 121 }; static const yytype_int16 yycheck[] = { 9, 10, 11, 12, 13, 46, 4, 3, 49, 4, 4, 0, 125, 5, 96, 128, 14, 26, 13, 28, 29, 15, 31, 32, 33, 107, 7, 36, 37, 4, 7, 129, 9, 14, 132, 76, 7, 14, 13, 80, 7, 123, 9, 14, 6, 54, 3, 14, 4, 58, 4, 60, 61, 62, 136, 137, 7, 66, 67, 68, 7, 8, 9, 14, 7, 8, 9, 10, 11, 12, 7, 8, 9, 7, 8, 9, 7, 73, 13, 88, 89, 77, 91, 7, 8, 94, 95, 3, 97, 7, 8, 3, 4, 3, 4, 3, 4, 4, 4, 14, 14, 14, 7, 7, 4, 69, 23, 83, 82, 118, 103, 120, 119, 122, -1, 124, -1, -1, 109 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 5, 18, 6, 0, 3, 39, 4, 7, 8, 9, 10, 11, 12, 21, 22, 24, 35, 44, 4, 23, 23, 23, 23, 23, 23, 19, 26, 25, 7, 24, 7, 8, 9, 36, 7, 8, 9, 45, 15, 20, 23, 27, 23, 23, 23, 23, 23, 46, 23, 23, 4, 13, 28, 7, 14, 29, 30, 31, 37, 25, 7, 8, 3, 47, 48, 25, 7, 8, 23, 4, 23, 38, 39, 23, 23, 23, 49, 23, 23, 23, 26, 14, 33, 34, 14, 32, 39, 7, 9, 40, 25, 4, 39, 7, 9, 50, 25, 27, 34, 3, 4, 42, 23, 23, 14, 41, 43, 23, 23, 23, 43, 51, 52, 23, 4, 4, 37, 7, 43, 7, 46, 7, 53, 7, 23, 4, 42, 23, 23, 4, 43, 23, 40, 4, 40, 50, 50 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc, scanner) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_dl_parsedata_t* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_dl_parsedata_t* context; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_dl_parsedata_t* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_dl_parsedata_t* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, igraph_i_dl_parsedata_t* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; igraph_i_dl_parsedata_t* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, igraph_i_dl_parsedata_t* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; igraph_i_dl_parsedata_t* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (igraph_i_dl_parsedata_t* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (igraph_i_dl_parsedata_t* context) #else int yyparse (context) igraph_i_dl_parsedata_t* context; #endif #endif { /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 111 "src/foreign-dl-parser.y" { context->n=(yyvsp[(3) - (7)].integer); ;} break; case 7: #line 117 "src/foreign-dl-parser.y" { context->type=IGRAPH_DL_MATRIX; ;} break; case 8: #line 118 "src/foreign-dl-parser.y" { context->type=IGRAPH_DL_EDGELIST1; ;} break; case 9: #line 119 "src/foreign-dl-parser.y" { context->type=IGRAPH_DL_NODELIST1; ;} break; case 10: #line 122 "src/foreign-dl-parser.y" {;} break; case 11: #line 122 "src/foreign-dl-parser.y" {;} break; case 14: #line 126 "src/foreign-dl-parser.y" { ;} break; case 15: #line 127 "src/foreign-dl-parser.y" { ;} break; case 16: #line 128 "src/foreign-dl-parser.y" { ;} break; case 17: #line 131 "src/foreign-dl-parser.y" {;} break; case 18: #line 132 "src/foreign-dl-parser.y" { igraph_i_dl_add_str(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), context); ;} break; case 19: #line 138 "src/foreign-dl-parser.y" {;} break; case 20: #line 138 "src/foreign-dl-parser.y" { context->from += 1; context->to = 0; ;} break; case 22: #line 143 "src/foreign-dl-parser.y" { ;} break; case 23: #line 145 "src/foreign-dl-parser.y" { if (igraph_dl_yyget_text(scanner)[0]=='1') { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->to)); } context->to += 1; ;} break; case 24: #line 155 "src/foreign-dl-parser.y" {;} break; case 25: #line 157 "src/foreign-dl-parser.y" {;} break; case 28: #line 161 "src/foreign-dl-parser.y" { igraph_i_dl_add_str(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), context); ;} break; case 29: #line 165 "src/foreign-dl-parser.y" { context->from += 1; context->to = 0; ;} break; case 30: #line 169 "src/foreign-dl-parser.y" { context->from += 1; context->to = 0; ;} break; case 31: #line 174 "src/foreign-dl-parser.y" { ;} break; case 32: #line 178 "src/foreign-dl-parser.y" {;} break; case 33: #line 180 "src/foreign-dl-parser.y" {;} break; case 34: #line 181 "src/foreign-dl-parser.y" {;} break; case 35: #line 182 "src/foreign-dl-parser.y" {;} break; case 36: #line 183 "src/foreign-dl-parser.y" {;} break; case 37: #line 184 "src/foreign-dl-parser.y" {;} break; case 38: #line 187 "src/foreign-dl-parser.y" {;} break; case 39: #line 188 "src/foreign-dl-parser.y" {;} break; case 40: #line 191 "src/foreign-dl-parser.y" { igraph_i_dl_add_edge_w((yyvsp[(1) - (4)].integer)-1, (yyvsp[(2) - (4)].integer)-1, (yyvsp[(3) - (4)].real), context); ;} break; case 41: #line 193 "src/foreign-dl-parser.y" { igraph_i_dl_add_edge((yyvsp[(1) - (3)].integer)-1, (yyvsp[(2) - (3)].integer)-1, context); ;} break; case 42: #line 197 "src/foreign-dl-parser.y" { (yyval.integer)=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); ;} break; case 43: #line 200 "src/foreign-dl-parser.y" {;} break; case 44: #line 201 "src/foreign-dl-parser.y" {;} break; case 45: #line 204 "src/foreign-dl-parser.y" { igraph_i_dl_add_edge_w((yyvsp[(1) - (4)].integer), (yyvsp[(2) - (4)].integer), (yyvsp[(3) - (4)].real), context); ;} break; case 46: #line 206 "src/foreign-dl-parser.y" { igraph_i_dl_add_edge((yyvsp[(1) - (3)].integer), (yyvsp[(2) - (3)].integer), context); ;} break; case 47: #line 210 "src/foreign-dl-parser.y" { (yyval.real)=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); ;} break; case 48: #line 213 "src/foreign-dl-parser.y" { /* Copy label list to trie, if needed */ if (igraph_strvector_size(&context->labels) != 0) { long int i, id, n=igraph_strvector_size(&context->labels); for (i=0; itrie, STR(context->labels, i), &id); } igraph_strvector_clear(&context->labels); } igraph_trie_get2(&context->trie, igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), &(yyval.integer)); ;} break; case 49: #line 229 "src/foreign-dl-parser.y" {;} break; case 50: #line 231 "src/foreign-dl-parser.y" {;} break; case 51: #line 232 "src/foreign-dl-parser.y" {;} break; case 52: #line 233 "src/foreign-dl-parser.y" {;} break; case 53: #line 234 "src/foreign-dl-parser.y" {;} break; case 54: #line 235 "src/foreign-dl-parser.y" {;} break; case 55: #line 238 "src/foreign-dl-parser.y" {;} break; case 56: #line 239 "src/foreign-dl-parser.y" {;} break; case 57: #line 242 "src/foreign-dl-parser.y" {;} break; case 58: #line 244 "src/foreign-dl-parser.y" { context->from=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); ;} break; case 59: #line 247 "src/foreign-dl-parser.y" {;} break; case 60: #line 247 "src/foreign-dl-parser.y" { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from-1)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, (yyvsp[(2) - (2)].integer)-1)); ;} break; case 61: #line 253 "src/foreign-dl-parser.y" {;} break; case 62: #line 254 "src/foreign-dl-parser.y" {;} break; case 63: #line 257 "src/foreign-dl-parser.y" { ;} break; case 64: #line 259 "src/foreign-dl-parser.y" { context->from=(yyvsp[(1) - (1)].integer); ;} break; case 66: #line 263 "src/foreign-dl-parser.y" { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, (yyvsp[(2) - (2)].integer))); ;} break; /* Line 1267 of yacc.c. */ #line 1884 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (&yylloc, context, yymsg); } else { yyerror (&yylloc, context, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 269 "src/foreign-dl-parser.y" int igraph_dl_yyerror(YYLTYPE* locp, igraph_i_dl_parsedata_t* context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "%s in line %i", s, locp->first_line); return 0; } int igraph_i_dl_add_str(char *newstr, int length, igraph_i_dl_parsedata_t *context) { int tmp=newstr[length]; newstr[length]='\0'; IGRAPH_CHECK(igraph_strvector_add(&context->labels, newstr)); newstr[length]=tmp; return 0; } int igraph_i_dl_add_edge(long int from, long int to, igraph_i_dl_parsedata_t *context) { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, to)); return 0; } int igraph_i_dl_add_edge_w(long int from, long int to, igraph_real_t weight, igraph_i_dl_parsedata_t *context) { long int n=igraph_vector_size(&context->weights); long int n2=igraph_vector_size(&context->edges)/2; if (n != n2) { igraph_vector_resize(&context->weights, n2); for (; nweights)[n]=IGRAPH_NAN; } } IGRAPH_CHECK(igraph_i_dl_add_edge(from, to, context)); IGRAPH_CHECK(igraph_vector_push_back(&context->weights, weight)); return 0; } igraph/src/foreign-pajek-header.h0000644000175100001440000000255213431000472016447 0ustar hornikusers/* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_vector.h" #include "igraph_types_internal.h" typedef struct { void *scanner; int eof; char errmsg[300]; igraph_vector_t *vector; igraph_bool_t directed; int vcount, vcount2; int actfrom; int actto; int mode; /* 0: general, 1: vertex, 2: edge */ igraph_trie_t *vertex_attribute_names; igraph_vector_ptr_t *vertex_attributes; igraph_trie_t *edge_attribute_names; igraph_vector_ptr_t *edge_attributes; int vertexid; int actvertex; int actedge; } igraph_i_pajek_parsedata_t; igraph/src/bipartite.c0000644000175100001440000010554413431000472014463 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2008-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_bipartite.h" #include "igraph_attributes.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_constructors.h" #include "igraph_dqueue.h" #include "igraph_random.h" #include "igraph_nongraph.h" /** * \section about_bipartite Bipartite networks in igraph * * * A bipartite network contains two kinds of vertices and connections * are only possible between two vertices of different kind. There are * many natural examples, e.g. movies and actors as vertices and a * movie is connected to all participating actors, etc. * * * igraph does not have direct support for bipartite networks, at * least not at the C language level. In other words the igraph_t * structure does not contain information about the vertex types. * The C functions for bipartite networks usually have an additional * input argument to graph, called \c types, a boolean vector giving * the vertex types. * * * Most functions creating bipartite networks are able to create this * extra vector, you just need to supply an initialized boolean vector * to them. */ /** * \function igraph_bipartite_projection_size * Calculate the number of vertices and edges in the bipartite projections * * This function calculates the number of vertices and edges in the * two projections of a bipartite network. This is useful if you have * a big bipartite network and you want to estimate the amount of * memory you would need to calculate the projections themselves. * * \param graph The input graph. * \param types Boolean vector giving the vertex types of the graph. * \param vcount1 Pointer to an \c igraph_integer_t, the number of * vertices in the first projection is stored here. * \param ecount1 Pointer to an \c igraph_integer_t, the number of * edges in the first projection is stored here. * \param vcount2 Pointer to an \c igraph_integer_t, the number of * vertices in the second projection is stored here. * \param ecount2 Pointer to an \c igraph_integer_t, the number of * edges in the second projection is stored here. * \return Error code. * * \sa \ref igraph_bipartite_projection() to calculate the actual * projection. * * Time complexity: O(|V|*d^2+|E|), |V| is the number of vertices, |E| * is the number of edges, d is the average (total) degree of the * graphs. * * \example examples/simple/igraph_bipartite_projection.c */ int igraph_bipartite_projection_size(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_integer_t *vcount1, igraph_integer_t *ecount1, igraph_integer_t *vcount2, igraph_integer_t *ecount2) { long int no_of_nodes=igraph_vcount(graph); long int vc1=0, ec1=0, vc2=0, ec2=0; igraph_adjlist_t adjlist; igraph_vector_long_t added; long int i; IGRAPH_CHECK(igraph_vector_long_init(&added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &added); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); for (i=0; i= no_of_nodes) { IGRAPH_ERROR("No such vertex to probe", IGRAPH_EINVAL); } if (probe1 >= 0 && !proj1) { IGRAPH_ERROR("`probe1' given, but `proj1' is a null pointer", IGRAPH_EINVAL); } if (probe1 >=0) { t1=VECTOR(*types)[(long int)probe1]; if (proj2) { t2=1-t1; } else { t2=-1; } } else { t1 = proj1 ? 0 : -1; t2 = proj2 ? 1 : -1; } IGRAPH_CHECK(igraph_i_bipartite_projection(graph, types, proj1, t1, multiplicity1)); IGRAPH_FINALLY(igraph_destroy, proj1); IGRAPH_CHECK(igraph_i_bipartite_projection(graph, types, proj2, t2, multiplicity2)); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_full_bipartite * Create a full bipartite network * * A bipartite network contains two kinds of vertices and connections * are only possible between two vertices of different kind. There are * many natural examples, e.g. movies and actors as vertices and a * movie is connected to all participating actors, etc. * * * igraph does not have direct support for bipartite networks, at * least not at the C language level. In other words the igraph_t * structure does not contain information about the vertex types. * The C functions for bipartite networks usually have an additional * input argument to graph, called \c types, a boolean vector giving * the vertex types. * * * Most functions creating bipartite networks are able to create this * extra vector, you just need to supply an initialized boolean vector * to them. * * \param graph Pointer to an igraph_t object, the graph will be * created here. * \param types Pointer to a boolean vector. If not a null pointer, * then the vertex types will be stored here. * \param n1 Integer, the number of vertices of the first kind. * \param n2 Integer, the number of vertices of the second kind. * \param directed Boolean, whether to create a directed graph. * \param mode A constant that gives the type of connections for * directed graphs. If \c IGRAPH_OUT, then edges point from vertices * of the first kind to vertices of the second kind; if \c * IGRAPH_IN, then the opposite direction is realized; if \c * IGRAPH_ALL, then mutual edges will be created. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. * * \sa \ref igraph_full() for non-bipartite full graphs. */ int igraph_full_bipartite(igraph_t *graph, igraph_vector_bool_t *types, igraph_integer_t n1, igraph_integer_t n2, igraph_bool_t directed, igraph_neimode_t mode) { igraph_integer_t nn1=n1, nn2=n2; igraph_integer_t no_of_nodes=nn1+nn2; igraph_vector_t edges; long int no_of_edges; long int ptr=0; long int i, j; if (!directed) { no_of_edges=nn1 * nn2; } else if (mode==IGRAPH_OUT || mode==IGRAPH_IN) { no_of_edges=nn1 * nn2; } else { /* mode==IGRAPH_ALL */ no_of_edges=nn1 * nn2 * 2; } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); if (!directed || mode==IGRAPH_OUT) { for (i=0; i= no_of_nodes) { IGRAPH_ERROR("Invalid (negative) vertex id", IGRAPH_EINVVID); } /* Check types vector */ if (no_of_nodes != 0) { igraph_vector_bool_minmax(types, &min_type, &max_type); if (min_type < 0 || max_type > 1) { IGRAPH_WARNING("Non-binary type vector when creating a bipartite graph"); } } /* Check bipartiteness */ for (i=0; i * Note that this function can operate in two modes, depending on the * \p multiple argument. If it is FALSE (i.e. 0), then a single edge is * created for every non-zero element in the incidence matrix. If \p * multiple is TRUE (i.e. 1), then the matrix elements are rounded up * to the closest non-negative integer to get the number of edges to * create between a pair of vertices. * * * This function does not create multiple edges if \p multiple is * FALSE, but might create some if it is TRUE. * * \param graph Pointer to an uninitialized graph object. * \param types Pointer to an initialized boolean vector, or a null * pointer. If not a null pointer, then the vertex types are stored * here. It is resized as needed. * \param incidence The incidence matrix. * \param directed Gives whether to create an undirected or a directed * graph. * \param mode Specifies the direction of the edges in a directed * graph. If \c IGRAPH_OUT, then edges point from vertices * of the first kind (corresponding to rows) to vertices of the * second kind (corresponding to columns); if \c * IGRAPH_IN, then the opposite direction is realized; if \c * IGRAPH_ALL, then mutual edges will be created. * \param multiple How to interpret the incidence matrix elements. See * details below. * \return Error code. * * Time complexity: O(n*m), the size of the incidence matrix. */ int igraph_incidence(igraph_t *graph, igraph_vector_bool_t *types, const igraph_matrix_t *incidence, igraph_bool_t directed, igraph_neimode_t mode, igraph_bool_t multiple) { igraph_integer_t n1=(igraph_integer_t) igraph_matrix_nrow(incidence); igraph_integer_t n2=(igraph_integer_t) igraph_matrix_ncol(incidence); igraph_integer_t no_of_nodes=n1+n2; igraph_vector_t edges; long int i, j, k; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); if (multiple) { for (i=0; i * This function simply checks whether a graph \emph{could} be * bipartite. It tries to find a mapping that gives a possible division * of the vertices into two classes, such that no two vertices of the * same class are connected by an edge. * * * The existence of such a mapping is equivalent of having no circuits of * odd length in the graph. A graph with loop edges cannot bipartite. * * * Note that the mapping is not necessarily unique, e.g. if the graph has * at least two components, then the vertices in the separate components * can be mapped independently. * * \param graph The input graph. * \param res Pointer to a boolean, the result is stored here. * \param type Pointer to an initialized boolean vector, or a null * pointer. If not a null pointer and a mapping was found, then it * is stored here. If not a null pointer, but no mapping was found, * the contents of this vector is invalid. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. */ int igraph_is_bipartite(const igraph_t *graph, igraph_bool_t *res, igraph_vector_bool_t *type) { /* We basically do a breadth first search and label the vertices along the way. We stop as soon as we can find a contradiction. In the 'seen' vector 0 means 'not seen yet', 1 means type 1, 2 means type 2. */ long int no_of_nodes=igraph_vcount(graph); igraph_vector_char_t seen; igraph_dqueue_t Q; igraph_vector_t neis; igraph_bool_t bi=1; long int i; IGRAPH_CHECK(igraph_vector_char_init(&seen, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_char_destroy, &seen); IGRAPH_DQUEUE_INIT_FINALLY(&Q, 100); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); for (i=0; bi && i 1.0) { IGRAPH_ERROR("Invalid connection probability", IGRAPH_EINVAL); } if (types) { IGRAPH_CHECK(igraph_vector_bool_resize(types, n1 + n2)); igraph_vector_bool_null(types); for (i=n1; i 0) { IGRAPH_ERROR("Invalid number (too large) of edges", IGRAPH_EINVAL); } IGRAPH_CHECK(retval=igraph_empty(graph, n1 + n2, directed)); } else { long int i; double maxedges; if (!directed || mode != IGRAPH_ALL) { maxedges = n1 * n2; } else { maxedges = 2 * n1 * n2; } if (m > maxedges) { IGRAPH_ERROR("Invalid number (too large) of edges", IGRAPH_EINVAL); } if (maxedges == m) { IGRAPH_CHECK(retval=igraph_full_bipartite(graph, types, n1, n2, directed, mode)); } else { long int to, from; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&s, 0); IGRAPH_CHECK(igraph_random_sample(&s, 0, maxedges-1, m)); IGRAPH_CHECK(igraph_vector_reserve(&edges, igraph_vector_size(&s)*2)); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LAPACK_INTERNAL_H #define LAPACK_INTERNAL_H /* Note: only files calling the LAPACK routines directly need to include this header. */ #include "igraph_types.h" #include "config.h" #ifndef INTERNAL_LAPACK #define igraphdgeevx_ dgeevx_ #define igraphdgeev_ dgeev_ #define igraphdgebak_ dgebak_ #define igraphxerbla_ xerbla_ #define igraphdgebal_ dgebal_ #define igraphdisnan_ disnan_ #define igraphdlaisnan_ dlaisnan_ #define igraphdgehrd_ dgehrd_ #define igraphdgehd2_ dgehd2_ #define igraphdlarf_ dlarf_ #define igraphiladlc_ iladlc_ #define igraphiladlr_ iladlr_ #define igraphdlarfg_ dlarfg_ #define igraphdlapy2_ dlapy2_ #define igraphdlahr2_ dlahr2_ #define igraphdlacpy_ dlacpy_ #define igraphdlarfb_ dlarfb_ #define igraphilaenv_ ilaenv_ #define igraphieeeck_ ieeeck_ #define igraphiparmq_ iparmq_ #define igraphdhseqr_ dhseqr_ #define igraphdlahqr_ dlahqr_ #define igraphdlabad_ dlabad_ #define igraphdlanv2_ dlanv2_ #define igraphdlaqr0_ dlaqr0_ #define igraphdlaqr3_ dlaqr3_ #define igraphdlaqr4_ dlaqr4_ #define igraphdlaqr2_ dlaqr2_ #define igraphdlaset_ dlaset_ #define igraphdormhr_ dormhr_ #define igraphdormqr_ dormqr_ #define igraphdlarft_ dlarft_ #define igraphdorm2r_ dorm2r_ #define igraphdtrexc_ dtrexc_ #define igraphdlaexc_ dlaexc_ #define igraphdlange_ dlange_ #define igraphdlassq_ dlassq_ #define igraphdlarfx_ dlarfx_ #define igraphdlartg_ dlartg_ #define igraphdlasy2_ dlasy2_ #define igraphdlaqr5_ dlaqr5_ #define igraphdlaqr1_ dlaqr1_ #define igraphdlascl_ dlascl_ #define igraphdorghr_ dorghr_ #define igraphdorgqr_ dorgqr_ #define igraphdorg2r_ dorg2r_ #define igraphdtrevc_ dtrevc_ #define igraphdlaln2_ dlaln2_ #define igraphdladiv_ dladiv_ #define igraphdsyevr_ dsyevr_ #define igraphdsyrk_ dsyrk_ #define igraphdlansy_ dlansy_ #define igraphdormtr_ dormtr_ #define igraphdormql_ dormql_ #define igraphdorm2l_ dorm2l_ #define igraphdstebz_ dstebz_ #define igraphdlaebz_ dlaebz_ #define igraphdstein_ dstein_ #define igraphdlagtf_ dlagtf_ #define igraphdlagts_ dlagts_ #define igraphdlarnv_ dlarnv_ #define igraphdlaruv_ dlaruv_ #define igraphdstemr_ dstemr_ #define igraphdlae2_ dlae2_ #define igraphdlaev2_ dlaev2_ #define igraphdlanst_ dlanst_ #define igraphdlarrc_ dlarrc_ #define igraphdlarre_ dlarre_ #define igraphdlarra_ dlarra_ #define igraphdlarrb_ dlarrb_ #define igraphdlaneg_ dlaneg_ #define igraphdlarrd_ dlarrd_ #define igraphdlarrk_ dlarrk_ #define igraphdlasq2_ dlasq2_ #define igraphdlasq3_ dlasq3_ #define igraphdlasq4_ dlasq4_ #define igraphdlasq5_ dlasq5_ #define igraphdlasq6_ dlasq6_ #define igraphdlasrt_ dlasrt_ #define igraphdlarrj_ dlarrj_ #define igraphdlarrr_ dlarrr_ #define igraphdlarrv_ dlarrv_ #define igraphdlar1v_ dlar1v_ #define igraphdlarrf_ dlarrf_ #define igraphdpotrf_ dpotrf_ #define igraphdsterf_ dsterf_ #define igraphdsytrd_ dsytrd_ #define igraphdlatrd_ dlatrd_ #define igraphdsytd2_ dsytd2_ #define igraphdlanhs_ dlanhs_ #define igraphdgeqr2_ dgeqr2_ #define igraphdtrsen_ dtrsen_ #define igraphdlacn2_ dlacn2_ #define igraphdtrsyl_ dtrsyl_ #define igraphdlasr_ dlasr_ #define igraphdsteqr_ dsteqr_ #define igraphdgesv_ dgesv_ #define igraphdgetrf_ dgetrf_ #define igraphdgetf2_ dgetf2_ #define igraphdlaswp_ dlaswp_ #define igraphdgetrs_ dgetrs_ #define igraphlen_trim_ len_trim_ #define igraph_dlamc1_ dlamc1_ #define igraph_dlamc2_ dlamc2_ #define igraph_dlamc3_ dlamc3_ #define igraph_dlamc4_ dlamc4_ #define igraph_dlamc5_ dlamc5_ #define igraphddot_ ddot_ #endif int igraphdgetrf_(int *m, int *n, igraph_real_t *a, int *lda, int *ipiv, int *info); int igraphdgetrs_(char *trans, int *n, int *nrhs, igraph_real_t *a, int *lda, int *ipiv, igraph_real_t *b, int *ldb, int *info); int igraphdgesv_(int *n, int *nrhs, igraph_real_t *a, int *lda, int *ipiv, igraph_real_t *b, int *ldb, int *info); igraph_real_t igraphdlapy2_(igraph_real_t *x, igraph_real_t *y); int igraphdsyevr_(char *jobz, char *range, char *uplo, int *n, igraph_real_t *a, int *lda, igraph_real_t *vl, igraph_real_t *vu, int * il, int *iu, igraph_real_t *abstol, int *m, igraph_real_t *w, igraph_real_t *z, int *ldz, int *isuppz, igraph_real_t *work, int *lwork, int *iwork, int *liwork, int *info); int igraphdgeev_(char *jobvl, char *jobvr, int *n, igraph_real_t *a, int *lda, igraph_real_t *wr, igraph_real_t *wi, igraph_real_t *vl, int *ldvl, igraph_real_t *vr, int *ldvr, igraph_real_t *work, int *lwork, int *info); int igraphdgeevx_(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, igraph_real_t *a, int *lda, igraph_real_t *wr, igraph_real_t *wi, igraph_real_t *vl, int *ldvl, igraph_real_t *vr, int *ldvr, int *ilo, int *ihi, igraph_real_t *scale, igraph_real_t *abnrm, igraph_real_t *rconde, igraph_real_t *rcondv, igraph_real_t *work, int *lwork, int *iwork, int *info); int igraphdgehrd_(int *n, int *ilo, int *ihi, igraph_real_t *A, int *lda, igraph_real_t *tau, igraph_real_t *work, int *lwork, int *info); igraph_real_t igraphddot_(int *n, igraph_real_t *dx, int *incx, igraph_real_t *dy, int *incy); #endif igraph/src/gengraph_graph_molloy_hash.h0000644000175100001440000001633313431000472020054 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef GRAPH_MOLLOY_HASH_H #define GRAPH_MOLLOY_HASH_H #include "gengraph_definitions.h" #include "gengraph_hash.h" #include "gengraph_degree_sequence.h" #include #include // This class handles graphs with a constant degree sequence. #define FINAL_HEURISTICS 0 #define GKAN_HEURISTICS 1 #define FAB_HEURISTICS 2 #define OPTIMAL_HEURISTICS 3 #define BRUTE_FORCE_HEURISTICS 4 namespace gengraph { //**************************** // class graph_molloy_hash //**************************** class graph_molloy_hash { private: // Number of vertices int n; //Number of arcs ( = #edges * 2 ) int a; //Total size of links[] int size; // The degree sequence of the graph int *deg; // The array containing all links int *links; // The array containing pointers to adjacency list of every vertices int **neigh; // Counts total size void compute_size(); // Build neigh with deg and links void compute_neigh(); // Allocate memory according to degree_sequence (for constructor use only!!) int alloc(degree_sequence &); // Add edge (a,b). Return FALSE if vertex a is already full. // WARNING : only to be used by havelhakimi(), restore() or constructors inline bool add_edge(int a,int b,int *realdeg) { int deg_a = realdeg[a]; if(deg_a == deg[a]) return false; // Check that edge was not already inserted assert(fast_search(neigh[a],int((a==n-1 ? links+size : neigh[a+1])-neigh[a]),b)==NULL); assert(fast_search(neigh[b],int((b==n-1 ? links+size : neigh[b+1])-neigh[b]),a)==NULL); assert(deg[a] dmax. void depth_isolated(int v, long &calls, int &left_to_explore, int dmax, int * &Kbuff, bool *visited); public: //degree of v inline int degree(const int v) { return deg[v]; }; // For debug purposes : verify validity of the graph (symetry, simplicity) bool verify(); // Destroy deg[], neigh[] and links[] ~graph_molloy_hash(); // Allocate memory for the graph. Create deg and links. No edge is created. graph_molloy_hash(degree_sequence &); // Create graph from hard copy graph_molloy_hash(int *); // Create hard copy of graph int *hard_copy(); // Restore from backup void restore(int* back); //Clear hash tables void init(); // nb arcs inline int nbarcs() { return a; }; // nb vertices inline int nbvertices() { return n; }; // print graph in SUCC_LIST mode, in stdout void print(FILE *f = stdout); int print(igraph_t *graph); // Test if graph is connected bool is_connected(); // is edge ? inline bool is_edge(int a, int b) { assert(H_is(neigh[a],deg[a],b) == (fast_search(neigh[a],HASH_SIZE(deg[a]),b)!=NULL)); assert(H_is(neigh[b],deg[b],a) == (fast_search(neigh[b],HASH_SIZE(deg[b]),a)!=NULL)); assert(H_is(neigh[a],deg[a],b) == H_is(neigh[b],deg[b],a)); if(deg[a] 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt The original copyright notice follows here */ /*************************************************************************** NetDataTypes.cpp - description ------------------- begin : Mon Oct 6 2003 copyright : (C) 2003 by Joerg Reichardt email : reichardt@mitte ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include "NetDataTypes.h" //################################################################################# //############################################################################### //Constructor NNode::NNode(unsigned long ind, unsigned long c_ind, DLList *ll, char* n, int states) { index=ind; cluster_index=c_ind; neighbours = new DLList(); n_links = new DLList(); global_link_list=ll; strcpy(name,n); color.red=0; color.green=0; color.blue=0; strcpy(color.pajek_c,"Green"); clustering=0.0; marker=0; affiliations=0; weight=0.0; affinity=0.0; distance=0; max_states=states; state_history=new unsigned long[states+1]; } //Destructor NNode::~NNode() { Disconnect_From_All(); delete neighbours; delete n_links; delete [] state_history; neighbours=NULL; n_links=NULL; state_history=NULL; } void NNode::Add_StateHistory(unsigned int state) { if (max_states>=state) { state_history[state]++; } } void NNode::Set_Color(RGBcolor c) { color.red=c.red; color.blue=c.blue; color.green=c.green; strcpy(color.pajek_c,c.pajek_c); } int NNode::Connect_To(NNode* neighbour, double weight) { NLink *link; //sollen doppelte Links erlaubt sein?? NEIN if (!neighbour) return 0; if (!(neighbours->Is_In_List(neighbour)) && (neighbour!=this)) { neighbours->Push(neighbour); // nachbar hier eintragen neighbour->neighbours->Push(this); // diesen knoten beim nachbarn eintragen link=new NLink(this,neighbour, weight); //link erzeugen global_link_list->Push(link); // in globaler liste eintragen n_links->Push(link); // bei diesem Knoten eintragen neighbour->n_links->Push(link); // beim nachbarn eintragen return(1); } return(0); } NLink *NNode::Get_LinkToNeighbour(NNode* neighbour) { DLList_Iter iter; NLink *l_cur, *link=0; bool found=false; // finde einen bestimmten Link aus der Liste der links eines Knotens l_cur=iter.First(n_links); while (!iter.End() && !found) { if (((l_cur->Get_Start()==this) && (l_cur->Get_End()==neighbour)) || ((l_cur->Get_End()==this) && (l_cur->Get_Start()==neighbour))) { found=true; link=l_cur; } l_cur=iter.Next(); } if (found) return link; else return NULL; } int NNode::Disconnect_From(NNode* neighbour) { //sollen doppelte Links erlaubt sein?? s.o. if (!neighbours) return 0; neighbours->fDelete(neighbour); n_links->fDelete(Get_LinkToNeighbour(neighbour)); neighbour->n_links->fDelete(neighbour->Get_LinkToNeighbour(this)); neighbour->neighbours->fDelete(this); return 1; } int NNode::Disconnect_From_All() { int number_of_neighbours=0; while (neighbours->Size()) { Disconnect_From(neighbours->Pop()); number_of_neighbours++; } return(number_of_neighbours) ; } /* int NNode::Disconnect_From_All_Grandchildren() { int n_l=links->Size(); unsigned long pos=0; while ((n_l--)>1) { //alle bis auf das erste loeschen pos=(links->Get(n_l+1))->links->Is_In_List(this); // printf("%d %d\n",n_l,pos); (links->Get(n_l+1))->links->Delete(pos); } return(pos) ; } */ double NNode::Get_Links_Among_Neigbours(void) { // long neighbours1, neighbours2; double lam=0; DLList_Iter iter1, iter2; // neighbours1=neighbours->Size(); //so viele Nachbarn hat die Betrachtete Node NNode *step1,*step2; step1=iter1.First(neighbours); while (!iter1.End()) // for (int n1=1;n1<=neighbours1; n1++) { //step1=neighbours->Get(n1); //neighbours2=step1->neighbours->Size(); //so viele Nachbarn hat der n1-ste Nachbar step2=iter2.First(step1->Get_Neighbours()); while (!iter2.End()) //for (int n2=1;n2<=neighbours2; n2++) { //step2=step1->neighbours->Get(n2); if (step2->Get_Neighbours()->Is_In_List(this)) {lam++;} step2=iter2.Next(); } step1=iter1.Next(); } return(lam/2.0); } double NNode::Get_Clustering() { double c; unsigned long k; k=neighbours->Size(); if (k<=1) return(0); c=2.0*Get_Links_Among_Neigbours()/double(k*k-k); return(c); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++ //Constructor NLink::NLink(NNode *s, NNode *e, double w) { start=s; end=e; weight=w; old_weight=0; marker=0; } //Destructor NLink::~NLink() { if (start && end) start->Disconnect_From(end); } igraph/src/gengraph_definitions.h0000644000175100001440000001074513431000472016671 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DEFINITIONS_H #define DEFINITIONS_H #ifndef _MSC_VER #ifndef register #define register #endif #endif #include #include #include namespace gengraph { // Max line size in files #define FBUFF_SIZE 1000000 // disable lousy VC++ warnings #ifdef _ATL_VER_ #pragma warning(disable : 4127) #endif //_ATL_VER_ // Verbose #define VERBOSE_NONE 0 #define VERBOSE_SOME 1 #define VERBOSE_LOTS 2 int VERBOSE(); void SET_VERBOSE(int v); // Random number generator void my_srandom(int); int my_random(); int my_binomial(double pp, int n); double my_random01(); // (0,1] #define MY_RAND_MAX 0x7FFFFFFF // IPv4 address direct translation into 32-bit uint + special IP defs typedef unsigned int ip_addr; #define IP_NONE 0x7FFFFFFF #define IP_STAR 0x00000000 #define IP_MYSELF 0x7F000001 // Compatibility #ifdef _WIN32 #define strcasecmp _stricmp #endif //inline double round(double x) throw () { return (floor(0.5+x)); } // No assert #ifndef _DEBUG #ifndef NDEBUG #define NDEBUG #endif //NDEBUG #endif //_DEBUG // Min & Max #ifndef min #define defmin(type) inline type min(type a, type b) { return ab ? a : b; } defmax(int) defmax(double) defmax(unsigned long) #endif //max // Traceroute Sampling #define MODE_USP 0 #define MODE_ASP 1 #define MODE_RSP 2 // Debug definitions //#define PERFORMANCE_MONITOR //#define OPT_ISOLATED // Max Int #ifndef MAX_INT #define MAX_INT 0x7FFFFFFF #endif //MAX_INT //Edge type typedef struct { int from; int to; } edge; // Tag Int #define TAG_INT 0x40000000 // Oldies .... #define S_VECTOR_RAW //********************* // Routine definitions //********************* /* log(1+x) inline double logp(double x) { if(fabs(x)<1e-6) return x+0.5*x*x+0.333333333333333*x*x*x; else return log(1.0+x); } //*/ //Fast search or replace inline int* fast_rpl(int *m, const int a, const int b) { while(*m!=a) m++; *m = b; return m; } inline int* fast_search(int *m, const int size, const int a) { int *p = m+size; while(m != p--) if(*p == a) return p; return NULL; } // Lovely percentage print // inline void print_percent(double yo, FILE *f = stderr) { // int arf = int(100.0*yo); // if(double(arf)>100.0*yo) arf--; // if(arf<100) fprintf(f," "); // if(arf<10) fprintf(f," "); // fprintf(f,"%d.%d%%",arf,int(1000.0*yo-double(10*arf))); // } // Skips non-numerical chars, then numerical chars, then non-numerical chars. inline char skip_int(char* &c) { while(*c<'0' || *c>'9') c++; while(*c>='0' && *c<='9') c++; while(*c!=0 && (*c<'0' || *c>'9')) c++; return *c; } // distance+1 modulo 255 for breadth-first search inline unsigned char next_dist(const unsigned char c) { return c==255 ? 1 : c+1; } inline unsigned char prev_dist(const unsigned char c) { return c==1 ? 255 : c-1; } // 1/(RANDMAX+1) #define inv_RANDMAX (1.0/(1.0+double(MY_RAND_MAX))) // random number in ]0,1[, _very_ accurate around 0 inline double random_float() { int r=my_random(); double mul=inv_RANDMAX; while(r<=0x7FFFFF) { r<<=8; r+=(my_random()&0xFF); mul*=(1.0/256.0); } return double(r)*mul; } // Return true with probability p. Very accurate when p is small. #define test_proba(p) (random_float()<(p)) // Random bit generator, sparwise. static int _random_bits_stored = 0; static int _random_bits = 0; inline int random_bit() { register int a = _random_bits; _random_bits = a >> 1; if(_random_bits_stored--) return a&0x1; a = my_random(); _random_bits = a >> 1; _random_bits_stored = 30; return a&0x1; } // Hash Profiling (see hash.h) void _hash_prof(); } // namespace gengraph #endif //DEFINITIONS_H igraph/src/lapack.c0000644000175100001440000007771413431000472013742 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_lapack.h" #include "igraph_lapack_internal.h" /** * \function igraph_lapack_dgetrf * LU factorization of a general M-by-N matrix * * The factorization has the form * A = P * L * U * where P is a permutation matrix, L is lower triangular with unit * diagonal elements (lower trapezoidal if m > n), and U is upper * triangular (upper trapezoidal if m < n). * \param a The input/output matrix. On entry, the M-by-N matrix to be * factored. On exit, the factors L and U from the factorization * A = P * L * U; the unit diagonal elements of L are not * stored. * \param ipiv An integer vector, the pivot indices are stored here, * unless it is a null pointer. Row i of the matrix was * interchanged with row ipiv[i]. * \param info LAPACK error code. Zero on successful exit. If positive * and i, then U(i,i) is exactly zero. The factorization has been * completed, but the factor U is exactly singular, and division * by zero will occur if it is used to solve a system of * equations. If LAPACK returns an error, i.e. a negative info * value, then an igraph error is generated as well. * \return Error code. * * Time complexity: TODO. */ int igraph_lapack_dgetrf(igraph_matrix_t *a, igraph_vector_int_t *ipiv, int *info) { int m=(int) igraph_matrix_nrow(a); int n=(int) igraph_matrix_ncol(a); int lda=m > 0 ? m : 1; igraph_vector_int_t *myipiv=ipiv, vipiv; if (!ipiv) { IGRAPH_CHECK(igraph_vector_int_init(&vipiv, mdata), &lda, VECTOR(*myipiv), info); if (*info > 0) { IGRAPH_WARNING("LU: factor is exactly singular"); } else if (*info < 0) { switch(*info) { case -1: IGRAPH_ERROR("Invalid number of rows", IGRAPH_ELAPACK); break; case -2: IGRAPH_ERROR("Invalid number of columns", IGRAPH_ELAPACK); break; case -3: IGRAPH_ERROR("Invalid input matrix", IGRAPH_ELAPACK); break; case -4: IGRAPH_ERROR("Invalid LDA parameter", IGRAPH_ELAPACK); break; case -5: IGRAPH_ERROR("Invalid pivot vector", IGRAPH_ELAPACK); break; case -6: IGRAPH_ERROR("Invalid info argument", IGRAPH_ELAPACK); break; default: IGRAPH_ERROR("Unknown LAPACK error", IGRAPH_ELAPACK); break; } } if (!ipiv) { igraph_vector_int_destroy(&vipiv); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_lapack_dgetrs * Solve general system of linear equations using LU factorization * * This function calls LAPACK to solve a system of linear equations * A * X = B or A' * X = B * with a general N-by-N matrix A using the LU factorization * computed by \ref igraph_lapack_dgetrf. * \param transpose Logical scalar, whether to transpose the input * matrix. * \param a A matrix containing the L and U factors from the * factorization A = P*L*U. * \param ipiv An integer vector, the pivot indices from \ref * igraph_lapack_dgetrf must be given here. * \param b The right hand side matrix must be given here. * \return Error code. * * Time complexity: TODO. */ int igraph_lapack_dgetrs(igraph_bool_t transpose, const igraph_matrix_t *a, igraph_vector_int_t *ipiv, igraph_matrix_t *b) { char trans = transpose ? 'T' : 'N'; int n=(int) igraph_matrix_nrow(a); int nrhs=(int) igraph_matrix_ncol(b); int lda= n > 0 ? n : 1; int ldb= n > 0 ? n : 1; int info; if (n != igraph_matrix_ncol(a)) { IGRAPH_ERROR("Cannot LU solve matrix", IGRAPH_NONSQUARE); } if (n != igraph_matrix_nrow(b)) { IGRAPH_ERROR("Cannot LU solve matrix, RHS of wrong size", IGRAPH_EINVAL); } igraphdgetrs_(&trans, &n, &nrhs, VECTOR(a->data), &lda, VECTOR(*ipiv), VECTOR(b->data), &ldb, &info); if (info < 0) { switch(info) { case -1: IGRAPH_ERROR("Invalid transpose argument", IGRAPH_ELAPACK); break; case -2: IGRAPH_ERROR("Invalid number of rows/columns", IGRAPH_ELAPACK); break; case -3: IGRAPH_ERROR("Invalid number of RHS vectors", IGRAPH_ELAPACK); break; case -4: IGRAPH_ERROR("Invalid LU matrix", IGRAPH_ELAPACK); break; case -5: IGRAPH_ERROR("Invalid LDA parameter", IGRAPH_ELAPACK); break; case -6: IGRAPH_ERROR("Invalid pivot vector", IGRAPH_ELAPACK); break; case -7: IGRAPH_ERROR("Invalid RHS matrix", IGRAPH_ELAPACK); break; case -8: IGRAPH_ERROR("Invalid LDB parameter", IGRAPH_ELAPACK); break; case -9: IGRAPH_ERROR("Invalid info argument", IGRAPH_ELAPACK); break; default: IGRAPH_ERROR("Unknown LAPACK error", IGRAPH_ELAPACK); break; } } return 0; } /** * \function igraph_lapack_dgesv * Solve system of linear equations with LU factorization * * This function computes the solution to a real system of linear * equations A * X = B, where A is an N-by-N matrix and X and B are * N-by-NRHS matrices. * * The LU decomposition with partial pivoting and row * interchanges is used to factor A as * A = P * L * U, * where P is a permutation matrix, L is unit lower triangular, and U is * upper triangular. The factored form of A is then used to solve the * system of equations A * X = B. * \param a Matrix. On entry the N-by-N coefficient matrix, on exit, * the factors L and U from the factorization A=P*L*U; the unit * diagonal elements of L are not stored. * \param ipiv An integer vector or a null pointer. If not a null * pointer, then the pivot indices that define the permutation * matrix P, are stored here. Row i of the matrix was * interchanged with row IPIV(i). * \param b Matrix, on entry the right hand side matrix should be * stored here. On exit, if there was no error, and the info * argument is zero, then it contains the solution matrix X. * \param info The LAPACK info code. If it is positive, then * U(info,info) is exactly zero. In this case the factorization * has been completed, but the factor U is exactly * singular, so the solution could not be computed. * \return Error code. * * Time complexity: TODO. * * \example examples/simple/igraph_lapack_dgesv.c */ int igraph_lapack_dgesv(igraph_matrix_t *a, igraph_vector_int_t *ipiv, igraph_matrix_t *b, int *info) { int n=(int) igraph_matrix_nrow(a); int nrhs=(int) igraph_matrix_ncol(b); int lda= n > 0 ? n : 1; int ldb= n > 0 ? n : 1; igraph_vector_int_t *myipiv=ipiv, vipiv; if (n != igraph_matrix_ncol(a)) { IGRAPH_ERROR("Cannot LU solve matrix", IGRAPH_NONSQUARE); } if (n != igraph_matrix_nrow(b)) { IGRAPH_ERROR("Cannot LU solve matrix, RHS of wrong size", IGRAPH_EINVAL); } if (!ipiv) { IGRAPH_CHECK(igraph_vector_int_init(&vipiv, n)); IGRAPH_FINALLY(igraph_vector_int_destroy, &vipiv); myipiv=&vipiv; } igraphdgesv_(&n, &nrhs, VECTOR(a->data), &lda, VECTOR(*myipiv), VECTOR(b->data), &ldb, info); if (*info > 0) { IGRAPH_WARNING("LU: factor is exactly singular"); } else if (*info < 0) { switch(*info) { case -1: IGRAPH_ERROR("Invalid number of rows/column", IGRAPH_ELAPACK); break; case -2: IGRAPH_ERROR("Invalid number of RHS vectors", IGRAPH_ELAPACK); break; case -3: IGRAPH_ERROR("Invalid input matrix", IGRAPH_ELAPACK); break; case -4: IGRAPH_ERROR("Invalid LDA parameter", IGRAPH_ELAPACK); break; case -5: IGRAPH_ERROR("Invalid pivot vector", IGRAPH_ELAPACK); break; case -6: IGRAPH_ERROR("Invalid RHS matrix", IGRAPH_ELAPACK); break; case -7: IGRAPH_ERROR("Invalid LDB parameter", IGRAPH_ELAPACK); break; case -8: IGRAPH_ERROR("Invalid info argument", IGRAPH_ELAPACK); break; default: IGRAPH_ERROR("Unknown LAPACK error", IGRAPH_ELAPACK); break; } } if (!ipiv) { igraph_vector_int_destroy(&vipiv); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_lapack_dsyevr * Selected eigenvalues and optionally eigenvectors of a symmetric matrix * * Calls the DSYEVR LAPACK function to compute selected eigenvalues * and, optionally, eigenvectors of a real symmetric matrix A. * Eigenvalues and eigenvectors can be selected by specifying either * a range of values or a range of indices for the desired eigenvalues. * * See more in the LAPACK documentation. * \param A Matrix, on entry it contains the symmetric input * matrix. Only the leading N-by-N upper triangular part is * used for the computation. * \param which Constant that gives which eigenvalues (and possibly * the corresponding eigenvectors) to calculate. Possible * values are \c IGRAPH_LAPACK_DSYEV_ALL, all eigenvalues; * \c IGRAPH_LAPACK_DSYEV_INTERVAL, all eigenvalues in the * half-open interval (vl,vu]; * \c IGRAPH_LAPACK_DSYEV_SELECT, the il-th through iu-th * eigenvalues. * \param vl If \p which is \c IGRAPH_LAPACK_DSYEV_INTERVAL, then * this is the lower bound of the interval to be searched for * eigenvalues. See also the \p vestimate argument. * \param vu If \p which is \c IGRAPH_LAPACK_DSYEV_INTERVAL, then * this is the upper bound of the interval to be searched for * eigenvalues. See also the \p vestimate argument. * \param vestimate An upper bound for the number of eigenvalues in * the (vl,vu] interval, if \p which is \c * IGRAPH_LAPACK_DSYEV_INTERVAL. Memory is allocated only for * the given number of eigenvalues (and eigenvectors), so this * upper bound must be correct. * \param il The index of the smallest eigenvalue to return, if \p * which is \c IGRAPH_LAPACK_DSYEV_SELECT. * \param iu The index of the largets eigenvalue to return, if \p * which is \c IGRAPH_LAPACK_DSYEV_SELECT. * \param abstol The absolute error tolerance for the eigevalues. An * approximate eigenvalue is accepted as converged when it is * determined to lie in an interval [a,b] of width less than or * equal to abstol + EPS * max(|a|,|b|), where EPS is the * machine precision. * \param values An initialized vector, the eigenvalues are stored * here, unless it is a null pointer. It will be resized as * needed. * \param vectors An initialized matrix, the eigenvectors are stored * in its columns, unless it is a null pointer. It will be * resized as needed. * \param support An integer vector. If not a null pointer, then it * will be resized to (2*max(1,M)) (M is a the total number of * eigenvalues found). Then the support of the eigenvectors in * \p vectors is stored here, i.e., the indices * indicating the nonzero elements in \p vectors. * The i-th eigenvector is nonzero only in elements * support(2*i-1) through support(2*i). * \return Error code. * * Time complexity: TODO. * * \example examples/simple/igraph_lapack_dsyevr.c */ int igraph_lapack_dsyevr(const igraph_matrix_t *A, igraph_lapack_dsyev_which_t which, igraph_real_t vl, igraph_real_t vu, int vestimate, int il, int iu, igraph_real_t abstol, igraph_vector_t *values, igraph_matrix_t *vectors, igraph_vector_int_t *support) { igraph_matrix_t Acopy; char jobz = vectors ? 'V' : 'N', range, uplo='U'; int n=(int) igraph_matrix_nrow(A), lda=n, ldz=n; int m, info; igraph_vector_t *myvalues=values, vvalues; igraph_vector_int_t *mysupport=support, vsupport; igraph_vector_t work; igraph_vector_int_t iwork; int lwork=-1, liwork=-1; if (n != igraph_matrix_ncol(A)) { IGRAPH_ERROR("Cannot find eigenvalues/vectors", IGRAPH_NONSQUARE); } if (which==IGRAPH_LAPACK_DSYEV_INTERVAL && (vestimate < 1 || vestimate > n)) { IGRAPH_ERROR("Estimated (upper bound) number of eigenvalues must be " "between 1 and n", IGRAPH_EINVAL); } if (which==IGRAPH_LAPACK_DSYEV_SELECT && iu-il < 0) { IGRAPH_ERROR("Invalid 'il' and/or 'iu' values", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_copy(&Acopy, A)); IGRAPH_FINALLY(igraph_matrix_destroy, &Acopy); IGRAPH_VECTOR_INIT_FINALLY(&work, 1); IGRAPH_CHECK(igraph_vector_int_init(&iwork, 1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &iwork); if (!values) { IGRAPH_VECTOR_INIT_FINALLY(&vvalues, 0); myvalues=&vvalues; } if (!support) { IGRAPH_CHECK(igraph_vector_int_init(&vsupport, 0)); IGRAPH_FINALLY(igraph_vector_int_destroy, &vsupport); mysupport=&vsupport; } switch (which) { case IGRAPH_LAPACK_DSYEV_ALL: range = 'A'; IGRAPH_CHECK(igraph_vector_resize(myvalues, n)); IGRAPH_CHECK(igraph_vector_int_resize(mysupport, 2*n)); if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, n)); } break; case IGRAPH_LAPACK_DSYEV_INTERVAL: range = 'V'; IGRAPH_CHECK(igraph_vector_resize(myvalues, vestimate)); IGRAPH_CHECK(igraph_vector_int_resize(mysupport, 2*vestimate)); if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors,n, vestimate)); } break; case IGRAPH_LAPACK_DSYEV_SELECT: range = 'I'; IGRAPH_CHECK(igraph_vector_resize(myvalues, iu-il+1)); IGRAPH_CHECK(igraph_vector_int_resize(mysupport, 2*(iu-il+1))); if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, iu-il+1)); } break; } igraphdsyevr_(&jobz, &range, &uplo, &n, &MATRIX(Acopy,0,0), &lda, &vl, &vu, &il, &iu, &abstol, &m, VECTOR(*myvalues), vectors ? &MATRIX(*vectors,0,0) : 0, &ldz, VECTOR(*mysupport), VECTOR(work), &lwork, VECTOR(iwork), &liwork, &info); lwork=(int) VECTOR(work)[0]; liwork=VECTOR(iwork)[0]; IGRAPH_CHECK(igraph_vector_resize(&work, lwork)); IGRAPH_CHECK(igraph_vector_int_resize(&iwork, liwork)); igraphdsyevr_(&jobz, &range, &uplo, &n, &MATRIX(Acopy,0,0), &lda, &vl, &vu, &il, &iu, &abstol, &m, VECTOR(*myvalues), vectors ? &MATRIX(*vectors,0,0) : 0, &ldz, VECTOR(*mysupport), VECTOR(work), &lwork, VECTOR(iwork), &liwork, &info); if (values) { IGRAPH_CHECK(igraph_vector_resize(values, m)); } if (vectors) { IGRAPH_CHECK(igraph_matrix_resize(vectors, n, m)); } if (support) { IGRAPH_CHECK(igraph_vector_int_resize(support, m)); } if (!support) { igraph_vector_int_destroy(&vsupport); IGRAPH_FINALLY_CLEAN(1); } if (!values) { igraph_vector_destroy(&vvalues); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_int_destroy(&iwork); igraph_vector_destroy(&work); igraph_matrix_destroy(&Acopy); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \function igraph_lapack_dgeev * Eigenvalues and optionally eigenvectors of a non-symmetric matrix * * This function calls LAPACK to compute, for an N-by-N real * nonsymmetric matrix A, the eigenvalues and, optionally, the left * and/or right eigenvectors. * * * The right eigenvector v(j) of A satisfies * A * v(j) = lambda(j) * v(j) * where lambda(j) is its eigenvalue. * The left eigenvector u(j) of A satisfies * u(j)**H * A = lambda(j) * u(j)**H * where u(j)**H denotes the conjugate transpose of u(j). * * * The computed eigenvectors are normalized to have Euclidean norm * equal to 1 and largest component real. * * \param A matrix. On entry it contains the N-by-N input matrix. * \param valuesreal Pointer to an initialized vector, or a null * pointer. If not a null pointer, then the real parts of the * eigenvalues are stored here. The vector will be resized as * needed. * \param valuesimag Pointer to an initialized vector, or a null * pointer. If not a null pointer, then the imaginary parts of * the eigenvalues are stored here. The vector will be resized * as needed. * \param vectorsleft Pointer to an initialized matrix, or a null * pointer. If not a null pointer, then the left eigenvectors * are stored in the columns of the matrix. The matrix will be * resized as needed. * \param vectorsright Pointer to an initialized matrix, or a null * pointer. If not a null pointer, then the right eigenvectors * are stored in the columns of the matrix. The matrix will be * resized as needed. * \param info This argument is used for two purposes. As an input * argument it gives whether an igraph error should be * generated if the QR algorithm fails to compute all * eigenvalues. If \p info is non-zero, then an error is * generated, otherwise only a warning is given. * On exit it contains the LAPACK error code. * Zero means successful exit. * A negative values means that some of the arguments had an * illegal value, this always triggers an igraph error. An i * positive value means that the QR algorithm failed to * compute all the eigenvalues, and no eigenvectors have been * computed; element i+1:N of \p valuesreal and \p valuesimag * contain eigenvalues which have converged. This case only * generates an igraph error, if \p info was non-zero on entry. * \return Error code. * * Time complexity: TODO. * * \example examples/simple/igraph_lapack_dgeev.c */ int igraph_lapack_dgeev(const igraph_matrix_t *A, igraph_vector_t *valuesreal, igraph_vector_t *valuesimag, igraph_matrix_t *vectorsleft, igraph_matrix_t *vectorsright, int *info) { char jobvl= vectorsleft ? 'V' : 'N'; char jobvr= vectorsright ? 'V' : 'N'; int n=(int) igraph_matrix_nrow(A); int lda=n, ldvl=n, ldvr=n, lwork=-1; igraph_vector_t work; igraph_vector_t *myreal=valuesreal, *myimag=valuesimag, vreal, vimag; igraph_matrix_t Acopy; int error=*info; if (igraph_matrix_ncol(A) != n) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeev)", IGRAPH_NONSQUARE); } IGRAPH_CHECK(igraph_matrix_copy(&Acopy, A)); IGRAPH_FINALLY(igraph_matrix_destroy, &Acopy); IGRAPH_VECTOR_INIT_FINALLY(&work, 1); if (!valuesreal) { IGRAPH_VECTOR_INIT_FINALLY(&vreal, n); myreal=&vreal; } else { IGRAPH_CHECK(igraph_vector_resize(myreal, n)); } if (!valuesimag) { IGRAPH_VECTOR_INIT_FINALLY(&vimag, n); myimag=&vimag; } else { IGRAPH_CHECK(igraph_vector_resize(myimag, n)); } if (vectorsleft) { IGRAPH_CHECK(igraph_matrix_resize(vectorsleft, n, n)); } if (vectorsright) { IGRAPH_CHECK(igraph_matrix_resize(vectorsright, n, n)); } igraphdgeev_(&jobvl, &jobvr, &n, &MATRIX(Acopy,0,0), &lda, VECTOR(*myreal), VECTOR(*myimag), vectorsleft ? &MATRIX(*vectorsleft ,0,0) : 0, &ldvl, vectorsright ? &MATRIX(*vectorsright,0,0) : 0, &ldvr, VECTOR(work), &lwork, info); lwork=(int) VECTOR(work)[0]; IGRAPH_CHECK(igraph_vector_resize(&work, lwork)); igraphdgeev_(&jobvl, &jobvr, &n, &MATRIX(Acopy,0,0), &lda, VECTOR(*myreal), VECTOR(*myimag), vectorsleft ? &MATRIX(*vectorsleft ,0,0) : 0, &ldvl, vectorsright ? &MATRIX(*vectorsright,0,0) : 0, &ldvr, VECTOR(work), &lwork, info); if (*info < 0) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeev)", IGRAPH_ELAPACK); } else if (*info > 0) { if (error) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeev)", IGRAPH_ELAPACK); } else { IGRAPH_WARNING("Cannot calculate eigenvalues (dgeev)"); } } if (!valuesimag) { igraph_vector_destroy(&vimag); IGRAPH_FINALLY_CLEAN(1); } if (!valuesreal) { igraph_vector_destroy(&vreal); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&work); igraph_matrix_destroy(&Acopy); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_lapack_dgeevx * Eigenvalues/vectors of nonsymmetric matrices, expert mode * * This function calculates the eigenvalues and optionally the left * and/or right eigenvectors of a nonsymmetric N-by-N real matrix. * * * Optionally also, it computes a balancing transformation to improve * the conditioning of the eigenvalues and eigenvectors (\p ilo, \pihi, * \p scale, and \p abnrm), reciprocal condition numbers for the * eigenvalues (\p rconde), and reciprocal condition numbers for the * right eigenvectors (\p rcondv). * * * The right eigenvector v(j) of A satisfies * A * v(j) = lambda(j) * v(j) * where lambda(j) is its eigenvalue. * The left eigenvector u(j) of A satisfies * u(j)**H * A = lambda(j) * u(j)**H * where u(j)**H denotes the conjugate transpose of u(j). * * * The computed eigenvectors are normalized to have Euclidean norm * equal to 1 and largest component real. * * * Balancing a matrix means permuting the rows and columns to make it * more nearly upper triangular, and applying a diagonal similarity * transformation D * A * D**(-1), where D is a diagonal matrix, to * make its rows and columns closer in norm and the condition numbers * of its eigenvalues and eigenvectors smaller. The computed * reciprocal condition numbers correspond to the balanced matrix. * Permuting rows and columns will not change the condition numbers * (in exact arithmetic) but diagonal scaling will. For further * explanation of balancing, see section 4.10.2 of the LAPACK * Users' Guide. * * \param balance Scalar that indicated, whether the input matrix * should be balanced. Possible values: * \clist * \cli IGRAPH_LAPACK_DGEEVX_BALANCE_NONE * no not diagonally scale or permute. * \cli IGRAPH_LAPACK_DGEEVX_BALANCE_PERM * perform permutations to make the matrix more nearly upper * triangular. Do not diagonally scale. * \cli IGRAPH_LAPACK_DGEEVX_BALANCE_SCALE * diagonally scale the matrix, i.e. replace A by * D*A*D**(-1), where D is a diagonal matrix, chosen to make * the rows and columns of A more equal in norm. Do not * permute. * \cli IGRAPH_LAPACK_DGEEVX_BALANCE_BOTH * both diagonally scale and permute A. * \endclist * \param A The input matrix, must be square. * \param valuesreal An initialized vector, or a NULL pointer. If not * a NULL pointer, then the real parts of the eigenvalues are stored * here. The vector will be resized, as needed. * \param valuesimag An initialized vector, or a NULL pointer. If not * a NULL pointer, then the imaginary parts of the eigenvalues are stored * here. The vector will be resized, as needed. * \param vectorsleft An initialized matrix or a NULL pointer. If not * a null pointer, then the left eigenvectors are stored here. The * order corresponds to the eigenvalues and the eigenvectors are * stored in a compressed form. If the j-th eigenvalue is real then * column j contains the corresponding eigenvector. If the j-th and * (j+1)-th eigenvalues form a complex conjugate pair, then the j-th * and (j+1)-th columns contain their corresponding eigenvectors. * \param vectorsright An initialized matrix or a NULL pointer. If not * a null pointer, then the right eigenvectors are stored here. The * format is the same, as for the \p vectorsleft argument. * \param ilo * \param ihi \p ilo and \p ihi are integer values determined when A was * balanced. The balanced A(i,j) = 0 if I>J and * J=1,...,ilo-1 or I=ihi+1,...,N. * \param scale Pointer to an initialized vector or a NULL pointer. If * not a NULL pointer, then details of the permutations and scaling * factors applied when balancing \param A, are stored here. * If P(j) is the index of the row and column * interchanged with row and column j, and D(j) is the scaling * factor applied to row and column j, then * \clist * \cli scale(J) = P(J), for J = 1,...,ilo-1 * \cli scale(J) = D(J), for J = ilo,...,ihi * \cli scale(J) = P(J) for J = ihi+1,...,N. * \endclist * The order in which the interchanges are made is N to \p ihi+1, * then 1 to \p ilo-1. * \param abnrm Pointer to a real variable, the one-norm of the * balanced matrix is stored here. (The one-norm is the maximum of * the sum of absolute values of elements in any column.) * \param rconde An initialized vector or a NULL pointer. If not a * null pointer, then the reciprocal condition numbers of the * eigenvalues are stored here. * \param rcondv An initialized vector or a NULL pointer. If not a * null pointer, then the reciprocal condition numbers of the right * eigenvectors are stored here. * \param info This argument is used for two purposes. As an input * argument it gives whether an igraph error should be * generated if the QR algorithm fails to compute all * eigenvalues. If \p info is non-zero, then an error is * generated, otherwise only a warning is given. * On exit it contains the LAPACK error code. * Zero means successful exit. * A negative values means that some of the arguments had an * illegal value, this always triggers an igraph error. An i * positive value means that the QR algorithm failed to * compute all the eigenvalues, and no eigenvectors have been * computed; element i+1:N of \p valuesreal and \p valuesimag * contain eigenvalues which have converged. This case only * generated an igraph error, if \p info was non-zero on entry. * \return Error code. * * Time complexity: TODO * * \example examples/simple/igraph_lapack_dgeevx.c */ int igraph_lapack_dgeevx(igraph_lapack_dgeevx_balance_t balance, const igraph_matrix_t *A, igraph_vector_t *valuesreal, igraph_vector_t *valuesimag, igraph_matrix_t *vectorsleft, igraph_matrix_t *vectorsright, int *ilo, int *ihi, igraph_vector_t *scale, igraph_real_t *abnrm, igraph_vector_t *rconde, igraph_vector_t *rcondv, int *info) { char balanc; char jobvl= vectorsleft ? 'V' : 'N'; char jobvr= vectorsright ? 'V' : 'N'; char sense; int n=(int) igraph_matrix_nrow(A); int lda=n, ldvl=n, ldvr=n, lwork=-1; igraph_vector_t work; igraph_vector_int_t iwork; igraph_matrix_t Acopy; int error=*info; igraph_vector_t *myreal=valuesreal, *myimag=valuesimag, vreal, vimag; igraph_vector_t *myscale=scale, vscale; if (igraph_matrix_ncol(A) != n) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeevx)", IGRAPH_NONSQUARE); } switch (balance) { case IGRAPH_LAPACK_DGEEVX_BALANCE_NONE: balanc='N'; break; case IGRAPH_LAPACK_DGEEVX_BALANCE_PERM: balanc='P'; break; case IGRAPH_LAPACK_DGEEVX_BALANCE_SCALE: balanc='S'; break; case IGRAPH_LAPACK_DGEEVX_BALANCE_BOTH: balanc='B'; break; default: IGRAPH_ERROR("Invalid 'balance' argument", IGRAPH_EINVAL); break; } if (!rconde && !rcondv) { sense='N'; } else if (rconde && !rcondv) { sense='E'; } else if (!rconde && rcondv) { sense='V'; } else { sense='B'; } IGRAPH_CHECK(igraph_matrix_copy(&Acopy, A)); IGRAPH_FINALLY(igraph_matrix_destroy, &Acopy); IGRAPH_VECTOR_INIT_FINALLY(&work, 1); IGRAPH_CHECK(igraph_vector_int_init(&iwork, n)); IGRAPH_FINALLY(igraph_vector_int_destroy, &iwork); if (!valuesreal) { IGRAPH_VECTOR_INIT_FINALLY(&vreal, n); myreal=&vreal; } else { IGRAPH_CHECK(igraph_vector_resize(myreal, n)); } if (!valuesimag) { IGRAPH_VECTOR_INIT_FINALLY(&vimag, n); myimag=&vimag; } else { IGRAPH_CHECK(igraph_vector_resize(myimag, n)); } if (!scale) { IGRAPH_VECTOR_INIT_FINALLY(&vscale, n); myscale=&vscale; } else { IGRAPH_CHECK(igraph_vector_resize(scale, n)); } if (vectorsleft) { IGRAPH_CHECK(igraph_matrix_resize(vectorsleft, n, n)); } if (vectorsright) { IGRAPH_CHECK(igraph_matrix_resize(vectorsright, n, n)); } igraphdgeevx_(&balanc, &jobvl, &jobvr, &sense, &n, &MATRIX(Acopy,0,0), &lda, VECTOR(*myreal), VECTOR(*myimag), vectorsleft ? &MATRIX(*vectorsleft ,0,0) : 0, &ldvl, vectorsright ? &MATRIX(*vectorsright,0,0) : 0, &ldvr, ilo, ihi, VECTOR(*myscale), abnrm, rconde ? VECTOR(*rconde) : 0, rcondv ? VECTOR(*rcondv) : 0, VECTOR(work), &lwork, VECTOR(iwork), info); lwork=(int) VECTOR(work)[0]; IGRAPH_CHECK(igraph_vector_resize(&work, lwork)); igraphdgeevx_(&balanc, &jobvl, &jobvr, &sense, &n, &MATRIX(Acopy,0,0), &lda, VECTOR(*myreal), VECTOR(*myimag), vectorsleft ? &MATRIX(*vectorsleft ,0,0) : 0, &ldvl, vectorsright ? &MATRIX(*vectorsright,0,0) : 0, &ldvr, ilo, ihi, VECTOR(*myscale), abnrm, rconde ? VECTOR(*rconde) : 0, rcondv ? VECTOR(*rcondv) : 0, VECTOR(work), &lwork, VECTOR(iwork), info); if (*info < 0) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeev)", IGRAPH_ELAPACK); } else if (*info > 0) { if (error) { IGRAPH_ERROR("Cannot calculate eigenvalues (dgeev)", IGRAPH_ELAPACK); } else { IGRAPH_WARNING("Cannot calculate eigenvalues (dgeev)"); } } if (!scale) { igraph_vector_destroy(&vscale); IGRAPH_FINALLY_CLEAN(1); } if (!valuesimag) { igraph_vector_destroy(&vimag); IGRAPH_FINALLY_CLEAN(1); } if (!valuesreal) { igraph_vector_destroy(&vreal); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_int_destroy(&iwork); igraph_vector_destroy(&work); igraph_matrix_destroy(&Acopy); IGRAPH_FINALLY_CLEAN(3); return 0; } int igraph_lapack_dgehrd(const igraph_matrix_t *A, int ilo, int ihi, igraph_matrix_t *result) { int n=(int) igraph_matrix_nrow(A); int lda=n; int lwork=-1; igraph_vector_t work; igraph_real_t optwork; igraph_vector_t tau; igraph_matrix_t Acopy; int info=0; int i; if (igraph_matrix_ncol(A) != n) { IGRAPH_ERROR("Hessenberg reduction failed", IGRAPH_NONSQUARE); } if (ilo < 1 || ihi > n || ilo > ihi) { IGRAPH_ERROR("Invalid `ilo' and/or `ihi'", IGRAPH_EINVAL); } if (n <= 1) { IGRAPH_CHECK(igraph_matrix_update(result, A)); return 0; } IGRAPH_CHECK(igraph_matrix_copy(&Acopy, A)); IGRAPH_FINALLY(igraph_matrix_destroy, &Acopy); IGRAPH_VECTOR_INIT_FINALLY(&tau, n-1); igraphdgehrd_(&n, &ilo, &ihi, &MATRIX(Acopy, 0, 0), &lda, VECTOR(tau), &optwork, &lwork, &info); if (info != 0) { IGRAPH_ERROR("Internal Hessenberg transformation error", IGRAPH_EINTERNAL); } lwork=(int) optwork; IGRAPH_VECTOR_INIT_FINALLY(&work, lwork); igraphdgehrd_(&n, &ilo, &ihi, &MATRIX(Acopy, 0, 0), &lda, VECTOR(tau), VECTOR(work), &lwork, &info); if (info != 0) { IGRAPH_ERROR("Internal Hessenberg transformation error", IGRAPH_EINTERNAL); } igraph_vector_destroy(&work); igraph_vector_destroy(&tau); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_matrix_update(result, &Acopy)); igraph_matrix_destroy(&Acopy); IGRAPH_FINALLY_CLEAN(1); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NODE_H #define NODE_H #include #include #include "igraph_interface.h" class Node; using namespace std; class Node{ public: Node(); Node(int modulenr,double tpweight); vector members; vector< pair > inLinks; vector< pair > outLinks; double selfLink; double teleportWeight; double danglingSize; double exit; double size; }; void cpyNode(Node *newNode, Node *oldNode); #endif igraph/src/dsaup2.f0000644000175100001440000010001213431000472013662 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsaup2 c c\Description: c Intermediate level interface called by igraphdsaupd. c c\Usage: c call igraphdsaup2 c ( IDO, BMAT, N, WHICH, NEV, NP, TOL, RESID, MODE, IUPD, c ISHIFT, MXITER, V, LDV, H, LDH, RITZ, BOUNDS, Q, LDQ, WORKL, c IPNTR, WORKD, INFO ) c c\Arguments c c IDO, BMAT, N, WHICH, NEV, TOL, RESID: same as defined in igraphdsaupd. c MODE, ISHIFT, MXITER: see the definition of IPARAM in igraphdsaupd. c c NP Integer. (INPUT/OUTPUT) c Contains the number of implicit shifts to apply during c each Arnoldi/Lanczos iteration. c If ISHIFT=1, NP is adjusted dynamically at each iteration c to accelerate convergence and prevent stagnation. c This is also roughly equal to the number of matrix-vector c products (involving the operator OP) per Arnoldi iteration. c The logic for adjusting is contained within the current c subroutine. c If ISHIFT=0, NP is the number of shifts the user needs c to provide via reverse comunication. 0 < NP < NCV-NEV. c NP may be less than NCV-NEV since a leading block of the current c upper Tridiagonal matrix has split off and contains "unwanted" c Ritz values. c Upon termination of the IRA iteration, NP contains the number c of "converged" wanted Ritz values. c c IUPD Integer. (INPUT) c IUPD .EQ. 0: use explicit restart instead implicit update. c IUPD .NE. 0: use implicit update. c c V Double precision N by (NEV+NP) array. (INPUT/OUTPUT) c The Lanczos basis vectors. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (NEV+NP) by 2 array. (OUTPUT) c H is used to store the generated symmetric tridiagonal matrix c The subdiagonal is stored in the first column of H starting c at H(2,1). The main diagonal is stored in the igraphsecond column c of H starting at H(1,2). If igraphdsaup2 converges store the c B-norm of the final residual vector in H(1,1). c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c RITZ Double precision array of length NEV+NP. (OUTPUT) c RITZ(1:NEV) contains the computed Ritz values of OP. c c BOUNDS Double precision array of length NEV+NP. (OUTPUT) c BOUNDS(1:NEV) contain the error bounds corresponding to RITZ. c c Q Double precision (NEV+NP) by (NEV+NP) array. (WORKSPACE) c Private (replicated) work array used to accumulate the c rotation in the shift application step. c c LDQ Integer. (INPUT) c Leading dimension of Q exactly as declared in the calling c program. c c WORKL Double precision array of length at least 3*(NEV+NP). (INPUT/WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. It is used in the computation of the c tridiagonal eigenvalue problem, the calculation and c application of the shifts and convergence checking. c If ISHIFT .EQ. O and IDO .EQ. 3, the first NP locations c of WORKL are used in reverse communication to hold the user c supplied shifts. c c IPNTR Integer array of length 3. (OUTPUT) c Pointer to mark the starting locations in the WORKD for c vectors used by the Lanczos iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X. c IPNTR(2): pointer to the current result vector Y. c IPNTR(3): pointer to the vector B * X when used in one of c the spectral transformation modes. X is the current c operand. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Lanczos iteration c for reverse communication. The user should not use WORKD c as temporary workspace during the iteration !!!!!!!!!! c See Data Distribution Note in igraphdsaupd. c c INFO Integer. (INPUT/OUTPUT) c If INFO .EQ. 0, a randomly initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c Error flag on output. c = 0: Normal return. c = 1: All possible eigenvalues of OP has been found. c NP returns the size of the invariant subspace c spanning the operator OP. c = 2: No shifts could be applied. c = -8: Error return from trid. eigenvalue calculation; c This should never happen. c = -9: Starting vector is zero. c = -9999: Could not build an Lanczos factorization. c Size that was built in returned in NP. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett, "The Symmetric Eigenvalue Problem". Prentice-Hall, c 1980. c 4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", c Computer Physics Communications, 53 (1989), pp 169-179. c 5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to c Implement the Spectral Transformation", Math. Comp., 48 (1987), c pp 663-673. c 6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos c Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", c SIAM J. Matr. Anal. Apps., January (1993). c 7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines c for Updating the QR decomposition", ACM TOMS, December 1990, c Volume 16 Number 4, pp 369-377. c c\Routines called: c igraphdgetv0 ARPACK initial vector generation routine. c igraphdsaitr ARPACK Lanczos factorization routine. c igraphdsapps ARPACK application of implicit shifts routine. c igraphdsconv ARPACK convergence of Ritz values routine. c igraphdseigt ARPACK compute Ritz values and error bounds routine. c igraphdsgets ARPACK reorder Ritz values and error bounds routine. c igraphdsortr ARPACK sorting routine. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c dcopy Level 1 BLAS that copies one vector to another. c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c dscal Level 1 BLAS that scales a vector. c dswap Level 1 BLAS that swaps two vectors. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/15/93: Version ' 2.4' c xx/xx/95: Version ' 2.4'. (R.B. Lehoucq) c c\SCCS Information: @(#) c FILE: saup2.F SID: 2.6 DATE OF SID: 8/16/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsaup2 & ( ido, bmat, n, which, nev, np, tol, resid, mode, iupd, & ishift, mxiter, v, ldv, h, ldh, ritz, bounds, & q, ldq, workl, ipntr, workd, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1, which*2 integer ido, info, ishift, iupd, ldh, ldq, ldv, mxiter, & n, mode, nev, np Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% c integer ipntr(3) Double precision & bounds(nev+np), h(ldh,2), q(ldq,nev+np), resid(n), & ritz(nev+np), v(ldv,nev+np), workd(3*n), & workl(3*(nev+np)) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c character wprime*2 logical cnorm, getv0, initv, update, ushift integer ierr, iter, j, kplusp, msglvl, nconv, nevbef, nev0, & np0, nptemp, nevd2, nevm2, kp(3) Double precision & rnorm, temp, eps23 save cnorm, getv0, initv, update, ushift, & iter, kplusp, msglvl, nconv, nev0, np0, & rnorm, eps23 c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, igraphdgetv0, igraphdsaitr, dscal, & igraphdsconv, igraphdseigt, igraphdsgets, & igraphdsapps, igraphdsortr, igraphdvout, igraphivout, & igraphsecond, dswap c c %--------------------% c | External Functions | c %--------------------% c Double precision & ddot, dnrm2, dlamch external ddot, dnrm2, dlamch c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic min c c %-----------------------% c | Executable Statements | c %-----------------------% c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = msaup2 c c %---------------------------------% c | Set machine dependent constant. | c %---------------------------------% c eps23 = dlamch('Epsilon-Machine') eps23 = eps23**(2.0D+0/3.0D+0) c c %-------------------------------------% c | nev0 and np0 are integer variables | c | hold the initial values of NEV & NP | c %-------------------------------------% c nev0 = nev np0 = np c c %-------------------------------------% c | kplusp is the bound on the largest | c | Lanczos factorization built. | c | nconv is the current number of | c | "converged" eigenvlues. | c | iter is the counter on the current | c | iteration step. | c %-------------------------------------% c kplusp = nev0 + np0 nconv = 0 iter = 0 c c %--------------------------------------------% c | Set flags for computing the first NEV steps | c | of the Lanczos factorization. | c %--------------------------------------------% c getv0 = .true. update = .false. ushift = .false. cnorm = .false. c if (info .ne. 0) then c c %--------------------------------------------% c | User provides the initial residual vector. | c %--------------------------------------------% c initv = .true. info = 0 else initv = .false. end if end if c c %---------------------------------------------% c | Get a possibly random starting vector and | c | force it into the range of the operator OP. | c %---------------------------------------------% c 10 continue c if (getv0) then call igraphdgetv0 (ido, bmat, 1, initv, n, 1, v, ldv, resid, & rnorm, ipntr, workd, info) c if (ido .ne. 99) go to 9000 c if (rnorm .eq. zero) then c c %-----------------------------------------% c | The initial vector is zero. Error exit. | c %-----------------------------------------% c info = -9 go to 1200 end if getv0 = .false. ido = 0 end if c c %------------------------------------------------------------% c | Back from reverse communication: continue with update step | c %------------------------------------------------------------% c if (update) go to 20 c c %-------------------------------------------% c | Back from computing user specified shifts | c %-------------------------------------------% c if (ushift) go to 50 c c %-------------------------------------% c | Back from computing residual norm | c | at the end of the current iteration | c %-------------------------------------% c if (cnorm) go to 100 c c %----------------------------------------------------------% c | Compute the first NEV steps of the Lanczos factorization | c %----------------------------------------------------------% c call igraphdsaitr (ido, bmat, n, 0, nev0, mode, resid, rnorm, v, & ldv, h, ldh, ipntr, workd, info) c c %---------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP and possibly B | c %---------------------------------------------------% c if (ido .ne. 99) go to 9000 c if (info .gt. 0) then c c %-----------------------------------------------------% c | igraphdsaitr was unable to build an Lanczos factorization | c | of length NEV0. INFO is returned with the size of | c | the factorization built. Exit main loop. | c %-----------------------------------------------------% c np = info mxiter = iter info = -9999 go to 1200 end if c c %--------------------------------------------------------------% c | | c | M A I N LANCZOS I T E R A T I O N L O O P | c | Each iteration implicitly restarts the Lanczos | c | factorization in place. | c | | c %--------------------------------------------------------------% c 1000 continue c iter = iter + 1 c if (msglvl .gt. 0) then call igraphivout (logfil, 1, iter, ndigit, & '_saup2: **** Start of major iteration number ****') end if if (msglvl .gt. 1) then call igraphivout (logfil, 1, nev, ndigit, & '_saup2: The length of the current Lanczos factorization') call igraphivout (logfil, 1, np, ndigit, & '_saup2: Extend the Lanczos factorization by') end if c c %------------------------------------------------------------% c | Compute NP additional steps of the Lanczos factorization. | c %------------------------------------------------------------% c ido = 0 20 continue update = .true. c call igraphdsaitr (ido, bmat, n, nev, np, mode, resid, rnorm, & v, ldv, h, ldh, ipntr, workd, info) c c %---------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP and possibly B | c %---------------------------------------------------% c if (ido .ne. 99) go to 9000 c if (info .gt. 0) then c c %-----------------------------------------------------% c | igraphdsaitr was unable to build an Lanczos factorization | c | of length NEV0+NP0. INFO is returned with the size | c | of the factorization built. Exit main loop. | c %-----------------------------------------------------% c np = info mxiter = iter info = -9999 go to 1200 end if update = .false. c if (msglvl .gt. 1) then call igraphdvout (logfil, 1, rnorm, ndigit, & '_saup2: Current B-norm of residual for factorization') end if c c %--------------------------------------------------------% c | Compute the eigenvalues and corresponding error bounds | c | of the current symmetric tridiagonal matrix. | c %--------------------------------------------------------% c call igraphdseigt (rnorm, kplusp, h, ldh, ritz, bounds, workl, & ierr) c if (ierr .ne. 0) then info = -8 go to 1200 end if c c %----------------------------------------------------% c | Make a copy of eigenvalues and corresponding error | c | bounds obtained from _seigt. | c %----------------------------------------------------% c call dcopy(kplusp, ritz, 1, workl(kplusp+1), 1) call dcopy(kplusp, bounds, 1, workl(2*kplusp+1), 1) c c %---------------------------------------------------% c | Select the wanted Ritz values and their bounds | c | to be used in the convergence test. | c | The selection is based on the requested number of | c | eigenvalues instead of the current NEV and NP to | c | prevent possible misconvergence. | c | * Wanted Ritz values := RITZ(NP+1:NEV+NP) | c | * Shifts := RITZ(1:NP) := WORKL(1:NP) | c %---------------------------------------------------% c nev = nev0 np = np0 call igraphdsgets (ishift, which, nev, np, ritz, bounds, workl) c c %-------------------% c | Convergence test. | c %-------------------% c call dcopy (nev, bounds(np+1), 1, workl(np+1), 1) call igraphdsconv (nev, ritz(np+1), workl(np+1), tol, nconv) c if (msglvl .gt. 2) then kp(1) = nev kp(2) = np kp(3) = nconv call igraphivout (logfil, 3, kp, ndigit, & '_saup2: NEV, NP, NCONV are') call igraphdvout (logfil, kplusp, ritz, ndigit, & '_saup2: The eigenvalues of H') call igraphdvout (logfil, kplusp, bounds, ndigit, & '_saup2: Ritz estimates of the current NCV Ritz values') end if c c %---------------------------------------------------------% c | Count the number of unwanted Ritz values that have zero | c | Ritz estimates. If any Ritz estimates are equal to zero | c | then a leading block of H of order equal to at least | c | the number of Ritz values with zero Ritz estimates has | c | split off. None of these Ritz values may be removed by | c | shifting. Decrease NP the number of shifts to apply. If | c | no shifts may be applied, then prepare to exit | c %---------------------------------------------------------% c nptemp = np do 30 j=1, nptemp if (bounds(j) .eq. zero) then np = np - 1 nev = nev + 1 end if 30 continue c if ( (nconv .ge. nev0) .or. & (iter .gt. mxiter) .or. & (np .eq. 0) ) then c c %------------------------------------------------% c | Prepare to exit. Put the converged Ritz values | c | and corresponding bounds in RITZ(1:NCONV) and | c | BOUNDS(1:NCONV) respectively. Then sort. Be | c | careful when NCONV > NP since we don't want to | c | swap overlapping locations. | c %------------------------------------------------% c if (which .eq. 'BE') then c c %-----------------------------------------------------% c | Both ends of the spectrum are requested. | c | Sort the eigenvalues into algebraically decreasing | c | order first then swap low end of the spectrum next | c | to high end in appropriate locations. | c | NOTE: when np < floor(nev/2) be careful not to swap | c | overlapping locations. | c %-----------------------------------------------------% c wprime = 'SA' call igraphdsortr (wprime, .true., kplusp, ritz, bounds) nevd2 = nev / 2 nevm2 = nev - nevd2 if ( nev .gt. 1 ) then call dswap ( min(nevd2,np), ritz(nevm2+1), 1, & ritz( max(kplusp-nevd2+1,kplusp-np+1) ), 1) call dswap ( min(nevd2,np), bounds(nevm2+1), 1, & bounds( max(kplusp-nevd2+1,kplusp-np)+1 ), 1) end if c else c c %--------------------------------------------------% c | LM, SM, LA, SA case. | c | Sort the eigenvalues of H into the an order that | c | is opposite to WHICH, and apply the resulting | c | order to BOUNDS. The eigenvalues are sorted so | c | that the wanted part are always within the first | c | NEV locations. | c %--------------------------------------------------% c if (which .eq. 'LM') wprime = 'SM' if (which .eq. 'SM') wprime = 'LM' if (which .eq. 'LA') wprime = 'SA' if (which .eq. 'SA') wprime = 'LA' c call igraphdsortr (wprime, .true., kplusp, ritz, bounds) c end if c c %--------------------------------------------------% c | Scale the Ritz estimate of each Ritz value | c | by 1 / max(eps23,magnitude of the Ritz value). | c %--------------------------------------------------% c do 35 j = 1, nev0 temp = max( eps23, abs(ritz(j)) ) bounds(j) = bounds(j)/temp 35 continue c c %----------------------------------------------------% c | Sort the Ritz values according to the scaled Ritz | c | esitmates. This will push all the converged ones | c | towards the front of ritzr, ritzi, bounds | c | (in the case when NCONV < NEV.) | c %----------------------------------------------------% c wprime = 'LA' call igraphdsortr(wprime, .true., nev0, bounds, ritz) c c %----------------------------------------------% c | Scale the Ritz estimate back to its original | c | value. | c %----------------------------------------------% c do 40 j = 1, nev0 temp = max( eps23, abs(ritz(j)) ) bounds(j) = bounds(j)*temp 40 continue c c %--------------------------------------------------% c | Sort the "converged" Ritz values again so that | c | the "threshold" values and their associated Ritz | c | estimates appear at the appropriate position in | c | ritz and bound. | c %--------------------------------------------------% c if (which .eq. 'BE') then c c %------------------------------------------------% c | Sort the "converged" Ritz values in increasing | c | order. The "threshold" values are in the | c | middle. | c %------------------------------------------------% c wprime = 'LA' call igraphdsortr(wprime, .true., nconv, ritz, bounds) c else c c %----------------------------------------------% c | In LM, SM, LA, SA case, sort the "converged" | c | Ritz values according to WHICH so that the | c | "threshold" value appears at the front of | c | ritz. | c %----------------------------------------------% call igraphdsortr(which, .true., nconv, ritz, bounds) c end if c c %------------------------------------------% c | Use h( 1,1 ) as storage to communicate | c | rnorm to _seupd if needed | c %------------------------------------------% c h(1,1) = rnorm c if (msglvl .gt. 1) then call igraphdvout (logfil, kplusp, ritz, ndigit, & '_saup2: Sorted Ritz values.') call igraphdvout (logfil, kplusp, bounds, ndigit, & '_saup2: Sorted ritz estimates.') end if c c %------------------------------------% c | Max iterations have been exceeded. | c %------------------------------------% c if (iter .gt. mxiter .and. nconv .lt. nev) info = 1 c c %---------------------% c | No shifts to apply. | c %---------------------% c if (np .eq. 0 .and. nconv .lt. nev0) info = 2 c np = nconv go to 1100 c else if (nconv .lt. nev .and. ishift .eq. 1) then c c %---------------------------------------------------% c | Do not have all the requested eigenvalues yet. | c | To prevent possible stagnation, adjust the number | c | of Ritz values and the shifts. | c %---------------------------------------------------% c nevbef = nev nev = nev + min (nconv, np/2) if (nev .eq. 1 .and. kplusp .ge. 6) then nev = kplusp / 2 else if (nev .eq. 1 .and. kplusp .gt. 2) then nev = 2 end if np = kplusp - nev c c %---------------------------------------% c | If the size of NEV was just increased | c | resort the eigenvalues. | c %---------------------------------------% c if (nevbef .lt. nev) & call igraphdsgets (ishift, which, nev, np, ritz, bounds, & workl) c end if c if (msglvl .gt. 0) then call igraphivout (logfil, 1, nconv, ndigit, & '_saup2: no. of "converged" Ritz values at this iter.') if (msglvl .gt. 1) then kp(1) = nev kp(2) = np call igraphivout (logfil, 2, kp, ndigit, & '_saup2: NEV and NP are') call igraphdvout (logfil, nev, ritz(np+1), ndigit, & '_saup2: "wanted" Ritz values.') call igraphdvout (logfil, nev, bounds(np+1), ndigit, & '_saup2: Ritz estimates of the "wanted" values ') end if end if c if (ishift .eq. 0) then c c %-----------------------------------------------------% c | User specified shifts: reverse communication to | c | compute the shifts. They are returned in the first | c | NP locations of WORKL. | c %-----------------------------------------------------% c ushift = .true. ido = 3 go to 9000 end if c 50 continue c c %------------------------------------% c | Back from reverse communication; | c | User specified shifts are returned | c | in WORKL(1:*NP) | c %------------------------------------% c ushift = .false. c c c %---------------------------------------------------------% c | Move the NP shifts to the first NP locations of RITZ to | c | free up WORKL. This is for the non-exact shift case; | c | in the exact shift case, igraphdsgets already handles this. | c %---------------------------------------------------------% c if (ishift .eq. 0) call dcopy (np, workl, 1, ritz, 1) c if (msglvl .gt. 2) then call igraphivout (logfil, 1, np, ndigit, & '_saup2: The number of shifts to apply ') call igraphdvout (logfil, np, workl, ndigit, & '_saup2: shifts selected') if (ishift .eq. 1) then call igraphdvout (logfil, np, bounds, ndigit, & '_saup2: corresponding Ritz estimates') end if end if c c %---------------------------------------------------------% c | Apply the NP0 implicit shifts by QR bulge chasing. | c | Each shift is applied to the entire tridiagonal matrix. | c | The first 2*N locations of WORKD are used as workspace. | c | After igraphdsapps is done, we have a Lanczos | c | factorization of length NEV. | c %---------------------------------------------------------% c call igraphdsapps (n, nev, np, ritz, v, ldv, h, ldh, resid, & q, ldq, workd) c c %---------------------------------------------% c | Compute the B-norm of the updated residual. | c | Keep B*RESID in WORKD(1:N) to be used in | c | the first step of the next call to igraphdsaitr. | c %---------------------------------------------% c cnorm = .true. call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(n+1), 1) ipntr(1) = n + 1 ipntr(2) = 1 ido = 2 c c %----------------------------------% c | Exit in order to compute B*RESID | c %----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd, 1) end if c 100 continue c c %----------------------------------% c | Back from reverse communication; | c | WORKD(1:N) := B*RESID | c %----------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c if (bmat .eq. 'G') then rnorm = ddot (n, resid, 1, workd, 1) rnorm = sqrt(abs(rnorm)) else if (bmat .eq. 'I') then rnorm = dnrm2(n, resid, 1) end if cnorm = .false. 130 continue c if (msglvl .gt. 2) then call igraphdvout (logfil, 1, rnorm, ndigit, & '_saup2: B-norm of residual for NEV factorization') call igraphdvout (logfil, nev, h(1,2), ndigit, & '_saup2: main diagonal of compressed H matrix') call igraphdvout (logfil, nev-1, h(2,1), ndigit, & '_saup2: subdiagonal of compressed H matrix') end if c go to 1000 c c %---------------------------------------------------------------% c | | c | E N D O F M A I N I T E R A T I O N L O O P | c | | c %---------------------------------------------------------------% c 1100 continue c mxiter = iter nev = nconv c 1200 continue ido = 99 c c %------------% c | Error exit | c %------------% c call igraphsecond (t1) tsaup2 = t1 - t0 c 9000 continue return c c %---------------% c | End of igraphdsaup2 | c %---------------% c end igraph/src/foreign-pajek-parser.y0000644000175100001440000005367513430770201016553 0ustar hornikusers/* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "igraph_error.h" #include "igraph_attributes.h" #include "config.h" #include "igraph_math.h" #include #include "foreign-pajek-header.h" #include "foreign-pajek-parser.h" #define yyscan_t void* int igraph_pajek_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_pajek_yyerror(YYLTYPE* locp, igraph_i_pajek_parsedata_t *context, const char *s); char *igraph_pajek_yyget_text (yyscan_t yyscanner ); int igraph_pajek_yyget_leng (yyscan_t yyscanner ); int igraph_i_pajek_add_string_vertex_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_string_edge_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_vertex_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_edge_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, igraph_real_t number); int igraph_i_pajek_add_string_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, const char *str); int igraph_i_pajek_add_bipartite_type(igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_check_bipartite(igraph_i_pajek_parsedata_t *context); extern igraph_real_t igraph_pajek_get_number(const char *str, long int len); extern long int igraph_i_pajek_actvertex; extern long int igraph_i_pajek_actedge; #define scanner context->scanner %} %pure-parser %output="y.tab.c" %name-prefix="igraph_pajek_yy" %defines %locations %error-verbose %parse-param { igraph_i_pajek_parsedata_t* context } %lex-param { void *scanner } %union { long int intnum; double realnum; struct { char *str; int len; } string; } %type longint; %type arcfrom; %type arcto; %type edgefrom; %type edgeto; %type number; %type word; %type vpwordpar; %type epwordpar; %type vertex; %token NEWLINE %token NUM %token ALNUM %token QSTR %token PSTR %token NETWORKLINE %token VERTICESLINE %token ARCSLINE %token EDGESLINE %token ARCSLISTLINE %token EDGESLISTLINE %token MATRIXLINE %token ERROR %token VP_X_FACT %token VP_Y_FACT %token VP_IC %token VP_BC %token VP_LC %token VP_LR %token VP_LPHI %token VP_BW %token VP_FOS %token VP_PHI %token VP_R %token VP_Q %token VP_LA %token VP_FONT %token VP_URL %token VP_SIZE %token EP_C %token EP_S %token EP_A %token EP_W %token EP_H1 %token EP_H2 %token EP_A1 %token EP_A2 %token EP_K1 %token EP_K2 %token EP_AP %token EP_P %token EP_L %token EP_LP %token EP_LR %token EP_LPHI %token EP_LC %token EP_LA %token EP_SIZE %token EP_FOS %% input: nethead vertices edgeblock { if (context->vcount2 > 0) { igraph_i_pajek_check_bipartite(context); } }; nethead: /* empty */ | NETWORKLINE words NEWLINE; vertices: verticeshead NEWLINE vertdefs; verticeshead: VERTICESLINE longint { context->vcount=$2; context->vcount2=0; } | VERTICESLINE longint longint { context->vcount=$2; context->vcount2=$3; igraph_i_pajek_add_bipartite_type(context); }; vertdefs: /* empty */ | vertdefs vertexline; vertexline: NEWLINE | vertex NEWLINE | vertex { context->actvertex=$1; } vertexid vertexcoords shape params NEWLINE { } ; vertex: longint { $$=$1; context->mode=1; }; vertexid: word { igraph_i_pajek_add_string_vertex_attribute("id", $1.str, $1.len, context); igraph_i_pajek_add_string_vertex_attribute("name", $1.str, $1.len, context); }; vertexcoords: /* empty */ | number number { igraph_i_pajek_add_numeric_vertex_attribute("x", $1, context); igraph_i_pajek_add_numeric_vertex_attribute("y", $2, context); } | number number number { igraph_i_pajek_add_numeric_vertex_attribute("x", $1, context); igraph_i_pajek_add_numeric_vertex_attribute("y", $2, context); igraph_i_pajek_add_numeric_vertex_attribute("z", $3, context); }; shape: /* empty */ | word { igraph_i_pajek_add_string_vertex_attribute("shape", $1.str, $1.len, context); }; params: /* empty */ | params param; param: vpword | VP_X_FACT number { igraph_i_pajek_add_numeric_vertex_attribute("xfact", $2, context); } | VP_Y_FACT number { igraph_i_pajek_add_numeric_vertex_attribute("yfact", $2, context); } | VP_IC number number number { /* RGB color */ igraph_i_pajek_add_numeric_vertex_attribute("color-red", $2, context); igraph_i_pajek_add_numeric_vertex_attribute("color-green", $3, context); igraph_i_pajek_add_numeric_vertex_attribute("color-blue", $4, context); } | VP_BC number number number { igraph_i_pajek_add_numeric_vertex_attribute("framecolor-red", $2, context); igraph_i_pajek_add_numeric_vertex_attribute("framecolor-green", $3, context); igraph_i_pajek_add_numeric_vertex_attribute("framecolor-blue", $4, context); } | VP_LC number number number { igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-red", $2, context); igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-green", $3, context); igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-blue", $4, context); } | VP_LR number { igraph_i_pajek_add_numeric_vertex_attribute("labeldist", $2, context); } | VP_LPHI number { igraph_i_pajek_add_numeric_vertex_attribute("labeldegree2", $2, context); } | VP_BW number { igraph_i_pajek_add_numeric_vertex_attribute("framewidth", $2, context); } | VP_FOS number { igraph_i_pajek_add_numeric_vertex_attribute("fontsize", $2, context); } | VP_PHI number { igraph_i_pajek_add_numeric_vertex_attribute("rotation", $2, context); } | VP_R number { igraph_i_pajek_add_numeric_vertex_attribute("radius", $2, context); } | VP_Q number { igraph_i_pajek_add_numeric_vertex_attribute("diamondratio", $2, context); } | VP_LA number { igraph_i_pajek_add_numeric_vertex_attribute("labeldegree", $2, context); } | VP_SIZE number { igraph_i_pajek_add_numeric_vertex_attribute("vertexsize", $2, context); } ; vpword: VP_FONT { context->mode=3; } vpwordpar { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("font", $3.str, $3.len, context); } | VP_URL { context->mode=3; } vpwordpar { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("url", $3.str, $3.len, context); } | VP_IC { context->mode=3; } vpwordpar { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("color", $3.str, $3.len, context); } | VP_BC { context->mode=3; } vpwordpar { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("framecolor", $3.str, $3.len, context); } | VP_LC { context->mode=3; } vpwordpar { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("labelcolor", $3.str, $3.len, context); } ; vpwordpar: word { $$=$1; }; edgeblock: /* empty */ | edgeblock arcs | edgeblock edges | edgeblock arcslist | edgeblock edgeslist | edgeblock adjmatrix; arcs: ARCSLINE NEWLINE arcsdefs { context->directed=1; } | ARCSLINE number NEWLINE arcsdefs { context->directed=1; }; arcsdefs: /* empty */ | arcsdefs arcsline; arcsline: NEWLINE | arcfrom arcto { context->actedge++; context->mode=2; } weight edgeparams NEWLINE { igraph_vector_push_back(context->vector, $1-1); igraph_vector_push_back(context->vector, $2-1); } ; arcfrom: longint; arcto: longint; edges: EDGESLINE NEWLINE edgesdefs { context->directed=0; } | EDGESLINE number NEWLINE edgesdefs { context->directed=0; } edgesdefs: /* empty */ | edgesdefs edgesline; edgesline: NEWLINE | edgefrom edgeto { context->actedge++; context->mode=2; } weight edgeparams NEWLINE { igraph_vector_push_back(context->vector, $1-1); igraph_vector_push_back(context->vector, $2-1); } ; edgefrom: longint; edgeto: longint; weight: /* empty */ | number { igraph_i_pajek_add_numeric_edge_attribute("weight", $1, context); }; edgeparams: /* empty */ | edgeparams edgeparam; edgeparam: epword | EP_C number number number { igraph_i_pajek_add_numeric_edge_attribute("color-red", $2, context); igraph_i_pajek_add_numeric_edge_attribute("color-green", $3, context); igraph_i_pajek_add_numeric_edge_attribute("color-blue", $4, context); } | EP_S number { igraph_i_pajek_add_numeric_edge_attribute("arrowsize", $2, context); } | EP_W number { igraph_i_pajek_add_numeric_edge_attribute("edgewidth", $2, context); } | EP_H1 number { igraph_i_pajek_add_numeric_edge_attribute("hook1", $2, context); } | EP_H2 number { igraph_i_pajek_add_numeric_edge_attribute("hook2", $2, context); } | EP_A1 number { igraph_i_pajek_add_numeric_edge_attribute("angle1", $2, context); } | EP_A2 number { igraph_i_pajek_add_numeric_edge_attribute("angle2", $2, context); } | EP_K1 number { igraph_i_pajek_add_numeric_edge_attribute("velocity1", $2, context); } | EP_K2 number { igraph_i_pajek_add_numeric_edge_attribute("velocity2", $2, context); } | EP_AP number { igraph_i_pajek_add_numeric_edge_attribute("arrowpos", $2, context); } | EP_LP number { igraph_i_pajek_add_numeric_edge_attribute("labelpos", $2, context); } | EP_LR number { igraph_i_pajek_add_numeric_edge_attribute("labelangle", $2, context); } | EP_LPHI number { igraph_i_pajek_add_numeric_edge_attribute("labelangle2", $2, context); } | EP_LA number { igraph_i_pajek_add_numeric_edge_attribute("labeldegree", $2, context); } | EP_SIZE number { /* what is this??? */ igraph_i_pajek_add_numeric_edge_attribute("arrowsize", $2, context); } | EP_FOS number { igraph_i_pajek_add_numeric_edge_attribute("fontsize", $2, context); } ; epword: EP_A { context->mode=4; } epwordpar { context->mode=2; igraph_i_pajek_add_string_edge_attribute("arrowtype", $3.str, $3.len, context); } | EP_P { context->mode=4; } epwordpar { context->mode=2; igraph_i_pajek_add_string_edge_attribute("linepattern", $3.str, $3.len, context); } | EP_L { context->mode=4; } epwordpar { context->mode=2; igraph_i_pajek_add_string_edge_attribute("label", $3.str, $3.len, context); } | EP_LC { context->mode=4; } epwordpar { context->mode=2; igraph_i_pajek_add_string_edge_attribute("labelcolor", $3.str, $3.len, context); } | EP_C { context->mode=4; } epwordpar { context->mode=2; igraph_i_pajek_add_string_edge_attribute("color", $3.str, $3.len, context); } ; epwordpar: word { context->mode=2; $$=$1; }; arcslist: ARCSLISTLINE NEWLINE arcslistlines { context->directed=1; }; arcslistlines: /* empty */ | arcslistlines arclistline; arclistline: NEWLINE | arclistfrom arctolist NEWLINE; arctolist: /* empty */ | arctolist arclistto; arclistfrom: longint { context->mode=0; context->actfrom=labs($1)-1; }; arclistto: longint { igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, labs($1)-1); }; edgeslist: EDGESLISTLINE NEWLINE edgelistlines { context->directed=0; }; edgelistlines: /* empty */ | edgelistlines edgelistline; edgelistline: NEWLINE | edgelistfrom edgetolist NEWLINE; edgetolist: /* empty */ | edgetolist edgelistto; edgelistfrom: longint { context->mode=0; context->actfrom=labs($1)-1; }; edgelistto: longint { igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, labs($1)-1); }; /* -----------------------------------------------------*/ adjmatrix: matrixline NEWLINE adjmatrixlines; matrixline: MATRIXLINE { context->actfrom=0; context->actto=0; context->directed=(context->vcount2==0); }; adjmatrixlines: /* empty */ | adjmatrixlines adjmatrixline; adjmatrixline: adjmatrixnumbers NEWLINE { context->actfrom++; context->actto=0; }; adjmatrixnumbers: /* empty */ | adjmatrixentry adjmatrixnumbers; adjmatrixentry: number { if ($1 != 0) { if (context->vcount2==0) { context->actedge++; igraph_i_pajek_add_numeric_edge_attribute("weight", $1, context); igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, context->actto); } else if (context->vcount2 + context->actto < context->vcount) { context->actedge++; igraph_i_pajek_add_numeric_edge_attribute("weight", $1, context); igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, context->vcount2+context->actto); } } context->actto++; }; /* -----------------------------------------------------*/ longint: NUM { $$=igraph_pajek_get_number(igraph_pajek_yyget_text(scanner), igraph_pajek_yyget_leng(scanner)); }; number: NUM { $$=igraph_pajek_get_number(igraph_pajek_yyget_text(scanner), igraph_pajek_yyget_leng(scanner)); }; words: /* empty */ | words word; word: ALNUM { $$.str=igraph_pajek_yyget_text(scanner); $$.len=igraph_pajek_yyget_leng(scanner); } | NUM { $$.str=igraph_pajek_yyget_text(scanner); $$.len=igraph_pajek_yyget_leng(scanner); } | QSTR { $$.str=igraph_pajek_yyget_text(scanner)+1; $$.len=igraph_pajek_yyget_leng(scanner)-2; }; %% int igraph_pajek_yyerror(YYLTYPE* locp, igraph_i_pajek_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in Pajek file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_pajek_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } /* TODO: NA's */ int igraph_i_pajek_add_numeric_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, igraph_real_t number) { long int attrsize=igraph_trie_size(names); long int id; igraph_vector_t *na; igraph_attribute_record_t *rec; igraph_trie_get(names, attrname, &id); if (id == attrsize) { /* add a new attribute */ rec=igraph_Calloc(1, igraph_attribute_record_t); na=igraph_Calloc(1, igraph_vector_t); igraph_vector_init(na, count); rec->name=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); } rec=VECTOR(*attrs)[id]; na=(igraph_vector_t*)rec->value; if (igraph_vector_size(na) == vid) { IGRAPH_CHECK(igraph_vector_push_back(na, number)); } else if (igraph_vector_size(na) < vid) { long int origsize=igraph_vector_size(na); IGRAPH_CHECK(igraph_vector_resize(na, (long int)vid+1)); for (;origsizename=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_STRING; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); } rec=VECTOR(*attrs)[id]; na=(igraph_strvector_t*)rec->value; if (igraph_strvector_size(na) <= vid) { long int origsize=igraph_strvector_size(na); IGRAPH_CHECK(igraph_strvector_resize(na, vid+1)); for (;origsizevertex_attribute_names, context->vertex_attributes, context->vcount, name, context->actvertex-1, tmp); igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return ret; } int igraph_i_pajek_add_string_edge_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context) { char *tmp; int ret; tmp=igraph_Calloc(len+1, char); if (tmp==0) { IGRAPH_ERROR("cannot add element to hash table", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp); strncpy(tmp, value, len); tmp[len]='\0'; ret=igraph_i_pajek_add_string_attribute(context->edge_attribute_names, context->edge_attributes, context->actedge, name, context->actedge-1, tmp); igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return ret; } int igraph_i_pajek_add_numeric_vertex_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context) { return igraph_i_pajek_add_numeric_attribute(context->vertex_attribute_names, context->vertex_attributes, context->vcount, name, context->actvertex-1, value); } int igraph_i_pajek_add_numeric_edge_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context) { return igraph_i_pajek_add_numeric_attribute(context->edge_attribute_names, context->edge_attributes, context->actedge, name, context->actedge-1, value); } int igraph_i_pajek_add_bipartite_type(igraph_i_pajek_parsedata_t *context) { const char *attrname="type"; igraph_trie_t *names=context->vertex_attribute_names; igraph_vector_ptr_t *attrs=context->vertex_attributes; int i, n=context->vcount, n1=context->vcount2; long int attrid, attrsize=igraph_trie_size(names); igraph_attribute_record_t *rec; igraph_vector_t *na; if (n1 > n) { IGRAPH_ERROR("Invalid number of vertices in bipartite Pajek file", IGRAPH_PARSEERROR); } igraph_trie_get(names, attrname, &attrid); if (attrid != attrsize) { IGRAPH_ERROR("Duplicate 'type' attribute in Pajek file, " "this should not happen", IGRAPH_EINTERNAL); } /* add a new attribute */ rec=igraph_Calloc(1, igraph_attribute_record_t); na=igraph_Calloc(1, igraph_vector_t); igraph_vector_init(na, n); rec->name=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); for (i=0; ivector; int i, n1=context->vcount2; int ne=igraph_vector_size(edges); for (i=0; i n1 && v2 > n1) ) { IGRAPH_WARNING("Invalid edge in bipartite graph"); } } return 0; } igraph/src/gengraph_degree_sequence.cpp0000644000175100001440000002361013431000472020027 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_definitions.h" #include "gengraph_random.h" #include "gengraph_powerlaw.h" #include "gengraph_degree_sequence.h" #include "gengraph_hash.h" #include "igraph_statusbar.h" #include #include #include #include #include // using namespace __gnu_cxx; using namespace std; namespace gengraph { // shuffle an int[] randomly void random_permute(int *a, int n); // sort an array of positive integers in time & place O(n + max) void cumul_sort(int *q, int n); void degree_sequence::detach() { deg=NULL; } degree_sequence::~degree_sequence() { if(deg!=NULL) delete[] deg; deg = NULL; } void degree_sequence::make_even(int mini, int maxi) { if(total%2==0) return; if(maxi<0) maxi=0x7FFFFFFF; int i; for(i=0; imini) { deg[i]--; total--; break; } else if(deg[i] degree; // if(!DISTRIB) { // // Input is a 'raw' degree sequence d0 d1 d2 d3 ... // while(fgets(buff, FBUFF_SIZE, f)) { // int d = strtol(buff, &c, 10); // if(c == buff) continue; // degree.push_back(d); // total += d; // } // n = int(degree.size()); // deg = new int[n]; // int *yo = deg; // vector::iterator end = degree.end(); // for(vector::iterator it=degree.begin(); it!=end; *(yo++) = *(it++)); // } // else { // // Input is a degree distribution : d0 #(degree=d0), d1 #(degree=d1), ... // vector n_with_degree; // int line = 0; // int syntax = 0; // int ignored = 0; // int first_syntax = 0; // int first_ignored = 0; // while(fgets(buff, FBUFF_SIZE, f)) { // line++; // int d = strtol(buff, &c, 10); // if(c == buff) { ignored++; first_ignored = line; continue; } // char *cc; // int i = strtol(c, &cc, 10); // if(cc == c) { syntax++; first_syntax = line; continue; } // n += i; // total += i*d; // degree.push_back(d); // n_with_degree.push_back(i); // if( cc != c) { syntax++; first_syntax = line; } // } // if(VERBOSE()) { // if(ignored > 0) fprintf(stderr,"Ignored %d lines (first was line #%d)\n", ignored, first_ignored); // if(syntax > 0) fprintf(stderr,"Found %d probable syntax errors (first was line #%d)\n", syntax, first_syntax); // } // deg = new int[n]; // int *yo = deg; // vector::iterator it_n = n_with_degree.begin(); // for(vector::iterator it = degree.begin(); it != degree.end(); it++) // for(int k = *(it_n++); k--; *yo++ = *it); // } // if(VERBOSE()) { // if(total % 2 != 0) fprintf(stderr,"Warning: degree sequence is odd\n"); // fprintf(stderr,"Degree sequence created. N=%d, 2M=%d\n", n, total); // } // } // n vertices, exponent, min degree, max degree, average degree (optional, default is -1) degree_sequence:: degree_sequence(int _n, double exp, int degmin, int degmax, double z) { n=_n; if(exp==0.0) { // Binomial distribution if(z<0) { igraph_error("Fatal error in degree_sequence Ctor: " "positive average degree must be specified", __FILE__, __LINE__, IGRAPH_EINVAL); } if(degmax<0) degmax=n-1; total = int(floor(double(n)*z+0.5)); deg = new int[n]; KW_RNG::RNG myrand; double p = (z-double(degmin))/double(n); total=0; for(int i=0; idegmax); total+=deg[i]; } } else { // Power-law distribution igraph_status("Creating powerlaw sampler...", 0); powerlaw pw(exp, degmin, degmax); if(z==-1.0) { pw.init(); igraph_statusf("done. Mean=%f\n", 0, pw.mean()); } else { double offset = pw.init_to_mean(z); igraph_statusf("done. Offset=%f, Mean=%f\n", 0, offset, pw.mean()); } deg = new int[n]; total = 0; int i; igraph_statusf("Sampling %d random numbers...", 0, n); for(i=0; iwanted_total; i++) { total-=deg[i]; if(total+degmin<=wanted_total) deg[i]=wanted_total-total; else deg[i]=pw.sample(); total += deg[i]; } iterations += i; for(i=n-1; i>0 && total>1)>=wanted_total) deg[i]=wanted_total-total; else deg[i]=pw.sample(); total += deg[i]; } iterations += n-1-i; } igraph_statusf("done(%d iterations).", 0, iterations); igraph_statusf(" Now, degmax = %d\n", 0, dmax()); } shuffle(); } } // void degree_sequence::print() { // for(int i=0; ideg[i]) dmin=deg[i]; // int *dd = new int[dmax-dmin+1]; // for(i=dmin; i<=dmax; i++) dd[i-dmin]=0; // if(VERBOSE()) fprintf(stderr,"Computing cumulative distribution..."); // for(i=0; i0) printf("%d %d\n",i,dd[i-dmin]); // delete[] dd; // } bool degree_sequence::havelhakimi() { int i; int dm = dmax()+1; // Sort vertices using basket-sort, in descending degrees int *nb = new int[dm]; int *sorted = new int[n]; // init basket for(i=0; i=0; i--) { int t=nb[i]; nb[i]=c; c+=t; } // sort for(i=0; i0; ) { // We design by 'v' the vertex of highest degree (indexed by first) // look for current degree of v while(nb[d]<=first) d--; // store it in dv int dv = d; // bind it ! c -= dv; int dc = d; // residual degree of vertices we bind to int fc = ++first; // position of the first vertex with degree dc while(dv>0 && dc>0) { int lc = nb[dc]; if(lc!=fc) { while(dv>0 && lc>fc) { // binds v with sorted[--lc] dv--; lc--; } fc = nb[dc]; nb[dc] = lc; } dc--; } if(dv != 0) { // We couldn't bind entirely v delete[] nb; delete[] sorted; return false; } } delete[] nb; delete[] sorted; return true; } //************************* // Subroutines definitions //************************* inline int int_adjust(double x) { return(int(floor(x+random_float()))); } void random_permute(int *a, int n) { int j,tmp; for(int i=0; iqmax) qmax=q[i]; for(i=0; i0;i--) nb[i-1]+=nb[i]; // sort by q[i] int last_q; int tmp; int modifier = qmax-qmin+1; for(int current=0; current=qmin && tmp<=qmax) { last_q=qmin; do { q[current] = last_q+modifier; last_q = tmp; current = --nb[last_q-qmin]; } while((tmp=q[current])>=qmin && tmp<=qmax); q[current]=last_q+modifier; } } delete[] nb; for(i=0; i. */ #ifndef GRAPH_MOLLOY_OPT_H #define GRAPH_MOLLOY_OPT_H #include "gengraph_definitions.h" #include "gengraph_degree_sequence.h" #include "gengraph_qsort.h" #include #include "gengraph_random.h" namespace gengraph { // This class handles graphs with a constant degree sequence. class graph_molloy_opt { private: // Random generator KW_RNG::RNG rng; // Number of vertices int n; //Number of arcs ( = #edges * 2 ) int a; // The degree sequence of the graph int *deg; // The array containing all links int *links; // The array containing pointers to adjacency list of every vertices int **neigh; // Allocate memory according to degree_sequence (for constructor use only!!) void alloc(degree_sequence &); // Compute #edges inline void refresh_nbarcs() { a=0; for(int* d=deg+n; d!=deg; ) a += *(--d); } // Build neigh with deg and links void compute_neigh(); // Swap edges. The swap MUST be valid !!! inline void swap_edges(int from1, int to1, int from2, int to2) { fast_rpl(neigh[from1],to1,to2); fast_rpl(neigh[from2],to2,to1); fast_rpl(neigh[to1],from1,from2); fast_rpl(neigh[to2],from2,from1); } // Swap edges only if they are simple. return false if unsuccessful. bool swap_edges_simple(int ,int ,int, int); // Test if vertex is in an isolated component of size dmax. void depth_isolated(int v, long &calls, int &left_to_explore, int dmax, int * &Kbuff, bool *visited); // breadth-first search. Store the distance (modulo 3) in dist[]. Returns eplorated component size. int width_search(unsigned char *dist, int *buff, int v0=0, int toclear=-1); // depth-first search. int depth_search(bool *visited, int *buff, int v0=0); // breadth-first search that count the number of shortest paths going from src to each vertex int breadth_path_search(int src, int *buff, double *paths, unsigned char *dist); // Used by traceroute_sample() ONLY void add_traceroute_edge(int, int, int*, double** red=NULL, double t=1.0); // Used by traceroute() and betweenness(). if newdeg[]=NULL, do not discover edges. // breadth_path_search() must have been called to give the corresponding buff[],dist[],paths[] and nb_vertices void explore_usp(double *target, int nb_vertices, int *buff, double *paths, unsigned char *dist, int *newdeg=NULL, double **edge_redudancy=NULL); void explore_asp(double *target, int nb_vertices, int *buff, double *paths, unsigned char *dist, int *newdeg=NULL, double **edge_redudancy=NULL); void explore_rsp(double *target, int nb_vertices, int *buff, double *paths, unsigned char *dist, int *newdeg=NULL, double **edge_redudancy=NULL); // Return component indexes where vertices belong to, starting from 0, // sorted by size (biggest component has index 0) int *components(int *comp=NULL); // pick k random vertices of degree > 0. int *pick_random_vertices(int &k, int *output=NULL, int nb_v=-1, int *among=NULL); public: // neigh[] inline int** neighbors() { return neigh; }; // deg[] inline int* degrees() { return deg; }; //adjacency list of v inline int* operator[](const int v) { return neigh[v]; }; //degree of v inline int degree(const int v) { return deg[v]; }; //compare adjacency lists inline int compare(const int v, const int w) { return deg[v]==deg[w] ? lex_comp(neigh[v],neigh[w],deg[v]) : (deg[v]>deg[w] ? -1 : 1); }; // Detach deg[] and neigh[] void detach(); // Destroy deg and links ~graph_molloy_opt(); // Create graph from file (stdin not supported unless rewind() possible) graph_molloy_opt(FILE *f); // Allocate memory for the graph. Create deg and links. No edge is created. graph_molloy_opt(degree_sequence &); // Create graph from hard copy graph_molloy_opt(int *); // Create hard copy of graph int *hard_copy(); // Remove unused edges, updates neigh[], recreate links[] void clean(); // nb arcs inline int nbarcs() { return a; }; // last degree inline int last_degree() { return deg[n-1]; }; // nb vertices inline int nbvertices() { return n; }; // nb vertices having degree > 0 inline int nbvertices_real() { int s=0; for(int *d=deg+n; d--!=deg; ) if(*d) s++; return s; }; // return list of vertices with degree > 0. Compute #vertices, if not given. int *vertices_real(int &nb_v); // Keep only giant component void giant_comp(); // nb vertices in giant component int nbvertices_comp(); // nb arcs in giant component int nbarcs_comp(); // print graph in SUCC_LIST mode, in stdout void print(FILE *f=stdout, bool NOZERO=true); // Bind the graph avoiding multiple edges or self-edges (return false if fail) bool havelhakimi(); // Get the graph connected (return false if fail) bool make_connected(); // Test if graph is connected bool is_connected(); // Maximum degree int max_degree(); // breadth-first search. Store the distance (modulo 3) in dist[]. void breadth_search(int *dist, int v0=0, int* buff=NULL); // is edge ? inline bool is_edge(const int a, const int b) { if(deg[b] 0. If k \in [0,1[, k is understood as a density. int *pick_random_src(double k, int *nb=NULL, int* buff=NULL, int nb_v=-1, int* among=NULL); // pick k random vertices of degree > 0. If k \in [0,1], k is understood as a density. int *pick_random_dst(double k, int *nb=NULL, int* buff=NULL, int nb_v=-1, int* among=NULL); // For debug purposes : verify validity of the graph (symetry, simplicity) #define VERIFY_NORMAL 0 #define VERIFY_NONEIGH 1 #define VERIFY_NOARCS 2 bool verify(int mode=VERIFY_NORMAL); /*___________________________________________________________________________________ Not to use anymore : use graph_molloy_hash class instead public: // Shuffle. returns number of swaps done. void shuffle(long); // Connected Shuffle long connected_shuffle(long); // Get caracteristic K double eval_K(int quality = 100); // Get effective K double effective_K(int K, int quality = 10000); // Test window double window(int K, double ratio); // Try to shuffle n times. Return true if at the end, the graph was still connected. bool try_shuffle(int T, int K); //___________________________________________________________________________________ //*/ /*___________________________________________________________________________________ Not to use anymore : replaced by vertex_betweenness() 22/04/2005 // shortest paths where vertex is an extremity long long *vertex_betweenness_usp(bool trivial_path); // shortest paths where vertex is an extremity long long *vertex_betweenness_rsp(bool trivial_path); // same, but when multiple shortest path are possible, average the weights. double *vertex_betweenness_asp(bool trivial_path); //___________________________________________________________________________________ //*/ }; } // namespace gengraph #endif //GRAPH_MOLLOY_OPT_H igraph/src/igraph_psumtree.c0000644000175100001440000000521313431000472015666 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA Copyright (C) 2006 Elliot Paquette Kalamazoo College, 1200 Academy st, Kalamazoo, MI This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_psumtree.h" #include "igraph_error.h" #include "config.h" #include #include double igraph_i_log2(double f) { return log(f) / log(2.0); } int igraph_psumtree_init(igraph_psumtree_t *t, long int size) { t->size=size; t->offset=(long int) (pow(2, ceil(igraph_i_log2(size)))-1); IGRAPH_CHECK(igraph_vector_init((igraph_vector_t *)t, t->offset+t->size)); return 0; } void igraph_psumtree_destroy(igraph_psumtree_t *t) { igraph_vector_destroy((igraph_vector_t *)t); } igraph_real_t igraph_psumtree_get(const igraph_psumtree_t *t, long int idx) { const igraph_vector_t *tree=&t->v; return VECTOR(*tree)[t->offset+idx]; } int igraph_psumtree_search(const igraph_psumtree_t *t, long int *idx, igraph_real_t search) { const igraph_vector_t *tree=&t->v; long int i = 1; long int size = igraph_vector_size(tree); while( 2*i+1 <= size) { if( search <= VECTOR(*tree)[i*2-1] ) { i <<= 1; } else { search -= VECTOR(*tree)[i*2-1]; i <<= 1; i += 1; } } if (2*i <= size) { i=2*i; } *idx = i-t->offset-1; return IGRAPH_SUCCESS; } int igraph_psumtree_update(igraph_psumtree_t *t, long int idx, igraph_real_t new_value) { const igraph_vector_t *tree=&t->v; igraph_real_t difference; idx = idx + t->offset+1; difference = new_value - VECTOR(*tree)[idx-1]; while( idx >= 1 ) { VECTOR(*tree)[idx-1] += difference; idx >>= 1; } return IGRAPH_SUCCESS; } long int igraph_psumtree_size(const igraph_psumtree_t *t) { return t->size; } igraph_real_t igraph_psumtree_sum(const igraph_psumtree_t *t) { return VECTOR(t->v)[0]; } igraph/src/coloring.c0000644000175100001440000001114213431000472014302 0ustar hornikusers #include "igraph_coloring.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_types_internal.h" int igraph_i_vertex_coloring_greedy_cn(const igraph_t *graph, igraph_vector_int_t *colors) { long i, vertex, maxdeg; long vc = igraph_vcount(graph); igraph_2wheap_t cn; /* indexed heap storing number of already coloured neighbours */ igraph_vector_int_t neigh_colors; igraph_adjlist_t adjlist; IGRAPH_CHECK(igraph_vector_int_resize(colors, vc)); igraph_vector_int_fill(colors, 0); /* Nothing to do for 0 or 1 vertices. * Remember that colours are integers starting from 0, * and the 'colors' vector is already 0-initialized above. */ if (vc <= 1) return IGRAPH_SUCCESS; IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); /* find maximum degree and a corresponding vertex */ { igraph_vector_t degree; IGRAPH_CHECK(igraph_vector_init(°ree, 0)); IGRAPH_FINALLY(igraph_vector_destroy, °ree); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, 0)); vertex = igraph_vector_which_max(°ree); maxdeg = VECTOR(degree)[vertex]; igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(1); } IGRAPH_CHECK(igraph_vector_int_init(&neigh_colors, 0)); IGRAPH_CHECK(igraph_vector_int_reserve(&neigh_colors, maxdeg)); IGRAPH_FINALLY(igraph_vector_int_destroy, &neigh_colors); IGRAPH_CHECK(igraph_2wheap_init(&cn, vc)); IGRAPH_FINALLY(igraph_2wheap_destroy, &cn); for (i=0; i < vc; ++i) if (i != vertex) igraph_2wheap_push_with_index(&cn, i, 0); /* should not fail since memory was already reserved */ while (1) { igraph_vector_int_t *neighbors = igraph_adjlist_get(&adjlist, vertex); long neigh_count = igraph_vector_int_size(neighbors); /* colour current vertex */ { igraph_integer_t col; IGRAPH_CHECK(igraph_vector_int_resize(&neigh_colors, neigh_count)); for (i=0; i < neigh_count; ++i) VECTOR(neigh_colors)[i] = VECTOR(*colors)[ VECTOR(*neighbors)[i] ]; igraph_vector_int_sort(&neigh_colors); i=0; col = 0; do { while (i < neigh_count && VECTOR(neigh_colors)[i] == col) i++; col++; } while (i < neigh_count && VECTOR(neigh_colors)[i] == col); VECTOR(*colors)[vertex] = col; } /* increment number of coloured neighbours for each neighbour of vertex */ for (i=0; i < neigh_count; ++i) { long idx = VECTOR(*neighbors)[i]; if (igraph_2wheap_has_elem(&cn, idx)) igraph_2wheap_modify(&cn, idx, igraph_2wheap_get(&cn, idx) + 1); } /* stop if no more vertices left to colour */ if (igraph_2wheap_empty(&cn)) break; igraph_2wheap_delete_max_index(&cn, &vertex); IGRAPH_ALLOW_INTERRUPTION(); } /* subtract 1 from each colour value, so that colours start at 0 */ igraph_vector_int_add_constant(colors, -1); /* free data structures */ igraph_vector_int_destroy(&neigh_colors); igraph_adjlist_destroy(&adjlist); igraph_2wheap_destroy(&cn); IGRAPH_FINALLY_CLEAN(3); return IGRAPH_SUCCESS; } /** * \function igraph_vertex_coloring_greedy * \brief Computes a vertex coloring using a greedy algorithm. * * * This function assigns a "color"---represented as a non-negative integer---to * each vertex of the graph in such a way that neighboring vertices never have * the same color. The obtained coloring is not necessarily minimal. * * * Vertices are colored one by one, choosing the smallest color index that * differs from that of already colored neighbors. * Colors are represented with non-negative integers 0, 1, 2, ... * * \param graph The input graph. * \param colors Pointer to an initialized integer vector. The vertex colors will be stored here. * \param heuristic The vertex ordering heuristic to use during greedy coloring. See \ref igraph_coloring_greedy_t * * \return Error code. * * \example examples/simple/igraph_coloring.c */ int igraph_vertex_coloring_greedy(const igraph_t *graph, igraph_vector_int_t *colors, igraph_coloring_greedy_t heuristic) { switch (heuristic) { case IGRAPH_COLORING_GREEDY_COLORED_NEIGHBORS: return igraph_i_vertex_coloring_greedy_cn(graph, colors); default: return IGRAPH_EINVAL; } } igraph/src/drl_graph.cpp0000644000175100001440000011144713431000472015001 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the member definitions of the master class #include #include #include #include #include #include #include using namespace std; #include "drl_graph.h" #include "igraph_random.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #ifdef MUSE_MPI #include #endif namespace drl { // constructor -- initializes the schedule variables (as in // graph constructor) // graph::graph ( int proc_id, int tot_procs, char *int_file ) // { // // MPI parameters // myid = proc_id; // num_procs = tot_procs; // // initial annealing parameters // STAGE = 0; // iterations = 0; // temperature = 2000; // attraction = 10; // damping_mult = 1.0; // min_edges = 20; // first_add = fine_first_add = true; // fineDensity = false; // // Brian's original Vx schedule // liquid.iterations = 200; // liquid.temperature = 2000; // liquid.attraction = 2; // liquid.damping_mult = 1.0; // liquid.time_elapsed = 0; // expansion.iterations = 200; // expansion.temperature = 2000; // expansion.attraction = 10; // expansion.damping_mult = 1.0; // expansion.time_elapsed = 0; // cooldown.iterations = 200; // cooldown.temperature = 2000; // cooldown.attraction = 1; // cooldown.damping_mult = .1; // cooldown.time_elapsed = 0; // crunch.iterations = 50; // crunch.temperature = 250; // crunch.attraction = 1; // crunch. damping_mult = .25; // crunch.time_elapsed = 0; // simmer.iterations = 100; // simmer.temperature = 250; // simmer.attraction = .5; // simmer.damping_mult = 0.0; // simmer.time_elapsed = 0; // // scan .int file for node info // scan_int ( int_file ); // // populate node positions and ids // positions.reserve ( num_nodes ); // map < int, int >::iterator cat_iter; // for ( cat_iter = id_catalog.begin(); // cat_iter != id_catalog.end(); // cat_iter++ ) // positions.push_back ( Node( cat_iter->first ) ); // /* // // output positions .ids for debugging // for ( int id = 0; id < num_nodes; id++ ) // cout << positions[id].id << endl; // */ // // read .int file for graph info // read_int ( int_file ); // // initialize density server // density_server.Init(); // } graph::graph(const igraph_t *igraph, const igraph_layout_drl_options_t *options, const igraph_vector_t *weights) { myid = 0; num_procs = 1; STAGE = 0; iterations = options->init_iterations; temperature = options->init_temperature; attraction = options->init_attraction; damping_mult = options->init_damping_mult; min_edges = 20; first_add = fine_first_add = true; fineDensity = false; // Brian's original Vx schedule liquid.iterations = options->liquid_iterations; liquid.temperature = options->liquid_temperature; liquid.attraction = options->liquid_attraction; liquid.damping_mult = options->liquid_damping_mult; liquid.time_elapsed = 0; expansion.iterations = options->expansion_iterations; expansion.temperature = options->expansion_temperature; expansion.attraction = options->expansion_attraction; expansion.damping_mult = options->expansion_damping_mult; expansion.time_elapsed = 0; cooldown.iterations = options->cooldown_iterations; cooldown.temperature = options->cooldown_temperature; cooldown.attraction = options->cooldown_attraction; cooldown.damping_mult = options->cooldown_damping_mult; cooldown.time_elapsed = 0; crunch.iterations = options->crunch_iterations; crunch.temperature = options->crunch_temperature; crunch.attraction = options->crunch_attraction; crunch.damping_mult = options->crunch_damping_mult; crunch.time_elapsed = 0; simmer.iterations = options->simmer_iterations; simmer.temperature = options->simmer_temperature; simmer.attraction = options->simmer_attraction; simmer.damping_mult = options->simmer_damping_mult; simmer.time_elapsed = 0; // scan .int file for node info highest_sim = 1.0; num_nodes=igraph_vcount(igraph); long int no_of_edges=igraph_ecount(igraph); for (long int i=0; i::iterator cat_iter; for ( cat_iter = id_catalog.begin(); cat_iter != id_catalog.end(); cat_iter++) { cat_iter->second = cat_iter->first; } // populate node positions and ids positions.reserve ( num_nodes ); for ( cat_iter = id_catalog.begin(); cat_iter != id_catalog.end(); cat_iter++ ) { positions.push_back ( Node( cat_iter->first ) ); } // read .int file for graph info long int node_1, node_2; double weight; for (long int i=0; i> id1 >> id2 >> edge_weight; // // ignore negative weights! // if ( edge_weight <= 0 ) // { // cout << "Error: found negative edge weight in " << filename << ". Program stopped." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // if ( highest_sim < edge_weight ) // highest_sim = edge_weight; // id_catalog[id1] = 1; // id_catalog[id2] = 1; // } // fp.close(); // if ( id_catalog.size() == 0 ) // { // cout << "Error: Proc. " << myid << ": " << filename << " is empty. Program terminated." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // // label nodes with sequential integers starting at 0 // map< int, int>::iterator cat_iter; // int id_label; // for ( cat_iter = id_catalog.begin(), id_label = 0; // cat_iter != id_catalog.end(); cat_iter++, id_label++ ) // cat_iter->second = id_label; // /* // // output id_catalog for debugging: // for ( cat_iter = id_catalog.begin(); // cat_iter != id_catalog.end(); // cat_iter++ ) // cout << cat_iter->first << "\t" << cat_iter->second << endl; // */ // num_nodes = id_catalog.size(); // } // read in .parms file, if present /* void graph::read_parms ( char *parms_file ) { // read from .parms file ifstream parms_in ( parms_file ); if ( !parms_in ) { cout << "Error: could not open .parms file! Program stopped." << endl; #ifdef MUSE_MPI MPI_Abort ( MPI_COMM_WORLD, 1 ); #else exit (1); #endif } cout << "Processor " << myid << " reading .parms file." << endl; // read in stage parameters string parm_label; // this is ignored in the .parms file // initial parameters parms_in >> parm_label >> iterations; parms_in >> parm_label >> temperature; parms_in >> parm_label >> attraction; parms_in >> parm_label >> damping_mult; // liquid stage parms_in >> parm_label >> liquid.iterations; parms_in >> parm_label >> liquid.temperature; parms_in >> parm_label >> liquid.attraction; parms_in >> parm_label >> liquid.damping_mult; // expansion stage parms_in >> parm_label >> expansion.iterations; parms_in >> parm_label >> expansion.temperature; parms_in >> parm_label >> expansion.attraction; parms_in >> parm_label >> expansion.damping_mult; // cooldown stage parms_in >> parm_label >> cooldown.iterations; parms_in >> parm_label >> cooldown.temperature; parms_in >> parm_label >> cooldown.attraction; parms_in >> parm_label >> cooldown.damping_mult; // crunch stage parms_in >> parm_label >> crunch.iterations; parms_in >> parm_label >> crunch.temperature; parms_in >> parm_label >> crunch.attraction; parms_in >> parm_label >> crunch.damping_mult; // simmer stage parms_in >> parm_label >> simmer.iterations; parms_in >> parm_label >> simmer.temperature; parms_in >> parm_label >> simmer.attraction; parms_in >> parm_label >> simmer.damping_mult; parms_in.close(); // print out parameters for double checking if ( myid == 0 ) { cout << "Processor 0 reports the following inputs:" << endl; cout << "inital.iterations = " << iterations << endl; cout << "initial.temperature = " << temperature << endl; cout << "initial.attraction = " << attraction << endl; cout << "initial.damping_mult = " << damping_mult << endl; cout << " ..." << endl; cout << "liquid.iterations = " << liquid.iterations << endl; cout << "liquid.temperature = " << liquid.temperature << endl; cout << "liquid.attraction = " << liquid.attraction << endl; cout << "liquid.damping_mult = " << liquid.damping_mult << endl; cout << " ..." << endl; cout << "simmer.iterations = " << simmer.iterations << endl; cout << "simmer.temperature = " << simmer.temperature << endl; cout << "simmer.attraction = " << simmer.attraction << endl; cout << "simmer.damping_mult = " << simmer.damping_mult << endl; } } */ // init_parms -- this subroutine initializes the edge_cut variables // used in the original VxOrd starting with the edge_cut parameter. // In our version, edge_cut = 0 means no cutting, 1 = maximum cut. // We also set the random seed here. void graph::init_parms ( int rand_seed, float edge_cut, float real_parm ) { IGRAPH_UNUSED(rand_seed); // first we translate edge_cut the former tcl sliding scale //CUT_END = cut_length_end = 39000.0 * (1.0 - edge_cut) + 1000.0; CUT_END = cut_length_end = 40000.0 * (1.0 - edge_cut); // cut_length_end cannot actually be 0 if ( cut_length_end <= 1.0 ) cut_length_end = 1.0; float cut_length_start = 4.0 * cut_length_end; // now we set the parameters used by ReCompute cut_off_length = cut_length_start; cut_rate = ( cut_length_start - cut_length_end ) / 400.0; // finally set the number of iterations to leave .real coords fixed int full_comp_iters; full_comp_iters = liquid.iterations + expansion.iterations + cooldown.iterations + crunch.iterations + 3; // adjust real parm to iterations (do not enter simmer halfway) if ( real_parm < 0 ) real_iterations = (int)real_parm; else if ( real_parm == 1) real_iterations = full_comp_iters + simmer.iterations + 100; else real_iterations = (int)(real_parm*full_comp_iters); tot_iterations = 0; if ( real_iterations > 0 ) real_fixed = true; else real_fixed = false; // calculate total expected iterations (for progress bar display) tot_expected_iterations = liquid.iterations + expansion.iterations + cooldown.iterations + crunch.iterations + simmer.iterations; /* // output edge_cutting parms (for debugging) cout << "Processor " << myid << ": " << "cut_length_end = CUT_END = " << cut_length_end << ", cut_length_start = " << cut_length_start << ", cut_rate = " << cut_rate << endl; */ // set random seed // srand ( rand_seed ); // Don't need this in igraph } void graph::init_parms(const igraph_layout_drl_options_t *options) { double rand_seed = 0.0; double real_in = -1.0; init_parms(rand_seed, options->edge_cut, real_in); } // The following subroutine reads a .real file to obtain initial // coordinates. If a node is missing coordinates the coordinates // are computed // void graph::read_real ( char *real_file ) // { // cout << "Processor " << myid << " reading .real file ..." << endl; // // read in .real file and mark as fixed // ifstream real_in ( real_file ); // if ( !real_in ) // { // cout << "Error: proc. " << myid << " could not open .real file." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // int real_id; // float real_x, real_y; // while ( !real_in.eof () ) // { // real_id = -1; // real_in >> real_id >> real_x >> real_y; // if ( real_id >= 0 ) // { // positions[id_catalog[real_id]].x = real_x; // positions[id_catalog[real_id]].y = real_y; // positions[id_catalog[real_id]].fixed = true; // /* // // output positions read (for debugging) // cout << id_catalog[real_id] << " (" << positions[id_catalog[real_id]].x // << ", " << positions[id_catalog[real_id]].y << ") " // << positions[id_catalog[real_id]].fixed << endl; // */ // // add node to density grid // if ( real_iterations > 0 ) // density_server.Add ( positions[id_catalog[real_id]], fineDensity ); // } // } // real_in.close(); // } int graph::read_real ( const igraph_matrix_t *real_mat, const igraph_vector_bool_t *fixed) { long int n=igraph_matrix_nrow(real_mat); for (long int i=0; i 0 ) { density_server.Add ( positions[id_catalog[i]], fineDensity ); } } return 0; } // The read_part_int subroutine reads the .int // file produced by convert_sim and gathers the nodes and their // neighbors in the range start_ind to end_ind. // void graph::read_int ( char *file_name ) // { // ifstream int_file; // int_file.open ( file_name ); // if ( !int_file ) // { // cout << "Error (worker process " << myid << "): could not open .int file." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // cout << "Processor " << myid << " reading .int file ..." << endl; // int node_1, node_2; // float weight; // while ( !int_file.eof() ) // { // weight = 0; // all weights should be >= 0 // int_file >> node_1 >> node_2 >> weight; // if ( weight ) // otherwise we are at end of file // // or it is a self-connected node // { // // normalization from original vxord // weight /= highest_sim; // weight = weight*fabs(weight); // // initialize graph // if ( ( node_1 % num_procs ) == myid ) // (neighbors[id_catalog[node_1]])[id_catalog[node_2]] = weight; // if ( ( node_2 % num_procs ) == myid ) // (neighbors[id_catalog[node_2]])[id_catalog[node_1]] = weight; // } // } // int_file.close(); // /* // // the following code outputs the contents of the neighbors structure // // (to be used for debugging) // map >::iterator i; // map::iterator j; // for ( i = neighbors.begin(); i != neighbors.end(); i++ ) { // cout << myid << ": " << i->first << " "; // for (j = (i->second).begin(); j != (i->second).end(); j++ ) // cout << j->first << " (" << j->second << ") "; // cout << endl; // } // */ // } /********************************************* * Function: ReCompute * * Description: Compute the graph locations * * Modified from original code by B. Wylie * ********************************************/ int graph::ReCompute( ) { // carryover from original VxOrd int MIN = 1; /* // output parameters (for debugging) cout << "ReCompute is using the following parameters: "<< endl; cout << "STAGE: " << STAGE << ", iter: " << iterations << ", temp = " << temperature << ", attract = " << attraction << ", damping_mult = " << damping_mult << ", min_edges = " << min_edges << ", cut_off_length = " << cut_off_length << ", fineDensity = " << fineDensity << endl; */ /* igraph progress report */ float progress = (tot_iterations * 100.0 / tot_expected_iterations); switch (STAGE) { case 0: if (iterations == 0) IGRAPH_PROGRESS("DrL layout (initialization stage)", progress, 0); else IGRAPH_PROGRESS("DrL layout (liquid stage)", progress, 0); break; case 1: IGRAPH_PROGRESS("DrL layout (expansion stage)", progress, 0); break; case 2: IGRAPH_PROGRESS("DrL layout (cooldown and cluster phase)", progress, 0); break; case 3: IGRAPH_PROGRESS("DrL layout (crunch phase)", progress, 0); break; case 5: IGRAPH_PROGRESS("DrL layout (simmer phase)", progress, 0); break; case 6: IGRAPH_PROGRESS("DrL layout (final phase)", 100.0, 0); break; default: IGRAPH_PROGRESS("DrL layout (unknown phase)", 0.0, 0); break; } /* Compute Energies for individual nodes */ update_nodes (); // check to see if we need to free fixed nodes tot_iterations++; if ( tot_iterations >= real_iterations ) real_fixed = false; // **************************************** // AUTOMATIC CONTROL SECTION // **************************************** // STAGE 0: LIQUID if (STAGE == 0) { if ( iterations == 0 ) { start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering liquid stage ..."; } if (iterations < liquid.iterations) { temperature = liquid.temperature; attraction = liquid.attraction; damping_mult = liquid.damping_mult; iterations++; // if ( myid == 0 ) // cout << "." << flush; } else { stop_time = time( NULL ); liquid.time_elapsed = liquid.time_elapsed + (stop_time - start_time); temperature = expansion.temperature; attraction = expansion.attraction; damping_mult = expansion.damping_mult; iterations = 0; // go to next stage STAGE = 1; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering expansion stage ..."; } } // STAGE 1: EXPANSION if (STAGE == 1) { if (iterations < expansion.iterations) { // Play with vars if (attraction > 1) attraction -= .05; if (min_edges > 12) min_edges -= .05; cut_off_length -= cut_rate; if (damping_mult > .1) damping_mult -= .005; iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); expansion.time_elapsed = expansion.time_elapsed + (stop_time - start_time); min_edges = 12; damping_mult = cooldown.damping_mult; STAGE = 2; attraction = cooldown.attraction; temperature = cooldown.temperature; iterations = 0; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering cool-down stage ..."; } } // STAGE 2: Cool down and cluster else if(STAGE==2) { if (iterations < cooldown.iterations) { // Reduce temperature if (temperature > 50) temperature -= 10; // Reduce cut length if (cut_off_length > cut_length_end) cut_off_length -= cut_rate*2; if (min_edges > MIN) min_edges -= .2; //min_edges = 99; iterations++; // if ( myid == 0 ) // cout << "." << flush; } else { stop_time = time( NULL ); cooldown.time_elapsed = cooldown.time_elapsed + (stop_time - start_time); cut_off_length = cut_length_end; temperature = crunch.temperature; damping_mult = crunch.damping_mult; min_edges = MIN; //min_edges = 99; // In other words: no more cutting STAGE = 3; iterations = 0; attraction = crunch.attraction; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering crunch stage ..."; } } // STAGE 3: Crunch else if(STAGE==3) { if (iterations < crunch.iterations) { iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); crunch.time_elapsed = crunch.time_elapsed + (stop_time - start_time); iterations = 0; temperature = simmer.temperature; attraction = simmer.attraction; damping_mult = simmer.damping_mult; min_edges = 99; fineDensity = true; STAGE = 5; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering simmer stage ..."; } } // STAGE 5: Simmer else if( STAGE==5 ) { if (iterations < simmer.iterations) { if (temperature > 50) temperature -= 2; iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); simmer.time_elapsed = simmer.time_elapsed + (stop_time - start_time); STAGE = 6; // if ( myid == 0 ) // cout << "Layout calculation completed in " << // ( liquid.time_elapsed + expansion.time_elapsed + // cooldown.time_elapsed + crunch.time_elapsed + // simmer.time_elapsed ) // << " seconds (not including I/O)." // << endl; } } // STAGE 6: All Done! else if ( STAGE == 6) { /* // output parameters (for debugging) cout << "ReCompute is using the following parameters: "<< endl; cout << "STAGE: " << STAGE << ", iter: " << iterations << ", temp = " << temperature << ", attract = " << attraction << ", damping_mult = " << damping_mult << ", min_edges = " << min_edges << ", cut_off_length = " << cut_off_length << ", fineDensity = " << fineDensity << endl; */ return 0; } // **************************************** // END AUTOMATIC CONTROL SECTION // **************************************** // Still need more recomputation return 1; } // update_nodes -- this function will complete the primary node update // loop in layout's recompute routine. It follows exactly the same // sequence to ensure similarity of parallel layout to the standard layout void graph::update_nodes ( ) { vector node_indices; // node list of nodes currently being updated float old_positions[2*MAX_PROCS]; // positions before update float new_positions[2*MAX_PROCS]; // positions after update bool all_fixed; // check if all nodes are fixed // initial node list consists of 0,1,...,num_procs for ( int i = 0; i < num_procs; i++ ) node_indices.push_back( i ); // next we calculate the number of nodes there would be if the // num_nodes by num_procs schedule grid were perfectly square int square_num_nodes = (int)(num_procs + num_procs*floor ((float)(num_nodes-1)/(float)num_procs )); for ( int i = myid; i < square_num_nodes; i += num_procs ) { // get old positions get_positions ( node_indices, old_positions ); // default new position is old position get_positions ( node_indices, new_positions ); if ( i < num_nodes ) { // advance random sequence according to myid for ( int j = 0; j < 2*myid; j++ ) RNG_UNIF01(); // rand(); // calculate node energy possibilities if ( !(positions[i].fixed && real_fixed) ) update_node_pos ( i, old_positions, new_positions ); // advance random sequence for next iteration for ( unsigned int j = 2*myid; j < 2*(node_indices.size()-1); j++ ) RNG_UNIF01(); // rand(); } else { // advance random sequence according to use by // the other processors for ( unsigned int j = 0; j < 2*(node_indices.size()); j++ ) RNG_UNIF01(); //rand(); } // check if anything was actually updated (e.g. everything was fixed) all_fixed = true; for ( unsigned int j = 0; j < node_indices.size (); j++ ) if ( !(positions [ node_indices[j] ].fixed && real_fixed) ) all_fixed = false; // update positions across processors (if not all fixed) if ( !all_fixed ) { #ifdef MUSE_MPI MPI_Allgather ( &new_positions[2*myid], 2, MPI_FLOAT, new_positions, 2, MPI_FLOAT, MPI_COMM_WORLD ); #endif // update positions (old to new) update_density ( node_indices, old_positions, new_positions ); } /* if ( myid == 0 ) { // output node list (for debugging) for ( unsigned int j = 0; j < node_indices.size(); j++ ) cout << node_indices[j] << " "; cout << endl; } */ // compute node list for next update for ( unsigned int j = 0; j < node_indices.size(); j++ ) node_indices [j] += num_procs; while ( !node_indices.empty() && node_indices.back() >= num_nodes ) node_indices.pop_back ( ); } // update first_add and fine_first_add first_add = false; if ( fineDensity ) fine_first_add = false; } // The get_positions function takes the node_indices list // and returns the corresponding positions in an array. void graph::get_positions ( vector &node_indices, float return_positions[2*MAX_PROCS] ) { // fill positions for(unsigned int i=0; i < node_indices.size(); i++) { return_positions[2*i] = positions[ node_indices[i] ].x; return_positions[2*i+1] = positions[ node_indices[i] ].y; } } // update_node_pos -- this subroutine does the actual work of computing // the new position of a given node. num_act_proc gives the number // of active processes at this level for use by the random number // generators. void graph::update_node_pos ( int node_ind, float old_positions[2*MAX_PROCS], float new_positions[2*MAX_PROCS] ) { float energies[2]; // node energies for possible positions float updated_pos[2][2]; // possible positions float pos_x, pos_y; // old VxOrd parameter float jump_length = .010 * temperature; // subtract old node density_server.Subtract ( positions[node_ind], first_add, fine_first_add, fineDensity ); // compute node energy for old solution energies[0] = Compute_Node_Energy ( node_ind ); // move node to centroid position Solve_Analytic ( node_ind, pos_x, pos_y ); positions[node_ind].x = updated_pos[0][0] = pos_x; positions[node_ind].y = updated_pos[0][1] = pos_y; /* // ouput random numbers (for debugging) int rand_0, rand_1; rand_0 = rand(); rand_1 = rand(); cout << myid << ": " << rand_0 << ", " << rand_1 << endl; */ // Do random method (RAND_MAX is C++ maximum random number) updated_pos[1][0] = updated_pos[0][0] + (.5 - RNG_UNIF01()) * jump_length; updated_pos[1][1] = updated_pos[0][1] + (.5 - RNG_UNIF01()) * jump_length; // compute node energy for random position positions[node_ind].x = updated_pos[1][0]; positions[node_ind].y = updated_pos[1][1]; energies[1] = Compute_Node_Energy ( node_ind ); /* // output update possiblities (debugging): cout << node_ind << ": (" << updated_pos[0][0] << "," << updated_pos[0][1] << "), " << energies[0] << "; (" << updated_pos[1][0] << "," << updated_pos[1][1] << "), " << energies[1] << endl; */ // add back old position positions[node_ind].x = old_positions[2*myid]; positions[node_ind].y = old_positions[2*myid+1]; if ( !fineDensity && !first_add ) density_server.Add ( positions[node_ind], fineDensity ); else if ( !fine_first_add ) density_server.Add ( positions[node_ind], fineDensity ); // choose updated node position with lowest energy if ( energies[0] < energies[1] ) { new_positions[2*myid] = updated_pos[0][0]; new_positions[2*myid+1] = updated_pos[0][1]; positions[node_ind].energy = energies[0]; } else { new_positions[2*myid] = updated_pos[1][0]; new_positions[2*myid+1] = updated_pos[1][1]; positions[node_ind].energy = energies[1]; } } // update_density takes a sequence of node_indices and their positions and // updates the positions by subtracting the old positions and adding the // new positions to the density grid. void graph::update_density ( vector &node_indices, float old_positions[2*MAX_PROCS], float new_positions[2*MAX_PROCS] ) { // go through each node and subtract old position from // density grid before adding new position for ( unsigned int i = 0; i < node_indices.size(); i++ ) { positions[node_indices[i]].x = old_positions[2*i]; positions[node_indices[i]].y = old_positions[2*i+1]; density_server.Subtract ( positions[node_indices[i]], first_add, fine_first_add, fineDensity ); positions[node_indices[i]].x = new_positions[2*i]; positions[node_indices[i]].y = new_positions[2*i+1]; density_server.Add ( positions[node_indices[i]], fineDensity ); } } /******************************************** * Function: Compute_Node_Energy * * Description: Compute the node energy * * This code has been modified from the * * original code by B. Wylie. * *********************************************/ float graph::Compute_Node_Energy( int node_ind ) { /* Want to expand 4th power range of attraction */ float attraction_factor = attraction*attraction* attraction*attraction*2e-2; map ::iterator EI; float x_dis,y_dis; float energy_distance, weight; float node_energy=0; // Add up all connection energies for(EI = neighbors[node_ind].begin(); EI != neighbors[node_ind].end(); ++EI) { // Get edge weight weight = EI->second; // Compute x,y distance x_dis = positions[ node_ind ].x - positions[ EI->first ].x; y_dis = positions[ node_ind ].y - positions[ EI->first ].y; // Energy Distance energy_distance = x_dis*x_dis + y_dis*y_dis; if (STAGE<2) energy_distance *= energy_distance; // In the liquid phase we want to discourage long link distances if (STAGE==0) energy_distance *= energy_distance; node_energy += weight * attraction_factor * energy_distance; } // output effect of density (debugging) //cout << "[before: " << node_energy; // add density node_energy += density_server.GetDensity ( positions[ node_ind ].x, positions[ node_ind ].y, fineDensity ); // after calling density server (debugging) //cout << ", after: " << node_energy << "]" << endl; // return computated energy return node_energy; } /********************************************* * Function: Solve_Analytic * * Description: Compute the node position * * This is a modified version of the function * * originally written by B. Wylie * *********************************************/ void graph::Solve_Analytic( int node_ind, float &pos_x, float &pos_y ) { map ::iterator EI; float total_weight = 0; float x_dis, y_dis,x_cen=0, y_cen=0; float x=0,y=0,dis; float damping,weight; // Sum up all connections for(EI = neighbors[node_ind].begin(); EI != neighbors[node_ind].end(); ++EI) { weight = EI->second; total_weight += weight; x += weight * positions[ EI->first ].x; y += weight * positions[ EI->first ].y; } // Now set node position if (total_weight > 0) { // Compute centriod x_cen = x/total_weight; y_cen = y/total_weight; damping = 1.0 - damping_mult; pos_x = damping*positions[ node_ind ].x + (1.0-damping) * x_cen; pos_y = damping*positions[ node_ind ].y + (1.0-damping) * y_cen; } else { pos_x = positions[ node_ind ].x; pos_y = positions[ node_ind ].y; } // No cut edge flag (?) if (min_edges == 99) return; // Don't cut at end of scale if ( CUT_END >= 39500 ) return; float num_connections = sqrt((double)neighbors[node_ind].size()); float maxLength = 0; map::iterator maxIndex; // Go through nodes edges... cutting if necessary for(EI = maxIndex = neighbors[node_ind].begin(); EI !=neighbors[node_ind].end(); ++EI) { // Check for at least min edges if (neighbors[node_ind].size() < min_edges) continue; x_dis = x_cen - positions[ EI->first ].x; y_dis = y_cen - positions[ EI->first ].y; dis = x_dis*x_dis+y_dis*y_dis; dis *= num_connections; // Store maximum edge if (dis > maxLength) {maxLength = dis; maxIndex=EI;} } // If max length greater than cut_length then cut if (maxLength > cut_off_length) neighbors[ node_ind ].erase( maxIndex ); } // write_coord writes out the coordinate file of the final solutions // void graph::write_coord( const char *file_name ) // { // ofstream coordOUT( file_name ); // if ( !coordOUT ) // { // cout << "Could not open " << file_name << ". Program terminated." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // cout << "Writing out solution to " << file_name << " ..." << endl; // for (unsigned int i = 0; i < positions.size(); i++) { // coordOUT << positions[i].id << "\t" << positions[i].x << "\t" << positions[i].y < >::iterator i; map::iterator j; for ( i = neighbors.begin(); i != neighbors.end(); i++ ) for (j = (i->second).begin(); j != (i->second).end(); j++ ) simOUT << positions[i->first].id << "\t" << positions[j->first].id << "\t" << j->second << endl; simOUT.close(); } */ // get_tot_energy adds up the energy for each node to give an estimate of the // quality of the minimization. float graph::get_tot_energy ( ) { float my_tot_energy, tot_energy; my_tot_energy = 0; for ( int i = myid; i < num_nodes; i += num_procs ) my_tot_energy += positions[i].energy; //vector::iterator i; //for ( i = positions.begin(); i != positions.end(); i++ ) // tot_energy += i->energy; #ifdef MUSE_MPI MPI_Reduce ( &my_tot_energy, &tot_energy, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD ); #else tot_energy = my_tot_energy; #endif return tot_energy; } // The following subroutine draws the graph with possible intermediate // output (int_out is set to 0 if not proc. 0). int_out is the parameter // passed by the user, and coord_file is the .coord file. // void graph::draw_graph ( int int_out, char *coord_file ) // { // // layout graph (with possible intermediate output) // int count_iter = 0, count_file = 1; // char int_coord_file [MAX_FILE_NAME + MAX_INT_LENGTH]; // while ( ReCompute( ) ) // if ( (int_out > 0) && (count_iter == int_out) ) // { // // output intermediate solution // sprintf ( int_coord_file, "%s.%d", coord_file, count_file ); // write_coord ( int_coord_file ); // count_iter = 0; // count_file++; // } // else // count_iter++; // } int graph::draw_graph(igraph_matrix_t *res) { int count_iter=0; while (ReCompute()) { IGRAPH_ALLOW_INTERRUPTION(); count_iter++; } long int n=positions.size(); IGRAPH_CHECK(igraph_matrix_resize(res, n, 2)); for (long int i=0; i #include #include /* * For gcc with _STDINT_H, fill in the PRINTF_INT*_MODIFIER macros, and * do nothing else. On the Mac OS X version of gcc this is _STDINT_H_. */ #if ((defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L) || (defined (__WATCOMC__) && (defined (_STDINT_H_INCLUDED) || __WATCOMC__ >= 1250)) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) )) && !defined (_PSTDINT_H_INCLUDED) #include #define _PSTDINT_H_INCLUDED # ifndef PRINTF_INT64_MODIFIER # define PRINTF_INT64_MODIFIER "ll" # endif # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "l" # endif # ifndef PRINTF_INT16_MODIFIER # define PRINTF_INT16_MODIFIER "h" # endif # ifndef PRINTF_INTMAX_MODIFIER # define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER # endif # ifndef PRINTF_INT64_HEX_WIDTH # define PRINTF_INT64_HEX_WIDTH "16" # endif # ifndef PRINTF_INT32_HEX_WIDTH # define PRINTF_INT32_HEX_WIDTH "8" # endif # ifndef PRINTF_INT16_HEX_WIDTH # define PRINTF_INT16_HEX_WIDTH "4" # endif # ifndef PRINTF_INT8_HEX_WIDTH # define PRINTF_INT8_HEX_WIDTH "2" # endif # ifndef PRINTF_INT64_DEC_WIDTH # define PRINTF_INT64_DEC_WIDTH "20" # endif # ifndef PRINTF_INT32_DEC_WIDTH # define PRINTF_INT32_DEC_WIDTH "10" # endif # ifndef PRINTF_INT16_DEC_WIDTH # define PRINTF_INT16_DEC_WIDTH "5" # endif # ifndef PRINTF_INT8_DEC_WIDTH # define PRINTF_INT8_DEC_WIDTH "3" # endif # ifndef PRINTF_INTMAX_HEX_WIDTH # define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT64_HEX_WIDTH # endif # ifndef PRINTF_INTMAX_DEC_WIDTH # define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT64_DEC_WIDTH # endif /* * Something really weird is going on with Open Watcom. Just pull some of * these duplicated definitions from Open Watcom's stdint.h file for now. */ # if defined (__WATCOMC__) && __WATCOMC__ >= 1250 # if !defined (INT64_C) # define INT64_C(x) (x + (INT64_MAX - INT64_MAX)) # endif # if !defined (UINT64_C) # define UINT64_C(x) (x + (UINT64_MAX - UINT64_MAX)) # endif # if !defined (INT32_C) # define INT32_C(x) (x + (INT32_MAX - INT32_MAX)) # endif # if !defined (UINT32_C) # define UINT32_C(x) (x + (UINT32_MAX - UINT32_MAX)) # endif # if !defined (INT16_C) # define INT16_C(x) (x) # endif # if !defined (UINT16_C) # define UINT16_C(x) (x) # endif # if !defined (INT8_C) # define INT8_C(x) (x) # endif # if !defined (UINT8_C) # define UINT8_C(x) (x) # endif # if !defined (UINT64_MAX) # define UINT64_MAX 18446744073709551615ULL # endif # if !defined (INT64_MAX) # define INT64_MAX 9223372036854775807LL # endif # if !defined (UINT32_MAX) # define UINT32_MAX 4294967295UL # endif # if !defined (INT32_MAX) # define INT32_MAX 2147483647L # endif # if !defined (INTMAX_MAX) # define INTMAX_MAX INT64_MAX # endif # if !defined (INTMAX_MIN) # define INTMAX_MIN INT64_MIN # endif # endif #endif #ifndef _PSTDINT_H_INCLUDED #define _PSTDINT_H_INCLUDED #ifndef SIZE_MAX # define SIZE_MAX (~(size_t)0) #endif /* * Deduce the type assignments from limits.h under the assumption that * integer sizes in bits are powers of 2, and follow the ANSI * definitions. */ #ifndef UINT8_MAX # define UINT8_MAX 0xff #endif #ifndef uint8_t # if (UCHAR_MAX == UINT8_MAX) || defined (S_SPLINT_S) typedef unsigned char uint8_t; # define UINT8_C(v) ((uint8_t) v) # else # error "Platform not supported" # endif #endif #ifndef INT8_MAX # define INT8_MAX 0x7f #endif #ifndef INT8_MIN # define INT8_MIN INT8_C(0x80) #endif #ifndef int8_t # if (SCHAR_MAX == INT8_MAX) || defined (S_SPLINT_S) typedef signed char int8_t; # define INT8_C(v) ((int8_t) v) # else # error "Platform not supported" # endif #endif #ifndef UINT16_MAX # define UINT16_MAX 0xffff #endif #ifndef uint16_t #if (UINT_MAX == UINT16_MAX) || defined (S_SPLINT_S) typedef unsigned int uint16_t; # ifndef PRINTF_INT16_MODIFIER # define PRINTF_INT16_MODIFIER "" # endif # define UINT16_C(v) ((uint16_t) (v)) #elif (USHRT_MAX == UINT16_MAX) typedef unsigned short uint16_t; # define UINT16_C(v) ((uint16_t) (v)) # ifndef PRINTF_INT16_MODIFIER # define PRINTF_INT16_MODIFIER "h" # endif #else #error "Platform not supported" #endif #endif #ifndef INT16_MAX # define INT16_MAX 0x7fff #endif #ifndef INT16_MIN # define INT16_MIN INT16_C(0x8000) #endif #ifndef int16_t #if (INT_MAX == INT16_MAX) || defined (S_SPLINT_S) typedef signed int int16_t; # define INT16_C(v) ((int16_t) (v)) # ifndef PRINTF_INT16_MODIFIER # define PRINTF_INT16_MODIFIER "" # endif #elif (SHRT_MAX == INT16_MAX) typedef signed short int16_t; # define INT16_C(v) ((int16_t) (v)) # ifndef PRINTF_INT16_MODIFIER # define PRINTF_INT16_MODIFIER "h" # endif #else #error "Platform not supported" #endif #endif #ifndef UINT32_MAX # define UINT32_MAX (0xffffffffUL) #endif #ifndef uint32_t #if (ULONG_MAX == UINT32_MAX) || defined (S_SPLINT_S) typedef unsigned long uint32_t; # define UINT32_C(v) v ## UL # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "l" # endif #elif (UINT_MAX == UINT32_MAX) typedef unsigned int uint32_t; # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "" # endif # define UINT32_C(v) v ## U #elif (USHRT_MAX == UINT32_MAX) typedef unsigned short uint32_t; # define UINT32_C(v) ((unsigned short) (v)) # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "" # endif #else #error "Platform not supported" #endif #endif #ifndef INT32_MAX # define INT32_MAX (0x7fffffffL) #endif #ifndef INT32_MIN # define INT32_MIN INT32_C(0x80000000) #endif #ifndef int32_t #if (LONG_MAX == INT32_MAX) || defined (S_SPLINT_S) typedef signed long int32_t; # define INT32_C(v) v ## L # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "l" # endif #elif (INT_MAX == INT32_MAX) typedef signed int int32_t; # define INT32_C(v) v # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "" # endif #elif (SHRT_MAX == INT32_MAX) typedef signed short int32_t; # define INT32_C(v) ((short) (v)) # ifndef PRINTF_INT32_MODIFIER # define PRINTF_INT32_MODIFIER "" # endif #else #error "Platform not supported" #endif #endif /* * The macro stdint_int64_defined is temporarily used to record * whether or not 64 integer support is available. It must be * defined for any 64 integer extensions for new platforms that are * added. */ #undef stdint_int64_defined #if (defined(__STDC__) && defined(__STDC_VERSION__)) || defined (S_SPLINT_S) # if (__STDC__ && __STDC_VERSION >= 199901L) || defined (S_SPLINT_S) # define stdint_int64_defined typedef long long int64_t; typedef unsigned long long uint64_t; # define UINT64_C(v) v ## ULL # define INT64_C(v) v ## LL # ifndef PRINTF_INT64_MODIFIER # define PRINTF_INT64_MODIFIER "ll" # endif # endif #endif #if !defined (stdint_int64_defined) # if defined(__GNUC__) # define stdint_int64_defined __extension__ typedef long long int64_t; __extension__ typedef unsigned long long uint64_t; # define UINT64_C(v) v ## ULL # define INT64_C(v) v ## LL # ifndef PRINTF_INT64_MODIFIER # define PRINTF_INT64_MODIFIER "ll" # endif # elif defined(__MWERKS__) || defined (__SUNPRO_C) || defined (__SUNPRO_CC) || defined (__APPLE_CC__) || defined (_LONG_LONG) || defined (_CRAYC) || defined (S_SPLINT_S) # define stdint_int64_defined typedef long long int64_t; typedef unsigned long long uint64_t; # define UINT64_C(v) v ## ULL # define INT64_C(v) v ## LL # ifndef PRINTF_INT64_MODIFIER # define PRINTF_INT64_MODIFIER "ll" # endif # elif (defined(__WATCOMC__) && defined(__WATCOM_INT64__)) || (defined(_MSC_VER) && _INTEGRAL_MAX_BITS >= 64) || (defined (__BORLANDC__) && __BORLANDC__ > 0x460) || defined (__alpha) || defined (__DECC) # define stdint_int64_defined typedef __int64 int64_t; typedef unsigned __int64 uint64_t; # define UINT64_C(v) v ## UI64 # define INT64_C(v) v ## I64 # ifndef PRINTF_INT64_MODIFIER # define PRINTF_INT64_MODIFIER "I64" # endif # endif #endif #if !defined (LONG_LONG_MAX) && defined (INT64_C) # define LONG_LONG_MAX INT64_C (9223372036854775807) #endif #ifndef ULONG_LONG_MAX # define ULONG_LONG_MAX UINT64_C (18446744073709551615) #endif #if !defined (INT64_MAX) && defined (INT64_C) # define INT64_MAX INT64_C (9223372036854775807) #endif #if !defined (INT64_MIN) && defined (INT64_C) # define INT64_MIN INT64_C (-9223372036854775808) #endif #if !defined (UINT64_MAX) && defined (INT64_C) # define UINT64_MAX UINT64_C (18446744073709551615) #endif /* * Width of hexadecimal for number field. */ #ifndef PRINTF_INT64_HEX_WIDTH # define PRINTF_INT64_HEX_WIDTH "16" #endif #ifndef PRINTF_INT32_HEX_WIDTH # define PRINTF_INT32_HEX_WIDTH "8" #endif #ifndef PRINTF_INT16_HEX_WIDTH # define PRINTF_INT16_HEX_WIDTH "4" #endif #ifndef PRINTF_INT8_HEX_WIDTH # define PRINTF_INT8_HEX_WIDTH "2" #endif #ifndef PRINTF_INT64_DEC_WIDTH # define PRINTF_INT64_DEC_WIDTH "20" #endif #ifndef PRINTF_INT32_DEC_WIDTH # define PRINTF_INT32_DEC_WIDTH "10" #endif #ifndef PRINTF_INT16_DEC_WIDTH # define PRINTF_INT16_DEC_WIDTH "5" #endif #ifndef PRINTF_INT8_DEC_WIDTH # define PRINTF_INT8_DEC_WIDTH "3" #endif /* * Ok, lets not worry about 128 bit integers for now. Moore's law says * we don't need to worry about that until about 2040 at which point * we'll have bigger things to worry about. */ #ifdef stdint_int64_defined typedef int64_t intmax_t; typedef uint64_t uintmax_t; # define INTMAX_MAX INT64_MAX # define INTMAX_MIN INT64_MIN # define UINTMAX_MAX UINT64_MAX # define UINTMAX_C(v) UINT64_C(v) # define INTMAX_C(v) INT64_C(v) # ifndef PRINTF_INTMAX_MODIFIER # define PRINTF_INTMAX_MODIFIER PRINTF_INT64_MODIFIER # endif # ifndef PRINTF_INTMAX_HEX_WIDTH # define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT64_HEX_WIDTH # endif # ifndef PRINTF_INTMAX_DEC_WIDTH # define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT64_DEC_WIDTH # endif #else typedef int32_t intmax_t; typedef uint32_t uintmax_t; # define INTMAX_MAX INT32_MAX # define UINTMAX_MAX UINT32_MAX # define UINTMAX_C(v) UINT32_C(v) # define INTMAX_C(v) INT32_C(v) # ifndef PRINTF_INTMAX_MODIFIER # define PRINTF_INTMAX_MODIFIER PRINTF_INT32_MODIFIER # endif # ifndef PRINTF_INTMAX_HEX_WIDTH # define PRINTF_INTMAX_HEX_WIDTH PRINTF_INT32_HEX_WIDTH # endif # ifndef PRINTF_INTMAX_DEC_WIDTH # define PRINTF_INTMAX_DEC_WIDTH PRINTF_INT32_DEC_WIDTH # endif #endif /* * Because this file currently only supports platforms which have * precise powers of 2 as bit sizes for the default integers, the * least definitions are all trivial. Its possible that a future * version of this file could have different definitions. */ #ifndef stdint_least_defined typedef int8_t int_least8_t; typedef uint8_t uint_least8_t; typedef int16_t int_least16_t; typedef uint16_t uint_least16_t; typedef int32_t int_least32_t; typedef uint32_t uint_least32_t; # define PRINTF_LEAST32_MODIFIER PRINTF_INT32_MODIFIER # define PRINTF_LEAST16_MODIFIER PRINTF_INT16_MODIFIER # define UINT_LEAST8_MAX UINT8_MAX # define INT_LEAST8_MAX INT8_MAX # define UINT_LEAST16_MAX UINT16_MAX # define INT_LEAST16_MAX INT16_MAX # define UINT_LEAST32_MAX UINT32_MAX # define INT_LEAST32_MAX INT32_MAX # define INT_LEAST8_MIN INT8_MIN # define INT_LEAST16_MIN INT16_MIN # define INT_LEAST32_MIN INT32_MIN # ifdef stdint_int64_defined typedef int64_t int_least64_t; typedef uint64_t uint_least64_t; # define PRINTF_LEAST64_MODIFIER PRINTF_INT64_MODIFIER # define UINT_LEAST64_MAX UINT64_MAX # define INT_LEAST64_MAX INT64_MAX # define INT_LEAST64_MIN INT64_MIN # endif #endif #undef stdint_least_defined /* * The ANSI C committee pretending to know or specify anything about * performance is the epitome of misguided arrogance. The mandate of * this file is to *ONLY* ever support that absolute minimum * definition of the fast integer types, for compatibility purposes. * No extensions, and no attempt to suggest what may or may not be a * faster integer type will ever be made in this file. Developers are * warned to stay away from these types when using this or any other * stdint.h. */ typedef int_least8_t int_fast8_t; typedef uint_least8_t uint_fast8_t; typedef int_least16_t int_fast16_t; typedef uint_least16_t uint_fast16_t; typedef int_least32_t int_fast32_t; typedef uint_least32_t uint_fast32_t; #define UINT_FAST8_MAX UINT_LEAST8_MAX #define INT_FAST8_MAX INT_LEAST8_MAX #define UINT_FAST16_MAX UINT_LEAST16_MAX #define INT_FAST16_MAX INT_LEAST16_MAX #define UINT_FAST32_MAX UINT_LEAST32_MAX #define INT_FAST32_MAX INT_LEAST32_MAX #define INT_FAST8_MIN INT_LEAST8_MIN #define INT_FAST16_MIN INT_LEAST16_MIN #define INT_FAST32_MIN INT_LEAST32_MIN #ifdef stdint_int64_defined typedef int_least64_t int_fast64_t; typedef uint_least64_t uint_fast64_t; # define UINT_FAST64_MAX UINT_LEAST64_MAX # define INT_FAST64_MAX INT_LEAST64_MAX # define INT_FAST64_MIN INT_LEAST64_MIN #endif #undef stdint_int64_defined /* * Whatever piecemeal, per compiler thing we can do about the wchar_t * type limits. */ #if defined(__WATCOMC__) || defined(_MSC_VER) || defined (__GNUC__) # include # ifndef WCHAR_MIN # define WCHAR_MIN 0 # endif # ifndef WCHAR_MAX # define WCHAR_MAX ((wchar_t)-1) # endif #endif /* * Whatever piecemeal, per compiler/platform thing we can do about the * (u)intptr_t types and limits. */ #if defined (_MSC_VER) && defined (_UINTPTR_T_DEFINED) # define STDINT_H_UINTPTR_T_DEFINED #endif #ifndef STDINT_H_UINTPTR_T_DEFINED # if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) || defined (_WIN64) # define stdint_intptr_bits 64 # elif defined (__WATCOMC__) || defined (__TURBOC__) # if defined(__TINY__) || defined(__SMALL__) || defined(__MEDIUM__) # define stdint_intptr_bits 16 # else # define stdint_intptr_bits 32 # endif # elif defined (__i386__) || defined (_WIN32) || defined (WIN32) # define stdint_intptr_bits 32 # elif defined (__INTEL_COMPILER) /* TODO -- what will Intel do about x86-64? */ # endif # ifdef stdint_intptr_bits # define stdint_intptr_glue3_i(a,b,c) a##b##c # define stdint_intptr_glue3(a,b,c) stdint_intptr_glue3_i(a,b,c) # ifndef PRINTF_INTPTR_MODIFIER # define PRINTF_INTPTR_MODIFIER stdint_intptr_glue3(PRINTF_INT,stdint_intptr_bits,_MODIFIER) # endif # ifndef PTRDIFF_MAX # define PTRDIFF_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) # endif # ifndef PTRDIFF_MIN # define PTRDIFF_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) # endif # ifndef UINTPTR_MAX # define UINTPTR_MAX stdint_intptr_glue3(UINT,stdint_intptr_bits,_MAX) # endif # ifndef INTPTR_MAX # define INTPTR_MAX stdint_intptr_glue3(INT,stdint_intptr_bits,_MAX) # endif # ifndef INTPTR_MIN # define INTPTR_MIN stdint_intptr_glue3(INT,stdint_intptr_bits,_MIN) # endif # ifndef INTPTR_C # define INTPTR_C(x) stdint_intptr_glue3(INT,stdint_intptr_bits,_C)(x) # endif # ifndef UINTPTR_C # define UINTPTR_C(x) stdint_intptr_glue3(UINT,stdint_intptr_bits,_C)(x) # endif typedef stdint_intptr_glue3(uint,stdint_intptr_bits,_t) uintptr_t; typedef stdint_intptr_glue3( int,stdint_intptr_bits,_t) intptr_t; # else /* TODO -- This following is likely wrong for some platforms, and does nothing for the definition of uintptr_t. */ typedef ptrdiff_t intptr_t; # endif # define STDINT_H_UINTPTR_T_DEFINED #endif /* * Assumes sig_atomic_t is signed and we have a 2s complement machine. */ #ifndef SIG_ATOMIC_MAX # define SIG_ATOMIC_MAX ((((sig_atomic_t) 1) << (sizeof (sig_atomic_t)*CHAR_BIT-1)) - 1) #endif #endif #if defined (__TEST_PSTDINT_FOR_CORRECTNESS) /* * Please compile with the maximum warning settings to make sure macros are not * defined more than once. */ #include #include #include #define glue3_aux(x,y,z) x ## y ## z #define glue3(x,y,z) glue3_aux(x,y,z) #define DECLU(bits) glue3(uint,bits,_t) glue3(u,bits,=) glue3(UINT,bits,_C) (0); #define DECLI(bits) glue3(int,bits,_t) glue3(i,bits,=) glue3(INT,bits,_C) (0); #define DECL(us,bits) glue3(DECL,us,) (bits) #define TESTUMAX(bits) glue3(u,bits,=) glue3(~,u,bits); if (glue3(UINT,bits,_MAX) glue3(!=,u,bits)) printf ("Something wrong with UINT%d_MAX\n", bits) int main () { DECL(I,8) DECL(U,8) DECL(I,16) DECL(U,16) DECL(I,32) DECL(U,32) #ifdef INT64_MAX DECL(I,64) DECL(U,64) #endif intmax_t imax = INTMAX_C(0); uintmax_t umax = UINTMAX_C(0); char str0[256], str1[256]; sprintf (str0, "%d %x\n", 0, ~0); sprintf (str1, "%d %x\n", i8, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with i8 : %s\n", str1); sprintf (str1, "%u %x\n", u8, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with u8 : %s\n", str1); sprintf (str1, "%d %x\n", i16, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with i16 : %s\n", str1); sprintf (str1, "%u %x\n", u16, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with u16 : %s\n", str1); sprintf (str1, "%" PRINTF_INT32_MODIFIER "d %x\n", i32, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with i32 : %s\n", str1); sprintf (str1, "%" PRINTF_INT32_MODIFIER "u %x\n", u32, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with u32 : %s\n", str1); #ifdef INT64_MAX sprintf (str1, "%" PRINTF_INT64_MODIFIER "d %x\n", i64, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with i64 : %s\n", str1); #endif sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "d %x\n", imax, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with imax : %s\n", str1); sprintf (str1, "%" PRINTF_INTMAX_MODIFIER "u %x\n", umax, ~0); if (0 != strcmp (str0, str1)) printf ("Something wrong with umax : %s\n", str1); TESTUMAX(8); TESTUMAX(16); TESTUMAX(32); #ifdef INT64_MAX TESTUMAX(64); #endif return EXIT_SUCCESS; } #endif igraph/src/igraph_estack.c0000644000175100001440000000402113431000472015270 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_estack.h" int igraph_estack_init(igraph_estack_t *s, long int setsize, long int stacksize) { IGRAPH_CHECK(igraph_vector_bool_init(&s->isin, setsize)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &s->isin); IGRAPH_CHECK(igraph_stack_long_init(&s->stack, stacksize)); IGRAPH_FINALLY_CLEAN(1); return 0; } void igraph_estack_destroy(igraph_estack_t *s) { igraph_stack_long_destroy(&s->stack); igraph_vector_bool_destroy(&s->isin); } int igraph_estack_push(igraph_estack_t *s, long int elem) { if ( !VECTOR(s->isin)[elem] ) { IGRAPH_CHECK(igraph_stack_long_push(&s->stack, elem)); VECTOR(s->isin)[elem] = 1; } return 0; } long int igraph_estack_pop(igraph_estack_t *s) { long int elem=igraph_stack_long_pop(&s->stack); VECTOR(s->isin)[elem] = 0; return elem; } igraph_bool_t igraph_estack_iselement(const igraph_estack_t *s, long int elem) { return VECTOR(s->isin)[elem]; } long int igraph_estack_size(const igraph_estack_t *s) { return igraph_stack_long_size(&s->stack); } #ifndef USING_R int igraph_estack_print(const igraph_estack_t *s) { return igraph_stack_long_print(&s->stack); } #endif igraph/src/bigint.c0000644000175100001440000002130513431000472013744 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "bigint.h" #include "igraph_error.h" #include "igraph_memory.h" int igraph_biguint_init(igraph_biguint_t *b) { IGRAPH_CHECK(igraph_vector_limb_init(&b->v, IGRAPH_BIGUINT_DEFAULT_SIZE)); igraph_vector_limb_clear(&b->v); return 0; } void igraph_biguint_destroy(igraph_biguint_t *b) { igraph_vector_limb_destroy(&b->v); } int igraph_biguint_copy(igraph_biguint_t *to, igraph_biguint_t *from) { return igraph_vector_limb_copy(&to->v, &from->v); } int igraph_biguint_extend(igraph_biguint_t *b, limb_t l) { return igraph_vector_limb_push_back(&b->v, l); } int igraph_biguint_size(igraph_biguint_t *b) { return (int) igraph_vector_limb_size(&b->v); } int igraph_biguint_resize(igraph_biguint_t *b, int newlength) { int origlen=igraph_biguint_size(b); IGRAPH_CHECK(igraph_vector_limb_resize(&b->v, newlength)); if (newlength > origlen) { memset(VECTOR(b->v) + origlen, 0, (size_t) (newlength-origlen) * sizeof(limb_t)); } return 0; } int igraph_biguint_reserve(igraph_biguint_t *b, int length) { return igraph_vector_limb_reserve(&b->v, length); } int igraph_biguint_zero(igraph_biguint_t *b) { igraph_vector_limb_clear(&b->v); return 0; } int igraph_biguint_set_limb(igraph_biguint_t *b, int value) { IGRAPH_CHECK(igraph_vector_limb_resize(&b->v, 1)); VECTOR(b->v)[0]=(limb_t) value; return 0; } igraph_real_t igraph_biguint_get(igraph_biguint_t *b) { int size=igraph_biguint_size(b); int i; double val=VECTOR(b->v)[size-1]; if (size==0) { return 0.0; } for (i=size-2; i>=0; i--) { val = val * LIMBMASK + VECTOR(b->v)[i]; if (!IGRAPH_FINITE(val)) break; } return val; } int igraph_biguint_compare_limb(igraph_biguint_t *b, limb_t l) { int n=igraph_biguint_size(b); return bn_cmp_limb(VECTOR(b->v), l, (count_t) n); } int igraph_biguint_compare(igraph_biguint_t *left, igraph_biguint_t *right) { /* bn_cmp requires the two numbers to have the same number of limbs, so we do this partially by hand here */ int size_left=igraph_biguint_size(left); int size_right=igraph_biguint_size(right); while (size_left > size_right) { if (VECTOR(left->v)[--size_left] > 0) { return +1; } } while (size_right > size_left) { if (VECTOR(right->v)[--size_right] > 0) { return -1; } } return bn_cmp( VECTOR(left->v), VECTOR(right->v), (count_t) size_right ); } igraph_bool_t igraph_biguint_equal(igraph_biguint_t *left, igraph_biguint_t *right) { return 0 == igraph_biguint_compare(left, right); } igraph_bool_t igraph_biguint_bigger(igraph_biguint_t *left, igraph_biguint_t *right) { return 0 < igraph_biguint_compare(left, right); } igraph_bool_t igraph_biguint_biggerorequal(igraph_biguint_t *left, igraph_biguint_t *right) { return 0 <= igraph_biguint_compare(left, right); } int igraph_biguint_inc(igraph_biguint_t *res, igraph_biguint_t *b) { return igraph_biguint_add_limb(res, b, 1); } int igraph_biguint_dec(igraph_biguint_t *res, igraph_biguint_t *b) { return igraph_biguint_sub_limb(res, b, 1); } int igraph_biguint_add_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l) { int nlimb=igraph_biguint_size(b); limb_t carry; if (res != b) { IGRAPH_CHECK(igraph_biguint_resize(res, nlimb)); } carry=bn_add_limb( VECTOR(res->v), VECTOR(b->v), l, (count_t) nlimb); if (carry) { IGRAPH_CHECK(igraph_biguint_extend(res, carry)); } return 0; } int igraph_biguint_sub_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l) { int nlimb=igraph_biguint_size(b); if (res != b) { IGRAPH_CHECK(igraph_biguint_resize(res, nlimb)); } /* We don't check the return value here */ bn_sub_limb( VECTOR(res->v), VECTOR(b->v), l, (count_t) nlimb); return 0; } int igraph_biguint_mul_limb(igraph_biguint_t *res, igraph_biguint_t *b, limb_t l) { int nlimb=igraph_biguint_size(b); limb_t carry; if (res!= b) { IGRAPH_CHECK(igraph_biguint_resize(res, nlimb)); } carry=bn_mul_limb( VECTOR(res->v), VECTOR(b->v), l, (count_t) nlimb); if (carry) { IGRAPH_CHECK(igraph_biguint_extend(res, carry)); } return 0; } int igraph_biguint_add(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right) { int size_left=igraph_biguint_size(left); int size_right=igraph_biguint_size(right); limb_t carry; if (size_left > size_right) { IGRAPH_CHECK(igraph_biguint_resize(right, size_left)); size_right=size_left; } else if (size_left < size_right) { IGRAPH_CHECK(igraph_biguint_resize(left, size_right)); size_left=size_right; } IGRAPH_CHECK(igraph_biguint_resize(res, size_left)); carry=bn_add( VECTOR(res->v), VECTOR(left->v), VECTOR(right->v), (count_t) size_left); if (carry) { IGRAPH_CHECK(igraph_biguint_extend(res, carry)); } return 0; } int igraph_biguint_sub(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right) { int size_left=igraph_biguint_size(left); int size_right=igraph_biguint_size(right); if (size_left > size_right) { IGRAPH_CHECK(igraph_biguint_resize(right, size_left)); size_right=size_left; } else if (size_left < size_right) { IGRAPH_CHECK(igraph_biguint_resize(left, size_right)); size_left=size_right; } IGRAPH_CHECK(igraph_biguint_resize(res, size_left)); /* We don't check return value, left should not be smaller than right! */ bn_sub( VECTOR(res->v), VECTOR(left->v), VECTOR(right->v), (count_t) size_left); return 0; } int igraph_biguint_mul(igraph_biguint_t *res, igraph_biguint_t *left, igraph_biguint_t *right) { int size_left=igraph_biguint_size(left); int size_right=igraph_biguint_size(right); if (size_left > size_right) { IGRAPH_CHECK(igraph_biguint_resize(right, size_left)); size_right=size_left; } else if (size_left < size_right) { IGRAPH_CHECK(igraph_biguint_resize(left, size_right)); size_left=size_right; } IGRAPH_CHECK(igraph_biguint_resize(res, 2*size_left)); bn_mul( VECTOR(res->v), VECTOR(left->v), VECTOR(right->v), (count_t) size_left ); return 0; } int igraph_biguint_div(igraph_biguint_t *q, igraph_biguint_t *r, igraph_biguint_t *u, igraph_biguint_t *v) { int ret; int size_q=igraph_biguint_size(q); int size_r=igraph_biguint_size(r); int size_u=igraph_biguint_size(u); int size_v=igraph_biguint_size(v); int size_qru = size_q > size_r ? size_q : size_r; size_qru = size_u > size_qru ? size_u : size_qru; if (size_q < size_qru) { IGRAPH_CHECK(igraph_biguint_resize(q, size_qru)); } if (size_r < size_qru) { IGRAPH_CHECK(igraph_biguint_resize(r, size_qru)); } if (size_u < size_qru) { IGRAPH_CHECK(igraph_biguint_resize(u, size_qru)); } ret=bn_div( VECTOR(q->v), VECTOR(r->v), VECTOR(u->v), VECTOR(v->v), (count_t) size_qru, (count_t) size_v ); if (ret) { IGRAPH_ERROR("Bigint division by zero", IGRAPH_EDIVZERO); } return 0; } #ifndef USING_R int igraph_biguint_print(igraph_biguint_t *b) { return igraph_biguint_fprint(b, stdout); } #endif int igraph_biguint_fprint(igraph_biguint_t *b, FILE *file) { /* It is hard to control memory allocation for the bn2d function, so we do our own version */ int n=igraph_biguint_size(b); long int size=12*n+1; igraph_biguint_t tmp; char *dst; limb_t r; /* Zero? */ if (!bn_cmp_limb(VECTOR(b->v), 0, (count_t) n)) { fputs("0", file); return 0; } IGRAPH_CHECK(igraph_biguint_copy(&tmp, b)); IGRAPH_FINALLY(igraph_biguint_destroy, &tmp); dst=igraph_Calloc(size, char); if (!dst) { IGRAPH_ERROR("Cannot print big number", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, dst); size--; dst[size]='\0'; while (0 != bn_cmp_limb(VECTOR(tmp.v), 0, (count_t) n)) { r=bn_div_limb(VECTOR(tmp.v), VECTOR(tmp.v), 10, (count_t) n); dst[--size] = '0' + (char) r; } fputs(&dst[size], file); igraph_Free(dst); igraph_biguint_destroy(&tmp); IGRAPH_FINALLY_CLEAN(2); return 0; } igraph/src/layout.c0000644000175100001440000023023513431000472014011 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2003-2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_layout.h" #include "igraph_random.h" #include "igraph_memory.h" #include "igraph_iterators.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #include "igraph_paths.h" #include "igraph_structural.h" #include "igraph_visitor.h" #include "igraph_topology.h" #include "igraph_components.h" #include "igraph_types_internal.h" #include "igraph_dqueue.h" #include "igraph_arpack.h" #include "igraph_blas.h" #include "igraph_centrality.h" #include "igraph_eigen.h" #include "config.h" #include #include "igraph_math.h" /** * \section about_layouts * * Layout generator functions (or at least most of them) try to place the * vertices and edges of a graph on a 2D plane or in 3D space in a way * which visually pleases the human eye. * * They take a graph object and a number of parameters as arguments * and return an \type igraph_matrix_t, in which each row gives the * coordinates of a vertex. */ /** * \ingroup layout * \function igraph_layout_random * \brief Places the vertices uniform randomly on a plane. * * \param graph Pointer to an initialized graph object. * \param res Pointer to an initialized matrix object. This will * contain the result and will be resized as needed. * \return Error code. The current implementation always returns with * success. * * Time complexity: O(|V|), the * number of vertices. */ int igraph_layout_random(const igraph_t *graph, igraph_matrix_t *res) { long int no_of_nodes=igraph_vcount(graph); long int i; IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 2)); RNG_BEGIN(); for (i=0; i * * Time complexity: O(|V|), the number of vertices. */ int igraph_layout_random_3d(const igraph_t *graph, igraph_matrix_t *res) { long int no_of_nodes=igraph_vcount(graph); long int i; IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 3)); RNG_BEGIN(); for (i=0; i * The algorithm was described in the following paper: * Distributing many points on a sphere by E.B. Saff and * A.B.J. Kuijlaars, \emb Mathematical Intelligencer \eme 19.1 (1997) * 5--11. * * \param graph Pointer to an initialized graph object. * \param res Pointer to an initialized matrix object. This will * contain the result and will be resized as needed. * \return Error code. The current implementation always returns with * success. * * Added in version 0.2. * * Time complexity: O(|V|), the number of vertices in the graph. */ int igraph_layout_sphere(const igraph_t *graph, igraph_matrix_t *res) { long int no_of_nodes=igraph_vcount(graph); long int i; igraph_real_t h; IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 3)); if (no_of_nodes != 0) { MATRIX(*res, 0, 0)=M_PI; MATRIX(*res, 0, 1)=0; } for (i=1; i=2) { MATRIX(*res, no_of_nodes-1, 0)=0; MATRIX(*res, no_of_nodes-1, 1)=0; } for (i=0; i * This is a layout generator similar to the Large Graph Layout * algorithm and program * (http://lgl.sourceforge.net/). But unlike LGL, this * version uses a Fruchterman-Reingold style simulated annealing * algorithm for placing the vertices. The speedup is achieved by * placing the vertices on a grid and calculating the repulsion only * for vertices which are closer to each other than a limit. * * \param graph The (initialized) graph object to place. * \param res Pointer to an initialized matrix object to hold the * result. It will be resized if needed. * \param maxit The maximum number of cooling iterations to perform * for each layout step. A reasonable default is 150. * \param maxdelta The maximum length of the move allowed for a vertex * in a single iteration. A reasonable default is the number of * vertices. * \param area This parameter gives the area of the square on which * the vertices will be placed. A reasonable default value is the * number of vertices squared. * \param coolexp The cooling exponent. A reasonable default value is * 1.5. * \param repulserad Determines the radius at which vertex-vertex * repulsion cancels out attraction of adjacent vertices. A * reasonable default value is \p area times the number of vertices. * \param cellsize The size of the grid cells, one side of the * square. A reasonable default value is the fourth root of * \p area (or the square root of the number of vertices if \p area * is also left at its default value). * \param proot The root vertex, this is placed first, its neighbors * in the first iteration, second neighbors in the second, etc. If * negative then a random vertex is chosen. * \return Error code. * * Added in version 0.2. * * Time complexity: ideally O(dia*maxit*(|V|+|E|)), |V| is the number * of vertices, * dia is the diameter of the graph, worst case complexity is still * O(dia*maxit*(|V|^2+|E|)), this is the case when all vertices happen to be * in the same grid cell. */ int igraph_layout_lgl(const igraph_t *graph, igraph_matrix_t *res, igraph_integer_t maxit, igraph_real_t maxdelta, igraph_real_t area, igraph_real_t coolexp, igraph_real_t repulserad, igraph_real_t cellsize, igraph_integer_t proot) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_t mst; long int root; long int no_of_layers, actlayer=0; igraph_vector_t vids; igraph_vector_t layers; igraph_vector_t parents; igraph_vector_t edges; igraph_2dgrid_t grid; igraph_vector_t eids; igraph_vector_t forcex; igraph_vector_t forcey; igraph_real_t frk=sqrt(area/no_of_nodes); igraph_real_t H_n=0; IGRAPH_CHECK(igraph_minimum_spanning_tree_unweighted(graph, &mst)); IGRAPH_FINALLY(igraph_destroy, &mst); IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 2)); /* Determine the root vertex, random pick right now */ if (proot < 0) { root=RNG_INTEGER(0, no_of_nodes-1); } else { root=proot; } /* Assign the layers */ IGRAPH_VECTOR_INIT_FINALLY(&vids, 0); IGRAPH_VECTOR_INIT_FINALLY(&layers, 0); IGRAPH_VECTOR_INIT_FINALLY(&parents, 0); IGRAPH_CHECK(igraph_i_bfs(&mst, (igraph_integer_t) root, IGRAPH_ALL, &vids, &layers, &parents)); no_of_layers=igraph_vector_size(&layers)-1; /* We don't need the mst any more */ igraph_destroy(&mst); igraph_empty(&mst, 0, IGRAPH_UNDIRECTED); /* to make finalization work */ IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges)); IGRAPH_VECTOR_INIT_FINALLY(&eids, 0); IGRAPH_VECTOR_INIT_FINALLY(&forcex, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&forcey, no_of_nodes); /* Place the vertices randomly */ IGRAPH_CHECK(igraph_layout_random(graph, res)); igraph_matrix_scale(res, 1e6); /* This is the grid for calculating the vertices near to a given vertex */ IGRAPH_CHECK(igraph_2dgrid_init(&grid, res, -sqrt(area/M_PI),sqrt(area/M_PI), cellsize, -sqrt(area/M_PI),sqrt(area/M_PI), cellsize)); IGRAPH_FINALLY(igraph_2dgrid_destroy, &grid); /* Place the root vertex */ igraph_2dgrid_add(&grid, root, 0, 0); for (actlayer=1; actlayer epsilon) { long int jj; igraph_real_t t=maxdelta*pow((maxit-it)/(double)maxit, coolexp); long int vid, nei; IGRAPH_PROGRESS("Large graph layout", 100.0*((actlayer-1.0)/(no_of_layers-1.0)+((float)it)/(maxit*(no_of_layers-1.0))), 0); /* init */ igraph_vector_null(&forcex); igraph_vector_null(&forcey); maxchange=0; /* attractive "forces" along the edges */ for (jj=0; jj t) { ded=t/ded; fx*=ded; fy *=ded; } igraph_2dgrid_move(&grid, vvid, fx, fy); if (fx > maxchange) { maxchange=fx; } if (fy > maxchange) { maxchange=fy; } } it++; /* printf("%li iterations, maxchange: %f\n", it, (double)maxchange); */ } } IGRAPH_PROGRESS("Large graph layout", 100.0, 0); igraph_destroy(&mst); igraph_vector_destroy(&vids); igraph_vector_destroy(&layers); igraph_vector_destroy(&parents); igraph_vector_destroy(&edges); igraph_2dgrid_destroy(&grid); igraph_vector_destroy(&eids); igraph_vector_destroy(&forcex); igraph_vector_destroy(&forcey); IGRAPH_FINALLY_CLEAN(9); return 0; } /* Internal structure for Reingold-Tilford layout */ struct igraph_i_reingold_tilford_vertex { long int parent; /* Parent node index */ long int level; /* Level of the node */ igraph_real_t offset; /* X offset from parent node */ long int left_contour; /* Next left node of the contour of the subtree rooted at this node */ long int right_contour; /* Next right node of the contour of the subtree rooted at this node */ igraph_real_t offset_follow_lc; /* X offset when following the left contour */ igraph_real_t offset_follow_rc; /* X offset when following the right contour */ }; int igraph_i_layout_reingold_tilford_postorder(struct igraph_i_reingold_tilford_vertex *vdata, long int node, long int vcount); int igraph_i_layout_reingold_tilford_calc_coords(struct igraph_i_reingold_tilford_vertex *vdata, igraph_matrix_t *res, long int node, long int vcount, igraph_real_t xpos); int igraph_i_layout_reingold_tilford(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, long int root); int igraph_i_layout_reingold_tilford(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, long int root) { long int no_of_nodes=igraph_vcount(graph); long int i, n, j; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; igraph_adjlist_t allneis; igraph_vector_int_t *neis; struct igraph_i_reingold_tilford_vertex *vdata; IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, 2)); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, mode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); vdata=igraph_Calloc(no_of_nodes, struct igraph_i_reingold_tilford_vertex); if (vdata==0) { IGRAPH_ERROR("igraph_layout_reingold_tilford failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vdata); for (i=0; i= 0) { continue; } MATRIX(*res, neighbor, 1)=actdist+1; IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor)); IGRAPH_CHECK(igraph_dqueue_push(&q, actdist+1)); vdata[neighbor].parent = actnode; vdata[neighbor].level = actdist+1; } } /* Step 2: postorder tree traversal, determines the appropriate X * offsets for every node */ igraph_i_layout_reingold_tilford_postorder(vdata, root, no_of_nodes); /* Step 3: calculate real coordinates based on X offsets */ igraph_i_layout_reingold_tilford_calc_coords(vdata, res, root, no_of_nodes, vdata[root].offset); igraph_dqueue_destroy(&q); igraph_adjlist_destroy(&allneis); igraph_free(vdata); IGRAPH_FINALLY_CLEAN(3); IGRAPH_PROGRESS("Reingold-Tilford tree layout", 100.0, NULL); return 0; } int igraph_i_layout_reingold_tilford_calc_coords(struct igraph_i_reingold_tilford_vertex *vdata, igraph_matrix_t *res, long int node, long int vcount, igraph_real_t xpos) { long int i; MATRIX(*res, node, 0) = xpos; for (i=0; i= 0) { /* Now we will follow the right contour of leftroot and the * left contour of the subtree rooted at i */ long lnode, rnode; igraph_real_t loffset, roffset, minsep, rootsep; lnode = leftroot; rnode = i; minsep = 1; rootsep = vdata[leftroot].offset + minsep; loffset = 0; roffset = minsep; /*printf(" Contour: [%d, %d], offsets: [%lf, %lf], rootsep: %lf\n", lnode, rnode, loffset, roffset, rootsep);*/ while ((lnode >= 0) && (rnode >= 0)) { /* Step to the next level on the right contour of the left subtree */ if (vdata[lnode].right_contour >= 0) { loffset += vdata[lnode].offset_follow_rc; lnode = vdata[lnode].right_contour; } else { /* Left subtree ended there. The right contour of the left subtree * will continue to the next step on the right subtree. */ if (vdata[rnode].left_contour >= 0) { /*printf(" Left subtree ended, continuing left subtree's left and right contour on right subtree (node %ld)\n", vdata[rnode].left_contour);*/ vdata[lnode].left_contour = vdata[rnode].left_contour; vdata[lnode].right_contour = vdata[rnode].left_contour; vdata[lnode].offset_follow_lc = vdata[lnode].offset_follow_rc = (roffset-loffset)+vdata[rnode].offset_follow_lc; /*printf(" vdata[lnode].offset_follow_* = %.4f\n", vdata[lnode].offset_follow_lc);*/ } lnode = -1; } /* Step to the next level on the left contour of the right subtree */ if (vdata[rnode].left_contour >= 0) { roffset += vdata[rnode].offset_follow_lc; rnode = vdata[rnode].left_contour; } else { /* Right subtree ended here. The left contour of the right * subtree will continue to the next step on the left subtree. * Note that lnode has already been advanced here */ if (lnode >= 0) { /*printf(" Right subtree ended, continuing right subtree's left and right contour on left subtree (node %ld)\n", lnode);*/ vdata[rnode].left_contour = lnode; vdata[rnode].right_contour = lnode; vdata[rnode].offset_follow_lc = vdata[rnode].offset_follow_rc = (loffset-roffset); /* loffset has also been increased earlier */ /*printf(" vdata[rnode].offset_follow_* = %.4f\n", vdata[rnode].offset_follow_lc);*/ } rnode = -1; } /*printf(" Contour: [%d, %d], offsets: [%lf, %lf], rootsep: %lf\n", lnode, rnode, loffset, roffset, rootsep);*/ /* Push subtrees away if necessary */ if ((lnode >= 0) && (rnode >= 0) && (roffset - loffset < minsep)) { /*printf(" Pushing right subtree away by %lf\n", minsep-roffset+loffset);*/ rootsep += minsep-roffset+loffset; roffset = loffset+minsep; } } /*printf(" Offset of subtree with root node %d will be %lf\n", i, rootsep);*/ vdata[i].offset = rootsep; vdata[node].right_contour = i; vdata[node].offset_follow_rc = rootsep; avg = (avg*j)/(j+1) + rootsep/(j+1); leftrootidx=j; leftroot=i; } else { leftrootidx=j; leftroot=i; vdata[node].left_contour=i; vdata[node].right_contour=i; vdata[node].offset_follow_lc = 0.0; vdata[node].offset_follow_rc = 0.0; avg = vdata[i].offset; } j++; } } /*printf("Shifting node to be centered above children. Shift amount: %lf\n", avg);*/ vdata[node].offset_follow_lc -= avg; vdata[node].offset_follow_rc -= avg; for (i=0, j=0; i * Arranges the nodes in a tree where the given node is used as the root. * The tree is directed downwards and the parents are centered above its * children. For the exact algorithm, see: * * * Reingold, E and Tilford, J: Tidier drawing of trees. * IEEE Trans. Softw. Eng., SE-7(2):223--228, 1981 * * * If the given graph is not a tree, a breadth-first search is executed * first to obtain a possible spanning tree. * * \param graph The graph object. * \param res The result, the coordinates in a matrix. The parameter * should point to an initialized matrix object and will be resized. * \param mode Specifies which edges to consider when building the tree. * If it is \c IGRAPH_OUT then only the outgoing, if it is \c IGRAPH_IN * then only the incoming edges of a parent are considered. If it is * \c IGRAPH_ALL then all edges are used (this was the behavior in * igraph 0.5 and before). This parameter also influences how the root * vertices are calculated, if they are not given. See the \p roots parameter. * \param roots The index of the root vertex or root vertices. * If this is a non-empty vector then the supplied vertex ids are used * as the roots of the trees (or a single tree if the graph is connected). * If it is a null pointer of a pointer to an empty vector, then the root * vertices are automatically calculated based on topological sorting, * performed with the opposite mode than the \p mode argument. * After the vertices have been sorted, one is selected from each component. * \param rootlevel This argument can be useful when drawing forests which are * not trees (i.e. they are unconnected and have tree components). It specifies * the level of the root vertices for every tree in the forest. It is only * considered if not a null pointer and the \p roots argument is also given * (and it is not a null pointer of an empty vector). * \return Error code. * * Added in version 0.2. * * \sa \ref igraph_layout_reingold_tilford_circular(). * * \example examples/simple/igraph_layout_reingold_tilford.c */ int igraph_layout_reingold_tilford(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, const igraph_vector_t *roots, const igraph_vector_t *rootlevel) { long int no_of_nodes_orig=igraph_vcount(graph); long int no_of_nodes=no_of_nodes_orig; long int real_root; igraph_t extended; const igraph_t *pextended=graph; igraph_vector_t myroots; const igraph_vector_t *proots=roots; igraph_neimode_t mode2; /* TODO: possible speedup could be achieved if we use a table for storing * the children of each node in the tree. (Now the implementation uses a * single array containing the parent of each node and a node's children * are determined by looking for other nodes that have this node as parent) */ if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } if (mode==IGRAPH_IN) { mode2=IGRAPH_OUT; } else if (mode==IGRAPH_OUT) { mode2=IGRAPH_IN; } else { mode2=mode; } if ( (!roots || igraph_vector_size(roots)==0) && rootlevel && igraph_vector_size(rootlevel) != 0 ) { IGRAPH_WARNING("Reingold-Tilford layout: 'rootlevel' ignored"); } /* ----------------------------------------------------------------------- */ /* If root vertices are not given, then do a topological sort and take the last element from every component for directed graphs, or select the vertex with the maximum degree from each component for undirected graphs */ if (!roots || igraph_vector_size(roots)==0) { igraph_vector_t order, membership; igraph_integer_t no_comps; long int i, noseen=0; IGRAPH_VECTOR_INIT_FINALLY(&myroots, 0); IGRAPH_VECTOR_INIT_FINALLY(&order, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&membership, no_of_nodes); if (igraph_is_directed(graph) && mode != IGRAPH_ALL) { IGRAPH_CHECK(igraph_topological_sorting(graph, &order, mode2)); IGRAPH_CHECK(igraph_clusters(graph, &membership, /*csize=*/ 0, &no_comps, IGRAPH_WEAK)); } else { IGRAPH_CHECK(igraph_sort_vertex_ids_by_degree(graph, &order, igraph_vss_all(), IGRAPH_ALL, 0, IGRAPH_ASCENDING, 0)); IGRAPH_CHECK(igraph_clusters(graph, &membership, /*csize=*/ 0, &no_comps, IGRAPH_WEAK)); } IGRAPH_CHECK(igraph_vector_resize(&myroots, no_comps)); igraph_vector_null(&myroots); proots=&myroots; for (i=no_of_nodes-1; noseen < no_comps && i>=0; i--) { long int v=(long int) VECTOR(order)[i]; long int mem=(long int) VECTOR(membership)[v]; if (VECTOR(myroots)[mem]==0) { noseen += 1; VECTOR(myroots)[mem]=v+1; } } for (i=0; i 0 && igraph_vector_size(roots) > 1) { /* ----------------------------------------------------------------------- */ /* Many roots were given to us, check 'rootlevel' */ long int plus_levels=0; long int i; if (igraph_vector_size(roots) != igraph_vector_size(rootlevel)) { IGRAPH_ERROR("Reingold-Tilford: 'roots' and 'rootlevel' lengths differ", IGRAPH_EINVAL); } /* check if there is one which is not zero */ for (i=0; i=no_of_nodes) { IGRAPH_ERROR("invalid vertex id", IGRAPH_EINVVID); } } else { igraph_vector_t newedges; long int no_of_newedges=igraph_vector_size(proots); long int i; real_root=no_of_nodes; /* Make copy if needed */ if (pextended == graph) { pextended=&extended; IGRAPH_CHECK(igraph_copy(&extended, graph)); IGRAPH_FINALLY(igraph_destroy, &extended); } IGRAPH_VECTOR_INIT_FINALLY(&newedges, no_of_newedges*2); IGRAPH_CHECK(igraph_add_vertices(&extended, 1, 0)); for (i=0; i * This layout is almost the same as \ref igraph_layout_reingold_tilford(), but * the tree is drawn in a circular way, with the root vertex in the center. * * \param graph The graph object. * \param res The result, the coordinates in a matrix. The parameter * should point to an initialized matrix object and will be resized. * \param mode Specifies which edges to consider when building the tree. * If it is \c IGRAPH_OUT then only the outgoing, if it is \c IGRAPH_IN * then only the incoming edges of a parent are considered. If it is * \c IGRAPH_ALL then all edges are used (this was the behavior in * igraph 0.5 and before). This parameter also influences how the root * vertices are calculated, if they are not given. See the \p roots parameter. * \param roots The index of the root vertex or root vertices. * If this is a non-empty vector then the supplied vertex ids are used * as the roots of the trees (or a single tree if the graph is connected). * If it is a null pointer of a pointer to an empty vector, then the root * vertices are automatically calculated based on topological sorting, * performed with the opposite mode than the \p mode argument. * After the vertices have been sorted, one is selected from each component. * \param rootlevel This argument can be useful when drawing forests which are * not trees (i.e. they are unconnected and have tree components). It specifies * the level of the root vertices for every tree in the forest. It is only * considered if not a null pointer and the \p roots argument is also given * (and it is not a null pointer of an empty vector). Note that if you supply * a null pointer here and the graph has multiple components, all of the root * vertices will be mapped to the origin of the coordinate system, which does * not really make sense. * \return Error code. * * \sa \ref igraph_layout_reingold_tilford(). */ int igraph_layout_reingold_tilford_circular(const igraph_t *graph, igraph_matrix_t *res, igraph_neimode_t mode, const igraph_vector_t *roots, const igraph_vector_t *rootlevel) { long int no_of_nodes=igraph_vcount(graph); long int i; igraph_real_t ratio=2*M_PI*(no_of_nodes-1.0)/no_of_nodes; igraph_real_t minx, maxx; IGRAPH_CHECK(igraph_layout_reingold_tilford(graph, res, mode, roots, rootlevel)); if (no_of_nodes == 0) return 0; minx = maxx = MATRIX(*res, 0, 0); for (i=1; i maxx) maxx=MATRIX(*res, i, 0); if (MATRIX(*res, i, 0) < minx) minx=MATRIX(*res, i, 0); } ratio /= (maxx-minx); for (i=0; i this_node.x // other_node.y > this_node.y // the force will be on this_node away from other_node // the proportion (distance/y_distance) is equal to the proportion // (directed_force/y_force), as the two triangles are similar. // therefore, the magnitude of y_force = (directed_force*y_distance)/distance // the sign of y_force is negative, away from other_node igraph_real_t x_distance, y_distance; y_distance = MATRIX(*pos, other_node, 1)-MATRIX(*pos, this_node, 1); if (y_distance < 0) { y_distance = -y_distance; } *y = -1 * ((directed_force * y_distance) / distance); // the x component works in exactly the same way. x_distance = MATRIX(*pos, other_node, 0)-MATRIX(*pos, this_node, 0); if (x_distance < 0) { x_distance = -x_distance; } *x = -1 * ((directed_force * x_distance) / distance); // Now we need to reverse the polarity of our answers based on the falsness // of our assumptions. if (MATRIX(*pos, other_node, 0) < MATRIX(*pos, this_node, 0)) { *x = *x * -1; } if (MATRIX(*pos, other_node, 1) < MATRIX(*pos, this_node, 1)) { *y = *y * -1; } return 0; } int igraph_i_apply_electrical_force(const igraph_matrix_t *pos, igraph_vector_t *pending_forces_x, igraph_vector_t *pending_forces_y, long int other_node, long int this_node, igraph_real_t node_charge, igraph_real_t distance) { igraph_real_t directed_force = COULOMBS_CONSTANT * ((node_charge * node_charge)/(distance * distance)); igraph_real_t x_force, y_force; igraph_i_determine_electric_axal_forces(pos, &x_force, &y_force, directed_force, distance, other_node, this_node); VECTOR(*pending_forces_x)[this_node] += x_force; VECTOR(*pending_forces_y)[this_node] += y_force; VECTOR(*pending_forces_x)[other_node] -= x_force; VECTOR(*pending_forces_y)[other_node] -= y_force; return 0; } int igraph_i_determine_spring_axal_forces(const igraph_matrix_t *pos, igraph_real_t *x, igraph_real_t *y, igraph_real_t directed_force, igraph_real_t distance, int spring_length, long int other_node, long int this_node) { // if the spring is just the right size, the forces will be 0, so we can // skip the computation. // // if the spring is too long, our forces will be identical to those computed // by determine_electrical_axal_forces() (this_node will be pulled toward // other_node). // // if the spring is too short, our forces will be the opposite of those // computed by determine_electrical_axal_forces() (this_node will be pushed // away from other_node) // // finally, since both nodes are movable, only one-half of the total force // should be applied to each node, so half the forces for our answer. if (distance == spring_length) { *x = 0.0; *y = 0.0; } else { igraph_i_determine_electric_axal_forces(pos, x, y, directed_force, distance, other_node, this_node); if (distance < spring_length) { *x = -1 * *x; *y = -1 * *y; } *x = 0.5 * *x; *y = 0.5 * *y; } return 0; } int igraph_i_apply_spring_force(const igraph_matrix_t *pos, igraph_vector_t *pending_forces_x, igraph_vector_t *pending_forces_y, long int other_node, long int this_node, int spring_length, igraph_real_t spring_constant) { // determined using Hooke's Law: // force = -kx // where: // k = spring constant // x = displacement from ideal length in meters igraph_real_t distance, displacement, directed_force, x_force, y_force; distance = igraph_i_distance_between(pos, other_node, this_node); // let's protect ourselves from division by zero by ignoring two nodes that // happen to be in the same place. Since we separate all nodes before we // work on any of them, this will only happen in extremely rare circumstances, // and when it does, electrical force will probably push one or both of them // one way or another anyway. if (distance == 0.0) { return 0; } displacement = distance - spring_length; if (displacement < 0) { displacement = -displacement; } directed_force = -1 * spring_constant * displacement; // remember, this is force directed away from the spring; // a negative number is back towards the spring (or, in our case, back towards // the other node) // get the force that should be applied to >this< node igraph_i_determine_spring_axal_forces(pos, &x_force, &y_force, directed_force, distance, spring_length, other_node, this_node); VECTOR(*pending_forces_x)[this_node] += x_force; VECTOR(*pending_forces_y)[this_node] += y_force; VECTOR(*pending_forces_x)[other_node] -= x_force; VECTOR(*pending_forces_y)[other_node] -= y_force; return 0; } int igraph_i_move_nodes(igraph_matrix_t *pos, const igraph_vector_t *pending_forces_x, const igraph_vector_t *pending_forces_y, igraph_real_t node_mass, igraph_real_t max_sa_movement) { // Since each iteration is isolated, time is constant at 1. // Therefore: // Force effects acceleration. // acceleration (d(velocity)/time) = velocity // velocity (d(displacement)/time) = displacement // displacement = acceleration // determined using Newton's second law: // sum(F) = ma // therefore: // acceleration = force / mass // velocity = force / mass // displacement = force / mass long int this_node, no_of_nodes=igraph_vector_size(pending_forces_x); for (this_node=0; this_node < no_of_nodes; this_node++) { igraph_real_t x_movement, y_movement; x_movement = VECTOR(*pending_forces_x)[this_node] / node_mass; if (x_movement > max_sa_movement) { x_movement = max_sa_movement; } else if (x_movement < -max_sa_movement) { x_movement = -max_sa_movement; } y_movement = VECTOR(*pending_forces_y)[this_node] / node_mass; if (y_movement > max_sa_movement) { y_movement = max_sa_movement; } else if (y_movement < -max_sa_movement) { y_movement = -max_sa_movement; } MATRIX(*pos, this_node, 0) += x_movement; MATRIX(*pos, this_node, 1) += y_movement; } return 0; } /** * \function igraph_layout_graphopt * \brief Optimizes vertex layout via the graphopt algorithm. * * * This is a port of the graphopt layout algorithm by Michael Schmuhl. * graphopt version 0.4.1 was rewritten in C and the support for * layers was removed (might be added later) and a code was a bit * reorganized to avoid some unnecessary steps is the node charge (see below) * is zero. * * * graphopt uses physical analogies for defining attracting and repelling * forces among the vertices and then the physical system is simulated * until it reaches an equilibrium. (There is no simulated annealing or * anything like that, so a stable fixed point is not guaranteed.) * * * See also http://www.schmuhl.org/graphopt/ for the original graphopt. * \param graph The input graph. * \param res Pointer to an initialized matrix, the result will be stored here * and its initial contents is used the starting point of the simulation * if the \p use_seed argument is true. Note that in this case the * matrix should have the proper size, otherwise a warning is issued and * the supplied values are ignored. If no starting positions are given * (or they are invalid) then a random staring position is used. * The matrix will be resized if needed. * \param niter Integer constant, the number of iterations to perform. * Should be a couple of hundred in general. If you have a large graph * then you might want to only do a few iterations and then check the * result. If it is not good enough you can feed it in again in * the \p res argument. The original graphopt default if 500. * \param node_charge The charge of the vertices, used to calculate electric * repulsion. The original graphopt default is 0.001. * \param node_mass The mass of the vertices, used for the spring forces. * The original graphopt defaults to 30. * \param spring_length The length of the springs, an integer number. * The original graphopt defaults to zero. * \param spring_constant The spring constant, the original graphopt defaults * to one. * \param max_sa_movement Real constant, it gives the maximum amount of movement * allowed in a single step along a single axis. The original graphopt * default is 5. * \param use_seed Logical scalar, whether to use the positions in \p res as * a starting configuration. See also \p res above. * \return Error code. * * Time complexity: O(n (|V|^2+|E|) ), n is the number of iterations, * |V| is the number of vertices, |E| the number * of edges. If \p node_charge is zero then it is only O(n|E|). */ int igraph_layout_graphopt(const igraph_t *graph, igraph_matrix_t *res, igraph_integer_t niter, igraph_real_t node_charge, igraph_real_t node_mass, igraph_real_t spring_length, igraph_real_t spring_constant, igraph_real_t max_sa_movement, igraph_bool_t use_seed) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); int my_spring_length=(int) spring_length; igraph_vector_t pending_forces_x, pending_forces_y; /* Set a flag to calculate (or not) the electrical forces that the nodes */ /* apply on each other based on if both node types' charges are zero. */ igraph_bool_t apply_electric_charges= (node_charge!=0); long int this_node, other_node, edge; igraph_real_t distance; long int i; IGRAPH_VECTOR_INIT_FINALLY(&pending_forces_x, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&pending_forces_y, no_of_nodes); if (use_seed) { if (igraph_matrix_nrow(res) != no_of_nodes || igraph_matrix_ncol(res) != 2) { IGRAPH_WARNING("Invalid size for initial matrix, starting from random layout"); IGRAPH_CHECK(igraph_layout_random(graph, res)); } } else { IGRAPH_CHECK(igraph_layout_random(graph, res)); } IGRAPH_PROGRESS("Graphopt layout", 0, NULL); for(i=niter;i>0;i--) { /* Report progress in approx. every 100th step */ if (i%10 == 0) { IGRAPH_PROGRESS("Graphopt layout", 100.0-100.0*i/niter, NULL); } /* Clear pending forces on all nodes */ igraph_vector_null(&pending_forces_x); igraph_vector_null(&pending_forces_y); // Apply electrical force applied by all other nodes if (apply_electric_charges) { // Iterate through all nodes for (this_node = 0; this_node < no_of_nodes; this_node++) { IGRAPH_ALLOW_INTERRUPTION(); for (other_node = this_node + 1; other_node < no_of_nodes; other_node++) { distance = igraph_i_distance_between(res, this_node, other_node); // let's protect ourselves from division by zero by ignoring // two nodes that happen to be in the same place. Since we // separate all nodes before we work on any of them, this // will only happen in extremely rare circumstances, and when // it does, springs will probably pull them apart anyway. // also, if we are more than 50 away, the electric force // will be negligible. // ***** may not always be desirable **** if ((distance != 0.0) && (distance < 500.0)) { // if (distance != 0.0) { // Apply electrical force from node(counter2) on // node(counter) igraph_i_apply_electrical_force(res, &pending_forces_x, &pending_forces_y, other_node, this_node, node_charge, distance); } } } } // Apply force from springs for (edge = 0; edge < no_of_edges; edge++) { long int tthis_node=IGRAPH_FROM(graph, edge); long int oother_node=IGRAPH_TO(graph, edge); // Apply spring force on both nodes igraph_i_apply_spring_force(res, &pending_forces_x, &pending_forces_y, oother_node, tthis_node, my_spring_length, spring_constant); } // Effect the movement of the nodes based on all pending forces igraph_i_move_nodes(res, &pending_forces_x, &pending_forces_y, node_mass, max_sa_movement); } IGRAPH_PROGRESS("Graphopt layout", 100, NULL); igraph_vector_destroy(&pending_forces_y); igraph_vector_destroy(&pending_forces_x); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_layout_merge_dla(igraph_i_layout_mergegrid_t *grid, long int actg, igraph_real_t *x, igraph_real_t *y, igraph_real_t r, igraph_real_t cx, igraph_real_t cy, igraph_real_t startr, igraph_real_t killr); int igraph_i_layout_sphere_2d(igraph_matrix_t *coords, igraph_real_t *x, igraph_real_t *y, igraph_real_t *r); int igraph_i_layout_sphere_3d(igraph_matrix_t *coords, igraph_real_t *x, igraph_real_t *y, igraph_real_t *z, igraph_real_t *r); /** * \function igraph_layout_merge_dla * \brief Merge multiple layouts by using a DLA algorithm * * * First each layout is covered by a circle. Then the layout of the * largest graph is placed at the origin. Then the other layouts are * placed by the DLA algorithm, larger ones first and smaller ones * last. * \param thegraphs Pointer vector containing the graph object of * which the layouts will be merged. * \param coords Pointer vector containing matrix objects with the 2d * layouts of the graphs in \p thegraphs. * \param res Pointer to an initialized matrix object, the result will * be stored here. It will be resized if needed. * \return Error code. * * Added in version 0.2. This function is experimental. * * * Time complexity: TODO. */ int igraph_layout_merge_dla(igraph_vector_ptr_t *thegraphs, igraph_vector_ptr_t *coords, igraph_matrix_t *res) { long int graphs=igraph_vector_ptr_size(coords); igraph_vector_t sizes; igraph_vector_t x, y, r; igraph_vector_t nx, ny, nr; long int allnodes=0; long int i, j; long int actg; igraph_i_layout_mergegrid_t grid; long int jpos=0; igraph_real_t minx, maxx, miny, maxy; igraph_real_t area=0; igraph_real_t maxr=0; long int respos; /* Graphs are currently not used, only the coordinates */ IGRAPH_UNUSED(thegraphs); IGRAPH_VECTOR_INIT_FINALLY(&sizes, graphs); IGRAPH_VECTOR_INIT_FINALLY(&x, graphs); IGRAPH_VECTOR_INIT_FINALLY(&y, graphs); IGRAPH_VECTOR_INIT_FINALLY(&r, graphs); IGRAPH_VECTOR_INIT_FINALLY(&nx, graphs); IGRAPH_VECTOR_INIT_FINALLY(&ny, graphs); IGRAPH_VECTOR_INIT_FINALLY(&nr, graphs); RNG_BEGIN(); for (i=0; i maxr) { maxr=VECTOR(r)[i]; } igraph_i_layout_sphere_2d(mat, igraph_vector_e_ptr(&nx, i), igraph_vector_e_ptr(&ny, i), igraph_vector_e_ptr(&nr, i)); } igraph_vector_order2(&sizes); /* largest first */ /* 0. create grid */ minx=miny=-sqrt(5*area); maxx=maxy=sqrt(5*area); igraph_i_layout_mergegrid_init(&grid, minx, maxx, 200, miny, maxy, 200); IGRAPH_FINALLY(igraph_i_layout_mergegrid_destroy, &grid); /* fprintf(stderr, "Ok, starting DLA\n"); */ /* 1. place the largest */ actg=(long int) VECTOR(sizes)[jpos++]; igraph_i_layout_merge_place_sphere(&grid, 0, 0, VECTOR(r)[actg], actg); IGRAPH_PROGRESS("Merging layouts via DLA", 0.0, NULL); while (jposxmax) { xmax=MATRIX(*coords,i,0); } if (MATRIX(*coords,i,1) < ymin) { ymin=MATRIX(*coords,i,1); } else if (MATRIX(*coords,i,1)>ymax) { ymax=MATRIX(*coords,i,1); } } *x=(xmin+xmax)/2; *y=(ymin+ymax)/2; *r=sqrt( (xmax-xmin)*(xmax-xmin)+(ymax-ymin)*(ymax-ymin) ) / 2; return 0; } int igraph_i_layout_sphere_3d(igraph_matrix_t *coords, igraph_real_t *x, igraph_real_t *y, igraph_real_t *z, igraph_real_t *r) { long int nodes=igraph_matrix_nrow(coords); long int i; igraph_real_t xmin, xmax, ymin, ymax, zmin, zmax; xmin=xmax=MATRIX(*coords,0,0); ymin=ymax=MATRIX(*coords,0,1); zmin=zmax=MATRIX(*coords,0,2); for (i=1; ixmax) { xmax=MATRIX(*coords,i,0); } if (MATRIX(*coords,i,1) < ymin) { ymin=MATRIX(*coords,i,1); } else if (MATRIX(*coords,i,1)>ymax) { ymax=MATRIX(*coords,i,1); } if (MATRIX(*coords,i,2) < zmin) { zmin=MATRIX(*coords,i,2); } else if (MATRIX(*coords,i,2)>zmax) { zmax=MATRIX(*coords,i,2); } } *x=(xmin+xmax)/2; *y=(ymin+ymax)/2; *z=(zmin+zmax)/2; *r=sqrt( (xmax-xmin)*(xmax-xmin)+(ymax-ymin)*(ymax-ymin)+ (zmax-zmin)*(zmax-zmin) ) / 2; return 0; } #define DIST(x,y) (sqrt(pow((x)-cx,2)+pow((y)-cy,2))) int igraph_i_layout_merge_dla(igraph_i_layout_mergegrid_t *grid, long int actg, igraph_real_t *x, igraph_real_t *y, igraph_real_t r, igraph_real_t cx, igraph_real_t cy, igraph_real_t startr, igraph_real_t killr) { long int sp=-1; igraph_real_t angle, len; long int steps=0; /* The graph is not used, only its coordinates */ IGRAPH_UNUSED(actg); while (sp < 0) { /* start particle */ do { steps++; angle=RNG_UNIF(0,2*M_PI); len=RNG_UNIF(.5*startr, startr); *x=cx+len*cos(angle); *y=cy+len*sin(angle); sp=igraph_i_layout_mergegrid_get_sphere(grid, *x, *y, r); } while (sp >= 0); while (sp < 0 && DIST(*x,*y) * This layout requires a distance matrix, where the intersection of * row i and column j specifies the desired distance between vertex i * and vertex j. The algorithm will try to place the vertices in a * space having a given number of dimensions in a way that approximates * the distance relations prescribed in the distance matrix. igraph * uses the classical multidimensional scaling by Torgerson; for more * details, see Cox & Cox: Multidimensional Scaling (1994), Chapman * and Hall, London. * * * If the input graph is disconnected, igraph will decompose it * first into its subgraphs, lay out the subgraphs one by one * using the appropriate submatrices of the distance matrix, and * then merge the layouts using \ref igraph_layout_merge_dla. * Since \ref igraph_layout_merge_dla works for 2D layouts only, * you cannot run the MDS layout on disconnected graphs for * more than two dimensions. * * * Warning: if the graph is symmetric to the exchange of two vertices * (as is the case with leaves of a tree connecting to the same parent), * classical multidimensional scaling may assign the same coordinates to * these vertices. * * \param graph A graph object. * \param res Pointer to an initialized matrix object. This will * contain the result and will be resized if needed. * \param dist The distance matrix. It must be symmetric and this * function does not check whether the matrix is indeed * symmetric. Results are unspecified if you pass a non-symmetric * matrix here. You can set this parameter to null; in this * case, the shortest path lengths between vertices will be * used as distances. * \param dim The number of dimensions in the embedding space. For * 2D layouts, supply 2 here. * \param options This argument is currently ignored, it was used for * ARPACK, but LAPACK is used now for calculating the eigenvectors. * \return Error code. * * Added in version 0.6. * * * Time complexity: usually around O(|V|^2 dim). */ int igraph_layout_mds(const igraph_t* graph, igraph_matrix_t *res, const igraph_matrix_t *dist, long int dim, igraph_arpack_options_t *options) { long int i, no_of_nodes=igraph_vcount(graph); igraph_matrix_t m; igraph_bool_t conn; RNG_BEGIN(); /* Check the distance matrix */ if (dist && (igraph_matrix_nrow(dist) != no_of_nodes || igraph_matrix_ncol(dist) != no_of_nodes)) { IGRAPH_ERROR("invalid distance matrix size", IGRAPH_EINVAL); } /* Check the number of dimensions */ if (dim <= 1) { IGRAPH_ERROR("dim must be positive", IGRAPH_EINVAL); } if (dim > no_of_nodes) { IGRAPH_ERROR("dim must be less than the number of nodes", IGRAPH_EINVAL); } /* Copy or obtain the distance matrix */ if (dist == 0) { IGRAPH_CHECK(igraph_matrix_init(&m, no_of_nodes, no_of_nodes)); IGRAPH_FINALLY(igraph_matrix_destroy, &m); IGRAPH_CHECK(igraph_shortest_paths(graph, &m, igraph_vss_all(), igraph_vss_all(), IGRAPH_ALL)); } else { IGRAPH_CHECK(igraph_matrix_copy(&m, dist)); IGRAPH_FINALLY(igraph_matrix_destroy, &m); /* Make sure that the diagonal contains zeroes only */ for (i = 0; i < no_of_nodes; i++) MATRIX(m, i, i) = 0.0; } /* Check whether the graph is connected */ IGRAPH_CHECK(igraph_is_connected(graph, &conn, IGRAPH_WEAK)); if (conn) { /* Yes, it is, just do the MDS */ IGRAPH_CHECK(igraph_i_layout_mds_single(graph, res, &m, dim)); } else { /* The graph is not connected, lay out the components one by one */ igraph_vector_ptr_t layouts; igraph_vector_t comp, vertex_order; igraph_t subgraph; igraph_matrix_t *layout; igraph_matrix_t dist_submatrix; igraph_bool_t *seen_vertices; long int j, n, processed_vertex_count = 0; IGRAPH_VECTOR_INIT_FINALLY(&comp, 0); IGRAPH_VECTOR_INIT_FINALLY(&vertex_order, no_of_nodes); IGRAPH_CHECK(igraph_vector_ptr_init(&layouts, 0)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &layouts); igraph_vector_ptr_set_item_destructor(&layouts, (igraph_finally_func_t*)igraph_matrix_destroy); IGRAPH_CHECK(igraph_matrix_init(&dist_submatrix, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, &dist_submatrix); seen_vertices = igraph_Calloc(no_of_nodes, igraph_bool_t); if (seen_vertices == 0) IGRAPH_ERROR("cannot calculate MDS layout", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, seen_vertices); for (i = 0; i < no_of_nodes; i++) { if (seen_vertices[i]) continue; /* This is a vertex whose component we did not lay out so far */ IGRAPH_CHECK(igraph_subcomponent(graph, &comp, i, IGRAPH_ALL)); /* Take the subgraph */ IGRAPH_CHECK(igraph_induced_subgraph(graph, &subgraph, igraph_vss_vector(&comp), IGRAPH_SUBGRAPH_AUTO)); IGRAPH_FINALLY(igraph_destroy, &subgraph); /* Calculate the submatrix of the distances */ IGRAPH_CHECK(igraph_matrix_select_rows_cols(&m, &dist_submatrix, &comp, &comp)); /* Allocate a new matrix for storing the layout */ layout = igraph_Calloc(1, igraph_matrix_t); if (layout == 0) IGRAPH_ERROR("cannot calculate MDS layout", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, layout); IGRAPH_CHECK(igraph_matrix_init(layout, 0, 0)); IGRAPH_FINALLY(igraph_matrix_destroy, layout); /* Lay out the subgraph */ IGRAPH_CHECK(igraph_i_layout_mds_single(&subgraph, layout, &dist_submatrix, dim)); /* Store the layout */ IGRAPH_CHECK(igraph_vector_ptr_push_back(&layouts, layout)); IGRAPH_FINALLY_CLEAN(2); /* ownership of layout taken by layouts */ /* Free the newly created subgraph */ igraph_destroy(&subgraph); IGRAPH_FINALLY_CLEAN(1); /* Mark all the vertices in the component as visited */ n = igraph_vector_size(&comp); for (j = 0; j < n; j++) { seen_vertices[(long int)VECTOR(comp)[j]] = 1; VECTOR(vertex_order)[(long int)VECTOR(comp)[j]] = processed_vertex_count++; } } /* Merge the layouts - reusing dist_submatrix here */ IGRAPH_CHECK(igraph_layout_merge_dla(0, &layouts, &dist_submatrix)); /* Reordering the rows of res to match the original graph */ IGRAPH_CHECK(igraph_matrix_select_rows(&dist_submatrix, res, &vertex_order)); igraph_free(seen_vertices); igraph_matrix_destroy(&dist_submatrix); igraph_vector_ptr_destroy_all(&layouts); igraph_vector_destroy(&vertex_order); igraph_vector_destroy(&comp); IGRAPH_FINALLY_CLEAN(5); } RNG_END(); igraph_matrix_destroy(&m); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \function igraph_layout_bipartite * Simple layout for bipartite graphs * * The layout is created by first placing the vertices in two rows, * according to their types. Then the positions within the rows are * optimized to minimize edge crossings, by calling \ref * igraph_layout_sugiyama(). * * \param graph The input graph. * \param types A boolean vector containing ones and zeros, the vertex * types. Its length must match the number of vertices in the graph. * \param res Pointer to an initialized matrix, the result, the x and * y coordinates are stored here. * \param hgap The preferred minimum horizontal gap between vertices * in the same layer (i.e. vertices of the same type). * \param vgap The distance between layers. * \param maxiter Maximum number of iterations in the crossing * minimization stage. 100 is a reasonable default; if you feel * that you have too many edge crossings, increase this. * \return Error code. * * \sa \ref igraph_layout_sugiyama(). */ int igraph_layout_bipartite(const igraph_t *graph, const igraph_vector_bool_t *types, igraph_matrix_t *res, igraph_real_t hgap, igraph_real_t vgap, long int maxiter) { long int i, no_of_nodes=igraph_vcount(graph); igraph_vector_t layers; if (igraph_vector_bool_size(types) != no_of_nodes) { IGRAPH_ERROR("Invalid vertex type vector size", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&layers, no_of_nodes); for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_epidemics.h" #include "igraph_random.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_psumtree.h" #include "igraph_memory.h" #include "igraph_structural.h" int igraph_sir_init(igraph_sir_t *sir) { igraph_vector_init(&sir->times, 1); IGRAPH_FINALLY(igraph_vector_destroy, &sir->times); igraph_vector_int_init(&sir->no_s, 1); IGRAPH_FINALLY(igraph_vector_int_destroy, &sir->no_s); igraph_vector_int_init(&sir->no_i, 1); IGRAPH_FINALLY(igraph_vector_int_destroy, &sir->no_i); igraph_vector_int_init(&sir->no_r, 1); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \function igraph_sir_destroy * Deallocate memory associated with a SIR simulation run * * \param sir The \ref igraph_sir_t object storing the simulation. */ void igraph_sir_destroy(igraph_sir_t *sir) { igraph_vector_destroy(&sir->times); igraph_vector_int_destroy(&sir->no_s); igraph_vector_int_destroy(&sir->no_i); igraph_vector_int_destroy(&sir->no_r); } void igraph_i_sir_destroy(igraph_vector_ptr_t *v) { int i, n=igraph_vector_ptr_size(v); for (i=0; i * This function runs multiple simulations, all starting with a * single uniformly randomly chosen infected individual. * * \param graph The graph to perform the model on. For directed graphs * edge directions are ignored and a warning is given. * \param beta The rate of infection of an individual that is * susceptible and has a single infected neighbor. * The infection rate of a susceptible individual with n * infected neighbors is n times beta. Formally * this is the rate parameter of an exponential distribution. * \param gamma The rate of recovery of an infected individual. * Formally, this is the rate parameter of an exponential * distribution. * \param no_sim The number of simulation runs to perform. * \param result The result of the simulation is stored here, * in a list of \ref igraph_sir_t objects. To deallocate * memory, the user needs to call \ref igraph_sir_destroy on * each element, before destroying the pointer vector itself. * \return Error code. * * Time complexity: O(no_sim * (|V| + |E| log(|V|))). */ int igraph_sir(const igraph_t *graph, igraph_real_t beta, igraph_real_t gamma, igraph_integer_t no_sim, igraph_vector_ptr_t *result) { int infected; igraph_vector_int_t status; igraph_adjlist_t adjlist; int no_of_nodes=igraph_vcount(graph); int i, j, ns, ni, nr; igraph_vector_int_t *neis; igraph_psumtree_t tree; igraph_real_t psum; int neilen; igraph_bool_t simple; if (no_of_nodes==0) { IGRAPH_ERROR("Cannot run SIR model on empty graph", IGRAPH_EINVAL); } if (igraph_is_directed(graph)) { IGRAPH_WARNING("Edge directions are ignored in SIR model"); } if (beta < 0) { IGRAPH_ERROR("Beta must be non-negative in SIR model", IGRAPH_EINVAL); } if (gamma < 0) { IGRAPH_ERROR("Gamma must be non-negative in SIR model", IGRAPH_EINVAL); } if (no_sim <= 0) { IGRAPH_ERROR("Number of SIR simulations must be positive", IGRAPH_EINVAL); } igraph_is_simple(graph, &simple); if (!simple) { IGRAPH_ERROR("SIR model only works with simple graphs", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_int_init(&status, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &status); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_psumtree_init(&tree, no_of_nodes)); IGRAPH_FINALLY(igraph_psumtree_destroy, &tree); IGRAPH_CHECK(igraph_vector_ptr_resize(result, no_sim)); igraph_vector_ptr_null(result); IGRAPH_FINALLY(igraph_i_sir_destroy, result); for (i=0; itimes; igraph_vector_int_t *no_s_v = &sir->no_s; igraph_vector_int_t *no_i_v = &sir->no_i; igraph_vector_int_t *no_r_v = &sir->no_r; infected = RNG_INTEGER(0, no_of_nodes-1); /* Initially infected */ igraph_vector_int_null(&status); VECTOR(status)[infected] = S_I; ns = no_of_nodes - 1; ni = 1; nr = 0; VECTOR(*times_v)[0] = 0.0; VECTOR(*no_s_v)[0] = ns; VECTOR(*no_i_v)[0] = ni; VECTOR(*no_r_v)[0] = nr; if (igraph_psumtree_sum(&tree) != 0) { IGRAPH_ERROR("Internal SIR error", IGRAPH_EINTERNAL); } /* Rates */ igraph_psumtree_update(&tree, infected, gamma); neis=igraph_adjlist_get(&adjlist, infected); neilen=igraph_vector_int_size(neis); for (i=0; i 0) { igraph_real_t tt=igraph_rng_get_exp(igraph_rng_default(), psum); igraph_real_t r=RNG_UNIF(0, psum); long int vchange; igraph_psumtree_search(&tree, &vchange, r); neis=igraph_adjlist_get(&adjlist, vchange); neilen=igraph_vector_int_size(neis); if (VECTOR(status)[vchange] == S_I) { VECTOR(status)[vchange] = S_R; ni--; nr++; psum -= igraph_psumtree_get(&tree, vchange); igraph_psumtree_update(&tree, vchange, 0.0); for (i=0; i 0 */ } /* j < no_sim */ RNG_END(); igraph_psumtree_destroy(&tree); igraph_adjlist_destroy(&adjlist); igraph_vector_int_destroy(&status); IGRAPH_FINALLY_CLEAN(4); /* + result */ return 0; } igraph/src/flow.c0000644000175100001440000025002713431000472013444 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_flow.h" #include "igraph_error.h" #include "igraph_memory.h" #include "igraph_constants.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_conversion.h" #include "igraph_constructors.h" #include "igraph_progress.h" #include "igraph_structural.h" #include "igraph_components.h" #include "igraph_types_internal.h" #include "config.h" #include "igraph_math.h" #include "igraph_dqueue.h" #include "igraph_visitor.h" #include "igraph_interrupt_internal.h" #include "igraph_topology.h" #include #include /* * Some general remarks about the functions in this file. * * The following measures can be calculated: * ( 1) s-t maximum flow value, directed graph * ( 2) s-t maximum flow value, undirected graph * ( 3) s-t maximum flow, directed graph * ( 4) s-t maximum flow, undirected graph * ( 5) s-t minimum cut value, directed graph * ( 6) s-t minimum cut value, undirected graph * ( 7) minimum cut value, directed graph * ( 8) minimum cut value, undirected graph * ( 9) s-t minimum cut, directed graph * (10) s-t minimum cut, undirected graph * (11) minimum cut, directed graph * (12) minimum cut, undirected graph * (13) s-t edge connectivity, directed graph * (14) s-t edge connectivity, undirected graph * (15) edge connectivity, directed graph * (16) edge connectivity, undirected graph * (17) s-t vertex connectivity, directed graph * (18) s-t vertex connectivity, undirected graph * (19) vertex connectivity, directed graph * (20) vertex connectivity, undirected graph * (21) s-t number of edge disjoint paths, directed graph * (22) s-t number of edge disjoint paths, undirected graph * (23) s-t number of vertex disjoint paths, directed graph * (24) s-t number of vertex disjoint paths, undirected graph * (25) graph adhesion, directed graph * (26) graph adhesion, undirected graph * (27) graph cohesion, directed graph * (28) graph cohesion, undirected graph * * This is how they are calculated: * ( 1) igraph_maxflow_value, calls igraph_maxflow. * ( 2) igraph_maxflow_value, calls igraph_maxflow, this calls * igraph_i_maxflow_undirected. This transforms the graph into a * directed graph, including two mutual edges instead of every * undirected edge, then igraph_maxflow is called again with the * directed graph. * ( 3) igraph_maxflow, does the push-relabel algorithm, optionally * calculates the cut, the partitions and the flow itself. * ( 4) igraph_maxflow calls igraph_i_maxflow_undirected, this converts * the undirected graph into a directed one, adding two mutual edges * for each undirected edge, then igraph_maxflow is called again, * with the directed graph. After igraph_maxflow returns, we need * to edit the flow (and the cut) to make it sense for the * original graph. * ( 5) igraph_st_mincut_value, we just call igraph_maxflow_value * ( 6) igraph_st_mincut_value, we just call igraph_maxflow_value * ( 7) igraph_mincut_value, we call igraph_maxflow_value (|V|-1)*2 * times, from vertex 0 to all other vertices and from all other * vertices to vertex 0 * ( 8) We call igraph_i_mincut_value_undirected, that calls * igraph_i_mincut_undirected with partition=partition2=cut=NULL * The Stoer-Wagner algorithm is used. * ( 9) igraph_st_mincut, just calls igraph_maxflow. * (10) igraph_st_mincut, just calls igraph_maxflow. * (11) igraph_mincut, calls igraph_i_mincut_directed, which runs * the maximum flow algorithm 2(|V|-1) times, from vertex zero to * and from all other vertices and stores the smallest cut. * (12) igraph_mincut, igraph_i_mincut_undirected is called, * this is the Stoer-Wagner algorithm * (13) We just call igraph_maxflow_value, back to (1) * (14) We just call igraph_maxflow_value, back to (2) * (15) We just call igraph_mincut_value (possibly after some basic * checks). Back to (7) * (16) We just call igraph_mincut_value (possibly after some basic * checks). Back to (8). * (17) We call igraph_i_st_vertex_connectivity_directed. * That creates a new graph with 2*|V| vertices and smartly chosen * edges, so that the s-t edge connectivity of this graph is the * same as the s-t vertex connectivity of the original graph. * So finally it calls igraph_maxflow_value, go to (1) * (18) We call igraph_i_st_vertex_connectivity_undirected. * We convert the graph to a directed one, * IGRAPH_TO_DIRECTED_MUTUAL method. Then we call * igraph_i_st_vertex_connectivity_directed, see (17). * (19) We call igraph_i_vertex_connectivity_directed. * That calls igraph_st_vertex_connectivity for all pairs of * vertices. Back to (17). * (20) We call igraph_i_vertex_connectivity_undirected. * That converts the graph into a directed one * (IGRAPH_TO_DIRECTED_MUTUAL) and calls the directed version, * igraph_i_vertex_connectivity_directed, see (19). * (21) igraph_edge_disjoint_paths, we just call igraph_maxflow_value, (1). * (22) igraph_edge_disjoint_paths, we just call igraph_maxflow_value, (2). * (23) igraph_vertex_disjoint_paths, if there is a connection between * the two vertices, then we remove that (or all of them if there * are many), as this could mess up vertex connectivity * calculation. The we call * igraph_i_st_vertex_connectivity_directed, see (19). * (24) igraph_vertex_disjoint_paths, if there is a connection between * the two vertices, then we remove that (or all of them if there * are many), as this could mess up vertex connectivity * calculation. The we call * igraph_i_st_vertex_connectivity_undirected, see (20). * (25) We just call igraph_edge_connectivity, see (15). * (26) We just call igraph_edge_connectivity, see (16). * (27) We just call igraph_vertex_connectivity, see (19). * (28) We just call igraph_vertex_connectivity, see (20). */ /* * This is an internal function that calculates the maximum flow value * on undirected graphs, either for an s-t vertex pair or for the * graph (i.e. all vertex pairs). * * It does it by converting the undirected graph to a corresponding * directed graph, including reciprocal directed edges instead of each * undirected edge. */ int igraph_i_maxflow_undirected(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *flow, igraph_vector_t *cut, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity, igraph_maxflow_stats_t *stats) { igraph_integer_t no_of_edges=(igraph_integer_t) igraph_ecount(graph); igraph_integer_t no_of_nodes=(igraph_integer_t) igraph_vcount(graph); igraph_vector_t edges; igraph_vector_t newcapacity; igraph_t newgraph; long int i; /* We need to convert this to directed by hand, since we need to be sure that the edge ids will be handled properly to build the new capacity vector. */ IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&newcapacity, no_of_edges*2); IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*4)); IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); IGRAPH_CHECK(igraph_vector_resize(&edges, no_of_edges*4)); for (i=0; i= no_of_edges) { VECTOR(*cut)[i] -= no_of_edges; } } } /* The flow has one non-zero value for each real-nonreal edge pair, by definition, we convert it to a positive-negative vector. If for an edge the flow is negative that means that it is going from the bigger vertex id to the smaller one. For positive values the direction is the opposite. */ if (flow) { long int i; for (i=0; inogap)++; for (bo=b+1; bo <= no_of_nodes; bo++) { while (!igraph_dbuckets_empty_bucket(ibuckets, bo)) { long int n=igraph_dbuckets_pop(ibuckets, bo); (stats->nogapnodes)++; DIST(n)=no_of_nodes; } } } void igraph_i_mf_relabel(long int v, long int no_of_nodes, igraph_vector_long_t *distance, igraph_vector_long_t *first, igraph_vector_t *rescap, igraph_vector_long_t *to, igraph_vector_long_t *current, igraph_maxflow_stats_t *stats, int *nrelabelsince) { long int min=no_of_nodes; long int k, l, min_edge=0; (stats->norelabel)++; (*nrelabelsince)++; DIST(v)=no_of_nodes; for (k=FIRST(v), l=LAST(v); k 0 && DIST(HEAD(k)) < min) { min=DIST(HEAD(k)); min_edge=k; } } min++; if (min < no_of_nodes) { DIST(v) = min; CURRENT(v) = min_edge; } } void igraph_i_mf_push(long int v, long int e, long int n, igraph_vector_long_t *current, igraph_vector_t *rescap, igraph_vector_t *excess, long int target, long int source, igraph_buckets_t *buckets, igraph_dbuckets_t *ibuckets, igraph_vector_long_t *distance, igraph_vector_long_t *rev, igraph_maxflow_stats_t *stats, int *npushsince) { igraph_real_t delta= RESCAP(e) < EXCESS(v) ? RESCAP(e) : EXCESS(v); (stats->nopush)++; (*npushsince)++; if (EXCESS(n) == 0 && n != target) { igraph_dbuckets_delete(ibuckets, DIST(n), n); igraph_buckets_add(buckets, (long int) DIST(n), n); } RESCAP(e) -= delta; RESCAP(REV(e)) += delta; EXCESS(n) += delta; EXCESS(v) -= delta; } void igraph_i_mf_discharge(long int v, igraph_vector_long_t *current, igraph_vector_long_t *first, igraph_vector_t *rescap, igraph_vector_long_t *to, igraph_vector_long_t *distance, igraph_vector_t *excess, long int no_of_nodes, long int source, long int target, igraph_buckets_t *buckets, igraph_dbuckets_t *ibuckets, igraph_vector_long_t *rev, igraph_maxflow_stats_t *stats, int *npushsince, int *nrelabelsince) { do { long int i; long int start=(long int) CURRENT(v); long int stop =(long int) LAST(v); for (i = start; i < stop; i++) { if (RESCAP(i) > 0) { long int nei=HEAD(i); if (DIST(v) == DIST(nei)+1) { PUSH((v), i, nei); if (EXCESS(v) == 0) { break; } } } } if (i == stop) { long int origdist=DIST(v); RELABEL(v); if (igraph_buckets_empty_bucket(buckets, origdist) && igraph_dbuckets_empty_bucket(ibuckets, origdist)) { GAP(origdist); } if (DIST(v) == no_of_nodes) { break; } } else { CURRENT(v) = i; igraph_dbuckets_add(ibuckets, DIST(v), v); break; } } while (1); } void igraph_i_mf_bfs(igraph_dqueue_long_t *bfsq, long int source, long int target, long int no_of_nodes, igraph_buckets_t *buckets, igraph_dbuckets_t *ibuckets, igraph_vector_long_t *distance, igraph_vector_long_t *first, igraph_vector_long_t *current, igraph_vector_long_t *to, igraph_vector_t *excess, igraph_vector_t *rescap, igraph_vector_long_t *rev) { long int k, l; igraph_buckets_clear(buckets); igraph_dbuckets_clear(ibuckets); igraph_vector_long_fill(distance, no_of_nodes); DIST(target) = 0; igraph_dqueue_long_push(bfsq, target); while (!igraph_dqueue_long_empty(bfsq)) { long int node=igraph_dqueue_long_pop(bfsq); long int ndist=DIST(node)+1; for (k=FIRST(node), l=LAST(node); k 0) { long int nei=HEAD(k); if (DIST(nei) == no_of_nodes) { DIST(nei) = ndist; CURRENT(nei) = FIRST(nei); if (EXCESS(nei) > 0) { igraph_buckets_add(buckets, ndist, nei); } else { igraph_dbuckets_add(ibuckets, ndist, nei); } igraph_dqueue_long_push(bfsq, nei); } } } } } /** * \function igraph_maxflow * Maximum network flow between a pair of vertices * * This function implements the Goldberg-Tarjan algorithm for * calculating value of the maximum flow in a directed or undirected * graph. The algorithm was given in Andrew V. Goldberg, Robert * E. Tarjan: A New Approach to the Maximum-Flow Problem, Journal of * the ACM, 35(4), 921-940, 1988. * * The input of the function is a graph, a vector * of real numbers giving the capacity of the edges and two vertices * of the graph, the source and the target. A flow is a function * assigning positive real numbers to the edges and satisfying two * requirements: (1) the flow value is less than the capacity of the * edge and (2) at each vertex except the source and the target, the * incoming flow (ie. the sum of the flow on the incoming edges) is * the same as the outgoing flow (ie. the sum of the flow on the * outgoing edges). The value of the flow is the incoming flow at the * target vertex. The maximum flow is the flow with the maximum * value. * * \param graph The input graph, either directed or undirected. * \param value Pointer to a real number, the value of the maximum * will be placed here, unless it is a null pointer. * \param flow If not a null pointer, then it must be a pointer to an * initialized vector. The vector will be resized, and the flow * on each edge will be placed in it, in the order of the edge * ids. For undirected graphs this argument is bit trickier, * since for these the flow direction is not predetermined by * the edge direction. For these graphs the elements of the * \p flow vector can be negative, this means that the flow * goes from the bigger vertex id to the smaller one. Positive * values mean that the flow goes from the smaller vertex id to * the bigger one. * \param cut A null pointer or a pointer to an initialized vector. * If not a null pointer, then the minimum cut corresponding to * the maximum flow is stored here, i.e. all edge ids that are * part of the minimum cut are stored in the vector. * \param partition A null pointer or a pointer to an initialized * vector. If not a null pointer, then the first partition of * the minimum cut that corresponds to the maximum flow will be * placed here. The first partition is always the one that * contains the source vertex. * \param partition2 A null pointer or a pointer to an initialized * vector. If not a null pointer, then the second partition of * the minimum cut that corresponds to the maximum flow will be * placed here. The second partition is always the one that * contains the target vertex. * \param source The id of the source vertex. * \param target The id of the target vertex. * \param capacity Vector containing the capacity of the edges. If NULL, then * every edge is considered to have capacity 1.0. * \param stats Counts of the number of different operations * preformed by the algorithm are stored here. * \return Error code. * * Time complexity: O(|V|^3). In practice it is much faster, but i * cannot prove a better lower bound for the data structure i've * used. In fact, this implementation runs much faster than the * \c hi_pr implementation discussed in * B. V. Cherkassky and A. V. Goldberg: On implementing the * push-relabel method for the maximum flow problem, (Algorithmica, * 19:390--410, 1997) on all the graph classes i've tried. * * \sa \ref igraph_mincut_value(), \ref igraph_edge_connectivity(), * \ref igraph_vertex_connectivity() for * properties based on the maximum flow. * * \example examples/simple/flow.c * \example examples/simple/flow2.c */ int igraph_maxflow(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *flow, igraph_vector_t *cut, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity, igraph_maxflow_stats_t *stats) { igraph_integer_t no_of_nodes=(igraph_integer_t) igraph_vcount(graph); igraph_integer_t no_of_orig_edges=(igraph_integer_t) igraph_ecount(graph); igraph_integer_t no_of_edges=2*no_of_orig_edges; igraph_vector_t rescap, excess; igraph_vector_long_t from, to, rev, distance; igraph_vector_t edges, rank; igraph_vector_long_t current, first; igraph_buckets_t buckets; igraph_dbuckets_t ibuckets; igraph_dqueue_long_t bfsq; long int i, j, idx; int npushsince=0, nrelabelsince=0; igraph_maxflow_stats_t local_stats; /* used if the user passed a null pointer for stats */ if (stats == 0) { stats = &local_stats; } if (!igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_maxflow_undirected(graph, value, flow, cut, partition, partition2, source, target, capacity, stats)); return 0; } if (capacity && igraph_vector_size(capacity) != no_of_orig_edges) { IGRAPH_ERROR("Invalid capacity vector", IGRAPH_EINVAL); } if (source<0 || source>=no_of_nodes || target<0 || target>=no_of_nodes) { IGRAPH_ERROR("Invalid source or target vertex", IGRAPH_EINVAL); } stats->nopush = stats->norelabel = stats->nogap = stats->nogapnodes = stats->nobfs = 0; /* * The data structure: * - First of all, we consider every edge twice, first the edge * itself, but also its opposite. * - (from, to) contain all edges (original + opposite), ordered by * the id of the source vertex. During the algorithm we just need * 'to', so from is destroyed soon. We only need it in the * beginning, to create the 'first' pointers. * - 'first' is a pointer vector for 'to', first[i] points to the * first neighbor of vertex i and first[i+1]-1 is the last * neighbor of vertex i. (Unless vertex i is isolate, in which * case first[i]==first[i+1]). * - 'rev' contains a mapping from an edge to its opposite pair * - 'rescap' contains the residual capacities of the edges, this is * initially equal to the capacity of the edges for the original * edges and it is zero for the opposite edges. * - 'excess' contains the excess flow for the vertices. I.e. the flow * that is coming in, but it is not going out. * - 'current' stores the next neighboring vertex to check, for every * vertex, when excess flow is being pushed to neighbors. * - 'distance' stores the distance of the vertices from the source. * - 'rank' and 'edges' are only needed temporarily, for ordering and * storing the edges. * - we use an igraph_buckets_t data structure ('buckets') to find * the vertices with the highest 'distance' values quickly. * This always contains the vertices that have a positive excess * flow. */ #undef FIRST #undef LAST #undef CURRENT #undef RESCAP #undef REV #undef HEAD #undef EXCESS #undef DIST #define FIRST(i) (VECTOR(first)[(i)]) #define LAST(i) (VECTOR(first)[(i)+1]) #define CURRENT(i) (VECTOR(current)[(i)]) #define RESCAP(i) (VECTOR(rescap)[(i)]) #define REV(i) (VECTOR(rev)[(i)]) #define HEAD(i) (VECTOR(to)[(i)]) #define EXCESS(i) (VECTOR(excess)[(i)]) #define DIST(i) (VECTOR(distance)[(i)]) igraph_dqueue_long_init(&bfsq, no_of_nodes); IGRAPH_FINALLY(igraph_dqueue_long_destroy, &bfsq); IGRAPH_VECTOR_LONG_INIT_FINALLY(&to, no_of_edges); IGRAPH_VECTOR_LONG_INIT_FINALLY(&rev, no_of_edges); IGRAPH_VECTOR_INIT_FINALLY(&rescap, no_of_edges); IGRAPH_VECTOR_INIT_FINALLY(&excess, no_of_nodes); IGRAPH_VECTOR_LONG_INIT_FINALLY(&distance, no_of_nodes); IGRAPH_VECTOR_LONG_INIT_FINALLY(&first, no_of_nodes+1); IGRAPH_VECTOR_INIT_FINALLY(&rank, no_of_edges); IGRAPH_VECTOR_LONG_INIT_FINALLY(&from, no_of_edges); IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges); /* Create the basic data structure */ IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); IGRAPH_CHECK(igraph_vector_rank(&edges, &rank, no_of_nodes)); for (i=0; inobfs)++; while (!igraph_buckets_empty(&buckets)) { long int vertex=igraph_buckets_popmax(&buckets); DISCHARGE(vertex); if (npushsince > no_of_nodes / 2 && nrelabelsince > no_of_nodes) { (stats->nobfs)++; BFS(); npushsince = nrelabelsince = 0; } } /* Store the result */ if (value) { *value=EXCESS(target); } /* If we also need the minimum cut */ if (cut || partition || partition2) { /* We need to find all vertices from which the target is reachable in the residual graph. We do a breadth-first search, going backwards. */ igraph_dqueue_t Q; igraph_vector_bool_t added; long int marked=0; IGRAPH_CHECK(igraph_vector_bool_init(&added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &added); IGRAPH_CHECK(igraph_dqueue_init(&Q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &Q); igraph_dqueue_push(&Q, target); VECTOR(added)[(long int)target]=1; marked++; while (!igraph_dqueue_empty(&Q)) { long int actnode=(long int) igraph_dqueue_pop(&Q); for (i=FIRST(actnode), j=LAST(actnode); i 0.0) { VECTOR(added)[nei]=1; marked++; IGRAPH_CHECK(igraph_dqueue_push(&Q, nei)); } } } igraph_dqueue_destroy(&Q); IGRAPH_FINALLY_CLEAN(1); /* Now we marked each vertex that is on one side of the cut, check the crossing edges */ if (cut) { igraph_vector_clear(cut); for (i=0; i 0.0) { VECTOR(added)[nei]=1; IGRAPH_CHECK(igraph_dqueue_push(&Q, nei)); IGRAPH_CHECK(igraph_dqueue_push(&Q, actdist+1)); } } } /* !igraph_dqueue_empty(&Q) */ igraph_vector_int_destroy(&added); igraph_dqueue_destroy(&Q); IGRAPH_FINALLY_CLEAN(2); /* Reinitialize the buckets */ igraph_buckets_clear(&buckets); for (i=0; i 0.0 && i != source && i != target) { igraph_buckets_add(&buckets, (long int) DIST(i), i); } } /* Now we return the flow to the source */ while (!igraph_buckets_empty(&buckets)) { long int vertex=igraph_buckets_popmax(&buckets); /* DISCHARGE(vertex) comes here */ do { for (i=(long int) CURRENT(vertex), j=LAST(vertex); i 0) { long int nei=HEAD(i); if (DIST(vertex) == DIST(nei)+1) { igraph_real_t delta= RESCAP(i) < EXCESS(vertex) ? RESCAP(i) : EXCESS(vertex); RESCAP(i) -= delta; RESCAP(REV(i)) += delta; if (nei != source && EXCESS(nei) == 0.0 && DIST(nei) != no_of_nodes) { igraph_buckets_add(&buckets, (long int) DIST(nei), nei); } EXCESS(nei) += delta; EXCESS(vertex) -= delta; if (EXCESS(vertex) == 0) break; } } } if (i==j) { /* RELABEL(vertex) comes here */ igraph_real_t min; long int min_edge=0; DIST(vertex)=min=no_of_nodes; for (k=FIRST(vertex), l=LAST(vertex); k 0) { if (DIST(HEAD(k)) < min) { min=DIST(HEAD(k)); min_edge=k; } } } min++; if (min < no_of_nodes) { DIST(vertex)=min; CURRENT(vertex)=min_edge; /* Vertex is still active */ igraph_buckets_add(&buckets, (long int) DIST(vertex), vertex); } /* TODO: gap heuristics here ??? */ } else { CURRENT(vertex) = FIRST(vertex); } break; } while (1); } /* We need to eliminate flow cycles now. Before that we check that there is a cycle in the flow graph. First we do a couple of DFSes from the source vertex to the target and factor out the paths we find. If there is no more path to the target, then all remaining flow must be in flow cycles, so we don't need it at all. Some details. 'stack' contains the whole path of the DFS, both the vertices and the edges, they are alternating in the stack. 'current' helps finding the next outgoing edge of a vertex quickly, the next edge of 'v' is FIRST(v)+CURRENT(v). If this is LAST(v), then there are no more edges to try. The 'added' vector contains 0 if the vertex was not visited before, 1 if it is currently in 'stack', and 2 if it is not in 'stack', but it was visited before. */ IGRAPH_VECTOR_INIT_FINALLY(&flow_edges, 0); for (i=0, j=0; i RESCAP(pos)) { IGRAPH_CHECK(igraph_vector_push_back(&flow_edges, IGRAPH_FROM(graph, j))); IGRAPH_CHECK(igraph_vector_push_back(&flow_edges, IGRAPH_TO(graph, j))); } } IGRAPH_CHECK(igraph_create(&flow_graph, &flow_edges, no_of_nodes, IGRAPH_DIRECTED)); igraph_vector_destroy(&flow_edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &flow_graph); IGRAPH_CHECK(igraph_is_dag(&flow_graph, &dag)); igraph_destroy(&flow_graph); IGRAPH_FINALLY_CLEAN(1); if (!dag) { igraph_vector_long_t stack; igraph_vector_t mycap; IGRAPH_CHECK(igraph_vector_long_init(&stack, 0)); IGRAPH_FINALLY(igraph_vector_long_destroy, &stack); IGRAPH_CHECK(igraph_vector_int_init(&added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &added); IGRAPH_VECTOR_INIT_FINALLY(&mycap, no_of_edges); #define MYCAP(i) (VECTOR(mycap)[(i)]) for (i=0; i= 0 && VECTOR(stack)[idx+1] != nei; idx-=2) { long int e=VECTOR(stack)[idx]; igraph_real_t rcap= e >= 0 ? MYCAP(e) : MYCAP(edge); if (rcap < thisflow) { thisflow=rcap; } } MYCAP(edge) -= thisflow; RESCAP(edge) += thisflow; for (idx=igraph_vector_long_size(&stack)-2; idx >= 0 && VECTOR(stack)[idx+1] != nei; idx-=2) { long int e=VECTOR(stack)[idx]; if (e >= 0) { MYCAP(e) -= thisflow; RESCAP(e) += thisflow; } } CURRENT(actnode) += 1; } else if (edge < LAST(actnode)) { /* && VECTOR(added)[nei]==2 */ /* The next edge leads to a vertex that was visited before, but it is currently not in 'stack' */ CURRENT(actnode) += 1; } else { /* Go backward, take out the node and the edge that leads to it */ igraph_vector_long_pop_back(&stack); igraph_vector_long_pop_back(&stack); VECTOR(added)[actnode]=2; } } /* If non-empty, then it contains a path from source to target in the residual graph. We factor out this path from the flow. */ if (!igraph_vector_long_empty(&stack)) { long int pl=igraph_vector_long_size(&stack); igraph_real_t thisflow=EXCESS(target); for (i=2; iThis function implements the Goldberg-Tarjan algorithm for * calculating value of the maximum flow in a directed or undirected * graph. The algorithm was given in Andrew V. Goldberg, Robert * E. Tarjan: A New Approach to the Maximum-Flow Problem, Journal of * the ACM, 35(4), 921-940, 1988. * * The input of the function is a graph, a vector * of real numbers giving the capacity of the edges and two vertices * of the graph, the source and the target. A flow is a function * assigning positive real numbers to the edges and satisfying two * requirements: (1) the flow value is less than the capacity of the * edge and (2) at each vertex except the source and the target, the * incoming flow (ie. the sum of the flow on the incoming edges) is * the same as the outgoing flow (ie. the sum of the flow on the * outgoing edges). The value of the flow is the incoming flow at the * target vertex. The maximum flow is the flow with the maximum * value. * * According to a theorem by Ford and Fulkerson * (L. R. Ford Jr. and D. R. Fulkerson. Maximal flow through a * network. Canadian J. Math., 8:399-404, 1956.) the maximum flow * between two vertices is the same as the * minimum cut between them (also called the minimum s-t cut). So \ref * igraph_st_mincut_value() gives the same result in all cases as \c * igraph_maxflow_value(). * * Note that the value of the maximum flow is the same as the * minimum cut in the graph. * \param graph The input graph, either directed or undirected. * \param value Pointer to a real number, the result will be placed here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \param capacity Vector containing the capacity of the edges. If NULL, then * every edge is considered to have capacity 1.0. * \param stats Counts of the number of different operations * preformed by the algorithm are stored here. * \return Error code. * * Time complexity: O(|V|^3). * * \sa \ref igraph_maxflow() to calculate the actual flow. * \ref igraph_mincut_value(), \ref igraph_edge_connectivity(), * \ref igraph_vertex_connectivity() for * properties based on the maximum flow. */ int igraph_maxflow_value(const igraph_t *graph, igraph_real_t *value, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity, igraph_maxflow_stats_t *stats) { return igraph_maxflow(graph, value, /*flow=*/ 0, /*cut=*/ 0, /*partition=*/ 0, /*partition1=*/ 0, source, target, capacity, stats); } /** * \function igraph_st_mincut_value * \brief The minimum s-t cut in a graph * * The minimum s-t cut in a weighted (=valued) graph is the * total minimum edge weight needed to remove from the graph to * eliminate all paths from a given vertex (\c source) to * another vertex (\c target). Directed paths are considered in * directed graphs, and undirected paths in undirected graphs. * * The minimum s-t cut between two vertices is known to be same * as the maximum flow between these two vertices. So this function * calls \ref igraph_maxflow_value() to do the calculation. * \param graph The input graph. * \param value Pointer to a real variable, the result will be stored * here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \param capacity Pointer to the capacity vector, it should contain * non-negative numbers and its length should be the same the * the number of edges in the graph. It can be a null pointer, then * every edge has unit capacity. * \return Error code. * * Time complexity: O(|V|^3), see also the discussion for \ref * igraph_maxflow_value(), |V| is the number of vertices. */ int igraph_st_mincut_value(const igraph_t *graph, igraph_real_t *value, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity) { if (source == target) { IGRAPH_ERROR("source and target vertices are the same", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_maxflow_value(graph, value, source, target, capacity, 0)); return 0; } /** * \function igraph_st_mincut * Minimum cut between a source and a target vertex * * Finds the edge set that has the smallest total capacity among all * edge sets that disconnect the source and target vertices. * * The calculation is performed using maximum flow * techniques, by calling \ref igraph_maxflow(). * \param graph The input graph. * \param value Pointer to a real variable, the value of the cut is * stored here. * \param cut Pointer to a real vector, the edge ids that are included * in the cut are stored here. This argument is ignored if it * is a null pointer. * \param partition Pointer to a real vector, the vertex ids of the * vertices in the first partition of the cut are stored * here. The first partition is always the one that contains the * source vertex. This argument is ignored if it is a null pointer. * \param partition2 Pointer to a real vector, the vertex ids of the * vertices in the second partition of the cut are stored here. * The second partition is always the one that contains the * target vertex. This argument is ignored if it is a null pointer. * \param source Integer, the id of the source vertex. * \param target Integer, the id of the target vertex. * \param capacity Vector containing the capacity of the edges. If a * null pointer, then every edge is considered to have capacity * 1.0. * \return Error code. * * \sa \ref igraph_maxflow(). * * Time complexity: see \ref igraph_maxflow(). */ int igraph_st_mincut(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *cut, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_integer_t source, igraph_integer_t target, const igraph_vector_t *capacity) { return igraph_maxflow(graph, value, /*flow=*/ 0, cut, partition, partition2, source, target, capacity, 0); } /* This is a flow-based version, but there is a better one for undirected graphs */ /* int igraph_i_mincut_value_undirected(const igraph_t *graph, */ /* igraph_real_t *res, */ /* const igraph_vector_t *capacity) { */ /* long int no_of_edges=igraph_ecount(graph); */ /* long int no_of_nodes=igraph_vcount(graph); */ /* igraph_vector_t edges; */ /* igraph_vector_t newcapacity; */ /* igraph_t newgraph; */ /* long int i; */ /* /\* We need to convert this to directed by hand, since we need to be */ /* sure that the edge ids will be handled properly to build the new */ /* capacity vector. *\/ */ /* IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); */ /* IGRAPH_VECTOR_INIT_FINALLY(&newcapacity, no_of_edges*2); */ /* IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*4)); */ /* IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); */ /* IGRAPH_CHECK(igraph_vector_resize(&edges, no_of_edges*4)); */ /* for (i=0; i= 2) { long int last; igraph_real_t acut; long int a, n; igraph_vector_int_t *edges, *edges2; igraph_vector_int_t *neis, *neis2; do { a=igraph_i_cutheap_popmax(&heap); /* update the weights of the active vertices connected to a */ edges=igraph_inclist_get(&inclist, a); neis=igraph_adjlist_get(&adjlist, a); n=igraph_vector_int_size(edges); for (i=0; i 1); /* Now, there is only one active vertex left, calculate the cut of the phase */ acut=igraph_i_cutheap_maxvalue(&heap); last=igraph_i_cutheap_popmax(&heap); if (acut < mincut) { mincut=acut; mincut_step=act_step; } if (mincut == 0) { break; } /* And contract the last and the remaining vertex (a and last) */ /* Before actually doing that, make some notes */ act_step++; if (calc_cut) { IGRAPH_CHECK(igraph_vector_push_back(&mergehist, a)); IGRAPH_CHECK(igraph_vector_push_back(&mergehist, last)); } /* First remove the a--last edge if there is one, a is still the last deactivated vertex */ edges=igraph_inclist_get(&inclist, a); neis=igraph_adjlist_get(&adjlist, a); n=igraph_vector_int_size(edges); for (i=0; i=0; i--) { if ( mark[ (long int) VECTOR(mergehist)[2*i] ] ) { size++; mark [ (long int) VECTOR(mergehist)[2*i+1] ]=1; } } /* now store them, if requested */ if (partition) { IGRAPH_CHECK(igraph_vector_resize(partition, size)); idx=0; VECTOR(*partition)[idx++]=bignode; for (i=mincut_step-1; i>=0; i--) { if (mark[ (long int) VECTOR(mergehist)[2*i] ]) { VECTOR(*partition)[idx++] = VECTOR(mergehist)[2*i+1]; } } } /* The other partition too? */ if (partition2) { IGRAPH_CHECK(igraph_vector_resize(partition2, no_of_nodes-size)); idx=0; for (i=0; i For directed graphs an implementation based on * calculating 2|V|-2 maximum flows is used. * For undirected graphs we use the Stoer-Wagner * algorithm, as described in M. Stoer and F. Wagner: A simple min-cut * algorithm, Journal of the ACM, 44 585-591, 1997. * * * The first implementation of the actual cut calculation for * undirected graphs was made by Gregory Benison, thanks Greg. * \param graph The input graph. * \param value Pointer to a float, the value of the cut will be * stored here. * \param partition Pointer to an initialized vector, the ids * of the vertices in the first partition after separating the * graph will be stored here. The vector will be resized as * needed. This argument is ignored if it is a NULL pointer. * \param partition2 Pointer to an initialized vector the ids * of the vertices in the second partition will be stored here. * The vector will be resized as needed. This argument is ignored * if it is a NULL pointer. * \param cut Pointer to an initialized vector, the ids of the edges * in the cut will be stored here. This argument is ignored if it * is a NULL pointer. * \param capacity A numeric vector giving the capacities of the * edges. If a null pointer then all edges have unit capacity. * \return Error code. * * \sa \ref igraph_mincut_value(), a simpler interface for calculating * the value of the cut only. * * Time complexity: for directed graphs it is O(|V|^4), but see the * remarks at \ref igraph_maxflow(). For undirected graphs it is * O(|V||E|+|V|^2 log|V|). |V| and |E| are the number of vertices and * edges respectively. * * \example examples/simple/igraph_mincut.c */ int igraph_mincut(const igraph_t *graph, igraph_real_t *value, igraph_vector_t *partition, igraph_vector_t *partition2, igraph_vector_t *cut, const igraph_vector_t *capacity) { if (igraph_is_directed(graph)) { if (partition || partition2 || cut) { igraph_i_mincut_directed(graph, value, partition, partition2, cut, capacity); } else { return igraph_mincut_value(graph, value, capacity); } } else { IGRAPH_CHECK(igraph_i_mincut_undirected(graph, value, partition, partition2, cut, capacity)); return IGRAPH_SUCCESS; } return 0; } int igraph_i_mincut_value_undirected(const igraph_t *graph, igraph_real_t *res, const igraph_vector_t *capacity) { return igraph_i_mincut_undirected(graph, res, 0, 0, 0, capacity); } /** * \function igraph_mincut_value * \brief The minimum edge cut in a graph * * The minimum edge cut in a graph is the total minimum * weight of the edges needed to remove from the graph to make the * graph \em not strongly connected. (If the original graph is not * strongly connected then this is zero.) Note that in undirected * graphs strong connectedness is the same as weak connectedness. * * The minimum cut can be calculated with maximum flow * techniques, although the current implementation does this only for * directed graphs and a separate non-flow based implementation is * used for undirected graphs. See Mechthild Stoer and Frank Wagner: A * simple min-cut algorithm, Journal of the ACM 44 585--591, 1997. * For directed graphs * the maximum flow is calculated between a fixed vertex and all the * other vertices in the graph and this is done in both * directions. Then the minimum is taken to get the minimum cut. * * \param graph The input graph. * \param res Pointer to a real variable, the result will be stored * here. * \param capacity Pointer to the capacity vector, it should contain * the same number of non-negative numbers as the number of edges in * the graph. If a null pointer then all edges will have unit capacity. * \return Error code. * * \sa \ref igraph_mincut(), \ref igraph_maxflow_value(), \ref * igraph_st_mincut_value(). * * Time complexity: O(log(|V|)*|V|^2) for undirected graphs and * O(|V|^4) for directed graphs, but see also the discussion at the * documentation of \ref igraph_maxflow_value(). */ int igraph_mincut_value(const igraph_t *graph, igraph_real_t *res, const igraph_vector_t *capacity) { long int no_of_nodes=igraph_vcount(graph); igraph_real_t minmaxflow, flow; long int i; minmaxflow=IGRAPH_INFINITY; if (!igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_mincut_value_undirected(graph, res, capacity)); return 0; } for (i=1; i=no_of_nodes || target<0 || target>=no_of_nodes) { IGRAPH_ERROR("Invalid source or target vertex", IGRAPH_EINVAL); } switch (neighbors) { case IGRAPH_VCONN_NEI_ERROR: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn1)); if (conn1) { IGRAPH_ERROR("vertices connected", IGRAPH_EINVAL); return 0; } break; case IGRAPH_VCONN_NEI_NEGATIVE: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn1)); if (conn1) { *res=-1; return 0; } break; case IGRAPH_VCONN_NEI_NUMBER_OF_NODES: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn1)); if (conn1) { *res=no_of_nodes; return 0; } break; case IGRAPH_VCONN_NEI_IGNORE: break; default: IGRAPH_ERROR("Unknown `igraph_vconn_nei_t'", IGRAPH_EINVAL); break; } /* Create the new graph */ IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, 2*(no_of_edges+no_of_nodes))); IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); IGRAPH_CHECK(igraph_vector_resize(&edges, 2*(no_of_edges+no_of_nodes))); for (i=0; i<2*no_of_edges; i+=2) { igraph_integer_t to=(igraph_integer_t) VECTOR(edges)[i+1]; if (to != source && to != target) { VECTOR(edges)[i+1] = no_of_nodes + to; } } for (i=0; i=no_of_nodes || target<0 || target>=no_of_nodes) { IGRAPH_ERROR("Invalid source or target vertex", IGRAPH_EINVAL); } switch (neighbors) { case IGRAPH_VCONN_NEI_ERROR: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn)); if (conn) { IGRAPH_ERROR("vertices connected", IGRAPH_EINVAL); return 0; } break; case IGRAPH_VCONN_NEI_NEGATIVE: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn)); if (conn) { *res=-1; return 0; } break; case IGRAPH_VCONN_NEI_NUMBER_OF_NODES: IGRAPH_CHECK(igraph_are_connected(graph, source, target, &conn)); if (conn) { *res=no_of_nodes; return 0; } break; case IGRAPH_VCONN_NEI_IGNORE: break; default: IGRAPH_ERROR("Unknown `igraph_vconn_nei_t'", IGRAPH_EINVAL); break; } IGRAPH_CHECK(igraph_copy(&newgraph, graph)); IGRAPH_FINALLY(igraph_destroy, &newgraph); IGRAPH_CHECK(igraph_to_directed(&newgraph, IGRAPH_TO_DIRECTED_MUTUAL)); IGRAPH_CHECK(igraph_i_st_vertex_connectivity_directed(&newgraph, res, source, target, IGRAPH_VCONN_NEI_IGNORE)); igraph_destroy(&newgraph); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_st_vertex_connectivity * \brief The vertex connectivity of a pair of vertices * * The vertex connectivity of two vertices (\c source and * \c target) is the minimum number of vertices that have to be * deleted to eliminate all paths from \c source to \c * target. Directed paths are considered in directed graphs. * * The vertex connectivity of a pair is the same as the number * of different (ie. node-independent) paths from source to * target. * * The current implementation uses maximum flow calculations to * obtain the result. * \param graph The input graph. * \param res Pointer to an integer, the result will be stored here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \param neighbors A constant giving what to do if the two vertices * are connected. Possible values: * \c IGRAPH_VCONN_NEI_ERROR, stop with an error message, * \c IGRAPH_VCONN_NEGATIVE, return -1. * \c IGRAPH_VCONN_NUMBER_OF_NODES, return the number of nodes. * \c IGRAPH_VCONN_IGNORE, ignore the fact that the two vertices * are connected and calculated the number of vertices needed * to eliminate all paths except for the trivial (direct) paths * between \c source and \c vertex. TOOD: what about neighbors? * \return Error code. * * Time complexity: O(|V|^3), but see the discussion at \ref * igraph_maxflow_value(). * * \sa \ref igraph_vertex_connectivity(), * \ref igraph_edge_connectivity(), * \ref igraph_maxflow_value(). */ int igraph_st_vertex_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target, igraph_vconn_nei_t neighbors) { if (source == target) { IGRAPH_ERROR("source and target vertices are the same", IGRAPH_EINVAL); } if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_directed(graph, res, source, target, neighbors)); } else { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_undirected(graph, res, source, target, neighbors)); } return 0; } int igraph_i_vertex_connectivity_directed(const igraph_t *graph, igraph_integer_t *res) { igraph_integer_t no_of_nodes=(igraph_integer_t) igraph_vcount(graph); long int i, j; igraph_integer_t minconn=no_of_nodes-1, conn; for (i=0; i The vertex connectivity of a graph is the minimum * vertex connectivity along each pairs of vertices in the graph. * * The vertex connectivity of a graph is the same as group * cohesion as defined in Douglas R. White and Frank Harary: The * cohesiveness of blocks in social networks: node connectivity and * conditional density, Sociological Methodology 31:305--359, 2001. * \param graph The input graph. * \param res Pointer to an integer, the result will be stored here. * \param checks Logical constant. Whether to check that the graph is * connected and also the degree of the vertices. If the graph is * not (strongly) connected then the connectivity is obviously zero. Otherwise * if the minimum degree is one then the vertex connectivity is also * one. It is a good idea to perform these checks, as they can be * done quickly compared to the connectivity calculation itself. * They were suggested by Peter McMahan, thanks Peter. * \return Error code. * * Time complexity: O(|V|^5). * * \sa \ref igraph_st_vertex_connectivity(), \ref igraph_maxflow_value(), * and \ref igraph_edge_connectivity(). */ int igraph_vertex_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks) { igraph_bool_t ret=0; if (checks) { IGRAPH_CHECK(igraph_i_connectivity_checks(graph, res, &ret)); } /* Are we done yet? */ if (!ret) { if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_vertex_connectivity_directed(graph, res)); } else { IGRAPH_CHECK(igraph_i_vertex_connectivity_undirected(graph, res)); } } return 0; } /** * \function igraph_st_edge_connectivity * \brief Edge connectivity of a pair of vertices * * The edge connectivity of two vertices (\c source and * \c target) in a graph is the minimum number of edges that * have to be deleted from the graph to eliminate all paths from \c * source to \c target. * * This function uses the maximum flow algorithm to calculate * the edge connectivity. * \param graph The input graph, it has to be directed. * \param res Pointer to an integer, the result will be stored here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \return Error code. * * Time complexity: O(|V|^3). * * \sa \ref igraph_maxflow_value(), \ref igraph_edge_connectivity(), * \ref igraph_st_vertex_connectivity(), \ref * igraph_vertex_connectivity(). */ int igraph_st_edge_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target) { igraph_real_t flow; if (source == target) { IGRAPH_ERROR("source and target vertices are the same", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_maxflow_value(graph, &flow, source, target, 0, 0)); *res = (igraph_integer_t) flow; return 0; } /** * \function igraph_edge_connectivity * \brief The minimum edge connectivity in a graph. * * This is the minimum of the edge connectivity over all * pairs of vertices in the graph. * * * The edge connectivity of a graph is the same as group adhesion as * defined in Douglas R. White and Frank Harary: The cohesiveness of * blocks in social networks: node connectivity and conditional * density, Sociological Methodology 31:305--359, 2001. * \param graph The input graph. * \param res Pointer to an integer, the result will be stored here. * \param checks Logical constant. Whether to check that the graph is * connected and also the degree of the vertices. If the graph is * not (strongly) connected then the connectivity is obviously zero. Otherwise * if the minimum degree is one then the edge connectivity is also * one. It is a good idea to perform these checks, as they can be * done quickly compared to the connectivity calculation itself. * They were suggested by Peter McMahan, thanks Peter. * \return Error code. * * Time complexity: O(log(|V|)*|V|^2) for undirected graphs and * O(|V|^4) for directed graphs, but see also the discussion at the * documentation of \ref igraph_maxflow_value(). * * \sa \ref igraph_st_edge_connectivity(), \ref igraph_maxflow_value(), * \ref igraph_vertex_connectivity(). */ int igraph_edge_connectivity(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks) { igraph_bool_t ret=0; /* Use that vertex.connectivity(G) <= edge.connectivity(G) <= min(degree(G)) */ if (checks) { IGRAPH_CHECK(igraph_i_connectivity_checks(graph, res, &ret)); } if (!ret) { igraph_real_t real_res; IGRAPH_CHECK(igraph_mincut_value(graph, &real_res, 0)); *res = (igraph_integer_t)real_res; } return 0; } /** * \function igraph_edge_disjoint_paths * \brief The maximum number of edge-disjoint paths between two vertices. * * A set of paths between two vertices is called * edge-disjoint if they do not share any edges. The maximum number of * edge-disjoint paths are calculated by this function using maximum * flow techniques. Directed paths are considered in directed * graphs. * * Note that the number of disjoint paths is the same as the * edge connectivity of the two vertices using uniform edge weights. * \param graph The input graph, can be directed or undirected. * \param res Pointer to an integer variable, the result will be * stored here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \return Error code. * * Time complexity: O(|V|^3), but see the discussion at \ref * igraph_maxflow_value(). * * \sa \ref igraph_vertex_disjoint_paths(), \ref * igraph_st_edge_connectivity(), \ref igraph_maxflow_value(). */ int igraph_edge_disjoint_paths(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target) { igraph_real_t flow; if (source == target) { IGRAPH_ERROR("Not implemented for source=target", IGRAPH_UNIMPLEMENTED); } IGRAPH_CHECK(igraph_maxflow_value(graph, &flow, source, target, 0, 0)); *res = (igraph_integer_t) flow; return 0; } /** * \function igraph_vertex_disjoint_paths * \brief Maximum number of vertex-disjoint paths between two vertices. * * A set of paths between two vertices is called * vertex-disjoint if they share no vertices. The calculation is * performed by using maximum flow techniques. * * Note that the number of vertex-disjoint paths is the same as * the vertex connectivity of the two vertices in most cases (if the * two vertices are not connected by an edge). * \param graph The input graph. * \param res Pointer to an integer variable, the result will be * stored here. * \param source The id of the source vertex. * \param target The id of the target vertex. * \return Error code. * * Time complexity: O(|V|^3). * * \sa \ref igraph_edge_disjoint_paths(), \ref * igraph_vertex_connectivity(), \ref igraph_maxflow_value(). */ int igraph_vertex_disjoint_paths(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t source, igraph_integer_t target) { igraph_bool_t conn; if (source==target) { IGRAPH_ERROR("The source==target case is not implemented", IGRAPH_UNIMPLEMENTED); } igraph_are_connected(graph, source, target, &conn); if (conn) { /* We need to remove every (possibly directed) edge between source and target and calculate the disjoint paths on the new graph. Finally we add 1 for the removed connection(s). */ igraph_es_t es; igraph_vector_t v; igraph_t newgraph; IGRAPH_VECTOR_INIT_FINALLY(&v, 2); VECTOR(v)[0]=source; VECTOR(v)[1]=target; IGRAPH_CHECK(igraph_es_multipairs(&es, &v, IGRAPH_DIRECTED)); IGRAPH_FINALLY(igraph_es_destroy, &es); IGRAPH_CHECK(igraph_copy(&newgraph, graph)); IGRAPH_FINALLY(igraph_destroy, &newgraph); IGRAPH_CHECK(igraph_delete_edges(&newgraph, es)); if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_directed(&newgraph, res, source, target, IGRAPH_VCONN_NEI_IGNORE)); } else { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_undirected(&newgraph, res, source, target, IGRAPH_VCONN_NEI_IGNORE)); } if (res) { *res += 1; } IGRAPH_FINALLY_CLEAN(3); igraph_destroy(&newgraph); igraph_es_destroy(&es); igraph_vector_destroy(&v); } /* These do nothing if the two vertices are connected, so it is safe to call them. */ if (igraph_is_directed(graph)) { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_directed(graph, res, source, target, IGRAPH_VCONN_NEI_IGNORE)); } else { IGRAPH_CHECK(igraph_i_st_vertex_connectivity_undirected(graph, res, source, target, IGRAPH_VCONN_NEI_IGNORE)); } return 0; } /** * \function igraph_adhesion * \brief Graph adhesion, this is (almost) the same as edge connectivity. * * This quantity is defined by White and Harary in * The cohesiveness of blocks in social networks: node connectivity and * conditional density, (Sociological Methodology 31:305--359, 2001) * and basically it is the edge connectivity of the graph * with uniform edge weights. * \param graph The input graph, either directed or undirected. * \param res Pointer to an integer, the result will be stored here. * \param checks Logical constant. Whether to check that the graph is * connected and also the degree of the vertices. If the graph is * not (strongly) connected then the adhesion is obviously zero. Otherwise * if the minimum degree is one then the adhesion is also * one. It is a good idea to perform these checks, as they can be * done quickly compared to the edge connectivity calculation itself. * They were suggested by Peter McMahan, thanks Peter. * \return Error code. * * Time complexity: O(log(|V|)*|V|^2) for undirected graphs and * O(|V|^4) for directed graphs, but see also the discussion at the * documentation of \ref igraph_maxflow_value(). * * \sa \ref igraph_cohesion(), \ref igraph_maxflow_value(), \ref * igraph_edge_connectivity(), \ref igraph_mincut_value(). */ int igraph_adhesion(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks) { return igraph_edge_connectivity(graph, res, checks); } /** * \function igraph_cohesion * \brief Graph cohesion, this is the same as vertex connectivity. * * This quantity was defined by White and Harary in The * cohesiveness of blocks in social networks: node connectivity and * conditional density, (Sociological Methodology 31:305--359, 2001) * and it is the same as the vertex connectivity of a * graph. * \param graph The input graph. * \param res Pointer to an integer variable, the result will be * stored here. * \param checks Logical constant. Whether to check that the graph is * connected and also the degree of the vertices. If the graph is * not (strongly) connected then the cohesion is obviously zero. Otherwise * if the minimum degree is one then the cohesion is also * one. It is a good idea to perform these checks, as they can be * done quickly compared to the vertex connectivity calculation itself. * They were suggested by Peter McMahan, thanks Peter. * \return Error code. * * Time complexity: O(|V|^4), |V| is the number of vertices. In * practice it is more like O(|V|^2), see \ref igraph_maxflow_value(). * * \sa \ref igraph_vertex_connectivity(), \ref igraph_adhesion(), * \ref igraph_maxflow_value(). */ int igraph_cohesion(const igraph_t *graph, igraph_integer_t *res, igraph_bool_t checks) { IGRAPH_CHECK(igraph_vertex_connectivity(graph, res, checks)); return 0; } /** * \function igraph_gomory_hu_tree * \brief Gomory-Hu tree of a graph. * * * The Gomory-Hu tree is a concise representation of the value of all the * maximum flows (or minimum cuts) in a graph. The vertices of the tree * correspond exactly to the vertices of the original graph in the same order. * Edges of the Gomory-Hu tree are annotated by flow values. The value of * the maximum flow (or minimum cut) between an arbitrary (u,v) vertex * pair in the original graph is then given by the minimum flow value (i.e. * edge annotation) along the shortest path between u and v in the * Gomory-Hu tree. * * This implementation uses Gusfield's algorithm to construct the * Gomory-Hu tree. See the following paper for more details: * * * Gusfield D: Very simple methods for all pairs network flow analysis. SIAM J * Comput 19(1):143-155, 1990. * * \param graph The input graph. * \param tree Pointer to an uninitialized graph; the result will be * stored here. * \param flows Pointer to an uninitialized vector; the flow values * corresponding to each edge in the Gomory-Hu tree will * be returned here. You may pass a NULL pointer here if you are * not interested in the flow values. * \param capacity Vector containing the capacity of the edges. If NULL, then * every edge is considered to have capacity 1.0. * \return Error code. * * Time complexity: O(|V|^4) since it performs a max-flow calculation * between vertex zero and every other vertex and max-flow is * O(|V|^3). * * \sa \ref igraph_maxflow() */ int igraph_gomory_hu_tree(const igraph_t *graph, igraph_t *tree, igraph_vector_t *flows, const igraph_vector_t *capacity) { igraph_integer_t no_of_nodes = igraph_vcount(graph); igraph_integer_t source, target, mid, i, n; igraph_vector_t neighbors; igraph_vector_t flow_values; igraph_vector_t partition; igraph_vector_t partition2; igraph_real_t flow_value; if (igraph_is_directed(graph)) { IGRAPH_ERROR("Gomory-Hu tree can only be calculated for undirected graphs", IGRAPH_EINVAL); } /* Allocate memory */ IGRAPH_VECTOR_INIT_FINALLY(&neighbors, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&flow_values, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&partition, 0); IGRAPH_VECTOR_INIT_FINALLY(&partition2, 0); /* Initialize the tree: every edge points to node 0 */ /* Actually, this is done implicitly since both 'neighbors' and 'flow_values' are * initialized to zero already */ /* For each source vertex except vertex zero... */ for (source = 1; source < no_of_nodes; source++) { IGRAPH_ALLOW_INTERRUPTION(); IGRAPH_PROGRESS("Gomory-Hu tree", (100.0 * (source - 1)) / (no_of_nodes-1), 0); /* Find its current neighbor in the tree */ target = VECTOR(neighbors)[(long int)source]; /* Find the maximum flow between source and target */ IGRAPH_CHECK(igraph_maxflow(graph, &flow_value, 0, 0, &partition, &partition2, source, target, capacity, 0)); /* Store the maximum flow and determine which side each node is on */ VECTOR(flow_values)[(long int)source] = flow_value; /* Update the tree */ /* igraph_maxflow() guarantees that the source vertex will be in &partition * and not in &partition2 */ n = igraph_vector_size(&partition); for (i = 0; i < n; i++) { mid = VECTOR(partition)[i]; if (mid > source && VECTOR(neighbors)[(long int)mid] == target) { VECTOR(neighbors)[(long int)mid] = source; } } } IGRAPH_PROGRESS("Gomory-Hu tree", 100.0, 0); /* Re-use the 'partition' vector as an edge list now */ IGRAPH_CHECK(igraph_vector_resize(&partition, 2*(no_of_nodes-1))); for (i = 1, mid = 0; i < no_of_nodes; i++, mid += 2) { VECTOR(partition)[(long int)mid] = i; VECTOR(partition)[(long int)mid+1] = VECTOR(neighbors)[(long int)i]; } /* Create the tree graph; we use igraph_subgraph_edges here to keep the * graph and vertex attributes */ IGRAPH_CHECK(igraph_subgraph_edges(graph, tree, igraph_ess_none(), 0)); IGRAPH_CHECK(igraph_add_edges(tree, &partition, 0)); /* Free the allocated memory */ igraph_vector_destroy(&partition2); igraph_vector_destroy(&partition); igraph_vector_destroy(&neighbors); IGRAPH_FINALLY_CLEAN(3); /* Return the flow values to the caller */ if (flows != 0) { IGRAPH_CHECK(igraph_vector_update(flows, &flow_values)); if (no_of_nodes > 0) { igraph_vector_remove(flows, 0); } } /* Free the remaining allocated memory */ igraph_vector_destroy(&flow_values); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } igraph/src/gengraph_box_list.cpp0000644000175100001440000000410313431000472016523 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_box_list.h" #include namespace gengraph { void box_list::insert(int v) { register int d = deg[v]; if(d<1) return; if(d>dmax) dmax=d; int yo = list[d-1]; list[d-1] = v; prev[v] = -1; next[v] = yo; if(yo>=0) prev[yo]=v; } void box_list::pop(int v) { register int p = prev[v]; register int n = next[v]; if(p<0) { register int d = deg[v]; assert(list[d-1]==v); list[d-1] = n; if(d==dmax && n<0) do dmax--; while(dmax>0 && list[dmax-1]<0); } else next[p] = n; if(n>=0) prev[n] = p; } box_list::box_list(int n0, int *deg0) : n(n0), deg(deg0) { next = new int[n]; prev = new int[n]; dmax = -1; int i; for(i=0; idmax) dmax=deg[i]; list = new int[dmax]; for(i=0; i * * Copyright (C) 2008 David Morton de Lachapelle * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * * DESCRIPTION * ----------- * This file implements algorithm 5.8 of the above reference. * The optimal_partition function returns the minimizing partition * with size 'nt' of the objective function ||v-Pv||, where P is * a problem-specific projector. So far, Symmetric (matrix=1), * Laplacian (matrix=2) and Stochastic (matrix=3) projectors * have been implemented (the cost_matrix function below). * In the stochastic case, 'p' is expected to be a valid propability * vector. In all other cases, 'p' is ignored and can be set to NULL. * The group labels are given in 'gr' as positive consecutive integers * starting from 0. */ #include "igraph_error.h" #include "igraph_memory.h" #include "igraph_matrix.h" #include "igraph_vector.h" #include "scg_headers.h" int igraph_i_optimal_partition(const igraph_real_t *v, int *gr, int n, int nt, int matrix, const igraph_real_t *p, igraph_real_t *value) { int i, non_ties, q, j, l, part_ind, col; igraph_i_scg_indval_t *vs = igraph_Calloc(n, igraph_i_scg_indval_t); igraph_real_t *Cv, temp, sumOfSquares; igraph_vector_t ps; igraph_matrix_t F; igraph_matrix_int_t Q; /*----------------------------------------------- -----Sorts v and counts non-ties----------------- -----------------------------------------------*/ if (!vs) { IGRAPH_ERROR("SCG error", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vs); for (i=0; i vs[i-1].val + 1e-14) { non_ties++; } } if (nt >= non_ties) { IGRAPH_ERROR("`Invalid number of intervals, should be smaller than " "number of unique values in V", IGRAPH_EINVAL); } /*------------------------------------------------ ------Computes Cv, the matrix of costs------------ ------------------------------------------------*/ Cv = igraph_i_real_sym_matrix(n); if (!Cv) { IGRAPH_ERROR("SCG error", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, Cv); /* if stochastic SCG orders p */ if (matrix==3) { IGRAPH_VECTOR_INIT_FINALLY(&ps, n); for (i=0; i=0;j--)", for such loops never ends!*/ IGRAPH_MATRIX_INIT_FINALLY(&F, nt, n); IGRAPH_CHECK(igraph_matrix_int_init(&Q, nt, n)); IGRAPH_FINALLY(igraph_matrix_destroy, &Q); for (i=0; i=0; j--) { for (i=MATRIX(Q, j, col)-1; i<=col; i++) gr[vs[i].ind] = part_ind-1; if (MATRIX(Q, j, col) != 2) { col = MATRIX(Q, j, col)-2; part_ind -= 1; } else{ if (j>1) { for (l=0; l<=(j-1); l++) gr[vs[l].ind] = l; break; } else{ col = MATRIX(Q, j, col)-2; part_ind -= 1; } } } sumOfSquares = MATRIX(F, nt-1, n-1); igraph_matrix_destroy(&F); igraph_matrix_int_destroy(&Q); igraph_Free(vs); IGRAPH_FINALLY_CLEAN(3); if (value) { *value=sumOfSquares; } return 0; } int igraph_i_cost_matrix(igraph_real_t*Cv, const igraph_i_scg_indval_t *vs, int n, int matrix, const igraph_vector_t *ps) { /* if symmetric of Laplacian SCG -> same Cv */ if (matrix==1 || matrix==2) { int i,j; igraph_vector_t w, w2; IGRAPH_VECTOR_INIT_FINALLY(&w, n+1); IGRAPH_VECTOR_INIT_FINALLY(&w2, n+1); VECTOR(w)[1] = vs[0].val; VECTOR(w2)[1] = vs[0].val*vs[0].val; for (i=2; i<=n; i++) { VECTOR(w)[i] = VECTOR(w)[i-1] + vs[i-1].val; VECTOR(w2)[i] = VECTOR(w2)[i-1] + vs[i-1].val*vs[i-1].val; } for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_arpack.h" #include "igraph_arpack_internal.h" #include "igraph_memory.h" #include #include #include /* The ARPACK example file dssimp.f is used as a template */ int igraph_i_arpack_err_dsaupd(int error) { switch (error) { case 1: return IGRAPH_ARPACK_MAXIT; case 3: return IGRAPH_ARPACK_NOSHIFT; case -1: return IGRAPH_ARPACK_NPOS; case -2: return IGRAPH_ARPACK_NEVNPOS; case -3: return IGRAPH_ARPACK_NCVSMALL; case -4: return IGRAPH_ARPACK_NONPOSI; case -5: return IGRAPH_ARPACK_WHICHINV; case -6: return IGRAPH_ARPACK_BMATINV; case -7: return IGRAPH_ARPACK_WORKLSMALL; case -8: return IGRAPH_ARPACK_TRIDERR; case -9: return IGRAPH_ARPACK_ZEROSTART; case -10: return IGRAPH_ARPACK_MODEINV; case -11: return IGRAPH_ARPACK_MODEBMAT; case -12: return IGRAPH_ARPACK_ISHIFT; case -13: return IGRAPH_ARPACK_NEVBE; case -9999: return IGRAPH_ARPACK_NOFACT; default: return IGRAPH_ARPACK_UNKNOWN; } } int igraph_i_arpack_err_dseupd(int error) { switch (error) { case -1: return IGRAPH_ARPACK_NPOS; case -2: return IGRAPH_ARPACK_NEVNPOS; case -3: return IGRAPH_ARPACK_NCVSMALL; case -5: return IGRAPH_ARPACK_WHICHINV; case -6: return IGRAPH_ARPACK_BMATINV; case -7: return IGRAPH_ARPACK_WORKLSMALL; case -8: return IGRAPH_ARPACK_TRIDERR; case -9: return IGRAPH_ARPACK_ZEROSTART; case -10: return IGRAPH_ARPACK_MODEINV; case -11: return IGRAPH_ARPACK_MODEBMAT; case -12: return IGRAPH_ARPACK_NEVBE; case -14: return IGRAPH_ARPACK_FAILED; case -15: return IGRAPH_ARPACK_HOWMNY; case -16: return IGRAPH_ARPACK_HOWMNYS; case -17: return IGRAPH_ARPACK_EVDIFF; default: return IGRAPH_ARPACK_UNKNOWN; } } int igraph_i_arpack_err_dnaupd(int error) { switch (error) { case 1: return IGRAPH_ARPACK_MAXIT; case 3: return IGRAPH_ARPACK_NOSHIFT; case -1: return IGRAPH_ARPACK_NPOS; case -2: return IGRAPH_ARPACK_NEVNPOS; case -3: return IGRAPH_ARPACK_NCVSMALL; case -4: return IGRAPH_ARPACK_NONPOSI; case -5: return IGRAPH_ARPACK_WHICHINV; case -6: return IGRAPH_ARPACK_BMATINV; case -7: return IGRAPH_ARPACK_WORKLSMALL; case -8: return IGRAPH_ARPACK_TRIDERR; case -9: return IGRAPH_ARPACK_ZEROSTART; case -10: return IGRAPH_ARPACK_MODEINV; case -11: return IGRAPH_ARPACK_MODEBMAT; case -12: return IGRAPH_ARPACK_ISHIFT; case -9999: return IGRAPH_ARPACK_NOFACT; default: return IGRAPH_ARPACK_UNKNOWN; } } int igraph_i_arpack_err_dneupd(int error) { switch (error) { case 1: return IGRAPH_ARPACK_REORDER; case -1: return IGRAPH_ARPACK_NPOS; case -2: return IGRAPH_ARPACK_NEVNPOS; case -3: return IGRAPH_ARPACK_NCVSMALL; case -5: return IGRAPH_ARPACK_WHICHINV; case -6: return IGRAPH_ARPACK_BMATINV; case -7: return IGRAPH_ARPACK_WORKLSMALL; case -8: return IGRAPH_ARPACK_SHUR; case -9: return IGRAPH_ARPACK_LAPACK; case -10: return IGRAPH_ARPACK_MODEINV; case -11: return IGRAPH_ARPACK_MODEBMAT; case -12: return IGRAPH_ARPACK_HOWMNYS; case -13: return IGRAPH_ARPACK_HOWMNY; case -14: return IGRAPH_ARPACK_FAILED; case -15: return IGRAPH_ARPACK_EVDIFF; default: return IGRAPH_ARPACK_UNKNOWN; } } /** * \function igraph_arpack_options_init * Initialize ARPACK options * * Initializes ARPACK options, set them to default values. * You can always pass the initialized \ref igraph_arpack_options_t * object to built-in igraph functions without any modification. The * built-in igraph functions modify the options to perform their * calculation, e.g. \ref igraph_pagerank() always searches for the * eigenvalue with the largest magnitude, regardless of the supplied * value. * * If you want to implement your own function involving eigenvalue * calculation using ARPACK, however, you will likely need to set up * the fields for yourself. * \param o The \ref igraph_arpack_options_t object to initialize. * * Time complexity: O(1). */ void igraph_arpack_options_init(igraph_arpack_options_t *o) { o->bmat[0]='I'; o->n=0; /* needs to be updated! */ o->which[0]='X'; o->which[1]='X'; o->nev=1; o->tol=0; o->ncv=0; /* 0 means "automatic" */ o->ldv=o->n; /* will be updated to (real) n */ o->ishift=1; o->mxiter=3000; o->nb=1; o->mode=1; o->start=0; o->lworkl=0; o->sigma=0; o->sigmai=0; o->info=o->start; o->iparam[0]=o->ishift; o->iparam[1]=0; o->iparam[2]=o->mxiter; o->iparam[3]=o->nb; o->iparam[4]=0; o->iparam[5]=0; o->iparam[6]=o->mode; o->iparam[7]=0; o->iparam[8]=0; o->iparam[9]=0; o->iparam[10]=0; } /** * \function igraph_arpack_storage_init * Initialize ARPACK storage * * You only need this function if you want to run multiple eigenvalue * calculations using ARPACK, and want to spare the memory * allocation/deallocation between each two runs. Otherwise it is safe * to supply a null pointer as the \c storage argument of both \ref * igraph_arpack_rssolve() and \ref igraph_arpack_rnsolve() to make * memory allocated and deallocated automatically. * * Don't forget to call the \ref * igraph_arpack_storage_destroy() function on the storage object if * you don't need it any more. * \param s The \ref igraph_arpack_storage_t object to initialize. * \param maxn The maximum order of the matrices. * \param maxncv The maximum NCV parameter intended to use. * \param maxldv The maximum LDV parameter intended to use. * \param symm Whether symmetric or non-symmetric problems will be * solved using this \ref igraph_arpack_storage_t. (You cannot use * the same storage both with symmetric and non-symmetric solvers.) * \return Error code. * * Time complexity: O(maxncv*(maxldv+maxn)). */ int igraph_arpack_storage_init(igraph_arpack_storage_t *s, long int maxn, long int maxncv, long int maxldv, igraph_bool_t symm) { /* TODO: check arguments */ s->maxn=(int) maxn; s->maxncv=(int) maxncv; s->maxldv=(int) maxldv; #define CHECKMEM(x) \ if (!x) { \ IGRAPH_ERROR("Cannot allocate memory for ARPACK", IGRAPH_ENOMEM); \ } \ IGRAPH_FINALLY(igraph_free, x); s->v=igraph_Calloc(maxldv * maxncv, igraph_real_t); CHECKMEM(s->v); s->workd=igraph_Calloc(3*maxn, igraph_real_t); CHECKMEM(s->workd); s->d=igraph_Calloc(2*maxncv, igraph_real_t); CHECKMEM(s->d); s->resid=igraph_Calloc(maxn, igraph_real_t); CHECKMEM(s->resid); s->ax=igraph_Calloc(maxn, igraph_real_t); CHECKMEM(s->ax); s->select=igraph_Calloc(maxncv, int); CHECKMEM(s->select); if (symm) { s->workl=igraph_Calloc(maxncv*(maxncv+8), igraph_real_t); CHECKMEM(s->workl); s->di=0; s->workev=0; } else { s->workl=igraph_Calloc(3*maxncv*(maxncv+2), igraph_real_t); CHECKMEM(s->workl); s->di=igraph_Calloc(2*maxncv, igraph_real_t); CHECKMEM(s->di); s->workev=igraph_Calloc(3*maxncv, igraph_real_t); CHECKMEM(s->workev); IGRAPH_FINALLY_CLEAN(2); } #undef CHECKMEM IGRAPH_FINALLY_CLEAN(7); return 0; } /** * \function igraph_arpack_storage_destroy * Deallocate ARPACK storage * * \param s The \ref igraph_arpack_storage_t object for which the * memory will be deallocated. * * Time complexity: operating system dependent. */ void igraph_arpack_storage_destroy(igraph_arpack_storage_t *s) { if (s->di) { igraph_Free(s->di); } if (s->workev) { igraph_Free(s->workev); } igraph_Free(s->workl); igraph_Free(s->select); igraph_Free(s->ax); igraph_Free(s->resid); igraph_Free(s->d); igraph_Free(s->workd); igraph_Free(s->v); } /** * "Solver" for 1x1 eigenvalue problems since ARPACK sometimes blows up with * these. */ int igraph_i_arpack_rssolve_1x1(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t* options, igraph_vector_t* values, igraph_matrix_t* vectors) { igraph_real_t a, b; int nev = options->nev; if (nev <= 0) { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_NEVNPOS); } /* Probe the value in the matrix */ a = 1; if (fun(&b, &a, 1, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } options->nconv=nev; if (values != 0) { IGRAPH_CHECK(igraph_vector_resize(values, 1)); VECTOR(*values)[0] = b; } if (vectors != 0) { IGRAPH_CHECK(igraph_matrix_resize(vectors, 1, 1)); MATRIX(*vectors, 0, 0) = 1; } return IGRAPH_SUCCESS; } /** * "Solver" for 1x1 eigenvalue problems since ARPACK sometimes blows up with * these. */ int igraph_i_arpack_rnsolve_1x1(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t* options, igraph_matrix_t* values, igraph_matrix_t* vectors) { igraph_real_t a, b; int nev = options->nev; if (nev <= 0) { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_NEVNPOS); } /* Probe the value in the matrix */ a = 1; if (fun(&b, &a, 1, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } options->nconv=nev; if (values != 0) { IGRAPH_CHECK(igraph_matrix_resize(values, 1, 2)); MATRIX(*values, 0, 0) = b; MATRIX(*values, 0, 1) = 0; } if (vectors != 0) { IGRAPH_CHECK(igraph_matrix_resize(vectors, 1, 1)); MATRIX(*vectors, 0, 0) = 1; } return IGRAPH_SUCCESS; } /** * "Solver" for 2x2 nonsymmetric eigenvalue problems since ARPACK sometimes * blows up with these. */ int igraph_i_arpack_rnsolve_2x2(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t* options, igraph_matrix_t* values, igraph_matrix_t* vectors) { igraph_real_t vec[2], mat[4]; igraph_real_t a, b, c, d; igraph_real_t trace, det, tsq4_minus_d; igraph_complex_t eval1, eval2; igraph_complex_t evec1[2], evec2[2]; igraph_bool_t swap_evals = 0; igraph_bool_t complex_evals = 0; int nev = options->nev; if (nev <= 0) { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_NEVNPOS); } if (nev > 2) nev = 2; /* Probe the values in the matrix */ vec[0] = 1; vec[1] = 0; if (fun(mat, vec, 2, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } vec[0] = 0; vec[1] = 1; if (fun(mat+2, vec, 2, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } a = mat[0]; b = mat[2]; c = mat[1]; d = mat[3]; /* Get the trace and the determinant */ trace = a+d; det = a*d - b*c; tsq4_minus_d = trace*trace / 4 - det; /* Calculate the eigenvalues */ complex_evals = tsq4_minus_d < 0; eval1 = igraph_complex_sqrt_real(tsq4_minus_d); if (complex_evals) { eval2 = igraph_complex_mul_real(eval1, -1); } else { /* to avoid having -0 in the imaginary part */ eval2 = igraph_complex(-IGRAPH_REAL(eval1), 0); } eval1 = igraph_complex_add_real(eval1, trace/2); eval2 = igraph_complex_add_real(eval2, trace/2); if (c != 0) { evec1[0] = igraph_complex_sub_real(eval1, d); evec1[1] = igraph_complex(c, 0); evec2[0] = igraph_complex_sub_real(eval2, d); evec2[1] = igraph_complex(c, 0); } else if (b != 0) { evec1[0] = igraph_complex(b, 0); evec1[1] = igraph_complex_sub_real(eval1, a); evec2[0] = igraph_complex(b, 0); evec2[1] = igraph_complex_sub_real(eval2, a); } else { evec1[0] = igraph_complex(1, 0); evec1[1] = igraph_complex(0, 0); evec2[0] = igraph_complex(0, 0); evec2[1] = igraph_complex(1, 0); } /* Sometimes we have to swap eval1 with eval2 and evec1 with eval2; * determine whether we have to do it now */ if (options->which[0] == 'S') { if (options->which[1] == 'M') { /* eval1 must be the one with the smallest magnitude */ swap_evals = (igraph_complex_mod(eval1) > igraph_complex_mod(eval2)); } else if (options->which[1] == 'R') { /* eval1 must be the one with the smallest real part */ swap_evals = (IGRAPH_REAL(eval1) > IGRAPH_REAL(eval2)); } else if (options->which[1] == 'I') { /* eval1 must be the one with the smallest imaginary part */ swap_evals = (IGRAPH_IMAG(eval1) > IGRAPH_IMAG(eval2)); } else { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_WHICHINV); } } else if (options->which[0] == 'L') { if (options->which[1] == 'M') { /* eval1 must be the one with the largest magnitude */ swap_evals = (igraph_complex_mod(eval1) < igraph_complex_mod(eval2)); } else if (options->which[1] == 'R') { /* eval1 must be the one with the largest real part */ swap_evals = (IGRAPH_REAL(eval1) < IGRAPH_REAL(eval2)); } else if (options->which[1] == 'I') { /* eval1 must be the one with the largest imaginary part */ swap_evals = (IGRAPH_IMAG(eval1) < IGRAPH_IMAG(eval2)); } else { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_WHICHINV); } } else if (options->which[0] == 'X' && options->which[1] == 'X') { /* No preference on the ordering of eigenvectors */ } else { /* fprintf(stderr, "%c%c\n", options->which[0], options->which[1]); */ IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_WHICHINV); } options->nconv=nev; if (swap_evals) { igraph_complex_t dummy; dummy = eval1; eval1 = eval2; eval2 = dummy; dummy = evec1[0]; evec1[0] = evec2[0]; evec2[0] = dummy; dummy = evec1[1]; evec1[1] = evec2[1]; evec2[1] = dummy; } if (complex_evals) { /* The eigenvalues are conjugate pairs, so we store only the * one with positive imaginary part */ if (IGRAPH_IMAG(eval1) < 0) { eval1 = eval2; evec1[0] = evec2[0]; evec1[1] = evec2[1]; } } if (values != 0) { IGRAPH_CHECK(igraph_matrix_resize(values, nev, 2)); MATRIX(*values, 0, 0) = IGRAPH_REAL(eval1); MATRIX(*values, 0, 1) = IGRAPH_IMAG(eval1); if (nev > 1) { MATRIX(*values, 1, 0) = IGRAPH_REAL(eval2); MATRIX(*values, 1, 1) = IGRAPH_IMAG(eval2); } } if (vectors != 0) { if (complex_evals) { IGRAPH_CHECK(igraph_matrix_resize(vectors, 2, 2)); MATRIX(*vectors, 0, 0) = IGRAPH_REAL(evec1[0]); MATRIX(*vectors, 1, 0) = IGRAPH_REAL(evec1[1]); MATRIX(*vectors, 0, 1) = IGRAPH_IMAG(evec1[0]); MATRIX(*vectors, 1, 1) = IGRAPH_IMAG(evec1[1]); } else { IGRAPH_CHECK(igraph_matrix_resize(vectors, 2, nev)); MATRIX(*vectors, 0, 0) = IGRAPH_REAL(evec1[0]); MATRIX(*vectors, 1, 0) = IGRAPH_REAL(evec1[1]); if (nev > 1) { MATRIX(*vectors, 0, 1) = IGRAPH_REAL(evec2[0]); MATRIX(*vectors, 1, 1) = IGRAPH_REAL(evec2[1]); } } } return IGRAPH_SUCCESS; } /** * "Solver" for symmetric 2x2 eigenvalue problems since ARPACK sometimes blows * up with these. */ int igraph_i_arpack_rssolve_2x2(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t* options, igraph_vector_t* values, igraph_matrix_t* vectors) { igraph_real_t vec[2], mat[4]; igraph_real_t a, b, c, d; igraph_real_t trace, det, tsq4_minus_d; igraph_real_t eval1, eval2; int nev = options->nev; if (nev <= 0) { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_NEVNPOS); } if (nev > 2) nev = 2; /* Probe the values in the matrix */ vec[0] = 1; vec[1] = 0; if (fun(mat, vec, 2, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } vec[0] = 0; vec[1] = 1; if (fun(mat+2, vec, 2, extra)) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } a = mat[0]; b = mat[2]; c = mat[1]; d = mat[3]; /* Get the trace and the determinant */ trace = a+d; det = a*d - b*c; tsq4_minus_d = trace*trace / 4 - det; if (tsq4_minus_d >= 0) { /* Both eigenvalues are real */ eval1 = trace/2 + sqrt(tsq4_minus_d); eval2 = trace/2 - sqrt(tsq4_minus_d); if (c != 0) { mat[0] = eval1-d; mat[2] = eval2-d; mat[1] = c; mat[3] = c; } else if (b != 0) { mat[0] = b; mat[2] = b; mat[1] = eval1-a; mat[3] = eval2-a; } else { mat[0] = 1; mat[2] = 0; mat[1] = 0; mat[3] = 1; } } else { /* Both eigenvalues are complex. Should not happen with symmetric * matrices. */ IGRAPH_ERROR("ARPACK error, 2x2 matrix is not symmetric", IGRAPH_EINVAL); } /* eval1 is always the larger eigenvalue. If we want the smaller * one, we have to swap eval1 with eval2 and also the columns of mat */ if (options->which[0] == 'S') { trace = eval1; eval1 = eval2; eval2 = trace; trace = mat[0]; mat[0] = mat[2]; mat[2] = trace; trace = mat[1]; mat[1] = mat[3]; mat[3] = trace; } else if (options->which[0] == 'L' || options->which[0] == 'B') { /* Nothing to do here */ } else if (options->which[0] == 'X' && options->which[1] == 'X') { /* No preference on the ordering of eigenvectors */ } else { IGRAPH_ERROR("ARPACK error", IGRAPH_ARPACK_WHICHINV); } options->nconv=nev; if (values != 0) { IGRAPH_CHECK(igraph_vector_resize(values, nev)); VECTOR(*values)[0] = eval1; if (nev > 1) { VECTOR(*values)[1] = eval2; } } if (vectors != 0) { IGRAPH_CHECK(igraph_matrix_resize(vectors, 2, nev)); MATRIX(*vectors, 0, 0) = mat[0]; MATRIX(*vectors, 1, 0) = mat[1]; if (nev > 1) { MATRIX(*vectors, 0, 1) = mat[2]; MATRIX(*vectors, 1, 1) = mat[3]; } } return IGRAPH_SUCCESS; } int igraph_arpack_rssort(igraph_vector_t *values, igraph_matrix_t *vectors, const igraph_arpack_options_t *options, igraph_real_t *d, const igraph_real_t *v) { igraph_vector_t order; char sort[2]; int apply=1; unsigned int n=(unsigned int) options->n; int nconv=options->nconv; int nev=options->nev; unsigned int nans= (unsigned int) (nconv < nev ? nconv : nev); #define which(a,b) (options->which[0]==a && options->which[1]==b) if (which('L','A')) { sort[0]='S'; sort[1]='A'; } else if (which('S','A')) { sort[0]='L'; sort[1]='A'; } else if (which('L','M')) { sort[0]='S'; sort[1]='M'; } else if (which('S','M')) { sort[0]='L'; sort[1]='M'; } else if (which('B','E')) { sort[0]='L'; sort[1]='A'; } IGRAPH_CHECK(igraph_vector_init_seq(&order, 0, nconv-1)); IGRAPH_FINALLY(igraph_vector_destroy, &order); #ifdef HAVE_GFORTRAN igraphdsortr_(sort, &apply, &nconv, d, VECTOR(order), /*which_len=*/ 2); #else igraphdsortr_(sort, &apply, &nconv, d, VECTOR(order)); #endif /* BE is special */ if (which('B','E')) { int w=0, l1=0, l2=nev-1; igraph_vector_t order2, d2; IGRAPH_VECTOR_INIT_FINALLY(&order2, nev); IGRAPH_VECTOR_INIT_FINALLY(&d2, nev); while (l1 <= l2) { VECTOR(order2)[w] = VECTOR(order)[l1]; VECTOR(d2)[w]=d[l1]; w++; l1++; if (l1 <= l2) { VECTOR(order2)[w] = VECTOR(order)[l2]; VECTOR(d2)[w]=d[l2]; w++; l2--; } } igraph_vector_update(&order, &order2); igraph_vector_copy_to(&d2, d); igraph_vector_destroy(&order2); igraph_vector_destroy(&d2); IGRAPH_FINALLY_CLEAN(2); } #undef which /* Copy values */ if (values) { IGRAPH_CHECK(igraph_vector_resize(values, nans)); memcpy(VECTOR(*values), d, sizeof(igraph_real_t) * nans); } /* Reorder vectors */ if (vectors) { int i; IGRAPH_CHECK(igraph_matrix_resize(vectors, n, nans)); for (i=0; in; int nconv=options->nconv; int nev=options->nev; unsigned int nans=(unsigned int) (nconv < nev ? nconv : nev); #define which(a,b) (options->which[0]==a && options->which[1]==b) if (which('L','M')) { sort[0]='S'; sort[1]='M'; } else if (which('S', 'M')) { sort[0]='L'; sort[1]='M'; } else if (which('L', 'R')) { sort[0]='S'; sort[1]='R'; } else if (which('S', 'R')) { sort[0]='L'; sort[1]='R'; } else if (which('L', 'I')) { sort[0]='S'; sort[1]='I'; } else if (which('S', 'I')) { sort[0]='L'; sort[1]='I'; } #undef which IGRAPH_CHECK(igraph_vector_init_seq(&order, 0, nconv-1)); IGRAPH_FINALLY(igraph_vector_destroy, &order); #ifdef HAVE_GFORTRAN igraphdsortc_(sort, &apply, &nconv, dr, di, VECTOR(order), /*which_len=*/ 2); #else igraphdsortc_(sort, &apply, &nconv, dr, di, VECTOR(order)); #endif if (values) { IGRAPH_CHECK(igraph_matrix_resize(values, nans, 2)); memcpy(&MATRIX(*values, 0, 0), dr, sizeof(igraph_real_t) * nans); memcpy(&MATRIX(*values, 0, 1), di, sizeof(igraph_real_t) * nans); } if (vectors) { int i, nc=0, nr=0, ncol, wh=0, vx=0; for (i=0; inev * 2 + 1; /* Use twice the number of desired eigenvectors plus one by default */ options->ncv = min_ncv; /* ...but use at least 20 Lanczos vectors... */ if (options->ncv < 20) { options->ncv = 20; } /* ...but having ncv close to n leads to some problems with small graphs * (example: PageRank of "A <--> C, D <--> E, B"), so we don't let it * to be larger than n / 2... */ if (options->ncv > options->n / 2) { options->ncv = options->n / 2; } /* ...but we need at least min_ncv. */ if (options->ncv < min_ncv) { options->ncv = min_ncv; } /* ...but at most n-1 */ if (options->ncv > options->n) { options->ncv = options->n; } } /** * \function igraph_i_arpack_report_no_convergence * \brief Prints a warning that informs the user that the ARPACK solver * did not converge. */ void igraph_i_arpack_report_no_convergence(const igraph_arpack_options_t* options) { char buf[1024]; snprintf(buf, sizeof(buf), "ARPACK solver failed to converge (%d iterations, " "%d/%d eigenvectors converged)", options->iparam[2], options->iparam[4], options->nev); IGRAPH_WARNING(buf); } /** * \function igraph_arpack_rssolve * \brief ARPACK solver for symmetric matrices * * This is the ARPACK solver for symmetric matrices. Please use * \ref igraph_arpack_rnsolve() for non-symmetric matrices. * \param fun Pointer to an \ref igraph_arpack_function_t object, * the function that performs the matrix-vector multiplication. * \param extra An extra argument to be passed to \c fun. * \param options An \ref igraph_arpack_options_t object. * \param storage An \ref igraph_arpack_storage_t object, or a null * pointer. In the latter case memory allocation and deallocation * is performed automatically. Either this or the \p vectors argument * must be non-null if the ARPACK iteration is started from a * given starting vector. If both are given \p vectors take * precedence. * \param values If not a null pointer, then it should be a pointer to an * initialized vector. The eigenvalues will be stored here. The * vector will be resized as needed. * \param vectors If not a null pointer, then it must be a pointer to * an initialized matrix. The eigenvectors will be stored in the * columns of the matrix. The matrix will be resized as needed. * Either this or the \p vectors argument must be non-null if the * ARPACK iteration is started from a given starting vector. If * both are given \p vectors take precedence. * \return Error code. * * Time complexity: depends on the matrix-vector * multiplication. Usually a small number of iterations is enough, so * if the matrix is sparse and the matrix-vector multiplication can be * done in O(n) time (the number of vertices), then the eigenvalues * are found in O(n) time as well. */ int igraph_arpack_rssolve(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_vector_t *values, igraph_matrix_t *vectors) { igraph_real_t *v, *workl, *workd, *d, *resid, *ax; igraph_bool_t free_them=0; int *select, i; int ido=0; int rvec= vectors || storage ? 1 : 0; /* calculate eigenvectors? */ char *all="All"; int origldv=options->ldv, origlworkl=options->lworkl, orignev=options->nev, origncv=options->ncv; char origwhich[2]={ options->which[0], options->which[1] }; igraph_real_t origtol=options->tol; /* Special case for 1x1 and 2x2 matrices */ if (options->n == 1) { return igraph_i_arpack_rssolve_1x1(fun, extra, options, values, vectors); } else if (options->n == 2) { return igraph_i_arpack_rssolve_2x2(fun, extra, options, values, vectors); } /* Brush up options if needed */ if (options->ldv == 0) { options->ldv=options->n; } if (options->ncv == 0) { igraph_i_arpack_auto_ncv(options); } if (options->lworkl == 0) { options->lworkl=options->ncv*(options->ncv+8); } if (options->which[0] == 'X') { options->which[0]='L'; options->which[1]='M'; } if (storage) { /* Storage provided */ if (storage->maxn < options->n) { IGRAPH_ERROR("Not enough storage for ARPACK (`n')", IGRAPH_EINVAL); } if (storage->maxncv < options->ncv) { IGRAPH_ERROR("Not enough storage for ARPACK (`ncv')", IGRAPH_EINVAL); } if (storage->maxldv < options->ldv) { IGRAPH_ERROR("Not enough storage for ARPACK (`ldv')", IGRAPH_EINVAL); } v = storage->v; workl = storage->workl; workd = storage->workd; d = storage->d; resid = storage->resid; ax = storage->ax; select = storage->select; } else { /* Storage not provided */ free_them=1; #define CHECKMEM(x) \ if (!x) { \ IGRAPH_ERROR("Cannot allocate memory for ARPACK", IGRAPH_ENOMEM); \ } \ IGRAPH_FINALLY(igraph_free, x); v=igraph_Calloc(options->ldv * options->ncv, igraph_real_t); CHECKMEM(v); workl=igraph_Calloc(options->lworkl, igraph_real_t); CHECKMEM(workl); workd=igraph_Calloc(3*options->n, igraph_real_t); CHECKMEM(workd); d=igraph_Calloc(2*options->ncv, igraph_real_t); CHECKMEM(d); resid=igraph_Calloc(options->n, igraph_real_t); CHECKMEM(resid); ax=igraph_Calloc(options->n, igraph_real_t); CHECKMEM(ax); select=igraph_Calloc(options->ncv, int); CHECKMEM(select); #undef CHECKMEM } /* Set final bits */ options->iparam[0]=options->ishift; options->iparam[2]=options->mxiter; options->iparam[3]=options->nb; options->iparam[4]=0; options->iparam[6]=options->mode; options->info=options->start; if (options->start) { if (!storage && !vectors) { IGRAPH_ERROR("Starting vector not given", IGRAPH_EINVAL); } if (vectors && (igraph_matrix_nrow(vectors) != options->n || igraph_matrix_ncol(vectors) != 1)) { IGRAPH_ERROR("Invalid starting vector size", IGRAPH_EINVAL); } if (vectors) { for (i=0; in; i++) { resid[i]=MATRIX(*vectors, i, 0); } } } /* Ok, we have everything */ while (1) { #ifdef HAVE_GFORTRAN igraphdsaupd_(&ido, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->info, /*bmat_len=*/ 1, /*which_len=*/ 2); #else igraphdsaupd_(&ido, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->info); #endif if (ido==-1 || ido==1) { igraph_real_t *from=workd+options->ipntr[0]-1; igraph_real_t *to=workd+options->ipntr[1]-1; if (fun(to, from, options->n, extra) != 0) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } } else { break; } } if (options->info == 1) { igraph_i_arpack_report_no_convergence(options); } if (options->info != 0) { IGRAPH_ERROR("ARPACK error", igraph_i_arpack_err_dsaupd(options->info)); } options->ierr=0; #ifdef HAVE_GFORTRAN igraphdseupd_(&rvec, all, select, d, v, &options->ldv, &options->sigma, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->ierr, /*howmny_len=*/ 1, /*bmat_len=*/ 1, /*which_len=*/ 2); #else igraphdseupd_(&rvec, all, select, d, v, &options->ldv, &options->sigma, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->ierr); #endif if (options->ierr != 0) { IGRAPH_ERROR("ARPACK error", igraph_i_arpack_err_dseupd(options->ierr)); } /* Save the result */ options->noiter=options->iparam[2]; options->nconv=options->iparam[4]; options->numop=options->iparam[8]; options->numopb=options->iparam[9]; options->numreo=options->iparam[10]; if (options->nconv < options->nev) { IGRAPH_WARNING("Not enough eigenvalues/vectors in symmetric ARPACK " "solver"); } if (values || vectors) { IGRAPH_CHECK(igraph_arpack_rssort(values, vectors, options, d, v)); } options->ldv=origldv; options->ncv=origncv; options->lworkl=origlworkl; options->which[0] = origwhich[0]; options->which[1] = origwhich[1]; options->tol=origtol; options->nev=orignev; /* Clean up if needed */ if (free_them) { igraph_Free(select); igraph_Free(ax); igraph_Free(resid); igraph_Free(d); igraph_Free(workd); igraph_Free(workl); igraph_Free(v); IGRAPH_FINALLY_CLEAN(7); } return 0; } /** * \function igraph_arpack_rnsolve * \brief ARPACK solver for non-symmetric matrices * * Please always consider calling \ref igraph_arpack_rssolve() if your * matrix is symmetric, it is much faster. * \ref igraph_arpack_rnsolve() for non-symmetric matrices. * * Note that ARPACK is not called for 2x2 matrices as an exact algebraic * solution exists in these cases. * * \param fun Pointer to an \ref igraph_arpack_function_t object, * the function that performs the matrix-vector multiplication. * \param extra An extra argument to be passed to \c fun. * \param options An \ref igraph_arpack_options_t object. * \param storage An \ref igraph_arpack_storage_t object, or a null * pointer. In the latter case memory allocation and deallocation * is performed automatically. * \param values If not a null pointer, then it should be a pointer to an * initialized matrix. The (possibly complex) eigenvalues will be * stored here. The matrix will have two columns, the first column * contains the real, the second the imaginary parts of the * eigenvalues. * The matrix will be resized as needed. * \param vectors If not a null pointer, then it must be a pointer to * an initialized matrix. The eigenvectors will be stored in the * columns of the matrix. The matrix will be resized as needed. * \return Error code. * * Time complexity: depends on the matrix-vector * multiplication. Usually a small number of iterations is enough, so * if the matrix is sparse and the matrix-vector multiplication can be * done in O(n) time (the number of vertices), then the eigenvalues * are found in O(n) time as well. */ int igraph_arpack_rnsolve(igraph_arpack_function_t *fun, void *extra, igraph_arpack_options_t *options, igraph_arpack_storage_t *storage, igraph_matrix_t *values, igraph_matrix_t *vectors) { igraph_real_t *v, *workl, *workd, *dr, *di, *resid, *workev; igraph_bool_t free_them=0; int *select, i; int ido=0; int rvec= vectors || storage ? 1 : 0; char *all="All"; int origldv=options->ldv, origlworkl=options->lworkl, orignev=options->nev, origncv=options->ncv; char origwhich[2]={ options->which[0], options->which[1] }; igraph_real_t origtol=options->tol; int d_size; /* Special case for 1x1 and 2x2 matrices */ if (options->n == 1) { return igraph_i_arpack_rnsolve_1x1(fun, extra, options, values, vectors); } else if (options->n == 2) { return igraph_i_arpack_rnsolve_2x2(fun, extra, options, values, vectors); } /* Brush up options if needed */ if (options->ldv == 0) { options->ldv=options->n; } if (options->ncv == 0) { igraph_i_arpack_auto_ncv(options); } if (options->lworkl == 0) { options->lworkl=3*options->ncv*(options->ncv+2); } if (options->which[0] == 'X') { options->which[0]='L'; options->which[1]='M'; } if (storage) { /* Storage provided */ if (storage->maxn < options->n) { IGRAPH_ERROR("Not enough storage for ARPACK (`n')", IGRAPH_EINVAL); } if (storage->maxncv < options->ncv) { IGRAPH_ERROR("Not enough storage for ARPACK (`ncv')", IGRAPH_EINVAL); } if (storage->maxldv < options->ldv) { IGRAPH_ERROR("Not enough storage for ARPACK (`ldv')", IGRAPH_EINVAL); } v = storage->v; workl = storage->workl; workd = storage->workd; workev = storage->workev; dr = storage->d; di = storage->di; d_size = options->n; resid = storage->resid; select = storage->select; } else { /* Storage not provided */ free_them=1; #define CHECKMEM(x) \ if (!x) { \ IGRAPH_ERROR("Cannot allocate memory for ARPACK", IGRAPH_ENOMEM); \ } \ IGRAPH_FINALLY(igraph_free, x); v=igraph_Calloc(options->n * options->ncv, igraph_real_t); CHECKMEM(v); workl=igraph_Calloc(options->lworkl, igraph_real_t); CHECKMEM(workl); workd=igraph_Calloc(3*options->n, igraph_real_t); CHECKMEM(workd); d_size = 2*options->nev+1 > options->ncv ? 2*options->nev+1 : options->ncv; dr=igraph_Calloc(d_size, igraph_real_t); CHECKMEM(dr); di=igraph_Calloc(d_size, igraph_real_t); CHECKMEM(di); resid=igraph_Calloc(options->n, igraph_real_t); CHECKMEM(resid); select=igraph_Calloc(options->ncv, int); CHECKMEM(select); workev=igraph_Calloc(3*options->ncv, igraph_real_t); CHECKMEM(workev); #undef CHECKMEM } /* Set final bits */ options->iparam[0]=options->ishift; options->iparam[2]=options->mxiter; options->iparam[3]=options->nb; options->iparam[4]=0; options->iparam[6]=options->mode; options->info=options->start; if (options->start) { if (igraph_matrix_nrow(vectors) != options->n || igraph_matrix_ncol(vectors) != 1) { IGRAPH_ERROR("Invalid starting vector size", IGRAPH_EINVAL); } for (i=0; in; i++) { resid[i]=MATRIX(*vectors, i, 0); } } /* Ok, we have everything */ while (1) { #ifdef HAVE_GFORTRAN igraphdnaupd_(&ido, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->info, /*bmat_len=*/ 1, /*which_len=*/ 2); #else igraphdnaupd_(&ido, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->info); #endif if (ido==-1 || ido==1) { igraph_real_t *from=workd+options->ipntr[0]-1; igraph_real_t *to=workd+options->ipntr[1]-1; if (fun(to, from, options->n, extra) != 0) { IGRAPH_ERROR("ARPACK error while evaluating matrix-vector product", IGRAPH_ARPACK_PROD); } } else { break; } } if (options->info == 1) { igraph_i_arpack_report_no_convergence(options); } if (options->info != 0) { IGRAPH_ERROR("ARPACK error", igraph_i_arpack_err_dnaupd(options->info)); } options->ierr=0; #ifdef HAVE_GFORTRAN igraphdneupd_(&rvec, all, select, dr, di, v, &options->ldv, &options->sigma, &options->sigmai, workev, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->ierr, /*howmny_len=*/ 1, /*bmat_len=*/ 1, /*which_len=*/ 2); #else igraphdneupd_(&rvec, all, select, dr, di, v, &options->ldv, &options->sigma, &options->sigmai, workev, options->bmat, &options->n, options->which, &options->nev, &options->tol, resid, &options->ncv, v, &options->ldv, options->iparam, options->ipntr, workd, workl, &options->lworkl, &options->ierr); #endif if (options->ierr != 0) { IGRAPH_ERROR("ARPACK error", igraph_i_arpack_err_dneupd(options->info)); } /* Save the result */ options->noiter=options->iparam[2]; options->nconv=options->iparam[4]; options->numop=options->iparam[8]; options->numopb=options->iparam[9]; options->numreo=options->iparam[10]; if (options->nconv < options->nev) { IGRAPH_WARNING("Not enough eigenvalues/vectors in ARPACK " "solver"); } if (values || vectors) { IGRAPH_CHECK(igraph_arpack_rnsort(values, vectors, options, dr, di, v)); } options->ldv=origldv; options->ncv=origncv; options->lworkl=origlworkl; options->which[0] = origwhich[0]; options->which[1] = origwhich[1]; options->tol=origtol; options->nev=orignev; /* Clean up if needed */ if (free_them) { igraph_Free(workev); igraph_Free(select); igraph_Free(resid); igraph_Free(di); igraph_Free(dr); igraph_Free(workd); igraph_Free(workl); igraph_Free(v); IGRAPH_FINALLY_CLEAN(8); } return 0; } /** * \function igraph_arpack_unpack_complex * \brief Make the result of the non-symmetric ARPACK solver more readable * * This function works on the output of \ref igraph_arpack_rnsolve and * brushes it up a bit: it only keeps \p nev eigenvalues/vectors and * every eigenvector is stored in two columns of the \p vectors * matrix. * * * The output of the non-symmetric ARPACK solver is somewhat hard to * parse, as real eigenvectors occupy only one column in the matrix, * and the complex conjugate eigenvectors are not stored at all * (usually). The other problem is that the solver might return more * eigenvalues than requested. The common use of this function is to * call it directly after \ref igraph_arpack_rnsolve with its \p * vectors and \p values argument and \c options->nev as \p nev. * \param vectors The eigenvector matrix, as returned by \ref * igraph_arpack_rnsolve. It will be resized, typically it will be * larger. * \param values The eigenvalue matrix, as returned by \ref * igraph_arpack_rnsolve. It will be resized, typically extra, * unneeded rows (=eigenvalues) will be removed. * \param nev The number of eigenvalues/vectors to keep. Can be less * or equal than the number originally requested from ARPACK. * \return Error code. * * Time complexity: linear in the number of elements in the \p vectors * matrix. */ int igraph_arpack_unpack_complex(igraph_matrix_t *vectors, igraph_matrix_t *values, long int nev) { long int nodes=igraph_matrix_nrow(vectors); long int no_evs=igraph_matrix_nrow(values); long int i, j, k, wh; size_t colsize=(unsigned) nodes * sizeof(igraph_real_t); /* Error checks */ if (nev < 0) { IGRAPH_ERROR("`nev' cannot be negative", IGRAPH_EINVAL); } if (nev > no_evs) { IGRAPH_ERROR("`nev' too large, we don't have that many in `values'", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(vectors, nodes, nev * 2)); for (i=nev; i=origcol) { */ /* IGRAPH_WARNING("Too few columns in `vectors', ARPACK results are likely wrong"); */ /* } */ /* We copy the j-th eigenvector to the (k-1)-th and k-th column */ k=nev*2-1; for (i=nev-1; i>=0; i--) { if (MATRIX(*values,i,1)==0) { /* real */ memset( &MATRIX(*vectors,0,k), 0, colsize); if (k-1 != j) { memcpy( &MATRIX(*vectors,0,k-1), &MATRIX(*vectors,0,j), colsize); } k-=2; j-=1; } else { /* complex */ if (k!=j) { /* Separate copy required, otherwise 'from' and 'to' might overlap */ memcpy( &MATRIX(*vectors,0,k), &MATRIX(*vectors,0,j), colsize); memcpy( &MATRIX(*vectors,0,k-1), &MATRIX(*vectors,0,j-1), colsize); } if (i>1 && MATRIX(*values,i,1) != -MATRIX(*values,i-1,1)) { /* The next one is not a conjugate of this one */ j-=2; } else { /* Conjugate */ int l; for (l=0; l 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interface.h" #include "igraph_games.h" #include "igraph_random.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" #include "igraph_attributes.h" #include "igraph_constructors.h" #include "igraph_nongraph.h" #include "igraph_conversion.h" #include "igraph_psumtree.h" #include "igraph_dqueue.h" #include "igraph_adjlist.h" #include "igraph_iterators.h" #include "igraph_progress.h" #include "igraph_topology.h" #include "igraph_types_internal.h" #include "config.h" #include typedef struct { long int no; igraph_psumtree_t *sumtrees; } igraph_i_citing_cited_type_game_struct_t; void igraph_i_citing_cited_type_game_free ( igraph_i_citing_cited_type_game_struct_t *s); /** * \section about_games * * Games are randomized graph generators. Randomization means that * they generate a different graph every time you call them. */ int igraph_i_barabasi_game_bag(igraph_t *graph, igraph_integer_t n, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_bool_t directed, const igraph_t *start_from); int igraph_i_barabasi_game_psumtree_multiple(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t A, igraph_bool_t directed, const igraph_t *start_from); int igraph_i_barabasi_game_psumtree(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t A, igraph_bool_t directed, const igraph_t *start_from); int igraph_i_barabasi_game_bag(igraph_t *graph, igraph_integer_t n, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_bool_t directed, const igraph_t *start_from) { long int no_of_nodes=n; long int no_of_neighbors=m; long int *bag; long int bagp=0; igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int resp; long int i,j,k; long int bagsize, start_nodes, start_edges, new_edges, no_of_edges; if (!directed) { outpref = 1; } start_nodes= start_from ? igraph_vcount(start_from) : 1; start_edges= start_from ? igraph_ecount(start_from) : 0; if (outseq) { if (igraph_vector_size(outseq)>1) { new_edges=(long int) (igraph_vector_sum(outseq)-VECTOR(*outseq)[0]); } else { new_edges=0; } } else { new_edges=(no_of_nodes-start_nodes) * no_of_neighbors; } no_of_edges=start_edges+new_edges; resp=start_edges*2; bagsize=no_of_nodes + no_of_edges + (outpref ? no_of_edges : 0); IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); bag=igraph_Calloc(bagsize, long int); if (bag==0) { IGRAPH_ERROR("barabasi_game failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, bag); /* TODO: hack */ /* The first node(s) in the bag */ if (start_from) { igraph_vector_t deg; long int ii, jj, sn=igraph_vcount(start_from); igraph_neimode_t mm= outpref ? IGRAPH_ALL : IGRAPH_IN; IGRAPH_VECTOR_INIT_FINALLY(°, sn); IGRAPH_CHECK(igraph_degree(start_from, °, igraph_vss_all(), mm, IGRAPH_LOOPS)); for (ii=0; ii1) { new_edges=(long int) (igraph_vector_sum(outseq)-VECTOR(*outseq)[0]); } else { new_edges=0; } } else { new_edges=(no_of_nodes-start_nodes) * no_of_neighbors; } no_of_edges=start_edges+new_edges; edgeptr=start_edges*2; IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); IGRAPH_CHECK(igraph_psumtree_init(&sumtree, no_of_nodes)); IGRAPH_FINALLY(igraph_psumtree_destroy, &sumtree); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); /* first node(s) */ if (start_from) { long int ii, sn=igraph_vcount(start_from); igraph_neimode_t mm=outpref ? IGRAPH_ALL : IGRAPH_IN; IGRAPH_CHECK(igraph_degree(start_from, °ree, igraph_vss_all(), mm, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_vector_resize(°ree, no_of_nodes)); for (ii=0; ii1) { new_edges=(long int) (igraph_vector_sum(outseq)-VECTOR(*outseq)[0]); } else { new_edges=0; } } else { new_edges=(no_of_nodes-start_nodes) * no_of_neighbors; } no_of_edges=start_edges+new_edges; edgeptr=start_edges*2; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); IGRAPH_CHECK(igraph_psumtree_init(&sumtree, no_of_nodes)); IGRAPH_FINALLY(igraph_psumtree_destroy, &sumtree); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); RNG_BEGIN(); /* first node(s) */ if (start_from) { long int ii, sn=igraph_vcount(start_from); igraph_neimode_t mm=outpref ? IGRAPH_ALL : IGRAPH_IN; IGRAPH_CHECK(igraph_degree(start_from, °ree, igraph_vss_all(), mm, IGRAPH_LOOPS)); IGRAPH_CHECK(igraph_vector_resize(°ree, no_of_nodes)); for (ii=0; ii= i) { /* All existing vertices are cited */ for (to=0; to i ? i : no_of_neighbors; igraph_psumtree_update(&sumtree, i, pow(VECTOR(degree)[i], power)+A); } else { igraph_psumtree_update(&sumtree, i, A); } } RNG_END(); igraph_psumtree_destroy(&sumtree); igraph_vector_destroy(°ree); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_create(graph, &edges, n, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup generators * \function igraph_barabasi_game * \brief Generates a graph based on the Barabási-Albert model. * * \param graph An uninitialized graph object. * \param n The number of vertices in the graph. * \param power Power of the preferential attachment. The probability * that a vertex is cited is proportional to d^power+A, where * d is its degree (see also the \p outpref argument), power * and A are given by arguments. In the classic preferential * attachment model power=1. * \param m The number of outgoing edges generated for each * vertex. (Only if \p outseq is \c NULL.) * \param outseq Gives the (out-)degrees of the vertices. If this is * constant, this can be a NULL pointer or an empty (but * initialized!) vector, in this case \p m contains * the constant out-degree. The very first vertex has by definition * no outgoing edges, so the first number in this vector is * ignored. * \param outpref Boolean, if true not only the in- but also the out-degree * of a vertex increases its citation probability. Ie. the * citation probability is determined by the total degree of * the vertices. Ignored and assumed to be true if the graph * being generated is undirected. * \param A The probability that a vertex is cited is proportional to * d^power+A, where d is its degree (see also the \p outpref * argument), power and A are given by arguments. In the * previous versions of the function this parameter was * implicitly set to one. * \param directed Boolean, whether to generate a directed graph. * \param algo The algorithm to use to generate the network. Possible * values: * \clist * \cli IGRAPH_BARABASI_BAG * This is the algorithm that was previously (before version * 0.6) solely implemented in igraph. It works by putting the * ids of the vertices into a bag (multiset, really), exactly * as many times as their (in-)degree, plus once more. Then * the required number of cited vertices are drawn from the * bag, with replacement. This method might generate multiple * edges. It only works if power=1 and A=1. * \cli IGRAPH_BARABASI_PSUMTREE * This algorithm uses a partial prefix-sum tree to generate * the graph. It does not generate multiple edges and * works for any power and A values. * \cli IGRAPH_BARABASI_PSUMTREE_MULTIPLE * This algorithm also uses a partial prefix-sum tree to * generate the graph. The difference is, that now multiple * edges are allowed. This method was implemented under the * name \c igraph_nonlinear_barabasi_game before version 0.6. * \endclist * \param start_from Either a null pointer, or a graph. In the former * case, the starting configuration is a clique of size \p m. * In the latter case, the graph is a starting configuration. * The graph must be non-empty, i.e. it must have at least one * vertex. If a graph is supplied here and the \p outseq * argument is also given, then \p outseq should only contain * information on the vertices that are not in the \p * start_from graph. * \return Error code: * \c IGRAPH_EINVAL: invalid \p n, * \p m or \p outseq parameter. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges. * * \example examples/simple/igraph_barabasi_game.c * \example examples/simple/igraph_barabasi_game2.c */ int igraph_barabasi_game(igraph_t *graph, igraph_integer_t n, igraph_real_t power, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t A, igraph_bool_t directed, igraph_barabasi_algorithm_t algo, const igraph_t *start_from) { long int start_nodes= start_from ? igraph_vcount(start_from) : 0; long int newn= start_from ? n-start_nodes : n; /* Fix obscure parameterizations */ if (outseq && igraph_vector_size(outseq) == 0) { outseq=0; } if (!directed) { outpref=1; } /* Check arguments */ if (algo != IGRAPH_BARABASI_BAG && algo != IGRAPH_BARABASI_PSUMTREE && algo != IGRAPH_BARABASI_PSUMTREE_MULTIPLE) { IGRAPH_ERROR("Invalid algorithm", IGRAPH_EINVAL); } if (n < 0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVAL); } else if (newn < 0) { IGRAPH_ERROR("Starting graph has too many vertices", IGRAPH_EINVAL); } if (start_from && start_nodes==0) { IGRAPH_ERROR("Cannot start from an empty graph", IGRAPH_EINVAL); } if (outseq != 0 && igraph_vector_size(outseq) != 0 && igraph_vector_size(outseq) != newn) { IGRAPH_ERROR("Invalid out degree sequence length", IGRAPH_EINVAL); } if ( (outseq == 0 || igraph_vector_size(outseq) == 0) && m<0) { IGRAPH_ERROR("Invalid out degree", IGRAPH_EINVAL); } if (outseq && igraph_vector_min(outseq) < 0) { IGRAPH_ERROR("Negative out degree in sequence", IGRAPH_EINVAL); } if (!outpref && A <= 0) { IGRAPH_ERROR("Constant attractiveness (A) must be positive", IGRAPH_EINVAL); } if (outpref && A < 0) { IGRAPH_ERROR("Constant attractiveness (A) must be non-negative", IGRAPH_EINVAL); } if (algo == IGRAPH_BARABASI_BAG) { if (power != 1) { IGRAPH_ERROR("Power must be one for 'bag' algorithm", IGRAPH_EINVAL); } if (A != 1) { IGRAPH_ERROR("Constant attractiveness (A) must be one for bag algorithm", IGRAPH_EINVAL); } } if (start_from && directed != igraph_is_directed(start_from)) { IGRAPH_WARNING("Directedness of the start graph and the output graph" " mismatch"); } if (start_from && !igraph_is_directed(start_from) && !outpref) { IGRAPH_ERROR("`outpref' must be true if starting from an undirected " "graph", IGRAPH_EINVAL); } if (algo == IGRAPH_BARABASI_BAG) { return igraph_i_barabasi_game_bag(graph, n, m, outseq, outpref, directed, start_from); } else if (algo == IGRAPH_BARABASI_PSUMTREE) { return igraph_i_barabasi_game_psumtree(graph, n, power, m, outseq, outpref, A, directed, start_from); } else if (algo == IGRAPH_BARABASI_PSUMTREE_MULTIPLE) { return igraph_i_barabasi_game_psumtree_multiple(graph, n, power, m, outseq, outpref, A, directed, start_from); } return 0; } /** * \ingroup internal */ int igraph_erdos_renyi_game_gnp(igraph_t *graph, igraph_integer_t n, igraph_real_t p, igraph_bool_t directed, igraph_bool_t loops) { long int no_of_nodes=n; igraph_vector_t edges=IGRAPH_VECTOR_NULL; igraph_vector_t s=IGRAPH_VECTOR_NULL; int retval=0; if (n<0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVAL); } if (p<0.0 || p>1.0) { IGRAPH_ERROR("Invalid probability given", IGRAPH_EINVAL); } if (p==0.0 || no_of_nodes<=1) { IGRAPH_CHECK(retval=igraph_empty(graph, n, directed)); } else if (p==1.0) { IGRAPH_CHECK(retval=igraph_full(graph, n, directed, loops)); } else { long int i; double maxedges = n, last; if (directed && loops) { maxedges *= n; } else if (directed && !loops) { maxedges *= (n-1); } else if (!directed && loops) { maxedges *= (n+1)/2.0; } else { maxedges *= (n-1)/2.0; } IGRAPH_VECTOR_INIT_FINALLY(&s, 0); IGRAPH_CHECK(igraph_vector_reserve(&s, (long int) (maxedges*p*1.1))); RNG_BEGIN(); last=RNG_GEOM(p); while (last < maxedges) { IGRAPH_CHECK(igraph_vector_push_back(&s, last)); last += RNG_GEOM(p); last += 1; } RNG_END(); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, igraph_vector_size(&s)*2)); if (directed && loops) { for (i=0; i maxedges) { IGRAPH_ERROR("Invalid number (too large) of edges", IGRAPH_EINVAL); } if (maxedges == no_of_edges) { retval=igraph_full(graph, n, directed, loops); } else { long int slen; IGRAPH_VECTOR_INIT_FINALLY(&s, 0); IGRAPH_CHECK(igraph_random_sample(&s, 0, maxedges-1, (igraph_integer_t) no_of_edges)); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, igraph_vector_size(&s)*2)); slen=igraph_vector_size(&s); if (directed && loops) { for (i=0; i to) { dummy = from; from = to; to = dummy; } neis = igraph_adjlist_get(&al, from); if (from == to || igraph_vector_int_binsearch(neis, to, &j)) { /* Edge exists already */ VECTOR(residual_degrees)[from]++; VECTOR(residual_degrees)[to]++; IGRAPH_CHECK(igraph_set_add(&incomplete_vertices, from)); IGRAPH_CHECK(igraph_set_add(&incomplete_vertices, to)); } else { /* Insert the edge */ IGRAPH_CHECK(igraph_vector_int_insert(neis, j, to)); } } finished = igraph_set_empty(&incomplete_vertices); if (!finished) { /* We are not done yet; check if the remaining stubs are feasible. This * is done by enumerating all possible pairs and checking whether at * least one feasible pair is found. */ i = 0; failed = 1; while (failed && igraph_set_iterate(&incomplete_vertices, &i, &from)) { j = 0; while (igraph_set_iterate(&incomplete_vertices, &j, &to)) { if (from == to) { /* This is used to ensure that each pair is checked once only */ break; } if (from > to) { dummy = from; from = to; to = dummy; } neis = igraph_adjlist_get(&al, from); if (!igraph_vector_int_binsearch(neis, to, 0)) { /* Found a suitable pair, so we can continue */ failed = 0; break; } } } } } } /* Finish the RNG */ RNG_END(); /* Clean up */ igraph_set_destroy(&incomplete_vertices); igraph_vector_destroy(&residual_degrees); igraph_vector_destroy(&stubs); IGRAPH_FINALLY_CLEAN(3); /* Create the graph. We cannot use IGRAPH_ALL here for undirected graphs * because we did not add edges in both directions in the adjacency list. * We will use igraph_to_undirected in an extra step. */ IGRAPH_CHECK(igraph_adjlist(graph, &al, IGRAPH_OUT, 1)); IGRAPH_CHECK(igraph_to_undirected(graph, IGRAPH_TO_UNDIRECTED_EACH, 0)); /* Clear the adjacency list */ igraph_adjlist_destroy(&al); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } int igraph_degree_sequence_game_no_multiple_directed(igraph_t *graph, const igraph_vector_t *out_seq, const igraph_vector_t *in_seq) { igraph_adjlist_t al; igraph_bool_t deg_seq_ok, failed, finished; igraph_vector_t in_stubs = IGRAPH_VECTOR_NULL; igraph_vector_t out_stubs = IGRAPH_VECTOR_NULL; igraph_vector_int_t *neis; igraph_vector_t residual_in_degrees=IGRAPH_VECTOR_NULL; igraph_vector_t residual_out_degrees=IGRAPH_VECTOR_NULL; igraph_set_t incomplete_in_vertices; igraph_set_t incomplete_out_vertices; igraph_integer_t from, to; long int i, j, k; long int no_of_nodes, outsum; IGRAPH_CHECK(igraph_is_graphical_degree_sequence(out_seq, in_seq, °_seq_ok)); if (!deg_seq_ok) { IGRAPH_ERROR("No simple directed graph can realize the given degree sequence", IGRAPH_EINVAL); } outsum=(long int) igraph_vector_sum(out_seq); no_of_nodes=igraph_vector_size(out_seq); /* Allocate required data structures */ IGRAPH_CHECK(igraph_adjlist_init_empty(&al, (igraph_integer_t) no_of_nodes)); IGRAPH_FINALLY(igraph_adjlist_destroy, &al); IGRAPH_VECTOR_INIT_FINALLY(&out_stubs, 0); IGRAPH_CHECK(igraph_vector_reserve(&out_stubs, outsum)); IGRAPH_VECTOR_INIT_FINALLY(&in_stubs, 0); IGRAPH_CHECK(igraph_vector_reserve(&in_stubs, outsum)); IGRAPH_VECTOR_INIT_FINALLY(&residual_out_degrees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&residual_in_degrees, no_of_nodes); IGRAPH_CHECK(igraph_set_init(&incomplete_out_vertices, 0)); IGRAPH_FINALLY(igraph_set_destroy, &incomplete_out_vertices); IGRAPH_CHECK(igraph_set_init(&incomplete_in_vertices, 0)); IGRAPH_FINALLY(igraph_set_destroy, &incomplete_in_vertices); /* Start the RNG */ RNG_BEGIN(); /* Outer loop; this will try to construct a graph several times from scratch * until it finally succeeds. */ finished = 0; while (!finished) { /* Be optimistic :) */ failed = 0; /* Clear the adjacency list to get rid of the previous attempt (if any) */ igraph_adjlist_clear(&al); /* Initialize the residual degrees from the degree sequences */ IGRAPH_CHECK(igraph_vector_update(&residual_out_degrees, out_seq)); IGRAPH_CHECK(igraph_vector_update(&residual_in_degrees, in_seq)); /* While there are some unconnected stubs left... */ while (!finished && !failed) { /* Construct the initial stub vectors */ igraph_vector_clear(&out_stubs); igraph_vector_clear(&in_stubs); for (i = 0; i < no_of_nodes; i++) { for (j = 0; j < VECTOR(residual_out_degrees)[i]; j++) { igraph_vector_push_back(&out_stubs, i); } for (j = 0; j < VECTOR(residual_in_degrees)[i]; j++) { igraph_vector_push_back(&in_stubs, i); } } /* Clear the skipped stub counters and the set of incomplete vertices */ igraph_vector_null(&residual_out_degrees); igraph_vector_null(&residual_in_degrees); igraph_set_clear(&incomplete_out_vertices); igraph_set_clear(&incomplete_in_vertices); outsum = 0; /* Shuffle the out-stubs in-place */ igraph_vector_shuffle(&out_stubs); /* Connect the stubs where possible */ k = igraph_vector_size(&out_stubs); for (i = 0; i < k; i++) { from = (igraph_integer_t) VECTOR(out_stubs)[i]; to = (igraph_integer_t) VECTOR(in_stubs)[i]; neis = igraph_adjlist_get(&al, from); if (from == to || igraph_vector_int_binsearch(neis, to, &j)) { /* Edge exists already */ VECTOR(residual_out_degrees)[from]++; VECTOR(residual_in_degrees)[to]++; IGRAPH_CHECK(igraph_set_add(&incomplete_out_vertices, from)); IGRAPH_CHECK(igraph_set_add(&incomplete_in_vertices, to)); } else { /* Insert the edge */ IGRAPH_CHECK(igraph_vector_int_insert(neis, j, to)); } } /* Are we finished? */ finished = igraph_set_empty(&incomplete_out_vertices); if (!finished) { /* We are not done yet; check if the remaining stubs are feasible. This * is done by enumerating all possible pairs and checking whether at * least one feasible pair is found. */ i = 0; failed = 1; while (failed && igraph_set_iterate(&incomplete_out_vertices, &i, &from)) { j = 0; while (igraph_set_iterate(&incomplete_in_vertices, &j, &to)) { neis = igraph_adjlist_get(&al, from); if (from != to && !igraph_vector_int_binsearch(neis, to, 0)) { /* Found a suitable pair, so we can continue */ failed = 0; break; } } } } } } /* Finish the RNG */ RNG_END(); /* Clean up */ igraph_set_destroy(&incomplete_in_vertices); igraph_set_destroy(&incomplete_out_vertices); igraph_vector_destroy(&residual_in_degrees); igraph_vector_destroy(&residual_out_degrees); igraph_vector_destroy(&in_stubs); igraph_vector_destroy(&out_stubs); IGRAPH_FINALLY_CLEAN(6); /* Create the graph */ IGRAPH_CHECK(igraph_adjlist(graph, &al, IGRAPH_OUT, 1)); /* Clear the adjacency list */ igraph_adjlist_destroy(&al); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* This is in gengraph_mr-connected.cpp */ int igraph_degree_sequence_game_vl(igraph_t *graph, const igraph_vector_t *out_seq, const igraph_vector_t *in_seq); /** * \ingroup generators * \function igraph_degree_sequence_game * \brief Generates a random graph with a given degree sequence * * \param graph Pointer to an uninitialized graph object. * \param out_deg The degree sequence for an undirected graph (if * \p in_seq is of length zero), or the out-degree * sequence of a directed graph (if \p in_deq is not * of length zero. * \param in_deg It is either a zero-length vector or * \c NULL (if an undirected * graph is generated), or the in-degree sequence. * \param method The method to generate the graph. Possible values: * \clist * \cli IGRAPH_DEGSEQ_SIMPLE * For undirected graphs, this method puts all vertex ids in a bag * such that the multiplicity of a vertex in the bag is the same as * its degree. Then it draws pairs from the bag until the bag becomes * empty. This method can generate both loop (self) edges and multiple * edges. For directed graphs, the algorithm is basically the same, * but two separate bags are used for the in- and out-degrees. * \cli IGRAPH_DEGSEQ_SIMPLE_NO_MULTIPLE * This method is similar to \c IGRAPH_DEGSEQ_SIMPLE * but tries to avoid multiple and loop edges and restarts the * generation from scratch if it gets stuck. It is not guaranteed * to sample uniformly from the space of all possible graphs with * the given sequence, but it is relatively fast and it will * eventually succeed if the provided degree sequence is graphical, * but there is no upper bound on the number of iterations. * \cli IGRAPH_DEGSEQ_VL * This method is a much more sophisticated generator than the * previous ones. It can sample undirected, connected simple graphs * uniformly and uses Monte-Carlo methods to randomize the graphs. * This generator should be favoured if undirected and connected * graphs are to be generated and execution time is not a concern. * igraph uses the original implementation of Fabien Viger; see * http://www-rp.lip6.fr/~latapy/FV/generation.html * and the paper cited on it for the details of the algorithm. * \endclist * \return Error code: * \c IGRAPH_ENOMEM: there is not enough * memory to perform the operation. * \c IGRAPH_EINVAL: invalid method parameter, or * invalid in- and/or out-degree vectors. The degree vectors * should be non-negative, \p out_deg should sum * up to an even integer for undirected graphs; the length * and sum of \p out_deg and * \p in_deg * should match for directed graphs. * * Time complexity: O(|V|+|E|), the number of vertices plus the number of edges * for \c IGRAPH_DEGSEQ_SIMPLE. The time complexity of the * other modes is not known. * * \sa \ref igraph_barabasi_game(), \ref igraph_erdos_renyi_game(), * \ref igraph_is_degree_sequence(), * \ref igraph_is_graphical_degree_sequence() * * \example examples/simple/igraph_degree_sequence_game.c */ int igraph_degree_sequence_game(igraph_t *graph, const igraph_vector_t *out_deg, const igraph_vector_t *in_deg, igraph_degseq_t method) { int retval; if (in_deg && igraph_vector_empty(in_deg) && !igraph_vector_empty(out_deg)) { in_deg=0; } if (method==IGRAPH_DEGSEQ_SIMPLE) { retval=igraph_degree_sequence_game_simple(graph, out_deg, in_deg); } else if (method==IGRAPH_DEGSEQ_VL) { retval=igraph_degree_sequence_game_vl(graph, out_deg, in_deg); } else if (method==IGRAPH_DEGSEQ_SIMPLE_NO_MULTIPLE) { if (in_deg == 0 || (igraph_vector_empty(in_deg) && !igraph_vector_empty(out_deg))) { retval=igraph_degree_sequence_game_no_multiple_undirected(graph, out_deg); } else { retval=igraph_degree_sequence_game_no_multiple_directed(graph, out_deg, in_deg); } } else { IGRAPH_ERROR("Invalid degree sequence game method", IGRAPH_EINVAL); } return retval; } /** * \ingroup generators * \function igraph_growing_random_game * \brief Generates a growing random graph. * * * This function simulates a growing random graph. In each discrete * time step a new vertex is added and a number of new edges are also * added. These graphs are known to be different from standard (not * growing) random graphs. * \param graph Uninitialized graph object. * \param n The number of vertices in the graph. * \param m The number of edges to add in a time step (ie. after * adding a vertex). * \param directed Boolean, whether to generate a directed graph. * \param citation Boolean, if \c TRUE, the edges always * originate from the most recently added vertex. * \return Error code: * \c IGRAPH_EINVAL: invalid * \p n or \p m * parameter. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges. * * \example examples/simple/igraph_growing_random_game.c */ int igraph_growing_random_game(igraph_t *graph, igraph_integer_t n, igraph_integer_t m, igraph_bool_t directed, igraph_bool_t citation) { long int no_of_nodes=n; long int no_of_neighbors=m; long int no_of_edges; igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int resp=0; long int i,j; if (n<0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVAL); } if (m<0) { IGRAPH_ERROR("Invalid number of edges per step (m)", IGRAPH_EINVAL); } no_of_edges=(no_of_nodes-1) * no_of_neighbors; IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); RNG_BEGIN(); for (i=1; i * The different types of vertices prefer to connect other types of * vertices with a given probability. * * * The simulation goes like this: in each discrete time step a new * vertex is added to the graph. The type of this vertex is generated * based on \p type_dist. Then two vertices are selected uniformly * randomly from the graph. The probability that they will be * connected depends on the types of these vertices and is taken from * \p pref_matrix. Then another two vertices are selected and this is * repeated \p edges_per_step times in each time step. * \param graph Pointer to an uninitialized graph. * \param nodes The number of nodes in the graph. * \param types Number of node types. * \param edges_per_step The number of edges to be add per time step. * \param type_dist Vector giving the distribution of the vertex * types. * \param pref_matrix Matrix giving the connection probabilities for * the vertex types. * \param directed Logical, whether to generate a directed graph. * \return Error code. * * Added in version 0.2. * * Time complexity: O(|V|e*log(|V|)), |V| is the number of vertices, e * is \p edges_per_step. */ int igraph_callaway_traits_game (igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_integer_t edges_per_step, igraph_vector_t *type_dist, igraph_matrix_t *pref_matrix, igraph_bool_t directed) { long int i, j; igraph_vector_t edges; igraph_vector_t cumdist; igraph_real_t maxcum; igraph_vector_t nodetypes; /* TODO: parameter checks */ IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&cumdist, types+1); IGRAPH_VECTOR_INIT_FINALLY(&nodetypes, nodes); VECTOR(cumdist)[0]=0; for (i=0; i * The simulation goes like this: a single vertex is added at each * time step. This new vertex tries to connect to \p k vertices in the * graph. The probability that such a connection is realized depends * on the types of the vertices involved. * * \param graph Pointer to an uninitialized graph. * \param nodes The number of vertices in the graph. * \param types The number of vertex types. * \param k The number of connections tried in each time step. * \param type_dist Vector giving the distribution of vertex types. * \param pref_matrix Matrix giving the connection probabilities for * different vertex types. * \param directed Logical, whether to generate a directed graph. * \return Error code. * * Added in version 0.2. * * Time complexity: O(|V|*k*log(|V|)), |V| is the number of vertices * and k is the \p k parameter. */ int igraph_establishment_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_integer_t k, igraph_vector_t *type_dist, igraph_matrix_t *pref_matrix, igraph_bool_t directed) { long int i, j; igraph_vector_t edges; igraph_vector_t cumdist; igraph_vector_t potneis; igraph_real_t maxcum; igraph_vector_t nodetypes; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&cumdist, types+1); IGRAPH_VECTOR_INIT_FINALLY(&potneis, k); IGRAPH_VECTOR_INIT_FINALLY(&nodetypes, nodes); VECTOR(cumdist)[0]=0; for (i=0; i=time_window) { while ((j=(long int) igraph_dqueue_pop(&history)) != -1) { VECTOR(degree)[j] -= 1; igraph_psumtree_update(&sumtree, j, pow(VECTOR(degree)[j], power)+zero_appeal); } } sum=igraph_psumtree_sum(&sumtree); for (j=0; j * In this game, the probability that a node gains a new edge is * given by its (in-)degree (k) and age (l). This probability has a * degree dependent component multiplied by an age dependent * component. The degree dependent part is: \p deg_coef times k to the * power of \p pa_exp plus \p zero_deg_appeal; and the age dependent * part is \p age_coef times l to the power of \p aging_exp plus \p * zero_age_appeal. * * * The age is based on the number of vertices in the * network and the \p aging_bin argument: vertices grew one unit older * after each \p aging_bin vertices added to the network. * \param graph Pointer to an uninitialized graph object. * \param nodes The number of vertices in the graph. * \param m The number of edges to add in each time step. If the \p * outseq argument is not a null vector and not a zero-length * vector. * \param outseq The number of edges to add in each time step. If it * is a null pointer or a zero-length vector then it is ignored * and the \p m argument is used instead. * \param outpref Logical constant, whether the edges * initiated by a vertex contribute to the probability to gain * a new edge. * \param pa_exp The exponent of the preferential attachment, a small * positive number usually, the value 1 yields the classic * linear preferential attachment. * \param aging_exp The exponent of the aging, this is a negative * number usually. * \param aging_bin Integer constant, the number of vertices to add * before vertices in the network grew one unit older. * \param zero_deg_appeal The degree dependent part of the * attractiveness of the zero degree vertices. * \param zero_age_appeal The age dependent part of the attractiveness * of the vertices of age zero. This parameter is usually zero. * \param deg_coef The coefficient for the degree. * \param age_coef The coefficient for the age. * \param directed Logical constant, whether to generate a directed * graph. * \return Error code. * * Time complexity: O((|V|+|V|/aging_bin)*log(|V|)+|E|). |V| is the number * of vertices, |E| the number of edges. */ int igraph_barabasi_aging_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t pa_exp, igraph_real_t aging_exp, igraph_integer_t aging_bin, igraph_real_t zero_deg_appeal, igraph_real_t zero_age_appeal, igraph_real_t deg_coef, igraph_real_t age_coef, igraph_bool_t directed) { long int no_of_nodes=nodes; long int no_of_neighbors=m; long int binwidth=nodes/aging_bin+1; long int no_of_edges; igraph_vector_t edges; long int i, j, k; igraph_psumtree_t sumtree; long int edgeptr=0; igraph_vector_t degree; if (no_of_nodes<0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVAL); } if (outseq != 0 && igraph_vector_size(outseq) != 0 && igraph_vector_size(outseq) != no_of_nodes) { IGRAPH_ERROR("Invalid out degree sequence length", IGRAPH_EINVAL); } if ( (outseq == 0 || igraph_vector_size(outseq) == 0) && m<0) { IGRAPH_ERROR("Invalid out degree", IGRAPH_EINVAL); } if (aging_bin <= 0) { IGRAPH_ERROR("Invalid aging bin", IGRAPH_EINVAL); } if (outseq==0 || igraph_vector_size(outseq) == 0) { no_of_neighbors=m; no_of_edges=(no_of_nodes-1)*no_of_neighbors; } else { no_of_edges=0; for (i=1; i= 1; k++) { long int shnode=i-binwidth*k; long int deg=(long int) VECTOR(degree)[shnode]; long int age=(i-shnode)/binwidth; /* igraph_real_t old=igraph_psumtree_get(&sumtree, shnode); */ igraph_psumtree_update(&sumtree, shnode, (deg_coef*pow(deg, pa_exp)+zero_deg_appeal) * (age_coef*pow(age+2, aging_exp)+zero_age_appeal)); } } RNG_END(); igraph_vector_destroy(°ree); igraph_psumtree_destroy(&sumtree); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_create(graph, &edges, nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_recent_degree_aging_game * \brief Preferential attachment based on the number of edges gained recently, with aging of vertices * * * This game is very similar to \ref igraph_barabasi_aging_game(), * except that instead of the total number of incident edges the * number of edges gained in the last \p time_window time steps are * counted. * * The degree dependent part of the attractiveness is * given by k to the power of \p pa_exp plus \p zero_appeal; the age * dependent part is l to the power to \p aging_exp. * k is the number of edges gained in the last \p time_window time * steps, l is the age of the vertex. * \param graph Pointer to an uninitialized graph object. * \param nodes The number of vertices in the graph. * \param m The number of edges to add in each time step. If the \p * outseq argument is not a null vector or a zero-length vector * then it is ignored. * \param outseq Vector giving the number of edges to add in each time * step. If it is a null pointer or a zero-length vector then * it is ignored and the \p m argument is used. * \param outpref Logical constant, if true the edges initiated by a * vertex are also counted. Normally it is false. * \param pa_exp The exponent for the preferential attachment. * \param aging_exp The exponent for the aging, normally it is * negative: old vertices gain edges with less probability. * \param aging_bin Integer constant, gives the scale of the aging. * The age of the vertices is incremented by one after every \p * aging_bin vertex added. * \param time_window The time window to use to count the number of * incident edges for the vertices. * \param zero_appeal The degree dependent part of the attractiveness * for zero degree vertices. * \param directed Logical constant, whether to create a directed * graph. * \return Error code. * * Time complexity: O((|V|+|V|/aging_bin)*log(|V|)+|E|). |V| is the number * of vertices, |E| the number of edges. */ int igraph_recent_degree_aging_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t m, const igraph_vector_t *outseq, igraph_bool_t outpref, igraph_real_t pa_exp, igraph_real_t aging_exp, igraph_integer_t aging_bin, igraph_integer_t time_window, igraph_real_t zero_appeal, igraph_bool_t directed) { long int no_of_nodes=nodes; long int no_of_neighbors=m; long int binwidth=nodes/aging_bin+1; long int no_of_edges; igraph_vector_t edges; long int i, j, k; igraph_psumtree_t sumtree; long int edgeptr=0; igraph_vector_t degree; igraph_dqueue_t history; if (no_of_nodes<0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVAL); } if (outseq != 0 && igraph_vector_size(outseq) != 0 && igraph_vector_size(outseq) != no_of_nodes) { IGRAPH_ERROR("Invalid out degree sequence length", IGRAPH_EINVAL); } if ( (outseq == 0 || igraph_vector_size(outseq) == 0) && m<0) { IGRAPH_ERROR("Invalid out degree", IGRAPH_EINVAL); } if (aging_bin <= 0) { IGRAPH_ERROR("Invalid aging bin", IGRAPH_EINVAL); } if (outseq==0 || igraph_vector_size(outseq) == 0) { no_of_neighbors=m; no_of_edges=(no_of_nodes-1)*no_of_neighbors; } else { no_of_edges=0; for (i=1; i=time_window) { while ((j=(long int) igraph_dqueue_pop(&history)) != -1) { long int age=(i-j)/binwidth; VECTOR(degree)[j] -= 1; igraph_psumtree_update(&sumtree, j, (pow(VECTOR(degree)[j], pa_exp)+zero_appeal)* pow(age+1, aging_exp)); } } sum=igraph_psumtree_sum(&sumtree); for (j=0; j= 1; k++) { long int shnode=i-binwidth*k; long int deg=(long int) VECTOR(degree)[shnode]; long int age=(i-shnode)/binwidth; igraph_psumtree_update(&sumtree, shnode, (pow(deg, pa_exp)+zero_appeal) * pow(age+2, aging_exp)); } } RNG_END(); igraph_dqueue_destroy(&history); igraph_vector_destroy(°ree); igraph_psumtree_destroy(&sumtree); IGRAPH_FINALLY_CLEAN(3); IGRAPH_CHECK(igraph_create(graph, &edges, nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_grg_game * \brief Generating geometric random graphs. * * A geometric random graph is created by dropping points (=vertices) * randomly to the unit square and then connecting all those pairs * which are less than \c radius apart in Euclidean norm. * * * Original code contributed by Keith Briggs, thanks Keith. * \param graph Pointer to an uninitialized graph object, * \param nodes The number of vertices in the graph. * \param radius The radius within which the vertices will be connected. * \param torus Logical constant, if true periodic boundary conditions * will be used, ie. the vertices are assumed to be on a torus * instead of a square. * \return Error code. * * Time complexity: TODO, less than O(|V|^2+|E|). * * \example examples/simple/igraph_grg_game.c */ int igraph_grg_game(igraph_t *graph, igraph_integer_t nodes, igraph_real_t radius, igraph_bool_t torus, igraph_vector_t *x, igraph_vector_t *y) { long int i; igraph_vector_t myx, myy, *xx=&myx, *yy=&myy, edges; igraph_real_t r2=radius*radius; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, nodes)); if (x) { xx=x; IGRAPH_CHECK(igraph_vector_resize(xx, nodes)); } else { IGRAPH_VECTOR_INIT_FINALLY(xx, nodes); } if (y) { yy=y; IGRAPH_CHECK(igraph_vector_resize(yy, nodes)); } else { IGRAPH_VECTOR_INIT_FINALLY(yy, nodes); } RNG_BEGIN(); for (i=0; i 0.5) { dx=1-dx; } if (dy > 0.5) { dy=1-dy; } if (dx*dx+dy*dy < r2) { IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } j++; } if (j==nodes) { j=0; while (j=radius) { dy=fabs(VECTOR(*yy)[j]-yy1); if (dy > 0.5) { dy=1-dy; } if (dx*dx+dy*dy < r2) { IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } j++; } } } } if (!y) { igraph_vector_destroy(yy); IGRAPH_FINALLY_CLEAN(1); } if (!x) { igraph_vector_destroy(xx); IGRAPH_FINALLY_CLEAN(1); } IGRAPH_CHECK(igraph_create(graph, &edges, nodes, IGRAPH_UNDIRECTED)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } void igraph_i_preference_game_free_vids_by_type(igraph_vector_ptr_t *vecs); void igraph_i_preference_game_free_vids_by_type(igraph_vector_ptr_t *vecs) { int i=0, n; igraph_vector_t *v; n = (int) igraph_vector_ptr_size(vecs); for (i=0; i * This is practically the nongrowing variant of \ref * igraph_establishment_game. A given number of vertices are * generated. Every vertex is assigned to a vertex type according to * the given type probabilities. Finally, every * vertex pair is evaluated and an edge is created between them with a * probability depending on the types of the vertices involved. * * * In other words, this function generates a graph according to a * block-model. Vertices are divided into groups (or blocks), and * the probability the two vertices are connected depends on their * groups only. * * \param graph Pointer to an uninitialized graph. * \param nodes The number of vertices in the graph. * \param types The number of vertex types. * \param type_dist Vector giving the distribution of vertex types. If * \c NULL, all vertex types will have equal probability. See also the * \c fixed_sizes argument. * \param fixed_sizes Boolean. If true, then the number of vertices with a * given vertex type is fixed and the \c type_dist argument gives these * numbers for each vertex type. If true, and \c type_dist is \c NULL, * then the function tries to make vertex groups of the same size. If this * is not possible, then some groups will have an extra vertex. * \param pref_matrix Matrix giving the connection probabilities for * different vertex types. This should be symmetric if the requested * graph is undirected. * \param node_type_vec A vector where the individual generated vertex types * will be stored. If \c NULL , the vertex types won't be saved. * \param directed Logical, whether to generate a directed graph. If undirected * graphs are requested, only the lower left triangle of the preference * matrix is considered. * \param loops Logical, whether loop edges are allowed. * \return Error code. * * Added in version 0.3. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges in the graph. * * \sa igraph_establishment_game() * * \example examples/simple/igraph_preference_game.c */ int igraph_preference_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, const igraph_vector_t *type_dist, igraph_bool_t fixed_sizes, const igraph_matrix_t *pref_matrix, igraph_vector_t *node_type_vec, igraph_bool_t directed, igraph_bool_t loops) { long int i, j; igraph_vector_t edges, s; igraph_vector_t* nodetypes; igraph_vector_ptr_t vids_by_type; igraph_real_t maxcum, maxedges; if (types < 1) IGRAPH_ERROR("types must be >= 1", IGRAPH_EINVAL); if (nodes < 0) IGRAPH_ERROR("nodes must be >= 0", IGRAPH_EINVAL); if (type_dist && igraph_vector_size(type_dist) != types) { if (igraph_vector_size(type_dist) > types) IGRAPH_WARNING("length of type_dist > types, type_dist will be trimmed"); else IGRAPH_ERROR("type_dist vector too short", IGRAPH_EINVAL); } if (igraph_matrix_nrow(pref_matrix) < types || igraph_matrix_ncol(pref_matrix) < types) IGRAPH_ERROR("pref_matrix too small", IGRAPH_EINVAL); if (fixed_sizes && type_dist) { if (igraph_vector_sum(type_dist) != nodes) { IGRAPH_ERROR("Invalid group sizes, their sum must match the number" " of vertices", IGRAPH_EINVAL); } } if (node_type_vec) { IGRAPH_CHECK(igraph_vector_resize(node_type_vec, nodes)); nodetypes = node_type_vec; } else { nodetypes = igraph_Calloc(1, igraph_vector_t); if (nodetypes == 0) { IGRAPH_ERROR("preference_game failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, nodetypes); IGRAPH_VECTOR_INIT_FINALLY(nodetypes, nodes); } IGRAPH_CHECK(igraph_vector_ptr_init(&vids_by_type, types)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &vids_by_type); for (i=0; i j && !directed) continue; maxedges = v1_size * v2_size; } else { if (directed && loops) maxedges = v1_size * v1_size; else if (directed && !loops) maxedges = v1_size * (v1_size-1); else if (!directed && loops) maxedges = v1_size * (v1_size+1)/2; else maxedges = v1_size * (v1_size-1)/2; } IGRAPH_CHECK(igraph_vector_reserve(&s, (long int) (maxedges*p*1.1))); last=RNG_GEOM(p); while (last < maxedges) { IGRAPH_CHECK(igraph_vector_push_back(&s, last)); last += RNG_GEOM(p); last += 1; } l = igraph_vector_size(&s); IGRAPH_CHECK(igraph_vector_reserve(&edges, igraph_vector_size(&edges)+l*2)); if (i != j) { /* Generating the subgraph between vertices of type i and j */ for (k=0; k * This is the asymmetric variant of \ref igraph_preference_game() . * A given number of vertices are generated. Every vertex is assigned to an * "incoming" and an "outgoing" vertex type according to the given joint * type probabilities. Finally, every vertex pair is evaluated and a * directed edge is created between them with a probability depending on the * "outgoing" type of the source vertex and the "incoming" type of the target * vertex. * * \param graph Pointer to an uninitialized graph. * \param nodes The number of vertices in the graph. * \param types The number of vertex types. * \param type_dist_matrix Matrix giving the joint distribution of vertex types. * If null, incoming and outgoing vertex types are independent and uniformly * distributed. * \param pref_matrix Matrix giving the connection probabilities for * different vertex types. * \param node_type_in_vec A vector where the individual generated "incoming" * vertex types will be stored. If NULL, the vertex types won't be saved. * \param node_type_out_vec A vector where the individual generated "outgoing" * vertex types will be stored. If NULL, the vertex types won't be saved. * \param loops Logical, whether loop edges are allowed. * \return Error code. * * Added in version 0.3. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges in the graph. * * \sa \ref igraph_preference_game() */ int igraph_asymmetric_preference_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t types, igraph_matrix_t *type_dist_matrix, igraph_matrix_t *pref_matrix, igraph_vector_t *node_type_in_vec, igraph_vector_t *node_type_out_vec, igraph_bool_t loops) { long int i, j, k; igraph_vector_t edges, cumdist, s, intersect; igraph_vector_t *nodetypes_in; igraph_vector_t *nodetypes_out; igraph_vector_ptr_t vids_by_intype, vids_by_outtype; igraph_real_t maxcum, maxedges; if (types < 1) IGRAPH_ERROR("types must be >= 1", IGRAPH_EINVAL); if (nodes < 0) IGRAPH_ERROR("nodes must be >= 0", IGRAPH_EINVAL); if (type_dist_matrix) { if (igraph_matrix_nrow(type_dist_matrix) < types || igraph_matrix_ncol(type_dist_matrix) < types) IGRAPH_ERROR("type_dist_matrix too small", IGRAPH_EINVAL); else if (igraph_matrix_nrow(type_dist_matrix) > types || igraph_matrix_ncol(type_dist_matrix) > types) IGRAPH_WARNING("type_dist_matrix will be trimmed"); } if (igraph_matrix_nrow(pref_matrix) < types || igraph_matrix_ncol(pref_matrix) < types) IGRAPH_ERROR("pref_matrix too small", IGRAPH_EINVAL); IGRAPH_VECTOR_INIT_FINALLY(&cumdist, types*types+1); if (node_type_in_vec) { nodetypes_in=node_type_in_vec; IGRAPH_CHECK(igraph_vector_resize(nodetypes_in, nodes)); } else { nodetypes_in = igraph_Calloc(1, igraph_vector_t); if (nodetypes_in == 0) { IGRAPH_ERROR("asymmetric_preference_game failed", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(nodetypes_in, nodes); } if (node_type_out_vec) { nodetypes_out=node_type_out_vec; IGRAPH_CHECK(igraph_vector_resize(nodetypes_out, nodes)); } else { nodetypes_out = igraph_Calloc(1, igraph_vector_t); if (nodetypes_out == 0) { IGRAPH_ERROR("asymmetric_preference_game failed", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(nodetypes_out, nodes); } IGRAPH_CHECK(igraph_vector_ptr_init(&vids_by_intype, types)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &vids_by_intype); IGRAPH_CHECK(igraph_vector_ptr_init(&vids_by_outtype, types)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &vids_by_outtype); for (i=0; i0) { for (kk=0; kk0) { c--; from--; if (VECTOR(*v1)[from] == VECTOR(*v2)[to]) from--; } } igraph_vector_push_back(&edges, VECTOR(*v1)[from]); igraph_vector_push_back(&edges, VECTOR(*v2)[to]); } } else { for (kk=0; kk Note that this function modifies the input \p graph, * call \ref igraph_copy() if you want to keep it. * * \param graph The input graph, this will be rewired, it can be * directed or undirected. * \param prob The rewiring probability a constant between zero and * one (inclusive). * \param loops Boolean, whether loop edges are allowed in the new * graph, or not. * \param multiple Boolean, whether multiple edges are allowed in the * new graph. * \return Error code. * * \sa \ref igraph_watts_strogatz_game() uses this function for the * rewiring. * * Time complexity: O(|V|+|E|). */ int igraph_rewire_edges(igraph_t *graph, igraph_real_t prob, igraph_bool_t loops, igraph_bool_t multiple) { igraph_t newgraph; long int no_of_edges=igraph_ecount(graph); long int no_of_nodes=igraph_vcount(graph); long int endpoints=no_of_edges*2; long int to_rewire; igraph_vector_t edges; if (prob < 0 || prob > 1) { IGRAPH_ERROR("Rewiring probability should be between zero and one", IGRAPH_EINVAL); } if (prob == 0) { /* This is easy, just leave things as they are */ return IGRAPH_SUCCESS; } IGRAPH_VECTOR_INIT_FINALLY(&edges, endpoints); RNG_BEGIN(); if (prob != 0 && no_of_edges > 0) { if (multiple) { /* If multiple edges are allowed, then there is an easy and fast method. Each endpoint of an edge is rewired with probability p, so the "skips" between the really rewired endpoints follow a geometric distribution. */ IGRAPH_CHECK(igraph_get_edgelist(graph, &edges, 0)); to_rewire=(long int) RNG_GEOM(prob); while (to_rewire < endpoints) { if (loops) { VECTOR(edges)[to_rewire] = RNG_INTEGER(0, no_of_nodes-1); } else { long int opos = to_rewire % 2 ? to_rewire-1 : to_rewire+1; long int nei= (long int) VECTOR(edges)[opos]; long int r=RNG_INTEGER(0, no_of_nodes-2); VECTOR(edges)[ to_rewire ] = (r != nei ? r : no_of_nodes-1); } to_rewire += RNG_GEOM(prob)+1; } } else { IGRAPH_CHECK(igraph_i_rewire_edges_no_multiple(graph, prob, loops, &edges)); } } RNG_END(); IGRAPH_CHECK(igraph_create(&newgraph, &edges, (igraph_integer_t) no_of_nodes, igraph_is_directed(graph))); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &newgraph); IGRAPH_I_ATTRIBUTE_DESTROY(&newgraph); IGRAPH_I_ATTRIBUTE_COPY(&newgraph, graph, 1,1,1); IGRAPH_FINALLY_CLEAN(1); igraph_destroy(graph); *graph=newgraph; return 0; } /** * \function igraph_watts_strogatz_game * \brief The Watts-Strogatz small-world model * * This function generates a graph according to the Watts-Strogatz * model of small-world networks. The graph is obtained by creating a * circular undirected lattice and then rewire the edges randomly with * a constant probability. * * See also: Duncan J Watts and Steven H Strogatz: * Collective dynamics of small world networks, Nature * 393, 440-442, 1998. * \param graph The graph to initialize. * \param dim The dimension of the lattice. * \param size The size of the lattice along each dimension. * \param nei The size of the neighborhood for each vertex. This is * the same as the \p nei argument of \ref * igraph_connect_neighborhood(). * \param p The rewiring probability. A real number between zero and * one (inclusive). * \param loops Logical, whether to generate loop edges. * \param multiple Logical, whether to allow multiple edges in the * generated graph. * \return Error code. * * \sa \ref igraph_lattice(), \ref igraph_connect_neighborhood() and * \ref igraph_rewire_edges() can be used if more flexibility is * needed, eg. a different type of lattice. * * Time complexity: O(|V|*d^o+|E|), |V| and |E| are the number of * vertices and edges, d is the average degree, o is the \p nei * argument. */ int igraph_watts_strogatz_game(igraph_t *graph, igraph_integer_t dim, igraph_integer_t size, igraph_integer_t nei, igraph_real_t p, igraph_bool_t loops, igraph_bool_t multiple) { igraph_vector_t dimvector; long int i; if (dim < 1) { IGRAPH_ERROR("WS game: dimension should be at least one", IGRAPH_EINVAL); } if (size < 1) { IGRAPH_ERROR("WS game: lattice size should be at least one", IGRAPH_EINVAL); } if (p < 0 || p > 1) { IGRAPH_ERROR("WS game: rewiring probability should be between 0 and 1", IGRAPH_EINVAL); } /* Create the lattice first */ IGRAPH_VECTOR_INIT_FINALLY(&dimvector, dim); for (i=0; i * The \p preference argument specifies the preferences for the * citation lags, ie. its first elements contains the attractivity * of the very recently cited vertices, etc. The last element is * special, it contains the attractivity of the vertices which were * never cited. This element should be bigger than zero. * * * Note that this function generates networks with multiple edges if * \p edges_per_step is bigger than one, call \ref igraph_simplify() * on the result to get rid of these edges. * \param graph Pointer to an uninitialized graph object, the result * will be stored here. * \param node The number of vertices in the network. * \param edges_per_node The number of edges to add in each time * step. * \param pagebins The number of age bins to use. * \param preference Pointer to an initialized vector of length * \c pagebins+1. This contains the `attractivity' of the various * age bins, the last element is the attractivity of the vertices * which were never cited, and it should be greater than zero. * It is a good idea to have all positive values in this vector. * \param directed Logical constant, whether to create directed * networks. * \return Error code. * * \sa \ref igraph_barabasi_aging_game(). * * Time complexity: O(|V|*a+|E|*log|V|), |V| is the number of vertices, * |E| is the total number of edges, a is the \p pagebins parameter. */ int igraph_lastcit_game(igraph_t *graph, igraph_integer_t nodes, igraph_integer_t edges_per_node, igraph_integer_t pagebins, const igraph_vector_t *preference, igraph_bool_t directed) { long int no_of_nodes=nodes; igraph_psumtree_t sumtree; igraph_vector_t edges; long int i, j, k; long int *lastcit; long int *index; long int agebins=pagebins; long int binwidth=no_of_nodes/agebins+1; if (agebins != igraph_vector_size(preference)-1) { IGRAPH_ERROR("`preference' vector should be of length `agebins' plus one", IGRAPH_EINVAL); } if (agebins <=1 ) { IGRAPH_ERROR("at least two age bins are need for lastcit game", IGRAPH_EINVAL); } if (VECTOR(*preference)[agebins] <= 0) { IGRAPH_ERROR("the last element of the `preference' vector needs to be positive", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); lastcit=igraph_Calloc(no_of_nodes, long int); if (!lastcit) { IGRAPH_ERROR("lastcit game failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, lastcit); index=igraph_Calloc(no_of_nodes+1, long int); if (!index) { IGRAPH_ERROR("lastcit game failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, index); IGRAPH_CHECK(igraph_psumtree_init(&sumtree, nodes)); IGRAPH_FINALLY(igraph_psumtree_destroy, &sumtree); IGRAPH_CHECK(igraph_vector_reserve(&edges, nodes*edges_per_node)); /* The first node */ igraph_psumtree_update(&sumtree, 0, VECTOR(*preference)[agebins]); index[0]=0; index[1]=0; RNG_BEGIN(); for (i=1; i= 1; k++) { long int shnode=i-binwidth*k; long int m=index[shnode], n=index[shnode+1]; for (j=2*m; j<2*n; j+=2) { long int cnode=(long int) VECTOR(edges)[j+1]; if (lastcit[cnode]==shnode+1) { igraph_psumtree_update(&sumtree, cnode, VECTOR(*preference)[k]); } } } } RNG_END(); igraph_psumtree_destroy(&sumtree); igraph_free(index); igraph_free(lastcit); IGRAPH_FINALLY_CLEAN(3); IGRAPH_CHECK(igraph_create(graph, &edges, nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_cited_type_game * \brief Simulate a citation based on vertex types. * * Function to create a network based on some vertex categories. This * function creates a citation network, in each step a single vertex * and \p edges_per_step citating edges are added, nodes with * different categories (may) have different probabilities to get * cited, as given by the \p pref vector. * * * Note that this function might generate networks with multiple edges * if \p edges_per_step is greater than one. You might want to call * \ref igraph_simplify() on the result to remove multiple edges. * \param graph Pointer to an uninitialized graph object. * \param nodes The number of vertices in the network. * \param types Numeric vector giving the categories of the vertices, * so it should contain \p nodes non-negative integer * numbers. Types are numbered from zero. * \param pref The attractivity of the different vertex categories in * a vector. Its length should be the maximum element in \p types * plus one (types are numbered from zero). * \param edges_per_step Integer constant, the number of edges to add * in each time step. * \param directed Logical constant, whether to create a directed * network. * \return Error code. * * \sa \ref igraph_citing_cited_type_game() for a bit more general * game. * * Time complexity: O((|V|+|E|)log|V|), |V| and |E| are number of * vertices and edges, respectively. */ int igraph_cited_type_game(igraph_t *graph, igraph_integer_t nodes, const igraph_vector_t *types, const igraph_vector_t *pref, igraph_integer_t edges_per_step, igraph_bool_t directed) { igraph_vector_t edges; igraph_vector_t cumsum; igraph_real_t sum; long int i,j; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&cumsum, 2); IGRAPH_CHECK(igraph_vector_reserve(&cumsum, nodes+1)); IGRAPH_CHECK(igraph_vector_reserve(&edges, nodes*edges_per_step)); /* first node */ VECTOR(cumsum)[0]=0; sum=VECTOR(cumsum)[1]=VECTOR(*pref)[ (long int) VECTOR(*types)[0] ]; RNG_BEGIN(); for (i=1; isumtrees) { return; } for (i=0; ino; i++) { igraph_psumtree_destroy(&s->sumtrees[i]); } } /** * \function igraph_citing_cited_type_game * \brief Simulate a citation network based on vertex types. * * This game is similar to \ref igraph_cited_type_game() but here the * category of the citing vertex is also considered. * * * An evolving citation network is modeled here, a single vertex and * its \p edges_per_step citation are added in each time step. The * odds the a given vertex is cited by the new vertex depends on the * category of both the citing and the cited vertex and is given in * the \p pref matrix. The categories of the citing vertex correspond * to the rows, the categories of the cited vertex to the columns of * this matrix. Ie. the element in row \c i and column \c j gives the * probability that a \c j vertex is cited, if the category of the * citing vertex is \c i. * * * Note that this function might generate networks with multiple edges * if \p edges_per_step is greater than one. You might want to call * \ref igraph_simplify() on the result to remove multiple edges. * \param graph Pointer to an uninitialized graph object. * \param nodes The number of vertices in the network. * \param types A numeric matrix of length \p nodes, containing the * categories of the vertices. The categories are numbered from * zero. * \param pref The preference matrix, a square matrix is required, * both the number of rows and columns should be the maximum * element in \p types plus one (types are numbered from zero). * \param directed Logical constant, whether to create a directed * network. * \return Error code. * * Time complexity: O((|V|+|E|)log|V|), |V| and |E| are number of * vertices and edges, respectively. */ int igraph_citing_cited_type_game(igraph_t *graph, igraph_integer_t nodes, const igraph_vector_t *types, const igraph_matrix_t *pref, igraph_integer_t edges_per_step, igraph_bool_t directed) { igraph_vector_t edges; igraph_i_citing_cited_type_game_struct_t str = { 0, 0 }; igraph_psumtree_t *sumtrees; igraph_vector_t sums; long int nocats=igraph_matrix_ncol(pref); long int i, j; IGRAPH_VECTOR_INIT_FINALLY(&edges,0); str.sumtrees=sumtrees=igraph_Calloc(nocats, igraph_psumtree_t); if (!sumtrees) { IGRAPH_ERROR("Citing-cited type game failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_i_citing_cited_type_game_free, &str); for (i=0; i1) { IGRAPH_ERROR("Invalid probability for islands", IGRAPH_EINVAL); } if ( (n_inter<0) || (n_inter>islands_size) ) { IGRAPH_ERROR("Invalid number of inter-islands links", IGRAPH_EINVAL); } // how much memory ? nbNodes = islands_n*islands_size; maxpossibleedgesPerIsland = ((double)islands_size*((double)islands_size-(double)1))/(double)2; maxedgesPerIsland = islands_pin*maxpossibleedgesPerIsland; nbEdgesInterIslands = n_inter*(islands_n*(islands_n-1))/2; maxedges = maxedgesPerIsland*islands_n + nbEdgesInterIslands; // debug&tests : printf("total nodes %d, maxedgesperisland %f, maxedgesinterislands %d, maxedges %f\n", nbNodes, maxedgesPerIsland, nbEdgesInterIslands, maxedges); // reserve enough place for all the edges, thanks ! IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, (long int) maxedges)); RNG_BEGIN(); // first create all the islands for (is=1; is<=islands_n; is++) { // for each island // index for start and end of nodes in this island startIsland = islands_size*(is-1); endIsland = startIsland+islands_size -1; // debug&tests : printf("start %d,end %d\n", startIsland, endIsland); // create the random numbers to be used (into s) IGRAPH_VECTOR_INIT_FINALLY(&s, 0); IGRAPH_CHECK(igraph_vector_reserve(&s, (long int) maxedgesPerIsland)); last=RNG_GEOM(islands_pin); // debug&tests : printf("last=%f \n", last); while (last < maxpossibleedgesPerIsland) { // maxedgesPerIsland IGRAPH_CHECK(igraph_vector_push_back(&s, last)); myrand = RNG_GEOM(islands_pin); last += myrand; //RNG_GEOM(islands_pin); //printf("myrand=%f , last=%f \n", myrand, last); last += 1; } // change this to edges ! for (i=0; i * The generation process goes as follows. We start from N disconnected nodes * (where N is given by the length of the fitness vector). Then we randomly * select two vertices i and j, with probabilities proportional to their * fitnesses. (When the generated graph is directed, i is selected according to * the out-fitnesses and j is selected according to the in-fitnesses). If the * vertices are not connected yet (or if multiple edges are allowed), we * connect them; otherwise we select a new pair. This is repeated until the * desired number of links are created. * * * It can be shown that the \em expected degree of each vertex will be * proportional to its fitness, although the actual, observed degree will not * be. If you need to generate a graph with an exact degree sequence, consider * \ref igraph_degree_sequence_game instead. * * * This model is commonly used to generate static scale-free networks. To * achieve this, you have to draw the fitness scores from the desired power-law * distribution. Alternatively, you may use \ref igraph_static_power_law_game * which generates the fitnesses for you with a given exponent. * * * Reference: Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution * in scale-free networks. Phys Rev Lett 87(27):278701, 2001. * * \param graph Pointer to an uninitialized graph object. * \param fitness_out A numeric vector containing the fitness of each vertex. * For directed graphs, this specifies the out-fitness * of each vertex. * \param fitness_in If \c NULL, the generated graph will be undirected. * If not \c NULL, this argument specifies the in-fitness * of each vertex. * \param no_of_edges The number of edges in the generated graph. * \param loops Whether to allow loop edges in the generated graph. * \param multiple Whether to allow multiple edges in the generated graph. * * \return Error code: * \c IGRAPH_EINVAL: invalid parameter * \c IGRAPH_ENOMEM: there is not enough * memory for the operation. * * Time complexity: O(|V| + |E| log |E|). */ int igraph_static_fitness_game(igraph_t *graph, igraph_integer_t no_of_edges, igraph_vector_t* fitness_out, igraph_vector_t* fitness_in, igraph_bool_t loops, igraph_bool_t multiple) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; igraph_integer_t no_of_nodes, max_no_of_edges; igraph_integer_t outnodes, innodes, nodes; igraph_vector_t cum_fitness_in, cum_fitness_out; igraph_vector_t *p_cum_fitness_in, *p_cum_fitness_out; igraph_real_t x, max_in, max_out; igraph_bool_t is_directed = (fitness_in != 0); float num_steps; igraph_integer_t step_counter = 0; long int i, from, to, pos; if (fitness_out == 0) { IGRAPH_ERROR("fitness_out must not be null", IGRAPH_EINVAL); } if (no_of_edges < 0) { IGRAPH_ERROR("Invalid number of edges", IGRAPH_EINVAL); } no_of_nodes = (int) igraph_vector_size(fitness_out); if (no_of_nodes == 0) { IGRAPH_CHECK(igraph_empty(graph, 0, is_directed)); return IGRAPH_SUCCESS; } if (is_directed && igraph_vector_size(fitness_in) != no_of_nodes) { IGRAPH_ERROR("fitness_in must have the same size as fitness_out", IGRAPH_EINVAL); } /* Sanity checks for the fitnesses */ if (igraph_vector_min(fitness_out) < 0) { IGRAPH_ERROR("Fitness scores must be non-negative", IGRAPH_EINVAL); } if (fitness_in != 0 && igraph_vector_min(fitness_in) < 0) { IGRAPH_ERROR("Fitness scores must be non-negative", IGRAPH_EINVAL); } /* Avoid getting into an infinite loop when too many edges are requested */ if (!multiple) { if (is_directed) { outnodes = innodes = nodes = 0; for (i=0; i < no_of_nodes; i++) { if (VECTOR(*fitness_out)[i] != 0) outnodes++; if (VECTOR(*fitness_in)[i] != 0) innodes++; if (VECTOR(*fitness_out)[i] != 0 && VECTOR(*fitness_in)[i] != 0) nodes++; } max_no_of_edges = outnodes * innodes - (loops ? 0 : nodes); } else { nodes = 0; for (i=0; i < no_of_nodes; i++) { if (VECTOR(*fitness_out)[i] != 0) nodes++; } max_no_of_edges = loops ? nodes*(nodes+1)/2 : nodes*(nodes-1)/2; } if (no_of_edges > max_no_of_edges) IGRAPH_ERROR("Too many edges requested", IGRAPH_EINVAL); } /* Calculate the cumulative fitness scores */ IGRAPH_VECTOR_INIT_FINALLY(&cum_fitness_out, no_of_nodes); IGRAPH_CHECK(igraph_vector_cumsum(&cum_fitness_out, fitness_out)); max_out = igraph_vector_tail(&cum_fitness_out); p_cum_fitness_out = &cum_fitness_out; if (is_directed) { IGRAPH_VECTOR_INIT_FINALLY(&cum_fitness_in, no_of_nodes); IGRAPH_CHECK(igraph_vector_cumsum(&cum_fitness_in, fitness_in)); max_in = igraph_vector_tail(&cum_fitness_in); p_cum_fitness_in = &cum_fitness_in; } else { max_in = max_out; p_cum_fitness_in = &cum_fitness_out; } RNG_BEGIN(); num_steps = no_of_edges; if (multiple) { /* Generating when multiple edges are allowed */ IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, 2 * no_of_edges)); while (no_of_edges > 0) { /* Report progress after every 10000 edges */ if ((step_counter++) % 10000 == 0) { IGRAPH_PROGRESS("Static fitness game", 100.0*(1 - no_of_edges/num_steps), NULL); IGRAPH_ALLOW_INTERRUPTION(); } x = RNG_UNIF(0, max_out); igraph_vector_binsearch(p_cum_fitness_out, x, &from); x = RNG_UNIF(0, max_in); igraph_vector_binsearch(p_cum_fitness_in, x, &to); /* Skip if loop edge and loops = false */ if (!loops && from == to) continue; igraph_vector_push_back(&edges, from); igraph_vector_push_back(&edges, to); no_of_edges--; } /* Create the graph */ IGRAPH_CHECK(igraph_create(graph, &edges, no_of_nodes, is_directed)); /* Clear the edge list */ igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); } else { /* Multiple edges are disallowed */ igraph_adjlist_t al; igraph_vector_int_t* neis; IGRAPH_CHECK(igraph_adjlist_init_empty(&al, no_of_nodes)); IGRAPH_FINALLY(igraph_adjlist_destroy, &al); while (no_of_edges > 0) { /* Report progress after every 10000 edges */ if ((step_counter++) % 10000 == 0) { IGRAPH_PROGRESS("Static fitness game", 100.0*(1 - no_of_edges/num_steps), NULL); IGRAPH_ALLOW_INTERRUPTION(); } x = RNG_UNIF(0, max_out); igraph_vector_binsearch(p_cum_fitness_out, x, &from); x = RNG_UNIF(0, max_in); igraph_vector_binsearch(p_cum_fitness_in, x, &to); /* Skip if loop edge and loops = false */ if (!loops && from == to) continue; /* For undirected graphs, ensure that from < to */ if (!is_directed && from > to) { pos = from; from = to; to = pos; } /* Is there already an edge? If so, try again */ neis = igraph_adjlist_get(&al, from); if (igraph_vector_int_binsearch(neis, to, &pos)) continue; /* Insert the edge */ IGRAPH_CHECK(igraph_vector_int_insert(neis, pos, to)); no_of_edges--; } /* Create the graph. We cannot use IGRAPH_ALL here for undirected graphs * because we did not add edges in both directions in the adjacency list. * We will use igraph_to_undirected in an extra step. */ IGRAPH_CHECK(igraph_adjlist(graph, &al, IGRAPH_OUT, 1)); if (!is_directed) IGRAPH_CHECK(igraph_to_undirected(graph, IGRAPH_TO_UNDIRECTED_EACH, 0)); /* Clear the adjacency list */ igraph_adjlist_destroy(&al); IGRAPH_FINALLY_CLEAN(1); } RNG_END(); IGRAPH_PROGRESS("Static fitness game", 100.0, NULL); /* Cleanup before we create the graph */ if (is_directed) { igraph_vector_destroy(&cum_fitness_in); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&cum_fitness_out); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \ingroup generators * \function igraph_static_power_law_game * \brief Generates a non-growing random graph with expected power-law degree distributions. * * This game generates a directed or undirected random graph where the * degrees of vertices follow power-law distributions with prescribed * exponents. For directed graphs, the exponents of the in- and out-degree * distributions may be specified separately. * * * The game simply uses \ref igraph_static_fitness_game with appropriately * constructed fitness vectors. In particular, the fitness of vertex i * is i-alpha, where alpha = 1/(gamma-1) * and gamma is the exponent given in the arguments. * * * To remove correlations between in- and out-degrees in case of directed * graphs, the in-fitness vector will be shuffled after it has been set up * and before \ref igraph_static_fitness_game is called. * * * Note that significant finite size effects may be observed for exponents * smaller than 3 in the original formulation of the game. This function * provides an argument that lets you remove the finite size effects by * assuming that the fitness of vertex i is * (i+i0-1)-alpha, * where i0 is a constant chosen appropriately to ensure that the maximum * degree is less than the square root of the number of edges times the * average degree; see the paper of Chung and Lu, and Cho et al for more * details. * * * References: * * * Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution * in scale-free networks. Phys Rev Lett 87(27):278701, 2001. * * * Chung F and Lu L: Connected components in a random graph with given * degree sequences. Annals of Combinatorics 6, 125-145, 2002. * * * Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions in * scale-free networks under the Achlioptas process. Phys Rev Lett * 103:135702, 2009. * * \param graph Pointer to an uninitialized graph object. * \param no_of_nodes The number of nodes in the generated graph. * \param no_of_edges The number of edges in the generated graph. * \param exponent_out The power law exponent of the degree distribution. * For directed graphs, this specifies the exponent of the * out-degree distribution. It must be greater than or * equal to 2. If you pass \c IGRAPH_INFINITY here, you * will get back an Erdos-Renyi random network. * \param exponent_in If negative, the generated graph will be undirected. * If greater than or equal to 2, this argument specifies * the exponent of the in-degree distribution. If * non-negative but less than 2, an error will be * generated. * \param loops Whether to allow loop edges in the generated graph. * \param multiple Whether to allow multiple edges in the generated graph. * \param finite_size_correction Whether to use the proposed finite size * correction of Cho et al. * * \return Error code: * \c IGRAPH_EINVAL: invalid parameter * \c IGRAPH_ENOMEM: there is not enough * memory for the operation. * * Time complexity: O(|V| + |E| log |E|). */ int igraph_static_power_law_game(igraph_t *graph, igraph_integer_t no_of_nodes, igraph_integer_t no_of_edges, igraph_real_t exponent_out, igraph_real_t exponent_in, igraph_bool_t loops, igraph_bool_t multiple, igraph_bool_t finite_size_correction) { igraph_vector_t fitness_out, fitness_in; igraph_real_t alpha_out = 0.0, alpha_in = 0.0; long int i; igraph_real_t j; if (no_of_nodes < 0) { IGRAPH_ERROR("Invalid number of nodes", IGRAPH_EINVAL); } /* Calculate alpha_out */ if (exponent_out < 2) { IGRAPH_ERROR("out-degree exponent must be >= 2", IGRAPH_EINVAL); } else if (igraph_finite(exponent_out)) { alpha_out = -1.0 / (exponent_out - 1); } else { alpha_out = 0.0; } /* Construct the out-fitnesses */ IGRAPH_VECTOR_INIT_FINALLY(&fitness_out, no_of_nodes); j = no_of_nodes; if (finite_size_correction && alpha_out < -0.5) { /* See the Cho et al paper, first page first column + footnote 7 */ j += pow(no_of_nodes, 1 + 0.5 / alpha_out) * pow(10*sqrt(2)*(1 + alpha_out), -1.0 / alpha_out)-1; } if (j < no_of_nodes) j = no_of_nodes; for (i = 0; i < no_of_nodes; i++, j--) { VECTOR(fitness_out)[i] = pow(j, alpha_out); } if (exponent_in >= 0) { if (exponent_in < 2) { IGRAPH_ERROR("in-degree exponent must be >= 2; use negative numbers " "for undirected graphs", IGRAPH_EINVAL); } else if (igraph_finite(exponent_in)) { alpha_in = -1.0 / (exponent_in - 1); } else { alpha_in = 0.0; } IGRAPH_VECTOR_INIT_FINALLY(&fitness_in, no_of_nodes); j = no_of_nodes; if (finite_size_correction && alpha_in < -0.5) { /* See the Cho et al paper, first page first column + footnote 7 */ j += pow(no_of_nodes, 1 + 0.5 / alpha_in) * pow(10*sqrt(2)*(1 + alpha_in), -1.0 / alpha_in)-1; } if (j < no_of_nodes) j = no_of_nodes; for (i = 0; i < no_of_nodes; i++, j--) { VECTOR(fitness_in)[i] = pow(j, alpha_in); } IGRAPH_CHECK(igraph_vector_shuffle(&fitness_in)); IGRAPH_CHECK(igraph_static_fitness_game(graph, no_of_edges, &fitness_out, &fitness_in, loops, multiple)); igraph_vector_destroy(&fitness_in); IGRAPH_FINALLY_CLEAN(1); } else { IGRAPH_CHECK(igraph_static_fitness_game(graph, no_of_edges, &fitness_out, 0, loops, multiple)); } igraph_vector_destroy(&fitness_out); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \ingroup generators * \function igraph_k_regular_game * \brief Generates a random graph where each vertex has the same degree. * * This game generates a directed or undirected random graph where the * degrees of vertices are equal to a predefined constant k. For undirected * graphs, at least one of k and the number of vertices must be even. * * * The game simply uses \ref igraph_degree_sequence_game with appropriately * constructed degree sequences. * * \param graph Pointer to an uninitialized graph object. * \param no_of_nodes The number of nodes in the generated graph. * \param k The degree of each vertex in an undirected graph, or * the out-degree and in-degree of each vertex in a * directed graph. * \param directed Whether the generated graph will be directed. * \param multiple Whether to allow multiple edges in the generated graph. * * \return Error code: * \c IGRAPH_EINVAL: invalid parameter; e.g., negative number of nodes, * or odd number of nodes and odd k for undirected * graphs. * \c IGRAPH_ENOMEM: there is not enough memory for the operation. * * Time complexity: O(|V|+|E|) if \c multiple is true, otherwise not known. */ int igraph_k_regular_game(igraph_t *graph, igraph_integer_t no_of_nodes, igraph_integer_t k, igraph_bool_t directed, igraph_bool_t multiple) { igraph_vector_t degseq; igraph_degseq_t mode = multiple ? IGRAPH_DEGSEQ_SIMPLE : IGRAPH_DEGSEQ_SIMPLE_NO_MULTIPLE; /* Note to self: we are not using IGRAPH_DEGSEQ_VL when multiple = false * because the VL method is not really good at generating k-regular graphs. * Actually, that's why we have added SIMPLE_NO_MULTIPLE. */ if (no_of_nodes < 0) { IGRAPH_ERROR("number of nodes must be non-negative", IGRAPH_EINVAL); } if (k < 0) { IGRAPH_ERROR("degree must be non-negative", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(°seq, no_of_nodes); igraph_vector_fill(°seq, k); IGRAPH_CHECK(igraph_degree_sequence_game(graph, °seq, directed ? °seq : 0, mode)); igraph_vector_destroy(°seq); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \function igraph_correlated_game * Generate pairs of correlated random graphs * * Sample a new graph by perturbing the adjacency matrix of a * given graph and shuffling its vertices. * * \param old_graph The original graph. * \param new_graph The new graph will be stored here. * \param corr A scalar in the unit interval, the target Pearson * correlation between the adjacency matrices of the original the * generated graph (the adjacency matrix being used as a vector). * \param p A numeric scalar, the probability of an edge between two * vertices, it must in the open (0,1) interval. * \param permutation A permutation to apply to the vertices of the * generated graph. It can also be a null pointer, in which case * the vertices will not be permuted. * \return Error code * * \sa \ref igraph_correlated_pair_game() for generating a pair * of correlated random graphs in one go. */ int igraph_correlated_game(const igraph_t *old_graph, igraph_t *new_graph, igraph_real_t corr, igraph_real_t p, const igraph_vector_t *permutation) { int no_of_nodes=igraph_vcount(old_graph); int no_of_edges=igraph_ecount(old_graph); igraph_bool_t directed=igraph_is_directed(old_graph); igraph_real_t no_of_all=directed ? no_of_nodes * (no_of_nodes-1) : no_of_nodes * (no_of_nodes-1) / 2; igraph_real_t no_of_missing=no_of_all - no_of_edges; igraph_real_t q= p + corr * (1 - p); igraph_real_t p_del= 1 - q; igraph_real_t p_add= ((1 - q) * (p / (1 - p))); igraph_vector_t add, delete, edges, newedges; igraph_real_t last; int p_e=0, p_a=0, p_d=0, no_add, no_del; igraph_real_t inf=IGRAPH_INFINITY; igraph_real_t next_e, next_a, next_d; int i; if (corr < -1 || corr > 1) { IGRAPH_ERROR("Correlation must be in [-1,1] in correlated " "Erdos-Renyi game", IGRAPH_EINVAL); } if (p <= 0 || p >= 1) { IGRAPH_ERROR("Edge probability must be in (0,1) in correlated " "Erdos-Renyi game", IGRAPH_EINVAL); } if (permutation) { if (igraph_vector_size(permutation) != no_of_nodes) { IGRAPH_ERROR("Invalid permutation length in correlated Erdos-Renyi game", IGRAPH_EINVAL); } } /* Special cases */ if (corr == 0) { return igraph_erdos_renyi_game(new_graph, IGRAPH_ERDOS_RENYI_GNP, no_of_nodes, p, directed, IGRAPH_NO_LOOPS); } if (corr == 1) { /* We don't copy, because we don't need the attributes.... */ IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2); IGRAPH_CHECK(igraph_get_edgelist(old_graph, &edges, /* bycol= */ 0)); if (permutation) { int newec=igraph_vector_size(&edges); for (i=0; i 0) { last=RNG_GEOM(p_del); while (last < no_of_edges) { IGRAPH_CHECK(igraph_vector_push_back(&delete, last)); last += RNG_GEOM(p_del); last += 1; } } no_del=igraph_vector_size(&delete); if (p_add > 0) { last=RNG_GEOM(p_add); while (last < no_of_missing) { IGRAPH_CHECK(igraph_vector_push_back(&add, last)); last += RNG_GEOM(p_add); last += 1; } } no_add=igraph_vector_size(&add); RNG_END(); IGRAPH_CHECK(igraph_get_edgelist(old_graph, &edges, /* bycol= */ 0)); /* Now we are merging the original edges, the edges that are removed, and the new edges. We have the following pointers: - p_a: the next edge to add - p_d: the next edge to delete - p_e: the next original edge - next_e: the code of the next edge in 'edges' - next_a: the code of the next edge to add - next_d: the code of the next edge to delete */ #define D_CODE(f,t) (((t)==no_of_nodes-1 ? f : t) * no_of_nodes + (f)) #define U_CODE(f,t) ((t) * ((t)-1) / 2 + (f)) #define CODE(f,t) (directed ? D_CODE(f,t) : U_CODE(f,t)) #define CODEE() (CODE(VECTOR(edges)[2*p_e], VECTOR(edges)[2*p_e+1])) /* First we (re)code the edges to delete */ for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_TYPES_INTERNAL_H #define IGRAPH_TYPES_INTERNAL_H #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif #include "igraph_types.h" #include "igraph_matrix.h" #include "igraph_stack.h" #include "igraph_strvector.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" __BEGIN_DECLS /* -------------------------------------------------- */ /* Indexed heap */ /* -------------------------------------------------- */ /** * Indexed heap data type. * \ingroup internal */ typedef struct s_indheap { igraph_real_t* stor_begin; igraph_real_t* stor_end; igraph_real_t* end; int destroy; long int* index_begin; } igraph_indheap_t; #define IGRAPH_INDHEAP_NULL { 0,0,0,0,0 } int igraph_indheap_init (igraph_indheap_t* h, long int size); int igraph_indheap_init_array (igraph_indheap_t *t, igraph_real_t* data, long int len); void igraph_indheap_destroy (igraph_indheap_t* h); int igraph_indheap_clear(igraph_indheap_t *h); igraph_bool_t igraph_indheap_empty (igraph_indheap_t* h); int igraph_indheap_push (igraph_indheap_t* h, igraph_real_t elem); int igraph_indheap_push_with_index(igraph_indheap_t* h, long int idx, igraph_real_t elem); int igraph_indheap_modify(igraph_indheap_t* h, long int idx, igraph_real_t elem); igraph_real_t igraph_indheap_max (igraph_indheap_t* h); igraph_real_t igraph_indheap_delete_max(igraph_indheap_t* h); long int igraph_indheap_size (igraph_indheap_t* h); int igraph_indheap_reserve (igraph_indheap_t* h, long int size); long int igraph_indheap_max_index(igraph_indheap_t *h); void igraph_indheap_i_build(igraph_indheap_t* h, long int head); void igraph_indheap_i_shift_up(igraph_indheap_t* h, long int elem); void igraph_indheap_i_sink(igraph_indheap_t* h, long int head); void igraph_indheap_i_switch(igraph_indheap_t* h, long int e1, long int e2); /* -------------------------------------------------- */ /* Doubly indexed heap */ /* -------------------------------------------------- */ /* This is a heap containing double elements and two indices, its intended usage is the storage of weighted edges. */ /** * Doubly indexed heap data type. * \ingroup internal */ typedef struct s_indheap_d { igraph_real_t* stor_begin; igraph_real_t* stor_end; igraph_real_t* end; int destroy; long int* index_begin; long int* index2_begin; } igraph_d_indheap_t; #define IGRAPH_D_INDHEAP_NULL { 0,0,0,0,0,0 } int igraph_d_indheap_init (igraph_d_indheap_t* h, long int size); void igraph_d_indheap_destroy (igraph_d_indheap_t* h); igraph_bool_t igraph_d_indheap_empty (igraph_d_indheap_t* h); int igraph_d_indheap_push (igraph_d_indheap_t* h, igraph_real_t elem, long int idx, long int idx2); igraph_real_t igraph_d_indheap_max (igraph_d_indheap_t* h); igraph_real_t igraph_d_indheap_delete_max(igraph_d_indheap_t* h); long int igraph_d_indheap_size (igraph_d_indheap_t* h); int igraph_d_indheap_reserve (igraph_d_indheap_t* h, long int size); void igraph_d_indheap_max_index(igraph_d_indheap_t *h, long int *idx, long int *idx2); void igraph_d_indheap_i_build(igraph_d_indheap_t* h, long int head); void igraph_d_indheap_i_shift_up(igraph_d_indheap_t* h, long int elem); void igraph_d_indheap_i_sink(igraph_d_indheap_t* h, long int head); void igraph_d_indheap_i_switch(igraph_d_indheap_t* h, long int e1, long int e2); /* -------------------------------------------------- */ /* Two-way indexed heap */ /* -------------------------------------------------- */ /* This is a smart indexed heap. In addition to the "normal" indexed heap it allows to access every element through its index in O(1) time. In other words, for this heap the _modify operation is O(1), the normal heap does this in O(n) time.... */ typedef struct igraph_2wheap_t { long int size; igraph_vector_t data; igraph_vector_long_t index; igraph_vector_long_t index2; } igraph_2wheap_t; int igraph_2wheap_init(igraph_2wheap_t *h, long int size); void igraph_2wheap_destroy(igraph_2wheap_t *h); int igraph_2wheap_clear(igraph_2wheap_t *h); int igraph_2wheap_push_with_index(igraph_2wheap_t *h, long int idx, igraph_real_t elem); igraph_bool_t igraph_2wheap_empty(const igraph_2wheap_t *h); long int igraph_2wheap_size(const igraph_2wheap_t *h); long int igraph_2wheap_max_size(const igraph_2wheap_t *h); igraph_real_t igraph_2wheap_max(const igraph_2wheap_t *h); long int igraph_2wheap_max_index(const igraph_2wheap_t *h); igraph_real_t igraph_2wheap_deactivate_max(igraph_2wheap_t *h); igraph_bool_t igraph_2wheap_has_elem(const igraph_2wheap_t *h, long int idx); igraph_bool_t igraph_2wheap_has_active(const igraph_2wheap_t *h, long int idx); igraph_real_t igraph_2wheap_get(const igraph_2wheap_t *h, long int idx); igraph_real_t igraph_2wheap_delete_max(igraph_2wheap_t *h); igraph_real_t igraph_2wheap_delete_max_index(igraph_2wheap_t *h, long int *idx); int igraph_2wheap_modify(igraph_2wheap_t *h, long int idx, igraph_real_t elem); int igraph_2wheap_check(igraph_2wheap_t *h); /** * Trie data type * \ingroup internal */ typedef struct s_igraph_trie_node { igraph_strvector_t strs; igraph_vector_ptr_t children; igraph_vector_t values; } igraph_trie_node_t; typedef struct s_igraph_trie { igraph_strvector_t strs; igraph_vector_ptr_t children; igraph_vector_t values; long int maxvalue; igraph_bool_t storekeys; igraph_strvector_t keys; } igraph_trie_t; #define IGRAPH_TRIE_NULL { IGRAPH_STRVECTOR_NULL, IGRAPH_VECTOR_PTR_NULL, \ IGRAPH_VECTOR_NULL, 0, 0, IGRAPH_STRVECTOR_NULL } #define IGRAPH_TRIE_INIT_FINALLY(tr, sk) \ do { IGRAPH_CHECK(igraph_trie_init(tr, sk)); \ IGRAPH_FINALLY(igraph_trie_destroy, tr); } while (0) int igraph_trie_init(igraph_trie_t *t, igraph_bool_t storekeys); void igraph_trie_destroy(igraph_trie_t *t); int igraph_trie_get(igraph_trie_t *t, const char *key, long int *id); int igraph_trie_check(igraph_trie_t *t, const char *key, long int *id); int igraph_trie_get2(igraph_trie_t *t, const char *key, long int length, long int *id); void igraph_trie_idx(igraph_trie_t *t, long int idx, char **str); int igraph_trie_getkeys(igraph_trie_t *t, const igraph_strvector_t **strv); long int igraph_trie_size(igraph_trie_t *t); /** * 2d grid containing points */ typedef struct igraph_2dgrid_t { igraph_matrix_t *coords; igraph_real_t minx, maxx, deltax; igraph_real_t miny, maxy, deltay; long int stepsx, stepsy; igraph_matrix_t startidx; igraph_vector_t next; igraph_vector_t prev; igraph_real_t massx, massy; /* The sum of the coordinates */ long int vertices; /* Number of active vertices */ } igraph_2dgrid_t; int igraph_2dgrid_init(igraph_2dgrid_t *grid, igraph_matrix_t *coords, igraph_real_t minx, igraph_real_t maxx, igraph_real_t deltax, igraph_real_t miny, igraph_real_t maxy, igraph_real_t deltay); void igraph_2dgrid_destroy(igraph_2dgrid_t *grid); void igraph_2dgrid_add(igraph_2dgrid_t *grid, long int elem, igraph_real_t xc, igraph_real_t yc); void igraph_2dgrid_add2(igraph_2dgrid_t *grid, long int elem); void igraph_2dgrid_move(igraph_2dgrid_t *grid, long int elem, igraph_real_t xc, igraph_real_t yc); void igraph_2dgrid_getcenter(const igraph_2dgrid_t *grid, igraph_real_t *massx, igraph_real_t *massy); igraph_bool_t igraph_2dgrid_in(const igraph_2dgrid_t *grid, long int elem); igraph_real_t igraph_2dgrid_dist(const igraph_2dgrid_t *grid, long int e1, long int e2); int igraph_2dgrid_neighbors(igraph_2dgrid_t *grid, igraph_vector_t *eids, igraph_integer_t vid, igraph_real_t r); typedef struct igraph_2dgrid_iterator_t { long int vid, x, y; long int nei; long int nx[4], ny[4], ncells; } igraph_2dgrid_iterator_t; void igraph_2dgrid_reset(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it); igraph_integer_t igraph_2dgrid_next(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it); igraph_integer_t igraph_2dgrid_next_nei(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it); /* Another type of grid, each cell is owned by exactly one graph */ typedef struct igraph_i_layout_mergegrid_t { long int *data; long int stepsx, stepsy; igraph_real_t minx, maxx, deltax; igraph_real_t miny, maxy, deltay; } igraph_i_layout_mergegrid_t; int igraph_i_layout_mergegrid_init(igraph_i_layout_mergegrid_t *grid, igraph_real_t minx, igraph_real_t maxx, long int stepsx, igraph_real_t miny, igraph_real_t maxy, long int stepsy); void igraph_i_layout_mergegrid_destroy(igraph_i_layout_mergegrid_t *grid); int igraph_i_layout_merge_place_sphere(igraph_i_layout_mergegrid_t *grid, igraph_real_t x, igraph_real_t y, igraph_real_t r, long int id); long int igraph_i_layout_mergegrid_get(igraph_i_layout_mergegrid_t *grid, igraph_real_t x, igraph_real_t y); long int igraph_i_layout_mergegrid_get_sphere(igraph_i_layout_mergegrid_t *g, igraph_real_t x, igraph_real_t y, igraph_real_t r); /* string -> string hash table */ typedef struct igraph_hashtable_t { igraph_trie_t keys; igraph_strvector_t elements; igraph_strvector_t defaults; } igraph_hashtable_t; int igraph_hashtable_init(igraph_hashtable_t *ht); void igraph_hashtable_destroy(igraph_hashtable_t *ht); int igraph_hashtable_addset(igraph_hashtable_t *ht, const char *key, const char *def, const char *elem); int igraph_hashtable_addset2(igraph_hashtable_t *ht, const char *key, const char *def, const char *elem, int elemlen); int igraph_hashtable_get(igraph_hashtable_t *ht, const char *key, char **elem); int igraph_hashtable_getkeys(igraph_hashtable_t *ht, const igraph_strvector_t **sv); int igraph_hashtable_reset(igraph_hashtable_t *ht); /* Buckets, needed for the maximum flow algorithm */ typedef struct igraph_buckets_t { igraph_vector_long_t bptr; igraph_vector_long_t buckets; igraph_integer_t max, no; } igraph_buckets_t; int igraph_buckets_init(igraph_buckets_t *b, long int bsize, long int size); void igraph_buckets_destroy(igraph_buckets_t *b); void igraph_buckets_clear(igraph_buckets_t *b); long int igraph_buckets_popmax(igraph_buckets_t *b); long int igraph_buckets_pop(igraph_buckets_t *b, long int bucket); igraph_bool_t igraph_buckets_empty(const igraph_buckets_t *b); igraph_bool_t igraph_buckets_empty_bucket(const igraph_buckets_t *b, long int bucket); void igraph_buckets_add(igraph_buckets_t *b, long int bucket, long int elem); typedef struct igraph_dbuckets_t { igraph_vector_long_t bptr; igraph_vector_long_t next, prev; igraph_integer_t max, no; } igraph_dbuckets_t; int igraph_dbuckets_init(igraph_dbuckets_t *b, long int bsize, long int size); void igraph_dbuckets_destroy(igraph_dbuckets_t *b); void igraph_dbuckets_clear(igraph_dbuckets_t *b); long int igraph_dbuckets_popmax(igraph_dbuckets_t *b); long int igraph_dbuckets_pop(igraph_dbuckets_t *b, long int bucket); igraph_bool_t igraph_dbuckets_empty(const igraph_dbuckets_t *b); igraph_bool_t igraph_dbuckets_empty_bucket(const igraph_dbuckets_t *b, long int bucket); void igraph_dbuckets_add(igraph_dbuckets_t *b, long int bucket, long int elem); void igraph_dbuckets_delete(igraph_dbuckets_t *b, long int bucket, long int elem); /* Special maximum heap, needed for the minimum cut algorithm */ typedef struct igraph_i_cutheap_t { igraph_vector_t heap; igraph_vector_t index; igraph_vector_t hptr; long int dnodes; } igraph_i_cutheap_t; int igraph_i_cutheap_init(igraph_i_cutheap_t *ch, igraph_integer_t nodes); void igraph_i_cutheap_destroy(igraph_i_cutheap_t *ch); igraph_bool_t igraph_i_cutheap_empty(igraph_i_cutheap_t *ch); igraph_integer_t igraph_i_cutheap_active_size(igraph_i_cutheap_t *ch); igraph_integer_t igraph_i_cutheap_size(igraph_i_cutheap_t *ch); igraph_real_t igraph_i_cutheap_maxvalue(igraph_i_cutheap_t *ch); igraph_integer_t igraph_i_cutheap_popmax(igraph_i_cutheap_t *ch); int igraph_i_cutheap_update(igraph_i_cutheap_t *ch, igraph_integer_t index, igraph_real_t add); int igraph_i_cutheap_reset_undefine(igraph_i_cutheap_t *ch, long int vertex); /* -------------------------------------------------- */ /* Flexible set */ /* -------------------------------------------------- */ /** * Set containing integer numbers regardless of the order * \ingroup types */ typedef struct s_set { igraph_integer_t* stor_begin; igraph_integer_t* stor_end; igraph_integer_t* end; } igraph_set_t; #define IGRAPH_SET_NULL { 0,0,0 } #define IGRAPH_SET_INIT_FINALLY(v, size) \ do { IGRAPH_CHECK(igraph_set_init(v, size)); \ IGRAPH_FINALLY(igraph_set_destroy, v); } while (0) int igraph_set_init (igraph_set_t* set, long int size); void igraph_set_destroy (igraph_set_t* set); igraph_bool_t igraph_set_inited (igraph_set_t* set); int igraph_set_reserve (igraph_set_t* set, long int size); igraph_bool_t igraph_set_empty (const igraph_set_t* set); void igraph_set_clear (igraph_set_t* set); long int igraph_set_size (const igraph_set_t* set); int igraph_set_add (igraph_set_t* v, igraph_integer_t e); igraph_bool_t igraph_set_contains (igraph_set_t* set, igraph_integer_t e); igraph_bool_t igraph_set_iterate (igraph_set_t* set, long int* state, igraph_integer_t* element); /* -------------------------------------------------- */ /* Vectorlist, fixed length */ /* -------------------------------------------------- */ typedef struct igraph_fixed_vectorlist_t { igraph_vector_t *vecs; igraph_vector_ptr_t v; long int length; } igraph_fixed_vectorlist_t; void igraph_fixed_vectorlist_destroy(igraph_fixed_vectorlist_t *l); int igraph_fixed_vectorlist_convert(igraph_fixed_vectorlist_t *l, const igraph_vector_t *from, long int size); __END_DECLS #endif igraph/src/cattributes.c0000644000175100001440000037627613431000472015045 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_attributes.h" #include "igraph_memory.h" #include "config.h" #include "igraph_math.h" #include "igraph_interface.h" #include "igraph_random.h" #include /* An attribute is either a numeric vector (vector_t) or a string vector (strvector_t). The attribute itself is stored in a struct igraph_attribute_record_t, there is one such object for each attribute. The igraph_t has a pointer to an array of three vector_ptr_t's which contains pointers to igraph_i_cattribute_t's. Graph attributes are first, then vertex and edge attributes. */ igraph_bool_t igraph_i_cattribute_find(const igraph_vector_ptr_t *ptrvec, const char *name, long int *idx) { long int i, n=igraph_vector_ptr_size(ptrvec); igraph_bool_t l=0; for (i=0; !l && iname, name); } if (idx) { *idx=i-1; } return l; } typedef struct igraph_i_cattributes_t { igraph_vector_ptr_t gal; igraph_vector_ptr_t val; igraph_vector_ptr_t eal; } igraph_i_cattributes_t; int igraph_i_cattributes_copy_attribute_record(igraph_attribute_record_t **newrec, const igraph_attribute_record_t *rec) { igraph_vector_t *num, *newnum; igraph_strvector_t *str, *newstr; *newrec=igraph_Calloc(1, igraph_attribute_record_t); if (!(*newrec)) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, *newrec); (*newrec)->type=rec->type; (*newrec)->name=strdup(rec->name); if (!(*newrec)->name) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (void*)(*newrec)->name); if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) { num=(igraph_vector_t *)rec->value; newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newnum); IGRAPH_CHECK(igraph_vector_copy(newnum, num)); IGRAPH_FINALLY(igraph_vector_destroy, newnum); (*newrec)->value=newnum; } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { str=(igraph_strvector_t*)rec->value; newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newstr); IGRAPH_CHECK(igraph_strvector_copy(newstr, str)); IGRAPH_FINALLY(igraph_strvector_destroy, newstr); (*newrec)->value=newstr; } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *log = (igraph_vector_bool_t*) rec->value; igraph_vector_bool_t *newlog = igraph_Calloc(1, igraph_vector_bool_t); if (!newlog) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newlog); IGRAPH_CHECK(igraph_vector_bool_copy(newlog, log)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newlog); (*newrec)->value = newlog; } IGRAPH_FINALLY_CLEAN(4); return 0; } int igraph_i_cattribute_init(igraph_t *graph, igraph_vector_ptr_t *attr) { igraph_attribute_record_t *attr_rec; long int i, n; igraph_i_cattributes_t *nattr; n = attr ? igraph_vector_ptr_size(attr) : 0; nattr=igraph_Calloc(1, igraph_i_cattributes_t); if (!nattr) { IGRAPH_ERROR("Can't init attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, nattr); IGRAPH_CHECK(igraph_vector_ptr_init(&nattr->gal, n)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &nattr->gal); IGRAPH_CHECK(igraph_vector_ptr_init(&nattr->val, 0)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &nattr->val); IGRAPH_CHECK(igraph_vector_ptr_init(&nattr->eal, 0)); IGRAPH_FINALLY_CLEAN(3); for (i=0; igal)[i] = attr_rec; } graph->attr=nattr; return 0; } void igraph_i_cattribute_destroy(igraph_t *graph) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *als[3]= { &attr->gal, &attr->val, &attr->eal }; long int i, n, a; igraph_vector_t *num; igraph_strvector_t *str; igraph_vector_bool_t *boolvec; igraph_attribute_record_t *rec; for (a=0; a<3; a++) { n=igraph_vector_ptr_size(als[a]); for (i=0; itype == IGRAPH_ATTRIBUTE_NUMERIC) { num=(igraph_vector_t*)rec->value; igraph_vector_destroy(num); igraph_free(num); } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { str=(igraph_strvector_t*)rec->value; igraph_strvector_destroy(str); igraph_free(str); } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { boolvec=(igraph_vector_bool_t*)rec->value; igraph_vector_bool_destroy(boolvec); igraph_free(boolvec); } igraph_free((char*)rec->name); igraph_free(rec); } } } igraph_vector_ptr_destroy(&attr->gal); igraph_vector_ptr_destroy(&attr->val); igraph_vector_ptr_destroy(&attr->eal); igraph_free(graph->attr); graph->attr=0; } /* Almost the same as destroy, but we might have null pointers */ void igraph_i_cattribute_copy_free(igraph_i_cattributes_t *attr) { igraph_vector_ptr_t *als[3] = { &attr->gal, &attr->val, &attr->eal }; long int i, n, a; igraph_vector_t *num; igraph_strvector_t *str; igraph_vector_bool_t *boolvec; igraph_attribute_record_t *rec; for (a=0; a<3; a++) { n=igraph_vector_ptr_size(als[a]); for (i=0; itype == IGRAPH_ATTRIBUTE_NUMERIC) { num=(igraph_vector_t*)rec->value; igraph_vector_destroy(num); igraph_free(num); } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { boolvec=(igraph_vector_bool_t*)rec->value; igraph_vector_bool_destroy(boolvec); igraph_free(boolvec); } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { str=(igraph_strvector_t*)rec->value; igraph_strvector_destroy(str); igraph_free(str); } igraph_free((char*)rec->name); igraph_free(rec); } } } /* No reference counting here. If you use attributes in C you should know what you're doing. */ int igraph_i_cattribute_copy(igraph_t *to, const igraph_t *from, igraph_bool_t ga, igraph_bool_t va, igraph_bool_t ea) { igraph_i_cattributes_t *attrfrom=from->attr, *attrto; igraph_vector_ptr_t *alto[3], *alfrom[3]={ &attrfrom->gal, &attrfrom->val, &attrfrom->eal }; long int i, n, a; igraph_bool_t copy[3] = { ga, va, ea }; to->attr=attrto=igraph_Calloc(1, igraph_i_cattributes_t); if (!attrto) { IGRAPH_ERROR("Cannot copy attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, attrto); IGRAPH_VECTOR_PTR_INIT_FINALLY(&attrto->gal, 0); IGRAPH_VECTOR_PTR_INIT_FINALLY(&attrto->val, 0); IGRAPH_VECTOR_PTR_INIT_FINALLY(&attrto->eal, 0); IGRAPH_FINALLY_CLEAN(3); IGRAPH_FINALLY(igraph_i_cattribute_copy_free, attrto); alto[0]=&attrto->gal; alto[1]=&attrto->val; alto[2]=&attrto->eal; for (a=0; a<3; a++) { if (copy[a]) { n=igraph_vector_ptr_size(alfrom[a]); IGRAPH_CHECK(igraph_vector_ptr_resize(alto[a], n)); igraph_vector_ptr_null(alto[a]); for (i=0; iattr; igraph_vector_ptr_t *val=&attr->val; long int length=igraph_vector_ptr_size(val); long int nattrno=nattr==NULL ? 0 : igraph_vector_ptr_size(nattr); long int origlen=igraph_vcount(graph)-nv; long int newattrs=0, i; igraph_vector_t news; /* First add the new attributes if any */ newattrs=0; IGRAPH_VECTOR_INIT_FINALLY(&news, 0); for (i=0; iname; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, nname, &j); if (!l) { newattrs++; IGRAPH_CHECK(igraph_vector_push_back(&news, i)); } else { /* check types */ if (nattr_entry->type != ((igraph_attribute_record_t*)VECTOR(*val)[j])->type) { IGRAPH_ERROR("You cannot mix attribute types", IGRAPH_EINVAL); } } } /* Add NA/empty string vectors for the existing vertices */ if (newattrs != 0) { for (i=0; itype; if (!newrec) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newrec); newrec->type=type; newrec->name=strdup(tmp->name); if (!newrec->name) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)newrec->name); if (type==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newnum); IGRAPH_VECTOR_INIT_FINALLY(newnum, origlen); newrec->value=newnum; igraph_vector_fill(newnum, IGRAPH_NAN); } else if (type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newstr); IGRAPH_STRVECTOR_INIT_FINALLY(newstr, origlen); newrec->value=newstr; } else if (type==IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newbool); IGRAPH_CHECK(igraph_vector_bool_init(newbool, origlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); newrec->value=newbool; igraph_vector_bool_fill(newbool, 0); } IGRAPH_CHECK(igraph_vector_ptr_push_back(val, newrec)); IGRAPH_FINALLY_CLEAN(4); } length=igraph_vector_ptr_size(val); } /* Now append the new values */ for (i=0; iname; long int j; igraph_bool_t l=0; if (nattr) { l=igraph_i_cattribute_find(nattr, name, &j); } if (l) { /* This attribute is present in nattr */ igraph_vector_t *oldnum, *newnum; igraph_strvector_t *oldstr, *newstr; igraph_vector_bool_t *oldbool, *newbool; newrec=VECTOR(*nattr)[j]; oldnum=(igraph_vector_t*)oldrec->value; newnum=(igraph_vector_t*)newrec->value; oldstr=(igraph_strvector_t*)oldrec->value; newstr=(igraph_strvector_t*)newrec->value; oldbool=(igraph_vector_bool_t*)oldrec->value; newbool=(igraph_vector_bool_t*)newrec->value; if (oldrec->type != newrec->type) { IGRAPH_ERROR("Attribute types do not match", IGRAPH_EINVAL); } switch (oldrec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: if (nv != igraph_vector_size(newnum)) { IGRAPH_ERROR("Invalid numeric attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_append(oldnum, newnum)); break; case IGRAPH_ATTRIBUTE_STRING: if (nv != igraph_strvector_size(newstr)) { IGRAPH_ERROR("Invalid string attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_strvector_append(oldstr, newstr)); break; case IGRAPH_ATTRIBUTE_BOOLEAN: if (nv != igraph_vector_bool_size(newbool)) { IGRAPH_ERROR("Invalid Boolean attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_bool_append(oldbool, newbool)); break; default: IGRAPH_WARNING("Invalid attribute type"); break; } } else { /* No such attribute, append NA's */ igraph_vector_t *oldnum=(igraph_vector_t *)oldrec->value; igraph_strvector_t *oldstr=(igraph_strvector_t*)oldrec->value; igraph_vector_bool_t *oldbool=(igraph_vector_bool_t*)oldrec->value; switch (oldrec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: IGRAPH_CHECK(igraph_vector_resize(oldnum, origlen+nv)); for (j=origlen; jname); if (rec->type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *numv= (igraph_vector_t*) rec->value; igraph_vector_destroy(numv); igraph_Free(numv); } else if (rec->type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strv= (igraph_strvector_t*) rec->value; igraph_strvector_destroy(strv); igraph_Free(strv); } else if (rec->type == IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *boolv= (igraph_vector_bool_t*) rec->value; igraph_vector_bool_destroy(boolv); igraph_Free(boolv); } igraph_Free(rec); } igraph_vector_ptr_clear(v); } int igraph_i_cattribute_permute_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { if (graph==newgraph) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int valno=igraph_vector_ptr_size(val); long int i; for (i=0; itype; igraph_vector_t *num, *newnum; igraph_strvector_t *str, *newstr; igraph_vector_bool_t *oldbool, *newbool; switch (type) { case IGRAPH_ATTRIBUTE_NUMERIC: num=(igraph_vector_t*) oldrec->value; newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(newnum, 0); igraph_vector_index(num, newnum, idx); oldrec->value=newnum; igraph_vector_destroy(num); igraph_Free(num); IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_BOOLEAN: oldbool=(igraph_vector_bool_t*) oldrec->value; newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_bool_init(newbool, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); igraph_vector_bool_index(oldbool, newbool, idx); oldrec->value=newbool; igraph_vector_bool_destroy(oldbool); igraph_Free(oldbool); IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_STRING: str=(igraph_strvector_t*)oldrec->value; newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_strvector_init(newstr, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, newstr); igraph_strvector_index(str, newstr, idx); oldrec->value=newstr; igraph_strvector_destroy(str); igraph_Free(str); IGRAPH_FINALLY_CLEAN(1); break; default: IGRAPH_WARNING("Unknown edge attribute ignored"); } } } else { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int valno=igraph_vector_ptr_size(val); long int i; /* New vertex attributes */ igraph_i_cattributes_t *new_attr=newgraph->attr; igraph_vector_ptr_t *new_val=&new_attr->val; if (igraph_vector_ptr_size(new_val) != 0) { IGRAPH_ERROR("Vertex attributes were already copied", IGRAPH_EATTRIBUTES); } IGRAPH_CHECK(igraph_vector_ptr_resize(new_val, valno)); IGRAPH_FINALLY(igraph_i_cattribute_permute_free, new_val); for (i=0; itype; igraph_vector_t *num, *newnum; igraph_strvector_t *str, *newstr; igraph_vector_bool_t *oldbool, *newbool; /* The record itself */ igraph_attribute_record_t *new_rec= igraph_Calloc(1, igraph_attribute_record_t); if (!new_rec) { IGRAPH_ERROR("Cannot create vertex attributes", IGRAPH_ENOMEM); } new_rec->name = strdup(oldrec->name); new_rec->type = oldrec->type; VECTOR(*new_val)[i]=new_rec; /* The data */ switch (type) { case IGRAPH_ATTRIBUTE_NUMERIC: num=(igraph_vector_t*)oldrec->value; newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(newnum, 0); igraph_vector_index(num, newnum, idx); new_rec->value=newnum; IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_BOOLEAN: oldbool=(igraph_vector_bool_t*)oldrec->value; newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_bool_init(newbool, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); igraph_vector_bool_index(oldbool, newbool, idx); new_rec->value=newbool; IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_STRING: str=(igraph_strvector_t*)oldrec->value; newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot permute vertex attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_strvector_init(newstr, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, newstr); igraph_strvector_index(str, newstr, idx); new_rec->value=newstr; IGRAPH_FINALLY_CLEAN(1); break; default: IGRAPH_WARNING("Unknown vertex attribute ignored"); } } } IGRAPH_FINALLY_CLEAN(1); return 0; } typedef int igraph_cattributes_combine_num_t(const igraph_vector_t *input, igraph_real_t *output); typedef int igraph_cattributes_combine_str_t(const igraph_strvector_t *input, char **output); typedef int igraph_cattributes_combine_bool_t(const igraph_vector_bool_t *input, igraph_bool_t *output); int igraph_i_cattributes_cn_sum(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cn_prod(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cn_min(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; i 0 ? VECTOR(*oldv)[ (long int) VECTOR(*idx)[0] ] : nan; for (j=1; jvalue = newv; return 0; } int igraph_i_cattributes_cn_max(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; i 0 ? VECTOR(*oldv)[ (long int) VECTOR(*idx)[0] ] : nan; for (j=1; j m) { m=val; } } VECTOR(*newv)[i]=m; } IGRAPH_FINALLY_CLEAN(2); newrec->value = newv; return 0; } int igraph_i_cattributes_cn_random(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); RNG_BEGIN(); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cn_first(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cn_last(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cn_mean(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_t *oldv=oldrec->value; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_real_t nan=IGRAPH_NAN; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); for (i=0; i 0 ? 0.0 : nan; for (j=0; j0) { s=s/n; } VECTOR(*newv)[i]=s; } IGRAPH_FINALLY_CLEAN(2); newrec->value = newv; return 0; } int igraph_i_cattributes_cn_func(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges, igraph_cattributes_combine_num_t *func) { const igraph_vector_t *oldv=oldrec->value; long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_vector_t *newv=igraph_Calloc(1, igraph_vector_t); igraph_vector_t values; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_VECTOR_INIT_FINALLY(newv, newlen); IGRAPH_VECTOR_INIT_FINALLY(&values, 0); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_random(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); RNG_BEGIN(); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_first(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_last(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_all_is_true(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i, j, n, x; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_any_is_true(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i, j, n, x; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_cb_majority(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t * newrec, const igraph_vector_ptr_t *merges) { const igraph_vector_bool_t *oldv=oldrec->value; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); long int newlen=igraph_vector_ptr_size(merges); long int i, j, n, x, num_trues; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); RNG_BEGIN(); for (i=0; i n/2); } else { if (num_trues == n/2) { VECTOR(*newv)[i] = (RNG_UNIF01() < 0.5); } else { VECTOR(*newv)[i] = (num_trues > n/2); } } } RNG_END(); IGRAPH_FINALLY_CLEAN(2); newrec->value = newv; return 0; } int igraph_i_cattributes_cb_func(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges, igraph_cattributes_combine_bool_t *func) { const igraph_vector_bool_t *oldv=oldrec->value; long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_vector_bool_t *newv=igraph_Calloc(1, igraph_vector_bool_t); igraph_vector_bool_t values; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_bool_init(newv, newlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); IGRAPH_CHECK(igraph_vector_bool_init(&values, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_sn_random(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges) { const igraph_strvector_t *oldv=oldrec->value; long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_strvector_t *newv=igraph_Calloc(1, igraph_strvector_t); if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_strvector_init(newv, newlen)); IGRAPH_FINALLY(igraph_strvector_destroy, newv); RNG_BEGIN(); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_sn_first(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges) { const igraph_strvector_t *oldv=oldrec->value; long int i, newlen=igraph_vector_ptr_size(merges); igraph_strvector_t *newv=igraph_Calloc(1, igraph_strvector_t); if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_strvector_init(newv, newlen)); IGRAPH_FINALLY(igraph_strvector_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_sn_last(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges) { const igraph_strvector_t *oldv=oldrec->value; long int i, newlen=igraph_vector_ptr_size(merges); igraph_strvector_t *newv=igraph_Calloc(1, igraph_strvector_t); if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_strvector_init(newv, newlen)); IGRAPH_FINALLY(igraph_strvector_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_sn_concat(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges) { const igraph_strvector_t *oldv=oldrec->value; long int i, newlen=igraph_vector_ptr_size(merges); igraph_strvector_t *newv=igraph_Calloc(1, igraph_strvector_t); if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_strvector_init(newv, newlen)); IGRAPH_FINALLY(igraph_strvector_destroy, newv); for (i=0; ivalue = newv; return 0; } int igraph_i_cattributes_sn_func(const igraph_attribute_record_t *oldrec, igraph_attribute_record_t *newrec, const igraph_vector_ptr_t *merges, igraph_cattributes_combine_str_t *func) { const igraph_strvector_t *oldv=oldrec->value; long int newlen=igraph_vector_ptr_size(merges); long int i; igraph_strvector_t *newv=igraph_Calloc(1, igraph_strvector_t); igraph_strvector_t values; if (!newv) { IGRAPH_ERROR("Cannot combine attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_strvector_init(newv, newlen)); IGRAPH_FINALLY(igraph_strvector_destroy, newv); IGRAPH_CHECK(igraph_strvector_init(newv, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, &values); for (i=0; ivalue = newv; return 0; } int igraph_i_cattribute_combine_vertices(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb) { igraph_i_cattributes_t *attr=graph->attr; igraph_i_cattributes_t *toattr=newgraph->attr; igraph_vector_ptr_t *val=&attr->val; igraph_vector_ptr_t *new_val=&toattr->val; long int valno=igraph_vector_ptr_size(val); long int i, j, keepno=0; int *TODO; igraph_function_pointer_t *funcs; TODO=igraph_Calloc(valno, int); if (!TODO) { IGRAPH_ERROR("Cannot combine vertex attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, TODO); funcs=igraph_Calloc(valno, igraph_function_pointer_t); if (!funcs) { IGRAPH_ERROR("Cannot combine vertex attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, funcs); for (i=0; iname; igraph_attribute_combination_type_t todo; igraph_function_pointer_t voidfunc; igraph_attribute_combination_query(comb, name, &todo, &voidfunc); TODO[i]=todo; funcs[i]=voidfunc; if (todo != IGRAPH_ATTRIBUTE_COMBINE_IGNORE) { keepno++; } } IGRAPH_CHECK(igraph_vector_ptr_resize(new_val, keepno)); IGRAPH_FINALLY(igraph_i_cattribute_permute_free, new_val); for (i=0, j=0; iname; igraph_attribute_combination_type_t todo= (igraph_attribute_combination_type_t) (TODO[i]); igraph_attribute_type_t type=oldrec->type; igraph_cattributes_combine_num_t *numfunc= (igraph_cattributes_combine_num_t*) funcs[i]; igraph_cattributes_combine_str_t *strfunc= (igraph_cattributes_combine_str_t*) funcs[i]; igraph_cattributes_combine_bool_t *boolfunc= (igraph_cattributes_combine_bool_t*) funcs[i]; if (todo==IGRAPH_ATTRIBUTE_COMBINE_DEFAULT || todo==IGRAPH_ATTRIBUTE_COMBINE_IGNORE) { continue; } newrec=igraph_Calloc(1, igraph_attribute_record_t); if (!newrec) { IGRAPH_ERROR("Cannot combine vertex attributes", IGRAPH_ENOMEM); } newrec->name = strdup(name); newrec->type = type; VECTOR(*new_val)[j] = newrec; if (type==IGRAPH_ATTRIBUTE_NUMERIC) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_cn_func(oldrec, newrec, merges, numfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: IGRAPH_CHECK(igraph_i_cattributes_cn_sum(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: IGRAPH_CHECK(igraph_i_cattributes_cn_prod(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_CHECK(igraph_i_cattributes_cn_min(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_CHECK(igraph_i_cattributes_cn_max(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_cn_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_cn_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_cn_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: IGRAPH_CHECK(igraph_i_cattributes_cn_mean(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_ERROR("Median calculation not implemented", IGRAPH_UNIMPLEMENTED); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_ERROR("Cannot concatenate numeric attributes", IGRAPH_EATTRCOMBINE); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else if (type==IGRAPH_ATTRIBUTE_BOOLEAN) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_cb_func(oldrec, newrec, merges, boolfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_CHECK(igraph_i_cattributes_cb_any_is_true(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_CHECK(igraph_i_cattributes_cb_all_is_true(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_CHECK(igraph_i_cattributes_cb_majority(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_cb_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_cb_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_cb_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_ERROR("Cannot calculate concatenation of Booleans", IGRAPH_EATTRCOMBINE); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else if (type==IGRAPH_ATTRIBUTE_STRING) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_sn_func(oldrec, newrec, merges, strfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: IGRAPH_ERROR("Cannot sum strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: IGRAPH_ERROR("Cannot multiply strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_ERROR("Cannot find minimum of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_ERROR("Cannot find maximum of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: IGRAPH_ERROR("Cannot calculate mean of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_ERROR("Cannot calculate median of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_sn_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_sn_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_sn_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_CHECK(igraph_i_cattributes_sn_concat(oldrec, newrec, merges)); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else { IGRAPH_ERROR("Unknown attribute type, this should not happen", IGRAPH_UNIMPLEMENTED); } j++; } igraph_free(funcs); igraph_free(TODO); IGRAPH_FINALLY_CLEAN(2); return 0; } /* void igraph_i_cattribute_delete_vertices(igraph_t *graph, */ /* const igraph_vector_t *eidx, */ /* const igraph_vector_t *vidx) { */ /* igraph_i_cattributes_t *attr=graph->attr; */ /* igraph_vector_ptr_t *val=&attr->val; */ /* igraph_vector_ptr_t *eal=&attr->eal; */ /* long int valno=igraph_vector_ptr_size(val); */ /* long int ealno=igraph_vector_ptr_size(eal); */ /* long int i; */ /* long int origlen, newlen; */ /* /\* Vertices *\/ */ /* origlen=igraph_vector_size(vidx); */ /* newlen=0; */ /* for (i=0; i0) { */ /* newlen++; */ /* } */ /* } */ /* for (i=0; itype; */ /* igraph_vector_t *num=(igraph_vector_t*)oldrec->value; */ /* igraph_strvector_t *str=(igraph_strvector_t*)oldrec->value; */ /* switch (type) { */ /* case IGRAPH_ATTRIBUTE_NUMERIC: */ /* igraph_vector_permdelete(num, vidx, origlen-newlen); */ /* break; */ /* case IGRAPH_ATTRIBUTE_STRING: */ /* igraph_strvector_permdelete(str, vidx, origlen-newlen); */ /* break; */ /* default: */ /* IGRAPH_WARNING("Unknown vertex attribute ignored"); */ /* } */ /* } */ /* /\* Edges *\/ */ /* origlen=igraph_vector_size(eidx); */ /* newlen=0; */ /* for (i=0; i0) { */ /* newlen++; */ /* } */ /* } */ /* for (i=0; itype; */ /* igraph_vector_t *num=(igraph_vector_t*)oldrec->value; */ /* igraph_strvector_t *str=(igraph_strvector_t*)oldrec->value; */ /* switch (type) { */ /* case IGRAPH_ATTRIBUTE_NUMERIC: */ /* igraph_vector_permdelete(num, eidx, origlen-newlen); */ /* break; */ /* case IGRAPH_ATTRIBUTE_STRING: */ /* igraph_strvector_permdelete(str, eidx, origlen-newlen); */ /* break; */ /* default: */ /* IGRAPH_WARNING("Unknown edge attribute ignored"); */ /* } */ /* } */ /* } */ int igraph_i_cattribute_add_edges(igraph_t *graph, const igraph_vector_t *edges, igraph_vector_ptr_t *nattr) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int ealno=igraph_vector_ptr_size(eal); long int ne=igraph_vector_size(edges)/2; long int origlen=igraph_ecount(graph)-ne; long int nattrno= nattr == 0 ? 0 : igraph_vector_ptr_size(nattr); igraph_vector_t news; long int newattrs, i; /* First add the new attributes if any */ newattrs=0; IGRAPH_VECTOR_INIT_FINALLY(&news, 0); for (i=0; iname; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, nname, &j); if (!l) { newattrs++; IGRAPH_CHECK(igraph_vector_push_back(&news, i)); } else { /* check types */ if (nattr_entry->type != ((igraph_attribute_record_t*)VECTOR(*eal)[j])->type) { IGRAPH_ERROR("You cannot mix attribute types", IGRAPH_EINVAL); } } } /* Add NA/empty string vectors for the existing vertices */ if (newattrs != 0) { for (i=0; itype; if (!newrec) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newrec); newrec->type=type; newrec->name=strdup(tmp->name); if (!newrec->name) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)newrec->name); if (type==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newnum); IGRAPH_VECTOR_INIT_FINALLY(newnum, origlen); newrec->value=newnum; igraph_vector_fill(newnum, IGRAPH_NAN); } else if (type==IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newbool); IGRAPH_CHECK(igraph_vector_bool_init(newbool, origlen)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); newrec->value=newbool; igraph_vector_bool_fill(newbool, 0); } else if (type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot add attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newstr); IGRAPH_STRVECTOR_INIT_FINALLY(newstr, origlen); newrec->value=newstr; } IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, newrec)); IGRAPH_FINALLY_CLEAN(4); } ealno=igraph_vector_ptr_size(eal); } /* Now append the new values */ for (i=0; iname; long int j; igraph_bool_t l=0; if (nattr) { l=igraph_i_cattribute_find(nattr, name, &j); } if (l) { /* This attribute is present in nattr */ igraph_vector_t *oldnum, *newnum; igraph_strvector_t *oldstr, *newstr; igraph_vector_bool_t *oldbool, *newbool; newrec=VECTOR(*nattr)[j]; oldnum=(igraph_vector_t*)oldrec->value; newnum=(igraph_vector_t*)newrec->value; oldstr=(igraph_strvector_t*)oldrec->value; newstr=(igraph_strvector_t*)newrec->value; oldbool=(igraph_vector_bool_t*)oldrec->value; newbool=(igraph_vector_bool_t*)newrec->value; if (oldrec->type != newrec->type) { IGRAPH_ERROR("Attribute types do not match", IGRAPH_EINVAL); } switch (oldrec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: if (ne != igraph_vector_size(newnum)) { IGRAPH_ERROR("Invalid numeric attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_append(oldnum, newnum)); break; case IGRAPH_ATTRIBUTE_STRING: if (ne != igraph_strvector_size(newstr)) { IGRAPH_ERROR("Invalid string attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_strvector_append(oldstr, newstr)); break; case IGRAPH_ATTRIBUTE_BOOLEAN: if (ne != igraph_vector_bool_size(newbool)) { IGRAPH_ERROR("Invalid Boolean attribute length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_bool_append(oldbool, newbool)); break; default: IGRAPH_WARNING("Invalid attribute type"); break; } } else { /* No such attribute, append NA's */ igraph_vector_t *oldnum=(igraph_vector_t *)oldrec->value; igraph_strvector_t *oldstr=(igraph_strvector_t*)oldrec->value; igraph_vector_bool_t *oldbool=(igraph_vector_bool_t *)oldrec->value; switch (oldrec->type) { case IGRAPH_ATTRIBUTE_NUMERIC: IGRAPH_CHECK(igraph_vector_resize(oldnum, origlen+ne)); for (j=origlen; jattr; */ /* igraph_vector_ptr_t *eal=&attr->eal; */ /* long int ealno=igraph_vector_ptr_size(eal); */ /* long int i; */ /* long int origlen=igraph_vector_size(idx), newlen; */ /* newlen=0; */ /* for (i=0; i0) { */ /* newlen++; */ /* } */ /* } */ /* for (i=0; itype; */ /* igraph_vector_t *num=(igraph_vector_t*)oldrec->value; */ /* igraph_strvector_t *str=(igraph_strvector_t*)oldrec->value; */ /* switch (type) { */ /* case IGRAPH_ATTRIBUTE_NUMERIC: */ /* igraph_vector_permdelete(num, idx, origlen-newlen); */ /* break; */ /* case IGRAPH_ATTRIBUTE_STRING: */ /* igraph_strvector_permdelete(str, idx, origlen-newlen); */ /* break; */ /* default: */ /* IGRAPH_WARNING("Unknown edge attribute ignored"); */ /* } */ /* } */ /* } */ int igraph_i_cattribute_permute_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_t *idx) { if (graph == newgraph) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int ealno=igraph_vector_ptr_size(eal); long int i; for (i=0; itype; igraph_vector_t *num, *newnum; igraph_strvector_t *str, *newstr; igraph_vector_bool_t *oldbool, *newbool; switch (type) { case IGRAPH_ATTRIBUTE_NUMERIC: num=(igraph_vector_t*) oldrec->value; newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(newnum, 0); igraph_vector_index(num, newnum, idx); oldrec->value=newnum; igraph_vector_destroy(num); igraph_Free(num); IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_BOOLEAN: oldbool=(igraph_vector_bool_t*) oldrec->value; newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_bool_init(newbool, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); igraph_vector_bool_index(oldbool, newbool, idx); oldrec->value=newbool; igraph_vector_bool_destroy(oldbool); igraph_Free(oldbool); IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_STRING: str=(igraph_strvector_t*)oldrec->value; newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_strvector_init(newstr, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, newstr); igraph_strvector_index(str, newstr, idx); oldrec->value=newstr; igraph_strvector_destroy(str); igraph_Free(str); IGRAPH_FINALLY_CLEAN(1); break; default: IGRAPH_WARNING("Unknown edge attribute ignored"); } } } else { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int ealno=igraph_vector_ptr_size(eal); long int i; /* New edge attributes */ igraph_i_cattributes_t *new_attr=newgraph->attr; igraph_vector_ptr_t *new_eal=&new_attr->eal; IGRAPH_CHECK(igraph_vector_ptr_resize(new_eal, ealno)); IGRAPH_FINALLY(igraph_i_cattribute_permute_free, new_eal); for (i=0; itype; igraph_vector_t *num, *newnum; igraph_strvector_t *str, *newstr; igraph_vector_bool_t *oldbool, *newbool; /* The record itself */ igraph_attribute_record_t *new_rec= igraph_Calloc(1, igraph_attribute_record_t); if (!new_rec) { IGRAPH_ERROR("Cannot create edge attributes", IGRAPH_ENOMEM); } new_rec->name = strdup(oldrec->name); new_rec->type = oldrec->type; VECTOR(*new_eal)[i] = new_rec; switch (type) { case IGRAPH_ATTRIBUTE_NUMERIC: num=(igraph_vector_t*) oldrec->value; newnum=igraph_Calloc(1, igraph_vector_t); if (!newnum) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_VECTOR_INIT_FINALLY(newnum, 0); igraph_vector_index(num, newnum, idx); new_rec->value=newnum; IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_STRING: str=(igraph_strvector_t*)oldrec->value; newstr=igraph_Calloc(1, igraph_strvector_t); if (!newstr) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_strvector_init(newstr, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, newstr); igraph_strvector_index(str, newstr, idx); new_rec->value=newstr; IGRAPH_FINALLY_CLEAN(1); break; case IGRAPH_ATTRIBUTE_BOOLEAN: oldbool=(igraph_vector_bool_t*) oldrec->value; newbool=igraph_Calloc(1, igraph_vector_bool_t); if (!newbool) { IGRAPH_ERROR("Cannot permute edge attributes", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_bool_init(newbool, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, newbool); igraph_vector_bool_index(oldbool, newbool, idx); new_rec->value=newbool; IGRAPH_FINALLY_CLEAN(1); break; default: IGRAPH_WARNING("Unknown edge attribute ignored"); } } IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_combine_edges(const igraph_t *graph, igraph_t *newgraph, const igraph_vector_ptr_t *merges, const igraph_attribute_combination_t *comb) { igraph_i_cattributes_t *attr=graph->attr; igraph_i_cattributes_t *toattr=newgraph->attr; igraph_vector_ptr_t *eal=&attr->eal; igraph_vector_ptr_t *new_eal=&toattr->eal; long int ealno=igraph_vector_ptr_size(eal); long int i, j, keepno=0; int *TODO; igraph_function_pointer_t *funcs; TODO=igraph_Calloc(ealno, int); if (!TODO) { IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, TODO); funcs=igraph_Calloc(ealno, igraph_function_pointer_t); if (!funcs) { IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, funcs); for (i=0; iname; igraph_attribute_combination_type_t todo; igraph_function_pointer_t voidfunc; igraph_attribute_combination_query(comb, name, &todo, &voidfunc); TODO[i]=todo; funcs[i]=voidfunc; if (todo != IGRAPH_ATTRIBUTE_COMBINE_IGNORE) { keepno++; } } IGRAPH_CHECK(igraph_vector_ptr_resize(new_eal, keepno)); IGRAPH_FINALLY(igraph_i_cattribute_permute_free, new_eal); for (i=0, j=0; iname; igraph_attribute_combination_type_t todo= (igraph_attribute_combination_type_t) (TODO[i]); igraph_attribute_type_t type=oldrec->type; igraph_cattributes_combine_num_t *numfunc= (igraph_cattributes_combine_num_t*) funcs[i]; igraph_cattributes_combine_str_t *strfunc= (igraph_cattributes_combine_str_t*) funcs[i]; igraph_cattributes_combine_bool_t *boolfunc= (igraph_cattributes_combine_bool_t*) funcs[i]; if (todo==IGRAPH_ATTRIBUTE_COMBINE_DEFAULT || todo==IGRAPH_ATTRIBUTE_COMBINE_IGNORE) { continue; } newrec=igraph_Calloc(1, igraph_attribute_record_t); if (!newrec) { IGRAPH_ERROR("Cannot combine edge attributes", IGRAPH_ENOMEM); } newrec->name = strdup(name); newrec->type = type; VECTOR(*new_eal)[j] = newrec; if (type==IGRAPH_ATTRIBUTE_NUMERIC) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_cn_func(oldrec, newrec, merges, numfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: IGRAPH_CHECK(igraph_i_cattributes_cn_sum(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: IGRAPH_CHECK(igraph_i_cattributes_cn_prod(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_CHECK(igraph_i_cattributes_cn_min(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_CHECK(igraph_i_cattributes_cn_max(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_cn_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_cn_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_cn_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: IGRAPH_CHECK(igraph_i_cattributes_cn_mean(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_ERROR("Median calculation not implemented", IGRAPH_UNIMPLEMENTED); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_ERROR("Cannot concatenate numeric attributes", IGRAPH_EATTRCOMBINE); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else if (type==IGRAPH_ATTRIBUTE_BOOLEAN) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_cb_func(oldrec, newrec, merges, boolfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_CHECK(igraph_i_cattributes_cb_any_is_true(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_CHECK(igraph_i_cattributes_cb_all_is_true(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_CHECK(igraph_i_cattributes_cb_majority(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_cb_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_cb_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_cb_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_ERROR("Cannot calculate concatenation of Booleans", IGRAPH_EATTRCOMBINE); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else if (type==IGRAPH_ATTRIBUTE_STRING) { switch (todo) { case IGRAPH_ATTRIBUTE_COMBINE_FUNCTION: IGRAPH_CHECK(igraph_i_cattributes_sn_func(oldrec, newrec, merges, strfunc)); break; case IGRAPH_ATTRIBUTE_COMBINE_SUM: IGRAPH_ERROR("Cannot sum strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_PROD: IGRAPH_ERROR("Cannot multiply strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MIN: IGRAPH_ERROR("Cannot find minimum of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MAX: IGRAPH_ERROR("Cannot find maximum of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MEAN: IGRAPH_ERROR("Cannot calculate mean of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_MEDIAN: IGRAPH_ERROR("Cannot calculate median of strings", IGRAPH_EATTRCOMBINE); break; case IGRAPH_ATTRIBUTE_COMBINE_RANDOM: IGRAPH_CHECK(igraph_i_cattributes_sn_random(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_FIRST: IGRAPH_CHECK(igraph_i_cattributes_sn_first(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_LAST: IGRAPH_CHECK(igraph_i_cattributes_sn_last(oldrec, newrec, merges)); break; case IGRAPH_ATTRIBUTE_COMBINE_CONCAT: IGRAPH_CHECK(igraph_i_cattributes_sn_concat(oldrec, newrec, merges)); break; default: IGRAPH_ERROR("Unknown attribute_combination", IGRAPH_UNIMPLEMENTED); break; } } else { IGRAPH_ERROR("Unknown attribute type, this should not happen", IGRAPH_UNIMPLEMENTED); } j++; } igraph_free(funcs); igraph_free(TODO); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_cattribute_get_info(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes) { igraph_strvector_t *names[3] = { gnames, vnames, enames }; igraph_vector_t *types[3] = { gtypes, vtypes, etypes }; igraph_i_cattributes_t *at=graph->attr; igraph_vector_ptr_t *attr[3]={ &at->gal, &at->val, &at->eal }; long int i,j; for (i=0; i<3; i++) { igraph_strvector_t *n=names[i]; igraph_vector_t *t=types[i]; igraph_vector_ptr_t *al=attr[i]; long int len=igraph_vector_ptr_size(al); if (n) { IGRAPH_CHECK(igraph_strvector_resize(n, len)); } if (t) { IGRAPH_CHECK(igraph_vector_resize(t, len)); } for (j=0; jname; igraph_attribute_type_t type=rec->type; if (n) { IGRAPH_CHECK(igraph_strvector_set(n, j, name)); } if (t) { VECTOR(*t)[j]=type; } } } return 0; } igraph_bool_t igraph_i_cattribute_has_attr(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name) { igraph_i_cattributes_t *at=graph->attr; igraph_vector_ptr_t *attr[3]={ &at->gal, &at->val, &at->eal }; long int attrnum; switch (type) { case IGRAPH_ATTRIBUTE_GRAPH: attrnum=0; break; case IGRAPH_ATTRIBUTE_VERTEX: attrnum=1; break; case IGRAPH_ATTRIBUTE_EDGE: attrnum=2; break; default: IGRAPH_ERROR("Unknown attribute element type", IGRAPH_EINVAL); break; } return igraph_i_cattribute_find(attr[attrnum], name, 0); } int igraph_i_cattribute_gettype(const igraph_t *graph, igraph_attribute_type_t *type, igraph_attribute_elemtype_t elemtype, const char *name) { long int attrnum; igraph_attribute_record_t *rec; igraph_i_cattributes_t *at=graph->attr; igraph_vector_ptr_t *attr[3]={ &at->gal, &at->val, &at->eal }; igraph_vector_ptr_t *al; long int j; igraph_bool_t l=0; switch (elemtype) { case IGRAPH_ATTRIBUTE_GRAPH: attrnum=0; break; case IGRAPH_ATTRIBUTE_VERTEX: attrnum=1; break; case IGRAPH_ATTRIBUTE_EDGE: attrnum=2; break; default: IGRAPH_ERROR("Unknown attribute element type", IGRAPH_EINVAL); break; } al=attr[attrnum]; l=igraph_i_cattribute_find(al, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*al)[j]; *type=rec->type; return 0; } int igraph_i_cattribute_get_numeric_graph_attr(const igraph_t *graph, const char *name, igraph_vector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*gal)[j]; num=(igraph_vector_t*)rec->value; IGRAPH_CHECK(igraph_vector_resize(value, 1)); VECTOR(*value)[0]=VECTOR(*num)[0]; return 0; } int igraph_i_cattribute_get_bool_graph_attr(const igraph_t *graph, const char *name, igraph_vector_bool_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*gal)[j]; log=(igraph_vector_bool_t*)rec->value; IGRAPH_CHECK(igraph_vector_bool_resize(value, 1)); VECTOR(*value)[0]=VECTOR(*log)[0]; return 0; } int igraph_i_cattribute_get_string_graph_attr(const igraph_t *graph, const char *name, igraph_strvector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*gal)[j]; str=(igraph_strvector_t*)rec->value; IGRAPH_CHECK(igraph_strvector_resize(value, 1)); IGRAPH_CHECK(igraph_strvector_set(value, 0, STR(*str,0))); return 0; } int igraph_i_cattribute_get_numeric_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*val)[j]; num=(igraph_vector_t*)rec->value; if (igraph_vs_is_all(&vs)) { igraph_vector_clear(value); IGRAPH_CHECK(igraph_vector_append(value, num)); } else { igraph_vit_t it; long int i=0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_vector_resize(value, IGRAPH_VIT_SIZE(it))); for (; !IGRAPH_VIT_END(it); IGRAPH_VIT_NEXT(it), i++) { long int v=IGRAPH_VIT_GET(it); VECTOR(*value)[i]=VECTOR(*num)[v]; } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_get_bool_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_vector_bool_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; igraph_vit_t it; long int i, j, v; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*val)[j]; log=(igraph_vector_bool_t*)rec->value; if (igraph_vs_is_all(&vs)) { igraph_vector_bool_clear(value); IGRAPH_CHECK(igraph_vector_bool_append(value, log)); } else { IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_vector_bool_resize(value, IGRAPH_VIT_SIZE(it))); for (i = 0; !IGRAPH_VIT_END(it); IGRAPH_VIT_NEXT(it), i++) { v=IGRAPH_VIT_GET(it); VECTOR(*value)[i]=VECTOR(*log)[v]; } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_get_string_vertex_attr(const igraph_t *graph, const char *name, igraph_vs_t vs, igraph_strvector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*val)[j]; str=(igraph_strvector_t*)rec->value; if (igraph_vs_is_all(&vs)) { igraph_strvector_resize(value, 0); IGRAPH_CHECK(igraph_strvector_append(value, str)); } else { igraph_vit_t it; long int i=0; IGRAPH_CHECK(igraph_vit_create(graph, vs, &it)); IGRAPH_FINALLY(igraph_vit_destroy, &it); IGRAPH_CHECK(igraph_strvector_resize(value, IGRAPH_VIT_SIZE(it))); for (; !IGRAPH_VIT_END(it); IGRAPH_VIT_NEXT(it), i++) { long int v=IGRAPH_VIT_GET(it); char *s; igraph_strvector_get(str, v, &s); IGRAPH_CHECK(igraph_strvector_set(value, i, s)); } igraph_vit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_get_numeric_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*eal)[j]; num=(igraph_vector_t*)rec->value; if (igraph_es_is_all(&es)) { igraph_vector_clear(value); IGRAPH_CHECK(igraph_vector_append(value, num)); } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_vector_resize(value, IGRAPH_EIT_SIZE(it))); for (; !IGRAPH_EIT_END(it); IGRAPH_EIT_NEXT(it), i++) { long int e=IGRAPH_EIT_GET(it); VECTOR(*value)[i]=VECTOR(*num)[e]; } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_get_string_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_strvector_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*eal)[j]; str=(igraph_strvector_t*)rec->value; if (igraph_es_is_all(&es)) { igraph_strvector_resize(value, 0); IGRAPH_CHECK(igraph_strvector_append(value, str)); } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_strvector_resize(value, IGRAPH_EIT_SIZE(it))); for (; !IGRAPH_EIT_END(it); IGRAPH_EIT_NEXT(it), i++) { long int e=IGRAPH_EIT_GET(it); char *s; igraph_strvector_get(str, e, &s); IGRAPH_CHECK(igraph_strvector_set(value, i, s)); } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_cattribute_get_bool_edge_attr(const igraph_t *graph, const char *name, igraph_es_t es, igraph_vector_bool_t *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { IGRAPH_ERROR("Unknown attribute", IGRAPH_EINVAL); } rec=VECTOR(*eal)[j]; log=(igraph_vector_bool_t*)rec->value; if (igraph_es_is_all(&es)) { igraph_vector_bool_clear(value); IGRAPH_CHECK(igraph_vector_bool_append(value, log)); } else { igraph_eit_t it; long int i=0; IGRAPH_CHECK(igraph_eit_create(graph, es, &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); IGRAPH_CHECK(igraph_vector_bool_resize(value, IGRAPH_EIT_SIZE(it))); for (; !IGRAPH_EIT_END(it); IGRAPH_EIT_NEXT(it), i++) { long int e=IGRAPH_EIT_GET(it); VECTOR(*value)[i]=VECTOR(*log)[e]; } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); } return 0; } /* -------------------------------------- */ const igraph_attribute_table_t igraph_cattribute_table={ &igraph_i_cattribute_init, &igraph_i_cattribute_destroy, &igraph_i_cattribute_copy, &igraph_i_cattribute_add_vertices, &igraph_i_cattribute_permute_vertices, &igraph_i_cattribute_combine_vertices, &igraph_i_cattribute_add_edges, &igraph_i_cattribute_permute_edges, &igraph_i_cattribute_combine_edges, &igraph_i_cattribute_get_info, &igraph_i_cattribute_has_attr, &igraph_i_cattribute_gettype, &igraph_i_cattribute_get_numeric_graph_attr, &igraph_i_cattribute_get_string_graph_attr, &igraph_i_cattribute_get_bool_graph_attr, &igraph_i_cattribute_get_numeric_vertex_attr, &igraph_i_cattribute_get_string_vertex_attr, &igraph_i_cattribute_get_bool_vertex_attr, &igraph_i_cattribute_get_numeric_edge_attr, &igraph_i_cattribute_get_string_edge_attr, &igraph_i_cattribute_get_bool_edge_attr }; /* -------------------------------------- */ /** * \section cattributes * There is an experimental attribute handler that can be used * from C code. In this section we show how this works. This attribute * handler is by default not attached (the default is no attribute * handler), so we first need to attach it: * * igraph_i_set_attribute_table(&igraph_cattribute_table); * * * Now the attribute functions are available. Please note that * the attribute handler must be attached before you call any other * igraph functions, otherwise you might end up with graphs without * attributes and an active attribute handler, which might cause * unexpected program behaviour. The rule is that you attach the * attribute handler in the beginning of your * main() and never touch it again. (Detaching * the attribute handler might lead to memory leaks.) * * It is not currently possible to have attribute handlers on a * per-graph basis. All graphs in an application must be managed with * the same attribute handler. (Including the default case when there * is no attribute handler at all. * * The C attribute handler supports attaching real numbers and * character strings as attributes. No vectors are allowed, ie. every * vertex might have an attribute called name, but it is * not possible to have a coords graph (or other) * attribute which is a vector of numbers. * * \example examples/simple/cattributes.c * \example examples/simple/cattributes2.c * \example examples/simple/cattributes3.c * \example examples/simple/cattributes4.c */ /** * \function igraph_cattribute_GAN * Query a numeric graph attribute. * * Returns the value of the given numeric graph attribute. * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute to query. * \return The value of the attribute. * * \sa \ref GAN for a simpler interface. * * Time complexity: O(Ag), the number of graph attributes. */ igraph_real_t igraph_cattribute_GAN(const igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*gal)[j]; num=(igraph_vector_t*)rec->value; return VECTOR(*num)[0]; } /** * \function igraph_cattribute_GAB * Query a boolean graph attribute. * * Returns the value of the given numeric graph attribute. * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute to query. * \return The value of the attribute. * * \sa \ref GAB for a simpler interface. * * Time complexity: O(Ag), the number of graph attributes. */ igraph_bool_t igraph_cattribute_GAB(const igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*gal)[j]; log=(igraph_vector_bool_t*)rec->value; return VECTOR(*log)[0]; } /** * \function igraph_cattribute_GAS * Query a string graph attribute. * * Returns a const pointer to the string graph attribute * specified in \p name. * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute to query. * \return The value of the attribute. * * \sa \ref GAS for a simpler interface. * * Time complexity: O(Ag), the number of graph attributes. */ const char* igraph_cattribute_GAS(const igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*gal)[j]; str=(igraph_strvector_t*)rec->value; return STR(*str, 0); } /** * \function igraph_cattribute_VAN * Query a numeric vertex attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param vid The id of the queried vertex. * \return The value of the attribute. * * \sa \ref VAN macro for a simpler interface. * * Time complexity: O(Av), the number of vertex attributes. */ igraph_real_t igraph_cattribute_VAN(const igraph_t *graph, const char *name, igraph_integer_t vid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*val)[j]; num=(igraph_vector_t*)rec->value; return VECTOR(*num)[(long int)vid]; } /** * \function igraph_cattribute_VAB * Query a boolean vertex attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param vid The id of the queried vertex. * \return The value of the attribute. * * \sa \ref VAB macro for a simpler interface. * * Time complexity: O(Av), the number of vertex attributes. */ igraph_bool_t igraph_cattribute_VAB(const igraph_t *graph, const char *name, igraph_integer_t vid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*val)[j]; log=(igraph_vector_bool_t*)rec->value; return VECTOR(*log)[(long int)vid]; } /** * \function igraph_cattribute_VAS * Query a string vertex attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param vid The id of the queried vertex. * \return The value of the attribute. * * \sa The macro \ref VAS for a simpler interface. * * Time complexity: O(Av), the number of vertex attributes. */ const char* igraph_cattribute_VAS(const igraph_t *graph, const char *name, igraph_integer_t vid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*val)[j]; str=(igraph_strvector_t*)rec->value; return STR(*str, (long int)vid); } /** * \function igraph_cattribute_EAN * Query a numeric edge attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param eid The id of the queried edge. * \return The value of the attribute. * * \sa \ref EAN for an easier interface. * * Time complexity: O(Ae), the number of edge attributes. */ igraph_real_t igraph_cattribute_EAN(const igraph_t *graph, const char *name, igraph_integer_t eid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_vector_t *num; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*eal)[j]; num=(igraph_vector_t*)rec->value; return VECTOR(*num)[(long int)eid]; } /** * \function igraph_cattribute_EAB * Query a boolean edge attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param eid The id of the queried edge. * \return The value of the attribute. * * \sa \ref EAB for an easier interface. * * Time complexity: O(Ae), the number of edge attributes. */ igraph_bool_t igraph_cattribute_EAB(const igraph_t *graph, const char *name, igraph_integer_t eid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_vector_bool_t *log; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*eal)[j]; log=(igraph_vector_bool_t*)rec->value; return VECTOR(*log)[(long int)eid]; } /** * \function igraph_cattribute_EAS * Query a string edge attribute. * * The attribute must exist, otherwise an error is triggered. * \param graph The input graph. * \param name The name of the attribute. * \param eid The id of the queried edge. * \return The value of the attribute. * * \se \ref EAS if you want to type less. * * Time complexity: O(Ae), the number of edge attributes. */ const char* igraph_cattribute_EAS(const igraph_t *graph, const char *name, igraph_integer_t eid) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_attribute_record_t *rec; igraph_strvector_t *str; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (!l) { igraph_error("Unknown attribute", __FILE__, __LINE__, IGRAPH_EINVAL); return 0; } rec=VECTOR(*eal)[j]; str=(igraph_strvector_t*)rec->value; return STR(*str, (long int)eid); } /** * \function igraph_cattribute_VANV * Query a numeric vertex attribute for many vertices * * \param graph The input graph. * \param name The name of the attribute. * \param vids The vertices to query. * \param result Pointer to an initialized vector, the result is * stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(v), where v is the number of vertices in 'vids'. */ int igraph_cattribute_VANV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_vector_t *result) { return igraph_i_cattribute_get_numeric_vertex_attr(graph, name, vids, result); } /** * \function igraph_cattribute_VABV * Query a boolean vertex attribute for many vertices * * \param graph The input graph. * \param name The name of the attribute. * \param vids The vertices to query. * \param result Pointer to an initialized boolean vector, the result is * stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(v), where v is the number of vertices in 'vids'. */ int igraph_cattribute_VABV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_vector_bool_t *result) { return igraph_i_cattribute_get_bool_vertex_attr(graph, name, vids, result); } /** * \function igraph_cattribute_EANV * Query a numeric edge attribute for many edges * * \param graph The input graph. * \param name The name of the attribute. * \param eids The edges to query. * \param result Pointer to an initialized vector, the result is * stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(e), where e is the number of edges in 'eids'. */ int igraph_cattribute_EANV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_vector_t *result) { return igraph_i_cattribute_get_numeric_edge_attr(graph, name, eids, result); } /** * \function igraph_cattribute_EABV * Query a boolean edge attribute for many edges * * \param graph The input graph. * \param name The name of the attribute. * \param eids The edges to query. * \param result Pointer to an initialized boolean vector, the result is * stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(e), where e is the number of edges in 'eids'. */ int igraph_cattribute_EABV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_vector_bool_t *result) { return igraph_i_cattribute_get_bool_edge_attr(graph, name, eids, result); } /** * \function igraph_cattribute_VASV * Query a string vertex attribute for many vertices * * \param graph The input graph. * \param name The name of the attribute. * \param vids The vertices to query. * \param result Pointer to an initialized string vector, the result * is stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(v), where v is the number of vertices in 'vids'. * (We assume that the string attributes have a bounded length.) */ int igraph_cattribute_VASV(const igraph_t *graph, const char *name, igraph_vs_t vids, igraph_strvector_t *result) { return igraph_i_cattribute_get_string_vertex_attr(graph, name, vids, result); } /** * \function igraph_cattribute_EASV * Query a string edge attribute for many edges * * \param graph The input graph. * \param name The name of the attribute. * \param vids The edges to query. * \param result Pointer to an initialized string vector, the result * is stored here. It will be resized, if needed. * \return Error code. * * Time complexity: O(e), where e is the number of edges in * 'eids'. (We assume that the string attributes have a bounded length.) */ int igraph_cattribute_EASV(const igraph_t *graph, const char *name, igraph_es_t eids, igraph_strvector_t *result) { return igraph_i_cattribute_get_string_edge_attr(graph, name, eids, result); } /** * \function igraph_cattribute_list * List all attributes * * See \ref igraph_attribute_type_t for the various attribute types. * \param graph The input graph. * \param gnames String vector, the names of the graph attributes. * \param gtypes Numeric vector, the types of the graph attributes. * \param vnames String vector, the names of the vertex attributes. * \param vtypes Numeric vector, the types of the vertex attributes. * \param enames String vector, the names of the edge attributes. * \param etypes Numeric vector, the types of the edge attributes. * \return Error code. * * Naturally, the string vector with the attribute names and the * numeric vector with the attribute types are in the right order, * i.e. the first name corresponds to the first type, etc. * * Time complexity: O(Ag+Av+Ae), the number of all attributes. */ int igraph_cattribute_list(const igraph_t *graph, igraph_strvector_t *gnames, igraph_vector_t *gtypes, igraph_strvector_t *vnames, igraph_vector_t *vtypes, igraph_strvector_t *enames, igraph_vector_t *etypes) { return igraph_i_cattribute_get_info(graph, gnames, gtypes, vnames, vtypes, enames, etypes); } /** * \function igraph_cattribute_has_attr * Checks whether a (graph, vertex or edge) attribute exists * * \param graph The graph. * \param type The type of the attribute, \c IGRAPH_ATTRIBUTE_GRAPH, * \c IGRAPH_ATTRIBUTE_VERTEX or \c IGRAPH_ATTRIBUTE_EDGE. * \param name Character constant, the name of the attribute. * \return Logical value, TRUE if the attribute exists, FALSE otherwise. * * Time complexity: O(A), the number of (graph, vertex or edge) * attributes, assuming attribute names are not too long. */ igraph_bool_t igraph_cattribute_has_attr(const igraph_t *graph, igraph_attribute_elemtype_t type, const char *name) { return igraph_i_cattribute_has_attr(graph, type, name); } /** * \function igraph_cattribute_GAN_set * Set a numeric graph attribute * * \param graph The graph. * \param name Name of the graph attribute. If there is no such * attribute yet, then it will be added. * \param value The (new) value of the graph attribute. * \return Error code. * * \se \ref SETGAN if you want to type less. * * Time complexity: O(1). */ int igraph_cattribute_GAN_set(igraph_t *graph, const char *name, igraph_real_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*gal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_t *num=(igraph_vector_t *)rec->value; VECTOR(*num)[0]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_t *num; if (!rec) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; num=igraph_Calloc(1, igraph_vector_t); if (!num) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, num); IGRAPH_VECTOR_INIT_FINALLY(num, 1); VECTOR(*num)[0]=value; rec->value=num; IGRAPH_CHECK(igraph_vector_ptr_push_back(gal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_GAB_set * Set a boolean graph attribute * * \param graph The graph. * \param name Name of the graph attribute. If there is no such * attribute yet, then it will be added. * \param value The (new) value of the graph attribute. * \return Error code. * * \se \ref SETGAN if you want to type less. * * Time complexity: O(1). */ int igraph_cattribute_GAB_set(igraph_t *graph, const char *name, igraph_bool_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*gal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_BOOLEAN) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_bool_t *log=(igraph_vector_bool_t *)rec->value; VECTOR(*log)[0]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_bool_t *log; if (!rec) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_BOOLEAN; log=igraph_Calloc(1, igraph_vector_bool_t); if (!log) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, log); IGRAPH_CHECK(igraph_vector_bool_init(log, 1)); IGRAPH_FINALLY(igraph_vector_bool_destroy, log); VECTOR(*log)[0]=value; rec->value=log; IGRAPH_CHECK(igraph_vector_ptr_push_back(gal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_GAS_set * Set a string graph attribute. * * \param graph The graph. * \param name Name of the graph attribute. If there is no such * attribute yet, then it will be added. * \param value The (new) value of the graph attribute. It will be * copied. * \return Error code. * * \se \ref SETGAS if you want to type less. * * Time complexity: O(1). */ int igraph_cattribute_GAS_set(igraph_t *graph, const char *name, const char *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*gal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_strvector_t *str=(igraph_strvector_t*)rec->value; IGRAPH_CHECK(igraph_strvector_set(str, 0, value)); } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_strvector_t *str; if (!rec) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_STRING; str=igraph_Calloc(1, igraph_strvector_t); if (!str) { IGRAPH_ERROR("Cannot add graph attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, str); IGRAPH_STRVECTOR_INIT_FINALLY(str, 1); IGRAPH_CHECK(igraph_strvector_set(str, 0, value)); rec->value=str; IGRAPH_CHECK(igraph_vector_ptr_push_back(gal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAN_set * Set a numeric vertex attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all vertices * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param vid Vertices for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETVAN for a simpler way. * * Time complexity: O(n), the number of vertices if the attribute is * new, O(|vid|) otherwise. */ int igraph_cattribute_VAN_set(igraph_t *graph, const char *name, igraph_integer_t vid, igraph_real_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*val)[j]; if (rec->type != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_t *num=(igraph_vector_t*)rec->value; VECTOR(*num)[(long int)vid]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_t *num; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; num=igraph_Calloc(1, igraph_vector_t); if (!num) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, num); IGRAPH_VECTOR_INIT_FINALLY(num, igraph_vcount(graph)); igraph_vector_fill(num, IGRAPH_NAN); VECTOR(*num)[(long int)vid]=value; rec->value=num; IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAB_set * Set a boolean vertex attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all vertices * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param vid Vertices for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETVAB for a simpler way. * * Time complexity: O(n), the number of vertices if the attribute is * new, O(|vid|) otherwise. */ int igraph_cattribute_VAB_set(igraph_t *graph, const char *name, igraph_integer_t vid, igraph_bool_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*val)[j]; if (rec->type != IGRAPH_ATTRIBUTE_BOOLEAN) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_bool_t *log=(igraph_vector_bool_t*)rec->value; VECTOR(*log)[(long int)vid]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_bool_t *log; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_BOOLEAN; log=igraph_Calloc(1, igraph_vector_bool_t); if (!log) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, log); IGRAPH_CHECK(igraph_vector_bool_init(log, igraph_vcount(graph))); IGRAPH_FINALLY(igraph_vector_bool_destroy, log); igraph_vector_bool_fill(log, 0); VECTOR(*log)[(long int)vid]=value; rec->value=log; IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAS_set * Set a string vertex attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all vertices * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param vid Vertices for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETVAS for a simpler way. * * Time complexity: O(n*l), n is the number of vertices, l is the * length of the string to set. If the attribute if not new then only * O(|vid|*l). */ int igraph_cattribute_VAS_set(igraph_t *graph, const char *name, igraph_integer_t vid, const char *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*val)[j]; if (rec->type != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_strvector_t *str=(igraph_strvector_t*)rec->value; IGRAPH_CHECK(igraph_strvector_set(str, vid, value)); } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_strvector_t *str; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_STRING; str=igraph_Calloc(1, igraph_strvector_t); if (!str) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, str); IGRAPH_STRVECTOR_INIT_FINALLY(str, igraph_vcount(graph)); IGRAPH_CHECK(igraph_strvector_set(str, vid, value)); rec->value=str; IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAN_set * Set a numeric edge attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all edges * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param eid Edges for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETEAN for a simpler way. * * Time complexity: O(e), the number of edges if the attribute is * new, O(|eid|) otherwise. */ int igraph_cattribute_EAN_set(igraph_t *graph, const char *name, igraph_integer_t eid, igraph_real_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*eal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_t *num=(igraph_vector_t*)rec->value; VECTOR(*num)[(long int)eid]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_t *num; if (!rec) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; num=igraph_Calloc(1, igraph_vector_t); if (!num) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, num); IGRAPH_VECTOR_INIT_FINALLY(num, igraph_ecount(graph)); igraph_vector_fill(num, IGRAPH_NAN); VECTOR(*num)[(long int)eid]=value; rec->value=num; IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAB_set * Set a boolean edge attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all edges * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param eid Edges for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETEAB for a simpler way. * * Time complexity: O(e), the number of edges if the attribute is * new, O(|eid|) otherwise. */ int igraph_cattribute_EAB_set(igraph_t *graph, const char *name, igraph_integer_t eid, igraph_bool_t value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*eal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_BOOLEAN) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_vector_bool_t *log=(igraph_vector_bool_t*)rec->value; VECTOR(*log)[(long int)eid]=value; } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_bool_t *log; if (!rec) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_BOOLEAN; log=igraph_Calloc(1, igraph_vector_bool_t); if (!log) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, log); IGRAPH_CHECK(igraph_vector_bool_init(log, igraph_ecount(graph))); IGRAPH_FINALLY(igraph_vector_bool_destroy, log); igraph_vector_bool_fill(log, 0); VECTOR(*log)[(long int)eid]=value; rec->value=log; IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAS_set * Set a string edge attribute * * The attribute will be added if not present already. If present it * will be overwritten. The same \p value is set for all edges * included in \p vid. * \param graph The graph. * \param name Name of the attribute. * \param eid Edges for which to set the attribute. * \param value The (new) value of the attribute. * \return Error code. * * \sa \ref SETEAS for a simpler way. * * Time complexity: O(e*l), n is the number of edges, l is the * length of the string to set. If the attribute if not new then only * O(|eid|*l). */ int igraph_cattribute_EAS_set(igraph_t *graph, const char *name, igraph_integer_t eid, const char *value) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (l) { igraph_attribute_record_t *rec=VECTOR(*eal)[j]; if (rec->type != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_ERROR("Invalid attribute type", IGRAPH_EINVAL); } else { igraph_strvector_t *str=(igraph_strvector_t*)rec->value; IGRAPH_CHECK(igraph_strvector_set(str, eid, value)); } } else { igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_strvector_t *str; if (!rec) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); rec->type=IGRAPH_ATTRIBUTE_STRING; str=igraph_Calloc(1, igraph_strvector_t); if (!str) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, str); IGRAPH_STRVECTOR_INIT_FINALLY(str, igraph_ecount(graph)); IGRAPH_CHECK(igraph_strvector_set(str, eid, value)); rec->value=str; IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAN_setv * Set a numeric vertex attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param v The new attribute values. The length of this vector must * match the number of vertices. * \return Error code. * * \sa \ref SETVANV for a simpler way. * * Time complexity: O(n), the number of vertices. */ int igraph_cattribute_VAN_setv(igraph_t *graph, const char *name, const igraph_vector_t *v) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); /* Check length first */ if (igraph_vector_size(v) != igraph_vcount(graph)) { IGRAPH_ERROR("Invalid vertex attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*val)[j]; igraph_vector_t *num=(igraph_vector_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_vector_clear(num); IGRAPH_CHECK(igraph_vector_append(num, v)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_t *num; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); num=igraph_Calloc(1, igraph_vector_t); if (!num) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, num); rec->value=num; IGRAPH_CHECK(igraph_vector_copy(num, v)); IGRAPH_FINALLY(igraph_vector_destroy, num); IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAB_setv * Set a boolean vertex attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param v The new attribute values. The length of this boolean vector must * match the number of vertices. * \return Error code. * * \sa \ref SETVANV for a simpler way. * * Time complexity: O(n), the number of vertices. */ int igraph_cattribute_VAB_setv(igraph_t *graph, const char *name, const igraph_vector_bool_t *v) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); /* Check length first */ if (igraph_vector_bool_size(v) != igraph_vcount(graph)) { IGRAPH_ERROR("Invalid vertex attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*val)[j]; igraph_vector_bool_t *log=(igraph_vector_bool_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_BOOLEAN) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_vector_bool_clear(log); IGRAPH_CHECK(igraph_vector_bool_append(log, v)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_bool_t *log; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_BOOLEAN; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); log=igraph_Calloc(1, igraph_vector_bool_t); if (!log) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, log); rec->value=log; IGRAPH_CHECK(igraph_vector_bool_copy(log, v)); IGRAPH_FINALLY(igraph_vector_destroy, log); IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_VAS_setv * Set a string vertex attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param sv String vector, the new attribute values. The length of this vector must * match the number of vertices. * \return Error code. * * \sa \ref SETVASV for a simpler way. * * Time complexity: O(n+l), n is the number of vertices, l is the * total length of the strings. */ int igraph_cattribute_VAS_setv(igraph_t *graph, const char *name, const igraph_strvector_t *sv) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); /* Check length first */ if (igraph_strvector_size(sv) != igraph_vcount(graph)) { IGRAPH_ERROR("Invalid vertex attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*val)[j]; igraph_strvector_t *str=(igraph_strvector_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_strvector_clear(str); IGRAPH_CHECK(igraph_strvector_append(str, sv)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_strvector_t *str; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_STRING; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); str=igraph_Calloc(1, igraph_strvector_t); if (!str) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, str); rec->value=str; IGRAPH_CHECK(igraph_strvector_copy(str, sv)); IGRAPH_FINALLY(igraph_strvector_destroy, str); IGRAPH_CHECK(igraph_vector_ptr_push_back(val, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAN_setv * Set a numeric edge attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param v The new attribute values. The length of this vector must * match the number of edges. * \return Error code. * * \sa \ref SETEANV for a simpler way. * * Time complexity: O(e), the number of edges. */ int igraph_cattribute_EAN_setv(igraph_t *graph, const char *name, const igraph_vector_t *v) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); /* Check length first */ if (igraph_vector_size(v) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid edge attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*eal)[j]; igraph_vector_t *num=(igraph_vector_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_vector_clear(num); IGRAPH_CHECK(igraph_vector_append(num, v)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_t *num; if (!rec) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); num=igraph_Calloc(1, igraph_vector_t); if (!num) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, num); rec->value=num; IGRAPH_CHECK(igraph_vector_copy(num, v)); IGRAPH_FINALLY(igraph_vector_destroy, num); IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAB_setv * Set a boolean edge attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param v The new attribute values. The length of this vector must * match the number of edges. * \return Error code. * * \sa \ref SETEABV for a simpler way. * * Time complexity: O(e), the number of edges. */ int igraph_cattribute_EAB_setv(igraph_t *graph, const char *name, const igraph_vector_bool_t *v) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); /* Check length first */ if (igraph_vector_bool_size(v) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid edge attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*eal)[j]; igraph_vector_bool_t *log=(igraph_vector_bool_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_BOOLEAN) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_vector_bool_clear(log); IGRAPH_CHECK(igraph_vector_bool_append(log, v)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_vector_bool_t *log; if (!rec) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_BOOLEAN; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); log=igraph_Calloc(1, igraph_vector_bool_t); if (!log) { IGRAPH_ERROR("Cannot add edge attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, log); rec->value=log; IGRAPH_CHECK(igraph_vector_bool_copy(log, v)); IGRAPH_FINALLY(igraph_vector_bool_destroy, log); IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } /** * \function igraph_cattribute_EAS_setv * Set a string edge attribute for all vertices. * * The attribute will be added if not present yet. * \param graph The graph. * \param name Name of the attribute. * \param sv String vector, the new attribute values. The length of this vector must * match the number of edges. * \return Error code. * * \sa \ref SETEASV for a simpler way. * * Time complexity: O(e+l), e is the number of edges, l is the * total length of the strings. */ int igraph_cattribute_EAS_setv(igraph_t *graph, const char *name, const igraph_strvector_t *sv) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); /* Check length first */ if (igraph_strvector_size(sv) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid edge attribute vector length", IGRAPH_EINVAL); } if (l) { /* Already present, check type */ igraph_attribute_record_t *rec=VECTOR(*eal)[j]; igraph_strvector_t *str=(igraph_strvector_t *)rec->value; if (rec->type != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_ERROR("Attribute type mismatch", IGRAPH_EINVAL); } igraph_strvector_clear(str); IGRAPH_CHECK(igraph_strvector_append(str, sv)); } else { /* Add it */ igraph_attribute_record_t *rec=igraph_Calloc(1, igraph_attribute_record_t); igraph_strvector_t *str; if (!rec) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, rec); rec->type=IGRAPH_ATTRIBUTE_STRING; rec->name=strdup(name); if (!rec->name) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, (char*)rec->name); str=igraph_Calloc(1, igraph_strvector_t); if (!str) { IGRAPH_ERROR("Cannot add vertex attribute", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, str); rec->value=str; IGRAPH_CHECK(igraph_strvector_copy(str, sv)); IGRAPH_FINALLY(igraph_strvector_destroy, str); IGRAPH_CHECK(igraph_vector_ptr_push_back(eal, rec)); IGRAPH_FINALLY_CLEAN(4); } return 0; } void igraph_i_cattribute_free_rec(igraph_attribute_record_t *rec) { if (rec->type==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *num=(igraph_vector_t*)rec->value; igraph_vector_destroy(num); } else if (rec->type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *str=(igraph_strvector_t*)rec->value; igraph_strvector_destroy(str); } else if (rec->type==IGRAPH_ATTRIBUTE_BOOLEAN) { igraph_vector_bool_t *boolvec=(igraph_vector_bool_t*)rec->value; igraph_vector_bool_destroy(boolvec); } igraph_Free(rec->name); igraph_Free(rec->value); igraph_Free(rec); } /** * \function igraph_cattribute_remove_g * Remove a graph attribute * * \param graph The graph object. * \param name Name of the graph attribute to remove. * * \sa \ref DELGA for a simpler way. * */ void igraph_cattribute_remove_g(igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *gal=&attr->gal; long int j; igraph_bool_t l=igraph_i_cattribute_find(gal, name, &j); if (l) { igraph_i_cattribute_free_rec(VECTOR(*gal)[j]); igraph_vector_ptr_remove(gal, j); } else { IGRAPH_WARNING("Cannot remove non-existent graph attribute"); } } /** * \function igraph_cattribute_remove_v * Remove a vertex attribute * * \param graph The graph object. * \param name Name of the vertex attribute to remove. * * \sa \ref DELVA for a simpler way. * */ void igraph_cattribute_remove_v(igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *val=&attr->val; long int j; igraph_bool_t l=igraph_i_cattribute_find(val, name, &j); if (l) { igraph_i_cattribute_free_rec(VECTOR(*val)[j]); igraph_vector_ptr_remove(val, j); } else { IGRAPH_WARNING("Cannot remove non-existent graph attribute"); } } /** * \function igraph_cattribute_remove_e * Remove an edge attribute * * \param graph The graph object. * \param name Name of the edge attribute to remove. * * \sa \ref DELEA for a simpler way. * */ void igraph_cattribute_remove_e(igraph_t *graph, const char *name) { igraph_i_cattributes_t *attr=graph->attr; igraph_vector_ptr_t *eal=&attr->eal; long int j; igraph_bool_t l=igraph_i_cattribute_find(eal, name, &j); if (l) { igraph_i_cattribute_free_rec(VECTOR(*eal)[j]); igraph_vector_ptr_remove(eal, j); } else { IGRAPH_WARNING("Cannot remove non-existent graph attribute"); } } /** * \function igraph_cattribute_remove_all * Remove all graph/vertex/edge attributes * * \param graph The graph object. * \param g Boolean, whether to remove graph attributes. * \param v Boolean, whether to remove vertex attributes. * \param e Boolean, whether to remove edge attributes. * * \sa \ref DELGAS, \ref DELVAS, \ref DELEAS, \ref DELALL for simpler * ways. */ void igraph_cattribute_remove_all(igraph_t *graph, igraph_bool_t g, igraph_bool_t v, igraph_bool_t e) { igraph_i_cattributes_t *attr=graph->attr; if (g) { igraph_vector_ptr_t *gal=&attr->gal; long int i, n=igraph_vector_ptr_size(gal); for (i=0;ival; long int i, n=igraph_vector_ptr_size(val); for (i=0;ieal; long int i, n=igraph_vector_ptr_size(eal); for (i=0;i #include "uuidP.h" static const char *fmt_lower = "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x"; static const char *fmt_upper = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X"; #ifdef UUID_UNPARSE_DEFAULT_UPPER #define FMT_DEFAULT fmt_upper #else #define FMT_DEFAULT fmt_lower #endif static void uuid_unparse_x(const uuid_t uu, char *out, const char *fmt) { struct uuid uuid; uuid_unpack(uu, &uuid); sprintf(out, fmt, uuid.time_low, uuid.time_mid, uuid.time_hi_and_version, uuid.clock_seq >> 8, uuid.clock_seq & 0xFF, uuid.node[0], uuid.node[1], uuid.node[2], uuid.node[3], uuid.node[4], uuid.node[5]); } void uuid_unparse_lower(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, fmt_lower); } void uuid_unparse_upper(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, fmt_upper); } void uuid_unparse(const uuid_t uu, char *out) { uuid_unparse_x(uu, out, FMT_DEFAULT); } igraph/src/uuid/uuidP.h0000644000175100001440000000410613431000472014531 0ustar hornikusers/* * uuid.h -- private header file for uuids * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include #include #include "config.h" #include "uuid.h" #define LIBUUID_CLOCK_FILE "/var/lib/libuuid/clock.txt" /* * Offset between 15-Oct-1582 and 1-Jan-70 */ #define TIME_OFFSET_HIGH 0x01B21DD2 #define TIME_OFFSET_LOW 0x13814000 struct uuid { uint32_t time_low; uint16_t time_mid; uint16_t time_hi_and_version; uint16_t clock_seq; uint8_t node[6]; }; /* * prototypes */ void uuid_pack(const struct uuid *uu, uuid_t ptr); void uuid_unpack(const uuid_t in, struct uuid *uu); igraph/src/uuid/gen_uuid.c0000644000175100001440000003172713431000472015246 0ustar hornikusers/* * gen_uuid.c --- generate a DCE-compatible uuid * * Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ /* * Force inclusion of SVID stuff since we need it if we're compiling in * gcc-wall wall mode */ #define _DEFAULT_SOURCE #include "config.h" #ifdef _WIN32 #define _WIN32_WINNT 0x0500 #include #define UUID MYUUID #endif #include #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_STDLIB_H #include #endif #include #include #include #include #include #ifdef HAVE_SYS_TIME_H #include #endif #include #ifdef HAVE_SYS_FILE_H #include #endif #ifdef HAVE_SYS_IOCTL_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_SYS_UN_H #include #endif #ifdef HAVE_SYS_SOCKIO_H #include #endif #ifdef HAVE_NET_IF_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_NET_IF_DL_H #include #endif #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H) #include #endif #include "uuidP.h" #include "uuidd.h" #ifdef USING_R #include "igraph_random.h" #define srand(x) ; #define rand() RNG_INTEGER(0, RAND_MAX) #endif #ifdef HAVE_TLS #define THREAD_LOCAL static __thread #else #define THREAD_LOCAL static #endif #ifdef _WIN32 #if 0 /* MinGW has gettimeofday so we don't need this */ static int gettimeofday (struct timeval *tv, void *dummy) { FILETIME ftime; uint64_t n; GetSystemTimeAsFileTime (&ftime); n = (((uint64_t) ftime.dwHighDateTime << 32) + (uint64_t) ftime.dwLowDateTime); if (n) { n /= 10; n -= ((369 * 365 + 89) * (uint64_t) 86400) * 1000000; } tv->tv_sec = n / 1000000; tv->tv_usec = n % 1000000; } #endif #ifdef __MINGW32__ int gettimeofday (struct timeval *tv, void *dummy); #endif #ifdef __MINGW64__ int gettimeofday (struct timeval *tv, void *dummy); #endif static int getuid (void) { return 1; } #endif /* * Get the ethernet hardware address, if we can find it... * * XXX for a windows version, probably should use GetAdaptersInfo: * http://www.codeguru.com/cpp/i-n/network/networkinformation/article.php/c5451 * commenting out get_node_id just to get gen_uuid to compile under windows * is not the right way to go! */ static int get_node_id(unsigned char *node_id) { #ifdef HAVE_NET_IF_H int sd; struct ifreq ifr, *ifrp; struct ifconf ifc; char buf[1024]; int n, i; unsigned char *a; #ifdef HAVE_NET_IF_DL_H struct sockaddr_dl *sdlp; #endif /* * BSD 4.4 defines the size of an ifreq to be * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len * However, under earlier systems, sa_len isn't present, so the size is * just sizeof(struct ifreq) */ #ifdef HAVE_SA_LEN #define max(x, y) (((x) > (y)) ? (x) : (y)) #define ifreq_size(i) max(sizeof(struct ifreq),\ sizeof((i).ifr_name)+(i).ifr_addr.sa_len) #else #define ifreq_size(i) sizeof(struct ifreq) #endif /* HAVE_SA_LEN */ sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sd < 0) { return -1; } memset(buf, 0, sizeof(buf)); ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) { close(sd); return -1; } n = ifc.ifc_len; for (i = 0; i < n; i+= ifreq_size(*ifrp) ) { ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i); strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ); #ifdef SIOCGIFHWADDR if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) continue; a = (unsigned char *) &ifr.ifr_hwaddr.sa_data; #else #ifdef SIOCGENADDR if (ioctl(sd, SIOCGENADDR, &ifr) < 0) continue; a = (unsigned char *) ifr.ifr_enaddr; #else #ifdef HAVE_NET_IF_DL_H sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr; if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6)) continue; a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen]; #else /* * XXX we don't have a way of getting the hardware * address */ close(sd); return 0; #endif /* HAVE_NET_IF_DL_H */ #endif /* SIOCGENADDR */ #endif /* SIOCGIFHWADDR */ if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5]) continue; if (node_id) { memcpy(node_id, a, 6); close(sd); return 1; } } close(sd); #endif return 0; } #if defined(__linux__) && defined(__NR_gettid) && defined(HAVE_JRAND48) #define DO_JRAND_MIX static unsigned short ul_jrand_seed[3]; #endif static int random_get_fd(void) { int i, fd = -1; struct timeval tv; gettimeofday(&tv, NULL); #ifndef _WIN32 fd = open("/dev/urandom", O_RDONLY); if (fd == -1) fd = open("/dev/random", O_RDONLY | O_NONBLOCK); if (fd >= 0) { i = fcntl(fd, F_GETFD); if (i >= 0) fcntl(fd, F_SETFD, i | FD_CLOEXEC); } #endif srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec); #ifdef DO_JRAND_MIX ul_jrand_seed[0] = getpid() ^ (tv.tv_sec & 0xFFFF); ul_jrand_seed[1] = getppid() ^ (tv.tv_usec & 0xFFFF); ul_jrand_seed[2] = (tv.tv_sec ^ tv.tv_usec) >> 16; #endif /* Crank the random number generator a few times */ gettimeofday(&tv, NULL); for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--) rand(); return fd; } /* * Generate a stream of random nbytes into buf. * Use /dev/urandom if possible, and if not, * use glibc pseudo-random functions. */ static void random_get_bytes(void *buf, size_t nbytes) { size_t i, n = nbytes; int fd = random_get_fd(); int lose_counter = 0; unsigned char *cp = (unsigned char *) buf; if (fd >= 0) { while (n > 0) { ssize_t x = read(fd, cp, n); if (x <= 0) { if (lose_counter++ > 16) break; continue; } n -= x; cp += x; lose_counter = 0; } close(fd); } /* * We do this all the time, but this is the only source of * randomness if /dev/random/urandom is out to lunch. */ for (cp = buf, i = 0; i < nbytes; i++) *cp++ ^= (rand() >> 7) & 0xFF; #ifdef DO_JRAND_MIX { unsigned short tmp_seed[3]; memcpy(tmp_seed, ul_jrand_seed, sizeof(tmp_seed)); ul_jrand_seed[2] = ul_jrand_seed[2] ^ syscall(__NR_gettid); for (cp = buf, i = 0; i < nbytes; i++) *cp++ ^= (jrand48(tmp_seed) >> 7) & 0xFF; memcpy(ul_jrand_seed, tmp_seed, sizeof(ul_jrand_seed)-sizeof(unsigned short)); } #endif return; } #ifdef _WIN32 /* compatibility layer */ #define LOCK_EX 1 #define LOCK_UN 2 static int flock(int fd, int op) { HANDLE h = (HANDLE) _get_osfhandle(fd); OVERLAPPED offset; if (h < 0) return -1; memset(&offset, 0, sizeof(offset)); switch (op) { case LOCK_EX: return (LockFileEx(h, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &offset)) ? 0 : -1; case LOCK_UN: UnlockFileEx(h, 0, 1, 0, &offset); return 0; } return -1; } #endif /* Assume that the gettimeofday() has microsecond granularity */ #define MAX_ADJUSTMENT 10 /* * Get clock from global sequence clock counter. * * Return -1 if the clock counter could not be opened/locked (in this case * pseudorandom value is returned in @ret_clock_seq), otherwise return 0. */ static int get_clock(uint32_t *clock_high, uint32_t *clock_low, uint16_t *ret_clock_seq, int *num) { THREAD_LOCAL int adjustment = 0; THREAD_LOCAL struct timeval last = {0, 0}; THREAD_LOCAL int state_fd = -2; THREAD_LOCAL FILE *state_f; THREAD_LOCAL uint16_t clock_seq; struct timeval tv; uint64_t clock_reg; mode_t save_umask; int len; int ret = 0; if (state_fd == -2) { save_umask = umask(0); state_fd = open(LIBUUID_CLOCK_FILE, O_RDWR|O_CREAT, 0660); (void) umask(save_umask); if (state_fd != -1) { state_f = fdopen(state_fd, "r+"); if (!state_f) { close(state_fd); state_fd = -1; ret = -1; } } else ret = -1; } if (state_fd >= 0) { rewind(state_f); } if (state_fd >= 0) { unsigned int cl; unsigned long tv1, tv2; int a; if (fscanf(state_f, "clock: %04x tv: %lu %lu adj: %d\n", &cl, &tv1, &tv2, &a) == 4) { clock_seq = cl & 0x3FFF; last.tv_sec = tv1; last.tv_usec = tv2; adjustment = a; } } if ((last.tv_sec == 0) && (last.tv_usec == 0)) { random_get_bytes(&clock_seq, sizeof(clock_seq)); clock_seq &= 0x3FFF; gettimeofday(&last, NULL); last.tv_sec--; } try_again: gettimeofday(&tv, NULL); if ((tv.tv_sec < last.tv_sec) || ((tv.tv_sec == last.tv_sec) && (tv.tv_usec < last.tv_usec))) { clock_seq = (clock_seq+1) & 0x3FFF; adjustment = 0; last = tv; } else if ((tv.tv_sec == last.tv_sec) && (tv.tv_usec == last.tv_usec)) { if (adjustment >= MAX_ADJUSTMENT) goto try_again; adjustment++; } else { adjustment = 0; last = tv; } clock_reg = tv.tv_usec*10 + adjustment; clock_reg += ((uint64_t) tv.tv_sec)*10000000; clock_reg += (((uint64_t) 0x01B21DD2) << 32) + 0x13814000; if (num && (*num > 1)) { adjustment += *num - 1; last.tv_usec += adjustment / 10; adjustment = adjustment % 10; last.tv_sec += last.tv_usec / 1000000; last.tv_usec = last.tv_usec % 1000000; } if (state_fd >= 0) { rewind(state_f); len = fprintf(state_f, "clock: %04x tv: %016lu %08lu adj: %08d\n", clock_seq, (unsigned long) last.tv_sec, (unsigned long) last.tv_usec, adjustment); fflush(state_f); if (ftruncate(state_fd, len) < 0) { fprintf(state_f, " \n"); fflush(state_f); } rewind(state_f); } *clock_high = clock_reg >> 32; *clock_low = clock_reg; *ret_clock_seq = clock_seq; return ret; } int __uuid_generate_time(uuid_t out, int *num) { static unsigned char node_id[6]; static int has_init = 0; struct uuid uu; uint32_t clock_mid; int ret; if (!has_init) { if (get_node_id(node_id) <= 0) { random_get_bytes(node_id, 6); /* * Set multicast bit, to prevent conflicts * with IEEE 802 addresses obtained from * network cards */ node_id[0] |= 0x01; } has_init = 1; } ret = get_clock(&clock_mid, &uu.time_low, &uu.clock_seq, num); uu.clock_seq |= 0x8000; uu.time_mid = (uint16_t) clock_mid; uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000; memcpy(uu.node, node_id, 6); uuid_pack(&uu, out); return ret; } /* * Generate time-based UUID and store it to @out * * Since there is no daemon here, use fall-back right away */ static int uuid_generate_time_generic(uuid_t out) { return __uuid_generate_time(out, 0); } /* * Generate time-based UUID and store it to @out. * * Discards return value from uuid_generate_time_generic() */ void uuid_generate_time(uuid_t out) { (void)uuid_generate_time_generic(out); } int uuid_generate_time_safe(uuid_t out) { return uuid_generate_time_generic(out); } void __uuid_generate_random(uuid_t out, int *num) { uuid_t buf; struct uuid uu; int i, n; if (!num || !*num) n = 1; else n = *num; for (i = 0; i < n; i++) { random_get_bytes(buf, sizeof(buf)); uuid_unpack(buf, &uu); uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000; uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x4000; uuid_pack(&uu, out); out += sizeof(uuid_t); } } void uuid_generate_random(uuid_t out) { int num = 1; /* No real reason to use the daemon for random uuid's -- yet */ __uuid_generate_random(out, &num); } /* * Check whether good random source (/dev/random or /dev/urandom) * is available. */ static int have_random_source(void) { struct stat s; return (!stat("/dev/random", &s) || !stat("/dev/urandom", &s)); } /* * This is the generic front-end to uuid_generate_random and * uuid_generate_time. It uses uuid_generate_random only if * /dev/urandom is available, since otherwise we won't have * high-quality randomness. */ void uuid_generate(uuid_t out) { if (have_random_source()) uuid_generate_random(out); else uuid_generate_time(out); } igraph/src/uuid/clear.c0000644000175100001440000000321413431000472014523 0ustar hornikusers/* * clear.c -- Clear a UUID * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include #include "uuidP.h" void uuid_clear(uuid_t uu) { memset(uu, 0, 16); } igraph/src/uuid/parse.c0000644000175100001440000000456513431000472014561 0ustar hornikusers/* * parse.c --- UUID parsing * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include #include #include #include #include "uuidP.h" int uuid_parse(const char *in, uuid_t uu) { struct uuid uuid; int i; const char *cp; char buf[3]; if (strlen(in) != 36) return -1; for (i=0, cp = in; i <= 36; i++,cp++) { if ((i == 8) || (i == 13) || (i == 18) || (i == 23)) { if (*cp == '-') continue; else return -1; } if (i== 36) if (*cp == 0) continue; if (!isxdigit(*cp)) return -1; } uuid.time_low = strtoul(in, NULL, 16); uuid.time_mid = strtoul(in+9, NULL, 16); uuid.time_hi_and_version = strtoul(in+14, NULL, 16); uuid.clock_seq = strtoul(in+19, NULL, 16); cp = in+24; buf[2] = 0; for (i=0; i < 6; i++) { buf[0] = *cp++; buf[1] = *cp++; uuid.node[i] = strtoul(buf, NULL, 16); } uuid_pack(&uuid, uu); return 0; } igraph/src/uuid/uuidd.h0000644000175100001440000000423013431000472014553 0ustar hornikusers/* * Definitions used by the uuidd daemon * * Copyright (C) 2007 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #ifndef _UUID_UUIDD_H #define _UUID_UUIDD_H #define UUIDD_DIR _PATH_LOCALSTATEDIR "/uuidd" #define UUIDD_SOCKET_PATH UUIDD_DIR "/request" #define UUIDD_PIDFILE_PATH UUIDD_DIR "/uuidd.pid" #define UUIDD_PATH "/usr/sbin/uuidd" #define UUIDD_OP_GETPID 0 #define UUIDD_OP_GET_MAXOP 1 #define UUIDD_OP_TIME_UUID 2 #define UUIDD_OP_RANDOM_UUID 3 #define UUIDD_OP_BULK_TIME_UUID 4 #define UUIDD_OP_BULK_RANDOM_UUID 5 #define UUIDD_MAX_OP UUIDD_OP_BULK_RANDOM_UUID extern int __uuid_generate_time(uuid_t out, int *num); extern void __uuid_generate_random(uuid_t out, int *num); #endif /* _UUID_UUID_H */ igraph/src/uuid/compare.c0000644000175100001440000000416713431000472015073 0ustar hornikusers/* * compare.c --- compare whether or not two UUIDs are the same * * Returns 0 if the two UUIDs are different, and 1 if they are the same. * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include "uuidP.h" #include #define UUCMP(u1,u2) if (u1 != u2) return((u1 < u2) ? -1 : 1); int uuid_compare(const uuid_t uu1, const uuid_t uu2) { struct uuid uuid1, uuid2; uuid_unpack(uu1, &uuid1); uuid_unpack(uu2, &uuid2); UUCMP(uuid1.time_low, uuid2.time_low); UUCMP(uuid1.time_mid, uuid2.time_mid); UUCMP(uuid1.time_hi_and_version, uuid2.time_hi_and_version); UUCMP(uuid1.clock_seq, uuid2.clock_seq); return memcmp(uuid1.node, uuid2.node, 6); } igraph/src/uuid/win32/0000755000175100001440000000000013430770214014242 5ustar hornikusersigraph/src/uuid/win32/config.h0000644000175100001440000000476013431000472015660 0ustar hornikusers/* src/config.h. Generated from config.h.in by configure. */ /* src/config.h.in. Generated from configure.ac by autoheader. */ /* -- reflects MinGW + Win32 -- */ /* Define to 1 if you have the header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `jrand48' function. */ /* #undef HAVE_JRAND48 */ /* Define to 1 if you have the header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the header file. */ /* #undef HAVE_NETINET_IN_H */ /* Define to 1 if you have the header file. */ /* #undef HAVE_NET_IF_DL_H */ /* Define to 1 if you have the header file. */ /* #undef HAVE_NET_IF_H */ /* Define if struct sockaddr contains sa_len */ /* #undef HAVE_SA_LEN */ /* Define to 1 if you have the header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_FILE_H 1 /* Define to 1 if you have the header file. */ /* #undef HAVE_SYS_IOCTL_H */ /* Define to 1 if you have the header file. */ /* #undef HAVE_SYS_SOCKET_H */ /* Define to 1 if you have the header file. */ /* #undef HAVE_SYS_SOCKIO_H */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ /* #undef HAVE_SYS_SYSCALL_H */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_TIME_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ /* #undef HAVE_SYS_UN_H */ /* Define to 1 if you have the header file. */ #define HAVE_UNISTD_H 1 /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "Simon.Urbanek@r-project.org" /* Define to the full name of this package. */ #define PACKAGE_NAME "uuid" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "uuid 0.1" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "uuid" /* Define to the version of this package. */ #define PACKAGE_VERSION "0.1" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 igraph/src/uuid/R.c0000644000175100001440000000061313431000472013636 0ustar hornikusers#include "uuid.h" #include #include "igraph_random.h" SEXP UUID_gen(SEXP sTime) { RNG_BEGIN(); uuid_t u; char c[40]; int use_time = asInteger(sTime); if (use_time == TRUE) uuid_generate_time(u); else if (use_time == FALSE) uuid_generate_random(u); else uuid_generate(u); uuid_unparse_lower(u, c); RNG_END(); return mkString(c); } igraph/src/uuid/copy.c0000644000175100001440000000335713431000472014417 0ustar hornikusers/* * copy.c --- copy UUIDs * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include "uuidP.h" void uuid_copy(uuid_t dst, const uuid_t src) { unsigned char *cp1; const unsigned char *cp2; int i; for (i=0, cp1 = dst, cp2 = src; i < 16; i++) *cp1++ = *cp2++; } igraph/src/uuid/unpack.c0000644000175100001440000000405113431000472014716 0ustar hornikusers/* * Internal routine for unpacking UUID * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include #include "uuidP.h" void uuid_unpack(const uuid_t in, struct uuid *uu) { const uint8_t *ptr = in; uint32_t tmp; tmp = *ptr++; tmp = (tmp << 8) | *ptr++; tmp = (tmp << 8) | *ptr++; tmp = (tmp << 8) | *ptr++; uu->time_low = tmp; tmp = *ptr++; tmp = (tmp << 8) | *ptr++; uu->time_mid = tmp; tmp = *ptr++; tmp = (tmp << 8) | *ptr++; uu->time_hi_and_version = tmp; tmp = *ptr++; tmp = (tmp << 8) | *ptr++; uu->clock_seq = tmp; memcpy(uu->node, ptr, 6); } igraph/src/uuid/pack.c0000644000175100001440000000430413431000472014354 0ustar hornikusers/* * Internal routine for packing UUIDs * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include #include "uuidP.h" void uuid_pack(const struct uuid *uu, uuid_t ptr) { uint32_t tmp; unsigned char *out = ptr; tmp = uu->time_low; out[3] = (unsigned char) tmp; tmp >>= 8; out[2] = (unsigned char) tmp; tmp >>= 8; out[1] = (unsigned char) tmp; tmp >>= 8; out[0] = (unsigned char) tmp; tmp = uu->time_mid; out[5] = (unsigned char) tmp; tmp >>= 8; out[4] = (unsigned char) tmp; tmp = uu->time_hi_and_version; out[7] = (unsigned char) tmp; tmp >>= 8; out[6] = (unsigned char) tmp; tmp = uu->clock_seq; out[9] = (unsigned char) tmp; tmp >>= 8; out[8] = (unsigned char) tmp; memcpy(out+10, uu->node, 6); } igraph/src/uuid/Makevars.win0000644000175100001440000000002513431000472015556 0ustar hornikusersPKG_CPPFLAGS=-Iwin32 igraph/src/uuid/COPYING0000644000175100001440000000274513430770214014343 0ustar hornikusersThis library is free software; you can redistribute it and/or modify it under the terms of the Modified BSD License: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, and the entire permission notice in its entirety, including the disclaimer of warranties. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. igraph/src/uuid/isnull.c0000644000175100001440000000343613431000472014751 0ustar hornikusers/* * isnull.c --- Check whether or not the UUID is null * * Copyright (C) 1996, 1997 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #include "uuidP.h" /* Returns 1 if the uuid is the NULL uuid */ int uuid_is_null(const uuid_t uu) { const unsigned char *cp; int i; for (i=0, cp = uu; i < 16; i++) if (*cp++) return 0; return 1; } igraph/src/uuid/config.h.in0000644000175100001440000000435413430770214015331 0ustar hornikusers/* src/config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `jrand48' function. */ #undef HAVE_JRAND48 /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_NETINET_IN_H /* Define to 1 if you have the header file. */ #undef HAVE_NET_IF_DL_H /* Define to 1 if you have the header file. */ #undef HAVE_NET_IF_H /* Define if struct sockaddr contains sa_len */ #undef HAVE_SA_LEN /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_FILE_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKET_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKIO_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SYSCALL_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_UN_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS igraph/src/uuid/uuid.h0000644000175100001440000000634113431000472014414 0ustar hornikusers/* * Public include file for the UUID library * * Copyright (C) 1996, 1997, 1998 Theodore Ts'o. * * %Begin-Header% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, and the entire permission notice in its entirety, * including the disclaimer of warranties. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * %End-Header% */ #ifndef _UUID_UUID_H #define _UUID_UUID_H #include #ifndef _WIN32 #include #endif #include typedef unsigned char uuid_t[16]; /* UUID Variant definitions */ #define UUID_VARIANT_NCS 0 #define UUID_VARIANT_DCE 1 #define UUID_VARIANT_MICROSOFT 2 #define UUID_VARIANT_OTHER 3 /* UUID Type definitions */ #define UUID_TYPE_DCE_TIME 1 #define UUID_TYPE_DCE_RANDOM 4 /* Allow UUID constants to be defined */ #ifdef __GNUC__ #define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ static const uuid_t name __attribute__ ((unused)) = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} #else #define UUID_DEFINE(name,u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15) \ static const uuid_t name = {u0,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15} #endif #ifdef __cplusplus extern "C" { #endif /* clear.c */ void uuid_clear(uuid_t uu); /* compare.c */ int uuid_compare(const uuid_t uu1, const uuid_t uu2); /* copy.c */ void uuid_copy(uuid_t dst, const uuid_t src); /* gen_uuid.c */ void uuid_generate(uuid_t out); void uuid_generate_random(uuid_t out); void uuid_generate_time(uuid_t out); int uuid_generate_time_safe(uuid_t out); /* isnull.c */ int uuid_is_null(const uuid_t uu); /* parse.c */ int uuid_parse(const char *in, uuid_t uu); /* unparse.c */ void uuid_unparse(const uuid_t uu, char *out); void uuid_unparse_lower(const uuid_t uu, char *out); void uuid_unparse_upper(const uuid_t uu, char *out); /* uuid_time.c */ time_t uuid_time(const uuid_t uu, struct timeval *ret_tv); int uuid_type(const uuid_t uu); int uuid_variant(const uuid_t uu); #ifdef __cplusplus } #endif #endif /* _UUID_UUID_H */ igraph/src/uuid/Makevars.in0000644000175100001440000000005013431000472015365 0ustar hornikusersPKG_CPPFLAGS=@CPPFLAGS@ PKG_LIBS=@LIBS@ igraph/src/igraph_error.c0000644000175100001440000002325613431000472015162 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "igraph_error.h" #include "igraph_types.h" #include #include #include #include static IGRAPH_THREAD_LOCAL igraph_error_handler_t *igraph_i_error_handler=0; static IGRAPH_THREAD_LOCAL char igraph_i_errormsg_buffer[500]; static IGRAPH_THREAD_LOCAL char igraph_i_warningmsg_buffer[500]; static const char *igraph_i_error_strings[]= { /* 0 */ "No error", /* 1 */ "Failed", /* 2 */ "Out of memory", /* 3 */ "Parse error", /* 4 */ "Invalid value", /* 5 */ "Already exists", /* 6 */ "Invalid edge vector", /* 7 */ "Invalid vertex id", /* 8 */ "Non-square matrix", /* 9 */ "Invalid mode", /* 10 */ "File operation error", /* 11 */ "Unfold infinite iterator", /* 12 */ "Unimplemented function call", /* 13 */ "Interrupted", /* 14 */ "Numeric procedure did not converge", /* 15 */ "Matrix-vector product failed", /* 16 */ "N must be positive", /* 17 */ "NEV must be positive", /* 18 */ "NCV must be greater than NEV and less than or equal to N " "(and for the non-symmetric solver NCV-NEV >=2 must also hold)", /* 19 */ "Maximum number of iterations should be positive", /* 20 */ "Invalid WHICH parameter", /* 21 */ "Invalid BMAT parameter", /* 22 */ "WORKL is too small", /* 23 */ "LAPACK error in tridiagonal eigenvalue calculation", /* 24 */ "Starting vector is zero", /* 25 */ "MODE is invalid", /* 26 */ "MODE and BMAT are not compatible", /* 27 */ "ISHIFT must be 0 or 1", /* 28 */ "NEV and WHICH='BE' are incompatible", /* 29 */ "Could not build an Arnoldi factorization", /* 30 */ "No eigenvalues to sufficient accuracy", /* 31 */ "HOWMNY is invalid", /* 32 */ "HOWMNY='S' is not implemented", /* 33 */ "Different number of converged Ritz values", /* 34 */ "Error from calculation of a real Schur form", /* 35 */ "LAPACK (dtrevc) error for calculating eigenvectors", /* 36 */ "Unknown ARPACK error", /* 37 */ "Negative loop detected while calculating shortest paths", /* 38 */ "Internal error, likely a bug in igraph", /* 39 */ "Maximum number of iterations reached", /* 40 */ "No shifts could be applied during a cycle of the " "Implicitly restarted Arnoldi iteration. One possibility " "is to increase the size of NCV relative to NEV", /* 41 */ "The Schur form computed by LAPACK routine dlahqr " "could not be reordered by LAPACK routine dtrsen.", /* 42 */ "Big integer division by zero", /* 43 */ "GLPK Error, GLP_EBOUND", /* 44 */ "GLPK Error, GLP_EROOT", /* 45 */ "GLPK Error, GLP_ENOPFS", /* 46 */ "GLPK Error, GLP_ENODFS", /* 47 */ "GLPK Error, GLP_EFAIL", /* 48 */ "GLPK Error, GLP_EMIPGAP", /* 49 */ "GLPK Error, GLP_ETMLIM", /* 50 */ "GLPK Error, GLP_STOP", /* 51 */ "Internal attribute handler error", /* 52 */ "Unimplemented attribute combination for this type", /* 53 */ "LAPACK call resulted an error", /* 54 */ "Internal DrL error", /* 55 */ "Integer or double overflow", /* 56 */ "Internal GPLK error", /* 57 */ "CPU time exceeded", /* 58 */ "Integer or double underflow" }; const char* igraph_strerror(const int igraph_errno) { return igraph_i_error_strings[igraph_errno]; } int igraph_error(const char *reason, const char *file, int line, int igraph_errno) { if (igraph_i_error_handler) { igraph_i_error_handler(reason, file, line, igraph_errno); #ifndef USING_R } else { igraph_error_handler_abort(reason, file, line, igraph_errno); #endif } return igraph_errno; } int igraph_errorf(const char *reason, const char *file, int line, int igraph_errno, ...) { va_list ap; va_start(ap, igraph_errno); vsnprintf(igraph_i_errormsg_buffer, sizeof(igraph_i_errormsg_buffer) / sizeof(char), reason, ap); return igraph_error(igraph_i_errormsg_buffer, file, line, igraph_errno); } int igraph_errorvf(const char *reason, const char *file, int line, int igraph_errno, va_list ap) { vsnprintf(igraph_i_errormsg_buffer, sizeof(igraph_i_errormsg_buffer) / sizeof(char), reason, ap); return igraph_error(igraph_i_errormsg_buffer, file, line, igraph_errno); } #ifndef USING_R void igraph_error_handler_abort (const char *reason, const char *file, int line, int igraph_errno) { fprintf(stderr, "Error at %s:%i :%s, %s\n", file, line, reason, igraph_strerror(igraph_errno)); abort(); } #endif void igraph_error_handler_ignore (const char *reason, const char *file, int line, int igraph_errno) { IGRAPH_UNUSED(reason); IGRAPH_UNUSED(file); IGRAPH_UNUSED(line); IGRAPH_UNUSED(igraph_errno); IGRAPH_FINALLY_FREE(); } #ifndef USING_R void igraph_error_handler_printignore (const char *reason, const char *file, int line, int igraph_errno) { IGRAPH_FINALLY_FREE(); fprintf(stderr, "Error at %s:%i :%s, %s\n", file, line, reason, igraph_strerror(igraph_errno)); } #endif igraph_error_handler_t * igraph_set_error_handler (igraph_error_handler_t * new_handler) { igraph_error_handler_t * previous_handler = igraph_i_error_handler; igraph_i_error_handler = new_handler; return previous_handler; } IGRAPH_THREAD_LOCAL struct igraph_i_protectedPtr igraph_i_finally_stack[100]; /* * Adds another element to the free list */ void IGRAPH_FINALLY_REAL(void (*func)(void*), void* ptr) { int no=igraph_i_finally_stack[0].all; assert (no<100); assert (no>=0); igraph_i_finally_stack[no].ptr=ptr; igraph_i_finally_stack[no].func=func; igraph_i_finally_stack[0].all ++; /* printf("--> Finally stack contains now %d elements\n", igraph_i_finally_stack[0].all); */ } void IGRAPH_FINALLY_CLEAN(int minus) { igraph_i_finally_stack[0].all -= minus; if (igraph_i_finally_stack[0].all < 0) { /* fprintf(stderr, "corrupt finally stack, popping %d elements when only %d left\n", minus, igraph_i_finally_stack[0].all+minus); */ igraph_i_finally_stack[0].all = 0; } /* printf("<-- Finally stack contains now %d elements\n", igraph_i_finally_stack[0].all); */ } void IGRAPH_FINALLY_FREE(void) { int p; /* printf("[X] Finally stack will be cleaned (contained %d elements)\n", igraph_i_finally_stack[0].all); */ for (p=igraph_i_finally_stack[0].all-1; p>=0; p--) { igraph_i_finally_stack[p].func(igraph_i_finally_stack[p].ptr); } igraph_i_finally_stack[0].all=0; } int IGRAPH_FINALLY_STACK_SIZE(void) { return igraph_i_finally_stack[0].all; } static IGRAPH_THREAD_LOCAL igraph_warning_handler_t *igraph_i_warning_handler=0; /** * \function igraph_warning_handler_ignore * Ignore all warnings * * This warning handler function simply ignores all warnings. * \param reason Textual description of the warning. * \param file The source file in which the warning was noticed. * \param line The number of line in the source file which triggered the * warning.. * \param igraph_errno Warnings could have potentially error codes as well, * but this is currently not used in igraph. */ void igraph_warning_handler_ignore (const char *reason, const char *file, int line, int igraph_errno) { IGRAPH_UNUSED(reason); IGRAPH_UNUSED(file); IGRAPH_UNUSED(line); IGRAPH_UNUSED(igraph_errno); } #ifndef USING_R /** * \function igraph_warning_handler_print * Print all warning to the standard error * * This warning handler function simply prints all warnings to the * standard error. * \param reason Textual description of the warning. * \param file The source file in which the warning was noticed. * \param line The number of line in the source file which triggered the * warning.. * \param igraph_errno Warnings could have potentially error codes as well, * but this is currently not used in igraph. */ void igraph_warning_handler_print (const char *reason, const char *file, int line, int igraph_errno) { IGRAPH_UNUSED(igraph_errno); fprintf(stderr, "Warning: %s in file %s, line %i\n", reason, file, line); } #endif int igraph_warning(const char *reason, const char *file, int line, int igraph_errno) { if (igraph_i_warning_handler) { igraph_i_warning_handler(reason, file, line, igraph_errno); #ifndef USING_R } else { igraph_warning_handler_print(reason, file, line, igraph_errno); #endif } return igraph_errno; } int igraph_warningf(const char *reason, const char *file, int line, int igraph_errno, ...) { va_list ap; va_start(ap, igraph_errno); vsnprintf(igraph_i_warningmsg_buffer, sizeof(igraph_i_warningmsg_buffer) / sizeof(char), reason, ap); return igraph_warning(igraph_i_warningmsg_buffer, file, line, igraph_errno); } igraph_warning_handler_t * igraph_set_warning_handler (igraph_warning_handler_t * new_handler) { igraph_warning_handler_t * previous_handler = igraph_i_warning_handler; igraph_i_warning_handler = new_handler; return previous_handler; } igraph/src/igraph_marked_queue.c0000644000175100001440000000622213431000472016472 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_marked_queue.h" #define BATCH_MARKER -1 int igraph_marked_queue_init(igraph_marked_queue_t *q, long int size) { IGRAPH_CHECK(igraph_dqueue_init(&q->Q, 0)); IGRAPH_FINALLY(igraph_dqueue_destroy, &q->Q); IGRAPH_CHECK(igraph_vector_long_init(&q->set, size)); q->mark=1; q->size=0; IGRAPH_FINALLY_CLEAN(1); return 0; } void igraph_marked_queue_destroy(igraph_marked_queue_t *q) { igraph_vector_long_destroy(&q->set); igraph_dqueue_destroy(&q->Q); } void igraph_marked_queue_reset(igraph_marked_queue_t *q) { igraph_dqueue_clear(&q->Q); q->size = 0; q->mark += 1; if (q->mark==0) { igraph_vector_long_null(&q->set); q->mark += 1; } } igraph_bool_t igraph_marked_queue_empty(const igraph_marked_queue_t *q) { return q->size == 0; } long int igraph_marked_queue_size(const igraph_marked_queue_t *q) { return q->size; } igraph_bool_t igraph_marked_queue_iselement(const igraph_marked_queue_t *q, long int elem) { return (VECTOR(q->set)[elem] == q->mark); } int igraph_marked_queue_push(igraph_marked_queue_t *q, long int elem) { if (VECTOR(q->set)[elem] != q->mark) { IGRAPH_CHECK(igraph_dqueue_push(&q->Q, elem)); VECTOR(q->set)[elem] = q->mark; q->size += 1; } return 0; } int igraph_marked_queue_start_batch(igraph_marked_queue_t *q) { IGRAPH_CHECK(igraph_dqueue_push(&q->Q, BATCH_MARKER)); return 0; } void igraph_marked_queue_pop_back_batch(igraph_marked_queue_t *q) { long int size=igraph_dqueue_size(&q->Q); long int elem; while (size > 0 && (elem=(long int) igraph_dqueue_pop_back(&q->Q)) != BATCH_MARKER) { VECTOR(q->set)[elem]=0; size--; q->size--; } } #ifndef USING_R int igraph_marked_queue_print(const igraph_marked_queue_t *q) { IGRAPH_CHECK(igraph_dqueue_print(&q->Q)); return 0; } #endif int igraph_marked_queue_fprint(const igraph_marked_queue_t *q, FILE *file) { IGRAPH_CHECK(igraph_dqueue_fprint(&q->Q, file)); return 0; } int igraph_marked_queue_as_vector(const igraph_marked_queue_t *q, igraph_vector_t *vec) { long int i, p, n=igraph_dqueue_size(&q->Q); IGRAPH_CHECK(igraph_vector_resize(vec, q->size)); for (i=0, p=0; iQ, i); if (e != BATCH_MARKER) { VECTOR(*vec)[p++]=e; } } return 0; } igraph/src/dsaupd.f0000644000175100001440000006463513431000472013770 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsaupd c c\Description: c c Reverse communication interface for the Implicitly Restarted Arnoldi c Iteration. For symmetric problems this reduces to a variant of the Lanczos c method. This method has been designed to compute approximations to a c few eigenpairs of a linear operator OP that is real and symmetric c with respect to a real positive semi-definite symmetric matrix B, c i.e. c c B*OP = (OP')*B. c c Another way to express this condition is c c < x,OPy > = < OPx,y > where < z,w > = z'Bw . c c In the standard eigenproblem B is the identity matrix. c ( A' denotes transpose of A) c c The computed approximate eigenvalues are called Ritz values and c the corresponding approximate eigenvectors are called Ritz vectors. c c igraphdsaupd is usually called iteratively to solve one of the c following problems: c c Mode 1: A*x = lambda*x, A symmetric c ===> OP = A and B = I. c c Mode 2: A*x = lambda*M*x, A symmetric, M symmetric positive definite c ===> OP = inv[M]*A and B = M. c ===> (If M can be factored see remark 3 below) c c Mode 3: K*x = lambda*M*x, K symmetric, M symmetric positive semi-definite c ===> OP = (inv[K - sigma*M])*M and B = M. c ===> Shift-and-Invert mode c c Mode 4: K*x = lambda*KG*x, K symmetric positive semi-definite, c KG symmetric indefinite c ===> OP = (inv[K - sigma*KG])*K and B = K. c ===> Buckling mode c c Mode 5: A*x = lambda*M*x, A symmetric, M symmetric positive semi-definite c ===> OP = inv[A - sigma*M]*[A + sigma*M] and B = M. c ===> Cayley transformed mode c c NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v c should be accomplished either by a direct method c using a sparse matrix factorization and solving c c [A - sigma*M]*w = v or M*w = v, c c or through an iterative method for solving these c systems. If an iterative method is used, the c convergence test must be more stringent than c the accuracy requirements for the eigenvalue c approximations. c c\Usage: c call igraphdsaupd c ( IDO, BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, c IPNTR, WORKD, WORKL, LWORKL, INFO ) c c\Arguments c IDO Integer. (INPUT/OUTPUT) c Reverse communication flag. IDO must be zero on the first c call to igraphdsaupd. IDO will be set internally to c indicate the type of operation to be performed. Control is c then given back to the calling routine which has the c responsibility to carry out the requested operation and call c igraphdsaupd with the result. The operand is given in c WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)). c (If Mode = 2 see remark 5 below) c ------------------------------------------------------------- c IDO = 0: first call to the reverse communication interface c IDO = -1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c This is for the initialization phase to force the c starting vector into the range of OP. c IDO = 1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c In mode 3,4 and 5, the vector B * X is already c available in WORKD(ipntr(3)). It does not c need to be recomputed in forming OP * X. c IDO = 2: compute Y = B * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c IDO = 3: compute the IPARAM(8) shifts where c IPNTR(11) is the pointer into WORKL for c placing the shifts. See remark 6 below. c IDO = 99: done c ------------------------------------------------------------- c c BMAT Character*1. (INPUT) c BMAT specifies the type of the matrix B that defines the c semi-inner product for the operator OP. c B = 'I' -> standard eigenvalue problem A*x = lambda*x c B = 'G' -> generalized eigenvalue problem A*x = lambda*B*x c c N Integer. (INPUT) c Dimension of the eigenproblem. c c WHICH Character*2. (INPUT) c Specify which of the Ritz values of OP to compute. c c 'LA' - compute the NEV largest (algebraic) eigenvalues. c 'SA' - compute the NEV smallest (algebraic) eigenvalues. c 'LM' - compute the NEV largest (in magnitude) eigenvalues. c 'SM' - compute the NEV smallest (in magnitude) eigenvalues. c 'BE' - compute NEV eigenvalues, half from each end of the c spectrum. When NEV is odd, compute one more from the c high end than from the low end. c (see remark 1 below) c c NEV Integer. (INPUT) c Number of eigenvalues of OP to be computed. 0 < NEV < N. c c TOL Double precision scalar. (INPUT) c Stopping criterion: the relative accuracy of the Ritz value c is considered acceptable if BOUNDS(I) .LE. TOL*ABS(RITZ(I)). c If TOL .LE. 0. is passed a default is set: c DEFAULT = DLAMCH('EPS') (machine precision as computed c by the LAPACK auxiliary subroutine DLAMCH). c c RESID Double precision array of length N. (INPUT/OUTPUT) c On INPUT: c If INFO .EQ. 0, a random initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c On OUTPUT: c RESID contains the final residual vector. c c NCV Integer. (INPUT) c Number of columns of the matrix V (less than or equal to N). c This will indicate how many Lanczos vectors are generated c at each iteration. After the startup phase in which NEV c Lanczos vectors are generated, the algorithm generates c NCV-NEV Lanczos vectors at each subsequent update iteration. c Most of the cost in generating each Lanczos vector is in the c matrix-vector product OP*x. (See remark 4 below). c c V Double precision N by NCV array. (OUTPUT) c The NCV columns of V contain the Lanczos basis vectors. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c IPARAM Integer array of length 11. (INPUT/OUTPUT) c IPARAM(1) = ISHIFT: method for selecting the implicit shifts. c The shifts selected at each iteration are used to restart c the Arnoldi iteration in an implicit fashion. c ------------------------------------------------------------- c ISHIFT = 0: the shifts are provided by the user via c reverse communication. The NCV eigenvalues of c the current tridiagonal matrix T are returned in c the part of WORKL array corresponding to RITZ. c See remark 6 below. c ISHIFT = 1: exact shifts with respect to the reduced c tridiagonal matrix T. This is equivalent to c restarting the iteration with a starting vector c that is a linear combination of Ritz vectors c associated with the "wanted" Ritz values. c ------------------------------------------------------------- c c IPARAM(2) = LEVEC c No longer referenced. See remark 2 below. c c IPARAM(3) = MXITER c On INPUT: maximum number of Arnoldi update iterations allowed. c On OUTPUT: actual number of Arnoldi update iterations taken. c c IPARAM(4) = NB: blocksize to be used in the recurrence. c The code currently works only for NB = 1. c c IPARAM(5) = NCONV: number of "converged" Ritz values. c This represents the number of Ritz values that satisfy c the convergence criterion. c c IPARAM(6) = IUPD c No longer referenced. Implicit restarting is ALWAYS used. c c IPARAM(7) = MODE c On INPUT determines what type of eigenproblem is being solved. c Must be 1,2,3,4,5; See under \Description of igraphdsaupd for the c five modes available. c c IPARAM(8) = NP c When ido = 3 and the user provides shifts through reverse c communication (IPARAM(1)=0), igraphdsaupd returns NP, the number c of shifts the user is to provide. 0 < NP <=NCV-NEV. See Remark c 6 below. c c IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, c OUTPUT: NUMOP = total number of OP*x operations, c NUMOPB = total number of B*x operations if BMAT='G', c NUMREO = total number of steps of re-orthogonalization. c c IPNTR Integer array of length 11. (OUTPUT) c Pointer to mark the starting locations in the WORKD and WORKL c arrays for matrices/vectors used by the Lanczos iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X in WORKD. c IPNTR(2): pointer to the current result vector Y in WORKD. c IPNTR(3): pointer to the vector B * X in WORKD when used in c the shift-and-invert mode. c IPNTR(4): pointer to the next available location in WORKL c that is untouched by the program. c IPNTR(5): pointer to the NCV by 2 tridiagonal matrix T in WORKL. c IPNTR(6): pointer to the NCV RITZ values array in WORKL. c IPNTR(7): pointer to the Ritz estimates in array WORKL associated c with the Ritz values located in RITZ in WORKL. c IPNTR(11): pointer to the NP shifts in WORKL. See Remark 6 below. c c Note: IPNTR(8:10) is only referenced by igraphdseupd. See Remark 2. c IPNTR(8): pointer to the NCV RITZ values of the original system. c IPNTR(9): pointer to the NCV corresponding error bounds. c IPNTR(10): pointer to the NCV by NCV matrix of eigenvectors c of the tridiagonal matrix T. Only referenced by c igraphdseupd if RVEC = .TRUE. See Remarks. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The user should not use WORKD c as temporary workspace during the iteration. Upon termination c WORKD(1:N) contains B*RESID(1:N). If the Ritz vectors are desired c subroutine igraphdseupd uses this output. c See Data Distribution Note below. c c WORKL Double precision work array of length LWORKL. (OUTPUT/WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. See Data Distribution Note below. c c LWORKL Integer. (INPUT) c LWORKL must be at least NCV**2 + 8*NCV . c c INFO Integer. (INPUT/OUTPUT) c If INFO .EQ. 0, a randomly initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c Error flag on output. c = 0: Normal exit. c = 1: Maximum number of iterations taken. c All possible eigenvalues of OP has been found. IPARAM(5) c returns the number of wanted converged Ritz values. c = 2: No longer an informational error. Deprecated starting c with release 2 of ARPACK. c = 3: No shifts could be applied during a cycle of the c Implicitly restarted Arnoldi iteration. One possibility c is to increase the size of NCV relative to NEV. c See remark 4 below. c = -1: N must be positive. c = -2: NEV must be positive. c = -3: NCV must be greater than NEV and less than or equal to N. c = -4: The maximum number of Arnoldi update iterations allowed c must be greater than zero. c = -5: WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'. c = -6: BMAT must be one of 'I' or 'G'. c = -7: Length of private work array WORKL is not sufficient. c = -8: Error return from trid. eigenvalue calculation; c Informatinal error from LAPACK routine dsteqr. c = -9: Starting vector is zero. c = -10: IPARAM(7) must be 1,2,3,4,5. c = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable. c = -12: IPARAM(1) must be equal to 0 or 1. c = -13: NEV and WHICH = 'BE' are incompatable. c = -9999: Could not build an Arnoldi factorization. c IPARAM(5) returns the size of the current Arnoldi c factorization. The user is advised to check that c enough workspace and array storage has been allocated. c c c\Remarks c 1. The converged Ritz values are always returned in ascending c algebraic order. The computed Ritz values are approximate c eigenvalues of OP. The selection of WHICH should be made c with this in mind when Mode = 3,4,5. After convergence, c approximate eigenvalues of the original problem may be obtained c with the ARPACK subroutine igraphdseupd. c c 2. If the Ritz vectors corresponding to the converged Ritz values c are needed, the user must call igraphdseupd immediately following completion c of igraphdsaupd. This is new starting with version 2.1 of ARPACK. c c 3. If M can be factored into a Cholesky factorization M = LL' c then Mode = 2 should not be selected. Instead one should use c Mode = 1 with OP = inv(L)*A*inv(L'). Appropriate triangular c linear systems should be solved with L and L' rather c than computing inverses. After convergence, an approximate c eigenvector z of the original problem is recovered by solving c L'z = x where x is a Ritz vector of OP. c c 4. At present there is no a-priori analysis to guide the selection c of NCV relative to NEV. The only formal requrement is that NCV > NEV. c However, it is recommended that NCV .ge. 2*NEV. If many problems of c the same type are to be solved, one should experiment with increasing c NCV while keeping NEV fixed for a given test problem. This will c usually decrease the required number of OP*x operations but it c also increases the work and storage required to maintain the orthogonal c basis vectors. The optimal "cross-over" with respect to CPU time c is problem dependent and must be determined empirically. c c 5. If IPARAM(7) = 2 then in the Reverse commuication interface the user c must do the following. When IDO = 1, Y = OP * X is to be computed. c When IPARAM(7) = 2 OP = inv(B)*A. After computing A*X the user c must overwrite X with A*X. Y is then the solution to the linear set c of equations B*Y = A*X. c c 6. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the c NP = IPARAM(8) shifts in locations: c 1 WORKL(IPNTR(11)) c 2 WORKL(IPNTR(11)+1) c . c . c . c NP WORKL(IPNTR(11)+NP-1). c c The eigenvalues of the current tridiagonal matrix are located in c WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1). They are in the c order defined by WHICH. The associated Ritz estimates are located in c WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1). c c----------------------------------------------------------------------- c c\Data Distribution Note: c c Fortran-D syntax: c ================ c REAL RESID(N), V(LDV,NCV), WORKD(3*N), WORKL(LWORKL) c DECOMPOSE D1(N), D2(N,NCV) c ALIGN RESID(I) with D1(I) c ALIGN V(I,J) with D2(I,J) c ALIGN WORKD(I) with D1(I) range (1:N) c ALIGN WORKD(I) with D1(I-N) range (N+1:2*N) c ALIGN WORKD(I) with D1(I-2*N) range (2*N+1:3*N) c DISTRIBUTE D1(BLOCK), D2(BLOCK,:) c REPLICATED WORKL(LWORKL) c c Cray MPP syntax: c =============== c REAL RESID(N), V(LDV,NCV), WORKD(N,3), WORKL(LWORKL) c SHARED RESID(BLOCK), V(BLOCK,:), WORKD(BLOCK,:) c REPLICATED WORKL(LWORKL) c c c\BeginLib c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett, "The Symmetric Eigenvalue Problem". Prentice-Hall, c 1980. c 4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", c Computer Physics Communications, 53 (1989), pp 169-179. c 5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to c Implement the Spectral Transformation", Math. Comp., 48 (1987), c pp 663-673. c 6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos c Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", c SIAM J. Matr. Anal. Apps., January (1993). c 7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines c for Updating the QR decomposition", ACM TOMS, December 1990, c Volume 16 Number 4, pp 369-377. c 8. R.B. Lehoucq, D.C. Sorensen, "Implementation of Some Spectral c Transformations in a k-Step Arnoldi Method". In Preparation. c c\Routines called: c igraphdsaup2 ARPACK routine that implements the Implicitly Restarted c Arnoldi Iteration. c igraphdstats ARPACK routine that initialize timing and other statistics c variables. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c c\Authors c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/15/93: Version ' 2.4' c c\SCCS Information: @(#) c FILE: saupd.F SID: 2.7 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c 1. None c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsaupd & ( ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, & ipntr, workd, workl, lworkl, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1, which*2 integer ido, info, ldv, lworkl, n, ncv, nev Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% c integer iparam(11), ipntr(11) Double precision & resid(n), v(ldv,ncv), workd(3*n), workl(lworkl) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c integer bounds, ierr, ih, iq, ishift, iupd, iw, & ldh, ldq, msglvl, mxiter, mode, nb, & nev0, next, np, ritz, j save bounds, ierr, ih, iq, ishift, iupd, iw, & ldh, ldq, msglvl, mxiter, mode, nb, & nev0, next, np, ritz c c %----------------------% c | External Subroutines | c %----------------------% c external igraphdsaup2, igraphdvout, igraphivout, & igraphsecond, igraphdstats c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlamch external dlamch c c %-----------------------% c | Executable Statements | c %-----------------------% c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphdstats call igraphsecond (t0) msglvl = msaupd c ierr = 0 ishift = iparam(1) mxiter = iparam(3) nb = iparam(4) c c %--------------------------------------------% c | Revision 2 performs only implicit restart. | c %--------------------------------------------% c iupd = 1 mode = iparam(7) c c %----------------% c | Error checking | c %----------------% c if (n .le. 0) then ierr = -1 else if (nev .le. 0) then ierr = -2 else if (ncv .le. nev .or. ncv .gt. n) then ierr = -3 end if c c %----------------------------------------------% c | NP is the number of additional steps to | c | extend the length NEV Lanczos factorization. | c %----------------------------------------------% c np = ncv - nev c if (mxiter .le. 0) ierr = -4 if (which .ne. 'LM' .and. & which .ne. 'SM' .and. & which .ne. 'LA' .and. & which .ne. 'SA' .and. & which .ne. 'BE') ierr = -5 if (bmat .ne. 'I' .and. bmat .ne. 'G') ierr = -6 c if (lworkl .lt. ncv**2 + 8*ncv) ierr = -7 if (mode .lt. 1 .or. mode .gt. 5) then ierr = -10 else if (mode .eq. 1 .and. bmat .eq. 'G') then ierr = -11 else if (ishift .lt. 0 .or. ishift .gt. 1) then ierr = -12 else if (nev .eq. 1 .and. which .eq. 'BE') then ierr = -13 end if c c %------------% c | Error Exit | c %------------% c if (ierr .ne. 0) then info = ierr ido = 99 go to 9000 end if c c %------------------------% c | Set default parameters | c %------------------------% c if (nb .le. 0) nb = 1 if (tol .le. zero) tol = dlamch('EpsMach') c c %----------------------------------------------% c | NP is the number of additional steps to | c | extend the length NEV Lanczos factorization. | c | NEV0 is the local variable designating the | c | size of the invariant subspace desired. | c %----------------------------------------------% c np = ncv - nev nev0 = nev c c %-----------------------------% c | Zero out internal workspace | c %-----------------------------% c do 10 j = 1, ncv**2 + 8*ncv workl(j) = zero 10 continue c c %-------------------------------------------------------% c | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | c | etc... and the remaining workspace. | c | Also update pointer to be used on output. | c | Memory is laid out as follows: | c | workl(1:2*ncv) := generated tridiagonal matrix | c | workl(2*ncv+1:2*ncv+ncv) := ritz values | c | workl(3*ncv+1:3*ncv+ncv) := computed error bounds | c | workl(4*ncv+1:4*ncv+ncv*ncv) := rotation matrix Q | c | workl(4*ncv+ncv*ncv+1:7*ncv+ncv*ncv) := workspace | c %-------------------------------------------------------% c ldh = ncv ldq = ncv ih = 1 ritz = ih + 2*ldh bounds = ritz + ncv iq = bounds + ncv iw = iq + ncv**2 next = iw + 3*ncv c ipntr(4) = next ipntr(5) = ih ipntr(6) = ritz ipntr(7) = bounds ipntr(11) = iw end if c c %-------------------------------------------------------% c | Carry out the Implicitly restarted Lanczos Iteration. | c %-------------------------------------------------------% c call igraphdsaup2 & ( ido, bmat, n, which, nev0, np, tol, resid, mode, iupd, & ishift, mxiter, v, ldv, workl(ih), ldh, workl(ritz), & workl(bounds), workl(iq), ldq, workl(iw), ipntr, workd, & info ) c c %--------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP or shifts. | c %--------------------------------------------------% c if (ido .eq. 3) iparam(8) = np if (ido .ne. 99) go to 9000 c iparam(3) = mxiter iparam(5) = np iparam(9) = nopx iparam(10) = nbx iparam(11) = nrorth c c %------------------------------------% c | Exit if there was an informational | c | error within igraphdsaup2. | c %------------------------------------% c if (info .lt. 0) go to 9000 if (info .eq. 2) info = 3 c if (msglvl .gt. 0) then call igraphivout (logfil, 1, mxiter, ndigit, & '_saupd: number of update iterations taken') call igraphivout (logfil, 1, np, ndigit, & '_saupd: number of "converged" Ritz values') call igraphdvout (logfil, np, workl(Ritz), ndigit, & '_saupd: final Ritz values') call igraphdvout (logfil, np, workl(Bounds), ndigit, & '_saupd: corresponding error bounds') end if c call igraphsecond (t1) tsaupd = t1 - t0 c c 9000 continue c return c c %---------------% c | End of igraphdsaupd | c %---------------% c end igraph/src/dngets.f0000644000175100001440000001772713431000472013774 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdngets c c\Description: c Given the eigenvalues of the upper Hessenberg matrix H, c computes the NP shifts AMU that are zeros of the polynomial of c degree NP which filters out components of the unwanted eigenvectors c corresponding to the AMU's based on some given criteria. c c NOTE: call this even in the case of user specified shifts in order c to sort the eigenvalues, and error bounds of H for later use. c c\Usage: c call igraphdngets c ( ISHIFT, WHICH, KEV, NP, RITZR, RITZI, BOUNDS, SHIFTR, SHIFTI ) c c\Arguments c ISHIFT Integer. (INPUT) c Method for selecting the implicit shifts at each iteration. c ISHIFT = 0: user specified shifts c ISHIFT = 1: exact shift with respect to the matrix H. c c WHICH Character*2. (INPUT) c Shift selection criteria. c 'LM' -> want the KEV eigenvalues of largest magnitude. c 'SM' -> want the KEV eigenvalues of smallest magnitude. c 'LR' -> want the KEV eigenvalues of largest real part. c 'SR' -> want the KEV eigenvalues of smallest real part. c 'LI' -> want the KEV eigenvalues of largest imaginary part. c 'SI' -> want the KEV eigenvalues of smallest imaginary part. c c KEV Integer. (INPUT/OUTPUT) c INPUT: KEV+NP is the size of the matrix H. c OUTPUT: Possibly increases KEV by one to keep complex conjugate c pairs together. c c NP Integer. (INPUT/OUTPUT) c Number of implicit shifts to be computed. c OUTPUT: Possibly decreases NP by one to keep complex conjugate c pairs together. c c RITZR, Double precision array of length KEV+NP. (INPUT/OUTPUT) c RITZI On INPUT, RITZR and RITZI contain the real and imaginary c parts of the eigenvalues of H. c On OUTPUT, RITZR and RITZI are sorted so that the unwanted c eigenvalues are in the first NP locations and the wanted c portion is in the last KEV locations. When exact shifts are c selected, the unwanted part corresponds to the shifts to c be applied. Also, if ISHIFT .eq. 1, the unwanted eigenvalues c are further sorted so that the ones with largest Ritz values c are first. c c BOUNDS Double precision array of length KEV+NP. (INPUT/OUTPUT) c Error bounds corresponding to the ordering in RITZ. c c SHIFTR, SHIFTI *** USE deprecated as of version 2.1. *** c c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c igraphdsortc ARPACK sorting routine. c dcopy Level 1 BLAS that copies one vector to another . c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.1' c c\SCCS Information: @(#) c FILE: ngets.F SID: 2.3 DATE OF SID: 4/20/96 RELEASE: 2 c c\Remarks c 1. xxxx c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdngets ( ishift, which, kev, np, ritzr, ritzi, & bounds, shiftr, shifti ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character*2 which integer ishift, kev, np c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & bounds(kev+np), ritzr(kev+np), ritzi(kev+np), & shiftr(1), shifti(1) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0, zero = 0.0) c c %---------------% c | Local Scalars | c %---------------% c integer msglvl c c %----------------------% c | External Subroutines | c %----------------------% c external dcopy, igraphdsortc, igraphsecond c c %----------------------% c | Intrinsics Functions | c %----------------------% c intrinsic abs c c %-----------------------% c | Executable Statements | c %-----------------------% c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = mngets c c %----------------------------------------------------% c | LM, SM, LR, SR, LI, SI case. | c | Sort the eigenvalues of H into the desired order | c | and apply the resulting order to BOUNDS. | c | The eigenvalues are sorted so that the wanted part | c | are always in the last KEV locations. | c | We first do a pre-processing sort in order to keep | c | complex conjugate pairs together | c %----------------------------------------------------% c if (which .eq. 'LM') then call igraphdsortc ('LR', .true., kev+np, ritzr, ritzi, bounds) else if (which .eq. 'SM') then call igraphdsortc ('SR', .true., kev+np, ritzr, ritzi, bounds) else if (which .eq. 'LR') then call igraphdsortc ('LM', .true., kev+np, ritzr, ritzi, bounds) else if (which .eq. 'SR') then call igraphdsortc ('SM', .true., kev+np, ritzr, ritzi, bounds) else if (which .eq. 'LI') then call igraphdsortc ('LM', .true., kev+np, ritzr, ritzi, bounds) else if (which .eq. 'SI') then call igraphdsortc ('SM', .true., kev+np, ritzr, ritzi, bounds) end if c call igraphdsortc (which, .true., kev+np, ritzr, ritzi, bounds) c c %-------------------------------------------------------% c | Increase KEV by one if the ( ritzr(np),ritzi(np) ) | c | = ( ritzr(np+1),-ritzi(np+1) ) and ritz(np) .ne. zero | c | Accordingly decrease NP by one. In other words keep | c | complex conjugate pairs together. | c %-------------------------------------------------------% c if ( ( ritzr(np+1) - ritzr(np) ) .eq. zero & .and. ( ritzi(np+1) + ritzi(np) ) .eq. zero ) then np = np - 1 kev = kev + 1 end if c if ( ishift .eq. 1 ) then c c %-------------------------------------------------------% c | Sort the unwanted Ritz values used as shifts so that | c | the ones with largest Ritz estimates are first | c | This will tend to minimize the effects of the | c | forward instability of the iteration when they shifts | c | are applied in subroutine igraphdnapps. | c | Be careful and use 'SR' since we want to sort BOUNDS! | c %-------------------------------------------------------% c call igraphdsortc ( 'SR', .true., np, bounds, ritzr, ritzi ) end if c call igraphsecond (t1) tngets = tngets + (t1 - t0) c if (msglvl .gt. 0) then call igraphivout (logfil, 1, kev, ndigit, '_ngets: KEV is') call igraphivout (logfil, 1, np, ndigit, '_ngets: NP is') call igraphdvout (logfil, kev+np, ritzr, ndigit, & '_ngets: Eigenvalues of current H matrix -- real part') call igraphdvout (logfil, kev+np, ritzi, ndigit, & '_ngets: Eigenvalues of current H matrix -- imag part') call igraphdvout (logfil, kev+np, bounds, ndigit, & '_ngets: Ritz estimates of the current KEV+NP Ritz values') end if c return c c %---------------% c | End of igraphdngets | c %---------------% c end igraph/src/array.c0000644000175100001440000000261413431000472013610 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_array.h" #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "array.pmt" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "array.pmt" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "array.pmt" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "array.pmt" #include "igraph_pmt_off.h" #undef BASE_BOOL igraph/src/qsort.c0000644000175100001440000001332013431000472013636 0ustar hornikusers/*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef _MSC_VER /* MSVC does not have inline when compiling C source files */ #define inline __inline #define __unused #endif #ifndef __unused #define __unused __attribute__ ((unused)) #endif #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)qsort.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ /*#include */ #include #ifdef I_AM_QSORT_R typedef int cmp_t(void *, const void *, const void *); #else typedef int cmp_t(const void *, const void *); #endif static inline char *med3(char *, char *, char *, cmp_t *, void *); static inline void swapfunc(char *, char *, int, int); #define igraph_min(a, b) (a) < (b) ? a : b /* * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function". */ #define swapcode(TYPE, parmi, parmj, n) { \ long i = (n) / sizeof (TYPE); \ TYPE *pi = (TYPE *) (parmi); \ TYPE *pj = (TYPE *) (parmj); \ do { \ TYPE t = *pi; \ *pi++ = *pj; \ *pj++ = t; \ } while (--i > 0); \ } #define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \ es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1; static inline void swapfunc(a, b, n, swaptype) char *a, *b; int n, swaptype; { if(swaptype <= 1) swapcode(long, a, b, n) else swapcode(char, a, b, n) } #define swap(a, b) \ if (swaptype == 0) { \ long t = *(long *)(a); \ *(long *)(a) = *(long *)(b); \ *(long *)(b) = t; \ } else \ swapfunc(a, b, es, swaptype) #define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype) #ifdef I_AM_QSORT_R #define CMP(t, x, y) (cmp((t), (x), (y))) #else #define CMP(t, x, y) (cmp((x), (y))) #endif static inline char * med3(char *a, char *b, char *c, cmp_t *cmp, void *thunk #ifndef I_AM_QSORT_R __unused #endif ) { return CMP(thunk, a, b) < 0 ? (CMP(thunk, b, c) < 0 ? b : (CMP(thunk, a, c) < 0 ? c : a )) :(CMP(thunk, b, c) > 0 ? b : (CMP(thunk, a, c) < 0 ? a : c )); } #ifdef I_AM_QSORT_R void igraph_qsort_r(void *a, size_t n, size_t es, void *thunk, cmp_t *cmp) #else #define thunk NULL void igraph_qsort(void *a, size_t n, size_t es, cmp_t *cmp) #endif { char *pa, *pb, *pc, *pd, *pl, *pm, *pn; int d, r, swaptype, swap_cnt; loop: SWAPINIT(a, es); swap_cnt = 0; if (n < 7) { for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) for (pl = pm; pl > (char *)a && CMP(thunk, pl - es, pl) > 0; pl -= es) swap(pl, pl - es); return; } pm = (char *)a + (n / 2) * es; if (n > 7) { pl = a; pn = (char *)a + (n - 1) * es; if (n > 40) { d = (n / 8) * es; pl = med3(pl, pl + d, pl + 2 * d, cmp, thunk); pm = med3(pm - d, pm, pm + d, cmp, thunk); pn = med3(pn - 2 * d, pn - d, pn, cmp, thunk); } pm = med3(pl, pm, pn, cmp, thunk); } swap(a, pm); pa = pb = (char *)a + es; pc = pd = (char *)a + (n - 1) * es; for (;;) { while (pb <= pc && (r = CMP(thunk, pb, a)) <= 0) { if (r == 0) { swap_cnt = 1; swap(pa, pb); pa += es; } pb += es; } while (pb <= pc && (r = CMP(thunk, pc, a)) >= 0) { if (r == 0) { swap_cnt = 1; swap(pc, pd); pd -= es; } pc -= es; } if (pb > pc) break; swap(pb, pc); swap_cnt = 1; pb += es; pc -= es; } if (swap_cnt == 0) { /* Switch to insertion sort */ for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) for (pl = pm; pl > (char *)a && CMP(thunk, pl - es, pl) > 0; pl -= es) swap(pl, pl - es); return; } pn = (char *)a + n * es; r = igraph_min(pa - (char *)a, pb - pa); vecswap(a, pb - r, r); r = igraph_min((size_t)(pd - pc), (size_t)(pn - pd - es)); vecswap(pb, pn - r, r); if ((size_t)(r = pb - pa) > es) #ifdef I_AM_QSORT_R igraph_qsort_r(a, r / es, es, thunk, cmp); #else igraph_qsort(a, r / es, es, cmp); #endif if ((size_t)(r = pd - pc) > es) { /* Iterate rather than recurse to save stack space */ a = pn - r; n = r / es; goto loop; } /* qsort(pn - r, r / es, es, cmp);*/ } igraph/src/drl_Node_3d.h0000644000175100001440000000441713431000472014616 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __NODE_H__ #define __NODE_H__ // The node class contains information about a given node for // use by the density server process. // structure coord used to pass position information between // density server and graph class namespace drl3d { class Node { public: bool fixed; // if true do not change the // position of this node int id; float x,y,z; float sub_x,sub_y,sub_z; float energy; public: Node( int node_id ) { x = y = z = 0.0; fixed = false; id = node_id; } ~Node() { } }; } // namespace drl3d #endif //__NODE_H__ igraph/src/gengraph_mr-connected.cpp0000644000175100001440000001420713431000472017264 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "gengraph_header.h" #include "gengraph_graph_molloy_optimized.h" #include "gengraph_graph_molloy_hash.h" #include "gengraph_degree_sequence.h" #include "gengraph_random.h" #include "igraph_datatype.h" #include "igraph_types.h" #include "igraph_error.h" namespace gengraph { // return negative number if program should exit int parse_options(int &argc, char** &argv); // options static const bool MONITOR_TIME = false; static const int SHUFFLE_TYPE = FINAL_HEURISTICS; static const bool RAW_DEGREES = false; static const FILE *Fdeg = stdin; //_________________________________________________________________________ // int main(int argc, char** argv) { // // options // SET_VERBOSE(VERBOSE_NONE); // if(parse_options(argc, argv) < 0) return -1; // //Read degree distribution // degree_sequence dd(Fdeg, !RAW_DEGREES); // //Allocate memory // if(VERBOSE()) fprintf(stderr,"Allocate memory for graph..."); // graph_molloy_opt g(dd); // dd.~degree_sequence(); // //Realize degree sequence // if(VERBOSE()) fprintf(stderr,"done\nRealize degree sequence..."); // bool FAILED = !g.havelhakimi(); // if(VERBOSE()) fprintf(stderr," %s\n", FAILED ? "Failed" : "Success"); // if(FAILED) return 2; // //Merge connected components together // if(VERBOSE()) fprintf(stderr,"Connecting..."); // FAILED = !g.make_connected(); // if(VERBOSE()) fprintf(stderr," %s\n", FAILED ? "Failed" : "Success"); // if(FAILED) return 3; // //Convert graph_molloy_opt to graph_molloy_hash // if(VERBOSE()) fprintf(stderr,"Convert adjacency lists into hash tables..."); // int *hc = g.hard_copy(); // g.~graph_molloy_opt(); // graph_molloy_hash gh(hc); // delete[] hc; // if(VERBOSE()) fprintf(stderr,"Done\n"); // //Shuffle // gh.shuffle(5*gh.nbarcs(), SHUFFLE_TYPE); // //Output // gh.print(); // if(MONITOR_TIME) { // double t = double(clock()) / double(CLOCKS_PER_SEC); // fprintf(stderr,"Time used: %f\n", t); // } // return 0; // } //_________________________________________________________________________ // int parse_options(int &argc, char** &argv) { // bool HELP = false; // int argc0 = argc; // argc = 1; // for(int a=1; a %s returns a graph in its standard output\n",argv[0]); // fprintf(stderr," If no file is given, %s reads its standard input\n",argv[0]); // fprintf(stderr," [-v] and [-vv] options causes extra verbose.\n"); // fprintf(stderr," [-g] option uses the Gkantsidis heuristics.\n"); // fprintf(stderr," [-b] option uses the Brute Force heuristics.\n"); // fprintf(stderr," [-f] option uses the Modified Gkantsidis heuristics.\n"); // fprintf(stderr," [-o] option uses the Optimal Gkantsidis heuristics.\n"); // fprintf(stderr," [-t] option monitors computation time\n"); // fprintf(stderr," [-s] does a srandom(0) to get a constant random graph\n"); // fprintf(stderr," [-raw] is to take raw degree sequences as input\n"); // return -1; // } // return 0; // } } // namespace gengraph using namespace gengraph; extern "C" { int igraph_degree_sequence_game_vl(igraph_t *graph, const igraph_vector_t *out_seq, const igraph_vector_t *in_seq) { long int sum=igraph_vector_sum(out_seq); if (sum % 2 != 0) { IGRAPH_ERROR("Sum of degrees should be even", IGRAPH_EINVAL); } RNG_BEGIN(); if (in_seq && igraph_vector_size(in_seq) != 0) { RNG_END(); IGRAPH_ERROR("This generator works with undirected graphs only", IGRAPH_EINVAL); } degree_sequence *dd = new degree_sequence(out_seq); graph_molloy_opt *g = new graph_molloy_opt(*dd); delete dd; if (!g->havelhakimi()) { delete g; RNG_END(); IGRAPH_ERROR("Cannot realize the given degree sequence as an undirected, simple graph", IGRAPH_EINVAL); } if (!g->make_connected()) { delete g; RNG_END(); IGRAPH_ERROR("Cannot make a connected graph from the given degree sequence", IGRAPH_EINVAL); } int *hc = g->hard_copy(); delete g; graph_molloy_hash *gh = new graph_molloy_hash(hc); delete [] hc; gh->shuffle(5*gh->nbarcs(), 100*gh->nbarcs(), SHUFFLE_TYPE); IGRAPH_CHECK(gh->print(graph)); delete gh; RNG_END(); return 0; } } igraph/src/maximal_cliques.c0000644000175100001440000003072713431000472015655 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_cliques.h" #include "igraph_constants.h" #include "igraph_interface.h" #include "igraph_community.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_memory.h" #include "igraph_progress.h" #include "igraph_math.h" #define CONCAT2x(a,b) a ## b #define CONCAT2(a,b) CONCAT2x(a,b) #define FUNCTION(name,sfx) CONCAT2(name,sfx) int igraph_i_maximal_cliques_reorder_adjlists( const igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, const igraph_vector_int_t *pos, igraph_adjlist_t *adjlist); int igraph_i_maximal_cliques_select_pivot(const igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, const igraph_vector_int_t *pos, const igraph_adjlist_t *adjlist, int *pivot, igraph_vector_int_t *nextv, int oldPS, int oldXE); int igraph_i_maximal_cliques_down(igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, int mynextv, igraph_vector_int_t *R, int *newPS, int *newXE); int igraph_i_maximal_cliques_PX(igraph_vector_int_t *PX, int PS, int *PE, int *XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, int v, igraph_vector_int_t *H); int igraph_i_maximal_cliques_up(igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, igraph_vector_int_t *R, igraph_vector_int_t *H); #define PRINT_PX do { \ int j; \ printf("PX="); \ for (j=0; j= sPS && avneipos <= sPE) { if (pp != avnei) { int tmp=*avnei; *avnei = *pp; *pp = tmp; } pp++; } } } return 0; } int igraph_i_maximal_cliques_select_pivot(const igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, const igraph_vector_int_t *pos, const igraph_adjlist_t *adjlist, int *pivot, igraph_vector_int_t *nextv, int oldPS, int oldXE) { igraph_vector_int_t *pivotvectneis; int i, pivotvectlen, j, usize=-1; int soldPS=oldPS+1, soldXE=oldXE+1, sPS=PS+1, sPE=PE+1; /* Choose a pivotvect, and bring up P vertices at the same time */ for (i=PS; i<=XE; i++) { int av=VECTOR(*PX)[i]; igraph_vector_int_t *avneis=igraph_adjlist_get(adjlist, av); int *avp=VECTOR(*avneis); int avlen=igraph_vector_int_size(avneis); int *ave=avp+avlen; int *avnei=avp, *pp=avp; for (; avnei < ave; avnei++) { int avneipos=VECTOR(*pos)[(int)(*avnei)]; if (avneipos < soldPS || avneipos > soldXE) { break; } if (avneipos >= sPS && avneipos <= sPE) { if (pp != avnei) { int tmp=*avnei; *avnei = *pp; *pp = tmp; } pp++; } } if ((j=pp-avp) > usize) { *pivot = av; usize=j; } } igraph_vector_int_push_back(nextv, -1); pivotvectneis=igraph_adjlist_get(adjlist, *pivot); pivotvectlen=igraph_vector_int_size(pivotvectneis); for (j=PS; j <= PE; j++) { int vcand=VECTOR(*PX)[j]; igraph_bool_t nei=0; int k=0; for (k=0; k < pivotvectlen; k++) { int unv=VECTOR(*pivotvectneis)[k]; int unvpos=VECTOR(*pos)[unv]; if (unvpos < sPS || unvpos > sPE) { break; } if (unv == vcand) { nei=1; break; } } if (!nei) { igraph_vector_int_push_back(nextv, vcand); } } return 0; } #define SWAP(p1,p2) do { \ int v1=VECTOR(*PX)[p1]; \ int v2=VECTOR(*PX)[p2]; \ VECTOR(*PX)[p1] = v2; \ VECTOR(*PX)[p2] = v1; \ VECTOR(*pos)[v1] = (p2)+1; \ VECTOR(*pos)[v2] = (p1)+1; \ } while (0) int igraph_i_maximal_cliques_down(igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, int mynextv, igraph_vector_int_t *R, int *newPS, int *newXE) { igraph_vector_int_t *vneis=igraph_adjlist_get(adjlist, mynextv); int j, vneislen=igraph_vector_int_size(vneis); int sPS=PS+1, sPE=PE+1, sXS=XS+1, sXE=XE+1; *newPS=PE+1; *newXE=XS-1; for (j=0; j= sPS && vneipos <= sPE) { (*newPS)--; SWAP(vneipos-1, *newPS); } else if (vneipos >= sXS && vneipos <= sXE) { (*newXE)++; SWAP(vneipos-1, *newXE); } } igraph_vector_int_push_back(R, mynextv); return 0; } #undef SWAP int igraph_i_maximal_cliques_PX(igraph_vector_int_t *PX, int PS, int *PE, int *XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, int v, igraph_vector_int_t *H) { int vpos=VECTOR(*pos)[v]-1; int tmp=VECTOR(*PX)[*PE]; VECTOR(*PX)[vpos]=tmp; VECTOR(*PX)[*PE]=v; VECTOR(*pos)[v]=(*PE)+1; VECTOR(*pos)[tmp]=vpos+1; (*PE)--; (*XS)--; igraph_vector_int_push_back(H, v); return 0; } int igraph_i_maximal_cliques_up(igraph_vector_int_t *PX, int PS, int PE, int XS, int XE, igraph_vector_int_t *pos, igraph_adjlist_t *adjlist, igraph_vector_int_t *R, igraph_vector_int_t *H) { int vv; igraph_vector_int_pop_back(R); while ((vv=igraph_vector_int_pop_back(H)) != -1) { int vvpos=VECTOR(*pos)[vv]; int tmp=VECTOR(*PX)[XS]; VECTOR(*PX)[XS]=vv; VECTOR(*PX)[vvpos-1]=tmp; VECTOR(*pos)[vv]=XS+1; VECTOR(*pos)[tmp]=vvpos; PE++; XS++; } return 0; } /** * \function igraph_maximal_cliques * \brief Find all maximal cliques of a graph * * * A maximal clique is a clique which can't be extended any more by * adding a new vertex to it. * * * If you are only interested in the size of the largest clique in the * graph, use \ref igraph_clique_number() instead. * * * The current implementation uses a modified Bron-Kerbosch * algorithm to find the maximal cliques, see: David Eppstein, * Maarten Löffler, Darren Strash: Listing All Maximal Cliques in * Sparse Graphs in Near-Optimal Time. Algorithms and Computation, * Lecture Notes in Computer Science Volume 6506, 2010, pp 403-414. * * The implementation of this function changed between * igraph 0.5 and 0.6 and also between 0.6 and 0.7, so the order of * the cliques and the order of vertices within the cliques will * almost surely be different between these three versions. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in a clique. * The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. Note that vertices * of a clique may be returned in arbitrary order. * \param min_size Integer giving the minimum size of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the cliques to be * returned. If negative or zero, no upper bound will be used. * \return Error code. * * \sa \ref igraph_maximal_independent_vertex_sets(), \ref * igraph_clique_number() * * Time complexity: O(d(n-d)3^(d/3)) worst case, d is the degeneracy * of the graph, this is typically small for sparse graphs. * * \example examples/simple/igraph_maximal_cliques.c */ int igraph_maximal_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size); #define IGRAPH_MC_ORIG #include "maximal_cliques_template.h" #undef IGRAPH_MC_ORIG /** * \function igraph_maximal_cliques_count * Count the number of maximal cliques in a graph * * * The current implementation uses a modified Bron-Kerbosch * algorithm to find the maximal cliques, see: David Eppstein, * Maarten Löffler, Darren Strash: Listing All Maximal Cliques in * Sparse Graphs in Near-Optimal Time. Algorithms and Computation, * Lecture Notes in Computer Science Volume 6506, 2010, pp 403-414. * * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_vector_t * objects which contain the indices of vertices involved in a clique. * The pointer vector will be resized if needed but note that the * objects in the pointer vector will not be freed. Note that vertices * of a clique may be returned in arbitrary order. * \param min_size Integer giving the minimum size of the cliques to be * returned. If negative or zero, no lower bound will be used. * \param max_size Integer giving the maximum size of the cliques to be * returned. If negative or zero, no upper bound will be used. * \return Error code. * * \sa \ref igraph_maximal_cliques(). * * Time complexity: O(d(n-d)3^(d/3)) worst case, d is the degeneracy * of the graph, this is typically small for sparse graphs. * * \example examples/simple/igraph_maximal_cliques.c */ int igraph_maximal_cliques_count(const igraph_t *graph, igraph_integer_t *res, igraph_integer_t min_size, igraph_integer_t max_size); #define IGRAPH_MC_COUNT #include "maximal_cliques_template.h" #undef IGRAPH_MC_COUNT /** * \function igraph_maximal_cliques_file * Find maximal cliques and write them to a file * * TODO */ int igraph_maximal_cliques_file(const igraph_t *graph, FILE *outfile, igraph_integer_t min_size, igraph_integer_t max_size); #define IGRAPH_MC_FILE #include "maximal_cliques_template.h" #undef IGRAPH_MC_FILE /** * \function igraph_maximal_cliques_subset * Maximal cliques for a subset of initial vertices * * TODO */ int igraph_maximal_cliques_subset(const igraph_t *graph, igraph_vector_int_t *subset, igraph_vector_ptr_t *res, igraph_integer_t *no, FILE *outfile, igraph_integer_t min_size, igraph_integer_t max_size); #define IGRAPH_MC_FULL #include "maximal_cliques_template.h" #undef IGRAPH_MC_FULL igraph/src/debug.h0000644000175100001440000000135113431000472013562 0ustar hornikusersc c\SCCS Information: @(#) c FILE: debug.h SID: 2.3 DATE OF SID: 11/16/95 RELEASE: 2 c c %---------------------------------% c | See debug.doc for documentation | c %---------------------------------% integer logfil, ndigit, mgetv0, & msaupd, msaup2, msaitr, mseigt, msapps, msgets, mseupd, & mnaupd, mnaup2, mnaitr, mneigh, mnapps, mngets, mneupd, & mcaupd, mcaup2, mcaitr, mceigh, mcapps, mcgets, mceupd common /debug/ & logfil, ndigit, mgetv0, & msaupd, msaup2, msaitr, mseigt, msapps, msgets, mseupd, & mnaupd, mnaup2, mnaitr, mneigh, mnapps, mngets, mneupd, & mcaupd, mcaup2, mcaitr, mceigh, mcapps, mcgets, mceupd igraph/src/layout_kk.c0000644000175100001440000005445413431000472014505 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_layout.h" #include "igraph_interface.h" #include "igraph_paths.h" #include "igraph_random.h" /** * \ingroup layout * \function igraph_layout_kamada_kawai * \brief Places the vertices on a plane according the Kamada-Kawai algorithm. * * * This is a force directed layout, see Kamada, T. and Kawai, S.: An * Algorithm for Drawing General Undirected Graphs. Information * Processing Letters, 31/1, 7--15, 1989. * \param graph A graph object. * \param res Pointer to an initialized matrix object. This will * contain the result (x-positions in column zero and * y-positions in column one) and will be resized if needed. * \param use_seed Boolean, whether to use the values supplied in the * \p res argument as the initial configuration. If zero then a * random initial configuration is used. * \param maxiter The maximum number of iterations to perform. A reasonable * default value is at least ten (or more) times the number of * vertices. * \param epsilon Stop the iteration, if the maximum delta value of the * algorithm is smaller than still. It is safe to leave it at zero, * and then \p maxiter iterations are performed. * \param kkconst The Kamada-Kawai vertex attraction constant. * Typical value: number of vertices. * \param weights Edge weights, larger values will result longer edges. * \param minx Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote x \endquote coordinate for every vertex. * \param maxx Same as \p minx, but the maximum \quote x \endquote * coordinates. * \param miny Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote y \endquote coordinate for every vertex. * \param maxy Same as \p miny, but the maximum \quote y \endquote * coordinates. * \return Error code. * * Time complexity: O(|V|) for each iteration, after an O(|V|^2 * log|V|) initialization step. |V| is the number of vertices in the * graph. */ int igraph_layout_kamada_kawai(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t epsilon, igraph_real_t kkconst, const igraph_vector_t *weights, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_integer_t no_edges=igraph_ecount(graph); igraph_real_t L, L0=sqrt(no_nodes); igraph_matrix_t dij, lij, kij; igraph_real_t max_dij; igraph_vector_t D1, D2; igraph_integer_t i, j, m; if (maxiter < 0) { IGRAPH_ERROR("Number of iterations must be non-negatice in " "Kamada-Kawai layout", IGRAPH_EINVAL); } if (kkconst <= 0) { IGRAPH_ERROR("`K' constant must be positive in Kamada-Kawai layout", IGRAPH_EINVAL); } if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 2)) { IGRAPH_ERROR("Invalid start position matrix size in " "Kamada-Kawai layout", IGRAPH_EINVAL); } if (weights && igraph_vector_size(weights) != no_edges) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (minx && igraph_vector_size(minx) != no_nodes) { IGRAPH_ERROR("Invalid minx vector length", IGRAPH_EINVAL); } if (maxx && igraph_vector_size(maxx) != no_nodes) { IGRAPH_ERROR("Invalid maxx vector length", IGRAPH_EINVAL); } if (minx && maxx && !igraph_vector_all_le(minx, maxx)) { IGRAPH_ERROR("minx must not be greater than maxx", IGRAPH_EINVAL); } if (miny && igraph_vector_size(miny) != no_nodes) { IGRAPH_ERROR("Invalid miny vector length", IGRAPH_EINVAL); } if (maxy && igraph_vector_size(maxy) != no_nodes) { IGRAPH_ERROR("Invalid maxy vector length", IGRAPH_EINVAL); } if (miny && maxy && !igraph_vector_all_le(miny, maxy)) { IGRAPH_ERROR("miny must not be greater than maxy", IGRAPH_EINVAL); } if (!use_seed) { if (minx || maxx || miny || maxy) { const igraph_real_t width=sqrt(no_nodes), height=width; IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 2)); RNG_BEGIN(); for (i=0; i max_dij) { max_dij = MATRIX(dij, i, j); } } } for (i=0; i max_dij) { MATRIX(dij, i, j) = max_dij; } } } L = L0 / max_dij; for (i=0; i max_delta) { m=i; max_delta=delta; } } if (max_delta < epsilon) { break; } old_x=MATRIX(*res, m, 0); old_y=MATRIX(*res, m, 1); /* Calculate D1 and D2, A, B, C */ for (i=0; i VECTOR(*maxx)[m]) { new_x = VECTOR(*maxx)[m]; } if (miny && new_y < VECTOR(*miny)[m]) { new_y = VECTOR(*miny)[m]; } if (maxy && new_y > VECTOR(*maxy)[m]) { new_y = VECTOR(*maxy)[m]; } /* Update delta, only with/for the affected node */ VECTOR(D1)[m] = VECTOR(D2)[m] = 0.0; for (i=0; i * This is a force directed layout, see Kamada, T. and Kawai, S.: An * Algorithm for Drawing General Undirected Graphs. Information * Processing Letters, 31/1, 7--15, 1989. * \param graph A graph object. * \param res Pointer to an initialized matrix object. This will * contain the result (x-positions in column zero and * y-positions in column one) and will be resized if needed. * \param use_seed Boolean, whether to use the values supplied in the * \p res argument as the initial configuration. If zero then a * random initial configuration is used. * \param maxiter The maximum number of iterations to perform. A reasonable * default value is at least ten (or more) times the number of * vertices. * \param epsilon Stop the iteration, if the maximum delta value of the * algorithm is smaller than still. It is safe to leave it at zero, * and then \p maxiter iterations are performed. * \param kkconst The Kamada-Kawai vertex attraction constant. * Typical value: number of vertices. * \param weights Edge weights, larger values will result longer edges. * \param minx Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote x \endquote coordinate for every vertex. * \param maxx Same as \p minx, but the maximum \quote x \endquote * coordinates. * \param miny Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote y \endquote coordinate for every vertex. * \param maxy Same as \p miny, but the maximum \quote y \endquote * coordinates. * \param minz Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote z \endquote coordinate for every vertex. * \param maxz Same as \p minz, but the maximum \quote z \endquote * coordinates. * \return Error code. * * Time complexity: O(|V|) for each iteration, after an O(|V|^2 * log|V|) initialization step. |V| is the number of vertices in the * graph. */ int igraph_layout_kamada_kawai_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t epsilon, igraph_real_t kkconst, const igraph_vector_t *weights, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy, const igraph_vector_t *minz, const igraph_vector_t *maxz) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_integer_t no_edges=igraph_ecount(graph); igraph_real_t L, L0=sqrt(no_nodes); igraph_matrix_t dij, lij, kij; igraph_real_t max_dij; igraph_vector_t D1, D2, D3; igraph_integer_t i, j, m; if (maxiter < 0) { IGRAPH_ERROR("Number of iterations must be non-negatice in " "Kamada-Kawai layout", IGRAPH_EINVAL); } if (kkconst <= 0) { IGRAPH_ERROR("`K' constant must be positive in Kamada-Kawai layout", IGRAPH_EINVAL); } if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 3)) { IGRAPH_ERROR("Invalid start position matrix size in " "3d Kamada-Kawai layout", IGRAPH_EINVAL); } if (weights && igraph_vector_size(weights) != no_edges) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (minx && igraph_vector_size(minx) != no_nodes) { IGRAPH_ERROR("Invalid minx vector length", IGRAPH_EINVAL); } if (maxx && igraph_vector_size(maxx) != no_nodes) { IGRAPH_ERROR("Invalid maxx vector length", IGRAPH_EINVAL); } if (minx && maxx && !igraph_vector_all_le(minx, maxx)) { IGRAPH_ERROR("minx must not be greater than maxx", IGRAPH_EINVAL); } if (miny && igraph_vector_size(miny) != no_nodes) { IGRAPH_ERROR("Invalid miny vector length", IGRAPH_EINVAL); } if (maxy && igraph_vector_size(maxy) != no_nodes) { IGRAPH_ERROR("Invalid maxy vector length", IGRAPH_EINVAL); } if (miny && maxy && !igraph_vector_all_le(miny, maxy)) { IGRAPH_ERROR("miny must not be greater than maxy", IGRAPH_EINVAL); } if (minz && igraph_vector_size(minz) != no_nodes) { IGRAPH_ERROR("Invalid minz vector length", IGRAPH_EINVAL); } if (maxz && igraph_vector_size(maxz) != no_nodes) { IGRAPH_ERROR("Invalid maxz vector length", IGRAPH_EINVAL); } if (minz && maxz && !igraph_vector_all_le(minz, maxz)) { IGRAPH_ERROR("minz must not be greater than maxz", IGRAPH_EINVAL); } if (!use_seed) { if (minx || maxx || miny || maxy || minz || maxz) { const igraph_real_t width=sqrt(no_nodes), height=width, depth=width; IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 3)); RNG_BEGIN(); for (i=0; i max_dij) { max_dij = MATRIX(dij, i, j); } } } for (i=0; i max_dij) { MATRIX(dij, i, j) = max_dij; } } } L = L0 / max_dij; for (i=0; i max_delta) { m=i; max_delta=delta; } } if (max_delta < epsilon) { break; } old_x=MATRIX(*res, m, 0); old_y=MATRIX(*res, m, 1); old_z=MATRIX(*res, m, 2); /* Calculate D1, D2 and D3, and other coefficients */ for (i=0; i VECTOR(*maxx)[m]) { new_x = VECTOR(*maxx)[m]; } if (miny && new_y < VECTOR(*miny)[m]) { new_y = VECTOR(*miny)[m]; } if (maxy && new_y > VECTOR(*maxy)[m]) { new_y = VECTOR(*maxy)[m]; } if (minz && new_z < VECTOR(*minz)[m]) { new_z = VECTOR(*minz)[m]; } if (maxz && new_z > VECTOR(*maxz)[m]) { new_z = VECTOR(*maxz)[m]; } /* Update delta, only with/for the affected node */ VECTOR(D1)[m] = VECTOR(D2)[m] = VECTOR(D3)[m] = 0.0; for (i=0; i #include SEXP promise_as_lazy(SEXP promise, SEXP env, int follow_symbols) { // recurse until we find the real promise, not a promise of a promise // never go past the global environment while(TYPEOF(promise) == PROMSXP && env != R_GlobalEnv) { env = PRENV(promise); promise = PREXPR(promise); // If the promise is threaded through multiple functions, we'll // get some symbols along the way. If the symbol is bound to a promise // keep going on up if (follow_symbols && TYPEOF(promise) == SYMSXP) { SEXP obj = findVar(promise, env); if (TYPEOF(obj) == PROMSXP) { promise = obj; } } } // Make named list for output SEXP lazy = PROTECT(allocVector(VECSXP, 2)); SET_VECTOR_ELT(lazy, 0, promise); SET_VECTOR_ELT(lazy, 1, env); SEXP names = PROTECT(allocVector(STRSXP, 2)); SET_STRING_ELT(names, 0, mkChar("expr")); SET_STRING_ELT(names, 1, mkChar("env")); setAttrib(lazy, install("names"), names); setAttrib(lazy, install("class"), PROTECT(mkString("lazy"))); UNPROTECT(3); return lazy; } SEXP make_lazy(SEXP name, SEXP env, SEXP follow_symbols_) { SEXP promise = PROTECT(findVar(name, env)); int follow_symbols = asLogical(follow_symbols_); SEXP ret = promise_as_lazy(promise, env, follow_symbols); UNPROTECT(1); return ret; } SEXP make_lazy_dots(SEXP env, SEXP follow_symbols_) { SEXP dots = PROTECT(findVar(install("..."), env)); int follow_symbols = asLogical(follow_symbols_); // Figure out how many elements in dots int n = 0; for(SEXP nxt = dots; nxt != R_NilValue; nxt = CDR(nxt)) { n++; } // Allocate list to store results SEXP lazy_dots = PROTECT(allocVector(VECSXP, n)); SEXP names = PROTECT(allocVector(STRSXP, n)); // Iterate through all elements of dots, converting promises into lazy exprs int i = 0; SEXP nxt = dots; while(nxt != R_NilValue) { SEXP promise = CAR(nxt); SEXP lazy = promise_as_lazy(promise, env, follow_symbols); SET_VECTOR_ELT(lazy_dots, i, lazy); if (TAG(nxt) != R_NilValue) SET_STRING_ELT(names, i, PRINTNAME(TAG(nxt))); nxt = CDR(nxt); i++; } setAttrib(lazy_dots, install("names"), names); setAttrib(lazy_dots, install("class"), PROTECT(mkString("lazy_dots"))); UNPROTECT(4); return lazy_dots; } #include #include /* For now, replace with pure R alternative ------------------------------------ // This is a bit naughty, but there's no other way to create a promise SEXP Rf_mkPROMISE(SEXP, SEXP); SEXP Rf_installTrChar(SEXP); SEXP lazy_to_promise(SEXP x) { // arg is a list of length 2 - LANGSXP/SYMSXP, followed by ENVSXP return Rf_mkPROMISE(VECTOR_ELT(x, 0), VECTOR_ELT(x, 1)); } SEXP eval_call_(SEXP fun, SEXP dots, SEXP env) { if (TYPEOF(fun) != SYMSXP && TYPEOF(fun) != LANGSXP) { error("fun must be a call or a symbol"); } if (TYPEOF(dots) != VECSXP) { error("dots must be a list"); } if (!inherits(dots, "lazy_dots")) { error("dots must be of class lazy_dots"); } if (TYPEOF(env) != ENVSXP) { error("env must be an environment"); } int n = length(dots); if (n == 0) { return LCONS(fun, R_NilValue); } SEXP names = GET_NAMES(dots); SEXP args = R_NilValue; for (int i = n - 1; i >= 0; --i) { SEXP dot = VECTOR_ELT(dots, i); SEXP prom = lazy_to_promise(dot); args = PROTECT(CONS(prom, args)); if (names != R_NilValue) { SEXP name = STRING_ELT(names, i); if (strlen(CHAR(name)) > 0) SET_TAG(args, Rf_installTrChar(name)); } } UNPROTECT(n); SEXP call = LCONS(fun, args); return eval(call, env); } */ #include #include /* Fails on Linux -------------------------------------------------------------- SEXP Rf_mkPROMISE(SEXP, SEXP); SEXP promise_(SEXP expr, SEXP env) { if (TYPEOF(expr) != SYMSXP && TYPEOF(expr) != LANGSXP) { error("expr must be a call or a symbol"); } if (TYPEOF(env) != ENVSXP) { error("env must be an environment"); } return Rf_mkPROMISE(expr, env); } */ SEXP promise_expr_(SEXP prom) { if (TYPEOF(prom) != PROMSXP) { error("prom must be a promise"); } return PREXPR(prom); } SEXP promise_env_(SEXP prom) { if (TYPEOF(prom) != PROMSXP) { error("prom must be a promise"); } return PRENV(prom); } igraph/src/optimal_modularity.c0000644000175100001440000001737413431000472016421 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interface.h" #include "igraph_structural.h" #include "igraph_community.h" #include "igraph_error.h" #include "igraph_glpk_support.h" #include "igraph_interrupt_internal.h" #include "igraph_centrality.h" #include "config.h" #ifdef HAVE_GLPK #include #endif /** * \function igraph_community_optimal_modularity * Calculate the community structure with the highest modularity value * * This function calculates the optimal community structure for a * graph, in terms of maximal modularity score. * * * The calculation is done by transforming the modularity maximization * into an integer programming problem, and then calling the GLPK * library to solve that. Please see Ulrik Brandes et al.: On * Modularity Clustering, IEEE Transactions on Knowledge and Data * Engineering 20(2):172-188, 2008. * * * Note that modularity optimization is an NP-complete problem, and * all known algorithms for it have exponential time complexity. This * means that you probably don't want to run this function on larger * graphs. Graphs with up to fifty vertices should be fine, graphs * with a couple of hundred vertices might be possible. * * \param graph The input graph. It is always treated as undirected. * \param modularity Pointer to a real number, or a null pointer. * If it is not a null pointer, then a optimal modularity value * is returned here. * \param membership Pointer to a vector, or a null pointer. If not a * null pointer, then the membership vector of the optimal * community structure is stored here. * \param weights Vector giving the weights of the edges. If it is * \c NULL then each edge is supposed to have the same weight. * \return Error code. * * \sa \ref igraph_modularity(), \ref igraph_community_fastgreedy() * for an algorithm that finds a local optimum in a greedy way. * * Time complexity: exponential in the number of vertices. * * \example examples/simple/igraph_community_optimal_modularity.c */ int igraph_community_optimal_modularity(const igraph_t *graph, igraph_real_t *modularity, igraph_vector_t *membership, const igraph_vector_t *weights) { #ifndef HAVE_GLPK IGRAPH_ERROR("GLPK is not available", IGRAPH_UNIMPLEMENTED); #else igraph_integer_t no_of_nodes=(igraph_integer_t) igraph_vcount(graph); igraph_integer_t no_of_edges=(igraph_integer_t) igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); int no_of_variables=no_of_nodes * (no_of_nodes+1)/2; int i, j, k, l, st; int idx[] = { 0, 0, 0, 0 }; double coef[] = { 0.0, 1.0, 1.0, -2.0 }; igraph_real_t total_weight; igraph_vector_t indegree; igraph_vector_t outdegree; glp_prob *ip; glp_iocp parm; if (weights != 0) { if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid length of weight vector", IGRAPH_EINVAL); } if (igraph_vector_min(weights) < 0) { IGRAPH_ERROR("Negative weights are not allowed in weight vector", IGRAPH_EINVAL); } } if (weights) { total_weight = igraph_vector_sum(weights); } else { total_weight = no_of_edges; } if (!directed) { total_weight *= 2; } /* Special case */ if (no_of_edges == 0 || total_weight == 0) { if (modularity) { *modularity=IGRAPH_NAN; } if (membership) { IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); igraph_vector_null(membership); } } IGRAPH_VECTOR_INIT_FINALLY(&indegree, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&outdegree, no_of_nodes); IGRAPH_CHECK(igraph_strength(graph, &indegree, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS, weights)); IGRAPH_CHECK(igraph_strength(graph, &outdegree, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS, weights)); glp_term_out(GLP_OFF); ip = glp_create_prob(); IGRAPH_FINALLY(glp_delete_prob, ip); glp_set_obj_dir(ip, GLP_MAX); st=glp_add_cols(ip, no_of_variables); /* variables are binary */ for (i=0; i j) { l = i; i = j; j = l; } c = weights ? VECTOR(*weights)[k] : 1.0; if (!directed || i == j) { c *= 2.0; } glp_set_obj_coef(ip, st+IDX(i,j), c + glp_get_obj_coef(ip, st+IDX(i,j))); } } /* solve it */ glp_init_iocp(&parm); parm.br_tech = GLP_BR_DTH; parm.bt_tech = GLP_BT_BLB; parm.presolve = GLP_ON; parm.binarize = GLP_ON; parm.cb_func = igraph_i_glpk_interruption_hook; IGRAPH_GLPK_CHECK(glp_intopt(ip, &parm), "Modularity optimization failed"); /* store the results */ if (modularity) { *modularity = glp_mip_obj_val(ip) / total_weight; } if (membership) { long int comm=0; /* id of the last community that was found */ IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); for (i=0; i 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "igraph_error.h" #include "igraph_attributes.h" #include "config.h" #include "igraph_math.h" #include #include "foreign-pajek-header.h" #include "foreign-pajek-parser.h" #define yyscan_t void* int igraph_pajek_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_pajek_yyerror(YYLTYPE* locp, igraph_i_pajek_parsedata_t *context, const char *s); char *igraph_pajek_yyget_text (yyscan_t yyscanner ); int igraph_pajek_yyget_leng (yyscan_t yyscanner ); int igraph_i_pajek_add_string_vertex_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_string_edge_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_vertex_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_edge_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_add_numeric_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, igraph_real_t number); int igraph_i_pajek_add_string_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, const char *str); int igraph_i_pajek_add_bipartite_type(igraph_i_pajek_parsedata_t *context); int igraph_i_pajek_check_bipartite(igraph_i_pajek_parsedata_t *context); extern igraph_real_t igraph_pajek_get_number(const char *str, long int len); extern long int igraph_i_pajek_actvertex; extern long int igraph_i_pajek_actedge; #define scanner context->scanner /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 118 "src/foreign-pajek-parser.y" { long int intnum; double realnum; struct { char *str; int len; } string; } /* Line 193 of yacc.c. */ #line 301 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 326 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 5 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 250 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 52 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 66 /* YYNRULES -- Number of rules. */ #define YYNRULES 137 /* YYNRULES -- Number of states. */ #define YYNSTATES 207 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 306 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 7, 8, 12, 16, 19, 23, 24, 27, 29, 32, 33, 41, 43, 45, 46, 49, 53, 54, 56, 57, 60, 62, 65, 68, 73, 78, 83, 86, 89, 92, 95, 98, 101, 104, 107, 110, 111, 115, 116, 120, 121, 125, 126, 130, 131, 135, 137, 138, 141, 144, 147, 150, 153, 157, 162, 163, 166, 168, 169, 176, 178, 180, 184, 189, 190, 193, 195, 196, 203, 205, 207, 208, 210, 211, 214, 216, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 254, 257, 260, 263, 266, 267, 271, 272, 276, 277, 281, 282, 286, 287, 291, 293, 297, 298, 301, 303, 307, 308, 311, 313, 315, 319, 320, 323, 325, 329, 330, 333, 335, 337, 341, 343, 344, 347, 350, 351, 354, 356, 358, 360, 361, 364, 366, 368 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 53, 0, -1, 54, 55, 73, -1, -1, 8, 116, 3, -1, 56, 3, 57, -1, 9, 114, -1, 9, 114, 114, -1, -1, 57, 58, -1, 3, -1, 60, 3, -1, -1, 60, 59, 61, 62, 63, 64, 3, -1, 114, -1, 117, -1, -1, 115, 115, -1, 115, 115, 115, -1, -1, 117, -1, -1, 64, 65, -1, 66, -1, 16, 115, -1, 17, 115, -1, 18, 115, 115, 115, -1, 19, 115, 115, 115, -1, 20, 115, 115, 115, -1, 21, 115, -1, 22, 115, -1, 23, 115, -1, 24, 115, -1, 25, 115, -1, 26, 115, -1, 27, 115, -1, 28, 115, -1, 31, 115, -1, -1, 29, 67, 72, -1, -1, 30, 68, 72, -1, -1, 18, 69, 72, -1, -1, 19, 70, 72, -1, -1, 20, 71, 72, -1, 117, -1, -1, 73, 74, -1, 73, 80, -1, 73, 96, -1, 73, 102, -1, 73, 108, -1, 10, 3, 75, -1, 10, 115, 3, 75, -1, -1, 75, 76, -1, 3, -1, -1, 78, 79, 77, 86, 87, 3, -1, 114, -1, 114, -1, 11, 3, 81, -1, 11, 115, 3, 81, -1, -1, 81, 82, -1, 3, -1, -1, 84, 85, 83, 86, 87, 3, -1, 114, -1, 114, -1, -1, 115, -1, -1, 87, 88, -1, 89, -1, 32, 115, 115, 115, -1, 33, 115, -1, 35, 115, -1, 36, 115, -1, 37, 115, -1, 38, 115, -1, 39, 115, -1, 40, 115, -1, 41, 115, -1, 42, 115, -1, 45, 115, -1, 46, 115, -1, 47, 115, -1, 49, 115, -1, 50, 115, -1, 51, 115, -1, -1, 34, 90, 95, -1, -1, 43, 91, 95, -1, -1, 44, 92, 95, -1, -1, 48, 93, 95, -1, -1, 32, 94, 95, -1, 117, -1, 12, 3, 97, -1, -1, 97, 98, -1, 3, -1, 100, 99, 3, -1, -1, 99, 101, -1, 114, -1, 114, -1, 13, 3, 103, -1, -1, 103, 104, -1, 3, -1, 106, 105, 3, -1, -1, 105, 107, -1, 114, -1, 114, -1, 109, 3, 110, -1, 14, -1, -1, 110, 111, -1, 112, 3, -1, -1, 113, 112, -1, 115, -1, 4, -1, 4, -1, -1, 116, 117, -1, 5, -1, 4, -1, 6, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 192, 192, 196, 196, 198, 200, 204, 210, 210, 212, 213, 214, 214, 217, 219, 224, 225, 229, 235, 235, 239, 239, 242, 243, 246, 249, 254, 259, 264, 267, 270, 273, 276, 279, 282, 285, 288, 293, 293, 297, 297, 301, 301, 305, 305, 310, 310, 317, 319, 319, 319, 319, 319, 319, 321, 322, 324, 324, 326, 327, 327, 333, 335, 337, 338, 340, 340, 342, 343, 343, 349, 351, 353, 353, 357, 357, 360, 361, 366, 369, 372, 375, 378, 381, 384, 387, 390, 393, 396, 399, 402, 405, 408, 413, 413, 417, 417, 421, 421, 425, 425, 429, 429, 435, 437, 439, 439, 441, 441, 443, 443, 445, 447, 452, 454, 454, 456, 456, 458, 458, 460, 462, 469, 471, 476, 476, 478, 480, 480, 482, 502, 505, 508, 508, 510, 512, 514 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "NEWLINE", "NUM", "ALNUM", "QSTR", "PSTR", "NETWORKLINE", "VERTICESLINE", "ARCSLINE", "EDGESLINE", "ARCSLISTLINE", "EDGESLISTLINE", "MATRIXLINE", "ERROR", "VP_X_FACT", "VP_Y_FACT", "VP_IC", "VP_BC", "VP_LC", "VP_LR", "VP_LPHI", "VP_BW", "VP_FOS", "VP_PHI", "VP_R", "VP_Q", "VP_LA", "VP_FONT", "VP_URL", "VP_SIZE", "EP_C", "EP_S", "EP_A", "EP_W", "EP_H1", "EP_H2", "EP_A1", "EP_A2", "EP_K1", "EP_K2", "EP_AP", "EP_P", "EP_L", "EP_LP", "EP_LR", "EP_LPHI", "EP_LC", "EP_LA", "EP_SIZE", "EP_FOS", "$accept", "input", "nethead", "vertices", "verticeshead", "vertdefs", "vertexline", "@1", "vertex", "vertexid", "vertexcoords", "shape", "params", "param", "vpword", "@2", "@3", "@4", "@5", "@6", "vpwordpar", "edgeblock", "arcs", "arcsdefs", "arcsline", "@7", "arcfrom", "arcto", "edges", "edgesdefs", "edgesline", "@8", "edgefrom", "edgeto", "weight", "edgeparams", "edgeparam", "epword", "@9", "@10", "@11", "@12", "@13", "epwordpar", "arcslist", "arcslistlines", "arclistline", "arctolist", "arclistfrom", "arclistto", "edgeslist", "edgelistlines", "edgelistline", "edgetolist", "edgelistfrom", "edgelistto", "adjmatrix", "matrixline", "adjmatrixlines", "adjmatrixline", "adjmatrixnumbers", "adjmatrixentry", "longint", "number", "words", "word", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 52, 53, 54, 54, 55, 56, 56, 57, 57, 58, 58, 59, 58, 60, 61, 62, 62, 62, 63, 63, 64, 64, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 67, 66, 68, 66, 69, 66, 70, 66, 71, 66, 72, 73, 73, 73, 73, 73, 73, 74, 74, 75, 75, 76, 77, 76, 78, 79, 80, 80, 81, 81, 82, 83, 82, 84, 85, 86, 86, 87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 90, 89, 91, 89, 92, 89, 93, 89, 94, 89, 95, 96, 97, 97, 98, 98, 99, 99, 100, 101, 102, 103, 103, 104, 104, 105, 105, 106, 107, 108, 109, 110, 110, 111, 112, 112, 113, 114, 115, 116, 116, 117, 117, 117 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 3, 0, 3, 3, 2, 3, 0, 2, 1, 2, 0, 7, 1, 1, 0, 2, 3, 0, 1, 0, 2, 1, 2, 2, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 1, 0, 2, 2, 2, 2, 2, 3, 4, 0, 2, 1, 0, 6, 1, 1, 3, 4, 0, 2, 1, 0, 6, 1, 1, 0, 1, 0, 2, 1, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 1, 3, 0, 2, 1, 3, 0, 2, 1, 1, 3, 0, 2, 1, 3, 0, 2, 1, 1, 3, 1, 0, 2, 2, 0, 2, 1, 1, 1, 0, 2, 1, 1, 1 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 3, 133, 0, 0, 0, 1, 0, 49, 0, 4, 136, 135, 137, 134, 131, 6, 2, 8, 7, 0, 0, 0, 0, 124, 50, 51, 52, 53, 54, 0, 5, 57, 132, 0, 66, 0, 106, 115, 125, 10, 9, 12, 14, 55, 57, 64, 66, 105, 114, 123, 11, 0, 59, 58, 0, 62, 56, 68, 67, 0, 71, 65, 108, 107, 110, 112, 117, 116, 119, 121, 126, 0, 128, 130, 16, 15, 60, 63, 69, 72, 0, 0, 127, 129, 19, 0, 73, 73, 109, 111, 113, 118, 120, 122, 21, 20, 17, 75, 74, 75, 0, 18, 0, 0, 13, 0, 0, 42, 44, 46, 0, 0, 0, 0, 0, 0, 0, 0, 38, 40, 0, 22, 23, 61, 102, 0, 94, 0, 0, 0, 0, 0, 0, 0, 0, 96, 98, 0, 0, 0, 100, 0, 0, 0, 76, 77, 70, 24, 25, 0, 0, 0, 0, 0, 0, 29, 30, 31, 32, 33, 34, 35, 36, 0, 0, 37, 0, 0, 79, 0, 80, 81, 82, 83, 84, 85, 86, 87, 0, 0, 88, 89, 90, 0, 91, 92, 93, 43, 48, 0, 45, 0, 47, 0, 39, 41, 103, 104, 0, 95, 97, 99, 101, 26, 27, 28, 78 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 2, 3, 7, 8, 30, 40, 51, 41, 74, 84, 94, 100, 121, 122, 163, 164, 149, 151, 153, 187, 16, 24, 43, 53, 86, 54, 76, 25, 45, 58, 87, 59, 78, 97, 102, 144, 145, 169, 178, 179, 183, 166, 196, 26, 47, 63, 80, 64, 89, 27, 48, 67, 81, 68, 92, 28, 29, 49, 70, 71, 72, 55, 73, 4, 188 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -167 static const yytype_int16 yypact[] = { -4, -167, 7, 36, 22, -167, 44, -167, 49, -167, -167, -167, -167, -167, -167, 44, 10, -167, -167, 12, 27, 51, 56, -167, -167, -167, -167, -167, -167, 58, 29, -167, -167, 59, -167, 60, -167, -167, -167, -167, -167, 61, -167, 31, -167, 33, -167, 35, 37, 39, -167, 5, -167, -167, 44, -167, 31, -167, -167, 44, -167, 33, -167, -167, -167, -167, -167, -167, -167, -167, -167, 62, 65, -167, 65, -167, -167, -167, -167, -167, 47, 53, -167, -167, 5, 65, 65, 65, -167, -167, -167, -167, -167, -167, -167, -167, 65, -167, -167, -167, 219, -167, 150, 170, -167, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, -167, -167, 65, -167, -167, -167, 65, 65, -167, 65, 65, 65, 65, 65, 65, 65, 65, -167, -167, 65, 65, 65, -167, 65, 65, 65, -167, -167, -167, -167, -167, 5, 65, 5, 65, 5, 65, -167, -167, -167, -167, -167, -167, -167, -167, 5, 5, -167, 5, 65, -167, 5, -167, -167, -167, -167, -167, -167, -167, -167, 5, 5, -167, -167, -167, 5, -167, -167, -167, -167, -167, 65, -167, 65, -167, 65, -167, -167, -167, -167, 65, -167, -167, -167, -167, -167, -167, -167, -167 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -145, -167, -167, 26, -167, -167, -167, -167, -167, 25, -167, -167, -167, -167, -15, -26, -167, -167, -167, -167, -167, -167, -167, -166, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, -167, 2, -167, -1, -19, -167, -2 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -129 static const yytype_int16 yytable[] = { 33, 35, 13, 199, 1, 15, 190, 5, 192, 10, 11, 12, 200, 201, 18, 31, 32, 202, 194, 195, 19, 20, 21, 22, 23, 9, 10, 11, 12, 42, 34, 32, 39, 14, 52, 14, 57, 14, 62, 14, 66, 14, -128, 32, 60, 6, 65, 69, 14, 75, 88, 14, 17, 77, 36, 85, 91, 14, 79, 37, 60, 38, 44, 46, 50, 82, 96, 98, 98, 32, 56, 61, 99, 103, 83, 0, 0, 101, 0, 90, 93, 0, 95, 0, 0, 0, 147, 148, 150, 152, 154, 155, 156, 157, 158, 159, 160, 161, 162, 0, 0, 165, 0, 0, 0, 167, 168, 0, 170, 171, 172, 173, 174, 175, 176, 177, 0, 0, 180, 181, 182, 0, 184, 185, 186, 0, 0, 0, 0, 0, 0, 189, 0, 191, 0, 193, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 0, 0, 0, 0, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 197, 0, 0, 197, 0, 0, 203, 0, 204, 146, 205, 0, 197, 197, 0, 206, 0, 197, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120 }; static const yytype_int16 yycheck[] = { 19, 20, 4, 169, 8, 6, 151, 0, 153, 4, 5, 6, 178, 179, 15, 3, 4, 183, 163, 164, 10, 11, 12, 13, 14, 3, 4, 5, 6, 30, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 3, 4, 45, 9, 47, 48, 4, 51, 3, 4, 3, 54, 3, 74, 3, 4, 59, 3, 61, 3, 3, 3, 3, 3, 85, 86, 87, 4, 44, 46, 87, 99, 72, -1, -1, 96, -1, 80, 81, -1, 84, -1, -1, -1, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, -1, -1, 120, -1, -1, -1, 124, 125, -1, 127, 128, 129, 130, 131, 132, 133, 134, -1, -1, 137, 138, 139, -1, 141, 142, 143, -1, -1, -1, -1, -1, -1, 150, -1, 152, -1, 154, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 167, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 166, -1, -1, 169, -1, -1, 189, -1, 191, 3, 193, -1, 178, 179, -1, 198, -1, 183, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 8, 53, 54, 116, 0, 9, 55, 56, 3, 4, 5, 6, 117, 4, 114, 73, 3, 114, 10, 11, 12, 13, 14, 74, 80, 96, 102, 108, 109, 57, 3, 4, 115, 3, 115, 3, 3, 3, 3, 58, 60, 114, 75, 3, 81, 3, 97, 103, 110, 3, 59, 3, 76, 78, 114, 75, 3, 82, 84, 114, 81, 3, 98, 100, 114, 3, 104, 106, 114, 111, 112, 113, 115, 61, 117, 79, 114, 85, 114, 99, 105, 3, 112, 62, 115, 77, 83, 3, 101, 114, 3, 107, 114, 63, 117, 115, 86, 115, 86, 64, 115, 87, 87, 3, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 65, 66, 3, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 88, 89, 3, 115, 115, 69, 115, 70, 115, 71, 115, 115, 115, 115, 115, 115, 115, 115, 115, 67, 68, 115, 94, 115, 115, 90, 115, 115, 115, 115, 115, 115, 115, 115, 91, 92, 115, 115, 115, 93, 115, 115, 115, 72, 117, 115, 72, 115, 72, 115, 72, 72, 95, 117, 115, 95, 95, 95, 95, 115, 115, 115, 115 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc, scanner) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_pajek_parsedata_t* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_pajek_parsedata_t* context; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_pajek_parsedata_t* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_pajek_parsedata_t* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, igraph_i_pajek_parsedata_t* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; igraph_i_pajek_parsedata_t* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, igraph_i_pajek_parsedata_t* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; igraph_i_pajek_parsedata_t* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (igraph_i_pajek_parsedata_t* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (igraph_i_pajek_parsedata_t* context) #else int yyparse (context) igraph_i_pajek_parsedata_t* context; #endif #endif { /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 192 "src/foreign-pajek-parser.y" { if (context->vcount2 > 0) { igraph_i_pajek_check_bipartite(context); } ;} break; case 6: #line 200 "src/foreign-pajek-parser.y" { context->vcount=(yyvsp[(2) - (2)].intnum); context->vcount2=0; ;} break; case 7: #line 204 "src/foreign-pajek-parser.y" { context->vcount=(yyvsp[(2) - (3)].intnum); context->vcount2=(yyvsp[(3) - (3)].intnum); igraph_i_pajek_add_bipartite_type(context); ;} break; case 12: #line 214 "src/foreign-pajek-parser.y" { context->actvertex=(yyvsp[(1) - (1)].intnum); ;} break; case 13: #line 214 "src/foreign-pajek-parser.y" { ;} break; case 14: #line 217 "src/foreign-pajek-parser.y" { (yyval.intnum)=(yyvsp[(1) - (1)].intnum); context->mode=1; ;} break; case 15: #line 219 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_string_vertex_attribute("id", (yyvsp[(1) - (1)].string).str, (yyvsp[(1) - (1)].string).len, context); igraph_i_pajek_add_string_vertex_attribute("name", (yyvsp[(1) - (1)].string).str, (yyvsp[(1) - (1)].string).len, context); ;} break; case 17: #line 225 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("x", (yyvsp[(1) - (2)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("y", (yyvsp[(2) - (2)].realnum), context); ;} break; case 18: #line 229 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("x", (yyvsp[(1) - (3)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("y", (yyvsp[(2) - (3)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("z", (yyvsp[(3) - (3)].realnum), context); ;} break; case 20: #line 235 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_string_vertex_attribute("shape", (yyvsp[(1) - (1)].string).str, (yyvsp[(1) - (1)].string).len, context); ;} break; case 24: #line 243 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("xfact", (yyvsp[(2) - (2)].realnum), context); ;} break; case 25: #line 246 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("yfact", (yyvsp[(2) - (2)].realnum), context); ;} break; case 26: #line 249 "src/foreign-pajek-parser.y" { /* RGB color */ igraph_i_pajek_add_numeric_vertex_attribute("color-red", (yyvsp[(2) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("color-green", (yyvsp[(3) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("color-blue", (yyvsp[(4) - (4)].realnum), context); ;} break; case 27: #line 254 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("framecolor-red", (yyvsp[(2) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("framecolor-green", (yyvsp[(3) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("framecolor-blue", (yyvsp[(4) - (4)].realnum), context); ;} break; case 28: #line 259 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-red", (yyvsp[(2) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-green", (yyvsp[(3) - (4)].realnum), context); igraph_i_pajek_add_numeric_vertex_attribute("labelcolor-blue", (yyvsp[(4) - (4)].realnum), context); ;} break; case 29: #line 264 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("labeldist", (yyvsp[(2) - (2)].realnum), context); ;} break; case 30: #line 267 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("labeldegree2", (yyvsp[(2) - (2)].realnum), context); ;} break; case 31: #line 270 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("framewidth", (yyvsp[(2) - (2)].realnum), context); ;} break; case 32: #line 273 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("fontsize", (yyvsp[(2) - (2)].realnum), context); ;} break; case 33: #line 276 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("rotation", (yyvsp[(2) - (2)].realnum), context); ;} break; case 34: #line 279 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("radius", (yyvsp[(2) - (2)].realnum), context); ;} break; case 35: #line 282 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("diamondratio", (yyvsp[(2) - (2)].realnum), context); ;} break; case 36: #line 285 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("labeldegree", (yyvsp[(2) - (2)].realnum), context); ;} break; case 37: #line 288 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_vertex_attribute("vertexsize", (yyvsp[(2) - (2)].realnum), context); ;} break; case 38: #line 293 "src/foreign-pajek-parser.y" { context->mode=3; ;} break; case 39: #line 293 "src/foreign-pajek-parser.y" { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("font", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 40: #line 297 "src/foreign-pajek-parser.y" { context->mode=3; ;} break; case 41: #line 297 "src/foreign-pajek-parser.y" { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("url", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 42: #line 301 "src/foreign-pajek-parser.y" { context->mode=3; ;} break; case 43: #line 301 "src/foreign-pajek-parser.y" { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("color", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 44: #line 305 "src/foreign-pajek-parser.y" { context->mode=3; ;} break; case 45: #line 305 "src/foreign-pajek-parser.y" { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("framecolor", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 46: #line 310 "src/foreign-pajek-parser.y" { context->mode=3; ;} break; case 47: #line 310 "src/foreign-pajek-parser.y" { context->mode=1; igraph_i_pajek_add_string_vertex_attribute("labelcolor", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 48: #line 317 "src/foreign-pajek-parser.y" { (yyval.string)=(yyvsp[(1) - (1)].string); ;} break; case 55: #line 321 "src/foreign-pajek-parser.y" { context->directed=1; ;} break; case 56: #line 322 "src/foreign-pajek-parser.y" { context->directed=1; ;} break; case 60: #line 327 "src/foreign-pajek-parser.y" { context->actedge++; context->mode=2; ;} break; case 61: #line 328 "src/foreign-pajek-parser.y" { igraph_vector_push_back(context->vector, (yyvsp[(1) - (6)].intnum)-1); igraph_vector_push_back(context->vector, (yyvsp[(2) - (6)].intnum)-1); ;} break; case 64: #line 337 "src/foreign-pajek-parser.y" { context->directed=0; ;} break; case 65: #line 338 "src/foreign-pajek-parser.y" { context->directed=0; ;} break; case 69: #line 343 "src/foreign-pajek-parser.y" { context->actedge++; context->mode=2; ;} break; case 70: #line 344 "src/foreign-pajek-parser.y" { igraph_vector_push_back(context->vector, (yyvsp[(1) - (6)].intnum)-1); igraph_vector_push_back(context->vector, (yyvsp[(2) - (6)].intnum)-1); ;} break; case 74: #line 353 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("weight", (yyvsp[(1) - (1)].realnum), context); ;} break; case 78: #line 361 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("color-red", (yyvsp[(2) - (4)].realnum), context); igraph_i_pajek_add_numeric_edge_attribute("color-green", (yyvsp[(3) - (4)].realnum), context); igraph_i_pajek_add_numeric_edge_attribute("color-blue", (yyvsp[(4) - (4)].realnum), context); ;} break; case 79: #line 366 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("arrowsize", (yyvsp[(2) - (2)].realnum), context); ;} break; case 80: #line 369 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("edgewidth", (yyvsp[(2) - (2)].realnum), context); ;} break; case 81: #line 372 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("hook1", (yyvsp[(2) - (2)].realnum), context); ;} break; case 82: #line 375 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("hook2", (yyvsp[(2) - (2)].realnum), context); ;} break; case 83: #line 378 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("angle1", (yyvsp[(2) - (2)].realnum), context); ;} break; case 84: #line 381 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("angle2", (yyvsp[(2) - (2)].realnum), context); ;} break; case 85: #line 384 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("velocity1", (yyvsp[(2) - (2)].realnum), context); ;} break; case 86: #line 387 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("velocity2", (yyvsp[(2) - (2)].realnum), context); ;} break; case 87: #line 390 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("arrowpos", (yyvsp[(2) - (2)].realnum), context); ;} break; case 88: #line 393 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("labelpos", (yyvsp[(2) - (2)].realnum), context); ;} break; case 89: #line 396 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("labelangle", (yyvsp[(2) - (2)].realnum), context); ;} break; case 90: #line 399 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("labelangle2", (yyvsp[(2) - (2)].realnum), context); ;} break; case 91: #line 402 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("labeldegree", (yyvsp[(2) - (2)].realnum), context); ;} break; case 92: #line 405 "src/foreign-pajek-parser.y" { /* what is this??? */ igraph_i_pajek_add_numeric_edge_attribute("arrowsize", (yyvsp[(2) - (2)].realnum), context); ;} break; case 93: #line 408 "src/foreign-pajek-parser.y" { igraph_i_pajek_add_numeric_edge_attribute("fontsize", (yyvsp[(2) - (2)].realnum), context); ;} break; case 94: #line 413 "src/foreign-pajek-parser.y" { context->mode=4; ;} break; case 95: #line 413 "src/foreign-pajek-parser.y" { context->mode=2; igraph_i_pajek_add_string_edge_attribute("arrowtype", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 96: #line 417 "src/foreign-pajek-parser.y" { context->mode=4; ;} break; case 97: #line 417 "src/foreign-pajek-parser.y" { context->mode=2; igraph_i_pajek_add_string_edge_attribute("linepattern", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 98: #line 421 "src/foreign-pajek-parser.y" { context->mode=4; ;} break; case 99: #line 421 "src/foreign-pajek-parser.y" { context->mode=2; igraph_i_pajek_add_string_edge_attribute("label", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 100: #line 425 "src/foreign-pajek-parser.y" { context->mode=4; ;} break; case 101: #line 425 "src/foreign-pajek-parser.y" { context->mode=2; igraph_i_pajek_add_string_edge_attribute("labelcolor", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 102: #line 429 "src/foreign-pajek-parser.y" { context->mode=4; ;} break; case 103: #line 429 "src/foreign-pajek-parser.y" { context->mode=2; igraph_i_pajek_add_string_edge_attribute("color", (yyvsp[(3) - (3)].string).str, (yyvsp[(3) - (3)].string).len, context); ;} break; case 104: #line 435 "src/foreign-pajek-parser.y" { context->mode=2; (yyval.string)=(yyvsp[(1) - (1)].string); ;} break; case 105: #line 437 "src/foreign-pajek-parser.y" { context->directed=1; ;} break; case 112: #line 445 "src/foreign-pajek-parser.y" { context->mode=0; context->actfrom=labs((yyvsp[(1) - (1)].intnum))-1; ;} break; case 113: #line 447 "src/foreign-pajek-parser.y" { igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, labs((yyvsp[(1) - (1)].intnum))-1); ;} break; case 114: #line 452 "src/foreign-pajek-parser.y" { context->directed=0; ;} break; case 121: #line 460 "src/foreign-pajek-parser.y" { context->mode=0; context->actfrom=labs((yyvsp[(1) - (1)].intnum))-1; ;} break; case 122: #line 462 "src/foreign-pajek-parser.y" { igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, labs((yyvsp[(1) - (1)].intnum))-1); ;} break; case 124: #line 471 "src/foreign-pajek-parser.y" { context->actfrom=0; context->actto=0; context->directed=(context->vcount2==0); ;} break; case 127: #line 478 "src/foreign-pajek-parser.y" { context->actfrom++; context->actto=0; ;} break; case 130: #line 482 "src/foreign-pajek-parser.y" { if ((yyvsp[(1) - (1)].realnum) != 0) { if (context->vcount2==0) { context->actedge++; igraph_i_pajek_add_numeric_edge_attribute("weight", (yyvsp[(1) - (1)].realnum), context); igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, context->actto); } else if (context->vcount2 + context->actto < context->vcount) { context->actedge++; igraph_i_pajek_add_numeric_edge_attribute("weight", (yyvsp[(1) - (1)].realnum), context); igraph_vector_push_back(context->vector, context->actfrom); igraph_vector_push_back(context->vector, context->vcount2+context->actto); } } context->actto++; ;} break; case 131: #line 502 "src/foreign-pajek-parser.y" { (yyval.intnum)=igraph_pajek_get_number(igraph_pajek_yyget_text(scanner), igraph_pajek_yyget_leng(scanner)); ;} break; case 132: #line 505 "src/foreign-pajek-parser.y" { (yyval.realnum)=igraph_pajek_get_number(igraph_pajek_yyget_text(scanner), igraph_pajek_yyget_leng(scanner)); ;} break; case 135: #line 510 "src/foreign-pajek-parser.y" { (yyval.string).str=igraph_pajek_yyget_text(scanner); (yyval.string).len=igraph_pajek_yyget_leng(scanner); ;} break; case 136: #line 512 "src/foreign-pajek-parser.y" { (yyval.string).str=igraph_pajek_yyget_text(scanner); (yyval.string).len=igraph_pajek_yyget_leng(scanner); ;} break; case 137: #line 514 "src/foreign-pajek-parser.y" { (yyval.string).str=igraph_pajek_yyget_text(scanner)+1; (yyval.string).len=igraph_pajek_yyget_leng(scanner)-2; ;} break; /* Line 1267 of yacc.c. */ #line 2356 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (&yylloc, context, yymsg); } else { yyerror (&yylloc, context, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 517 "src/foreign-pajek-parser.y" int igraph_pajek_yyerror(YYLTYPE* locp, igraph_i_pajek_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in Pajek file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_pajek_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } /* TODO: NA's */ int igraph_i_pajek_add_numeric_attribute(igraph_trie_t *names, igraph_vector_ptr_t *attrs, long int count, const char *attrname, igraph_integer_t vid, igraph_real_t number) { long int attrsize=igraph_trie_size(names); long int id; igraph_vector_t *na; igraph_attribute_record_t *rec; igraph_trie_get(names, attrname, &id); if (id == attrsize) { /* add a new attribute */ rec=igraph_Calloc(1, igraph_attribute_record_t); na=igraph_Calloc(1, igraph_vector_t); igraph_vector_init(na, count); rec->name=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); } rec=VECTOR(*attrs)[id]; na=(igraph_vector_t*)rec->value; if (igraph_vector_size(na) == vid) { IGRAPH_CHECK(igraph_vector_push_back(na, number)); } else if (igraph_vector_size(na) < vid) { long int origsize=igraph_vector_size(na); IGRAPH_CHECK(igraph_vector_resize(na, (long int)vid+1)); for (;origsizename=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_STRING; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); } rec=VECTOR(*attrs)[id]; na=(igraph_strvector_t*)rec->value; if (igraph_strvector_size(na) <= vid) { long int origsize=igraph_strvector_size(na); IGRAPH_CHECK(igraph_strvector_resize(na, vid+1)); for (;origsizevertex_attribute_names, context->vertex_attributes, context->vcount, name, context->actvertex-1, tmp); igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return ret; } int igraph_i_pajek_add_string_edge_attribute(const char *name, const char *value, int len, igraph_i_pajek_parsedata_t *context) { char *tmp; int ret; tmp=igraph_Calloc(len+1, char); if (tmp==0) { IGRAPH_ERROR("cannot add element to hash table", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, tmp); strncpy(tmp, value, len); tmp[len]='\0'; ret=igraph_i_pajek_add_string_attribute(context->edge_attribute_names, context->edge_attributes, context->actedge, name, context->actedge-1, tmp); igraph_Free(tmp); IGRAPH_FINALLY_CLEAN(1); return ret; } int igraph_i_pajek_add_numeric_vertex_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context) { return igraph_i_pajek_add_numeric_attribute(context->vertex_attribute_names, context->vertex_attributes, context->vcount, name, context->actvertex-1, value); } int igraph_i_pajek_add_numeric_edge_attribute(const char *name, igraph_real_t value, igraph_i_pajek_parsedata_t *context) { return igraph_i_pajek_add_numeric_attribute(context->edge_attribute_names, context->edge_attributes, context->actedge, name, context->actedge-1, value); } int igraph_i_pajek_add_bipartite_type(igraph_i_pajek_parsedata_t *context) { const char *attrname="type"; igraph_trie_t *names=context->vertex_attribute_names; igraph_vector_ptr_t *attrs=context->vertex_attributes; int i, n=context->vcount, n1=context->vcount2; long int attrid, attrsize=igraph_trie_size(names); igraph_attribute_record_t *rec; igraph_vector_t *na; if (n1 > n) { IGRAPH_ERROR("Invalid number of vertices in bipartite Pajek file", IGRAPH_PARSEERROR); } igraph_trie_get(names, attrname, &attrid); if (attrid != attrsize) { IGRAPH_ERROR("Duplicate 'type' attribute in Pajek file, " "this should not happen", IGRAPH_EINTERNAL); } /* add a new attribute */ rec=igraph_Calloc(1, igraph_attribute_record_t); na=igraph_Calloc(1, igraph_vector_t); igraph_vector_init(na, n); rec->name=strdup(attrname); rec->type=IGRAPH_ATTRIBUTE_NUMERIC; rec->value=na; igraph_vector_ptr_push_back(attrs, rec); for (i=0; ivector; int i, n1=context->vcount2; int ne=igraph_vector_size(edges); for (i=0; i n1 && v2 > n1) ) { IGRAPH_WARNING("Invalid edge in bipartite graph"); } } return 0; } igraph/src/Makevars.win0000644000175100001440000001541613431000472014622 0ustar hornikusers PKG_CPPFLAGS= -I${LIB_XML}/include/libxml2 -I${LIB_XML}/include -DLIBXML_STATIC -DUSING_R -DHAVE_FMEMOPEN=0 -DHAVE_OPEN_MEMSTREAM=0 -DHAVE_RINTF -DWin32 -DHAVE_LIBXML -Wall -DPACKAGE_VERSION=\"1.2.4\" -DHAVE_FMIN=1 -DHAVE_LOG2=1 -DHAVE_SNPRINTF -Ics -I${GLPK_HOME}/include -DHAVE_GLPK=1 -Iplfit -Iprpack -DIGRAPH_THREAD_LOCAL= -DPRPACK_IGRAPH_SUPPORT -I. -Iinclude -ICHOLMOD/Include -IAMD/Include -ICOLAMD/Include -ISuiteSparse_config -DNDEBUG -DNPARTITION -DNTIMER -DNCAMD -DNPRINT -I$(LIB_GMP)/include PKG_CFLAGS = -DINTERNAL_ARPACK -I. -I$(LIB_GMP)/include -DHAVE_GFORTRAN PKG_LIBS = -L${LIB_XML}/lib -lxml2 -liconv -lz -lws2_32 -L${GLPK_HOME}/lib -lglpk -lgmp -L$(LIB_GMP)/lib $(BLAS_LIBS) $(LAPACK_LIBS) OBJECTS=AMD/Source/amd.o AMD/Source/amd_1.o AMD/Source/amd_2.o AMD/Source/amd_aat.o AMD/Source/amd_control.o AMD/Source/amd_defaults.o AMD/Source/amd_dump.o AMD/Source/amd_global.o AMD/Source/amd_info.o AMD/Source/amd_order.o AMD/Source/amd_post_tree.o AMD/Source/amd_postorder.o AMD/Source/amd_preprocess.o AMD/Source/amd_valid.o AMD/Source/amdbar.o CHOLMOD/Check/cholmod_check.o CHOLMOD/Check/cholmod_read.o CHOLMOD/Check/cholmod_write.o CHOLMOD/Cholesky/cholmod_amd.o CHOLMOD/Cholesky/cholmod_analyze.o CHOLMOD/Cholesky/cholmod_colamd.o CHOLMOD/Cholesky/cholmod_etree.o CHOLMOD/Cholesky/cholmod_factorize.o CHOLMOD/Cholesky/cholmod_postorder.o CHOLMOD/Cholesky/cholmod_rcond.o CHOLMOD/Cholesky/cholmod_resymbol.o CHOLMOD/Cholesky/cholmod_rowcolcounts.o CHOLMOD/Cholesky/cholmod_rowfac.o CHOLMOD/Cholesky/cholmod_solve.o CHOLMOD/Cholesky/cholmod_spsolve.o CHOLMOD/Core/cholmod_aat.o CHOLMOD/Core/cholmod_add.o CHOLMOD/Core/cholmod_band.o CHOLMOD/Core/cholmod_change_factor.o CHOLMOD/Core/cholmod_common.o CHOLMOD/Core/cholmod_complex.o CHOLMOD/Core/cholmod_copy.o CHOLMOD/Core/cholmod_dense.o CHOLMOD/Core/cholmod_error.o CHOLMOD/Core/cholmod_factor.o CHOLMOD/Core/cholmod_memory.o CHOLMOD/Core/cholmod_sparse.o CHOLMOD/Core/cholmod_transpose.o CHOLMOD/Core/cholmod_triplet.o CHOLMOD/Core/cholmod_version.o CHOLMOD/MatrixOps/cholmod_drop.o CHOLMOD/MatrixOps/cholmod_horzcat.o CHOLMOD/MatrixOps/cholmod_norm.o CHOLMOD/MatrixOps/cholmod_scale.o CHOLMOD/MatrixOps/cholmod_sdmult.o CHOLMOD/MatrixOps/cholmod_ssmult.o CHOLMOD/MatrixOps/cholmod_submatrix.o CHOLMOD/MatrixOps/cholmod_symmetry.o CHOLMOD/MatrixOps/cholmod_vertcat.o CHOLMOD/Modify/cholmod_rowadd.o CHOLMOD/Modify/cholmod_rowdel.o CHOLMOD/Modify/cholmod_updown.o CHOLMOD/Partition/cholmod_camd.o CHOLMOD/Partition/cholmod_ccolamd.o CHOLMOD/Partition/cholmod_csymamd.o CHOLMOD/Partition/cholmod_metis.o CHOLMOD/Partition/cholmod_nesdis.o CHOLMOD/Supernodal/cholmod_super_numeric.o CHOLMOD/Supernodal/cholmod_super_solve.o CHOLMOD/Supernodal/cholmod_super_symbolic.o COLAMD/Source/colamd.o COLAMD/Source/colamd_global.o DensityGrid.o DensityGrid_3d.o NetDataTypes.o NetRoutines.o SuiteSparse_config/SuiteSparse_config.o adjlist.o arpack.o array.o atlas.o attributes.o basic_query.o bfgs.o bigint.o bignum.o bipartite.o blas.o bliss.o bliss/bliss_heap.o bliss/defs.o bliss/graph.o bliss/orbit.o bliss/partition.o bliss/uintseqhash.o bliss/utils.o cattributes.o centrality.o cliquer/cliquer.o cliquer/cliquer_graph.o cliquer/reorder.o cliques.o clustertool.o cocitation.o cohesive_blocks.o coloring.o community.o complex.o components.o conversion.o cores.o cs/cs_add.o cs/cs_amd.o cs/cs_chol.o cs/cs_cholsol.o cs/cs_compress.o cs/cs_counts.o cs/cs_cumsum.o cs/cs_dfs.o cs/cs_dmperm.o cs/cs_droptol.o cs/cs_dropzeros.o cs/cs_dupl.o cs/cs_entry.o cs/cs_ereach.o cs/cs_etree.o cs/cs_fkeep.o cs/cs_gaxpy.o cs/cs_happly.o cs/cs_house.o cs/cs_ipvec.o cs/cs_leaf.o cs/cs_load.o cs/cs_lsolve.o cs/cs_ltsolve.o cs/cs_lu.o cs/cs_lusol.o cs/cs_malloc.o cs/cs_maxtrans.o cs/cs_multiply.o cs/cs_norm.o cs/cs_permute.o cs/cs_pinv.o cs/cs_post.o cs/cs_print.o cs/cs_pvec.o cs/cs_qr.o cs/cs_qrsol.o cs/cs_randperm.o cs/cs_reach.o cs/cs_scatter.o cs/cs_scc.o cs/cs_schol.o cs/cs_spsolve.o cs/cs_sqr.o cs/cs_symperm.o cs/cs_tdfs.o cs/cs_transpose.o cs/cs_updown.o cs/cs_usolve.o cs/cs_util.o cs/cs_utsolve.o decomposition.o distances.o dotproduct.o dqueue.o drl_graph.o drl_graph_3d.o drl_layout.o drl_layout_3d.o drl_parse.o eigen.o embedding.o fast_community.o feedback_arc_set.o flow.o foreign-dl-lexer.o foreign-dl-parser.o foreign-gml-lexer.o foreign-gml-parser.o foreign-graphml.o foreign-lgl-lexer.o foreign-lgl-parser.o foreign-ncol-lexer.o foreign-ncol-parser.o foreign-pajek-lexer.o foreign-pajek-parser.o foreign.o forestfire.o fortran_intrinsics.o games.o gengraph_box_list.o gengraph_degree_sequence.o gengraph_graph_molloy_hash.o gengraph_graph_molloy_optimized.o gengraph_mr-connected.o gengraph_powerlaw.o gengraph_random.o glet.o glpk_support.o gml_tree.o hacks.o heap.o igraph_buckets.o igraph_cliquer.o igraph_error.o igraph_estack.o igraph_fixed_vectorlist.o igraph_grid.o igraph_hashtable.o igraph_heap.o igraph_hrg.o igraph_hrg_types.o igraph_marked_queue.o igraph_psumtree.o igraph_set.o igraph_stack.o igraph_strvector.o igraph_trie.o infomap.o infomap_FlowGraph.o infomap_Greedy.o infomap_Node.o interrupt.o iterators.o lad.o lapack.o layout.o layout_dh.o layout_fr.o layout_gem.o layout_kk.o lsap.o matching.o math.o matrix.o maximal_cliques.o memory.o microscopic_update.o mixing.o motifs.o operators.o optimal_modularity.o other.o paths.o plfit/error.o plfit/gss.o plfit/kolmogorov.o plfit/lbfgs.o plfit/options.o plfit/plfit.o plfit/zeta.o pottsmodel_2.o progress.o prpack.o prpack/prpack_base_graph.o prpack/prpack_igraph_graph.o prpack/prpack_preprocessed_ge_graph.o prpack/prpack_preprocessed_gs_graph.o prpack/prpack_preprocessed_scc_graph.o prpack/prpack_preprocessed_schur_graph.o prpack/prpack_result.o prpack/prpack_solver.o prpack/prpack_utils.o qsort.o qsort_r.o random.o random_walk.o sbm.o scan.o scg.o scg_approximate_methods.o scg_exact_scg.o scg_kmeans.o scg_optimal_method.o scg_utils.o separators.o sir.o spanning_trees.o sparsemat.o spectral_properties.o spmatrix.o st-cuts.o statusbar.o structural_properties.o structure_generators.o sugiyama.o topology.o triangles.o type_indexededgelist.o types.o vector.o vector_ptr.o version.o visitors.o walktrap.o walktrap_communities.o walktrap_graph.o walktrap_heap.o zeroin.o dgetv0.o dlaqrb.o dmout.o dnaitr.o dnapps.o dnaup2.o dnaupd.o dnconv.o dneigh.o dneupd.o dngets.o dsaitr.o dsapps.o dsaup2.o dsaupd.o dsconv.o dseigt.o dsesrt.o dseupd.o dsgets.o dsortc.o dsortr.o dstatn.o dstats.o dstqrb.o dvout.o ivout.o second.o simpleraytracer/Color.o simpleraytracer/Light.o simpleraytracer/Point.o simpleraytracer/RIgraphRay.o simpleraytracer/Ray.o simpleraytracer/RayTracer.o simpleraytracer/RayVector.o simpleraytracer/Shape.o simpleraytracer/Sphere.o simpleraytracer/Triangle.o simpleraytracer/unit_limiter.o uuid/R.o uuid/clear.o uuid/compare.o uuid/copy.o uuid/gen_uuid.o uuid/isnull.o uuid/pack.o uuid/parse.o uuid/unpack.o uuid/unparse.o rinterface.o rinterface_extra.o lazyeval.o igraph/src/scan.c0000644000175100001440000006504613431000472013426 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_scan.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" #include "igraph_arpack.h" #include "igraph_eigen.h" #include "igraph_centrality.h" #include "igraph_operators.h" #include "igraph_dqueue.h" #include "igraph_stack.h" /** * \function igraph_local_scan_0 * Local scan-statistics, k=0 * * K=0 scan-statistics is arbitrarily defined as the vertex degree for * unweighted, and the vertex strength for weighted graphs. See \ref * igraph_degree() and \ref igraph_strength(). * * \param graph The input graph * \param res An initialized vector, the results are stored here. * \param weights Weight vector for weighted graphs, null pointer for * unweighted graphs. * \param mode Type of the neighborhood, \c IGRAPH_OUT means outgoing, * \c IGRAPH_IN means incoming and \c IGRAPH_ALL means all edges. * \return Error code. * */ int igraph_local_scan_0(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode) { if (weights) { igraph_strength(graph, res, igraph_vss_all(), mode, /*loops=*/ 1, weights); } else { igraph_degree(graph, res, igraph_vss_all(), mode, /*loops=*/ 1); } return 0; } /* From triangles.c */ int igraph_i_trans4_al_simplify(igraph_adjlist_t *al, const igraph_vector_int_t *rank); /* This removes loop, multiple edges and edges that point "backwards" according to the rank vector. It works on edge lists */ int igraph_i_trans4_il_simplify(const igraph_t *graph, igraph_inclist_t *il, const igraph_vector_int_t *rank) { long int i; long int n=il->length; igraph_vector_int_t mark; igraph_vector_int_init(&mark, n); IGRAPH_FINALLY(igraph_vector_int_destroy, &mark); for (i=0; iincs[i]; int j, l=igraph_vector_int_size(v); int irank=VECTOR(*rank)[i]; VECTOR(mark)[i] = i+1; for (j=0; j irank && VECTOR(mark)[e] != i+1) { VECTOR(mark)[e]=i+1; j++; } else { VECTOR(*v)[j] = igraph_vector_int_tail(v); igraph_vector_int_pop_back(v); l--; } } } igraph_vector_int_destroy(&mark); IGRAPH_FINALLY_CLEAN(1); return 0; } /* This one handles both weighted and unweighted cases */ int igraph_i_local_scan_1_directed(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, igraph_neimode_t mode) { int no_of_nodes=igraph_vcount(graph); igraph_inclist_t incs; int i, node; igraph_vector_int_t neis; IGRAPH_CHECK(igraph_inclist_init(graph, &incs, mode)); IGRAPH_FINALLY(igraph_inclist_destroy, &incs); igraph_vector_int_init(&neis, no_of_nodes); IGRAPH_FINALLY(igraph_vector_int_destroy, &neis); igraph_vector_resize(res, no_of_nodes); igraph_vector_null(res); for (node=0; node < no_of_nodes; node++) { igraph_vector_int_t *edges1=igraph_inclist_get(&incs, node); int edgeslen1=igraph_vector_int_size(edges1); IGRAPH_ALLOW_INTERRUPTION(); /* Mark neighbors and self*/ VECTOR(neis)[node] = node+1; for (i=0; i=0; nn--) { node=VECTOR(order)[nn]; IGRAPH_ALLOW_INTERRUPTION(); neis1=igraph_inclist_get(&allinc, node); neilen1=igraph_vector_int_size(neis1); /* Mark the neighbors of the node */ for (i=0; iigraph_vector_int_t * objects, the neighborhoods, one for each vertex in the * graph. * \return Error code. */ int igraph_local_scan_neighborhood_ecount(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *weights, const igraph_vector_ptr_t *neighborhoods) { int node, no_of_nodes=igraph_vcount(graph); igraph_inclist_t incs; igraph_vector_int_t marked; igraph_bool_t directed=igraph_is_directed(graph); if (weights && igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length in local scan", IGRAPH_EINVAL); } if (igraph_vector_ptr_size(neighborhoods) != no_of_nodes) { IGRAPH_ERROR("Invalid neighborhood list length in local scan", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_int_init(&marked, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &marked); IGRAPH_CHECK(igraph_inclist_init(graph, &incs, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &incs); IGRAPH_CHECK(igraph_vector_resize(res, no_of_nodes)); igraph_vector_null(res); for (node=0; node < no_of_nodes; node++) { igraph_vector_int_t *nei=VECTOR(*neighborhoods)[node]; int i, neilen=igraph_vector_int_size(nei); VECTOR(marked)[node] = node + 1; for (i=0; i= no_of_nodes) { IGRAPH_ERROR("Invalid vertex id in neighborhood list in local scan", IGRAPH_EINVAL); } VECTOR(marked)[vertex] = node + 1; } for (i=0; i standard eigenvalue problem A*x = lambda*x c B = 'G' -> generalized eigenvalue problem A*x = lambda*B*x c c ITRY Integer. (INPUT) c ITRY counts the number of times that igraphdgetv0 is called. c It should be set to 1 on the initial call to igraphdgetv0. c c INITV Logical variable. (INPUT) c .TRUE. => the initial residual vector is given in RESID. c .FALSE. => generate a random initial residual vector. c c N Integer. (INPUT) c Dimension of the problem. c c J Integer. (INPUT) c Index of the residual vector to be generated, with respect to c the Arnoldi process. J > 1 in case of a "restart". c c V Double precision N by J array. (INPUT) c The first J-1 columns of V contain the current Arnoldi basis c if this is a "restart". c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c RESID Double precision array of length N. (INPUT/OUTPUT) c Initial residual vector to be generated. If RESID is c provided, force RESID into the range of the operator OP. c c RNORM Double precision scalar. (OUTPUT) c B-norm of the generated residual. c c IPNTR Integer array of length 3. (OUTPUT) c c WORKD Double precision work array of length 2*N. (REVERSE COMMUNICATION). c On exit, WORK(1:N) = B*RESID to be used in SSAITR. c c IERR Integer. (OUTPUT) c = 0: Normal exit. c = -1: Cannot generate a nontrivial restarted residual vector c in the range of the operator OP. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c c\Routines called: c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine for vector output. c dlarnv LAPACK routine for generating a random vector. c dgemv Level 2 BLAS routine for matrix vector multiplication. c dcopy Level 1 BLAS that copies one vector to another. c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: getv0.F SID: 2.6 DATE OF SID: 8/27/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdgetv0 & ( ido, bmat, itry, initv, n, j, v, ldv, resid, rnorm, & ipntr, workd, ierr ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1 logical initv integer ido, ierr, itry, j, ldv, n Double precision & rnorm c c %-----------------% c | Array Arguments | c %-----------------% c integer ipntr(3) Double precision & resid(n), v(ldv,j), workd(2*n) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %------------------------% c | Local Scalars & Arrays | c %------------------------% c logical first, inits, orth integer idist, iseed(4), iter, msglvl, jj Double precision & rnorm0 save first, iseed, inits, iter, msglvl, orth, rnorm0 c c %----------------------% c | External Subroutines | c %----------------------% c external dlarnv, igraphdvout, dcopy, dgemv, igraphsecond c c %--------------------% c | External Functions | c %--------------------% c Double precision & ddot, dnrm2 external ddot, dnrm2 c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic abs, sqrt c c %-----------------% c | Data Statements | c %-----------------% c data inits /.true./ c c %-----------------------% c | Executable Statements | c %-----------------------% c c c %-----------------------------------% c | Initialize the seed of the LAPACK | c | random number generator | c %-----------------------------------% c if (inits) then iseed(1) = 1 iseed(2) = 3 iseed(3) = 5 iseed(4) = 7 inits = .false. end if c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = mgetv0 c ierr = 0 iter = 0 first = .FALSE. orth = .FALSE. c c %-----------------------------------------------------% c | Possibly generate a random starting vector in RESID | c | Use a LAPACK random number generator used by the | c | matrix generation routines. | c | idist = 1: uniform (0,1) distribution; | c | idist = 2: uniform (-1,1) distribution; | c | idist = 3: normal (0,1) distribution; | c %-----------------------------------------------------% c if (.not.initv) then idist = 2 call dlarnv (idist, iseed, n, resid) end if c c %----------------------------------------------------------% c | Force the starting vector into the range of OP to handle | c | the generalized problem when B is possibly (singular). | c %----------------------------------------------------------% c call igraphsecond (t2) if (bmat .eq. 'G') then nopx = nopx + 1 ipntr(1) = 1 ipntr(2) = n + 1 call dcopy (n, resid, 1, workd, 1) ido = -1 go to 9000 end if end if c c %-----------------------------------------% c | Back from computing OP*(initial-vector) | c %-----------------------------------------% c if (first) go to 20 c c %-----------------------------------------------% c | Back from computing B*(orthogonalized-vector) | c %-----------------------------------------------% c if (orth) go to 40 c if (bmat .eq. 'G') then call igraphsecond (t3) tmvopx = tmvopx + (t3 - t2) end if c c %------------------------------------------------------% c | Starting vector is now in the range of OP; r = OP*r; | c | Compute B-norm of starting vector. | c %------------------------------------------------------% c call igraphsecond (t2) first = .TRUE. if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, workd(n+1), 1, resid, 1) ipntr(1) = n + 1 ipntr(2) = 1 ido = 2 go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd, 1) end if c 20 continue c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c first = .FALSE. if (bmat .eq. 'G') then rnorm0 = ddot (n, resid, 1, workd, 1) rnorm0 = sqrt(abs(rnorm0)) else if (bmat .eq. 'I') then rnorm0 = dnrm2(n, resid, 1) end if rnorm = rnorm0 c c %---------------------------------------------% c | Exit if this is the very first Arnoldi step | c %---------------------------------------------% c if (j .eq. 1) go to 50 c c %---------------------------------------------------------------- c | Otherwise need to B-orthogonalize the starting vector against | c | the current Arnoldi basis using Gram-Schmidt with iter. ref. | c | This is the case where an invariant subspace is encountered | c | in the middle of the Arnoldi factorization. | c | | c | s = V^{T}*B*r; r = r - V*s; | c | | c | Stopping criteria used for iter. ref. is discussed in | c | Parlett's book, page 107 and in Gragg & Reichel TOMS paper. | c %---------------------------------------------------------------% c orth = .TRUE. 30 continue c call dgemv ('T', n, j-1, one, v, ldv, workd, 1, & zero, workd(n+1), 1) call dgemv ('N', n, j-1, -one, v, ldv, workd(n+1), 1, & one, resid, 1) c c %----------------------------------------------------------% c | Compute the B-norm of the orthogonalized starting vector | c %----------------------------------------------------------% c call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(n+1), 1) ipntr(1) = n + 1 ipntr(2) = 1 ido = 2 go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd, 1) end if c 40 continue c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c if (bmat .eq. 'G') then rnorm = ddot (n, resid, 1, workd, 1) rnorm = sqrt(abs(rnorm)) else if (bmat .eq. 'I') then rnorm = dnrm2(n, resid, 1) end if c c %--------------------------------------% c | Check for further orthogonalization. | c %--------------------------------------% c if (msglvl .gt. 2) then call igraphdvout (logfil, 1, rnorm0, ndigit, & '_getv0: re-orthonalization ; rnorm0 is') call igraphdvout (logfil, 1, rnorm, ndigit, & '_getv0: re-orthonalization ; rnorm is') end if c if (rnorm .gt. 0.717*rnorm0) go to 50 c iter = iter + 1 if (iter .le. 1) then c c %-----------------------------------% c | Perform iterative refinement step | c %-----------------------------------% c rnorm0 = rnorm go to 30 else c c %------------------------------------% c | Iterative refinement step "failed" | c %------------------------------------% c do 45 jj = 1, n resid(jj) = zero 45 continue rnorm = zero ierr = -1 end if c 50 continue c if (msglvl .gt. 0) then call igraphdvout (logfil, 1, rnorm, ndigit, & '_getv0: B-norm of initial / restarted starting vector') end if if (msglvl .gt. 2) then call igraphdvout (logfil, n, resid, ndigit, & '_getv0: initial / restarted starting vector') end if ido = 99 c call igraphsecond (t1) tgetv0 = tgetv0 + (t1 - t0) c 9000 continue return c c %---------------% c | End of igraphdgetv0 | c %---------------% c end igraph/src/layout_fr.c0000644000175100001440000005752013431000472014504 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_layout.h" #include "igraph_random.h" #include "igraph_interface.h" #include "igraph_components.h" #include "igraph_types_internal.h" int igraph_layout_i_fr(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_integer_t no_edges=igraph_ecount(graph); igraph_integer_t i; igraph_vector_float_t dispx, dispy; igraph_real_t temp=start_temp; igraph_real_t difftemp=start_temp / niter; float width=sqrtf(no_nodes), height=width; igraph_bool_t conn=1; float C; igraph_is_connected(graph, &conn, IGRAPH_WEAK); if (!conn) { C = no_nodes * sqrtf(no_nodes); } RNG_BEGIN(); if (!use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 2)); for (i=0; i 0) { MATRIX(*res, v, 0) += (dx / displen) * mx; MATRIX(*res, v, 1) += (dy / displen) * my; } if (minx && MATRIX(*res, v, 0) < VECTOR(*minx)[v]) { MATRIX(*res, v, 0) = VECTOR(*minx)[v]; } if (maxx && MATRIX(*res, v, 0) > VECTOR(*maxx)[v]) { MATRIX(*res, v, 0) = VECTOR(*maxx)[v]; } if (miny && MATRIX(*res, v, 1) < VECTOR(*miny)[v]) { MATRIX(*res, v, 1) = VECTOR(*miny)[v]; } if (maxy && MATRIX(*res, v, 1) > VECTOR(*maxy)[v]) { MATRIX(*res, v, 1) = VECTOR(*maxy)[v]; } } temp -= difftemp; } RNG_END(); igraph_vector_float_destroy(&dispx); igraph_vector_float_destroy(&dispy); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_layout_i_grid_fr(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_integer_t no_edges=igraph_ecount(graph); float width=sqrtf(no_nodes), height=width; igraph_2dgrid_t grid; igraph_vector_float_t dispx, dispy; igraph_real_t temp=start_temp; igraph_real_t difftemp=start_temp / niter; igraph_2dgrid_iterator_t vidit; igraph_integer_t i; const float cellsize=2.0; RNG_BEGIN(); if (!use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 2)); for (i=0; i 0) { MATRIX(*res, v, 0) += (dx / displen) * mx; MATRIX(*res, v, 1) += (dy / displen) * my; } if (minx && MATRIX(*res, v, 0) < VECTOR(*minx)[v]) { MATRIX(*res, v, 0) = VECTOR(*minx)[v]; } if (maxx && MATRIX(*res, v, 0) > VECTOR(*maxx)[v]) { MATRIX(*res, v, 0) = VECTOR(*maxx)[v]; } if (miny && MATRIX(*res, v, 1) < VECTOR(*miny)[v]) { MATRIX(*res, v, 1) = VECTOR(*miny)[v]; } if (maxy && MATRIX(*res, v, 1) > VECTOR(*maxy)[v]) { MATRIX(*res, v, 1) = VECTOR(*maxy)[v]; } } temp -= difftemp; } igraph_vector_float_destroy(&dispx); igraph_vector_float_destroy(&dispy); igraph_2dgrid_destroy(&grid); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup layout * \function igraph_layout_fruchterman_reingold * \brief Places the vertices on a plane according to the Fruchterman-Reingold algorithm. * * * This is a force-directed layout, see Fruchterman, T.M.J. and * Reingold, E.M.: Graph Drawing by Force-directed Placement. * Software -- Practice and Experience, 21/11, 1129--1164, * 1991. * \param graph Pointer to an initialized graph object. * \param res Pointer to an initialized matrix object. This will * contain the result and will be resized as needed. * \param use_seed Logical, if true the supplied values in the * \p res argument are used as an initial layout, if * false a random initial layout is used. * \param niter The number of iterations to do. A reasonable * default value is 500. * \param start_temp Start temperature. This is the maximum amount * of movement alloved along one axis, within one step, for a * vertex. Currently it is decreased linearly to zero during * the iteration. * \param grid Whether to use the (fast but less accurate) grid based * version of the algorithm. Possible values: \c * IGRAPH_LAYOUT_GRID, \c IGRAPH_LAYOUT_NOGRID, \c * IGRAPH_LAYOUT_AUTOGRID. The last one uses the grid based * version only for large graphs, currently the ones with * more than 1000 vertices. * \param weight Pointer to a vector containing edge weights, * the attraction along the edges will be multiplied by these. * It will be ignored if it is a null-pointer. * \param minx Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote x \endquote coordinate for every vertex. * \param maxx Same as \p minx, but the maximum \quote x \endquote * coordinates. * \param miny Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote y \endquote coordinate for every vertex. * \param maxy Same as \p miny, but the maximum \quote y \endquote * coordinates. * \return Error code. * * Time complexity: O(|V|^2) in each * iteration, |V| is the number of * vertices in the graph. */ int igraph_layout_fruchterman_reingold(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, igraph_layout_grid_t grid, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy) { igraph_integer_t no_nodes=igraph_vcount(graph); if (niter < 0) { IGRAPH_ERROR("Number of iterations must be non-negative in " "Fruchterman-Reingold layout", IGRAPH_EINVAL); } if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 2)) { IGRAPH_ERROR("Invalid start position matrix size in " "Fruchterman-Reingold layout", IGRAPH_EINVAL); } if (weight && igraph_vector_size(weight) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (minx && igraph_vector_size(minx) != no_nodes) { IGRAPH_ERROR("Invalid minx vector length", IGRAPH_EINVAL); } if (maxx && igraph_vector_size(maxx) != no_nodes) { IGRAPH_ERROR("Invalid maxx vector length", IGRAPH_EINVAL); } if (minx && maxx && !igraph_vector_all_le(minx, maxx)) { IGRAPH_ERROR("minx must not be greater than maxx", IGRAPH_EINVAL); } if (miny && igraph_vector_size(miny) != no_nodes) { IGRAPH_ERROR("Invalid miny vector length", IGRAPH_EINVAL); } if (maxy && igraph_vector_size(maxy) != no_nodes) { IGRAPH_ERROR("Invalid maxy vector length", IGRAPH_EINVAL); } if (miny && maxy && !igraph_vector_all_le(miny, maxy)) { IGRAPH_ERROR("miny must not be greater than maxy", IGRAPH_EINVAL); } if (grid == IGRAPH_LAYOUT_AUTOGRID) { if (no_nodes > 1000) { grid = IGRAPH_LAYOUT_GRID; } else { grid = IGRAPH_LAYOUT_NOGRID; } } if (grid == IGRAPH_LAYOUT_GRID) { return igraph_layout_i_grid_fr(graph, res, use_seed, niter, start_temp, weight, minx, maxx, miny, maxy); } else { return igraph_layout_i_fr(graph, res, use_seed, niter, start_temp, weight, minx, maxx, miny, maxy); } } /** * \function igraph_layout_fruchterman_reingold_3d * \brief 3D Fruchterman-Reingold algorithm. * * This is the 3D version of the force based * Fruchterman-Reingold layout (see \ref * igraph_layout_fruchterman_reingold for the 2D version * * \param graph Pointer to an initialized graph object. * \param res Pointer to an initialized matrix object. This will * contain the result and will be resized as needed. * \param use_seed Logical, if true the supplied values in the * \p res argument are used as an initial layout, if * false a random initial layout is used. * \param niter The number of iterations to do. A reasonable * default value is 500. * \param start_temp Start temperature. This is the maximum amount * of movement alloved along one axis, within one step, for a * vertex. Currently it is decreased linearly to zero during * the iteration. * \param weight Pointer to a vector containing edge weights, * the attraction along the edges will be multiplied by these. * It will be ignored if it is a null-pointer. * \param minx Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote x \endquote coordinate for every vertex. * \param maxx Same as \p minx, but the maximum \quote x \endquote * coordinates. * \param miny Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote y \endquote coordinate for every vertex. * \param maxy Same as \p miny, but the maximum \quote y \endquote * coordinates. * \param minz Pointer to a vector, or a \c NULL pointer. If not a * \c NULL pointer then the vector gives the minimum * \quote z \endquote coordinate for every vertex. * \param maxz Same as \p minz, but the maximum \quote z \endquote * coordinates. * \return Error code. * * Added in version 0.2. * * Time complexity: O(|V|^2) in each * iteration, |V| is the number of * vertices in the graph. * */ int igraph_layout_fruchterman_reingold_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t niter, igraph_real_t start_temp, const igraph_vector_t *weight, const igraph_vector_t *minx, const igraph_vector_t *maxx, const igraph_vector_t *miny, const igraph_vector_t *maxy, const igraph_vector_t *minz, const igraph_vector_t *maxz) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_integer_t no_edges=igraph_ecount(graph); igraph_integer_t i; igraph_vector_float_t dispx, dispy, dispz; igraph_real_t temp=start_temp; igraph_real_t difftemp=start_temp / niter; float width=sqrtf(no_nodes), height=width, depth=width; igraph_bool_t conn=1; float C; if (niter < 0) { IGRAPH_ERROR("Number of iterations must be non-negative in " "Fruchterman-Reingold layout", IGRAPH_EINVAL); } if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 3)) { IGRAPH_ERROR("Invalid start position matrix size in " "Fruchterman-Reingold layout", IGRAPH_EINVAL); } if (weight && igraph_vector_size(weight) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector length", IGRAPH_EINVAL); } if (minx && igraph_vector_size(minx) != no_nodes) { IGRAPH_ERROR("Invalid minx vector length", IGRAPH_EINVAL); } if (maxx && igraph_vector_size(maxx) != no_nodes) { IGRAPH_ERROR("Invalid maxx vector length", IGRAPH_EINVAL); } if (minx && maxx && !igraph_vector_all_le(minx, maxx)) { IGRAPH_ERROR("minx must not be greater than maxx", IGRAPH_EINVAL); } if (miny && igraph_vector_size(miny) != no_nodes) { IGRAPH_ERROR("Invalid miny vector length", IGRAPH_EINVAL); } if (maxy && igraph_vector_size(maxy) != no_nodes) { IGRAPH_ERROR("Invalid maxy vector length", IGRAPH_EINVAL); } if (miny && maxy && !igraph_vector_all_le(miny, maxy)) { IGRAPH_ERROR("miny must not be greater than maxy", IGRAPH_EINVAL); } if (minz && igraph_vector_size(minz) != no_nodes) { IGRAPH_ERROR("Invalid minz vector length", IGRAPH_EINVAL); } if (maxz && igraph_vector_size(maxz) != no_nodes) { IGRAPH_ERROR("Invalid maxz vector length", IGRAPH_EINVAL); } if (minz && maxz && !igraph_vector_all_le(minz, maxz)) { IGRAPH_ERROR("minz must not be greater than maxz", IGRAPH_EINVAL); } igraph_is_connected(graph, &conn, IGRAPH_WEAK); if (!conn) { C = no_nodes * sqrtf(no_nodes); } RNG_BEGIN(); if (!use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 3)); for (i=0; i 0) { MATRIX(*res, v, 0) += (dx / displen) * mx; MATRIX(*res, v, 1) += (dy / displen) * my; MATRIX(*res, v, 2) += (dz / displen) * mz; } if (minx && MATRIX(*res, v, 0) < VECTOR(*minx)[v]) { MATRIX(*res, v, 0) = VECTOR(*minx)[v]; } if (maxx && MATRIX(*res, v, 0) > VECTOR(*maxx)[v]) { MATRIX(*res, v, 0) = VECTOR(*maxx)[v]; } if (miny && MATRIX(*res, v, 1) < VECTOR(*miny)[v]) { MATRIX(*res, v, 1) = VECTOR(*miny)[v]; } if (maxy && MATRIX(*res, v, 1) > VECTOR(*maxy)[v]) { MATRIX(*res, v, 1) = VECTOR(*maxy)[v]; } if (minz && MATRIX(*res, v, 2) < VECTOR(*minz)[v]) { MATRIX(*res, v, 2) = VECTOR(*minz)[v]; } if (maxz && MATRIX(*res, v, 2) > VECTOR(*maxz)[v]) { MATRIX(*res, v, 2) = VECTOR(*maxz)[v]; } } temp -= difftemp; } RNG_END(); igraph_vector_float_destroy(&dispx); igraph_vector_float_destroy(&dispy); igraph_vector_float_destroy(&dispz); IGRAPH_FINALLY_CLEAN(3); return 0; } igraph/src/embedding.c0000644000175100001440000010445113431000472014412 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_embedding.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_random.h" #include "igraph_centrality.h" #include "igraph_blas.h" typedef struct { const igraph_t *graph; const igraph_vector_t *cvec; const igraph_vector_t *cvec2; igraph_adjlist_t *outlist, *inlist; igraph_inclist_t *eoutlist, *einlist; igraph_vector_t *tmp; const igraph_vector_t *weights; } igraph_i_asembedding_data_t; /* Adjacency matrix, unweighted, undirected. Eigendecomposition is used */ int igraph_i_asembeddingu(igraph_real_t *to, const igraph_real_t *from, int n, void *extra) { igraph_i_asembedding_data_t *data=extra; igraph_adjlist_t *outlist=data->outlist; const igraph_vector_t *cvec=data->cvec; igraph_vector_int_t *neis; int i, j, nlen; /* to = (A+cD) from */ for (i=0; ieoutlist; const igraph_vector_t *cvec=data->cvec; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_int_t *incs; int i, j, nlen; /* to = (A+cD) from */ for (i=0; ioutlist; igraph_adjlist_t *inlist=data->inlist; const igraph_vector_t *cvec=data->cvec; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* tmp = (A+cD)' from */ for (i=0; iinlist; const igraph_vector_t *cvec=data->cvec; igraph_vector_int_t *neis; int i, j, nlen; /* to = (A+cD)' from */ for (i=0; ieoutlist; igraph_inclist_t *inlist=data->einlist; const igraph_vector_t *cvec=data->cvec; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *incs; int i, j, nlen; /* tmp = (A+cD)' from */ for (i=0; ieinlist; const igraph_vector_t *cvec=data->cvec; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_int_t *incs; int i, j, nlen; /* to = (A+cD)' from */ for (i=0; ioutlist; const igraph_vector_t *cvec=data->cvec; igraph_vector_int_t *neis; int i, j, nlen; /* to = (D-A) from */ for (i=0; ieoutlist; const igraph_vector_t *cvec=data->cvec; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_int_t *incs; int i, j, nlen; /* to = (D-A) from */ for (i=0; ioutlist; const igraph_vector_t *cvec=data->cvec; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* to = D^1/2 from */ for (i=0; ieoutlist; const igraph_vector_t *cvec=data->cvec; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *incs; int i, j, nlen; /* to = D^-1/2 from */ for (i=0; ioutlist; igraph_adjlist_t *inlist=data->inlist; const igraph_vector_t *deg_in=data->cvec; const igraph_vector_t *deg_out=data->cvec2; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* tmp = O' from */ for (i=0; iinlist; const igraph_vector_t *deg_in=data->cvec; const igraph_vector_t *deg_out=data->cvec2; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* to = O' from */ for (i=0; ieoutlist; igraph_inclist_t *inlist=data->einlist; const igraph_vector_t *deg_in=data->cvec; const igraph_vector_t *deg_out=data->cvec2; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* tmp = O' from */ for (i=0; ieinlist; const igraph_vector_t *deg_in=data->cvec; const igraph_vector_t *deg_out=data->cvec2; const igraph_vector_t *weights=data->weights; const igraph_t *graph=data->graph; igraph_vector_t *tmp=data->tmp; igraph_vector_int_t *neis; int i, j, nlen; /* to = O' from */ for (i=0; i vc) { IGRAPH_ERROR("Too many singular values requested", IGRAPH_EINVAL); } if (no <= 0) { IGRAPH_ERROR("No singular values requested", IGRAPH_EINVAL); } if (cveclen != 1 && cveclen != vc) { IGRAPH_ERROR("Augmentation vector size is invalid, it should be " "the number of vertices or scalar", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_matrix_resize(X, vc, no)); if (Y) { IGRAPH_CHECK(igraph_matrix_resize(Y, vc, no)); } /* empty graph */ if (igraph_ecount(graph) == 0) { igraph_matrix_null(X); if (Y) { igraph_matrix_null(Y); } return 0; } igraph_vector_init(&tmp, vc); IGRAPH_FINALLY(igraph_vector_destroy, &tmp); if (!weights) { IGRAPH_CHECK(igraph_adjlist_init(graph, &outlist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &outlist); if (!symmetric) { IGRAPH_CHECK(igraph_adjlist_init(graph, &inlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &inlist); } } else { IGRAPH_CHECK(igraph_inclist_init(graph, &eoutlist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &eoutlist); if (!symmetric) { IGRAPH_CHECK(igraph_inclist_init(graph, &einlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_inclist_destroy, &einlist); } } IGRAPH_VECTOR_INIT_FINALLY(&tmpD, no); options->n=vc; options->start=0; /* random start vector */ options->nev=no; switch (which) { case IGRAPH_EIGEN_LM: options->which[0]='L'; options->which[1]='M'; break; case IGRAPH_EIGEN_LA: options->which[0]='L'; options->which[1]='A'; break; case IGRAPH_EIGEN_SA: options->which[0]='S'; options->which[1]='A'; break; default: break; } options->ncv = no + 3; if (options->ncv > vc) { options->ncv = vc; } IGRAPH_CHECK(igraph_arpack_rssolve(callback, &data, options, 0, &tmpD, X)); if (!symmetric) { /* calculate left eigenvalues */ IGRAPH_CHECK(igraph_matrix_resize(Y, vc, no)); for (i = 0; i < no; i++) { igraph_real_t norm; igraph_vector_t v; callback_right(&MATRIX(*Y, 0, i), &MATRIX(*X, 0, i), vc, &data); igraph_vector_view(&v, &MATRIX(*Y, 0, i), vc); norm = 1.0 / igraph_blas_dnrm2(&v); igraph_vector_scale(&v, norm); } } else if (Y) { IGRAPH_CHECK(igraph_matrix_update(Y, X)); } if (zapsmall) { igraph_vector_zapsmall(&tmpD, 0); igraph_matrix_zapsmall(X, 0); if (Y) { igraph_matrix_zapsmall(Y, 0); } } if (D) { igraph_vector_update(D, &tmpD); if (!eigen) { for (i=0; i * For undirected graphs the latent positions are calculated as * X=U^no D^(1/2) where U^no equals to the first no columns of U, and * D^(1/2) is a diagonal matrix containing the square root of the selected * singular values on the diagonal. * * * For directed graphs the embedding is defined as the pair * X=U^no D^(1/2), Y=V^no D^(1/2). (For undirected graphs U=V, * so it is enough to keep one of them.) * * \param graph The input graph, can be directed or undirected. * \param no An integer scalar. This value is the embedding dimension of * the spectral embedding. Should be smaller than the number of * vertices. The largest no-dimensional non-zero * singular values are used for the spectral embedding. * \param weights Optional edge weights. Supply a null pointer for * unweighted graphs. * \param which Which eigenvalues (or singular values, for directed * graphs) to use, possible values: * IGRAPH_EIGEN_LM: the ones with the largest magnitude, * IGRAPH_EIGEN_LA: the (algebraic) largest ones, or * IGRAPH_EIGEN_SA: the (algebraic) smallest ones. * For directed graphs, IGRAPH_EIGEN_LM and * IGRAPH_EIGEN_LA are the same, because singular * values are used for the orderinf instead of eigenvalues. * \param scaled Whether to return X and Y (if scaled is non-zero), or * U and V. * \param X Initialized matrix, the estimated latent positions are * stored here. * \param Y Initialized matrix or a null pointer. If not a null * pointer, then the second half of the latent positions are * stored here. (For undirected graphs, this always equals X.) * \param D Initialized vector or a null pointer. If not a null * pointer, then the eigenvalues (for undirected graphs) or the * singular values (for directed graphs) are stored here. * \param cvec A numeric vector, its length is the number vertices in the * graph. This vector is added to the diagonal of the adjacency * matrix, before performing the SVD. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices), nev and * which parameters and it always starts the * calculation from a random start vector. * \return Error code. * */ int igraph_adjacency_spectral_embedding(const igraph_t *graph, igraph_integer_t no, const igraph_vector_t *weights, igraph_eigen_which_position_t which, igraph_bool_t scaled, igraph_matrix_t *X, igraph_matrix_t *Y, igraph_vector_t *D, const igraph_vector_t *cvec, igraph_arpack_options_t *options) { igraph_arpack_function_t *callback, *callback_right; igraph_bool_t directed=igraph_is_directed(graph); if (directed) { callback = weights ? igraph_i_asembeddingw : igraph_i_asembedding; callback_right = (weights ? igraph_i_asembeddingw_right : igraph_i_asembedding_right); } else { callback = weights ? igraph_i_asembeddinguw : igraph_i_asembeddingu; callback_right = 0; } return igraph_i_spectral_embedding(graph, no, weights, which, scaled, X, Y, D, cvec, /* deg2=*/ 0, options, callback, callback_right, /*symmetric=*/ !directed, /*eigen=*/ !directed, /*zapsmall=*/ 1); } int igraph_i_lse_und(const igraph_t *graph, igraph_integer_t no, const igraph_vector_t *weights, igraph_eigen_which_position_t which, igraph_neimode_t degmode, igraph_laplacian_spectral_embedding_type_t type, igraph_bool_t scaled, igraph_matrix_t *X, igraph_matrix_t *Y, igraph_vector_t *D, igraph_arpack_options_t *options) { igraph_arpack_function_t *callback; igraph_vector_t deg; switch (type) { case IGRAPH_EMBEDDING_D_A: callback = weights ? igraph_i_lsembedding_daw : igraph_i_lsembedding_da; break; case IGRAPH_EMBEDDING_DAD: callback = weights ? igraph_i_lsembedding_dadw : igraph_i_lsembedding_dad; break; case IGRAPH_EMBEDDING_I_DAD: callback = weights ? igraph_i_lsembedding_idadw : igraph_i_lsembedding_idad; break; default: IGRAPH_ERROR("Invalid Laplacian spectral embedding type", IGRAPH_EINVAL); break; } IGRAPH_VECTOR_INIT_FINALLY(°, 0); igraph_strength(graph, °, igraph_vss_all(), IGRAPH_ALL, /*loops=*/ 1, weights); switch (type) { case IGRAPH_EMBEDDING_D_A: break; case IGRAPH_EMBEDDING_DAD: case IGRAPH_EMBEDDING_I_DAD: { int i, n=igraph_vector_size(°); for (i=0; iIGRAPH_EIGEN_LM: the ones with the largest magnitude, * IGRAPH_EIGEN_LA: the (algebraic) largest ones, or * IGRAPH_EIGEN_SA: the (algebraic) smallest ones. * For directed graphs, IGRAPH_EIGEN_LM and * IGRAPH_EIGEN_LA are the same, because singular * values are used for the ordering instead of eigenvalues. * \param type The type of the Laplacian to use. Various definitions * exist for the Laplacian of a graph, and one can choose * between them with this argument. Possible values: * IGRAPH_EMBEDDING_D_A means D - A where D is the * degree matrix and A is the adjacency matrix; * IGRAPH_EMBEDDING_DAD means Di times A times Di, * where Di is the inverse of the square root of the degree matrix; * IGRAPH_EMBEDDING_I_DAD means I - Di A Di, where I * is the identity matrix. * \param scaled Whether to return X and Y (if scaled is non-zero), or * U and V. * \param X Initialized matrix, the estimated latent positions are * stored here. * \param Y Initialized matrix or a null pointer. If not a null * pointer, then the second half of the latent positions are * stored here. (For undirected graphs, this always equals X.) * \param D Initialized vector or a null pointer. If not a null * pointer, then the eigenvalues (for undirected graphs) or the * singular values (for directed graphs) are stored here. * \param options Options to ARPACK. See \ref igraph_arpack_options_t * for details. Note that the function overwrites the * n (number of vertices), nev and * which parameters and it always starts the * calculation from a random start vector. * \return Error code. * * \sa \ref igraph_adjacency_spectral_embedding to embed the adjacency * matrix. */ int igraph_laplacian_spectral_embedding(const igraph_t *graph, igraph_integer_t no, const igraph_vector_t *weights, igraph_eigen_which_position_t which, igraph_neimode_t degmode, igraph_laplacian_spectral_embedding_type_t type, igraph_bool_t scaled, igraph_matrix_t *X, igraph_matrix_t *Y, igraph_vector_t *D, igraph_arpack_options_t *options) { if (igraph_is_directed(graph)) { return igraph_i_lse_dir(graph, no, weights, which, degmode, type, scaled, X, Y, D, options); } else { return igraph_i_lse_und(graph, no, weights, which, degmode, type, scaled, X, Y, D, options); } } /** * \function igraph_dim_select * Dimensionality selection * * Dimensionality selection for singular values using * profile likelihood. * * * The input of the function is a numeric vector which contains * the measure of "importance" for each dimension. * * * For spectral embedding, these are the singular values of the adjacency * matrix. The singular values are assumed to be generated from a * Gaussian mixture distribution with two components that have different * means and same variance. The dimensionality d is chosen to * maximize the likelihood when the d largest singular values are * assigned to one component of the mixture and the rest of the singular * values assigned to the other component. * * * This function can also be used for the general separation problem, * where we assume that the left and the right of the vector are coming * from two Normal distributions, with different means, and we want * to know their border. * * \param sv A numeric vector, the ordered singular values. * \param dim The result is stored here. * \return Error code. * * Time complexity: O(n), n is the number of values in sv. * * \sa \ref igraph_adjacency_spectral_embedding(). */ int igraph_dim_select(const igraph_vector_t *sv, igraph_integer_t *dim) { int i, n=igraph_vector_size(sv); igraph_real_t x, x2, sum1=0.0, sum2=igraph_vector_sum(sv); igraph_real_t sumsq1=0.0, sumsq2=0.0; /* to be set */ igraph_real_t oldmean1, oldmean2, mean1=0.0, mean2=sum2/n; igraph_real_t varsq1=0.0, varsq2=0.0; /* to be set */ igraph_real_t var1, var2, sd, profile, max=IGRAPH_NEGINFINITY; if (n==0) { IGRAPH_ERROR("Need at least one singular value for dimensionality " "selection", IGRAPH_EINVAL); } if (n==1) { *dim=1; return 0; } for (i=0; i max) { max=profile; *dim=n1; } } /* Plus the last case, all elements in one group */ x = VECTOR(*sv)[n-1]; sum1 += x; oldmean1 = mean1; mean1 = sum1 / n; sumsq1 += x * x; varsq1 += (x-oldmean1) * (x-mean1); var1 = varsq1 / (n-1); sd=sqrt(var1); profile= /* - n * log(2.0*M_PI)/2.0 */ /* This is redundant */ - n * log(sd) - (sumsq1 - 2*mean1*sum1 + n*mean1*mean1) / 2.0 / sd / sd; if (profile > max) { max=profile; *dim=n; } return 0; } igraph/src/heap.pmt0000644000175100001440000002165713430770202014001 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include #define PARENT(x) (((x)+1)/2-1) #define LEFTCHILD(x) (((x)+1)*2-1) #define RIGHTCHILD(x) (((x)+1)*2) /** * \ingroup heap * \function igraph_heap_init * \brief Initializes an empty heap object. * * Creates an empty heap, but allocates size for some elements. * \param h Pointer to an uninitialized heap object. * \param alloc_size Number of elements to allocate memory for. * \return Error code. * * Time complexity: O(\p alloc_size), assuming memory allocation is a * linear operation. */ int FUNCTION(igraph_heap,init)(TYPE(igraph_heap)* h, long int alloc_size) { if (alloc_size <= 0 ) { alloc_size=1; } h->stor_begin=igraph_Calloc(alloc_size, BASE); if (h->stor_begin==0) { IGRAPH_ERROR("heap init failed", IGRAPH_ENOMEM); } h->stor_end=h->stor_begin + alloc_size; h->end=h->stor_begin; h->destroy=1; return 0; } /** * \ingroup heap * \function igraph_heap_init_array * \brief Build a heap from an array. * * Initializes a heap object from an array, the heap is also * built of course (constructor). * \param h Pointer to an uninitialized heap object. * \param data Pointer to an array of base data type. * \param len The length of the array at \p data. * \return Error code. * * Time complexity: O(n), the number of elements in the heap. */ int FUNCTION(igraph_heap,init_array)(TYPE(igraph_heap) *h, BASE* data, long int len) { h->stor_begin=igraph_Calloc(len, BASE); if (h->stor_begin==0) { IGRAPH_ERROR("heap init from array failed", IGRAPH_ENOMEM); } h->stor_end=h->stor_begin+len; h->end=h->stor_end; h->destroy=1; memcpy(h->stor_begin, data, (size_t) len*sizeof(igraph_real_t)); FUNCTION(igraph_heap,i_build) (h->stor_begin, h->end-h->stor_begin, 0); return 0; } /** * \ingroup heap * \function igraph_heap_destroy * \brief Destroys an initialized heap object. * * \param h The heap object. * * Time complexity: O(1). */ void FUNCTION(igraph_heap,destroy)(TYPE(igraph_heap)* h) { if (h->destroy) { if (h->stor_begin != 0) { igraph_Free(h->stor_begin); h->stor_begin=0; } } } /** * \ingroup heap * \function igraph_heap_empty * \brief Decides whether a heap object is empty. * * \param h The heap object. * \return \c TRUE if the heap is empty, \c FALSE otherwise. * * TIme complexity: O(1). */ igraph_bool_t FUNCTION(igraph_heap,empty)(TYPE(igraph_heap)* h) { assert(h != NULL); assert(h->stor_begin != NULL); return h->stor_begin == h->end; } /** * \ingroup heap * \function igraph_heap_push * \brief Add an element. * * Adds an element to the heap. * \param h The heap object. * \param elem The element to add. * \return Error code. * * Time complexity: O(log n), n is the number of elements in the * heap if no reallocation is needed, O(n) otherwise. It is ensured * that n push operations are performed in O(n log n) time. */ int FUNCTION(igraph_heap,push)(TYPE(igraph_heap)* h, BASE elem) { assert(h != NULL); assert(h->stor_begin != NULL); /* full, allocate more storage */ if (h->stor_end == h->end) { long int new_size = FUNCTION(igraph_heap,size)(h) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(FUNCTION(igraph_heap,reserve)(h, new_size)); } *(h->end) = elem; h->end += 1; /* maintain heap */ FUNCTION(igraph_heap,i_shift_up)(h->stor_begin, FUNCTION(igraph_heap,size)(h), FUNCTION(igraph_heap,size)(h)-1); return 0; } /** * \ingroup heap * \function igraph_heap_top * \brief Top element. * * For maximum heaps this is the largest, for minimum heaps the * smallest element of the heap. * \param h The heap object. * \return The top element. * * Time complexity: O(1). */ BASE FUNCTION(igraph_heap,top)(TYPE(igraph_heap)* h) { assert(h != NULL); assert(h->stor_begin != NULL); assert(h->stor_begin != h->end); return h->stor_begin[0]; } /** * \ingroup heap * \function igraph_heap_delete_top * \brief Return and removes the top element * * Removes and returns the top element of the heap. For maximum heaps * this is the largest, for minimum heaps the smallest element. * \param h The heap object. * \return The top element. * * Time complexity: O(log n), n is the number of elements in the * heap. */ BASE FUNCTION(igraph_heap,delete_top)(TYPE(igraph_heap)* h) { BASE tmp; assert(h != NULL); assert(h->stor_begin != NULL); tmp=h->stor_begin[0]; FUNCTION(igraph_heap,i_switch)(h->stor_begin, 0, FUNCTION(igraph_heap,size)(h)-1); h->end -= 1; FUNCTION(igraph_heap,i_sink)(h->stor_begin, h->end-h->stor_begin, 0); return tmp; } /** * \ingroup heap * \function igraph_heap_size * \brief Number of elements * * Gives the number of elements in a heap. * \param h The heap object. * \return The number of elements in the heap. * * Time complexity: O(1). */ long int FUNCTION(igraph_heap,size)(TYPE(igraph_heap)* h) { assert(h != NULL); assert(h->stor_begin != NULL); return h->end - h->stor_begin; } /** * \ingroup heap * \function igraph_heap_reserve * \brief Allocate more memory * * Allocates memory for future use. The size of the heap is * unchanged. If the heap is larger than the \p size parameter then * nothing happens. * \param h The heap object. * \param size The number of elements to allocate memory for. * \return Error code. * * Time complexity: O(\p size) if \p size is larger than the current * number of elements. O(1) otherwise. */ int FUNCTION(igraph_heap,reserve)(TYPE(igraph_heap)* h, long int size) { long int actual_size=FUNCTION(igraph_heap,size)(h); BASE *tmp; assert(h != NULL); assert(h->stor_begin != NULL); if (size <= actual_size) { return 0; } tmp=igraph_Realloc(h->stor_begin, (size_t) size, BASE); if (tmp==0) { IGRAPH_ERROR("heap reserve failed", IGRAPH_ENOMEM); } h->stor_begin=tmp; h->stor_end=h->stor_begin + size; h->end=h->stor_begin+actual_size; return 0; } /** * \ingroup heap * \brief Build a heap, this should not be called directly. */ void FUNCTION(igraph_heap,i_build)(BASE* arr, long int size, long int head) { if (RIGHTCHILD(head) < size) { /* both subtrees */ FUNCTION(igraph_heap,i_build)(arr, size, LEFTCHILD(head) ); FUNCTION(igraph_heap,i_build)(arr, size, RIGHTCHILD(head)); FUNCTION(igraph_heap,i_sink)(arr, size, head); } else if (LEFTCHILD(head) < size) { /* only left */ FUNCTION(igraph_heap,i_build)(arr, size, LEFTCHILD(head)); FUNCTION(igraph_heap,i_sink)(arr, size, head); } else { /* none */ } } /** * \ingroup heap * \brief Shift an element upwards in a heap, this should not be * called directly. */ void FUNCTION(igraph_heap,i_shift_up)(BASE* arr, long int size, long int elem) { if (elem==0 || arr[elem] HEAPLESS arr[PARENT(elem)]) { /* at the top */ } else { FUNCTION(igraph_heap,i_switch)(arr, elem, PARENT(elem)); FUNCTION(igraph_heap,i_shift_up)(arr, size, PARENT(elem)); } } /** * \ingroup heap * \brief Moves an element down in a heap, this function should not be * called directly. */ void FUNCTION(igraph_heap,i_sink)(BASE* arr, long int size, long int head) { if (LEFTCHILD(head) >= size) { /* no subtrees */ } else if (RIGHTCHILD(head) == size || arr[LEFTCHILD(head)] HEAPMOREEQ arr[RIGHTCHILD(head)]) { /* sink to the left if needed */ if (arr[head] HEAPLESS arr[LEFTCHILD(head)]) { FUNCTION(igraph_heap,i_switch)(arr, head, LEFTCHILD(head)); FUNCTION(igraph_heap,i_sink)(arr, size, LEFTCHILD(head)); } } else { /* sink to the right */ if (arr[head] HEAPLESS arr[RIGHTCHILD(head)]) { FUNCTION(igraph_heap,i_switch)(arr, head, RIGHTCHILD(head)); FUNCTION(igraph_heap,i_sink)(arr, size, RIGHTCHILD(head)); } } } /** * \ingroup heap * \brief Switches two elements in a heap, this function should not be * called directly. */ void FUNCTION(igraph_heap,i_switch)(BASE* arr, long int e1, long int e2) { if (e1!=e2) { BASE tmp=arr[e1]; arr[e1]=arr[e2]; arr[e2]=tmp; } } igraph/src/layout_gem.c0000644000175100001440000002103013431000472014630 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_layout.h" #include "igraph_interface.h" #include "igraph_random.h" #include "igraph_math.h" /** * \ingroup layout * \function igraph_layout_gem * * The GEM layout algorithm, as described in Arne Frick, Andreas Ludwig, * Heiko Mehldau: A Fast Adaptive Layout Algorithm for Undirected Graphs, * Proc. Graph Drawing 1994, LNCS 894, pp. 388-403, 1995. * \param graph The input graph. Edge directions are ignored in * directed graphs. * \param res The result is stored here. If the \p use_seed argument * is true (non-zero), then this matrix is also used as the * starting point of the algorithm. * \param use_seed Boolean, whether to use the supplied coordinates in * \p res as the starting point. If false (zero), then a * uniform random starting point is used. * \param maxiter The maximum number of iterations to * perform. Updating a single vertex counts as an iteration. * A reasonable default is 40 * n * n, where n is the number of * vertices. The original paper suggests 4 * n * n, but this * usually only works if the other parameters are set up carefully. * \param temp_max The maximum allowed local temperature. A reasonable * default is the number of vertices. * \param temp_min The global temperature at which the algorithm * terminates (even before reaching \p maxiter iterations). A * reasonable default is 1/10. * \param temp_init Initial local temperature of all vertices. A * reasonable default is the square root of the number of * vertices. * \return Error code. * * Time complexity: O(t * n * (n+e)), where n is the number of vertices, * e is the number of edges and t is the number of time steps * performed. */ int igraph_layout_gem(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_real_t temp_max, igraph_real_t temp_min, igraph_real_t temp_init) { igraph_integer_t no_nodes = igraph_vcount(graph); igraph_vector_int_t perm; igraph_vector_float_t impulse_x, impulse_y, temp, skew_gauge; igraph_integer_t i; float temp_global; igraph_integer_t perm_pointer = 0; float barycenter_x = 0.0, barycenter_y = 0.0; igraph_vector_t phi; igraph_vector_t neis; const float elen_des2 = 128 * 128; const float gamma = 1/16.0; const float alpha_o = M_PI; const float alpha_r = M_PI / 3.0; const float sigma_o = 1.0 / 3.0; const float sigma_r = 1.0 / 2.0 / no_nodes; if (maxiter < 0) { IGRAPH_ERROR("Number of iterations must be non-negative in GEM layout", IGRAPH_EINVAL); } if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 2)) { IGRAPH_ERROR("Invalid start position matrix size in GEM layout", IGRAPH_EINVAL); } if (temp_max <= 0) { IGRAPH_ERROR("Maximum temperature should be positive in GEM layout", IGRAPH_EINVAL); } if (temp_min <= 0) { IGRAPH_ERROR("Minimum temperature should be positive in GEM layout", IGRAPH_EINVAL); } if (temp_init <= 0) { IGRAPH_ERROR("Initial temperature should be positive in GEM layout", IGRAPH_EINVAL); } if (temp_max < temp_init || temp_init < temp_min) { IGRAPH_ERROR("Minimum <= Initial <= Maximum temperature is required " "in GEM layout", IGRAPH_EINVAL); } if (no_nodes == 0) { return 0; } IGRAPH_CHECK(igraph_vector_float_init(&impulse_x, no_nodes)); IGRAPH_FINALLY(igraph_vector_float_destroy, &impulse_x); IGRAPH_CHECK(igraph_vector_float_init(&impulse_y, no_nodes)); IGRAPH_FINALLY(igraph_vector_float_destroy, &impulse_y); IGRAPH_CHECK(igraph_vector_float_init(&temp, no_nodes)); IGRAPH_FINALLY(igraph_vector_float_destroy, &temp); IGRAPH_CHECK(igraph_vector_float_init(&skew_gauge, no_nodes)); IGRAPH_FINALLY(igraph_vector_float_destroy, &skew_gauge); IGRAPH_CHECK(igraph_vector_int_init_seq(&perm, 0, no_nodes-1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &perm); IGRAPH_VECTOR_INIT_FINALLY(&phi, no_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 10); RNG_BEGIN(); /* Initialization */ igraph_degree(graph, &phi, igraph_vss_all(), IGRAPH_ALL, IGRAPH_LOOPS); if (!use_seed) { const igraph_real_t width_half=no_nodes*100, height_half=width_half; IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 2)); for (i=0; i temp_min * no_nodes && maxiter > 0) { /* choose a vertex v to update */ igraph_integer_t u, v, nlen, j; float px, py, pvx, pvy; if (!perm_pointer) { igraph_vector_int_shuffle(&perm); perm_pointer=no_nodes-1; } v=VECTOR(perm)[perm_pointer--]; /* compute v's impulse */ px = (barycenter_x/no_nodes - MATRIX(*res, v, 0)) * gamma * VECTOR(phi)[v]; py = (barycenter_y/no_nodes - MATRIX(*res, v, 1)) * gamma * VECTOR(phi)[v]; px += RNG_UNIF(-32.0, 32.0); py += RNG_UNIF(-32.0, 32.0); for (u = 0; u < no_nodes; u++) { float dx, dy, dist2; if (u == v) { continue; } dx=MATRIX(*res, v, 0) - MATRIX(*res, u, 0); dy=MATRIX(*res, v, 1) - MATRIX(*res, u, 1); dist2=dx * dx + dy * dy; if (dist2 != 0) { px += dx * elen_des2 / dist2; py += dy * elen_des2 / dist2; } } IGRAPH_CHECK(igraph_neighbors(graph, &neis, v, IGRAPH_ALL)); nlen=igraph_vector_size(&neis); for (j = 0; j < nlen; j++) { igraph_integer_t u=VECTOR(neis)[j]; float dx=MATRIX(*res, v, 0) - MATRIX(*res, u, 0); float dy=MATRIX(*res, v, 1) - MATRIX(*res, u, 1); float dist2= dx * dx + dy * dy; px -= dx * dist2 / (elen_des2 * VECTOR(phi)[v]); py -= dy * dist2 / (elen_des2 * VECTOR(phi)[v]); } /* update v's position and temperature */ if (px != 0 || py != 0) { float plen = sqrtf(px * px + py * py); px *= VECTOR(temp)[v] / plen; py *= VECTOR(temp)[v] / plen; MATRIX(*res, v, 0) += px; MATRIX(*res, v, 1) += py; barycenter_x += px; barycenter_y += py; } pvx=VECTOR(impulse_x)[v]; pvy=VECTOR(impulse_y)[v]; if (pvx != 0 || pvy != 0) { float beta = atan2f(pvy - py, pvx - px); float sin_beta = sinf(beta); float sign_sin_beta = (sin_beta > 0) ? 1 : ((sin_beta < 0) ? -1 : 0); float cos_beta = cosf(beta); float abs_cos_beta = fabsf(cos_beta); float old_temp=VECTOR(temp)[v]; if (sin(beta) >= sin(M_PI_2 + alpha_r / 2.0)) { VECTOR(skew_gauge)[v] += sigma_r * sign_sin_beta; } if (abs_cos_beta >= cosf(alpha_o / 2.0)) { VECTOR(temp)[v] *= sigma_o * cos_beta; } VECTOR(temp)[v] *= (1 - fabsf(VECTOR(skew_gauge)[v])); if (VECTOR(temp)[v] > temp_max) { VECTOR(temp)[v] = temp_max; } VECTOR(impulse_x)[v] = px; VECTOR(impulse_y)[v] = py; temp_global += VECTOR(temp)[v] - old_temp; } maxiter--; } /* while temp && iter */ RNG_END(); igraph_vector_destroy(&neis); igraph_vector_destroy(&phi); igraph_vector_int_destroy(&perm); igraph_vector_float_destroy(&skew_gauge); igraph_vector_float_destroy(&temp); igraph_vector_float_destroy(&impulse_y); igraph_vector_float_destroy(&impulse_x); IGRAPH_FINALLY_CLEAN(7); return 0; } igraph/src/spectral_properties.c0000644000175100001440000003066013431000472016565 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=8 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_structural.h" #include "igraph_interface.h" #include "config.h" #include int igraph_i_weighted_laplacian(const igraph_t *graph, igraph_matrix_t *res, igraph_sparsemat_t *sparseres, igraph_bool_t normalized, const igraph_vector_t *weights) { igraph_eit_t edgeit; int no_of_nodes=(int) igraph_vcount(graph); int no_of_edges=(int) igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); igraph_vector_t degree; long int i; if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid edge weight vector length", IGRAPH_EINVAL); } if (res) { IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, no_of_nodes)); igraph_matrix_null(res); } if (sparseres) { int nz=directed ? no_of_edges + no_of_nodes : no_of_edges * 2 + no_of_nodes; igraph_sparsemat_resize(sparseres, no_of_nodes, no_of_nodes, nz); } IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &edgeit)); IGRAPH_FINALLY(igraph_eit_destroy, &edgeit); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); if (directed) { if (!normalized) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); long int from=IGRAPH_FROM(graph, edge); long int to =IGRAPH_TO (graph, edge); igraph_real_t weight=VECTOR(*weights)[edge]; if (from != to) { if (res) { MATRIX(*res, from, to) -= weight; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) from, (int)to, -weight)); } VECTOR(degree)[from] += weight; } IGRAPH_EIT_NEXT(edgeit); } /* And the diagonal */ for (i=0; i 0 ? 1 : 0; if (res) { MATRIX(*res, i, i) = t; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) i, (int) i, t)); } } IGRAPH_EIT_RESET(edgeit); while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); long int from=IGRAPH_FROM(graph, edge); long int to =IGRAPH_TO (graph, edge); igraph_real_t weight=VECTOR(*weights)[edge]; if (from != to) { igraph_real_t t=weight / VECTOR(degree)[from]; if (res) { MATRIX(*res, from, to) -= t; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) from, (int) to, -t)); } } IGRAPH_EIT_NEXT(edgeit); } } } else /* undirected */ { if (!normalized) { while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); long int from=IGRAPH_FROM(graph, edge); long int to =IGRAPH_TO (graph, edge); igraph_real_t weight=VECTOR(*weights)[edge]; if (from != to) { if (res) { MATRIX(*res, from, to) -= weight; MATRIX(*res, to, from) -= weight; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) from, (int) to, -weight)); IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) to, (int) from, -weight)); } VECTOR(degree)[from] += weight; VECTOR(degree)[to] += weight; } IGRAPH_EIT_NEXT(edgeit); } /* And the diagonal */ for (i=0; i 0 ? 1 : 0; if (res) { MATRIX(*res, i, i) = t; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) i, (int) i, t)); } VECTOR(degree)[i] = sqrt(VECTOR(degree)[i]); } IGRAPH_EIT_RESET(edgeit); while (!IGRAPH_EIT_END(edgeit)) { long int edge=IGRAPH_EIT_GET(edgeit); long int from=IGRAPH_FROM(graph, edge); long int to =IGRAPH_TO (graph, edge); igraph_real_t weight=VECTOR(*weights)[edge]; if (from != to) { double diff = weight / (VECTOR(degree)[from] * VECTOR(degree)[to]); if (res) { MATRIX(*res, from, to) -= diff; MATRIX(*res, to, from) -= diff; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) from, (int) to, -diff)); IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, (int) to, (int) from, -diff)); } } IGRAPH_EIT_NEXT(edgeit); } } } igraph_vector_destroy(°ree); igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_laplacian * \brief Returns the Laplacian matrix of a graph * * * The graph Laplacian matrix is similar to an adjacency matrix but * contains -1's instead of 1's and the vertex degrees are included in * the diagonal. So the result for edge i--j is -1 if i!=j and is equal * to the degree of vertex i if i==j. igraph_laplacian will work on a * directed graph; in this case, the diagonal will contain the out-degrees. * Loop edges will be ignored. * * * The normalized version of the Laplacian matrix has 1 in the diagonal and * -1/sqrt(d[i]d[j]) if there is an edge from i to j. * * * The first version of this function was written by Vincent Matossian. * \param graph Pointer to the graph to convert. * \param res Pointer to an initialized matrix object, the result is * stored here. It will be resized if needed. * If it is a null pointer, then it is ignored. * At least one of \p res and \p sparseres must be a non-null pointer. * \param sparseres Pointer to an initialized sparse matrix object, the * result is stored here, if it is not a null pointer. * At least one of \p res and \p sparseres must be a non-null pointer. * \param normalized Whether to create a normalized Laplacian matrix. * \param weights An optional vector containing edge weights, to calculate * the weighted Laplacian matrix. Set it to a null pointer to * calculate the unweighted Laplacian. * \return Error code. * * Time complexity: O(|V||V|), * |V| is the * number of vertices in the graph. * * \example examples/simple/igraph_laplacian.c */ int igraph_laplacian(const igraph_t *graph, igraph_matrix_t *res, igraph_sparsemat_t *sparseres, igraph_bool_t normalized, const igraph_vector_t *weights) { igraph_eit_t edgeit; int no_of_nodes=(int) igraph_vcount(graph); int no_of_edges=(int) igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); int from, to; igraph_integer_t ffrom, fto; igraph_vector_t degree; int i; if (!res && !sparseres) { IGRAPH_ERROR("Laplacian: give at least one of `res' or `sparseres'", IGRAPH_EINVAL); } if (weights) { return igraph_i_weighted_laplacian(graph, res, sparseres, normalized, weights); } if (res) { IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes, no_of_nodes)); igraph_matrix_null(res); } if (sparseres) { int nz=directed ? no_of_edges + no_of_nodes : no_of_edges * 2 + no_of_nodes; IGRAPH_CHECK(igraph_sparsemat_resize(sparseres, no_of_nodes, no_of_nodes, nz)); } IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(0), &edgeit)); IGRAPH_FINALLY(igraph_eit_destroy, &edgeit); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_OUT, IGRAPH_NO_LOOPS)); if (directed){ if (!normalized) { for (i=0;i0 ? 1 : 0; if (res) { MATRIX(*res, i, i) = t; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, i, i, t)); } if (VECTOR(degree)[i] > 0) VECTOR(degree)[i] = 1.0 / VECTOR(degree)[i]; } while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; if (from != to) { if (res) { MATRIX(*res, from, to) -= VECTOR(degree)[from]; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, from, to, -VECTOR(degree)[from])); } } IGRAPH_EIT_NEXT(edgeit); } } } else { if (!normalized) { for(i=0;i0 ? 1: 0; if (res) { MATRIX(*res, i, i) = t; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, i, i, t)); } VECTOR(degree)[i] = sqrt(VECTOR(degree)[i]); } while (!IGRAPH_EIT_END(edgeit)) { igraph_edge(graph, IGRAPH_EIT_GET(edgeit), &ffrom, &fto); from=ffrom; to=fto; if (from != to) { double diff = 1.0 / (VECTOR(degree)[from] * VECTOR(degree)[to]); if (res) { MATRIX(*res, from, to) -= diff; MATRIX(*res, to, from) -= diff; } if (sparseres) { IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, from, to, -diff)); IGRAPH_CHECK(igraph_sparsemat_entry(sparseres, to, from, -diff)); } } IGRAPH_EIT_NEXT(edgeit); } } } igraph_vector_destroy(°ree); igraph_eit_destroy(&edgeit); IGRAPH_FINALLY_CLEAN(2); return 0; } igraph/src/foreign-ncol-lexer.c0000644000175100001440000016065213431000472016200 0ustar hornikusers#line 2 "lex.yy.c" #line 4 "lex.yy.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE igraph_ncol_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via igraph_ncol_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void igraph_ncol_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void igraph_ncol_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_ncol_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void igraph_ncol_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_ncol_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_ncol_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void igraph_ncol_yypop_buffer_state (yyscan_t yyscanner ); static void igraph_ncol_yyensure_buffer_stack (yyscan_t yyscanner ); static void igraph_ncol_yy_load_buffer_state (yyscan_t yyscanner ); static void igraph_ncol_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER igraph_ncol_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE igraph_ncol_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_ncol_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_ncol_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *igraph_ncol_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *igraph_ncol_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void igraph_ncol_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer igraph_ncol_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ igraph_ncol_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_ncol_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ igraph_ncol_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_ncol_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define igraph_ncol_yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 5 #define YY_END_OF_BUFFER 6 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[12] = { 0, 1, 1, 6, 3, 1, 2, 2, 3, 1, 2, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[5] = { 0, 1, 2, 3, 4 } ; static yyconst flex_int16_t yy_base[16] = { 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 10, 10, 7, 5, 2, 2 } ; static yyconst flex_int16_t yy_def[16] = { 0, 11, 1, 11, 12, 13, 14, 15, 12, 13, 11, 0, 11, 11, 11, 11 } ; static yyconst flex_int16_t yy_nxt[15] = { 0, 4, 5, 6, 7, 10, 10, 9, 8, 11, 3, 11, 11, 11, 11 } ; static yyconst flex_int16_t yy_chk[15] = { 0, 1, 1, 1, 1, 15, 14, 13, 12, 3, 11, 11, 11, 11, 11 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "src/foreign-ncol-lexer.l" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #line 24 "src/foreign-ncol-lexer.l" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-ncol-header.h" #include "foreign-ncol-parser.h" #define YY_EXTRA_TYPE igraph_i_ncol_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); #define YY_NO_INPUT 1 #line 500 "lex.yy.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int igraph_ncol_yylex_init (yyscan_t* scanner); int igraph_ncol_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int igraph_ncol_yylex_destroy (yyscan_t yyscanner ); int igraph_ncol_yyget_debug (yyscan_t yyscanner ); void igraph_ncol_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE igraph_ncol_yyget_extra (yyscan_t yyscanner ); void igraph_ncol_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *igraph_ncol_yyget_in (yyscan_t yyscanner ); void igraph_ncol_yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *igraph_ncol_yyget_out (yyscan_t yyscanner ); void igraph_ncol_yyset_out (FILE * out_str ,yyscan_t yyscanner ); yy_size_t igraph_ncol_yyget_leng (yyscan_t yyscanner ); char *igraph_ncol_yyget_text (yyscan_t yyscanner ); int igraph_ncol_yyget_lineno (yyscan_t yyscanner ); void igraph_ncol_yyset_lineno (int line_number ,yyscan_t yyscanner ); YYSTYPE * igraph_ncol_yyget_lval (yyscan_t yyscanner ); void igraph_ncol_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); YYLTYPE *igraph_ncol_yyget_lloc (yyscan_t yyscanner ); void igraph_ncol_yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int igraph_ncol_yywrap (yyscan_t yyscanner ); #else extern int igraph_ncol_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int igraph_ncol_yylex \ (YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner); #define YY_DECL int igraph_ncol_yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; #line 77 "src/foreign-ncol-lexer.l" /* ------------------------------------------------whitespace------*/ #line 743 "lex.yy.c" yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { igraph_ncol_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_ncol_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_ncol_yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 12 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 10 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 80 "src/foreign-ncol-lexer.l" { } YY_BREAK /* ---------------------------------------------------newline------*/ case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 83 "src/foreign-ncol-lexer.l" { return NEWLINE; } YY_BREAK /* ----------------------------------------------alphanumeric------*/ case 3: YY_RULE_SETUP #line 86 "src/foreign-ncol-lexer.l" { return ALNUM; } YY_BREAK case YY_STATE_EOF(INITIAL): #line 88 "src/foreign-ncol-lexer.l" { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } YY_BREAK /* ---------------------------------------------anything else------*/ case 4: YY_RULE_SETUP #line 97 "src/foreign-ncol-lexer.l" { return ERROR; } YY_BREAK case 5: YY_RULE_SETUP #line 99 "src/foreign-ncol-lexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 869 "lex.yy.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * igraph_ncol_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( igraph_ncol_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of igraph_ncol_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ igraph_ncol_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; igraph_ncol_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) igraph_ncol_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 12 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 12 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 11); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ igraph_ncol_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( igraph_ncol_yywrap(yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void igraph_ncol_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ igraph_ncol_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_ncol_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_ncol_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); igraph_ncol_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void igraph_ncol_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * igraph_ncol_yypop_buffer_state(); * igraph_ncol_yypush_buffer_state(new_buffer); */ igraph_ncol_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; igraph_ncol_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (igraph_ncol_yywrap()) processing, but the only time this flag * is looked at is after igraph_ncol_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void igraph_ncol_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE igraph_ncol_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) igraph_ncol_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) igraph_ncol_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yy_create_buffer()" ); b->yy_is_our_buffer = 1; igraph_ncol_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with igraph_ncol_yy_create_buffer() * @param yyscanner The scanner object. */ void igraph_ncol_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) igraph_ncol_yyfree((void *) b->yy_ch_buf ,yyscanner ); igraph_ncol_yyfree((void *) b ,yyscanner ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a igraph_ncol_yyrestart() or at EOF. */ static void igraph_ncol_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; igraph_ncol_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then igraph_ncol_yy_init_buffer was _probably_ * called from igraph_ncol_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void igraph_ncol_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) igraph_ncol_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void igraph_ncol_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; igraph_ncol_yyensure_buffer_stack(yyscanner); /* This block is copied from igraph_ncol_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from igraph_ncol_yy_switch_to_buffer. */ igraph_ncol_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void igraph_ncol_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; igraph_ncol_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { igraph_ncol_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void igraph_ncol_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_ncol_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_ncol_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_ncol_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) igraph_ncol_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; igraph_ncol_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to igraph_ncol_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * igraph_ncol_yy_scan_bytes() instead. */ YY_BUFFER_STATE igraph_ncol_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return igraph_ncol_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to igraph_ncol_yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_ncol_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) igraph_ncol_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_ncol_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = igraph_ncol_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in igraph_ncol_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE igraph_ncol_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int igraph_ncol_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int igraph_ncol_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *igraph_ncol_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *igraph_ncol_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t igraph_ncol_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *igraph_ncol_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void igraph_ncol_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void igraph_ncol_yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_ncol_yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void igraph_ncol_yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_ncol_yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see igraph_ncol_yy_switch_to_buffer */ void igraph_ncol_yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void igraph_ncol_yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int igraph_ncol_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void igraph_ncol_yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * igraph_ncol_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void igraph_ncol_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *igraph_ncol_yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void igraph_ncol_yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* igraph_ncol_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int igraph_ncol_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_ncol_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* igraph_ncol_yylex_init_extra has the same functionality as igraph_ncol_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to igraph_ncol_yyalloc in * the yyextra field. */ int igraph_ncol_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; igraph_ncol_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_ncol_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); igraph_ncol_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from igraph_ncol_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * igraph_ncol_yylex_init() */ return 0; } /* igraph_ncol_yylex_destroy is for both reentrant and non-reentrant scanners. */ int igraph_ncol_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ igraph_ncol_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; igraph_ncol_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ igraph_ncol_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ igraph_ncol_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * igraph_ncol_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ igraph_ncol_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *igraph_ncol_yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *igraph_ncol_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void igraph_ncol_yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see igraph_ncol_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 99 "src/foreign-ncol-lexer.l" igraph/src/foreign-gml-lexer.c0000644000175100001440000016313513431000472016023 0ustar hornikusers#line 2 "lex.yy.c" #line 4 "lex.yy.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE igraph_gml_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via igraph_gml_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void igraph_gml_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void igraph_gml_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_gml_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void igraph_gml_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_gml_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_gml_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void igraph_gml_yypop_buffer_state (yyscan_t yyscanner ); static void igraph_gml_yyensure_buffer_stack (yyscan_t yyscanner ); static void igraph_gml_yy_load_buffer_state (yyscan_t yyscanner ); static void igraph_gml_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER igraph_gml_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE igraph_gml_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_gml_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_gml_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *igraph_gml_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *igraph_gml_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void igraph_gml_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer igraph_gml_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ igraph_gml_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_gml_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ igraph_gml_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_gml_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define igraph_gml_yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 10 #define YY_END_OF_BUFFER 11 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[29] = { 0, 0, 0, 11, 9, 8, 7, 7, 9, 9, 3, 4, 5, 6, 1, 9, 7, 0, 2, 3, 0, 0, 4, 0, 1, 3, 0, 3, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 5, 6, 1, 1, 1, 1, 1, 1, 1, 7, 1, 8, 9, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 1, 1, 11, 11, 11, 11, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 13, 1, 14, 1, 11, 1, 11, 11, 11, 11, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[15] = { 0, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1 } ; static yyconst flex_int16_t yy_base[32] = { 0, 0, 11, 42, 43, 43, 37, 37, 34, 28, 9, 0, 43, 43, 34, 33, 43, 30, 43, 0, 24, 15, 0, 30, 43, 14, 21, 10, 43, 26, 13, 29 } ; static yyconst flex_int16_t yy_def[32] = { 0, 28, 1, 28, 28, 28, 28, 28, 29, 28, 28, 30, 28, 28, 28, 31, 28, 29, 28, 10, 28, 28, 30, 31, 28, 28, 28, 28, 0, 28, 28, 28 } ; static yyconst flex_int16_t yy_nxt[58] = { 0, 4, 5, 6, 7, 8, 4, 4, 9, 4, 10, 11, 11, 12, 13, 14, 22, 15, 20, 19, 27, 21, 26, 26, 25, 27, 21, 17, 17, 17, 23, 27, 23, 24, 25, 18, 24, 16, 19, 18, 16, 16, 28, 3, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28 } ; static yyconst flex_int16_t yy_chk[58] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 30, 2, 10, 10, 27, 10, 21, 21, 25, 21, 25, 29, 29, 29, 31, 26, 31, 23, 20, 17, 15, 14, 9, 8, 7, 6, 3, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "src/foreign-gml-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #line 24 "src/foreign-gml-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-gml-header.h" #include "foreign-gml-parser.h" #define YY_EXTRA_TYPE igraph_i_gml_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); #define YY_NO_INPUT 1 #line 514 "lex.yy.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int igraph_gml_yylex_init (yyscan_t* scanner); int igraph_gml_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int igraph_gml_yylex_destroy (yyscan_t yyscanner ); int igraph_gml_yyget_debug (yyscan_t yyscanner ); void igraph_gml_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE igraph_gml_yyget_extra (yyscan_t yyscanner ); void igraph_gml_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *igraph_gml_yyget_in (yyscan_t yyscanner ); void igraph_gml_yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *igraph_gml_yyget_out (yyscan_t yyscanner ); void igraph_gml_yyset_out (FILE * out_str ,yyscan_t yyscanner ); yy_size_t igraph_gml_yyget_leng (yyscan_t yyscanner ); char *igraph_gml_yyget_text (yyscan_t yyscanner ); int igraph_gml_yyget_lineno (yyscan_t yyscanner ); void igraph_gml_yyset_lineno (int line_number ,yyscan_t yyscanner ); YYSTYPE * igraph_gml_yyget_lval (yyscan_t yyscanner ); void igraph_gml_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); YYLTYPE *igraph_gml_yyget_lloc (yyscan_t yyscanner ); void igraph_gml_yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int igraph_gml_yywrap (yyscan_t yyscanner ); #else extern int igraph_gml_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int igraph_gml_yylex \ (YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner); #define YY_DECL int igraph_gml_yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ if ( yyleng > 0 ) \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \ (yytext[yyleng - 1] == '\n'); \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; #line 78 "src/foreign-gml-lexer.l" #line 759 "lex.yy.c" yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { igraph_gml_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_gml_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_gml_yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_current_state += YY_AT_BOL(); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 29 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 43 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 80 "src/foreign-gml-lexer.l" { /* comments ignored */ } YY_BREAK case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 82 "src/foreign-gml-lexer.l" { return STRING; } YY_BREAK case 3: YY_RULE_SETUP #line 83 "src/foreign-gml-lexer.l" { return NUM; } YY_BREAK case 4: YY_RULE_SETUP #line 84 "src/foreign-gml-lexer.l" { return KEYWORD; } YY_BREAK case 5: YY_RULE_SETUP #line 85 "src/foreign-gml-lexer.l" { return LISTOPEN; } YY_BREAK case 6: YY_RULE_SETUP #line 86 "src/foreign-gml-lexer.l" { return LISTCLOSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 87 "src/foreign-gml-lexer.l" { } YY_BREAK case 8: /* rule 8 can match eol */ YY_RULE_SETUP #line 88 "src/foreign-gml-lexer.l" { /* other whitespace ignored */ } YY_BREAK case YY_STATE_EOF(INITIAL): #line 90 "src/foreign-gml-lexer.l" { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return EOFF; } } YY_BREAK case 9: YY_RULE_SETUP #line 98 "src/foreign-gml-lexer.l" { return ERROR; } YY_BREAK case 10: YY_RULE_SETUP #line 99 "src/foreign-gml-lexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 912 "lex.yy.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * igraph_gml_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( igraph_gml_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of igraph_gml_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ igraph_gml_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; igraph_gml_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) igraph_gml_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; yy_current_state += YY_AT_BOL(); for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 29 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 29 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 28); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ igraph_gml_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( igraph_gml_yywrap(yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\n'); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void igraph_gml_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ igraph_gml_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_gml_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_gml_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); igraph_gml_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void igraph_gml_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * igraph_gml_yypop_buffer_state(); * igraph_gml_yypush_buffer_state(new_buffer); */ igraph_gml_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; igraph_gml_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (igraph_gml_yywrap()) processing, but the only time this flag * is looked at is after igraph_gml_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void igraph_gml_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE igraph_gml_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) igraph_gml_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) igraph_gml_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yy_create_buffer()" ); b->yy_is_our_buffer = 1; igraph_gml_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with igraph_gml_yy_create_buffer() * @param yyscanner The scanner object. */ void igraph_gml_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) igraph_gml_yyfree((void *) b->yy_ch_buf ,yyscanner ); igraph_gml_yyfree((void *) b ,yyscanner ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a igraph_gml_yyrestart() or at EOF. */ static void igraph_gml_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; igraph_gml_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then igraph_gml_yy_init_buffer was _probably_ * called from igraph_gml_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void igraph_gml_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) igraph_gml_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void igraph_gml_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; igraph_gml_yyensure_buffer_stack(yyscanner); /* This block is copied from igraph_gml_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from igraph_gml_yy_switch_to_buffer. */ igraph_gml_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void igraph_gml_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; igraph_gml_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { igraph_gml_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void igraph_gml_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_gml_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_gml_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_gml_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) igraph_gml_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; igraph_gml_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to igraph_gml_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * igraph_gml_yy_scan_bytes() instead. */ YY_BUFFER_STATE igraph_gml_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return igraph_gml_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to igraph_gml_yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_gml_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) igraph_gml_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_gml_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = igraph_gml_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in igraph_gml_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE igraph_gml_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int igraph_gml_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int igraph_gml_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *igraph_gml_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *igraph_gml_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t igraph_gml_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *igraph_gml_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void igraph_gml_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void igraph_gml_yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_gml_yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void igraph_gml_yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_gml_yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see igraph_gml_yy_switch_to_buffer */ void igraph_gml_yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void igraph_gml_yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int igraph_gml_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void igraph_gml_yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * igraph_gml_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void igraph_gml_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *igraph_gml_yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void igraph_gml_yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* igraph_gml_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int igraph_gml_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_gml_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* igraph_gml_yylex_init_extra has the same functionality as igraph_gml_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to igraph_gml_yyalloc in * the yyextra field. */ int igraph_gml_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; igraph_gml_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_gml_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); igraph_gml_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from igraph_gml_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * igraph_gml_yylex_init() */ return 0; } /* igraph_gml_yylex_destroy is for both reentrant and non-reentrant scanners. */ int igraph_gml_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ igraph_gml_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; igraph_gml_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ igraph_gml_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ igraph_gml_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * igraph_gml_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ igraph_gml_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *igraph_gml_yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *igraph_gml_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void igraph_gml_yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see igraph_gml_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 99 "src/foreign-gml-lexer.l" igraph/src/igraph_f2c.h0000644000175100001440000001112013431000472014473 0ustar hornikusers/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE typedef long int integer; typedef unsigned long int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; typedef long int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #ifdef INTEGER_STAR_8 /* Adjust for integer*8. */ typedef long long longint; /* system-dependent */ typedef unsigned long long ulongint; /* system-dependent */ #define qbit_clear(a,b) ((a) & ~((ulongint)1 << (b))) #define qbit_set(a,b) ((a) | ((ulongint)1 << (b))) #endif #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ #ifdef f2c_i2 /* for -i2 */ typedef short flag; typedef short ftnlen; typedef short ftnint; #else typedef long int flag; typedef long int ftnlen; typedef long int ftnint; #endif /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; /*typedef long int Long;*/ /* No longer used; formerly in Namelist */ struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (doublereal)abs(x) #define min(a,b) ((a) <= (b) ? (a) : (b)) #define max(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (doublereal)min(a,b) #define dmax(a,b) (doublereal)max(a,b) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef int /* Unknown procedure type */ (*U_fp)(...); typedef shortint (*J_fp)(...); typedef integer (*I_fp)(...); typedef real (*R_fp)(...); typedef doublereal (*D_fp)(...), (*E_fp)(...); typedef /* Complex */ VOID (*C_fp)(...); typedef /* Double Complex */ VOID (*Z_fp)(...); typedef logical (*L_fp)(...); typedef shortlogical (*K_fp)(...); typedef /* Character */ VOID (*H_fp)(...); typedef /* Subroutine */ int (*S_fp)(...); #else typedef int /* Unknown procedure type */ (*U_fp)(); typedef shortint (*J_fp)(); typedef integer (*I_fp)(); typedef real (*R_fp)(); typedef doublereal (*D_fp)(), (*E_fp)(); typedef /* Complex */ VOID (*C_fp)(); typedef /* Double Complex */ VOID (*Z_fp)(); typedef logical (*L_fp)(); typedef shortlogical (*K_fp)(); typedef /* Character */ VOID (*H_fp)(); typedef /* Subroutine */ int (*S_fp)(); #endif /* E_fp is for real functions when -R is not specified */ typedef VOID C_f; /* complex function */ typedef VOID H_f; /* character function */ typedef VOID Z_f; /* double complex function */ typedef doublereal E_f; /* real function with -R not specified */ /* undef any lower-case symbols that your C compiler predefines, e.g.: */ #ifndef Skip_f2c_Undefs #undef cray #undef gcos #undef mc68010 #undef mc68020 #undef mips #undef pdp11 #undef sgi #undef sparc #undef sun #undef sun2 #undef sun3 #undef sun4 #undef u370 #undef u3b #undef u3b2 #undef u3b5 #undef unix #undef vax #endif #endif igraph/src/matrix.c0000644000175100001440000001046013431000472013774 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_matrix.h" #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_INT #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_LONG #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_COMPLEX #include "igraph_pmt.h" #include "matrix.pmt" #include "igraph_pmt_off.h" #undef BASE_COMPLEX #ifndef USING_R int igraph_matrix_complex_print(const igraph_matrix_complex_t *m) { long int nr=igraph_matrix_complex_nrow(m); long int nc=igraph_matrix_complex_ncol(m); long int i, j; for (i=0; idata, &real->data)); return 0; } int igraph_matrix_complex_imag(const igraph_matrix_complex_t *v, igraph_matrix_t *imag) { long int nrow=igraph_matrix_complex_nrow(v); long int ncol=igraph_matrix_complex_ncol(v); IGRAPH_CHECK(igraph_matrix_resize(imag, nrow, ncol)); IGRAPH_CHECK(igraph_vector_complex_imag(&v->data, &imag->data)); return 0; } int igraph_matrix_complex_realimag(const igraph_matrix_complex_t *v, igraph_matrix_t *real, igraph_matrix_t *imag) { long int nrow=igraph_matrix_complex_nrow(v); long int ncol=igraph_matrix_complex_ncol(v); IGRAPH_CHECK(igraph_matrix_resize(real, nrow, ncol)); IGRAPH_CHECK(igraph_matrix_resize(imag, nrow, ncol)); IGRAPH_CHECK(igraph_vector_complex_realimag(&v->data, &real->data, &imag->data)); return 0; } int igraph_matrix_complex_create(igraph_matrix_complex_t *v, const igraph_matrix_t *real, const igraph_matrix_t *imag) { IGRAPH_CHECK(igraph_vector_complex_create(&v->data, &real->data, &imag->data)); return 0; } int igraph_matrix_complex_create_polar(igraph_matrix_complex_t *v, const igraph_matrix_t *r, const igraph_matrix_t *theta) { IGRAPH_CHECK(igraph_vector_complex_create_polar(&v->data, &r->data, &theta->data)); return 0; } igraph_bool_t igraph_matrix_all_e_tol(const igraph_matrix_t *lhs, const igraph_matrix_t *rhs, igraph_real_t tol) { return igraph_vector_e_tol(&lhs->data, &rhs->data, tol); } int igraph_matrix_zapsmall(igraph_matrix_t *m, igraph_real_t tol) { return igraph_vector_zapsmall(&m->data, tol); } igraph/src/dnaupd.f0000644000175100001440000006614513431000472013761 0ustar hornikusersc\BeginDoc c c\Name: igraphdnaupd c c\Description: c Reverse communication interface for the Implicitly Restarted Arnoldi c iteration. This subroutine computes approximations to a few eigenpairs c of a linear operator "OP" with respect to a semi-inner product defined by c a symmetric positive semi-definite real matrix B. B may be the identity c matrix. NOTE: If the linear operator "OP" is real and symmetric c with respect to the real positive semi-definite symmetric matrix B, c i.e. B*OP = (OP')*B, then subroutine ssaupd should be used instead. c c The computed approximate eigenvalues are called Ritz values and c the corresponding approximate eigenvectors are called Ritz vectors. c c igraphdnaupd is usually called iteratively to solve one of the c following problems: c c Mode 1: A*x = lambda*x. c ===> OP = A and B = I. c c Mode 2: A*x = lambda*M*x, M symmetric positive definite c ===> OP = inv[M]*A and B = M. c ===> (If M can be factored see remark 3 below) c c Mode 3: A*x = lambda*M*x, M symmetric semi-definite c ===> OP = Real_Part{ inv[A - sigma*M]*M } and B = M. c ===> shift-and-invert mode (in real arithmetic) c If OP*x = amu*x, then c amu = 1/2 * [ 1/(lambda-sigma) + 1/(lambda-conjg(sigma)) ]. c Note: If sigma is real, i.e. imaginary part of sigma is zero; c Real_Part{ inv[A - sigma*M]*M } == inv[A - sigma*M]*M c amu == 1/(lambda-sigma). c c Mode 4: A*x = lambda*M*x, M symmetric semi-definite c ===> OP = Imaginary_Part{ inv[A - sigma*M]*M } and B = M. c ===> shift-and-invert mode (in real arithmetic) c If OP*x = amu*x, then c amu = 1/2i * [ 1/(lambda-sigma) - 1/(lambda-conjg(sigma)) ]. c c Both mode 3 and 4 give the same enhancement to eigenvalues close to c the (complex) shift sigma. However, as lambda goes to infinity, c the operator OP in mode 4 dampens the eigenvalues more strongly than c does OP defined in mode 3. c c NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v c should be accomplished either by a direct method c using a sparse matrix factorization and solving c c [A - sigma*M]*w = v or M*w = v, c c or through an iterative method for solving these c systems. If an iterative method is used, the c convergence test must be more stringent than c the accuracy requirements for the eigenvalue c approximations. c c\Usage: c call igraphdnaupd c ( IDO, BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, c IPNTR, WORKD, WORKL, LWORKL, INFO ) c c\Arguments c IDO Integer. (INPUT/OUTPUT) c Reverse communication flag. IDO must be zero on the first c call to igraphdnaupd. IDO will be set internally to c indicate the type of operation to be performed. Control is c then given back to the calling routine which has the c responsibility to carry out the requested operation and call c igraphdnaupd with the result. The operand is given in c WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)). c ------------------------------------------------------------- c IDO = 0: first call to the reverse communication interface c IDO = -1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c This is for the initialization phase to force the c starting vector into the range of OP. c IDO = 1: compute Y = OP * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c In mode 3 and 4, the vector B * X is already c available in WORKD(ipntr(3)). It does not c need to be recomputed in forming OP * X. c IDO = 2: compute Y = B * X where c IPNTR(1) is the pointer into WORKD for X, c IPNTR(2) is the pointer into WORKD for Y. c IDO = 3: compute the IPARAM(8) real and imaginary parts c of the shifts where INPTR(14) is the pointer c into WORKL for placing the shifts. See Remark c 5 below. c IDO = 99: done c ------------------------------------------------------------- c c BMAT Character*1. (INPUT) c BMAT specifies the type of the matrix B that defines the c semi-inner product for the operator OP. c BMAT = 'I' -> standard eigenvalue problem A*x = lambda*x c BMAT = 'G' -> generalized eigenvalue problem A*x = lambda*B*x c c N Integer. (INPUT) c Dimension of the eigenproblem. c c WHICH Character*2. (INPUT) c 'LM' -> want the NEV eigenvalues of largest magnitude. c 'SM' -> want the NEV eigenvalues of smallest magnitude. c 'LR' -> want the NEV eigenvalues of largest real part. c 'SR' -> want the NEV eigenvalues of smallest real part. c 'LI' -> want the NEV eigenvalues of largest imaginary part. c 'SI' -> want the NEV eigenvalues of smallest imaginary part. c c NEV Integer. (INPUT) c Number of eigenvalues of OP to be computed. 0 < NEV < N-1. c c TOL Double precision scalar. (INPUT) c Stopping criterion: the relative accuracy of the Ritz value c is considered acceptable if BOUNDS(I) .LE. TOL*ABS(RITZ(I)) c where ABS(RITZ(I)) is the magnitude when RITZ(I) is complex. c DEFAULT = DLAMCH('EPS') (machine precision as computed c by the LAPACK auxiliary subroutine DLAMCH). c c RESID Double precision array of length N. (INPUT/OUTPUT) c On INPUT: c If INFO .EQ. 0, a random initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c On OUTPUT: c RESID contains the final residual vector. c c NCV Integer. (INPUT) c Number of columns of the matrix V. NCV must satisfy the two c inequalities 2 <= NCV-NEV and NCV <= N. c This will indicate how many Arnoldi vectors are generated c at each iteration. After the startup phase in which NEV c Arnoldi vectors are generated, the algorithm generates c approximately NCV-NEV Arnoldi vectors at each subsequent update c iteration. Most of the cost in generating each Arnoldi vector is c in the matrix-vector operation OP*x. c NOTE: 2 <= NCV-NEV in order that complex conjugate pairs of Ritz c values are kept together. (See remark 4 below) c c V Double precision array N by NCV. (OUTPUT) c Contains the final set of Arnoldi basis vectors. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling program. c c IPARAM Integer array of length 11. (INPUT/OUTPUT) c IPARAM(1) = ISHIFT: method for selecting the implicit shifts. c The shifts selected at each iteration are used to restart c the Arnoldi iteration in an implicit fashion. c ------------------------------------------------------------- c ISHIFT = 0: the shifts are provided by the user via c reverse communication. The real and imaginary c parts of the NCV eigenvalues of the Hessenberg c matrix H are returned in the part of the WORKL c array corresponding to RITZR and RITZI. See remark c 5 below. c ISHIFT = 1: exact shifts with respect to the current c Hessenberg matrix H. This is equivalent to c restarting the iteration with a starting vector c that is a linear combination of approximate Schur c vectors associated with the "wanted" Ritz values. c ------------------------------------------------------------- c c IPARAM(2) = No longer referenced. c c IPARAM(3) = MXITER c On INPUT: maximum number of Arnoldi update iterations allowed. c On OUTPUT: actual number of Arnoldi update iterations taken. c c IPARAM(4) = NB: blocksize to be used in the recurrence. c The code currently works only for NB = 1. c c IPARAM(5) = NCONV: number of "converged" Ritz values. c This represents the number of Ritz values that satisfy c the convergence criterion. c c IPARAM(6) = IUPD c No longer referenced. Implicit restarting is ALWAYS used. c c IPARAM(7) = MODE c On INPUT determines what type of eigenproblem is being solved. c Must be 1,2,3,4; See under \Description of igraphdnaupd for the c four modes available. c c IPARAM(8) = NP c When ido = 3 and the user provides shifts through reverse c communication (IPARAM(1)=0), igraphdnaupd returns NP, the number c of shifts the user is to provide. 0 < NP <=NCV-NEV. See Remark c 5 below. c c IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, c OUTPUT: NUMOP = total number of OP*x operations, c NUMOPB = total number of B*x operations if BMAT='G', c NUMREO = total number of steps of re-orthogonalization. c c IPNTR Integer array of length 14. (OUTPUT) c Pointer to mark the starting locations in the WORKD and WORKL c arrays for matrices/vectors used by the Arnoldi iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X in WORKD. c IPNTR(2): pointer to the current result vector Y in WORKD. c IPNTR(3): pointer to the vector B * X in WORKD when used in c the shift-and-invert mode. c IPNTR(4): pointer to the next available location in WORKL c that is untouched by the program. c IPNTR(5): pointer to the NCV by NCV upper Hessenberg matrix c H in WORKL. c IPNTR(6): pointer to the real part of the ritz value array c RITZR in WORKL. c IPNTR(7): pointer to the imaginary part of the ritz value array c RITZI in WORKL. c IPNTR(8): pointer to the Ritz estimates in array WORKL associated c with the Ritz values located in RITZR and RITZI in WORKL. c c IPNTR(14): pointer to the NP shifts in WORKL. See Remark 5 below. c c Note: IPNTR(9:13) is only referenced by igraphdneupd. See Remark 2 below. c c IPNTR(9): pointer to the real part of the NCV RITZ values of the c original system. c IPNTR(10): pointer to the imaginary part of the NCV RITZ values of c the original system. c IPNTR(11): pointer to the NCV corresponding error bounds. c IPNTR(12): pointer to the NCV by NCV upper quasi-triangular c Schur matrix for H. c IPNTR(13): pointer to the NCV by NCV matrix of eigenvectors c of the upper Hessenberg matrix H. Only referenced by c igraphdneupd if RVEC = .TRUE. See Remark 2 below. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The user should not use WORKD c as temporary workspace during the iteration. Upon termination c WORKD(1:N) contains B*RESID(1:N). If an invariant subspace c associated with the converged Ritz values is desired, see remark c 2 below, subroutine igraphdneupd uses this output. c See Data Distribution Note below. c c WORKL Double precision work array of length LWORKL. (OUTPUT/WORKSPACE) c Private (replicated) array on each PE or array allocated on c the front end. See Data Distribution Note below. c c LWORKL Integer. (INPUT) c LWORKL must be at least 3*NCV**2 + 6*NCV. c c INFO Integer. (INPUT/OUTPUT) c If INFO .EQ. 0, a randomly initial residual vector is used. c If INFO .NE. 0, RESID contains the initial residual vector, c possibly from a previous run. c Error flag on output. c = 0: Normal exit. c = 1: Maximum number of iterations taken. c All possible eigenvalues of OP has been found. IPARAM(5) c returns the number of wanted converged Ritz values. c = 2: No longer an informational error. Deprecated starting c with release 2 of ARPACK. c = 3: No shifts could be applied during a cycle of the c Implicitly restarted Arnoldi iteration. One possibility c is to increase the size of NCV relative to NEV. c See remark 4 below. c = -1: N must be positive. c = -2: NEV must be positive. c = -3: NCV-NEV >= 2 and less than or equal to N. c = -4: The maximum number of Arnoldi update iteration c must be greater than zero. c = -5: WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI' c = -6: BMAT must be one of 'I' or 'G'. c = -7: Length of private work array is not sufficient. c = -8: Error return from LAPACK eigenvalue calculation; c = -9: Starting vector is zero. c = -10: IPARAM(7) must be 1,2,3,4. c = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable. c = -12: IPARAM(1) must be equal to 0 or 1. c = -9999: Could not build an Arnoldi factorization. c IPARAM(5) returns the size of the current Arnoldi c factorization. c c\Remarks c 1. The computed Ritz values are approximate eigenvalues of OP. The c selection of WHICH should be made with this in mind when c Mode = 3 and 4. After convergence, approximate eigenvalues of the c original problem may be obtained with the ARPACK subroutine igraphdneupd. c c 2. If a basis for the invariant subspace corresponding to the converged Ritz c values is needed, the user must call igraphdneupd immediately following c completion of igraphdnaupd. This is new starting with release 2 of ARPACK. c c 3. If M can be factored into a Cholesky factorization M = LL' c then Mode = 2 should not be selected. Instead one should use c Mode = 1 with OP = inv(L)*A*inv(L'). Appropriate triangular c linear systems should be solved with L and L' rather c than computing inverses. After convergence, an approximate c eigenvector z of the original problem is recovered by solving c L'z = x where x is a Ritz vector of OP. c c 4. At present there is no a-priori analysis to guide the selection c of NCV relative to NEV. The only formal requrement is that NCV > NEV + 2. c However, it is recommended that NCV .ge. 2*NEV+1. If many problems of c the same type are to be solved, one should experiment with increasing c NCV while keeping NEV fixed for a given test problem. This will c usually decrease the required number of OP*x operations but it c also increases the work and storage required to maintain the orthogonal c basis vectors. The optimal "cross-over" with respect to CPU time c is problem dependent and must be determined empirically. c See Chapter 8 of Reference 2 for further information. c c 5. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the c NP = IPARAM(8) real and imaginary parts of the shifts in locations c real part imaginary part c ----------------------- -------------- c 1 WORKL(IPNTR(14)) WORKL(IPNTR(14)+NP) c 2 WORKL(IPNTR(14)+1) WORKL(IPNTR(14)+NP+1) c . . c . . c . . c NP WORKL(IPNTR(14)+NP-1) WORKL(IPNTR(14)+2*NP-1). c c Only complex conjugate pairs of shifts may be applied and the pairs c must be placed in consecutive locations. The real part of the c eigenvalues of the current upper Hessenberg matrix are located in c WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1) and the imaginary part c in WORKL(IPNTR(7)) through WORKL(IPNTR(7)+NCV-1). They are ordered c according to the order defined by WHICH. The complex conjugate c pairs are kept together and the associated Ritz estimates are located in c WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1). c c----------------------------------------------------------------------- c c\Data Distribution Note: c c Fortran-D syntax: c ================ c Double precision resid(n), v(ldv,ncv), workd(3*n), workl(lworkl) c decompose d1(n), d2(n,ncv) c align resid(i) with d1(i) c align v(i,j) with d2(i,j) c align workd(i) with d1(i) range (1:n) c align workd(i) with d1(i-n) range (n+1:2*n) c align workd(i) with d1(i-2*n) range (2*n+1:3*n) c distribute d1(block), d2(block,:) c replicated workl(lworkl) c c Cray MPP syntax: c =============== c Double precision resid(n), v(ldv,ncv), workd(n,3), workl(lworkl) c shared resid(block), v(block,:), workd(block,:) c replicated workl(lworkl) c c CM2/CM5 syntax: c ============== c c----------------------------------------------------------------------- c c include 'ex-nonsym.doc' c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c 3. B.N. Parlett & Y. Saad, "Complex Shift and Invert Strategies for c Real Matrices", Linear Algebra and its Applications, vol 88/89, c pp 575-595, (1987). c c\Routines called: c igraphdnaup2 ARPACK routine that implements the Implicitly Restarted c Arnoldi Iteration. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/16/93: Version '1.1' c c\SCCS Information: @(#) c FILE: naupd.F SID: 2.5 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdnaupd & ( ido, bmat, n, which, nev, tol, resid, ncv, v, ldv, iparam, & ipntr, workd, workl, lworkl, info ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1, which*2 integer ido, info, ldv, lworkl, n, ncv, nev Double precision & tol c c %-----------------% c | Array Arguments | c %-----------------% c integer iparam(11), ipntr(14) Double precision & resid(n), v(ldv,ncv), workd(3*n), workl(lworkl) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c integer bounds, ierr, ih, iq, ishift, iupd, iw, & ldh, ldq, levec, mode, msglvl, mxiter, nb, & nev0, next, np, ritzi, ritzr, j save bounds, ih, iq, ishift, iupd, iw, ldh, ldq, & levec, mode, msglvl, mxiter, nb, nev0, next, & np, ritzi, ritzr c c %----------------------% c | External Subroutines | c %----------------------% c external igraphdnaup2, igraphdvout, igraphivout, & igraphsecond, igraphdstatn c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlamch external dlamch c c %-----------------------% c | Executable Statements | c %-----------------------% c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphdstatn call igraphsecond (t0) msglvl = mnaupd c c %----------------% c | Error checking | c %----------------% c ierr = 0 ishift = iparam(1) levec = iparam(2) mxiter = iparam(3) nb = iparam(4) c c %--------------------------------------------% c | Revision 2 performs only implicit restart. | c %--------------------------------------------% c iupd = 1 mode = iparam(7) c if (n .le. 0) then ierr = -1 else if (nev .le. 0) then ierr = -2 else if (ncv .le. nev+1 .or. ncv .gt. n) then ierr = -3 else if (mxiter .le. 0) then ierr = -4 else if (which .ne. 'LM' .and. & which .ne. 'SM' .and. & which .ne. 'LR' .and. & which .ne. 'SR' .and. & which .ne. 'LI' .and. & which .ne. 'SI') then ierr = -5 else if (bmat .ne. 'I' .and. bmat .ne. 'G') then ierr = -6 else if (lworkl .lt. 3*ncv**2 + 6*ncv) then ierr = -7 else if (mode .lt. 1 .or. mode .gt. 5) then ierr = -10 else if (mode .eq. 1 .and. bmat .eq. 'G') then ierr = -11 else if (ishift .lt. 0 .or. ishift .gt. 1) then ierr = -12 end if c c %------------% c | Error Exit | c %------------% c if (ierr .ne. 0) then info = ierr ido = 99 go to 9000 end if c c %------------------------% c | Set default parameters | c %------------------------% c if (nb .le. 0) nb = 1 if (tol .le. zero) tol = dlamch('EpsMach') c c %----------------------------------------------% c | NP is the number of additional steps to | c | extend the length NEV Lanczos factorization. | c | NEV0 is the local variable designating the | c | size of the invariant subspace desired. | c %----------------------------------------------% c np = ncv - nev nev0 = nev c c %-----------------------------% c | Zero out internal workspace | c %-----------------------------% c do 10 j = 1, 3*ncv**2 + 6*ncv workl(j) = zero 10 continue c c %-------------------------------------------------------------% c | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | c | etc... and the remaining workspace. | c | Also update pointer to be used on output. | c | Memory is laid out as follows: | c | workl(1:ncv*ncv) := generated Hessenberg matrix | c | workl(ncv*ncv+1:ncv*ncv+2*ncv) := real and imaginary | c | parts of ritz values | c | workl(ncv*ncv+2*ncv+1:ncv*ncv+3*ncv) := error bounds | c | workl(ncv*ncv+3*ncv+1:2*ncv*ncv+3*ncv) := rotation matrix Q | c | workl(2*ncv*ncv+3*ncv+1:3*ncv*ncv+6*ncv) := workspace | c | The final workspace is needed by subroutine igraphdneigh called | c | by igraphdnaup2. Subroutine igraphdneigh calls LAPACK routines for | c | calculating eigenvalues and the last row of the eigenvector | c | matrix. | c %-------------------------------------------------------------% c ldh = ncv ldq = ncv ih = 1 ritzr = ih + ldh*ncv ritzi = ritzr + ncv bounds = ritzi + ncv iq = bounds + ncv iw = iq + ldq*ncv next = iw + ncv**2 + 3*ncv c ipntr(4) = next ipntr(5) = ih ipntr(6) = ritzr ipntr(7) = ritzi ipntr(8) = bounds ipntr(14) = iw c end if c c %-------------------------------------------------------% c | Carry out the Implicitly restarted Arnoldi Iteration. | c %-------------------------------------------------------% c call igraphdnaup2 & ( ido, bmat, n, which, nev0, np, tol, resid, mode, iupd, & ishift, mxiter, v, ldv, workl(ih), ldh, workl(ritzr), & workl(ritzi), workl(bounds), workl(iq), ldq, workl(iw), & ipntr, workd, info ) c c %--------------------------------------------------% c | ido .ne. 99 implies use of reverse communication | c | to compute operations involving OP or shifts. | c %--------------------------------------------------% c if (ido .eq. 3) iparam(8) = np if (ido .ne. 99) go to 9000 c iparam(3) = mxiter iparam(5) = np iparam(9) = nopx iparam(10) = nbx iparam(11) = nrorth c c %------------------------------------% c | Exit if there was an informational | c | error within igraphdnaup2. | c %------------------------------------% c if (info .lt. 0) go to 9000 if (info .eq. 2) info = 3 c if (msglvl .gt. 0) then call igraphivout (logfil, 1, mxiter, ndigit, & '_naupd: Number of update iterations taken') call igraphivout (logfil, 1, np, ndigit, & '_naupd: Number of wanted "converged" Ritz values') call igraphdvout (logfil, np, workl(ritzr), ndigit, & '_naupd: Real part of the final Ritz values') call igraphdvout (logfil, np, workl(ritzi), ndigit, & '_naupd: Imaginary part of the final Ritz values') call igraphdvout (logfil, np, workl(bounds), ndigit, & '_naupd: Associated Ritz estimates') end if c call igraphsecond (t1) tnaupd = t1 - t0 c c 9000 continue c return c c %---------------% c | End of igraphdnaupd | c %---------------% c end igraph/src/AMD/0000755000175100001440000000000013430770171012735 5ustar hornikusersigraph/src/AMD/Include/0000755000175100001440000000000013430770171014320 5ustar hornikusersigraph/src/AMD/Include/amd.h0000644000175100001440000004363013431000472015227 0ustar hornikusers/* ========================================================================= */ /* === AMD: approximate minimum degree ordering =========================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD Version 2.2, Copyright (c) 2007 by Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* AMD finds a symmetric ordering P of a matrix A so that the Cholesky * factorization of P*A*P' has fewer nonzeros and takes less work than the * Cholesky factorization of A. If A is not symmetric, then it performs its * ordering on the matrix A+A'. Two sets of user-callable routines are * provided, one for int integers and the other for SuiteSparse_long integers. * * The method is based on the approximate minimum degree algorithm, discussed * in Amestoy, Davis, and Duff, "An approximate degree ordering algorithm", * SIAM Journal of Matrix Analysis and Applications, vol. 17, no. 4, pp. * 886-905, 1996. This package can perform both the AMD ordering (with * aggressive absorption), and the AMDBAR ordering (without aggressive * absorption) discussed in the above paper. This package differs from the * Fortran codes discussed in the paper: * * (1) it can ignore "dense" rows and columns, leading to faster run times * (2) it computes the ordering of A+A' if A is not symmetric * (3) it is followed by a depth-first post-ordering of the assembly tree * (or supernodal elimination tree) * * For historical reasons, the Fortran versions, amd.f and amdbar.f, have * been left (nearly) unchanged. They compute the identical ordering as * described in the above paper. */ #ifndef AMD_H #define AMD_H /* make it easy for C++ programs to include AMD */ #ifdef __cplusplus extern "C" { #endif /* get the definition of size_t: */ #include #include "SuiteSparse_config.h" int amd_order /* returns AMD_OK, AMD_OK_BUT_JUMBLED, * AMD_INVALID, or AMD_OUT_OF_MEMORY */ ( int n, /* A is n-by-n. n must be >= 0. */ const int Ap [ ], /* column pointers for A, of size n+1 */ const int Ai [ ], /* row indices of A, of size nz = Ap [n] */ int P [ ], /* output permutation, of size n */ double Control [ ], /* input Control settings, of size AMD_CONTROL */ double Info [ ] /* output Info statistics, of size AMD_INFO */ ) ; SuiteSparse_long amd_l_order /* see above for description of arguments */ ( SuiteSparse_long n, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], SuiteSparse_long P [ ], double Control [ ], double Info [ ] ) ; /* Input arguments (not modified): * * n: the matrix A is n-by-n. * Ap: an int/SuiteSparse_long array of size n+1, containing column * pointers of A. * Ai: an int/SuiteSparse_long array of size nz, containing the row * indices of A, where nz = Ap [n]. * Control: a double array of size AMD_CONTROL, containing control * parameters. Defaults are used if Control is NULL. * * Output arguments (not defined on input): * * P: an int/SuiteSparse_long array of size n, containing the output * permutation. If row i is the kth pivot row, then P [k] = i. In * MATLAB notation, the reordered matrix is A (P,P). * Info: a double array of size AMD_INFO, containing statistical * information. Ignored if Info is NULL. * * On input, the matrix A is stored in column-oriented form. The row indices * of nonzero entries in column j are stored in Ai [Ap [j] ... Ap [j+1]-1]. * * If the row indices appear in ascending order in each column, and there * are no duplicate entries, then amd_order is slightly more efficient in * terms of time and memory usage. If this condition does not hold, a copy * of the matrix is created (where these conditions do hold), and the copy is * ordered. This feature is new to v2.0 (v1.2 and earlier required this * condition to hold for the input matrix). * * Row indices must be in the range 0 to * n-1. Ap [0] must be zero, and thus nz = Ap [n] is the number of nonzeros * in A. The array Ap is of size n+1, and the array Ai is of size nz = Ap [n]. * The matrix does not need to be symmetric, and the diagonal does not need to * be present (if diagonal entries are present, they are ignored except for * the output statistic Info [AMD_NZDIAG]). The arrays Ai and Ap are not * modified. This form of the Ap and Ai arrays to represent the nonzero * pattern of the matrix A is the same as that used internally by MATLAB. * If you wish to use a more flexible input structure, please see the * umfpack_*_triplet_to_col routines in the UMFPACK package, at * http://www.suitesparse.com. * * Restrictions: n >= 0. Ap [0] = 0. Ap [j] <= Ap [j+1] for all j in the * range 0 to n-1. nz = Ap [n] >= 0. Ai [0..nz-1] must be in the range 0 * to n-1. Finally, Ai, Ap, and P must not be NULL. If any of these * restrictions are not met, AMD returns AMD_INVALID. * * AMD returns: * * AMD_OK if the matrix is valid and sufficient memory can be allocated to * perform the ordering. * * AMD_OUT_OF_MEMORY if not enough memory can be allocated. * * AMD_INVALID if the input arguments n, Ap, Ai are invalid, or if P is * NULL. * * AMD_OK_BUT_JUMBLED if the matrix had unsorted columns, and/or duplicate * entries, but was otherwise valid. * * The AMD routine first forms the pattern of the matrix A+A', and then * computes a fill-reducing ordering, P. If P [k] = i, then row/column i of * the original is the kth pivotal row. In MATLAB notation, the permuted * matrix is A (P,P), except that 0-based indexing is used instead of the * 1-based indexing in MATLAB. * * The Control array is used to set various parameters for AMD. If a NULL * pointer is passed, default values are used. The Control array is not * modified. * * Control [AMD_DENSE]: controls the threshold for "dense" rows/columns. * A dense row/column in A+A' can cause AMD to spend a lot of time in * ordering the matrix. If Control [AMD_DENSE] >= 0, rows/columns * with more than Control [AMD_DENSE] * sqrt (n) entries are ignored * during the ordering, and placed last in the output order. The * default value of Control [AMD_DENSE] is 10. If negative, no * rows/columns are treated as "dense". Rows/columns with 16 or * fewer off-diagonal entries are never considered "dense". * * Control [AMD_AGGRESSIVE]: controls whether or not to use aggressive * absorption, in which a prior element is absorbed into the current * element if is a subset of the current element, even if it is not * adjacent to the current pivot element (refer to Amestoy, Davis, * & Duff, 1996, for more details). The default value is nonzero, * which means to perform aggressive absorption. This nearly always * leads to a better ordering (because the approximate degrees are * more accurate) and a lower execution time. There are cases where * it can lead to a slightly worse ordering, however. To turn it off, * set Control [AMD_AGGRESSIVE] to 0. * * Control [2..4] are not used in the current version, but may be used in * future versions. * * The Info array provides statistics about the ordering on output. If it is * not present, the statistics are not returned. This is not an error * condition. * * Info [AMD_STATUS]: the return value of AMD, either AMD_OK, * AMD_OK_BUT_JUMBLED, AMD_OUT_OF_MEMORY, or AMD_INVALID. * * Info [AMD_N]: n, the size of the input matrix * * Info [AMD_NZ]: the number of nonzeros in A, nz = Ap [n] * * Info [AMD_SYMMETRY]: the symmetry of the matrix A. It is the number * of "matched" off-diagonal entries divided by the total number of * off-diagonal entries. An entry A(i,j) is matched if A(j,i) is also * an entry, for any pair (i,j) for which i != j. In MATLAB notation, * S = spones (A) ; * B = tril (S, -1) + triu (S, 1) ; * symmetry = nnz (B & B') / nnz (B) ; * * Info [AMD_NZDIAG]: the number of entries on the diagonal of A. * * Info [AMD_NZ_A_PLUS_AT]: the number of nonzeros in A+A', excluding the * diagonal. If A is perfectly symmetric (Info [AMD_SYMMETRY] = 1) * with a fully nonzero diagonal, then Info [AMD_NZ_A_PLUS_AT] = nz-n * (the smallest possible value). If A is perfectly unsymmetric * (Info [AMD_SYMMETRY] = 0, for an upper triangular matrix, for * example) with no diagonal, then Info [AMD_NZ_A_PLUS_AT] = 2*nz * (the largest possible value). * * Info [AMD_NDENSE]: the number of "dense" rows/columns of A+A' that were * removed from A prior to ordering. These are placed last in the * output order P. * * Info [AMD_MEMORY]: the amount of memory used by AMD, in bytes. In the * current version, this is 1.2 * Info [AMD_NZ_A_PLUS_AT] + 9*n * times the size of an integer. This is at most 2.4nz + 9n. This * excludes the size of the input arguments Ai, Ap, and P, which have * a total size of nz + 2*n + 1 integers. * * Info [AMD_NCMPA]: the number of garbage collections performed. * * Info [AMD_LNZ]: the number of nonzeros in L (excluding the diagonal). * This is a slight upper bound because mass elimination is combined * with the approximate degree update. It is a rough upper bound if * there are many "dense" rows/columns. The rest of the statistics, * below, are also slight or rough upper bounds, for the same reasons. * The post-ordering of the assembly tree might also not exactly * correspond to a true elimination tree postordering. * * Info [AMD_NDIV]: the number of divide operations for a subsequent LDL' * or LU factorization of the permuted matrix A (P,P). * * Info [AMD_NMULTSUBS_LDL]: the number of multiply-subtract pairs for a * subsequent LDL' factorization of A (P,P). * * Info [AMD_NMULTSUBS_LU]: the number of multiply-subtract pairs for a * subsequent LU factorization of A (P,P), assuming that no numerical * pivoting is required. * * Info [AMD_DMAX]: the maximum number of nonzeros in any column of L, * including the diagonal. * * Info [14..19] are not used in the current version, but may be used in * future versions. */ /* ------------------------------------------------------------------------- */ /* direct interface to AMD */ /* ------------------------------------------------------------------------- */ /* amd_2 is the primary AMD ordering routine. It is not meant to be * user-callable because of its restrictive inputs and because it destroys * the user's input matrix. It does not check its inputs for errors, either. * However, if you can work with these restrictions it can be faster than * amd_order and use less memory (assuming that you can create your own copy * of the matrix for AMD to destroy). Refer to AMD/Source/amd_2.c for a * description of each parameter. */ void amd_2 ( int n, int Pe [ ], int Iw [ ], int Len [ ], int iwlen, int pfree, int Nv [ ], int Next [ ], int Last [ ], int Head [ ], int Elen [ ], int Degree [ ], int W [ ], double Control [ ], double Info [ ] ) ; void amd_l2 ( SuiteSparse_long n, SuiteSparse_long Pe [ ], SuiteSparse_long Iw [ ], SuiteSparse_long Len [ ], SuiteSparse_long iwlen, SuiteSparse_long pfree, SuiteSparse_long Nv [ ], SuiteSparse_long Next [ ], SuiteSparse_long Last [ ], SuiteSparse_long Head [ ], SuiteSparse_long Elen [ ], SuiteSparse_long Degree [ ], SuiteSparse_long W [ ], double Control [ ], double Info [ ] ) ; /* ------------------------------------------------------------------------- */ /* amd_valid */ /* ------------------------------------------------------------------------- */ /* Returns AMD_OK or AMD_OK_BUT_JUMBLED if the matrix is valid as input to * amd_order; the latter is returned if the matrix has unsorted and/or * duplicate row indices in one or more columns. Returns AMD_INVALID if the * matrix cannot be passed to amd_order. For amd_order, the matrix must also * be square. The first two arguments are the number of rows and the number * of columns of the matrix. For its use in AMD, these must both equal n. * * NOTE: this routine returned TRUE/FALSE in v1.2 and earlier. */ int amd_valid ( int n_row, /* # of rows */ int n_col, /* # of columns */ const int Ap [ ], /* column pointers, of size n_col+1 */ const int Ai [ ] /* row indices, of size Ap [n_col] */ ) ; SuiteSparse_long amd_l_valid ( SuiteSparse_long n_row, SuiteSparse_long n_col, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ] ) ; /* ------------------------------------------------------------------------- */ /* AMD memory manager and printf routines */ /* ------------------------------------------------------------------------- */ /* The user can redefine these to change the malloc, free, and printf routines * that AMD uses. */ #ifndef EXTERN #define EXTERN extern #endif EXTERN void *(*amd_malloc) (size_t) ; /* pointer to malloc */ EXTERN void (*amd_free) (void *) ; /* pointer to free */ EXTERN void *(*amd_realloc) (void *, size_t) ; /* pointer to realloc */ EXTERN void *(*amd_calloc) (size_t, size_t) ; /* pointer to calloc */ EXTERN int (*amd_printf) (const char *, ...) ; /* pointer to printf */ /* ------------------------------------------------------------------------- */ /* AMD Control and Info arrays */ /* ------------------------------------------------------------------------- */ /* amd_defaults: sets the default control settings */ void amd_defaults (double Control [ ]) ; void amd_l_defaults (double Control [ ]) ; /* amd_control: prints the control settings */ void amd_control (double Control [ ]) ; void amd_l_control (double Control [ ]) ; /* amd_info: prints the statistics */ void amd_info (double Info [ ]) ; void amd_l_info (double Info [ ]) ; #define AMD_CONTROL 5 /* size of Control array */ #define AMD_INFO 20 /* size of Info array */ /* contents of Control */ #define AMD_DENSE 0 /* "dense" if degree > Control [0] * sqrt (n) */ #define AMD_AGGRESSIVE 1 /* do aggressive absorption if Control [1] != 0 */ /* default Control settings */ #define AMD_DEFAULT_DENSE 10.0 /* default "dense" degree 10*sqrt(n) */ #define AMD_DEFAULT_AGGRESSIVE 1 /* do aggressive absorption by default */ /* contents of Info */ #define AMD_STATUS 0 /* return value of amd_order and amd_l_order */ #define AMD_N 1 /* A is n-by-n */ #define AMD_NZ 2 /* number of nonzeros in A */ #define AMD_SYMMETRY 3 /* symmetry of pattern (1 is sym., 0 is unsym.) */ #define AMD_NZDIAG 4 /* # of entries on diagonal */ #define AMD_NZ_A_PLUS_AT 5 /* nz in A+A' */ #define AMD_NDENSE 6 /* number of "dense" rows/columns in A */ #define AMD_MEMORY 7 /* amount of memory used by AMD */ #define AMD_NCMPA 8 /* number of garbage collections in AMD */ #define AMD_LNZ 9 /* approx. nz in L, excluding the diagonal */ #define AMD_NDIV 10 /* number of fl. point divides for LU and LDL' */ #define AMD_NMULTSUBS_LDL 11 /* number of fl. point (*,-) pairs for LDL' */ #define AMD_NMULTSUBS_LU 12 /* number of fl. point (*,-) pairs for LU */ #define AMD_DMAX 13 /* max nz. in any column of L, incl. diagonal */ /* ------------------------------------------------------------------------- */ /* return values of AMD */ /* ------------------------------------------------------------------------- */ #define AMD_OK 0 /* success */ #define AMD_OUT_OF_MEMORY -1 /* malloc failed, or problem too large */ #define AMD_INVALID -2 /* input arguments are not valid */ #define AMD_OK_BUT_JUMBLED 1 /* input matrix is OK for amd_order, but * columns were not sorted, and/or duplicate entries were present. AMD had * to do extra work before ordering the matrix. This is a warning, not an * error. */ /* ========================================================================== */ /* === AMD version ========================================================== */ /* ========================================================================== */ /* AMD Version 1.2 and later include the following definitions. * As an example, to test if the version you are using is 1.2 or later: * * #ifdef AMD_VERSION * if (AMD_VERSION >= AMD_VERSION_CODE (1,2)) ... * #endif * * This also works during compile-time: * * #if defined(AMD_VERSION) && (AMD_VERSION >= AMD_VERSION_CODE (1,2)) * printf ("This is version 1.2 or later\n") ; * #else * printf ("This is an early version\n") ; * #endif * * Versions 1.1 and earlier of AMD do not include a #define'd version number. */ #define AMD_DATE "Jun 20, 2012" #define AMD_VERSION_CODE(main,sub) ((main) * 1000 + (sub)) #define AMD_MAIN_VERSION 2 #define AMD_SUB_VERSION 3 #define AMD_SUBSUB_VERSION 1 #define AMD_VERSION AMD_VERSION_CODE(AMD_MAIN_VERSION,AMD_SUB_VERSION) #ifdef __cplusplus } #endif #endif igraph/src/AMD/Include/amd_internal.h0000644000175100001440000002161113431000472017116 0ustar hornikusers/* ========================================================================= */ /* === amd_internal.h ====================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* This file is for internal use in AMD itself, and does not normally need to * be included in user code (it is included in UMFPACK, however). All others * should use amd.h instead. * * The following compile-time definitions affect how AMD is compiled. * * -DNPRINT * * Disable all printing. stdio.h will not be included. Printing can * be re-enabled at run-time by setting the global pointer amd_printf * to printf (or mexPrintf for a MATLAB mexFunction). * * -DNMALLOC * * No memory manager is defined at compile-time. You MUST define the * function pointers amd_malloc, amd_free, amd_realloc, and * amd_calloc at run-time for AMD to work properly. */ /* ========================================================================= */ /* === NDEBUG ============================================================== */ /* ========================================================================= */ /* * Turning on debugging takes some work (see below). If you do not edit this * file, then debugging is always turned off, regardless of whether or not * -DNDEBUG is specified in your compiler options. * * If AMD is being compiled as a mexFunction, then MATLAB_MEX_FILE is defined, * and mxAssert is used instead of assert. If debugging is not enabled, no * MATLAB include files or functions are used. Thus, the AMD library libamd.a * can be safely used in either a stand-alone C program or in another * mexFunction, without any change. */ /* AMD will be exceedingly slow when running in debug mode. The next three lines ensure that debugging is turned off. */ #ifndef NDEBUG #define NDEBUG #endif /* To enable debugging, uncomment the following line: #undef NDEBUG */ /* ------------------------------------------------------------------------- */ /* ANSI include files */ /* ------------------------------------------------------------------------- */ /* from stdlib.h: size_t, malloc, free, realloc, and calloc */ #include #if !defined(NPRINT) || !defined(NDEBUG) /* from stdio.h: printf. Not included if NPRINT is defined at compile time. * fopen and fscanf are used when debugging. */ #include #endif /* from limits.h: INT_MAX and LONG_MAX */ #include /* from math.h: sqrt */ #include /* ------------------------------------------------------------------------- */ /* MATLAB include files (only if being used in or via MATLAB) */ /* ------------------------------------------------------------------------- */ #ifdef MATLAB_MEX_FILE #include "matrix.h" #include "mex.h" #endif /* ------------------------------------------------------------------------- */ /* basic definitions */ /* ------------------------------------------------------------------------- */ #ifdef FLIP #undef FLIP #endif #ifdef MAX #undef MAX #endif #ifdef MIN #undef MIN #endif #ifdef EMPTY #undef EMPTY #endif #ifdef GLOBAL #undef GLOBAL #endif #ifdef PRIVATE #undef PRIVATE #endif /* FLIP is a "negation about -1", and is used to mark an integer i that is * normally non-negative. FLIP (EMPTY) is EMPTY. FLIP of a number > EMPTY * is negative, and FLIP of a number < EMTPY is positive. FLIP (FLIP (i)) = i * for all integers i. UNFLIP (i) is >= EMPTY. */ #define EMPTY (-1) #define FLIP(i) (-(i)-2) #define UNFLIP(i) ((i < EMPTY) ? FLIP (i) : (i)) /* for integer MAX/MIN, or for doubles when we don't care how NaN's behave: */ #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) /* logical expression of p implies q: */ #define IMPLIES(p,q) (!(p) || (q)) /* Note that the IBM RS 6000 xlc predefines TRUE and FALSE in . */ /* The Compaq Alpha also predefines TRUE and FALSE. */ #ifdef TRUE #undef TRUE #endif #ifdef FALSE #undef FALSE #endif #define TRUE (1) #define FALSE (0) #define PRIVATE static #define GLOBAL #define EMPTY (-1) /* Note that Linux's gcc 2.96 defines NULL as ((void *) 0), but other */ /* compilers (even gcc 2.95.2 on Solaris) define NULL as 0 or (0). We */ /* need to use the ANSI standard value of 0. */ #ifdef NULL #undef NULL #endif #define NULL 0 /* largest value of size_t */ #ifndef SIZE_T_MAX #ifdef SIZE_MAX /* C99 only */ #define SIZE_T_MAX SIZE_MAX #else #define SIZE_T_MAX ((size_t) (-1)) #endif #endif /* ------------------------------------------------------------------------- */ /* integer type for AMD: int or SuiteSparse_long */ /* ------------------------------------------------------------------------- */ #include "amd.h" #if defined (DLONG) || defined (ZLONG) #define Int SuiteSparse_long #define ID SuiteSparse_long_id #define Int_MAX SuiteSparse_long_max #define AMD_order amd_l_order #define AMD_defaults amd_l_defaults #define AMD_control amd_l_control #define AMD_info amd_l_info #define AMD_1 amd_l1 #define AMD_2 amd_l2 #define AMD_valid amd_l_valid #define AMD_aat amd_l_aat #define AMD_postorder amd_l_postorder #define AMD_post_tree amd_l_post_tree #define AMD_dump amd_l_dump #define AMD_debug amd_l_debug #define AMD_debug_init amd_l_debug_init #define AMD_preprocess amd_l_preprocess #else #define Int int #define ID "%d" #define Int_MAX INT_MAX #define AMD_order amd_order #define AMD_defaults amd_defaults #define AMD_control amd_control #define AMD_info amd_info #define AMD_1 amd_1 #define AMD_2 amd_2 #define AMD_valid amd_valid #define AMD_aat amd_aat #define AMD_postorder amd_postorder #define AMD_post_tree amd_post_tree #define AMD_dump amd_dump #define AMD_debug amd_debug #define AMD_debug_init amd_debug_init #define AMD_preprocess amd_preprocess #endif /* ========================================================================= */ /* === PRINTF macro ======================================================== */ /* ========================================================================= */ /* All output goes through the PRINTF macro. */ #define PRINTF(params) { if (amd_printf != NULL) (void) amd_printf params ; } /* ------------------------------------------------------------------------- */ /* AMD routine definitions (not user-callable) */ /* ------------------------------------------------------------------------- */ GLOBAL size_t AMD_aat ( Int n, const Int Ap [ ], const Int Ai [ ], Int Len [ ], Int Tp [ ], double Info [ ] ) ; GLOBAL void AMD_1 ( Int n, const Int Ap [ ], const Int Ai [ ], Int P [ ], Int Pinv [ ], Int Len [ ], Int slen, Int S [ ], double Control [ ], double Info [ ] ) ; GLOBAL void AMD_postorder ( Int nn, Int Parent [ ], Int Npiv [ ], Int Fsize [ ], Int Order [ ], Int Child [ ], Int Sibling [ ], Int Stack [ ] ) ; GLOBAL Int AMD_post_tree ( Int root, Int k, Int Child [ ], const Int Sibling [ ], Int Order [ ], Int Stack [ ] #ifndef NDEBUG , Int nn #endif ) ; GLOBAL void AMD_preprocess ( Int n, const Int Ap [ ], const Int Ai [ ], Int Rp [ ], Int Ri [ ], Int W [ ], Int Flag [ ] ) ; /* ------------------------------------------------------------------------- */ /* debugging definitions */ /* ------------------------------------------------------------------------- */ #ifndef NDEBUG /* from assert.h: assert macro */ #include #ifndef EXTERN #define EXTERN extern #endif EXTERN Int AMD_debug ; GLOBAL void AMD_debug_init ( char *s ) ; GLOBAL void AMD_dump ( Int n, Int Pe [ ], Int Iw [ ], Int Len [ ], Int iwlen, Int pfree, Int Nv [ ], Int Next [ ], Int Last [ ], Int Head [ ], Int Elen [ ], Int Degree [ ], Int W [ ], Int nel ) ; #ifdef ASSERT #undef ASSERT #endif /* Use mxAssert if AMD is compiled into a mexFunction */ #ifdef MATLAB_MEX_FILE #define ASSERT(expression) (mxAssert ((expression), "")) #else #define ASSERT(expression) (assert (expression)) #endif #define AMD_DEBUG0(params) { PRINTF (params) ; } #define AMD_DEBUG1(params) { if (AMD_debug >= 1) PRINTF (params) ; } #define AMD_DEBUG2(params) { if (AMD_debug >= 2) PRINTF (params) ; } #define AMD_DEBUG3(params) { if (AMD_debug >= 3) PRINTF (params) ; } #define AMD_DEBUG4(params) { if (AMD_debug >= 4) PRINTF (params) ; } #else /* no debugging */ #define ASSERT(expression) #define AMD_DEBUG0(params) #define AMD_DEBUG1(params) #define AMD_DEBUG2(params) #define AMD_DEBUG3(params) #define AMD_DEBUG4(params) #endif igraph/src/AMD/README.txt0000644000175100001440000002130113430770171014430 0ustar hornikusersAMD, Copyright (c) 2009-2012 by Timothy A. Davis (http://www.suitesparse.com), Patrick R. Amestoy, and Iain S. Duff. All Rights Reserved. AMD is available under alternate licences; contact T. Davis for details. AMD: a set of routines for permuting sparse matrices prior to factorization. Includes a version in C, a version in Fortran, and a MATLAB mexFunction. Requires SuiteSparse_config, in the ../SuiteSparse_config directory relative to this directory. Quick start (Unix, or Windows with Cygwin): To compile, test, and install AMD, you may wish to first configure the installation by editting the ../SuiteSparse_config/SuiteSparse_config.mk file. Next, cd to this directory (AMD) and type "make" (or "make lib" if you do not have MATLAB). To compile and run a demo program for the Fortran version, type "make fortran". When done, type "make clean" to remove unused *.o files (keeps the compiled libraries and demo programs). See the User Guide (Doc/AMD_UserGuide.pdf), or ../SuiteSparse_config/SuiteSparse_config.mk for more details. Quick start (for MATLAB users); To compile, test, and install the AMD mexFunction, cd to the AMD/MATLAB directory and type amd_make at the MATLAB prompt. ------------------------------------------------------------------------------- AMD License: Your use or distribution of AMD or any modified version of AMD implies that you agree to this License. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Permission is hereby granted to use or copy this program under the terms of the GNU LGPL, provided that the Copyright, this License, and the Availability of the original version is retained on all copies. User documentation of any code that uses this code or any modified version of this code must cite the Copyright, this License, the Availability note, and "Used by permission." Permission to modify the code and to distribute modified code is granted, provided the Copyright, this License, and the Availability note are retained, and a notice that the code was modified is included. Availability: http://www.suitesparse.com ------------------------------------------------------------------------------- This is the AMD README file. It is a terse overview of AMD. Refer to the User Guide (Doc/AMD_UserGuide.pdf) for how to install and use AMD. Description: AMD is a set of routines for pre-ordering sparse matrices prior to Cholesky or LU factorization, using the approximate minimum degree ordering algorithm. Written in ANSI/ISO C with a MATLAB interface, and in Fortran 77. Authors: Timothy A. Davis (DrTimothyAldenDavis@gmail.com) Patrick R. Amestory, ENSEEIHT, Toulouse, France. Iain S. Duff, Rutherford Appleton Laboratory, UK. Acknowledgements: This work was supported by the National Science Foundation, under grants DMS-9504974, DMS-9803599, and CCR-0203270. Portions of this work were done while on sabbatical at Stanford University and Lawrence Berkeley National Laboratory (with funding from the SciDAC program). I would like to thank Gene Golub, Esmond Ng, and Horst Simon for making this sabbatical possible. ------------------------------------------------------------------------------- Files and directories in the AMD distribution: ------------------------------------------------------------------------------- --------------------------------------------------------------------------- Subdirectories of the AMD directory: --------------------------------------------------------------------------- Doc documentation Source primary source code Include include file for use in your code that calls AMD Demo demo programs. also serves as test of the AMD installation. MATLAB AMD mexFunction for MATLAB, and supporting m-files Lib where the compiled C-callable and Fortran-callable AMD libraries placed. --------------------------------------------------------------------------- Files in the AMD directory: --------------------------------------------------------------------------- Makefile top-level Makefile for GNU make or original make. Windows users would require Cygwin to use "make" README.txt this file --------------------------------------------------------------------------- Doc directory: documentation --------------------------------------------------------------------------- ChangeLog change log License the AMD License Makefile for creating the documentation AMD_UserGuide.bib AMD User Guide (references) AMD_UserGuide.tex AMD User Guide (LaTeX) AMD_UserGuide.pdf AMD User Guide (PDF) lesser.txt the GNU LGPL license --------------------------------------------------------------------------- Source directory: --------------------------------------------------------------------------- amd_order.c user-callable, primary AMD ordering routine amd_control.c user-callable, prints the control parameters amd_defaults.c user-callable, sets default control parameters amd_info.c user-callable, prints the statistics from AMD amd_1.c non-user-callable, construct A+A' amd_2.c user-callable, primary ordering kernel (a C version of amd.f and amdbar.f, with post-ordering added) amd_aat.c non-user-callable, computes nnz (A+A') amd_dump.c non-user-callable, debugging routines amd_postorder.c non-user-callable, postorder amd_post_tree.c non-user-callable, postorder just one tree amd_valid.c non-user-callable, verifies a matrix amd_preprocess.c non-user-callable, computes A', removes duplic amd.f user-callable Fortran 77 version amdbar.f user-callable Fortran 77 version --------------------------------------------------------------------------- Include directory: --------------------------------------------------------------------------- amd.h include file for C programs that use AMD amd_internal.h non-user-callable, include file for AMD --------------------------------------------------------------------------- Demo directory: --------------------------------------------------------------------------- Makefile for GNU make or original make amd_demo.c C demo program for AMD amd_demo.out output of amd_demo.c amd_demo2.c C demo program for AMD, jumbled matrix amd_demo2.out output of amd_demo2.c amd_l_demo.c C demo program for AMD (long integer version) amd_l_demo.out output of amd_l_demo.c amd_simple.c simple C demo program for AMD amd_simple.out output of amd_simple.c amd_f77demo.f Fortran 77 demo program for AMD amd_f77demo.out output of amd_f77demo.f amd_f77simple.c simple Fortran 77 demo program for AMD amd_f77simple.out output of amd_f77simple.f amd_f77cross.f Fortran 77 demo, calls the C version of AMD amd_f77cross.out output of amd_f77cross.f amd_f77wrapper.c Fortran-callable wrapper for C version of AMD --------------------------------------------------------------------------- MATLAB directory: --------------------------------------------------------------------------- GNUmakefile a nice Makefile, for GNU make Makefile an ugly Unix Makefile (for older make's) Contents.m for "help amd2" listing of toolbox contents amd2.m MATLAB help file for AMD amd_make.m MATLAB m-file for compiling AMD mexFunction amd_install.m compile and install the AMD mexFunction amd_mex.c AMD mexFunction for MATLAB amd_demo.m MATLAB demo for AMD amd_demo.m.out diary output of amd_demo.m can_24.mat input file for AMD demo --------------------------------------------------------------------------- Lib directory: libamd.a and libamdf77.a libraries placed here --------------------------------------------------------------------------- GNUmakefile a nice Makefile, for GNU make Makefile an ugly Unix Makefile (for older make's) libamd.def AMD definitions for Windows igraph/src/AMD/Makefile0000644000175100001440000000337513562737552014421 0ustar hornikusers#------------------------------------------------------------------------------ # AMD Makefile (for GNU Make or original make) #------------------------------------------------------------------------------ VERSION = 2.3.1 default: all include ../SuiteSparse_config/SuiteSparse_config.mk demos: all # Compile all C code. Do not compile the FORTRAN versions. all: ( cd Lib ; $(MAKE) ) ( cd Demo ; $(MAKE) ) # compile just the C-callable libraries (not Demos) library: ( cd Lib ; $(MAKE) ) # compile the FORTRAN libraries and demo programs (not compiled by "make all") fortran: ( cd Lib ; $(MAKE) fortran ) ( cd Demo ; $(MAKE) fortran ) # compile a FORTRAN demo program that calls the C version of AMD # (not compiled by "make all") cross: ( cd Demo ; $(MAKE) cross ) # remove object files, but keep the compiled programs and library archives clean: ( cd Lib ; $(MAKE) clean ) ( cd Demo ; $(MAKE) clean ) ( cd MATLAB ; $(RM) $(CLEAN) ) ( cd Doc ; $(MAKE) clean ) # clean, and then remove compiled programs and library archives purge: ( cd Lib ; $(MAKE) purge ) ( cd Demo ; $(MAKE) purge ) ( cd MATLAB ; $(RM) $(CLEAN) ; $(RM) *.mex* ) ( cd Doc ; $(MAKE) purge ) distclean: purge # create PDF documents for the original distribution docs: ( cd Doc ; $(MAKE) ) # get ready for distribution dist: purge ( cd Demo ; $(MAKE) dist ) ( cd Doc ; $(MAKE) ) ccode: library lib: library # install AMD install: $(CP) Lib/libamd.a $(INSTALL_LIB)/libamd.$(VERSION).a ( cd $(INSTALL_LIB) ; ln -sf libamd.$(VERSION).a libamd.a ) $(CP) Include/amd.h $(INSTALL_INCLUDE) chmod 644 $(INSTALL_LIB)/libamd* chmod 644 $(INSTALL_INCLUDE)/amd.h # uninstall AMD uninstall: $(RM) $(INSTALL_LIB)/libamd*.a $(RM) $(INSTALL_INCLUDE)/amd.h igraph/src/AMD/Source/0000755000175100001440000000000013561251652014200 5ustar hornikusersigraph/src/AMD/Source/amd_postorder.c0000644000175100001440000001260513431000472017176 0ustar hornikusers/* ========================================================================= */ /* === AMD_postorder ======================================================= */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* Perform a postordering (via depth-first search) of an assembly tree. */ #include "amd_internal.h" GLOBAL void AMD_postorder ( /* inputs, not modified on output: */ Int nn, /* nodes are in the range 0..nn-1 */ Int Parent [ ], /* Parent [j] is the parent of j, or EMPTY if root */ Int Nv [ ], /* Nv [j] > 0 number of pivots represented by node j, * or zero if j is not a node. */ Int Fsize [ ], /* Fsize [j]: size of node j */ /* output, not defined on input: */ Int Order [ ], /* output post-order */ /* workspaces of size nn: */ Int Child [ ], Int Sibling [ ], Int Stack [ ] ) { Int i, j, k, parent, frsize, f, fprev, maxfrsize, bigfprev, bigf, fnext ; for (j = 0 ; j < nn ; j++) { Child [j] = EMPTY ; Sibling [j] = EMPTY ; } /* --------------------------------------------------------------------- */ /* place the children in link lists - bigger elements tend to be last */ /* --------------------------------------------------------------------- */ for (j = nn-1 ; j >= 0 ; j--) { if (Nv [j] > 0) { /* this is an element */ parent = Parent [j] ; if (parent != EMPTY) { /* place the element in link list of the children its parent */ /* bigger elements will tend to be at the end of the list */ Sibling [j] = Child [parent] ; Child [parent] = j ; } } } #ifndef NDEBUG { Int nels, ff, nchild ; AMD_DEBUG1 (("\n\n================================ AMD_postorder:\n")); nels = 0 ; for (j = 0 ; j < nn ; j++) { if (Nv [j] > 0) { AMD_DEBUG1 (( ""ID" : nels "ID" npiv "ID" size "ID " parent "ID" maxfr "ID"\n", j, nels, Nv [j], Fsize [j], Parent [j], Fsize [j])) ; /* this is an element */ /* dump the link list of children */ nchild = 0 ; AMD_DEBUG1 ((" Children: ")) ; for (ff = Child [j] ; ff != EMPTY ; ff = Sibling [ff]) { AMD_DEBUG1 ((ID" ", ff)) ; ASSERT (Parent [ff] == j) ; nchild++ ; ASSERT (nchild < nn) ; } AMD_DEBUG1 (("\n")) ; parent = Parent [j] ; if (parent != EMPTY) { ASSERT (Nv [parent] > 0) ; } nels++ ; } } } AMD_DEBUG1 (("\n\nGo through the children of each node, and put\n" "the biggest child last in each list:\n")) ; #endif /* --------------------------------------------------------------------- */ /* place the largest child last in the list of children for each node */ /* --------------------------------------------------------------------- */ for (i = 0 ; i < nn ; i++) { if (Nv [i] > 0 && Child [i] != EMPTY) { #ifndef NDEBUG Int nchild ; AMD_DEBUG1 (("Before partial sort, element "ID"\n", i)) ; nchild = 0 ; for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { ASSERT (f >= 0 && f < nn) ; AMD_DEBUG1 ((" f: "ID" size: "ID"\n", f, Fsize [f])) ; nchild++ ; ASSERT (nchild <= nn) ; } #endif /* find the biggest element in the child list */ fprev = EMPTY ; maxfrsize = EMPTY ; bigfprev = EMPTY ; bigf = EMPTY ; for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { ASSERT (f >= 0 && f < nn) ; frsize = Fsize [f] ; if (frsize >= maxfrsize) { /* this is the biggest seen so far */ maxfrsize = frsize ; bigfprev = fprev ; bigf = f ; } fprev = f ; } ASSERT (bigf != EMPTY) ; fnext = Sibling [bigf] ; AMD_DEBUG1 (("bigf "ID" maxfrsize "ID" bigfprev "ID" fnext "ID " fprev " ID"\n", bigf, maxfrsize, bigfprev, fnext, fprev)) ; if (fnext != EMPTY) { /* if fnext is EMPTY then bigf is already at the end of list */ if (bigfprev == EMPTY) { /* delete bigf from the element of the list */ Child [i] = fnext ; } else { /* delete bigf from the middle of the list */ Sibling [bigfprev] = fnext ; } /* put bigf at the end of the list */ Sibling [bigf] = EMPTY ; ASSERT (Child [i] != EMPTY) ; ASSERT (fprev != bigf) ; ASSERT (fprev != EMPTY) ; Sibling [fprev] = bigf ; } #ifndef NDEBUG AMD_DEBUG1 (("After partial sort, element "ID"\n", i)) ; for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { ASSERT (f >= 0 && f < nn) ; AMD_DEBUG1 ((" "ID" "ID"\n", f, Fsize [f])) ; ASSERT (Nv [f] > 0) ; nchild-- ; } ASSERT (nchild == 0) ; #endif } } /* --------------------------------------------------------------------- */ /* postorder the assembly tree */ /* --------------------------------------------------------------------- */ for (i = 0 ; i < nn ; i++) { Order [i] = EMPTY ; } k = 0 ; for (i = 0 ; i < nn ; i++) { if (Parent [i] == EMPTY && Nv [i] > 0) { AMD_DEBUG1 (("Root of assembly tree "ID"\n", i)) ; k = AMD_post_tree (i, k, Child, Sibling, Order, Stack #ifndef NDEBUG , nn #endif ) ; } } } igraph/src/AMD/Source/amd_valid.c0000644000175100001440000000564413431000472016261 0ustar hornikusers/* ========================================================================= */ /* === AMD_valid =========================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* Check if a column-form matrix is valid or not. The matrix A is * n_row-by-n_col. The row indices of entries in column j are in * Ai [Ap [j] ... Ap [j+1]-1]. Required conditions are: * * n_row >= 0 * n_col >= 0 * nz = Ap [n_col] >= 0 number of entries in the matrix * Ap [0] == 0 * Ap [j] <= Ap [j+1] for all j in the range 0 to n_col. * Ai [0 ... nz-1] must be in the range 0 to n_row-1. * * If any of the above conditions hold, AMD_INVALID is returned. If the * following condition holds, AMD_OK_BUT_JUMBLED is returned (a warning, * not an error): * * row indices in Ai [Ap [j] ... Ap [j+1]-1] are not sorted in ascending * order, and/or duplicate entries exist. * * Otherwise, AMD_OK is returned. * * In v1.2 and earlier, this function returned TRUE if the matrix was valid * (now returns AMD_OK), or FALSE otherwise (now returns AMD_INVALID or * AMD_OK_BUT_JUMBLED). */ #include "amd_internal.h" GLOBAL Int AMD_valid ( /* inputs, not modified on output: */ Int n_row, /* A is n_row-by-n_col */ Int n_col, const Int Ap [ ], /* column pointers of A, of size n_col+1 */ const Int Ai [ ] /* row indices of A, of size nz = Ap [n_col] */ ) { Int nz, j, p1, p2, ilast, i, p, result = AMD_OK ; if (n_row < 0 || n_col < 0 || Ap == NULL || Ai == NULL) { return (AMD_INVALID) ; } nz = Ap [n_col] ; if (Ap [0] != 0 || nz < 0) { /* column pointers must start at Ap [0] = 0, and Ap [n] must be >= 0 */ AMD_DEBUG0 (("column 0 pointer bad or nz < 0\n")) ; return (AMD_INVALID) ; } for (j = 0 ; j < n_col ; j++) { p1 = Ap [j] ; p2 = Ap [j+1] ; AMD_DEBUG2 (("\nColumn: "ID" p1: "ID" p2: "ID"\n", j, p1, p2)) ; if (p1 > p2) { /* column pointers must be ascending */ AMD_DEBUG0 (("column "ID" pointer bad\n", j)) ; return (AMD_INVALID) ; } ilast = EMPTY ; for (p = p1 ; p < p2 ; p++) { i = Ai [p] ; AMD_DEBUG3 (("row: "ID"\n", i)) ; if (i < 0 || i >= n_row) { /* row index out of range */ AMD_DEBUG0 (("index out of range, col "ID" row "ID"\n", j, i)); return (AMD_INVALID) ; } if (i <= ilast) { /* row index unsorted, or duplicate entry present */ AMD_DEBUG1 (("index unsorted/dupl col "ID" row "ID"\n", j, i)); result = AMD_OK_BUT_JUMBLED ; } ilast = i ; } } return (result) ; } igraph/src/AMD/Source/amd_2.c0000644000175100001440000017647113431000472015332 0ustar hornikusers/* ========================================================================= */ /* === AMD_2 =============================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* AMD_2: performs the AMD ordering on a symmetric sparse matrix A, followed * by a postordering (via depth-first search) of the assembly tree using the * AMD_postorder routine. */ #include "amd_internal.h" /* ========================================================================= */ /* === clear_flag ========================================================== */ /* ========================================================================= */ static Int clear_flag (Int wflg, Int wbig, Int W [ ], Int n) { Int x ; if (wflg < 2 || wflg >= wbig) { for (x = 0 ; x < n ; x++) { if (W [x] != 0) W [x] = 1 ; } wflg = 2 ; } /* at this point, W [0..n-1] < wflg holds */ return (wflg) ; } /* ========================================================================= */ /* === AMD_2 =============================================================== */ /* ========================================================================= */ GLOBAL void AMD_2 ( Int n, /* A is n-by-n, where n > 0 */ Int Pe [ ], /* Pe [0..n-1]: index in Iw of row i on input */ Int Iw [ ], /* workspace of size iwlen. Iw [0..pfree-1] * holds the matrix on input */ Int Len [ ], /* Len [0..n-1]: length for row/column i on input */ Int iwlen, /* length of Iw. iwlen >= pfree + n */ Int pfree, /* Iw [pfree ... iwlen-1] is empty on input */ /* 7 size-n workspaces, not defined on input: */ Int Nv [ ], /* the size of each supernode on output */ Int Next [ ], /* the output inverse permutation */ Int Last [ ], /* the output permutation */ Int Head [ ], Int Elen [ ], /* the size columns of L for each supernode */ Int Degree [ ], Int W [ ], /* control parameters and output statistics */ double Control [ ], /* array of size AMD_CONTROL */ double Info [ ] /* array of size AMD_INFO */ ) { /* * Given a representation of the nonzero pattern of a symmetric matrix, A, * (excluding the diagonal) perform an approximate minimum (UMFPACK/MA38-style) * degree ordering to compute a pivot order such that the introduction of * nonzeros (fill-in) in the Cholesky factors A = LL' is kept low. At each * step, the pivot selected is the one with the minimum UMFAPACK/MA38-style * upper-bound on the external degree. This routine can optionally perform * aggresive absorption (as done by MC47B in the Harwell Subroutine * Library). * * The approximate degree algorithm implemented here is the symmetric analog of * the degree update algorithm in MA38 and UMFPACK (the Unsymmetric-pattern * MultiFrontal PACKage, both by Davis and Duff). The routine is based on the * MA27 minimum degree ordering algorithm by Iain Duff and John Reid. * * This routine is a translation of the original AMDBAR and MC47B routines, * in Fortran, with the following modifications: * * (1) dense rows/columns are removed prior to ordering the matrix, and placed * last in the output order. The presence of a dense row/column can * increase the ordering time by up to O(n^2), unless they are removed * prior to ordering. * * (2) the minimum degree ordering is followed by a postordering (depth-first * search) of the assembly tree. Note that mass elimination (discussed * below) combined with the approximate degree update can lead to the mass * elimination of nodes with lower exact degree than the current pivot * element. No additional fill-in is caused in the representation of the * Schur complement. The mass-eliminated nodes merge with the current * pivot element. They are ordered prior to the current pivot element. * Because they can have lower exact degree than the current element, the * merger of two or more of these nodes in the current pivot element can * lead to a single element that is not a "fundamental supernode". The * diagonal block can have zeros in it. Thus, the assembly tree used here * is not guaranteed to be the precise supernodal elemination tree (with * "funadmental" supernodes), and the postordering performed by this * routine is not guaranteed to be a precise postordering of the * elimination tree. * * (3) input parameters are added, to control aggressive absorption and the * detection of "dense" rows/columns of A. * * (4) additional statistical information is returned, such as the number of * nonzeros in L, and the flop counts for subsequent LDL' and LU * factorizations. These are slight upper bounds, because of the mass * elimination issue discussed above. * * (5) additional routines are added to interface this routine to MATLAB * to provide a simple C-callable user-interface, to check inputs for * errors, compute the symmetry of the pattern of A and the number of * nonzeros in each row/column of A+A', to compute the pattern of A+A', * to perform the assembly tree postordering, and to provide debugging * ouput. Many of these functions are also provided by the Fortran * Harwell Subroutine Library routine MC47A. * * (6) both int and SuiteSparse_long versions are provided. In the * descriptions below and integer is and int or SuiteSparse_long depending * on which version is being used. ********************************************************************** ***** CAUTION: ARGUMENTS ARE NOT CHECKED FOR ERRORS ON INPUT. ****** ********************************************************************** ** If you want error checking, a more versatile input format, and a ** ** simpler user interface, use amd_order or amd_l_order instead. ** ** This routine is not meant to be user-callable. ** ********************************************************************** * ---------------------------------------------------------------------------- * References: * ---------------------------------------------------------------------------- * * [1] Timothy A. Davis and Iain Duff, "An unsymmetric-pattern multifrontal * method for sparse LU factorization", SIAM J. Matrix Analysis and * Applications, vol. 18, no. 1, pp. 140-158. Discusses UMFPACK / MA38, * which first introduced the approximate minimum degree used by this * routine. * * [2] Patrick Amestoy, Timothy A. Davis, and Iain S. Duff, "An approximate * minimum degree ordering algorithm," SIAM J. Matrix Analysis and * Applications, vol. 17, no. 4, pp. 886-905, 1996. Discusses AMDBAR and * MC47B, which are the Fortran versions of this routine. * * [3] Alan George and Joseph Liu, "The evolution of the minimum degree * ordering algorithm," SIAM Review, vol. 31, no. 1, pp. 1-19, 1989. * We list below the features mentioned in that paper that this code * includes: * * mass elimination: * Yes. MA27 relied on supervariable detection for mass elimination. * * indistinguishable nodes: * Yes (we call these "supervariables"). This was also in the MA27 * code - although we modified the method of detecting them (the * previous hash was the true degree, which we no longer keep track * of). A supervariable is a set of rows with identical nonzero * pattern. All variables in a supervariable are eliminated together. * Each supervariable has as its numerical name that of one of its * variables (its principal variable). * * quotient graph representation: * Yes. We use the term "element" for the cliques formed during * elimination. This was also in the MA27 code. The algorithm can * operate in place, but it will work more efficiently if given some * "elbow room." * * element absorption: * Yes. This was also in the MA27 code. * * external degree: * Yes. The MA27 code was based on the true degree. * * incomplete degree update and multiple elimination: * No. This was not in MA27, either. Our method of degree update * within MC47B is element-based, not variable-based. It is thus * not well-suited for use with incomplete degree update or multiple * elimination. * * Authors, and Copyright (C) 2004 by: * Timothy A. Davis, Patrick Amestoy, Iain S. Duff, John K. Reid. * * Acknowledgements: This work (and the UMFPACK package) was supported by the * National Science Foundation (ASC-9111263, DMS-9223088, and CCR-0203270). * The UMFPACK/MA38 approximate degree update algorithm, the unsymmetric analog * which forms the basis of AMD, was developed while Tim Davis was supported by * CERFACS (Toulouse, France) in a post-doctoral position. This C version, and * the etree postorder, were written while Tim Davis was on sabbatical at * Stanford University and Lawrence Berkeley National Laboratory. * ---------------------------------------------------------------------------- * INPUT ARGUMENTS (unaltered): * ---------------------------------------------------------------------------- * n: The matrix order. Restriction: n >= 1. * * iwlen: The size of the Iw array. On input, the matrix is stored in * Iw [0..pfree-1]. However, Iw [0..iwlen-1] should be slightly larger * than what is required to hold the matrix, at least iwlen >= pfree + n. * Otherwise, excessive compressions will take place. The recommended * value of iwlen is 1.2 * pfree + n, which is the value used in the * user-callable interface to this routine (amd_order.c). The algorithm * will not run at all if iwlen < pfree. Restriction: iwlen >= pfree + n. * Note that this is slightly more restrictive than the actual minimum * (iwlen >= pfree), but AMD_2 will be very slow with no elbow room. * Thus, this routine enforces a bare minimum elbow room of size n. * * pfree: On input the tail end of the array, Iw [pfree..iwlen-1], is empty, * and the matrix is stored in Iw [0..pfree-1]. During execution, * additional data is placed in Iw, and pfree is modified so that * Iw [pfree..iwlen-1] is always the unused part of Iw. * * Control: A double array of size AMD_CONTROL containing input parameters * that affect how the ordering is computed. If NULL, then default * settings are used. * * Control [AMD_DENSE] is used to determine whether or not a given input * row is "dense". A row is "dense" if the number of entries in the row * exceeds Control [AMD_DENSE] times sqrt (n), except that rows with 16 or * fewer entries are never considered "dense". To turn off the detection * of dense rows, set Control [AMD_DENSE] to a negative number, or to a * number larger than sqrt (n). The default value of Control [AMD_DENSE] * is AMD_DEFAULT_DENSE, which is defined in amd.h as 10. * * Control [AMD_AGGRESSIVE] is used to determine whether or not aggressive * absorption is to be performed. If nonzero, then aggressive absorption * is performed (this is the default). * ---------------------------------------------------------------------------- * INPUT/OUPUT ARGUMENTS: * ---------------------------------------------------------------------------- * * Pe: An integer array of size n. On input, Pe [i] is the index in Iw of * the start of row i. Pe [i] is ignored if row i has no off-diagonal * entries. Thus Pe [i] must be in the range 0 to pfree-1 for non-empty * rows. * * During execution, it is used for both supervariables and elements: * * Principal supervariable i: index into Iw of the description of * supervariable i. A supervariable represents one or more rows of * the matrix with identical nonzero pattern. In this case, * Pe [i] >= 0. * * Non-principal supervariable i: if i has been absorbed into another * supervariable j, then Pe [i] = FLIP (j), where FLIP (j) is defined * as (-(j)-2). Row j has the same pattern as row i. Note that j * might later be absorbed into another supervariable j2, in which * case Pe [i] is still FLIP (j), and Pe [j] = FLIP (j2) which is * < EMPTY, where EMPTY is defined as (-1) in amd_internal.h. * * Unabsorbed element e: the index into Iw of the description of element * e, if e has not yet been absorbed by a subsequent element. Element * e is created when the supervariable of the same name is selected as * the pivot. In this case, Pe [i] >= 0. * * Absorbed element e: if element e is absorbed into element e2, then * Pe [e] = FLIP (e2). This occurs when the pattern of e (which we * refer to as Le) is found to be a subset of the pattern of e2 (that * is, Le2). In this case, Pe [i] < EMPTY. If element e is "null" * (it has no nonzeros outside its pivot block), then Pe [e] = EMPTY, * and e is the root of an assembly subtree (or the whole tree if * there is just one such root). * * Dense variable i: if i is "dense", then Pe [i] = EMPTY. * * On output, Pe holds the assembly tree/forest, which implicitly * represents a pivot order with identical fill-in as the actual order * (via a depth-first search of the tree), as follows. If Nv [i] > 0, * then i represents a node in the assembly tree, and the parent of i is * Pe [i], or EMPTY if i is a root. If Nv [i] = 0, then (i, Pe [i]) * represents an edge in a subtree, the root of which is a node in the * assembly tree. Note that i refers to a row/column in the original * matrix, not the permuted matrix. * * Info: A double array of size AMD_INFO. If present, (that is, not NULL), * then statistics about the ordering are returned in the Info array. * See amd.h for a description. * ---------------------------------------------------------------------------- * INPUT/MODIFIED (undefined on output): * ---------------------------------------------------------------------------- * * Len: An integer array of size n. On input, Len [i] holds the number of * entries in row i of the matrix, excluding the diagonal. The contents * of Len are undefined on output. * * Iw: An integer array of size iwlen. On input, Iw [0..pfree-1] holds the * description of each row i in the matrix. The matrix must be symmetric, * and both upper and lower triangular parts must be present. The * diagonal must not be present. Row i is held as follows: * * Len [i]: the length of the row i data structure in the Iw array. * Iw [Pe [i] ... Pe [i] + Len [i] - 1]: * the list of column indices for nonzeros in row i (simple * supervariables), excluding the diagonal. All supervariables * start with one row/column each (supervariable i is just row i). * If Len [i] is zero on input, then Pe [i] is ignored on input. * * Note that the rows need not be in any particular order, and there * may be empty space between the rows. * * During execution, the supervariable i experiences fill-in. This is * represented by placing in i a list of the elements that cause fill-in * in supervariable i: * * Len [i]: the length of supervariable i in the Iw array. * Iw [Pe [i] ... Pe [i] + Elen [i] - 1]: * the list of elements that contain i. This list is kept short * by removing absorbed elements. * Iw [Pe [i] + Elen [i] ... Pe [i] + Len [i] - 1]: * the list of supervariables in i. This list is kept short by * removing nonprincipal variables, and any entry j that is also * contained in at least one of the elements (j in Le) in the list * for i (e in row i). * * When supervariable i is selected as pivot, we create an element e of * the same name (e=i): * * Len [e]: the length of element e in the Iw array. * Iw [Pe [e] ... Pe [e] + Len [e] - 1]: * the list of supervariables in element e. * * An element represents the fill-in that occurs when supervariable i is * selected as pivot (which represents the selection of row i and all * non-principal variables whose principal variable is i). We use the * term Le to denote the set of all supervariables in element e. Absorbed * supervariables and elements are pruned from these lists when * computationally convenient. * * CAUTION: THE INPUT MATRIX IS OVERWRITTEN DURING COMPUTATION. * The contents of Iw are undefined on output. * ---------------------------------------------------------------------------- * OUTPUT (need not be set on input): * ---------------------------------------------------------------------------- * * Nv: An integer array of size n. During execution, ABS (Nv [i]) is equal to * the number of rows that are represented by the principal supervariable * i. If i is a nonprincipal or dense variable, then Nv [i] = 0. * Initially, Nv [i] = 1 for all i. Nv [i] < 0 signifies that i is a * principal variable in the pattern Lme of the current pivot element me. * After element me is constructed, Nv [i] is set back to a positive * value. * * On output, Nv [i] holds the number of pivots represented by super * row/column i of the original matrix, or Nv [i] = 0 for non-principal * rows/columns. Note that i refers to a row/column in the original * matrix, not the permuted matrix. * * Elen: An integer array of size n. See the description of Iw above. At the * start of execution, Elen [i] is set to zero for all rows i. During * execution, Elen [i] is the number of elements in the list for * supervariable i. When e becomes an element, Elen [e] = FLIP (esize) is * set, where esize is the size of the element (the number of pivots, plus * the number of nonpivotal entries). Thus Elen [e] < EMPTY. * Elen (i) = EMPTY set when variable i becomes nonprincipal. * * For variables, Elen (i) >= EMPTY holds until just before the * postordering and permutation vectors are computed. For elements, * Elen [e] < EMPTY holds. * * On output, Elen [i] is the degree of the row/column in the Cholesky * factorization of the permuted matrix, corresponding to the original row * i, if i is a super row/column. It is equal to EMPTY if i is * non-principal. Note that i refers to a row/column in the original * matrix, not the permuted matrix. * * Note that the contents of Elen on output differ from the Fortran * version (Elen holds the inverse permutation in the Fortran version, * which is instead returned in the Next array in this C version, * described below). * * Last: In a degree list, Last [i] is the supervariable preceding i, or EMPTY * if i is the head of the list. In a hash bucket, Last [i] is the hash * key for i. * * Last [Head [hash]] is also used as the head of a hash bucket if * Head [hash] contains a degree list (see the description of Head, * below). * * On output, Last [0..n-1] holds the permutation. That is, if * i = Last [k], then row i is the kth pivot row (where k ranges from 0 to * n-1). Row Last [k] of A is the kth row in the permuted matrix, PAP'. * * Next: Next [i] is the supervariable following i in a link list, or EMPTY if * i is the last in the list. Used for two kinds of lists: degree lists * and hash buckets (a supervariable can be in only one kind of list at a * time). * * On output Next [0..n-1] holds the inverse permutation. That is, if * k = Next [i], then row i is the kth pivot row. Row i of A appears as * the (Next[i])-th row in the permuted matrix, PAP'. * * Note that the contents of Next on output differ from the Fortran * version (Next is undefined on output in the Fortran version). * ---------------------------------------------------------------------------- * LOCAL WORKSPACE (not input or output - used only during execution): * ---------------------------------------------------------------------------- * * Degree: An integer array of size n. If i is a supervariable, then * Degree [i] holds the current approximation of the external degree of * row i (an upper bound). The external degree is the number of nonzeros * in row i, minus ABS (Nv [i]), the diagonal part. The bound is equal to * the exact external degree if Elen [i] is less than or equal to two. * * We also use the term "external degree" for elements e to refer to * |Le \ Lme|. If e is an element, then Degree [e] is |Le|, which is the * degree of the off-diagonal part of the element e (not including the * diagonal part). * * Head: An integer array of size n. Head is used for degree lists. * Head [deg] is the first supervariable in a degree list. All * supervariables i in a degree list Head [deg] have the same approximate * degree, namely, deg = Degree [i]. If the list Head [deg] is empty then * Head [deg] = EMPTY. * * During supervariable detection Head [hash] also serves as a pointer to * a hash bucket. If Head [hash] >= 0, there is a degree list of degree * hash. The hash bucket head pointer is Last [Head [hash]]. If * Head [hash] = EMPTY, then the degree list and hash bucket are both * empty. If Head [hash] < EMPTY, then the degree list is empty, and * FLIP (Head [hash]) is the head of the hash bucket. After supervariable * detection is complete, all hash buckets are empty, and the * (Last [Head [hash]] = EMPTY) condition is restored for the non-empty * degree lists. * * W: An integer array of size n. The flag array W determines the status of * elements and variables, and the external degree of elements. * * for elements: * if W [e] = 0, then the element e is absorbed. * if W [e] >= wflg, then W [e] - wflg is the size of the set * |Le \ Lme|, in terms of nonzeros (the sum of ABS (Nv [i]) for * each principal variable i that is both in the pattern of * element e and NOT in the pattern of the current pivot element, * me). * if wflg > W [e] > 0, then e is not absorbed and has not yet been * seen in the scan of the element lists in the computation of * |Le\Lme| in Scan 1 below. * * for variables: * during supervariable detection, if W [j] != wflg then j is * not in the pattern of variable i. * * The W array is initialized by setting W [i] = 1 for all i, and by * setting wflg = 2. It is reinitialized if wflg becomes too large (to * ensure that wflg+n does not cause integer overflow). * ---------------------------------------------------------------------------- * LOCAL INTEGERS: * ---------------------------------------------------------------------------- */ Int deg, degme, dext, lemax, e, elenme, eln, i, ilast, inext, j, jlast, jnext, k, knt1, knt2, knt3, lenj, ln, me, mindeg, nel, nleft, nvi, nvj, nvpiv, slenme, wbig, we, wflg, wnvi, ok, ndense, ncmpa, dense, aggressive ; unsigned Int hash ; /* unsigned, so that hash % n is well defined.*/ /* * deg: the degree of a variable or element * degme: size, |Lme|, of the current element, me (= Degree [me]) * dext: external degree, |Le \ Lme|, of some element e * lemax: largest |Le| seen so far (called dmax in Fortran version) * e: an element * elenme: the length, Elen [me], of element list of pivotal variable * eln: the length, Elen [...], of an element list * hash: the computed value of the hash function * i: a supervariable * ilast: the entry in a link list preceding i * inext: the entry in a link list following i * j: a supervariable * jlast: the entry in a link list preceding j * jnext: the entry in a link list, or path, following j * k: the pivot order of an element or variable * knt1: loop counter used during element construction * knt2: loop counter used during element construction * knt3: loop counter used during compression * lenj: Len [j] * ln: length of a supervariable list * me: current supervariable being eliminated, and the current * element created by eliminating that supervariable * mindeg: current minimum degree * nel: number of pivots selected so far * nleft: n - nel, the number of nonpivotal rows/columns remaining * nvi: the number of variables in a supervariable i (= Nv [i]) * nvj: the number of variables in a supervariable j (= Nv [j]) * nvpiv: number of pivots in current element * slenme: number of variables in variable list of pivotal variable * wbig: = (INT_MAX - n) for the int version, (SuiteSparse_long_max - n) * for the SuiteSparse_long version. wflg is not allowed to * be >= wbig. * we: W [e] * wflg: used for flagging the W array. See description of Iw. * wnvi: wflg - Nv [i] * x: either a supervariable or an element * * ok: true if supervariable j can be absorbed into i * ndense: number of "dense" rows/columns * dense: rows/columns with initial degree > dense are considered "dense" * aggressive: true if aggressive absorption is being performed * ncmpa: number of garbage collections * ---------------------------------------------------------------------------- * LOCAL DOUBLES, used for statistical output only (except for alpha): * ---------------------------------------------------------------------------- */ double f, r, ndiv, s, nms_lu, nms_ldl, dmax, alpha, lnz, lnzme ; /* * f: nvpiv * r: degme + nvpiv * ndiv: number of divisions for LU or LDL' factorizations * s: number of multiply-subtract pairs for LU factorization, for the * current element me * nms_lu number of multiply-subtract pairs for LU factorization * nms_ldl number of multiply-subtract pairs for LDL' factorization * dmax: the largest number of entries in any column of L, including the * diagonal * alpha: "dense" degree ratio * lnz: the number of nonzeros in L (excluding the diagonal) * lnzme: the number of nonzeros in L (excl. the diagonal) for the * current element me * ---------------------------------------------------------------------------- * LOCAL "POINTERS" (indices into the Iw array) * ---------------------------------------------------------------------------- */ Int p, p1, p2, p3, p4, pdst, pend, pj, pme, pme1, pme2, pn, psrc ; /* * Any parameter (Pe [...] or pfree) or local variable starting with "p" (for * Pointer) is an index into Iw, and all indices into Iw use variables starting * with "p." The only exception to this rule is the iwlen input argument. * * p: pointer into lots of things * p1: Pe [i] for some variable i (start of element list) * p2: Pe [i] + Elen [i] - 1 for some variable i * p3: index of first supervariable in clean list * p4: * pdst: destination pointer, for compression * pend: end of memory to compress * pj: pointer into an element or variable * pme: pointer into the current element (pme1...pme2) * pme1: the current element, me, is stored in Iw [pme1...pme2] * pme2: the end of the current element * pn: pointer into a "clean" variable, also used to compress * psrc: source pointer, for compression */ /* ========================================================================= */ /* INITIALIZATIONS */ /* ========================================================================= */ /* Note that this restriction on iwlen is slightly more restrictive than * what is actually required in AMD_2. AMD_2 can operate with no elbow * room at all, but it will be slow. For better performance, at least * size-n elbow room is enforced. */ ASSERT (iwlen >= pfree + n) ; ASSERT (n > 0) ; /* initialize output statistics */ lnz = 0 ; ndiv = 0 ; nms_lu = 0 ; nms_ldl = 0 ; dmax = 1 ; me = EMPTY ; mindeg = 0 ; ncmpa = 0 ; nel = 0 ; lemax = 0 ; /* get control parameters */ if (Control != (double *) NULL) { alpha = Control [AMD_DENSE] ; aggressive = (Control [AMD_AGGRESSIVE] != 0) ; } else { alpha = AMD_DEFAULT_DENSE ; aggressive = AMD_DEFAULT_AGGRESSIVE ; } /* Note: if alpha is NaN, this is undefined: */ if (alpha < 0) { /* only remove completely dense rows/columns */ dense = n-2 ; } else { dense = alpha * sqrt ((double) n) ; } dense = MAX (16, dense) ; dense = MIN (n, dense) ; AMD_DEBUG1 (("\n\nAMD (debug), alpha %g, aggr. "ID"\n", alpha, aggressive)) ; for (i = 0 ; i < n ; i++) { Last [i] = EMPTY ; Head [i] = EMPTY ; Next [i] = EMPTY ; /* if separate Hhead array is used for hash buckets: * Hhead [i] = EMPTY ; */ Nv [i] = 1 ; W [i] = 1 ; Elen [i] = 0 ; Degree [i] = Len [i] ; } #ifndef NDEBUG AMD_DEBUG1 (("\n======Nel "ID" initial\n", nel)) ; AMD_dump (n, Pe, Iw, Len, iwlen, pfree, Nv, Next, Last, Head, Elen, Degree, W, -1) ; #endif /* initialize wflg */ wbig = Int_MAX - n ; wflg = clear_flag (0, wbig, W, n) ; /* --------------------------------------------------------------------- */ /* initialize degree lists and eliminate dense and empty rows */ /* --------------------------------------------------------------------- */ ndense = 0 ; for (i = 0 ; i < n ; i++) { deg = Degree [i] ; ASSERT (deg >= 0 && deg < n) ; if (deg == 0) { /* ------------------------------------------------------------- * we have a variable that can be eliminated at once because * there is no off-diagonal non-zero in its row. Note that * Nv [i] = 1 for an empty variable i. It is treated just * the same as an eliminated element i. * ------------------------------------------------------------- */ Elen [i] = FLIP (1) ; nel++ ; Pe [i] = EMPTY ; W [i] = 0 ; } else if (deg > dense) { /* ------------------------------------------------------------- * Dense variables are not treated as elements, but as unordered, * non-principal variables that have no parent. They do not take * part in the postorder, since Nv [i] = 0. Note that the Fortran * version does not have this option. * ------------------------------------------------------------- */ AMD_DEBUG1 (("Dense node "ID" degree "ID"\n", i, deg)) ; ndense++ ; Nv [i] = 0 ; /* do not postorder this node */ Elen [i] = EMPTY ; nel++ ; Pe [i] = EMPTY ; } else { /* ------------------------------------------------------------- * place i in the degree list corresponding to its degree * ------------------------------------------------------------- */ inext = Head [deg] ; ASSERT (inext >= EMPTY && inext < n) ; if (inext != EMPTY) Last [inext] = i ; Next [i] = inext ; Head [deg] = i ; } } /* ========================================================================= */ /* WHILE (selecting pivots) DO */ /* ========================================================================= */ while (nel < n) { #ifndef NDEBUG AMD_DEBUG1 (("\n======Nel "ID"\n", nel)) ; if (AMD_debug >= 2) { AMD_dump (n, Pe, Iw, Len, iwlen, pfree, Nv, Next, Last, Head, Elen, Degree, W, nel) ; } #endif /* ========================================================================= */ /* GET PIVOT OF MINIMUM DEGREE */ /* ========================================================================= */ /* ----------------------------------------------------------------- */ /* find next supervariable for elimination */ /* ----------------------------------------------------------------- */ ASSERT (mindeg >= 0 && mindeg < n) ; for (deg = mindeg ; deg < n ; deg++) { me = Head [deg] ; if (me != EMPTY) break ; } mindeg = deg ; ASSERT (me >= 0 && me < n) ; AMD_DEBUG1 (("=================me: "ID"\n", me)) ; /* ----------------------------------------------------------------- */ /* remove chosen variable from link list */ /* ----------------------------------------------------------------- */ inext = Next [me] ; ASSERT (inext >= EMPTY && inext < n) ; if (inext != EMPTY) Last [inext] = EMPTY ; Head [deg] = inext ; /* ----------------------------------------------------------------- */ /* me represents the elimination of pivots nel to nel+Nv[me]-1. */ /* place me itself as the first in this set. */ /* ----------------------------------------------------------------- */ elenme = Elen [me] ; nvpiv = Nv [me] ; ASSERT (nvpiv > 0) ; nel += nvpiv ; /* ========================================================================= */ /* CONSTRUCT NEW ELEMENT */ /* ========================================================================= */ /* ----------------------------------------------------------------- * At this point, me is the pivotal supervariable. It will be * converted into the current element. Scan list of the pivotal * supervariable, me, setting tree pointers and constructing new list * of supervariables for the new element, me. p is a pointer to the * current position in the old list. * ----------------------------------------------------------------- */ /* flag the variable "me" as being in Lme by negating Nv [me] */ Nv [me] = -nvpiv ; degme = 0 ; ASSERT (Pe [me] >= 0 && Pe [me] < iwlen) ; if (elenme == 0) { /* ------------------------------------------------------------- */ /* construct the new element in place */ /* ------------------------------------------------------------- */ pme1 = Pe [me] ; pme2 = pme1 - 1 ; for (p = pme1 ; p <= pme1 + Len [me] - 1 ; p++) { i = Iw [p] ; ASSERT (i >= 0 && i < n && Nv [i] >= 0) ; nvi = Nv [i] ; if (nvi > 0) { /* ----------------------------------------------------- */ /* i is a principal variable not yet placed in Lme. */ /* store i in new list */ /* ----------------------------------------------------- */ /* flag i as being in Lme by negating Nv [i] */ degme += nvi ; Nv [i] = -nvi ; Iw [++pme2] = i ; /* ----------------------------------------------------- */ /* remove variable i from degree list. */ /* ----------------------------------------------------- */ ilast = Last [i] ; inext = Next [i] ; ASSERT (ilast >= EMPTY && ilast < n) ; ASSERT (inext >= EMPTY && inext < n) ; if (inext != EMPTY) Last [inext] = ilast ; if (ilast != EMPTY) { Next [ilast] = inext ; } else { /* i is at the head of the degree list */ ASSERT (Degree [i] >= 0 && Degree [i] < n) ; Head [Degree [i]] = inext ; } } } } else { /* ------------------------------------------------------------- */ /* construct the new element in empty space, Iw [pfree ...] */ /* ------------------------------------------------------------- */ p = Pe [me] ; pme1 = pfree ; slenme = Len [me] - elenme ; for (knt1 = 1 ; knt1 <= elenme + 1 ; knt1++) { if (knt1 > elenme) { /* search the supervariables in me. */ e = me ; pj = p ; ln = slenme ; AMD_DEBUG2 (("Search sv: "ID" "ID" "ID"\n", me,pj,ln)) ; } else { /* search the elements in me. */ e = Iw [p++] ; ASSERT (e >= 0 && e < n) ; pj = Pe [e] ; ln = Len [e] ; AMD_DEBUG2 (("Search element e "ID" in me "ID"\n", e,me)) ; ASSERT (Elen [e] < EMPTY && W [e] > 0 && pj >= 0) ; } ASSERT (ln >= 0 && (ln == 0 || (pj >= 0 && pj < iwlen))) ; /* --------------------------------------------------------- * search for different supervariables and add them to the * new list, compressing when necessary. this loop is * executed once for each element in the list and once for * all the supervariables in the list. * --------------------------------------------------------- */ for (knt2 = 1 ; knt2 <= ln ; knt2++) { i = Iw [pj++] ; ASSERT (i >= 0 && i < n && (i == me || Elen [i] >= EMPTY)); nvi = Nv [i] ; AMD_DEBUG2 ((": "ID" "ID" "ID" "ID"\n", i, Elen [i], Nv [i], wflg)) ; if (nvi > 0) { /* ------------------------------------------------- */ /* compress Iw, if necessary */ /* ------------------------------------------------- */ if (pfree >= iwlen) { AMD_DEBUG1 (("GARBAGE COLLECTION\n")) ; /* prepare for compressing Iw by adjusting pointers * and lengths so that the lists being searched in * the inner and outer loops contain only the * remaining entries. */ Pe [me] = p ; Len [me] -= knt1 ; /* check if nothing left of supervariable me */ if (Len [me] == 0) Pe [me] = EMPTY ; Pe [e] = pj ; Len [e] = ln - knt2 ; /* nothing left of element e */ if (Len [e] == 0) Pe [e] = EMPTY ; ncmpa++ ; /* one more garbage collection */ /* store first entry of each object in Pe */ /* FLIP the first entry in each object */ for (j = 0 ; j < n ; j++) { pn = Pe [j] ; if (pn >= 0) { ASSERT (pn >= 0 && pn < iwlen) ; Pe [j] = Iw [pn] ; Iw [pn] = FLIP (j) ; } } /* psrc/pdst point to source/destination */ psrc = 0 ; pdst = 0 ; pend = pme1 - 1 ; while (psrc <= pend) { /* search for next FLIP'd entry */ j = FLIP (Iw [psrc++]) ; if (j >= 0) { AMD_DEBUG2 (("Got object j: "ID"\n", j)) ; Iw [pdst] = Pe [j] ; Pe [j] = pdst++ ; lenj = Len [j] ; /* copy from source to destination */ for (knt3 = 0 ; knt3 <= lenj - 2 ; knt3++) { Iw [pdst++] = Iw [psrc++] ; } } } /* move the new partially-constructed element */ p1 = pdst ; for (psrc = pme1 ; psrc <= pfree-1 ; psrc++) { Iw [pdst++] = Iw [psrc] ; } pme1 = p1 ; pfree = pdst ; pj = Pe [e] ; p = Pe [me] ; } /* ------------------------------------------------- */ /* i is a principal variable not yet placed in Lme */ /* store i in new list */ /* ------------------------------------------------- */ /* flag i as being in Lme by negating Nv [i] */ degme += nvi ; Nv [i] = -nvi ; Iw [pfree++] = i ; AMD_DEBUG2 ((" s: "ID" nv "ID"\n", i, Nv [i])); /* ------------------------------------------------- */ /* remove variable i from degree link list */ /* ------------------------------------------------- */ ilast = Last [i] ; inext = Next [i] ; ASSERT (ilast >= EMPTY && ilast < n) ; ASSERT (inext >= EMPTY && inext < n) ; if (inext != EMPTY) Last [inext] = ilast ; if (ilast != EMPTY) { Next [ilast] = inext ; } else { /* i is at the head of the degree list */ ASSERT (Degree [i] >= 0 && Degree [i] < n) ; Head [Degree [i]] = inext ; } } } if (e != me) { /* set tree pointer and flag to indicate element e is * absorbed into new element me (the parent of e is me) */ AMD_DEBUG1 ((" Element "ID" => "ID"\n", e, me)) ; Pe [e] = FLIP (me) ; W [e] = 0 ; } } pme2 = pfree - 1 ; } /* ----------------------------------------------------------------- */ /* me has now been converted into an element in Iw [pme1..pme2] */ /* ----------------------------------------------------------------- */ /* degme holds the external degree of new element */ Degree [me] = degme ; Pe [me] = pme1 ; Len [me] = pme2 - pme1 + 1 ; ASSERT (Pe [me] >= 0 && Pe [me] < iwlen) ; Elen [me] = FLIP (nvpiv + degme) ; /* FLIP (Elen (me)) is now the degree of pivot (including * diagonal part). */ #ifndef NDEBUG AMD_DEBUG2 (("New element structure: length= "ID"\n", pme2-pme1+1)) ; for (pme = pme1 ; pme <= pme2 ; pme++) AMD_DEBUG3 ((" "ID"", Iw[pme])); AMD_DEBUG3 (("\n")) ; #endif /* ----------------------------------------------------------------- */ /* make sure that wflg is not too large. */ /* ----------------------------------------------------------------- */ /* With the current value of wflg, wflg+n must not cause integer * overflow */ wflg = clear_flag (wflg, wbig, W, n) ; /* ========================================================================= */ /* COMPUTE (W [e] - wflg) = |Le\Lme| FOR ALL ELEMENTS */ /* ========================================================================= */ /* ----------------------------------------------------------------- * Scan 1: compute the external degrees of previous elements with * respect to the current element. That is: * (W [e] - wflg) = |Le \ Lme| * for each element e that appears in any supervariable in Lme. The * notation Le refers to the pattern (list of supervariables) of a * previous element e, where e is not yet absorbed, stored in * Iw [Pe [e] + 1 ... Pe [e] + Len [e]]. The notation Lme * refers to the pattern of the current element (stored in * Iw [pme1..pme2]). If aggressive absorption is enabled, and * (W [e] - wflg) becomes zero, then the element e will be absorbed * in Scan 2. * ----------------------------------------------------------------- */ AMD_DEBUG2 (("me: ")) ; for (pme = pme1 ; pme <= pme2 ; pme++) { i = Iw [pme] ; ASSERT (i >= 0 && i < n) ; eln = Elen [i] ; AMD_DEBUG3 ((""ID" Elen "ID": \n", i, eln)) ; if (eln > 0) { /* note that Nv [i] has been negated to denote i in Lme: */ nvi = -Nv [i] ; ASSERT (nvi > 0 && Pe [i] >= 0 && Pe [i] < iwlen) ; wnvi = wflg - nvi ; for (p = Pe [i] ; p <= Pe [i] + eln - 1 ; p++) { e = Iw [p] ; ASSERT (e >= 0 && e < n) ; we = W [e] ; AMD_DEBUG4 ((" e "ID" we "ID" ", e, we)) ; if (we >= wflg) { /* unabsorbed element e has been seen in this loop */ AMD_DEBUG4 ((" unabsorbed, first time seen")) ; we -= nvi ; } else if (we != 0) { /* e is an unabsorbed element */ /* this is the first we have seen e in all of Scan 1 */ AMD_DEBUG4 ((" unabsorbed")) ; we = Degree [e] + wnvi ; } AMD_DEBUG4 (("\n")) ; W [e] = we ; } } } AMD_DEBUG2 (("\n")) ; /* ========================================================================= */ /* DEGREE UPDATE AND ELEMENT ABSORPTION */ /* ========================================================================= */ /* ----------------------------------------------------------------- * Scan 2: for each i in Lme, sum up the degree of Lme (which is * degme), plus the sum of the external degrees of each Le for the * elements e appearing within i, plus the supervariables in i. * Place i in hash list. * ----------------------------------------------------------------- */ for (pme = pme1 ; pme <= pme2 ; pme++) { i = Iw [pme] ; ASSERT (i >= 0 && i < n && Nv [i] < 0 && Elen [i] >= 0) ; AMD_DEBUG2 (("Updating: i "ID" "ID" "ID"\n", i, Elen[i], Len [i])); p1 = Pe [i] ; p2 = p1 + Elen [i] - 1 ; pn = p1 ; hash = 0 ; deg = 0 ; ASSERT (p1 >= 0 && p1 < iwlen && p2 >= -1 && p2 < iwlen) ; /* ------------------------------------------------------------- */ /* scan the element list associated with supervariable i */ /* ------------------------------------------------------------- */ /* UMFPACK/MA38-style approximate degree: */ if (aggressive) { for (p = p1 ; p <= p2 ; p++) { e = Iw [p] ; ASSERT (e >= 0 && e < n) ; we = W [e] ; if (we != 0) { /* e is an unabsorbed element */ /* dext = | Le \ Lme | */ dext = we - wflg ; if (dext > 0) { deg += dext ; Iw [pn++] = e ; hash += e ; AMD_DEBUG4 ((" e: "ID" hash = "ID"\n",e,hash)) ; } else { /* external degree of e is zero, absorb e into me*/ AMD_DEBUG1 ((" Element "ID" =>"ID" (aggressive)\n", e, me)) ; ASSERT (dext == 0) ; Pe [e] = FLIP (me) ; W [e] = 0 ; } } } } else { for (p = p1 ; p <= p2 ; p++) { e = Iw [p] ; ASSERT (e >= 0 && e < n) ; we = W [e] ; if (we != 0) { /* e is an unabsorbed element */ dext = we - wflg ; ASSERT (dext >= 0) ; deg += dext ; Iw [pn++] = e ; hash += e ; AMD_DEBUG4 ((" e: "ID" hash = "ID"\n",e,hash)) ; } } } /* count the number of elements in i (including me): */ Elen [i] = pn - p1 + 1 ; /* ------------------------------------------------------------- */ /* scan the supervariables in the list associated with i */ /* ------------------------------------------------------------- */ /* The bulk of the AMD run time is typically spent in this loop, * particularly if the matrix has many dense rows that are not * removed prior to ordering. */ p3 = pn ; p4 = p1 + Len [i] ; for (p = p2 + 1 ; p < p4 ; p++) { j = Iw [p] ; ASSERT (j >= 0 && j < n) ; nvj = Nv [j] ; if (nvj > 0) { /* j is unabsorbed, and not in Lme. */ /* add to degree and add to new list */ deg += nvj ; Iw [pn++] = j ; hash += j ; AMD_DEBUG4 ((" s: "ID" hash "ID" Nv[j]= "ID"\n", j, hash, nvj)) ; } } /* ------------------------------------------------------------- */ /* update the degree and check for mass elimination */ /* ------------------------------------------------------------- */ /* with aggressive absorption, deg==0 is identical to the * Elen [i] == 1 && p3 == pn test, below. */ ASSERT (IMPLIES (aggressive, (deg==0) == (Elen[i]==1 && p3==pn))) ; if (Elen [i] == 1 && p3 == pn) { /* --------------------------------------------------------- */ /* mass elimination */ /* --------------------------------------------------------- */ /* There is nothing left of this node except for an edge to * the current pivot element. Elen [i] is 1, and there are * no variables adjacent to node i. Absorb i into the * current pivot element, me. Note that if there are two or * more mass eliminations, fillin due to mass elimination is * possible within the nvpiv-by-nvpiv pivot block. It is this * step that causes AMD's analysis to be an upper bound. * * The reason is that the selected pivot has a lower * approximate degree than the true degree of the two mass * eliminated nodes. There is no edge between the two mass * eliminated nodes. They are merged with the current pivot * anyway. * * No fillin occurs in the Schur complement, in any case, * and this effect does not decrease the quality of the * ordering itself, just the quality of the nonzero and * flop count analysis. It also means that the post-ordering * is not an exact elimination tree post-ordering. */ AMD_DEBUG1 ((" MASS i "ID" => parent e "ID"\n", i, me)) ; Pe [i] = FLIP (me) ; nvi = -Nv [i] ; degme -= nvi ; nvpiv += nvi ; nel += nvi ; Nv [i] = 0 ; Elen [i] = EMPTY ; } else { /* --------------------------------------------------------- */ /* update the upper-bound degree of i */ /* --------------------------------------------------------- */ /* the following degree does not yet include the size * of the current element, which is added later: */ Degree [i] = MIN (Degree [i], deg) ; /* --------------------------------------------------------- */ /* add me to the list for i */ /* --------------------------------------------------------- */ /* move first supervariable to end of list */ Iw [pn] = Iw [p3] ; /* move first element to end of element part of list */ Iw [p3] = Iw [p1] ; /* add new element, me, to front of list. */ Iw [p1] = me ; /* store the new length of the list in Len [i] */ Len [i] = pn - p1 + 1 ; /* --------------------------------------------------------- */ /* place in hash bucket. Save hash key of i in Last [i]. */ /* --------------------------------------------------------- */ /* NOTE: this can fail if hash is negative, because the ANSI C * standard does not define a % b when a and/or b are negative. * That's why hash is defined as an unsigned Int, to avoid this * problem. */ hash = hash % n ; ASSERT (((Int) hash) >= 0 && ((Int) hash) < n) ; /* if the Hhead array is not used: */ j = Head [hash] ; if (j <= EMPTY) { /* degree list is empty, hash head is FLIP (j) */ Next [i] = FLIP (j) ; Head [hash] = FLIP (i) ; } else { /* degree list is not empty, use Last [Head [hash]] as * hash head. */ Next [i] = Last [j] ; Last [j] = i ; } /* if a separate Hhead array is used: * Next [i] = Hhead [hash] ; Hhead [hash] = i ; */ Last [i] = hash ; } } Degree [me] = degme ; /* ----------------------------------------------------------------- */ /* Clear the counter array, W [...], by incrementing wflg. */ /* ----------------------------------------------------------------- */ /* make sure that wflg+n does not cause integer overflow */ lemax = MAX (lemax, degme) ; wflg += lemax ; wflg = clear_flag (wflg, wbig, W, n) ; /* at this point, W [0..n-1] < wflg holds */ /* ========================================================================= */ /* SUPERVARIABLE DETECTION */ /* ========================================================================= */ AMD_DEBUG1 (("Detecting supervariables:\n")) ; for (pme = pme1 ; pme <= pme2 ; pme++) { i = Iw [pme] ; ASSERT (i >= 0 && i < n) ; AMD_DEBUG2 (("Consider i "ID" nv "ID"\n", i, Nv [i])) ; if (Nv [i] < 0) { /* i is a principal variable in Lme */ /* --------------------------------------------------------- * examine all hash buckets with 2 or more variables. We do * this by examing all unique hash keys for supervariables in * the pattern Lme of the current element, me * --------------------------------------------------------- */ /* let i = head of hash bucket, and empty the hash bucket */ ASSERT (Last [i] >= 0 && Last [i] < n) ; hash = Last [i] ; /* if Hhead array is not used: */ j = Head [hash] ; if (j == EMPTY) { /* hash bucket and degree list are both empty */ i = EMPTY ; } else if (j < EMPTY) { /* degree list is empty */ i = FLIP (j) ; Head [hash] = EMPTY ; } else { /* degree list is not empty, restore Last [j] of head j */ i = Last [j] ; Last [j] = EMPTY ; } /* if separate Hhead array is used: * i = Hhead [hash] ; Hhead [hash] = EMPTY ; */ ASSERT (i >= EMPTY && i < n) ; AMD_DEBUG2 (("----i "ID" hash "ID"\n", i, hash)) ; while (i != EMPTY && Next [i] != EMPTY) { /* ----------------------------------------------------- * this bucket has one or more variables following i. * scan all of them to see if i can absorb any entries * that follow i in hash bucket. Scatter i into w. * ----------------------------------------------------- */ ln = Len [i] ; eln = Elen [i] ; ASSERT (ln >= 0 && eln >= 0) ; ASSERT (Pe [i] >= 0 && Pe [i] < iwlen) ; /* do not flag the first element in the list (me) */ for (p = Pe [i] + 1 ; p <= Pe [i] + ln - 1 ; p++) { ASSERT (Iw [p] >= 0 && Iw [p] < n) ; W [Iw [p]] = wflg ; } /* ----------------------------------------------------- */ /* scan every other entry j following i in bucket */ /* ----------------------------------------------------- */ jlast = i ; j = Next [i] ; ASSERT (j >= EMPTY && j < n) ; while (j != EMPTY) { /* ------------------------------------------------- */ /* check if j and i have identical nonzero pattern */ /* ------------------------------------------------- */ AMD_DEBUG3 (("compare i "ID" and j "ID"\n", i,j)) ; /* check if i and j have the same Len and Elen */ ASSERT (Len [j] >= 0 && Elen [j] >= 0) ; ASSERT (Pe [j] >= 0 && Pe [j] < iwlen) ; ok = (Len [j] == ln) && (Elen [j] == eln) ; /* skip the first element in the list (me) */ for (p = Pe [j] + 1 ; ok && p <= Pe [j] + ln - 1 ; p++) { ASSERT (Iw [p] >= 0 && Iw [p] < n) ; if (W [Iw [p]] != wflg) ok = 0 ; } if (ok) { /* --------------------------------------------- */ /* found it! j can be absorbed into i */ /* --------------------------------------------- */ AMD_DEBUG1 (("found it! j "ID" => i "ID"\n", j,i)); Pe [j] = FLIP (i) ; /* both Nv [i] and Nv [j] are negated since they */ /* are in Lme, and the absolute values of each */ /* are the number of variables in i and j: */ Nv [i] += Nv [j] ; Nv [j] = 0 ; Elen [j] = EMPTY ; /* delete j from hash bucket */ ASSERT (j != Next [j]) ; j = Next [j] ; Next [jlast] = j ; } else { /* j cannot be absorbed into i */ jlast = j ; ASSERT (j != Next [j]) ; j = Next [j] ; } ASSERT (j >= EMPTY && j < n) ; } /* ----------------------------------------------------- * no more variables can be absorbed into i * go to next i in bucket and clear flag array * ----------------------------------------------------- */ wflg++ ; i = Next [i] ; ASSERT (i >= EMPTY && i < n) ; } } } AMD_DEBUG2 (("detect done\n")) ; /* ========================================================================= */ /* RESTORE DEGREE LISTS AND REMOVE NONPRINCIPAL SUPERVARIABLES FROM ELEMENT */ /* ========================================================================= */ p = pme1 ; nleft = n - nel ; for (pme = pme1 ; pme <= pme2 ; pme++) { i = Iw [pme] ; ASSERT (i >= 0 && i < n) ; nvi = -Nv [i] ; AMD_DEBUG3 (("Restore i "ID" "ID"\n", i, nvi)) ; if (nvi > 0) { /* i is a principal variable in Lme */ /* restore Nv [i] to signify that i is principal */ Nv [i] = nvi ; /* --------------------------------------------------------- */ /* compute the external degree (add size of current element) */ /* --------------------------------------------------------- */ deg = Degree [i] + degme - nvi ; deg = MIN (deg, nleft - nvi) ; ASSERT (IMPLIES (aggressive, deg > 0) && deg >= 0 && deg < n) ; /* --------------------------------------------------------- */ /* place the supervariable at the head of the degree list */ /* --------------------------------------------------------- */ inext = Head [deg] ; ASSERT (inext >= EMPTY && inext < n) ; if (inext != EMPTY) Last [inext] = i ; Next [i] = inext ; Last [i] = EMPTY ; Head [deg] = i ; /* --------------------------------------------------------- */ /* save the new degree, and find the minimum degree */ /* --------------------------------------------------------- */ mindeg = MIN (mindeg, deg) ; Degree [i] = deg ; /* --------------------------------------------------------- */ /* place the supervariable in the element pattern */ /* --------------------------------------------------------- */ Iw [p++] = i ; } } AMD_DEBUG2 (("restore done\n")) ; /* ========================================================================= */ /* FINALIZE THE NEW ELEMENT */ /* ========================================================================= */ AMD_DEBUG2 (("ME = "ID" DONE\n", me)) ; Nv [me] = nvpiv ; /* save the length of the list for the new element me */ Len [me] = p - pme1 ; if (Len [me] == 0) { /* there is nothing left of the current pivot element */ /* it is a root of the assembly tree */ Pe [me] = EMPTY ; W [me] = 0 ; } if (elenme != 0) { /* element was not constructed in place: deallocate part of */ /* it since newly nonprincipal variables may have been removed */ pfree = p ; } /* The new element has nvpiv pivots and the size of the contribution * block for a multifrontal method is degme-by-degme, not including * the "dense" rows/columns. If the "dense" rows/columns are included, * the frontal matrix is no larger than * (degme+ndense)-by-(degme+ndense). */ if (Info != (double *) NULL) { f = nvpiv ; r = degme + ndense ; dmax = MAX (dmax, f + r) ; /* number of nonzeros in L (excluding the diagonal) */ lnzme = f*r + (f-1)*f/2 ; lnz += lnzme ; /* number of divide operations for LDL' and for LU */ ndiv += lnzme ; /* number of multiply-subtract pairs for LU */ s = f*r*r + r*(f-1)*f + (f-1)*f*(2*f-1)/6 ; nms_lu += s ; /* number of multiply-subtract pairs for LDL' */ nms_ldl += (s + lnzme)/2 ; } #ifndef NDEBUG AMD_DEBUG2 (("finalize done nel "ID" n "ID"\n ::::\n", nel, n)) ; for (pme = Pe [me] ; pme <= Pe [me] + Len [me] - 1 ; pme++) { AMD_DEBUG3 ((" "ID"", Iw [pme])) ; } AMD_DEBUG3 (("\n")) ; #endif } /* ========================================================================= */ /* DONE SELECTING PIVOTS */ /* ========================================================================= */ if (Info != (double *) NULL) { /* count the work to factorize the ndense-by-ndense submatrix */ f = ndense ; dmax = MAX (dmax, (double) ndense) ; /* number of nonzeros in L (excluding the diagonal) */ lnzme = (f-1)*f/2 ; lnz += lnzme ; /* number of divide operations for LDL' and for LU */ ndiv += lnzme ; /* number of multiply-subtract pairs for LU */ s = (f-1)*f*(2*f-1)/6 ; nms_lu += s ; /* number of multiply-subtract pairs for LDL' */ nms_ldl += (s + lnzme)/2 ; /* number of nz's in L (excl. diagonal) */ Info [AMD_LNZ] = lnz ; /* number of divide ops for LU and LDL' */ Info [AMD_NDIV] = ndiv ; /* number of multiply-subtract pairs for LDL' */ Info [AMD_NMULTSUBS_LDL] = nms_ldl ; /* number of multiply-subtract pairs for LU */ Info [AMD_NMULTSUBS_LU] = nms_lu ; /* number of "dense" rows/columns */ Info [AMD_NDENSE] = ndense ; /* largest front is dmax-by-dmax */ Info [AMD_DMAX] = dmax ; /* number of garbage collections in AMD */ Info [AMD_NCMPA] = ncmpa ; /* successful ordering */ Info [AMD_STATUS] = AMD_OK ; } /* ========================================================================= */ /* POST-ORDERING */ /* ========================================================================= */ /* ------------------------------------------------------------------------- * Variables at this point: * * Pe: holds the elimination tree. The parent of j is FLIP (Pe [j]), * or EMPTY if j is a root. The tree holds both elements and * non-principal (unordered) variables absorbed into them. * Dense variables are non-principal and unordered. * * Elen: holds the size of each element, including the diagonal part. * FLIP (Elen [e]) > 0 if e is an element. For unordered * variables i, Elen [i] is EMPTY. * * Nv: Nv [e] > 0 is the number of pivots represented by the element e. * For unordered variables i, Nv [i] is zero. * * Contents no longer needed: * W, Iw, Len, Degree, Head, Next, Last. * * The matrix itself has been destroyed. * * n: the size of the matrix. * No other scalars needed (pfree, iwlen, etc.) * ------------------------------------------------------------------------- */ /* restore Pe */ for (i = 0 ; i < n ; i++) { Pe [i] = FLIP (Pe [i]) ; } /* restore Elen, for output information, and for postordering */ for (i = 0 ; i < n ; i++) { Elen [i] = FLIP (Elen [i]) ; } /* Now the parent of j is Pe [j], or EMPTY if j is a root. Elen [e] > 0 * is the size of element e. Elen [i] is EMPTY for unordered variable i. */ #ifndef NDEBUG AMD_DEBUG2 (("\nTree:\n")) ; for (i = 0 ; i < n ; i++) { AMD_DEBUG2 ((" "ID" parent: "ID" ", i, Pe [i])) ; ASSERT (Pe [i] >= EMPTY && Pe [i] < n) ; if (Nv [i] > 0) { /* this is an element */ e = i ; AMD_DEBUG2 ((" element, size is "ID"\n", Elen [i])) ; ASSERT (Elen [e] > 0) ; } AMD_DEBUG2 (("\n")) ; } AMD_DEBUG2 (("\nelements:\n")) ; for (e = 0 ; e < n ; e++) { if (Nv [e] > 0) { AMD_DEBUG3 (("Element e= "ID" size "ID" nv "ID" \n", e, Elen [e], Nv [e])) ; } } AMD_DEBUG2 (("\nvariables:\n")) ; for (i = 0 ; i < n ; i++) { Int cnt ; if (Nv [i] == 0) { AMD_DEBUG3 (("i unordered: "ID"\n", i)) ; j = Pe [i] ; cnt = 0 ; AMD_DEBUG3 ((" j: "ID"\n", j)) ; if (j == EMPTY) { AMD_DEBUG3 ((" i is a dense variable\n")) ; } else { ASSERT (j >= 0 && j < n) ; while (Nv [j] == 0) { AMD_DEBUG3 ((" j : "ID"\n", j)) ; j = Pe [j] ; AMD_DEBUG3 ((" j:: "ID"\n", j)) ; cnt++ ; if (cnt > n) break ; } e = j ; AMD_DEBUG3 ((" got to e: "ID"\n", e)) ; } } } #endif /* ========================================================================= */ /* compress the paths of the variables */ /* ========================================================================= */ for (i = 0 ; i < n ; i++) { if (Nv [i] == 0) { /* ------------------------------------------------------------- * i is an un-ordered row. Traverse the tree from i until * reaching an element, e. The element, e, was the principal * supervariable of i and all nodes in the path from i to when e * was selected as pivot. * ------------------------------------------------------------- */ AMD_DEBUG1 (("Path compression, i unordered: "ID"\n", i)) ; j = Pe [i] ; ASSERT (j >= EMPTY && j < n) ; AMD_DEBUG3 ((" j: "ID"\n", j)) ; if (j == EMPTY) { /* Skip a dense variable. It has no parent. */ AMD_DEBUG3 ((" i is a dense variable\n")) ; continue ; } /* while (j is a variable) */ while (Nv [j] == 0) { AMD_DEBUG3 ((" j : "ID"\n", j)) ; j = Pe [j] ; AMD_DEBUG3 ((" j:: "ID"\n", j)) ; ASSERT (j >= 0 && j < n) ; } /* got to an element e */ e = j ; AMD_DEBUG3 (("got to e: "ID"\n", e)) ; /* ------------------------------------------------------------- * traverse the path again from i to e, and compress the path * (all nodes point to e). Path compression allows this code to * compute in O(n) time. * ------------------------------------------------------------- */ j = i ; /* while (j is a variable) */ while (Nv [j] == 0) { jnext = Pe [j] ; AMD_DEBUG3 (("j "ID" jnext "ID"\n", j, jnext)) ; Pe [j] = e ; j = jnext ; ASSERT (j >= 0 && j < n) ; } } } /* ========================================================================= */ /* postorder the assembly tree */ /* ========================================================================= */ AMD_postorder (n, Pe, Nv, Elen, W, /* output order */ Head, Next, Last) ; /* workspace */ /* ========================================================================= */ /* compute output permutation and inverse permutation */ /* ========================================================================= */ /* W [e] = k means that element e is the kth element in the new * order. e is in the range 0 to n-1, and k is in the range 0 to * the number of elements. Use Head for inverse order. */ for (k = 0 ; k < n ; k++) { Head [k] = EMPTY ; Next [k] = EMPTY ; } for (e = 0 ; e < n ; e++) { k = W [e] ; ASSERT ((k == EMPTY) == (Nv [e] == 0)) ; if (k != EMPTY) { ASSERT (k >= 0 && k < n) ; Head [k] = e ; } } /* construct output inverse permutation in Next, * and permutation in Last */ nel = 0 ; for (k = 0 ; k < n ; k++) { e = Head [k] ; if (e == EMPTY) break ; ASSERT (e >= 0 && e < n && Nv [e] > 0) ; Next [e] = nel ; nel += Nv [e] ; } ASSERT (nel == n - ndense) ; /* order non-principal variables (dense, & those merged into supervar's) */ for (i = 0 ; i < n ; i++) { if (Nv [i] == 0) { e = Pe [i] ; ASSERT (e >= EMPTY && e < n) ; if (e != EMPTY) { /* This is an unordered variable that was merged * into element e via supernode detection or mass * elimination of i when e became the pivot element. * Place i in order just before e. */ ASSERT (Next [i] == EMPTY && Nv [e] > 0) ; Next [i] = Next [e] ; Next [e]++ ; } else { /* This is a dense unordered variable, with no parent. * Place it last in the output order. */ Next [i] = nel++ ; } } } ASSERT (nel == n) ; AMD_DEBUG2 (("\n\nPerm:\n")) ; for (i = 0 ; i < n ; i++) { k = Next [i] ; ASSERT (k >= 0 && k < n) ; Last [k] = i ; AMD_DEBUG2 ((" perm ["ID"] = "ID"\n", k, i)) ; } } igraph/src/AMD/Source/amd_info.c0000644000175100001440000001011513431000472016102 0ustar hornikusers/* ========================================================================= */ /* === AMD_info ============================================================ */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* User-callable. Prints the output statistics for AMD. See amd.h * for details. If the Info array is not present, nothing is printed. */ #include "amd_internal.h" #define PRI(format,x) { if (x >= 0) { PRINTF ((format, x)) ; }} GLOBAL void AMD_info ( double Info [ ] ) { double n, ndiv, nmultsubs_ldl, nmultsubs_lu, lnz, lnzd ; PRINTF (("\nAMD version %d.%d.%d, %s, results:\n", AMD_MAIN_VERSION, AMD_SUB_VERSION, AMD_SUBSUB_VERSION, AMD_DATE)) ; if (!Info) { return ; } n = Info [AMD_N] ; ndiv = Info [AMD_NDIV] ; nmultsubs_ldl = Info [AMD_NMULTSUBS_LDL] ; nmultsubs_lu = Info [AMD_NMULTSUBS_LU] ; lnz = Info [AMD_LNZ] ; lnzd = (n >= 0 && lnz >= 0) ? (n + lnz) : (-1) ; /* AMD return status */ PRINTF ((" status: ")) ; if (Info [AMD_STATUS] == AMD_OK) { PRINTF (("OK\n")) ; } else if (Info [AMD_STATUS] == AMD_OUT_OF_MEMORY) { PRINTF (("out of memory\n")) ; } else if (Info [AMD_STATUS] == AMD_INVALID) { PRINTF (("invalid matrix\n")) ; } else if (Info [AMD_STATUS] == AMD_OK_BUT_JUMBLED) { PRINTF (("OK, but jumbled\n")) ; } else { PRINTF (("unknown\n")) ; } /* statistics about the input matrix */ PRI (" n, dimension of A: %.20g\n", n); PRI (" nz, number of nonzeros in A: %.20g\n", Info [AMD_NZ]) ; PRI (" symmetry of A: %.4f\n", Info [AMD_SYMMETRY]) ; PRI (" number of nonzeros on diagonal: %.20g\n", Info [AMD_NZDIAG]) ; PRI (" nonzeros in pattern of A+A' (excl. diagonal): %.20g\n", Info [AMD_NZ_A_PLUS_AT]) ; PRI (" # dense rows/columns of A+A': %.20g\n", Info [AMD_NDENSE]) ; /* statistics about AMD's behavior */ PRI (" memory used, in bytes: %.20g\n", Info [AMD_MEMORY]) ; PRI (" # of memory compactions: %.20g\n", Info [AMD_NCMPA]) ; /* statistics about the ordering quality */ PRINTF (("\n" " The following approximate statistics are for a subsequent\n" " factorization of A(P,P) + A(P,P)'. They are slight upper\n" " bounds if there are no dense rows/columns in A+A', and become\n" " looser if dense rows/columns exist.\n\n")) ; PRI (" nonzeros in L (excluding diagonal): %.20g\n", lnz) ; PRI (" nonzeros in L (including diagonal): %.20g\n", lnzd) ; PRI (" # divide operations for LDL' or LU: %.20g\n", ndiv) ; PRI (" # multiply-subtract operations for LDL': %.20g\n", nmultsubs_ldl) ; PRI (" # multiply-subtract operations for LU: %.20g\n", nmultsubs_lu) ; PRI (" max nz. in any column of L (incl. diagonal): %.20g\n", Info [AMD_DMAX]) ; /* total flop counts for various factorizations */ if (n >= 0 && ndiv >= 0 && nmultsubs_ldl >= 0 && nmultsubs_lu >= 0) { PRINTF (("\n" " chol flop count for real A, sqrt counted as 1 flop: %.20g\n" " LDL' flop count for real A: %.20g\n" " LDL' flop count for complex A: %.20g\n" " LU flop count for real A (with no pivoting): %.20g\n" " LU flop count for complex A (with no pivoting): %.20g\n\n", n + ndiv + 2*nmultsubs_ldl, ndiv + 2*nmultsubs_ldl, 9*ndiv + 8*nmultsubs_ldl, ndiv + 2*nmultsubs_lu, 9*ndiv + 8*nmultsubs_lu)) ; } } igraph/src/AMD/Source/amd_aat.c0000644000175100001440000001135713431000472015725 0ustar hornikusers/* ========================================================================= */ /* === AMD_aat ============================================================= */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* AMD_aat: compute the symmetry of the pattern of A, and count the number of * nonzeros each column of A+A' (excluding the diagonal). Assumes the input * matrix has no errors, with sorted columns and no duplicates * (AMD_valid (n, n, Ap, Ai) must be AMD_OK, but this condition is not * checked). */ #include "amd_internal.h" GLOBAL size_t AMD_aat /* returns nz in A+A' */ ( Int n, const Int Ap [ ], const Int Ai [ ], Int Len [ ], /* Len [j]: length of column j of A+A', excl diagonal*/ Int Tp [ ], /* workspace of size n */ double Info [ ] ) { Int p1, p2, p, i, j, pj, pj2, k, nzdiag, nzboth, nz ; double sym ; size_t nzaat ; #ifndef NDEBUG AMD_debug_init ("AMD AAT") ; for (k = 0 ; k < n ; k++) Tp [k] = EMPTY ; ASSERT (AMD_valid (n, n, Ap, Ai) == AMD_OK) ; #endif if (Info != (double *) NULL) { /* clear the Info array, if it exists */ for (i = 0 ; i < AMD_INFO ; i++) { Info [i] = EMPTY ; } Info [AMD_STATUS] = AMD_OK ; } for (k = 0 ; k < n ; k++) { Len [k] = 0 ; } nzdiag = 0 ; nzboth = 0 ; nz = Ap [n] ; for (k = 0 ; k < n ; k++) { p1 = Ap [k] ; p2 = Ap [k+1] ; AMD_DEBUG2 (("\nAAT Column: "ID" p1: "ID" p2: "ID"\n", k, p1, p2)) ; /* construct A+A' */ for (p = p1 ; p < p2 ; ) { /* scan the upper triangular part of A */ j = Ai [p] ; if (j < k) { /* entry A (j,k) is in the strictly upper triangular part, * add both A (j,k) and A (k,j) to the matrix A+A' */ Len [j]++ ; Len [k]++ ; AMD_DEBUG3 ((" upper ("ID","ID") ("ID","ID")\n", j,k, k,j)); p++ ; } else if (j == k) { /* skip the diagonal */ p++ ; nzdiag++ ; break ; } else /* j > k */ { /* first entry below the diagonal */ break ; } /* scan lower triangular part of A, in column j until reaching * row k. Start where last scan left off. */ ASSERT (Tp [j] != EMPTY) ; ASSERT (Ap [j] <= Tp [j] && Tp [j] <= Ap [j+1]) ; pj2 = Ap [j+1] ; for (pj = Tp [j] ; pj < pj2 ; ) { i = Ai [pj] ; if (i < k) { /* A (i,j) is only in the lower part, not in upper. * add both A (i,j) and A (j,i) to the matrix A+A' */ Len [i]++ ; Len [j]++ ; AMD_DEBUG3 ((" lower ("ID","ID") ("ID","ID")\n", i,j, j,i)) ; pj++ ; } else if (i == k) { /* entry A (k,j) in lower part and A (j,k) in upper */ pj++ ; nzboth++ ; break ; } else /* i > k */ { /* consider this entry later, when k advances to i */ break ; } } Tp [j] = pj ; } /* Tp [k] points to the entry just below the diagonal in column k */ Tp [k] = p ; } /* clean up, for remaining mismatched entries */ for (j = 0 ; j < n ; j++) { for (pj = Tp [j] ; pj < Ap [j+1] ; pj++) { i = Ai [pj] ; /* A (i,j) is only in the lower part, not in upper. * add both A (i,j) and A (j,i) to the matrix A+A' */ Len [i]++ ; Len [j]++ ; AMD_DEBUG3 ((" lower cleanup ("ID","ID") ("ID","ID")\n", i,j, j,i)) ; } } /* --------------------------------------------------------------------- */ /* compute the symmetry of the nonzero pattern of A */ /* --------------------------------------------------------------------- */ /* Given a matrix A, the symmetry of A is: * B = tril (spones (A), -1) + triu (spones (A), 1) ; * sym = nnz (B & B') / nnz (B) ; * or 1 if nnz (B) is zero. */ if (nz == nzdiag) { sym = 1 ; } else { sym = (2 * (double) nzboth) / ((double) (nz - nzdiag)) ; } nzaat = 0 ; for (k = 0 ; k < n ; k++) { nzaat += Len [k] ; } AMD_DEBUG1 (("AMD nz in A+A', excluding diagonal (nzaat) = %g\n", (double) nzaat)) ; AMD_DEBUG1 ((" nzboth: "ID" nz: "ID" nzdiag: "ID" symmetry: %g\n", nzboth, nz, nzdiag, sym)) ; if (Info != (double *) NULL) { Info [AMD_STATUS] = AMD_OK ; Info [AMD_N] = n ; Info [AMD_NZ] = nz ; Info [AMD_SYMMETRY] = sym ; /* symmetry of pattern of A */ Info [AMD_NZDIAG] = nzdiag ; /* nonzeros on diagonal of A */ Info [AMD_NZ_A_PLUS_AT] = nzaat ; /* nonzeros in A+A' */ } return (nzaat) ; } igraph/src/AMD/Source/amd_control.c0000644000175100001440000000337213431000472016636 0ustar hornikusers/* ========================================================================= */ /* === AMD_control ========================================================= */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* User-callable. Prints the control parameters for AMD. See amd.h * for details. If the Control array is not present, the defaults are * printed instead. */ #include "amd_internal.h" GLOBAL void AMD_control ( double Control [ ] ) { double alpha ; Int aggressive ; if (Control != (double *) NULL) { alpha = Control [AMD_DENSE] ; aggressive = Control [AMD_AGGRESSIVE] != 0 ; } else { alpha = AMD_DEFAULT_DENSE ; aggressive = AMD_DEFAULT_AGGRESSIVE ; } PRINTF (("\nAMD version %d.%d.%d, %s: approximate minimum degree ordering\n" " dense row parameter: %g\n", AMD_MAIN_VERSION, AMD_SUB_VERSION, AMD_SUBSUB_VERSION, AMD_DATE, alpha)) ; if (alpha < 0) { PRINTF ((" no rows treated as dense\n")) ; } else { PRINTF (( " (rows with more than max (%g * sqrt (n), 16) entries are\n" " considered \"dense\", and placed last in output permutation)\n", alpha)) ; } if (aggressive) { PRINTF ((" aggressive absorption: yes\n")) ; } else { PRINTF ((" aggressive absorption: no\n")) ; } PRINTF ((" size of AMD integer: %d\n\n", sizeof (Int))) ; } igraph/src/AMD/Source/amd_order.c0000644000175100001440000001337413431000472016274 0ustar hornikusers/* ========================================================================= */ /* === AMD_order =========================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* User-callable AMD minimum degree ordering routine. See amd.h for * documentation. */ #include "amd_internal.h" /* ========================================================================= */ /* === AMD_order =========================================================== */ /* ========================================================================= */ GLOBAL Int AMD_order ( Int n, const Int Ap [ ], const Int Ai [ ], Int P [ ], double Control [ ], double Info [ ] ) { Int *Len, *S, nz, i, *Pinv, info, status, *Rp, *Ri, *Cp, *Ci, ok ; size_t nzaat, slen ; double mem = 0 ; #ifndef NDEBUG AMD_debug_init ("amd") ; #endif /* clear the Info array, if it exists */ info = Info != (double *) NULL ; if (info) { for (i = 0 ; i < AMD_INFO ; i++) { Info [i] = EMPTY ; } Info [AMD_N] = n ; Info [AMD_STATUS] = AMD_OK ; } /* make sure inputs exist and n is >= 0 */ if (Ai == (Int *) NULL || Ap == (Int *) NULL || P == (Int *) NULL || n < 0) { if (info) Info [AMD_STATUS] = AMD_INVALID ; return (AMD_INVALID) ; /* arguments are invalid */ } if (n == 0) { return (AMD_OK) ; /* n is 0 so there's nothing to do */ } nz = Ap [n] ; if (info) { Info [AMD_NZ] = nz ; } if (nz < 0) { if (info) Info [AMD_STATUS] = AMD_INVALID ; return (AMD_INVALID) ; } /* check if n or nz will cause size_t overflow */ if (((size_t) n) >= SIZE_T_MAX / sizeof (Int) || ((size_t) nz) >= SIZE_T_MAX / sizeof (Int)) { if (info) Info [AMD_STATUS] = AMD_OUT_OF_MEMORY ; return (AMD_OUT_OF_MEMORY) ; /* problem too large */ } /* check the input matrix: AMD_OK, AMD_INVALID, or AMD_OK_BUT_JUMBLED */ status = AMD_valid (n, n, Ap, Ai) ; if (status == AMD_INVALID) { if (info) Info [AMD_STATUS] = AMD_INVALID ; return (AMD_INVALID) ; /* matrix is invalid */ } /* allocate two size-n integer workspaces */ Len = amd_malloc (n * sizeof (Int)) ; Pinv = amd_malloc (n * sizeof (Int)) ; mem += n ; mem += n ; if (!Len || !Pinv) { /* :: out of memory :: */ amd_free (Len) ; amd_free (Pinv) ; if (info) Info [AMD_STATUS] = AMD_OUT_OF_MEMORY ; return (AMD_OUT_OF_MEMORY) ; } if (status == AMD_OK_BUT_JUMBLED) { /* sort the input matrix and remove duplicate entries */ AMD_DEBUG1 (("Matrix is jumbled\n")) ; Rp = amd_malloc ((n+1) * sizeof (Int)) ; Ri = amd_malloc (MAX (nz,1) * sizeof (Int)) ; mem += (n+1) ; mem += MAX (nz,1) ; if (!Rp || !Ri) { /* :: out of memory :: */ amd_free (Rp) ; amd_free (Ri) ; amd_free (Len) ; amd_free (Pinv) ; if (info) Info [AMD_STATUS] = AMD_OUT_OF_MEMORY ; return (AMD_OUT_OF_MEMORY) ; } /* use Len and Pinv as workspace to create R = A' */ AMD_preprocess (n, Ap, Ai, Rp, Ri, Len, Pinv) ; Cp = Rp ; Ci = Ri ; } else { /* order the input matrix as-is. No need to compute R = A' first */ Rp = NULL ; Ri = NULL ; Cp = (Int *) Ap ; Ci = (Int *) Ai ; } /* --------------------------------------------------------------------- */ /* determine the symmetry and count off-diagonal nonzeros in A+A' */ /* --------------------------------------------------------------------- */ nzaat = AMD_aat (n, Cp, Ci, Len, P, Info) ; AMD_DEBUG1 (("nzaat: %g\n", (double) nzaat)) ; ASSERT ((MAX (nz-n, 0) <= nzaat) && (nzaat <= 2 * (size_t) nz)) ; /* --------------------------------------------------------------------- */ /* allocate workspace for matrix, elbow room, and 6 size-n vectors */ /* --------------------------------------------------------------------- */ S = NULL ; slen = nzaat ; /* space for matrix */ ok = ((slen + nzaat/5) >= slen) ; /* check for size_t overflow */ slen += nzaat/5 ; /* add elbow room */ for (i = 0 ; ok && i < 7 ; i++) { ok = ((slen + n) > slen) ; /* check for size_t overflow */ slen += n ; /* size-n elbow room, 6 size-n work */ } mem += slen ; ok = ok && (slen < SIZE_T_MAX / sizeof (Int)) ; /* check for overflow */ ok = ok && (slen < Int_MAX) ; /* S[i] for Int i must be OK */ if (ok) { S = amd_malloc (slen * sizeof (Int)) ; } AMD_DEBUG1 (("slen %g\n", (double) slen)) ; if (!S) { /* :: out of memory :: (or problem too large) */ amd_free (Rp) ; amd_free (Ri) ; amd_free (Len) ; amd_free (Pinv) ; if (info) Info [AMD_STATUS] = AMD_OUT_OF_MEMORY ; return (AMD_OUT_OF_MEMORY) ; } if (info) { /* memory usage, in bytes. */ Info [AMD_MEMORY] = mem * sizeof (Int) ; } /* --------------------------------------------------------------------- */ /* order the matrix */ /* --------------------------------------------------------------------- */ AMD_1 (n, Cp, Ci, P, Pinv, Len, slen, S, Control, Info) ; /* --------------------------------------------------------------------- */ /* free the workspace */ /* --------------------------------------------------------------------- */ amd_free (Rp) ; amd_free (Ri) ; amd_free (Len) ; amd_free (Pinv) ; amd_free (S) ; if (info) Info [AMD_STATUS] = status ; return (status) ; /* successful ordering */ } igraph/src/AMD/Source/amdbar.f0000644000175100001440000014607213431000472015573 0ustar hornikusersC----------------------------------------------------------------------- C AMDBAR: approximate minimum degree, without aggressive absorption C----------------------------------------------------------------------- SUBROUTINE AMDBAR $ (N, PE, IW, LEN, IWLEN, PFREE, NV, NEXT, $ LAST, HEAD, ELEN, DEGREE, NCMPA, W) INTEGER N, IWLEN, PFREE, NCMPA, IW (IWLEN), PE (N), $ DEGREE (N), NV (N), NEXT (N), LAST (N), HEAD (N), $ ELEN (N), W (N), LEN (N) C Given a representation of the nonzero pattern of a symmetric matrix, C A, (excluding the diagonal) perform an approximate minimum C (UMFPACK/MA38-style) degree ordering to compute a pivot order C such that the introduction of nonzeros (fill-in) in the Cholesky C factors A = LL^T are kept low. At each step, the pivot C selected is the one with the minimum UMFPACK/MA38-style C upper-bound on the external degree. C C This routine does not do aggresive absorption (as done by AMD). C ********************************************************************** C ***** CAUTION: ARGUMENTS ARE NOT CHECKED FOR ERRORS ON INPUT. ****** C ********************************************************************** C References: C C [1] Timothy A. Davis and Iain Duff, "An unsymmetric-pattern C multifrontal method for sparse LU factorization", SIAM J. C Matrix Analysis and Applications, vol. 18, no. 1, pp. C 140-158. Discusses UMFPACK / MA38, which first introduced C the approximate minimum degree used by this routine. C C [2] Patrick Amestoy, Timothy A. Davis, and Iain S. Duff, "An C approximate degree ordering algorithm," SIAM J. Matrix C Analysis and Applications, vol. 17, no. 4, pp. 886-905, C 1996. Discusses AMD, AMDBAR, and MC47B. C C [3] Alan George and Joseph Liu, "The evolution of the minimum C degree ordering algorithm," SIAM Review, vol. 31, no. 1, C pp. 1-19, 1989. We list below the features mentioned in C that paper that this code includes: C C mass elimination: C Yes. MA27 relied on supervariable detection for mass C elimination. C indistinguishable nodes: C Yes (we call these "supervariables"). This was also in C the MA27 code - although we modified the method of C detecting them (the previous hash was the true degree, C which we no longer keep track of). A supervariable is C a set of rows with identical nonzero pattern. All C variables in a supervariable are eliminated together. C Each supervariable has as its numerical name that of C one of its variables (its principal variable). C quotient graph representation: C Yes. We use the term "element" for the cliques formed C during elimination. This was also in the MA27 code. C The algorithm can operate in place, but it will work C more efficiently if given some "elbow room." C element absorption: C Yes. This was also in the MA27 code. C external degree: C Yes. The MA27 code was based on the true degree. C incomplete degree update and multiple elimination: C No. This was not in MA27, either. Our method of C degree update within MC47B/BD is element-based, not C variable-based. It is thus not well-suited for use C with incomplete degree update or multiple elimination. C----------------------------------------------------------------------- C Authors, and Copyright (C) 1995 by: C Timothy A. Davis, Patrick Amestoy, Iain S. Duff, & John K. Reid. C C Acknowledgements: C This work (and the UMFPACK package) was supported by the C National Science Foundation (ASC-9111263 and DMS-9223088). C The UMFPACK/MA38 approximate degree update algorithm, the C unsymmetric analog which forms the basis of MC47B/BD, was C developed while Tim Davis was supported by CERFACS (Toulouse, C France) in a post-doctoral position. C C Date: September, 1995 C----------------------------------------------------------------------- C----------------------------------------------------------------------- C INPUT ARGUMENTS (unaltered): C----------------------------------------------------------------------- C n: The matrix order. C C Restriction: 1 .le. n .lt. (iovflo/2)-2, where iovflo is C the largest positive integer that your computer can represent. C iwlen: The length of iw (1..iwlen). On input, the matrix is C stored in iw (1..pfree-1). However, iw (1..iwlen) should be C slightly larger than what is required to hold the matrix, at C least iwlen .ge. pfree + n is recommended. Otherwise, C excessive compressions will take place. C *** We do not recommend running this algorithm with *** C *** iwlen .lt. pfree + n. *** C *** Better performance will be obtained if *** C *** iwlen .ge. pfree + n *** C *** or better yet *** C *** iwlen .gt. 1.2 * pfree *** C *** (where pfree is its value on input). *** C The algorithm will not run at all if iwlen .lt. pfree-1. C C Restriction: iwlen .ge. pfree-1 C----------------------------------------------------------------------- C INPUT/OUPUT ARGUMENTS: C----------------------------------------------------------------------- C pe: On input, pe (i) is the index in iw of the start of row i, or C zero if row i has no off-diagonal non-zeros. C C During execution, it is used for both supervariables and C elements: C C * Principal supervariable i: index into iw of the C description of supervariable i. A supervariable C represents one or more rows of the matrix C with identical nonzero pattern. C * Non-principal supervariable i: if i has been absorbed C into another supervariable j, then pe (i) = -j. C That is, j has the same pattern as i. C Note that j might later be absorbed into another C supervariable j2, in which case pe (i) is still -j, C and pe (j) = -j2. C * Unabsorbed element e: the index into iw of the description C of element e, if e has not yet been absorbed by a C subsequent element. Element e is created when C the supervariable of the same name is selected as C the pivot. C * Absorbed element e: if element e is absorbed into element C e2, then pe (e) = -e2. This occurs when the pattern of C e (that is, Le) is found to be a subset of the pattern C of e2 (that is, Le2). If element e is "null" (it has C no nonzeros outside its pivot block), then pe (e) = 0. C C On output, pe holds the assembly tree/forest, which implicitly C represents a pivot order with identical fill-in as the actual C order (via a depth-first search of the tree). C C On output: C If nv (i) .gt. 0, then i represents a node in the assembly tree, C and the parent of i is -pe (i), or zero if i is a root. C If nv (i) = 0, then (i,-pe (i)) represents an edge in a C subtree, the root of which is a node in the assembly tree. C pfree: On input the tail end of the array, iw (pfree..iwlen), C is empty, and the matrix is stored in iw (1..pfree-1). C During execution, additional data is placed in iw, and pfree C is modified so that iw (pfree..iwlen) is always the unused part C of iw. On output, pfree is set equal to the size of iw that C would have been needed for no compressions to occur. If C ncmpa is zero, then pfree (on output) is less than or equal to C iwlen, and the space iw (pfree+1 ... iwlen) was not used. C Otherwise, pfree (on output) is greater than iwlen, and all the C memory in iw was used. C----------------------------------------------------------------------- C INPUT/MODIFIED (undefined on output): C----------------------------------------------------------------------- C len: On input, len (i) holds the number of entries in row i of the C matrix, excluding the diagonal. The contents of len (1..n) C are undefined on output. C iw: On input, iw (1..pfree-1) holds the description of each row i C in the matrix. The matrix must be symmetric, and both upper C and lower triangular parts must be present. The diagonal must C not be present. Row i is held as follows: C C len (i): the length of the row i data structure C iw (pe (i) ... pe (i) + len (i) - 1): C the list of column indices for nonzeros C in row i (simple supervariables), excluding C the diagonal. All supervariables start with C one row/column each (supervariable i is just C row i). C if len (i) is zero on input, then pe (i) is ignored C on input. C C Note that the rows need not be in any particular order, C and there may be empty space between the rows. C C During execution, the supervariable i experiences fill-in. C This is represented by placing in i a list of the elements C that cause fill-in in supervariable i: C C len (i): the length of supervariable i C iw (pe (i) ... pe (i) + elen (i) - 1): C the list of elements that contain i. This list C is kept short by removing absorbed elements. C iw (pe (i) + elen (i) ... pe (i) + len (i) - 1): C the list of supervariables in i. This list C is kept short by removing nonprincipal C variables, and any entry j that is also C contained in at least one of the elements C (j in Le) in the list for i (e in row i). C C When supervariable i is selected as pivot, we create an C element e of the same name (e=i): C C len (e): the length of element e C iw (pe (e) ... pe (e) + len (e) - 1): C the list of supervariables in element e. C C An element represents the fill-in that occurs when supervariable C i is selected as pivot (which represents the selection of row i C and all non-principal variables whose principal variable is i). C We use the term Le to denote the set of all supervariables C in element e. Absorbed supervariables and elements are pruned C from these lists when computationally convenient. C C CAUTION: THE INPUT MATRIX IS OVERWRITTEN DURING COMPUTATION. C The contents of iw are undefined on output. C----------------------------------------------------------------------- C OUTPUT (need not be set on input): C----------------------------------------------------------------------- C nv: During execution, abs (nv (i)) is equal to the number of rows C that are represented by the principal supervariable i. If i is C a nonprincipal variable, then nv (i) = 0. Initially, C nv (i) = 1 for all i. nv (i) .lt. 0 signifies that i is a C principal variable in the pattern Lme of the current pivot C element me. On output, nv (e) holds the true degree of element C e at the time it was created (including the diagonal part). C ncmpa: The number of times iw was compressed. If this is C excessive, then the execution took longer than what could have C been. To reduce ncmpa, try increasing iwlen to be 10% or 20% C larger than the value of pfree on input (or at least C iwlen .ge. pfree + n). The fastest performance will be C obtained when ncmpa is returned as zero. If iwlen is set to C the value returned by pfree on *output*, then no compressions C will occur. C elen: See the description of iw above. At the start of execution, C elen (i) is set to zero. During execution, elen (i) is the C number of elements in the list for supervariable i. When e C becomes an element, elen (e) = -nel is set, where nel is the C current step of factorization. elen (i) = 0 is done when i C becomes nonprincipal. C C For variables, elen (i) .ge. 0 holds until just before the C permutation vectors are computed. For elements, C elen (e) .lt. 0 holds. C C On output elen (1..n) holds the inverse permutation (the same C as the 'INVP' argument in Sparspak). That is, if k = elen (i), C then row i is the kth pivot row. Row i of A appears as the C (elen(i))-th row in the permuted matrix, PAP^T. C last: In a degree list, last (i) is the supervariable preceding i, C or zero if i is the head of the list. In a hash bucket, C last (i) is the hash key for i. last (head (hash)) is also C used as the head of a hash bucket if head (hash) contains a C degree list (see head, below). C C On output, last (1..n) holds the permutation (the same as the C 'PERM' argument in Sparspak). That is, if i = last (k), then C row i is the kth pivot row. Row last (k) of A is the k-th row C in the permuted matrix, PAP^T. C----------------------------------------------------------------------- C LOCAL (not input or output - used only during execution): C----------------------------------------------------------------------- C degree: If i is a supervariable, then degree (i) holds the C current approximation of the external degree of row i (an upper C bound). The external degree is the number of nonzeros in row i, C minus abs (nv (i)) (the diagonal part). The bound is equal to C the external degree if elen (i) is less than or equal to two. C C We also use the term "external degree" for elements e to refer C to |Le \ Lme|. If e is an element, then degree (e) holds |Le|, C which is the degree of the off-diagonal part of the element e C (not including the diagonal part). C head: head is used for degree lists. head (deg) is the first C supervariable in a degree list (all supervariables i in a C degree list deg have the same approximate degree, namely, C deg = degree (i)). If the list deg is empty then C head (deg) = 0. C C During supervariable detection head (hash) also serves as a C pointer to a hash bucket. C If head (hash) .gt. 0, there is a degree list of degree hash. C The hash bucket head pointer is last (head (hash)). C If head (hash) = 0, then the degree list and hash bucket are C both empty. C If head (hash) .lt. 0, then the degree list is empty, and C -head (hash) is the head of the hash bucket. C After supervariable detection is complete, all hash buckets C are empty, and the (last (head (hash)) = 0) condition is C restored for the non-empty degree lists. C next: next (i) is the supervariable following i in a link list, or C zero if i is the last in the list. Used for two kinds of C lists: degree lists and hash buckets (a supervariable can be C in only one kind of list at a time). C w: The flag array w determines the status of elements and C variables, and the external degree of elements. C C for elements: C if w (e) = 0, then the element e is absorbed C if w (e) .ge. wflg, then w (e) - wflg is the size of C the set |Le \ Lme|, in terms of nonzeros (the C sum of abs (nv (i)) for each principal variable i that C is both in the pattern of element e and NOT in the C pattern of the current pivot element, me). C if wflg .gt. w (e) .gt. 0, then e is not absorbed and has C not yet been seen in the scan of the element lists in C the computation of |Le\Lme| in loop 150 below. C C for variables: C during supervariable detection, if w (j) .ne. wflg then j is C not in the pattern of variable i C C The w array is initialized by setting w (i) = 1 for all i, C and by setting wflg = 2. It is reinitialized if wflg becomes C too large (to ensure that wflg+n does not cause integer C overflow). C----------------------------------------------------------------------- C LOCAL INTEGERS: C----------------------------------------------------------------------- INTEGER DEG, DEGME, DMAX, E, ELENME, ELN, HASH, HMOD, I, $ ILAST, INEXT, J, JLAST, JNEXT, K, KNT1, KNT2, KNT3, $ LENJ, LN, MAXMEM, ME, MEM, MINDEG, NEL, NEWMEM, $ NLEFT, NVI, NVJ, NVPIV, SLENME, WE, WFLG, WNVI, X C deg: the degree of a variable or element C degme: size, |Lme|, of the current element, me (= degree (me)) C dext: external degree, |Le \ Lme|, of some element e C dmax: largest |Le| seen so far C e: an element C elenme: the length, elen (me), of element list of pivotal var. C eln: the length, elen (...), of an element list C hash: the computed value of the hash function C hmod: the hash function is computed modulo hmod = max (1,n-1) C i: a supervariable C ilast: the entry in a link list preceding i C inext: the entry in a link list following i C j: a supervariable C jlast: the entry in a link list preceding j C jnext: the entry in a link list, or path, following j C k: the pivot order of an element or variable C knt1: loop counter used during element construction C knt2: loop counter used during element construction C knt3: loop counter used during compression C lenj: len (j) C ln: length of a supervariable list C maxmem: amount of memory needed for no compressions C me: current supervariable being eliminated, and the C current element created by eliminating that C supervariable C mem: memory in use assuming no compressions have occurred C mindeg: current minimum degree C nel: number of pivots selected so far C newmem: amount of new memory needed for current pivot element C nleft: n - nel, the number of nonpivotal rows/columns remaining C nvi: the number of variables in a supervariable i (= nv (i)) C nvj: the number of variables in a supervariable j (= nv (j)) C nvpiv: number of pivots in current element C slenme: number of variables in variable list of pivotal variable C we: w (e) C wflg: used for flagging the w array. See description of iw. C wnvi: wflg - nv (i) C x: either a supervariable or an element C----------------------------------------------------------------------- C LOCAL POINTERS: C----------------------------------------------------------------------- INTEGER P, P1, P2, P3, PDST, PEND, PJ, PME, PME1, PME2, PN, PSRC C Any parameter (pe (...) or pfree) or local variable C starting with "p" (for Pointer) is an index into iw, C and all indices into iw use variables starting with C "p." The only exception to this rule is the iwlen C input argument. C p: pointer into lots of things C p1: pe (i) for some variable i (start of element list) C p2: pe (i) + elen (i) - 1 for some var. i (end of el. list) C p3: index of first supervariable in clean list C pdst: destination pointer, for compression C pend: end of memory to compress C pj: pointer into an element or variable C pme: pointer into the current element (pme1...pme2) C pme1: the current element, me, is stored in iw (pme1...pme2) C pme2: the end of the current element C pn: pointer into a "clean" variable, also used to compress C psrc: source pointer, for compression C----------------------------------------------------------------------- C FUNCTIONS CALLED: C----------------------------------------------------------------------- INTRINSIC MAX, MIN, MOD C======================================================================= C INITIALIZATIONS C======================================================================= WFLG = 2 MINDEG = 1 NCMPA = 0 NEL = 0 HMOD = MAX (1, N-1) DMAX = 0 MEM = PFREE - 1 MAXMEM = MEM ME = 0 DO 10 I = 1, N LAST (I) = 0 HEAD (I) = 0 NV (I) = 1 W (I) = 1 ELEN (I) = 0 DEGREE (I) = LEN (I) 10 CONTINUE C ---------------------------------------------------------------- C initialize degree lists and eliminate rows with no off-diag. nz. C ---------------------------------------------------------------- DO 20 I = 1, N DEG = DEGREE (I) IF (DEG .GT. 0) THEN C ---------------------------------------------------------- C place i in the degree list corresponding to its degree C ---------------------------------------------------------- INEXT = HEAD (DEG) IF (INEXT .NE. 0) LAST (INEXT) = I NEXT (I) = INEXT HEAD (DEG) = I ELSE C ---------------------------------------------------------- C we have a variable that can be eliminated at once because C there is no off-diagonal non-zero in its row. C ---------------------------------------------------------- NEL = NEL + 1 ELEN (I) = -NEL PE (I) = 0 W (I) = 0 ENDIF 20 CONTINUE C======================================================================= C WHILE (selecting pivots) DO C======================================================================= 30 CONTINUE IF (NEL .LT. N) THEN C======================================================================= C GET PIVOT OF MINIMUM DEGREE C======================================================================= C ------------------------------------------------------------- C find next supervariable for elimination C ------------------------------------------------------------- DO 40 DEG = MINDEG, N ME = HEAD (DEG) IF (ME .GT. 0) GOTO 50 40 CONTINUE 50 CONTINUE MINDEG = DEG C ------------------------------------------------------------- C remove chosen variable from link list C ------------------------------------------------------------- INEXT = NEXT (ME) IF (INEXT .NE. 0) LAST (INEXT) = 0 HEAD (DEG) = INEXT C ------------------------------------------------------------- C me represents the elimination of pivots nel+1 to nel+nv(me). C place me itself as the first in this set. It will be moved C to the nel+nv(me) position when the permutation vectors are C computed. C ------------------------------------------------------------- ELENME = ELEN (ME) ELEN (ME) = - (NEL + 1) NVPIV = NV (ME) NEL = NEL + NVPIV C======================================================================= C CONSTRUCT NEW ELEMENT C======================================================================= C ------------------------------------------------------------- C At this point, me is the pivotal supervariable. It will be C converted into the current element. Scan list of the C pivotal supervariable, me, setting tree pointers and C constructing new list of supervariables for the new element, C me. p is a pointer to the current position in the old list. C ------------------------------------------------------------- C flag the variable "me" as being in Lme by negating nv (me) NV (ME) = -NVPIV DEGME = 0 IF (ELENME .EQ. 0) THEN C ---------------------------------------------------------- C construct the new element in place C ---------------------------------------------------------- PME1 = PE (ME) PME2 = PME1 - 1 DO 60 P = PME1, PME1 + LEN (ME) - 1 I = IW (P) NVI = NV (I) IF (NVI .GT. 0) THEN C ---------------------------------------------------- C i is a principal variable not yet placed in Lme. C store i in new list C ---------------------------------------------------- DEGME = DEGME + NVI C flag i as being in Lme by negating nv (i) NV (I) = -NVI PME2 = PME2 + 1 IW (PME2) = I C ---------------------------------------------------- C remove variable i from degree list. C ---------------------------------------------------- ILAST = LAST (I) INEXT = NEXT (I) IF (INEXT .NE. 0) LAST (INEXT) = ILAST IF (ILAST .NE. 0) THEN NEXT (ILAST) = INEXT ELSE C i is at the head of the degree list HEAD (DEGREE (I)) = INEXT ENDIF ENDIF 60 CONTINUE C this element takes no new memory in iw: NEWMEM = 0 ELSE C ---------------------------------------------------------- C construct the new element in empty space, iw (pfree ...) C ---------------------------------------------------------- P = PE (ME) PME1 = PFREE SLENME = LEN (ME) - ELENME DO 120 KNT1 = 1, ELENME + 1 IF (KNT1 .GT. ELENME) THEN C search the supervariables in me. E = ME PJ = P LN = SLENME ELSE C search the elements in me. E = IW (P) P = P + 1 PJ = PE (E) LN = LEN (E) ENDIF C ------------------------------------------------------- C search for different supervariables and add them to the C new list, compressing when necessary. this loop is C executed once for each element in the list and once for C all the supervariables in the list. C ------------------------------------------------------- DO 110 KNT2 = 1, LN I = IW (PJ) PJ = PJ + 1 NVI = NV (I) IF (NVI .GT. 0) THEN C ------------------------------------------------- C compress iw, if necessary C ------------------------------------------------- IF (PFREE .GT. IWLEN) THEN C prepare for compressing iw by adjusting C pointers and lengths so that the lists being C searched in the inner and outer loops contain C only the remaining entries. PE (ME) = P LEN (ME) = LEN (ME) - KNT1 IF (LEN (ME) .EQ. 0) THEN C nothing left of supervariable me PE (ME) = 0 ENDIF PE (E) = PJ LEN (E) = LN - KNT2 IF (LEN (E) .EQ. 0) THEN C nothing left of element e PE (E) = 0 ENDIF NCMPA = NCMPA + 1 C store first item in pe C set first entry to -item DO 70 J = 1, N PN = PE (J) IF (PN .GT. 0) THEN PE (J) = IW (PN) IW (PN) = -J ENDIF 70 CONTINUE C psrc/pdst point to source/destination PDST = 1 PSRC = 1 PEND = PME1 - 1 C while loop: 80 CONTINUE IF (PSRC .LE. PEND) THEN C search for next negative entry J = -IW (PSRC) PSRC = PSRC + 1 IF (J .GT. 0) THEN IW (PDST) = PE (J) PE (J) = PDST PDST = PDST + 1 C copy from source to destination LENJ = LEN (J) DO 90 KNT3 = 0, LENJ - 2 IW (PDST + KNT3) = IW (PSRC + KNT3) 90 CONTINUE PDST = PDST + LENJ - 1 PSRC = PSRC + LENJ - 1 ENDIF GOTO 80 ENDIF C move the new partially-constructed element P1 = PDST DO 100 PSRC = PME1, PFREE - 1 IW (PDST) = IW (PSRC) PDST = PDST + 1 100 CONTINUE PME1 = P1 PFREE = PDST PJ = PE (E) P = PE (ME) ENDIF C ------------------------------------------------- C i is a principal variable not yet placed in Lme C store i in new list C ------------------------------------------------- DEGME = DEGME + NVI C flag i as being in Lme by negating nv (i) NV (I) = -NVI IW (PFREE) = I PFREE = PFREE + 1 C ------------------------------------------------- C remove variable i from degree link list C ------------------------------------------------- ILAST = LAST (I) INEXT = NEXT (I) IF (INEXT .NE. 0) LAST (INEXT) = ILAST IF (ILAST .NE. 0) THEN NEXT (ILAST) = INEXT ELSE C i is at the head of the degree list HEAD (DEGREE (I)) = INEXT ENDIF ENDIF 110 CONTINUE IF (E .NE. ME) THEN C set tree pointer and flag to indicate element e is C absorbed into new element me (the parent of e is me) PE (E) = -ME W (E) = 0 ENDIF 120 CONTINUE PME2 = PFREE - 1 C this element takes newmem new memory in iw (possibly zero) NEWMEM = PFREE - PME1 MEM = MEM + NEWMEM MAXMEM = MAX (MAXMEM, MEM) ENDIF C ------------------------------------------------------------- C me has now been converted into an element in iw (pme1..pme2) C ------------------------------------------------------------- C degme holds the external degree of new element DEGREE (ME) = DEGME PE (ME) = PME1 LEN (ME) = PME2 - PME1 + 1 C ------------------------------------------------------------- C make sure that wflg is not too large. With the current C value of wflg, wflg+n must not cause integer overflow C ------------------------------------------------------------- IF (WFLG + N .LE. WFLG) THEN DO 130 X = 1, N IF (W (X) .NE. 0) W (X) = 1 130 CONTINUE WFLG = 2 ENDIF C======================================================================= C COMPUTE (w (e) - wflg) = |Le\Lme| FOR ALL ELEMENTS C======================================================================= C ------------------------------------------------------------- C Scan 1: compute the external degrees of previous elements C with respect to the current element. That is: C (w (e) - wflg) = |Le \ Lme| C for each element e that appears in any supervariable in Lme. C The notation Le refers to the pattern (list of C supervariables) of a previous element e, where e is not yet C absorbed, stored in iw (pe (e) + 1 ... pe (e) + iw (pe (e))). C The notation Lme refers to the pattern of the current element C (stored in iw (pme1..pme2)). If (w (e) - wflg) becomes C zero, then the element e will be absorbed in scan 2. C ------------------------------------------------------------- DO 150 PME = PME1, PME2 I = IW (PME) ELN = ELEN (I) IF (ELN .GT. 0) THEN C note that nv (i) has been negated to denote i in Lme: NVI = -NV (I) WNVI = WFLG - NVI DO 140 P = PE (I), PE (I) + ELN - 1 E = IW (P) WE = W (E) IF (WE .GE. WFLG) THEN C unabsorbed element e has been seen in this loop WE = WE - NVI ELSE IF (WE .NE. 0) THEN C e is an unabsorbed element C this is the first we have seen e in all of Scan 1 WE = DEGREE (E) + WNVI ENDIF W (E) = WE 140 CONTINUE ENDIF 150 CONTINUE C======================================================================= C DEGREE UPDATE AND ELEMENT ABSORPTION C======================================================================= C ------------------------------------------------------------- C Scan 2: for each i in Lme, sum up the degree of Lme (which C is degme), plus the sum of the external degrees of each Le C for the elements e appearing within i, plus the C supervariables in i. Place i in hash list. C ------------------------------------------------------------- DO 180 PME = PME1, PME2 I = IW (PME) P1 = PE (I) P2 = P1 + ELEN (I) - 1 PN = P1 HASH = 0 DEG = 0 C ---------------------------------------------------------- C scan the element list associated with supervariable i C ---------------------------------------------------------- C UMFPACK/MA38-style approximate degree: DO 160 P = P1, P2 E = IW (P) WE = W (E) IF (WE .NE. 0) THEN C e is an unabsorbed element DEG = DEG + WE - WFLG IW (PN) = E PN = PN + 1 HASH = HASH + E ENDIF 160 CONTINUE C count the number of elements in i (including me): ELEN (I) = PN - P1 + 1 C ---------------------------------------------------------- C scan the supervariables in the list associated with i C ---------------------------------------------------------- P3 = PN DO 170 P = P2 + 1, P1 + LEN (I) - 1 J = IW (P) NVJ = NV (J) IF (NVJ .GT. 0) THEN C j is unabsorbed, and not in Lme. C add to degree and add to new list DEG = DEG + NVJ IW (PN) = J PN = PN + 1 HASH = HASH + J ENDIF 170 CONTINUE C ---------------------------------------------------------- C update the degree and check for mass elimination C ---------------------------------------------------------- IF (ELEN (I) .EQ. 1 .AND. P3 .EQ. PN) THEN C ------------------------------------------------------- C mass elimination C ------------------------------------------------------- C There is nothing left of this node except for an C edge to the current pivot element. elen (i) is 1, C and there are no variables adjacent to node i. C Absorb i into the current pivot element, me. PE (I) = -ME NVI = -NV (I) DEGME = DEGME - NVI NVPIV = NVPIV + NVI NEL = NEL + NVI NV (I) = 0 ELEN (I) = 0 ELSE C ------------------------------------------------------- C update the upper-bound degree of i C ------------------------------------------------------- C the following degree does not yet include the size C of the current element, which is added later: DEGREE (I) = MIN (DEGREE (I), DEG) C ------------------------------------------------------- C add me to the list for i C ------------------------------------------------------- C move first supervariable to end of list IW (PN) = IW (P3) C move first element to end of element part of list IW (P3) = IW (P1) C add new element to front of list. IW (P1) = ME C store the new length of the list in len (i) LEN (I) = PN - P1 + 1 C ------------------------------------------------------- C place in hash bucket. Save hash key of i in last (i). C ------------------------------------------------------- HASH = MOD (HASH, HMOD) + 1 J = HEAD (HASH) IF (J .LE. 0) THEN C the degree list is empty, hash head is -j NEXT (I) = -J HEAD (HASH) = -I ELSE C degree list is not empty C use last (head (hash)) as hash head NEXT (I) = LAST (J) LAST (J) = I ENDIF LAST (I) = HASH ENDIF 180 CONTINUE DEGREE (ME) = DEGME C ------------------------------------------------------------- C Clear the counter array, w (...), by incrementing wflg. C ------------------------------------------------------------- DMAX = MAX (DMAX, DEGME) WFLG = WFLG + DMAX C make sure that wflg+n does not cause integer overflow IF (WFLG + N .LE. WFLG) THEN DO 190 X = 1, N IF (W (X) .NE. 0) W (X) = 1 190 CONTINUE WFLG = 2 ENDIF C at this point, w (1..n) .lt. wflg holds C======================================================================= C SUPERVARIABLE DETECTION C======================================================================= DO 250 PME = PME1, PME2 I = IW (PME) IF (NV (I) .LT. 0) THEN C i is a principal variable in Lme C ------------------------------------------------------- C examine all hash buckets with 2 or more variables. We C do this by examing all unique hash keys for super- C variables in the pattern Lme of the current element, me C ------------------------------------------------------- HASH = LAST (I) C let i = head of hash bucket, and empty the hash bucket J = HEAD (HASH) IF (J .EQ. 0) GOTO 250 IF (J .LT. 0) THEN C degree list is empty I = -J HEAD (HASH) = 0 ELSE C degree list is not empty, restore last () of head I = LAST (J) LAST (J) = 0 ENDIF IF (I .EQ. 0) GOTO 250 C while loop: 200 CONTINUE IF (NEXT (I) .NE. 0) THEN C ---------------------------------------------------- C this bucket has one or more variables following i. C scan all of them to see if i can absorb any entries C that follow i in hash bucket. Scatter i into w. C ---------------------------------------------------- LN = LEN (I) ELN = ELEN (I) C do not flag the first element in the list (me) DO 210 P = PE (I) + 1, PE (I) + LN - 1 W (IW (P)) = WFLG 210 CONTINUE C ---------------------------------------------------- C scan every other entry j following i in bucket C ---------------------------------------------------- JLAST = I J = NEXT (I) C while loop: 220 CONTINUE IF (J .NE. 0) THEN C ------------------------------------------------- C check if j and i have identical nonzero pattern C ------------------------------------------------- IF (LEN (J) .NE. LN) THEN C i and j do not have same size data structure GOTO 240 ENDIF IF (ELEN (J) .NE. ELN) THEN C i and j do not have same number of adjacent el GOTO 240 ENDIF C do not flag the first element in the list (me) DO 230 P = PE (J) + 1, PE (J) + LN - 1 IF (W (IW (P)) .NE. WFLG) THEN C an entry (iw(p)) is in j but not in i GOTO 240 ENDIF 230 CONTINUE C ------------------------------------------------- C found it! j can be absorbed into i C ------------------------------------------------- PE (J) = -I C both nv (i) and nv (j) are negated since they C are in Lme, and the absolute values of each C are the number of variables in i and j: NV (I) = NV (I) + NV (J) NV (J) = 0 ELEN (J) = 0 C delete j from hash bucket J = NEXT (J) NEXT (JLAST) = J GOTO 220 C ------------------------------------------------- 240 CONTINUE C j cannot be absorbed into i C ------------------------------------------------- JLAST = J J = NEXT (J) GOTO 220 ENDIF C ---------------------------------------------------- C no more variables can be absorbed into i C go to next i in bucket and clear flag array C ---------------------------------------------------- WFLG = WFLG + 1 I = NEXT (I) IF (I .NE. 0) GOTO 200 ENDIF ENDIF 250 CONTINUE C======================================================================= C RESTORE DEGREE LISTS AND REMOVE NONPRINCIPAL SUPERVAR. FROM ELEMENT C======================================================================= P = PME1 NLEFT = N - NEL DO 260 PME = PME1, PME2 I = IW (PME) NVI = -NV (I) IF (NVI .GT. 0) THEN C i is a principal variable in Lme C restore nv (i) to signify that i is principal NV (I) = NVI C ------------------------------------------------------- C compute the external degree (add size of current elem) C ------------------------------------------------------- DEG = MAX (1, MIN (DEGREE (I) + DEGME-NVI, NLEFT-NVI)) C ------------------------------------------------------- C place the supervariable at the head of the degree list C ------------------------------------------------------- INEXT = HEAD (DEG) IF (INEXT .NE. 0) LAST (INEXT) = I NEXT (I) = INEXT LAST (I) = 0 HEAD (DEG) = I C ------------------------------------------------------- C save the new degree, and find the minimum degree C ------------------------------------------------------- MINDEG = MIN (MINDEG, DEG) DEGREE (I) = DEG C ------------------------------------------------------- C place the supervariable in the element pattern C ------------------------------------------------------- IW (P) = I P = P + 1 ENDIF 260 CONTINUE C======================================================================= C FINALIZE THE NEW ELEMENT C======================================================================= NV (ME) = NVPIV + DEGME C nv (me) is now the degree of pivot (including diagonal part) C save the length of the list for the new element me LEN (ME) = P - PME1 IF (LEN (ME) .EQ. 0) THEN C there is nothing left of the current pivot element PE (ME) = 0 W (ME) = 0 ENDIF IF (NEWMEM .NE. 0) THEN C element was not constructed in place: deallocate part C of it (final size is less than or equal to newmem, C since newly nonprincipal variables have been removed). PFREE = P MEM = MEM - NEWMEM + LEN (ME) ENDIF C======================================================================= C END WHILE (selecting pivots) GOTO 30 ENDIF C======================================================================= C======================================================================= C COMPUTE THE PERMUTATION VECTORS C======================================================================= C ---------------------------------------------------------------- C The time taken by the following code is O(n). At this C point, elen (e) = -k has been done for all elements e, C and elen (i) = 0 has been done for all nonprincipal C variables i. At this point, there are no principal C supervariables left, and all elements are absorbed. C ---------------------------------------------------------------- C ---------------------------------------------------------------- C compute the ordering of unordered nonprincipal variables C ---------------------------------------------------------------- DO 290 I = 1, N IF (ELEN (I) .EQ. 0) THEN C ---------------------------------------------------------- C i is an un-ordered row. Traverse the tree from i until C reaching an element, e. The element, e, was the C principal supervariable of i and all nodes in the path C from i to when e was selected as pivot. C ---------------------------------------------------------- J = -PE (I) C while (j is a variable) do: 270 CONTINUE IF (ELEN (J) .GE. 0) THEN J = -PE (J) GOTO 270 ENDIF E = J C ---------------------------------------------------------- C get the current pivot ordering of e C ---------------------------------------------------------- K = -ELEN (E) C ---------------------------------------------------------- C traverse the path again from i to e, and compress the C path (all nodes point to e). Path compression allows C this code to compute in O(n) time. Order the unordered C nodes in the path, and place the element e at the end. C ---------------------------------------------------------- J = I C while (j is a variable) do: 280 CONTINUE IF (ELEN (J) .GE. 0) THEN JNEXT = -PE (J) PE (J) = -E IF (ELEN (J) .EQ. 0) THEN C j is an unordered row ELEN (J) = K K = K + 1 ENDIF J = JNEXT GOTO 280 ENDIF C leave elen (e) negative, so we know it is an element ELEN (E) = -K ENDIF 290 CONTINUE C ---------------------------------------------------------------- C reset the inverse permutation (elen (1..n)) to be positive, C and compute the permutation (last (1..n)). C ---------------------------------------------------------------- DO 300 I = 1, N K = ABS (ELEN (I)) LAST (K) = I ELEN (I) = K 300 CONTINUE C======================================================================= C RETURN THE MEMORY USAGE IN IW C======================================================================= C If maxmem is less than or equal to iwlen, then no compressions C occurred, and iw (maxmem+1 ... iwlen) was unused. Otherwise C compressions did occur, and iwlen would have had to have been C greater than or equal to maxmem for no compressions to occur. C Return the value of maxmem in the pfree argument. PFREE = MAXMEM RETURN END igraph/src/AMD/Source/amd.f0000644000175100001440000014662113431000472015106 0ustar hornikusersC----------------------------------------------------------------------- C AMD: approximate minimum degree, with aggressive absorption C----------------------------------------------------------------------- SUBROUTINE AMD $ (N, PE, IW, LEN, IWLEN, PFREE, NV, NEXT, $ LAST, HEAD, ELEN, DEGREE, NCMPA, W) INTEGER N, IWLEN, PFREE, NCMPA, IW (IWLEN), PE (N), $ DEGREE (N), NV (N), NEXT (N), LAST (N), HEAD (N), $ ELEN (N), W (N), LEN (N) C Given a representation of the nonzero pattern of a symmetric matrix, C A, (excluding the diagonal) perform an approximate minimum C (UMFPACK/MA38-style) degree ordering to compute a pivot order C such that the introduction of nonzeros (fill-in) in the Cholesky C factors A = LL^T are kept low. At each step, the pivot C selected is the one with the minimum UMFPACK/MA38-style C upper-bound on the external degree. C C Aggresive absorption is used to tighten the bound on the degree. C ********************************************************************** C ***** CAUTION: ARGUMENTS ARE NOT CHECKED FOR ERRORS ON INPUT. ****** C ********************************************************************** C References: C C [1] Timothy A. Davis and Iain Duff, "An unsymmetric-pattern C multifrontal method for sparse LU factorization", SIAM J. C Matrix Analysis and Applications, vol. 18, no. 1, pp. C 140-158. Discusses UMFPACK / MA38, which first introduced C the approximate minimum degree used by this routine. C C [2] Patrick Amestoy, Timothy A. Davis, and Iain S. Duff, "An C approximate degree ordering algorithm," SIAM J. Matrix C Analysis and Applications, vol. 17, no. 4, pp. 886-905, C 1996. Discusses AMD, AMDBAR, and MC47B. C C [3] Alan George and Joseph Liu, "The evolution of the minimum C degree ordering algorithm," SIAM Review, vol. 31, no. 1, C pp. 1-19, 1989. We list below the features mentioned in C that paper that this code includes: C C mass elimination: C Yes. MA27 relied on supervariable detection for mass C elimination. C indistinguishable nodes: C Yes (we call these "supervariables"). This was also in C the MA27 code - although we modified the method of C detecting them (the previous hash was the true degree, C which we no longer keep track of). A supervariable is C a set of rows with identical nonzero pattern. All C variables in a supervariable are eliminated together. C Each supervariable has as its numerical name that of C one of its variables (its principal variable). C quotient graph representation: C Yes. We use the term "element" for the cliques formed C during elimination. This was also in the MA27 code. C The algorithm can operate in place, but it will work C more efficiently if given some "elbow room." C element absorption: C Yes. This was also in the MA27 code. C external degree: C Yes. The MA27 code was based on the true degree. C incomplete degree update and multiple elimination: C No. This was not in MA27, either. Our method of C degree update within MC47B/BD is element-based, not C variable-based. It is thus not well-suited for use C with incomplete degree update or multiple elimination. C----------------------------------------------------------------------- C Authors, and Copyright (C) 1995 by: C Timothy A. Davis, Patrick Amestoy, Iain S. Duff, & John K. Reid. C C Acknowledgements: C This work (and the UMFPACK package) was supported by the C National Science Foundation (ASC-9111263 and DMS-9223088). C The UMFPACK/MA38 approximate degree update algorithm, the C unsymmetric analog which forms the basis of MC47B/BD, was C developed while Tim Davis was supported by CERFACS (Toulouse, C France) in a post-doctoral position. C C Date: September, 1995 C----------------------------------------------------------------------- C----------------------------------------------------------------------- C INPUT ARGUMENTS (unaltered): C----------------------------------------------------------------------- C n: The matrix order. C C Restriction: 1 .le. n .lt. (iovflo/2)-2, where iovflo is C the largest positive integer that your computer can represent. C iwlen: The length of iw (1..iwlen). On input, the matrix is C stored in iw (1..pfree-1). However, iw (1..iwlen) should be C slightly larger than what is required to hold the matrix, at C least iwlen .ge. pfree + n is recommended. Otherwise, C excessive compressions will take place. C *** We do not recommend running this algorithm with *** C *** iwlen .lt. pfree + n. *** C *** Better performance will be obtained if *** C *** iwlen .ge. pfree + n *** C *** or better yet *** C *** iwlen .gt. 1.2 * pfree *** C *** (where pfree is its value on input). *** C The algorithm will not run at all if iwlen .lt. pfree-1. C C Restriction: iwlen .ge. pfree-1 C----------------------------------------------------------------------- C INPUT/OUPUT ARGUMENTS: C----------------------------------------------------------------------- C pe: On input, pe (i) is the index in iw of the start of row i, or C zero if row i has no off-diagonal non-zeros. C C During execution, it is used for both supervariables and C elements: C C * Principal supervariable i: index into iw of the C description of supervariable i. A supervariable C represents one or more rows of the matrix C with identical nonzero pattern. C * Non-principal supervariable i: if i has been absorbed C into another supervariable j, then pe (i) = -j. C That is, j has the same pattern as i. C Note that j might later be absorbed into another C supervariable j2, in which case pe (i) is still -j, C and pe (j) = -j2. C * Unabsorbed element e: the index into iw of the description C of element e, if e has not yet been absorbed by a C subsequent element. Element e is created when C the supervariable of the same name is selected as C the pivot. C * Absorbed element e: if element e is absorbed into element C e2, then pe (e) = -e2. This occurs when the pattern of C e (that is, Le) is found to be a subset of the pattern C of e2 (that is, Le2). If element e is "null" (it has C no nonzeros outside its pivot block), then pe (e) = 0. C C On output, pe holds the assembly tree/forest, which implicitly C represents a pivot order with identical fill-in as the actual C order (via a depth-first search of the tree). C C On output: C If nv (i) .gt. 0, then i represents a node in the assembly tree, C and the parent of i is -pe (i), or zero if i is a root. C If nv (i) = 0, then (i,-pe (i)) represents an edge in a C subtree, the root of which is a node in the assembly tree. C pfree: On input the tail end of the array, iw (pfree..iwlen), C is empty, and the matrix is stored in iw (1..pfree-1). C During execution, additional data is placed in iw, and pfree C is modified so that iw (pfree..iwlen) is always the unused part C of iw. On output, pfree is set equal to the size of iw that C would have been needed for no compressions to occur. If C ncmpa is zero, then pfree (on output) is less than or equal to C iwlen, and the space iw (pfree+1 ... iwlen) was not used. C Otherwise, pfree (on output) is greater than iwlen, and all the C memory in iw was used. C----------------------------------------------------------------------- C INPUT/MODIFIED (undefined on output): C----------------------------------------------------------------------- C len: On input, len (i) holds the number of entries in row i of the C matrix, excluding the diagonal. The contents of len (1..n) C are undefined on output. C iw: On input, iw (1..pfree-1) holds the description of each row i C in the matrix. The matrix must be symmetric, and both upper C and lower triangular parts must be present. The diagonal must C not be present. Row i is held as follows: C C len (i): the length of the row i data structure C iw (pe (i) ... pe (i) + len (i) - 1): C the list of column indices for nonzeros C in row i (simple supervariables), excluding C the diagonal. All supervariables start with C one row/column each (supervariable i is just C row i). C if len (i) is zero on input, then pe (i) is ignored C on input. C C Note that the rows need not be in any particular order, C and there may be empty space between the rows. C C During execution, the supervariable i experiences fill-in. C This is represented by placing in i a list of the elements C that cause fill-in in supervariable i: C C len (i): the length of supervariable i C iw (pe (i) ... pe (i) + elen (i) - 1): C the list of elements that contain i. This list C is kept short by removing absorbed elements. C iw (pe (i) + elen (i) ... pe (i) + len (i) - 1): C the list of supervariables in i. This list C is kept short by removing nonprincipal C variables, and any entry j that is also C contained in at least one of the elements C (j in Le) in the list for i (e in row i). C C When supervariable i is selected as pivot, we create an C element e of the same name (e=i): C C len (e): the length of element e C iw (pe (e) ... pe (e) + len (e) - 1): C the list of supervariables in element e. C C An element represents the fill-in that occurs when supervariable C i is selected as pivot (which represents the selection of row i C and all non-principal variables whose principal variable is i). C We use the term Le to denote the set of all supervariables C in element e. Absorbed supervariables and elements are pruned C from these lists when computationally convenient. C C CAUTION: THE INPUT MATRIX IS OVERWRITTEN DURING COMPUTATION. C The contents of iw are undefined on output. C----------------------------------------------------------------------- C OUTPUT (need not be set on input): C----------------------------------------------------------------------- C nv: During execution, abs (nv (i)) is equal to the number of rows C that are represented by the principal supervariable i. If i is C a nonprincipal variable, then nv (i) = 0. Initially, C nv (i) = 1 for all i. nv (i) .lt. 0 signifies that i is a C principal variable in the pattern Lme of the current pivot C element me. On output, nv (e) holds the true degree of element C e at the time it was created (including the diagonal part). C ncmpa: The number of times iw was compressed. If this is C excessive, then the execution took longer than what could have C been. To reduce ncmpa, try increasing iwlen to be 10% or 20% C larger than the value of pfree on input (or at least C iwlen .ge. pfree + n). The fastest performance will be C obtained when ncmpa is returned as zero. If iwlen is set to C the value returned by pfree on *output*, then no compressions C will occur. C elen: See the description of iw above. At the start of execution, C elen (i) is set to zero. During execution, elen (i) is the C number of elements in the list for supervariable i. When e C becomes an element, elen (e) = -nel is set, where nel is the C current step of factorization. elen (i) = 0 is done when i C becomes nonprincipal. C C For variables, elen (i) .ge. 0 holds until just before the C permutation vectors are computed. For elements, C elen (e) .lt. 0 holds. C C On output elen (1..n) holds the inverse permutation (the same C as the 'INVP' argument in Sparspak). That is, if k = elen (i), C then row i is the kth pivot row. Row i of A appears as the C (elen(i))-th row in the permuted matrix, PAP^T. C last: In a degree list, last (i) is the supervariable preceding i, C or zero if i is the head of the list. In a hash bucket, C last (i) is the hash key for i. last (head (hash)) is also C used as the head of a hash bucket if head (hash) contains a C degree list (see head, below). C C On output, last (1..n) holds the permutation (the same as the C 'PERM' argument in Sparspak). That is, if i = last (k), then C row i is the kth pivot row. Row last (k) of A is the k-th row C in the permuted matrix, PAP^T. C----------------------------------------------------------------------- C LOCAL (not input or output - used only during execution): C----------------------------------------------------------------------- C degree: If i is a supervariable, then degree (i) holds the C current approximation of the external degree of row i (an upper C bound). The external degree is the number of nonzeros in row i, C minus abs (nv (i)) (the diagonal part). The bound is equal to C the external degree if elen (i) is less than or equal to two. C C We also use the term "external degree" for elements e to refer C to |Le \ Lme|. If e is an element, then degree (e) holds |Le|, C which is the degree of the off-diagonal part of the element e C (not including the diagonal part). C head: head is used for degree lists. head (deg) is the first C supervariable in a degree list (all supervariables i in a C degree list deg have the same approximate degree, namely, C deg = degree (i)). If the list deg is empty then C head (deg) = 0. C C During supervariable detection head (hash) also serves as a C pointer to a hash bucket. C If head (hash) .gt. 0, there is a degree list of degree hash. C The hash bucket head pointer is last (head (hash)). C If head (hash) = 0, then the degree list and hash bucket are C both empty. C If head (hash) .lt. 0, then the degree list is empty, and C -head (hash) is the head of the hash bucket. C After supervariable detection is complete, all hash buckets C are empty, and the (last (head (hash)) = 0) condition is C restored for the non-empty degree lists. C next: next (i) is the supervariable following i in a link list, or C zero if i is the last in the list. Used for two kinds of C lists: degree lists and hash buckets (a supervariable can be C in only one kind of list at a time). C w: The flag array w determines the status of elements and C variables, and the external degree of elements. C C for elements: C if w (e) = 0, then the element e is absorbed C if w (e) .ge. wflg, then w (e) - wflg is the size of C the set |Le \ Lme|, in terms of nonzeros (the C sum of abs (nv (i)) for each principal variable i that C is both in the pattern of element e and NOT in the C pattern of the current pivot element, me). C if wflg .gt. w (e) .gt. 0, then e is not absorbed and has C not yet been seen in the scan of the element lists in C the computation of |Le\Lme| in loop 150 below. C C for variables: C during supervariable detection, if w (j) .ne. wflg then j is C not in the pattern of variable i C C The w array is initialized by setting w (i) = 1 for all i, C and by setting wflg = 2. It is reinitialized if wflg becomes C too large (to ensure that wflg+n does not cause integer C overflow). C----------------------------------------------------------------------- C LOCAL INTEGERS: C----------------------------------------------------------------------- INTEGER DEG, DEGME, DEXT, DMAX, E, ELENME, ELN, HASH, HMOD, I, $ ILAST, INEXT, J, JLAST, JNEXT, K, KNT1, KNT2, KNT3, $ LENJ, LN, MAXMEM, ME, MEM, MINDEG, NEL, NEWMEM, $ NLEFT, NVI, NVJ, NVPIV, SLENME, WE, WFLG, WNVI, X C deg: the degree of a variable or element C degme: size, |Lme|, of the current element, me (= degree (me)) C dext: external degree, |Le \ Lme|, of some element e C dmax: largest |Le| seen so far C e: an element C elenme: the length, elen (me), of element list of pivotal var. C eln: the length, elen (...), of an element list C hash: the computed value of the hash function C hmod: the hash function is computed modulo hmod = max (1,n-1) C i: a supervariable C ilast: the entry in a link list preceding i C inext: the entry in a link list following i C j: a supervariable C jlast: the entry in a link list preceding j C jnext: the entry in a link list, or path, following j C k: the pivot order of an element or variable C knt1: loop counter used during element construction C knt2: loop counter used during element construction C knt3: loop counter used during compression C lenj: len (j) C ln: length of a supervariable list C maxmem: amount of memory needed for no compressions C me: current supervariable being eliminated, and the C current element created by eliminating that C supervariable C mem: memory in use assuming no compressions have occurred C mindeg: current minimum degree C nel: number of pivots selected so far C newmem: amount of new memory needed for current pivot element C nleft: n - nel, the number of nonpivotal rows/columns remaining C nvi: the number of variables in a supervariable i (= nv (i)) C nvj: the number of variables in a supervariable j (= nv (j)) C nvpiv: number of pivots in current element C slenme: number of variables in variable list of pivotal variable C we: w (e) C wflg: used for flagging the w array. See description of iw. C wnvi: wflg - nv (i) C x: either a supervariable or an element C----------------------------------------------------------------------- C LOCAL POINTERS: C----------------------------------------------------------------------- INTEGER P, P1, P2, P3, PDST, PEND, PJ, PME, PME1, PME2, PN, PSRC C Any parameter (pe (...) or pfree) or local variable C starting with "p" (for Pointer) is an index into iw, C and all indices into iw use variables starting with C "p." The only exception to this rule is the iwlen C input argument. C p: pointer into lots of things C p1: pe (i) for some variable i (start of element list) C p2: pe (i) + elen (i) - 1 for some var. i (end of el. list) C p3: index of first supervariable in clean list C pdst: destination pointer, for compression C pend: end of memory to compress C pj: pointer into an element or variable C pme: pointer into the current element (pme1...pme2) C pme1: the current element, me, is stored in iw (pme1...pme2) C pme2: the end of the current element C pn: pointer into a "clean" variable, also used to compress C psrc: source pointer, for compression C----------------------------------------------------------------------- C FUNCTIONS CALLED: C----------------------------------------------------------------------- INTRINSIC MAX, MIN, MOD C======================================================================= C INITIALIZATIONS C======================================================================= WFLG = 2 MINDEG = 1 NCMPA = 0 NEL = 0 HMOD = MAX (1, N-1) DMAX = 0 MEM = PFREE - 1 MAXMEM = MEM ME = 0 DO 10 I = 1, N LAST (I) = 0 HEAD (I) = 0 NV (I) = 1 W (I) = 1 ELEN (I) = 0 DEGREE (I) = LEN (I) 10 CONTINUE C ---------------------------------------------------------------- C initialize degree lists and eliminate rows with no off-diag. nz. C ---------------------------------------------------------------- DO 20 I = 1, N DEG = DEGREE (I) IF (DEG .GT. 0) THEN C ---------------------------------------------------------- C place i in the degree list corresponding to its degree C ---------------------------------------------------------- INEXT = HEAD (DEG) IF (INEXT .NE. 0) LAST (INEXT) = I NEXT (I) = INEXT HEAD (DEG) = I ELSE C ---------------------------------------------------------- C we have a variable that can be eliminated at once because C there is no off-diagonal non-zero in its row. C ---------------------------------------------------------- NEL = NEL + 1 ELEN (I) = -NEL PE (I) = 0 W (I) = 0 ENDIF 20 CONTINUE C======================================================================= C WHILE (selecting pivots) DO C======================================================================= 30 CONTINUE IF (NEL .LT. N) THEN C======================================================================= C GET PIVOT OF MINIMUM DEGREE C======================================================================= C ------------------------------------------------------------- C find next supervariable for elimination C ------------------------------------------------------------- DO 40 DEG = MINDEG, N ME = HEAD (DEG) IF (ME .GT. 0) GOTO 50 40 CONTINUE 50 CONTINUE MINDEG = DEG C ------------------------------------------------------------- C remove chosen variable from link list C ------------------------------------------------------------- INEXT = NEXT (ME) IF (INEXT .NE. 0) LAST (INEXT) = 0 HEAD (DEG) = INEXT C ------------------------------------------------------------- C me represents the elimination of pivots nel+1 to nel+nv(me). C place me itself as the first in this set. It will be moved C to the nel+nv(me) position when the permutation vectors are C computed. C ------------------------------------------------------------- ELENME = ELEN (ME) ELEN (ME) = - (NEL + 1) NVPIV = NV (ME) NEL = NEL + NVPIV C======================================================================= C CONSTRUCT NEW ELEMENT C======================================================================= C ------------------------------------------------------------- C At this point, me is the pivotal supervariable. It will be C converted into the current element. Scan list of the C pivotal supervariable, me, setting tree pointers and C constructing new list of supervariables for the new element, C me. p is a pointer to the current position in the old list. C ------------------------------------------------------------- C flag the variable "me" as being in Lme by negating nv (me) NV (ME) = -NVPIV DEGME = 0 IF (ELENME .EQ. 0) THEN C ---------------------------------------------------------- C construct the new element in place C ---------------------------------------------------------- PME1 = PE (ME) PME2 = PME1 - 1 DO 60 P = PME1, PME1 + LEN (ME) - 1 I = IW (P) NVI = NV (I) IF (NVI .GT. 0) THEN C ---------------------------------------------------- C i is a principal variable not yet placed in Lme. C store i in new list C ---------------------------------------------------- DEGME = DEGME + NVI C flag i as being in Lme by negating nv (i) NV (I) = -NVI PME2 = PME2 + 1 IW (PME2) = I C ---------------------------------------------------- C remove variable i from degree list. C ---------------------------------------------------- ILAST = LAST (I) INEXT = NEXT (I) IF (INEXT .NE. 0) LAST (INEXT) = ILAST IF (ILAST .NE. 0) THEN NEXT (ILAST) = INEXT ELSE C i is at the head of the degree list HEAD (DEGREE (I)) = INEXT ENDIF ENDIF 60 CONTINUE C this element takes no new memory in iw: NEWMEM = 0 ELSE C ---------------------------------------------------------- C construct the new element in empty space, iw (pfree ...) C ---------------------------------------------------------- P = PE (ME) PME1 = PFREE SLENME = LEN (ME) - ELENME DO 120 KNT1 = 1, ELENME + 1 IF (KNT1 .GT. ELENME) THEN C search the supervariables in me. E = ME PJ = P LN = SLENME ELSE C search the elements in me. E = IW (P) P = P + 1 PJ = PE (E) LN = LEN (E) ENDIF C ------------------------------------------------------- C search for different supervariables and add them to the C new list, compressing when necessary. this loop is C executed once for each element in the list and once for C all the supervariables in the list. C ------------------------------------------------------- DO 110 KNT2 = 1, LN I = IW (PJ) PJ = PJ + 1 NVI = NV (I) IF (NVI .GT. 0) THEN C ------------------------------------------------- C compress iw, if necessary C ------------------------------------------------- IF (PFREE .GT. IWLEN) THEN C prepare for compressing iw by adjusting C pointers and lengths so that the lists being C searched in the inner and outer loops contain C only the remaining entries. PE (ME) = P LEN (ME) = LEN (ME) - KNT1 IF (LEN (ME) .EQ. 0) THEN C nothing left of supervariable me PE (ME) = 0 ENDIF PE (E) = PJ LEN (E) = LN - KNT2 IF (LEN (E) .EQ. 0) THEN C nothing left of element e PE (E) = 0 ENDIF NCMPA = NCMPA + 1 C store first item in pe C set first entry to -item DO 70 J = 1, N PN = PE (J) IF (PN .GT. 0) THEN PE (J) = IW (PN) IW (PN) = -J ENDIF 70 CONTINUE C psrc/pdst point to source/destination PDST = 1 PSRC = 1 PEND = PME1 - 1 C while loop: 80 CONTINUE IF (PSRC .LE. PEND) THEN C search for next negative entry J = -IW (PSRC) PSRC = PSRC + 1 IF (J .GT. 0) THEN IW (PDST) = PE (J) PE (J) = PDST PDST = PDST + 1 C copy from source to destination LENJ = LEN (J) DO 90 KNT3 = 0, LENJ - 2 IW (PDST + KNT3) = IW (PSRC + KNT3) 90 CONTINUE PDST = PDST + LENJ - 1 PSRC = PSRC + LENJ - 1 ENDIF GOTO 80 ENDIF C move the new partially-constructed element P1 = PDST DO 100 PSRC = PME1, PFREE - 1 IW (PDST) = IW (PSRC) PDST = PDST + 1 100 CONTINUE PME1 = P1 PFREE = PDST PJ = PE (E) P = PE (ME) ENDIF C ------------------------------------------------- C i is a principal variable not yet placed in Lme C store i in new list C ------------------------------------------------- DEGME = DEGME + NVI C flag i as being in Lme by negating nv (i) NV (I) = -NVI IW (PFREE) = I PFREE = PFREE + 1 C ------------------------------------------------- C remove variable i from degree link list C ------------------------------------------------- ILAST = LAST (I) INEXT = NEXT (I) IF (INEXT .NE. 0) LAST (INEXT) = ILAST IF (ILAST .NE. 0) THEN NEXT (ILAST) = INEXT ELSE C i is at the head of the degree list HEAD (DEGREE (I)) = INEXT ENDIF ENDIF 110 CONTINUE IF (E .NE. ME) THEN C set tree pointer and flag to indicate element e is C absorbed into new element me (the parent of e is me) PE (E) = -ME W (E) = 0 ENDIF 120 CONTINUE PME2 = PFREE - 1 C this element takes newmem new memory in iw (possibly zero) NEWMEM = PFREE - PME1 MEM = MEM + NEWMEM MAXMEM = MAX (MAXMEM, MEM) ENDIF C ------------------------------------------------------------- C me has now been converted into an element in iw (pme1..pme2) C ------------------------------------------------------------- C degme holds the external degree of new element DEGREE (ME) = DEGME PE (ME) = PME1 LEN (ME) = PME2 - PME1 + 1 C ------------------------------------------------------------- C make sure that wflg is not too large. With the current C value of wflg, wflg+n must not cause integer overflow C ------------------------------------------------------------- IF (WFLG + N .LE. WFLG) THEN DO 130 X = 1, N IF (W (X) .NE. 0) W (X) = 1 130 CONTINUE WFLG = 2 ENDIF C======================================================================= C COMPUTE (w (e) - wflg) = |Le\Lme| FOR ALL ELEMENTS C======================================================================= C ------------------------------------------------------------- C Scan 1: compute the external degrees of previous elements C with respect to the current element. That is: C (w (e) - wflg) = |Le \ Lme| C for each element e that appears in any supervariable in Lme. C The notation Le refers to the pattern (list of C supervariables) of a previous element e, where e is not yet C absorbed, stored in iw (pe (e) + 1 ... pe (e) + iw (pe (e))). C The notation Lme refers to the pattern of the current element C (stored in iw (pme1..pme2)). If (w (e) - wflg) becomes C zero, then the element e will be absorbed in scan 2. C ------------------------------------------------------------- DO 150 PME = PME1, PME2 I = IW (PME) ELN = ELEN (I) IF (ELN .GT. 0) THEN C note that nv (i) has been negated to denote i in Lme: NVI = -NV (I) WNVI = WFLG - NVI DO 140 P = PE (I), PE (I) + ELN - 1 E = IW (P) WE = W (E) IF (WE .GE. WFLG) THEN C unabsorbed element e has been seen in this loop WE = WE - NVI ELSE IF (WE .NE. 0) THEN C e is an unabsorbed element C this is the first we have seen e in all of Scan 1 WE = DEGREE (E) + WNVI ENDIF W (E) = WE 140 CONTINUE ENDIF 150 CONTINUE C======================================================================= C DEGREE UPDATE AND ELEMENT ABSORPTION C======================================================================= C ------------------------------------------------------------- C Scan 2: for each i in Lme, sum up the degree of Lme (which C is degme), plus the sum of the external degrees of each Le C for the elements e appearing within i, plus the C supervariables in i. Place i in hash list. C ------------------------------------------------------------- DO 180 PME = PME1, PME2 I = IW (PME) P1 = PE (I) P2 = P1 + ELEN (I) - 1 PN = P1 HASH = 0 DEG = 0 C ---------------------------------------------------------- C scan the element list associated with supervariable i C ---------------------------------------------------------- DO 160 P = P1, P2 E = IW (P) C dext = | Le \ Lme | DEXT = W (E) - WFLG IF (DEXT .GT. 0) THEN DEG = DEG + DEXT IW (PN) = E PN = PN + 1 HASH = HASH + E ELSE IF (DEXT .EQ. 0) THEN C aggressive absorption: e is not adjacent to me, but C the |Le \ Lme| is 0, so absorb it into me PE (E) = -ME W (E) = 0 ELSE C element e has already been absorbed, due to C regular absorption, in do loop 120 above. Ignore it. CONTINUE ENDIF 160 CONTINUE C count the number of elements in i (including me): ELEN (I) = PN - P1 + 1 C ---------------------------------------------------------- C scan the supervariables in the list associated with i C ---------------------------------------------------------- P3 = PN DO 170 P = P2 + 1, P1 + LEN (I) - 1 J = IW (P) NVJ = NV (J) IF (NVJ .GT. 0) THEN C j is unabsorbed, and not in Lme. C add to degree and add to new list DEG = DEG + NVJ IW (PN) = J PN = PN + 1 HASH = HASH + J ENDIF 170 CONTINUE C ---------------------------------------------------------- C update the degree and check for mass elimination C ---------------------------------------------------------- IF (DEG .EQ. 0) THEN C ------------------------------------------------------- C mass elimination C ------------------------------------------------------- C There is nothing left of this node except for an C edge to the current pivot element. elen (i) is 1, C and there are no variables adjacent to node i. C Absorb i into the current pivot element, me. PE (I) = -ME NVI = -NV (I) DEGME = DEGME - NVI NVPIV = NVPIV + NVI NEL = NEL + NVI NV (I) = 0 ELEN (I) = 0 ELSE C ------------------------------------------------------- C update the upper-bound degree of i C ------------------------------------------------------- C the following degree does not yet include the size C of the current element, which is added later: DEGREE (I) = MIN (DEGREE (I), DEG) C ------------------------------------------------------- C add me to the list for i C ------------------------------------------------------- C move first supervariable to end of list IW (PN) = IW (P3) C move first element to end of element part of list IW (P3) = IW (P1) C add new element to front of list. IW (P1) = ME C store the new length of the list in len (i) LEN (I) = PN - P1 + 1 C ------------------------------------------------------- C place in hash bucket. Save hash key of i in last (i). C ------------------------------------------------------- HASH = MOD (HASH, HMOD) + 1 J = HEAD (HASH) IF (J .LE. 0) THEN C the degree list is empty, hash head is -j NEXT (I) = -J HEAD (HASH) = -I ELSE C degree list is not empty C use last (head (hash)) as hash head NEXT (I) = LAST (J) LAST (J) = I ENDIF LAST (I) = HASH ENDIF 180 CONTINUE DEGREE (ME) = DEGME C ------------------------------------------------------------- C Clear the counter array, w (...), by incrementing wflg. C ------------------------------------------------------------- DMAX = MAX (DMAX, DEGME) WFLG = WFLG + DMAX C make sure that wflg+n does not cause integer overflow IF (WFLG + N .LE. WFLG) THEN DO 190 X = 1, N IF (W (X) .NE. 0) W (X) = 1 190 CONTINUE WFLG = 2 ENDIF C at this point, w (1..n) .lt. wflg holds C======================================================================= C SUPERVARIABLE DETECTION C======================================================================= DO 250 PME = PME1, PME2 I = IW (PME) IF (NV (I) .LT. 0) THEN C i is a principal variable in Lme C ------------------------------------------------------- C examine all hash buckets with 2 or more variables. We C do this by examing all unique hash keys for super- C variables in the pattern Lme of the current element, me C ------------------------------------------------------- HASH = LAST (I) C let i = head of hash bucket, and empty the hash bucket J = HEAD (HASH) IF (J .EQ. 0) GOTO 250 IF (J .LT. 0) THEN C degree list is empty I = -J HEAD (HASH) = 0 ELSE C degree list is not empty, restore last () of head I = LAST (J) LAST (J) = 0 ENDIF IF (I .EQ. 0) GOTO 250 C while loop: 200 CONTINUE IF (NEXT (I) .NE. 0) THEN C ---------------------------------------------------- C this bucket has one or more variables following i. C scan all of them to see if i can absorb any entries C that follow i in hash bucket. Scatter i into w. C ---------------------------------------------------- LN = LEN (I) ELN = ELEN (I) C do not flag the first element in the list (me) DO 210 P = PE (I) + 1, PE (I) + LN - 1 W (IW (P)) = WFLG 210 CONTINUE C ---------------------------------------------------- C scan every other entry j following i in bucket C ---------------------------------------------------- JLAST = I J = NEXT (I) C while loop: 220 CONTINUE IF (J .NE. 0) THEN C ------------------------------------------------- C check if j and i have identical nonzero pattern C ------------------------------------------------- IF (LEN (J) .NE. LN) THEN C i and j do not have same size data structure GOTO 240 ENDIF IF (ELEN (J) .NE. ELN) THEN C i and j do not have same number of adjacent el GOTO 240 ENDIF C do not flag the first element in the list (me) DO 230 P = PE (J) + 1, PE (J) + LN - 1 IF (W (IW (P)) .NE. WFLG) THEN C an entry (iw(p)) is in j but not in i GOTO 240 ENDIF 230 CONTINUE C ------------------------------------------------- C found it! j can be absorbed into i C ------------------------------------------------- PE (J) = -I C both nv (i) and nv (j) are negated since they C are in Lme, and the absolute values of each C are the number of variables in i and j: NV (I) = NV (I) + NV (J) NV (J) = 0 ELEN (J) = 0 C delete j from hash bucket J = NEXT (J) NEXT (JLAST) = J GOTO 220 C ------------------------------------------------- 240 CONTINUE C j cannot be absorbed into i C ------------------------------------------------- JLAST = J J = NEXT (J) GOTO 220 ENDIF C ---------------------------------------------------- C no more variables can be absorbed into i C go to next i in bucket and clear flag array C ---------------------------------------------------- WFLG = WFLG + 1 I = NEXT (I) IF (I .NE. 0) GOTO 200 ENDIF ENDIF 250 CONTINUE C======================================================================= C RESTORE DEGREE LISTS AND REMOVE NONPRINCIPAL SUPERVAR. FROM ELEMENT C======================================================================= P = PME1 NLEFT = N - NEL DO 260 PME = PME1, PME2 I = IW (PME) NVI = -NV (I) IF (NVI .GT. 0) THEN C i is a principal variable in Lme C restore nv (i) to signify that i is principal NV (I) = NVI C ------------------------------------------------------- C compute the external degree (add size of current elem) C ------------------------------------------------------- DEG = MIN (DEGREE (I) + DEGME - NVI, NLEFT - NVI) C ------------------------------------------------------- C place the supervariable at the head of the degree list C ------------------------------------------------------- INEXT = HEAD (DEG) IF (INEXT .NE. 0) LAST (INEXT) = I NEXT (I) = INEXT LAST (I) = 0 HEAD (DEG) = I C ------------------------------------------------------- C save the new degree, and find the minimum degree C ------------------------------------------------------- MINDEG = MIN (MINDEG, DEG) DEGREE (I) = DEG C ------------------------------------------------------- C place the supervariable in the element pattern C ------------------------------------------------------- IW (P) = I P = P + 1 ENDIF 260 CONTINUE C======================================================================= C FINALIZE THE NEW ELEMENT C======================================================================= NV (ME) = NVPIV + DEGME C nv (me) is now the degree of pivot (including diagonal part) C save the length of the list for the new element me LEN (ME) = P - PME1 IF (LEN (ME) .EQ. 0) THEN C there is nothing left of the current pivot element PE (ME) = 0 W (ME) = 0 ENDIF IF (NEWMEM .NE. 0) THEN C element was not constructed in place: deallocate part C of it (final size is less than or equal to newmem, C since newly nonprincipal variables have been removed). PFREE = P MEM = MEM - NEWMEM + LEN (ME) ENDIF C======================================================================= C END WHILE (selecting pivots) GOTO 30 ENDIF C======================================================================= C======================================================================= C COMPUTE THE PERMUTATION VECTORS C======================================================================= C ---------------------------------------------------------------- C The time taken by the following code is O(n). At this C point, elen (e) = -k has been done for all elements e, C and elen (i) = 0 has been done for all nonprincipal C variables i. At this point, there are no principal C supervariables left, and all elements are absorbed. C ---------------------------------------------------------------- C ---------------------------------------------------------------- C compute the ordering of unordered nonprincipal variables C ---------------------------------------------------------------- DO 290 I = 1, N IF (ELEN (I) .EQ. 0) THEN C ---------------------------------------------------------- C i is an un-ordered row. Traverse the tree from i until C reaching an element, e. The element, e, was the C principal supervariable of i and all nodes in the path C from i to when e was selected as pivot. C ---------------------------------------------------------- J = -PE (I) C while (j is a variable) do: 270 CONTINUE IF (ELEN (J) .GE. 0) THEN J = -PE (J) GOTO 270 ENDIF E = J C ---------------------------------------------------------- C get the current pivot ordering of e C ---------------------------------------------------------- K = -ELEN (E) C ---------------------------------------------------------- C traverse the path again from i to e, and compress the C path (all nodes point to e). Path compression allows C this code to compute in O(n) time. Order the unordered C nodes in the path, and place the element e at the end. C ---------------------------------------------------------- J = I C while (j is a variable) do: 280 CONTINUE IF (ELEN (J) .GE. 0) THEN JNEXT = -PE (J) PE (J) = -E IF (ELEN (J) .EQ. 0) THEN C j is an unordered row ELEN (J) = K K = K + 1 ENDIF J = JNEXT GOTO 280 ENDIF C leave elen (e) negative, so we know it is an element ELEN (E) = -K ENDIF 290 CONTINUE C ---------------------------------------------------------------- C reset the inverse permutation (elen (1..n)) to be positive, C and compute the permutation (last (1..n)). C ---------------------------------------------------------------- DO 300 I = 1, N K = ABS (ELEN (I)) LAST (K) = I ELEN (I) = K 300 CONTINUE C======================================================================= C RETURN THE MEMORY USAGE IN IW C======================================================================= C If maxmem is less than or equal to iwlen, then no compressions C occurred, and iw (maxmem+1 ... iwlen) was unused. Otherwise C compressions did occur, and iwlen would have had to have been C greater than or equal to maxmem for no compressions to occur. C Return the value of maxmem in the pfree argument. PFREE = MAXMEM RETURN END igraph/src/AMD/Source/amd_global.c0000644000175100001440000000615513431000472016420 0ustar hornikusers/* ========================================================================= */ /* === amd_global ========================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ #include #ifdef MATLAB_MEX_FILE #include "mex.h" #include "matrix.h" #endif #ifndef NULL #define NULL 0 #endif /* ========================================================================= */ /* === Default AMD memory manager ========================================== */ /* ========================================================================= */ /* The user can redefine these global pointers at run-time to change the memory * manager used by AMD. AMD only uses malloc and free; realloc and calloc are * include for completeness, in case another package wants to use the same * memory manager as AMD. * * If compiling as a MATLAB mexFunction, the default memory manager is mxMalloc. * You can also compile AMD as a standard ANSI-C library and link a mexFunction * against it, and then redefine these pointers at run-time, in your * mexFunction. * * If -DNMALLOC is defined at compile-time, no memory manager is specified at * compile-time. You must then define these functions at run-time, before * calling AMD, for AMD to work properly. */ #ifndef NMALLOC #ifdef MATLAB_MEX_FILE /* MATLAB mexFunction: */ void *(*amd_malloc) (size_t) = mxMalloc ; void (*amd_free) (void *) = mxFree ; void *(*amd_realloc) (void *, size_t) = mxRealloc ; void *(*amd_calloc) (size_t, size_t) = mxCalloc ; #else /* standard ANSI-C: */ void *(*amd_malloc) (size_t) = malloc ; void (*amd_free) (void *) = free ; void *(*amd_realloc) (void *, size_t) = realloc ; void *(*amd_calloc) (size_t, size_t) = calloc ; #endif #else /* no memory manager defined at compile-time; you MUST define one at run-time */ void *(*amd_malloc) (size_t) = NULL ; void (*amd_free) (void *) = NULL ; void *(*amd_realloc) (void *, size_t) = NULL ; void *(*amd_calloc) (size_t, size_t) = NULL ; #endif /* ========================================================================= */ /* === Default AMD printf routine ========================================== */ /* ========================================================================= */ /* The user can redefine this global pointer at run-time to change the printf * routine used by AMD. If NULL, no printing occurs. * * If -DNPRINT is defined at compile-time, stdio.h is not included. Printing * can then be enabled at run-time by setting amd_printf to a non-NULL function. */ #ifndef NPRINT #ifdef MATLAB_MEX_FILE int (*amd_printf) (const char *, ...) = mexPrintf ; #else #include int (*amd_printf) (const char *, ...) = printf ; #endif #else int (*amd_printf) (const char *, ...) = NULL ; #endif igraph/src/AMD/Source/amd_1.c0000644000175100001440000001311613431000472015313 0ustar hornikusers/* ========================================================================= */ /* === AMD_1 =============================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* AMD_1: Construct A+A' for a sparse matrix A and perform the AMD ordering. * * The n-by-n sparse matrix A can be unsymmetric. It is stored in MATLAB-style * compressed-column form, with sorted row indices in each column, and no * duplicate entries. Diagonal entries may be present, but they are ignored. * Row indices of column j of A are stored in Ai [Ap [j] ... Ap [j+1]-1]. * Ap [0] must be zero, and nz = Ap [n] is the number of entries in A. The * size of the matrix, n, must be greater than or equal to zero. * * This routine must be preceded by a call to AMD_aat, which computes the * number of entries in each row/column in A+A', excluding the diagonal. * Len [j], on input, is the number of entries in row/column j of A+A'. This * routine constructs the matrix A+A' and then calls AMD_2. No error checking * is performed (this was done in AMD_valid). */ #include "amd_internal.h" GLOBAL void AMD_1 ( Int n, /* n > 0 */ const Int Ap [ ], /* input of size n+1, not modified */ const Int Ai [ ], /* input of size nz = Ap [n], not modified */ Int P [ ], /* size n output permutation */ Int Pinv [ ], /* size n output inverse permutation */ Int Len [ ], /* size n input, undefined on output */ Int slen, /* slen >= sum (Len [0..n-1]) + 7n, * ideally slen = 1.2 * sum (Len) + 8n */ Int S [ ], /* size slen workspace */ double Control [ ], /* input array of size AMD_CONTROL */ double Info [ ] /* output array of size AMD_INFO */ ) { Int i, j, k, p, pfree, iwlen, pj, p1, p2, pj2, *Iw, *Pe, *Nv, *Head, *Elen, *Degree, *s, *W, *Sp, *Tp ; /* --------------------------------------------------------------------- */ /* construct the matrix for AMD_2 */ /* --------------------------------------------------------------------- */ ASSERT (n > 0) ; iwlen = slen - 6*n ; s = S ; Pe = s ; s += n ; Nv = s ; s += n ; Head = s ; s += n ; Elen = s ; s += n ; Degree = s ; s += n ; W = s ; s += n ; Iw = s ; s += iwlen ; ASSERT (AMD_valid (n, n, Ap, Ai) == AMD_OK) ; /* construct the pointers for A+A' */ Sp = Nv ; /* use Nv and W as workspace for Sp and Tp [ */ Tp = W ; pfree = 0 ; for (j = 0 ; j < n ; j++) { Pe [j] = pfree ; Sp [j] = pfree ; pfree += Len [j] ; } /* Note that this restriction on iwlen is slightly more restrictive than * what is strictly required in AMD_2. AMD_2 can operate with no elbow * room at all, but it will be very slow. For better performance, at * least size-n elbow room is enforced. */ ASSERT (iwlen >= pfree + n) ; #ifndef NDEBUG for (p = 0 ; p < iwlen ; p++) Iw [p] = EMPTY ; #endif for (k = 0 ; k < n ; k++) { AMD_DEBUG1 (("Construct row/column k= "ID" of A+A'\n", k)) ; p1 = Ap [k] ; p2 = Ap [k+1] ; /* construct A+A' */ for (p = p1 ; p < p2 ; ) { /* scan the upper triangular part of A */ j = Ai [p] ; ASSERT (j >= 0 && j < n) ; if (j < k) { /* entry A (j,k) in the strictly upper triangular part */ ASSERT (Sp [j] < (j == n-1 ? pfree : Pe [j+1])) ; ASSERT (Sp [k] < (k == n-1 ? pfree : Pe [k+1])) ; Iw [Sp [j]++] = k ; Iw [Sp [k]++] = j ; p++ ; } else if (j == k) { /* skip the diagonal */ p++ ; break ; } else /* j > k */ { /* first entry below the diagonal */ break ; } /* scan lower triangular part of A, in column j until reaching * row k. Start where last scan left off. */ ASSERT (Ap [j] <= Tp [j] && Tp [j] <= Ap [j+1]) ; pj2 = Ap [j+1] ; for (pj = Tp [j] ; pj < pj2 ; ) { i = Ai [pj] ; ASSERT (i >= 0 && i < n) ; if (i < k) { /* A (i,j) is only in the lower part, not in upper */ ASSERT (Sp [i] < (i == n-1 ? pfree : Pe [i+1])) ; ASSERT (Sp [j] < (j == n-1 ? pfree : Pe [j+1])) ; Iw [Sp [i]++] = j ; Iw [Sp [j]++] = i ; pj++ ; } else if (i == k) { /* entry A (k,j) in lower part and A (j,k) in upper */ pj++ ; break ; } else /* i > k */ { /* consider this entry later, when k advances to i */ break ; } } Tp [j] = pj ; } Tp [k] = p ; } /* clean up, for remaining mismatched entries */ for (j = 0 ; j < n ; j++) { for (pj = Tp [j] ; pj < Ap [j+1] ; pj++) { i = Ai [pj] ; ASSERT (i >= 0 && i < n) ; /* A (i,j) is only in the lower part, not in upper */ ASSERT (Sp [i] < (i == n-1 ? pfree : Pe [i+1])) ; ASSERT (Sp [j] < (j == n-1 ? pfree : Pe [j+1])) ; Iw [Sp [i]++] = j ; Iw [Sp [j]++] = i ; } } #ifndef NDEBUG for (j = 0 ; j < n-1 ; j++) ASSERT (Sp [j] == Pe [j+1]) ; ASSERT (Sp [n-1] == pfree) ; #endif /* Tp and Sp no longer needed ] */ /* --------------------------------------------------------------------- */ /* order the matrix */ /* --------------------------------------------------------------------- */ AMD_2 (n, Pe, Iw, Len, iwlen, pfree, Nv, Pinv, P, Head, Elen, Degree, W, Control, Info) ; } igraph/src/AMD/Source/amd_dump.c0000644000175100001440000001162413431000472016122 0ustar hornikusers/* ========================================================================= */ /* === AMD_dump ============================================================ */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* Debugging routines for AMD. Not used if NDEBUG is not defined at compile- * time (the default). See comments in amd_internal.h on how to enable * debugging. Not user-callable. */ #include "amd_internal.h" #ifndef NDEBUG /* This global variable is present only when debugging */ GLOBAL Int AMD_debug = -999 ; /* default is no debug printing */ /* ========================================================================= */ /* === AMD_debug_init ====================================================== */ /* ========================================================================= */ /* Sets the debug print level, by reading the file debug.amd (if it exists) */ GLOBAL void AMD_debug_init ( char *s ) { FILE *f ; f = fopen ("debug.amd", "r") ; if (f == (FILE *) NULL) { AMD_debug = -999 ; } else { fscanf (f, ID, &AMD_debug) ; fclose (f) ; } if (AMD_debug >= 0) { printf ("%s: AMD_debug_init, D= "ID"\n", s, AMD_debug) ; } } /* ========================================================================= */ /* === AMD_dump ============================================================ */ /* ========================================================================= */ /* Dump AMD's data structure, except for the hash buckets. This routine * cannot be called when the hash buckets are non-empty. */ GLOBAL void AMD_dump ( Int n, /* A is n-by-n */ Int Pe [ ], /* pe [0..n-1]: index in iw of start of row i */ Int Iw [ ], /* workspace of size iwlen, iwlen [0..pfree-1] * holds the matrix on input */ Int Len [ ], /* len [0..n-1]: length for row i */ Int iwlen, /* length of iw */ Int pfree, /* iw [pfree ... iwlen-1] is empty on input */ Int Nv [ ], /* nv [0..n-1] */ Int Next [ ], /* next [0..n-1] */ Int Last [ ], /* last [0..n-1] */ Int Head [ ], /* head [0..n-1] */ Int Elen [ ], /* size n */ Int Degree [ ], /* size n */ Int W [ ], /* size n */ Int nel ) { Int i, pe, elen, nv, len, e, p, k, j, deg, w, cnt, ilast ; if (AMD_debug < 0) return ; ASSERT (pfree <= iwlen) ; AMD_DEBUG3 (("\nAMD dump, pfree: "ID"\n", pfree)) ; for (i = 0 ; i < n ; i++) { pe = Pe [i] ; elen = Elen [i] ; nv = Nv [i] ; len = Len [i] ; w = W [i] ; if (elen >= EMPTY) { if (nv == 0) { AMD_DEBUG3 (("\nI "ID": nonprincipal: ", i)) ; ASSERT (elen == EMPTY) ; if (pe == EMPTY) { AMD_DEBUG3 ((" dense node\n")) ; ASSERT (w == 1) ; } else { ASSERT (pe < EMPTY) ; AMD_DEBUG3 ((" i "ID" -> parent "ID"\n", i, FLIP (Pe[i]))); } } else { AMD_DEBUG3 (("\nI "ID": active principal supervariable:\n",i)); AMD_DEBUG3 ((" nv(i): "ID" Flag: %d\n", nv, (nv < 0))) ; ASSERT (elen >= 0) ; ASSERT (nv > 0 && pe >= 0) ; p = pe ; AMD_DEBUG3 ((" e/s: ")) ; if (elen == 0) AMD_DEBUG3 ((" : ")) ; ASSERT (pe + len <= pfree) ; for (k = 0 ; k < len ; k++) { j = Iw [p] ; AMD_DEBUG3 ((" "ID"", j)) ; ASSERT (j >= 0 && j < n) ; if (k == elen-1) AMD_DEBUG3 ((" : ")) ; p++ ; } AMD_DEBUG3 (("\n")) ; } } else { e = i ; if (w == 0) { AMD_DEBUG3 (("\nE "ID": absorbed element: w "ID"\n", e, w)) ; ASSERT (nv > 0 && pe < 0) ; AMD_DEBUG3 ((" e "ID" -> parent "ID"\n", e, FLIP (Pe [e]))) ; } else { AMD_DEBUG3 (("\nE "ID": unabsorbed element: w "ID"\n", e, w)) ; ASSERT (nv > 0 && pe >= 0) ; p = pe ; AMD_DEBUG3 ((" : ")) ; ASSERT (pe + len <= pfree) ; for (k = 0 ; k < len ; k++) { j = Iw [p] ; AMD_DEBUG3 ((" "ID"", j)) ; ASSERT (j >= 0 && j < n) ; p++ ; } AMD_DEBUG3 (("\n")) ; } } } /* this routine cannot be called when the hash buckets are non-empty */ AMD_DEBUG3 (("\nDegree lists:\n")) ; if (nel >= 0) { cnt = 0 ; for (deg = 0 ; deg < n ; deg++) { if (Head [deg] == EMPTY) continue ; ilast = EMPTY ; AMD_DEBUG3 ((ID": \n", deg)) ; for (i = Head [deg] ; i != EMPTY ; i = Next [i]) { AMD_DEBUG3 ((" "ID" : next "ID" last "ID" deg "ID"\n", i, Next [i], Last [i], Degree [i])) ; ASSERT (i >= 0 && i < n && ilast == Last [i] && deg == Degree [i]) ; cnt += Nv [i] ; ilast = i ; } AMD_DEBUG3 (("\n")) ; } ASSERT (cnt == n - nel) ; } } #endif igraph/src/AMD/Source/amd_defaults.c0000644000175100001440000000234513431000472016764 0ustar hornikusers/* ========================================================================= */ /* === AMD_defaults ======================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* User-callable. Sets default control parameters for AMD. See amd.h * for details. */ #include "amd_internal.h" /* ========================================================================= */ /* === AMD defaults ======================================================== */ /* ========================================================================= */ GLOBAL void AMD_defaults ( double Control [ ] ) { Int i ; if (Control != (double *) NULL) { for (i = 0 ; i < AMD_CONTROL ; i++) { Control [i] = 0 ; } Control [AMD_DENSE] = AMD_DEFAULT_DENSE ; Control [AMD_AGGRESSIVE] = AMD_DEFAULT_AGGRESSIVE ; } } igraph/src/AMD/Source/amd_post_tree.c0000644000175100001440000000716713431000472017170 0ustar hornikusers/* ========================================================================= */ /* === AMD_post_tree ======================================================= */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* Post-ordering of a supernodal elimination tree. */ #include "amd_internal.h" GLOBAL Int AMD_post_tree ( Int root, /* root of the tree */ Int k, /* start numbering at k */ Int Child [ ], /* input argument of size nn, undefined on * output. Child [i] is the head of a link * list of all nodes that are children of node * i in the tree. */ const Int Sibling [ ], /* input argument of size nn, not modified. * If f is a node in the link list of the * children of node i, then Sibling [f] is the * next child of node i. */ Int Order [ ], /* output order, of size nn. Order [i] = k * if node i is the kth node of the reordered * tree. */ Int Stack [ ] /* workspace of size nn */ #ifndef NDEBUG , Int nn /* nodes are in the range 0..nn-1. */ #endif ) { Int f, head, h, i ; #if 0 /* --------------------------------------------------------------------- */ /* recursive version (Stack [ ] is not used): */ /* --------------------------------------------------------------------- */ /* this is simple, but can caouse stack overflow if nn is large */ i = root ; for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { k = AMD_post_tree (f, k, Child, Sibling, Order, Stack, nn) ; } Order [i] = k++ ; return (k) ; #endif /* --------------------------------------------------------------------- */ /* non-recursive version, using an explicit stack */ /* --------------------------------------------------------------------- */ /* push root on the stack */ head = 0 ; Stack [0] = root ; while (head >= 0) { /* get head of stack */ ASSERT (head < nn) ; i = Stack [head] ; AMD_DEBUG1 (("head of stack "ID" \n", i)) ; ASSERT (i >= 0 && i < nn) ; if (Child [i] != EMPTY) { /* the children of i are not yet ordered */ /* push each child onto the stack in reverse order */ /* so that small ones at the head of the list get popped first */ /* and the biggest one at the end of the list gets popped last */ for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { head++ ; ASSERT (head < nn) ; ASSERT (f >= 0 && f < nn) ; } h = head ; ASSERT (head < nn) ; for (f = Child [i] ; f != EMPTY ; f = Sibling [f]) { ASSERT (h > 0) ; Stack [h--] = f ; AMD_DEBUG1 (("push "ID" on stack\n", f)) ; ASSERT (f >= 0 && f < nn) ; } ASSERT (Stack [h] == i) ; /* delete child list so that i gets ordered next time we see it */ Child [i] = EMPTY ; } else { /* the children of i (if there were any) are already ordered */ /* remove i from the stack and order it. Front i is kth front */ head-- ; AMD_DEBUG1 (("pop "ID" order "ID"\n", i, k)) ; Order [i] = k++ ; ASSERT (k <= nn) ; } #ifndef NDEBUG AMD_DEBUG1 (("\nStack:")) ; for (h = head ; h >= 0 ; h--) { Int j = Stack [h] ; AMD_DEBUG1 ((" "ID, j)) ; ASSERT (j >= 0 && j < nn) ; } AMD_DEBUG1 (("\n\n")) ; ASSERT (head < nn) ; #endif } return (k) ; } igraph/src/AMD/Source/amd_preprocess.c0000644000175100001440000000734013431000472017342 0ustar hornikusers/* ========================================================================= */ /* === AMD_preprocess ====================================================== */ /* ========================================================================= */ /* ------------------------------------------------------------------------- */ /* AMD, Copyright (c) Timothy A. Davis, */ /* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ /* email: DrTimothyAldenDavis@gmail.com */ /* ------------------------------------------------------------------------- */ /* Sorts, removes duplicate entries, and transposes from the nonzero pattern of * a column-form matrix A, to obtain the matrix R. The input matrix can have * duplicate entries and/or unsorted columns (AMD_valid (n,Ap,Ai) must not be * AMD_INVALID). * * This input condition is NOT checked. This routine is not user-callable. */ #include "amd_internal.h" /* ========================================================================= */ /* === AMD_preprocess ====================================================== */ /* ========================================================================= */ /* AMD_preprocess does not check its input for errors or allocate workspace. * On input, the condition (AMD_valid (n,n,Ap,Ai) != AMD_INVALID) must hold. */ GLOBAL void AMD_preprocess ( Int n, /* input matrix: A is n-by-n */ const Int Ap [ ], /* size n+1 */ const Int Ai [ ], /* size nz = Ap [n] */ /* output matrix R: */ Int Rp [ ], /* size n+1 */ Int Ri [ ], /* size nz (or less, if duplicates present) */ Int W [ ], /* workspace of size n */ Int Flag [ ] /* workspace of size n */ ) { /* --------------------------------------------------------------------- */ /* local variables */ /* --------------------------------------------------------------------- */ Int i, j, p, p2 ; ASSERT (AMD_valid (n, n, Ap, Ai) != AMD_INVALID) ; /* --------------------------------------------------------------------- */ /* count the entries in each row of A (excluding duplicates) */ /* --------------------------------------------------------------------- */ for (i = 0 ; i < n ; i++) { W [i] = 0 ; /* # of nonzeros in row i (excl duplicates) */ Flag [i] = EMPTY ; /* Flag [i] = j if i appears in column j */ } for (j = 0 ; j < n ; j++) { p2 = Ap [j+1] ; for (p = Ap [j] ; p < p2 ; p++) { i = Ai [p] ; if (Flag [i] != j) { /* row index i has not yet appeared in column j */ W [i]++ ; /* one more entry in row i */ Flag [i] = j ; /* flag row index i as appearing in col j*/ } } } /* --------------------------------------------------------------------- */ /* compute the row pointers for R */ /* --------------------------------------------------------------------- */ Rp [0] = 0 ; for (i = 0 ; i < n ; i++) { Rp [i+1] = Rp [i] + W [i] ; } for (i = 0 ; i < n ; i++) { W [i] = Rp [i] ; Flag [i] = EMPTY ; } /* --------------------------------------------------------------------- */ /* construct the row form matrix R */ /* --------------------------------------------------------------------- */ /* R = row form of pattern of A */ for (j = 0 ; j < n ; j++) { p2 = Ap [j+1] ; for (p = Ap [j] ; p < p2 ; p++) { i = Ai [p] ; if (Flag [i] != j) { /* row index i has not yet appeared in column j */ Ri [W [i]++] = j ; /* put col j in row i */ Flag [i] = j ; /* flag row index i as appearing in col j*/ } } } #ifndef NDEBUG ASSERT (AMD_valid (n, n, Rp, Ri) == AMD_OK) ; for (j = 0 ; j < n ; j++) { ASSERT (W [j] == Rp [j+1]) ; } #endif } igraph/src/hrg_rbtree.h0000644000175100001440000001346713431000472014632 0ustar hornikusers/* -*- mode: C++ -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // **************************************************************************************************** // *** COPYRIGHT NOTICE ******************************************************************************* // rbtree - red-black tree (self-balancing binary tree data structure) // Copyright (C) 2004 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // **************************************************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science AND Santa Fe Institute // Created : Spring 2004 // Modified : many, many times // // **************************************************************************************************** #ifndef IGRAPH_HRG_RBTREE #define IGRAPH_HRG_RBTREE #include using namespace std; namespace fitHRG { // ******** Basic Structures ********************************************* #ifndef IGRAPH_HRG_LIST #define IGRAPH_HRG_LIST class list { public: int x; // stored elementd in linked-list list* next; // pointer to next elementd list(): x(-1), next(0) { } ~list() { } }; #endif class keyValuePair { public: int x; // elementrb key (int) int y; // stored value (int) keyValuePair* next; // linked-list pointer keyValuePair(): x(-1), y(-1), next(0) { } ~keyValuePair() { } }; // ******** Tree elementrb Class ***************************************** class elementrb { public: int key; // search key (int) int value; // stored value (int) bool color; // F: BLACK, T: RED short int mark; // marker elementrb *parent; // pointer to parent node elementrb *left; // pointer for left subtree elementrb *right; // pointer for right subtree elementrb(): key(-1), value(-1), color(false), mark(0), parent(0), left(0), right(0) { } ~elementrb() { } }; // ******** Red-Black Tree Class ***************************************** // This vector implementation is a red-black balanced binary tree data // structure. It provides find a stored elementrb in time O(log n), // find the maximum elementrb in time O(1), delete an elementrb in // time O(log n), and insert an elementrb in time O(log n). // // Note that the key=0 is assumed to be a special value, and thus you // cannot insert such an item. Beware of this limitation. class rbtree { private: elementrb* root; // binary tree root elementrb* leaf; // all leaf nodes int support; // number of nodes in the tree void rotateLeft(elementrb *x); // left-rotation operator void rotateRight(elementrb *y); // right-rotation operator void insertCleanup(elementrb *z); // house-keeping after insertion void deleteCleanup(elementrb *x); // house-keeping after deletion keyValuePair* returnSubtreeAsList(elementrb *z, keyValuePair *head); void deleteSubTree(elementrb *z); // delete subtree rooted at z elementrb* returnMinKey(elementrb *z); // returns minimum of subtree // rooted at z elementrb* returnSuccessor(elementrb *z); // returns successor of z's key public: rbtree(); ~rbtree(); // default constructor/destructor // returns value associated with searchKey int returnValue(const int searchKey); // returns T if searchKey found, and points foundNode at the // corresponding node elementrb* findItem(const int searchKey); // insert a new key with stored value void insertItem(int newKey, int newValue); // selete a node with given key void deleteItem(int killKey); // replace value of a node with given key void replaceItem(int key, int newValue); // increment the value of the given key void incrementValue(int key); // delete the entire tree void deleteTree(); // return array of keys in tree int* returnArrayOfKeys(); // return list of keys in tree list* returnListOfKeys(); // return the tree as a list of keyValuePairs keyValuePair* returnTreeAsList(); // returns the maximum key in the tree keyValuePair returnMaxKey(); // returns the minimum key in the tree keyValuePair returnMinKey(); // returns number of items in tree int returnNodecount(); }; } #endif igraph/src/foreign-dl-parser.y0000644000175100001440000002240213430770201016040 0ustar hornikusers/* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "igraph_hacks_internal.h" #include "igraph_math.h" #include "igraph_types_internal.h" #include "foreign-dl-header.h" #include "foreign-dl-parser.h" #include #define yyscan_t void* int igraph_dl_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_dl_yyerror(YYLTYPE* locp, igraph_i_dl_parsedata_t* context, const char *s); char *igraph_dl_yyget_text (yyscan_t yyscanner ); int igraph_dl_yyget_leng (yyscan_t yyscanner ); int igraph_i_dl_add_str(char *newstr, int length, igraph_i_dl_parsedata_t *context); int igraph_i_dl_add_edge(long int from, long int to, igraph_i_dl_parsedata_t *context); int igraph_i_dl_add_edge_w(long int from, long int to, igraph_real_t weight, igraph_i_dl_parsedata_t *context); extern igraph_real_t igraph_pajek_get_number(const char *str, long int len); #define scanner context->scanner %} %pure-parser %output="y.tab.c" %name-prefix="igraph_dl_yy" %defines %locations %error-verbose %parse-param { igraph_i_dl_parsedata_t* context } %lex-param { void* scanner } %union { long int integer; igraph_real_t real; }; %type integer elabel; %type weight; %token NUM %token NEWLINE %token DL %token NEQ %token DATA %token LABELS %token LABELSEMBEDDED %token FORMATFULLMATRIX %token FORMATEDGELIST1 %token FORMATNODELIST1 %token DIGIT %token LABEL %token EOFF %token ERROR %% input: DL NEQ integer NEWLINE rest trail eof { context->n=$3; }; trail: | trail newline; eof: | EOFF; rest: formfullmatrix { context->type=IGRAPH_DL_MATRIX; } | edgelist1 { context->type=IGRAPH_DL_EDGELIST1; } | nodelist1 { context->type=IGRAPH_DL_NODELIST1; } ; formfullmatrix: FORMATFULLMATRIX newline fullmatrix {} | fullmatrix {} ; newline: | NEWLINE ; fullmatrix: DATA newline fullmatrixdata { } | LABELS newline labels newline DATA newline fullmatrixdata { } | LABELSEMBEDDED newline DATA newline labeledfullmatrixdata { } ; labels: {} /* nothing, empty matrix */ | labels newline LABEL { igraph_i_dl_add_str(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), context); } ; fullmatrixdata: {} | fullmatrixdata zerooneseq NEWLINE { context->from += 1; context->to = 0; } ; zerooneseq: | zerooneseq zeroone { } ; zeroone: DIGIT { if (igraph_dl_yyget_text(scanner)[0]=='1') { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->to)); } context->to += 1; } ; labeledfullmatrixdata: reallabeledfullmatrixdata {} ; reallabeledfullmatrixdata: labelseq NEWLINE labeledmatrixlines {} ; labelseq: | labelseq newline label ; label: LABEL { igraph_i_dl_add_str(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), context); }; labeledmatrixlines: labeledmatrixline { context->from += 1; context->to = 0; } | labeledmatrixlines labeledmatrixline { context->from += 1; context->to = 0; }; labeledmatrixline: LABEL zerooneseq NEWLINE { } ; /*-----------------------------------------------------------*/ edgelist1: FORMATEDGELIST1 newline edgelist1rest {} ; edgelist1rest: DATA newline edgelist1data {} | LABELS newline labels newline DATA newline edgelist1data {} | LABELSEMBEDDED newline DATA newline labelededgelist1data {} | LABELS newline labels newline LABELSEMBEDDED newline DATA newline labelededgelist1data {} | LABELSEMBEDDED newline LABELS newline labels newline DATA newline labelededgelist1data {} ; edgelist1data: {} /* nothing, empty graph */ | edgelist1data edgelist1dataline {} ; edgelist1dataline: integer integer weight NEWLINE { igraph_i_dl_add_edge_w($1-1, $2-1, $3, context); } | integer integer NEWLINE { igraph_i_dl_add_edge($1-1, $2-1, context); } ; integer: NUM { $$=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); }; labelededgelist1data: {} /* nothing, empty graph */ | labelededgelist1data labelededgelist1dataline {} ; labelededgelist1dataline: elabel elabel weight NEWLINE { igraph_i_dl_add_edge_w($1, $2, $3, context); } | elabel elabel NEWLINE { igraph_i_dl_add_edge($1, $2, context); }; weight: NUM { $$=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); }; elabel: LABEL { /* Copy label list to trie, if needed */ if (igraph_strvector_size(&context->labels) != 0) { long int i, id, n=igraph_strvector_size(&context->labels); for (i=0; itrie, STR(context->labels, i), &id); } igraph_strvector_clear(&context->labels); } igraph_trie_get2(&context->trie, igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner), &$$); }; /*-----------------------------------------------------------*/ nodelist1: FORMATNODELIST1 newline nodelist1rest {} ; nodelist1rest: DATA nodelist1data {} | LABELS newline labels newline DATA newline nodelist1data {} | LABELSEMBEDDED newline DATA newline labelednodelist1data {} | LABELS newline labels newline LABELSEMBEDDED newline DATA newline labelednodelist1data {} | LABELSEMBEDDED newline LABELS newline labels newline DATA newline labelednodelist1data {} ; nodelist1data: {} /* nothing, empty graph */ | nodelist1data nodelist1dataline {} ; nodelist1dataline: from tolist NEWLINE {} ; from: NUM { context->from=igraph_pajek_get_number(igraph_dl_yyget_text(scanner), igraph_dl_yyget_leng(scanner)); } ; tolist: {} | tolist integer { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from-1)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, $2-1)); } ; labelednodelist1data: {} /* nothing, empty graph */ | labelednodelist1data labelednodelist1dataline {} ; labelednodelist1dataline: fromelabel labeltolist NEWLINE { } ; fromelabel: elabel { context->from=$1; }; labeltolist: | labeltolist elabel { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, context->from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, $2)); } ; %% int igraph_dl_yyerror(YYLTYPE* locp, igraph_i_dl_parsedata_t* context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "%s in line %i", s, locp->first_line); return 0; } int igraph_i_dl_add_str(char *newstr, int length, igraph_i_dl_parsedata_t *context) { int tmp=newstr[length]; newstr[length]='\0'; IGRAPH_CHECK(igraph_strvector_add(&context->labels, newstr)); newstr[length]=tmp; return 0; } int igraph_i_dl_add_edge(long int from, long int to, igraph_i_dl_parsedata_t *context) { IGRAPH_CHECK(igraph_vector_push_back(&context->edges, from)); IGRAPH_CHECK(igraph_vector_push_back(&context->edges, to)); return 0; } int igraph_i_dl_add_edge_w(long int from, long int to, igraph_real_t weight, igraph_i_dl_parsedata_t *context) { long int n=igraph_vector_size(&context->weights); long int n2=igraph_vector_size(&context->edges)/2; if (n != n2) { igraph_vector_resize(&context->weights, n2); for (; nweights)[n]=IGRAPH_NAN; } } IGRAPH_CHECK(igraph_i_dl_add_edge(from, to, context)); IGRAPH_CHECK(igraph_vector_push_back(&context->weights, weight)); return 0; } igraph/src/infomap_Greedy.cc0000644000175100001440000004516513431000472015575 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "infomap_Greedy.h" #include #define plogp( x ) ( (x) > 0.0 ? (x)*log(x) : 0.0 ) Greedy::Greedy(FlowGraph * fgraph){ graph = fgraph; Nnode = graph->Nnode; alpha = graph->alpha;// teleportation probability beta = 1.0 - alpha; // probability to take normal step Nempty = 0; vector(Nnode).swap(mod_empty); vector(Nnode).swap(node_index); vector(Nnode).swap(mod_exit); vector(Nnode).swap(mod_size); vector(Nnode).swap(mod_danglingSize); vector(Nnode).swap(mod_teleportWeight); vector(Nnode).swap(mod_members); nodeSize_log_nodeSize = graph->nodeSize_log_nodeSize; exit_log_exit = graph->exit_log_exit; size_log_size = graph->size_log_size; exitFlow = graph->exitFlow; Node ** node = graph->node; for (int i=0; iexit; mod_size[i] = node[i]->size; mod_danglingSize[i] = node[i]->danglingSize; mod_teleportWeight[i] = node[i]->teleportWeight; mod_members[i] = node[i]->members.size(); } exit = plogp(exitFlow); codeLength = exit - 2.0*exit_log_exit + size_log_size - nodeSize_log_nodeSize; } Greedy::~Greedy() { } void delete_Greedy(Greedy *greedy) { delete greedy; } /** Greedy optimizing (as in Blodel and Al.) : * for each vertex (selected in a random order) compute the best possible move within neighborhood */ bool Greedy::optimize() { bool moved = false; Node ** node = graph->node; RNG_BEGIN(); // Generate random enumeration of nodes vector randomOrder(Nnode); for (int i=0; i redirect(Nnode,0); vector > > flowNtoM(Nnode); for (int k=0; k INT_MAX) { for (int j=0;joutLinks.size(); if (NoutLinks == 0) { //dangling node, add node to calculate flow below redirect[oldM] = offset + NmodLinks; flowNtoM[NmodLinks].first = oldM; flowNtoM[NmodLinks].second.first = 0.0; flowNtoM[NmodLinks].second.second = 0.0; NmodLinks++; } else { for (int j=0; joutLinks[j].first]; // index destination du lien double nb_flow = node[flip]->outLinks[j].second; // wgt du lien if (redirect[nb_M] >= offset) { flowNtoM[redirect[nb_M] - offset].second.first += nb_flow; } else { redirect[nb_M] = offset + NmodLinks; flowNtoM[NmodLinks].first = nb_M; flowNtoM[NmodLinks].second.first = nb_flow; flowNtoM[NmodLinks].second.second = 0.0; NmodLinks++; } } } // For all inLinks int NinLinks = node[flip]->inLinks.size(); for (int j=0; jinLinks[j].first]; double nb_flow = node[flip]->inLinks[j].second; if (redirect[nb_M] >= offset) { flowNtoM[redirect[nb_M] - offset].second.second += nb_flow; } else{ redirect[nb_M] = offset + NmodLinks; flowNtoM[NmodLinks].first = nb_M; flowNtoM[NmodLinks].second.first = 0.0; flowNtoM[NmodLinks].second.second = nb_flow; NmodLinks++; } } // For teleportation and dangling nodes for (int j=0;jsize + beta*node[flip]->danglingSize)* (mod_teleportWeight[oldM]-node[flip]->teleportWeight); flowNtoM[j].second.second += (alpha*(mod_size[oldM] - node[flip]->size) + beta*(mod_danglingSize[oldM] - node[flip]->danglingSize)) * node[flip]->teleportWeight; } else { flowNtoM[j].second.first += (alpha*node[flip]->size + beta*node[flip]->danglingSize) * mod_teleportWeight[newM]; flowNtoM[j].second.second += (alpha*mod_size[newM] + beta*mod_danglingSize[newM] ) * node[flip]->teleportWeight; } } // Calculate flow to/from own module (default value if no link to // own module) double outFlowOldM = (alpha*node[flip]->size + beta*node[flip]->danglingSize) * (mod_teleportWeight[oldM] - node[flip]->teleportWeight) ; double inFlowOldM = (alpha*(mod_size[oldM] - node[flip]->size) + beta*(mod_danglingSize[oldM] - node[flip]->danglingSize)) * node[flip]->teleportWeight; if (redirect[oldM] >= offset) { outFlowOldM = flowNtoM[redirect[oldM] - offset].second.first; inFlowOldM = flowNtoM[redirect[oldM] - offset].second.second; } // Option to move to empty module (if node not already alone) if (mod_members[oldM] > static_cast(node[flip]->members.size())) { if (Nempty > 0) { flowNtoM[NmodLinks].first = mod_empty[Nempty-1]; flowNtoM[NmodLinks].second.first = 0.0; flowNtoM[NmodLinks].second.second = 0.0; NmodLinks++; } } // Randomize link order for optimized search for (int j=0;jexit + outFlowOldM + inFlowOldM) + plogp(mod_exit[newM] + node[flip]->exit - outFlowNewM - inFlowNewM); double delta_size_log_size = - plogp(mod_exit[oldM] + mod_size[oldM]) - plogp(mod_exit[newM] + mod_size[newM]) + plogp(mod_exit[oldM] + mod_size[oldM] - node[flip]->exit - node[flip]->size + outFlowOldM + inFlowOldM) + plogp(mod_exit[newM] + mod_size[newM] + node[flip]->exit + node[flip]->size - outFlowNewM - inFlowNewM); double deltaL = delta_exit - 2.0*delta_exit_log_exit + delta_size_log_size; if (deltaL - best_delta < -1e-10) { bestM = newM; best_outFlow = outFlowNewM; best_inFlow = inFlowNewM; best_delta = deltaL; } } } // Make best possible move if (bestM != oldM) { //Update empty module vector if (mod_members[bestM] == 0) { Nempty--; } if (mod_members[oldM] == static_cast(node[flip]->members.size())) { mod_empty[Nempty] = oldM; Nempty++; } exitFlow -= mod_exit[oldM] + mod_exit[bestM]; exit_log_exit -= plogp(mod_exit[oldM]) + plogp(mod_exit[bestM]); size_log_size -= plogp(mod_exit[oldM] + mod_size[oldM]) + plogp(mod_exit[bestM] + mod_size[bestM]); mod_exit[oldM] -= node[flip]->exit - outFlowOldM - inFlowOldM; mod_size[oldM] -= node[flip]->size; mod_danglingSize[oldM] -= node[flip]->danglingSize; mod_teleportWeight[oldM] -= node[flip]->teleportWeight; mod_members[oldM] -= node[flip]->members.size(); mod_exit[bestM] += node[flip]->exit - best_outFlow - best_inFlow; mod_size[bestM] += node[flip]->size; mod_danglingSize[bestM] += node[flip]->danglingSize; mod_teleportWeight[bestM] += node[flip]->teleportWeight; mod_members[bestM] += node[flip]->members.size(); exitFlow += mod_exit[oldM] + mod_exit[bestM]; // Update terms in map equation exit_log_exit += plogp(mod_exit[oldM]) + plogp(mod_exit[bestM]); size_log_size += plogp(mod_exit[oldM] + mod_size[oldM]) + plogp(mod_exit[bestM] + mod_size[bestM]); exit = plogp(exitFlow); // Update code length codeLength = exit - 2.0*exit_log_exit + size_log_size - nodeSize_log_nodeSize; node_index[flip] = bestM; moved = true; } offset += Nnode; } RNG_END(); return moved; } /** Apply the move to the given network */ void Greedy::apply(bool sort) { //void Greedy::level(Node ***node_tmp, bool sort) { //old fct prepare(sort) vector modSnode; // will give ids of no-empty modules (nodes) int Nmod = 0; if (sort) { multimap Msize; for (int i=0; i 0) { Nmod++; Msize.insert(pair(mod_size[i],i)); } } for (multimap::reverse_iterator it = Msize.rbegin(); it != Msize.rend(); it++) { modSnode.push_back(it->second); } } else { for (int i=0;i 0) { Nmod++; modSnode.push_back(i); } } } //modSnode[id_when_no_empty_node] = id_in_mod_tbl // Create the new graph FlowGraph * tmp_fgraph = new FlowGraph(Nmod); IGRAPH_FINALLY(delete_FlowGraph, tmp_fgraph); Node ** node_tmp = tmp_fgraph->node ; Node ** node = graph->node; vector nodeInMod = vector(Nnode); // creation of new nodes for (int i=0;i().swap(node_tmp[i]->members); // clear membership node_tmp[i]->exit = mod_exit[modSnode[i]]; node_tmp[i]->size = mod_size[modSnode[i]]; node_tmp[i]->danglingSize = mod_danglingSize[modSnode[i]]; node_tmp[i]->teleportWeight = mod_teleportWeight[modSnode[i]]; nodeInMod[modSnode[i]] = i; } //nodeInMode[id_in_mod_tbl] = id_when_no_empty_node // Calculate outflow of links to different modules vector > outFlowNtoM(Nmod); map::iterator it_M; for (int i=0;imembers.begin(), node[i]->members.end(), back_inserter( node_tmp[i_M]->members ) ); int NoutLinks = node[i]->outLinks.size(); for (int j=0; joutLinks[j].first; int nb_M = nodeInMod[node_index[nb]]; double nb_flow = node[i]->outLinks[j].second; if (nb != i) { it_M = outFlowNtoM[i_M].find(nb_M); if (it_M != outFlowNtoM[i_M].end()) { it_M->second += nb_flow; } else { outFlowNtoM[i_M].insert(make_pair(nb_M,nb_flow)); } } } } // Create outLinks at new level for (int i=0;ifirst != i) { node_tmp[i]->outLinks.push_back(make_pair(it_M->first,it_M->second)); } } } // Calculate inflow of links from different modules vector > inFlowNtoM(Nmod); for (int i=0;iinLinks.size(); for (int j=0;jinLinks[j].first; int nb_M = nodeInMod[node_index[nb]]; double nb_flow = node[i]->inLinks[j].second; if (nb != i) { it_M = inFlowNtoM[i_M].find(nb_M); if (it_M != inFlowNtoM[i_M].end()) { it_M->second += nb_flow; } else { inFlowNtoM[i_M].insert(make_pair(nb_M,nb_flow)); } } } } // Create inLinks at new level for (int i=0;ifirst != i) { node_tmp[i]->inLinks.push_back(make_pair(it_M->first,it_M->second)); } } } // Option to move to empty module vector().swap(mod_empty); Nempty = 0; //swap node between tmp_graph and graph, then destroy tmp_fgraph graph->swap(tmp_fgraph); Nnode = Nmod; delete tmp_fgraph; IGRAPH_FINALLY_CLEAN(1); } /** * RAZ et recalcul : * - mod_exit * - mod_size * - mod_danglingSize * - mod_teleportWeight * - mod_members * and * - exit_log_exit * - size_log_size * - exitFlow * - exit * - codeLength * according to **node / node[i]->index */ void Greedy::tune(void) { exit_log_exit = 0.0; size_log_size = 0.0; exitFlow = 0.0; for (int i=0;inode; // Update all values except contribution from teleportation for (int i=0; i < Nnode; i++) { int i_M = node_index[i]; // module id of node i int Nlinks = node[i]->outLinks.size(); mod_size[i_M] += node[i]->size; mod_danglingSize[i_M] += node[i]->danglingSize; mod_teleportWeight[i_M] += node[i]->teleportWeight; mod_members[i_M]++; for (int j=0;joutLinks[j].first; double neighbor_w = node[i]->outLinks[j].second; int neighbor_M = node_index[neighbor]; if (i_M != neighbor_M) // neighbor in an other module mod_exit[i_M] += neighbor_w; } } // Update contribution from teleportation for (int i=0;inode; //printf("setMove nNode:%d \n", Nnode); for (int i=0 ; i new : %d -> %d \n", oldM, newM); if (newM != oldM) { // Si je comprend bien : // outFlow... : c'est le "flow" de i-> autre sommet du meme module // inFlow... : c'est le "flow" depuis un autre sommet du meme module --> i double outFlowOldM = (alpha*node[i]->size + beta*node[i]->danglingSize)* (mod_teleportWeight[oldM]-node[i]->teleportWeight); double inFlowOldM = (alpha*(mod_size[oldM]-node[i]->size) + beta*(mod_danglingSize[oldM] - node[i]->danglingSize)) * node[i]->teleportWeight; double outFlowNewM = (alpha*node[i]->size + beta*node[i]->danglingSize) * mod_teleportWeight[newM]; double inFlowNewM = (alpha*mod_size[newM] + beta*mod_danglingSize[newM]) * node[i]->teleportWeight; // For all outLinks int NoutLinks = node[i]->outLinks.size(); for (int j=0; joutLinks[j].first]; double nb_flow = node[i]->outLinks[j].second; if (nb_M == oldM) { outFlowOldM += nb_flow; } else if (nb_M == newM) { outFlowNewM += nb_flow; } } // For all inLinks int NinLinks = node[i]->inLinks.size(); for (int j=0; jinLinks[j].first]; double nb_flow = node[i]->inLinks[j].second; if (nb_M == oldM) { inFlowOldM += nb_flow; } else if (nb_M == newM) { inFlowNewM += nb_flow; } } // Update empty module vector // RAZ de mod_empty et Nempty ds calibrate() if (mod_members[newM] == 0) { // si le nouveau etait vide, on a un vide de moins... Nempty--; } if (mod_members[oldM] == static_cast(node[i]->members.size())) { // si l'ancien avait la taille de celui qui bouge, un vide de plus mod_empty[Nempty] = oldM; Nempty++; } exitFlow -= mod_exit[oldM] + mod_exit[newM]; exit_log_exit -= plogp(mod_exit[oldM]) + plogp(mod_exit[newM]); size_log_size -= plogp(mod_exit[oldM] + mod_size[oldM]) + plogp(mod_exit[newM] + mod_size[newM]); mod_exit[oldM] -= node[i]->exit - outFlowOldM - inFlowOldM; mod_size[oldM] -= node[i]->size; mod_danglingSize[oldM] -= node[i]->danglingSize; mod_teleportWeight[oldM] -= node[i]->teleportWeight; mod_members[oldM] -= node[i]->members.size(); mod_exit[newM] += node[i]->exit - outFlowNewM - inFlowNewM; mod_size[newM] += node[i]->size; mod_danglingSize[newM] += node[i]->danglingSize; mod_teleportWeight[newM] += node[i]->teleportWeight; mod_members[newM] += node[i]->members.size(); exitFlow += mod_exit[oldM] + mod_exit[newM]; exit_log_exit += plogp(mod_exit[oldM]) + plogp(mod_exit[newM]); size_log_size += plogp(mod_exit[oldM] + mod_size[oldM]) + plogp(mod_exit[newM] + mod_size[newM]); exit = plogp(exitFlow); codeLength = exit - 2.0*exit_log_exit + size_log_size - nodeSize_log_nodeSize; node_index[i] = newM; } } } igraph/src/dsaitr.f0000644000175100001440000007452113431000472013771 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsaitr c c\Description: c Reverse communication interface for applying NP additional steps to c a K step symmetric Arnoldi factorization. c c Input: OP*V_{k} - V_{k}*H = r_{k}*e_{k}^T c c with (V_{k}^T)*B*V_{k} = I, (V_{k}^T)*B*r_{k} = 0. c c Output: OP*V_{k+p} - V_{k+p}*H = r_{k+p}*e_{k+p}^T c c with (V_{k+p}^T)*B*V_{k+p} = I, (V_{k+p}^T)*B*r_{k+p} = 0. c c where OP and B are as in igraphdsaupd. The B-norm of r_{k+p} is also c computed and returned. c c\Usage: c call igraphdsaitr c ( IDO, BMAT, N, K, NP, MODE, RESID, RNORM, V, LDV, H, LDH, c IPNTR, WORKD, INFO ) c c\Arguments c IDO Integer. (INPUT/OUTPUT) c Reverse communication flag. c ------------------------------------------------------------- c IDO = 0: first call to the reverse communication interface c IDO = -1: compute Y = OP * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y. c This is for the restart phase to force the new c starting vector into the range of OP. c IDO = 1: compute Y = OP * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y, c IPNTR(3) is the pointer into WORK for B * X. c IDO = 2: compute Y = B * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y. c IDO = 99: done c ------------------------------------------------------------- c When the routine is used in the "shift-and-invert" mode, the c vector B * Q is already available and does not need to be c recomputed in forming OP * Q. c c BMAT Character*1. (INPUT) c BMAT specifies the type of matrix B that defines the c semi-inner product for the operator OP. See igraphdsaupd. c B = 'I' -> standard eigenvalue problem A*x = lambda*x c B = 'G' -> generalized eigenvalue problem A*x = lambda*M*x c c N Integer. (INPUT) c Dimension of the eigenproblem. c c K Integer. (INPUT) c Current order of H and the number of columns of V. c c NP Integer. (INPUT) c Number of additional Arnoldi steps to take. c c MODE Integer. (INPUT) c Signifies which form for "OP". If MODE=2 then c a reduction in the number of B matrix vector multiplies c is possible since the B-norm of OP*x is equivalent to c the inv(B)-norm of A*x. c c RESID Double precision array of length N. (INPUT/OUTPUT) c On INPUT: RESID contains the residual vector r_{k}. c On OUTPUT: RESID contains the residual vector r_{k+p}. c c RNORM Double precision scalar. (INPUT/OUTPUT) c On INPUT the B-norm of r_{k}. c On OUTPUT the B-norm of the updated residual r_{k+p}. c c V Double precision N by K+NP array. (INPUT/OUTPUT) c On INPUT: V contains the Arnoldi vectors in the first K c columns. c On OUTPUT: V contains the new NP Arnoldi vectors in the next c NP columns. The first K columns are unchanged. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (K+NP) by 2 array. (INPUT/OUTPUT) c H is used to store the generated symmetric tridiagonal matrix c with the subdiagonal in the first column starting at H(2,1) c and the main diagonal in the igraphsecond column. c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c IPNTR Integer array of length 3. (OUTPUT) c Pointer to mark the starting locations in the WORK for c vectors used by the Arnoldi iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X. c IPNTR(2): pointer to the current result vector Y. c IPNTR(3): pointer to the vector B * X when used in the c shift-and-invert mode. X is the current operand. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The calling program should not c use WORKD as temporary workspace during the iteration !!!!!! c On INPUT, WORKD(1:N) = B*RESID where RESID is associated c with the K step Arnoldi factorization. Used to save some c computation at the first step. c On OUTPUT, WORKD(1:N) = B*RESID where RESID is associated c with the K+NP step Arnoldi factorization. c c INFO Integer. (OUTPUT) c = 0: Normal exit. c > 0: Size of an invariant subspace of OP is found that is c less than K + NP. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\Routines called: c igraphdgetv0 ARPACK routine to generate the initial vector. c igraphivout ARPACK utility routine that prints integers. c igraphdmout ARPACK utility routine that prints matrices. c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c dlascl LAPACK routine for careful scaling of a matrix. c dgemv Level 2 BLAS routine for matrix vector multiplication. c daxpy Level 1 BLAS that computes a vector triad. c dscal Level 1 BLAS that scales a vector. c dcopy Level 1 BLAS that copies one vector to another . c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/93: Version ' 2.4' c c\SCCS Information: @(#) c FILE: saitr.F SID: 2.6 DATE OF SID: 8/28/96 RELEASE: 2 c c\Remarks c The algorithm implemented is: c c restart = .false. c Given V_{k} = [v_{1}, ..., v_{k}], r_{k}; c r_{k} contains the initial residual vector even for k = 0; c Also assume that rnorm = || B*r_{k} || and B*r_{k} are already c computed by the calling program. c c betaj = rnorm ; p_{k+1} = B*r_{k} ; c For j = k+1, ..., k+np Do c 1) if ( betaj < tol ) stop or restart depending on j. c if ( restart ) generate a new starting vector. c 2) v_{j} = r(j-1)/betaj; V_{j} = [V_{j-1}, v_{j}]; c p_{j} = p_{j}/betaj c 3) r_{j} = OP*v_{j} where OP is defined as in igraphdsaupd c For shift-invert mode p_{j} = B*v_{j} is already available. c wnorm = || OP*v_{j} || c 4) Compute the j-th step residual vector. c w_{j} = V_{j}^T * B * OP * v_{j} c r_{j} = OP*v_{j} - V_{j} * w_{j} c alphaj <- j-th component of w_{j} c rnorm = || r_{j} || c betaj+1 = rnorm c If (rnorm > 0.717*wnorm) accept step and go back to 1) c 5) Re-orthogonalization step: c s = V_{j}'*B*r_{j} c r_{j} = r_{j} - V_{j}*s; rnorm1 = || r_{j} || c alphaj = alphaj + s_{j}; c 6) Iterative refinement step: c If (rnorm1 > 0.717*rnorm) then c rnorm = rnorm1 c accept step and go back to 1) c Else c rnorm = rnorm1 c If this is the first time in step 6), go to 5) c Else r_{j} lies in the span of V_{j} numerically. c Set r_{j} = 0 and rnorm = 0; go to 1) c EndIf c End Do c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsaitr & (ido, bmat, n, k, np, mode, resid, rnorm, v, ldv, h, ldh, & ipntr, workd, info) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1 integer ido, info, k, ldh, ldv, n, mode, np Double precision & rnorm c c %-----------------% c | Array Arguments | c %-----------------% c integer ipntr(3) Double precision & h(ldh,2), resid(n), v(ldv,k+np), workd(3*n) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c logical first, orth1, orth2, rstart, step3, step4 integer i, ierr, ipj, irj, ivj, iter, itry, j, msglvl, & infol, jj Double precision & rnorm1, wnorm, safmin, temp1 save orth1, orth2, rstart, step3, step4, & ierr, ipj, irj, ivj, iter, itry, j, msglvl, & rnorm1, safmin, wnorm c c %-----------------------% c | Local Array Arguments | c %-----------------------% c Double precision & xtemp(2) c c %----------------------% c | External Subroutines | c %----------------------% c external daxpy, dcopy, dscal, dgemv, igraphdgetv0, & igraphdvout, igraphdmout, & dlascl, igraphivout, igraphsecond c c %--------------------% c | External Functions | c %--------------------% c Double precision & ddot, dnrm2, dlamch external ddot, dnrm2, dlamch c c %-----------------% c | Data statements | c %-----------------% c data first / .true. / c c %-----------------------% c | Executable Statements | c %-----------------------% c if (first) then first = .false. c c %--------------------------------% c | safmin = safe minimum is such | c | that 1/sfmin does not overflow | c %--------------------------------% c safmin = dlamch('safmin') end if c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = msaitr c c %------------------------------% c | Initial call to this routine | c %------------------------------% c info = 0 step3 = .false. step4 = .false. rstart = .false. orth1 = .false. orth2 = .false. c c %--------------------------------% c | Pointer to the current step of | c | the factorization to build | c %--------------------------------% c j = k + 1 c c %------------------------------------------% c | Pointers used for reverse communication | c | when using WORKD. | c %------------------------------------------% c ipj = 1 irj = ipj + n ivj = irj + n end if c c %-------------------------------------------------% c | When in reverse communication mode one of: | c | STEP3, STEP4, ORTH1, ORTH2, RSTART | c | will be .true. | c | STEP3: return from computing OP*v_{j}. | c | STEP4: return from computing B-norm of OP*v_{j} | c | ORTH1: return from computing B-norm of r_{j+1} | c | ORTH2: return from computing B-norm of | c | correction to the residual vector. | c | RSTART: return from OP computations needed by | c | igraphdgetv0. | c %-------------------------------------------------% c if (step3) go to 50 if (step4) go to 60 if (orth1) go to 70 if (orth2) go to 90 if (rstart) go to 30 c c %------------------------------% c | Else this is the first step. | c %------------------------------% c c %--------------------------------------------------------------% c | | c | A R N O L D I I T E R A T I O N L O O P | c | | c | Note: B*r_{j-1} is already in WORKD(1:N)=WORKD(IPJ:IPJ+N-1) | c %--------------------------------------------------------------% c 1000 continue c if (msglvl .gt. 2) then call igraphivout (logfil, 1, j, ndigit, & '_saitr: generating Arnoldi vector no.') call igraphdvout (logfil, 1, rnorm, ndigit, & '_saitr: B-norm of the current residual =') end if c c %---------------------------------------------------------% c | Check for exact zero. Equivalent to determing whether a | c | j-step Arnoldi factorization is present. | c %---------------------------------------------------------% c if (rnorm .gt. zero) go to 40 c c %---------------------------------------------------% c | Invariant subspace found, generate a new starting | c | vector which is orthogonal to the current Arnoldi | c | basis and continue the iteration. | c %---------------------------------------------------% c if (msglvl .gt. 0) then call igraphivout (logfil, 1, j, ndigit, & '_saitr: ****** restart at step ******') end if c c %---------------------------------------------% c | ITRY is the loop variable that controls the | c | maximum amount of times that a restart is | c | attempted. NRSTRT is used by stat.h | c %---------------------------------------------% c nrstrt = nrstrt + 1 itry = 1 20 continue rstart = .true. ido = 0 30 continue c c %--------------------------------------% c | If in reverse communication mode and | c | RSTART = .true. flow returns here. | c %--------------------------------------% c call igraphdgetv0 (ido, bmat, itry, .false., n, j, v, ldv, & resid, rnorm, ipntr, workd, ierr) if (ido .ne. 99) go to 9000 if (ierr .lt. 0) then itry = itry + 1 if (itry .le. 3) go to 20 c c %------------------------------------------------% c | Give up after several restart attempts. | c | Set INFO to the size of the invariant subspace | c | which spans OP and exit. | c %------------------------------------------------% c info = j - 1 call igraphsecond (t1) tsaitr = tsaitr + (t1 - t0) ido = 99 go to 9000 end if c 40 continue c c %---------------------------------------------------------% c | STEP 2: v_{j} = r_{j-1}/rnorm and p_{j} = p_{j}/rnorm | c | Note that p_{j} = B*r_{j-1}. In order to avoid overflow | c | when reciprocating a small RNORM, test against lower | c | machine bound. | c %---------------------------------------------------------% c call dcopy (n, resid, 1, v(1,j), 1) if (rnorm .ge. safmin) then temp1 = one / rnorm call dscal (n, temp1, v(1,j), 1) call dscal (n, temp1, workd(ipj), 1) else c c %-----------------------------------------% c | To scale both v_{j} and p_{j} carefully | c | use LAPACK routine SLASCL | c %-----------------------------------------% c call dlascl ('General', i, i, rnorm, one, n, 1, & v(1,j), n, infol) call dlascl ('General', i, i, rnorm, one, n, 1, & workd(ipj), n, infol) end if c c %------------------------------------------------------% c | STEP 3: r_{j} = OP*v_{j}; Note that p_{j} = B*v_{j} | c | Note that this is not quite yet r_{j}. See STEP 4 | c %------------------------------------------------------% c step3 = .true. nopx = nopx + 1 call igraphsecond (t2) call dcopy (n, v(1,j), 1, workd(ivj), 1) ipntr(1) = ivj ipntr(2) = irj ipntr(3) = ipj ido = 1 c c %-----------------------------------% c | Exit in order to compute OP*v_{j} | c %-----------------------------------% c go to 9000 50 continue c c %-----------------------------------% c | Back from reverse communication; | c | WORKD(IRJ:IRJ+N-1) := OP*v_{j}. | c %-----------------------------------% c call igraphsecond (t3) tmvopx = tmvopx + (t3 - t2) c step3 = .false. c c %------------------------------------------% c | Put another copy of OP*v_{j} into RESID. | c %------------------------------------------% c call dcopy (n, workd(irj), 1, resid, 1) c c %-------------------------------------------% c | STEP 4: Finish extending the symmetric | c | Arnoldi to length j. If MODE = 2 | c | then B*OP = B*inv(B)*A = A and | c | we don't need to compute B*OP. | c | NOTE: If MODE = 2 WORKD(IVJ:IVJ+N-1) is | c | assumed to have A*v_{j}. | c %-------------------------------------------% c if (mode .eq. 2) go to 65 call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 step4 = .true. ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %-------------------------------------% c | Exit in order to compute B*OP*v_{j} | c %-------------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy(n, resid, 1 , workd(ipj), 1) end if 60 continue c c %-----------------------------------% c | Back from reverse communication; | c | WORKD(IPJ:IPJ+N-1) := B*OP*v_{j}. | c %-----------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c step4 = .false. c c %-------------------------------------% c | The following is needed for STEP 5. | c | Compute the B-norm of OP*v_{j}. | c %-------------------------------------% c 65 continue if (mode .eq. 2) then c c %----------------------------------% c | Note that the B-norm of OP*v_{j} | c | is the inv(B)-norm of A*v_{j}. | c %----------------------------------% c wnorm = ddot (n, resid, 1, workd(ivj), 1) wnorm = sqrt(abs(wnorm)) else if (bmat .eq. 'G') then wnorm = ddot (n, resid, 1, workd(ipj), 1) wnorm = sqrt(abs(wnorm)) else if (bmat .eq. 'I') then wnorm = dnrm2(n, resid, 1) end if c c %-----------------------------------------% c | Compute the j-th residual corresponding | c | to the j step factorization. | c | Use Classical Gram Schmidt and compute: | c | w_{j} <- V_{j}^T * B * OP * v_{j} | c | r_{j} <- OP*v_{j} - V_{j} * w_{j} | c %-----------------------------------------% c c c %------------------------------------------% c | Compute the j Fourier coefficients w_{j} | c | WORKD(IPJ:IPJ+N-1) contains B*OP*v_{j}. | c %------------------------------------------% c if (mode .ne. 2 ) then call dgemv('T', n, j, one, v, ldv, workd(ipj), 1, zero, & workd(irj), 1) else if (mode .eq. 2) then call dgemv('T', n, j, one, v, ldv, workd(ivj), 1, zero, & workd(irj), 1) end if c c %--------------------------------------% c | Orthgonalize r_{j} against V_{j}. | c | RESID contains OP*v_{j}. See STEP 3. | c %--------------------------------------% c call dgemv('N', n, j, -one, v, ldv, workd(irj), 1, one, & resid, 1) c c %--------------------------------------% c | Extend H to have j rows and columns. | c %--------------------------------------% c h(j,2) = workd(irj + j - 1) if (j .eq. 1 .or. rstart) then h(j,1) = zero else h(j,1) = rnorm end if call igraphsecond (t4) c orth1 = .true. iter = 0 c call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(irj), 1) ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %----------------------------------% c | Exit in order to compute B*r_{j} | c %----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd(ipj), 1) end if 70 continue c c %---------------------------------------------------% c | Back from reverse communication if ORTH1 = .true. | c | WORKD(IPJ:IPJ+N-1) := B*r_{j}. | c %---------------------------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c orth1 = .false. c c %------------------------------% c | Compute the B-norm of r_{j}. | c %------------------------------% c if (bmat .eq. 'G') then rnorm = ddot (n, resid, 1, workd(ipj), 1) rnorm = sqrt(abs(rnorm)) else if (bmat .eq. 'I') then rnorm = dnrm2(n, resid, 1) end if c c %-----------------------------------------------------------% c | STEP 5: Re-orthogonalization / Iterative refinement phase | c | Maximum NITER_ITREF tries. | c | | c | s = V_{j}^T * B * r_{j} | c | r_{j} = r_{j} - V_{j}*s | c | alphaj = alphaj + s_{j} | c | | c | The stopping criteria used for iterative refinement is | c | discussed in Parlett's book SEP, page 107 and in Gragg & | c | Reichel ACM TOMS paper; Algorithm 686, Dec. 1990. | c | Determine if we need to correct the residual. The goal is | c | to enforce ||v(:,1:j)^T * r_{j}|| .le. eps * || r_{j} || | c %-----------------------------------------------------------% c if (rnorm .gt. 0.717*wnorm) go to 100 nrorth = nrorth + 1 c c %---------------------------------------------------% c | Enter the Iterative refinement phase. If further | c | refinement is necessary, loop back here. The loop | c | variable is ITER. Perform a step of Classical | c | Gram-Schmidt using all the Arnoldi vectors V_{j} | c %---------------------------------------------------% c 80 continue c if (msglvl .gt. 2) then xtemp(1) = wnorm xtemp(2) = rnorm call igraphdvout (logfil, 2, xtemp, ndigit, & '_saitr: re-orthonalization ; wnorm and rnorm are') end if c c %----------------------------------------------------% c | Compute V_{j}^T * B * r_{j}. | c | WORKD(IRJ:IRJ+J-1) = v(:,1:J)'*WORKD(IPJ:IPJ+N-1). | c %----------------------------------------------------% c call dgemv ('T', n, j, one, v, ldv, workd(ipj), 1, & zero, workd(irj), 1) c c %----------------------------------------------% c | Compute the correction to the residual: | c | r_{j} = r_{j} - V_{j} * WORKD(IRJ:IRJ+J-1). | c | The correction to H is v(:,1:J)*H(1:J,1:J) + | c | v(:,1:J)*WORKD(IRJ:IRJ+J-1)*e'_j, but only | c | H(j,j) is updated. | c %----------------------------------------------% c call dgemv ('N', n, j, -one, v, ldv, workd(irj), 1, & one, resid, 1) c if (j .eq. 1 .or. rstart) h(j,1) = zero h(j,2) = h(j,2) + workd(irj + j - 1) c orth2 = .true. call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(irj), 1) ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %-----------------------------------% c | Exit in order to compute B*r_{j}. | c | r_{j} is the corrected residual. | c %-----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd(ipj), 1) end if 90 continue c c %---------------------------------------------------% c | Back from reverse communication if ORTH2 = .true. | c %---------------------------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c c %-----------------------------------------------------% c | Compute the B-norm of the corrected residual r_{j}. | c %-----------------------------------------------------% c if (bmat .eq. 'G') then rnorm1 = ddot (n, resid, 1, workd(ipj), 1) rnorm1 = sqrt(abs(rnorm1)) else if (bmat .eq. 'I') then rnorm1 = dnrm2(n, resid, 1) end if c if (msglvl .gt. 0 .and. iter .gt. 0) then call igraphivout (logfil, 1, j, ndigit, & '_saitr: Iterative refinement for Arnoldi residual') if (msglvl .gt. 2) then xtemp(1) = rnorm xtemp(2) = rnorm1 call igraphdvout (logfil, 2, xtemp, ndigit, & '_saitr: iterative refinement ; rnorm and rnorm1 are') end if end if c c %-----------------------------------------% c | Determine if we need to perform another | c | step of re-orthogonalization. | c %-----------------------------------------% c if (rnorm1 .gt. 0.717*rnorm) then c c %--------------------------------% c | No need for further refinement | c %--------------------------------% c rnorm = rnorm1 c else c c %-------------------------------------------% c | Another step of iterative refinement step | c | is required. NITREF is used by stat.h | c %-------------------------------------------% c nitref = nitref + 1 rnorm = rnorm1 iter = iter + 1 if (iter .le. 1) go to 80 c c %-------------------------------------------------% c | Otherwise RESID is numerically in the span of V | c %-------------------------------------------------% c do 95 jj = 1, n resid(jj) = zero 95 continue rnorm = zero end if c c %----------------------------------------------% c | Branch here directly if iterative refinement | c | wasn't necessary or after at most NITER_REF | c | steps of iterative refinement. | c %----------------------------------------------% c 100 continue c rstart = .false. orth2 = .false. c call igraphsecond (t5) titref = titref + (t5 - t4) c c %----------------------------------------------------------% c | Make sure the last off-diagonal element is non negative | c | If not perform a similarity transformation on H(1:j,1:j) | c | and scale v(:,j) by -1. | c %----------------------------------------------------------% c if (h(j,1) .lt. zero) then h(j,1) = -h(j,1) if ( j .lt. k+np) then call dscal(n, -one, v(1,j+1), 1) else call dscal(n, -one, resid, 1) end if end if c c %------------------------------------% c | STEP 6: Update j = j+1; Continue | c %------------------------------------% c j = j + 1 if (j .gt. k+np) then call igraphsecond (t1) tsaitr = tsaitr + (t1 - t0) ido = 99 c if (msglvl .gt. 1) then call igraphdvout (logfil, k+np, h(1,2), ndigit, & '_saitr: main diagonal of matrix H of step K+NP.') if (k+np .gt. 1) then call igraphdvout (logfil, k+np-1, h(2,1), ndigit, & '_saitr: sub diagonal of matrix H of step K+NP.') end if end if c go to 9000 end if c c %--------------------------------------------------------% c | Loop back to extend the factorization by another step. | c %--------------------------------------------------------% c go to 1000 c c %---------------------------------------------------------------% c | | c | E N D O F M A I N I T E R A T I O N L O O P | c | | c %---------------------------------------------------------------% c 9000 continue return c c %---------------% c | End of igraphdsaitr | c %---------------% c end igraph/src/infomap_Greedy.h0000644000175100001440000000413113431000472015423 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GREEDY_H #define GREEDY_H #include #include #include #include #include "igraph_random.h" #include "infomap_Node.h" #include "infomap_FlowGraph.h" class Greedy { public: Greedy(FlowGraph * fgraph); // initialise les attributs par rapport au graph ~Greedy(); void setMove(int *moveTo); //virtual void determMove(int *moveTo); bool optimize(); //virtual void move(bool &moved); void apply(bool sort); //virtual void level(Node ***, bool sort); void tune(void); /**************************************************************************/ FlowGraph * graph; int Nnode; double exit; double exitFlow; double exit_log_exit; double size_log_size; double nodeSize_log_nodeSize; double codeLength; double alpha,beta; // local copy of fgraph alpha, beta (=alpha - Nnode = graph->Nnode;1) vector node_index; // module number of each node int Nempty; vector mod_empty; vector mod_exit; // version tmp de node vector mod_size; vector mod_danglingSize; vector mod_teleportWeight; vector mod_members; }; void delete_Greedy(Greedy *greedy); #endif igraph/src/gengraph_random.h0000644000175100001440000001643013431000472015633 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef RNG_H #define RNG_H #include "igraph_random.h" #include using namespace std; namespace KW_RNG { typedef signed int sint; typedef unsigned int uint; typedef signed long slong; typedef unsigned long ulong; class RNG { public: RNG() { } RNG(ulong z_, ulong w_, ulong jsr_, ulong jcong_ ) { IGRAPH_UNUSED(z_); IGRAPH_UNUSED(w_); IGRAPH_UNUSED(jsr_); IGRAPH_UNUSED(jcong_); }; ~RNG() { } void init(ulong z_, ulong w_, ulong jsr_, ulong jcong_ ) { IGRAPH_UNUSED(z_); IGRAPH_UNUSED(w_); IGRAPH_UNUSED(jsr_); IGRAPH_UNUSED(jcong_); } long rand_int31() { return RNG_INT31(); } double rand_halfopen01() // (0,1] { return RNG_UNIF01(); } int binomial(double pp, int n) { return RNG_BINOM(n,pp); } }; } // namespace KW_RNG /* This was the original RNG, but now we use the igraph version */ // __________________________________________________________________________ // random.h - a Random Number Generator Class // random.cpp - contains the non-inline class methods // __________________________________________________________________________ // This C++ code uses the simple, very fast "KISS" (Keep It Simple // Stupid) random number generator suggested by George Marsaglia in a // Usenet posting from 1999. He describes it as "one of my favorite // generators". It generates high-quality random numbers that // apparently pass all commonly used tests for randomness. In fact, it // generates random numbers by combining the results of three other good // random number generators that have different periods and are // constructed from completely different algorithms. It does not have // the ultra-long period of some other generators - a "problem" that can // be fixed fairly easily - but that seems to be its only potential // problem. The period is about 2^123. // The ziggurat method of Marsaglia is used to generate exponential and // normal variates. The method as well as source code can be found in // the article "The Ziggurat Method for Generating Random Variables" by // Marsaglia and Tsang, Journal of Statistical Software 5, 2000. // The method for generating gamma variables appears in "A Simple Method // for Generating Gamma Variables" by Marsaglia and Tsang, ACM // Transactions on Mathematical Software, Vol. 26, No 3, Sep 2000, pages // 363-372. // The code for Poisson and Binomial random numbers comes from // Numerical Recipes in C. // Some of this code is unlikely to work correctly as is on 64 bit // machines. // #include // #include // #ifdef _WIN32 // #include // #define getpid _getpid // #else // #include // #endif // //#ifdef _WIN32 // static const double PI = 3.1415926535897932; // static const double AD_l = 0.6931471805599453; // static const double AD_a = 5.7133631526454228; // static const double AD_b = 3.4142135623730950; // static const double AD_c = -1.6734053240284925; // static const double AD_p = 0.9802581434685472; // static const double AD_A = 5.6005707569738080; // static const double AD_B = 3.3468106480569850; // static const double AD_H = 0.0026106723602095; // static const double AD_D = 0.0857864376269050; // //#endif //_WIN32 // namespace KW_RNG { // class RNG // { // private: // ulong z, w, jsr, jcong; // Seeds // ulong kn[128], ke[256]; // double wn[128],fn[128], we[256],fe[256]; // /* // #ifndef _WIN32 // static const double PI = 3.1415926535897932; // static const double AD_l = 0.6931471805599453; // static const double AD_a = 5.7133631526454228; // static const double AD_b = 3.4142135623730950; // static const double AD_c = -1.6734053240284925; // static const double AD_p = 0.9802581434685472; // static const double AD_A = 5.6005707569738080; // static const double AD_B = 3.3468106480569850; // static const double AD_H = 0.0026106723602095; // static const double AD_D = 0.0857864376269050; // #endif //_WIN32 // */ // public: // RNG() { init(); zigset(); } // RNG(ulong z_, ulong w_, ulong jsr_, ulong jcong_ ) : // z(z_), w(w_), jsr(jsr_), jcong(jcong_) { zigset(); } // ~RNG() { } // inline ulong znew() // { return (z = 36969 * (z & 65535) + (z >> 16)); } // inline ulong wnew() // { return (w = 18000 * (w & 65535) + (w >> 16)); } // inline ulong MWC() // { return (((znew() & 65535) << 16) + wnew()); } // inline ulong SHR3() // { jsr ^= ((jsr & 32767) << 17); jsr ^= (jsr >> 13); return (jsr ^= ((jsr << 5) & 0xFFFFFFFF)); } // inline ulong CONG() // { return (jcong = (69069 * jcong + 1234567) & 0xFFFFFFFF); } // inline double RNOR() { // slong h = rand_int32(); // ulong i = h & 127; // return (((ulong) abs((sint) h) < kn[i]) ? h * wn[i] : nfix(h, i)); // } // inline double REXP() { // ulong j = rand_int32(); // ulong i = j & 255; // return ((j < ke[i]) ? j * we[i] : efix(j, i)); // } // double nfix(slong h, ulong i); // double efix(ulong j, ulong i); // void zigset(); // inline void init() // { ulong yo = time(0) + getpid(); // z = w = jsr = jcong = yo; } // inline void init(ulong z_, ulong w_, ulong jsr_, ulong jcong_ ) // { z = z_; w = w_; jsr = jsr_; jcong = jcong_; } // inline ulong rand_int32() // [0,2^32-1] // { return ((MWC() ^ CONG()) + SHR3()) & 0xFFFFFFFF; } // inline long rand_int31() // [0,2^31-1] // { return long(rand_int32() >> 1);} // inline double rand_closed01() // [0,1] // { return ((double) rand_int32() / 4294967295.0); } // inline double rand_open01() // (0,1) // { return (((double) rand_int32() + 0.5) / 4294967296.0); } // inline double rand_halfclosed01() // [0,1) // { return ((double) rand_int32() / 4294967296.0); } // inline double rand_halfopen01() // (0,1] // { return (((double) rand_int32() + 0.5) / 4294967295.5); } // // Continuous Distributions // inline double uniform(double x = 0.0, double y = 1.0) // { return rand_closed01() * (y - x) + x; } // inline double normal(double mu = 0.0, double sd = 1.0) // { return RNOR() * sd + mu; } // inline double exponential(double lambda = 1) // { return REXP() / lambda; } // double gamma(double shape = 1, double scale = 1); // double chi_square(double df) // { return gamma(df / 2.0, 0.5); } // double beta(double a1, double a2) // { double x1 = gamma(a1, 1); return (x1 / (x1 + gamma(a2, 1))); } // // Discrete Distributions // double poisson(double lambda); // int binomial(double pp, int n); // }; // class RNG // } // namespace #endif // RNG_H igraph/src/gengraph_degree_sequence.h0000644000175100001440000000435313431000472017477 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DEGREE_SEQUENCE_H #define DEGREE_SEQUENCE_H #include "igraph_types.h" #include "igraph_datatype.h" namespace gengraph { class degree_sequence { private: int n; int * deg; int total; public : // #vertices inline int size() { return n; }; inline int sum() { return total; }; inline int operator[](int i) { return deg[i]; }; inline int *seq() { return deg; }; inline void assign(int n0, int* d0) { n=n0; deg=d0; }; inline int dmax() { int dm = deg[0]; for(int i=1; idm) dm=deg[i]; return dm; } void make_even(int mini=-1, int maxi=-1); void sort(); void shuffle(); // raw constructor degree_sequence(int n, int *degs); // read-from-file constrictor degree_sequence(FILE *f, bool DISTRIB=true); // simple power-law constructor : Pk = int((x+k0)^(-exp),x=k..k+1), with k0 so that avg(X)=z degree_sequence(int n, double exp, int degmin, int degmax, double avg_degree=-1.0); // igraph constructor degree_sequence(const igraph_vector_t *out_seq); // destructor ~degree_sequence(); // unbind the deg[] vector (so that it doesn't get deleted when the class is destroyed) void detach(); // compute total number of arcs void compute_total(); // raw print (vertex by vertex) void print(); // distribution print (degree frequency) void print_cumul(); // is degree sequence realizable ? bool havelhakimi(); }; } // namespace gengraph #endif //DEGREE_SEQUENCE_H igraph/src/NetRoutines.cpp0000644000175100001440000002211113431000472015303 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Jörg Reichardt The original copyright notice follows here */ /*************************************************************************** NetRoutines.cpp - description ------------------- begin : Tue Oct 28 2003 copyright : (C) 2003 by Joerg Reichardt email : reichardt@mitte ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include #include #include #include "NetRoutines.h" #include "NetDataTypes.h" #include "igraph_types.h" #include "igraph_interface.h" #include "igraph_conversion.h" int igraph_i_read_network(const igraph_t *graph, const igraph_vector_t *weights, network *net, igraph_bool_t use_weights, unsigned int states) { double av_k=0.0, sum_weight=0.0, min_weight=1e60, max_weight=-1e60; unsigned long min_k=999999999, max_k=0; long max_index=0; char name[255]; NNode *node1,*node2; DLList_Iter iter; igraph_vector_t edgelist; long int no_of_edges=(long int)igraph_ecount(graph); long int ii; char *empty=new char[1]; empty[0]='\0'; IGRAPH_VECTOR_INIT_FINALLY(&edgelist, no_of_edges*2); IGRAPH_CHECK(igraph_get_edgelist(graph, &edgelist, 0 /* rowwise */)); for (ii=0; iinode_list->Push(new NNode(i,0,net->link_list, empty,states)); max_index=i1; } if (max_indexnode_list->Push(new NNode(i,0,net->link_list, empty,states)); max_index=i2; } node1=net->node_list->Get(i1-1); sprintf(name,"%li",i1); node1->Set_Name(name); node2=net->node_list->Get(i2-1); sprintf(name,"%li",i2); node2->Set_Name(name); node1->Connect_To(node2,Links); if (Linksmax_weight) max_weight=Links; sum_weight+=Links; } IGRAPH_FINALLY_CLEAN(1); igraph_vector_destroy(&edgelist); node1=iter.First(net->node_list); while (!iter.End()) { if (node1->Get_Degree()>max_k) max_k=node1->Get_Degree(); if (node1->Get_Degree()Get_Degree(); av_k+=node1->Get_Degree(); node1=iter.Next(); } net->av_k=av_k/double(net->node_list->Size()); net->sum_weights=sum_weight; net->av_weight=sum_weight/double(net->link_list->Size()); net->min_k=min_k; net->max_k=max_k; net->min_weight=min_weight; net->max_weight=max_weight; net->sum_bids=0; net->min_bids=0; net->max_bids=0; delete [] empty; return 0; } //############################################################################################################### void reduce_cliques(DLList*> *global_cluster_list, FILE *file) { unsigned long size; ClusterList *c_cur, *largest_c=0; DLList*> *subsets; DLList_Iter*> c_iter, sub_iter; DLList_Iter iter; NNode *n_cur; if (!(global_cluster_list->Size())) return; //wir suchen den groessten Cluster c_cur=c_iter.First(global_cluster_list); size=0; while (!(c_iter.End())) { if (c_cur->Size()>size) { size=c_cur->Size(); largest_c=c_cur; } c_cur=c_iter.Next(); } // printf("Groesster Cluster hat %u Elemente.\n",largest_c->Size()); //Schauen, ob es Teilmengen gibt, die ebenfalls gefunden wurden subsets=new DLList*>(); c_cur=c_iter.First(global_cluster_list); while (!(c_iter.End())) { if ((*c_cur<*largest_c || *c_cur==*largest_c) && c_cur!=largest_c) //alle echten Teilcluster von largest_c und die doppelten { subsets->Push(c_cur); } c_cur=c_iter.Next(); } // die gefundenen Subsets werden aus der cluster_liste geloescht while (subsets->Size()) { global_cluster_list->fDelete(subsets->Pop()); } delete subsets; // Dann schreiben wir den groessten Cluster in das File fprintf(file,"Energie: %1.12f Nodes:%3lu - ",largest_c->Get_Energy(),largest_c->Size()); n_cur=iter.First(largest_c); while (!(iter.End())) { fprintf(file,"%s",n_cur->Get_Name()); n_cur=iter.Next(); if (n_cur) fprintf(file,", "); } fprintf(file,"\n"); //Schliesslich schmeissen wir noch den eben gefundenen groessten Cluster raus global_cluster_list->fDelete(largest_c); //und dann geht es von vorn mit der Reduzierten ClusterListe los reduce_cliques(global_cluster_list, file); } //################################################################################## void reduce_cliques2(network *net, bool only_double, long marker) { unsigned long size; ClusterList *c_cur, *largest_c=0; DLList_Iter*> c_iter; do { //wir suchen den groessten, nicht markierten Cluster size=0; c_cur=c_iter.First(net->cluster_list); while (!(c_iter.End())) { if ((c_cur->Size()>size) && (c_cur->Get_Marker()!=marker)) { size=c_cur->Size(); largest_c=c_cur; } c_cur=c_iter.Next(); } // printf("Groesster Cluster hat %u Elemente.\n",largest_c->Size()); //Schauen, ob es Teilmengen gibt, die ebenfalls gefunden wurden c_cur=c_iter.First(net->cluster_list); while (!(c_iter.End())) { if (((!only_double && (*c_cur<*largest_c)) || (*c_cur==*largest_c)) && (c_cur!=largest_c)) //alle echten Teilcluster von largest_c und die doppelten { net->cluster_list->fDelete(c_cur); while (c_cur->Get_Candidates()->Size()) c_cur->Get_Candidates()->Pop(); while (c_cur->Size()) c_cur->Pop(); // die knoten aber nicht loeschen!! delete c_cur; // nicht vergessen, die global geloeschte Clusterliste zu loeschen } c_cur=c_iter.Next(); } //Schliesslich markieren wir noch den eben gefundenen groessten Cluster largest_c->Set_Marker(marker); } while (size); } //################################################################################################## unsigned long iterate_nsf_hierarchy(NNode *parent, unsigned long depth,FILE *file) { NNode* next_node; unsigned long newdepth, maxdepth; bool first=true; DLList_Iter *iter; maxdepth=newdepth=depth; iter=new DLList_Iter; next_node=iter->First(parent->Get_Neighbours()); while (!(iter->End())) { if (next_node->Get_Marker()>parent->Get_Marker()) // wir gehen nach unten { if (first) fprintf(file,",("); // eine Neue Klammer auf if (first) fprintf(file,"%s",next_node->Get_Name()); // nur vor dem ersten kein Komma else fprintf(file,",%s",next_node->Get_Name()); // sonst immer mit Komma first=false; newdepth=iterate_nsf_hierarchy(next_node,depth+1, file); if (maxdepthNext(); } if (!first) fprintf(file,")"); //hat es ueberhaupt einen gegeben? //dann klamer zu! delete iter; return maxdepth; } //################################################################ void clear_all_markers(network *net) { DLList_Iter iter; NNode *n_cur; n_cur=iter.First(net->node_list); while (!iter.End()) { n_cur->Set_Marker(0); n_cur=iter.Next(); } } igraph/src/cocitation.c0000644000175100001440000006613013431000472014631 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_cocitation.h" #include "igraph_memory.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_interface.h" #include "config.h" #include int igraph_cocitation_real(const igraph_t *graph, igraph_matrix_t *res, igraph_vs_t vids, igraph_neimode_t mode, igraph_vector_t *weights); /** * \ingroup structural * \function igraph_cocitation * \brief Cocitation coupling. * * * Two vertices are cocited if there is another vertex citing both of * them. \ref igraph_cocitation() simply counts how many times two vertices are * cocited. * The cocitation score for each given vertex and all other vertices * in the graph will be calculated. * \param graph The graph object to analyze. * \param res Pointer to a matrix, the result of the calculation will * be stored here. The number of its rows is the same as the * number of vertex ids in \p vids, the number of * columns is the number of vertices in the graph. * \param vids The vertex ids of the vertices for which the * calculation will be done. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * * Time complexity: O(|V|d^2), |V| is * the number of vertices in the graph, * d is the (maximum) degree of * the vertices in the graph. * * \sa \ref igraph_bibcoupling() * * \example examples/simple/igraph_cocitation.c */ int igraph_cocitation(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids) { return igraph_cocitation_real(graph, res, vids, IGRAPH_OUT, 0); } /** * \ingroup structural * \function igraph_bibcoupling * \brief Bibliographic coupling. * * * The bibliographic coupling of two vertices is the number * of other vertices they both cite, \ref igraph_bibcoupling() calculates * this. * The bibliographic coupling score for each given vertex and all * other vertices in the graph will be calculated. * \param graph The graph object to analyze. * \param res Pointer to a matrix, the result of the calculation will * be stored here. The number of its rows is the same as the * number of vertex ids in \p vids, the number of * columns is the number of vertices in the graph. * \param vids The vertex ids of the vertices for which the * calculation will be done. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * * Time complexity: O(|V|d^2), * |V| is the number of vertices in * the graph, d is the (maximum) * degree of the vertices in the graph. * * \sa \ref igraph_cocitation() */ int igraph_bibcoupling(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids) { return igraph_cocitation_real(graph, res, vids, IGRAPH_IN, 0); } /** * \ingroup structural * \function igraph_similarity_inverse_log_weighted * \brief Vertex similarity based on the inverse logarithm of vertex degrees. * * * The inverse log-weighted similarity of two vertices is the number of * their common neighbors, weighted by the inverse logarithm of their degrees. * It is based on the assumption that two vertices should be considered * more similar if they share a low-degree common neighbor, since high-degree * common neighbors are more likely to appear even by pure chance. * * * Isolated vertices will have zero similarity to any other vertex. * Self-similarities are not calculated. * * * See the following paper for more details: Lada A. Adamic and Eytan Adar: * Friends and neighbors on the Web. Social Networks, 25(3):211-230, 2003. * * \param graph The graph object to analyze. * \param res Pointer to a matrix, the result of the calculation will * be stored here. The number of its rows is the same as the * number of vertex ids in \p vids, the number of * columns is the number of vertices in the graph. * \param vids The vertex ids of the vertices for which the * calculation will be done. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. Nodes * will be weighted according to their in-degree. * \cli IGRAPH_IN * the incoming edges will be considered for each node. Nodes * will be weighted according to their out-degree. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. Every node is weighted according to its undirected * degree. * \endclist * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * * Time complexity: O(|V|d^2), * |V| is the number of vertices in * the graph, d is the (maximum) * degree of the vertices in the graph. * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_inverse_log_weighted(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode) { igraph_vector_t weights; igraph_neimode_t mode0; long int i, no_of_nodes; switch (mode) { case IGRAPH_OUT: mode0 = IGRAPH_IN; break; case IGRAPH_IN: mode0 = IGRAPH_OUT; break; default: mode0 = IGRAPH_ALL; } no_of_nodes = igraph_vcount(graph); IGRAPH_VECTOR_INIT_FINALLY(&weights, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, &weights, igraph_vss_all(), mode0, 1)); for (i=0; i < no_of_nodes; i++) { if (VECTOR(weights)[i] > 1) VECTOR(weights)[i] = 1.0 / log(VECTOR(weights)[i]); } IGRAPH_CHECK(igraph_cocitation_real(graph, res, vids, mode0, &weights)); igraph_vector_destroy(&weights); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_cocitation_real(const igraph_t *graph, igraph_matrix_t *res, igraph_vs_t vids, igraph_neimode_t mode, igraph_vector_t *weights) { long int no_of_nodes=igraph_vcount(graph); long int no_of_vids; long int from, i, j, k, l, u, v; igraph_vector_t neis=IGRAPH_VECTOR_NULL; igraph_vector_t vid_reverse_index; igraph_vit_t vit; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); no_of_vids = IGRAPH_VIT_SIZE(vit); /* Create a mapping from vertex IDs to the row of the matrix where * the result for this vertex will appear */ IGRAPH_VECTOR_INIT_FINALLY(&vid_reverse_index, no_of_nodes); igraph_vector_fill(&vid_reverse_index, -1); for (IGRAPH_VIT_RESET(vit), i = 0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { v = IGRAPH_VIT_GET(vit); if (v < 0 || v >= no_of_nodes) IGRAPH_ERROR("invalid vertex ID in vertex selector", IGRAPH_EINVAL); VECTOR(vid_reverse_index)[v] = i; } IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_matrix_resize(res, no_of_vids, no_of_nodes)); igraph_matrix_null(res); /* The result */ for (from=0; from * The Jaccard similarity coefficient of two vertices is the number of common * neighbors divided by the number of vertices that are neighbors of at * least one of the two vertices being considered. This function calculates * the pairwise Jaccard similarities for some (or all) of the vertices. * * \param graph The graph object to analyze * \param res Pointer to a matrix, the result of the calculation will * be stored here. The number of its rows and columns is the same * as the number of vertex ids in \p vids. * \param vids The vertex ids of the vertices for which the * calculation will be done. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves in the neighbor * sets. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|V|^2 d), * |V| is the number of vertices in the vertex iterator given, d is the * (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_dice(), a measure very similar to the Jaccard * coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_jaccard(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops) { igraph_lazy_adjlist_t al; igraph_vit_t vit, vit2; long int i, j, k; long int len_union, len_intersection; igraph_vector_t *v1, *v2; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit2)); IGRAPH_FINALLY(igraph_vit_destroy, &vit2); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &al, mode, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &al); IGRAPH_CHECK(igraph_matrix_resize(res, IGRAPH_VIT_SIZE(vit), IGRAPH_VIT_SIZE(vit))); if (loops) { for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { i=IGRAPH_VIT_GET(vit); v1=igraph_lazy_adjlist_get(&al, (igraph_integer_t) i); if (!igraph_vector_binsearch(v1, i, &k)) igraph_vector_insert(v1, k, i); } } for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { MATRIX(*res, i, i) = 1.0; for (IGRAPH_VIT_RESET(vit2), j=0; !IGRAPH_VIT_END(vit2); IGRAPH_VIT_NEXT(vit2), j++) { if (j <= i) continue; v1=igraph_lazy_adjlist_get(&al, IGRAPH_VIT_GET(vit)); v2=igraph_lazy_adjlist_get(&al, IGRAPH_VIT_GET(vit2)); igraph_i_neisets_intersect(v1, v2, &len_union, &len_intersection); if (len_union > 0) MATRIX(*res, i, j) = ((igraph_real_t)len_intersection)/len_union; else MATRIX(*res, i, j) = 0.0; MATRIX(*res, j, i) = MATRIX(*res, i, j); } } igraph_lazy_adjlist_destroy(&al); igraph_vit_destroy(&vit); igraph_vit_destroy(&vit2); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup structural * \function igraph_similarity_jaccard_pairs * \brief Jaccard similarity coefficient for given vertex pairs. * * * The Jaccard similarity coefficient of two vertices is the number of common * neighbors divided by the number of vertices that are neighbors of at * least one of the two vertices being considered. This function calculates * the pairwise Jaccard similarities for a list of vertex pairs. * * \param graph The graph object to analyze * \param res Pointer to a vector, the result of the calculation will * be stored here. The number of elements is the same as the number * of pairs in \p pairs. * \param pairs A vector that contains the pairs for which the similarity * will be calculated. Each pair is defined by two consecutive elements, * i.e. the first and second element of the vector specifies the first * pair, the third and fourth element specifies the second pair and so on. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves in the neighbor * sets. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(nd), n is the number of pairs in the given vector, d is * the (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_jaccard() to calculate the Jaccard similarity * between all pairs of a vertex set, or \ref igraph_similarity_dice() and * \ref igraph_similarity_dice_pairs() for a measure very similar to the * Jaccard coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_jaccard_pairs(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *pairs, igraph_neimode_t mode, igraph_bool_t loops) { igraph_lazy_adjlist_t al; long int i, j, k, u, v; long int len_union, len_intersection; igraph_vector_t *v1, *v2; igraph_bool_t *seen; k = igraph_vector_size(pairs); if (k % 2 != 0) IGRAPH_ERROR("number of elements in `pairs' must be even", IGRAPH_EINVAL); IGRAPH_CHECK(igraph_vector_resize(res, k/2)); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &al, mode, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &al); if (loops) { /* Add the loop edges */ i = igraph_vcount(graph); seen = igraph_Calloc(i, igraph_bool_t); if (seen == 0) IGRAPH_ERROR("cannot calculate Jaccard similarity", IGRAPH_ENOMEM); IGRAPH_FINALLY(free, seen); for (i = 0; i < k; i++) { j = (long int) VECTOR(*pairs)[i]; if (seen[j]) continue; seen[j] = 1; v1=igraph_lazy_adjlist_get(&al, (igraph_integer_t) j); if (!igraph_vector_binsearch(v1, j, &u)) igraph_vector_insert(v1, u, j); } free(seen); IGRAPH_FINALLY_CLEAN(1); } for (i = 0, j = 0; i < k; i += 2, j++) { u = (long int) VECTOR(*pairs)[i]; v = (long int) VECTOR(*pairs)[i+1]; if (u == v) { VECTOR(*res)[j] = 1.0; continue; } v1 = igraph_lazy_adjlist_get(&al, (igraph_integer_t) u); v2 = igraph_lazy_adjlist_get(&al, (igraph_integer_t) v); igraph_i_neisets_intersect(v1, v2, &len_union, &len_intersection); if (len_union > 0) VECTOR(*res)[j] = ((igraph_real_t)len_intersection) / len_union; else VECTOR(*res)[j] = 0.0; } igraph_lazy_adjlist_destroy(&al); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup structural * \function igraph_similarity_jaccard_es * \brief Jaccard similarity coefficient for a given edge selector. * * * The Jaccard similarity coefficient of two vertices is the number of common * neighbors divided by the number of vertices that are neighbors of at * least one of the two vertices being considered. This function calculates * the pairwise Jaccard similarities for the endpoints of edges in a given edge * selector. * * \param graph The graph object to analyze * \param res Pointer to a vector, the result of the calculation will * be stored here. The number of elements is the same as the number * of edges in \p es. * \param es An edge selector that specifies the edges to be included in the * result. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves in the neighbor * sets. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(nd), n is the number of edges in the edge selector, d is * the (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_jaccard() and \ref igraph_similarity_jaccard_pairs() * to calculate the Jaccard similarity between all pairs of a vertex set or * some selected vertex pairs, or \ref igraph_similarity_dice(), * \ref igraph_similarity_dice_pairs() and \ref igraph_similarity_dice_es() for a * measure very similar to the Jaccard coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_jaccard_es(const igraph_t *graph, igraph_vector_t *res, const igraph_es_t es, igraph_neimode_t mode, igraph_bool_t loops) { igraph_vector_t v; igraph_eit_t eit; IGRAPH_VECTOR_INIT_FINALLY(&v, 0); IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); while (!IGRAPH_EIT_END(eit)) { long int eid = IGRAPH_EIT_GET(eit); igraph_vector_push_back(&v, IGRAPH_FROM(graph, eid)); igraph_vector_push_back(&v, IGRAPH_TO(graph, eid)); IGRAPH_EIT_NEXT(eit); } igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); IGRAPH_CHECK(igraph_similarity_jaccard_pairs(graph, res, &v, mode, loops)); igraph_vector_destroy(&v); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \ingroup structural * \function igraph_similarity_dice * \brief Dice similarity coefficient. * * * The Dice similarity coefficient of two vertices is twice the number of common * neighbors divided by the sum of the degrees of the vertices. This function * calculates the pairwise Dice similarities for some (or all) of the vertices. * * \param graph The graph object to analyze * \param res Pointer to a matrix, the result of the calculation will * be stored here. The number of its rows and columns is the same * as the number of vertex ids in \p vids. * \param vids The vertex ids of the vertices for which the * calculation will be done. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves as their own * neighbors. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|V|^2 d), * |V| is the number of vertices in the vertex iterator given, d is the * (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_jaccard(), a measure very similar to the Dice * coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_dice(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops) { long int i, j, nr, nc; IGRAPH_CHECK(igraph_similarity_jaccard(graph, res, vids, mode, loops)); nr = igraph_matrix_nrow(res); nc = igraph_matrix_ncol(res); for (i = 0; i < nr; i++) { for (j = 0; j < nc; j++) { igraph_real_t x = MATRIX(*res, i, j); MATRIX(*res, i, j) = 2*x / (1+x); } } return IGRAPH_SUCCESS; } /** * \ingroup structural * \function igraph_similarity_dice_pairs * \brief Dice similarity coefficient for given vertex pairs. * * * The Dice similarity coefficient of two vertices is twice the number of common * neighbors divided by the sum of the degrees of the vertices. This function * calculates the pairwise Dice similarities for a list of vertex pairs. * * \param graph The graph object to analyze * \param res Pointer to a vector, the result of the calculation will * be stored here. The number of elements is the same as the number * of pairs in \p pairs. * \param pairs A vector that contains the pairs for which the similarity * will be calculated. Each pair is defined by two consecutive elements, * i.e. the first and second element of the vector specifies the first * pair, the third and fourth element specifies the second pair and so on. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves as their own * neighbors. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(nd), n is the number of pairs in the given vector, d is * the (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_dice() to calculate the Dice similarity * between all pairs of a vertex set, or \ref igraph_similarity_jaccard(), * \ref igraph_similarity_jaccard_pairs() and \ref igraph_similarity_jaccard_es() * for a measure very similar to the Dice coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_dice_pairs(const igraph_t *graph, igraph_vector_t *res, const igraph_vector_t *pairs, igraph_neimode_t mode, igraph_bool_t loops) { long int i, n; IGRAPH_CHECK(igraph_similarity_jaccard_pairs(graph, res, pairs, mode, loops)); n = igraph_vector_size(res); for (i = 0; i < n; i++) { igraph_real_t x = VECTOR(*res)[i]; VECTOR(*res)[i] = 2*x / (1+x); } return IGRAPH_SUCCESS; } /** * \ingroup structural * \function igraph_similarity_dice_es * \brief Dice similarity coefficient for a given edge selector. * * * The Dice similarity coefficient of two vertices is twice the number of common * neighbors divided by the sum of the degrees of the vertices. This function * calculates the pairwise Dice similarities for the endpoints of edges in a given * edge selector. * * \param graph The graph object to analyze * \param res Pointer to a vector, the result of the calculation will * be stored here. The number of elements is the same as the number * of edges in \p es. * \param es An edge selector that specifies the edges to be included in the * result. * \param mode The type of neighbors to be used for the calculation in * directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing edges will be considered for each node. * \cli IGRAPH_IN * the incoming edges will be considered for each node. * \cli IGRAPH_ALL * the directed graph is considered as an undirected one for the * computation. * \endclist * \param loops Whether to include the vertices themselves as their own * neighbors. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * invalid vertex id passed. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(nd), n is the number of pairs in the given vector, d is * the (maximum) degree of the vertices in the graph. * * \sa \ref igraph_similarity_dice() and \ref igraph_similarity_dice_pairs() * to calculate the Dice similarity between all pairs of a vertex set or * some selected vertex pairs, or \ref igraph_similarity_jaccard(), * \ref igraph_similarity_jaccard_pairs() and \ref igraph_similarity_jaccard_es() * for a measure very similar to the Dice coefficient * * \example examples/simple/igraph_similarity.c */ int igraph_similarity_dice_es(const igraph_t *graph, igraph_vector_t *res, const igraph_es_t es, igraph_neimode_t mode, igraph_bool_t loops) { long int i, n; IGRAPH_CHECK(igraph_similarity_jaccard_es(graph, res, es, mode, loops)); n = igraph_vector_size(res); for (i = 0; i < n; i++) { igraph_real_t x = VECTOR(*res)[i]; VECTOR(*res)[i] = 2*x / (1+x); } return IGRAPH_SUCCESS; } igraph/src/gengraph_qsort.h0000644000175100001440000002467413431000472015534 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef QSORT_H #define QSORT_H #include #include #ifndef register #define register #endif namespace gengraph { //___________________________________________________________________________ // check if every element is zero inline bool check_zero(int *mem, int n) { for(int *v = mem+n; v!=mem; ) if(*(--v)!=0) return false; return true; } //___________________________________________________________________________ // Sort simple integer arrays in ASCENDING order //___________________________________________________________________________ inline int med3(int a, int b, int c) { if(atmp) { *w = *(w-1); w--; } *w = tmp; } } inline int partitionne(int *v, int t, int p) { int i=0; int j=t-1; while(ip) j--; if(i>1], v[(t>>2)+2], v[t-(t>>1)-2])); qsort(v,x); qsort(v+x,t-x); } } inline int qsort_median(int *v, int t, int pos) { if(t<10) { isort(v,t); return v[pos]; } int x = partitionne(v, t, med3(v[t>>1], v[(t>>2)+2], v[t-(t>>1)-2])); if(postmp) { *w = *(w-1); w--; } *w = tmp; } } inline int partitionne(double *v, int t, double p) { int i=0; int j=t-1; while(ip) j--; if(i>1], v[(t>>2)+2], v[t-(t>>1)-2])); qsort(v,x); qsort(v+x,t-x); } } inline double qsort_median(double *v, int t, int pos) { if(t<10) { isort(v,t); return v[pos]; } int x = partitionne(v, t, med3(v[t>>1], v[(t>>2)+2], v[t-(t>>1)-2])); if(pos0 && tmp>1]], mem[v[(t>>2)+3]], mem[v[t-(t>>1)-3]]); int i=0; int j=t-1; while(ip) j--; if(imx) mx=x; if(x0) return b; else return (ca>0) ? c : a; } else { if(cb<0) return b; else return (ca<0) ? c : a; } } } // Lexicographic sort inline void lex_isort(int **l, int *v, int t, int s) { if(t<2) return; for(int i=1; i>1]], l[v[(t>>2)+2]], l[v[t-(t>>1)-2]], s); int i=0; int j=t-1; // printf("pivot = %d\n",p); while(i0) j--; if(ikey[b]) return 1; else { int cmp=lex_comp_indirect(key,neigh[a],neigh[b],qsort_min(degs[a],degs[b])); if(cmp==0) { if(degs[a]>degs[b]) return -1; if(degs[a]0) return b; else return (ca>0) ? c : a; } else { if(cb<0) return b; else return (ca<0) ? c : a; } } } // Sort integer arrays in ASCENDING order inline void mix_isort_indirect(int *key, int *v, int t, int **neigh, int *degs) { if(t<2) return; for(int i=1; i>1], v[(t>>2)+2], v[t-(t>>1)-2], neigh, degs); int i=0; int j=t-1; // printf("pivot = %d\n",p); while(i0) j--; if(i * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * $Id: bignum.c,v 1.17 2005/07/23 02:55:53 pullmoll Exp $ ******************************************************************************/ #include #include "bignum.h" #include "config.h" #include "math.h" #include "igraph_error.h" #ifndef ASM_X86 #ifdef X86 #define ASM_X86 1 #endif #endif /** * @brief Return hex representation of a big number * * Returns the hex representation of a[], * where a is a big number integer with nlimb limbs. * * @param a pointer to an array of limbs * @param nlimb number of limbs in the array * * @result string containing the hex representation of a */ const char *bn2x(limb_t *a, count_t nlimb) { static IGRAPH_THREAD_LOCAL count_t which = 0; static IGRAPH_THREAD_LOCAL char *xbuff[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; char *dst; count_t size; count_t n = nlimb; if (0 == n) return "0"; which = (which + 1) % 8; size = 8 * n + 1; if (NULL != xbuff[which]) free(xbuff[which]); dst = xbuff[which] = calloc(size, sizeof(char)); if (NULL == dst) return "memory error"; while (n-- > 0) { dst += snprintf(dst, size, "%08x", a[n]); size -= 8; } return xbuff[which]; } /** * @brief Return decimal representation of a big number * * Returns the decimal representation of a[], * where a is a big number integer with nlimb limbs. * * @param a pointer to an array of limbs * @param nlimb number of limbs in the array * * @result string containing the decimal representation of a */ const char *bn2d(limb_t *a, count_t nlimb) { static IGRAPH_THREAD_LOCAL count_t which = 0; static IGRAPH_THREAD_LOCAL char *dbuff[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; static IGRAPH_THREAD_LOCAL limb_t v[BN_MAXSIZE]; limb_t r; char *dst; count_t size; count_t n = bn_sizeof(a, nlimb); if (0 == n) return "0"; bn_copy(v, a, n); which = (which + 1) % 8; size = 12 * n + 1; if (NULL != dbuff[which]) free(dbuff[which]); dst = dbuff[which] = calloc(size, sizeof(char)); if (NULL == dst) return "memory error"; size--; while (0 != bn_cmp_limb(v, 0, n)) { r = bn_div_limb(v, v, 10, n); dst[--size] = '0' + (char) r; } return &dst[size]; } /** * @brief Return decimal representation of a big number pair * * Returns the decimal representation of a[].b[], * where a is a big number integer with alimb limbs, * and b is a multiprecision fixed fraction with blimb limbs. * * @param a pointer to an array of limbs * @param alimb number of limbs in the a array * @param b pointer to an array of limbs * @param blimb number of limbs in the b array * * @result string containing the decimal representation of a.b */ const char *bn2f(limb_t *a, count_t alimb, limb_t *b, count_t blimb) { static IGRAPH_THREAD_LOCAL count_t which = 0; static IGRAPH_THREAD_LOCAL char *dbuff[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; static IGRAPH_THREAD_LOCAL limb_t v[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t w[BN_MAXSIZE]; limb_t r; char *dst; count_t size; bn_copy(v, a, alimb); bn_copy(w, b, blimb); which = (which + 1) % 8; size = 12 * (alimb + blimb) + 1 + 1; if (NULL != dbuff[which]) free(dbuff[which]); dst = dbuff[which] = calloc(size, sizeof(char)); if (NULL == dst) return "memory error"; size = 12 * alimb; while (0 != bn_cmp_limb(w, 0, blimb) && size < 12 * (alimb + blimb)) { r = bn_mul_limb(w, w, 10, blimb); dst[size++] = '0' + (char) r; } size = 12 * alimb; dst[size] = '.'; while (0 != bn_cmp_limb(v, 0, alimb) && size > 0) { r = bn_div_limb(v, v, 10, alimb); dst[--size] = '0' + (char) r; } return &dst[size]; } /** * @brief Return binary representation of a big number * * Returns the binary representation of a[], * where a is a big number integer with nlimb limbs. * * @param a pointer to an array of limbs * @param nlimb number of limbs in the array * * @result string containing the binary representation of a */ const char *bn2b(limb_t *a, count_t nlimb) { static IGRAPH_THREAD_LOCAL count_t which = 0; static IGRAPH_THREAD_LOCAL char *bbuff[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; limb_t r; char *dst; count_t size; count_t n = bn_sizeof(a, nlimb); if (0 == n) return "0"; which = (which + 1) % 8; size = LIMBBITS * n + 1; if (NULL != bbuff[which]) free(bbuff[which]); dst = bbuff[which] = calloc(size, sizeof(char)); if (NULL == dst) return "memory error"; n = 0; size--; while (size-- > 0) { r = (a[n/LIMBBITS] >> (n%LIMBBITS)) & 1; n++; dst[size] = '0' + (char) r; } return &dst[size]; } /** * @brief Zero an array of limbs * * Sets a[] = 0 * where a is a big number integer of nlimb limbs. * * @param a pointer to an array of limbs * @param nlimb number of limbs in the array * */ void bn_zero(limb_t a[], count_t nlimb) { memset(a, 0, nlimb * sizeof(limb_t)); } /** * @brief Set an array of limbs to a single limb value * * Sets a[] = d * where a is a big number integer of nlimb limbs, * and d is a single limb * * @param a pointer to an array of limbs to set * @param d limb value to set a to * @param nlimb number of limbs in the array * */ void bn_limb(limb_t a[], limb_t d, count_t nlimb) { memset(a, 0, nlimb * sizeof(limb_t)); a[0] = d; } /** * @brief Copy an array of limbs * * Sets a[] = b[] * where a and b are a big number integers of nlimb limbs * * @param a pointer to an array of limbs (destination) * @param b pointer to an array of limbs (source) * @param nlimb number of limbs in the arrays */ void bn_copy(limb_t a[], limb_t b[], count_t nlimb) { memcpy(a, b, nlimb * sizeof(limb_t)); } /** * @brief Return significant size of a big number * * Returns size of significant limbs in a[] * i.e. searches for the first non-zero limb from * nlimb-1 downto 0. * * @param a pointer to an array of limbs (candidate) * @param nlimb number of limbs in the arrays * * @result number of significant limbs in a */ count_t bn_sizeof(limb_t a[], count_t nlimb) { while (nlimb-- > 0) if (0 != a[nlimb]) return ++nlimb; return 0; } /** * @brief Return sign of a bignum minus a limb * * Returns the sign of (a[] - b) * where a is a big number integer of nlimb limbs, * and b is a single limb + * @param a pointer to an array of limbs (minuend) * @param b a single limb (subtrahend) * @param nlimb number of limbs in the array a * * @result sign of the comparison: -1 ab */ int bn_cmp_limb(limb_t a[], limb_t b, count_t nlimb) { if (0 == nlimb) return 0; while (nlimb-- > 1) if (0 != a[nlimb]) return +1; if (a[0] < b) return -1; if (a[0] > b) return +1; return 0; } /** * @brief Return sign of bignum a minus bignum b * * Returns the sign of (a[] - b[]) * where a and b are a big number integers of nlimb limbs * * @param a pointer to an array of limbs (minuend) * @param b pointer to an array of limbs (subtrahend) * @param nlimb number of limbs in the arrays * * @result sign of the comparison: -1 ab */ int bn_cmp(limb_t a[], limb_t b[], count_t nlimb) { if (0 == nlimb) return 0; while (nlimb-- > 0) { if (a[nlimb] > b[nlimb]) return +1; /* GT */ if (a[nlimb] < b[nlimb]) return -1; /* LT */ } return 0; /* EQ */ } /** * @brief Single limb is even test * * Returns 1 if a is even, else 0 * where a is a single limb * * @param a a single limb * * @result zero if a is odd, 1 if a is even */ int sl_iseven(limb_t a) { return (a & 1) ? 0 : 1; } /** * @brief bignum is even test * * Returns 1 if a[] is even, else 0 * where a is a big number integer of nlimb limbs * Note: a zero limb big number integer is even! * * @param a pointer to an array of limbs * @param nlimb number of limbs in the arrays * * @result zero if a is odd, 1 if a is even */ int bn_iseven(limb_t *a, count_t nlimb) { if (0 == nlimb) return 1; return (a[0] & 1) ? 0 : 1; } /** * @brief Add a single limb to a bignum * * Computes w[] = u[] + v * where w, u are big number integers of nlimb lims each, * and v is a single limb. * Returns carry if the addition overflows. * * Ref: Derived from Knuth Algorithm A. * * @param w pointer to an array of limbs receiving result * @param u pointer to an array of limbs (addend 1) * @param v a single limb * @param nlimb number of limbs in the arrays w and u * * @result The carry status of the addition */ limb_t bn_add_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb) { limb_t carry; count_t j; /* Copy u to w, so we can bail out if no borrow is left */ if (w != u) bn_copy(w, u, nlimb); /* Add v to first limb of u */ w[0] += v; carry = (w[0] < v ? 1 : 0); /* Add carry to subsequent limbs */ for (j = 1; 0 != carry && j < nlimb; j++) { w[j] += carry; carry = (w[j] < carry ? 1 : 0); } return carry; } /** * @brief Subtract a single limb from a bignum * * Computes w[] = u[] - v * where w, u are big number integers of nlimb limbs each, * and v is a single limb. * Returns borrow (0 if u >= v, or 1 if v > u). * * Ref: Derived from Knuth Algorithm S. * * @param w pointer to an array of limbs receiving the result * @param u pointer to an array of limbs (minuend) * @param v single limb (subtrahend) * @param nlimb number of limbs in the arrays * * @result borrow of the subtraction (0 if u >= v, 1 if u < v) */ limb_t bn_sub_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb) { limb_t borrow; count_t j; /* Copy u to w, so we can bail out if no borrow is left */ if (w != u) bn_copy(w, u, nlimb); /* Subtract v from first limb of u */ w[0] -= v; borrow = (w[0] > ~v ? 1 : 0); /* Subtract borrow from subsequent limbs */ for (j = 1; 0 != borrow && j < nlimb; j++) { w[j] -= borrow; borrow = (w[j] > ~borrow ? 1 : 0); } return borrow; } /** * @brief Divide a bignum by a single limb * * Computes quotient q[] = u[] / v * and returns remainder r = u[] % v * where q, u are big number integers of nlimb limbs each, * and v is a single limb. * * Makes no assumptions about normalisation. * * Ref: Knuth Vol 2 Ch 4.3.1 Exercise 16 p625 * * @param q pointer to an array of limbs receiving the quotient * @param u pointer to an array of limbs (dividend) * @param v single limb (divisor) * @param nlimb number of limbs in the arrays * * @result single limb remainder of the division (modulo) */ limb_t bn_div_limb(limb_t q[], limb_t u[], limb_t v, count_t nlimb) { count_t j; limb_t t[2], r; count_t shift; if (0 == nlimb) return 0; if (0 == v) return LIMBMASK; /* Divide by zero error */ /* * Normalize first: * qequires high bit of V to be set, * so find most significant by shifting * until DIGMSB is set. */ for (shift = 0; 0 == (v & DIGMSB); shift++) v <<= 1; r = bn_shl(q, u, shift, nlimb); j = nlimb; while (j-- > 0) { t[0] = q[j]; t[1] = r; sl_div(&q[j], &r, t, v); } /* Unnormalize */ r >>= shift; return r; } /** * @brief Modulo a bignum by a single limb * * Computes remainder (modulo) r = u[] mod v * Computes r = u[] mod v * where u is a big number integer of nlimb * and r, v are single precision limbs * * Use remainder from divide function. * * @param u pointer to an array of limbs (dividend) * @param v single limb (divisor) * @param nlimb number of limbs in the arrays * * @result single limb remainder of the division (modulo) */ limb_t bn_mod_limb(limb_t u[], limb_t v, count_t nlimb) { static IGRAPH_THREAD_LOCAL limb_t q[2*BN_MAXSIZE]; limb_t r; r = bn_div_limb(q, u, v, nlimb); bn_zero(q, nlimb); return r; } /** * @brief Multiply a bignum by a single limb * * Computes product w[] = u[] * v * Returns overflow k * where w, u are big number integers of nlimb each * and v is a single limb * * @param w pointer to an array of limbs to receive the result * @param u pointer to an array of limbs (factor) * @param v single limb (other factor) * @param nlimb number of limbs in the arrays * * @result zero if no overflow, else overflow (value of w[nlimb]) */ limb_t bn_mul_limb(limb_t w[], limb_t u[], limb_t v, count_t nlimb) { limb_t t[2]; limb_t carry; count_t j; if (0 == v) { bn_zero(w, nlimb); return 0; } for (j = 0, carry = 0; j < nlimb; j++) { sl_mul(t, u[j], v); w[j] = t[0] + carry; carry = t[1] + (w[j] < carry ? 1 : 0); } return carry; } #if HAVE_U64 /** * @brief Computes quotient and remainder of 64 bit / 32 bit * * Computes quotient q = u[] / v, remainder r = u[] mod v * where u[] is a double limb. * * With native support for double limb division * * @param q pointer to the limb to receive the quotient * @param r pointer to the limb to receive the remainder * @param u pointer to an array of two limbs * @param v single limb divisor * * @result zero on success */ limb_t sl_div(limb_t *q, limb_t *r, limb_t u[2], limb_t v) { #if ASM_X86 limb_t qq; limb_t rr; if (0 == v) /* division by zero */ return LIMBMASK; asm volatile( "divl %4" : "=a"(qq), "=d"(rr) : "a"(u[0]), "d"(u[1]), "g"(v)); *q = qq; *r = rr; #else dlimb_t dd; if (0 == v) /* division by zero */ return LIMBMASK; dd = ((dlimb_t)u[1] << LIMBBITS) | u[0]; *q = (limb_t) (dd / v); *r = dd % v; #endif return 0; } #else #define B (HALFMASK + 1) /** * @brief Computes quotient and remainder of 64 bit / 32 bit * * Computes quotient q = u / v, remainder r = u mod v * where u is a double limb * and q, v, r are single precision limbs. * Returns high limb of quotient (max value is 1) * Assumes normalized such that v1 >= b/2 * where b is size of HALF_DIGIT * i.e. the most significant bit of v should be one * * In terms of half-limbs in Knuth notation: * (q2q1q0) = (u4u3u2u1u0) / (v1v0) * (r1r0) = (u4u3u2u1u0) % (v1v0) * for m = 2, n = 2 where u4 = 0 * * We set q = (q1q0) and return q2 as "overflow' * Returned q2 is either 0 or 1. * * @param q pointer to the limb to receive the quotient * @param r pointer to the limb to receive the remainder * @param u pointer to an array of two limbs * @param v single limb divisor * * @result zero on success */ limb_t sl_div(limb_t *q, limb_t *r, limb_t u[2], limb_t v) { limb_t quot; limb_t rem; limb_t ul; limb_t uh; limb_t p0; limb_t p1; limb_t v0; limb_t v1; limb_t u0; limb_t u1; limb_t u2; limb_t u3; limb_t borrow; limb_t q1; limb_t q2; limb_t s; limb_t t; /* Check for normalisation */ if (0 == (v & DIGMSB)) { *q = *r = 0; return LIMBMASK; } /* Split up into half-limbs */ v0 = LSH(v); v1 = MSH(v); u0 = LSH(u[0]); u1 = MSH(u[0]); u2 = LSH(u[1]); u3 = MSH(u[1]); /* Do three rounds of Knuth Algorithm D Vol 2 p272 */ /* * ROUND 1 calculate q2: * estimate quot = (u4u3)/v1 = 0 or 1, * then set (u4u3u2) -= quot*(v1v0) where u4 = 0. */ quot = u3 / v1; if (quot > 0) { rem = u3 - quot * v1; t = SHL(rem) | u2; if (quot * v0 > t) quot--; } uh = 0; /* (u4) */ ul = u[1]; /* (u3u2) */ if (quot > 0) { /* (u4u3u2) -= quot*(v1v0) where u4 = 0 */ p0 = quot * v0; p1 = quot * v1; s = p0 + SHL(p1); ul -= s; borrow = (ul > ~s ? 1 : 0); uh -= MSH(p1) - borrow; if (0 != MSH(uh)) { /* add back */ quot--; ul += v; uh = 0; } } q2 = quot; /* * ROUND 2 calculate q1: * estimate quot = (u3u2) / v1, * then set (u3u2u1) -= quot*(v1v0) */ t = ul; quot = t / v1; rem = t - quot * v1; /* Test on v0 */ t = SHL(rem) | u1; if (B == quot || (quot * v0) > t) { quot--; rem += v1; t = SHL(rem) | u1; if (rem < B && (quot * v0) > t) quot--; } /* * multiply and subtract: * (u3u2u1)' = (u3u2u1) - quot*(v1v0) */ uh = MSH(ul); /* (0u3) */ ul = SHL(ul) | u1; /* (u2u1) */ p0 = quot * v0; p1 = quot * v1; s = p0 + SHL(p1); ul -= s; borrow = (ul > ~s ? 1 : 0); uh -= MSH(p1) - borrow; if (0 != MSH(uh)) { /* add back v */ quot--; ul += v; uh = 0; } /* quotient q1 */ q1 = quot; /* * ROUND 3: * calculate q0; estimate quot = (u2u1) / v1, * then set (u2u1u0) -= quot(v1v0) */ t = ul; quot = t / v1; rem = t - quot * v1; /* Test on v0 */ t = SHL(rem) | u0; if (B == quot || (quot * v0) > t) { quot--; rem += v1; t = SHL(rem) | u0; if (rem < B && (quot * v0) > t) quot--; } /* * multiply and subtract: * (u2u1u0)" = (u2u1u0)' - quot(v1v0) */ uh = MSH(ul); /* (0u2) */ ul = SHL(ul) | u0; /* (u1u0) */ p0 = quot * v0; p1 = quot * v1; s = p0 + SHL(p1); ul -= s; borrow = (ul > ~s ? 1 : 0); uh -= MSH(p1) - borrow; if (0 != MSH(uh)) { /* add back v */ quot--; ul += v; uh = 0; } /* quotient q1q0 */ *q = SHL(q1) | LSH(quot); /* Remainder is in (u1u0) i.e. ul */ *r = ul; /* quotient q2 (overflow) is returned */ return q2; } #endif /* HAVE_U64 */ /** * @brief Return greatest common divisor of two single limbs * * Returns gcd(x, y) * * Ref: Schneier 2nd ed, p245 * * @param x single limb candidate #1 * @param y single limb candidate #2 * * @result return zero if x and y are zero, else gcd(x,y) */ limb_t sl_gcd(limb_t x, limb_t y) { limb_t g; if (x + y == 0) return 0; /* Error */ g = y; while (x > 0) { g = x; x = y % x; y = g; } return g; } /** * @brief Compute single limb exp = x^e mod m * * Computes exp = x^e mod m * Binary left-to-right method * * @param exp pointer to limb to receive result * @param x single limb x (base) * @param e single limb e (exponent) * @param m single limb m (modulus) * * @result zero on success (always!?) */ int sl_modexp(limb_t *exp, limb_t x, limb_t e, limb_t m) { limb_t mask; limb_t y; /* Temp variable */ /* Find most significant bit in e */ for (mask = DIGMSB; mask > 0; mask >>= 1) { if (e & mask) break; } y = x; for (mask >>= 1; mask > 0; mask >>= 1) { sl_modmul(&y, y, y, m); /* y = (y^2) % m */ if (e & mask) sl_modmul(&y, y, x, m); /* y = (y*x) % m*/ } *exp = y; return 0; } /** * @brief Compute single limb inverse inv = u^(-1) % v * * Computes inv = u^(-1) % v * Ref: Knuth Algorithm X Vol 2 p 342 * ignoring u2, v2, t2 and avoiding negative numbers * * @param inv pointer to limb to receive result * @param u single limb to inverse * @param v single limb modulus * * @result zero on success (always!?) */ int sl_modinv(limb_t *inv, limb_t u, limb_t v) { limb_t u1, u3, v1, v3, t1, t3, q, w; int iter = 1; /* Step X1. Initialize */ u1 = 1; u3 = u; v1 = 0; v3 = v; /* Step X2. */ while (v3 != 0) { /* Step X3. */ q = u3 / v3; /* Divide and */ t3 = u3 % v3; w = q * v1; /* "Subtract" */ t1 = u1 + w; /* Swap */ u1 = v1; v1 = t1; u3 = v3; v3 = t3; iter = -iter; } if (iter < 0) *inv = v - u1; else *inv = u1; return 0; } /** * @brief Compute single limb a = (x * y) % mod * * Computes a = (x * y) % m * * @param a pointer to single limb to receive result * @param x single limb factor 1 * @param y single limb factor 2 * @param m single limb modulus * * @result zero on success (always!?) */ int sl_modmul(limb_t *a, limb_t x, limb_t y, limb_t m) { static IGRAPH_THREAD_LOCAL limb_t pp[2]; /* pp[] = x * y */ sl_mul(pp, x, y); /* *a = pp[] % m */ *a = bn_mod_limb(pp, m, 2); /* Clean temp */ pp[0] = pp[1] = 0; return 0; } #if HAVE_U64 /** * @brief Compute double limb product of two single limbs * * Computes p[] = x * y * where p is two limbs (double precision) and x, y are single * limbs. Use double precision natively supported on this machine. * * @param p pointer to an array of two limbs receiving the result * @param x single limb factor #1 * @param y single limb factor #2 * * @result zero on success (always) */ int sl_mul(limb_t p[2], limb_t x, limb_t y) { dlimb_t dd; dd = (dlimb_t)x * y; p[0] = (limb_t)dd; p[1] = (limb_t)(dd >> 32); return 0; } #else /** * @brief Compute double limb product of two single limbs * * Computes p[] = x * y * Source: Arbitrary Precision Computation * http://numbers.computation.free.fr/Constants/constants.html * * The limbs x and y are split in halves and the four products * x1*y1, x0*y1, x1*y0 and x0*y0 are added shifting them to * their respective least significant bit position: * p[1] = x1*y1 + high(x0*y1 + x1*y0) + ch << 16 + cl * p[0] = x0*y0 + low(x0*y1 + x1*y0) << 16 * ch = carry from adding x0*y1 + x1*y0 * cl = carry from adding low(x0*y1 + x1*y0) << 16 to p[0] * * @param p pointer to an array of two limbs receiving the result * @param x single limb factor #1 * @param y single limb factor #2 * * @result zero on success (always) */ int sl_mul(limb_t p[2], limb_t x, limb_t y) { limb_t x0, y0, x1, y1; limb_t t, u, carry; /* * Split each x,y into two halves * x = x0 + B*x1 * y = y0 + B*y1 * where B = 2^16, half the limb size * Product is * xy = x0y0 + B(x0y1 + x1y0) + B^2(x1y1) */ x0 = LSH(x); x1 = MSH(x); y0 = LSH(y); y1 = MSH(y); /* Compute low part (w/o carry) */ p[0] = x0 * y0; /* middle part */ t = x0 * y1; u = x1 * y0; t += u; carry = (t < u ? 1 : 0); /* * The carry will go to high half of p[1], * and the high half of t will go into the * into low half of p[1] */ carry = SHL(carry) + MSH(t); /* add low half of t to high half of p[0] */ t = SHL(t); p[0] += t; if (p[0] < t) carry++; p[1] = x1 * y1 + carry; return 0; } #endif /* HAVE_U64 */ /** * @brief Compute division of big number by a "half digit" * * Computes q[] = u[] / v, also returns r = u[] % v * where q, a are big number integers of nlimb limbs each, * and d, r are single limbs * * Using bit-by-bit method from MSB to LSB, * so v must be <= HALFMASK * * According to "Principles in PGP by Phil Zimmermann" * * @param q pointer to an array of limbs to receive the result * @param u pointer to an array of limbs (dividend) * @param v single limb (actually half limb) divisor * @param nlimb number of limbs in the arrays * * @result returns remainder of the division */ limb_t bn_div_hdig(limb_t q[], limb_t u[], limb_t v, count_t nlimb) { limb_t mask = DIGMSB; limb_t r = 0; if (v > HALFMASK) { igraph_errorf("bn_div_hdig called with v:%x", __FILE__, __LINE__, (int) v); } if (0 == nlimb) return 0; if (0 == v) return 0; /* Divide by zero error */ /* Initialize quotient */ bn_zero(q, nlimb); /* Work from MSB to LSB */ while (nlimb > 0) { /* Multiply remainder by 2 */ r <<= 1; /* Look at current bit */ if (u[nlimb-1] & mask) r++; if (r >= v) { /* Remainder became greater than divisor */ r -= v; q[nlimb-1] |= mask; } /* next bit */ mask >>= 1; if (0 != mask) continue; /* next limb */ --nlimb; mask = DIGMSB; } return r; } /** * @brief Compute single limb remainder of bignum % single limb * * Computes r = u[] % v * where a is a big number integer of nlimb * and r, v are single limbs, using bit-by-bit * method from MSB to LSB. * * Ref: * Derived from principles in PGP by Phil Zimmermann * Note: * This method will only work until r <<= 1 overflows. * i.e. for d < DIGMSB, but we keep HALF_DIGIT * limit for safety, and also because we don't * have a 32nd bit. * * @param u pointer to big number to divide * @param v single limb (actually half limb) modulus * @param nlimb number of limbs in the array * * @result returns remainder of the division */ limb_t bn_mod_hdig(limb_t u[], limb_t v, count_t nlimb) { limb_t mask; limb_t r; if (0 == nlimb) return 0; if (0 == v) return 0; /* Divide by zero error */ if (v > HALFMASK) { igraph_errorf("bn_mod_hdig called with v:%x", __FILE__, __LINE__, (int) v); } /* Work from left to right */ mask = DIGMSB; r = 0; while (nlimb > 0) { /* Multiply remainder by 2 */ r <<= 1; /* Look at current bit */ if (u[nlimb-1] & mask) r++; if (r >= v) /* Remainder became greater than divisor */ r -= v; /* next bit */ mask >>= 1; if (0 != mask) continue; /* next limb */ --nlimb; mask = DIGMSB; } return r; } /** * @brief Addition of two bignum arrays * * Computes w[] = u[] + v[] * where w, u, v are big number integers of nlimb limbs each. * Returns carry, i.e. w[nlimb], as 0 or 1. * * Ref: Knuth Vol 2 Ch 4.3.1 p 266 Algorithm A. * * @param w pointer to array of limbs to receive the result * @param u pointer to array of limbs (addend #1) * @param v pointer to array of limbs (addend #2) * @param nlimb number of limbs in the arrays * * @result returns the carry, i.e. w[nlimb], as 0 or 1 */ limb_t bn_add(limb_t w[], limb_t u[], limb_t v[], count_t nlimb) { limb_t carry; count_t j; for (j = 0, carry = 0; j < nlimb; j++) { /* * add limbs w[j] = u[j] + v[j] + carry; * set carry = 1 if carry (overflow) occurs */ w[j] = u[j] + carry; carry = (w[j] < carry ? 1 : 0); w[j] = w[j] + v[j]; if (w[j] < v[j]) carry++; } /* w[n] = carry */ return carry; } /** * @brief Subtraction of two bignum arrays * * Calculates w[] = u[] - v[] where u[] >= v[] * w, u, v are big number integers of nlimb limbs each * Returns 0 if ok, or 1 if v was greater than u. * * Ref: Knuth Vol 2 Ch 4.3.1 p 267 Algorithm S. * * @param w pointer to array of limbs to receive the result * @param u pointer to array of limbs (minuend) * @param v pointer to array of limbs (subtrahend) * @param nlimb number of limbs in the arrays * * @result zero on success, 1 if v was greater than u */ limb_t bn_sub(limb_t w[], limb_t u[], limb_t v[], count_t nlimb) { limb_t borrow; count_t j; for (j = 0, borrow = 0; j < nlimb; j++) { /* * Subtract limbs w[j] = u[j] - v[j] - borrow; * set borrow = 1 if borrow occurs */ w[j] = u[j] - borrow; borrow = (w[j] > ~borrow ? 1 : 0); w[j] = w[j] - v[j]; if (w[j] > ~v[j]) borrow++; } /* borrow should be 0, if u >= v */ return borrow; } /** * @brief Product of two bignum arrays * * Computes product w[] = u[] * v[] * where u, v are big number integers of nlimb each * and w is a big number integer of 2*nlimb limbs. * * Ref: Knuth Vol 2 Ch 4.3.1 p 268 Algorithm M. * * @param w pointer to array of limbs to receive the result * @param u pointer to array of limbs (factor #1) * @param v pointer to array of limbs (factor #2) * @param nlimb number of limbs in the arrays * * @result zero on success (always!?) */ int bn_mul(limb_t w[], limb_t u[], limb_t v[], count_t nlimb) { limb_t t[2]; limb_t carry; count_t i, j, m, n; m = n = nlimb; /* zero result */ bn_zero(w, 2*nlimb); for (j = 0; j < n; j++) { /* zero multiplier? */ if (0 == v[j]) { w[j+m] = 0; continue; } /* Initialize i */ carry = 0; for (i = 0; i < m; i++) { /* * Multiply and add: * t = u[i] * v[j] + w[i+j] + carry */ sl_mul(t, u[i], v[j]); t[0] += carry; if (t[0] < carry) t[1]++; t[0] += w[i+j]; if (t[0] < w[i+j]) t[1]++; w[i+j] = t[0]; carry = t[1]; } w[j+m] = carry; } return 0; } /** * @brief Shift left a bignum by a number of bits (less than LIMBBITS) * * Computes a[] = b[] << x * Where a and b are big number integers of nlimb each. * The shift count must be less than LIMBBITS * * @param a pointer to array of limbs to receive the result * @param b pointer to array of limbs to shift left * @param x number of bits to shift (must be less than LIMBBITS) * @param nlimb number of limbs in the arrays * * @result returns a single limb "carry", i.e. bits that came out left */ limb_t bn_shl(limb_t a[], limb_t b[], count_t x, count_t nlimb) { count_t i, y; limb_t carry, temp; if (0 == nlimb) return 0; if (0 == x) { /* no shift at all */ if (a != b) bn_copy(a, b, nlimb); return 0; } /* check shift amount */ if (x >= LIMBBITS) { igraph_errorf("bn_shl() called with x >= %d", __FILE__, __LINE__, LIMBBITS); return 0; } y = LIMBBITS - x; carry = 0; for (i = 0; i < nlimb; i++) { temp = b[i] >> y; a[i] = (b[i] << x) | carry; carry = temp; } return carry; } /** * @brief Shift right a bignum by a number of bits (less than LIMBBITS) * * Computes a[] = b[] >> x * Where a and b are big number integers of nlimb each. * The shift count must be less than LIMBBITS * * @param a pointer to array of limbs to receive the result * @param b pointer to array of limbs to shift right * @param x number of bits to shift (must be less than LIMBBITS) * @param nlimb number of limbs in the arrays * * @result returns a single limb "carry", i.e. bits that came out right */ limb_t bn_shr(limb_t a[], limb_t b[], count_t x, count_t nlimb) { count_t i, y; limb_t carry, temp; if (0 == nlimb) return 0; if (0 == x) { /* no shift at all */ if (a != b) bn_copy(a, b, nlimb); return 0; } /* check shift amount */ if (x >= LIMBBITS) { igraph_errorf("bn_shr() called with x >= %d", __FILE__, __LINE__, LIMBBITS); } y = LIMBBITS - x; carry = 0; i = nlimb; while (i-- > 0) { temp = b[i] << y; a[i] = (b[i] >> x) | carry; carry = temp; } return carry; } /** * @brief Check a quotient for overflow * * Returns 1 if quot is too big, * i.e. if (quot * Vn-2) > (b.rem + Uj+n-2) * Returns 0 if ok * * @param quot quotient under test * @param rem remainder * @param * * @result zero on success */ static int quot_overflow(limb_t quot, limb_t rem, limb_t v, limb_t u) { limb_t t[2]; sl_mul(t, quot, v); if (t[1] < rem) return 0; if (t[1] > rem) return 1; if (t[0] > u) return 1; return 0; } /** * @brief Compute quotient and remainder of bignum division * * Computes quotient q[] = u[] / v[] * and remainder r[] = u[] % v[] * where q, r, u are big number integers of ulimb limbs, * and the divisor v of vlimb limbs. * * Ref: Knuth Vol 2 Ch 4.3.1 p 272 Algorithm D. * * @param q pointer to array of limbs to receive quotient * @param r pointer to array of limbs to receive remainder * @param u pointer to array of limbs (dividend) * @param ulimb number of limbs in the q, r, u arrays * @param v pointer to array of limbs (divisor) * @param vlimb number of limbs in the v array * * @result zero on success, LIMBASK on division by zero */ int bn_div(limb_t q[], limb_t r[], limb_t u[], limb_t v[], count_t ulimb, count_t vlimb) { static IGRAPH_THREAD_LOCAL limb_t qq[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t uu[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t vv[BN_MAXSIZE]; limb_t mask; limb_t overflow; limb_t quot; limb_t rem; limb_t t[2]; limb_t *ww; count_t n, m, i, j, shift; int ok, cmp; /* find size of v */ n = bn_sizeof(v, vlimb); /* Catch special cases */ if (0 == n) return (int) LIMBMASK; /* Error: divide by zero */ if (1 == n) { /* Use short division instead */ r[0] = bn_div_limb(q, u, v[0], ulimb); return 0; } /* find size of u */ m = bn_sizeof(u, ulimb); if (m < n) { /* v > u: just set q = 0 and r = u */ bn_zero(q, ulimb); bn_copy(r, u, ulimb); return 0; } if (m == n) { /* u and v are the same length: compare them */ cmp = bn_cmp(u, v, (unsigned int)n); if (0 == cmp) { /* v == u: set q = 1 and r = 0 */ bn_limb(q, 1, ulimb); bn_zero(r, ulimb); return 0; } if (cmp < 0) { /* v > u: set q = 0 and r = u */ bn_zero(q, ulimb); bn_copy(r, u, ulimb); return 0; } } /* m greater than or equal to n */ m -= n; /* clear quotient qq */ bn_zero(qq, ulimb); /* * Normalize v: requires high bit of v[n-1] to be set, * so find most significant bit, then shift left */ mask = DIGMSB; for (shift = 0; shift < LIMBBITS; shift++) { if (v[n-1] & mask) break; mask >>= 1; } /* normalize vv from v */ overflow = bn_shl(vv, v, shift, n); /* copy normalized dividend u into remainder uu */ overflow = bn_shl(uu, u, shift, n + m); /* new limb u[m+n] */ t[0] = overflow; j = m + 1; while (j-- > 0) { /* quot = (b * u[j+n] + u[j+n-1]) / v[n-1] */ ok = 0; /* This is Uj+n */ t[1] = t[0]; t[0] = uu[j+n-1]; overflow = sl_div(", &rem, t, vv[n-1]); if (overflow) { /* quot = b */ quot = LIMBMASK; rem = uu[j+n-1] + vv[n-1]; if (rem < vv[n-1]) ok = 1; } if (0 == ok && quot_overflow(quot, rem, vv[n-2], uu[j+n-2])) { /* quot * v[n-2] > b * rem + u[j+n-2] */ quot--; rem += vv[n-1]; if (rem >= vv[n-1]) if (quot_overflow(quot, rem, vv[n-2], uu[j+n-2])) quot--; } /* multiply and subtract vv[] * quot */ ww = &uu[j]; if (0 == quot) { overflow = 0; } else { /* quot is non zero */ limb_t tt[2]; limb_t borrow; for (i = 0, borrow = 0; i < n; i++) { sl_mul(tt, quot, vv[i]); ww[i] -= borrow; borrow = (ww[i] > ~borrow ? 1 : 0); ww[i] -= tt[0]; if (ww[i] > ~tt[0]) borrow++; borrow += tt[1]; } /* * w[n] is not in array w[0..n-1]: * subtract final borrow */ overflow = t[1] - borrow; } /* test for remainder */ if (overflow) { quot--; /* add back if mul/sub was negative */ overflow = bn_add(ww, ww, vv, n); } qq[j] = quot; /* u[j+n] for next round */ t[0] = uu[j+n-1]; } /* clear uu[] limbs from n to n+m */ for (j = n; j < m+n; j++) uu[j] = 0; /* denormalize remainder */ bn_shr(r, uu, shift, n); /* copy quotient */ bn_copy(q, qq, n + m); /* clear temps */ bn_zero(qq, n); bn_zero(uu, n); bn_zero(vv, n); return 0; } /** * @brief Compute remainder of bignum division (modulo) * * Calculates r[] = u[] % v[] * where r, v are big number integers of length vlimb * and u is a big number integer of length ulimb. * r may overlap v. * * Note that r here is only vlimb long, * whereas in bn_div it is ulimb long. * * Use remainder from bn_div function. * * @param r pointer to array of limbs to receive remainder * @param u pointer to array of limbs (dividend) * @param ulimb number of limbs in the u array * @param v pointer to array of limbs (divisor) * @param vlimb number of limbs in the r and v array * * @result zero on success, LIMBASK on division by zero */ limb_t bn_mod(limb_t r[], limb_t u[], count_t ulimb, limb_t v[], count_t vlimb) { static IGRAPH_THREAD_LOCAL limb_t qq[2*BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t rr[2*BN_MAXSIZE]; limb_t d0; /* rr[] = u[] % v[n] */ d0 = (limb_t) bn_div(qq, rr, u, v, ulimb, vlimb); /* copy vlimb limbs of remainder */ bn_copy(r, rr, vlimb); /* zero temps */ bn_zero(rr, ulimb); bn_zero(qq, ulimb); return d0; } /** * @brief Compute greatest common divisor * * Computes g = gcd(x, y) * Reference: Schneier * * @param g pointer to array of limbs to receive the gcd * @param x pointer to array of limbs (candidate #1) * @param y pointer to array of limbs (candidate #2) * @param nlimb number of limbs in the arrays * * @result zero on succes (always) */ int bn_gcd(limb_t g[], limb_t x[], limb_t y[], count_t nlimb) { static IGRAPH_THREAD_LOCAL limb_t yy[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t xx[BN_MAXSIZE]; bn_copy(xx, x, nlimb); bn_copy(yy, y, nlimb); /* g = y */ bn_copy(g, yy, nlimb); /* while (x > 0) { */ while (0 != bn_cmp_limb(xx, 0, nlimb)) { /* g = x */ bn_copy(g, xx, nlimb); /* x = y % x */ bn_mod(xx, yy, nlimb, xx, nlimb); /* y = g */ bn_copy(yy, g, nlimb); } bn_zero(xx, nlimb); bn_zero(yy, nlimb); /* gcd is left in g */ return 0; } /** * @brief Compute modular exponentiation of bignums * * Computes y[] = (x[]^e[]) % m[] * Binary MSB to LSB method * * @param y pointer to array of limbs to receive the result * @param x pointer to array of limbs (base) * @param e pointer to array of limbs (exponent) * @param m pointer to array of limbs (modulus) * @param nlimb number of limbs in the arrays * * @result zero on success, -1 on error (nlimb is zero) */ int bn_modexp(limb_t y[], limb_t x[], limb_t e[], limb_t m[], count_t nlimb) { limb_t mask; count_t n; if (nlimb == 0) return -1; /* Find second-most significant bit in e */ n = bn_sizeof(e, nlimb); for (mask = DIGMSB; 0 != mask; mask >>= 1) { if (e[n-1] & mask) break; } /* next bit, because we start off with y[] == x[] */ mask >>= 1; if (0 == mask) { mask = DIGMSB; n--; } /* y[] = x[] */ bn_copy(y, x, nlimb); while (n > 0) { /* y[] = (y[] ^ 2) % m[] */ bn_modmul(y, y, y, m, nlimb); if (e[n-1] & mask) /* y[] = (y[] * x[]) % m[] */ bn_modmul(y, y, x, m, nlimb); /* next bit */ mask >>= 1; if (0 == mask) { mask = DIGMSB; n--; } } return 0; } /** * @brief Compute modular product of two bignums * * Computes a[] = (x[] * y[]) % m[] * where a, x, y and m are big numbers of nlimb length * * @param a pointer to array of limbs to receive the result * @param x pointer to array of limbs (factor #1) * @param y pointer to array of limbs (factor #2) * @param m pointer to array of limbs (modulus) * @param nlimb number of limbs in the arrays * * @result zero on success, LIMBMASK if m was zero (division by zero) */ limb_t bn_modmul(limb_t a[], limb_t x[], limb_t y[], limb_t m[], count_t nlimb) { static IGRAPH_THREAD_LOCAL limb_t pp[2*BN_MAXSIZE]; limb_t d0; /* pp[] = x[] * y[] (NB: double size pp[]) */ bn_mul(pp, x, y, nlimb); /* a[] = pp[] % m[] */ d0 = bn_mod(a, pp, 2*nlimb, m, nlimb); /* zero temp */ bn_zero(pp, 2*nlimb); return d0; } /** * @brief Compute modular inverse * * Computes inv[] = u[]^(-1) % v[] * Ref: Knuth Algorithm X Vol 2 p 342 * ignoring u2, v2, t2 and avoiding negative numbers. * * @param inv pointer to array of limbs receiving the result * @param u pointer to array of limbs (candidate) * @param v pointer to array of limbs (modulus) * @param nlimb number of limbs in the arrays * * @result zero on success */ int bn_modinv(limb_t inv[], limb_t u[], limb_t v[], count_t nlimb) { /* Allocate temp variables */ static IGRAPH_THREAD_LOCAL limb_t u1[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t u3[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t v1[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t v3[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t t1[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t t3[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t q[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t w[2*BN_MAXSIZE]; int iter; /* Step X1. Initialize */ bn_limb(u1, 1, nlimb); /* u1 = 1 */ bn_limb(v1, 0, nlimb); /* v1 = 0 */ bn_copy(u3, u, nlimb); /* u3 = u */ bn_copy(v3, v, nlimb); /* v3 = v */ /* remember odd/even iterations */ iter = 1; /* Step X2. Loop while v3 != 0 */ while (0 != bn_cmp_limb(v3, 0, nlimb)) { /* Step X3. Divide and "Subtract" */ /* q = u3 / v3, t3 = u3 % v3 */ bn_div(q, t3, u3, v3, nlimb, nlimb); /* w = q * v1 */ bn_mul(w, q, v1, nlimb); /* t1 = u1 + w */ bn_add(t1, u1, w, nlimb); /* Swap u1 <= v1 <= t1 */ bn_copy(u1, v1, nlimb); bn_copy(v1, t1, nlimb); /* Swap u3 <= v3 <= t3 */ bn_copy(u3, v3, nlimb); bn_copy(v3, t3, nlimb); iter ^= 1; } if (iter) bn_copy(inv, u1, nlimb); /* inv = u1 */ else bn_sub(inv, v, u1, nlimb); /* inv = v - u1 */ /* clear temp vars */ bn_zero(u1, nlimb); bn_zero(v1, nlimb); bn_zero(t1, nlimb); bn_zero(u3, nlimb); bn_zero(v3, nlimb); bn_zero(t3, nlimb); bn_zero(q, nlimb); bn_zero(w, 2*nlimb); return 0; } /** * @brief Compute square root (and fraction) of a bignum * * Compute q[] = sqrt(u[]), * where q and u are big number integers of nlimb limbs * * Method according to sqrt.html of 2001-08-15: * Act on bytes from MSB to LSB, counting the number of times * that we can subtract consecutive odd numbers starting with * 1, 3, 5. Just uses add, subtract, shift and comparisons. * * The pointer r can be NULL if caller is not interested in * the (partial) fraction. * * @param q pointer to array of limbs to receive the result (integer) * @param r pointer to array of limbs to receive the result (fraction) * @param u pointer to array of limbs (square) * @param rlimb number of limbs in the q and r arrays * @param ulimb number of limbs in the u array * * @result zero on success */ int bn_sqrt(limb_t q[], limb_t r[], limb_t u[], count_t rlimb, count_t ulimb) { static IGRAPH_THREAD_LOCAL limb_t step[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t accu[BN_MAXSIZE]; static IGRAPH_THREAD_LOCAL limb_t w[2*BN_MAXSIZE]; limb_t d; count_t m, n; count_t shift; bn_zero(q, ulimb); bn_limb(step, 1, BN_MAXSIZE); bn_limb(accu, 0, BN_MAXSIZE); n = bn_sizeof(u, ulimb); /* determine first non-zero byte from MSB to LSB */ if (0 != (u[n-1] >> 24)) { shift = 32; } else if (0 != (u[n-1] >> 16)) { shift = 24; } else if (0 != (u[n-1] >> 8)) { shift = 16; } else { shift = 8; } m = 1; while (n-- > 0) { while (shift > 0) { /* shift accu one byte left */ bn_shl(accu, accu, 8, m+1); /* shift for next byte from u[] */ shift -= 8; accu[0] |= (u[n] >> shift) & 0xff; /* digit = 0 */ d = 0; /* subtract consecutive odd numbers step[] until overflow */ for (d = 0; bn_cmp(step, accu, m+1) <= 0; d++) { bn_sub(accu, accu, step, m+1); bn_add_limb(step, step, 2, m+1); } /* put digit into result */ bn_shl(q, q, 4, m); q[0] |= d; /* step[] = 2 * q[] * 16 + 1 */ bn_shl(step, q, 5, m+1); bn_add_limb(step, step, 1, m+1); } shift = 32; if (0 == (n & 1)) m++; } /* Caller does not want to know the fraction? */ if (NULL == r) return 0; /* nothing left to do if remainder is zero */ if (0 == bn_cmp_limb(accu, 0, ulimb)) { bn_zero(r, rlimb); return 0; } /* Start off with the integer part */ bn_zero(w, 2*BN_MAXSIZE); bn_copy(w, q, ulimb); n = rlimb * (LIMBBITS / 4); while (n-- > 0) { /* shift accu one byte left */ bn_shl(accu, accu, 8, rlimb); /* subtract consecutive odd numbers step[] until overflow */ for (d = 0; bn_cmp(step, accu, rlimb) <= 0; d++) { bn_sub(accu, accu, step, rlimb); bn_add_limb(step, step, 2, rlimb); } /* put digit into result */ bn_shl(w, w, 4, rlimb); w[0] |= d; /* step[] = 2 * w[] * 16 + 1 */ bn_shl(step, w, 5, rlimb); bn_add_limb(step, step, 1, rlimb); } /* copy remainder */ bn_copy(r, w, rlimb); return 0; } igraph/src/drl_graph_3d.cpp0000644000175100001440000006252313431000472015367 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This file contains the member definitions of the master class #include #include #include #include #include #include #include using namespace std; #include "drl_graph_3d.h" #include "igraph_random.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #ifdef MUSE_MPI #include #endif namespace drl3d { graph::graph(const igraph_t *igraph, const igraph_layout_drl_options_t *options, const igraph_vector_t *weights) { myid = 0; num_procs = 1; STAGE = 0; iterations = options->init_iterations; temperature = options->init_temperature; attraction = options->init_attraction; damping_mult = options->init_damping_mult; min_edges = 20; first_add = fine_first_add = true; fineDensity = false; // Brian's original Vx schedule liquid.iterations = options->liquid_iterations; liquid.temperature = options->liquid_temperature; liquid.attraction = options->liquid_attraction; liquid.damping_mult = options->liquid_damping_mult; liquid.time_elapsed = 0; expansion.iterations = options->expansion_iterations; expansion.temperature = options->expansion_temperature; expansion.attraction = options->expansion_attraction; expansion.damping_mult = options->expansion_damping_mult; expansion.time_elapsed = 0; cooldown.iterations = options->cooldown_iterations; cooldown.temperature = options->cooldown_temperature; cooldown.attraction = options->cooldown_attraction; cooldown.damping_mult = options->cooldown_damping_mult; cooldown.time_elapsed = 0; crunch.iterations = options->crunch_iterations; crunch.temperature = options->crunch_temperature; crunch.attraction = options->crunch_attraction; crunch.damping_mult = options->crunch_damping_mult; crunch.time_elapsed = 0; simmer.iterations = options->simmer_iterations; simmer.temperature = options->simmer_temperature; simmer.attraction = options->simmer_attraction; simmer.damping_mult = options->simmer_damping_mult; simmer.time_elapsed = 0; // scan .int file for node info highest_sim = 1.0; num_nodes=igraph_vcount(igraph); long int no_of_edges=igraph_ecount(igraph); for (long int i=0; i::iterator cat_iter; for ( cat_iter = id_catalog.begin(); cat_iter != id_catalog.end(); cat_iter++) { cat_iter->second = cat_iter->first; } // populate node positions and ids positions.reserve ( num_nodes ); for ( cat_iter = id_catalog.begin(); cat_iter != id_catalog.end(); cat_iter++ ) { positions.push_back ( Node( cat_iter->first ) ); } // read .int file for graph info long int node_1, node_2; double weight; for (long int i=0; i 0 ) real_fixed = true; else real_fixed = false; // calculate total expected iterations (for progress bar display) tot_expected_iterations = liquid.iterations + expansion.iterations + cooldown.iterations + crunch.iterations + simmer.iterations; /* // output edge_cutting parms (for debugging) cout << "Processor " << myid << ": " << "cut_length_end = CUT_END = " << cut_length_end << ", cut_length_start = " << cut_length_start << ", cut_rate = " << cut_rate << endl; */ // set random seed // srand ( rand_seed ); // Don't need this in igraph } void graph::init_parms(const igraph_layout_drl_options_t *options) { double rand_seed = 0.0; double real_in = -1.0; init_parms(rand_seed, options->edge_cut, real_in); } int graph::read_real ( const igraph_matrix_t *real_mat, const igraph_vector_bool_t *fixed) { long int n=igraph_matrix_nrow(real_mat); for (long int i=0; i 0 ) { density_server.Add ( positions[id_catalog[i]], fineDensity ); } } return 0; } /********************************************* * Function: ReCompute * * Description: Compute the graph locations * * Modified from original code by B. Wylie * ********************************************/ int graph::ReCompute( ) { // carryover from original VxOrd int MIN = 1; /* // output parameters (for debugging) cout << "ReCompute is using the following parameters: "<< endl; cout << "STAGE: " << STAGE << ", iter: " << iterations << ", temp = " << temperature << ", attract = " << attraction << ", damping_mult = " << damping_mult << ", min_edges = " << min_edges << ", cut_off_length = " << cut_off_length << ", fineDensity = " << fineDensity << endl; */ /* igraph progress report */ float progress = (tot_iterations * 100.0 / tot_expected_iterations); switch (STAGE) { case 0: if (iterations == 0) IGRAPH_PROGRESS("DrL layout (initialization stage)", progress, 0); else IGRAPH_PROGRESS("DrL layout (liquid stage)", progress, 0); break; case 1: IGRAPH_PROGRESS("DrL layout (expansion stage)", progress, 0); break; case 2: IGRAPH_PROGRESS("DrL layout (cooldown and cluster phase)", progress, 0); break; case 3: IGRAPH_PROGRESS("DrL layout (crunch phase)", progress, 0); break; case 5: IGRAPH_PROGRESS("DrL layout (simmer phase)", progress, 0); break; case 6: IGRAPH_PROGRESS("DrL layout (final phase)", 100.0, 0); break; default: IGRAPH_PROGRESS("DrL layout (unknown phase)", 0.0, 0); break; } /* Compute Energies for individual nodes */ update_nodes (); // check to see if we need to free fixed nodes tot_iterations++; if ( tot_iterations >= real_iterations ) real_fixed = false; // **************************************** // AUTOMATIC CONTROL SECTION // **************************************** // STAGE 0: LIQUID if (STAGE == 0) { if ( iterations == 0 ) { start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering liquid stage ..."; } if (iterations < liquid.iterations) { temperature = liquid.temperature; attraction = liquid.attraction; damping_mult = liquid.damping_mult; iterations++; // if ( myid == 0 ) // cout << "." << flush; } else { stop_time = time( NULL ); liquid.time_elapsed = liquid.time_elapsed + (stop_time - start_time); temperature = expansion.temperature; attraction = expansion.attraction; damping_mult = expansion.damping_mult; iterations = 0; // go to next stage STAGE = 1; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering expansion stage ..."; } } // STAGE 1: EXPANSION if (STAGE == 1) { if (iterations < expansion.iterations) { // Play with vars if (attraction > 1) attraction -= .05; if (min_edges > 12) min_edges -= .05; cut_off_length -= cut_rate; if (damping_mult > .1) damping_mult -= .005; iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); expansion.time_elapsed = expansion.time_elapsed + (stop_time - start_time); min_edges = 12; damping_mult = cooldown.damping_mult; STAGE = 2; attraction = cooldown.attraction; temperature = cooldown.temperature; iterations = 0; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering cool-down stage ..."; } } // STAGE 2: Cool down and cluster else if(STAGE==2) { if (iterations < cooldown.iterations) { // Reduce temperature if (temperature > 50) temperature -= 10; // Reduce cut length if (cut_off_length > cut_length_end) cut_off_length -= cut_rate*2; if (min_edges > MIN) min_edges -= .2; //min_edges = 99; iterations++; // if ( myid == 0 ) // cout << "." << flush; } else { stop_time = time( NULL ); cooldown.time_elapsed = cooldown.time_elapsed + (stop_time - start_time); cut_off_length = cut_length_end; temperature = crunch.temperature; damping_mult = crunch.damping_mult; min_edges = MIN; //min_edges = 99; // In other words: no more cutting STAGE = 3; iterations = 0; attraction = crunch.attraction; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering crunch stage ..."; } } // STAGE 3: Crunch else if(STAGE==3) { if (iterations < crunch.iterations) { iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); crunch.time_elapsed = crunch.time_elapsed + (stop_time - start_time); iterations = 0; temperature = simmer.temperature; attraction = simmer.attraction; damping_mult = simmer.damping_mult; min_edges = 99; fineDensity = true; STAGE = 5; start_time = time( NULL ); // if ( myid == 0 ) // cout << "Entering simmer stage ..."; } } // STAGE 5: Simmer else if( STAGE==5 ) { if (iterations < simmer.iterations) { if (temperature > 50) temperature -= 2; iterations++; // if ( myid == 0 ) cout << "." << flush; } else { stop_time = time( NULL ); simmer.time_elapsed = simmer.time_elapsed + (stop_time - start_time); STAGE = 6; // if ( myid == 0 ) // cout << "Layout calculation completed in " << // ( liquid.time_elapsed + expansion.time_elapsed + // cooldown.time_elapsed + crunch.time_elapsed + // simmer.time_elapsed ) // << " seconds (not including I/O)." // << endl; } } // STAGE 6: All Done! else if ( STAGE == 6) { /* // output parameters (for debugging) cout << "ReCompute is using the following parameters: "<< endl; cout << "STAGE: " << STAGE << ", iter: " << iterations << ", temp = " << temperature << ", attract = " << attraction << ", damping_mult = " << damping_mult << ", min_edges = " << min_edges << ", cut_off_length = " << cut_off_length << ", fineDensity = " << fineDensity << endl; */ return 0; } // **************************************** // END AUTOMATIC CONTROL SECTION // **************************************** // Still need more recomputation return 1; } // update_nodes -- this function will complete the primary node update // loop in layout's recompute routine. It follows exactly the same // sequence to ensure similarity of parallel layout to the standard layout void graph::update_nodes ( ) { vector node_indices; // node list of nodes currently being updated float old_positions[2*MAX_PROCS]; // positions before update float new_positions[2*MAX_PROCS]; // positions after update bool all_fixed; // check if all nodes are fixed // initial node list consists of 0,1,...,num_procs for ( int i = 0; i < num_procs; i++ ) node_indices.push_back( i ); // next we calculate the number of nodes there would be if the // num_nodes by num_procs schedule grid were perfectly square int square_num_nodes = (int)(num_procs + num_procs*floor ((float)(num_nodes-1)/(float)num_procs )); for ( int i = myid; i < square_num_nodes; i += num_procs ) { // get old positions get_positions ( node_indices, old_positions ); // default new position is old position get_positions ( node_indices, new_positions ); if ( i < num_nodes ) { // advance random sequence according to myid for ( int j = 0; j < 2*myid; j++ ) RNG_UNIF01(); // rand(); // calculate node energy possibilities if ( !(positions[i].fixed && real_fixed) ) update_node_pos ( i, old_positions, new_positions ); // advance random sequence for next iteration for ( unsigned int j = 2*myid; j < 2*(node_indices.size()-1); j++ ) RNG_UNIF01(); // rand(); } else { // advance random sequence according to use by // the other processors for ( unsigned int j = 0; j < 2*(node_indices.size()); j++ ) RNG_UNIF01(); //rand(); } // check if anything was actually updated (e.g. everything was fixed) all_fixed = true; for ( unsigned int j = 0; j < node_indices.size (); j++ ) if ( !(positions [ node_indices[j] ].fixed && real_fixed) ) all_fixed = false; // update positions across processors (if not all fixed) if ( !all_fixed ) { #ifdef MUSE_MPI MPI_Allgather ( &new_positions[2*myid], 2, MPI_FLOAT, new_positions, 2, MPI_FLOAT, MPI_COMM_WORLD ); #endif // update positions (old to new) update_density ( node_indices, old_positions, new_positions ); } /* if ( myid == 0 ) { // output node list (for debugging) for ( unsigned int j = 0; j < node_indices.size(); j++ ) cout << node_indices[j] << " "; cout << endl; } */ // compute node list for next update for ( unsigned int j = 0; j < node_indices.size(); j++ ) node_indices [j] += num_procs; while ( !node_indices.empty() && node_indices.back() >= num_nodes ) node_indices.pop_back ( ); } // update first_add and fine_first_add first_add = false; if ( fineDensity ) fine_first_add = false; } // The get_positions function takes the node_indices list // and returns the corresponding positions in an array. void graph::get_positions ( vector &node_indices, float return_positions[3*MAX_PROCS] ) { // fill positions for(unsigned int i=0; i < node_indices.size(); i++) { return_positions[3*i] = positions[ node_indices[i] ].x; return_positions[3*i+1] = positions[ node_indices[i] ].y; return_positions[3*i+2] = positions[ node_indices[i] ].z; } } // update_node_pos -- this subroutine does the actual work of computing // the new position of a given node. num_act_proc gives the number // of active processes at this level for use by the random number // generators. void graph::update_node_pos ( int node_ind, float old_positions[3*MAX_PROCS], float new_positions[3*MAX_PROCS] ) { float energies[2]; // node energies for possible positions float updated_pos[2][3]; // possible positions float pos_x, pos_y, pos_z; // old VxOrd parameter float jump_length = .010 * temperature; // subtract old node density_server.Subtract ( positions[node_ind], first_add, fine_first_add, fineDensity ); // compute node energy for old solution energies[0] = Compute_Node_Energy ( node_ind ); // move node to centroid position Solve_Analytic ( node_ind, pos_x, pos_y, pos_z ); positions[node_ind].x = updated_pos[0][0] = pos_x; positions[node_ind].y = updated_pos[0][1] = pos_y; positions[node_ind].z = updated_pos[0][2] = pos_z; /* // ouput random numbers (for debugging) int rand_0, rand_1; rand_0 = rand(); rand_1 = rand(); cout << myid << ": " << rand_0 << ", " << rand_1 << endl; */ // Do random method (RAND_MAX is C++ maximum random number) updated_pos[1][0] = updated_pos[0][0] + (.5 - RNG_UNIF01()) * jump_length; updated_pos[1][1] = updated_pos[0][1] + (.5 - RNG_UNIF01()) * jump_length; updated_pos[1][2] = updated_pos[0][2] + (.5 - RNG_UNIF01()) * jump_length; // compute node energy for random position positions[node_ind].x = updated_pos[1][0]; positions[node_ind].y = updated_pos[1][1]; positions[node_ind].z = updated_pos[1][2]; energies[1] = Compute_Node_Energy ( node_ind ); /* // output update possiblities (debugging): cout << node_ind << ": (" << updated_pos[0][0] << "," << updated_pos[0][1] << "), " << energies[0] << "; (" << updated_pos[1][0] << "," << updated_pos[1][1] << "), " << energies[1] << endl; */ // add back old position positions[node_ind].x = old_positions[3*myid]; positions[node_ind].y = old_positions[3*myid+1]; positions[node_ind].z = old_positions[3*myid+2]; if ( !fineDensity && !first_add ) density_server.Add ( positions[node_ind], fineDensity ); else if ( !fine_first_add ) density_server.Add ( positions[node_ind], fineDensity ); // choose updated node position with lowest energy if ( energies[0] < energies[1] ) { new_positions[3*myid] = updated_pos[0][0]; new_positions[3*myid+1] = updated_pos[0][1]; new_positions[3*myid+2] = updated_pos[0][2]; positions[node_ind].energy = energies[0]; } else { new_positions[3*myid] = updated_pos[1][0]; new_positions[3*myid+1] = updated_pos[1][1]; new_positions[3*myid+2] = updated_pos[1][2]; positions[node_ind].energy = energies[1]; } } // update_density takes a sequence of node_indices and their positions and // updates the positions by subtracting the old positions and adding the // new positions to the density grid. void graph::update_density ( vector &node_indices, float old_positions[3*MAX_PROCS], float new_positions[3*MAX_PROCS] ) { // go through each node and subtract old position from // density grid before adding new position for ( unsigned int i = 0; i < node_indices.size(); i++ ) { positions[node_indices[i]].x = old_positions[3*i]; positions[node_indices[i]].y = old_positions[3*i+1]; positions[node_indices[i]].z = old_positions[3*i+2]; density_server.Subtract ( positions[node_indices[i]], first_add, fine_first_add, fineDensity ); positions[node_indices[i]].x = new_positions[3*i]; positions[node_indices[i]].y = new_positions[3*i+1]; positions[node_indices[i]].z = new_positions[3*i+2]; density_server.Add ( positions[node_indices[i]], fineDensity ); } } /******************************************** * Function: Compute_Node_Energy * * Description: Compute the node energy * * This code has been modified from the * * original code by B. Wylie. * *********************************************/ float graph::Compute_Node_Energy( int node_ind ) { /* Want to expand 4th power range of attraction */ float attraction_factor = attraction*attraction* attraction*attraction*2e-2; map ::iterator EI; float x_dis,y_dis,z_dis; float energy_distance, weight; float node_energy=0; // Add up all connection energies for(EI = neighbors[node_ind].begin(); EI != neighbors[node_ind].end(); ++EI) { // Get edge weight weight = EI->second; // Compute x,y distance x_dis = positions[ node_ind ].x - positions[ EI->first ].x; y_dis = positions[ node_ind ].y - positions[ EI->first ].y; z_dis = positions[ node_ind ].z - positions[ EI->first ].z; // Energy Distance energy_distance = x_dis*x_dis + y_dis*y_dis + z_dis*z_dis; if (STAGE<2) energy_distance *= energy_distance; // In the liquid phase we want to discourage long link distances if (STAGE==0) energy_distance *= energy_distance; node_energy += weight * attraction_factor * energy_distance; } // output effect of density (debugging) //cout << "[before: " << node_energy; // add density node_energy += density_server.GetDensity ( positions[ node_ind ].x, positions[ node_ind ].y, positions[ node_ind ].z, fineDensity ); // after calling density server (debugging) //cout << ", after: " << node_energy << "]" << endl; // return computated energy return node_energy; } /********************************************* * Function: Solve_Analytic * * Description: Compute the node position * * This is a modified version of the function * * originally written by B. Wylie * *********************************************/ void graph::Solve_Analytic( int node_ind, float &pos_x, float &pos_y, float &pos_z) { map ::iterator EI; float total_weight = 0; float x_dis, y_dis, z_dis, x_cen=0, y_cen=0, z_cen=0; float x=0,y=0,z=0,dis; float damping,weight; // Sum up all connections for(EI = neighbors[node_ind].begin(); EI != neighbors[node_ind].end(); ++EI) { weight = EI->second; total_weight += weight; x += weight * positions[ EI->first ].x; y += weight * positions[ EI->first ].y; z += weight * positions[ EI->first ].z; } // Now set node position if (total_weight > 0) { // Compute centriod x_cen = x/total_weight; y_cen = y/total_weight; z_cen = z/total_weight; damping = 1.0 - damping_mult; pos_x = damping*positions[ node_ind ].x + (1.0-damping) * x_cen; pos_y = damping*positions[ node_ind ].y + (1.0-damping) * y_cen; pos_z = damping*positions[ node_ind ].z + (1.0-damping) * z_cen; } // No cut edge flag (?) if (min_edges == 99) return; // Don't cut at end of scale if ( CUT_END >= 39500 ) return; float num_connections = (float)sqrt((float)neighbors[node_ind].size()); float maxLength = 0; map::iterator maxIndex; // Go through nodes edges... cutting if necessary for(EI = maxIndex = neighbors[node_ind].begin(); EI !=neighbors[node_ind].end(); ++EI) { // Check for at least min edges if (neighbors[node_ind].size() < min_edges) continue; x_dis = x_cen - positions[ EI->first ].x; y_dis = y_cen - positions[ EI->first ].y; z_dis = z_cen - positions[ EI->first ].z; dis = x_dis*x_dis+y_dis*y_dis+z_dis*z_dis; dis *= num_connections; // Store maximum edge if (dis > maxLength) {maxLength = dis; maxIndex=EI;} } // If max length greater than cut_length then cut if (maxLength > cut_off_length) neighbors[ node_ind ].erase( maxIndex ); } // get_tot_energy adds up the energy for each node to give an estimate of the // quality of the minimization. float graph::get_tot_energy ( ) { float my_tot_energy, tot_energy; my_tot_energy = 0; for ( int i = myid; i < num_nodes; i += num_procs ) my_tot_energy += positions[i].energy; //vector::iterator i; //for ( i = positions.begin(); i != positions.end(); i++ ) // tot_energy += i->energy; #ifdef MUSE_MPI MPI_Reduce ( &my_tot_energy, &tot_energy, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD ); #else tot_energy = my_tot_energy; #endif return tot_energy; } int graph::draw_graph(igraph_matrix_t *res) { int count_iter=0; while (ReCompute()) { IGRAPH_ALLOW_INTERRUPTION(); count_iter++; } long int n=positions.size(); IGRAPH_CHECK(igraph_matrix_resize(res, n, 3)); for (long int i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // **************************************************************************************************** // *** COPYRIGHT NOTICE ******************************************************************************* // splittree_eq.h - a binary search tree data structure for storing dendrogram split frequencies // Copyright (C) 2006-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // **************************************************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science AND Santa Fe Institute // Created : 19 April 2006 // Modified : 19 May 2007 // : 20 May 2008 (cleaned up for public consumption) // // *********************************************************************** // // Data structure for storing the split frequences in the sampled // dendrograms. Data is stored efficiently as a red-black binary // search tree (this is a modified version of the rbtree.h file). // // *********************************************************************** #ifndef IGRAPH_HRG_SPLITTREE #define IGRAPH_HRG_SPLITTREE #include using namespace std; namespace fitHRG { // ******** Basic Structures ********************************************* #ifndef IGRAPH_HRG_SLIST #define IGRAPH_HRG_SLIST class slist { public: string x; // stored elementd in linked-list slist* next; // pointer to next elementd slist(): x(""), next(0) { } ~slist() { } }; #endif class keyValuePairSplit { public: string x; // elementsp split (string) double y; // stored weight (double) int c; // stored count (int) keyValuePairSplit* next; // linked-list pointer keyValuePairSplit(): x(""), y(0.0), c(0), next(0) { } ~keyValuePairSplit() { } }; // ******** Tree elementsp Class ***************************************** class elementsp { public: string split; // split represented as a string double weight; // total weight of this split int count; // number of observations of this split bool color; // F: BLACK, T: RED short int mark; // marker elementsp *parent; // pointer to parent node elementsp *left; // pointer for left subtree elementsp *right; // pointer for right subtree elementsp(): split(""), weight(0.0), count(0), color(false), mark(0), parent(0), left(0), right(0) { } ~elementsp() { } }; // ******** Red-Black Tree Class ***************************************** // This vector implementation is a red-black balanced binary tree data // structure. It provides find a stored elementsp in time O(log n), // find the maximum elementsp in time O(1), delete an elementsp in // time O(log n), and insert an elementsp in time O(log n). // // Note that the split="" is assumed to be a special value, and thus // you cannot insert such an item. Beware of this limitation. // class splittree { private: elementsp* root; // binary tree root elementsp* leaf; // all leaf nodes int support; // number of nodes in the tree double total_weight; // total weight stored int total_count; // total number of observations stored // left-rotation operator void rotateLeft(elementsp*); // right-rotation operator void rotateRight(elementsp*); // house-keeping after insertion void insertCleanup(elementsp*); // house-keeping after deletion void deleteCleanup(elementsp*); keyValuePairSplit* returnSubtreeAsList(elementsp*, keyValuePairSplit*); // delete subtree rooted at z void deleteSubTree(elementsp*); // returns minimum of subtree rooted at z elementsp* returnMinKey(elementsp*); // returns successor of z's key elementsp* returnSuccessor(elementsp*); public: // default constructor/destructor splittree(); ~splittree(); // returns value associated with searchKey double returnValue(const string); // returns T if searchKey found, and points foundNode at the // corresponding node elementsp* findItem(const string); // update total_count and total_weight void finishedThisRound(); // insert a new key with stored value bool insertItem(string, double); void clearTree(); // delete a node with given key void deleteItem(string); // delete the entire tree void deleteTree(); // return array of keys in tree string* returnArrayOfKeys(); // return list of keys in tree slist* returnListOfKeys(); // return the tree as a list of keyValuePairSplits keyValuePairSplit* returnTreeAsList(); // returns the maximum key in the tree keyValuePairSplit returnMaxKey(); // returns the minimum key in the tree keyValuePairSplit returnMinKey(); // returns number of items in tree int returnNodecount(); // returns list of splits with given number of Ms keyValuePairSplit* returnTheseSplits(const int); // returns sum of stored values double returnTotal(); }; } // namespace fitHRG #endif igraph/src/drl_graph_3d.h0000644000175100001440000001024413431000472015025 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // The graph class contains the methods necessary to draw the // graph. It calls on the density server class to obtain // position and density information #include "DensityGrid_3d.h" #include "igraph_layout.h" namespace drl3d { // layout schedule information struct layout_schedule { int iterations; float temperature; float attraction; float damping_mult; time_t time_elapsed; }; class graph { public: // Methods void init_parms ( int rand_seed, float edge_cut, float real_parm ); void init_parms ( const igraph_layout_drl_options_t *options ); int read_real ( const igraph_matrix_t *real_mat, const igraph_vector_bool_t *fixed); int draw_graph (igraph_matrix_t *res); float get_tot_energy ( ); // Con/Decon graph( const igraph_t *igraph, const igraph_layout_drl_options_t *options, const igraph_vector_t *weights); ~graph( ) { } private: // Methods int ReCompute ( ); void update_nodes ( ); float Compute_Node_Energy ( int node_ind ); void Solve_Analytic ( int node_ind, float &pos_x, float &pos_y, float &pos_z ); void get_positions ( vector &node_indices, float return_positions[3*MAX_PROCS] ); void update_density ( vector &node_indices, float old_positions[3*MAX_PROCS], float new_positions[3*MAX_PROCS] ); void update_node_pos ( int node_ind, float old_positions[3*MAX_PROCS], float new_positions[3*MAX_PROCS] ); // MPI information int myid, num_procs; // graph decomposition information int num_nodes; // number of nodes in graph float highest_sim; // highest sim for normalization map id_catalog; // id_catalog[file id] = internal id map > neighbors; // neighbors of nodes on this proc. // graph layout information vector positions; DensityGrid density_server; // original VxOrd information int STAGE, iterations; float temperature, attraction, damping_mult; float min_edges, CUT_END, cut_length_end, cut_off_length, cut_rate; bool first_add, fine_first_add, fineDensity; // scheduling variables layout_schedule liquid; layout_schedule expansion; layout_schedule cooldown; layout_schedule crunch; layout_schedule simmer; // timing statistics time_t start_time, stop_time; // online clustering information int real_iterations; // number of iterations to hold .real input fixed int tot_iterations; int tot_expected_iterations; // for progress bar bool real_fixed; }; } // namespace drl3d igraph/src/foreign-lgl-parser.y0000644000175100001440000001027713430770201016226 0ustar hornikusers/* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include "foreign-lgl-header.h" #include "foreign-lgl-parser.h" #define yyscan_t void* int igraph_lgl_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_lgl_yyerror(YYLTYPE* locp, igraph_i_lgl_parsedata_t *context, const char *s); char *igraph_lgl_yyget_text (yyscan_t yyscanner ); int igraph_lgl_yyget_leng (yyscan_t yyscanner ); igraph_real_t igraph_lgl_get_number(const char *str, long int len); #define scanner context->scanner %} %pure-parser %output="y.tab.c" %name-prefix="igraph_lgl_yy" %defines %locations %error-verbose %parse-param { igraph_i_lgl_parsedata_t* context } %lex-param { void *scanner } %union { long int edgenum; double weightnum; } %type edgeid %type weight %token ALNUM %token NEWLINE %token HASH %token ERROR %% input : /* empty */ | input NEWLINE | input vertex ; vertex : vertexdef edges ; vertexdef : HASH edgeid NEWLINE { context->actvertex=$2; } ; edges : /* empty */ | edges edge ; edge : edgeid NEWLINE { igraph_vector_push_back(context->vector, context->actvertex); igraph_vector_push_back(context->vector, $1); igraph_vector_push_back(context->weights, 0); } | edgeid weight NEWLINE { igraph_vector_push_back(context->vector, context->actvertex); igraph_vector_push_back(context->vector, $1); igraph_vector_push_back(context->weights, $2); context->has_weights = 1; } ; edgeid : ALNUM { igraph_trie_get2(context->trie, igraph_lgl_yyget_text(scanner), igraph_lgl_yyget_leng(scanner), &$$); }; weight : ALNUM { $$=igraph_lgl_get_number(igraph_lgl_yyget_text(scanner), igraph_lgl_yyget_leng(scanner)); } ; %% int igraph_lgl_yyerror(YYLTYPE* locp, igraph_i_lgl_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char), "Parse error in LGL file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_lgl_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } igraph/src/paths.c0000644000175100001440000001164313431000472013613 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "igraph_vector_ptr.h" #include "igraph_iterators.h" #include "igraph_adjlist.h" #include "igraph_stack.h" /** * \function igraph_get_all_simple_paths * List all simple paths from one source * * A path is simple, if its vertices are unique, no vertex * is visited more than once. * * * Note that potentially there are exponentially many * paths between two vertices of a graph, and you may * run out of memory when using this function, if your * graph is lattice-like. * * * This function currently ignored multiple and loop edges. * \param graph The input graph. * \param res Initialized integer vector, all paths are * returned here, separated by -1 markers. The paths * are included in arbitrary order, as they are found. * \param from The start vertex. * \param to The target vertices. * \param mode The type of the paths to consider, it is ignored * for undirectred graphs. * \return Error code. * * Time complexity: O(n!) in the worst case, n is the number of * vertices. */ int igraph_get_all_simple_paths(const igraph_t *graph, igraph_vector_int_t *res, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode) { igraph_integer_t no_nodes=igraph_vcount(graph); igraph_vit_t vit; igraph_bool_t toall=igraph_vs_is_all(&to); igraph_vector_char_t markto; igraph_lazy_adjlist_t adjlist; igraph_vector_int_t stack; igraph_vector_char_t added; igraph_vector_int_t nptr; int iteration; if (from < 0 || from >= no_nodes) { IGRAPH_ERROR("Invalid starting vertex", IGRAPH_EINVAL); } if (!toall) { igraph_vector_char_init(&markto, no_nodes); IGRAPH_FINALLY(igraph_vector_char_destroy, &markto); IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); for (; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { VECTOR(markto)[ IGRAPH_VIT_GET(vit) ] = 1; } igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); } IGRAPH_CHECK(igraph_vector_char_init(&added, no_nodes)); IGRAPH_FINALLY(igraph_vector_char_destroy, &added); IGRAPH_CHECK(igraph_vector_int_init(&stack, 100)); IGRAPH_FINALLY(igraph_vector_int_destroy, &stack); IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, mode, /*simplify=*/ 1)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_vector_int_init(&nptr, no_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &nptr); igraph_vector_int_clear(res); igraph_vector_int_clear(&stack); igraph_vector_int_push_back(&stack, from); VECTOR(added)[from] = 1; while (!igraph_vector_int_empty(&stack)) { int act=igraph_vector_int_tail(&stack); igraph_vector_t *neis=igraph_lazy_adjlist_get(&adjlist, act); int n=igraph_vector_size(neis); int *ptr=igraph_vector_int_e_ptr(&nptr, act); igraph_bool_t any; int nei; if (iteration == 0) { IGRAPH_ALLOW_INTERRUPTION(); } /* Search for a neighbor that was not yet visited */ any = 0; while (!any && (*ptr) = 10000) { iteration = 0; } } igraph_vector_int_destroy(&nptr); igraph_lazy_adjlist_destroy(&adjlist); igraph_vector_int_destroy(&stack); igraph_vector_char_destroy(&added); IGRAPH_FINALLY_CLEAN(4); if (!toall) { igraph_vector_char_destroy(&markto); IGRAPH_FINALLY_CLEAN(1); } return 0; } igraph/src/walktrap_heap.cpp0000644000175100001440000001410213431000472015647 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: heap.cpp //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #include "walktrap_heap.h" #include #include using namespace std; using namespace igraph::walktrap; void Neighbor_heap::move_up(int index) { while(H[index/2]->delta_sigma > H[index]->delta_sigma) { Neighbor* tmp = H[index/2]; H[index]->heap_index = index/2; H[index/2] = H[index]; tmp->heap_index = index; H[index] = tmp; index = index/2; } } void Neighbor_heap::move_down(int index) { while(true) { int min = index; if((2*index < size) && (H[2*index]->delta_sigma < H[min]->delta_sigma)) min = 2*index; if(2*index+1 < size && H[2*index+1]->delta_sigma < H[min]->delta_sigma) min = 2*index+1; if(min != index) { Neighbor* tmp = H[min]; H[index]->heap_index = min; H[min] = H[index]; tmp->heap_index = index; H[index] = tmp; index = min; } else break; } } Neighbor* Neighbor_heap::get_first() { if(size == 0) return 0; else return H[0]; } void Neighbor_heap::remove(Neighbor* N) { if(N->heap_index == -1 || size == 0) return; Neighbor* last_N = H[--size]; H[N->heap_index] = last_N; last_N->heap_index = N->heap_index; move_up(last_N->heap_index); move_down(last_N->heap_index); N->heap_index = -1; } void Neighbor_heap::add(Neighbor* N) { if(size >= max_size) return; N->heap_index = size++; H[N->heap_index] = N; move_up(N->heap_index); } void Neighbor_heap::update(Neighbor* N) { if(N->heap_index == -1) return; move_up(N->heap_index); move_down(N->heap_index); } long Neighbor_heap::memory() { return (sizeof(Neighbor_heap) + long(max_size)*sizeof(Neighbor*)); } Neighbor_heap::Neighbor_heap(int max_s) { max_size = max_s; size = 0; H = new Neighbor*[max_s]; } Neighbor_heap::~Neighbor_heap() { delete[] H; } bool Neighbor_heap::is_empty() { return (size == 0); } //################################################################# void Min_delta_sigma_heap::move_up(int index) { while(delta_sigma[H[index/2]] < delta_sigma[H[index]]) { int tmp = H[index/2]; I[H[index]] = index/2; H[index/2] = H[index]; I[tmp] = index; H[index] = tmp; index = index/2; } } void Min_delta_sigma_heap::move_down(int index) { while(true) { int max = index; if(2*index < size && delta_sigma[H[2*index]] > delta_sigma[H[max]]) max = 2*index; if(2*index+1 < size && delta_sigma[H[2*index+1]] > delta_sigma[H[max]]) max = 2*index+1; if(max != index) { int tmp = H[max]; I[H[index]] = max; H[max] = H[index]; I[tmp] = index; H[index] = tmp; index = max; } else break; } } int Min_delta_sigma_heap::get_max_community() { if(size == 0) return -1; else return H[0]; } void Min_delta_sigma_heap::remove_community(int community) { if(I[community] == -1 || size == 0) return; int last_community = H[--size]; H[I[community]] = last_community; I[last_community] = I[community]; move_up(I[last_community]); move_down(I[last_community]); I[community] = -1; } void Min_delta_sigma_heap::update(int community) { if(community < 0 || community >= max_size) return; if(I[community] == -1) { I[community] = size++; H[I[community]] = community; } move_up(I[community]); move_down(I[community]); } long Min_delta_sigma_heap::memory() { return (sizeof(Min_delta_sigma_heap) + long(max_size)*(2*sizeof(int) + sizeof(float))); } Min_delta_sigma_heap::Min_delta_sigma_heap(int max_s) { max_size = max_s; size = 0; H = new int[max_s]; I = new int[max_s]; delta_sigma = new float[max_s]; for(int i = 0; i < max_size; i++) { I[i] = -1; delta_sigma[i] = 1.; } } Min_delta_sigma_heap::~Min_delta_sigma_heap() { delete[] H; delete[] I; delete[] delta_sigma; } bool Min_delta_sigma_heap::is_empty() { return (size == 0); } igraph/src/dnaitr.f0000644000175100001440000007425313431000472013766 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdnaitr c c\Description: c Reverse communication interface for applying NP additional steps to c a K step nonsymmetric Arnoldi factorization. c c Input: OP*V_{k} - V_{k}*H = r_{k}*e_{k}^T c c with (V_{k}^T)*B*V_{k} = I, (V_{k}^T)*B*r_{k} = 0. c c Output: OP*V_{k+p} - V_{k+p}*H = r_{k+p}*e_{k+p}^T c c with (V_{k+p}^T)*B*V_{k+p} = I, (V_{k+p}^T)*B*r_{k+p} = 0. c c where OP and B are as in igraphdnaupd. The B-norm of r_{k+p} is also c computed and returned. c c\Usage: c call igraphdnaitr c ( IDO, BMAT, N, K, NP, NB, RESID, RNORM, V, LDV, H, LDH, c IPNTR, WORKD, INFO ) c c\Arguments c IDO Integer. (INPUT/OUTPUT) c Reverse communication flag. c ------------------------------------------------------------- c IDO = 0: first call to the reverse communication interface c IDO = -1: compute Y = OP * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y. c This is for the restart phase to force the new c starting vector into the range of OP. c IDO = 1: compute Y = OP * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y, c IPNTR(3) is the pointer into WORK for B * X. c IDO = 2: compute Y = B * X where c IPNTR(1) is the pointer into WORK for X, c IPNTR(2) is the pointer into WORK for Y. c IDO = 99: done c ------------------------------------------------------------- c When the routine is used in the "shift-and-invert" mode, the c vector B * Q is already available and do not need to be c recompute in forming OP * Q. c c BMAT Character*1. (INPUT) c BMAT specifies the type of the matrix B that defines the c semi-inner product for the operator OP. See igraphdnaupd. c B = 'I' -> standard eigenvalue problem A*x = lambda*x c B = 'G' -> generalized eigenvalue problem A*x = lambda*M**x c c N Integer. (INPUT) c Dimension of the eigenproblem. c c K Integer. (INPUT) c Current size of V and H. c c NP Integer. (INPUT) c Number of additional Arnoldi steps to take. c c NB Integer. (INPUT) c Blocksize to be used in the recurrence. c Only work for NB = 1 right now. The goal is to have a c program that implement both the block and non-block method. c c RESID Double precision array of length N. (INPUT/OUTPUT) c On INPUT: RESID contains the residual vector r_{k}. c On OUTPUT: RESID contains the residual vector r_{k+p}. c c RNORM Double precision scalar. (INPUT/OUTPUT) c B-norm of the starting residual on input. c B-norm of the updated residual r_{k+p} on output. c c V Double precision N by K+NP array. (INPUT/OUTPUT) c On INPUT: V contains the Arnoldi vectors in the first K c columns. c On OUTPUT: V contains the new NP Arnoldi vectors in the next c NP columns. The first K columns are unchanged. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (K+NP) by (K+NP) array. (INPUT/OUTPUT) c H is used to store the generated upper Hessenberg matrix. c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c IPNTR Integer array of length 3. (OUTPUT) c Pointer to mark the starting locations in the WORK for c vectors used by the Arnoldi iteration. c ------------------------------------------------------------- c IPNTR(1): pointer to the current operand vector X. c IPNTR(2): pointer to the current result vector Y. c IPNTR(3): pointer to the vector B * X when used in the c shift-and-invert mode. X is the current operand. c ------------------------------------------------------------- c c WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) c Distributed array to be used in the basic Arnoldi iteration c for reverse communication. The calling program should not c use WORKD as temporary workspace during the iteration !!!!!! c On input, WORKD(1:N) = B*RESID and is used to save some c computation at the first step. c c INFO Integer. (OUTPUT) c = 0: Normal exit. c > 0: Size of the spanning invariant subspace of OP found. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c c\Routines called: c igraphdgetv0 ARPACK routine to generate the initial vector. c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdmout ARPACK utility routine that prints matrices c igraphdvout ARPACK utility routine that prints vectors. c dlabad LAPACK routine that computes machine constants. c dlamch LAPACK routine that determines machine constants. c dlascl LAPACK routine for careful scaling of a matrix. c dlanhs LAPACK routine that computes various norms of a matrix. c dgemv Level 2 BLAS routine for matrix vector multiplication. c daxpy Level 1 BLAS that computes a vector triad. c dscal Level 1 BLAS that scales a vector. c dcopy Level 1 BLAS that copies one vector to another . c ddot Level 1 BLAS that computes the scalar product of two vectors. c dnrm2 Level 1 BLAS that computes the norm of a vector. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c xx/xx/92: Version ' 2.4' c c\SCCS Information: @(#) c FILE: naitr.F SID: 2.4 DATE OF SID: 8/27/96 RELEASE: 2 c c\Remarks c The algorithm implemented is: c c restart = .false. c Given V_{k} = [v_{1}, ..., v_{k}], r_{k}; c r_{k} contains the initial residual vector even for k = 0; c Also assume that rnorm = || B*r_{k} || and B*r_{k} are already c computed by the calling program. c c betaj = rnorm ; p_{k+1} = B*r_{k} ; c For j = k+1, ..., k+np Do c 1) if ( betaj < tol ) stop or restart depending on j. c ( At present tol is zero ) c if ( restart ) generate a new starting vector. c 2) v_{j} = r(j-1)/betaj; V_{j} = [V_{j-1}, v_{j}]; c p_{j} = p_{j}/betaj c 3) r_{j} = OP*v_{j} where OP is defined as in igraphdnaupd c For shift-invert mode p_{j} = B*v_{j} is already available. c wnorm = || OP*v_{j} || c 4) Compute the j-th step residual vector. c w_{j} = V_{j}^T * B * OP * v_{j} c r_{j} = OP*v_{j} - V_{j} * w_{j} c H(:,j) = w_{j}; c H(j,j-1) = rnorm c rnorm = || r_(j) || c If (rnorm > 0.717*wnorm) accept step and go back to 1) c 5) Re-orthogonalization step: c s = V_{j}'*B*r_{j} c r_{j} = r_{j} - V_{j}*s; rnorm1 = || r_{j} || c alphaj = alphaj + s_{j}; c 6) Iterative refinement step: c If (rnorm1 > 0.717*rnorm) then c rnorm = rnorm1 c accept step and go back to 1) c Else c rnorm = rnorm1 c If this is the first time in step 6), go to 5) c Else r_{j} lies in the span of V_{j} numerically. c Set r_{j} = 0 and rnorm = 0; go to 1) c EndIf c End Do c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdnaitr & (ido, bmat, n, k, np, nb, resid, rnorm, v, ldv, h, ldh, & ipntr, workd, info) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c character bmat*1 integer ido, info, k, ldh, ldv, n, nb, np Double precision & rnorm c c %-----------------% c | Array Arguments | c %-----------------% c integer ipntr(3) Double precision & h(ldh,k+np), resid(n), v(ldv,k+np), workd(3*n) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c logical first, orth1, orth2, rstart, step3, step4 integer ierr, i, infol, ipj, irj, ivj, iter, itry, j, msglvl, & jj Double precision & betaj, ovfl, temp1, rnorm1, smlnum, tst1, ulp, unfl, & wnorm save first, orth1, orth2, rstart, step3, step4, & ierr, ipj, irj, ivj, iter, itry, j, msglvl, ovfl, & betaj, rnorm1, smlnum, ulp, unfl, wnorm c c %-----------------------% c | Local Array Arguments | c %-----------------------% c Double precision & xtemp(2) c c %----------------------% c | External Subroutines | c %----------------------% c external daxpy, dcopy, dscal, dgemv, igraphdgetv0, dlabad, & igraphdvout, igraphdmout, igraphivout, igraphsecond c c %--------------------% c | External Functions | c %--------------------% c Double precision & ddot, dnrm2, dlanhs, dlamch external ddot, dnrm2, dlanhs, dlamch c c %---------------------% c | Intrinsic Functions | c %---------------------% c intrinsic abs, sqrt c c %-----------------% c | Data statements | c %-----------------% c data first / .true. / c c %-----------------------% c | Executable Statements | c %-----------------------% c if (first) then c c %-----------------------------------------% c | Set machine-dependent constants for the | c | the splitting and deflation criterion. | c | If norm(H) <= sqrt(OVFL), | c | overflow should not occur. | c | REFERENCE: LAPACK subroutine dlahqr | c %-----------------------------------------% c unfl = dlamch( 'safe minimum' ) ovfl = one / unfl call dlabad( unfl, ovfl ) ulp = dlamch( 'precision' ) smlnum = unfl*( n / ulp ) first = .false. end if c if (ido .eq. 0) then c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = mnaitr c c %------------------------------% c | Initial call to this routine | c %------------------------------% c info = 0 step3 = .false. step4 = .false. rstart = .false. orth1 = .false. orth2 = .false. j = k + 1 ipj = 1 irj = ipj + n ivj = irj + n end if c c %-------------------------------------------------% c | When in reverse communication mode one of: | c | STEP3, STEP4, ORTH1, ORTH2, RSTART | c | will be .true. when .... | c | STEP3: return from computing OP*v_{j}. | c | STEP4: return from computing B-norm of OP*v_{j} | c | ORTH1: return from computing B-norm of r_{j+1} | c | ORTH2: return from computing B-norm of | c | correction to the residual vector. | c | RSTART: return from OP computations needed by | c | igraphdgetv0. | c %-------------------------------------------------% c if (step3) go to 50 if (step4) go to 60 if (orth1) go to 70 if (orth2) go to 90 if (rstart) go to 30 c c %-----------------------------% c | Else this is the first step | c %-----------------------------% c c %--------------------------------------------------------------% c | | c | A R N O L D I I T E R A T I O N L O O P | c | | c | Note: B*r_{j-1} is already in WORKD(1:N)=WORKD(IPJ:IPJ+N-1) | c %--------------------------------------------------------------% 1000 continue c if (msglvl .gt. 1) then call igraphivout (logfil, 1, j, ndigit, & '_naitr: generating Arnoldi vector number') call igraphdvout (logfil, 1, rnorm, ndigit, & '_naitr: B-norm of the current residual is') end if c c %---------------------------------------------------% c | STEP 1: Check if the B norm of j-th residual | c | vector is zero. Equivalent to determing whether | c | an exact j-step Arnoldi factorization is present. | c %---------------------------------------------------% c betaj = rnorm if (rnorm .gt. zero) go to 40 c c %---------------------------------------------------% c | Invariant subspace found, generate a new starting | c | vector which is orthogonal to the current Arnoldi | c | basis and continue the iteration. | c %---------------------------------------------------% c if (msglvl .gt. 0) then call igraphivout (logfil, 1, j, ndigit, & '_naitr: ****** RESTART AT STEP ******') end if c c %---------------------------------------------% c | ITRY is the loop variable that controls the | c | maximum amount of times that a restart is | c | attempted. NRSTRT is used by stat.h | c %---------------------------------------------% c betaj = zero nrstrt = nrstrt + 1 itry = 1 20 continue rstart = .true. ido = 0 30 continue c c %--------------------------------------% c | If in reverse communication mode and | c | RSTART = .true. flow returns here. | c %--------------------------------------% c call igraphdgetv0 (ido, bmat, itry, .false., n, j, v, ldv, & resid, rnorm, ipntr, workd, ierr) if (ido .ne. 99) go to 9000 if (ierr .lt. 0) then itry = itry + 1 if (itry .le. 3) go to 20 c c %------------------------------------------------% c | Give up after several restart attempts. | c | Set INFO to the size of the invariant subspace | c | which spans OP and exit. | c %------------------------------------------------% c info = j - 1 call igraphsecond (t1) tnaitr = tnaitr + (t1 - t0) ido = 99 go to 9000 end if c 40 continue c c %---------------------------------------------------------% c | STEP 2: v_{j} = r_{j-1}/rnorm and p_{j} = p_{j}/rnorm | c | Note that p_{j} = B*r_{j-1}. In order to avoid overflow | c | when reciprocating a small RNORM, test against lower | c | machine bound. | c %---------------------------------------------------------% c call dcopy (n, resid, 1, v(1,j), 1) if (rnorm .ge. unfl) then temp1 = one / rnorm call dscal (n, temp1, v(1,j), 1) call dscal (n, temp1, workd(ipj), 1) else c c %-----------------------------------------% c | To scale both v_{j} and p_{j} carefully | c | use LAPACK routine SLASCL | c %-----------------------------------------% c call dlascl ('General', i, i, rnorm, one, n, 1, & v(1,j), n, infol) call dlascl ('General', i, i, rnorm, one, n, 1, & workd(ipj), n, infol) end if c c %------------------------------------------------------% c | STEP 3: r_{j} = OP*v_{j}; Note that p_{j} = B*v_{j} | c | Note that this is not quite yet r_{j}. See STEP 4 | c %------------------------------------------------------% c step3 = .true. nopx = nopx + 1 call igraphsecond (t2) call dcopy (n, v(1,j), 1, workd(ivj), 1) ipntr(1) = ivj ipntr(2) = irj ipntr(3) = ipj ido = 1 c c %-----------------------------------% c | Exit in order to compute OP*v_{j} | c %-----------------------------------% c go to 9000 50 continue c c %----------------------------------% c | Back from reverse communication; | c | WORKD(IRJ:IRJ+N-1) := OP*v_{j} | c | if step3 = .true. | c %----------------------------------% c call igraphsecond (t3) tmvopx = tmvopx + (t3 - t2) step3 = .false. c c %------------------------------------------% c | Put another copy of OP*v_{j} into RESID. | c %------------------------------------------% c call dcopy (n, workd(irj), 1, resid, 1) c c %---------------------------------------% c | STEP 4: Finish extending the Arnoldi | c | factorization to length j. | c %---------------------------------------% c call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 step4 = .true. ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %-------------------------------------% c | Exit in order to compute B*OP*v_{j} | c %-------------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd(ipj), 1) end if 60 continue c c %----------------------------------% c | Back from reverse communication; | c | WORKD(IPJ:IPJ+N-1) := B*OP*v_{j} | c | if step4 = .true. | c %----------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c step4 = .false. c c %-------------------------------------% c | The following is needed for STEP 5. | c | Compute the B-norm of OP*v_{j}. | c %-------------------------------------% c if (bmat .eq. 'G') then wnorm = ddot (n, resid, 1, workd(ipj), 1) wnorm = sqrt(abs(wnorm)) else if (bmat .eq. 'I') then wnorm = dnrm2(n, resid, 1) end if c c %-----------------------------------------% c | Compute the j-th residual corresponding | c | to the j step factorization. | c | Use Classical Gram Schmidt and compute: | c | w_{j} <- V_{j}^T * B * OP * v_{j} | c | r_{j} <- OP*v_{j} - V_{j} * w_{j} | c %-----------------------------------------% c c c %------------------------------------------% c | Compute the j Fourier coefficients w_{j} | c | WORKD(IPJ:IPJ+N-1) contains B*OP*v_{j}. | c %------------------------------------------% c call dgemv ('T', n, j, one, v, ldv, workd(ipj), 1, & zero, h(1,j), 1) c c %--------------------------------------% c | Orthogonalize r_{j} against V_{j}. | c | RESID contains OP*v_{j}. See STEP 3. | c %--------------------------------------% c call dgemv ('N', n, j, -one, v, ldv, h(1,j), 1, & one, resid, 1) c if (j .gt. 1) h(j,j-1) = betaj c call igraphsecond (t4) c orth1 = .true. c call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(irj), 1) ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %----------------------------------% c | Exit in order to compute B*r_{j} | c %----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd(ipj), 1) end if 70 continue c c %---------------------------------------------------% c | Back from reverse communication if ORTH1 = .true. | c | WORKD(IPJ:IPJ+N-1) := B*r_{j}. | c %---------------------------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c orth1 = .false. c c %------------------------------% c | Compute the B-norm of r_{j}. | c %------------------------------% c if (bmat .eq. 'G') then rnorm = ddot (n, resid, 1, workd(ipj), 1) rnorm = sqrt(abs(rnorm)) else if (bmat .eq. 'I') then rnorm = dnrm2(n, resid, 1) end if c c %-----------------------------------------------------------% c | STEP 5: Re-orthogonalization / Iterative refinement phase | c | Maximum NITER_ITREF tries. | c | | c | s = V_{j}^T * B * r_{j} | c | r_{j} = r_{j} - V_{j}*s | c | alphaj = alphaj + s_{j} | c | | c | The stopping criteria used for iterative refinement is | c | discussed in Parlett's book SEP, page 107 and in Gragg & | c | Reichel ACM TOMS paper; Algorithm 686, Dec. 1990. | c | Determine if we need to correct the residual. The goal is | c | to enforce ||v(:,1:j)^T * r_{j}|| .le. eps * || r_{j} || | c | The following test determines whether the sine of the | c | angle between OP*x and the computed residual is less | c | than or equal to 0.717. | c %-----------------------------------------------------------% c if (rnorm .gt. 0.717*wnorm) go to 100 iter = 0 nrorth = nrorth + 1 c c %---------------------------------------------------% c | Enter the Iterative refinement phase. If further | c | refinement is necessary, loop back here. The loop | c | variable is ITER. Perform a step of Classical | c | Gram-Schmidt using all the Arnoldi vectors V_{j} | c %---------------------------------------------------% c 80 continue c if (msglvl .gt. 2) then xtemp(1) = wnorm xtemp(2) = rnorm call igraphdvout (logfil, 2, xtemp, ndigit, & '_naitr: re-orthonalization; wnorm and rnorm are') call igraphdvout (logfil, j, h(1,j), ndigit, & '_naitr: j-th column of H') end if c c %----------------------------------------------------% c | Compute V_{j}^T * B * r_{j}. | c | WORKD(IRJ:IRJ+J-1) = v(:,1:J)'*WORKD(IPJ:IPJ+N-1). | c %----------------------------------------------------% c call dgemv ('T', n, j, one, v, ldv, workd(ipj), 1, & zero, workd(irj), 1) c c %---------------------------------------------% c | Compute the correction to the residual: | c | r_{j} = r_{j} - V_{j} * WORKD(IRJ:IRJ+J-1). | c | The correction to H is v(:,1:J)*H(1:J,1:J) | c | + v(:,1:J)*WORKD(IRJ:IRJ+J-1)*e'_j. | c %---------------------------------------------% c call dgemv ('N', n, j, -one, v, ldv, workd(irj), 1, & one, resid, 1) call daxpy (j, one, workd(irj), 1, h(1,j), 1) c orth2 = .true. call igraphsecond (t2) if (bmat .eq. 'G') then nbx = nbx + 1 call dcopy (n, resid, 1, workd(irj), 1) ipntr(1) = irj ipntr(2) = ipj ido = 2 c c %-----------------------------------% c | Exit in order to compute B*r_{j}. | c | r_{j} is the corrected residual. | c %-----------------------------------% c go to 9000 else if (bmat .eq. 'I') then call dcopy (n, resid, 1, workd(ipj), 1) end if 90 continue c c %---------------------------------------------------% c | Back from reverse communication if ORTH2 = .true. | c %---------------------------------------------------% c if (bmat .eq. 'G') then call igraphsecond (t3) tmvbx = tmvbx + (t3 - t2) end if c c %-----------------------------------------------------% c | Compute the B-norm of the corrected residual r_{j}. | c %-----------------------------------------------------% c if (bmat .eq. 'G') then rnorm1 = ddot (n, resid, 1, workd(ipj), 1) rnorm1 = sqrt(abs(rnorm1)) else if (bmat .eq. 'I') then rnorm1 = dnrm2(n, resid, 1) end if c if (msglvl .gt. 0 .and. iter .gt. 0) then call igraphivout (logfil, 1, j, ndigit, & '_naitr: Iterative refinement for Arnoldi residual') if (msglvl .gt. 2) then xtemp(1) = rnorm xtemp(2) = rnorm1 call igraphdvout (logfil, 2, xtemp, ndigit, & '_naitr: iterative refinement ; rnorm and rnorm1 are') end if end if c c %-----------------------------------------% c | Determine if we need to perform another | c | step of re-orthogonalization. | c %-----------------------------------------% c if (rnorm1 .gt. 0.717*rnorm) then c c %---------------------------------------% c | No need for further refinement. | c | The cosine of the angle between the | c | corrected residual vector and the old | c | residual vector is greater than 0.717 | c | In other words the corrected residual | c | and the old residual vector share an | c | angle of less than arcCOS(0.717) | c %---------------------------------------% c rnorm = rnorm1 c else c c %-------------------------------------------% c | Another step of iterative refinement step | c | is required. NITREF is used by stat.h | c %-------------------------------------------% c nitref = nitref + 1 rnorm = rnorm1 iter = iter + 1 if (iter .le. 1) go to 80 c c %-------------------------------------------------% c | Otherwise RESID is numerically in the span of V | c %-------------------------------------------------% c do 95 jj = 1, n resid(jj) = zero 95 continue rnorm = zero end if c c %----------------------------------------------% c | Branch here directly if iterative refinement | c | wasn't necessary or after at most NITER_REF | c | steps of iterative refinement. | c %----------------------------------------------% c 100 continue c rstart = .false. orth2 = .false. c call igraphsecond (t5) titref = titref + (t5 - t4) c c %------------------------------------% c | STEP 6: Update j = j+1; Continue | c %------------------------------------% c j = j + 1 if (j .gt. k+np) then call igraphsecond (t1) tnaitr = tnaitr + (t1 - t0) ido = 99 do 110 i = max(1,k), k+np-1 c c %--------------------------------------------% c | Check for splitting and deflation. | c | Use a standard test as in the QR algorithm | c | REFERENCE: LAPACK subroutine dlahqr | c %--------------------------------------------% c tst1 = abs( h( i, i ) ) + abs( h( i+1, i+1 ) ) if( tst1.eq.zero ) & tst1 = dlanhs( '1', k+np, h, ldh, workd(n+1) ) if( abs( h( i+1,i ) ).le.max( ulp*tst1, smlnum ) ) & h(i+1,i) = zero 110 continue c if (msglvl .gt. 2) then call igraphdmout (logfil, k+np, k+np, h, ldh, ndigit, & '_naitr: Final upper Hessenberg matrix H of order K+NP') end if c go to 9000 end if c c %--------------------------------------------------------% c | Loop back to extend the factorization by another step. | c %--------------------------------------------------------% c go to 1000 c c %---------------------------------------------------------------% c | | c | E N D O F M A I N I T E R A T I O N L O O P | c | | c %---------------------------------------------------------------% c 9000 continue return c c %---------------% c | End of igraphdnaitr | c %---------------% c end igraph/src/dqueue.pmt0000644000175100001440000002127513430770200014346 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \section igraph_dqueue * * This is the classic data type of the double ended queue. Most of * the time it is used if a First-In-First-Out (FIFO) behavior is * needed. See the operations below. * * * * \example examples/simple/dqueue.c * */ /** * \ingroup dqueue * \function igraph_dqueue_init * \brief Initialize a double ended queue (deque). * * The queue will be always empty. * \param q Pointer to an uninitialized deque. * \param size How many elements to allocate memory for. * \return Error code. * * Time complexity: O(\p size). */ int FUNCTION(igraph_dqueue,init) (TYPE(igraph_dqueue)* q, long int size) { assert(q != 0); if (size <= 0 ) { size=1; } q->stor_begin=igraph_Calloc(size, BASE); if (q->stor_begin==0) { IGRAPH_ERROR("dqueue init failed", IGRAPH_ENOMEM); } q->stor_end=q->stor_begin + size; q->begin=q->stor_begin; q->end=NULL; return 0; } /** * \ingroup dqueue * \function igraph_dqueue_destroy * \brief Destroy a double ended queue. * * \param q The queue to destroy * * Time complexity: O(1). */ void FUNCTION(igraph_dqueue,destroy) (TYPE(igraph_dqueue)* q) { assert(q != 0); if (q->stor_begin != 0) { igraph_Free(q->stor_begin); q->stor_begin=0; } } /** * \ingroup dqueue * \function igraph_dqueue_empty * \brief Decide whether the queue is empty. * * \param q The queue. * \return Boolean, \c TRUE if \p q contains at least one element, \c * FALSE otherwise. * * Time complexity: O(1). */ igraph_bool_t FUNCTION(igraph_dqueue,empty) (const TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); return q->end == NULL; } /** * \ingroup dqueue * \function igraph_dqueue_clear * \brief Remove all elements from the queue. * * \param q The queue * * Time complexity: O(1). */ void FUNCTION(igraph_dqueue,clear) (TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); q->begin=q->stor_begin; q->end=NULL; } /** * \ingroup dqueue * \function igraph_dqueue_full * \brief Check whether the queue is full. * * If a queue is full the next igraph_dqueue_push() operation will allocate * more memory. * \param q The queue. * \return \c TRUE if \p q is full, \c FALSE otherwise. * * Time complecity: O(1). */ igraph_bool_t FUNCTION(igraph_dqueue,full) (TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); return q->begin == q->end; } /** * \ingroup dqueue * \function igraph_dqueue_size * \brief Number of elements in the queue. * * \param q The queue. * \return Integer, the number of elements currently in the queue. * * Time complexity: O(1). */ long int FUNCTION(igraph_dqueue,size) (const TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); if (q->end==NULL) { return 0; } else if (q->begin < q->end) { return q->end - q->begin; } else { return q->stor_end - q->begin + q->end - q->stor_begin; } } /** * \ingroup dqueue * \function igraph_dqueue_head * \brief Head of the queue. * * The queue must contain at least one element. * \param q The queue. * \return The first element in the queue. * * Time complexity: O(1). */ BASE FUNCTION(igraph_dqueue,head) (const TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); return *(q->begin); } /** * \ingroup dqueue * \function igraph_dqueue_back * \brief Tail of the queue. * * The queue must contain at least one element. * \param q The queue. * \return The last element in the queue. * * Time complexity: O(1). */ BASE FUNCTION(igraph_dqueue,back) (const TYPE(igraph_dqueue)* q) { assert(q != 0); assert(q->stor_begin != 0); if (q->end == q->stor_begin) return *(q->stor_end-1); return *(q->end-1); } /** * \ingroup dqueue * \function igraph_dqueue_pop * \brief Remove the head. * * Removes and returns the first element in the queue. The queue must * be non-empty. * \param q The input queue. * \return The first element in the queue. * * Time complexity: O(1). */ BASE FUNCTION(igraph_dqueue,pop) (TYPE(igraph_dqueue)* q) { BASE tmp=*(q->begin); assert(q != 0); assert(q->stor_begin != 0); (q->begin)++; if (q->begin==q->stor_end) { q->begin=q->stor_begin; } if (q->begin==q->end) { q->end=NULL; } return tmp; } /** * \ingroup dqueue * \function igraph_dqueue_pop_back * \brief Remove the tail * * Removes and returns the last element in the queue. The queue must * be non-empty. * \param q The queue. * \return The last element in the queue. * * Time complexity: O(1). */ BASE FUNCTION(igraph_dqueue,pop_back) (TYPE(igraph_dqueue)* q) { BASE tmp; assert(q != 0); assert(q->stor_begin != 0); if (q->end != q->stor_begin) { tmp=*((q->end)-1); q->end = (q->end)-1; } else { tmp=*((q->stor_end)-1); q->end = (q->stor_end)-1; } if (q->begin==q->end) { q->end=NULL; } return tmp; } /** * \ingroup dqueue * \function igraph_dqueue_push * \brief Appends an element. * * Append an element to the end of the queue. * \param q The queue. * \param elem The element to append. * \return Error code. * * Time complexity: O(1) if no memory allocation is needed, O(n), the * number of elements in the queue otherwise. But not that by * allocating always twice as much memory as the current size of the * queue we ensure that n push operations can always be done in at * most O(n) time. (Assuming memory allocation is at most linear.) */ int FUNCTION(igraph_dqueue,push) (TYPE(igraph_dqueue)* q, BASE elem) { assert(q != 0); assert(q->stor_begin != 0); if (q->begin != q->end) { /* not full */ if (q->end==NULL) { q->end=q->begin; } *(q->end) = elem; (q->end)++; if (q->end==q->stor_end) { q->end=q->stor_begin; } } else { /* full, allocate more storage */ BASE *bigger=NULL, *old=q->stor_begin; bigger=igraph_Calloc( 2*(q->stor_end - q->stor_begin)+1, BASE ); if (bigger==0) { IGRAPH_ERROR("dqueue push failed", IGRAPH_ENOMEM); } if (q->stor_end - q->begin) { memcpy(bigger, q->begin, (size_t)(q->stor_end - q->begin) * sizeof(BASE)); } if (q->end - q->stor_begin > 0) { memcpy(bigger + (q->stor_end - q->begin), q->stor_begin, (size_t)(q->end - q->stor_begin) * sizeof(BASE)); } q->end =bigger + (q->stor_end - q->stor_begin); q->stor_end =bigger + 2*(q->stor_end - q->stor_begin) + 1; q->stor_begin=bigger; q->begin =bigger; *(q->end) = elem; (q->end)++; if (q->end==q->stor_end) { q->end=q->stor_begin; } igraph_Free(old); } return 0; } #if defined (OUT_FORMAT) #ifndef USING_R int FUNCTION(igraph_dqueue,print)(const TYPE(igraph_dqueue)* q) { return FUNCTION(igraph_dqueue,fprint)(q, stdout); } #endif int FUNCTION(igraph_dqueue,fprint)(const TYPE(igraph_dqueue)* q, FILE *file) { if (q->end != NULL) { /* There is one element at least */ BASE *p=q->begin; fprintf(file, OUT_FORMAT, *p); p++; if (q->end > q->begin) { /* Q is in one piece */ while (p != q->end) { fprintf(file, " " OUT_FORMAT, *p); p++; } } else { /* Q is in two pieces */ while (p != q->stor_end) { fprintf(file, " " OUT_FORMAT, *p); p++; } p=q->stor_begin; while (p != q->end) { fprintf(file, " " OUT_FORMAT, *p); p++; } } } fprintf(file, "\n"); return 0; } #endif BASE FUNCTION(igraph_dqueue,e)(const TYPE(igraph_dqueue) *q, long int idx) { if ((q->begin + idx < q->end) || (q->begin >= q->end && q->begin+idx < q->stor_end)) { return q->begin[idx]; } else if (q->begin >= q->end && q->stor_begin+idx < q->end) { idx = idx-(q->stor_end - q->begin); return q->stor_begin[idx]; } else { return 0; /* Error */ } } igraph/src/foreign-lgl-lexer.l0000644000175100001440000000606113430770201016030 0ustar hornikusers/* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-lgl-header.h" #include "foreign-lgl-parser.h" #define YY_EXTRA_TYPE igraph_i_lgl_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); %} %option noyywrap %option prefix="igraph_lgl_yy" %option outfile="lex.yy.c" %option nounput %option noinput %option nodefault %option reentrant %option bison-bridge %option bison-locations alnum [^ \t\r\n#] %% /* --------------------------------------------------hashmark------*/ # { return HASH; } /* ------------------------------------------------whitespace------*/ [ \t]* { } /* ---------------------------------------------------newline------*/ \n\r|\r\n|\n|\r { return NEWLINE; } /* ----------------------------------------------alphanumeric------*/ {alnum}+ { return ALNUM; } <> { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } . { return ERROR; } %% igraph/src/igraph_hacks_internal.h0000644000175100001440000000274413431000472017022 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_HACKS_INTERNAL_H #define IGRAPH_HACKS_INTERNAL_H #include "config.h" #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS #ifndef HAVE_STRDUP # define strdup igraph_i_strdup char* igraph_i_strdup(const char *s); #endif #ifndef HAVE_STPCPY # define stpcpy igraph_i_stpcpy char* igraph_i_stpcpy(char* s1, const char* s2); #else # ifndef HAVE_STPCPY_SIGNATURE char* stpcpy(char* s1, const char* s2); # endif #endif __END_DECLS #endif igraph/src/distances.c0000644000175100001440000001464013431000472014451 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_datatype.h" #include "igraph_dqueue.h" #include "igraph_iterators.h" #include "igraph_interrupt_internal.h" #include "igraph_vector.h" #include "igraph_interface.h" #include "igraph_adjlist.h" int igraph_i_eccentricity(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, igraph_neimode_t mode, const igraph_adjlist_t *adjlist) { int no_of_nodes=igraph_vcount(graph); igraph_dqueue_long_t q; igraph_vit_t vit; igraph_vector_int_t counted; int i, mark=1; igraph_vector_t vneis; igraph_vector_int_t *neis; IGRAPH_CHECK(igraph_dqueue_long_init(&q, 100)); IGRAPH_FINALLY(igraph_dqueue_long_destroy, &q); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_CHECK(igraph_vector_int_init(&counted, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &counted); if (!adjlist) { IGRAPH_VECTOR_INIT_FINALLY(&vneis, 0); } IGRAPH_CHECK(igraph_vector_resize(res, IGRAPH_VIT_SIZE(vit))); igraph_vector_fill(res, -1); for (i=0, IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), mark++, i++) { long int source; source=IGRAPH_VIT_GET(vit); IGRAPH_CHECK(igraph_dqueue_long_push(&q, source)); IGRAPH_CHECK(igraph_dqueue_long_push(&q, 0)); VECTOR(counted)[source]=mark; IGRAPH_ALLOW_INTERRUPTION(); while (!igraph_dqueue_long_empty(&q)) { long int act=igraph_dqueue_long_pop(&q); long int dist=igraph_dqueue_long_pop(&q); int j, n; if (dist > VECTOR(*res)[i]) { VECTOR(*res)[i]=dist; } if (adjlist) { neis=igraph_adjlist_get(adjlist, act); n=(int) igraph_vector_int_size(neis); for (j=0; j * This implementation ignores vertex pairs that are in different * components. Isolated vertices have eccentricity zero. * * \param graph The input graph, it can be directed or undirected. * \param res Pointer to an initialized vector, the result is stored * here. * \param vids The vertices for which the eccentricity is calculated. * \param mode What kind of paths to consider for the calculation: * \c IGRAPH_OUT, paths that follow edge directions; * \c IGRAPH_IN, paths that follow the opposite directions; and * \c IGRAPH_ALL, paths that ignore edge directions. This argument * is ignored for undirected graphs. * \return Error code. * * Time complexity: O(v*(|V|+|E|)), where |V| is the number of * vertices, |E| is the number of edges and v is the number of * vertices for which eccentricity is calculated. * * \sa \ref igraph_radius(). * * \example examples/simple/igraph_eccentricity.c */ int igraph_eccentricity(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, igraph_neimode_t mode) { return igraph_i_eccentricity(graph, res, vids, mode, /*adjlist=*/ 0); } /** * \function igraph_radius * Radius of a graph * * The radius of a graph is the defined as the minimum eccentricity of * its vertices, see \ref igraph_eccentricity(). * * \param graph The input graph, it can be directed or undirected. * \param radius Pointer to a real variable, the result is stored * here. * \param mode What kind of paths to consider for the calculation: * \c IGRAPH_OUT, paths that follow edge directions; * \c IGRAPH_IN, paths that follow the opposite directions; and * \c IGRAPH_ALL, paths that ignore edge directions. This argument * is ignored for undirected graphs. * \return Error code. * * Time complexity: O(|V|(|V|+|E|)), where |V| is the number of * vertices and |E| is the number of edges. * * \sa \ref igraph_eccentricity(). * * \example examples/simple/igraph_radius.c */ int igraph_radius(const igraph_t *graph, igraph_real_t *radius, igraph_neimode_t mode) { int no_of_nodes=igraph_vcount(graph); if (no_of_nodes==0) { *radius = IGRAPH_NAN; } else { igraph_adjlist_t adjlist; igraph_vector_t ecc; IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, mode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_VECTOR_INIT_FINALLY(&ecc, igraph_vcount(graph)); IGRAPH_CHECK(igraph_i_eccentricity(graph, &ecc, igraph_vss_all(), mode, &adjlist)); *radius = igraph_vector_min(&ecc); igraph_vector_destroy(&ecc); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(2); } return 0; } igraph/src/zeroin.c0000644000175100001440000001522413431000472014001 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* from GNU R's zeroin.c, minor modifications by Gabor Csardi */ /* from NETLIB c/brent.shar with max.iter, add'l info and convergence details hacked in by Peter Dalgaard */ /************************************************************************* * C math library * function ZEROIN - obtain a function zero within the given range * * Input * double zeroin(ax,bx,f,info,Tol,Maxit) * double ax; Root will be seeked for within * double bx; a range [ax,bx] * double (*f)(double x, void *info); Name of the function whose zero * will be seeked for * void *info; Add'l info passed to f * double *Tol; Acceptable tolerance for the root * value. * May be specified as 0.0 to cause * the program to find the root as * accurate as possible * * int *Maxit; Max. iterations * * * Output * Zeroin returns an estimate for the root with accuracy * 4*EPSILON*abs(x) + tol * *Tol returns estimated precision * *Maxit returns actual # of iterations, or -1 if maxit was * reached without convergence. * * Algorithm * G.Forsythe, M.Malcolm, C.Moler, Computer methods for mathematical * computations. M., Mir, 1980, p.180 of the Russian edition * * The function makes use of the bisection procedure combined with * the linear or quadric inverse interpolation. * At every step program operates on three abscissae - a, b, and c. * b - the last and the best approximation to the root * a - the last but one approximation * c - the last but one or even earlier approximation than a that * 1) |f(b)| <= |f(c)| * 2) f(b) and f(c) have opposite signs, i.e. b and c confine * the root * At every step Zeroin selects one of the two new approximations, the * former being obtained by the bisection procedure and the latter * resulting in the interpolation (if a,b, and c are all different * the quadric interpolation is utilized, otherwise the linear one). * If the latter (i.e. obtained by the interpolation) point is * reasonable (i.e. lies within the current interval [b,c] not being * too close to the boundaries) it is accepted. The bisection result * is used in the other case. Therefore, the range of uncertainty is * ensured to be reduced at least by the factor 1.6 * ************************************************************************ */ #include "igraph_types.h" #include "igraph_interrupt_internal.h" #include #include #define EPSILON DBL_EPSILON int igraph_zeroin( /* An estimate of the root */ igraph_real_t *ax, /* Left border | of the range */ igraph_real_t *bx, /* Right border| the root is seeked*/ igraph_real_t (*f)(igraph_real_t x, void *info), /* Function under investigation */ void *info, /* Add'l info passed on to f */ igraph_real_t *Tol, /* Acceptable tolerance */ int *Maxit, /* Max # of iterations */ igraph_real_t *res) /* Result is stored here */ { igraph_real_t a,b,c, /* Abscissae, descr. see above */ fa, fb, fc; /* f(a), f(b), f(c) */ igraph_real_t tol; int maxit; a = *ax; b = *bx; fa = (*f)(a, info); fb = (*f)(b, info); c = a; fc = fa; maxit = *Maxit + 1; tol = * Tol; /* First test if we have found a root at an endpoint */ if(fa == 0.0) { *Tol = 0.0; *Maxit = 0; *res=a; return 0; } if(fb == 0.0) { *Tol = 0.0; *Maxit = 0; *res=b; return 0; } while(maxit--) /* Main iteration loop */ { igraph_real_t prev_step = b-a; /* Distance from the last but one to the last approximation */ igraph_real_t tol_act; /* Actual tolerance */ igraph_real_t p; /* Interpolation step is calcu- */ igraph_real_t q; /* lated in the form p/q; divi- * sion operations is delayed * until the last moment */ igraph_real_t new_step; /* Step at this iteration */ IGRAPH_ALLOW_INTERRUPTION(); if( fabs(fc) < fabs(fb) ) { /* Swap data for b to be the */ a = b; b = c; c = a; /* best approximation */ fa=fb; fb=fc; fc=fa; } tol_act = 2*EPSILON*fabs(b) + tol/2; new_step = (c-b)/2; if( fabs(new_step) <= tol_act || fb == (igraph_real_t)0 ) { *Maxit -= maxit; *Tol = fabs(c-b); *res=b; return 0; /* Acceptable approx. is found */ } /* Decide if the interpolation can be tried */ if( fabs(prev_step) >= tol_act /* If prev_step was large enough*/ && fabs(fa) > fabs(fb) ) { /* and was in true direction, * Interpolation may be tried */ register igraph_real_t t1,cb,t2; cb = c-b; if( a==c ) { /* If we have only two distinct */ /* points linear interpolation */ t1 = fb/fa; /* can only be applied */ p = cb*t1; q = 1.0 - t1; } else { /* Quadric inverse interpolation*/ q = fa/fc; t1 = fb/fc; t2 = fb/fa; p = t2 * ( cb*q*(q-t1) - (b-a)*(t1-1.0) ); q = (q-1.0) * (t1-1.0) * (t2-1.0); } if( p>(igraph_real_t)0 ) /* p was calculated with the */ q = -q; /* opposite sign; make p positive */ else /* and assign possible minus to */ p = -p; /* q */ if( p < (0.75*cb*q-fabs(tol_act*q)/2) /* If b+p/q falls in [b,c]*/ && p < fabs(prev_step*q/2) ) /* and isn't too large */ new_step = p/q; /* it is accepted * If p/q is too large then the * bisection procedure can * reduce [b,c] range to more * extent */ } if( fabs(new_step) < tol_act) { /* Adjust the step to be not less*/ if( new_step > (igraph_real_t)0 ) /* than tolerance */ new_step = tol_act; else new_step = -tol_act; } a = b; fa = fb; /* Save the previous approx. */ b += new_step; fb = (*f)(b, info); /* Do step to a new approxim. */ if( (fb > 0 && fc > 0) || (fb < 0 && fc < 0) ) { /* Adjust c for it to have a sign opposite to that of b */ c = a; fc = fa; } } /* failed! */ *Tol = fabs(c-b); *Maxit = -1; *res=b; return IGRAPH_DIVERGED; } igraph/src/random.c0000644000175100001440000020547113431000472013760 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include #include #include #include "igraph_math.h" #include "igraph_types.h" #include "igraph_vector.h" #include "igraph_memory.h" #include "igraph_matrix.h" /** * \section about_rngs * *
* About random numbers in igraph, use cases * * * Some algorithms in igraph, e.g. the generation of random graphs, * require random number generators (RNGs). Prior to version 0.6 * igraph did not have a sophisticated way to deal with random number * generators at the C level, but this has changed. From version 0.6 * different and multiple random number generators are supported. * *
* */ /** * \section rng_use_cases * *
Use cases * *
Normal (default) use * * If the user does not use any of the RNG functions explicitly, but calls * some of the randomized igraph functions, then a default RNG is set * up the first time an igraph function needs random numbers. The * seed of this RNG is the output of the time(0) function * call, using the time function from the standard C * library. This ensures that igraph creates a different random graph, * each time the C program is called. * * * * The created default generator is stored internally and can be * queried with the \ref igraph_rng_default() function. * *
* *
Reproducible simulations * * If reproducible results are needed, then the user should set the * seed of the default random number generator explicitly, using the * \ref igraph_rng_seed() function on the default generator, \ref * igraph_rng_default(). When setting the seed to the same number, * igraph generates exactly the same random graph (or series of random * graphs). * *
* *
Changing the default generator * * By default igraph uses the \ref igraph_rng_default() random number * generator. This can be changed any time by calling \ref * igraph_rng_set_default(), with an already initialized random number * generator. Note that the old (replaced) generator is not * destroyed, so no memory is deallocated. * *
* *
Using multiple generators * * igraph also provides functions to set up multiple random number * generators, using the \ref igraph_rng_init() function, and then * generating random numbers from them, e.g. with \ref igraph_rng_get_integer() * and/or \ref igraph_rng_get_unif() calls. * * * * Note that initializing a new random number generator is * independent of the generator that the igraph functions themselves * use. If you want to replace that, then please use \ref * igraph_rng_set_default(). * *
* *
Example * * \example examples/simple/random_seed.c * *
* *
*/ /* ------------------------------------ */ typedef struct { int i, j; long int x[31]; } igraph_i_rng_glibc2_state_t; unsigned long int igraph_i_rng_glibc2_get(int *i, int *j, int n, long int *x) { unsigned long int k; x[*i] += x[*j]; k = (x[*i] >> 1) & 0x7FFFFFFF; (*i)++; if (*i == n) { *i = 0; } (*j)++ ; if (*j == n) { *j = 0; } return k; } unsigned long int igraph_rng_glibc2_get(void *vstate) { igraph_i_rng_glibc2_state_t *state = (igraph_i_rng_glibc2_state_t*) vstate; return igraph_i_rng_glibc2_get(&state->i, &state->j, 31, state->x); } igraph_real_t igraph_rng_glibc2_get_real(void *state) { return igraph_rng_glibc2_get(state) / 2147483648.0; } /* this function is independent of the bit size */ void igraph_i_rng_glibc2_init(long int *x, int n, unsigned long int s) { int i; if (s==0) { s=1; } x[0] = (long) s; for (i=1 ; ix, 31, seed); state->i=3; state->j=0; for (i=0;i<10*31; i++) { igraph_rng_glibc2_get(state); } return 0; } int igraph_rng_glibc2_init(void **state) { igraph_i_rng_glibc2_state_t *st; st=igraph_Calloc(1, igraph_i_rng_glibc2_state_t); if (!st) { IGRAPH_ERROR("Cannot initialize RNG", IGRAPH_ENOMEM); } (*state)=st; igraph_rng_glibc2_seed(st, 0); return 0; } void igraph_rng_glibc2_destroy(void *vstate) { igraph_i_rng_glibc2_state_t *state = (igraph_i_rng_glibc2_state_t*) vstate; igraph_Free(state); } /** * \var igraph_rngtype_glibc2 * \brief The random number generator type introduced in GNU libc 2 * * It is a linear feedback shift register generator with a 128-byte * buffer. This generator was the default prior to igraph version 0.6, * at least on systems relying on GNU libc. * * This generator was ported from the GNU Scientific Library. */ const igraph_rng_type_t igraph_rngtype_glibc2 = { /* name= */ "LIBC", /* min= */ 0, /* max= */ RAND_MAX, /* init= */ igraph_rng_glibc2_init, /* destroy= */ igraph_rng_glibc2_destroy, /* seed= */ igraph_rng_glibc2_seed, /* get= */ igraph_rng_glibc2_get, /* get_real= */ igraph_rng_glibc2_get_real, /* get_norm= */ 0, /* get_geom= */ 0, /* get_binom= */ 0, /* get_exp= */ 0 }; /* ------------------------------------ */ typedef struct { unsigned long int x; } igraph_i_rng_rand_state_t; unsigned long int igraph_rng_rand_get(void *vstate) { igraph_i_rng_rand_state_t *state = vstate; state->x = (1103515245 * state->x + 12345) & 0x7fffffffUL; return state->x; } igraph_real_t igraph_rng_rand_get_real(void *vstate) { return igraph_rng_rand_get (vstate) / 2147483648.0 ; } int igraph_rng_rand_seed(void *vstate, unsigned long int seed) { igraph_i_rng_rand_state_t *state = vstate; state->x = seed; return 0; } int igraph_rng_rand_init(void **state) { igraph_i_rng_rand_state_t *st; st=igraph_Calloc(1, igraph_i_rng_rand_state_t); if (!st) { IGRAPH_ERROR("Cannot initialize RNG", IGRAPH_ENOMEM); } (*state)=st; igraph_rng_rand_seed(st, 0); return 0; } void igraph_rng_rand_destroy(void *vstate) { igraph_i_rng_rand_state_t *state = (igraph_i_rng_rand_state_t*) vstate; igraph_Free(state); } /** * \var igraph_rngtype_rand * \brief The old BSD rand/stand random number generator * * The sequence is * x_{n+1} = (a x_n + c) mod m * with a = 1103515245, c = 12345 and m = 2^31 = 2147483648. The seed * specifies the initial value, x_1. * * The theoretical value of x_{10001} is 1910041713. * * The period of this generator is 2^31. * * This generator is not very good -- the low bits of successive * numbers are correlated. * * This generator was ported from the GNU Scientific Library. */ const igraph_rng_type_t igraph_rngtype_rand = { /* name= */ "RAND", /* min= */ 0, /* max= */ 0x7fffffffUL, /* init= */ igraph_rng_rand_init, /* destroy= */ igraph_rng_rand_destroy, /* seed= */ igraph_rng_rand_seed, /* get= */ igraph_rng_rand_get, /* get_real= */ igraph_rng_rand_get_real, /* get_norm= */ 0, /* get_geom= */ 0, /* get_binom= */ 0, /* get_exp= */ 0 }; /* ------------------------------------ */ #define N 624 /* Period parameters */ #define M 397 /* most significant w-r bits */ static const unsigned long UPPER_MASK = 0x80000000UL; /* least significant r bits */ static const unsigned long LOWER_MASK = 0x7fffffffUL; typedef struct { unsigned long mt[N]; int mti; } igraph_i_rng_mt19937_state_t; unsigned long int igraph_rng_mt19937_get(void *vstate) { igraph_i_rng_mt19937_state_t *state = vstate; unsigned long k ; unsigned long int *const mt = state->mt; #define MAGIC(y) (((y)&0x1) ? 0x9908b0dfUL : 0) if (state->mti >= N) { /* generate N words at one time */ int kk; for (kk = 0; kk < N - M; kk++) { unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >> 1) ^ MAGIC(y); } for (; kk < N - 1; kk++) { unsigned long y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ MAGIC(y); } { unsigned long y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ MAGIC(y); } state->mti = 0; } #undef MAGIC /* Tempering */ k = mt[state->mti]; k ^= (k >> 11); k ^= (k << 7) & 0x9d2c5680UL; k ^= (k << 15) & 0xefc60000UL; k ^= (k >> 18); state->mti++; return k; } igraph_real_t igraph_rng_mt19937_get_real(void *vstate) { return igraph_rng_mt19937_get (vstate) / 4294967296.0 ; } int igraph_rng_mt19937_seed(void *vstate, unsigned long int seed) { igraph_i_rng_mt19937_state_t *state = vstate; int i; memset(state, 0, sizeof(igraph_i_rng_mt19937_state_t)); if (seed == 0) { seed = 4357; /* the default seed is 4357 */ } state->mt[0]= seed & 0xffffffffUL; for (i = 1; i < N; i++) { /* See Knuth's "Art of Computer Programming" Vol. 2, 3rd Ed. p.106 for multiplier. */ state->mt[i] = (1812433253UL * (state->mt[i-1] ^ (state->mt[i-1] >> 30)) + (unsigned long) i); state->mt[i] &= 0xffffffffUL; } state->mti = i; return 0; } int igraph_rng_mt19937_init(void **state) { igraph_i_rng_mt19937_state_t *st; st=igraph_Calloc(1, igraph_i_rng_mt19937_state_t); if (!st) { IGRAPH_ERROR("Cannot initialize RNG", IGRAPH_ENOMEM); } (*state)=st; igraph_rng_mt19937_seed(st, 0); return 0; } void igraph_rng_mt19937_destroy(void *vstate) { igraph_i_rng_mt19937_state_t *state = (igraph_i_rng_mt19937_state_t*) vstate; igraph_Free(state); } /** * \var igraph_rngtype_mt19937 * \brief The MT19937 random number generator * * The MT19937 generator of Makoto Matsumoto and Takuji Nishimura is a * variant of the twisted generalized feedback shift-register * algorithm, and is known as the “Mersenne Twister†generator. It has * a Mersenne prime period of 2^19937 - 1 (about 10^6000) and is * equi-distributed in 623 dimensions. It has passed the diehard * statistical tests. It uses 624 words of state per generator and is * comparable in speed to the other generators. The original generator * used a default seed of 4357 and choosing s equal to zero in * gsl_rng_set reproduces this. Later versions switched to 5489 as the * default seed, you can choose this explicitly via igraph_rng_seed * instead if you require it. * * For more information see, * Makoto Matsumoto and Takuji Nishimura, “Mersenne Twister: A * 623-dimensionally equidistributed uniform pseudorandom number * generatorâ€. ACM Transactions on Modeling and Computer Simulation, * Vol. 8, No. 1 (Jan. 1998), Pages 3–30 * * The generator igraph_rngtype_mt19937 uses the second revision of the * seeding procedure published by the two authors above in 2002. The * original seeding procedures could cause spurious artifacts for some * seed values. * * This generator was ported from the GNU Scientific Library. */ const igraph_rng_type_t igraph_rngtype_mt19937 = { /* name= */ "MT19937", /* min= */ 0, /* max= */ 0xffffffffUL, /* init= */ igraph_rng_mt19937_init, /* destroy= */ igraph_rng_mt19937_destroy, /* seed= */ igraph_rng_mt19937_seed, /* get= */ igraph_rng_mt19937_get, /* get_real= */ igraph_rng_mt19937_get_real, /* get_norm= */ 0, /* get_geom= */ 0, /* get_binom= */ 0, /* get_exp= */ 0 }; #undef N #undef M /* ------------------------------------ */ #ifndef USING_R igraph_i_rng_mt19937_state_t igraph_i_rng_default_state; #define addr(a) (&a) /** * \var igraph_i_rng_default * The default igraph random number generator * * This generator is used by all builtin igraph functions that need to * generate random numbers; e.g. all random graph generators. * * You can use \ref igraph_i_rng_default with \ref igraph_rng_seed() * to set its seed. * * You can change the default generator using the \ref * igraph_rng_set_default() function. */ IGRAPH_THREAD_LOCAL igraph_rng_t igraph_i_rng_default = { addr(igraph_rngtype_mt19937), addr(igraph_i_rng_default_state), /* def= */ 1 }; #undef addr /** * \function igraph_rng_set_default * Set the default igraph random number generator * * \param rng The random number generator to use as default from now * on. Calling \ref igraph_rng_destroy() on it, while it is still * being used as the default will result craches and/or * unpredictable results. * * Time complexity: O(1). */ void igraph_rng_set_default(igraph_rng_t *rng) { igraph_i_rng_default = (*rng); } #endif /* ------------------------------------ */ #ifdef USING_R double unif_rand(void); double norm_rand(void); double exp_rand(void); double Rf_rgeom(double); double Rf_rbinom(double, double); double Rf_rgamma(double, double); int igraph_rng_R_init(void **state) { IGRAPH_ERROR("R RNG error, unsupported function called", IGRAPH_EINTERNAL); return 0; } void igraph_rng_R_destroy(void *state) { igraph_error("R RNG error, unsupported function called", __FILE__, __LINE__, IGRAPH_EINTERNAL); } int igraph_rng_R_seed(void *state, unsigned long int seed) { IGRAPH_ERROR("R RNG error, unsupported function called", IGRAPH_EINTERNAL); return 0; } unsigned long int igraph_rng_R_get(void *state) { return (unsigned long) (unif_rand() * 0x7FFFFFFFUL); } igraph_real_t igraph_rng_R_get_real(void *state) { return unif_rand(); } igraph_real_t igraph_rng_R_get_norm(void *state) { return norm_rand(); } igraph_real_t igraph_rng_R_get_geom(void *state, igraph_real_t p) { return Rf_rgeom(p); } igraph_real_t igraph_rng_R_get_binom(void *state, long int n, igraph_real_t p) { return Rf_rbinom(n, p); } igraph_real_t igraph_rng_R_get_gamma(void *state, igraph_real_t shape, igraph_real_t scale) { return Rf_rgamma(shape, scale); } igraph_real_t igraph_rng_R_get_exp(void *state, igraph_real_t rate) { igraph_real_t scale = 1.0 / rate; if (!IGRAPH_FINITE(scale) || scale <= 0.0) { if (scale == 0.0) { return 0.0; } return IGRAPH_NAN; } return scale * exp_rand(); } igraph_rng_type_t igraph_rngtype_R = { /* name= */ "GNU R", /* min= */ 0, /* max= */ 0x7FFFFFFFUL, /* init= */ igraph_rng_R_init, /* destroy= */ igraph_rng_R_destroy, /* seed= */ igraph_rng_R_seed, /* get= */ igraph_rng_R_get, /* get_real= */ igraph_rng_R_get_real, /* get_norm= */ igraph_rng_R_get_norm, /* get_geom= */ igraph_rng_R_get_geom, /* get_binom= */ igraph_rng_R_get_binom, /* get_exp= */ igraph_rng_R_get_exp }; IGRAPH_THREAD_LOCAL igraph_rng_t igraph_i_rng_default = { &igraph_rngtype_R, 0, /* def= */ 1 }; #endif /* ------------------------------------ */ /** * \function igraph_rng_default * Query the default random number generator. * * \return A pointer to the default random number generator. * * \sa igraph_rng_set_default() */ igraph_rng_t *igraph_rng_default() { return &igraph_i_rng_default; } /* ------------------------------------ */ double igraph_norm_rand(igraph_rng_t *rng); double igraph_rgeom(igraph_rng_t *rng, double p); double igraph_rbinom(igraph_rng_t *rng, double nin, double pp); double igraph_rexp(igraph_rng_t *rng, double rate); double igraph_rgamma(igraph_rng_t *rng, double shape, double scale); /** * \function igraph_rng_init * Initialize a random number generator * * This function allocates memory for a random number generator, with * the given type, and sets its seed to the default. * * \param rng Pointer to an uninitialized RNG. * \param type The type of the RNG, please see the documentation for * the supported types. * \return Error code. * * Time complexity: depends on the type of the generator, but usually * it should be O(1). */ int igraph_rng_init(igraph_rng_t *rng, const igraph_rng_type_t *type) { rng->type=type; IGRAPH_CHECK(rng->type->init(&rng->state)); return 0; } /** * \function igraph_rng_destroy * Deallocate memory associated with a random number generator * * \param rng The RNG to destroy. Do not destroy an RNG that is used * as the default igraph RNG. * * Time complexity: O(1). */ void igraph_rng_destroy(igraph_rng_t *rng) { rng->type->destroy(rng->state); } /** * \function igraph_rng_seed * Set the seed of a random number generator * * \param rng The RNG. * \param seed The new seed. * \return Error code. * * Time complexity: usually O(1), but may depend on the type of the * RNG. */ int igraph_rng_seed(igraph_rng_t *rng, unsigned long int seed) { const igraph_rng_type_t *type=rng->type; rng->def=0; IGRAPH_CHECK(type->seed(rng->state, seed)); return 0; } /** * \function igraph_rng_max * Query the maximum possible integer for a random number generator * * \param rng The RNG. * \return The largest possible integer that can be generated by * calling \ref igraph_rng_get_integer() on the RNG. * * Time complexity: O(1). */ unsigned long int igraph_rng_max(igraph_rng_t *rng) { const igraph_rng_type_t *type=rng->type; return type->max; } /** * \function igraph_rng_min * Query the minimum possible integer for a random number generator * * \param rng The RNG. * \return The smallest possible integer that can be generated by * calling \ref igraph_rng_get_integer() on the RNG. * * Time complexity: O(1). */ unsigned long int igraph_rng_min(igraph_rng_t *rng) { const igraph_rng_type_t *type=rng->type; return type->min; } /** * \function igraph_rng_name * Query the type of a random number generator * * \param rng The RNG. * \return The name of the type of the generator. Do not deallocate or * change the returned string pointer. * * Time complexity: O(1). */ const char *igraph_rng_name(igraph_rng_t *rng) { const igraph_rng_type_t *type=rng->type; return type->name; } /** * \function igraph_rng_get_integer * Generate an integer random number from an interval * * \param rng Pointer to the RNG to use for the generation. Use \ref * igraph_rng_default() here to use the default igraph RNG. * \param l Lower limit, inclusive, it can be negative as well. * \param h Upper limit, inclusive, it can be negative as well, but it * should be at least l. * \return The generated random integer. * * Time complexity: depends on the generator, but should be usually * O(1). */ long int igraph_rng_get_integer(igraph_rng_t *rng, long int l, long int h) { const igraph_rng_type_t *type=rng->type; if (type->get_real) { return (long int)(type->get_real(rng->state)*(h-l+1)+l); } else if (type->get) { unsigned long int max=type->max; return (long int)(type->get(rng->state) / ((double)max+1)*(h-l+1)+l); } IGRAPH_ERROR("Internal random generator error", IGRAPH_EINTERNAL); return 0; } /** * \function igraph_rng_get_normal * Normally distributed random numbers * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \param m The mean. * \param s Standard deviation. * \return The generated normally distributed random number. * * Time complexity: depends on the type of the RNG. */ igraph_real_t igraph_rng_get_normal(igraph_rng_t *rng, igraph_real_t m, igraph_real_t s) { const igraph_rng_type_t *type=rng->type; if (type->get_norm) { return type->get_norm(rng->state)*s+m; } else { return igraph_norm_rand(rng)*s+m; } } /** * \function igraph_rng_get_unif * Generate real, uniform random numbers from an interval * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \param l The lower bound, it can be negative. * \param h The upper bound, it can be negative, but it has to be * larger than the lower bound. * \return The generated uniformly distributed random number. * * Time complexity: depends on the type of the RNG. */ igraph_real_t igraph_rng_get_unif(igraph_rng_t *rng, igraph_real_t l, igraph_real_t h) { const igraph_rng_type_t *type=rng->type; if (type->get_real) { return type->get_real(rng->state)*(h-l)+l; } else if (type->get) { unsigned long int max=type->max; return type->get(rng->state)/((double)max+1)*(double)(h-l)+l; } IGRAPH_ERROR("Internal random generator error", IGRAPH_EINTERNAL); return 0; } /** * \function igraph_rng_get_unif01 * Generate real, uniform random number from the unit interval * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \return The generated uniformly distributed random number. * * Time complexity: depends on the type of the RNG. */ igraph_real_t igraph_rng_get_unif01(igraph_rng_t *rng) { const igraph_rng_type_t *type=rng->type; if (type->get_real) { return type->get_real(rng->state); } else if (type->get) { unsigned long int max=type->max; return type->get(rng->state)/((double)max+1); } IGRAPH_ERROR("Internal random generator error", IGRAPH_EINTERNAL); return 0; } /** * \function igraph_rng_get_geom * Generate geometrically distributed random numbers * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \param p The probability of success in each trial. Must be larger * than zero and smaller or equal to 1. * \return The generated geometrically distributed random number. * * Time complexity: depends on the type of the RNG. */ igraph_real_t igraph_rng_get_geom(igraph_rng_t *rng, igraph_real_t p) { const igraph_rng_type_t *type=rng->type; if (type->get_geom) { return type->get_geom(rng->state, p); } else { return igraph_rgeom(rng, p); } } /** * \function igraph_rng_get_binom * Generate binomially distributed random numbers * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \param n Number of observations. * \param p Probability of an event. * \return The generated binomially distributed random number. * * Time complexity: depends on the type of the RNG. */ igraph_real_t igraph_rng_get_binom(igraph_rng_t *rng, long int n, igraph_real_t p) { const igraph_rng_type_t *type=rng->type; if (type->get_binom) { return type->get_binom(rng->state, n, p); } else { return igraph_rbinom(rng, n, p); } } /** * \function igraph_rng_get_gamma * Generate sample from a Gamma distribution * * \param rng Pointer to the RNG to use. Use \ref igraph_rng_default() * here to use the default igraph RNG. * \param a * \param scale * \return The generated sample * * Time complexity: depends on RNG. */ igraph_real_t igraph_rng_get_gamma(igraph_rng_t *rng, igraph_real_t shape, igraph_real_t scale) { const igraph_rng_type_t *type=rng->type; if (type->get_gamma) { return type->get_gamma(rng->state, shape, scale); } else { return igraph_rgamma(rng, shape, scale); } } unsigned long int igraph_rng_get_int31(igraph_rng_t *rng) { const igraph_rng_type_t *type=rng->type; unsigned long int max=type->max; if (type->get && max==0x7FFFFFFFUL) { return type->get(rng->state); } else if (type->get_real) { return (unsigned long int) (type->get_real(rng->state)*0x7FFFFFFFUL); } else { return (unsigned long int) (igraph_rng_get_unif01(rng)*0x7FFFFFFFUL); } } igraph_real_t igraph_rng_get_exp(igraph_rng_t *rng, igraph_real_t rate) { const igraph_rng_type_t *type=rng->type; if (type->get_exp) { return type->get_exp(rng->state, rate); } else { return igraph_rexp(rng, rate); } } #ifndef HAVE_EXPM1 #ifndef USING_R /* R provides a replacement */ /* expm1 replacement */ double expm1 (double x) { if (fabs(x) < M_LN2) { /* Compute the Taylor series S = x + (1/2!) x^2 + (1/3!) x^3 + ... */ double i = 1.0; double sum = x; double term = x / 1.0; do { term *= x / ++i; sum += term; } while (fabs(term) > fabs(sum) * 2.22e-16); return sum; } return expl(x) - 1.0L; } #endif #endif #ifndef HAVE_RINT #ifndef USING_R /* R provides a replacement */ /* rint replacement */ double rint (double x) { return ( (x<0.) ? -floor(-x+.5) : floor(x+.5) ); } #endif #endif #ifndef HAVE_RINTF float rintf (float x) { return ( (x<(float)0.) ? -(float)floor(-x+.5) : (float)floor(x+.5) ); } #endif /* * \ingroup internal * * This function appends the rest of the needed random number to the * result vector. */ int igraph_i_random_sample_alga(igraph_vector_t *res, igraph_integer_t l, igraph_integer_t h, igraph_integer_t length) { igraph_real_t N=h-l+1; igraph_real_t n=length; igraph_real_t top=N-n; igraph_real_t Nreal=N; igraph_real_t S=0; igraph_real_t V, quot; l=l-1; while (n>=2) { V=RNG_UNIF01(); S=1; quot=top/Nreal; while (quot>V) { S+=1; top=-1.0+top; Nreal=-1.0+Nreal; quot=(quot*top)/Nreal; } l+=S; igraph_vector_push_back(res, l); /* allocated */ Nreal=-1.0+Nreal; n=-1+n; } S=floor(round(Nreal)*RNG_UNIF01()); l+=S+1; igraph_vector_push_back(res, l); /* allocated */ return 0; } /** * \ingroup nongraph * \function igraph_random_sample * \brief Generates an increasing random sequence of integers. * *
* This function generates an increasing sequence of random integer * numbers from a given interval. The algorithm is taken literally * from (Vitter 1987). This method can be used for generating numbers from a * \em very large interval. It is primarily created for randomly * selecting some edges from the sometimes huge set of possible edges * in a large graph. * * Note that the type of the lower and the upper limit is \c igraph_real_t, * not \c igraph_integer_t. This does not mean that you can pass fractional * numbers there; these values must still be integral, but we need the * longer range of \c igraph_real_t in several places in the library * (for instance, when generating Erdos-Renyi graphs). * \param res Pointer to an initialized vector. This will hold the * result. It will be resized to the proper size. * \param l The lower limit of the generation interval (inclusive). This must * be less than or equal to the upper limit, and it must be integral. * Passing a fractional number here results in undefined behaviour. * \param h The upper limit of the generation interval (inclusive). This must * be greater than or equal to the lower limit, and it must be integral. * Passing a fractional number here results in undefined behaviour. * \param length The number of random integers to generate. * \return The error code \c IGRAPH_EINVAL is returned in each of the * following cases: (1) The given lower limit is greater than the * given upper limit, i.e. \c l > \c h. (2) Assuming that * \c l < \c h and N is the sample size, the above error code is * returned if N > |\c h - \c l|, i.e. the sample size exceeds the * size of the candidate pool. * * Time complexity: according to (Vitter 1987), the expected * running time is O(length). * * * Reference: * \clist * \cli (Vitter 1987) * J. S. Vitter. An efficient algorithm for sequential random sampling. * \emb ACM Transactions on Mathematical Software, \eme 13(1):58--67, 1987. * \endclist * * \example examples/simple/igraph_random_sample.c */ int igraph_random_sample(igraph_vector_t *res, igraph_real_t l, igraph_real_t h, igraph_integer_t length) { igraph_real_t N=h-l+1; igraph_real_t n=length; int retval; igraph_real_t nreal=length; igraph_real_t ninv=(nreal != 0) ? 1.0/nreal : 0.0; igraph_real_t Nreal=N; igraph_real_t Vprime; igraph_real_t qu1=-n+1+N; igraph_real_t qu1real=-nreal+1.0+Nreal; igraph_real_t negalphainv=-13; igraph_real_t threshold=-negalphainv*n; igraph_real_t S; /* getting back some sense of sanity */ if (l > h) IGRAPH_ERROR("Lower limit is greater than upper limit", IGRAPH_EINVAL); /* now we know that l <= h */ if (length > N) IGRAPH_ERROR("Sample size exceeds size of candidate pool", IGRAPH_EINVAL); /* treat rare cases quickly */ if (l==h) { IGRAPH_CHECK(igraph_vector_resize(res, 1)); VECTOR(*res)[0] = l; return 0; } if (length==0) { igraph_vector_clear(res); return 0; } if (length==N) { long int i = 0; IGRAPH_CHECK(igraph_vector_resize(res, length)); for (i = 0; i < length; i++) { VECTOR(*res)[i] = l++; } return 0; } igraph_vector_clear(res); IGRAPH_CHECK(igraph_vector_reserve(res, length)); RNG_BEGIN(); Vprime=exp(log(RNG_UNIF01())*ninv); l=l-1; while (n>1 && threshold < N) { igraph_real_t X, U; igraph_real_t limit, t; igraph_real_t negSreal, y1, y2, top, bottom; igraph_real_t nmin1inv=1.0/(-1.0+nreal); while (1) { while(1) { X=Nreal*(-Vprime+1.0); S=floor(X); // if (S==0) { S=1; } if (S S) { bottom=-nreal+Nreal; limit=-S+N; } else { bottom=-1.0+negSreal+Nreal; limit=qu1; } for (t=-1+N; t>=limit; t--) { y2=(y2*top)/bottom; top=-1.0+top; bottom=-1.0+bottom; } if (Nreal/(-X+Nreal) >= y1*exp(log(y2)*nmin1inv)) { Vprime=exp(log(RNG_UNIF01())*nmin1inv); break; } Vprime=exp(log(RNG_UNIF01())*ninv); } l+=S+1; igraph_vector_push_back(res, l); /* allocated */ N=-S+(-1+N); Nreal=negSreal+(-1.0+Nreal); n=-1+n; nreal=-1.0+nreal; ninv=nmin1inv; qu1=-S+qu1; qu1real=negSreal+qu1real; threshold=threshold+negalphainv; } if (n>1) { retval=igraph_i_random_sample_alga(res, (igraph_integer_t) l+1, (igraph_integer_t) h, (igraph_integer_t) n); } else { retval=0; S=floor(N*Vprime); l+=S+1; igraph_vector_push_back(res, l); /* allocated */ } RNG_END(); return retval; } #ifdef USING_R /* These are never called. But they are correct, nevertheless */ double igraph_norm_rand(igraph_rng_t *rng) { return norm_rand(); } double igraph_rgeom(igraph_rng_t *rng, double p) { return Rf_rgeom(p); } double igraph_rbinom(igraph_rng_t *rng, double nin, double pp) { return Rf_rbinom(nin, pp); } double igraph_rexp(igraph_rng_t *rng, double rate) { igraph_real_t scale = 1.0 / rate; if (!IGRAPH_FINITE(scale) || scale <= 0.0) { if (scale == 0.0) { return 0.0; } return IGRAPH_NAN; } return scale * exp_rand(); } double igraph_rgamma(igraph_rng_t *rng, double shape, double scale) { return Rf_rgamma(shape, scale); } #else /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000 The R Development Core Team * based on AS 111 (C) 1977 Royal Statistical Society * and on AS 241 (C) 1988 Royal Statistical Society * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * SYNOPSIS * * double qnorm5(double p, double mu, double sigma, * int lower_tail, int log_p) * {qnorm (..) is synonymous and preferred inside R} * * DESCRIPTION * * Compute the quantile function for the normal distribution. * * For small to moderate probabilities, algorithm referenced * below is used to obtain an initial approximation which is * polished with a final Newton step. * * For very large arguments, an algorithm of Wichura is used. * * REFERENCE * * Beasley, J. D. and S. G. Springer (1977). * Algorithm AS 111: The percentage points of the normal distribution, * Applied Statistics, 26, 118-121. * * Wichura, M.J. (1988). * Algorithm AS 241: The Percentage Points of the Normal Distribution. * Applied Statistics, 37, 477-484. */ /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998-2004 The R Development Core Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* Private header file for use during compilation of Mathlib */ #ifndef MATHLIB_PRIVATE_H #define MATHLIB_PRIVATE_H #define ML_POSINF IGRAPH_INFINITY #define ML_NEGINF -IGRAPH_INFINITY #define ML_NAN IGRAPH_NAN #define ML_ERROR(x) /* nothing */ #define ML_UNDERFLOW (DBL_MIN * DBL_MIN) #define ML_VALID(x) (!ISNAN(x)) #define ME_NONE 0 /* no error */ #define ME_DOMAIN 1 /* argument out of domain */ #define ME_RANGE 2 /* value out of range */ #define ME_NOCONV 4 /* process did not converge */ #define ME_PRECISION 8 /* does not have "full" precision */ #define ME_UNDERFLOW 16 /* and underflow occurred (important for IEEE)*/ #define ML_ERR_return_NAN { ML_ERROR(ME_DOMAIN); return ML_NAN; } /* Wilcoxon Rank Sum Distribution */ #define WILCOX_MAX 50 /* Wilcoxon Signed Rank Distribution */ #define SIGNRANK_MAX 50 /* Formerly private part of Mathlib.h */ /* always remap internal functions */ #define bd0 Rf_bd0 #define chebyshev_eval Rf_chebyshev_eval #define chebyshev_init Rf_chebyshev_init #define i1mach Rf_i1mach #define gammalims Rf_gammalims #define lfastchoose Rf_lfastchoose #define lgammacor Rf_lgammacor #define stirlerr Rf_stirlerr /* Chebyshev Series */ int chebyshev_init(double*, int, double); double chebyshev_eval(double, const double *, const int); /* Gamma and Related Functions */ void gammalims(double*, double*); double lgammacor(double); /* log(gamma) correction */ double stirlerr(double); /* Stirling expansion "error" */ double lfastchoose(double, double); double bd0(double, double); /* Consider adding these two to the API (Rmath.h): */ double dbinom_raw(double, double, double, double, int); double dpois_raw (double, double, int); double pnchisq_raw(double, double, double, double, double, int); int i1mach(int); /* From toms708.c */ void bratio(double a, double b, double x, double y, double *w, double *w1, int *ierr); #endif /* MATHLIB_PRIVATE_H */ /* Utilities for `dpq' handling (density/probability/quantile) */ /* give_log in "d"; log_p in "p" & "q" : */ #define give_log log_p /* "DEFAULT" */ /* --------- */ #define R_D__0 (log_p ? ML_NEGINF : 0.) /* 0 */ #define R_D__1 (log_p ? 0. : 1.) /* 1 */ #define R_DT_0 (lower_tail ? R_D__0 : R_D__1) /* 0 */ #define R_DT_1 (lower_tail ? R_D__1 : R_D__0) /* 1 */ #define R_D_Lval(p) (lower_tail ? (p) : (1 - (p))) /* p */ #define R_D_Cval(p) (lower_tail ? (1 - (p)) : (p)) /* 1 - p */ #define R_D_val(x) (log_p ? log(x) : (x)) /* x in pF(x,..) */ #define R_D_qIv(p) (log_p ? exp(p) : (p)) /* p in qF(p,..) */ #define R_D_exp(x) (log_p ? (x) : exp(x)) /* exp(x) */ #define R_D_log(p) (log_p ? (p) : log(p)) /* log(p) */ #define R_D_Clog(p) (log_p ? log1p(-(p)) : (1 - (p)))/* [log](1-p) */ /* log(1-exp(x)): R_D_LExp(x) == (log1p(- R_D_qIv(x))) but even more stable:*/ #define R_D_LExp(x) (log_p ? R_Log1_Exp(x) : log1p(-x)) /*till 1.8.x: * #define R_DT_val(x) R_D_val(R_D_Lval(x)) * #define R_DT_Cval(x) R_D_val(R_D_Cval(x)) */ #define R_DT_val(x) (lower_tail ? R_D_val(x) : R_D_Clog(x)) #define R_DT_Cval(x) (lower_tail ? R_D_Clog(x) : R_D_val(x)) /*#define R_DT_qIv(p) R_D_Lval(R_D_qIv(p)) * p in qF ! */ #define R_DT_qIv(p) (log_p ? (lower_tail ? exp(p) : - expm1(p)) \ : R_D_Lval(p)) /*#define R_DT_CIv(p) R_D_Cval(R_D_qIv(p)) * 1 - p in qF */ #define R_DT_CIv(p) (log_p ? (lower_tail ? -expm1(p) : exp(p)) \ : R_D_Cval(p)) #define R_DT_exp(x) R_D_exp(R_D_Lval(x)) /* exp(x) */ #define R_DT_Cexp(x) R_D_exp(R_D_Cval(x)) /* exp(1 - x) */ #define R_DT_log(p) (lower_tail? R_D_log(p) : R_D_LExp(p))/* log(p) in qF */ #define R_DT_Clog(p) (lower_tail? R_D_LExp(p): R_D_log(p))/* log(1-p) in qF*/ #define R_DT_Log(p) (lower_tail? (p) : R_Log1_Exp(p)) /* == R_DT_log when we already "know" log_p == TRUE :*/ #define R_Q_P01_check(p) \ if ((log_p && p > 0) || \ (!log_p && (p < 0 || p > 1)) ) \ ML_ERR_return_NAN /* additions for density functions (C.Loader) */ #define R_D_fexp(f,x) (give_log ? -0.5*log(f)+(x) : exp(x)/sqrt(f)) #define R_D_forceint(x) floor((x) + 0.5) #define R_D_nonint(x) (fabs((x) - floor((x)+0.5)) > 1e-7) /* [neg]ative or [non int]eger : */ #define R_D_negInonint(x) (x < 0. || R_D_nonint(x)) #define R_D_nonint_check(x) \ if(R_D_nonint(x)) { \ MATHLIB_WARNING("non-integer x = %f", x); \ return R_D__0; \ } double igraph_qnorm5(double p, double mu, double sigma, int lower_tail, int log_p) { double p_, q, r, val; #ifdef IEEE_754 if (ISNAN(p) || ISNAN(mu) || ISNAN(sigma)) return p + mu + sigma; #endif if (p == R_DT_0) return ML_NEGINF; if (p == R_DT_1) return ML_POSINF; R_Q_P01_check(p); if(sigma < 0) ML_ERR_return_NAN; if(sigma == 0) return mu; p_ = R_DT_qIv(p);/* real lower_tail prob. p */ q = p_ - 0.5; /*-- use AS 241 --- */ /* double ppnd16_(double *p, long *ifault)*/ /* ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3 Produces the normal deviate Z corresponding to a given lower tail area of P; Z is accurate to about 1 part in 10**16. (original fortran code used PARAMETER(..) for the coefficients and provided hash codes for checking them...) */ if (fabs(q) <= .425) {/* 0.075 <= p <= 0.925 */ r = .180625 - q * q; val = q * (((((((r * 2509.0809287301226727 + 33430.575583588128105) * r + 67265.770927008700853) * r + 45921.953931549871457) * r + 13731.693765509461125) * r + 1971.5909503065514427) * r + 133.14166789178437745) * r + 3.387132872796366608) / (((((((r * 5226.495278852854561 + 28729.085735721942674) * r + 39307.89580009271061) * r + 21213.794301586595867) * r + 5394.1960214247511077) * r + 687.1870074920579083) * r + 42.313330701600911252) * r + 1.); } else { /* closer than 0.075 from {0,1} boundary */ /* r = min(p, 1-p) < 0.075 */ if (q > 0) r = R_DT_CIv(p);/* 1-p */ else r = p_;/* = R_DT_Iv(p) ^= p */ r = sqrt(- ((log_p && ((lower_tail && q <= 0) || (!lower_tail && q > 0))) ? p : /* else */ log(r))); /* r = sqrt(-log(r)) <==> min(p, 1-p) = exp( - r^2 ) */ if (r <= 5.) { /* <==> min(p,1-p) >= exp(-25) ~= 1.3888e-11 */ r += -1.6; val = (((((((r * 7.7454501427834140764e-4 + .0227238449892691845833) * r + .24178072517745061177) * r + 1.27045825245236838258) * r + 3.64784832476320460504) * r + 5.7694972214606914055) * r + 4.6303378461565452959) * r + 1.42343711074968357734) / (((((((r * 1.05075007164441684324e-9 + 5.475938084995344946e-4) * r + .0151986665636164571966) * r + .14810397642748007459) * r + .68976733498510000455) * r + 1.6763848301838038494) * r + 2.05319162663775882187) * r + 1.); } else { /* very close to 0 or 1 */ r += -5.; val = (((((((r * 2.01033439929228813265e-7 + 2.71155556874348757815e-5) * r + .0012426609473880784386) * r + .026532189526576123093) * r + .29656057182850489123) * r + 1.7848265399172913358) * r + 5.4637849111641143699) * r + 6.6579046435011037772) / (((((((r * 2.04426310338993978564e-15 + 1.4215117583164458887e-7)* r + 1.8463183175100546818e-5) * r + 7.868691311456132591e-4) * r + .0148753612908506148525) * r + .13692988092273580531) * r + .59983220655588793769) * r + 1.); } if(q < 0.0) val = -val; /* return (q >= 0.)? r : -r ;*/ } return mu + sigma * val; } double fsign(double x, double y) { #ifdef IEEE_754 if (ISNAN(x) || ISNAN(y)) return x + y; #endif return ((y >= 0) ? fabs(x) : -fabs(x)); } int imax2(int x, int y) { return (x < y) ? y : x; } int imin2(int x, int y) { return (x < y) ? x : y; } #if HAVE_WORKING_ISFINITE || HAVE_ISFINITE /* isfinite is defined in according to C99 */ # define R_FINITE(x) isfinite(x) #elif HAVE_WORKING_FINITE || HAVE_FINITE /* include header needed to define finite() */ # ifdef HAVE_IEEE754_H # include /* newer Linuxen */ # else # ifdef HAVE_IEEEFP_H # include /* others [Solaris], .. */ # endif # endif # define R_FINITE(x) finite(x) #else # define R_FINITE(x) R_finite(x) #endif int R_finite(double x) { #if HAVE_WORKING_ISFINITE || HAVE_ISFINITE return isfinite(x); #elif HAVE_WORKING_FINITE || HAVE_FINITE return finite(x); #else /* neither finite nor isfinite work. Do we really need the AIX exception? */ # ifdef _AIX # include return FINITE(x); # elif defined(_MSC_VER) return _finite(x); #else return (!isnan(x) & (x != 1/0.0) & (x != -1.0/0.0)); # endif #endif } int R_isnancpp(double x) { return (isnan(x)!=0); } #ifdef __cplusplus int R_isnancpp(double); /* in arithmetic.c */ # define ISNAN(x) R_isnancpp(x) #else # define ISNAN(x) (isnan(x)!=0) #endif double igraph_norm_rand(igraph_rng_t *rng) { double u1; #define BIG 134217728 /* 2^27 */ /* unif_rand() alone is not of high enough precision */ u1 = igraph_rng_get_unif01(rng); u1 = (int)(BIG*u1) + igraph_rng_get_unif01(rng); return igraph_qnorm5(u1/BIG, 0.0, 1.0, 1, 0); } /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000-2002 the R Development Core Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * SYNOPSIS * * #include * double exp_rand(void); * * DESCRIPTION * * Random variates from the standard exponential distribution. * * REFERENCE * * Ahrens, J.H. and Dieter, U. (1972). * Computer methods for sampling from the exponential and * normal distributions. * Comm. ACM, 15, 873-882. */ double igraph_exp_rand(igraph_rng_t *rng) { /* q[k-1] = sum(log(2)^k / k!) k=1,..,n, */ /* The highest n (here 8) is determined by q[n-1] = 1.0 */ /* within standard precision */ const double q[] = { 0.6931471805599453, 0.9333736875190459, 0.9888777961838675, 0.9984959252914960, 0.9998292811061389, 0.9999833164100727, 0.9999985691438767, 0.9999998906925558, 0.9999999924734159, 0.9999999995283275, 0.9999999999728814, 0.9999999999985598, 0.9999999999999289, 0.9999999999999968, 0.9999999999999999, 1.0000000000000000 }; double a, u, ustar, umin; int i; a = 0.; /* precaution if u = 0 is ever returned */ u = igraph_rng_get_unif01(rng); while(u <= 0.0 || u >= 1.0) u = igraph_rng_get_unif01(rng); for (;;) { u += u; if (u > 1.0) break; a += q[0]; } u -= 1.; if (u <= q[0]) return a + u; i = 0; ustar = igraph_rng_get_unif01(rng); umin = ustar; do { ustar = igraph_rng_get_unif01(rng); if (ustar < umin) umin = ustar; i++; } while (u > q[i]); return a + umin * q[0]; } /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000-2001 The R Development Core Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * SYNOPSIS * * #include * double rpois(double lambda) * * DESCRIPTION * * Random variates from the Poisson distribution. * * REFERENCE * * Ahrens, J.H. and Dieter, U. (1982). * Computer generation of Poisson deviates * from modified normal distributions. * ACM Trans. Math. Software 8, 163-179. */ #define a0 -0.5 #define a1 0.3333333 #define a2 -0.2500068 #define a3 0.2000118 #define a4 -0.1661269 #define a5 0.1421878 #define a6 -0.1384794 #define a7 0.1250060 #define one_7 0.1428571428571428571 #define one_12 0.0833333333333333333 #define one_24 0.0416666666666666667 #define repeat for(;;) #define FALSE 0 #define TRUE 1 #define M_1_SQRT_2PI 0.398942280401432677939946059934 /* 1/sqrt(2pi) */ double igraph_rpois(igraph_rng_t *rng, double mu) { /* Factorial Table (0:9)! */ const double fact[10] = { 1., 1., 2., 6., 24., 120., 720., 5040., 40320., 362880. }; /* These are static --- persistent between calls for same mu : */ static IGRAPH_THREAD_LOCAL int l, m; static IGRAPH_THREAD_LOCAL double b1, b2, c, c0, c1, c2, c3; static IGRAPH_THREAD_LOCAL double pp[36], p0, p, q, s, d, omega; static IGRAPH_THREAD_LOCAL double big_l;/* integer "w/o overflow" */ static IGRAPH_THREAD_LOCAL double muprev = 0., muprev2 = 0.;/*, muold = 0.*/ /* Local Vars [initialize some for -Wall]: */ double del, difmuk= 0., E= 0., fk= 0., fx, fy, g, px, py, t, u= 0., v, x; double pois = -1.; int k, kflag, big_mu, new_big_mu = FALSE; if (!R_FINITE(mu)) ML_ERR_return_NAN; if (mu <= 0.) return 0.; big_mu = mu >= 10.; if(big_mu) new_big_mu = FALSE; if (!(big_mu && mu == muprev)) {/* maybe compute new persistent par.s */ if (big_mu) { new_big_mu = TRUE; /* Case A. (recalculation of s,d,l because mu has changed): * The Poisson probabilities pk exceed the discrete normal * probabilities fk whenever k >= m(mu). */ muprev = mu; s = sqrt(mu); d = 6. * mu * mu; big_l = floor(mu - 1.1484); /* = an upper bound to m(mu) for all mu >= 10.*/ } else { /* Small mu ( < 10) -- not using normal approx. */ /* Case B. (start new table and calculate p0 if necessary) */ /*muprev = 0.;-* such that next time, mu != muprev ..*/ if (mu != muprev) { muprev = mu; m = imax2(1, (int) mu); l = 0; /* pp[] is already ok up to pp[l] */ q = p0 = p = exp(-mu); } repeat { /* Step U. uniform sample for inversion method */ u = igraph_rng_get_unif01(rng); if (u <= p0) return 0.; /* Step T. table comparison until the end pp[l] of the pp-table of cumulative Poisson probabilities (0.458 > ~= pp[9](= 0.45792971447) for mu=10 ) */ if (l != 0) { for (k = (u <= 0.458) ? 1 : imin2(l, m); k <= l; k++) if (u <= pp[k]) return (double)k; if (l == 35) /* u > pp[35] */ continue; } /* Step C. creation of new Poisson probabilities p[l..] and their cumulatives q =: pp[k] */ l++; for (k = l; k <= 35; k++) { p *= mu / k; q += p; pp[k] = q; if (u <= q) { l = k; return (double)k; } } l = 35; } /* end(repeat) */ }/* mu < 10 */ } /* end {initialize persistent vars} */ /* Only if mu >= 10 : ----------------------- */ /* Step N. normal sample */ g = mu + s * igraph_norm_rand(rng);/* norm_rand() ~ N(0,1), standard normal */ if (g >= 0.) { pois = floor(g); /* Step I. immediate acceptance if pois is large enough */ if (pois >= big_l) return pois; /* Step S. squeeze acceptance */ fk = pois; difmuk = mu - fk; u = igraph_rng_get_unif01(rng); /* ~ U(0,1) - sample */ if (d * u >= difmuk * difmuk * difmuk) return pois; } /* Step P. preparations for steps Q and H. (recalculations of parameters if necessary) */ if (new_big_mu || mu != muprev2) { /* Careful! muprev2 is not always == muprev because one might have exited in step I or S */ muprev2 = mu; omega = M_1_SQRT_2PI / s; /* The quantities b1, b2, c3, c2, c1, c0 are for the Hermite * approximations to the discrete normal probabilities fk. */ b1 = one_24 / mu; b2 = 0.3 * b1 * b1; c3 = one_7 * b1 * b2; c2 = b2 - 15. * c3; c1 = b1 - 6. * b2 + 45. * c3; c0 = 1. - b1 + 3. * b2 - 15. * c3; c = 0.1069 / mu; /* guarantees majorization by the 'hat'-function. */ } if (g >= 0.) { /* 'Subroutine' F is called (kflag=0 for correct return) */ kflag = 0; goto Step_F; } repeat { /* Step E. Exponential Sample */ E = igraph_exp_rand(rng);/* ~ Exp(1) (standard exponential) */ /* sample t from the laplace 'hat' (if t <= -0.6744 then pk < fk for all mu >= 10.) */ u = 2 * igraph_rng_get_unif01(rng) - 1.; t = 1.8 + fsign(E, u); if (t > -0.6744) { pois = floor(mu + s * t); fk = pois; difmuk = mu - fk; /* 'subroutine' F is called (kflag=1 for correct return) */ kflag = 1; Step_F: /* 'subroutine' F : calculation of px,py,fx,fy. */ if (pois < 10) { /* use factorials from table fact[] */ px = -mu; py = pow(mu, pois) / fact[(int)pois]; } else { /* Case pois >= 10 uses polynomial approximation a0-a7 for accuracy when advisable */ del = one_12 / fk; del = del * (1. - 4.8 * del * del); v = difmuk / fk; if (fabs(v) <= 0.25) px = fk * v * v * (((((((a7 * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v + a0) - del; else /* |v| > 1/4 */ px = fk * log(1. + v) - difmuk - del; py = M_1_SQRT_2PI / sqrt(fk); } x = (0.5 - difmuk) / s; x *= x;/* x^2 */ fx = -0.5 * x; fy = omega * (((c3 * x + c2) * x + c1) * x + c0); if (kflag > 0) { /* Step H. Hat acceptance (E is repeated on rejection) */ if (c * fabs(u) <= py * exp(px + E) - fy * exp(fx + E)) break; } else /* Step Q. Quotient acceptance (rare case) */ if (fy - u * fy <= py * exp(px - fx)) break; }/* t > -.67.. */ } return pois; } #undef a1 #undef a2 #undef a3 #undef a4 #undef a5 #undef a6 #undef a7 double igraph_rgeom(igraph_rng_t *rng, double p) { if (ISNAN(p) || p <= 0 || p > 1) ML_ERR_return_NAN; return igraph_rpois(rng, igraph_exp_rand(rng) * ((1 - p) / p)); } /* This is from nmath/rbinom.c */ #define repeat for(;;) double igraph_rbinom(igraph_rng_t *rng, double nin, double pp) { /* FIXME: These should become THREAD_specific globals : */ static IGRAPH_THREAD_LOCAL double c, fm, npq, p1, p2, p3, p4, qn; static IGRAPH_THREAD_LOCAL double xl, xll, xlr, xm, xr; static IGRAPH_THREAD_LOCAL double psave = -1.0; static IGRAPH_THREAD_LOCAL int nsave = -1; static IGRAPH_THREAD_LOCAL int m; double f, f1, f2, u, v, w, w2, x, x1, x2, z, z2; double p, q, np, g, r, al, alv, amaxp, ffm, ynorm; int i,ix,k, n; if (!R_FINITE(nin)) ML_ERR_return_NAN; n = floor(nin + 0.5); if (n != nin) ML_ERR_return_NAN; if (!R_FINITE(pp) || /* n=0, p=0, p=1 are not errors */ n < 0 || pp < 0. || pp > 1.) ML_ERR_return_NAN; if (n == 0 || pp == 0.) return 0; if (pp == 1.) return n; p = fmin(pp, 1. - pp); q = 1. - p; np = n * p; r = p / q; g = r * (n + 1); /* Setup, perform only when parameters change [using static (globals): */ /* FIXING: Want this thread safe -- use as little (thread globals) as possible */ if (pp != psave || n != nsave) { psave = pp; nsave = n; if (np < 30.0) { /* inverse cdf logic for mean less than 30 */ qn = pow(q, (double) n); goto L_np_small; } else { ffm = np + p; m = ffm; fm = m; npq = np * q; p1 = (int)(2.195 * sqrt(npq) - 4.6 * q) + 0.5; xm = fm + 0.5; xl = xm - p1; xr = xm + p1; c = 0.134 + 20.5 / (15.3 + fm); al = (ffm - xl) / (ffm - xl * p); xll = al * (1.0 + 0.5 * al); al = (xr - ffm) / (xr * q); xlr = al * (1.0 + 0.5 * al); p2 = p1 * (1.0 + c + c); p3 = p2 + c / xll; p4 = p3 + c / xlr; } } else if (n == nsave) { if (np < 30.0) goto L_np_small; } /*-------------------------- np = n*p >= 30 : ------------------- */ repeat { u = igraph_rng_get_unif01(rng) * p4; v = igraph_rng_get_unif01(rng); /* triangular region */ if (u <= p1) { ix = xm - p1 * v + u; goto finis; } /* parallelogram region */ if (u <= p2) { x = xl + (u - p1) / c; v = v * c + 1.0 - fabs(xm - x) / p1; if (v > 1.0 || v <= 0.) continue; ix = x; } else { if (u > p3) { /* right tail */ ix = xr - log(v) / xlr; if (ix > n) continue; v = v * (u - p3) * xlr; } else {/* left tail */ ix = xl + log(v) / xll; if (ix < 0) continue; v = v * (u - p2) * xll; } } /* determine appropriate way to perform accept/reject test */ k = abs(ix - m); if (k <= 20 || k >= npq / 2 - 1) { /* explicit evaluation */ f = 1.0; if (m < ix) { for (i = m + 1; i <= ix; i++) f *= (g / i - r); } else if (m != ix) { for (i = ix + 1; i <= m; i++) f /= (g / i - r); } if (v <= f) goto finis; } else { /* squeezing using upper and lower bounds on log(f(x)) */ amaxp = (k / npq) * ((k * (k / 3. + 0.625) + 0.1666666666666) / npq + 0.5); ynorm = -k * k / (2.0 * npq); alv = log(v); if (alv < ynorm - amaxp) goto finis; if (alv <= ynorm + amaxp) { /* Stirling's formula to machine accuracy */ /* for the final acceptance/rejection test */ x1 = ix + 1; f1 = fm + 1.0; z = n + 1 - fm; w = n - ix + 1.0; z2 = z * z; x2 = x1 * x1; f2 = f1 * f1; w2 = w * w; if (alv <= xm * log(f1 / x1) + (n - m + 0.5) * log(z / w) + (ix - m) * log(w * p / (x1 * q)) + (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / f2) / f2) / f2) / f2) / f1 / 166320.0 + (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / z2) / z2) / z2) / z2) / z / 166320.0 + (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / x2) / x2) / x2) / x2) / x1 / 166320.0 + (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / w2) / w2) / w2) / w2) / w / 166320.) goto finis; } } } L_np_small: /*---------------------- np = n*p < 30 : ------------------------- */ repeat { ix = 0; f = qn; u = igraph_rng_get_unif01(rng); repeat { if (u < f) goto finis; if (ix > 110) break; u -= f; ix++; f *= (g / ix - r); } } finis: if (psave > 0.5) ix = n - ix; return (double)ix; } igraph_real_t igraph_rexp(igraph_rng_t *rng, double rate) { igraph_real_t scale = 1.0 / rate; if (!IGRAPH_FINITE(scale) || scale <= 0.0) { if (scale == 0.0) { return 0.0; } return IGRAPH_NAN; } return scale * igraph_exp_rand(rng); } /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000 The R Core Team * Copyright (C) 2003 The R Foundation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * http://www.r-project.org/Licenses/ * * SYNOPSIS * * double dnorm4(double x, double mu, double sigma, int give_log) * {dnorm (..) is synonymous and preferred inside R} * * DESCRIPTION * * Compute the density of the normal distribution. */ double igraph_dnorm(double x, double mu, double sigma, int give_log) { #ifdef IEEE_754 if (ISNAN(x) || ISNAN(mu) || ISNAN(sigma)) return x + mu + sigma; #endif if(!R_FINITE(sigma)) return R_D__0; if(!R_FINITE(x) && mu == x) return ML_NAN;/* x-mu is NaN */ if (sigma <= 0) { if (sigma < 0) ML_ERR_return_NAN; /* sigma == 0 */ return (x == mu) ? ML_POSINF : R_D__0; } x = (x - mu) / sigma; if(!R_FINITE(x)) return R_D__0; return (give_log ? -(M_LN_SQRT_2PI + 0.5 * x * x + log(sigma)) : M_1_SQRT_2PI * exp(-0.5 * x * x) / sigma); /* M_1_SQRT_2PI = 1 / sqrt(2 * pi) */ } /* This is from nmath/rgamma.c */ /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000--2008 The R Core Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * http://www.r-project.org/Licenses/ * * SYNOPSIS * * #include * double rgamma(double a, double scale); * * DESCRIPTION * * Random variates from the gamma distribution. * * REFERENCES * * [1] Shape parameter a >= 1. Algorithm GD in: * * Ahrens, J.H. and Dieter, U. (1982). * Generating gamma variates by a modified * rejection technique. * Comm. ACM, 25, 47-54. * * * [2] Shape parameter 0 < a < 1. Algorithm GS in: * * Ahrens, J.H. and Dieter, U. (1974). * Computer methods for sampling from gamma, beta, * poisson and binomial distributions. * Computing, 12, 223-246. * * Input: a = parameter (mean) of the standard gamma distribution. * Output: a variate from the gamma(a)-distribution */ double igraph_rgamma(igraph_rng_t *rng, double a, double scale) { /* Constants : */ const static double sqrt32 = 5.656854; const static double exp_m1 = 0.36787944117144232159;/* exp(-1) = 1/e */ /* Coefficients q[k] - for q0 = sum(q[k]*a^(-k)) * Coefficients a[k] - for q = q0+(t*t/2)*sum(a[k]*v^k) * Coefficients e[k] - for exp(q)-1 = sum(e[k]*q^k) */ const static double q1 = 0.04166669; const static double q2 = 0.02083148; const static double q3 = 0.00801191; const static double q4 = 0.00144121; const static double q5 = -7.388e-5; const static double q6 = 2.4511e-4; const static double q7 = 2.424e-4; const static double a1 = 0.3333333; const static double a2 = -0.250003; const static double a3 = 0.2000062; const static double a4 = -0.1662921; const static double a5 = 0.1423657; const static double a6 = -0.1367177; const static double a7 = 0.1233795; /* State variables [FIXME for threading!] :*/ static double aa = 0.; static double aaa = 0.; static double s, s2, d; /* no. 1 (step 1) */ static double q0, b, si, c;/* no. 2 (step 4) */ double e, p, q, r, t, u, v, w, x, ret_val; if (!R_FINITE(a) || !R_FINITE(scale) || a < 0.0 || scale <= 0.0) { if(scale == 0.) return 0.; ML_ERR_return_NAN; } if (a < 1.) { /* GS algorithm for parameters a < 1 */ if(a == 0) return 0.; e = 1.0 + exp_m1 * a; repeat { p = e * igraph_rng_get_unif01(rng); if (p >= 1.0) { x = -log((e - p) / a); if (igraph_exp_rand(rng) >= (1.0 - a) * log(x)) break; } else { x = exp(log(p) / a); if (igraph_exp_rand(rng) >= x) break; } } return scale * x; } /* --- a >= 1 : GD algorithm --- */ /* Step 1: Recalculations of s2, s, d if a has changed */ if (a != aa) { aa = a; s2 = a - 0.5; s = sqrt(s2); d = sqrt32 - s * 12.0; } /* Step 2: t = standard normal deviate, x = (s,1/2) -normal deviate. */ /* immediate acceptance (i) */ t = igraph_norm_rand(rng); x = s + 0.5 * t; ret_val = x * x; if (t >= 0.0) return scale * ret_val; /* Step 3: u = 0,1 - uniform sample. squeeze acceptance (s) */ u = igraph_rng_get_unif01(rng); if (d * u <= t * t * t) return scale * ret_val; /* Step 4: recalculations of q0, b, si, c if necessary */ if (a != aaa) { aaa = a; r = 1.0 / a; q0 = ((((((q7 * r + q6) * r + q5) * r + q4) * r + q3) * r + q2) * r + q1) * r; /* Approximation depending on size of parameter a */ /* The constants in the expressions for b, si and c */ /* were established by numerical experiments */ if (a <= 3.686) { b = 0.463 + s + 0.178 * s2; si = 1.235; c = 0.195 / s - 0.079 + 0.16 * s; } else if (a <= 13.022) { b = 1.654 + 0.0076 * s2; si = 1.68 / s + 0.275; c = 0.062 / s + 0.024; } else { b = 1.77; si = 0.75; c = 0.1515 / s; } } /* Step 5: no quotient test if x not positive */ if (x > 0.0) { /* Step 6: calculation of v and quotient q */ v = t / (s + s); if (fabs(v) <= 0.25) q = q0 + 0.5 * t * t * ((((((a7 * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v; else q = q0 - s * t + 0.25 * t * t + (s2 + s2) * log(1.0 + v); /* Step 7: quotient acceptance (q) */ if (log(1.0 - u) <= q) return scale * ret_val; } repeat { /* Step 8: e = standard exponential deviate * u = 0,1 -uniform deviate * t = (b,si)-double exponential (laplace) sample */ e = igraph_exp_rand(rng); u = igraph_rng_get_unif01(rng); u = u + u - 1.0; if (u < 0.0) t = b - si * e; else t = b + si * e; /* Step 9: rejection if t < tau(1) = -0.71874483771719 */ if (t >= -0.71874483771719) { /* Step 10: calculation of v and quotient q */ v = t / (s + s); if (fabs(v) <= 0.25) q = q0 + 0.5 * t * t * ((((((a7 * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v; else q = q0 - s * t + 0.25 * t * t + (s2 + s2) * log(1.0 + v); /* Step 11: hat acceptance (h) */ /* (if q not positive go to step 8) */ if (q > 0.0) { w = expm1(q); /* ^^^^^ original code had approximation with rel.err < 2e-7 */ /* if t is rejected sample again at step 8 */ if (c * fabs(u) <= w * exp(e - 0.5 * t * t)) break; } } } /* repeat .. until `t' is accepted */ x = s + 0.5 * t; return scale * x * x; } #endif int igraph_rng_get_dirichlet(igraph_rng_t *rng, const igraph_vector_t *alpha, igraph_vector_t *result) { igraph_integer_t len=igraph_vector_size(alpha); igraph_integer_t j; igraph_real_t sum=0.0; if (len < 2) { IGRAPH_ERROR("Dirichlet parameter vector too short, must " "have at least two entries", IGRAPH_EINVAL); } if (igraph_vector_min(alpha) <= 0) { IGRAPH_ERROR("Dirichlet concentration parameters must be positive", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vector_resize(result, len)); RNG_BEGIN(); for (j = 0; j < len; j++) { VECTOR(*result)[j] = igraph_rng_get_gamma(rng, VECTOR(*alpha)[j], 1.0); sum += VECTOR(*result)[j]; } for (j = 0; j < len; j++) { VECTOR(*result)[j] /= sum; } RNG_END(); return 0; } /********************************************************** * Testing purposes * *********************************************************/ /* int main() { */ /* int i; */ /* RNG_BEGIN(); */ /* for (i=0; i<1000; i++) { */ /* printf("%li ", RNG_INTEGER(1,10)); */ /* } */ /* printf("\n"); */ /* for (i=0; i<1000; i++) { */ /* printf("%f ", RNG_UNIF(0,1)); */ /* } */ /* printf("\n"); */ /* for (i=0; i<1000; i++) { */ /* printf("%f ", RNG_NORMAL(0,5)); */ /* } */ /* printf("\n"); */ /* RNG_END(); */ /* return 0; */ /* } */ igraph/src/foreign-gml-parser.h0000644000175100001440000000533713431000472016204 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton interface for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { STRING = 258, NUM = 259, KEYWORD = 260, LISTOPEN = 261, LISTCLOSE = 262, EOFF = 263, ERROR = 264 }; #endif /* Tokens. */ #define STRING 258 #define NUM 259 #define KEYWORD 260 #define LISTOPEN 261 #define LISTCLOSE 262 #define EOFF 263 #define ERROR 264 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 93 "src/foreign-gml-parser.y" { struct { char *s; int len; } str; void *tree; double real; } /* Line 1529 of yacc.c. */ #line 76 "y.tab.h" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif igraph/src/drl_layout_3d.cpp0000644000175100001440000001071713431000472015601 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Layout // // This program implements a parallel force directed graph drawing // algorithm. The algorithm used is based upon a random decomposition // of the graph and simulated shared memory of node position and density. // In this version, the simulated shared memory is spread among all processors // // The structure of the inputs and outputs of this code will be displayed // if the program is called without parameters, or if an erroneous // parameter is passed to the program. // // S. Martin // 5/6/2005 // C++ library routines #include #include #include #include #include #include #include using namespace std; // layout routines and constants #include "drl_layout_3d.h" #include "drl_parse.h" #include "drl_graph_3d.h" // MPI #ifdef MUSE_MPI #include #endif using namespace drl3d; #include "igraph_layout.h" #include "igraph_random.h" #include "igraph_interface.h" /** * \function igraph_layout_drl_3d * The DrL layout generator, 3d version. * * This function implements the force-directed DrL layout generator. * Please see more in the technical report: Martin, S., Brown, W.M., * Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) * Layout. SAND Reports, 2008. 2936: p. 1-10. * * This function uses a modified DrL generator that does * the layout in three dimensions. * \param graph The input graph. * \param use_seed Logical scalar, if true, then the coordinates * supplied in the \p res argument are used as starting points. * \param res Pointer to a matrix, the result layout is stored * here. It will be resized as needed. * \param options The parameters to pass to the layout generator. * \param weights Edge weights, pointer to a vector. If this is a null * pointer then every edge will have the same weight. * \param fixed Pointer to a logical vector, or a null pointer. This * can be used to fix the position of some vertices. Vertices for * which it is true will not be moved, but stay at the coordinates * given in the \p res matrix. This argument is ignored if it is a * null pointer or if use_seed is false. * \return Error code. * * Time complexity: ???. * * \sa \ref igraph_layout_drl() for the standard 2d version. */ int igraph_layout_drl_3d(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_layout_drl_options_t *options, const igraph_vector_t *weights, const igraph_vector_bool_t *fixed) { RNG_BEGIN(); drl3d::graph neighbors(graph, options, weights); neighbors.init_parms(options); if (use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, igraph_vcount(graph), 3)); neighbors.read_real(res, fixed); } neighbors.draw_graph(res); RNG_END(); return 0; } igraph/src/prpack.cpp0000644000175100001440000000657113431000472014320 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "prpack.h" #include "prpack/prpack_igraph_graph.h" #include "prpack/prpack_solver.h" #include "igraph_error.h" using namespace prpack; using namespace std; /* * PRPACK-based implementation of \c igraph_personalized_pagerank. * * See \c igraph_personalized_pagerank for the documentation of the parameters. */ int igraph_personalized_pagerank_prpack(const igraph_t *graph, igraph_vector_t *vector, igraph_real_t *value, const igraph_vs_t vids, igraph_bool_t directed, igraph_real_t damping, igraph_vector_t *reset, const igraph_vector_t *weights) { long int i, no_of_nodes = igraph_vcount(graph), nodes_to_calc; igraph_vit_t vit; double* u = 0; double* v = 0; const prpack_result* res; if (reset) { /* Normalize reset vector so the sum is 1 */ double reset_sum = igraph_vector_sum(reset); if (igraph_vector_min(reset) < 0) { IGRAPH_ERROR("the reset vector must not contain negative elements", IGRAPH_EINVAL); } if (reset_sum == 0) { IGRAPH_ERROR("the sum of the elements in the reset vector must not be zero", IGRAPH_EINVAL); } // Construct the personalization vector v = new double[no_of_nodes]; for (i = 0; i < no_of_nodes; i++) { v[i] = VECTOR(*reset)[i] / reset_sum; } } // Construct and run the solver prpack_igraph_graph prpack_graph(graph, weights, directed); prpack_solver solver(&prpack_graph, false); res = solver.solve(damping, 1e-10, u, v, ""); // Delete the personalization vector if (v) { delete[] v; } // Check whether the solver converged // TODO: this is commented out because some of the solvers do not implement it yet /* if (!res->converged) { IGRAPH_WARNING("PRPACK solver failed to converge. Results may be inaccurate."); } */ // Fill the result vector IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); IGRAPH_CHECK(igraph_vector_resize(vector, nodes_to_calc)); for (IGRAPH_VIT_RESET(vit), i = 0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { VECTOR(*vector)[i] = res->x[(long int)IGRAPH_VIT_GET(vit)]; } igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); // TODO: can we get the eigenvalue? We'll just fake it until we can. if (value) { *value = 1.0; } delete res; return IGRAPH_SUCCESS; } igraph/src/rinterface_extra.c0000644000175100001440000002135413431000472016021 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library R interface. Copyright (C) 2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph.h" #include #include #include #include "rinterface.h" #include /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++C */ /* C */ /* Given a HIERARCHIC CLUSTERING, described as a sequence of C */ /* agglomerations, prepare the seq. of aggloms. and "horiz." C */ /* order of objects for plotting the dendrogram using S routine C */ /* 'plclust'. C */ /* C */ /* Parameters: C */ /* C */ /* IA, IB: vectors of dimension N defining the agglomer- C */ /* ations. C */ /* IIA, IIB: used to store IA and IB values differently C */ /* (in form needed for S command 'plclust' C */ /* IORDER: "horiz." order of objects for dendrogram C */ /* C */ /* F. Murtagh, ESA/ESO/STECF, Garching, June 1991 C */ /* C */ /* HISTORY C */ /* C */ /* Adapted from routine HCASS, which additionally determines C */ /* cluster assignments at all levels, at extra comput. expense C */ /* C */ /* ---------------------------------------------------------------C */ int igraphhcass2(int *n, int *ia, int *ib, int *iorder, int *iia, int *iib) { /* System generated locals */ int i__1, i__2, i__3; /* Local variables */ static int i__, j, k, k1, k2, loc; /* Args */ /* Var */ /* Following bit is to get seq. of merges into format acceptable to plclust I coded clusters as lowest seq. no. of constituents; S's 'hclust' codes singletons as -ve numbers, and non-singletons with their seq. nos. */ /* Parameter adjustments */ --iib; --iia; --iorder; --ib; --ia; /* Function Body */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { iia[i__] = ia[i__]; iib[i__] = ib[i__]; } i__1 = *n - 2; for (i__ = 1; i__ <= i__1; ++i__) { /* In the following, smallest (+ve or -ve) seq. no. wanted */ /* Computing MIN */ i__2 = ia[i__], i__3 = ib[i__]; k = i__2 < i__3 ? i__2 : i__3; i__2 = *n - 1; for (j = i__ + 1; j <= i__2; ++j) { if (ia[j] == k) { iia[j] = -i__; } if (ib[j] == k) { iib[j] = -i__; } } } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { iia[i__] = -iia[i__]; iib[i__] = -iib[i__]; } i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { if (iia[i__] > 0 && iib[i__] < 0) { k = iia[i__]; iia[i__] = iib[i__]; iib[i__] = k; } if (iia[i__] > 0 && iib[i__] > 0) { /* Computing MIN */ i__2 = iia[i__], i__3 = iib[i__]; k1 = i__2 < i__3 ? i__2 : i__3; /* Computing MAX */ i__2 = iia[i__], i__3 = iib[i__]; k2 = i__2 > i__3 ? i__2 : i__3; iia[i__] = k1; iib[i__] = k2; } } /* NEW PART FOR 'ORDER' */ iorder[1] = iia[*n - 1]; iorder[2] = iib[*n - 1]; loc = 2; for (i__ = *n - 2; i__ >= 1; --i__) { i__1 = loc; for (j = 1; j <= i__1; ++j) { if (iorder[j] == i__) { /* REPLACE IORDER(J) WITH IIA(I) AND IIB(I) */ iorder[j] = iia[i__]; if (j == loc) { ++loc; iorder[loc] = iib[i__]; } else { ++loc; i__2 = j + 2; for (k = loc; k >= i__2; --k) { iorder[k] = iorder[k - 1]; } iorder[j + 1] = iib[i__]; } goto L171; } } /* SHOULD NEVER REACH HERE */ L171: ; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { iorder[i__] = -iorder[i__]; } return 0; } /* hcass2_ */ SEXP R_igraph_psumtree_draw(SEXP plength, SEXP howmany, SEXP prob) { SEXP result; int length=INTEGER(plength)[0]; int i, n=INTEGER(howmany)[0]; igraph_psumtree_t tree; igraph_real_t sum; PROTECT(result=NEW_INTEGER(n)); igraph_psumtree_init(&tree, length); if (isNull(prob)) { for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // **************************************************************************************************** // *** COPYRIGHT NOTICE ******************************************************************************* // graph_simp.h - graph data structure // Copyright (C) 2006-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // **************************************************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science AND Santa Fe Institute // Created : 21 June 2006 // Modified : 23 December 2007 (cleaned up for public consumption) // // ************************************************************************ // // Simple graph data structure. The basic structure is an adjacency // list of edges, along with degree information for the vertices. // // ************************************************************************ #ifndef IGRAPH_HRG_SIMPLEGRAPH #define IGRAPH_HRG_SIMPLEGRAPH #include #include #include #include "hrg_rbtree.h" using namespace std; namespace fitHRG { // ******** Basic Structures ********************************************* #ifndef IGRAPH_HRG_SIMPLEEDGE #define IGRAPH_HRG_SIMPLEEDGE class simpleEdge { public: int x; // index of edge terminator simpleEdge* next; // pointer to next elementd simpleEdge(): x(-1), next(0) { } ~simpleEdge() { } }; #endif #ifndef IGRAPH_HRG_SIMPLEVERT #define IGRAPH_HRG_SIMPLEVERT class simpleVert { public: string name; // (external) name of vertex int degree; // degree of this vertex int group_true; // index of vertex's true group simpleVert(): name(""), degree(0), group_true(-1) { } ~simpleVert() { } }; #endif #ifndef IGRAPH_HRG_TWOEDGE #define IGRAPH_HRG_TWOEDGE class twoEdge { public: int o; // index of edge originator int x; // index of edge terminator twoEdge(): o(-1), x(-1) { } ~twoEdge() { } }; #endif // ******** Graph Class with Edge Statistics ***************************** class simpleGraph { public: simpleGraph(const int); ~simpleGraph(); // add group label to vertex i bool addGroup(const int, const int); // add (i,j) to graph bool addLink(const int, const int); // true if (i,j) is already in graph bool doesLinkExist(const int, const int); // returns A(i,j) double getAdjacency(const int, const int); // returns degree of vertex i int getDegree(const int); // returns group label of vertex i int getGroupLabel(const int); // returns name of vertex i string getName(const int); // returns edge list of vertex i simpleEdge* getNeighborList(const int); // return pointer to a node simpleVert* getNode(const int); // returns num_groups int getNumGroups(); // returns m int getNumLinks(); // returns n int getNumNodes(); // set name of vertex i bool setName(const int, const string); private: simpleVert* nodes; // list of nodes simpleEdge** nodeLink; // linked list of neighbors to vertex simpleEdge** nodeLinkTail; // pointers to tail of neighbor list double** A; // adjacency matrix for this graph twoEdge* E; // list of all edges (array) int n; // number of vertices int m; // number of directed edges int num_groups; // number of bins in node histograms // quicksort functions void QsortMain(block*, int, int); int QsortPartition(block*, int, int, int); }; } // namespace fitHRG #endif igraph/src/gengraph_hash.h0000644000175100001440000001763113431000472015302 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef HASH_H #define HASH_H #include #include "gengraph_definitions.h" //_________________________________________________________________________ // Hash table profiling... Active only if definition below is uncommented //_________________________________________________________________________ //#define _HASH_PROFILE namespace gengraph { #ifdef _HASH_PROFILE void _hash_add_iter(); void _hash_add_call(); void _hash_put_iter(); void _hash_put_call(); void _hash_rm_iter(); void _hash_rm_call(); void _hash_find_iter(); void _hash_find_call(); void _hash_rand_iter(); void _hash_rand_call(); void _hash_expand_call(); void _hash_prof(); #define _HASH_ADD_ITER() _hash_add_iter() #define _HASH_ADD_CALL() _hash_add_call() #define _HASH_PUT_ITER() _hash_put_iter() #define _HASH_PUT_CALL() _hash_put_call() #define _HASH_RM_ITER() _hash_rm_iter() #define _HASH_RM_CALL() _hash_rm_call() #define _HASH_FIND_ITER() _hash_find_iter() #define _HASH_FIND_CALL() _hash_find_call() #define _HASH_RAND_ITER() _hash_rand_iter() #define _HASH_RAND_CALL() _hash_rand_call() #define _HASH_EXP_CALL() _hash_expand_call() #else #define _HASH_ADD_ITER() {} #define _HASH_ADD_CALL() {} #define _HASH_PUT_ITER() {} #define _HASH_PUT_CALL() {} #define _HASH_RM_ITER() {} #define _HASH_RM_CALL() {} #define _HASH_FIND_ITER() {} #define _HASH_FIND_CALL() {} #define _HASH_RAND_ITER() {} #define _HASH_RAND_CALL() {} #define _HASH_EXP_CALL() {} #endif //_________________________________________________________________________ // Hash Table properties. Works best when HASH_SIZE_IS_POWER2 is uncommented // but takes 2.25 times the needed space, in average (from 1.5 to 3) // If you have memory issues, Try to comment it: tables will take 1.5 times // the minimal space //_________________________________________________________________________ #define HASH_SIZE_IS_POWER2 #define MACRO_RATHER_THAN_INLINE // under HASH_MIN_SIZE, vectors are not hash table (just a simle array) #define HASH_MIN_SIZE 100 #define IS_HASH(x) ((x)>HASH_MIN_SIZE) #define HASH_NONE (-1) #ifdef HASH_SIZE_IS_POWER2 inline int HASH_EXPAND(int x) { _HASH_EXP_CALL(); x+=x; x |= x>>1; x |= x>>2; x |= x>>4; x |= x>>8; x |= x>>16; return x+1; } #define HASH_KEY(x,size) ((x*2198737)&((size)-1)) #endif //HASH_SIZE_IS_POWER2 #ifdef MACRO_RATHER_THAN_INLINE #ifndef HASH_SIZE_IS_POWER2 #define HASH_EXPAND(x) ((x)+((x)>>1)) #define HASH_UNEXPAND(x) ((((x)<<1)+1)/3) #define HASH_KEY(x,size) ((x)%(size)) #endif //HASH_SIZE_IS_POWER2 #define HASH_SIZE(x) (IS_HASH(x) ? HASH_EXPAND(x) : (x) ) #define HASH_REKEY(k,size) ((k)==0 ? (size)-1 : (k)-1) #else //MACRO_RATHER_THAN_INLINE #ifndef HASH_SIZE_IS_POWER2 inline int HASH_KEY(const int x, const int size) { assert(x>=0); return x%size; }; inline int HASH_EXPAND(const int x) { _HASH_EXP_CALL(); return x+(x>>1); }; inline int HASH_UNEXPAND(const int x) { return ((x<<1)+1)/3; }; #endif //HASH_SIZE_IS_POWER2 inline int HASH_REKEY(const int k, const int s) { assert(k>=0); if(k==0) return s-1; else return k-1; }; inline int HASH_SIZE(const int x) { if(IS_HASH(x)) return HASH_EXPAND(x); else return x; }; #endif //MACRO_RATHER_THAN_INLINE inline int HASH_PAIR_KEY(const int x, const int y, const int size) { return HASH_KEY(x*1434879443+y, size); } //_________________________________________________________________________ // Hash-only functions : table must NOT be Raw. // the argument 'size' is the total size of the hash table //_________________________________________________________________________ // copy hash table into raw vector inline void H_copy(int *mem, int *h, int size) { for(int i=HASH_EXPAND(size); i--; h++) if(*h != HASH_NONE) *(mem++)=*h; } // Look for the place to add an element. Return NULL if element is already here. inline int* H_add(int* h, const int size, int a) { _HASH_ADD_CALL(); _HASH_ADD_ITER(); int k = HASH_KEY(a, size); if(h[k]==HASH_NONE) return h+k; while(h[k]!=a) { _HASH_ADD_ITER(); k=HASH_REKEY(k,size); if(h[k]==HASH_NONE) return h+k; } return NULL; } // would element be well placed in newk ? inline bool H_better(const int a, const int size, const int currentk, const int newk) { int k = HASH_KEY(a, size); if(newk=newk); else return (k=newk); } // removes h[k] inline void H_rm(int* h, const int size, int k) { _HASH_RM_CALL(); int lasthole = k; do { _HASH_RM_ITER(); k = HASH_REKEY(k,size); int next = h[k]; if(next==HASH_NONE) break; if(H_better(next,size,k,lasthole)) { h[lasthole] = next; lasthole = k; } } while(true); h[lasthole] = HASH_NONE; } //put a inline int* H_put(int* h, const int size, const int a) { assert(H_add(h,size,a)!=NULL); _HASH_PUT_CALL(); _HASH_PUT_ITER(); int k = HASH_KEY(a, size); while(h[k]!=HASH_NONE) { k=HASH_REKEY(k,size); _HASH_PUT_ITER(); } h[k]=a; assert(H_add(h,size,a)==NULL); return h+k; } // find A inline int H_find(int *h, int size, const int a) { assert(H_add(h,size,a)==NULL); _HASH_FIND_CALL(); _HASH_FIND_ITER(); int k = HASH_KEY(a, size); while(h[k]!=a) { k=HASH_REKEY(k,size); _HASH_FIND_ITER(); } return k; } // Look for the place to add an element. Return NULL if element is already here. inline bool H_pair_insert(int* h, const int size, int a, int b) { _HASH_ADD_CALL(); _HASH_ADD_ITER(); int k = HASH_PAIR_KEY(a, b, size); if(h[2*k]==HASH_NONE) { h[2*k]=a; h[2*k+1]=b; return true; } while(h[2*k]!=a || h[2*k+1]!=b) { _HASH_ADD_ITER(); k=HASH_REKEY(k,size); if(h[2*k]==HASH_NONE) { h[2*k]=a; h[2*k+1]=b; return true; } } return false; } //_________________________________________________________________________ // Generic functions : table can be either Hash or Raw. // the argument 'size' is the number of elements //_________________________________________________________________________ // Look for an element inline bool H_is(int *mem, const int size, const int elem) { if(IS_HASH(size)) return (H_add(mem, HASH_EXPAND(size), elem)==NULL); else return fast_search(mem, size, elem)!=NULL; } //pick random location (containing an element) inline int* H_random(int* mem, int size) { if(!IS_HASH(size)) return mem+(my_random()%size); _HASH_RAND_CALL(); size = HASH_EXPAND(size); int* yo; do { yo = mem + HASH_KEY(my_random(),size); _HASH_RAND_ITER(); } while(*yo==HASH_NONE); return yo; } // replace *k by b inline int* H_rpl(int *mem, int size, int* k, const int b) { assert(!H_is(mem,size,b)); if(!IS_HASH(size)) { *k=b; return k; } else { size = HASH_EXPAND(size); assert(mem + int(k-mem) == k); H_rm(mem, size, int(k-mem)); return H_put(mem, size, b); } } // replace a by b inline int* H_rpl(int *mem, int size, const int a, const int b) { assert(H_is(mem,size,a)); assert(!H_is(mem,size,b)); if(!IS_HASH(size)) return fast_rpl(mem,a,b); else { size = HASH_EXPAND(size); H_rm(mem, size, H_find(mem, size, a)); return H_put(mem, size, b); } } } // namespace gengraph #endif //HASH_H igraph/src/dstatn.f0000644000175100001440000000272413431000472013774 0ustar hornikusersc c %---------------------------------------------% c | Initialize statistic and timing information | c | for nonsymmetric Arnoldi code. | c %---------------------------------------------% c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\SCCS Information: @(#) c FILE: statn.F SID: 2.4 DATE OF SID: 4/20/96 RELEASE: 2 c subroutine igraphdstatn c c %--------------------------------% c | See stat.doc for documentation | c %--------------------------------% c include 'stat.h' c c %-----------------------% c | Executable Statements | c %-----------------------% c nopx = 0 nbx = 0 nrorth = 0 nitref = 0 nrstrt = 0 c tnaupd = 0.0D+0 tnaup2 = 0.0D+0 tnaitr = 0.0D+0 tneigh = 0.0D+0 tngets = 0.0D+0 tnapps = 0.0D+0 tnconv = 0.0D+0 titref = 0.0D+0 tgetv0 = 0.0D+0 trvec = 0.0D+0 c c %----------------------------------------------------% c | User time including reverse communication overhead | c %----------------------------------------------------% c tmvopx = 0.0D+0 tmvbx = 0.0D+0 c return c c c %---------------% c | End of igraphdstatn | c %---------------% c end igraph/src/motifs.c0000644000175100001440000010216313431000472013773 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_motifs.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_interface.h" #include "igraph_nongraph.h" #include "igraph_structural.h" #include "igraph_stack.h" #include "config.h" #include extern unsigned int igraph_i_isoclass_3[]; extern unsigned int igraph_i_isoclass_4[]; extern unsigned int igraph_i_isoclass_3u[]; extern unsigned int igraph_i_isoclass_4u[]; extern unsigned int igraph_i_isoclass2_3[]; extern unsigned int igraph_i_isoclass2_4[]; extern unsigned int igraph_i_isoclass2_3u[]; extern unsigned int igraph_i_isoclass2_4u[]; extern unsigned int igraph_i_isoclass_3_idx[]; extern unsigned int igraph_i_isoclass_4_idx[]; extern unsigned int igraph_i_isoclass_3u_idx[]; extern unsigned int igraph_i_isoclass_4u_idx[]; /** * Callback function for igraph_motifs_randesu that counts the motifs by * isomorphism class in a histogram. */ igraph_bool_t igraph_i_motifs_randesu_update_hist(const igraph_t *graph, igraph_vector_t *vids, int isoclass, void* extra) { igraph_vector_t *hist = (igraph_vector_t*)extra; IGRAPH_UNUSED(graph); IGRAPH_UNUSED(vids); VECTOR(*hist)[isoclass]++; return 0; } /** * \function igraph_motifs_randesu * \brief Count the number of motifs in a graph * * * Motifs are small connected subgraphs of a given structure in a * graph. It is argued that the motif profile (ie. the number of * different motifs in the graph) is characteristic for different * types of networks and network function is related to the motifs in * the graph. * * * This function is able to find the different motifs of size three * and four (ie. the number of different subgraphs with three and four * vertices) in the network. * * * In a big network the total number of motifs can be very large, so * it takes a lot of time to find all of them, a sampling method can * be used. This function is capable of doing sampling via the * \c cut_prob argument. This argument gives the probability that * a branch of the motif search tree will not be explored. See * S. Wernicke and F. Rasche: FANMOD: a tool for fast network motif * detection, Bioinformatics 22(9), 1152--1153, 2006 for details. * * * Set the \c cut_prob argument to a zero vector for finding all * motifs. * * * Directed motifs will be counted in directed graphs and undirected * motifs in undirected graphs. * * \param graph The graph to find the motifs in. * \param hist The result of the computation, it gives the number of * motifs found for each isomorphism class. See * \ref igraph_isoclass() for help about isomorphism classes. * Note that this function does \em not count isomorphism * classes that are not connected and will report NaN (more * precisely \c IGRAPH_NAN) for them. * \param size The size of the motifs to search for. Only three and * four are implemented currently. The limitation is not in the * motif finding code, but the graph isomorphism code. * \param cut_prob Vector of probabilities for cutting the search tree * at a given level. The first element is the first level, etc. * Supply all zeros here (of length \c size) to find all motifs * in a graph. * \return Error code. * \sa \ref igraph_motifs_randesu_estimate() for estimating the number * of motifs in a graph, this can help to set the \c cut_prob * parameter; \ref igraph_motifs_randesu_no() to calculate the total * number of motifs of a given size in a graph; * \ref igraph_motifs_randesu_callback() for calling a callback function * for every motif found. * * Time complexity: TODO. * * \example examples/simple/igraph_motifs_randesu.c */ int igraph_motifs_randesu(const igraph_t *graph, igraph_vector_t *hist, int size, const igraph_vector_t *cut_prob) { int histlen; if (size != 3 && size != 4) { IGRAPH_ERROR("Only 3 and 4 vertex motifs are implemented", IGRAPH_EINVAL); } if (size==3) { histlen = igraph_is_directed(graph) ? 16 : 4; } else { histlen = igraph_is_directed(graph) ? 218 : 11; } IGRAPH_CHECK(igraph_vector_resize(hist, histlen)); igraph_vector_null(hist); IGRAPH_CHECK(igraph_motifs_randesu_callback(graph, size, cut_prob, &igraph_i_motifs_randesu_update_hist, hist)); if (size == 3) { if (igraph_is_directed(graph)) { VECTOR(*hist)[0] = VECTOR(*hist)[1] = VECTOR(*hist)[3] = IGRAPH_NAN; } else { VECTOR(*hist)[0] = VECTOR(*hist)[1] = IGRAPH_NAN; } } else if (size == 4) { if (igraph_is_directed(graph)) { int not_connected[] = { 0, 1, 2, 4, 5, 6, 9, 10, 11, 15, 22, 23, 27, 28, 33, 34, 39, 62, 120 }; int i, n=sizeof(not_connected) / sizeof(int); for (i=0; i * Similarly to \ref igraph_motifs_randesu(), this function is able to find the * different motifs of size three and four (ie. the number of different * subgraphs with three and four vertices) in the network. However, instead of * counting them, the function will call a callback function for each motif * found to allow further tests or post-processing. * * * The \c cut_prob argument also allows sampling the motifs, just like for * \ref igraph_motifs_randesu(). Set the \c cut_prob argument to a zero vector * for finding all motifs. * * \param graph The graph to find the motifs in. * \param size The size of the motifs to search for. Only three and * four are implemented currently. The limitation is not in the * motif finding code, but the graph isomorphism code. * \param cut_prob Vector of probabilities for cutting the search tree * at a given level. The first element is the first level, etc. * Supply all zeros here (of length \c size) to find all motifs * in a graph. * \param callback A pointer to a function of type \ref igraph_motifs_handler_t. * This function will be called whenever a new motif is found. * \param extra Extra argument to pass to the callback function. * \return Error code. * * Time complexity: TODO. * * \example examples/simple/igraph_motifs_randesu.c */ int igraph_motifs_randesu_callback(const igraph_t *graph, int size, const igraph_vector_t *cut_prob, igraph_motifs_handler_t *callback, void* extra) { long int no_of_nodes=igraph_vcount(graph); igraph_adjlist_t allneis, alloutneis; igraph_vector_int_t *neis; long int father; long int i, j, s; long int motifs=0; igraph_vector_t vids; /* this is G */ igraph_vector_t adjverts; /* this is V_E */ igraph_stack_t stack; /* this is S */ long int *added; char *subg; unsigned int *arr_idx, *arr_code; int code=0; unsigned char mul, idx; igraph_bool_t terminate = 0; if (size != 3 && size != 4) { IGRAPH_ERROR("Only 3 and 4 vertex motifs are implemented", IGRAPH_EINVAL); } if (size==3) { mul=3; if (igraph_is_directed(graph)) { arr_idx=igraph_i_isoclass_3_idx; arr_code=igraph_i_isoclass2_3; } else { arr_idx=igraph_i_isoclass_3u_idx; arr_code=igraph_i_isoclass2_3u; } } else { mul=4; if (igraph_is_directed(graph)) { arr_idx=igraph_i_isoclass_4_idx; arr_code=igraph_i_isoclass2_4; } else { arr_idx=igraph_i_isoclass_4u_idx; arr_code=igraph_i_isoclass2_4u; } } added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot find motifs", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); subg=igraph_Calloc(no_of_nodes, char); if (subg==0) { IGRAPH_ERROR("Cannot find motifs", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, subg); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); IGRAPH_CHECK(igraph_adjlist_init(graph, &alloutneis, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &alloutneis); IGRAPH_VECTOR_INIT_FINALLY(&vids, 0); IGRAPH_VECTOR_INIT_FINALLY(&adjverts, 0); IGRAPH_CHECK(igraph_stack_init(&stack, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); RNG_BEGIN(); for (father=0; father father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, father)); } added[nei] += 1; } /* init S */ igraph_stack_clear(&stack); while (level > 1 || !igraph_vector_empty(&adjverts)) { igraph_real_t cp=VECTOR(*cut_prob)[level]; if (level==size-1) { s=igraph_vector_size(&adjverts)/2; for (i=0; i cp) { /* yes, step down */ IGRAPH_CHECK(igraph_vector_push_back(&vids, nei)); subg[nei] = (char) level+1; added[nei] += 1; level += 1; IGRAPH_CHECK(igraph_stack_push(&stack, neifather)); IGRAPH_CHECK(igraph_stack_push(&stack, nei)); IGRAPH_CHECK(igraph_stack_push(&stack, level)); neis=igraph_adjlist_get(&allneis, nei); s=igraph_vector_int_size(neis); for (i=0; i father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei2)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); } added[nei2] += 1; } } } else { /* no, step back */ long int nei, neifather; while (!igraph_stack_empty(&stack) && level==igraph_stack_top(&stack)-1) { igraph_stack_pop(&stack); nei=(long int) igraph_stack_pop(&stack); neifather=(long int) igraph_stack_pop(&stack); igraph_vector_push_back(&adjverts, nei); igraph_vector_push_back(&adjverts, neifather); } nei=(long int) igraph_vector_pop_back(&vids); subg[nei]=0; added[nei] -= 1; level -= 1; neis=igraph_adjlist_get(&allneis, nei); s=igraph_vector_int_size(neis); for (i=0; i * This function is useful for large graphs for which it is not * feasible to count all the different motifs, because there is very * many of them. * * * The total number of motifs is estimated by taking a sample of * vertices and counts all motifs in which these vertices are * included. (There is also a \c cut_prob parameter which gives the * probabilities to cut a branch of the search tree.) * * * Directed motifs will be counted in directed graphs and undirected * motifs in undirected graphs. * * \param graph The graph object to study. * \param est Pointer to an integer type, the result will be stored * here. * \param size The size of the motif to look for. * \param cut_prob Vector giving the probabilities to cut a branch of * the search tree and omit counting the motifs in that branch. * It contains a probability for each level. Supply \c size * zeros here to count all the motifs in the sample. * \param sample_size The number of vertices to use as the * sample. This parameter is only used if the \c parsample * argument is a null pointer. * \param parsample Either pointer to an initialized vector or a null * pointer. If a vector then the vertex ids in the vector are * used as a sample. If a null pointer then the \c sample_size * argument is used to create a sample of vertices drawn with * uniform probability. * \return Error code. * \sa \ref igraph_motifs_randesu(), \ref igraph_motifs_randesu_no(). * * Time complexity: TODO. */ int igraph_motifs_randesu_estimate(const igraph_t *graph, igraph_integer_t *est, int size, const igraph_vector_t *cut_prob, igraph_integer_t sample_size, const igraph_vector_t *parsample) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t neis; igraph_vector_t vids; /* this is G */ igraph_vector_t adjverts; /* this is V_E */ igraph_stack_t stack; /* this is S */ long int *added; igraph_vector_t *sample; long int sam; long int i; added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot find motifs", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_VECTOR_INIT_FINALLY(&vids, 0); IGRAPH_VECTOR_INIT_FINALLY(&adjverts, 0); IGRAPH_CHECK(igraph_stack_init(&stack, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); if (parsample==0) { sample=igraph_Calloc(1, igraph_vector_t); if (sample==0) { IGRAPH_ERROR("Cannot estimate motifs", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, sample); IGRAPH_VECTOR_INIT_FINALLY(sample, 0); IGRAPH_CHECK(igraph_random_sample(sample, 0, no_of_nodes-1, sample_size)); } else { sample=(igraph_vector_t*)parsample; sample_size=(igraph_integer_t) igraph_vector_size(sample); } *est=0; RNG_BEGIN(); for (sam=0; sam father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, father)); } added[nei] += 1; } /* init S */ igraph_stack_clear(&stack); while (level > 1 || !igraph_vector_empty(&adjverts)) { igraph_real_t cp=VECTOR(*cut_prob)[level]; if (level==size-1) { s=igraph_vector_size(&adjverts)/2; for (i=0; i cp) { /* Yes, step down */ IGRAPH_CHECK(igraph_vector_push_back(&vids, nei)); added[nei] += 1; level += 1; IGRAPH_CHECK(igraph_stack_push(&stack, neifather)); IGRAPH_CHECK(igraph_stack_push(&stack, nei)); IGRAPH_CHECK(igraph_stack_push(&stack, level)); IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) nei, IGRAPH_ALL)); s=igraph_vector_size(&neis); for (i=0; i father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei2)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); } added[nei2] += 1; } } } else { /* no, step back */ long int nei, neifather; while (!igraph_stack_empty(&stack) && level==igraph_stack_top(&stack)-1) { igraph_stack_pop(&stack); nei=(long int) igraph_stack_pop(&stack); neifather=(long int) igraph_stack_pop(&stack); igraph_vector_push_back(&adjverts, nei); igraph_vector_push_back(&adjverts, neifather); } nei=(long int) igraph_vector_pop_back(&vids); added[nei] -= 1; level -= 1; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) nei, IGRAPH_ALL)); s=igraph_vector_size(&neis); for (i=0; i * This function counts the total number of motifs in a graph without * assigning isomorphism classes to them. * * * Directed motifs will be counted in directed graphs and undirected * motifs in undirected graphs. * * \param graph The graph object to study. * \param no Pointer to an integer type, the result will be stored * here. * \param size The size of the motifs to count. * \param cut_prob Vector giving the probabilities that a branch of * the search tree will be cut at a given level. * \return Error code. * \sa \ref igraph_motifs_randesu(), \ref * igraph_motifs_randesu_estimate(). * * Time complexity: TODO. */ int igraph_motifs_randesu_no(const igraph_t *graph, igraph_integer_t *no, int size, const igraph_vector_t *cut_prob) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t neis; igraph_vector_t vids; /* this is G */ igraph_vector_t adjverts; /* this is V_E */ igraph_stack_t stack; /* this is S */ long int *added; long int father; long int i; added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot find motifs", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_VECTOR_INIT_FINALLY(&vids, 0); IGRAPH_VECTOR_INIT_FINALLY(&adjverts, 0); IGRAPH_CHECK(igraph_stack_init(&stack, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); *no=0; RNG_BEGIN(); for (father=0; father father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, father)); } added[nei] += 1; } /* init S */ igraph_stack_clear(&stack); while (level > 1 || !igraph_vector_empty(&adjverts)) { igraph_real_t cp=VECTOR(*cut_prob)[level]; if (level==size-1) { s=igraph_vector_size(&adjverts)/2; for (i=0; i cp) { /* Yes, step down */ IGRAPH_CHECK(igraph_vector_push_back(&vids, nei)); added[nei] += 1; level += 1; IGRAPH_CHECK(igraph_stack_push(&stack, neifather)); IGRAPH_CHECK(igraph_stack_push(&stack, nei)); IGRAPH_CHECK(igraph_stack_push(&stack, level)); IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) nei, IGRAPH_ALL)); s=igraph_vector_size(&neis); for (i=0; i father) { IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei2)); IGRAPH_CHECK(igraph_vector_push_back(&adjverts, nei)); } added[nei2] += 1; } } } else { /* no, step back */ long int nei, neifather; while (!igraph_stack_empty(&stack) && level==igraph_stack_top(&stack)-1) { igraph_stack_pop(&stack); nei=(long int) igraph_stack_pop(&stack); neifather=(long int) igraph_stack_pop(&stack); igraph_vector_push_back(&adjverts, nei); igraph_vector_push_back(&adjverts, neifather); } nei=(long int) igraph_vector_pop_back(&vids); added[nei] -= 1; level -= 1; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) nei, IGRAPH_ALL)); s=igraph_vector_size(&neis); for (i=0; i * Dyad census means classifying each pair of vertices of a directed * graph into three categories: mutual, there is an edge from \c a to * \c b and also from \c b to \c a; asymmetric, there is an edge * either from \c a to \c b or from \c b to \c a but not the other way * and null, no edges between \c a and \c b. * * * Holland, P.W. and Leinhardt, S. (1970). A Method for Detecting * Structure in Sociometric Data. American Journal of Sociology, * 70, 492-513. * \param graph The input graph, a warning is given if undirected as * the results are undefined for undirected graphs. * \param mut Pointer to an integer, the number of mutual dyads is * stored here. * \param asym Pointer to an integer, the number of asymmetric dyads * is stored here. * \param null Pointer to an integer, the number of null dyads is * stored here. In case of an integer overflow (i.e. too many * null dyads), -1 will be returned. * \return Error code. * * \sa \ref igraph_reciprocity(), \ref igraph_triad_census(). * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. */ int igraph_dyad_census(const igraph_t *graph, igraph_integer_t *mut, igraph_integer_t *asym, igraph_integer_t *null) { igraph_integer_t nonrec=0, rec=0; igraph_vector_t inneis, outneis; igraph_integer_t vc=igraph_vcount(graph); long int i; if (!igraph_is_directed(graph)) { IGRAPH_WARNING("Dyad census called on undirected graph"); } IGRAPH_VECTOR_INIT_FINALLY(&inneis, 0); IGRAPH_VECTOR_INIT_FINALLY(&outneis, 0); for (i=0; i VECTOR(outneis)[op]) { nonrec += 1; op++; } else { rec += 1; ip++; op++; } } nonrec += (igraph_vector_size(&inneis)-ip) + (igraph_vector_size(&outneis)-op); } igraph_vector_destroy(&inneis); igraph_vector_destroy(&outneis); IGRAPH_FINALLY_CLEAN(2); *mut = rec / 2; *asym = nonrec / 2; if (vc % 2) { *null = vc * ((vc-1)/2); } else { *null = (vc/2) * (vc-1); } if (*null < vc) { IGRAPH_WARNING("Integer overflow, returning -1"); *null = -1; } else { *null = *null-(*mut)-(*asym); } return 0; } /** * \function igraph_triad_census_24 * TODO */ int igraph_triad_census_24(const igraph_t *graph, igraph_real_t *res2, igraph_real_t *res4) { long int vc=igraph_vcount(graph); igraph_vector_long_t seen; igraph_vector_int_t *neis, *neis2; long int i, j, k, s, neilen, neilen2, ign; igraph_adjlist_t adjlist; IGRAPH_CHECK(igraph_vector_long_init(&seen, vc)); IGRAPH_FINALLY(igraph_vector_long_destroy, &seen); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); *res2=*res4=0; for (i=0; i0 && nei==VECTOR(*neis)[j-1])) { continue; } neis2=igraph_adjlist_get(&adjlist, nei); neilen2=igraph_vector_int_size(neis2); s=0; for (k=0; k0 && nei2==VECTOR(*neis2)[k-1]) { continue; } if (VECTOR(seen)[nei2] != i+1 && VECTOR(seen)[nei2] != -(i+1)) { s++; } } if (VECTOR(seen)[nei] > 0) { *res2 += vc-s-neilen+ign-1; } else { *res4 += vc-s-neilen+ign-1; } } } igraph_adjlist_destroy(&adjlist); igraph_vector_long_destroy(&seen); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_triad_census * \brief Triad census, as defined by Davis and Leinhardt * * * Calculating the triad census means classifying every triple of * vertices in a directed graph. A triple can be in one of 16 states: * \clist * \cli 003 * A, B, C, the empty graph. * \cli 012 * A->B, C, a graph with a single directed edge. * \cli 102 * A<->B, C, a graph with a mutual connection between two vertices. * \cli 021D * A<-B->C, the binary out-tree. * \cli 021U * A->B<-C, the binary in-tree. * \cli 021C * A->B->C, the directed line. * \cli 111D * A<->B<-C. * \cli 111U * A<->B->C. * \cli 030T * A->B<-C, A->C. * \cli 030C * A<-B<-C, A->C. * \cli 201 * A<->B<->C. * \cli 120D * A<-B->C, A<->C. * \cli 120U * A->B<-C, A<->C. * \cli 120C * A->B->C, A<->C. * \cli 210 * A->B<->C, A<->C. * \cli 300 * A<->B<->C, A<->C, the complete graph. * \endclist * * * See also Davis, J.A. and Leinhardt, S. (1972). The Structure of * Positive Interpersonal Relations in Small Groups. In J. Berger * (Ed.), Sociological Theories in Progress, Volume 2, 218-251. * Boston: Houghton Mifflin. * * * This function calls \ref igraph_motifs_randesu() which is an * implementation of the FANMOD motif finder tool, see \ref * igraph_motifs_randesu() for details. Note that the order of the * triads is not the same for \ref igraph_triad_census() and \ref * igraph_motifs_randesu(). * * \param graph The input graph. A warning is given for undirected * graphs, as the result is undefined for those. * \param res Pointer to an initialized vector, the result is stored * here in the same order as given in the list above. Note that this * order is different than the one used by \ref igraph_motifs_randesu(). * \return Error code. * * \sa \ref igraph_motifs_randesu(), \ref igraph_dyad_census(). * * Time complexity: TODO. */ int igraph_triad_census(const igraph_t *graph, igraph_vector_t *res) { igraph_vector_t cut_prob; igraph_real_t m2, m4; igraph_vector_t tmp; igraph_integer_t vc=igraph_vcount(graph); igraph_real_t total; if (!igraph_is_directed(graph)) { IGRAPH_WARNING("Triad census called on an undirected graph"); } IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_VECTOR_INIT_FINALLY(&cut_prob, 3); /* all zeros */ IGRAPH_CHECK(igraph_vector_resize(res, 16)); igraph_vector_null(res); IGRAPH_CHECK(igraph_motifs_randesu(graph, &tmp, 3, &cut_prob)); IGRAPH_CHECK(igraph_triad_census_24(graph, &m2, &m4)); total = ((igraph_real_t)vc) * (vc-1); total *= (vc-2); total /= 6; /* Reorder */ if (igraph_is_directed(graph)) { VECTOR(tmp)[0] = 0; VECTOR(tmp)[1] = m2; VECTOR(tmp)[3] = m4; VECTOR(tmp)[0] = total - igraph_vector_sum(&tmp); VECTOR(*res)[0] = VECTOR(tmp)[0]; VECTOR(*res)[1] = VECTOR(tmp)[1]; VECTOR(*res)[2] = VECTOR(tmp)[3]; VECTOR(*res)[3] = VECTOR(tmp)[6]; VECTOR(*res)[4] = VECTOR(tmp)[2]; VECTOR(*res)[5] = VECTOR(tmp)[4]; VECTOR(*res)[6] = VECTOR(tmp)[5]; VECTOR(*res)[7] = VECTOR(tmp)[9]; VECTOR(*res)[8] = VECTOR(tmp)[7]; VECTOR(*res)[9] = VECTOR(tmp)[11]; VECTOR(*res)[10] = VECTOR(tmp)[10]; VECTOR(*res)[11] = VECTOR(tmp)[8]; VECTOR(*res)[12] = VECTOR(tmp)[13]; VECTOR(*res)[13] = VECTOR(tmp)[12]; VECTOR(*res)[14] = VECTOR(tmp)[14]; VECTOR(*res)[15] = VECTOR(tmp)[15]; } else { VECTOR(tmp)[0] = 0; VECTOR(tmp)[1] = m2; VECTOR(tmp)[0] = total - igraph_vector_sum(&tmp); VECTOR(*res)[0] = VECTOR(tmp)[0]; VECTOR(*res)[2] = VECTOR(tmp)[1]; VECTOR(*res)[10] = VECTOR(tmp)[2]; VECTOR(*res)[15] = VECTOR(tmp)[3]; } igraph_vector_destroy(&cut_prob); igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(2); return 0; } igraph/src/infomap.cc0000644000175100001440000002415113431000472014266 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ---- The original version of this file was written by Martin Rosvall email: martin.rosvall@physics.umu.se homePage: http://www.tp.umu.se/~rosvall/ It was integrated in igraph by Emmanuel Navarro email: navarro@irit.fr homePage: http://www.irit.fr/~Emmanuel.Navarro/ */ #include #include "igraph_interface.h" #include "igraph_community.h" #include "igraph_interrupt_internal.h" #include "infomap_Node.h" #include "infomap_Greedy.h" /****************************************************************************/ int infomap_partition(FlowGraph * fgraph, bool rcall) { Greedy * greedy; // save the original graph FlowGraph * cpy_fgraph = new FlowGraph(fgraph); IGRAPH_FINALLY(delete_FlowGraph, cpy_fgraph); int Nnode = cpy_fgraph->Nnode; // "real" number of vertex, ie. number of vertex of the graph int iteration = 0; double outer_oldCodeLength, newCodeLength; int *initial_move = NULL; bool initial_move_done = true; do { // Main loop outer_oldCodeLength = fgraph->codeLength; if (iteration > 0) { /**********************************************************************/ // FIRST PART: re-split the network (if need) // =========================================== // intial_move indicate current clustering initial_move = new int[Nnode]; // new_cluster_id --> old_cluster_id (save curent clustering state) IGRAPH_FINALLY(operator delete [], initial_move); initial_move_done = false; int *subMoveTo = NULL; // enventual new partitionment of original graph if ((iteration % 2 == 0) && (fgraph->Nnode > 1)) { // 0/ Submodule movements : partition each module of the // current partition (rec. call) subMoveTo = new int[Nnode]; // vid_cpy_fgraph --> new_cluster_id (new partition) IGRAPH_FINALLY(operator delete [], subMoveTo); int subModIndex = 0; for (int i=0 ; i < fgraph->Nnode ; i++) { // partition each non trivial module int sub_Nnode = fgraph->node[i]->members.size(); if (sub_Nnode > 1) { // If the module is not trivial int *sub_members = new int[sub_Nnode]; // id_sub --> id IGRAPH_FINALLY(operator delete [], sub_members); for (int j=0 ; j < sub_Nnode ; j++) sub_members[j] = fgraph->node[i]->members[j]; // extraction of the subgraph FlowGraph *sub_fgraph = new FlowGraph(cpy_fgraph, sub_Nnode, sub_members); IGRAPH_FINALLY(delete_FlowGraph, sub_fgraph); sub_fgraph->initiate(); // recursif call of partitionment on the subgraph infomap_partition(sub_fgraph, true); // Record membership changes for (int j=0; j < sub_fgraph->Nnode; j++) { int Nmembers = sub_fgraph->node[j]->members.size(); for (int k=0; knode[j]->members[k]]] = subModIndex; } initial_move[subModIndex] = i; subModIndex++; } delete sub_fgraph; IGRAPH_FINALLY_CLEAN(1); delete [] sub_members; IGRAPH_FINALLY_CLEAN(1); } else{ subMoveTo[fgraph->node[i]->members[0]] = subModIndex; initial_move[subModIndex] = i; subModIndex++; } } } else { // 1/ Single-node movements : allows each node to move (again) // save current modules for (int i=0; i < fgraph->Nnode; i++) { // for each module int Nmembers = fgraph->node[i]->members.size(); // Module size for (int j=0;jnode[i]->members[j]] = i; } } } fgraph->back_to(cpy_fgraph); if (subMoveTo) { Greedy *cpy_greedy = new Greedy(fgraph); IGRAPH_FINALLY(delete_Greedy, cpy_greedy); cpy_greedy->setMove(subMoveTo); cpy_greedy->apply(false); delete_Greedy(cpy_greedy); IGRAPH_FINALLY_CLEAN(1); delete [] subMoveTo; IGRAPH_FINALLY_CLEAN(1); } } /**********************************************************************/ // SECOND PART: greedy optimizing it self // =========================================== double oldCodeLength; do { // greedy optimizing object creation greedy = new Greedy(fgraph); IGRAPH_FINALLY(delete_Greedy, greedy); // Initial move to apply ? if (!initial_move_done && initial_move) { initial_move_done = true; greedy->setMove(initial_move); } oldCodeLength = greedy->codeLength; bool moved = true; int Nloops = 0; //int count = 0; double inner_oldCodeLength = 1000; while (moved) { // main greedy optimizing loop inner_oldCodeLength = greedy->codeLength; moved = greedy->optimize(); Nloops++; //count++; if (fabs(greedy->codeLength - inner_oldCodeLength) < 1.0e-10) // if the move does'n reduce the codelenght -> exit ! moved = false; //if (count == 10) { // greedy->tune(); // count = 0; //} } // transform the network to network of modules: greedy->apply(true); newCodeLength = greedy->codeLength; // destroy greedy object delete greedy; IGRAPH_FINALLY_CLEAN(1); } while (oldCodeLength - newCodeLength > 1.0e-10); // while there is some improvement if (iteration > 0) { delete [] initial_move; IGRAPH_FINALLY_CLEAN(1); } iteration++; if (!rcall) IGRAPH_ALLOW_INTERRUPTION(); } while (outer_oldCodeLength - newCodeLength > 1.0e-10); delete cpy_fgraph; IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /** * \function igraph_community_infomap * \brief Find community structure that minimizes the expected * description length of a random walker trajectory. * * Implementation of the InfoMap community detection algorithm.of * Martin Rosvall and Carl T. Bergstrom. * * See : * Visualization of the math and the map generator: www.mapequation.org * [2] The original paper: M. Rosvall and C. T. Bergstrom, Maps of * information flow reveal community structure in complex networks, PNAS * 105, 1118 (2008) [http://dx.doi.org/10.1073/pnas.0706851105 , * http://arxiv.org/abs/0707.0609 ] * [3] A more detailed paper: M. Rosvall, D. Axelsson, and C. T. Bergstrom, * The map equation, Eur. Phys. J. Special Topics 178, 13 (2009). * [http://dx.doi.org/10.1140/epjst/e2010-01179-1 , * http://arxiv.org/abs/0906.1405 ] * * The original C++ implementation of Martin Rosvall is used, * see http://www.tp.umu.se/~rosvall/downloads/infomap_undir.tgz . * Intergation in igraph has be done by Emmanuel Navarro (who is grateful to * Martin Rosvall and Carl T. Bergstrom for providing this source code.) * * * Note that the graph must not contain isolated vertices. * * * If you want to specify a random seed (as in original * implementation) you can use \ref igraph_rng_seed(). * * \param graph The input graph. * \param e_weights Numeric vector giving the weights of the edges. * If it is a NULL pointer then all edges will have equal * weights. The weights are expected to be positive. * \param v_weights Numeric vector giving the weights of the vertices. * If it is a NULL pointer then all vertices will have equal * weights. The weights are expected to be positive. * \param nb_trials The number of attempts to partition the network * (can be any integer value equal or larger than 1). * \param membership Pointer to a vector. The membership vector is * stored here. * \param codelength Pointer to a real. If not NULL the code length of the * partition is stored here. * \return Error code. * * \sa \ref igraph_community_spinglass(), \ref * igraph_community_edge_betweenness(), \ref igraph_community_walktrap(). * * Time complexity: TODO. */ int igraph_community_infomap(const igraph_t * graph, const igraph_vector_t *e_weights, const igraph_vector_t *v_weights, int nb_trials, igraph_vector_t *membership, igraph_real_t *codelength) { FlowGraph * fgraph = new FlowGraph(graph, e_weights, v_weights); IGRAPH_FINALLY(delete_FlowGraph, fgraph); // compute stationary distribution fgraph->initiate(); FlowGraph * cpy_fgraph ; double shortestCodeLength = 1000.0; // create membership vector int Nnode = fgraph->Nnode; IGRAPH_CHECK(igraph_vector_resize(membership, Nnode)); for (int trial = 0; trial < nb_trials; trial++) { cpy_fgraph = new FlowGraph(fgraph); IGRAPH_FINALLY(delete_FlowGraph, cpy_fgraph); //partition the network IGRAPH_CHECK(infomap_partition(cpy_fgraph, false)); // if better than the better... if (cpy_fgraph->codeLength < shortestCodeLength) { shortestCodeLength = cpy_fgraph->codeLength; // ... store the partition for (int i=0 ; i < cpy_fgraph->Nnode ; i++) { int Nmembers = cpy_fgraph->node[i]->members.size(); for (int k=0; k < Nmembers; k++) { //cluster[ cpy_fgraph->node[i]->members[k] ] = i; VECTOR(*membership)[cpy_fgraph->node[i]->members[k]] = i; } } } delete_FlowGraph(cpy_fgraph); IGRAPH_FINALLY_CLEAN(1); } *codelength = (igraph_real_t) shortestCodeLength/log(2.0); delete fgraph; IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } igraph/src/drl_layout.cpp0000644000175100001440000003541313431000472015213 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Layout // // This program implements a parallel force directed graph drawing // algorithm. The algorithm used is based upon a random decomposition // of the graph and simulated shared memory of node position and density. // In this version, the simulated shared memory is spread among all processors // // The structure of the inputs and outputs of this code will be displayed // if the program is called without parameters, or if an erroneous // parameter is passed to the program. // // S. Martin // 5/6/2005 // C++ library routines #include #include #include #include #include #include #include using namespace std; // layout routines and constants #include "drl_layout.h" #include "drl_parse.h" #include "drl_graph.h" // MPI #ifdef MUSE_MPI #include #endif using namespace drl; #include "igraph_layout.h" #include "igraph_random.h" #include "igraph_interface.h" namespace drl { // int main(int argc, char **argv) { // // initialize MPI // int myid, num_procs; // #ifdef MUSE_MPI // MPI_Init ( &argc, &argv ); // MPI_Comm_size ( MPI_COMM_WORLD, &num_procs ); // MPI_Comm_rank ( MPI_COMM_WORLD, &myid ); // #else // myid = 0; // num_procs = 1; // #endif // // parameters that must be broadcast to all processors // int rand_seed; // float edge_cut; // char int_file[MAX_FILE_NAME]; // char coord_file[MAX_FILE_NAME]; // char real_file[MAX_FILE_NAME]; // char parms_file[MAX_FILE_NAME]; // int int_out = 0; // int edges_out = 0; // int parms_in = 0; // float real_in = -1.0; // // user interaction is handled by processor 0 // if ( myid == 0 ) // { // if ( num_procs > MAX_PROCS ) // { // cout << "Error: Maximum number of processors is " << MAX_PROCS << "." << endl; // cout << "Adjust compile time parameter." << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // // get user input // parse command_line ( argc, argv ); // rand_seed = command_line.rand_seed; // edge_cut = command_line.edge_cut; // int_out = command_line.int_out; // edges_out = command_line.edges_out; // parms_in = command_line.parms_in; // real_in = command_line.real_in; // strcpy ( coord_file, command_line.coord_file.c_str() ); // strcpy ( int_file, command_line.sim_file.c_str() ); // strcpy ( real_file, command_line.real_file.c_str() ); // strcpy ( parms_file, command_line.parms_file.c_str() ); // } // // now we initialize all processors by reading .int file // #ifdef MUSE_MPI // MPI_Bcast ( &int_file, MAX_FILE_NAME, MPI_CHAR, 0, MPI_COMM_WORLD ); // #endif // graph neighbors ( myid, num_procs, int_file ); // // check for user supplied parameters // #ifdef MUSE_MPI // MPI_Bcast ( &parms_in, 1, MPI_INT, 0, MPI_COMM_WORLD ); // #endif // if ( parms_in ) // { // #ifdef MUSE_MPI // MPI_Bcast ( &parms_file, MAX_FILE_NAME, MPI_CHAR, 0, MPI_COMM_WORLD ); // #endif // neighbors.read_parms ( parms_file ); // } // // set random seed, edge cutting, and real iterations parameters // #ifdef MUSE_MPI // MPI_Bcast ( &rand_seed, 1, MPI_INT, 0, MPI_COMM_WORLD ); // MPI_Bcast ( &edge_cut, 1, MPI_FLOAT, 0, MPI_COMM_WORLD ); // MPI_Bcast ( &real_in, 1, MPI_INT, 0, MPI_COMM_WORLD ); // #endif // neighbors.init_parms ( rand_seed, edge_cut, real_in ); // // check for .real file with existing coordinates // if ( real_in >= 0 ) // { // #ifdef MUSE_MPI // MPI_Bcast ( &real_file, MAX_FILE_NAME, MPI_CHAR, 0, MPI_COMM_WORLD ); // #endif // neighbors.read_real ( real_file ); // } // neighbors.draw_graph ( int_out, coord_file ); // // do we have to write out the edges? // #ifdef MUSE_MPI // MPI_Bcast ( &edges_out, 1, MPI_INT, 0, MPI_COMM_WORLD ); // #endif // if ( edges_out ) // { // #ifdef MUSE_MPI // MPI_Bcast ( &coord_file, MAX_FILE_NAME, MPI_CHAR, 0, MPI_COMM_WORLD ); // #endif // for ( int i = 0; i < num_procs; i++ ) // { // if ( myid == i ) // neighbors.write_sim ( coord_file ); // #ifdef MUSE_MPI // MPI_Barrier ( MPI_COMM_WORLD ); // #endif // } // } // // finally we output file and quit // float tot_energy; // tot_energy = neighbors.get_tot_energy (); // if ( myid == 0 ) // { // neighbors.write_coord ( coord_file ); // cout << "Total Energy: " << tot_energy << "." << endl // << "Program terminated successfully." << endl; // } // // MPI finalize // #ifdef MUSE_MPI // MPI_Finalize (); // #endif // return 0; // } } // namespace drl /** * \section about_drl * * * DrL is a sophisticated layout generator developed and implemented by * Shawn Martin et al. As of October 2012 the original DrL homepage is * unfortunately not available. You can read more about this algorithm * in the following technical report: Martin, S., Brown, W.M., * Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) * Layout. SAND Reports, 2008. 2936: p. 1-10. * * * * Only a subset of the complete DrL functionality is * included in igraph, parallel runs and recursive, multi-level * layouting is not supported. * * * * The parameters of the layout are stored in an \ref * igraph_layout_drl_options_t structure, this can be initialized by * calling the function \ref igraph_layout_drl_options_init(). * The fields of this structure can then be adjusted by hand if needed. * The layout is calculated by an \ref igraph_layout_drl() call. * */ /** * \function igraph_layout_drl_options_init * Initialize parameters for the DrL layout generator * * This function can be used to initialize the struct holding the * parameters for the DrL layout generator. There are a number of * predefined templates available, it is a good idea to start from one * of these by modifying some parameters. * \param options The struct to initialize. * \param templ The template to use. Currently the following templates * are supplied: \c IGRAPH_LAYOUT_DRL_DEFAULT, \c * IGRAPH_LAYOUT_DRL_COARSEN, \c IGRAPH_LAYOUT_DRL_COARSEST, * \c IGRAPH_LAYOUT_DRL_REFINE and \c IGRAPH_LAYOUT_DRL_FINAL. * \return Error code. * * Time complexity: O(1). */ int igraph_layout_drl_options_init(igraph_layout_drl_options_t *options, igraph_layout_drl_default_t templ) { options->edge_cut=32.0/40.0; switch (templ) { case IGRAPH_LAYOUT_DRL_DEFAULT: options->init_iterations = 0; options->init_temperature = 2000; options->init_attraction = 10; options->init_damping_mult = 1.0; options->liquid_iterations = 200; options->liquid_temperature = 2000; options->liquid_attraction = 10; options->liquid_damping_mult = 1.0; options->expansion_iterations = 200; options->expansion_temperature = 2000; options->expansion_attraction = 2; options->expansion_damping_mult = 1.0; options->cooldown_iterations = 200; options->cooldown_temperature = 2000; options->cooldown_attraction = 1; options->cooldown_damping_mult = .1; options->crunch_iterations = 50; options->crunch_temperature = 250; options->crunch_attraction = 1; options->crunch_damping_mult = 0.25; options->simmer_iterations = 100; options->simmer_temperature = 250; options->simmer_attraction = .5; options->simmer_damping_mult = 0; break; case IGRAPH_LAYOUT_DRL_COARSEN: options->init_iterations = 0; options->init_temperature = 2000; options->init_attraction = 10; options->init_damping_mult = 1.0; options->liquid_iterations = 200; options->liquid_temperature = 2000; options->liquid_attraction = 2; options->liquid_damping_mult = 1.0; options->expansion_iterations = 200; options->expansion_temperature = 2000; options->expansion_attraction = 10; options->expansion_damping_mult = 1.0; options->cooldown_iterations = 200; options->cooldown_temperature = 2000; options->cooldown_attraction = 1; options->cooldown_damping_mult = .1; options->crunch_iterations = 50; options->crunch_temperature = 250; options->crunch_attraction = 1; options->crunch_damping_mult = 0.25; options->simmer_iterations = 100; options->simmer_temperature = 250; options->simmer_attraction = .5; options->simmer_damping_mult = 0; break; case IGRAPH_LAYOUT_DRL_COARSEST: options->init_iterations = 0; options->init_temperature = 2000; options->init_attraction = 10; options->init_damping_mult = 1.0; options->liquid_iterations = 200; options->liquid_temperature = 2000; options->liquid_attraction = 2; options->liquid_damping_mult = 1.0; options->expansion_iterations = 200; options->expansion_temperature = 2000; options->expansion_attraction = 10; options->expansion_damping_mult = 1.0; options->cooldown_iterations = 200; options->cooldown_temperature = 2000; options->cooldown_attraction = 1; options->cooldown_damping_mult = .1; options->crunch_iterations = 200; options->crunch_temperature = 250; options->crunch_attraction = 1; options->crunch_damping_mult = 0.25; options->simmer_iterations = 100; options->simmer_temperature = 250; options->simmer_attraction = .5; options->simmer_damping_mult = 0; break; case IGRAPH_LAYOUT_DRL_REFINE: options->init_iterations = 0; options->init_temperature = 50; options->init_attraction = .5; options->init_damping_mult = 0; options->liquid_iterations = 0; options->liquid_temperature = 2000; options->liquid_attraction = 2; options->liquid_damping_mult = 1.0; options->expansion_iterations = 50; options->expansion_temperature = 500; options->expansion_attraction = .1; options->expansion_damping_mult = .25; options->cooldown_iterations = 50; options->cooldown_temperature = 200; options->cooldown_attraction = 1; options->cooldown_damping_mult = .1; options->crunch_iterations = 50; options->crunch_temperature = 250; options->crunch_attraction = 1; options->crunch_damping_mult = 0.25; options->simmer_iterations = 0; options->simmer_temperature = 250; options->simmer_attraction = .5; options->simmer_damping_mult = 0; break; case IGRAPH_LAYOUT_DRL_FINAL: options->init_iterations = 0; options->init_temperature = 50; options->init_attraction = .5; options->init_damping_mult = 0; options->liquid_iterations = 0; options->liquid_temperature = 2000; options->liquid_attraction = 2; options->liquid_damping_mult = 1.0; options->expansion_iterations = 50; options->expansion_temperature = 50; options->expansion_attraction = .1; options->expansion_damping_mult = .25; options->cooldown_iterations = 50; options->cooldown_temperature = 200; options->cooldown_attraction = 1; options->cooldown_damping_mult = .1; options->crunch_iterations = 50; options->crunch_temperature = 250; options->crunch_attraction = 1; options->crunch_damping_mult = 0.25; options->simmer_iterations = 25; options->simmer_temperature = 250; options->simmer_attraction = .5; options->simmer_damping_mult = 0; break; default: IGRAPH_ERROR("Unknown DrL template", IGRAPH_EINVAL); break; } return 0; } /** * \function igraph_layout_drl * The DrL layout generator * * This function implements the force-directed DrL layout generator. * Please see more in the following technical report: Martin, S., * Brown, W.M., Klavans, R., Boyack, K.W., DrL: Distributed Recursive * (Graph) Layout. SAND Reports, 2008. 2936: p. 1-10. * \param graph The input graph. * \param use_seed Logical scalar, if true, then the coordinates * supplied in the \p res argument are used as starting points. * \param res Pointer to a matrix, the result layout is stored * here. It will be resized as needed. * \param options The parameters to pass to the layout generator. * \param weights Edge weights, pointer to a vector. If this is a null * pointer then every edge will have the same weight. * \param fixed Pointer to a logical vector, or a null pointer. This * can be used to fix the position of some vertices. Vertices for * which it is true will not be moved, but stay at the coordinates * given in the \p res matrix. This argument is ignored if it is a * null pointer or if use_seed is false. * \return Error code. * * Time complexity: ???. */ int igraph_layout_drl(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_layout_drl_options_t *options, const igraph_vector_t *weights, const igraph_vector_bool_t *fixed) { RNG_BEGIN(); drl::graph neighbors(graph, options, weights); neighbors.init_parms(options); if (use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, igraph_vcount(graph), 2)); neighbors.read_real(res, fixed); } neighbors.draw_graph(res); RNG_END(); return 0; } igraph/src/prpack/0000755000175100001440000000000013567553110013617 5ustar hornikusersigraph/src/prpack/prpack_edge_list.h0000644000175100001440000000034713431000472017257 0ustar hornikusers#ifndef PRPACK_EDGE_LIST #define PRPACK_EDGE_LIST namespace prpack { class prpack_edge_list { public: int num_vs; int num_es; int* heads; int* tails; }; }; #endif igraph/src/prpack/prpack_preprocessed_scc_graph.cpp0000644000175100001440000001600113431000472022354 0ustar hornikusers#include "prpack_preprocessed_scc_graph.h" #include #include #include using namespace prpack; using namespace std; void prpack_preprocessed_scc_graph::initialize() { heads_inside = NULL; tails_inside = NULL; vals_inside = NULL; heads_outside = NULL; tails_outside = NULL; vals_outside = NULL; ii = NULL; d = NULL; num_outlinks = NULL; divisions = NULL; encoding = NULL; decoding = NULL; } void prpack_preprocessed_scc_graph::initialize_weighted(const prpack_base_graph* bg) { vals_inside = new double[num_es]; vals_outside = new double[num_es]; d = new double[num_vs]; fill(d, d + num_vs, 1); for (int comp_i = 0; comp_i < num_comps; ++comp_i) { const int start_i = divisions[comp_i]; const int end_i = (comp_i + 1 != num_comps) ? divisions[comp_i + 1] : num_vs; for (int i = start_i; i < end_i; ++i) { ii[i] = 0; const int decoded = decoding[i]; const int start_j = bg->tails[decoded]; const int end_j = (decoded + 1 != num_vs) ? bg->tails[decoded + 1] : bg->num_es; tails_inside[i] = num_es_inside; tails_outside[i] = num_es_outside; for (int j = start_j; j < end_j; ++j) { const int h = encoding[bg->heads[j]]; if (h == i) { ii[i] += bg->vals[j]; } else { if (start_i <= h && h < end_i) { heads_inside[num_es_inside] = h; vals_inside[num_es_inside] = bg->vals[j]; ++num_es_inside; } else { heads_outside[num_es_outside] = h; vals_outside[num_es_outside] = bg->vals[j]; ++num_es_outside; } } d[h] -= bg->vals[j]; } } } } void prpack_preprocessed_scc_graph::initialize_unweighted(const prpack_base_graph* bg) { num_outlinks = new double[num_vs]; fill(num_outlinks, num_outlinks + num_vs, 0); for (int comp_i = 0; comp_i < num_comps; ++comp_i) { const int start_i = divisions[comp_i]; const int end_i = (comp_i + 1 != num_comps) ? divisions[comp_i + 1] : num_vs; for (int i = start_i; i < end_i; ++i) { ii[i] = 0; const int decoded = decoding[i]; const int start_j = bg->tails[decoded]; const int end_j = (decoded + 1 != num_vs) ? bg->tails[decoded + 1] : bg->num_es; tails_inside[i] = num_es_inside; tails_outside[i] = num_es_outside; for (int j = start_j; j < end_j; ++j) { const int h = encoding[bg->heads[j]]; if (h == i) { ++ii[i]; } else { if (start_i <= h && h < end_i) heads_inside[num_es_inside++] = h; else heads_outside[num_es_outside++] = h; } ++num_outlinks[h]; } } } for (int i = 0; i < num_vs; ++i) { if (num_outlinks[i] == 0) num_outlinks[i] = -1; ii[i] /= num_outlinks[i]; } } prpack_preprocessed_scc_graph::prpack_preprocessed_scc_graph(const prpack_base_graph* bg) { initialize(); // initialize instance variables num_vs = bg->num_vs; num_es = bg->num_es - bg->num_self_es; // initialize Tarjan's algorithm variables num_comps = 0; int mn = 0; // the number of vertices seen so far int sz = 0; // size of st int decoding_i = 0; // size of decoding currently filled in decoding = new int[num_vs]; int* scc = new int[num_vs]; // the strongly connected component this vertex is in int* low = new int[num_vs]; // the lowest index this vertex can reach int* num = new int[num_vs]; // the index of this vertex in the dfs traversal int* st = new int[num_vs]; // a stack for the dfs memset(num, -1, num_vs*sizeof(num[0])); memset(scc, -1, num_vs*sizeof(scc[0])); int* cs1 = new int[num_vs]; // call stack variable for dfs int* cs2 = new int[num_vs]; // call stack variable for dfs // run iterative Tarjan's algorithm for (int root = 0; root < num_vs; ++root) { if (num[root] != -1) continue; int csz = 1; cs1[0] = root; cs2[0] = bg->tails[root]; // dfs while (csz) { const int p = cs1[csz - 1]; // node we're dfs-ing on int& it = cs2[csz - 1]; // iteration of the for loop if (it == bg->tails[p]) { low[p] = num[p] = mn++; st[sz++] = p; } else { low[p] = min(low[p], low[bg->heads[it - 1]]); } bool done = false; int end_it = (p + 1 != num_vs) ? bg->tails[p + 1] : bg->num_es; for (; it < end_it; ++it) { int h = bg->heads[it]; if (scc[h] == -1) { if (num[h] == -1) { // dfs(h, p); cs1[csz] = h; cs2[csz++] = bg->tails[h]; ++it; done = true; break; } low[p] = min(low[p], low[h]); } } if (done) continue; // if p is the first explored vertex of a scc if (low[p] == num[p]) { cs1[num_vs - 1 - num_comps] = decoding_i; while (scc[p] != num_comps) { scc[st[--sz]] = num_comps; decoding[decoding_i++] = st[sz]; } ++num_comps; } --csz; } } // set up other instance variables divisions = new int[num_comps]; divisions[0] = 0; for (int i = 1; i < num_comps; ++i) divisions[i] = cs1[num_vs - 1 - i]; encoding = num; for (int i = 0; i < num_vs; ++i) encoding[decoding[i]] = i; // fill in inside and outside instance variables ii = new double[num_vs]; tails_inside = cs1; heads_inside = new int[num_es]; tails_outside = cs2; heads_outside = new int[num_es]; num_es_inside = num_es_outside = 0; // continue initialization based off of weightedness if (bg->vals != NULL) initialize_weighted(bg); else initialize_unweighted(bg); // free memory // do not free num <==> encoding // do not free cs1 <==> tails_inside // do not free cs2 <==> tails_outside delete[] scc; delete[] low; delete[] st; } prpack_preprocessed_scc_graph::~prpack_preprocessed_scc_graph() { delete[] heads_inside; delete[] tails_inside; delete[] vals_inside; delete[] heads_outside; delete[] tails_outside; delete[] vals_outside; delete[] ii; delete[] d; delete[] num_outlinks; delete[] divisions; delete[] encoding; delete[] decoding; } igraph/src/prpack/prpack_utils.h0000644000175100001440000000171613431000472016461 0ustar hornikusers#ifndef PRPACK_UTILS #define PRPACK_UTILS #ifdef MATLAB_MEX_FILE #include "mex.h" #endif #include // Computes the time taken to do X and stores it in T. #define TIME(T, X) \ (T) = prpack_utils::get_time(); \ (X); \ (T) = prpack_utils::get_time() - (T) // Computes S += A using C as a carry-over. // This is a macro over a function as it is faster this way. #define COMPENSATED_SUM(S, A, C) \ double compensated_sum_y = (A) - (C); \ double compensated_sum_t = (S) + compensated_sum_y; \ (C) = compensated_sum_t - (S) - compensated_sum_y; \ (S) = compensated_sum_t namespace prpack { class prpack_utils { public: static double get_time(); static void validate(const bool condition, const std::string& msg); static double* permute(const int length, const double* a, const int* coding); }; }; #endif igraph/src/prpack/prpack_base_graph.cpp0000644000175100001440000002265713431000472017756 0ustar hornikusers#include "prpack_base_graph.h" #include "prpack_utils.h" #include #include #include #include #include #include using namespace prpack; using namespace std; void prpack_base_graph::initialize() { heads = NULL; tails = NULL; vals = NULL; } prpack_base_graph::prpack_base_graph() { initialize(); num_vs = num_es = 0; } prpack_base_graph::prpack_base_graph(const prpack_csc* g) { initialize(); num_vs = g->num_vs; num_es = g->num_es; // fill in heads and tails num_self_es = 0; int* hs = g->heads; int* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = hs[h]; const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = ts[ti]; ++tails[t]; if (h == t) ++num_self_es; } } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = hs[h]; const int end_ti = (h + 1 != num_vs) ? hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = ts[ti]; heads[tails[t] + osets[t]++] = h; } } // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const prpack_int64_csc* g) { initialize(); // TODO remove the assert and add better behavior assert(num_vs <= std::numeric_limits::max()); num_vs = (int)g->num_vs; num_es = (int)g->num_es; // fill in heads and tails num_self_es = 0; int64_t* hs = g->heads; int64_t* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = (int)hs[h]; const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = (int)ts[ti]; ++tails[t]; if (h == t) ++num_self_es; } } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int h = 0; h < num_vs; ++h) { const int start_ti = (int)hs[h]; const int end_ti = (h + 1 != num_vs) ? (int)hs[h + 1] : num_es; for (int ti = start_ti; ti < end_ti; ++ti) { const int t = (int)ts[ti]; heads[tails[t] + osets[t]++] = h; } } // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const prpack_csr* g) { initialize(); assert(false); // TODO } prpack_base_graph::prpack_base_graph(const prpack_edge_list* g) { initialize(); num_vs = g->num_vs; num_es = g->num_es; // fill in heads and tails num_self_es = 0; int* hs = g->heads; int* ts = g->tails; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) heads[tails[ts[i]] + osets[ts[i]]++] = hs[i]; // clean up delete[] osets; } prpack_base_graph::prpack_base_graph(const char* filename, const char* format, const bool weighted) { initialize(); FILE* f = fopen(filename, "r"); const string s(filename); const string t(format); const string ext = (t == "") ? s.substr(s.rfind('.') + 1) : t; if (ext == "smat") { read_smat(f, weighted); } else { prpack_utils::validate(!weighted, "Error: graph format is not compatible with weighted option."); if (ext == "edges" || ext == "eg2") { read_edges(f); } else if (ext == "graph-txt") { read_ascii(f); } else { prpack_utils::validate(false, "Error: invalid graph format."); } } fclose(f); } prpack_base_graph::~prpack_base_graph() { delete[] heads; delete[] tails; delete[] vals; } void prpack_base_graph::read_smat(FILE* f, const bool weighted) { // read in header double ignore = 0.0; assert(fscanf(f, "%d %lf %d", &num_vs, &ignore, &num_es) == 3); // fill in heads and tails num_self_es = 0; int* hs = new int[num_es]; int* ts = new int[num_es]; heads = new int[num_es]; tails = new int[num_vs]; double* vs = NULL; if (weighted) { vs = new double[num_es]; vals = new double[num_es]; } memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { assert(fscanf(f, "%d %d %lf", &hs[i], &ts[i], &((weighted) ? vs[i] : ignore)) == 3); ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { const int temp = sum; sum += tails[i]; tails[i] = temp; } int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) { const int idx = tails[ts[i]] + osets[ts[i]]++; heads[idx] = hs[i]; if (weighted) vals[idx] = vs[i]; } // clean up delete[] hs; delete[] ts; delete[] vs; delete[] osets; } void prpack_base_graph::read_edges(FILE* f) { vector > al; int h, t; num_es = num_self_es = 0; while (fscanf(f, "%d %d", &h, &t) == 2) { const int m = (h < t) ? t : h; if ((int) al.size() < m + 1) al.resize(m + 1); al[t].push_back(h); ++num_es; if (h == t) ++num_self_es; } num_vs = al.size(); heads = new int[num_es]; tails = new int[num_vs]; for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; for (int j = 0; j < (int) al[tails_i].size(); ++j) heads[heads_i++] = al[tails_i][j]; } } void prpack_base_graph::read_ascii(FILE* f) { assert(fscanf(f, "%d", &num_vs) == 1); while (getc(f) != '\n'); vector* al = new vector[num_vs]; num_es = num_self_es = 0; char s[32]; for (int h = 0; h < num_vs; ++h) { bool line_ended = false; while (!line_ended) { for (int i = 0; ; ++i) { s[i] = getc(f); if ('9' < s[i] || s[i] < '0') { line_ended = s[i] == '\n'; if (i != 0) { s[i] = '\0'; const int t = atoi(s); al[t].push_back(h); ++num_es; if (h == t) ++num_self_es; } break; } } } } heads = new int[num_es]; tails = new int[num_vs]; for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; for (int j = 0; j < (int) al[tails_i].size(); ++j) heads[heads_i++] = al[tails_i][j]; } delete[] al; } prpack_base_graph::prpack_base_graph(int nverts, int nedges, std::pair* edges) { initialize(); num_vs = nverts; num_es = nedges; // fill in heads and tails num_self_es = 0; int* hs = new int[num_es]; int* ts = new int[num_es]; tails = new int[num_vs]; memset(tails, 0, num_vs*sizeof(tails[0])); for (int i = 0; i < num_es; ++i) { assert(edges[i].first >= 0 && edges[i].first < num_vs); assert(edges[i].second >= 0 && edges[i].second < num_vs); hs[i] = edges[i].first; ts[i] = edges[i].second; ++tails[ts[i]]; if (hs[i] == ts[i]) ++num_self_es; } for (int i = 0, sum = 0; i < num_vs; ++i) { int temp = sum; sum += tails[i]; tails[i] = temp; } heads = new int[num_es]; int* osets = new int[num_vs]; memset(osets, 0, num_vs*sizeof(osets[0])); for (int i = 0; i < num_es; ++i) heads[tails[ts[i]] + osets[ts[i]]++] = hs[i]; // clean up delete[] hs; delete[] ts; delete[] osets; } /** Normalize the edge weights to sum to one. */ void prpack_base_graph::normalize_weights() { if (!vals) { // skip normalizing weights if not using values return; } std::vector rowsums(num_vs,0.); // the graph is in a compressed in-edge list. for (int i=0; i using namespace prpack; prpack_result::prpack_result() { x = NULL; } prpack_result::~prpack_result() { delete[] x; } igraph/src/prpack/prpack_base_graph.h0000644000175100001440000000241013431000472017404 0ustar hornikusers#ifndef PRPACK_ADJACENCY_LIST #define PRPACK_ADJACENCY_LIST #include "prpack_csc.h" #include "prpack_csr.h" #include "prpack_edge_list.h" #include #include namespace prpack { class prpack_base_graph { private: // helper methods void initialize(); void read_smat(std::FILE* f, const bool weighted); void read_edges(std::FILE* f); void read_ascii(std::FILE* f); public: // instance variables int num_vs; int num_es; int num_self_es; int* heads; int* tails; double* vals; // constructors prpack_base_graph(); // only to support inheritance prpack_base_graph(const prpack_csc* g); prpack_base_graph(const prpack_int64_csc* g); prpack_base_graph(const prpack_csr* g); prpack_base_graph(const prpack_edge_list* g); prpack_base_graph(const char* filename, const char* format, const bool weighted); prpack_base_graph(int nverts, int nedges, std::pair* edges); // destructor ~prpack_base_graph(); // operations void normalize_weights(); }; }; #endif igraph/src/prpack/prpack_csc.h0000644000175100001440000000102613431000472016063 0ustar hornikusers#ifndef PRPACK_CSC #define PRPACK_CSC #if !defined(_MSC_VER) && !defined (__MINGW32__) && !defined (__MINGW64__) # include #else # include typedef __int64 int64_t; #endif namespace prpack { class prpack_csc { public: int num_vs; int num_es; int* heads; int* tails; }; class prpack_int64_csc { public: int64_t num_vs; int64_t num_es; int64_t* heads; int64_t* tails; }; }; #endif igraph/src/prpack/prpack_csr.h0000644000175100001440000000032513431000472016103 0ustar hornikusers#ifndef PRPACK_CSR #define PRPACK_CSR namespace prpack { class prpack_csr { public: int num_vs; int num_es; int* heads; int* tails; }; }; #endif igraph/src/prpack/prpack_solver.h0000644000175100001440000001547213431000472016637 0ustar hornikusers#ifndef PRPACK_SOLVER #define PRPACK_SOLVER #include "prpack_base_graph.h" #include "prpack_csc.h" #include "prpack_csr.h" #include "prpack_edge_list.h" #include "prpack_preprocessed_ge_graph.h" #include "prpack_preprocessed_gs_graph.h" #include "prpack_preprocessed_scc_graph.h" #include "prpack_preprocessed_schur_graph.h" #include "prpack_result.h" // TODO Make this a user configurable variable #define PRPACK_SOLVER_MAX_ITERS 1000000 namespace prpack { // Solver class. class prpack_solver { private: // instance variables double read_time; prpack_base_graph* bg; prpack_preprocessed_ge_graph* geg; prpack_preprocessed_gs_graph* gsg; prpack_preprocessed_schur_graph* sg; prpack_preprocessed_scc_graph* sccg; bool owns_bg; // methods void initialize(); static prpack_result* solve_via_ge( const double alpha, const double tol, const int num_vs, const double* matrix, const double* uv); static prpack_result* solve_via_ge_uv( const double alpha, const double tol, const int num_vs, const double* matrix, const double* d, const double* u, const double* v); static prpack_result* solve_via_gs( const double alpha, const double tol, const int num_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v); static prpack_result* solve_via_gs_err( const double alpha, const double tol, const int num_vs, const int num_es, const int* heads, const int* tails, const double* ii, const double* num_outlinks, const double* u, const double* v); static prpack_result* solve_via_schur_gs( const double alpha, const double tol, const int num_vs, const int num_no_in_vs, const int num_no_out_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* uv, const int* encoding, const int* decoding, const bool should_normalize = true); static prpack_result* solve_via_schur_gs_uv( const double alpha, const double tol, const int num_vs, const int num_no_in_vs, const int num_no_out_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v, const int* encoding, const int* decoding); static prpack_result* solve_via_scc_gs( const double alpha, const double tol, const int num_vs, const int num_es_inside, const int* heads_inside, const int* tails_inside, const double* vals_inside, const int num_es_outside, const int* heads_outside, const int* tails_outside, const double* vals_outside, const double* ii, const double* d, const double* num_outlinks, const double* uv, const int num_comps, const int* divisions, const int* encoding, const int* decoding, const bool should_normalize = true); static prpack_result* solve_via_scc_gs_uv( const double alpha, const double tol, const int num_vs, const int num_es_inside, const int* heads_inside, const int* tails_inside, const double* vals_inside, const int num_es_outside, const int* heads_outside, const int* tails_outside, const double* vals_outside, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v, const int num_comps, const int* divisions, const int* encoding, const int* decoding); static void ge(const int sz, double* A, double* b); static void normalize(const int length, double* x); static prpack_result* combine_uv( const int num_vs, const double* d, const double* num_outlinks, const int* encoding, const double alpha, const prpack_result* ret_u, const prpack_result* ret_v); public: // constructors prpack_solver(const prpack_csc* g); prpack_solver(const prpack_int64_csc* g); prpack_solver(const prpack_csr* g); prpack_solver(const prpack_edge_list* g); prpack_solver(prpack_base_graph* g, bool owns_bg=true); prpack_solver(const char* filename, const char* format, const bool weighted); // destructor ~prpack_solver(); // methods int get_num_vs(); prpack_result* solve(const double alpha, const double tol, const char* method); prpack_result* solve( const double alpha, const double tol, const double* u, const double* v, const char* method); }; }; #endif igraph/src/prpack/prpack_igraph_graph.h0000644000175100001440000000075013431000472017751 0ustar hornikusers#ifndef PRPACK_IGRAPH_GRAPH #define PRPACK_IGRAPH_GRAPH #ifdef PRPACK_IGRAPH_SUPPORT #include "igraph_interface.h" #include "prpack_base_graph.h" namespace prpack { class prpack_igraph_graph : public prpack_base_graph { public: // constructors explicit prpack_igraph_graph(const igraph_t* g, const igraph_vector_t* weights = 0, igraph_bool_t directed = true); }; }; // PRPACK_IGRAPH_SUPPORT #endif // PRPACK_IGRAPH_GRAPH #endif igraph/src/prpack/prpack_igraph_graph.cpp0000644000175100001440000000765413431000472020316 0ustar hornikusers#include "prpack_igraph_graph.h" #include #include using namespace prpack; using namespace std; #ifdef PRPACK_IGRAPH_SUPPORT prpack_igraph_graph::prpack_igraph_graph(const igraph_t* g, const igraph_vector_t* weights, igraph_bool_t directed) { const igraph_bool_t treat_as_directed = igraph_is_directed(g) && directed; igraph_es_t es; igraph_eit_t eit; igraph_vector_t neis; long int i, j, eid, sum, temp, num_ignored_es; int *p_head, *p_head_copy; double* p_weight; // Get the number of vertices and edges. For undirected graphs, we add // an edge in both directions. num_vs = igraph_vcount(g); num_es = igraph_ecount(g); num_self_es = 0; if (!treat_as_directed) { num_es *= 2; } // Allocate memory for heads and tails p_head = heads = new int[num_es]; tails = new int[num_vs]; memset(tails, 0, num_vs * sizeof(tails[0])); // Allocate memory for weights if needed if (weights != 0) { p_weight = vals = new double[num_es]; } // Count the number of ignored edges (those with negative or zero weight) num_ignored_es = 0; if (treat_as_directed) { // Select all the edges and iterate over them by the source vertices es = igraph_ess_all(IGRAPH_EDGEORDER_TO); // Add the edges igraph_eit_create(g, es, &eit); while (!IGRAPH_EIT_END(eit)) { eid = IGRAPH_EIT_GET(eit); IGRAPH_EIT_NEXT(eit); // Handle the weight if (weights != 0) { // Does this edge have zero or negative weight? if (VECTOR(*weights)[eid] <= 0) { // Ignore it. num_ignored_es++; continue; } *p_weight = VECTOR(*weights)[eid]; ++p_weight; } *p_head = IGRAPH_FROM(g, eid); ++p_head; ++tails[IGRAPH_TO(g, eid)]; if (IGRAPH_FROM(g, eid) == IGRAPH_TO(g, eid)) { ++num_self_es; } } igraph_eit_destroy(&eit); } else { // Select all the edges and iterate over them by the target vertices igraph_vector_init(&neis, 0); for (i = 0; i < num_vs; i++) { igraph_incident(g, &neis, i, IGRAPH_ALL); temp = igraph_vector_size(&neis); // TODO: should loop edges be added in both directions? p_head_copy = p_head; for (j = 0; j < temp; j++) { if (weights != 0) { if (VECTOR(*weights)[(long int)VECTOR(neis)[j]] <= 0) { // Ignore num_ignored_es++; continue; } *p_weight = VECTOR(*weights)[(long int)VECTOR(neis)[j]]; ++p_weight; } *p_head = IGRAPH_OTHER(g, VECTOR(neis)[j], i); if (i == *p_head) { num_self_es++; } ++p_head; } tails[i] = p_head - p_head_copy; } igraph_vector_destroy(&neis); } // Decrease num_es by the number of ignored edges num_es -= num_ignored_es; // Finalize the tails vector for (i = 0, sum = 0; i < num_vs; ++i) { temp = sum; sum += tails[i]; tails[i] = temp; } // Normalize the weights normalize_weights(); // Debug /* printf("Heads:"); for (i = 0; i < num_es; ++i) { printf(" %d", heads[i]); } printf("\n"); printf("Tails:"); for (i = 0; i < num_vs; ++i) { printf(" %d", tails[i]); } printf("\n"); if (vals) { printf("Vals:"); for (i = 0; i < num_es; ++i) { printf(" %.4f", vals[i]); } printf("\n"); } printf("===========================\n"); */ } // PRPACK_IGRAPH_SUPPORT #endif igraph/src/prpack/prpack_preprocessed_schur_graph.h0000644000175100001440000000167413431000472022407 0ustar hornikusers#ifndef PRPACK_PREPROCESSED_SCHUR_GRAPH #define PRPACK_PREPROCESSED_SCHUR_GRAPH #include "prpack_preprocessed_graph.h" #include "prpack_base_graph.h" namespace prpack { class prpack_preprocessed_schur_graph : public prpack_preprocessed_graph { private: // helper methods void initialize(); void initialize_weighted(const prpack_base_graph* bg); void initialize_unweighted(const prpack_base_graph* bg); public: // instance variables int num_no_in_vs; int num_no_out_vs; int* heads; int* tails; double* vals; double* ii; double* num_outlinks; int* encoding; int* decoding; // constructors prpack_preprocessed_schur_graph(const prpack_base_graph* bg); // destructor ~prpack_preprocessed_schur_graph(); }; }; #endif igraph/src/prpack/prpack_solver.cpp0000644000175100001440000007270713431000472017176 0ustar hornikusers#include "prpack_solver.h" #include "prpack_utils.h" #include #include #include #include using namespace prpack; using namespace std; void prpack_solver::initialize() { geg = NULL; gsg = NULL; sg = NULL; sccg = NULL; owns_bg = true; } prpack_solver::prpack_solver(const prpack_csc* g) { initialize(); TIME(read_time, bg = new prpack_base_graph(g)); } prpack_solver::prpack_solver(const prpack_int64_csc* g) { initialize(); TIME(read_time, bg = new prpack_base_graph(g)); } prpack_solver::prpack_solver(const prpack_csr* g) { initialize(); TIME(read_time, bg = new prpack_base_graph(g)); } prpack_solver::prpack_solver(const prpack_edge_list* g) { initialize(); TIME(read_time, bg = new prpack_base_graph(g)); } prpack_solver::prpack_solver(prpack_base_graph* g, bool owns_bg) { initialize(); this->owns_bg = owns_bg; TIME(read_time, bg = g); } prpack_solver::prpack_solver(const char* filename, const char* format, const bool weighted) { initialize(); TIME(read_time, bg = new prpack_base_graph(filename, format, weighted)); } prpack_solver::~prpack_solver() { if (owns_bg) { delete bg; } delete geg; delete gsg; delete sg; delete sccg; } int prpack_solver::get_num_vs() { return bg->num_vs; } prpack_result* prpack_solver::solve(const double alpha, const double tol, const char* method) { return solve(alpha, tol, NULL, NULL, method); } prpack_result* prpack_solver::solve( const double alpha, const double tol, const double* u, const double* v, const char* method) { double preprocess_time = 0; double compute_time = 0; prpack_result* ret = NULL; // decide which method to run string m; if (strcmp(method, "") != 0) m = string(method); else { if (bg->num_vs < 128) m = "ge"; else if (sccg != NULL) m = "sccgs"; else if (sg != NULL) m = "sg"; else m = "sccgs"; if (u != v) m += "_uv"; } // run the appropriate method if (m == "ge") { if (geg == NULL) { TIME(preprocess_time, geg = new prpack_preprocessed_ge_graph(bg)); } TIME(compute_time, ret = solve_via_ge( alpha, tol, geg->num_vs, geg->matrix, u)); } else if (m == "ge_uv") { if (geg == NULL) { TIME(preprocess_time, geg = new prpack_preprocessed_ge_graph(bg)); } TIME(compute_time, ret = solve_via_ge_uv( alpha, tol, geg->num_vs, geg->matrix, geg->d, u, v)); } else if (m == "gs") { if (gsg == NULL) { TIME(preprocess_time, gsg = new prpack_preprocessed_gs_graph(bg)); } TIME(compute_time, ret = solve_via_gs( alpha, tol, gsg->num_vs, gsg->num_es, gsg->heads, gsg->tails, gsg->vals, gsg->ii, gsg->d, gsg->num_outlinks, u, v)); } else if (m == "gserr") { if (gsg == NULL) { TIME(preprocess_time, gsg = new prpack_preprocessed_gs_graph(bg)); } TIME(compute_time, ret = solve_via_gs_err( alpha, tol, gsg->num_vs, gsg->num_es, gsg->heads, gsg->tails, gsg->ii, gsg->num_outlinks, u, v)); } else if (m == "sgs") { if (sg == NULL) { TIME(preprocess_time, sg = new prpack_preprocessed_schur_graph(bg)); } TIME(compute_time, ret = solve_via_schur_gs( alpha, tol, sg->num_vs, sg->num_no_in_vs, sg->num_no_out_vs, sg->num_es, sg->heads, sg->tails, sg->vals, sg->ii, sg->d, sg->num_outlinks, u, sg->encoding, sg->decoding)); } else if (m == "sgs_uv") { if (sg == NULL) { TIME(preprocess_time, sg = new prpack_preprocessed_schur_graph(bg)); } TIME(compute_time, ret = solve_via_schur_gs_uv( alpha, tol, sg->num_vs, sg->num_no_in_vs, sg->num_no_out_vs, sg->num_es, sg->heads, sg->tails, sg->vals, sg->ii, sg->d, sg->num_outlinks, u, v, sg->encoding, sg->decoding)); } else if (m == "sccgs") { if (sccg == NULL) { TIME(preprocess_time, sccg = new prpack_preprocessed_scc_graph(bg)); } TIME(compute_time, ret = solve_via_scc_gs( alpha, tol, sccg->num_vs, sccg->num_es_inside, sccg->heads_inside, sccg->tails_inside, sccg->vals_inside, sccg->num_es_outside, sccg->heads_outside, sccg->tails_outside, sccg->vals_outside, sccg->ii, sccg->d, sccg->num_outlinks, u, sccg->num_comps, sccg->divisions, sccg->encoding, sccg->decoding)); } else if (m == "sccgs_uv") { if (sccg == NULL) { TIME(preprocess_time, sccg = new prpack_preprocessed_scc_graph(bg)); } TIME(compute_time, ret = solve_via_scc_gs_uv( alpha, tol, sccg->num_vs, sccg->num_es_inside, sccg->heads_inside, sccg->tails_inside, sccg->vals_inside, sccg->num_es_outside, sccg->heads_outside, sccg->tails_outside, sccg->vals_outside, sccg->ii, sccg->d, sccg->num_outlinks, u, v, sccg->num_comps, sccg->divisions, sccg->encoding, sccg->decoding)); } else { // TODO: throw exception } ret->method = m.c_str(); ret->read_time = read_time; ret->preprocess_time = preprocess_time; ret->compute_time = compute_time; ret->num_vs = bg->num_vs; ret->num_es = bg->num_es; return ret; } // VARIOUS SOLVING METHODS //////////////////////////////////////////////////////////////////////// prpack_result* prpack_solver::solve_via_ge( const double alpha, const double tol, const int num_vs, const double* matrix, const double* uv) { prpack_result* ret = new prpack_result(); // initialize uv values const double uv_const = 1.0/num_vs; const int uv_exists = (uv) ? 1 : 0; uv = (uv) ? uv : &uv_const; // create matrix A double* A = new double[num_vs*num_vs]; for (int i = 0; i < num_vs*num_vs; ++i) A[i] = -alpha*matrix[i]; for (int i = 0; i < num_vs*num_vs; i += num_vs + 1) ++A[i]; // create vector b double* b = new double[num_vs]; for (int i = 0; i < num_vs; ++i) b[i] = uv[uv_exists*i]; // solve and normalize ge(num_vs, A, b); normalize(num_vs, b); // clean up and return delete[] A; ret->num_es_touched = -1; ret->x = b; return ret; } prpack_result* prpack_solver::solve_via_ge_uv( const double alpha, const double tol, const int num_vs, const double* matrix, const double* d, const double* u, const double* v) { prpack_result* ret = new prpack_result(); // initialize u and v values const double u_const = 1.0/num_vs; const double v_const = 1.0/num_vs; const int u_exists = (u) ? 1 : 0; const int v_exists = (v) ? 1 : 0; u = (u) ? u : &u_const; v = (v) ? v : &v_const; // create matrix A double* A = new double[num_vs*num_vs]; for (int i = 0; i < num_vs*num_vs; ++i) A[i] = -alpha*matrix[i]; for (int i = 0, inum_vs = 0; i < num_vs; ++i, inum_vs += num_vs) for (int j = 0; j < num_vs; ++j) A[inum_vs + j] -= alpha*u[u_exists*i]*d[j]; for (int i = 0; i < num_vs*num_vs; i += num_vs + 1) ++A[i]; // create vector b double* b = new double[num_vs]; for (int i = 0; i < num_vs; ++i) b[i] = (1 - alpha)*v[v_exists*i]; // solve ge(num_vs, A, b); // clean up and return delete[] A; ret->num_es_touched = -1; ret->x = b; return ret; } // Vanilla Gauss-Seidel. prpack_result* prpack_solver::solve_via_gs( const double alpha, const double tol, const int num_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v) { prpack_result* ret = new prpack_result(); const bool weighted = vals != NULL; // initialize u and v values const double u_const = 1.0/num_vs; const double v_const = 1.0/num_vs; const int u_exists = (u) ? 1 : 0; const int v_exists = (v) ? 1 : 0; u = (u) ? u : &u_const; v = (v) ? v : &v_const; // initialize the eigenvector (and use personalization vector) double* x = new double[num_vs]; for (int i = 0; i < num_vs; ++i) x[i] = 0; // initialize delta double delta = 0; // run Gauss-Seidel ret->num_es_touched = 0; double err = 1, c = 0; do { if (weighted) { for (int i = 0; i < num_vs; ++i) { double new_val = 0; const int start_j = tails[i]; const int end_j = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int j = start_j; j < end_j; ++j) // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads[j]]*vals[j]; new_val = alpha*new_val + (1 - alpha)*v[v_exists*i]; delta -= alpha*x[i]*d[i]; new_val += delta*u[u_exists*i]; new_val /= 1 - alpha*(d[i]*u[u_exists*i] + (1 - d[i])*ii[i]); delta += alpha*new_val*d[i]; COMPENSATED_SUM(err, x[i] - new_val, c); x[i] = new_val; } } else { for (int i = 0; i < num_vs; ++i) { const double old_val = x[i]*num_outlinks[i]; double new_val = 0; const int start_j = tails[i]; const int end_j = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int j = start_j; j < end_j; ++j) // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads[j]]; new_val = alpha*new_val + (1 - alpha)*v[v_exists*i]; if (num_outlinks[i] < 0) { delta -= alpha*old_val; new_val += delta*u[u_exists*i]; new_val /= 1 - alpha*u[u_exists*i]; delta += alpha*new_val; } else { new_val += delta*u[u_exists*i]; new_val /= 1 - alpha*ii[i]; } COMPENSATED_SUM(err, old_val - new_val, c); x[i] = new_val/num_outlinks[i]; } } // update iteration index ret->num_es_touched += num_es; } while (err >= tol); // undo num_outlinks transformation if (!weighted) for (int i = 0; i < num_vs; ++i) x[i] *= num_outlinks[i]; // return results ret->x = x; return ret; } // Implement a gauss-seidel-like process with a strict error bound // we return a solution with 1-norm error less than tol. prpack_result* prpack_solver::solve_via_gs_err( const double alpha, const double tol, const int num_vs, const int num_es, const int* heads, const int* tails, const double* ii, const double* num_outlinks, const double* u, const double* v) { prpack_result* ret = new prpack_result(); // initialize u and v values const double u_const = 1.0/num_vs; const double v_const = 1.0/num_vs; const int u_exists = (u) ? 1 : 0; const int v_exists = (v) ? 1 : 0; u = (u) ? u : &u_const; v = (v) ? v : &v_const; // Note to Dave, we can't rescale v because we could be running this // same routine from multiple threads. // initialize the eigenvector (and use personalization vector) double* x = new double[num_vs]; for (int i = 0; i < num_vs; ++i) { x[i] = 0.; } // initialize delta double delta = 0.; // run Gauss-Seidel, note that we store x/deg[i] throughout this // iteration. int64_t maxedges = (int64_t)((double)num_es*std::min( log(tol)/log(alpha), (double)PRPACK_SOLVER_MAX_ITERS)); ret->num_es_touched = 0; double err=1., c = 0.; do { // iterate through vertices for (int i = 0; i < num_vs; ++i) { double old_val = x[i]*num_outlinks[i]; // adjust back to the "true" value. double new_val = 0.; int start_j = tails[i], end_j = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int j = start_j; j < end_j; ++j) { // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads[j]]; } new_val = alpha*new_val + alpha*ii[i]*old_val + (1.0-alpha)*v[v_exists*i]; new_val += delta*u[u_exists*i]; // add the dangling node adjustment if (num_outlinks[i] < 0) { delta += alpha*(new_val - old_val); } // note that new_val > old_val, but the fabs is just for COMPENSATED_SUM(err, -(new_val - old_val), c); x[i] = new_val/num_outlinks[i]; } // update iteration index ret->num_es_touched += num_es; } while (err >= tol && ret->num_es_touched < maxedges); if (err >= tol) { ret->converged = 0; } else { ret->converged = 1; } // undo num_outlinks transformation for (int i = 0; i < num_vs; ++i) x[i] *= num_outlinks[i]; // return results ret->x = x; return ret; } // Gauss-Seidel using the Schur complement to separate dangling nodes. prpack_result* prpack_solver::solve_via_schur_gs( const double alpha, const double tol, const int num_vs, const int num_no_in_vs, const int num_no_out_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* uv, const int* encoding, const int* decoding, const bool should_normalize) { prpack_result* ret = new prpack_result(); const bool weighted = vals != NULL; // initialize uv values const double uv_const = 1.0/num_vs; const int uv_exists = (uv) ? 1 : 0; uv = (uv) ? prpack_utils::permute(num_vs, uv, encoding) : &uv_const; // initialize the eigenvector (and use personalization vector) double* x = new double[num_vs]; for (int i = 0; i < num_vs - num_no_out_vs; ++i) x[i] = uv[uv_exists*i]/(1 - alpha*ii[i])/((weighted) ? 1 : num_outlinks[i]); // run Gauss-Seidel for the top left part of (I - alpha*P)*x = uv ret->num_es_touched = 0; double err, c; do { // iterate through vertices int num_es_touched = 0; err = c = 0; #pragma omp parallel for firstprivate(c) reduction(+:err, num_es_touched) schedule(dynamic, 64) for (int i = num_no_in_vs; i < num_vs - num_no_out_vs; ++i) { double new_val = 0; const int start_j = tails[i]; const int end_j = (i + 1 != num_vs) ? tails[i + 1] : num_es; if (weighted) { for (int j = start_j; j < end_j; ++j) // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads[j]]*vals[j]; COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]), c); new_val = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i]); x[i] = new_val; } else { for (int j = start_j; j < end_j; ++j) // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads[j]]; COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]*num_outlinks[i]), c); new_val = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i]); x[i] = new_val/num_outlinks[i]; } num_es_touched += end_j - start_j; } // update iteration index ret->num_es_touched += num_es_touched; } while (err/(1 - alpha) >= tol); // solve for the dangling nodes int num_es_touched = 0; #pragma omp parallel for reduction(+:num_es_touched) schedule(dynamic, 64) for (int i = num_vs - num_no_out_vs; i < num_vs; ++i) { x[i] = 0; const int start_j = tails[i]; const int end_j = (i + 1 != num_vs) ? tails[i + 1] : num_es; for (int j = start_j; j < end_j; ++j) x[i] += x[heads[j]]*((weighted) ? vals[j] : 1); x[i] = (alpha*x[i] + uv[uv_exists*i])/(1 - alpha*ii[i]); num_es_touched += end_j - start_j; } ret->num_es_touched += num_es_touched; // undo num_outlinks transformation if (!weighted) for (int i = 0; i < num_vs - num_no_out_vs; ++i) x[i] *= num_outlinks[i]; // normalize x to get the solution for: (I - alpha*P - alpha*u*d')*x = (1 - alpha)*v if (should_normalize) normalize(num_vs, x); // return results ret->x = prpack_utils::permute(num_vs, x, decoding); delete[] x; if (uv_exists) delete[] uv; return ret; } prpack_result* prpack_solver::solve_via_schur_gs_uv( const double alpha, const double tol, const int num_vs, const int num_no_in_vs, const int num_no_out_vs, const int num_es, const int* heads, const int* tails, const double* vals, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v, const int* encoding, const int* decoding) { // solve uv = u prpack_result* ret_u = solve_via_schur_gs( alpha, tol, num_vs, num_no_in_vs, num_no_out_vs, num_es, heads, tails, vals, ii, d, num_outlinks, u, encoding, decoding, false); // solve uv = v prpack_result* ret_v = solve_via_schur_gs( alpha, tol, num_vs, num_no_in_vs, num_no_out_vs, num_es, heads, tails, vals, ii, d, num_outlinks, v, encoding, decoding, false); // combine the u and v cases return combine_uv(num_vs, d, num_outlinks, encoding, alpha, ret_u, ret_v); } /** Gauss-Seidel using strongly connected components. * Notes: * If not weighted, then we store x[i] = "x[i]/outdegree" to * avoid additional arithmetic. We don't do this for the weighted * case because the adjustment may not be constant. */ prpack_result* prpack_solver::solve_via_scc_gs( const double alpha, const double tol, const int num_vs, const int num_es_inside, const int* heads_inside, const int* tails_inside, const double* vals_inside, const int num_es_outside, const int* heads_outside, const int* tails_outside, const double* vals_outside, const double* ii, const double* d, const double* num_outlinks, const double* uv, const int num_comps, const int* divisions, const int* encoding, const int* decoding, const bool should_normalize) { prpack_result* ret = new prpack_result(); const bool weighted = vals_inside != NULL; // initialize uv values const double uv_const = 1.0/num_vs; const int uv_exists = (uv) ? 1 : 0; uv = (uv) ? prpack_utils::permute(num_vs, uv, encoding) : &uv_const; // CHECK initialize the solution with one iteration of GS from x=0. double* x = new double[num_vs]; for (int i = 0; i < num_vs; ++i) x[i] = uv[uv_exists*i]/(1 - alpha*ii[i])/((weighted) ? 1 : num_outlinks[i]); // create x_outside double* x_outside = new double[num_vs]; // run Gauss-Seidel for (I - alpha*P)*x = uv ret->num_es_touched = 0; for (int comp_i = 0; comp_i < num_comps; ++comp_i) { const int start_comp = divisions[comp_i]; const int end_comp = (comp_i + 1 != num_comps) ? divisions[comp_i + 1] : num_vs; const bool parallelize = end_comp - start_comp > 512; // initialize relevant x_outside values for (int i = start_comp; i < end_comp; ++i) { x_outside[i] = 0; const int start_j = tails_outside[i]; const int end_j = (i + 1 != num_vs) ? tails_outside[i + 1] : num_es_outside; for (int j = start_j; j < end_j; ++j) x_outside[i] += x[heads_outside[j]]*((weighted) ? vals_outside[j] : 1.); ret->num_es_touched += end_j - start_j; } double err, c; do { int num_es_touched = 0; err = c = 0; if (parallelize) { // iterate through vertices #pragma omp parallel for firstprivate(c) reduction(+:err, num_es_touched) schedule(dynamic, 64) for (int i = start_comp; i < end_comp; ++i) { double new_val = x_outside[i]; const int start_j = tails_inside[i]; const int end_j = (i + 1 != num_vs) ? tails_inside[i + 1] : num_es_inside; if (weighted) { for (int j = start_j; j < end_j; ++j) { // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads_inside[j]]*vals_inside[j]; } COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]), c); x[i] = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i]); } else { for (int j = start_j; j < end_j; ++j) { // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads_inside[j]]; } COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]*num_outlinks[i]), c); x[i] = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i])/num_outlinks[i]; } num_es_touched += end_j - start_j; } } else { for (int i = start_comp; i < end_comp; ++i) { double new_val = x_outside[i]; const int start_j = tails_inside[i]; const int end_j = (i + 1 != num_vs) ? tails_inside[i + 1] : num_es_inside; if (weighted) { for (int j = start_j; j < end_j; ++j) { // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads_inside[j]]*vals_inside[j]; } COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]), c); x[i] = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i]); } else { for (int j = start_j; j < end_j; ++j) { // TODO: might want to use compensation summation for large: end_j - start_j new_val += x[heads_inside[j]]; } COMPENSATED_SUM(err, fabs(uv[uv_exists*i] + alpha*new_val - (1 - alpha*ii[i])*x[i]*num_outlinks[i]), c); x[i] = (alpha*new_val + uv[uv_exists*i])/(1 - alpha*ii[i])/num_outlinks[i]; } num_es_touched += end_j - start_j; } } // update iteration index ret->num_es_touched += num_es_touched; } while (err/(1 - alpha) >= tol*(end_comp - start_comp)/num_vs); } // undo num_outlinks transformation if (!weighted) for (int i = 0; i < num_vs; ++i) x[i] *= num_outlinks[i]; // normalize x to get the solution for: (I - alpha*P - alpha*u*d')*x = (1 - alpha)*v if (should_normalize) normalize(num_vs, x); // return results ret->x = prpack_utils::permute(num_vs, x, decoding); delete[] x; delete[] x_outside; if (uv_exists) delete[] uv; return ret; } prpack_result* prpack_solver::solve_via_scc_gs_uv( const double alpha, const double tol, const int num_vs, const int num_es_inside, const int* heads_inside, const int* tails_inside, const double* vals_inside, const int num_es_outside, const int* heads_outside, const int* tails_outside, const double* vals_outside, const double* ii, const double* d, const double* num_outlinks, const double* u, const double* v, const int num_comps, const int* divisions, const int* encoding, const int* decoding) { // solve uv = u prpack_result* ret_u = solve_via_scc_gs( alpha, tol, num_vs, num_es_inside, heads_inside, tails_inside, vals_inside, num_es_outside, heads_outside, tails_outside, vals_outside, ii, d, num_outlinks, u, num_comps, divisions, encoding, decoding, false); // solve uv = v prpack_result* ret_v = solve_via_scc_gs( alpha, tol, num_vs, num_es_inside, heads_inside, tails_inside, vals_inside, num_es_outside, heads_outside, tails_outside, vals_outside, ii, d, num_outlinks, v, num_comps, divisions, encoding, decoding, false); // combine u and v return combine_uv(num_vs, d, num_outlinks, encoding, alpha, ret_u, ret_v); } // VARIOUS HELPER METHODS ///////////////////////////////////////////////////////////////////////// // Run Gaussian-Elimination (note: this changes A and returns the solution in b) void prpack_solver::ge(const int sz, double* A, double* b) { // put into triangular form for (int i = 0, isz = 0; i < sz; ++i, isz += sz) for (int k = 0, ksz = 0; k < i; ++k, ksz += sz) if (A[isz + k] != 0) { const double coeff = A[isz + k]/A[ksz + k]; A[isz + k] = 0; for (int j = k + 1; j < sz; ++j) A[isz + j] -= coeff*A[ksz + j]; b[i] -= coeff*b[k]; } // backwards substitution for (int i = sz - 1, isz = (sz - 1)*sz; i >= 0; --i, isz -= sz) { for (int j = i + 1; j < sz; ++j) b[i] -= A[isz + j]*b[j]; b[i] /= A[isz + i]; } } // Normalize a vector to sum to 1. void prpack_solver::normalize(const int length, double* x) { double norm = 0, c = 0; for (int i = 0; i < length; ++i) { COMPENSATED_SUM(norm, x[i], c); } norm = 1/norm; for (int i = 0; i < length; ++i) x[i] *= norm; } // Combine u and v results. prpack_result* prpack_solver::combine_uv( const int num_vs, const double* d, const double* num_outlinks, const int* encoding, const double alpha, const prpack_result* ret_u, const prpack_result* ret_v) { prpack_result* ret = new prpack_result(); const bool weighted = d != NULL; double delta_u = 0; double delta_v = 0; for (int i = 0; i < num_vs; ++i) { if ((weighted) ? (d[encoding[i]] == 1) : (num_outlinks[encoding[i]] < 0)) { delta_u += ret_u->x[i]; delta_v += ret_v->x[i]; } } const double s = ((1 - alpha)*alpha*delta_v)/(1 - alpha*delta_u); const double t = 1 - alpha; ret->x = new double[num_vs]; for (int i = 0; i < num_vs; ++i) ret->x[i] = s*ret_u->x[i] + t*ret_v->x[i]; ret->num_es_touched = ret_u->num_es_touched + ret_v->num_es_touched; // clean up and return delete ret_u; delete ret_v; return ret; } igraph/src/prpack/prpack_preprocessed_gs_graph.h0000644000175100001440000000153313431000472021666 0ustar hornikusers#ifndef PRPACK_PREPROCESSED_GS_GRAPH #define PRPACK_PREPROCESSED_GS_GRAPH #include "prpack_preprocessed_graph.h" #include "prpack_base_graph.h" namespace prpack { // Pre-processed graph class class prpack_preprocessed_gs_graph : public prpack_preprocessed_graph { private: // helper methods void initialize(); void initialize_weighted(const prpack_base_graph* bg); void initialize_unweighted(const prpack_base_graph* bg); public: // instance variables int* heads; int* tails; double* vals; double* ii; double* num_outlinks; // constructors prpack_preprocessed_gs_graph(const prpack_base_graph* bg); // destructor ~prpack_preprocessed_gs_graph(); }; }; #endif igraph/src/prpack/prpack_preprocessed_scc_graph.h0000644000175100001440000000220313431000472022020 0ustar hornikusers#ifndef PRPACK_PREPROCESSED_SCC_GRAPH #define PRPACK_PREPROCESSED_SCC_GRAPH #include "prpack_preprocessed_graph.h" #include "prpack_base_graph.h" namespace prpack { // Pre-processed graph class class prpack_preprocessed_scc_graph : public prpack_preprocessed_graph { private: // helper methods void initialize(); void initialize_weighted(const prpack_base_graph* bg); void initialize_unweighted(const prpack_base_graph* bg); public: // instance variables int num_es_inside; int* heads_inside; int* tails_inside; double* vals_inside; int num_es_outside; int* heads_outside; int* tails_outside; double* vals_outside; double* ii; double* num_outlinks; int num_comps; int* divisions; int* encoding; int* decoding; // constructors prpack_preprocessed_scc_graph(const prpack_base_graph* bg); // destructor ~prpack_preprocessed_scc_graph(); }; }; #endif igraph/src/prpack/prpack_preprocessed_schur_graph.cpp0000644000175100001440000001001513431000472022727 0ustar hornikusers#include "prpack_preprocessed_schur_graph.h" #include #include using namespace prpack; using namespace std; void prpack_preprocessed_schur_graph::initialize() { heads = NULL; tails = NULL; vals = NULL; ii = NULL; d = NULL; num_outlinks = NULL; encoding = NULL; decoding = NULL; } void prpack_preprocessed_schur_graph::initialize_weighted(const prpack_base_graph* bg) { // permute d ii = d; d = new double[num_vs]; for (int i = 0; i < num_vs; ++i) d[encoding[i]] = ii[i]; // convert bg to head/tail format for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { ii[tails_i] = 0; tails[tails_i] = heads_i; const int decoded = decoding[tails_i]; const int start_i = bg->tails[decoded]; const int end_i = (decoded + 1 != num_vs) ? bg->tails[decoded + 1] : bg->num_es; for (int i = start_i; i < end_i; ++i) { if (decoded == bg->heads[i]) ii[tails_i] += bg->vals[i]; else { heads[heads_i] = encoding[bg->heads[i]]; vals[heads_i] = bg->vals[i]; ++heads_i; } } } } void prpack_preprocessed_schur_graph::initialize_unweighted(const prpack_base_graph* bg) { // permute num_outlinks ii = num_outlinks; num_outlinks = new double[num_vs]; for (int i = 0; i < num_vs; ++i) num_outlinks[encoding[i]] = (ii[i] == 0) ? -1 : ii[i]; // convert bg to head/tail format for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { ii[tails_i] = 0; tails[tails_i] = heads_i; const int decoded = decoding[tails_i]; const int start_i = bg->tails[decoded]; const int end_i = (decoded + 1 != num_vs) ? bg->tails[decoded + 1] : bg->num_es; for (int i = start_i; i < end_i; ++i) { if (decoded == bg->heads[i]) ++ii[tails_i]; else heads[heads_i++] = encoding[bg->heads[i]]; } if (ii[tails_i] > 0) ii[tails_i] /= num_outlinks[tails_i]; } } prpack_preprocessed_schur_graph::prpack_preprocessed_schur_graph(const prpack_base_graph* bg) { initialize(); // initialize instance variables num_vs = bg->num_vs; num_es = bg->num_es - bg->num_self_es; tails = new int[num_vs]; heads = new int[num_es]; const bool weighted = bg->vals != NULL; if (weighted) { vals = new double[num_vs]; d = new double[num_vs]; fill(d, d + num_vs, 1); for (int i = 0; i < bg->num_es; ++i) d[bg->heads[i]] -= bg->vals[i]; } else { num_outlinks = new double[num_vs]; fill(num_outlinks, num_outlinks + num_vs, 0); for (int i = 0; i < bg->num_es; ++i) ++num_outlinks[bg->heads[i]]; } // permute no-inlink vertices to the beginning, and no-outlink vertices to the end encoding = new int[num_vs]; decoding = new int[num_vs]; num_no_in_vs = num_no_out_vs = 0; for (int i = 0; i < num_vs; ++i) { if (bg->tails[i] == ((i + 1 != num_vs) ? bg->tails[i + 1] : bg->num_es)) { decoding[encoding[i] = num_no_in_vs] = i; ++num_no_in_vs; } else if ((weighted) ? (d[i] == 1) : (num_outlinks[i] == 0)) { decoding[encoding[i] = num_vs - 1 - num_no_out_vs] = i; ++num_no_out_vs; } } // permute everything else for (int i = 0, p = num_no_in_vs; i < num_vs; ++i) if (bg->tails[i] < ((i + 1 != num_vs) ? bg->tails[i + 1] : bg->num_es) && ((weighted) ? (d[i] < 1) : (num_outlinks[i] > 0))) decoding[encoding[i] = p++] = i; // continue initialization based off of weightedness if (weighted) initialize_weighted(bg); else initialize_unweighted(bg); } prpack_preprocessed_schur_graph::~prpack_preprocessed_schur_graph() { delete[] heads; delete[] tails; delete[] vals; delete[] ii; delete[] d; delete[] num_outlinks; delete[] encoding; delete[] decoding; } igraph/src/prpack/prpack_utils.cpp0000644000175100001440000000262613431000472017015 0ustar hornikusers/** * @file prpack_utils.cpp * An assortment of utility functions for reporting errors, checking time, * and working with vectors. */ #include #include "prpack_utils.h" #include #include #include using namespace prpack; using namespace std; #ifdef PRPACK_IGRAPH_SUPPORT #include "igraph_error.h" #endif #if defined(_WIN32) || defined(_WIN64) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #include #endif double prpack_utils::get_time() { LARGE_INTEGER t, freq; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&freq); return double(t.QuadPart)/double(freq.QuadPart); } #else #include #include double prpack_utils::get_time() { struct timeval t; gettimeofday(&t, 0); return (t.tv_sec*1.0 + t.tv_usec/1000000.0); } #endif // Fails and outputs 'msg' if 'condition' is false. void prpack_utils::validate(const bool condition, const string& msg) { if (!condition) { #ifdef PRPACK_IGRAPH_SUPPORT igraph_error("Internal error in PRPACK", __FILE__, __LINE__, IGRAPH_EINTERNAL); #else cerr << msg << endl; exit(-1); #endif } } // Permute a vector. double* prpack_utils::permute(const int length, const double* a, const int* coding) { double* ret = new double[length]; for (int i = 0; i < length; ++i) ret[coding[i]] = a[i]; return ret; } igraph/src/prpack/prpack_preprocessed_ge_graph.h0000644000175100001440000000136313431000472021651 0ustar hornikusers#ifndef PRPACK_PREPROCESSED_GE_GRAPH #define PRPACK_PREPROCESSED_GE_GRAPH #include "prpack_preprocessed_graph.h" #include "prpack_base_graph.h" namespace prpack { // Pre-processed graph class class prpack_preprocessed_ge_graph : public prpack_preprocessed_graph { private: // helper methods void initialize(); void initialize_weighted(const prpack_base_graph* bg); void initialize_unweighted(const prpack_base_graph* bg); public: // instance variables double* matrix; // constructors prpack_preprocessed_ge_graph(const prpack_base_graph* bg); // destructor ~prpack_preprocessed_ge_graph(); }; }; #endif igraph/src/prpack/prpack_preprocessed_ge_graph.cpp0000644000175100001440000000376113431000472022210 0ustar hornikusers#include "prpack_preprocessed_ge_graph.h" #include using namespace prpack; using namespace std; void prpack_preprocessed_ge_graph::initialize() { matrix = NULL; d = NULL; } void prpack_preprocessed_ge_graph::initialize_weighted(const prpack_base_graph* bg) { // initialize d fill(d, d + num_vs, 1); // fill in the matrix for (int i = 0, inum_vs = 0; i < num_vs; ++i, inum_vs += num_vs) { const int start_j = bg->tails[i]; const int end_j = (i + 1 != num_vs) ? bg->tails[i + 1] : bg->num_es; for (int j = start_j; j < end_j; ++j) d[bg->heads[j]] -= matrix[inum_vs + bg->heads[j]] = bg->vals[j]; } } void prpack_preprocessed_ge_graph::initialize_unweighted(const prpack_base_graph* bg) { // fill in the matrix for (int i = 0, inum_vs = 0; i < num_vs; ++i, inum_vs += num_vs) { const int start_j = bg->tails[i]; const int end_j = (i + 1 != num_vs) ? bg->tails[i + 1] : bg->num_es; for (int j = start_j; j < end_j; ++j) ++matrix[inum_vs + bg->heads[j]]; } // normalize the columns for (int j = 0; j < num_vs; ++j) { double sum = 0; for (int inum_vs = 0; inum_vs < num_vs*num_vs; inum_vs += num_vs) sum += matrix[inum_vs + j]; if (sum > 0) { d[j] = 0; const double coeff = 1/sum; for (int inum_vs = 0; inum_vs < num_vs*num_vs; inum_vs += num_vs) matrix[inum_vs + j] *= coeff; } else { d[j] = 1; } } } prpack_preprocessed_ge_graph::prpack_preprocessed_ge_graph(const prpack_base_graph* bg) { initialize(); num_vs = bg->num_vs; num_es = bg->num_es; matrix = new double[num_vs*num_vs]; d = new double[num_vs]; fill(matrix, matrix + num_vs*num_vs, 0); if (bg->vals != NULL) initialize_weighted(bg); else initialize_unweighted(bg); } prpack_preprocessed_ge_graph::~prpack_preprocessed_ge_graph() { delete[] matrix; delete[] d; } igraph/src/prpack/prpack_preprocessed_gs_graph.cpp0000644000175100001440000000461613431000472022226 0ustar hornikusers#include "prpack_preprocessed_gs_graph.h" #include using namespace prpack; using namespace std; void prpack_preprocessed_gs_graph::initialize() { heads = NULL; tails = NULL; vals = NULL; ii = NULL; d = NULL; num_outlinks = NULL; } void prpack_preprocessed_gs_graph::initialize_weighted(const prpack_base_graph* bg) { vals = new double[num_es]; d = new double[num_vs]; fill(d, d + num_vs, 1); for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; ii[tails_i] = 0; const int start_j = bg->tails[tails_i]; const int end_j = (tails_i + 1 != num_vs) ? bg->tails[tails_i + 1]: bg->num_es; for (int j = start_j; j < end_j; ++j) { if (tails_i == bg->heads[j]) ii[tails_i] += bg->vals[j]; else { heads[heads_i] = bg->heads[j]; vals[heads_i] = bg->vals[j]; ++heads_i; } d[bg->heads[j]] -= bg->vals[j]; } } } void prpack_preprocessed_gs_graph::initialize_unweighted(const prpack_base_graph* bg) { num_outlinks = new double[num_vs]; fill(num_outlinks, num_outlinks + num_vs, 0); for (int tails_i = 0, heads_i = 0; tails_i < num_vs; ++tails_i) { tails[tails_i] = heads_i; ii[tails_i] = 0; const int start_j = bg->tails[tails_i]; const int end_j = (tails_i + 1 != num_vs) ? bg->tails[tails_i + 1]: bg->num_es; for (int j = start_j; j < end_j; ++j) { if (tails_i == bg->heads[j]) ++ii[tails_i]; else heads[heads_i++] = bg->heads[j]; ++num_outlinks[bg->heads[j]]; } } for (int i = 0; i < num_vs; ++i) { if (num_outlinks[i] == 0) num_outlinks[i] = -1; ii[i] /= num_outlinks[i]; } } prpack_preprocessed_gs_graph::prpack_preprocessed_gs_graph(const prpack_base_graph* bg) { initialize(); num_vs = bg->num_vs; num_es = bg->num_es - bg->num_self_es; heads = new int[num_es]; tails = new int[num_vs]; ii = new double[num_vs]; if (bg->vals != NULL) initialize_weighted(bg); else initialize_unweighted(bg); } prpack_preprocessed_gs_graph::~prpack_preprocessed_gs_graph() { delete[] heads; delete[] tails; delete[] vals; delete[] ii; delete[] d; delete[] num_outlinks; } igraph/src/walktrap_graph.h0000644000175100001440000000661713431000472015514 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here */ // File: graph.h //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pascal.pons@gmail.com // Web page : http://www-rp.lip6.fr/~latapy/PP/walktrap.html // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details /* FSF address above was fixed by Tamas Nepusz */ #ifndef GRAPH_H #define GRAPH_H #include #include "igraph_community.h" namespace igraph { namespace walktrap { using namespace std; class Edge { // code an edge of a given vertex public: int neighbor; // the number of the neighbor vertex float weight; // the weight of the edge }; bool operator<(const Edge& E1, const Edge& E2); class Vertex { public: Edge* edges; // the edges of the vertex int degree; // number of neighbors float total_weight; // the total weight of the vertex Vertex(); // creates empty vertex ~Vertex(); // destructor }; class Graph { public: int nb_vertices; // number of vertices int nb_edges; // number of edges float total_weight; // total weight of the edges Vertex* vertices; // array of the vertices long memory(); // the total memory used in Bytes Graph(); // create an empty graph ~Graph(); // destructor char** index; // to keep the real name of the vertices int convert_from_igraph(const igraph_t * igraph, const igraph_vector_t *weights); }; } } /* end of namespaces */ #endif igraph/src/stat.h0000644000175100001440000000171313431000472013451 0ustar hornikusersc %--------------------------------% c | See stat.doc for documentation | c %--------------------------------% c c\SCCS Information: @(#) c FILE: stat.h SID: 2.2 DATE OF SID: 11/16/95 RELEASE: 2 c real t0, t1, t2, t3, t4, t5 c save t0, t1, t2, t3, t4, t5 c integer nopx, nbx, nrorth, nitref, nrstrt real tsaupd, tsaup2, tsaitr, tseigt, tsgets, tsapps, tsconv, & tnaupd, tnaup2, tnaitr, tneigh, tngets, tnapps, tnconv, & tcaupd, tcaup2, tcaitr, tceigh, tcgets, tcapps, tcconv, & tmvopx, tmvbx, tgetv0, titref, trvec common /timing/ & nopx, nbx, nrorth, nitref, nrstrt, & tsaupd, tsaup2, tsaitr, tseigt, tsgets, tsapps, tsconv, & tnaupd, tnaup2, tnaitr, tneigh, tngets, tnapps, tnconv, & tcaupd, tcaup2, tcaitr, tceigh, tcgets, tcapps, tcconv, & tmvopx, tmvbx, tgetv0, titref, trvec igraph/src/hacks.c0000644000175100001440000000317513431000472013566 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include "igraph_hacks_internal.h" /* These are implementations of common C functions that may be missing from some * compilers; for instance, icc does not provide stpcpy so we implement it * here. */ /** * Drop-in replacement for strdup. * Used only in compilers that do not have strdup or _strdup */ char* igraph_i_strdup(const char *s) { size_t n = strlen(s) + 1; char* result = (char*)malloc(sizeof(char) * n); if (result) memcpy(result, s, n); return result; } /** * Drop-in replacement for stpcpy. * Used only in compilers that do not have stpcpy */ char* igraph_i_stpcpy(char* s1, const char* s2) { char* result = strcpy(s1, s2); return result + strlen(s1); } igraph/src/igraph_hrg_types.cc0000644000175100001440000032045413431000472016200 0ustar hornikusers// *********************************************************************** // *** COPYRIGHT NOTICE ************************************************** // rbtree - red-black tree (self-balancing binary tree data structure) // Copyright (C) 2004 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // *********************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | // http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science // AND Santa Fe Institute // Created : Spring 2004 // Modified : many, many times // // *********************************************************************** #include "hrg_rbtree.h" #include "hrg_dendro.h" #include "hrg_graph.h" #include "hrg_splittree_eq.h" #include "hrg_graph_simp.h" #include "igraph_hrg.h" #include "igraph_constructors.h" #include "igraph_random.h" using namespace fitHRG; // ******** Red-Black Tree Methods *************************************** rbtree::rbtree() { root = new elementrb; leaf = new elementrb; leaf->parent = root; root->left = leaf; root->right = leaf; support = 0; } rbtree::~rbtree() { if (root != NULL && (root->left != leaf || root->right != leaf)) { deleteSubTree(root); } if (root) delete root; delete leaf; support = 0; root = 0; leaf = 0; } void rbtree::deleteTree() { if (root != NULL) { deleteSubTree(root); } } // does not leak memory void rbtree::deleteSubTree(elementrb *z) { if (z->left != leaf) { deleteSubTree(z->left); } if (z->right != leaf) { deleteSubTree(z->right); } delete z; } // ******** Search Functions ********************************************* // public search function - if there exists a elementrb in the tree // with key=searchKey, it returns TRUE and foundNode is set to point // to the found node; otherwise, it sets foundNode=NULL and returns // FALSE elementrb* rbtree::findItem(const int searchKey) { elementrb *current=root; // empty tree; bail out if (current->key==-1) { return NULL; } while (current != leaf) { // left-or-right? if (searchKey < current->key) { // try moving down-left if (current->left != leaf) { current = current->left; } else { // failure; bail out return NULL; } } else { // left-or-right? if (searchKey > current->key) { // try moving down-left if (current->right != leaf) { current = current->right; } else { // failure; bail out return NULL; } } else { // found (searchKey==current->key) return current; } } } return NULL; } int rbtree::returnValue(const int searchKey) { elementrb* test = findItem(searchKey); if (!test) { return 0; } else { return test->value; } } // ******** Return Item Functions **************************************** int* rbtree::returnArrayOfKeys() { int* array; array = new int [support]; bool flag_go = true; int index = 0; elementrb *curr; if (support == 1) { array[0] = root->key; } else if (support == 2) { array[0] = root->key; if (root->left == leaf) { array[1] = root->right->key; } else { array[1] = root->left->key; } } else { for (int i=0; imark = 1; while (flag_go) { // - is it time, and is left child the leaf node? if (curr->mark == 1 && curr->left == leaf) { curr->mark = 2; } // - is it time, and is right child the leaf node? if (curr->mark == 2 && curr->right == leaf) { curr->mark = 3; } if (curr->mark == 1) { // - go left curr->mark = 2; curr = curr->left; curr->mark = 1; } else if (curr->mark == 2) { // - else go right curr->mark = 3; curr = curr->right; curr->mark = 1; } else { // - else go up a level curr->mark = 0; array[index++] = curr->key; curr = curr->parent; if (curr == NULL) { flag_go = false; } } } } return array; } list* rbtree::returnListOfKeys() { keyValuePair *curr, *prev; list *head=0, *tail=0, *newlist; curr = returnTreeAsList(); while (curr != NULL) { newlist = new list; newlist->x = curr->x; if (head == NULL) { head = newlist; tail = head; } else { tail->next = newlist; tail = newlist; } prev = curr; curr = curr->next; delete prev; prev = NULL; } return head; } keyValuePair* rbtree::returnTreeAsList() { // pre-order traversal keyValuePair *head, *tail; head = new keyValuePair; head->x = root->key; head->y = root->value; tail = head; if (root->left != leaf) { tail = returnSubtreeAsList(root->left, tail); } if (root->right != leaf) { tail = returnSubtreeAsList(root->right, tail); } if (head->x == -1) { return NULL; /* empty tree */ } else { return head; } } keyValuePair* rbtree::returnSubtreeAsList(elementrb *z, keyValuePair *head) { keyValuePair *newnode, *tail; newnode = new keyValuePair; newnode->x = z->key; newnode->y = z->value; head->next = newnode; tail = newnode; if (z->left != leaf) { tail = returnSubtreeAsList(z->left, tail); } if (z->right != leaf) { tail = returnSubtreeAsList(z->right, tail); } return tail; } keyValuePair rbtree::returnMaxKey() { keyValuePair themax; elementrb *current; current = root; // search to bottom-right corner of tree while (current->right != leaf) { current = current->right; } themax.x = current->key; themax.y = current->value; return themax; } keyValuePair rbtree::returnMinKey() { keyValuePair themin; elementrb *current; current = root; // search to bottom-left corner of tree while (current->left != leaf) { current = current->left; } themin.x = current->key; themin.y = current->value; return themin; } // private functions for deleteItem() (although these could easily be // made public, I suppose) elementrb* rbtree::returnMinKey(elementrb *z) { elementrb *current; current = z; // search to bottom-right corner of tree while (current->left != leaf) { current = current->left; } return current; } elementrb* rbtree::returnSuccessor(elementrb *z) { elementrb *current, *w; w = z; // if right-subtree exists, return min of it if (w->right != leaf) { return returnMinKey(w->right); } // else search up in tree current = w->parent; while ((current!=NULL) && (w==current->right)) { w = current; // move up in tree until find a non-right-child current = current->parent; } return current; } int rbtree::returnNodecount() { return support; } // ******** Insert Functions ********************************************* // public insert function void rbtree::insertItem(int newKey, int newValue) { // first we check to see if newKey is already present in the tree; // if so, we do nothing; if not, we must find where to insert the // key elementrb *newNode, *current; // find newKey in tree; return pointer to it O(log k) current = findItem(newKey); if (current == NULL) { newNode = new elementrb; // elementrb for the rbtree newNode->key = newKey; newNode->value = newValue; newNode->color = true; // new nodes are always RED newNode->parent = NULL; // new node initially has no parent newNode->left = leaf; // left leaf newNode->right = leaf; // right leaf support++; // increment node count in rbtree // must now search for where to insert newNode, i.e., find the // correct parent and set the parent and child to point to each // other properly current = root; if (current->key==-1) { // insert as root delete root; // delete old root root = newNode; // set root to newNode leaf->parent = newNode; // set leaf's parent current = leaf; // skip next loop } // search for insertion point while (current != leaf) { // left-or-right? if (newKey < current->key) { // try moving down-left if (current->left != leaf) { current = current->left; } else { // else found new parent newNode->parent = current; // set parent current->left = newNode; // set child current = leaf; // exit search } } else { // try moving down-right if (current->right != leaf) { current = current->right; } else { // else found new parent newNode->parent = current; // set parent current->right = newNode; // set child current = leaf; // exit search } } } // now do the house-keeping necessary to preserve the red-black // properties insertCleanup(newNode); } return; } // private house-keeping function for insertion void rbtree::insertCleanup(elementrb *z) { // fix now if z is root if (z->parent==NULL) { z->color = false; return; } elementrb *temp; // while z is not root and z's parent is RED while (z->parent!=NULL && z->parent->color) { if (z->parent == z->parent->parent->left) { // z's parent is LEFT-CHILD temp = z->parent->parent->right; // grab z's uncle if (temp->color) { z->parent->color = false; // color z's parent BLACK (Case 1) temp->color = false; // color z's uncle BLACK (Case 1) z->parent->parent->color = true; // color z's grandpar. RED (Case 1) z = z->parent->parent; // set z = z's grandparent (Case 1) } else { if (z == z->parent->right) { // z is RIGHT-CHILD z = z->parent; // set z = z's parent (Case 2) rotateLeft(z); // perform left-rotation (Case 2) } z->parent->color = false; // color z's parent BLACK (Case 3) z->parent->parent->color = true; // color z's grandpar. RED (Case 3) rotateRight(z->parent->parent); // perform right-rotation (Case 3) } } else { // z's parent is RIGHT-CHILD temp = z->parent->parent->left; // grab z's uncle if (temp->color) { z->parent->color = false; // color z's parent BLACK (Case 1) temp->color = false; // color z's uncle BLACK (Case 1) z->parent->parent->color = true; // color z's grandpar. RED (Case 1) z = z->parent->parent; // set z = z's grandparent (Case 1) } else { if (z == z->parent->left) { // z is LEFT-CHILD z = z->parent; // set z = z's parent (Case 2) rotateRight(z); // perform right-rotation (Case 2) } z->parent->color = false; // color z's parent BLACK (Case 3) z->parent->parent->color = true; // color z's grandpar. RED (Case 3) rotateLeft(z->parent->parent); // perform left-rotation (Case 3) } } } root->color = false; // color the root BLACK return; } // ******** Delete // ******** Functions ********************************************* void rbtree::replaceItem(int key, int newValue) { elementrb* ptr; ptr = findItem(key); ptr->value = newValue; return; } void rbtree::incrementValue(int key) { elementrb* ptr; ptr = findItem(key); ptr->value = 1+ptr->value; return; } // public delete function void rbtree::deleteItem(int killKey) { elementrb *x, *y, *z; z = findItem(killKey); if (z == NULL) { return; } // item not present; bail out if (support==1) { // attempt to delete the root root->key = -1; // restore root node to default state root->value = -1; root->color = false; root->parent = NULL; root->left = leaf; root->right = leaf; support--; // set support to zero return; // exit - no more work to do } if (z != NULL) { support--; // decrement node count if ((z->left == leaf) || (z->right==leaf)) { y = z; // case of less than two children, // set y to be z } else { y = returnSuccessor(z); // set y to be z's key-successor } if (y->left!=leaf) { x = y->left; // pick y's one child (left-child) } else { x = y->right; // (right-child) } x->parent = y->parent; // make y's child's parent be y's parent if (y->parent==NULL) { root = x; // if y is the root, x is now root } else { if (y == y->parent->left) { // decide y's relationship with y's parent y->parent->left = x; // replace x as y's parent's left child } else { y->parent->right = x; // replace x as y's parent's left child } } if (y!=z) { // insert y into z's spot z->key = y->key; // copy y data into z z->value = y->value; } // do house-keeping to maintain balance if (y->color==false) { deleteCleanup(x); } delete y; y = NULL; } return; } void rbtree::deleteCleanup(elementrb *x) { elementrb *w, *t; // until x is the root, or x is RED while ((x != root) && (x->color==false)) { if (x==x->parent->left) { // branch on x being a LEFT-CHILD w = x->parent->right; // grab x's sibling if (w->color==true) { // if x's sibling is RED w->color = false; // color w BLACK (case 1) x->parent->color = true; // color x's parent RED (case 1) rotateLeft(x->parent); // left rotation on x's parent (case 1) w = x->parent->right; // make w be x's right sibling (case 1) } if ((w->left->color==false) && (w->right->color==false)) { w->color = true; // color w RED (case 2) x = x->parent; // examine x's parent (case 2) } else { if (w->right->color==false) { w->left->color = false; // color w's left child BLACK (case 3) w->color = true; // color w RED (case 3) t = x->parent; // store x's parent (case 3) rotateRight(w); // right rotation on w (case 3) x->parent = t; // restore x's parent (case 3) w = x->parent->right; // make w be x's right sibling (case 3) } w->color = x->parent->color; // w's color := x's parent's (case 4) x->parent->color = false; // color x's parent BLACK (case 4) w->right->color = false; // color w's right child BLACK (case 4) rotateLeft(x->parent); // left rotation on x's parent (case 4) x = root; // finished work. bail out (case 4) } } else { // x is RIGHT-CHILD w = x->parent->left; // grab x's sibling if (w->color==true) { // if x's sibling is RED w->color = false; // color w BLACK (case 1) x->parent->color = true; // color x's parent RED (case 1) rotateRight(x->parent); // right rotation on x's parent (case 1) w = x->parent->left; // make w be x's left sibling (case 1) } if ((w->right->color==false) && (w->left->color==false)) { w->color = true; // color w RED (case 2) x= x->parent; // examine x's parent (case 2) } else { if (w->left->color==false) { w->right->color = false; // color w's right child BLACK (case 3) w->color = true; // color w RED (case 3) t = x->parent; // store x's parent (case 3) rotateLeft(w); // left rotation on w (case 3) x->parent = t; // restore x's parent (case 3) w = x->parent->left; // make w be x's left sibling (case 3) } w->color = x->parent->color; // w's color := x's parent's (case 4) x->parent->color = false; // color x's parent BLACK (case 4) w->left->color = false; // color w's left child BLACK (case 4) rotateRight(x->parent); // right rotation on x's parent (case 4) x = root; // x is now the root (case 4) } } } x->color = false; // color x (the root) BLACK (exit) return; } // ******** Rotation Functions ****************************************** void rbtree::rotateLeft(elementrb *x) { elementrb *y; // do pointer-swapping operations for left-rotation y = x->right; // grab right child x->right = y->left; // make x's RIGHT-CHILD be y's LEFT-CHILD y->left->parent = x; // make x be y's LEFT-CHILD's parent y->parent = x->parent; // make y's new parent be x's old parent if (x->parent==NULL) { root = y; // if x was root, make y root } else { // if x is LEFT-CHILD, make y be x's parent's if (x == x->parent->left) { x->parent->left = y; // left-child } else { x->parent->right = y; // right-child } } y->left = x; // make x be y's LEFT-CHILD x->parent = y; // make y be x's parent return; } void rbtree::rotateRight(elementrb *y) { elementrb *x; // do pointer-swapping operations for right-rotation x = y->left; // grab left child y->left = x->right; // replace left child yith x's right subtree x->right->parent = y; // replace y as x's right subtree's parent x->parent = y->parent; // make x's new parent be y's old parent // if y was root, make x root if (y->parent==NULL) { root = x; } else { // if y is RIGHT-CHILD, make x be y's parent's if (y == y->parent->right) { // right-child y->parent->right = x; } else { // left-child y->parent->left = x; } } x->right = y; // make y be x's RIGHT-CHILD y->parent = x; // make x be y's parent return; } // *********************************************************************** // *** COPYRIGHT NOTICE ************************************************** // dendro.h - hierarchical random graph (hrg) data structure // Copyright (C) 2005-2009 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // *********************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | // http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science // AND Santa Fe Institute // Created : 26 October 2005 - 7 December 2005 // Modified : 23 December 2007 (cleaned up for public consumption) // // *********************************************************************** // // Maximum likelihood dendrogram data structure. This is the heart of // the HRG algorithm: all manipulations are done here and all data is // stored here. The data structure uses the separate graph data // structure to store the basic adjacency information (in a // dangerously mutable way). // // *********************************************************************** // ******** Dendrogram Methods ******************************************* dendro::dendro(): root(0), internal(0), leaf(0), d(0), splithist(0), paths(0), ctree(0), cancestor(0), g(0) { } dendro::~dendro() { list *curr, *prev; if (g) { delete g; g =0; } // O(m) if (internal) { delete [] internal; internal =0; } // O(n) if (leaf) { delete [] leaf; leaf =0; } // O(n) if (d) { delete d; d =0; } // O(n) if (splithist){ delete splithist; splithist=0; } // potentially long if (paths) { for (int i=0; inext; delete prev; prev = 0; } paths[i] = 0; } delete [] paths; } paths=0; if (ctree) { delete [] ctree; ctree = 0; } // O(n) if (cancestor){ delete [] cancestor; cancestor = 0; } // O(n) } // ********************************************************************* void dendro::binarySearchInsert(elementd* x, elementd* y) { if (y->p < x->p) { // go to left subtree if (x->L == NULL) { // check if left subtree is empty x->L = y; // make x left child y->M = x; // make y parent of child return; } else { binarySearchInsert(x->L, y); } } else { // go to right subtree if (x->R == NULL) { // check if right subtree is empty x->R = y; // make x right child y->M = x; // make y parent of child return; } else { binarySearchInsert(x->R, y); } } return; } // ********************************************************************** list* dendro::binarySearchFind(const double v) { list *head = NULL, *tail = NULL, *newlist; elementd *current = root; bool flag_stopSearch = false; while (!flag_stopSearch) { // continue until we're finished newlist = new list; // add this node to the path newlist->x = current->label; if (current == root) { head = newlist; tail = head; } else { tail->next = newlist; tail = newlist; } if (v < current->p) { // now try left subtree if (current->L->type == GRAPH) { flag_stopSearch = true; } else { current = current->L; } } else { // else try right subtree if (current->R->type == GRAPH) { flag_stopSearch = true; } else { current = current->R; } } } return head; } // *********************************************************************** string dendro::buildSplit(elementd* thisNode) { // A "split" is defined as the bipartition of vertices into the sets // of leaves below the internal vertex in the tree (denoted by "C"), // and those above it (denoted as "M"). For simplicity, we represent // this bipartition as a character string of length n, where the ith // character denotes the partition membership (C,M) of the ith leaf // node. bool flag_go = true; const short int k = 1+DENDRO+GRAPH; elementd* curr; split sp; sp.initializeSplit(n); // default split string O(n) curr = thisNode; // - set start node as top this sub-tree curr->type = k+1; // - initialize in-order tree traversal while (flag_go) { // - is it time, and is left child a graph node? if (curr->type == k+1 && curr->L->type == GRAPH) { sp.s[curr->L->index] = 'C'; // - mark this leaf curr->type = k+2; } // - is it time, and is right child a graph node? if (curr->type == k+2 && curr->R->type == GRAPH) { sp.s[curr->R->index] = 'C'; // - mark this leaf curr->type = k+3; } if (curr->type == k+1) { // - go left curr->type = k+2; curr = curr->L; curr->type = k+1; } else if (curr->type == k+2) { // - else go right curr->type = k+3; curr = curr->R; curr->type = k+1; } else { // - else go up a level curr->type = DENDRO; if (curr->index == thisNode->index || curr->M == NULL) { flag_go = false; curr = NULL; } else { curr = curr->M; } } } // any leaf that was not already marked must be in the remainder of // the tree for (int i=0; inumNodes(); // size of graph leaf = new elementd [n]; // allocate memory for G, O(n) internal = new elementd [n-1]; // allocate memory for D, O(n) d = new interns(n-2); // allocate memory for internal // edges of D, O(n) for (int i=0; ilabel = 0; root->index = 0; root->p = RNG_UNIF01(); // insert remaining internal vertices, O(n log n) for (int i=1; i<(n-1); i++) { internal[i].label = i; internal[i].index = i; internal[i].p = RNG_UNIF01(); binarySearchInsert(root, &internal[i]); } // --- Hang leaf nodes off end of dendrogram O(n log n) // To impose this random hierarchical relationship on G, we first // take a random permutation of the leaf vertices and then replace // the NULLs at the bottom of the tree in-order with the leafs. As a // hack to ensure that we can find the leafs later using a binary // search, we assign each of them the p value of their parent, // perturbed slightly so as to preserve the binary search property. block* array; array = new block [n]; for (int i=0; i leaf for each leaf O(n log n) // Using the binary search property, we can find each leaf node in // O(log n) time. The binarySearchFind() function returns the list // of internal node indices that the search crossed, in the order of // root -> ... -> leaf, for use in the subsequent few operations. if (paths != NULL) { list *curr, *prev; for (int i=0; inext; delete prev; prev = NULL; } paths[i] = NULL; } delete [] paths; } paths = NULL; paths = new list* [n]; for (int i=0; igetNeighborList(i); while (curr != NULL) { ancestor = findCommonAncestor(paths, i, curr->x); ancestor->e += 1; curr = curr->next; } } for (int i=0; i<(n-1); i++) { internal[i].e /= 2; } // --- Count n for each internal node O(n log n) // To tabulate the number of leafs in each subtree rooted at an // internal node, we use the path information computed above. for (int i=0; iM; while (ancestor != NULL) { ancestor->n++; ancestor = ancestor->M; } } // --- Label all internal vertices O(n log n) // We want to label each internal vertex with the smallest leaf // index of its children. This will allow us to collapse many // leaf-orderings into a single dendrogram structure that is // independent of child-exhanges (since these have no impact on the // likelihood of the hierarchical structure). To do this, we loop // over the leaf vertices from smallest to largest and walk along // that leaf's path from the root. If we find an unlabeled internal // node, then we mark it with this leaf's index. for (int i=0; ilabel == -1 || ancestor->label > leaf[i].label) { ancestor->label = leaf[i].label; } ancestor = ancestor->M; } } // --- Exchange children to enforce order-property O(n) // We state that the order-property requires that an internal node's // label is the smallest index of its left subtree. The dendrogram // so far doesn't reflect this, so we need to step through each // internal vertex and make that adjustment (swapping nL and nR if // we make a change). elementd *tempe; for (int i=0; i<(n-1); i++) { if (internal[i].L->label > internal[i].label) { tempe = internal[i].L; internal[i].L = internal[i].R; internal[i].R = tempe; } } // --- Tabulate internal dendrogram edges O(n^2) // For the MCMC moves later on, we'll need to be able to choose, // uniformly at random, an internal edge of the dendrogram to // manipulate. There are always n-2 of them, and we can find them // simply by scanning across the internal vertices and observing // which have children that are also internal vertices. Note: very // important that the order property be enforced before this step is // taken; otherwise, the internal edges wont reflect the actual // dendrogram structure. for (int i=0; i<(n-1); i++) { if (internal[i].L->type == DENDRO) { d->addEdge(i, internal[i].L->index, LEFT); } if (internal[i].R->type == DENDRO) { d->addEdge(i, internal[i].R->index, RIGHT); } } // --- Clear memory for paths O(n log n) // Now that we're finished using the paths, we need to deallocate // them manually. list *current, *previous; for (int i=0; inext; delete previous; previous = NULL; } paths[i] = NULL; } delete [] paths; paths = NULL; // --- Compute p_i for each internal node O(n) // Each internal node's p_i = e_i / (nL_i*nR_i), and now that we // have each of those pieces, we may calculate this value for each // internal node. Given these, we can then calculate the // log-likelihood of the entire dendrogram structure \log(L) = // \sum_{i=1}^{n} ( ( e_i \log[p_i] ) + ( (nL_i*nR_i - e_i) // \log[1-p_i] ) ) L = 0.0; double dL; int nL_nR, ei; for (int i=0; i<(n-1); i++) { nL_nR = internal[i].L->n*internal[i].R->n; ei = internal[i].e; internal[i].p = (double)(ei) / (double)(nL_nR); if (ei == 0 || ei == nL_nR) { dL = 0.0; } else { dL = ei * log(internal[i].p) + (nL_nR - ei) * log(1.0-internal[i].p); } internal[i].logL = dL; L += dL; } for (int i=0; i<(n-1); i++) { if (internal[i].label > internal[i].L->label) { tempe = internal[i].L; internal[i].L = internal[i].R; internal[i].R = tempe; } } // Dendrogram is now built return; } // *********************************************************************** void dendro::clearDendrograph() { // Clear out the memory and references used by the dendrograph // structure - this is intended to be called just before an // importDendrogramStructure call so as to avoid memory leaks and // overwriting the references therein. if (g != NULL) { delete g; g = NULL; } // O(m) if (leaf != NULL) { delete [] leaf; leaf = NULL; } // O(n) if (internal != NULL) { delete [] internal; internal = NULL; } // O(n) if (d != NULL) { delete d; d = NULL; } // O(n) root = NULL; return; } // ********************************************************************** int dendro::computeEdgeCount(const int a, const short int atype, const int b, const short int btype) { // This function computes the number of edges that cross between the // subtree internal[a] and the subtree internal[b]. To do this, we // use an array A[1..n] integers which take values -1 if A[i] is in // the subtree defined by internal[a], +1 if A[i] is in the subtree // internal[b], and 0 otherwise. Taking the smaller of the two sets, // we then scan over the edges attached to that set of vertices and // count the number of endpoints we see in the other set. bool flag_go = true; int nA, nB; int count = 0; const short int k = 1+DENDRO+GRAPH; elementd* curr; // First, we push the leaf nodes in the L and R subtrees into // balanced binary tree structures so that we can search them // quickly later on. if (atype == GRAPH) { // default case, subtree A is size 1 // insert single node as member of left subtree subtreeL.insertItem(a,-1); nA = 1; // } else { // explore subtree A, O(|A|) curr = &internal[a]; curr->type = k+1; nA = 0; while (flag_go) { if (curr->index == internal[a].M->index) { internal[a].type = DENDRO; flag_go = false; } else { // - is it time, and is left child a graph node? if (curr->type == k+1 && curr->L->type == GRAPH) { subtreeL.insertItem(curr->L->index, -1); curr->type = k+2; nA++; } // - is it time, and is right child a graph node? if (curr->type == k+2 && curr->R->type == GRAPH) { subtreeL.insertItem(curr->R->index, -1); curr->type = k+3; nA++; } if (curr->type == k+1) { // - go left curr->type = k+2; curr = curr->L; curr->type = k+1; } else if (curr->type == k+2) { // - else go right curr->type = k+3; curr = curr->R; curr->type = k+1; } else { // - else go up a level curr->type = DENDRO; curr = curr->M; if (curr == NULL) { flag_go = false; } } } } } if (btype == GRAPH) { // default case, subtree A is size 1 // insert node as single member of right subtree subtreeR.insertItem(b,1); nB = 1; } else { flag_go = true; // explore subtree B, O(|B|) curr = &internal[b]; curr->type = k+1; nB = 0; while (flag_go) { if (curr->index == internal[b].M->index) { internal[b].type = DENDRO; flag_go = false; } else { // - is it time, and is left child a graph node? if (curr->type == k+1 && curr->L->type == GRAPH) { subtreeR.insertItem(curr->L->index, 1); curr->type = k+2; nB++; } // - is it time, and is right child a graph node? if (curr->type == k+2 && curr->R->type == GRAPH) { subtreeR.insertItem(curr->R->index, 1); curr->type = k+3; nB++; } if (curr->type == k+1) { // - look left curr->type = k+2; curr = curr->L; curr->type = k+1; } else if (curr->type == k+2) { // - look right curr->type = k+3; curr = curr->R; curr->type = k+1; } else { // - else go up a level curr->type = DENDRO; curr = curr->M; if (curr == NULL) { flag_go = false; } } } } } // Now, we take the smaller subtree and ask how many of its // emerging edges have their partner in the other subtree. O(|A| log // |A|) time edge* current; int* treeList; if (nA < nB) { // subtreeL is smaller treeList = subtreeL.returnArrayOfKeys(); for (int i=0; igetNeighborList(treeList[i]); // loop over each of its neighbors v_j while (current != NULL) { // to see if v_j is in A if (subtreeR.findItem(current->x) != NULL) { count++; } current = current->next; } subtreeL.deleteItem(treeList[i]); } delete [] treeList; treeList = subtreeR.returnArrayOfKeys(); for (int i=0; igetNeighborList(treeList[i]); // loop over each of its neighbors v_j while (current != NULL) { // to see if v_j is in B if (subtreeL.findItem(current->x) != NULL) { count++; } current = current->next; } subtreeR.deleteItem(treeList[i]); } delete [] treeList; treeList = subtreeL.returnArrayOfKeys(); for (int i=0; ireturnArrayOfKeys(); tot = splithist->returnTotal(); leng = splithist->returnNodecount(); for (int i=0; ireturnValue(array[i]) / tot) < 0.5) { splithist->deleteItem(array[i]); } } delete [] array; array = NULL; return; } // ********************************************************************** elementd* dendro::findCommonAncestor(list** paths, const int i, const int j) { list* headOne = paths[i]; list* headTwo = paths[j]; elementd* lastStep = NULL; while (headOne->x == headTwo->x) { lastStep = &internal[headOne->x]; headOne = headOne->next; headTwo = headTwo->next; if (headOne == NULL || headTwo == NULL) { break; } } return lastStep; // Returns address of an internal node; do not deallocate } // ********************************************************************** int dendro::getConsensusSize() { string *array; double value, tot; int numSplits, numCons; numSplits = splithist->returnNodecount(); array = splithist->returnArrayOfKeys(); tot = splithist->returnTotal(); numCons = 0; for (int i=0; ireturnValue(array[i]); if (value / tot > 0.5) { numCons++; } } delete [] array; array = NULL; return numCons; } // ********************************************************************** splittree* dendro::getConsensusSplits() { string *array; splittree *consensusTree; double value, tot; consensusTree = new splittree; int numSplits; // We look at all of the splits in our split histogram and add any // one that's in the majority to our consensusTree, which we then // return (note that consensusTree needs to be deallocated by the // user). numSplits = splithist->returnNodecount(); array = splithist->returnArrayOfKeys(); tot = splithist->returnTotal(); for (int i=0; ireturnValue(array[i]); if (value / tot > 0.5) { consensusTree->insertItem(array[i], value / tot); } } delete [] array; array = NULL; return consensusTree; } // *********************************************************************** double dendro::getLikelihood() { return L; } // *********************************************************************** void dendro::getSplitList(splittree* split_tree) { string sp; for (int i=0; i<(n-1); i++) { sp = d->getSplit(i); if (!sp.empty() && sp[1] != '-') { split_tree->insertItem(sp,0.0); } } return; } // *********************************************************************** double dendro::getSplitTotalWeight() { if (splithist) { return splithist->returnTotal(); } else { return 0; } } // *********************************************************************** bool dendro::importDendrogramStructure(const igraph_hrg_t *hrg) { n=igraph_hrg_size(hrg); // allocate memory for G, O(n) leaf = new elementd[n]; // allocate memory for D, O(n) internal = new elementd[n-1]; // allocate memory for internal edges of D, O(n) d = new interns(n-2); // initialize leaf nodes for (int i=0; ilabel=0; for (int i=1; ileft)[i]; int R=VECTOR(hrg->right)[i]; if (L < 0) { internal[i].L = &internal[-L-1]; internal[-L-1].M = &internal[i]; } else { internal[i].L = &leaf[L]; leaf[L].M = &internal[i]; } if (R < 0) { internal[i].R = &internal[-R-1]; internal[-R-1].M = &internal[i]; } else { internal[i].R = &leaf[R]; leaf[R].M = &internal[i]; } internal[i].p = VECTOR(hrg->prob)[i]; internal[i].e = VECTOR(hrg->edges)[i]; internal[i].n = VECTOR(hrg->vertices)[i]; internal[i].index = i; } // --- Label all internal vertices O(n log n) elementd *curr; for (int i=0; ilabel == -1 || curr->label > leaf[i].label) { curr->label = leaf[i].label; } curr = curr -> M; } } // --- Exchange children to enforce order-property O(n) elementd *tempe; for (int i=0; ilabel > internal[i].label) { tempe = internal[i].L; internal[i].L = internal[i].R; internal[i].R = tempe; } } // --- Tabulate internal dendrogram edges O(n) for (int i=0; i<(n-1); i++) { if (internal[i].L->type == DENDRO) { d->addEdge(i, internal[i].L->index, LEFT); } if (internal[i].R->type == DENDRO) { d->addEdge(i, internal[i].R->index, RIGHT); } } // --- Compute p_i for each internal node O(n) // Each internal node's p_i = e_i / (nL_i*nR_i), and now that we // have each of those pieces, we may calculate this value for each // internal node. Given these, we can then calculate the // log-likelihood of the entire dendrogram structure // \log(L) = \sum_{i=1}^{n} ( ( e_i \log[p_i] ) + // ( (nL_i*nR_i - e_i) \log[1-p_i] ) ) L = 0.0; double dL; int nL_nR, ei; for (int i=0; i<(n-1); i++) { nL_nR = internal[i].L->n*internal[i].R->n; ei = internal[i].e; if (ei == 0 || ei == nL_nR) { dL = 0.0; } else { dL = (double)(ei) * log(internal[i].p) + (double)(nL_nR - ei) * log(1.0-internal[i].p); } internal[i].logL = dL; L += dL; } return true; } // *********************************************************************** void dendro::makeRandomGraph() { if (g != NULL) { delete g; } g = NULL; g = new graph(n); list *curr, *prev; if (paths) { for (int i=0; inext; delete prev; prev = NULL; } paths[i] = NULL; } delete [] paths; } // build paths from root O(n d) paths = new list* [n]; for (int i=0; ip) { if (!(g->doesLinkExist(i,j))) { g->addLink(i,j); } if (!(g->doesLinkExist(j,i))) { g->addLink(j,i); } } } } for (int i=0; inext; delete prev; prev = NULL; } paths[i] = NULL; } delete [] paths; // delete paths data structure O(n log n) paths = NULL; return; } // ********************************************************************** bool dendro::monteCarloMove(double& delta, bool& ftaken, const double T) { // A single MC move begins with the selection of a random internal // edge (a,b) of the dendrogram. This also determines the three // subtrees i, j, k that we will rearrange, and we choose uniformly // from among the options. // // If (a,b) is a left-edge, then we have ((i,j),k), and moves // ((i,j),k) -> ((i,k),j) (alpha move) // -> (i,(j,k)) + enforce order-property for (j,k) (beta move) // // If (a,b) is a right-edge, then we have (i,(j,k)), and moves // (i,(j,k)) -> ((i,k),j) (alpha move) // -> ((i,j),k) (beta move) // // For each of these moves, we need to know what the change in // likelihood will be, so that we can determine with what // probability we execute the move. elementd *temp; ipair *tempPair; int x, y, e_x, e_y, n_i, n_j, n_k, n_x, n_y; short int t; double p_x, p_y, L_x, L_y, dLogL; string new_split; // The remainder of the code executes a single MCMC move, where we // sample the dendrograms proportionally to their likelihoods (i.e., // temperature=1, if you're comparing it to the usual MCMC // framework). delta = 0.0; ftaken = false; tempPair = d->getRandomEdge(); // returns address; no need to deallocate x = tempPair->x; // copy contents of referenced random edge y = tempPair->y; // into local variables t = tempPair->t; if (t == LEFT) { if (RNG_UNIF01() < 0.5) { // ## LEFT ALPHA move: ((i,j),k) -> ((i,k),j) // We need to calculate the change in the likelihood (dLogL) // that would result from this move. Most of the information // needed to do this is already available, the exception being // e_ik, the number of edges that span the i and k subtrees. I // use a slow algorithm O(n) to do this, since I don't know of a // better way at this point. (After several attempts to find a // faster method, no luck.) n_i = internal[y].L->n; n_j = internal[y].R->n; n_k = internal[x].R->n; n_y = n_i*n_k; e_y = computeEdgeCount(internal[y].L->index, internal[y].L->type, internal[x].R->index, internal[x].R->type); p_y = (double)(e_y) / (double)(n_y); if (e_y == 0 || e_y == n_y) { L_y = 0.0; } else { L_y = (double)(e_y) * log(p_y) + (double)(n_y - e_y) * log(1.0-p_y); } n_x = (n_i+n_k)*n_j; e_x = internal[x].e + internal[y].e - e_y; // e_yj p_x = (double)(e_x) / (double)(n_x); if (e_x == 0 || e_x == n_x) { L_x = 0.0; } else { L_x = (double)(e_x) * log(p_x) + (double)(n_x - e_x) * log(1.0-p_x); } dLogL = (L_x - internal[x].logL) + (L_y - internal[y].logL); if ((dLogL > 0.0) || (RNG_UNIF01() < exp(T*dLogL))) { // make LEFT ALPHA move ftaken = true; d->swapEdges(x, internal[x].R->index, RIGHT, y, internal[y].R->index, RIGHT); temp = internal[x].R; // - swap j and k internal[x].R = internal[y].R; internal[y].R = temp; internal[x].R->M = &internal[x]; // - adjust parent pointers internal[y].R->M = &internal[y]; internal[y].n = n_i + n_k; // - update n for [y] internal[x].e = e_x; // - update e_i for [x] and [y] internal[y].e = e_y; internal[x].p = p_x; // - update p_i for [x] and [y] internal[y].p = p_y; internal[x].logL = L_x; // - update L_i for [x] and [y] internal[y].logL = L_y; // - order-property maintained L += dLogL; // - update LogL delta = dLogL; } } else { // ## LEFT BETA move: ((i,j),k) -> (i,(j,k)) n_i = internal[y].L->n; n_j = internal[y].R->n; n_k = internal[x].R->n; n_y = n_j*n_k; e_y = computeEdgeCount(internal[y].R->index, internal[y].R->type, internal[x].R->index, internal[x].R->type); p_y = (double)(e_y) / (double)(n_y); if (e_y == 0 || e_y == n_y) { L_y = 0.0; } else { L_y = (double)(e_y) * log(p_y) + (double)(n_y - e_y) * log(1.0-p_y); } n_x = (n_j+n_k)*n_i; e_x = internal[x].e + internal[y].e - e_y; // e_yj p_x = (double)(e_x) / (double)(n_x); if (e_x == 0 || e_x == n_x) { L_x = 0.0; } else { L_x = (double)(e_x) * log(p_x) + (double)(n_x - e_x) * log(1.0-p_x); } dLogL = (L_x - internal[x].logL) + (L_y - internal[y].logL); if ((dLogL > 0.0) || (RNG_UNIF01() < exp(T*dLogL))) { // make LEFT BETA move ftaken = true; d->swapEdges(y, internal[y].L->index, LEFT, y, internal[y].R->index, RIGHT); temp = internal[y].L; // - swap L and R of [y] internal[y].L = internal[y].R; internal[y].R = temp; d->swapEdges(x, internal[x].R->index, RIGHT, y, internal[y].R->index, RIGHT); temp = internal[x].R; // - swap i and k internal[x].R = internal[y].R; internal[y].R = temp; internal[x].R->M = &internal[x]; // - adjust parent pointers internal[y].R->M = &internal[y]; d->swapEdges(x, internal[x].L->index, LEFT, x, internal[x].R->index, RIGHT); temp = internal[x].L; // - swap L and R of [x] internal[x].L = internal[x].R; internal[x].R = temp; internal[y].n = n_j + n_k; // - update n internal[x].e = e_x; // - update e_i internal[y].e = e_y; internal[x].p = p_x; // - update p_i internal[y].p = p_y; internal[x].logL = L_x; // - update logL_i internal[y].logL = L_y; if (internal[y].R->label < internal[y].L->label) { // - enforce order-property if necessary d->swapEdges(y, internal[y].L->index, LEFT, y, internal[y].R->index, RIGHT); temp = internal[y].L; internal[y].L = internal[y].R; internal[y].R = temp; } // internal[y].label = internal[y].L->label; L += dLogL; // - update LogL delta = dLogL; } } } else { // right-edge: t == RIGHT if (RNG_UNIF01() < 0.5) { // alpha move: (i,(j,k)) -> ((i,k),j) n_i = internal[x].L->n; n_j = internal[y].L->n; n_k = internal[y].R->n; n_y = n_i*n_k; e_y = computeEdgeCount(internal[x].L->index, internal[x].L->type, internal[y].R->index, internal[y].R->type); p_y = (double)(e_y) / (double)(n_y); if (e_y == 0 || e_y == n_y) { L_y = 0.0; } else { L_y = (double)(e_y) * log(p_y) + (double)(n_y - e_y) * log(1.0-p_y); } n_x = (n_i+n_k)*n_j; e_x = internal[x].e + internal[y].e - e_y; // e_yj p_x = (double)(e_x) / (double)(n_x); if (e_x == 0 || e_x == n_x) { L_x = 0.0; } else { L_x = (double)(e_x) * log(p_x) + (double)(n_x - e_x) * log(1.0-p_x); } dLogL = (L_x - internal[x].logL) + (L_y - internal[y].logL); if ((dLogL > 0.0) || (RNG_UNIF01() < exp(T*dLogL))) { // make RIGHT ALPHA move ftaken = true; d->swapEdges(x, internal[x].L->index, LEFT, x, internal[x].R->index, RIGHT); temp = internal[x].L; // - swap L and R of [x] internal[x].L = internal[x].R; internal[x].R = temp; d->swapEdges(y, internal[y].L->index, LEFT, x, internal[x].R->index, RIGHT); temp = internal[y].L; // - swap i and j internal[y].L = internal[x].R; internal[x].R = temp; internal[x].R->M = &internal[x]; // - adjust parent pointers internal[y].L->M = &internal[y]; internal[y].n = n_i + n_k; // - update n internal[x].e = e_x; // - update e_i internal[y].e = e_y; internal[x].p = p_x; // - update p_i internal[y].p = p_y; internal[x].logL = L_x; // - update logL_i internal[y].logL = L_y; internal[y].label = internal[x].label; // - update order property L += dLogL; // - update LogL delta = dLogL; } } else { // beta move: (i,(j,k)) -> ((i,j),k) n_i = internal[x].L->n; n_j = internal[y].L->n; n_k = internal[y].R->n; n_y = n_i*n_j; e_y = computeEdgeCount(internal[x].L->index, internal[x].L->type, internal[y].L->index, internal[y].L->type); p_y = (double)(e_y) / (double)(n_y); if (e_y == 0 || e_y == n_y) { L_y = 0.0; } else { L_y = (double)(e_y) * log(p_y) + (double)(n_y - e_y) * log(1.0-p_y); } n_x = (n_i+n_j)*n_k; e_x = internal[x].e + internal[y].e - e_y; // e_yk p_x = (double)(e_x) / (double)(n_x); if (e_x == 0 || e_x == n_x) { L_x = 0.0; } else { L_x = (double)(e_x) * log(p_x) + (double)(n_x - e_x) * log(1.0-p_x); } dLogL = (L_x - internal[x].logL) + (L_y - internal[y].logL); if ((dLogL > 0.0) || (RNG_UNIF01() < exp(T*dLogL))) { // make RIGHT BETA move ftaken = true; d->swapEdges(x, internal[x].L->index, LEFT, x, internal[x].R->index, RIGHT); temp = internal[x].L; // - swap L and R of [x] internal[x].L = internal[x].R; internal[x].R = temp; d->swapEdges(x, internal[x].R->index, RIGHT, y, internal[y].R->index, RIGHT); temp = internal[x].R; // - swap i and k internal[x].R = internal[y].R; internal[y].R = temp; internal[x].R->M = &internal[x]; // - adjust parent pointers internal[y].R->M = &internal[y]; d->swapEdges(y, internal[y].L->index, LEFT, y, internal[y].R->index, RIGHT); temp = internal[y].L; // - swap L and R of [y] internal[y].L = internal[y].R; internal[y].R = temp; internal[y].n = n_i + n_j; // - update n internal[x].e = e_x; // - update e_i internal[y].e = e_y; internal[x].p = p_x; // - update p_i internal[y].p = p_y; internal[x].logL = L_x; // - update logL_i internal[y].logL = L_y; internal[y].label = internal[x].label; // - order-property L += dLogL; // - update LogL delta = dLogL; } } } return true; } // ********************************************************************** void dendro::refreshLikelihood() { // recalculates the log-likelihood of the dendrogram structure L = 0.0; double dL; int nL_nR, ei; for (int i=0; i<(n-1); i++) { nL_nR = internal[i].L->n*internal[i].R->n; ei = internal[i].e; internal[i].p = (double)(ei) / (double)(nL_nR); if (ei == 0 || ei == nL_nR) { dL = 0.0; } else { dL = ei * log(internal[i].p) + (nL_nR - ei) * log(1.0-internal[i].p); } internal[i].logL = dL; L += dL; } return; } // ********************************************************************** void dendro::QsortMain (block* array, int left, int right) { if (right > left) { int pivot = left; int part = QsortPartition(array, left, right, pivot); QsortMain(array, left, part-1); QsortMain(array, part+1, right ); } return; } int dendro::QsortPartition (block* array, int left, int right, int index) { block p_value, temp; p_value.x = array[index].x; p_value.y = array[index].y; // swap(array[p_value], array[right]) temp.x = array[right].x; temp.y = array[right].y; array[right].x = array[index].x; array[right].y = array[index].y; array[index].x = temp.x; array[index].y = temp.y; int stored = left; for (int i=left; inumNodes(); // First, cull the split hist so that only splits with weight >= 0.5 // remain cullSplitHist(); int treesize = splithist->returnNodecount(); // Now, initialize the various arrays we use to keep track of the // internal structure of the consensus tree. ctree = new cnode[treesize]; cancestor = new int[n]; for (int i=0; i=0; i--) { // First, we get a list of all the splits with this exactly i Ms curr = splithist->returnTheseSplits(i); // Now we loop over that list while (curr != NULL) { splithist->deleteItem(curr->x); // add weight to this internal node ctree[ii].weight = curr->y; // examine each letter of this split for (int j=0; jx[j] == 'C') { // - node is child of this internal node if (cancestor[j] == -1) { // - first time this leaf has ever been seen newChild = new child; newChild->type = GRAPH; newChild->index = j; newChild->next = NULL; // - attach child to list if (ctree[ii].lastChild == NULL) { ctree[ii].children = newChild; ctree[ii].lastChild = newChild; ctree[ii].degree = 1; } else { ctree[ii].lastChild->next = newChild; ctree[ii].lastChild = newChild; ctree[ii].degree += 1; } } else { // - this leaf has been seen before // If the parent of the ancestor of this leaf is the // current internal node then this leaf is already a // descendant of this internal node, and we can move on; // otherwise, we need to add that ancestor to this // internal node's child list, and update various // relations if (ctree[cancestor[j]].parent != ii) { ctree[cancestor[j]].parent = ii; newChild = new child; newChild->type = DENDRO; newChild->index = cancestor[j]; newChild->next = NULL; // - attach child to list if (ctree[ii].lastChild == NULL) { ctree[ii].children = newChild; ctree[ii].lastChild = newChild; ctree[ii].degree = 1; } else { ctree[ii].lastChild->next = newChild; ctree[ii].lastChild = newChild; ctree[ii].degree += 1; } } } // note new ancestry for this leaf cancestor[j] = ii; } } // update internal node index ii++; prev = curr; curr = curr->next; delete prev; } } // Return the consensus tree igraph_vector_resize(parents, ii + orig_nodes); if (weights) { igraph_vector_resize(weights, ii); } for (int i=0; itype == GRAPH) { VECTOR(*parents)[sit->index] = orig_nodes + i; } sat=sit; sit=sit->next; delete sat; } if (weights) { VECTOR(*weights)[i] = ctree[i].weight; } ctree[i].children=0; } // Plus the isolate nodes for (int i=0; iindex; int ri=internal[i].R->index; VECTOR(hrg->left )[i] = internal[i].L->type == DENDRO ? -li-1 : li; VECTOR(hrg->right)[i] = internal[i].R->type == DENDRO ? -ri-1 : ri; VECTOR(hrg->prob )[i] = internal[i].p; VECTOR(hrg->edges)[i] = internal[i].e; VECTOR(hrg->vertices)[i] = internal[i].n; } } void dendro::recordGraphStructure(igraph_t *graph) { igraph_vector_t edges; int no_of_nodes=g->numNodes(); int no_of_edges=g->numLinks() / 2; int idx=0; igraph_vector_init(&edges, no_of_edges*2); IGRAPH_FINALLY(igraph_vector_destroy, &edges); for (int i=0; igetNeighborList(i); while (curr) { if (i < curr->x) { VECTOR(edges)[idx++] = i; VECTOR(edges)[idx++] = curr->x; } curr = curr->next; } } igraph_create(graph, &edges, no_of_nodes, /* directed= */ 0); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); } // ********************************************************************** list* dendro::reversePathToRoot(const int leafIndex) { list *head, *subhead, *newlist; head = subhead = newlist = NULL; elementd *current = &leaf[leafIndex]; // continue until we're finished while (current != NULL) { // add this node to the path newlist = new list; newlist->x = current->index; newlist->next = NULL; if (head == NULL) { head = newlist; } else { subhead = head; head = newlist; head->next = subhead; } current = current->M; } return head; } // *********************************************************************** bool dendro::sampleSplitLikelihoods(int &sample_num) { // In order to compute the majority agreement dendrogram at // equilibrium, we need to calculate the leaf partition defined by // each split (internal edge) of the tree. Because splits are only // defined on a Cayley tree, the buildSplit() function returns the // default "--...--" string for the root and the root's left // child. When tabulating the frequency of splits, one of these // needs to be excluded. IGRAPH_UNUSED(sample_num); string* array; int k; double tot; string new_split; // To decompose the tree into its splits, we simply loop over all // the internal nodes and replace the old split for the ith internal // node with its new split. This is a bit time consuming to do // O(n^2), so try not to do this very often. Once the decomposition // is had, we insert them into the split histogram, which tracks the // cumulative weight for each respective split observed. if (splithist == NULL) { splithist = new splittree; } for (int i=0; i<(n-1); i++) { new_split = buildSplit(&internal[i]); d->replaceSplit(i, new_split); if (!new_split.empty() && new_split[1] != '-') { if (!splithist->insertItem(new_split, 1.0)) { return false; } } } splithist->finishedThisRound(); // For large graphs, the split histogram can get extremely large, so // we need to employ some measures to prevent it from swamping the // available memory. When the number of splits exceeds a threshold // (say, a million), we progressively delete splits that have a // weight less than a rising (k*0.001 of the total weight) fraction // of the splits, on the assumption that losing such weight is // unlikely to effect the ultimate split statistics. This deletion // procedure is slow O(m lg m), but should only happen very rarely. int split_max = n*500; int leng; if (splithist->returnNodecount() > split_max) { k=1; while (splithist->returnNodecount() > split_max) { array = splithist->returnArrayOfKeys(); tot = splithist->returnTotal(); leng = splithist->returnNodecount(); for (int i=0; ireturnValue(array[i]) / tot) < k*0.001) { splithist->deleteItem(array[i]); } } delete [] array; array = NULL; k++; } } return true; } void dendro::sampleAdjacencyLikelihoods() { // Here, we sample the probability values associated with every // adjacency in A, weighted by their likelihood. The weighted // histogram is stored in the graph data structure, so we simply // need to add an observation to each node-pair that corresponds to // the associated branch point's probability and the dendrogram's // overall likelihood. double nn; double norm = ((double)(n) * (double)(n)) / 4.0; if (L > 0.0) { L = 0.0; } elementd* ancestor; list *currL, *prevL; if (paths != NULL) { for (int i=0; inext; delete prevL; prevL = NULL; } paths[i] = NULL; } delete [] paths; } paths = NULL; paths = new list* [n]; for (int i=0; iL->n) * (double)(ancestor->R->n)) / norm; // add obs of ->p to (i,j) histogram, and g->addAdjacencyObs(i, j, ancestor->p, nn); // add obs of ->p to (j,i) histogram g->addAdjacencyObs(j, i, ancestor->p, nn); } } // finish-up: upate total weight in histograms g->addAdjacencyEnd(); return; } void dendro::resetDendrograph() { // Reset the dendrograph structure for the next trial if (leaf != NULL) { delete [] leaf; leaf = NULL; } // O(n) if (internal != NULL) { delete [] internal; internal = NULL; } // O(n) if (d != NULL) { delete d; d = NULL; } // O(n) root = NULL; if (paths != NULL) { list *curr, *prev; for (int i=0; inext; delete prev; prev = NULL; } paths[i] = NULL; } delete [] paths; } paths = NULL; L = 1.0; return; } // ********************************************************************** // *** COPYRIGHT NOTICE ************************************************* // graph.h - graph data structure for hierarchical random graphs // Copyright (C) 2005-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // ********************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | // http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science // AND Santa Fe Institute // Created : 8 November 2005 // Modified : 23 December 2007 (cleaned up for public consumption) // // *********************************************************************** // // Graph data structure for hierarchical random graphs. The basic // structure is an adjacency list of edges; however, many additional // pieces of metadata are stored as well. Each node stores its // external name, its degree and (if assigned) its group index. // // *********************************************************************** // ******** Constructor / Destructor ************************************* graph::graph(const int size, bool predict) : predict(predict) { n = size; m = 0; nodes = new vert [n]; nodeLink = new edge* [n]; nodeLinkTail = new edge* [n]; for (int i=0; inext; delete prev; } } delete [] nodeLink; nodeLink = NULL; delete [] nodeLinkTail; nodeLinkTail = NULL; delete [] nodes; nodes = NULL; if (predict) { for (int i=0; i= 0 && i < n && j >= 0 && j < n) { newedge = new edge; newedge->x = j; if (nodeLink[i] == NULL) { // first neighbor nodeLink[i] = newedge; nodeLinkTail[i] = newedge; nodes[i].degree = 1; } else { // subsequent neighbor nodeLinkTail[i]->next = newedge; nodeLinkTail[i] = newedge; nodes[i].degree++; } // increment edge count m++; return true; } else { return false; } } // *********************************************************************** bool graph::addAdjacencyObs(const int i, const int j, const double probability, const double size) { // Adds the observation obs to the histogram of the edge (i,j) // Note: user must manually add observation to edge (j,i) by calling // this function with that argument if (bin_resolution > 0.0 && probability >= 0.0 && probability <= 1.0 && size >= 0.0 && size <= 1.0 && i >= 0 && i < n && j >= 0 && j < n) { int index = (int)(probability/bin_resolution + 0.5); if (index < 0) { index = 0; } else if (index > num_bins) { index = num_bins; } // Add the weight to the proper probability bin if (A[i][j][index] < 0.5) { A[i][j][index] = 1.0; } else { A[i][j][index] += 1.0; } return true; } return false; } // ********************************************************************** void graph::addAdjacencyEnd() { // We need to also keep a running total of how much weight has been added // to the histogram, and the number of observations in the histogram. if (obs_count==0) { total_weight = 1.0; obs_count = 1; } else { total_weight += 1.0; obs_count++; } return; } bool graph::doesLinkExist(const int i, const int j) { // This function determines if the edge (i,j) already exists in the // adjacency list of v_i edge* curr; if (i >= 0 && i < n && j >= 0 && j < n) { curr = nodeLink[i]; while (curr != NULL) { if (curr->x == j) { return true; } curr = curr->next; } } return false; } // ********************************************************************** int graph::getDegree(const int i) { if (i >= 0 && i < n) { return nodes[i].degree; } else { return -1; } } string graph::getName(const int i) { if (i >= 0 && i < n) { return nodes[i].name; } else { return ""; } } // NOTE: Returns address; deallocation of returned object is dangerous edge* graph::getNeighborList(const int i) { if (i >= 0 && i < n) { return nodeLink[i]; } else { return NULL; } } double* graph::getAdjacencyHist(const int i, const int j) { if (i >= 0 && i < n && j >= 0 && j < n) { return A[i][j]; } else { return NULL; } } // ********************************************************************** double graph::getAdjacencyAverage(const int i, const int j) { double average = 0.0; if (i != j) { for (int k=0; k 0.0) { average += (A[i][j][k] / total_weight)*((double)(k)*bin_resolution); } } } return average; } int graph::numLinks() { return m; } int graph::numNodes() { return n; } double graph::getBinResolution() { return bin_resolution; } int graph::getNumBins() { return num_bins; } double graph::getTotalWeight() { return total_weight; } // *********************************************************************** void graph::resetAllAdjacencies() { for (int i=0; i= 0 && i < n && j >= 0 && j < n) { for (int k=0; knext; delete prev; } nodeLink[i] = NULL; nodeLinkTail[i] = NULL; nodes[i].degree = 0; } m = 0; return; } // ********************************************************************** void graph::setAdjacencyHistograms(const int bin_count) { // For all possible adjacencies, setup an edge histograms num_bins = bin_count+1; bin_resolution = 1.0 / (double)(bin_count); for (int i=0; i= 0 && i < n) { nodes[i].name = text; return true; } else { return false; } } // ********************************************************************** interns::interns(const int n) { q = n; count = 0; edgelist = new ipair [q]; splitlist = new string [q+1]; indexLUT = new int* [q+1]; for (int i=0; i<(q+1); i++) { indexLUT[i] = new int [2]; indexLUT[i][0] = indexLUT[i][1] = -1; } } interns::~interns() { delete [] edgelist; delete [] splitlist; for (int i=0; i<(q+1); i++) { delete [] indexLUT[i]; } delete [] indexLUT; } // *********************************************************************** // NOTE: Returns an address to another object -- do not deallocate ipair* interns::getEdge(const int i) { return &edgelist[i]; } // *********************************************************************** // NOTE: Returns an address to another object -- do not deallocate ipair* interns::getRandomEdge() { return &edgelist[(int)(floor((double)(q)*RNG_UNIF01()))]; } // *********************************************************************** string interns::getSplit(const int i) { if (i >= 0 && i <= q) { return splitlist[i]; } else { return ""; } } // ********************************************************************** bool interns::addEdge(const int new_x, const int new_y, const short int new_type) { // This function adds a new edge (i,j,t,sp) to the list of internal // edges. After checking that the inputs fall in the appropriate // range of values, it records the new edgelist index in the // indexLUT and then puts the input values into that edgelist // location. if (count < q && new_x >= 0 && new_x < (q+1) && new_y >= 0 && new_y < (q+2) && (new_type == LEFT || new_type == RIGHT)) { if (new_type == LEFT) { indexLUT[new_x][0] = count; } else { indexLUT[new_x][1] = count; } edgelist[count].x = new_x; edgelist[count].y = new_y; edgelist[count].t = new_type; count++; return true; } else { return false; } } // ********************************************************************** bool interns::replaceSplit(const int i, const string sp) { // When an internal edge is changed, its split must be replaced as // well. This function provides that access; it stores the split // defined by an internal edge (x,y) at the location [y], which // is unique. if (i >= 0 && i <= q) { splitlist[i] = sp; return true; } return false; } // *********************************************************************** bool interns::swapEdges(const int one_x, const int one_y, const short int one_type, const int two_x, const int two_y, const short int two_type) { // The moves on the dendrogram always swap edges, either of which // (or both, or neither) can by internal edges. So, this function // mirrors that operation for the internal edgelist and indexLUT. int index, jndex, temp; bool one_isInternal = false; bool two_isInternal = false; if (one_x >= 0 && one_x < (q+1) && two_x >= 0 && two_x < (q+1) && (two_type == LEFT || two_type == RIGHT) && one_y >= 0 && one_y < (q+2) && two_y >= 0 && two_y < (q+2) && (one_type == LEFT || one_type == RIGHT)) { if (one_type == LEFT) { temp = 0; } else { temp = 1; } if (indexLUT[one_x][temp] > -1) { one_isInternal = true; } if (two_type == LEFT) { temp = 0; } else { temp = 1; } if (indexLUT[two_x][temp] > -1) { two_isInternal = true; } if (one_isInternal && two_isInternal) { if (one_type == LEFT) { index = indexLUT[one_x][0]; } else { index = indexLUT[one_x][1]; } if (two_type == LEFT) { jndex = indexLUT[two_x][0]; } else { jndex = indexLUT[two_x][1]; } temp = edgelist[index].y; edgelist[index].y = edgelist[jndex].y; edgelist[jndex].y = temp; } else if (one_isInternal) { if (one_type == LEFT) { index = indexLUT[one_x][0]; indexLUT[one_x][0] = -1; } else { index = indexLUT[one_x][1]; indexLUT[one_x][1] = -1; } edgelist[index].x = two_x; edgelist[index].t = two_type; if (two_type == LEFT) { indexLUT[two_x][0] = index; } else { indexLUT[two_x][1] = index; } // add new } else if (two_isInternal) { if (two_type == LEFT) { index = indexLUT[two_x][0]; indexLUT[two_x][0] = -1; } else { index = indexLUT[two_x][1]; indexLUT[two_x][1] = -1; } edgelist[index].x = one_x; edgelist[index].t = one_type; if (one_type == LEFT) { indexLUT[one_x][0] = index; } else { indexLUT[one_x][1] = index; } // add new } else { ; } // else neither is internal return true; } else { return false; } } // ******** Red-Black Tree Methods *************************************** splittree::splittree() { root = new elementsp; leaf = new elementsp; leaf->parent = root; root->left = leaf; root->right = leaf; support = 0; total_weight = 0.0; total_count = 0; } splittree::~splittree() { if (root != NULL && (root->left != leaf || root->right != leaf)) { deleteSubTree(root); root = NULL; } support = 0; total_weight = 0.0; total_count = 0; if (root) delete root; delete leaf; root = NULL; leaf = NULL; } void splittree::deleteTree() { if (root != NULL) { deleteSubTree(root); root = NULL; } return; } void splittree::deleteSubTree(elementsp *z) { if (z->left != leaf) { deleteSubTree(z->left); z->left = NULL; } if (z->right != leaf) { deleteSubTree(z->right); z->right = NULL; } delete z; /* No point in setting z to NULL here because z is passed by value */ /* z = NULL; */ return; } // ******** Reset Functions ********************************************* // O(n lg n) void splittree::clearTree() { string *array = returnArrayOfKeys(); for (int i=0; isplit.empty()) { return NULL; } // empty tree; bail out while (current != leaf) { if (searchKey.compare(current->split) < 0) { // left-or-right? // try moving down-left if (current->left != leaf) { current = current->left; } else { // failure; bail out return NULL; } } else { if (searchKey.compare(current->split) > 0) { // left-or-right? if (current->right != leaf) { // try moving down-left current = current->right; } else { // failure; bail out return NULL; } } else { // found (searchKey==current->split) return current; } } } return NULL; } double splittree::returnValue(const string searchKey) { elementsp* test = findItem(searchKey); if (test == NULL) { return 0.0; } else { return test->weight; } } // ******** Return Item Functions *************************************** // public function which returns the tree, via pre-order traversal, as // a linked list string* splittree::returnArrayOfKeys() { string* array; array = new string [support]; bool flag_go = true; int index = 0; elementsp *curr; if (support == 1) { array[0] = root->split; } else if (support == 2) { array[0] = root->split; if (root->left == leaf) { array[1] = root->right->split; } else { array[1] = root->left->split; } } else { for (int i=0; imark = 1; while (flag_go) { // - is it time, and is left child the leaf node? if (curr->mark == 1 && curr->left == leaf) { curr->mark = 2; } // - is it time, and is right child the leaf node? if (curr->mark == 2 && curr->right == leaf) { curr->mark = 3; } if (curr->mark == 1) { // - go left curr->mark = 2; curr = curr->left; curr->mark = 1; } else if (curr->mark == 2) { // - else go right curr->mark = 3; curr = curr->right; curr->mark = 1; } else { // - else go up a level curr->mark = 0; array[index++] = curr->split; curr = curr->parent; if (curr == NULL) { flag_go = false; } } } } return array; } slist* splittree::returnListOfKeys() { keyValuePairSplit *curr, *prev; slist *head = NULL, *tail = NULL, *newlist; curr = returnTreeAsList(); while (curr != NULL) { newlist = new slist; newlist->x = curr->x; if (head == NULL) { head = newlist; tail = head; } else { tail->next = newlist; tail = newlist; } prev = curr; curr = curr->next; delete prev; prev = NULL; } return head; } // pre-order traversal keyValuePairSplit* splittree::returnTreeAsList() { keyValuePairSplit *head, *tail; head = new keyValuePairSplit; head->x = root->split; head->y = root->weight; head->c = root->count; tail = head; if (root->left != leaf) { tail = returnSubtreeAsList(root->left, tail); } if (root->right != leaf) { tail = returnSubtreeAsList(root->right, tail); } if (head->x.empty()) { return NULL; /* empty tree */ } else { return head; } } keyValuePairSplit* splittree::returnSubtreeAsList(elementsp *z, keyValuePairSplit *head) { keyValuePairSplit *newnode, *tail; newnode = new keyValuePairSplit; newnode->x = z->split; newnode->y = z->weight; newnode->c = z->count; head->next = newnode; tail = newnode; if (z->left != leaf) { tail = returnSubtreeAsList(z->left, tail); } if (z->right != leaf) { tail = returnSubtreeAsList(z->right, tail); } return tail; } keyValuePairSplit splittree::returnMaxKey() { keyValuePairSplit themax; elementsp *current; current = root; // search to bottom-right corner of tree while (current->right != leaf) { current = current->right; } themax.x = current->split; themax.y = current->weight; return themax; } keyValuePairSplit splittree::returnMinKey() { keyValuePairSplit themin; elementsp *current; current = root; // search to bottom-left corner of tree while (current->left != leaf) { current = current->left; } themin.x = current->split; themin.y = current->weight; return themin; } // private functions for deleteItem() (although these could easily be // made public, I suppose) elementsp* splittree::returnMinKey(elementsp *z) { elementsp *current; current = z; // search to bottom-right corner of tree while (current->left != leaf) { current = current->left; } // return pointer to the minimum return current; } elementsp* splittree::returnSuccessor(elementsp *z) { elementsp *current, *w; w = z; // if right-subtree exists, return min of it if (w->right != leaf) { return returnMinKey(w->right); } // else search up in tree // move up in tree until find a non-right-child current = w->parent; while ((current!=NULL) && (w==current->right)) { w = current; current = current->parent; } return current; } int splittree::returnNodecount() { return support; } keyValuePairSplit* splittree::returnTheseSplits(const int target) { keyValuePairSplit *head, *curr, *prev, *newhead, *newtail, *newpair; int count, len; head = returnTreeAsList(); prev = newhead = newtail = newpair = NULL; curr = head; while (curr != NULL) { count = 0; len = curr->x.size(); for (int i=0; ix[i] == 'M') { count++; } } if (count == target && curr->x[1] != '*') { newpair = new keyValuePairSplit; newpair->x = curr->x; newpair->y = curr->y; newpair->next = NULL; if (newhead == NULL) { newhead = newpair; newtail = newpair; } else { newtail->next = newpair; newtail = newpair; } } prev = curr; curr = curr->next; delete prev; prev = NULL; } return newhead; } double splittree::returnTotal() { return total_weight; } // ******** Insert Functions ********************************************* void splittree::finishedThisRound() { // We need to also keep a running total of how much weight has been // added to the histogram. if (total_count == 0) { total_weight = 1.0; total_count = 1; } else { total_weight += 1.0; total_count++; } return; } // public insert function bool splittree::insertItem(string newKey, double newValue) { // first we check to see if newKey is already present in the tree; // if so, we do nothing; if not, we must find where to insert the // key elementsp *newNode, *current; // find newKey in tree; return pointer to it O(log k) current = findItem(newKey); if (current != NULL) { current->weight += 1.0; // And finally, we keep track of how many observations went into // the histogram current->count++; return true; } else { newNode = new elementsp; // elementsp for the splittree newNode->split = newKey; // store newKey newNode->weight = newValue; // store newValue newNode->color = true; // new nodes are always RED newNode->parent = NULL; // new node initially has no parent newNode->left = leaf; // left leaf newNode->right = leaf; // right leaf newNode->count = 1; support++; // increment node count in splittree // must now search for where to insert newNode, i.e., find the // correct parent and set the parent and child to point to each // other properly current = root; if (current->split.empty()) { // insert as root delete root; // delete old root root = newNode; // set root to newNode leaf->parent = newNode; // set leaf's parent current = leaf; // skip next loop } // search for insertion point while (current != leaf) { // left-or-right? if (newKey.compare(current->split) < 0) { // try moving down-left if (current->left != leaf) { current = current->left; } else { // else found new parent newNode->parent = current; // set parent current->left = newNode; // set child current = leaf; // exit search } } else { // if (current->right != leaf) { // try moving down-right current = current->right; } else { // else found new parent newNode->parent = current; // set parent current->right = newNode; // set child current = leaf; // exit search } } } // now do the house-keeping necessary to preserve the red-black // properties insertCleanup(newNode); } return true; } // private house-keeping function for insertion void splittree::insertCleanup(elementsp *z) { // fix now if z is root if (z->parent==NULL) { z->color = false; return; } elementsp *temp; // while z is not root and z's parent is RED while (z->parent!=NULL && z->parent->color) { if (z->parent == z->parent->parent->left) { // z's parent is LEFT-CHILD temp = z->parent->parent->right; // grab z's uncle if (temp->color) { z->parent->color = false; // color z's parent BLACK (Case 1) temp->color = false; // color z's uncle BLACK (Case 1) z->parent->parent->color = true; // color z's grandpa RED (Case 1) z = z->parent->parent; // set z = z's grandpa (Case 1) } else { if (z == z->parent->right) { // z is RIGHT-CHILD z = z->parent; // set z = z's parent (Case 2) rotateLeft(z); // perform left-rotation (Case 2) } z->parent->color = false; // color z's parent BLACK (Case 3) z->parent->parent->color = true; // color z's grandpa RED (Case 3) rotateRight(z->parent->parent); // perform right-rotation (Case 3) } } else { // z's parent is RIGHT-CHILD temp = z->parent->parent->left; // grab z's uncle if (temp->color) { z->parent->color = false; // color z's parent BLACK (Case 1) temp->color = false; // color z's uncle BLACK (Case 1) z->parent->parent->color = true; // color z's grandpa RED (Case 1) z = z->parent->parent; // set z = z's grandpa (Case 1) } else { if (z == z->parent->left) { // z is LEFT-CHILD z = z->parent; // set z = z's parent (Case 2) rotateRight(z); // perform right-rotation (Case 2) } z->parent->color = false; // color z's parent BLACK (Case 3) z->parent->parent->color = true; // color z's grandpa RED (Case 3) rotateLeft(z->parent->parent); // perform left-rotation (Case 3) } } } root->color = false; // color the root BLACK return; } // ******** Delete Functions ******************************************** // public delete function void splittree::deleteItem(string killKey) { elementsp *x, *y, *z; z = findItem(killKey); if (z == NULL) { return; } // item not present; bail out if (support==1) { // -- attempt to delete the root root->split = ""; // restore root node to default state root->weight = 0.0; // root->color = false; // root->parent = NULL; // root->left = leaf; // root->right = leaf; // support--; // set support to zero total_weight = 0.0; // set total weight to zero total_count--; // return; // exit - no more work to do } if (z != NULL) { support--; // decrement node count if ((z->left == leaf) || (z->right==leaf)) { // case of less than two children y = z; // set y to be z } else { y = returnSuccessor(z); // set y to be z's key-successor } if (y->left!=leaf) { x = y->left; // pick y's one child (left-child) } else { x = y->right; // (right-child) } x->parent = y->parent; // make y's child's parent be y's parent if (y->parent==NULL) { root = x; // if y is the root, x is now root } else { if (y == y->parent->left) {// decide y's relationship with y's parent y->parent->left = x; // replace x as y's parent's left child } else { y->parent->right = x; } // replace x as y's parent's left child } if (y!=z) { // insert y into z's spot z->split = y->split; // copy y data into z z->weight = y->weight; // z->count = y->count; // } // // do house-keeping to maintain balance if (y->color==false) { deleteCleanup(x); } delete y; // deallocate y y = NULL; // point y to NULL for safety } // return; } void splittree::deleteCleanup(elementsp *x) { elementsp *w, *t; // until x is the root, or x is RED while ((x != root) && (x->color==false)) { if (x==x->parent->left) { // branch on x being a LEFT-CHILD w = x->parent->right; // grab x's sibling if (w->color==true) { // if x's sibling is RED w->color = false; // color w BLACK (case 1) x->parent->color = true; // color x's parent RED (case 1) rotateLeft(x->parent); // left rotation on x's parent (case 1) w = x->parent->right; // make w be x's right sibling (case 1) } if ((w->left->color==false) && (w->right->color==false)) { w->color = true; // color w RED (case 2) x = x->parent; // examine x's parent (case 2) } else { // if (w->right->color==false) { w->left->color = false; // color w's left child BLACK (case 3) w->color = true; // color w RED (case 3) t = x->parent; // store x's parent rotateRight(w); // right rotation on w (case 3) x->parent = t; // restore x's parent w = x->parent->right; // make w be x's right sibling (case 3) } // w->color = x->parent->color; // w's color := x's parent's (case 4) x->parent->color = false; // color x's parent BLACK (case 4) w->right->color = false; // color w's right child BLACK (case 4) rotateLeft(x->parent); // left rotation on x's parent (case 4) x = root; // finished work. bail out (case 4) } // } else { // x is RIGHT-CHILD w = x->parent->left; // grab x's sibling if (w->color==true) { // if x's sibling is RED w->color = false; // color w BLACK (case 1) x->parent->color = true; // color x's parent RED (case 1) rotateRight(x->parent); // right rotation on x's parent (case 1) w = x->parent->left; // make w be x's left sibling (case 1) } if ((w->right->color==false) && (w->left->color==false)) { w->color = true; // color w RED (case 2) x= x->parent; // examine x's parent (case 2) } else { // if (w->left->color==false) { // w->right->color = false; // color w's right child BLACK (case 3) w->color = true; // color w RED (case 3) t = x->parent; // store x's parent rotateLeft(w); // left rotation on w (case 3) x->parent = t; // restore x's parent w = x->parent->left; // make w be x's left sibling (case 3) } // w->color = x->parent->color; // w's color := x's parent's (case 4) x->parent->color = false; // color x's parent BLACK (case 4) w->left->color = false; // color w's left child BLACK (case 4) rotateRight(x->parent); // right rotation on x's parent (case 4) x = root; // x is now the root (case 4) } } } x->color = false; // color x (the root) BLACK (exit) return; } // ******** Rotation Functions ******************************************* void splittree::rotateLeft(elementsp *x) { elementsp *y; // do pointer-swapping operations for left-rotation y = x->right; // grab right child x->right = y->left; // make x's RIGHT-CHILD be y's LEFT-CHILD y->left->parent = x; // make x be y's LEFT-CHILD's parent y->parent = x->parent; // make y's new parent be x's old parent if (x->parent==NULL) { root = y; // if x was root, make y root } else { // if (x == x->parent->left) { // if x is LEFT-CHILD, make y be x's parent's x->parent->left = y; // left-child } else { x->parent->right = y; // right-child } } y->left = x; // make x be y's LEFT-CHILD x->parent = y; // make y be x's parent return; } void splittree::rotateRight(elementsp *y) { elementsp *x; // do pointer-swapping operations for right-rotation x = y->left; // grab left child y->left = x->right; // replace left child yith x's right subtree x->right->parent = y; // replace y as x's right subtree's parent x->parent = y->parent; // make x's new parent be y's old parent if (y->parent==NULL) { root = x; // if y was root, make x root } else { if (y == y->parent->right) { // if y is R-CHILD, make x be y's parent's y->parent->right = x; // right-child } else { y->parent->left = x; // left-child } } x->right = y; // make y be x's RIGHT-CHILD y->parent = x; // make x be y's parent return; } // *********************************************************************** // *** COPYRIGHT NOTICE ************************************************** // graph_simp.h - graph data structure // Copyright (C) 2006-2008 Aaron Clauset // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.gnu.org/licenses/gpl.txt for more details. // // *********************************************************************** // Author : Aaron Clauset ( aaronc@santafe.edu | // http://www.santafe.edu/~aaronc/ ) // Collaborators: Cristopher Moore and Mark E.J. Newman // Project : Hierarchical Random Graphs // Location : University of New Mexico, Dept. of Computer Science // AND Santa Fe Institute // Created : 21 June 2006 // Modified : 23 December 2007 (cleaned up for public consumption) // // ************************************************************************ // ******** Constructor / Destructor ************************************* simpleGraph::simpleGraph(const int size): n(size), m(0), num_groups(0) { nodes = new simpleVert [n]; nodeLink = new simpleEdge* [n]; nodeLinkTail = new simpleEdge* [n]; A = new double* [n]; for (int i=0; inext; delete prev; } } curr = NULL; prev = NULL; if (E != NULL) { delete [] E; E = NULL; } delete [] A; A = NULL; delete [] nodeLink; nodeLink = NULL; delete [] nodeLinkTail; nodeLinkTail = NULL; delete [] nodes; nodes = NULL; } // *********************************************************************** bool simpleGraph::addGroup(const int i, const int group_index) { if (i >= 0 && i < n) { nodes[i].group_true = group_index; return true; } else { return false; } } // *********************************************************************** bool simpleGraph::addLink(const int i, const int j) { // Adds the directed edge (i,j) to the adjacency list for v_i simpleEdge* newedge; if (i >= 0 && i < n && j >= 0 && j < n) { A[i][j] = 1.0; newedge = new simpleEdge; newedge->x = j; if (nodeLink[i] == NULL) { // first neighbor nodeLink[i] = newedge; nodeLinkTail[i] = newedge; nodes[i].degree = 1; } else { // subsequent neighbor nodeLinkTail[i]->next = newedge; nodeLinkTail[i] = newedge; nodes[i].degree++; } m++; // increment edge count newedge = NULL; return true; } else { return false; } } // *********************************************************************** bool simpleGraph::doesLinkExist(const int i, const int j) { // This function determines if the edge (i,j) already exists in the // adjacency list of v_i if (i >= 0 && i < n && j >= 0 && j < n) { if (A[i][j] > 0.1) { return true; } else { return false; } } else { return false; } return false; } // ********************************************************************** double simpleGraph::getAdjacency(const int i, const int j) { if (i >= 0 && i < n && j >= 0 && j < n) { return A[i][j]; } else { return -1.0; } } int simpleGraph::getDegree(const int i) { if (i >= 0 && i < n) { return nodes[i].degree; } else { return -1; } } int simpleGraph::getGroupLabel(const int i) { if (i >= 0 && i < n) { return nodes[i].group_true; } else { return -1; } } string simpleGraph::getName(const int i) { if (i >= 0 && i < n) { return nodes[i].name; } else { return ""; } } // NOTE: The following three functions return addresses; deallocation // of returned object is dangerous simpleEdge* simpleGraph::getNeighborList(const int i) { if (i >= 0 && i < n) { return nodeLink[i]; } else { return NULL; } } // END-NOTE // ********************************************************************* int simpleGraph::getNumGroups() { return num_groups; } int simpleGraph::getNumLinks() { return m; } int simpleGraph::getNumNodes() { return n; } simpleVert* simpleGraph::getNode(const int i) { if (i >= 0 && i= 0 && i < n) { nodes[i].name = text; return true; } else { return false; } } // ********************************************************************** void simpleGraph::QsortMain (block* array, int left, int right) { if (right > left) { int pivot = left; int part = QsortPartition(array, left, right, pivot); QsortMain(array, left, part-1); QsortMain(array, part+1, right ); } return; } int simpleGraph::QsortPartition (block* array, int left, int right, int index) { block p_value, temp; p_value.x = array[index].x; p_value.y = array[index].y; // swap(array[p_value], array[right]) temp.x = array[right].x; temp.y = array[right].y; array[right].x = array[index].x; array[right].y = array[index].y; array[index].x = temp.x; array[index].y = temp.y; int stored = left; for (int i=left; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The contents of this file was originally taken from the LAD homepage: http://liris.cnrs.fr/csolnon/LAD.html and then modified to fit better into igraph. Unfortunately LAD seems to have no version numbers. The files were apparently last changed on the 29th of June, 2010. The original copyright message follows here. The CeCILL-B V1 license is GPL compatible, because instead of V1, one can freely choose to use V2, and V2 is explicitly GPL compatible. */ /* This software has been written by Christine Solnon. It is distributed under the CeCILL-B FREE SOFTWARE LICENSE see http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html for more details */ /* Several modifications had to be made to the original LAD implementation to make it compile with non-C99-compliant compilers such as MSVC. In particular, I had to remove all the variable-sized arrays. -- Tamas Nepusz, 11 July 2013 */ #include #include #include #include #include #include #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_vector.h" #include "igraph_vector_ptr.h" #include "igraph_memory.h" #include "igraph_matrix.h" #include "igraph_interrupt_internal.h" /* define boolean type as char */ #define true 1 #define false 0 #define bool char /* helper to allocate an array of given size and free it using IGRAPH_FINALLY * when needed */ #define ALLOC_ARRAY(VAR, SIZE, TYPE) { \ VAR = igraph_Calloc(SIZE, TYPE); \ if (VAR == 0) { \ IGRAPH_ERROR("cannot allocate '" #VAR "' array in LAD isomorphism search", IGRAPH_ENOMEM); \ } \ IGRAPH_FINALLY(igraph_free, VAR); \ } /* helper to allocate an array of given size and store its address in a * pointer array */ #define ALLOC_ARRAY_IN_HISTORY(VAR, SIZE, TYPE, HISTORY) { \ VAR = igraph_Calloc(SIZE, TYPE); \ if (VAR == 0) { \ IGRAPH_ERROR("cannot allocate '" #VAR "' array in LAD isomorphism search", IGRAPH_ENOMEM); \ } \ IGRAPH_FINALLY(igraph_free, VAR); \ IGRAPH_CHECK(igraph_vector_ptr_push_back(HISTORY, VAR)); \ IGRAPH_FINALLY_CLEAN(1); \ } /* ---------------------------------------------------------*/ /* Coming from graph.c */ /* ---------------------------------------------------------*/ typedef struct{ long int nbVertices; /* Number of vertices */ igraph_vector_t nbSucc; igraph_adjlist_t succ; igraph_matrix_char_t isEdge; } Tgraph; int igraph_i_lad_createGraph(const igraph_t *igraph, Tgraph* graph) { long int i, j, n; long int no_of_nodes=igraph_vcount(igraph); igraph_vector_int_t *neis; IGRAPH_VECTOR_INIT_FINALLY(&graph->nbSucc, no_of_nodes); IGRAPH_CHECK(igraph_degree(igraph, &graph->nbSucc, igraph_vss_all(), IGRAPH_OUT, IGRAPH_LOOPS)); graph->nbVertices = no_of_nodes; IGRAPH_CHECK(igraph_adjlist_init(igraph, &graph->succ, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &graph->succ); IGRAPH_CHECK(igraph_matrix_char_init(&graph->isEdge, no_of_nodes, no_of_nodes)); IGRAPH_FINALLY(igraph_matrix_char_destroy, &graph->isEdge); for (i=0; isucc, i); n=igraph_vector_int_size(neis); for (j=0; jisEdge, i, v)) { IGRAPH_ERROR("LAD functions only work on simple graphs, " "simplify your graph", IGRAPH_EINVAL); } MATRIX(graph->isEdge, i, v) = 1; } } return 0; } /* ---------------------------------------------------------*/ /* Coming from domains.c */ /* ---------------------------------------------------------*/ typedef struct{ igraph_vector_int_t nbVal; /* nbVal[u] = number of values in D[u] */ igraph_vector_int_t firstVal; /* firstVal[u] = pos in val of the first value of D[u] */ igraph_vector_int_t val; /* val[firstVal[u]..firstVal[u]+nbVal[u]-1] = values of D[u] */ igraph_matrix_int_t posInVal; /* If v in D[u] then firstVal[u] <= posInVal[u][v] < firstVal[u]+nbVal[u] and val[posInVal[u][v]] = v otherwise posInVal[u][v] >= firstVal[u]+nbVal[u] */ int valSize; /* size of val */ igraph_matrix_int_t firstMatch; /* firstMatch[u][v] = pos in match of the first vertex of the covering matching of G_(u, v) */ igraph_vector_int_t matching; /* matching[firstMatch[u][v]..firstMatch[u][v]+nbSucc[u]-1] = covering matching of G_(u, v) */ int nextOutToFilter; /* position in toFilter of the next pattern node whose domain should be filtered (-1 if no domain to filter) */ int lastInToFilter; /* position in toFilter of the last pattern node whose domain should be filtered */ igraph_vector_int_t toFilter; /* contain all pattern nodes whose domain should be filtered */ igraph_vector_char_t markedToFilter; /* markedToFilter[u]=true if u is in toFilter; false otherwise */ igraph_vector_int_t globalMatchingP; /* globalMatchingP[u] = node of Gt matched to u in globalAllDiff(Np) */ igraph_vector_int_t globalMatchingT; /* globalMatchingT[v] = node of Gp matched to v in globalAllDiff(Np) or -1 if v is not matched */ } Tdomain; bool igraph_i_lad_toFilterEmpty(Tdomain* D) { /* return true if there is no more nodes in toFilter */ return (D->nextOutToFilter < 0); } void igraph_i_lad_resetToFilter(Tdomain *D) { /* empty to filter and unmark the vertices that are marked to be filtered */ igraph_vector_char_null(&D->markedToFilter); D->nextOutToFilter = -1; } int igraph_i_lad_nextToFilter(Tdomain* D, int size) { /* precondition: emptyToFilter = false remove a node from toFilter (FIFO) unmark this node and return it */ int u = VECTOR(D->toFilter)[D->nextOutToFilter]; VECTOR(D->markedToFilter)[u] = false; if (D->nextOutToFilter == D->lastInToFilter) { /* u was the last node in tofilter */ D->nextOutToFilter = -1; } else if (D->nextOutToFilter == size-1) { D->nextOutToFilter = 0; } else { D->nextOutToFilter++; } return u; } void igraph_i_lad_addToFilter(int u, Tdomain* D, int size) { /* if u is not marked, then add it to toFilter and mark it */ if (VECTOR(D->markedToFilter)[u]) { return; } VECTOR(D->markedToFilter)[u] = true; if (D->nextOutToFilter < 0) { D->lastInToFilter = 0; D->nextOutToFilter = 0; } else if (D->lastInToFilter == size-1) { D->lastInToFilter = 0; } else { D->lastInToFilter++; } VECTOR(D->toFilter)[D->lastInToFilter] = u; } bool igraph_i_lad_isInD(int u, int v, Tdomain* D) { /* returns true if v belongs to D(u); false otherwise */ return (MATRIX(D->posInVal, u, v) < VECTOR(D->firstVal)[u] + VECTOR(D->nbVal)[u]); } int igraph_i_lad_augmentingPath(int u, Tdomain* D, int nbV, bool* result) { /* return true if there exists an augmenting path starting from u and ending on a free vertex v in the bipartite directed graph G=(U, V, E) such that U=pattern nodes, V=target nodes, and E={(u, v), v in D(u)} U {(v, u), D->globalMatchingP[u]=v} update D-globalMatchingP and D->globalMatchingT consequently */ int *fifo, *pred; bool *marked; int nextIn = 0; int nextOut = 0; int i, v, v2, u2, j; /* Allocate memory */ ALLOC_ARRAY(fifo, nbV, int); ALLOC_ARRAY(pred, nbV, int); ALLOC_ARRAY(marked, nbV, bool); for (i=0; i < VECTOR(D->nbVal)[u]; i++) { v = VECTOR(D->val)[ VECTOR(D->firstVal)[u]+i ]; /* v in D(u) */ if (VECTOR(D->globalMatchingT)[v] < 0) { /* v is free => augmenting path found */ VECTOR(D->globalMatchingP)[u]=v; VECTOR(D->globalMatchingT)[v]=u; *result = true; goto cleanup; } /* v is not free => add it to fifo */ pred[v] = u; fifo[nextIn++] = v; marked[v] = true; } while (nextOut < nextIn) { u2 = VECTOR(D->globalMatchingT)[fifo[nextOut++]]; for (i=0; i < VECTOR(D->nbVal)[u2]; i++) { v = VECTOR(D->val)[ VECTOR(D->firstVal)[u2]+i ]; /* v in D(u2) */ if (VECTOR(D->globalMatchingT)[v] < 0) { /* v is free => augmenting path found */ j=0; while (u2 != u) { /* update global matching wrt path */ if (j>100) { IGRAPH_ERROR("LAD failed", IGRAPH_EINTERNAL); } j++; v2 = VECTOR(D->globalMatchingP)[u2]; VECTOR(D->globalMatchingP)[u2]=v; VECTOR(D->globalMatchingT)[v]=u2; v = v2; u2 = pred[v]; } VECTOR(D->globalMatchingP)[u]=v; VECTOR(D->globalMatchingT)[v]=u; *result = true; goto cleanup; } if (!marked[v]) { /* v is not free and not marked => add it to fifo */ pred[v] = u2; fifo[nextIn++] = v; marked[v] = true; } } } cleanup: igraph_free(fifo); igraph_free(pred); igraph_free(marked); IGRAPH_FINALLY_CLEAN(3); return 0; } int igraph_i_lad_removeAllValuesButOne(int u, int v, Tdomain* D, Tgraph* Gp, Tgraph* Gt, bool* result) { /* remove all values but v from D(u) and add all successors of u in toFilter return false if an inconsistency is detected wrt to global all diff */ int j, oldPos, newPos; igraph_vector_int_t *uneis=igraph_adjlist_get(&Gp->succ, u); int n=(int) igraph_vector_int_size(uneis); /* add all successors of u in toFilter */ for (j=0; jnbVertices)); } /* remove all values but v from D[u] */ oldPos = MATRIX(D->posInVal, u, v); newPos = VECTOR(D->firstVal)[u]; VECTOR(D->val)[oldPos] = VECTOR(D->val)[newPos]; VECTOR(D->val)[newPos] = v; MATRIX(D->posInVal, u, VECTOR(D->val)[newPos]) = newPos; MATRIX(D->posInVal, u, VECTOR(D->val)[oldPos]) = oldPos; VECTOR(D->nbVal)[u] = 1; /* update global matchings that support the global all different constraint */ if (VECTOR(D->globalMatchingP)[u] != v) { VECTOR(D->globalMatchingT)[ VECTOR(D->globalMatchingP)[u] ]=-1; VECTOR(D->globalMatchingP)[u] = -1; IGRAPH_CHECK(igraph_i_lad_augmentingPath(u, D, (int) (Gt->nbVertices), result)); } else { *result = true; } return 0; } int igraph_i_lad_removeValue(int u, int v, Tdomain* D, Tgraph* Gp, Tgraph* Gt, bool* result) { /* remove v from D(u) and add all successors of u in toFilter return false if an inconsistency is detected wrt global all diff */ int j; igraph_vector_int_t *uneis=igraph_adjlist_get(&Gp->succ, u); int n=(int) igraph_vector_int_size(uneis); int oldPos, newPos; /* add all successors of u in toFilter */ for (j=0; jnbVertices)); } /* remove v from D[u] */ oldPos = MATRIX(D->posInVal, u, v); VECTOR(D->nbVal)[u]--; newPos = VECTOR(D->firstVal)[u] + VECTOR(D->nbVal)[u]; VECTOR(D->val)[oldPos] = VECTOR(D->val)[newPos]; VECTOR(D->val)[newPos] = v; MATRIX(D->posInVal, u, VECTOR(D->val)[oldPos]) = oldPos; MATRIX(D->posInVal, u, VECTOR(D->val)[newPos]) = newPos; /* update global matchings that support the global all different constraint */ if (VECTOR(D->globalMatchingP)[u] == v) { VECTOR(D->globalMatchingP)[u] = -1; VECTOR(D->globalMatchingT)[v] = -1; IGRAPH_CHECK(igraph_i_lad_augmentingPath(u, D, (int) (Gt->nbVertices), result)); } else { *result = true; } return 0; } int igraph_i_lad_matchVertices(int nb, igraph_vector_int_t* toBeMatched, bool induced, Tdomain* D, Tgraph* Gp, Tgraph* Gt, int *invalid) { /* for each u in toBeMatched[0..nb-1], match u to D->val[D->firstVal[u] and filter domains of other non matched vertices wrt FC(Edges) and FC(diff) (this is not mandatory, as LAD is stronger than FC(Edges) and GAC(allDiff) is stronger than FC(diff), but this speeds up the solution process). return false if an inconsistency is detected by FC(Edges) or FC(diff); true otherwise; */ int j, u, v, u2, oldNbVal; igraph_vector_int_t *vneis; bool result = false; while (nb>0) { u = VECTOR(*toBeMatched)[--nb]; v = VECTOR(D->val)[ VECTOR(D->firstVal)[u] ]; vneis = igraph_adjlist_get(&Gt->succ, v); /* match u to v */ for (u2=0; u2nbVertices; u2++) { result = 0; if (u != u2) { oldNbVal = VECTOR(D->nbVal)[u2]; if (igraph_i_lad_isInD(u2, v, D)) { IGRAPH_CHECK(igraph_i_lad_removeValue(u2, v, D, Gp, Gt, &result)); if (!result) { *invalid = 1 ; return 0; } } if (MATRIX(Gp->isEdge, u, u2)) { /* remove from D[u2] vertices which are not adjacent to v */ j = VECTOR(D->firstVal)[u2]; while (j < VECTOR(D->firstVal)[u2] + VECTOR(D->nbVal)[u2]) { if (MATRIX(Gt->isEdge, v, VECTOR(D->val)[j])) { j++; } else { IGRAPH_CHECK(igraph_i_lad_removeValue(u2, VECTOR(D->val)[j], D, Gp, Gt, &result)); if (!result) { *invalid = 1; return 0; } } } } else if (induced) { /* (u, u2) is not an edge => remove neighbors of v from D[u2] */ if (VECTOR(D->nbVal)[u2] < VECTOR(Gt->nbSucc)[v]) { j = VECTOR(D->firstVal)[u2]; while (j < VECTOR(D->firstVal)[u2] + VECTOR(D->nbVal)[u2]) { if (!MATRIX(Gt->isEdge, v, VECTOR(D->val)[j])) { j++; } else { IGRAPH_CHECK(igraph_i_lad_removeValue(u2, VECTOR(D->val)[j], D, Gp, Gt, &result)); if (!result) { *invalid = 1; return 0; } } } } else { for (j=0; jnbSucc)[v]; j++) { if (igraph_i_lad_isInD(u2, (int) VECTOR(*vneis)[j], D)) { IGRAPH_CHECK(igraph_i_lad_removeValue(u2, (int) VECTOR(*vneis)[j], D, Gp, Gt, &result)); if (!result) { *invalid = 1; return 0; } } } } } if (VECTOR(D->nbVal)[u2] == 0) { *invalid = 1; /* D[u2] is empty */ return 0; } if ((VECTOR(D->nbVal)[u2] == 1) && (oldNbVal > 1)) { VECTOR(*toBeMatched)[nb++]=u2; } } } } *invalid = 0; return 0; } bool igraph_i_lad_matchVertex(int u, bool induced, Tdomain* D, Tgraph* Gp, Tgraph *Gt) { int invalid; /* match u to D->val[D->firstVal[u]] and filter domains of other non matched vertices wrt FC(Edges) and FC(diff) (this is not mandatory, as LAD is stronger than FC(Edges) and GAC(allDiff) is stronger than FC(diff), but this speeds up the solution process). return false if an inconsistency is detected by FC(Edges) or FC(diff); true otherwise; */ igraph_vector_int_t toBeMatched; igraph_vector_int_init(&toBeMatched, Gp->nbVertices); IGRAPH_FINALLY(igraph_vector_int_destroy, &toBeMatched); VECTOR(toBeMatched)[0]=u; igraph_i_lad_matchVertices(1, &toBeMatched, induced, D, Gp, Gt, &invalid); igraph_vector_int_destroy(&toBeMatched); IGRAPH_FINALLY_CLEAN(1); return invalid ? false : true; } int igraph_i_lad_qcompare (void const *a, void const *b) { /* function used by the qsort function */ int pa = *((int*)a) - *((int*)b); return pa; } bool igraph_i_lad_compare(int size_mu, int* mu, int size_mv, int* mv) { /* return true if for every element u of mu there exists a different element v of mv such that u <= v; return false otherwise */ int i, j; qsort(mu, (size_t) size_mu, sizeof(int), igraph_i_lad_qcompare); qsort(mv, (size_t) size_mv, sizeof(int), igraph_i_lad_qcompare); i = size_mv-1; for (j=size_mu-1; j>=0; j--) { if (mu[j]>mv[i]) { return false; } i--; } return true; } int igraph_i_lad_initDomains(bool initialDomains, igraph_vector_ptr_t *domains, Tdomain* D, Tgraph* Gp, Tgraph* Gt, int *empty) { /* for every pattern node u, initialize D(u) with every vertex v such that for every neighbor u' of u there exists a different neighbor v' of v such that degree(u) <= degree(v) if initialDomains, then filter initial domains wrt compatibilities given in file return false if a domain is empty and true otherwise */ int *val; bool *dom; int *mu, *mv; int matchingSize, u, v, i, j; igraph_vector_t *vec; igraph_vector_t *Gp_uneis; igraph_vector_t *Gt_vneis; val = igraph_Calloc(Gp->nbVertices*Gt->nbVertices, int); if (val == 0) { IGRAPH_ERROR("cannot allocated 'val' array in igraph_i_lad_initDomains", IGRAPH_ENOMEM); } dom = igraph_Calloc(Gt->nbVertices, bool); if (dom == 0) { igraph_free(val); IGRAPH_ERROR("cannot allocated 'dom' array in igraph_i_lad_initDomains", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_int_init(&D->globalMatchingP, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->globalMatchingP); igraph_vector_int_fill(&D->globalMatchingP, -1L); IGRAPH_CHECK(igraph_vector_int_init(&D->globalMatchingT, Gt->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->globalMatchingT); igraph_vector_int_fill(&D->globalMatchingT, -1L); IGRAPH_CHECK(igraph_vector_int_init(&D->nbVal, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->nbVal); IGRAPH_CHECK(igraph_vector_int_init(&D->firstVal, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->firstVal); IGRAPH_CHECK(igraph_matrix_int_init(&D->posInVal, Gp->nbVertices, Gt->nbVertices)); IGRAPH_FINALLY(igraph_matrix_int_destroy, &D->posInVal); IGRAPH_CHECK(igraph_matrix_int_init(&D->firstMatch, Gp->nbVertices, Gt->nbVertices)); IGRAPH_FINALLY(igraph_matrix_int_destroy, &D->firstMatch); IGRAPH_CHECK(igraph_vector_char_init(&D->markedToFilter, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_char_destroy, &D->markedToFilter); IGRAPH_CHECK(igraph_vector_int_init(&D->toFilter, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->toFilter); D->valSize = 0; matchingSize = 0; for (u=0; unbVertices; u++) { igraph_vector_int_t *Gp_uneis=igraph_adjlist_get(&Gp->succ, u); if (initialDomains) { /* read the list of target vertices which are compatible with u */ vec=VECTOR(*domains)[u]; i=(int) igraph_vector_size(vec); memset(dom, false, sizeof(bool)*(size_t)(Gt->nbVertices)); for (j=0; jmarkedToFilter)[u] = true; VECTOR(D->toFilter)[u] = u; VECTOR(D->nbVal)[u] = 0; VECTOR(D->firstVal)[u] = D->valSize; for (v=0; vnbVertices; v++) { igraph_vector_int_t *Gt_vneis=igraph_adjlist_get(&Gt->succ, v); if ((initialDomains) && (!dom[v])) { /* v not in D(u) */ MATRIX(D->posInVal, u, v) = (int) (VECTOR(D->firstVal)[u] + Gt->nbVertices); } else { MATRIX(D->firstMatch, u, v) = matchingSize; matchingSize += VECTOR(Gp->nbSucc)[u]; if (VECTOR(Gp->nbSucc)[u] <= VECTOR(Gt->nbSucc)[v]) { mu = igraph_Calloc((long int) VECTOR(Gp->nbSucc)[u], int); if (mu == 0) { igraph_free(val); igraph_free(dom); IGRAPH_ERROR("cannot allocate 'mu' array in igraph_i_lad_initDomains", IGRAPH_ENOMEM); } mv = igraph_Calloc((long int) VECTOR(Gt->nbSucc)[v], int); if (mv == 0) { igraph_free(mu); igraph_free(val); igraph_free(dom); IGRAPH_ERROR("cannot allocate 'mv' array in igraph_i_lad_initDomains", IGRAPH_ENOMEM); } for (i=0; inbSucc)[u]; i++) { mu[i]=(int) VECTOR(Gp->nbSucc)[(long int) VECTOR(*Gp_uneis)[i]]; } for (i=0; inbSucc)[v]; i++) { mv[i]=(int) VECTOR(Gt->nbSucc)[(long int) VECTOR(*Gt_vneis)[i]]; } if (igraph_i_lad_compare((int) VECTOR(Gp->nbSucc)[u], mu, (int) VECTOR(Gt->nbSucc)[v], mv)==1) { val[D->valSize] = v; VECTOR(D->nbVal)[u]++; MATRIX(D->posInVal, u, v) = D->valSize++; } else { /* v not in D(u) */ MATRIX(D->posInVal, u, v) = (int)(VECTOR(D->firstVal)[u] + Gt->nbVertices); } igraph_free(mu); mu = 0; igraph_free(mv); mv = 0; } else { /* v not in D(u) */ MATRIX(D->posInVal, u, v) = (int) (VECTOR(D->firstVal)[u] + Gt->nbVertices); } } } if (VECTOR(D->nbVal)[u] == 0) { *empty = 1; /* empty domain */ igraph_free(val); igraph_free(dom); return 0; } } IGRAPH_CHECK(igraph_vector_int_init(&D->val, D->valSize)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->val); for (i=0; ivalSize; i++) { VECTOR(D->val)[i] = val[i]; } IGRAPH_CHECK(igraph_vector_int_init(&D->matching, matchingSize)); IGRAPH_FINALLY(igraph_vector_int_destroy, &D->matching); igraph_vector_int_fill(&D->matching, -1); D->nextOutToFilter = 0; D->lastInToFilter = (int) (Gp->nbVertices-1); *empty=0; igraph_free(val); igraph_free(dom); return 0; } /* ---------------------------------------------------------*/ /* Coming from allDiff.c */ /* ---------------------------------------------------------*/ #define white 0 #define grey 1 #define black 2 #define toBeDeleted 3 #define deleted 4 void igraph_i_lad_addToDelete(int u, int* list, int* nb, int* marked) { if (marked[u]sizeOfV) { *invalid = 1; /* trivial case of infeasibility */ return 0; } ALLOC_ARRAY(matchedWithV, sizeOfV, int); ALLOC_ARRAY(nbPred, sizeOfV, int); ALLOC_ARRAY(pred, sizeOfV*sizeOfU, int); ALLOC_ARRAY(nbSucc, sizeOfU, int); ALLOC_ARRAY(succ, sizeOfU*sizeOfV, int); ALLOC_ARRAY(listV, sizeOfV, int); ALLOC_ARRAY(listU, sizeOfU, int); ALLOC_ARRAY(listDV, sizeOfV, int); ALLOC_ARRAY(listDU, sizeOfU, int); ALLOC_ARRAY(markedV, sizeOfV, int); ALLOC_ARRAY(markedU, sizeOfU, int); ALLOC_ARRAY(unmatched, sizeOfU, int); ALLOC_ARRAY(posInUnmatched, sizeOfU, int); IGRAPH_CHECK(igraph_vector_int_init(&path, 0)); IGRAPH_FINALLY(igraph_vector_int_destroy, &path); /* initialize matchedWithV and unmatched */ memset(matchedWithV, -1, (size_t)sizeOfV*sizeof(int)); for (u=0; u= 0) { matchedWithV[VECTOR(*matchedWithU)[u]]=u; } else { posInUnmatched[u]=nbUnmatched; unmatched[nbUnmatched++]=u; } } /* try to match unmatched vertices of U with free vertices of V */ j=0; while (j= 0)); i++) { } if (i == VECTOR(*firstAdj)[u] + VECTOR(*degree)[u]) { j++; /* no free vertex for u */ } else { v=VECTOR(*adj)[i]; /* v is free => match u with v */ VECTOR(*matchedWithU)[u]=v; matchedWithV[v]=u; unmatched[j]=unmatched[--nbUnmatched]; posInUnmatched[unmatched[j]]=j; } } while (nbUnmatched > 0) { /* Try to increase the number of matched vertices */ /* step 1 : build the DAG */ memset(markedU, white, (size_t) sizeOfU*sizeof(int)); memset(nbSucc, 0, (size_t) sizeOfU*sizeof(int)); memset(markedV, white, (size_t) sizeOfV*sizeof(int)); memset(nbPred, 0, (size_t) sizeOfV*sizeof(int)); /* first layer of the DAG from the free nodes of U */ nbV=0; for (j=0; j0)) { /* build next layer from nodes of V to nodes of U */ nbU=0; for (i=0; i0)) { /* v is the final node of an augmenting path */ IGRAPH_CHECK(igraph_vector_int_resize(&path, 1)); VECTOR(path)[0]=v; nbDV=0; nbDU=0; igraph_i_lad_addToDelete(v, listDV, &nbDV, markedV); do{ u=pred[v*sizeOfU + 0]; /* (u, v) belongs to the augmenting path */ IGRAPH_CHECK(igraph_vector_int_push_back(&path, u)); igraph_i_lad_addToDelete(u, listDU, &nbDU, markedU); if (VECTOR(*matchedWithU)[u]!=-1) { /* u is not the initial node of the augmenting path */ v=VECTOR(*matchedWithU)[u]; /* (v, u) belongs to the augmenting path */ IGRAPH_CHECK(igraph_vector_int_push_back(&path, v)); igraph_i_lad_addToDelete(v, listDV, &nbDV, markedV); } } while (VECTOR(*matchedWithU)[u]!=-1); /* delete nodes of listDV and listDU */ while ((nbDV>0) || (nbDU>0)) { while (nbDV>0) { /* delete v */ v=listDV[--nbDV]; markedV[v]=deleted; u=matchedWithV[v]; if (u!=-1) { igraph_i_lad_addToDelete(u, listDU, &nbDU, markedU); } for (i=0; i0) { /* delete u */ u = listDU[--nbDU]; markedU[u]=deleted; v=VECTOR(*matchedWithU)[u]; if (v!=-1) { igraph_i_lad_addToDelete(v, listDV, &nbDV, markedV); } j=0; for (i=0; i1) { u=igraph_vector_int_pop_back(&path); v=igraph_vector_int_pop_back(&path); w=matchedWithV[v]; /* match v with u instead of v with w */ VECTOR(*matchedWithU)[u]=v; matchedWithV[v]=u; } } } } *invalid=0; cleanup: /* Free the allocated arrays */ igraph_vector_int_destroy(&path); igraph_free(posInUnmatched); igraph_free(unmatched); igraph_free(markedU); igraph_free(markedV); igraph_free(listDU); igraph_free(listDV); igraph_free(listU); igraph_free(listV); igraph_free(succ); igraph_free(nbSucc); igraph_free(pred); igraph_free(nbPred); igraph_free(matchedWithV); IGRAPH_FINALLY_CLEAN(14); return 0; } void igraph_i_lad_DFS(int nbU, int nbV, int u, bool* marked, int* nbSucc, int* succ, igraph_vector_int_t * matchedWithU, int* order, int* nb) { /* perform a depth first search, starting from u, in the bipartite graph Go=(U, V, E) such that U = vertices of Gp V = vertices of Gt E = { (u, matchedWithU[u]) / u is a vertex of Gp } U { (v, u) / v is a vertex of D[u] which is not matched to v} Given a vertex v of Gt, nbSucc[v]=number of successors of v and succ[v]=list of successors of v. order[nb^out+1..nb^in] contains the vertices discovered by the DFS */ int i; int v=VECTOR(*matchedWithU)[u]; /* the only one predecessor of v is u */ marked[u]=true; if (v >= 0) { for (i=0; i number it */ order[*nb]=u; (*nb)--; } int igraph_i_lad_SCC(int nbU, int nbV, int* numV, int* numU, int* nbSucc, int* succ, int* nbPred, int* pred, igraph_vector_int_t * matchedWithU, igraph_vector_int_t * matchedWithV) { /* postrelation: numV[v]==numU[u] iff they belong to the same strongly connected component in the bipartite graph Go=(U, V, E) such that U = vertices of Gp V = vertices of Gt E = { (u, matchedWithU[u]) / u is a vertex of Gp } U { (v, u) / v is a vertex of D[u] which is not matched to v} Given a vertex v of Gt, nbSucc[v]=number of sucessors of v and succ[v]=list of successors of v */ int *order; bool *marked; int *fifo; int u, v, i, j, k, nbSCC, nb; /* Allocate memory */ ALLOC_ARRAY(order, nbU, int); ALLOC_ARRAY(marked, nbU, bool); ALLOC_ARRAY(fifo, nbV, int); /* Order vertices of Gp wrt DFS */ nb=nbU-1; for (u=0; u0) { v=fifo[--k]; u=VECTOR(*matchedWithV)[v]; if (u!=-1) { numU[u]=nbSCC; for (j=0; jglobalMatchingP is an all different matching of the pattern vertices postcondition: filter domains wrt GAC(allDiff) return false if an inconsistency is detected; true otherwise Build the bipartite directed graph Go=(U, V, E) such that E = { (u, v) / u is a vertex of Gp which is matched to v (i.e., v=D->globalMatchingP[u])} U { (v, u) / v is a vertex of Gt which is in D(u) but is not matched to u} */ int *nbPred; /* nbPred[u] = nb of predecessors of u in Go */ int *pred; /* pred[u][i] = ith predecessor of u in Go */ int *nbSucc; /* nbSucc[v] = nb of successors of v in Go */ int *succ; /* succ[v][i] = ith successor of v in Go */ int u, v, i, w, oldNbVal, nbToMatch; int *numV, *numU; igraph_vector_int_t toMatch; bool *used; int *list; int nb=0; bool result; /* Allocate memory */ ALLOC_ARRAY(nbPred, Gp->nbVertices, int); ALLOC_ARRAY(pred, Gp->nbVertices*Gt->nbVertices, int); ALLOC_ARRAY(nbSucc, Gt->nbVertices, int); ALLOC_ARRAY(succ, Gt->nbVertices*Gp->nbVertices, int); ALLOC_ARRAY(numV, Gt->nbVertices, int); ALLOC_ARRAY(numU, Gp->nbVertices, int); ALLOC_ARRAY(used, Gp->nbVertices*Gt->nbVertices, bool); ALLOC_ARRAY(list, Gt->nbVertices, int); IGRAPH_CHECK(igraph_vector_int_init(&toMatch, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_int_destroy, &toMatch); for (u=0; unbVertices; u++) { for (i=0; i < VECTOR(D->nbVal)[u]; i++) { v=VECTOR(D->val)[ VECTOR(D->firstVal)[u]+i ]; /* v in D(u) */ used[u*Gt->nbVertices+v]=false; if (v != VECTOR(D->globalMatchingP)[u]) { pred[u*Gt->nbVertices + (nbPred[u]++)]=v; succ[v*Gp->nbVertices + (nbSucc[v]++)]=u; } } } /* mark as used all edges of paths starting from free vertices */ for (v=0; vnbVertices; v++) { if (VECTOR(D->globalMatchingT)[v] < 0) { /* v is free */ list[nb++]=v; numV[v]=true; } } while (nb>0) { v=list[--nb]; for (i=0; inbVertices + i]; used[u*Gt->nbVertices+v]=true; if (numU[u]==false) { numU[u]=true; w=VECTOR(D->globalMatchingP)[u]; used[u*Gt->nbVertices+w]=true; if (numV[w]==false) { list[nb++]=w; numV[w]=true; } } } } /* look for strongly connected components in Go */ IGRAPH_CHECK( igraph_i_lad_SCC((int)(Gp->nbVertices), (int)(Gt->nbVertices), numV, numU, nbSucc, succ, nbPred, pred, &D->globalMatchingP, &D->globalMatchingT)); /* remove v from D[u] if (u, v) is not marked as used and u and v are not in the same SCC and D->globalMatchingP[u] != v */ nbToMatch = 0; for (u=0; unbVertices; u++) { oldNbVal = VECTOR(D->nbVal)[u]; for (i=0; i < VECTOR(D->nbVal)[u]; i++) { v=VECTOR(D->val)[ VECTOR(D->firstVal)[u]+i ]; /* v in D(u) */ if ((!used[u*Gt->nbVertices+v]) && (numV[v]!=numU[u]) && (VECTOR(D->globalMatchingP)[u]!=v)) { IGRAPH_CHECK(igraph_i_lad_removeValue(u, v, D, Gp, Gt, &result)); if (!result) { *invalid = 1; /* Yes, this is ugly. */ goto cleanup; } } } if (VECTOR(D->nbVal)[u] == 0) { *invalid = 1; /* Yes, this is ugly. */ goto cleanup; } if ((oldNbVal>1) && (VECTOR(D->nbVal)[u]==1)) { VECTOR(toMatch)[nbToMatch++] = u; } } IGRAPH_CHECK(igraph_i_lad_matchVertices(nbToMatch, &toMatch, induced, D, Gp, Gt, invalid)); cleanup: igraph_vector_int_destroy(&toMatch); igraph_free(list); igraph_free(used); igraph_free(numU); igraph_free(numV); igraph_free(succ); igraph_free(nbSucc); igraph_free(pred); igraph_free(nbPred); IGRAPH_FINALLY_CLEAN(9); return 0; } /* ---------------------------------------------------------*/ /* Coming from lad.c */ /* ---------------------------------------------------------*/ int igraph_i_lad_checkLAD(int u, int v, Tdomain* D, Tgraph* Gp, Tgraph* Gt, bool *result) { /* return true if G_(u, v) has a adj(u)-covering matching; false otherwise */ int u2, v2, i, j; int nbMatched = 0; igraph_vector_int_t *Gp_uneis=igraph_adjlist_get(&Gp->succ, u); int *num, *numInv; igraph_vector_int_t nbComp; igraph_vector_int_t firstComp; igraph_vector_int_t comp; int nbNum=0; int posInComp=0; igraph_vector_int_t matchedWithU; int invalid; /* special case when u has only 1 adjacent node => no need to call Hopcroft and Karp */ if (VECTOR(Gp->nbSucc)[u]==1) { u2 = (int) VECTOR(*Gp_uneis)[0]; /* u2 is the only node adjacent to u */ v2 = VECTOR(D->matching)[ MATRIX(D->firstMatch, u, v) ]; if ((v2 != -1) && (igraph_i_lad_isInD(u2, v2, D))) { *result = true; return 0; } /* look for a support of edge (u, u2) for v */ for (i=VECTOR(D->firstVal)[u2]; i < VECTOR(D->firstVal)[u2] + VECTOR(D->nbVal)[u2]; i++) { if (MATRIX(Gt->isEdge, v, VECTOR(D->val)[i])) { VECTOR(D->matching)[ MATRIX(D->firstMatch, u, v) ] = VECTOR(D->val)[i]; *result = true; return 0; } } *result = false; return 0; } /* general case (when u has more than 1 adjacent node) */ for (i=0; inbSucc)[u]; i++) { /* remove from the matching of G_(u, v) edges which no longer belong to G_(u, v) */ u2 = (int) VECTOR(*Gp_uneis)[i]; v2 = VECTOR(D->matching)[ MATRIX(D->firstMatch, u, v)+i]; if ((v2 != -1) && (igraph_i_lad_isInD(u2, v2, D))) { nbMatched++; } } if (nbMatched == VECTOR(Gp->nbSucc)[u]) { *result = true; return 0; } /* The matching still covers adj(u) */ /* Allocate memory */ ALLOC_ARRAY(num, Gt->nbVertices, int); ALLOC_ARRAY(numInv, Gt->nbVertices, int); /* Build the bipartite graph let U be the set of nodes adjacent to u let V be the set of nodes that are adjacent to v, and that belong to domains of nodes of U */ /* nbComp[u]=number of elements of V that are compatible with u */ IGRAPH_CHECK(igraph_vector_int_init(&nbComp, (long int) VECTOR(Gp->nbSucc)[u])); IGRAPH_FINALLY(igraph_vector_int_destroy, &nbComp); IGRAPH_CHECK(igraph_vector_int_init(&firstComp, (long int) VECTOR(Gp->nbSucc)[u])); IGRAPH_FINALLY(igraph_vector_int_destroy, &firstComp); /* comp[firstComp[u]..firstComp[u]+nbComp[u]-1] = nodes of Gt that are compatible with u */ IGRAPH_CHECK(igraph_vector_int_init(&comp, (long int) (VECTOR(Gp->nbSucc)[u] * Gt->nbVertices))); IGRAPH_FINALLY(igraph_vector_int_destroy, &comp); IGRAPH_CHECK(igraph_vector_int_init(&matchedWithU, (long int) VECTOR(Gp->nbSucc)[u])); IGRAPH_FINALLY(igraph_vector_int_destroy, &matchedWithU); memset(num, -1, (size_t) (Gt->nbVertices) * sizeof(int)); for (i=0; inbSucc)[u]; i++) { u2 = (int) VECTOR(*Gp_uneis)[i]; /* u2 is adjacent to u */ /* search for all nodes v2 in D[u2] which are adjacent to v */ VECTOR(nbComp)[i]=0; VECTOR(firstComp)[i]=posInComp; if (VECTOR(D->nbVal)[u2] > VECTOR(Gt->nbSucc)[v]) { for (j=VECTOR(D->firstVal)[u2]; j < VECTOR(D->firstVal)[u2] + VECTOR(D->nbVal)[u2]; j++) { v2 = VECTOR(D->val)[j]; /* v2 belongs to D[u2] */ if (MATRIX(Gt->isEdge, v, v2)) { /* v2 is a successor of v */ if (num[v2]<0) { /* v2 has not yet been added to V */ num[v2]=nbNum; numInv[nbNum++]=v2; } VECTOR(comp)[posInComp++]=num[v2]; VECTOR(nbComp)[i]++; } } } else { igraph_vector_int_t *Gt_vneis=igraph_adjlist_get(&Gt->succ, v); for (j=0; jnbSucc)[v]; j++) { v2 = (int) VECTOR(*Gt_vneis)[j]; /* v2 is a successor of v */ if (igraph_i_lad_isInD(u2, v2, D)) { /* v2 belongs to D[u2] */ if (num[v2]<0) { /* v2 has not yet been added to V */ num[v2]=nbNum; numInv[nbNum++]=v2; } VECTOR(comp)[posInComp++]=num[v2]; VECTOR(nbComp)[i]++; } } } if (VECTOR(nbComp)[i]==0) { *result = false; /* u2 has no compatible vertex in succ[v] */ goto cleanup; } /* u2 is matched to v2 in the matching that supports (u, v) */ v2 = VECTOR(D->matching)[ MATRIX(D->firstMatch, u, v)+i]; if ((v2 != -1) && (igraph_i_lad_isInD(u2, v2, D))) { VECTOR(matchedWithU)[i]=num[v2]; } else { VECTOR(matchedWithU)[i]=-1; } } /* Call Hopcroft Karp to update the matching */ IGRAPH_CHECK( igraph_i_lad_updateMatching((int) VECTOR(Gp->nbSucc)[u], nbNum, &nbComp, &firstComp, &comp, &matchedWithU, &invalid) ); if (invalid) { *result = false; goto cleanup; } for (i=0; inbSucc)[u]; i++) { VECTOR(D->matching)[ MATRIX(D->firstMatch, u, v)+i] = numInv[ VECTOR(matchedWithU)[i] ]; } *result = true; cleanup: igraph_free(numInv); igraph_free(num); igraph_vector_int_destroy(&matchedWithU); igraph_vector_int_destroy(&comp); igraph_vector_int_destroy(&firstComp); igraph_vector_int_destroy(&nbComp); IGRAPH_FINALLY_CLEAN(6); return 0; } /* ---------------------------------------------------------*/ /* Coming from main.c */ /* ---------------------------------------------------------*/ int igraph_i_lad_filter(bool induced, Tdomain* D, Tgraph* Gp, Tgraph* Gt, bool *result) { /* filter domains of all vertices in D->toFilter wrt LAD and ensure GAC(allDiff) return false if some domain becomes empty; true otherwise */ int u, v, i, oldNbVal; int invalid; bool result2; while (!igraph_i_lad_toFilterEmpty(D)) { while (!igraph_i_lad_toFilterEmpty(D)) { u=igraph_i_lad_nextToFilter(D, (int) (Gp->nbVertices)); oldNbVal = VECTOR(D->nbVal)[u]; i = VECTOR(D->firstVal)[u]; while (i < VECTOR(D->firstVal)[u] + VECTOR(D->nbVal)[u]) { /* for every target node v in D(u), check if G_(u, v) has a covering matching */ v=VECTOR(D->val)[i]; IGRAPH_CHECK(igraph_i_lad_checkLAD(u, v, D, Gp, Gt, &result2)); if (result2) { i++; } else { IGRAPH_CHECK(igraph_i_lad_removeValue(u, v, D, Gp, Gt, &result2)); if (!result2) { *result = false; return 0; } } } if ((VECTOR(D->nbVal)[u]==1) && (oldNbVal>1) && (!igraph_i_lad_matchVertex(u, induced, D, Gp, Gt))) { *result = false; return 0; } if (VECTOR(D->nbVal)[u]==0) { *result = false; return 0; } } igraph_i_lad_ensureGACallDiff(induced, Gp, Gt, D, &invalid); if (invalid) { *result = false; return 0; } } *result = true; return 0; } int igraph_i_lad_solve(int timeLimit, bool firstSol, bool induced, Tdomain* D, Tgraph* Gp, Tgraph* Gt, int *invalid, igraph_bool_t *iso, igraph_vector_t *map, igraph_vector_ptr_t *maps, int *nbNodes, int *nbFail, int *nbSol, clock_t *begin, igraph_vector_ptr_t *alloc_history) { /* if firstSol then search for the first solution; otherwise search for all solutions if induced then search for induced subgraphs; otherwise search for partial subgraphs return false if CPU time limit exceeded before the search is completed, return true otherwise */ int u, v, minDom, i; int* nbVal; int* globalMatching; clock_t end=clock(); igraph_vector_t *vec; int* val; bool result; (*nbNodes)++; if ( (double)(end - *begin) / CLOCKS_PER_SEC >= timeLimit) { /* CPU time limit exceeded */ IGRAPH_ERROR("LAD CPU time exceeded", IGRAPH_CPUTIME); } /* Allocate memory */ ALLOC_ARRAY_IN_HISTORY(nbVal, Gp->nbVertices, int, alloc_history); ALLOC_ARRAY_IN_HISTORY(globalMatching, Gp->nbVertices, int, alloc_history); IGRAPH_CHECK(igraph_i_lad_filter(induced, D, Gp, Gt, &result)); if (!result) { /* filtering has detected an inconsistency */ (*nbFail)++; igraph_i_lad_resetToFilter(D); *invalid=0; goto cleanup; } /* The current node of the search tree is consistent wrt to LAD and GAC(allDiff) Save domain sizes and global all different matching and search for the non matched vertex minDom with smallest domain */ minDom=-1; for (u=0; unbVertices; u++) { nbVal[u]=VECTOR(D->nbVal)[u]; if ((nbVal[u]>1) && ((minDom<0) || (nbVal[u]globalMatchingP)[u]; } if (minDom==-1) { /* All vertices are matched => Solution found */ if (iso) { *iso = 1; } (*nbSol)++; if (map && igraph_vector_size(map)==0) { IGRAPH_CHECK(igraph_vector_resize(map, Gp->nbVertices)); for (u=0; unbVertices; u++) { VECTOR(*map)[u] = VECTOR(D->val)[ VECTOR(D->firstVal)[u] ]; } } if (maps) { vec=igraph_Calloc(1, igraph_vector_t); if (!vec) { IGRAPH_ERROR("LAD failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vec); IGRAPH_CHECK(igraph_vector_init(vec, Gp->nbVertices)); IGRAPH_FINALLY(igraph_vector_destroy, vec); for (u=0; unbVertices; u++) { VECTOR(*vec)[u] = VECTOR(D->val)[ VECTOR(D->firstVal)[u] ]; } IGRAPH_CHECK(igraph_vector_ptr_push_back(maps, vec)); IGRAPH_FINALLY_CLEAN(2); } igraph_i_lad_resetToFilter(D); *invalid=0; goto cleanup; } /* save the domain of minDom to iterate on its values */ ALLOC_ARRAY_IN_HISTORY(val, VECTOR(D->nbVal)[minDom], int, alloc_history); for (i=0; i < VECTOR(D->nbVal)[minDom]; i++) { val[i]=VECTOR(D->val)[ VECTOR(D->firstVal)[minDom]+i ]; } /* branch on minDom=v, for every target node v in D(u) */ for(i=0; ((iglobalMatchingT, -1); for (u=0; unbVertices; u++) { VECTOR(D->nbVal)[u] = nbVal[u]; VECTOR(D->globalMatchingP)[u] = globalMatching[u]; VECTOR(D->globalMatchingT)[globalMatching[u]] = u; } } *invalid=0; igraph_free(val); igraph_vector_ptr_pop_back(alloc_history); cleanup: igraph_free(globalMatching); igraph_vector_ptr_pop_back(alloc_history); igraph_free(nbVal); igraph_vector_ptr_pop_back(alloc_history); return 0; } /** * \function igraph_subisomorphic_lad * Check subgraph isomorphism with the LAD algorithm * * Check whether \p pattern is isomorphic to a subgraph os \p target. * The original LAD implementation by Christine Solnon was used as the * basis of this code. * * * See more about at http://liris.cnrs.fr/csolnon/LAD.html and in * Christine Solnon: AllDifferent-based Filtering for Subgraph * Isomorphism. Artificial Intelligence, 174(12-13):850-864, August * 2010, Elsevier * * \param pattern The smaller graph, it can be directed or undirected. * \param target The bigger graph, it can be directed or undirected. * \param domains A pointer vector, or a null pointer. If a pointer * vector, then it must contain pointers to \c igraph_vector_t * objects and the length of the vector must match the number of * vertices in the \p pattern graph. For each vertex, the ids of * the compatible vertices in the target graph are listed. * \param iso Pointer to a boolean, or a null pointer. If not a null * pointer, then the boolean is set to TRUE (1) if a subgraph * isomorphism is found, and to FALSE (0) otherwise. * \param map Pointer to a vector or a null pointer. If not a null * pointer and a subgraph isomorphism is found, the matching * vertices from the target graph are listed here, for each vertex * (in vertex id order) from the pattern graph. * \param maps Pointer vector or a null pointer. If not a null * pointer, then all subgraph isomorphisms are stored in the * pointer vector, in \c igraph_vector_t objects. * \param induced Boolean, whether to search for induced matching * subgraphs. * \param time_limit Processor time limit in seconds. Supply zero * here for no limit. If the time limit is over, then the function * signals an error. * \return Error code * * \sa \ref igraph_subisomorphic_vf2() for the VF2 algorithm. * * Time complexity: exponential. * * \example examples/simple/igraph_subisomorphic_lad.c */ int igraph_subisomorphic_lad(const igraph_t *pattern, const igraph_t *target, igraph_vector_ptr_t *domains, igraph_bool_t *iso, igraph_vector_t *map, igraph_vector_ptr_t *maps, igraph_bool_t induced, int time_limit) { bool firstSol = maps == 0; bool initialDomains = domains != 0; Tgraph Gp, Gt; Tdomain D; int invalidDomain; int u, nbToMatch = 0; igraph_vector_int_t toMatch; /* Number of nodes in the search tree */ int nbNodes=0; /* number of failed nodes in the search tree */ int nbFail=0; /* number of solutions found */ int nbSol=0; /* reusable structure to get CPU time usage */ clock_t begin=clock(); /* Stack to store memory blocks that are allocated during igraph_i_lad_solve */ igraph_vector_ptr_t alloc_history; if (!iso && !map && !maps) { IGRAPH_ERROR("Please give least one of `iso', `map' or `maps'", IGRAPH_EINVAL); } if (igraph_is_directed(pattern) != igraph_is_directed(target)) { IGRAPH_ERROR("Cannot search for a directed pattern in an undirected target " "or vice versa", IGRAPH_EINVAL); } if (time_limit<=0) { time_limit = INT_MAX; } if (iso) { *iso = (igraph_vcount(pattern) == 0); } if (map) { igraph_vector_clear(map); } if (maps) { igraph_vector_ptr_clear(maps); } if (igraph_vcount(pattern) == 0) { /* Special case for empty graphs */ return IGRAPH_SUCCESS; } IGRAPH_CHECK(igraph_i_lad_createGraph(pattern, &Gp)); IGRAPH_CHECK(igraph_i_lad_createGraph(target, &Gt)); if (Gp.nbVertices > Gt.nbVertices) { goto exit3; } IGRAPH_CHECK(igraph_i_lad_initDomains(initialDomains, domains, &D, &Gp, &Gt, &invalidDomain)); if (invalidDomain) { goto exit2; } IGRAPH_CHECK(igraph_i_lad_updateMatching((int) (Gp.nbVertices), (int) (Gt.nbVertices), &D.nbVal, &D.firstVal, &D.val, &D.globalMatchingP, &invalidDomain)); if (invalidDomain) { goto exit; } IGRAPH_CHECK(igraph_i_lad_ensureGACallDiff((char) induced, &Gp, &Gt, &D, &invalidDomain)); if (invalidDomain) { goto exit; } for (u=0; u #include #include #include #include using namespace std; #include "drl_layout.h" #include "drl_parse.h" namespace drl { // void parse::print_syntax( const char *error_string ) // { // cout << endl << "Error: " << error_string << endl; // cout << endl << "Layout" << endl // << "------" << endl // << "S. Martin" << endl // << "Version " << DRL_VERSION << endl << endl // << "This program provides a parallel adaptation of a force directed" << endl // << "graph layout algorithm for use with large datasets." << endl << endl // << "Usage: layout [options] root_file" << endl << endl // << "root_file -- the root name of the file being processed." << endl << endl // << "INPUT" << endl // << "-----" << endl // << "root_file.int -- the input file containing the graph to draw using layout." << endl // << " The .int file must have the suffix \".int\" and each line of .int file" << endl // << " should have the form" << endl // << "\tnode_id node_id weight" << endl // << " where node_id's are integers in sequence starting from 0, and" << endl // << " weight is a float > 0." << endl << endl // << "OUTPUT" << endl // << "------" << endl // << "root_file.icoord -- the resulting output file, containing an ordination" << endl // << " of the graph. The .icoord file will have the suffix \".icoord\" and" << endl // << " each line of the .icoord file will be of the form" << endl // << "\tnode_id x-coord y-coord" << endl << endl // << "Options:" << endl << endl // << "\t-s {int>=0} random seed (default value is 0)" << endl // << "\t-c {real[0,1]} edge cutting (default 32/40 = .8)" << endl // << "\t (old max was 39/40 = .975)" << endl // << "\t-p input parameters from .parms file" << endl // << "\t-r {real[0,1]} input coordinates from .real file" << endl // << "\t (hold fixed until fraction of optimization schedule reached)" << endl // << "\t-i {int>=0} intermediate output interval (default 0: no output)" << endl // << "\t-e output .iedges file (same prefix as .coord file)" << endl << endl; // #ifdef MUSE_MPI // MPI_Abort ( MPI_COMM_WORLD, 1 ); // #else // exit (1); // #endif // } // parse::parse ( int argc, char** argv) // { // map m; // // make sure there is at least one argument // if ( argc < 2) // print_syntax ( "not enough arguments!" ); // // make sure coord_file ends in ".coord" // parms_file = real_file = sim_file = coord_file = argv[argc-1]; // parms_file = parms_file + ".parms"; // real_file = real_file + ".real"; // sim_file = sim_file + ".int"; // coord_file = coord_file + ".icoord"; // char error_string[200]; // sprintf ( error_string, "%s %d %s", "root file name cannot be longer than", MAX_FILE_NAME-7, // "characters."); // if ( coord_file.length() > MAX_FILE_NAME ) // print_syntax ( error_string ); // // echo sim_file and coord_file // cout << "Using " << sim_file << " for .int file, and " << coord_file << " for .icoord file." << endl; // // set defaults // rand_seed = 0; // //edge_cut = 32.0/39.0; // (old default) // edge_cut = 32.0/40.0; // int_out = 0; // edges_out = 0; // parms_in = 0; // real_in = -1.0; // // now check for optional arguments // string arg; // for( int i = 1; i= (argc-1) ) // print_syntax ( "-s flag has no argument." ); // else // { // rand_seed = atoi ( argv[i] ); // if ( rand_seed < 0 ) // print_syntax ( "random seed must be >= 0." ); // } // } // // check for edge cutting // else if ( arg == "-c" ) // { // i++; // if ( i >= (argc-1) ) // print_syntax ( "-c flag has no argument." ); // else // { // edge_cut = atof ( argv[i] ); // if ( (edge_cut < 0) || (edge_cut > 1) ) // print_syntax ( "edge cut must be between 0 and 1." ); // } // } // // check for intermediate output // else if ( arg == "-i" ) // { // i++; // if ( i >= (argc-1) ) // print_syntax ( "-i flag has no argument." ); // else // { // int_out = atoi ( argv[i] ); // if ( int_out < 0 ) // print_syntax ( "intermediate output must be >= 0." ); // } // } // // check for .real input // else if ( arg == "-r" ) // { // i++; // if ( i >= (argc-1) ) // print_syntax ( "-r flag has no argument." ); // else // { // real_in = atof ( argv[i] ); // if ( (real_in < 0) || (real_in > 1) ) // print_syntax ( "real iteration fraction must be from 0 to 1." ); // } // } // else if ( arg == "-e" ) // edges_out = 1; // else if ( arg == "-p" ) // parms_in = 1; // else // print_syntax ( "unrecongized option!" ); // } // if ( parms_in ) // cout << "Using " << parms_file << " for .parms file." << endl; // if ( real_in >= 0 ) // cout << "Using " << real_file << " for .real file." << endl; // // echo arguments input or default // cout << "Using random seed = " << rand_seed << endl // << " edge_cutting = " << edge_cut << endl // << " intermediate output = " << int_out << endl // << " output .iedges file = " << edges_out << endl; // if ( real_in >= 0 ) // cout << " holding .real fixed until iterations = " << real_in << endl; // } } // namespace drl igraph/src/igraph_cliquer.c0000644000175100001440000002431713431000472015474 0ustar hornikusers #include "igraph_cliquer.h" #include "igraph_memory.h" #include "igraph_constants.h" #include "igraph_interrupt_internal.h" #include "cliquer/cliquer.h" #include "config.h" #include /* Call this to allow for interruption in Cliquer callback functions */ #define CLIQUER_ALLOW_INTERRUPTION() \ { \ if (igraph_i_interruption_handler) \ if (igraph_allow_interruption(NULL) != IGRAPH_SUCCESS) { \ cliquer_interrupted = 1; \ return FALSE; \ } \ } /* Interruptable Cliquer functions must be wrapped in CLIQUER_INTERRUPTABLE when called */ #define CLIQUER_INTERRUPTABLE(x) \ { \ cliquer_interrupted = 0; \ x; \ if (cliquer_interrupted) return IGRAPH_INTERRUPTED; \ } /* Nonzero value signals interuption from Cliquer callback function */ static IGRAPH_THREAD_LOCAL int cliquer_interrupted; /* For use with IGRAPH_FINALLY */ static void free_clique_list(igraph_vector_ptr_t *vp) { igraph_integer_t i, len; len = igraph_vector_ptr_size(vp); for (i=0; i < len; ++i) igraph_vector_destroy((igraph_vector_t *) VECTOR(*vp)[i]); igraph_vector_ptr_free_all(vp); } /* We shall use this option struct for all calls to Cliquer */ static IGRAPH_THREAD_LOCAL clique_options igraph_cliquer_opt = { reorder_by_default, NULL, NULL, NULL, NULL, NULL, NULL, 0 }; /* Convert an igraph graph to a Cliquer graph */ static void igraph_to_cliquer(const igraph_t *ig, graph_t **cg) { igraph_integer_t vcount, ecount; int i; if (igraph_is_directed(ig)) IGRAPH_WARNING("Edge directions are ignored for clique calculations"); vcount = igraph_vcount(ig); ecount = igraph_ecount(ig); *cg = graph_new(vcount); for (i=0; i < ecount; ++i) { long s, t; s = IGRAPH_FROM(ig, i); t = IGRAPH_TO(ig, i); if (s != t) GRAPH_ADD_EDGE(*cg, s, t); } } /* Copy weights to a Cliquer graph */ static int set_weights(const igraph_vector_t *vertex_weights, graph_t *g) { int i; assert(vertex_weights != NULL); if (igraph_vector_size(vertex_weights) != g->n) IGRAPH_ERROR("Invalid vertex weight vector length", IGRAPH_EINVAL); for (i=0; i < g->n; ++i) { g->weights[i] = VECTOR(*vertex_weights)[i]; if (g->weights[i] != VECTOR(*vertex_weights)[i]) IGRAPH_WARNING("Only integer vertex weights are supported; weights will be truncated to their integer parts"); if (g->weights[i] <= 0) IGRAPH_ERROR("Vertex weights must be positive", IGRAPH_EINVAL); } return IGRAPH_SUCCESS; } /* Find all cliques. */ static boolean collect_cliques_callback(set_t s, graph_t *g, clique_options *opt) { igraph_vector_ptr_t *list; igraph_vector_t *clique; int i, j; CLIQUER_ALLOW_INTERRUPTION(); list = (igraph_vector_ptr_t *) opt->user_data; clique = (igraph_vector_t *) malloc(sizeof(igraph_vector_t)); igraph_vector_init(clique, set_size(s)); i = -1; j = 0; while ((i = set_return_next(s,i)) >= 0) VECTOR(*clique)[j++] = i; igraph_vector_ptr_push_back(list, clique); return TRUE; } int igraph_i_cliquer_cliques(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_integer_t min_size, igraph_integer_t max_size) { graph_t *g; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) { igraph_vector_ptr_clear(res); return IGRAPH_SUCCESS; } if (min_size <= 0) min_size = 1; if (max_size <= 0) max_size = 0; if (max_size > 0 && max_size < min_size) IGRAPH_ERROR("max_size must not be smaller than min_size", IGRAPH_EINVAL); igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); igraph_vector_ptr_clear(res); igraph_cliquer_opt.user_data = res; igraph_cliquer_opt.user_function = &collect_cliques_callback; IGRAPH_FINALLY(free_clique_list, res); CLIQUER_INTERRUPTABLE(clique_unweighted_find_all(g, min_size, max_size, /* maximal= */ FALSE, &igraph_cliquer_opt)); IGRAPH_FINALLY_CLEAN(1); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* Count cliques of each size. */ static boolean count_cliques_callback(set_t s, graph_t *g, clique_options *opt) { igraph_vector_t *hist; CLIQUER_ALLOW_INTERRUPTION(); hist = (igraph_vector_t *) opt->user_data; VECTOR(*hist)[set_size(s)-1] += 1; return TRUE; } int igraph_i_cliquer_histogram(const igraph_t *graph, igraph_vector_t *hist, igraph_integer_t min_size, igraph_integer_t max_size) { graph_t *g; int i; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) { igraph_vector_clear(hist); return IGRAPH_SUCCESS; } if (min_size <= 0) min_size = 1; if (max_size <= 0) max_size = vcount; /* also used for initial hist vector size, do not set to zero */ if (max_size < min_size) IGRAPH_ERROR("max_size must not be smaller than min_size", IGRAPH_EINVAL); igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); igraph_vector_resize(hist, max_size); igraph_vector_null(hist); igraph_cliquer_opt.user_data = hist; igraph_cliquer_opt.user_function = &count_cliques_callback; CLIQUER_INTERRUPTABLE(clique_unweighted_find_all(g, min_size, max_size, /* maximal= */ FALSE, &igraph_cliquer_opt)); for (i=max_size; i > 0; --i) if (VECTOR(*hist)[i-1] > 0) break; igraph_vector_resize(hist, i); igraph_vector_resize_min(hist); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* Call function for each clique. */ struct callback_data { igraph_clique_handler_t *handler; void *arg; }; static boolean callback_callback(set_t s, graph_t *g, clique_options *opt) { igraph_vector_t *clique; struct callback_data *cd; int i, j; CLIQUER_ALLOW_INTERRUPTION(); cd = (struct callback_data *) opt->user_data; clique = (igraph_vector_t *) malloc(sizeof(igraph_vector_t)); igraph_vector_init(clique, set_size(s)); i = -1; j = 0; while ((i = set_return_next(s,i)) >= 0) VECTOR(*clique)[j++] = i; return (*(cd->handler))(clique, cd->arg); } int igraph_i_cliquer_callback(const igraph_t *graph, igraph_integer_t min_size, igraph_integer_t max_size, igraph_clique_handler_t *cliquehandler_fn, void *arg) { graph_t *g; struct callback_data cd; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) return IGRAPH_SUCCESS; if (min_size <= 0) min_size = 1; if (max_size <= 0) max_size = 0; if (max_size > 0 && max_size < min_size) IGRAPH_ERROR("max_size must not be smaller than min_size", IGRAPH_EINVAL); igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); cd.handler = cliquehandler_fn; cd.arg = arg; igraph_cliquer_opt.user_data = &cd; igraph_cliquer_opt.user_function = &callback_callback; CLIQUER_INTERRUPTABLE(clique_unweighted_find_all(g, min_size, max_size, /* maximal= */ FALSE, &igraph_cliquer_opt)); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* Find weighted cliques in given weight range. */ int igraph_i_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res, igraph_real_t min_weight, igraph_real_t max_weight, igraph_bool_t maximal) { graph_t *g; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) { igraph_vector_ptr_clear(res); return IGRAPH_SUCCESS; } if (min_weight != (int) min_weight) { IGRAPH_WARNING("Only integer vertex weights are supported; the minimum weight will be truncated to its integer part"); min_weight = (int) min_weight; } if (max_weight != (int) max_weight) { IGRAPH_WARNING("Only integer vertex weights are supported; the maximum weight will be truncated to its integer part"); max_weight = (int) max_weight; } if (min_weight <= 0) min_weight = 1; if (max_weight <= 0) max_weight = 0; if (max_weight > 0 && max_weight < min_weight) IGRAPH_ERROR("max_weight must not be smaller than min_weight", IGRAPH_EINVAL); igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); IGRAPH_CHECK(set_weights(vertex_weights, g)); igraph_vector_ptr_clear(res); igraph_cliquer_opt.user_data = res; igraph_cliquer_opt.user_function = &collect_cliques_callback; IGRAPH_FINALLY(free_clique_list, res); CLIQUER_INTERRUPTABLE(clique_find_all(g, min_weight, max_weight, maximal, &igraph_cliquer_opt)); IGRAPH_FINALLY_CLEAN(1); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* Find largest weighted cliques. */ int igraph_i_largest_weighted_cliques(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_vector_ptr_t *res) { graph_t *g; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) { igraph_vector_ptr_clear(res); return IGRAPH_SUCCESS; } igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); IGRAPH_CHECK(set_weights(vertex_weights, g)); igraph_vector_ptr_clear(res); igraph_cliquer_opt.user_data = res; igraph_cliquer_opt.user_function = &collect_cliques_callback; IGRAPH_FINALLY(free_clique_list, res); CLIQUER_INTERRUPTABLE(clique_find_all(g, 0, 0, FALSE, &igraph_cliquer_opt)); IGRAPH_FINALLY_CLEAN(1); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } /* Find weight of largest weight clique. */ int igraph_i_weighted_clique_number(const igraph_t *graph, const igraph_vector_t *vertex_weights, igraph_real_t *res) { graph_t *g; igraph_integer_t vcount = igraph_vcount(graph); if (vcount == 0) { *res = 0; return IGRAPH_SUCCESS; } igraph_to_cliquer(graph, &g); IGRAPH_FINALLY(graph_free, g); IGRAPH_CHECK(set_weights(vertex_weights, g)); igraph_cliquer_opt.user_function = NULL; /* we are not using a callback function, thus this is not interruptable */ *res = clique_max_weight(g, &igraph_cliquer_opt); graph_free(g); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } igraph/src/operators.c0000644000175100001440000011552713431000472014520 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_operators.h" #include "igraph_error.h" #include "igraph_memory.h" #include "igraph_interrupt_internal.h" #include "igraph_interface.h" #include "igraph_constructors.h" #include "igraph_adjlist.h" #include "igraph_attributes.h" #include "igraph_conversion.h" #include "igraph_qsort.h" #include #include "config.h" /** * \function igraph_disjoint_union * \brief Creates the union of two disjoint graphs * * * First the vertices of the second graph will be relabeled with new * vertex ids to have two disjoint sets of vertex ids, then the union * of the two graphs will be formed. * If the two graphs have |V1| and |V2| vertices and |E1| and |E2| * edges respectively then the new graph will have |V1|+|V2| vertices * and |E1|+|E2| edges. * * * Both graphs need to have the same directedness, ie. either both * directed or both undirected. * * * The current version of this function cannot handle graph, vertex * and edge attributes, they will be lost. * * \param res Pointer to an uninitialized graph object, the result * will stored here. * \param left The first graph. * \param right The second graph. * \return Error code. * \sa \ref igraph_disjoint_union_many() for creating the disjoint union * of more than two graphs, \ref igraph_union() for non-disjoint * union. * * Time complexity: O(|V1|+|V2|+|E1|+|E2|). * * \example examples/simple/igraph_disjoint_union.c */ int igraph_disjoint_union(igraph_t *res, const igraph_t *left, const igraph_t *right) { long int no_of_nodes_left=igraph_vcount(left); long int no_of_nodes_right=igraph_vcount(right); long int no_of_edges_left=igraph_ecount(left); long int no_of_edges_right=igraph_ecount(right); igraph_vector_t edges; igraph_bool_t directed_left=igraph_is_directed(left); igraph_integer_t from, to; long int i; if (directed_left != igraph_is_directed(right)) { IGRAPH_ERROR("Cannot union directed and undirected graphs", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, 2*(no_of_edges_left+no_of_edges_right))); for (i=0; i * First the vertices in the graphs will be relabeled with new vertex * ids to have pairwise disjoint vertex id sets and then the union of * the graphs is formed. * The number of vertices and edges in the result is the total number * of vertices and edges in the graphs. * * * Both graphs need to have the same directedness, ie. either both * directed or both undirected. * * * The current version of this function cannot handle graph, vertex * and edge attributes, they will be lost. * * \param res Pointer to an uninitialized graph object, the result of * the operation will be stored here. * \param graphs Pointer vector, contains pointers to initialized * graph objects. * \return Error code. * \sa \ref igraph_disjoint_union() for an easier syntax if you have * only two graphs, \ref igraph_union_many() for non-disjoint union. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges in the result. */ int igraph_disjoint_union_many(igraph_t *res, const igraph_vector_ptr_t *graphs) { long int no_of_graphs=igraph_vector_ptr_size(graphs); igraph_bool_t directed=1; igraph_vector_t edges; long int no_of_edges=0; long int shift=0; igraph_t *graph; long int i, j; igraph_integer_t from, to; if (no_of_graphs != 0) { graph=VECTOR(*graphs)[0]; directed=igraph_is_directed(graph); for (i=0; i from2) { return 1; } else { long int to1=VECTOR(*edgelist)[edge1+1]; long int to2=VECTOR(*edgelist)[edge2+1]; if (to1 < to2) { return -1; } else if (to1 > to2) { return 1; } else { return 0; } } } #define IGRAPH_MODE_UNION 1 #define IGRAPH_MODE_INTERSECTION 2 int igraph_i_merge(igraph_t *res, int mode, const igraph_t *left, const igraph_t *right, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2) { long int no_of_nodes_left=igraph_vcount(left); long int no_of_nodes_right=igraph_vcount(right); long int no_of_nodes; long int no_edges_left=igraph_ecount(left); long int no_edges_right=igraph_ecount(right); igraph_bool_t directed=igraph_is_directed(left); igraph_vector_t edges; igraph_vector_t edges1, edges2; igraph_vector_long_t order1, order2; long int i, j, eptr=0; long int idx1, idx2, edge1=-1, edge2=-1, from1=-1, from2=-1, to1=-1, to2=-1; igraph_bool_t l; if (directed != igraph_is_directed(right)) { IGRAPH_ERROR("Cannot make union or intersection of directed " "and undirected graph", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&edges1, no_edges_left*2); IGRAPH_VECTOR_INIT_FINALLY(&edges2, no_edges_right*2); IGRAPH_CHECK(igraph_vector_long_init(&order1, no_edges_left)); IGRAPH_FINALLY(igraph_vector_long_destroy, &order1); IGRAPH_CHECK(igraph_vector_long_init(&order2, no_edges_right)); IGRAPH_FINALLY(igraph_vector_long_destroy, &order2); if (edge_map1) { switch (mode) { case IGRAPH_MODE_UNION: IGRAPH_CHECK(igraph_vector_resize(edge_map1, no_edges_left)); break; case IGRAPH_MODE_INTERSECTION: igraph_vector_clear(edge_map1); break; } } if (edge_map2) { switch (mode) { case IGRAPH_MODE_UNION: IGRAPH_CHECK(igraph_vector_resize(edge_map2, no_edges_right)); break; case IGRAPH_MODE_INTERSECTION: igraph_vector_clear(edge_map2); break; } } no_of_nodes=no_of_nodes_left > no_of_nodes_right ? no_of_nodes_left : no_of_nodes_right; /* We merge the two edge lists. We need to sort them first. For undirected graphs, we also need to make sure that for every edge, that larger (non-smaller) vertex id is in the second column. */ IGRAPH_CHECK(igraph_get_edgelist(left, &edges1, /*bycol=*/ 0)); IGRAPH_CHECK(igraph_get_edgelist(right, &edges2, /*bycol=*/ 0)); if (!directed) { for (i=0, j=0; i VECTOR(edges1)[j+1]) { long int tmp=VECTOR(edges1)[j]; VECTOR(edges1)[j]=VECTOR(edges1)[j+1]; VECTOR(edges1)[j+1]=tmp; } } for (i=0, j=0; i VECTOR(edges2)[j+1]) { long int tmp=VECTOR(edges2)[j]; VECTOR(edges2)[j]=VECTOR(edges2)[j+1]; VECTOR(edges2)[j+1]=tmp; } } } for (i=0; i= no_edges_right || (idx1 < no_edges_left && from1 < from2) || (idx1 < no_edges_left && from1 == from2 && to1 < to2)) { /* Edge from first graph */ if (mode==IGRAPH_MODE_UNION) { IGRAPH_CHECK(igraph_vector_push_back(&edges, from1)); IGRAPH_CHECK(igraph_vector_push_back(&edges, to1)); if (edge_map1) { VECTOR(*edge_map1)[edge1]=eptr; } eptr++; } INC1(); } else if (idx1 >= no_edges_left || (idx2 < no_edges_right && from2 < from1) || (idx2 < no_edges_right && from1 == from2 && to2 < to1)) { /* Edge from second graph */ if (mode==IGRAPH_MODE_UNION) { IGRAPH_CHECK(igraph_vector_push_back(&edges, from2)); IGRAPH_CHECK(igraph_vector_push_back(&edges, to2)); if (edge_map2) { VECTOR(*edge_map2)[edge2]=eptr; } eptr++; } INC2(); } else { /* Edge from both */ IGRAPH_CHECK(igraph_vector_push_back(&edges, from1)); IGRAPH_CHECK(igraph_vector_push_back(&edges, to1)); if (mode==IGRAPH_MODE_UNION) { if (edge_map1) { VECTOR(*edge_map1)[edge1]=eptr; } if (edge_map2) { VECTOR(*edge_map2)[edge2]=eptr; } } else if (mode==IGRAPH_MODE_INTERSECTION) { if (edge_map1) { IGRAPH_CHECK(igraph_vector_push_back(edge_map1, edge1)); } if (edge_map2) { IGRAPH_CHECK(igraph_vector_push_back(edge_map2, edge2)); } } eptr++; INC1(); INC2(); } CONT(); } #undef INC1 #undef INC2 igraph_vector_long_destroy(&order2); igraph_vector_long_destroy(&order1); igraph_vector_destroy(&edges2); igraph_vector_destroy(&edges1); IGRAPH_FINALLY_CLEAN(4); IGRAPH_CHECK(igraph_create(res, &edges, no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_intersection * \brief Collect the common edges from two graphs. * * * The result graph contains only edges present both in the first and * the second graph. The number of vertices in the result graph is the * same as the larger from the two arguments. * * \param res Pointer to an uninitialized graph object. This will * contain the result of the operation. * \param left The first operand, a graph object. * \param right The second operand, a graph object. * \param edge_map1 Null pointer, or an initialized \type igraph_vector_t. * If the latter, then a mapping from the edges of the result graph, to * the edges of the \p left input graph is stored here. * \param edge_map2 Null pointer, or an \type igraph_vector_t. The same * as \p edge_map1, but for the \p right input graph. * \return Error code. * \sa \ref igraph_intersection_many() to calculate the intersection * of many graphs at once, \ref igraph_union(), \ref * igraph_difference() for other operators. * * Time complexity: O(|V|+|E|), |V| is the number of nodes, |E| * is the number of edges in the smaller graph of the two. (The one * containing less vertices is considered smaller.) * * \example examples/simple/igraph_intersection.c */ int igraph_intersection(igraph_t *res, const igraph_t *left, const igraph_t *right, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2) { return igraph_i_merge(res, IGRAPH_MODE_INTERSECTION, left, right, edge_map1, edge_map2); } void igraph_i_union_many_free(igraph_vector_ptr_t *v) { long int i, n=igraph_vector_ptr_size(v); for (i=0; i * This function calculates the intersection of the graphs stored in * the \c graphs argument. Only those edges will be included in the * result graph which are part of every graph in \c graphs. * * * The number of vertices in the result graph will be the maximum * number of vertices in the argument graphs. * * \param res Pointer to an uninitialized graph object, the result of * the operation will be stored here. * \param graphs Pointer vector, contains pointers to graphs objects, * the operands of the intersection operator. * \param edgemaps If not a null pointer, then it must be an initialized * pointer vector and the mappings of edges from the graphs to the * result graph will be stored here, in the same order as * \p graphs. Each mapping is stored in a separate * \type igraph_vector_t object. For the edges that are not in * the intersection, -1 is stored. * \return Error code. * \sa \ref igraph_intersection() for the intersection of two graphs, * \ref igraph_union_many(), \ref igraph_union() and \ref * igraph_difference() for other operators. * * Time complexity: O(|V|+|E|), |V| is the number of vertices, * |E| is the number of edges in the smallest graph (ie. the graph having * the less vertices). */ int igraph_intersection_many(igraph_t *res, const igraph_vector_ptr_t *graphs, igraph_vector_ptr_t *edgemaps) { long int no_of_graphs=igraph_vector_ptr_size(graphs); long int no_of_nodes=0; igraph_bool_t directed=1; igraph_vector_t edges; igraph_vector_ptr_t edge_vects, order_vects; long int i, j, tailfrom = no_of_graphs > 0 ? 0 : -1, tailto=-1; igraph_vector_long_t no_edges; igraph_bool_t allne= no_of_graphs == 0 ? 0 : 1, allsame=0; long int idx=0; /* Check directedness */ if (no_of_graphs != 0) { directed=igraph_is_directed(VECTOR(*graphs)[0]); } for (i=1; i no_of_nodes) { no_of_nodes=n; } VECTOR(no_edges)[i] = igraph_ecount(VECTOR(*graphs)[i]); allne = allne && VECTOR(no_edges)[i] > 0; } if (edgemaps) { for (i=0; i VECTOR(*edges)[j+1]) { long int tmp=VECTOR(*edges)[j]; VECTOR(*edges)[j]=VECTOR(*edges)[j+1]; VECTOR(*edges)[j+1]=tmp; } } } for (k=0; k tailfrom || (from==tailfrom && to > tailto)) { igraph_vector_long_pop_back(VECTOR(order_vects)[j]); if (igraph_vector_long_empty(VECTOR(order_vects)[j])) { allne=0; break; } } else { break; } } if (from != tailfrom || to != tailto) { allsame=0; } } /* Add the edge, if the smallest tail element was present in all graphs. */ if (allsame) { IGRAPH_CHECK(igraph_vector_push_back(&edges, tailfrom)); IGRAPH_CHECK(igraph_vector_push_back(&edges, tailto)); } /* Drop edges matching the smalles tail elements from the order vectors, build edge maps */ if (allne) { for (j=0; j 0) { igraph_i_union_many_free2(&order_vects); igraph_i_union_many_free(&edge_vects); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_long_destroy(&no_edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_CHECK(igraph_create(res, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); if (edgemaps) { IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_union * \brief Calculates the union of two graphs. * * * The number of vertices in the result is that of the larger graph * from the two arguments. The result graph contains edges which are * present in at least one of the operand graphs. * * \param res Pointer to an uninitialized graph object, the result * will be stored here. * \param left The first graph. * \param right The second graph. * \param edge_map1 Pointer to an initialized vector or a null pointer. * If not a null pointer, it will contain a mapping from the edges * of the first argument graph (\p left) to the edges of the * result graph. * \param edge_map2 The same as \p edge_map1, but for the second * graph, \p right. * \return Error code. * \sa \ref igraph_union_many() for the union of many graphs, * \ref igraph_intersection() and \ref igraph_difference() for other * operators. * * Time complexity: O(|V|+|E|), |V| is the number of * vertices, |E| the number of edges in the result graph. * * \example examples/simple/igraph_union.c */ int igraph_union(igraph_t *res, const igraph_t *left, const igraph_t *right, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2) { return igraph_i_merge(res, IGRAPH_MODE_UNION, left, right, edge_map1, edge_map2); } /** * \function igraph_union_many * \brief Creates the union of many graphs. * * * The result graph will contain as many vertices as the largest graph * among the arguments does, and an edge will be included in it if it * is part of at least one operand graph. * * * The directedness of the operand graphs must be the same. * * \param res Pointer to an uninitialized graph object, this will * contain the result. * \param graphs Pointer vector, contains pointers to the operands of * the union operator, graph objects of course. * \param edgemaps If not a null pointer, then it must be an initialized * pointer vector and the mappings of edges from the graphs to the * result graph will be stored here, in the same order as * \p graphs. Each mapping is stored in a separate * \type igraph_vector_t object. * \return Error code. * \sa \ref igraph_union() for the union of two graphs, \ref * igraph_intersection_many(), \ref igraph_intersection() and \ref * igraph_difference for other operators. * * * Time complexity: O(|V|+|E|), |V| is the number of vertices * in largest graph and |E| is the number of edges in the result graph. * * \example examples/simple/igraph_union.c */ int igraph_union_many(igraph_t *res, const igraph_vector_ptr_t *graphs, igraph_vector_ptr_t *edgemaps) { long int no_of_graphs=igraph_vector_ptr_size(graphs); long int no_of_nodes=0; igraph_bool_t directed=1; igraph_vector_t edges; igraph_vector_ptr_t edge_vects, order_vects; igraph_vector_long_t no_edges; long int i, j, tailfrom= no_of_graphs > 0 ? 0 : -1, tailto=-1; long int idx=0; /* Check directedness */ if (no_of_graphs != 0) { directed=igraph_is_directed(VECTOR(*graphs)[0]); no_of_nodes=igraph_vcount(VECTOR(*graphs)[0]); } for (i=1; i no_of_nodes) { no_of_nodes=n; } VECTOR(no_edges)[i] = igraph_ecount(VECTOR(*graphs)[i]); } if (edgemaps) { for (i=0; i VECTOR(*edges)[j+1]) { long int tmp=VECTOR(*edges)[j]; VECTOR(*edges)[j]=VECTOR(*edges)[j+1]; VECTOR(*edges)[j+1]=tmp; } } } for (k=0; k= 0) { /* Get the largest tail element */ tailfrom = tailto = -1; for (j=0; j tailfrom || (from == tailfrom && to > tailto)) { tailfrom = from; tailto = to; } } } if (tailfrom < 0) { continue; } /* add the edge */ IGRAPH_CHECK(igraph_vector_push_back(&edges, tailfrom)); IGRAPH_CHECK(igraph_vector_push_back(&edges, tailto)); /* update edge lists, we just modify the 'order' vectors */ for (j=0; j 0) { igraph_i_union_many_free2(&order_vects); igraph_i_union_many_free(&edge_vects); IGRAPH_FINALLY_CLEAN(2); } igraph_vector_long_destroy(&no_edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_CHECK(igraph_create(res, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); if (edgemaps) { IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_difference * \brief Calculate the difference of two graphs * * * The number of vertices in the result is the number of vertices in * the original graph, ie. the left, first operand. In the results * graph only edges will be included from \c orig which are not * present in \c sub. * * \param res Pointer to an uninitialized graph object, the result * will be stored here. * \param orig The left operand of the operator, a graph object. * \param sub The right operand of the operator, a graph object. * \return Error code. * \sa \ref igraph_intersection() and \ref igraph_union() for other * operators. * * Time complexity: O(|V|+|E|), |V| is the number vertices in * the smaller graph, |E| is the * number of edges in the result graph. * * \example examples/simple/igraph_difference.c */ int igraph_difference(igraph_t *res, const igraph_t *orig, const igraph_t *sub) { /* Quite nasty, but we will use that an edge adjacency list contains the vertices according to the order of the vertex ids at the "other" end of the edge. */ long int no_of_nodes_orig=igraph_vcount(orig); long int no_of_nodes_sub =igraph_vcount(sub); long int no_of_nodes=no_of_nodes_orig; long int smaller_nodes; igraph_bool_t directed=igraph_is_directed(orig); igraph_vector_t edges; igraph_vector_t edge_ids; igraph_vector_int_t *nei1, *nei2; igraph_inclist_t inc_orig, inc_sub; long int i; igraph_integer_t v1, v2; if (directed != igraph_is_directed(sub)) { IGRAPH_ERROR("Cannot subtract directed and undirected graphs", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edge_ids, 0); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_inclist_init(orig, &inc_orig, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &inc_orig); IGRAPH_CHECK(igraph_inclist_init(sub, &inc_sub, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_inclist_destroy, &inc_sub); smaller_nodes=no_of_nodes_orig > no_of_nodes_sub ? no_of_nodes_sub : no_of_nodes_orig; for (i=0; i=0 && n2>=0) { e1=(long int) VECTOR(*nei1)[n1]; e2=(long int) VECTOR(*nei2)[n2]; v1=IGRAPH_OTHER(orig, e1, i); v2=IGRAPH_OTHER(sub, e2, i); if (!directed && v1v2) { IGRAPH_CHECK(igraph_vector_push_back(&edge_ids, e1)); IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, v1)); n1--; } else if (v2>v1) { n2--; } else { n1--; n2--; } } /* Copy remaining edges */ while (n1>=0) { e1=(long int) VECTOR(*nei1)[n1]; v1=IGRAPH_OTHER(orig, e1, i); if (directed || v1 >= i) { IGRAPH_CHECK(igraph_vector_push_back(&edge_ids, e1)); IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, v1)); } n1--; } } /* copy remaining edges, use the previous value of 'i' */ for (; i=0) { e1=(long int) VECTOR(*nei1)[n1]; v1=IGRAPH_OTHER(orig, e1, i); if (directed || v1 >= i) { IGRAPH_CHECK(igraph_vector_push_back(&edge_ids, e1)); IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, v1)); } n1--; } } igraph_inclist_destroy(&inc_sub); igraph_inclist_destroy(&inc_orig); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_create(res, &edges, (igraph_integer_t) no_of_nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); /* Attributes */ if (orig->attr) { IGRAPH_I_ATTRIBUTE_DESTROY(res); IGRAPH_I_ATTRIBUTE_COPY(res, orig, /*graph=*/1, /*vertex=*/1, /*edge=*/0); IGRAPH_CHECK(igraph_i_attribute_permute_edges(orig, res, &edge_ids)); } igraph_vector_destroy(&edge_ids); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_complementer * \brief Create the complementer of a graph * * The complementer graph means that all edges which are * not part of the original graph will be included in the result. * * \param res Pointer to an uninitialized graph object. * \param graph The original graph. * \param loops Whether to add loop edges to the complementer graph. * \return Error code. * \sa \ref igraph_union(), \ref igraph_intersection() and \ref * igraph_difference(). * * Time complexity: O(|V|+|E1|+|E2|), |V| is the number of * vertices in the graph, |E1| is the number of edges in the original * and |E2| in the complementer graph. * * \example examples/simple/igraph_complementer.c */ int igraph_complementer(igraph_t *res, const igraph_t *graph, igraph_bool_t loops) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t edges; igraph_vector_t neis; long int i, j; long int zero=0, *limit; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); if (igraph_is_directed(graph)) { limit=&zero; } else { limit=&i; } for (i=0; i=*limit; j--) { if (igraph_vector_empty(&neis) || j>igraph_vector_tail(&neis)) { IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } else { igraph_vector_pop_back(&neis); } } } else { for (j=no_of_nodes-1; j>=*limit; j--) { if (igraph_vector_empty(&neis) || j>igraph_vector_tail(&neis)) { if (i!=j) { IGRAPH_CHECK(igraph_vector_push_back(&edges, i)); IGRAPH_CHECK(igraph_vector_push_back(&edges, j)); } } else { igraph_vector_pop_back(&neis); } } } } IGRAPH_CHECK(igraph_create(res, &edges, (igraph_integer_t) no_of_nodes, igraph_is_directed(graph))); igraph_vector_destroy(&edges); igraph_vector_destroy(&neis); IGRAPH_I_ATTRIBUTE_DESTROY(res); IGRAPH_I_ATTRIBUTE_COPY(res, graph, /*graph=*/1, /*vertex=*/1, /*edge=*/0); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_compose * \brief Calculates the composition of two graphs * * The composition of graphs contains the same number of vertices as * the bigger graph of the two operands. It contains an (i,j) edge if * and only if there is a k vertex, such that the first graphs * contains an (i,k) edge and the second graph a (k,j) edge. * * This is of course exactly the composition of two * binary relations. * * Two two graphs must have the same directedness, * otherwise the function returns with an error message. * Note that for undirected graphs the two relations are by definition * symmetric. * * \param res Pointer to an uninitialized graph object, the result * will be stored here. * \param g1 The firs operand, a graph object. * \param g2 The second operand, another graph object. * \param edge_map1 If not a null pointer, then it must be a pointer * to an initialized vector, and a mapping from the edges of * the result graph to the edges of the first graph is stored * here. * \param edge_map1 If not a null pointer, then it must be a pointer * to an initialized vector, and a mapping from the edges of * the result graph to the edges of the second graph is stored * here. * \return Error code. * * Time complexity: O(|V|*d1*d2), |V| is the number of vertices in the * first graph, d1 and d2 the average degree in the first and second * graphs. * * \example examples/simple/igraph_compose.c */ int igraph_compose(igraph_t *res, const igraph_t *g1, const igraph_t *g2, igraph_vector_t *edge_map1, igraph_vector_t *edge_map2) { long int no_of_nodes_left=igraph_vcount(g1); long int no_of_nodes_right=igraph_vcount(g2); long int no_of_nodes; igraph_bool_t directed=igraph_is_directed(g1); igraph_vector_t edges; igraph_vector_t neis1, neis2; long int i; if (directed != igraph_is_directed(g2)) { IGRAPH_ERROR("Cannot compose directed and undirected graph", IGRAPH_EINVAL); } no_of_nodes= no_of_nodes_left > no_of_nodes_right ? no_of_nodes_left : no_of_nodes_right; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis1, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis2, 0); if (edge_map1) { igraph_vector_clear(edge_map1); } if (edge_map2) { igraph_vector_clear(edge_map2); } for (i=0; i 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_constructors.h" #include "igraph_structural.h" #include "igraph_memory.h" #include "igraph_interface.h" #include "igraph_attributes.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_dqueue.h" #include "config.h" #include #include #include /** * \section about_generators * * Graph generators create graphs. * * Almost all functions which create graph objects are documented * here. The exceptions are \ref igraph_subgraph() and alike, these * create graphs based on another graph. */ /** * \ingroup generators * \function igraph_create * \brief Creates a graph with the specified edges. * * \param graph An uninitialized graph object. * \param edges The edges to add, the first two elements are the first * edge, etc. * \param n The number of vertices in the graph, if smaller or equal * to the highest vertex id in the \p edges vector it * will be increased automatically. So it is safe to give 0 * here. * \param directed Boolean, whether to create a directed graph or * not. If yes, then the first edge points from the first * vertex id in \p edges to the second, etc. * \return Error code: * \c IGRAPH_EINVEVECTOR: invalid edges * vector (odd number of vertices). * \c IGRAPH_EINVVID: invalid (negative) * vertex id. * * Time complexity: O(|V|+|E|), * |V| is the number of vertices, * |E| the number of edges in the * graph. * * \example examples/simple/igraph_create.c */ int igraph_create(igraph_t *graph, const igraph_vector_t *edges, igraph_integer_t n, igraph_bool_t directed) { igraph_bool_t has_edges=igraph_vector_size(edges) > 0; igraph_real_t max=has_edges ? igraph_vector_max(edges)+1 : 0; if (igraph_vector_size(edges) % 2 != 0) { IGRAPH_ERROR("Invalid (odd) edges vector", IGRAPH_EINVEVECTOR); } if (has_edges && !igraph_vector_isininterval(edges, 0, max-1)) { IGRAPH_ERROR("Invalid (negative) vertex id", IGRAPH_EINVVID); } IGRAPH_CHECK(igraph_empty(graph, n, directed)); IGRAPH_FINALLY(igraph_destroy, graph); if (has_edges) { igraph_integer_t vc=igraph_vcount(graph); if (vc < max) { IGRAPH_CHECK(igraph_add_vertices(graph, (igraph_integer_t) (max-vc), 0)); } IGRAPH_CHECK(igraph_add_edges(graph, edges, 0)); } IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_adjacency_directed(igraph_matrix_t *adjmatrix, igraph_vector_t *edges); int igraph_i_adjacency_max(igraph_matrix_t *adjmatrix, igraph_vector_t *edges); int igraph_i_adjacency_upper(igraph_matrix_t *adjmatrix, igraph_vector_t *edges); int igraph_i_adjacency_lower(igraph_matrix_t *adjmatrix, igraph_vector_t *edges); int igraph_i_adjacency_min(igraph_matrix_t *adjmatrix, igraph_vector_t *edges); int igraph_i_adjacency_directed(igraph_matrix_t *adjmatrix, igraph_vector_t *edges) { long int no_of_nodes=igraph_matrix_nrow(adjmatrix); long int i, j, k; for (i=0; iM2) { M1=M2; } for (k=0; kM2) { M1=M2; } if (M1 == 0.0) continue; if (i==j && !loops) { continue; } IGRAPH_CHECK(igraph_vector_push_back(edges, i)); IGRAPH_CHECK(igraph_vector_push_back(edges, j)); IGRAPH_CHECK(igraph_vector_push_back(weights, M1)); } } return 0; } /** * \ingroup generators * \function igraph_weighted_adjacency * \brief Creates a graph object from a weighted adjacency matrix. * * The order of the vertices in the matrix is preserved, i.e. the vertex * corresponding to the first row/column will be vertex with id 0, the * next row is for vertex 1, etc. * \param graph Pointer to an uninitialized graph object. * \param adjmatrix The weighted adjacency matrix. How it is interpreted * depends on the \p mode argument. The common feature is that * edges with zero weights are considered nonexistent (however, * negative weights are permitted). * \param mode Constant to specify how the given matrix is interpreted * as an adjacency matrix. Possible values * (A(i,j) * is the element in row i and column * j in the adjacency matrix * \p adjmatrix): * \clist * \cli IGRAPH_ADJ_DIRECTED * the graph will be directed and * an element gives the weight of the edge between two vertices. * \cli IGRAPH_ADJ_UNDIRECTED * this is the same as \c IGRAPH_ADJ_MAX, * for convenience. * \cli IGRAPH_ADJ_MAX * undirected graph will be created * and the weight of the edge between vertices * i and * j is * max(A(i,j), A(j,i)). * \cli IGRAPH_ADJ_MIN * undirected graph will be created * with edge weight min(A(i,j), A(j,i)) * between vertices * i and * j. * \cli IGRAPH_ADJ_PLUS * undirected graph will be created * with edge weight A(i,j)+A(j,i) * between vertices * i and * j. * \cli IGRAPH_ADJ_UPPER * undirected graph will be created, * only the upper right triangle (including the diagonal) is * used for the edge weights. * \cli IGRAPH_ADJ_LOWER * undirected graph will be created, * only the lower left triangle (including the diagonal) is * used for the edge weights. * \endclist * \param attr the name of the attribute that will store the edge weights. * If \c NULL , it will use \c weight as the attribute name. * \param loops Logical scalar, whether to ignore the diagonal elements * in the adjacency matrix. * \return Error code, * \c IGRAPH_NONSQUARE: non-square matrix. * * Time complexity: O(|V||V|), * |V| is the number of vertices in the graph. * * \example examples/simple/igraph_weighted_adjacency.c */ int igraph_weighted_adjacency(igraph_t *graph, igraph_matrix_t *adjmatrix, igraph_adjacency_t mode, const char* attr, igraph_bool_t loops) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; igraph_vector_t weights=IGRAPH_VECTOR_NULL; const char* default_attr = "weight"; igraph_vector_ptr_t attr_vec; igraph_attribute_record_t attr_rec; long int no_of_nodes; /* Some checks */ if (igraph_matrix_nrow(adjmatrix) != igraph_matrix_ncol(adjmatrix)) { IGRAPH_ERROR("Non-square matrix", IGRAPH_NONSQUARE); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&weights, 0); IGRAPH_VECTOR_PTR_INIT_FINALLY(&attr_vec, 1); /* Collect the edges */ no_of_nodes=igraph_matrix_nrow(adjmatrix); switch (mode) { case IGRAPH_ADJ_DIRECTED: IGRAPH_CHECK(igraph_i_weighted_adjacency_directed(adjmatrix, &edges, &weights, loops)); break; case IGRAPH_ADJ_MAX: IGRAPH_CHECK(igraph_i_weighted_adjacency_max(adjmatrix, &edges, &weights, loops)); break; case IGRAPH_ADJ_UPPER: IGRAPH_CHECK(igraph_i_weighted_adjacency_upper(adjmatrix, &edges, &weights, loops)); break; case IGRAPH_ADJ_LOWER: IGRAPH_CHECK(igraph_i_weighted_adjacency_lower(adjmatrix, &edges, &weights, loops)); break; case IGRAPH_ADJ_MIN: IGRAPH_CHECK(igraph_i_weighted_adjacency_min(adjmatrix, &edges, &weights, loops)); break; case IGRAPH_ADJ_PLUS: IGRAPH_CHECK(igraph_i_weighted_adjacency_plus(adjmatrix, &edges, &weights, loops)); break; } /* Prepare attribute record */ attr_rec.name = attr ? attr : default_attr; attr_rec.type = IGRAPH_ATTRIBUTE_NUMERIC; attr_rec.value = &weights; VECTOR(attr_vec)[0] = &attr_rec; /* Create graph */ IGRAPH_CHECK(igraph_empty(graph, (igraph_integer_t) no_of_nodes, (mode == IGRAPH_ADJ_DIRECTED))); IGRAPH_FINALLY(igraph_destroy, graph); if (igraph_vector_size(&edges)>0) { IGRAPH_CHECK(igraph_add_edges(graph, &edges, &attr_vec)); } IGRAPH_FINALLY_CLEAN(1); /* Cleanup */ igraph_vector_destroy(&edges); igraph_vector_destroy(&weights); igraph_vector_ptr_destroy(&attr_vec); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup generators * \function igraph_star * \brief Creates a \em star graph, every vertex connects only to the center. * * \param graph Pointer to an uninitialized graph object, this will * be the result. * \param n Integer constant, the number of vertices in the graph. * \param mode Constant, gives the type of the star graph to * create. Possible values: * \clist * \cli IGRAPH_STAR_OUT * directed star graph, edges point * \em from the center to the other vertices. * \cli IGRAPH_STAR_IN * directed star graph, edges point * \em to the center from the other vertices. * \cli IGRAPH_STAR_MUTUAL * directed star graph with mutual edges. * \cli IGRAPH_STAR_UNDIRECTED * an undirected star graph is * created. * \endclist * \param center Id of the vertex which will be the center of the * graph. * \return Error code: * \clist * \cli IGRAPH_EINVVID * invalid number of vertices. * \cli IGRAPH_EINVAL * invalid center vertex. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|V|), the * number of vertices in the graph. * * \sa \ref igraph_lattice(), \ref igraph_ring(), \ref igraph_tree() * for creating other regular structures. * * \example examples/simple/igraph_star.c */ int igraph_star(igraph_t *graph, igraph_integer_t n, igraph_star_mode_t mode, igraph_integer_t center) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int i; if (n<0) { IGRAPH_ERROR("Invalid number of vertices", IGRAPH_EINVVID); } if (center<0 || center >n-1) { IGRAPH_ERROR("Invalid center vertex", IGRAPH_EINVAL); } if (mode != IGRAPH_STAR_OUT && mode != IGRAPH_STAR_IN && mode != IGRAPH_STAR_MUTUAL && mode != IGRAPH_STAR_UNDIRECTED) { IGRAPH_ERROR("invalid mode", IGRAPH_EINVMODE); } if (mode != IGRAPH_STAR_MUTUAL) { IGRAPH_VECTOR_INIT_FINALLY(&edges, (n-1)*2); } else { IGRAPH_VECTOR_INIT_FINALLY(&edges, (n-1)*2*2); } if (mode == IGRAPH_STAR_OUT) { for (i=0; i 0) { weights[0]=1; for (i=1; i= 2) { IGRAPH_CHECK(igraph_connect_neighborhood(graph, nei, IGRAPH_ALL)); } /* clean up */ igraph_Free(coords); igraph_Free(weights); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup generators * \function igraph_ring * \brief Creates a \em ring graph, a one dimensional lattice. * * An undirected (circular) ring on n vertices is commonly known in graph * theory as the cycle graph C_n. * * \param graph Pointer to an uninitialized graph object. * \param n The number of vertices in the ring. * \param directed Logical, whether to create a directed ring. * \param mutual Logical, whether to create mutual edges in a directed * ring. It is ignored for undirected graphs. * \param circular Logical, if false, the ring will be open (this is * not a real \em ring actually). * \return Error code: * \c IGRAPH_EINVAL: invalid number of vertices. * * Time complexity: O(|V|), the * number of vertices in the graph. * * \sa \ref igraph_lattice() for generating more general lattices. * * \example examples/simple/igraph_ring.c */ int igraph_ring(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, igraph_bool_t mutual, igraph_bool_t circular) { igraph_vector_t v=IGRAPH_VECTOR_NULL; if (n<0) { IGRAPH_ERROR("negative number of vertices", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&v, 1); VECTOR(v)[0]=n; IGRAPH_CHECK(igraph_lattice(graph, &v, 1, directed, mutual, circular)); igraph_vector_destroy(&v); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup generators * \function igraph_tree * \brief Creates a tree in which almost all vertices have the same number of children. * * \param graph Pointer to an uninitialized graph object. * \param n Integer, the number of vertices in the graph. * \param children Integer, the number of children of a vertex in the * tree. * \param type Constant, gives whether to create a directed tree, and * if this is the case, also its orientation. Possible values: * \clist * \cli IGRAPH_TREE_OUT * directed tree, the edges point * from the parents to their children, * \cli IGRAPH_TREE_IN * directed tree, the edges point from * the children to their parents. * \cli IGRAPH_TREE_UNDIRECTED * undirected tree. * \endclist * \return Error code: * \c IGRAPH_EINVAL: invalid number of vertices. * \c IGRAPH_INVMODE: invalid mode argument. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges in the graph. * * \sa \ref igraph_lattice(), \ref igraph_star() for creating other regular * structures. * * \example examples/simple/igraph_tree.c */ int igraph_tree(igraph_t *graph, igraph_integer_t n, igraph_integer_t children, igraph_tree_mode_t type) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int i, j; long int idx=0; long int to=1; if (n<0 || children<=0) { IGRAPH_ERROR("Invalid number of vertices or children", IGRAPH_EINVAL); } if (type != IGRAPH_TREE_OUT && type != IGRAPH_TREE_IN && type != IGRAPH_TREE_UNDIRECTED) { IGRAPH_ERROR("Invalid mode argument", IGRAPH_EINVMODE); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 2*(n-1)); i=0; if (type == IGRAPH_TREE_OUT) { while (idx<2*(n-1)) { for (j=0; j * In a full graph every possible edge is present, every vertex is * connected to every other vertex. A full graph in \c igraph should be * distinguished from the concept of complete graphs as used in graph theory. * If n is a positive integer, then the complete graph K_n on n vertices is * the undirected simple graph with the following property. For any distinct * pair (u,v) of vertices in K_n, uv (or equivalently vu) is an edge of K_n. * In \c igraph, a full graph on n vertices can be K_n, a directed version of * K_n, or K_n with at least one loop edge. In any case, if F is a full graph * on n vertices as generated by \c igraph, then K_n is a subgraph of the * undirected version of F. * * \param graph Pointer to an uninitialized graph object. * \param n Integer, the number of vertices in the graph. * \param directed Logical, whether to create a directed graph. * \param loops Logical, whether to include self-edges (loops). * \return Error code: * \c IGRAPH_EINVAL: invalid number of vertices. * * Time complexity: O(|V|+|E|), * |V| is the number of vertices, * |E| the number of edges in the * graph. Of course this is the same as * O(|E|)=O(|V||V|) * here. * * \sa \ref igraph_lattice(), \ref igraph_star(), \ref igraph_tree() * for creating other regular structures. * * \example examples/simple/igraph_full.c */ int igraph_full(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, igraph_bool_t loops) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int i, j; if (n<0) { IGRAPH_ERROR("invalid number of vertices", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); if (directed && loops) { IGRAPH_CHECK(igraph_vector_reserve(&edges, n*n)); for (i=0; ii->j
edge is * present if and only if j<i. * If the \c directed argument is zero then an undirected graph is * created, and it is just a full graph. * \param graph Pointer to an uninitialized graph object, the result * is stored here. * \param n The number of vertices. * \param directed Whether to created a directed graph. If zero an * undirected graph is created. * \return Error code. * * Time complexity: O(|V|^2), as we have many edges. */ int igraph_full_citation(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed) { igraph_vector_t edges; long int i, j, ptr=0; IGRAPH_VECTOR_INIT_FINALLY(&edges, n*(n-1)); for (i=1; i * This function is handy when a relatively small graph needs to be created. * Instead of giving the edges as a vector, they are given simply as * arguments and a '-1' needs to be given after the last meaningful * edge argument. * * Note that only graphs which have vertices less than * the highest value of the 'int' type can be created this way. If you * give larger values then the result is undefined. * * \param graph Pointer to an uninitialized graph object. The result * will be stored here. * \param n The number of vertices in the graph; a nonnegative integer. * \param directed Logical constant; gives whether the graph should be * directed. Supported values are: * \clist * \cli IGRAPH_DIRECTED * The graph to be created will be \em directed. * \cli IGRAPH_UNDIRECTED * The graph to be created will be \em undirected. * \endclist * \param ... The additional arguments giving the edges of the * graph. Don't forget to supply an additional '-1' after the last * (meaningful) argument. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges in the graph to create. * * \example examples/simple/igraph_small.c */ int igraph_small(igraph_t *graph, igraph_integer_t n, igraph_bool_t directed, ...) { igraph_vector_t edges; va_list ap; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); va_start(ap, directed); while (1) { int num = va_arg(ap, int); if (num == -1) { break; } igraph_vector_push_back(&edges, num); } IGRAPH_CHECK(igraph_create(graph, &edges, n, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_extended_chordal_ring * Create an extended chordal ring * * An extended chordal ring is a regular graph, each node has the same * degree. It can be obtained from a simple ring by adding some extra * edges specified by a matrix. Let p denote the number of columns in * the W matrix. The extra edges of vertex i * are added according to column (i mod p) in * W. The number of extra edges is the number * of rows in W: for each row j an edge * i->i+w[ij] is added if i+w[ij] is less than the number of total * nodes. * * * See also Kotsis, G: Interconnection Topologies for Parallel Processing * Systems, PARS Mitteilungen 11, 1-6, 1993. * * \param graph Pointer to an uninitialized graph object, the result * will be stored here. The result is always an undirected graph. * \param nodes Integer constant, the number of vertices in the * graph. It must be at least 3. * \param W The matrix specifying the extra edges. The number of * columns should divide the number of total vertices. * \return Error code. * * \sa \ref igraph_ring(). * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. */ int igraph_extended_chordal_ring(igraph_t *graph, igraph_integer_t nodes, const igraph_matrix_t *W) { igraph_vector_t edges; long int period=igraph_matrix_ncol(W); long int degree=igraph_matrix_nrow(W)+2; long int i, j, mpos=0, epos=0; if (nodes<3) { IGRAPH_ERROR("An extended chordal ring has at least 3 nodes", IGRAPH_EINVAL); } if ((long int)nodes % period != 0) { IGRAPH_ERROR("The period (number of columns in W) should divide the " "number of nodes", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, nodes*degree); for (i=0; i 2) { for (i=0; i Note that the input graph is modified in place, no * new graph is created. Call \ref igraph_copy() if you want to keep * the original graph as well. * * For undirected graphs reachability is always * symmetric: if vertex A can be reached from vertex B in at * most \p order steps, then the opposite is also true. Only one * undirected (A,B) edge will be added in this case. * \param graph The input graph, this is the output graph as well. * \param order Integer constant, it gives the distance within which * the vertices will be connected to the source vertex. * \param mode Constant, it specifies how the neighborhood search is * performed for directed graphs. If \c IGRAPH_OUT then vertices * reachable from the source vertex will be connected, \c IGRAPH_IN * is the opposite. If \c IGRAPH_ALL then the directed graph is * considered as an undirected one. * \return Error code. * * \sa \ref igraph_lattice() uses this function to connect the * neighborhood of the vertices. * * Time complexity: O(|V|*d^k), |V| is the number of vertices in the * graph, d is the average degree and k is the \p order argument. */ int igraph_connect_neighborhood(igraph_t *graph, igraph_integer_t order, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q; igraph_vector_t edges; long int i, j, in; long int *added; igraph_vector_t neis; if (order<0) { IGRAPH_ERROR("Negative order, cannot connect neighborhood", IGRAPH_EINVAL); } if (order<2) { IGRAPH_WARNING("Order smaller than two, graph will be unchanged"); } if (!igraph_is_directed(graph)) { mode=IGRAPH_ALL; } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot connect neighborhood", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); for (i=0; i 1) { for (j=0; j * Please note that the graph will have \c m to the power \c n vertices and * even more edges, so probably you don't want to supply too big numbers for * \c m and \c n. * * * De Bruijn graphs have some interesting properties, please see another source, * eg. Wikipedia for details. * * \param graph Pointer to an uninitialized graph object, the result will be * stored here. * \param m Integer, the number of letters in the alphabet. * \param n Integer, the length of the strings. * \return Error code. * * \sa \ref igraph_kautz(). * * Time complexity: O(|V|+|E|), the number of vertices plus the number of edges. */ int igraph_de_bruijn(igraph_t *graph, igraph_integer_t m, igraph_integer_t n) { /* m - number of symbols */ /* n - length of strings */ long int no_of_nodes, no_of_edges; igraph_vector_t edges; long int i, j; long int mm=m; if (m<0 || n<0) { IGRAPH_ERROR("`m' and `n' should be non-negative in a de Bruijn graph", IGRAPH_EINVAL); } if (n==0) { return igraph_empty(graph, 1, IGRAPH_DIRECTED); } if (m==0) { return igraph_empty(graph, 0, IGRAPH_DIRECTED); } no_of_nodes=(long int) pow(m, n); no_of_edges=no_of_nodes*m; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); for (i=0; i * Kautz graphs have some interesting properties, see eg. Wikipedia * for details. * * * Vincent Matossian wrote the first version of this function in R, * thanks. * \param graph Pointer to an uninitialized graph object, the result * will be stored here. * \param m Integer, \c m+1 is the number of letters in the alphabet. * \param n Integer, \c n+1 is the length of the strings. * \return Error code. * * \sa \ref igraph_de_bruijn(). * * Time complexity: O(|V|* [(m+1)/m]^n +|E|), in practice it is more * like O(|V|+|E|). |V| is the number of vertices, |E| is the number * of edges and \c m and \c n are the corresponding arguments. */ int igraph_kautz(igraph_t *graph, igraph_integer_t m, igraph_integer_t n) { /* m+1 - number of symbols */ /* n+1 - length of strings */ long int mm=m; long int no_of_nodes, no_of_edges; long int allstrings; long int i, j, idx=0; igraph_vector_t edges; igraph_vector_long_t digits, table; igraph_vector_long_t index1, index2; long int actb=0; long int actvalue=0; if (m<0 || n<0) { IGRAPH_ERROR("`m' and `n' should be non-negative in a Kautz graph", IGRAPH_EINVAL); } if (n==0) { return igraph_full(graph, m+1, IGRAPH_DIRECTED, IGRAPH_NO_LOOPS); } if (m==0) { return igraph_empty(graph, 0, IGRAPH_DIRECTED); } no_of_nodes=(long int) ((m+1)*pow(m, n)); no_of_edges=no_of_nodes*m; allstrings=(long int) pow(m+1, n+1); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_long_init(&table, n+1)); IGRAPH_FINALLY(igraph_vector_long_destroy, &table); j=1; for (i=n; i>=0; i--) { VECTOR(table)[i]=j; j *= (m+1); } IGRAPH_CHECK(igraph_vector_long_init(&digits, n+1)); IGRAPH_FINALLY(igraph_vector_long_destroy, &digits); IGRAPH_CHECK(igraph_vector_long_init(&index1, (long int) pow(m+1, n+1))); IGRAPH_FINALLY(igraph_vector_long_destroy, &index1); IGRAPH_CHECK(igraph_vector_long_init(&index2, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &index2); /* Fill the index tables*/ while (1) { /* at the beginning of the loop, 0:actb contain the valid prefix */ /* we might need to fill it to get a valid string */ long int z=0; if (VECTOR(digits)[actb]==0) { z=1; } for (actb++; actb<=n; actb++) { VECTOR(digits)[actb]=z; actvalue += z*VECTOR(table)[actb]; z=1-z; } actb=n; /* ok, we have a valid string now */ VECTOR(index1)[actvalue]=idx+1; VECTOR(index2)[idx]=actvalue; idx++; /* finished? */ if (idx >= no_of_nodes) { break; } /* not yet, we need a valid prefix now */ while (1) { /* try to increase digits at position actb */ long int next=VECTOR(digits)[actb]+1; if (actb != 0 && VECTOR(digits)[actb-1]==next) { next++; } if (next <= m) { /* ok, no problem */ actvalue += (next-VECTOR(digits)[actb])*VECTOR(table)[actb]; VECTOR(digits)[actb]=next; break; } else { /* bad luck, try the previous digit */ actvalue -= VECTOR(digits)[actb]*VECTOR(table)[actb]; actb--; } } } IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); /* Now come the edges at last */ for (i=0; i 0) { /* Create a ring first */ for (i=0; i * LCF is short for Lederberg-Coxeter-Frucht, it is a concise notation for * 3-regular Hamiltonian graphs. It consists of three parameters: the * number of vertices in the graph, a list of shifts giving additional * edges to a cycle backbone, and another integer giving how many times * the shifts should be performed. See * http://mathworld.wolfram.com/LCFNotation.html for details. * * \param graph Pointer to an uninitialized graph object. * \param n Integer, the number of vertices in the graph. * \param ... The shifts and the number of repeats for the shifts, * plus an additional 0 to mark the end of the arguments. * \return Error code. * * \sa See \ref igraph_lcf_vector() for a similar function using a * vector_t instead of the variable length argument list. * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. * * \example examples/simple/igraph_lcf.c */ int igraph_lcf(igraph_t *graph, igraph_integer_t n, ...) { igraph_vector_t shifts; igraph_integer_t repeats; va_list ap; IGRAPH_VECTOR_INIT_FINALLY(&shifts, 0); va_start(ap, n); while (1) { int num=va_arg(ap, int); if (num==0) { break; } IGRAPH_CHECK(igraph_vector_push_back(&shifts, num)); } if (igraph_vector_size(&shifts)==0) { repeats=0; } else { repeats=(igraph_integer_t) igraph_vector_pop_back(&shifts); } IGRAPH_CHECK(igraph_lcf_vector(graph, n, &shifts, repeats)); igraph_vector_destroy(&shifts); IGRAPH_FINALLY_CLEAN(1); return 0; } const igraph_real_t igraph_i_famous_bull[] = { 5, 5, 0, 0,1,0,2,1,2,1,3,2,4 }; const igraph_real_t igraph_i_famous_chvatal[] = { 12, 24, 0, 5, 6, 6, 7, 7, 8, 8, 9, 5, 9, 4, 5, 4, 8, 2, 8, 2, 6, 0, 6, 0, 9, 3, 9, 3, 7, 1, 7, 1, 5, 1, 10, 4, 10, 4, 11, 2, 11, 0, 10, 0, 11, 3, 11, 3, 10, 1, 2 }; const igraph_real_t igraph_i_famous_coxeter[] = { 28, 42, 0, 0, 1, 0, 2, 0, 7, 1, 4, 1, 13, 2, 3, 2, 8, 3, 6, 3, 9, 4, 5, 4, 12, 5, 6, 5, 11, 6, 10, 7, 19, 7, 24, 8, 20, 8, 23, 9, 14, 9, 22, 10, 15, 10, 21, 11, 16, 11, 27, 12, 17, 12, 26, 13, 18, 13, 25, 14, 17, 14, 18, 15, 18, 15, 19, 16, 19, 16, 20, 17, 20, 21, 23, 21, 26, 22, 24, 22, 27, 23, 25, 24, 26, 25, 27 }; const igraph_real_t igraph_i_famous_cubical[] = { 8, 12, 0, 0, 1, 1, 2, 2, 3, 0, 3, 4, 5, 5, 6, 6, 7, 4, 7, 0, 4, 1, 5, 2, 6, 3, 7 }; const igraph_real_t igraph_i_famous_diamond[] = { 4, 5, 0, 0,1,0,2,1,2,1,3,2,3 }; const igraph_real_t igraph_i_famous_dodecahedron[] = { 20, 30, 0, 0, 1, 0, 4, 0, 5, 1, 2, 1, 6, 2, 3, 2, 7, 3, 4, 3, 8, 4, 9, 5, 10, 5, 11, 6, 10, 6, 14, 7, 13, 7, 14, 8, 12, 8, 13, 9, 11, 9, 12, 10, 15, 11, 16, 12, 17, 13, 18, 14, 19, 15, 16, 15, 19, 16, 17, 17, 18, 18, 19 }; const igraph_real_t igraph_i_famous_folkman[] = { 20, 40, 0, 0, 5, 0, 8, 0, 10, 0, 13, 1, 7, 1, 9, 1, 12, 1, 14, 2, 6, 2, 8, 2, 11, 2, 13, 3, 5, 3, 7, 3, 10, 3, 12, 4, 6, 4, 9, 4, 11, 4, 14, 5, 15, 5, 19, 6, 15, 6, 16, 7, 16, 7, 17, 8, 17, 8, 18, 9, 18, 9, 19, 10, 15, 10, 19, 11, 15, 11, 16, 12, 16, 12, 17, 13, 17, 13, 18, 14, 18, 14, 19 }; const igraph_real_t igraph_i_famous_franklin[] = { 12, 18, 0, 0, 1, 0, 2, 0, 6, 1, 3, 1, 7, 2, 4, 2, 10, 3, 5, 3, 11, 4, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 9, 8, 11, 9, 10, 10, 11 }; const igraph_real_t igraph_i_famous_frucht[] = { 12, 18, 0, 0, 1, 0, 2, 0, 11, 1, 3, 1, 6, 2, 5, 2, 10, 3, 4, 3, 6, 4, 8, 4, 11, 5, 9, 5, 10, 6, 7, 7, 8, 7, 9, 8, 9, 10, 11 }; const igraph_real_t igraph_i_famous_grotzsch[] = { 11, 20, 0, 0, 1, 0, 2, 0, 7, 0, 10, 1, 3, 1, 6, 1, 9, 2, 4, 2, 6, 2, 8, 3, 4, 3, 8, 3, 10, 4, 7, 4, 9, 5, 6, 5, 7, 5, 8, 5, 9, 5, 10 }; const igraph_real_t igraph_i_famous_heawood[] = { 14, 21, 0, 0, 1, 0, 5, 0, 13, 1, 2, 1, 10, 2, 3, 2, 7, 3, 4, 3, 12, 4, 5, 4, 9, 5, 6, 6, 7, 6, 11, 7, 8, 8, 9, 8, 13, 9, 10, 10, 11, 11, 12, 12, 13 }; const igraph_real_t igraph_i_famous_herschel[] = { 11, 18, 0, 0, 2, 0, 3, 0, 4, 0, 5, 1, 2, 1, 3, 1, 6, 1, 7, 2, 10, 3, 9, 4, 8, 4, 9, 5, 8, 5, 10, 6, 8, 6, 9, 7, 8, 7, 10 }; const igraph_real_t igraph_i_famous_house[] = { 5, 6, 0, 0,1,0,2,1,3,2,3,2,4,3,4 }; const igraph_real_t igraph_i_famous_housex[] = { 5, 8, 0, 0,1,0,2,0,3,1,2,1,3,2,3,2,4,3,4 }; const igraph_real_t igraph_i_famous_icosahedron[] = { 12, 30, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 8, 1, 2, 1, 6, 1, 7, 1, 8, 2, 4, 2, 5, 2, 6, 3, 4, 3, 8, 3, 9, 3, 11, 4, 5, 4, 11, 5, 6, 5, 10, 5, 11, 6, 7, 6, 10, 7, 8, 7, 9, 7, 10, 8, 9, 9, 10, 9, 11, 10, 11 }; const igraph_real_t igraph_i_famous_krackhardt_kite[] = { 10,18,0, 0,1,0,2,0,3,0,5, 1,3,1,4,1,6, 2,3,2,5, 3,4,3,5,3,6, 4,6, 5,6,5,7, 6,7, 7,8, 8,9 }; const igraph_real_t igraph_i_famous_levi[] = { 30, 45, 0, 0, 1, 0, 7, 0, 29, 1, 2, 1, 24, 2, 3, 2, 11, 3, 4, 3, 16, 4, 5, 4, 21, 5, 6, 5, 26, 6, 7, 6, 13, 7, 8, 8, 9, 8, 17, 9, 10, 9, 22, 10, 11, 10, 27, 11, 12, 12, 13, 12, 19, 13, 14, 14, 15, 14, 23, 15, 16, 15, 28, 16, 17, 17, 18, 18, 19, 18, 25, 19, 20, 20, 21, 20, 29, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29 }; const igraph_real_t igraph_i_famous_mcgee[] = { 24, 36, 0, 0, 1, 0, 7, 0, 23, 1, 2, 1, 18, 2, 3, 2, 14, 3, 4, 3, 10, 4, 5, 4, 21, 5, 6, 5, 17, 6, 7, 6, 13, 7, 8, 8, 9, 8, 20, 9, 10, 9, 16, 10, 11, 11, 12, 11, 23, 12, 13, 12, 19, 13, 14, 14, 15, 15, 16, 15, 22, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23 }; const igraph_real_t igraph_i_famous_meredith[] = { 70, 140, 0, 0, 4, 0, 5, 0, 6, 1, 4, 1, 5, 1, 6, 2, 4, 2, 5, 2, 6, 3, 4, 3, 5, 3, 6, 7, 11, 7, 12, 7, 13, 8, 11, 8, 12, 8, 13, 9, 11, 9, 12, 9, 13, 10, 11, 10, 12, 10, 13, 14, 18, 14, 19, 14, 20, 15, 18, 15, 19, 15, 20, 16, 18, 16, 19, 16, 20, 17, 18, 17, 19, 17, 20, 21, 25, 21, 26, 21, 27, 22, 25, 22, 26, 22, 27, 23, 25, 23, 26, 23, 27, 24, 25, 24, 26, 24, 27, 28, 32, 28, 33, 28, 34, 29, 32, 29, 33, 29, 34, 30, 32, 30, 33, 30, 34, 31, 32, 31, 33, 31, 34, 35, 39, 35, 40, 35, 41, 36, 39, 36, 40, 36, 41, 37, 39, 37, 40, 37, 41, 38, 39, 38, 40, 38, 41, 42, 46, 42, 47, 42, 48, 43, 46, 43, 47, 43, 48, 44, 46, 44, 47, 44, 48, 45, 46, 45, 47, 45, 48, 49, 53, 49, 54, 49, 55, 50, 53, 50, 54, 50, 55, 51, 53, 51, 54, 51, 55, 52, 53, 52, 54, 52, 55, 56, 60, 56, 61, 56, 62, 57, 60, 57, 61, 57, 62, 58, 60, 58, 61, 58, 62, 59, 60, 59, 61, 59, 62, 63, 67, 63, 68, 63, 69, 64, 67, 64, 68, 64, 69, 65, 67, 65, 68, 65, 69, 66, 67, 66, 68, 66, 69, 2, 50, 1, 51, 9, 57, 8, 58, 16, 64, 15, 65, 23, 36, 22, 37, 30, 43, 29, 44, 3, 21, 7, 24, 14, 31, 0, 17, 10, 28, 38, 42, 35, 66, 59, 63, 52, 56, 45, 49 }; const igraph_real_t igraph_i_famous_noperfectmatching[] = { 16, 27, 0, 0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3, 2, 4, 3, 4, 4, 5, 5, 6, 5, 7, 6, 12, 6, 13, 7, 8, 7, 9, 8, 9, 8, 10, 8, 11, 9, 10, 9, 11, 10, 11, 12, 13, 12, 14, 12, 15, 13, 14, 13, 15, 14, 15 }; const igraph_real_t igraph_i_famous_nonline[] = { 50, 72, 0, 0, 1, 0, 2, 0, 3, 4, 6, 4, 7, 5, 6, 5, 7, 6, 7, 7, 8, 9, 11, 9, 12, 9, 13, 10, 11, 10, 12, 10, 13, 11, 12, 11, 13, 12, 13, 14, 15, 15, 16, 15, 17, 16, 17, 16, 18, 17, 18, 18, 19, 20, 21, 20, 22, 20, 23, 21, 22, 21, 23, 21, 24, 22, 23, 22, 24, 24, 25, 26, 27, 26, 28, 26, 29, 27, 28, 27, 29, 27, 30, 27, 31, 28, 29, 28, 30, 28, 31, 30, 31, 32, 34, 32, 35, 32, 36, 33, 34, 33, 35, 33, 37, 34, 35, 36, 37, 38, 39, 38, 40, 38, 43, 39, 40, 39, 41, 39, 42, 39, 43, 40, 41, 41, 42, 42, 43, 44, 45, 44, 46, 45, 46, 45, 47, 46, 47, 46, 48, 47, 48, 47, 49, 48, 49 }; const igraph_real_t igraph_i_famous_octahedron[] = { 6, 12, 0, 0, 1, 0, 2, 1, 2, 3, 4, 3, 5, 4, 5, 0, 3, 0, 5, 1, 3, 1, 4, 2, 4, 2, 5 }; const igraph_real_t igraph_i_famous_petersen[] = { 10, 15, 0, 0,1,0,4,0,5, 1,2,1,6, 2,3,2,7, 3,4,3,8, 4,9, 5,7,5,8, 6,8,6,9, 7,9 }; const igraph_real_t igraph_i_famous_robertson[] = { 19, 38, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 0, 18, 0, 4, 4, 9, 9, 13, 13, 17, 2, 17, 2, 6, 6, 10, 10, 15, 0, 15, 1, 8, 8, 16, 5, 16, 5, 12, 1, 12, 7, 18, 7, 14, 3, 14, 3, 11, 11, 18 }; const igraph_real_t igraph_i_famous_smallestcyclicgroup[] = { 9, 15, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 2, 1, 3, 1, 7, 1, 8, 2, 5, 2, 6, 2, 7, 3, 8, 4, 5, 6, 7 }; const igraph_real_t igraph_i_famous_tetrahedron[] = { 4, 6, 0, 0, 3, 1, 3, 2, 3, 0, 1, 1, 2, 0, 2 }; const igraph_real_t igraph_i_famous_thomassen[] = { 34, 52, 0, 0, 2, 0, 3, 1, 3, 1, 4, 2, 4, 5, 7, 5, 8, 6, 8, 6, 9, 7, 9, 10, 12, 10, 13, 11, 13, 11, 14, 12, 14, 15, 17, 15, 18, 16, 18, 16, 19, 17, 19, 9, 19, 4, 14, 24, 25, 25, 26, 20, 26, 20, 21, 21, 22, 22, 23, 23, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 24, 33, 5, 24, 6, 25, 7, 26, 8, 20, 0, 20, 1, 21, 2, 22, 3, 23, 10, 27, 11, 28, 12, 29, 13, 30, 15, 30, 16, 31, 17, 32, 18, 33 }; const igraph_real_t igraph_i_famous_tutte[] = { 46, 69, 0, 0, 10, 0, 11, 0, 12, 1, 2, 1, 7, 1, 19, 2, 3, 2, 41, 3, 4, 3, 27, 4, 5, 4, 33, 5, 6, 5, 45, 6, 9, 6, 29, 7, 8, 7, 21, 8, 9, 8, 22, 9, 24, 10, 13, 10, 14, 11, 26, 11, 28, 12, 30, 12, 31, 13, 15, 13, 21, 14, 15, 14, 18, 15, 16, 16, 17, 16, 20, 17, 18, 17, 23, 18, 24, 19, 25, 19, 40, 20, 21, 20, 22, 22, 23, 23, 24, 25, 26, 25, 38, 26, 34, 27, 28, 27, 39, 28, 34, 29, 30, 29, 44, 30, 35, 31, 32, 31, 35, 32, 33, 32, 42, 33, 43, 34, 36, 35, 37, 36, 38, 36, 39, 37, 42, 37, 44, 38, 40, 39, 41, 40, 41, 42, 43, 43, 45, 44, 45 }; const igraph_real_t igraph_i_famous_uniquely3colorable[] = { 12, 22, 0, 0, 1, 0, 3, 0, 6, 0, 8, 1, 4, 1, 7, 1, 9, 2, 3, 2, 6, 2, 7, 2, 9, 2, 11, 3, 4, 3, 10, 4, 5, 4, 11, 5, 6, 5, 7, 5, 8, 5, 10, 8, 11, 9, 10 }; const igraph_real_t igraph_i_famous_walther[] = { 25, 31, 0, 0, 1, 1, 2, 1, 8, 2, 3, 2, 13, 3, 4, 3, 16, 4, 5, 5, 6, 5, 19, 6, 7, 6, 20, 7, 21, 8, 9, 8, 13, 9, 10, 9, 22, 10, 11, 10, 20, 11, 12, 13, 14, 14, 15, 14, 23, 15, 16, 15, 17, 17, 18, 18, 19, 18, 24, 20, 24, 22, 23, 23, 24 }; const igraph_real_t igraph_i_famous_zachary[] = { 34, 78, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0,10, 0,11, 0,12, 0,13, 0,17, 0,19, 0,21, 0,31, 1, 2, 1, 3, 1, 7, 1,13, 1,17, 1,19, 1,21, 1,30, 2, 3, 2, 7, 2,27, 2,28, 2,32, 2, 9, 2, 8, 2,13, 3, 7, 3,12, 3,13, 4, 6, 4,10, 5, 6, 5,10, 5,16, 6,16, 8,30, 8,32, 8,33, 9,33,13,33,14,32,14,33, 15,32,15,33,18,32,18,33,19,33,20,32,20,33, 22,32,22,33,23,25,23,27,23,32,23,33,23,29, 24,25,24,27,24,31,25,31,26,29,26,33,27,33, 28,31,28,33,29,32,29,33,30,32,30,33,31,32,31,33, 32,33 }; int igraph_i_famous(igraph_t *graph, const igraph_real_t *data); int igraph_i_famous(igraph_t *graph, const igraph_real_t *data) { long int no_of_nodes=(long int) data[0]; long int no_of_edges=(long int) data[1]; igraph_bool_t directed=(igraph_bool_t) data[2]; igraph_vector_t edges; igraph_vector_view(&edges, data+3, 2*no_of_edges); IGRAPH_CHECK(igraph_create(graph, &edges, (igraph_integer_t) no_of_nodes, directed)); return 0; } /** * \function igraph_famous * \brief Create a famous graph by simply providing its name * * * The name of the graph can be simply supplied as a string. * Note that this function creates graphs which don't take any parameters, * there are separate functions for graphs with parameters, eg. \ref * igraph_full() for creating a full graph. * * * The following graphs are supported: * \clist * \cli Bull * The bull graph, 5 vertices, 5 edges, resembles the * head of a bull if drawn properly. * \cli Chvatal * This is the smallest triangle-free graph that is * both 4-chromatic and 4-regular. According to the Grunbaum * conjecture there exists an m-regular, m-chromatic graph * with n vertices for every m>1 and n>2. The Chvatal graph * is an example for m=4 and n=12. It has 24 edges. * \cli Coxeter * A non-Hamiltonian cubic symmetric graph with 28 * vertices and 42 edges. * \cli Cubical * The Platonic graph of the cube. A convex regular * polyhedron with 8 vertices and 12 edges. * \cli Diamond * A graph with 4 vertices and 5 edges, resembles a * schematic diamond if drawn properly. * \cli Dodecahedral, Dodecahedron * Another Platonic solid * with 20 vertices and 30 edges. * \cli Folkman * The semisymmetric graph with minimum number of * vertices, 20 and 40 edges. A semisymmetric graph is * regular, edge transitive and not vertex transitive. * \cli Franklin * This is a graph whose embedding to the Klein * bottle can be colored with six colors, it is a * counterexample to the necessity of the Heawood * conjecture on a Klein bottle. It has 12 vertices and 18 * edges. * \cli Frucht * The Frucht Graph is the smallest cubical graph * whose automorphism group consists only of the identity * element. It has 12 vertices and 18 edges. * \cli Grotzsch * The Grötzsch graph is a triangle-free graph with * 11 vertices, 20 edges, and chromatic number 4. It is named after * German mathematician Herbert Grötzsch, and its existence * demonstrates that the assumption of planarity is necessary in * Grötzsch's theorem that every triangle-free planar * graph is 3-colorable. * \cli Heawood * The Heawood graph is an undirected graph with 14 * vertices and 21 edges. The graph is cubic, and all cycles in the * graph have six or more edges. Every smaller cubic graph has shorter * cycles, so this graph is the 6-cage, the smallest cubic graph of * girth 6. * \cli Herschel * The Herschel graph is the smallest * nonhamiltonian polyhedral graph. It is the * unique such graph on 11 nodes, and has 18 edges. * \cli House * The house graph is a 5-vertex, 6-edge graph, the * schematic draw of a house if drawn properly, basically a * triangle on top of a square. * \cli HouseX * The same as the house graph with an X in the square. 5 * vertices and 8 edges. * \cli Icosahedral, Icosahedron * A Platonic solid with 12 * vertices and 30 edges. * \cli Krackhardt_Kite * A social network with 10 vertices and 18 edges. * Krackhardt, D. Assessing the Political Landscape: * Structure, Cognition, and Power in Organizations. * Admin. Sci. Quart. 35, 342-369, 1990. * \cli Levi * The graph is a 4-arc transitive cubic graph, it has * 30 vertices and 45 edges. * \cli McGee * The McGee graph is the unique 3-regular 7-cage * graph, it has 24 vertices and 36 edges. * \cli Meredith * The Meredith graph is a quartic graph on 70 * nodes and 140 edges that is a counterexample to the conjecture that * every 4-regular 4-connected graph is Hamiltonian. * \cli Noperfectmatching * A connected graph with 16 vertices and * 27 edges containing no perfect matching. A matching in a graph * is a set of pairwise non-incident edges; that is, no two edges * share a common vertex. A perfect matching is a matching * which covers all vertices of the graph. * \cli Nonline * A graph whose connected components are the 9 * graphs whose presence as a vertex-induced subgraph in a * graph makes a nonline graph. It has 50 vertices and 72 edges. * \cli Octahedral, Octahedron * Platonic solid with 6 * vertices and 12 edges. * \cli Petersen * A 3-regular graph with 10 vertices and 15 edges. It is * the smallest hypohamiltonian graph, ie. it is * non-hamiltonian but removing any single vertex from it makes it * Hamiltonian. * \cli Robertson * The unique (4,5)-cage graph, ie. a 4-regular * graph of girth 5. It has 19 vertices and 38 edges. * \cli Smallestcyclicgroup * A smallest nontrivial graph * whose automorphism group is cyclic. It has 9 vertices and * 15 edges. * \cli Tetrahedral, Tetrahedron * Platonic solid with 4 * vertices and 6 edges. * \cli Thomassen * The smallest hypotraceable graph, * on 34 vertices and 52 edges. A hypotracable graph does * not contain a Hamiltonian path but after removing any * single vertex from it the remainder always contains a * Hamiltonian path. A graph containing a Hamiltonian path * is called traceable. * \cli Tutte * Tait's Hamiltonian graph conjecture states that * every 3-connected 3-regular planar graph is Hamiltonian. * This graph is a counterexample. It has 46 vertices and 69 * edges. * \cli Uniquely3colorable * Returns a 12-vertex, triangle-free * graph with chromatic number 3 that is uniquely * 3-colorable. * \cli Walther * An identity graph with 25 vertices and 31 * edges. An identity graph has a single graph automorphism, * the trivial one. * \cli Zachary * Social network of friendships between 34 members of a * karate club at a US university in the 1970s. See * W. W. Zachary, An information flow model for conflict and * fission in small groups, Journal of Anthropological * Research 33, 452-473 (1977). * \endclist * * \param graph Pointer to an uninitialized graph object. * \param name Character constant, the name of the graph to be * created, it is case insensitive. * \return Error code, IGRAPH_EINVAL if there is no graph with the * given name. * * \sa Other functions for creating graph structures: * \ref igraph_ring(), \ref igraph_tree(), \ref igraph_lattice(), \ref * igraph_full(). * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges in the graph. */ int igraph_famous(igraph_t *graph, const char *name) { if (!strcasecmp(name, "bull")) { return igraph_i_famous(graph, igraph_i_famous_bull); } else if (!strcasecmp(name, "chvatal")) { return igraph_i_famous(graph, igraph_i_famous_chvatal); } else if (!strcasecmp(name, "coxeter")) { return igraph_i_famous(graph, igraph_i_famous_coxeter); } else if (!strcasecmp(name, "cubical")) { return igraph_i_famous(graph, igraph_i_famous_cubical); } else if (!strcasecmp(name, "diamond")) { return igraph_i_famous(graph, igraph_i_famous_diamond); } else if (!strcasecmp(name, "dodecahedral") || !strcasecmp(name, "dodecahedron")) { return igraph_i_famous(graph, igraph_i_famous_dodecahedron); } else if (!strcasecmp(name, "folkman")) { return igraph_i_famous(graph, igraph_i_famous_folkman); } else if (!strcasecmp(name, "franklin")) { return igraph_i_famous(graph, igraph_i_famous_franklin); } else if (!strcasecmp(name, "frucht")) { return igraph_i_famous(graph, igraph_i_famous_frucht); } else if (!strcasecmp(name, "grotzsch")) { return igraph_i_famous(graph, igraph_i_famous_grotzsch); } else if (!strcasecmp(name, "heawood")) { return igraph_i_famous(graph, igraph_i_famous_heawood); } else if (!strcasecmp(name, "herschel")) { return igraph_i_famous(graph, igraph_i_famous_herschel); } else if (!strcasecmp(name, "house")) { return igraph_i_famous(graph, igraph_i_famous_house); } else if (!strcasecmp(name, "housex")) { return igraph_i_famous(graph, igraph_i_famous_housex); } else if (!strcasecmp(name, "icosahedral") || !strcasecmp(name, "icosahedron")) { return igraph_i_famous(graph, igraph_i_famous_icosahedron); } else if (!strcasecmp(name, "krackhardt_kite")) { return igraph_i_famous(graph, igraph_i_famous_krackhardt_kite); } else if (!strcasecmp(name, "levi")) { return igraph_i_famous(graph, igraph_i_famous_levi); } else if (!strcasecmp(name, "mcgee")) { return igraph_i_famous(graph, igraph_i_famous_mcgee); } else if (!strcasecmp(name, "meredith")) { return igraph_i_famous(graph, igraph_i_famous_meredith); } else if (!strcasecmp(name, "noperfectmatching")) { return igraph_i_famous(graph, igraph_i_famous_noperfectmatching); } else if (!strcasecmp(name, "nonline")) { return igraph_i_famous(graph, igraph_i_famous_nonline); } else if (!strcasecmp(name, "octahedral") || !strcasecmp(name, "octahedron")) { return igraph_i_famous(graph, igraph_i_famous_octahedron); } else if (!strcasecmp(name, "petersen")) { return igraph_i_famous(graph, igraph_i_famous_petersen); } else if (!strcasecmp(name, "robertson")) { return igraph_i_famous(graph, igraph_i_famous_robertson); } else if (!strcasecmp(name, "smallestcyclicgroup")) { return igraph_i_famous(graph, igraph_i_famous_smallestcyclicgroup); } else if (!strcasecmp(name, "tetrahedral") || !strcasecmp(name, "tetrahedron")) { return igraph_i_famous(graph, igraph_i_famous_tetrahedron); } else if (!strcasecmp(name, "thomassen")) { return igraph_i_famous(graph, igraph_i_famous_thomassen); } else if (!strcasecmp(name, "tutte")) { return igraph_i_famous(graph, igraph_i_famous_tutte); } else if (!strcasecmp(name, "uniquely3colorable")) { return igraph_i_famous(graph, igraph_i_famous_uniquely3colorable); } else if (!strcasecmp(name, "walther")) { return igraph_i_famous(graph, igraph_i_famous_walther); } else if (!strcasecmp(name, "zachary")) { return igraph_i_famous(graph, igraph_i_famous_zachary); } else { IGRAPH_ERROR("Unknown graph, see documentation", IGRAPH_EINVAL); } return 0; } /** * \function igraph_adjlist * Create a graph from an adjacency list * * An adjacency list is a list of vectors, containing the neighbors * of all vertices. For operations that involve many changes to the * graph structure, it is recommended that you convert the graph into * an adjacency list via \ref igraph_adjlist_init(), perform the * modifications (these are cheap for an adjacency list) and then * recreate the igraph graph via this function. * * \param graph Pointer to an uninitialized graph object. * \param adjlist The adjacency list. * \param mode Whether or not to create a directed graph. \c IGRAPH_ALL * means an undirected graph, \c IGRAPH_OUT means a * directed graph from an out-adjacency list (i.e. each * list contains the successors of the corresponding * vertices), \c IGRAPH_IN means a directed graph from an * in-adjacency list * \param duplicate Logical, for undirected graphs this specified * whether each edge is included twice, in the vectors of * both adjacent vertices. If this is false (0), then it is * assumed that every edge is included only once. This argument * is ignored for directed graphs. * \return Error code. * * \sa \ref igraph_adjlist_init() for the opposite operation. * * Time complexity: O(|V|+|E|). * */ int igraph_adjlist(igraph_t *graph, const igraph_adjlist_t *adjlist, igraph_neimode_t mode, igraph_bool_t duplicate) { long int no_of_nodes=igraph_adjlist_size(adjlist); long int no_of_edges=0; long int i; igraph_vector_t edges; long int edgeptr=0; duplicate = duplicate && (mode == IGRAPH_ALL); /* only duplicate if undirected */ for (i=0; i i) { if (edgeptr+2 > 2*no_of_edges) { IGRAPH_ERROR("Invalid adjacency list, most probably not correctly" " duplicated edges for an undirected graph", IGRAPH_EINVAL); } if (mode == IGRAPH_IN) { VECTOR(edges)[edgeptr++] = nei; VECTOR(edges)[edgeptr++] = i; } else { VECTOR(edges)[edgeptr++] = i; VECTOR(edges)[edgeptr++] = nei; } } } } /* loops */ if (duplicate) { loops=loops/2; } if (edgeptr+2*loops > 2*no_of_edges) { IGRAPH_ERROR("Invalid adjacency list, most probably not correctly" " duplicated edges for an undirected graph", IGRAPH_EINVAL); } for (j=0; j /* ========================================================================== */ /* === COLAMD version ======================================================= */ /* ========================================================================== */ /* COLAMD Version 2.4 and later will include the following definitions. * As an example, to test if the version you are using is 2.4 or later: * * #ifdef COLAMD_VERSION * if (COLAMD_VERSION >= COLAMD_VERSION_CODE (2,4)) ... * #endif * * This also works during compile-time: * * #if defined(COLAMD_VERSION) && (COLAMD_VERSION >= COLAMD_VERSION_CODE (2,4)) * printf ("This is version 2.4 or later\n") ; * #else * printf ("This is an early version\n") ; * #endif * * Versions 2.3 and earlier of COLAMD do not include a #define'd version number. */ #define COLAMD_DATE "Jun 1, 2012" #define COLAMD_VERSION_CODE(main,sub) ((main) * 1000 + (sub)) #define COLAMD_MAIN_VERSION 2 #define COLAMD_SUB_VERSION 8 #define COLAMD_SUBSUB_VERSION 0 #define COLAMD_VERSION \ COLAMD_VERSION_CODE(COLAMD_MAIN_VERSION,COLAMD_SUB_VERSION) /* ========================================================================== */ /* === Knob and statistics definitions ====================================== */ /* ========================================================================== */ /* size of the knobs [ ] array. Only knobs [0..1] are currently used. */ #define COLAMD_KNOBS 20 /* number of output statistics. Only stats [0..6] are currently used. */ #define COLAMD_STATS 20 /* knobs [0] and stats [0]: dense row knob and output statistic. */ #define COLAMD_DENSE_ROW 0 /* knobs [1] and stats [1]: dense column knob and output statistic. */ #define COLAMD_DENSE_COL 1 /* knobs [2]: aggressive absorption */ #define COLAMD_AGGRESSIVE 2 /* stats [2]: memory defragmentation count output statistic */ #define COLAMD_DEFRAG_COUNT 2 /* stats [3]: colamd status: zero OK, > 0 warning or notice, < 0 error */ #define COLAMD_STATUS 3 /* stats [4..6]: error info, or info on jumbled columns */ #define COLAMD_INFO1 4 #define COLAMD_INFO2 5 #define COLAMD_INFO3 6 /* error codes returned in stats [3]: */ #define COLAMD_OK (0) #define COLAMD_OK_BUT_JUMBLED (1) #define COLAMD_ERROR_A_not_present (-1) #define COLAMD_ERROR_p_not_present (-2) #define COLAMD_ERROR_nrow_negative (-3) #define COLAMD_ERROR_ncol_negative (-4) #define COLAMD_ERROR_nnz_negative (-5) #define COLAMD_ERROR_p0_nonzero (-6) #define COLAMD_ERROR_A_too_small (-7) #define COLAMD_ERROR_col_length_negative (-8) #define COLAMD_ERROR_row_index_out_of_bounds (-9) #define COLAMD_ERROR_out_of_memory (-10) #define COLAMD_ERROR_internal_error (-999) /* ========================================================================== */ /* === Prototypes of user-callable routines ================================= */ /* ========================================================================== */ #include "SuiteSparse_config.h" size_t colamd_recommended /* returns recommended value of Alen, */ /* or 0 if input arguments are erroneous */ ( int nnz, /* nonzeros in A */ int n_row, /* number of rows in A */ int n_col /* number of columns in A */ ) ; size_t colamd_l_recommended /* returns recommended value of Alen, */ /* or 0 if input arguments are erroneous */ ( SuiteSparse_long nnz, /* nonzeros in A */ SuiteSparse_long n_row, /* number of rows in A */ SuiteSparse_long n_col /* number of columns in A */ ) ; void colamd_set_defaults /* sets default parameters */ ( /* knobs argument is modified on output */ double knobs [COLAMD_KNOBS] /* parameter settings for colamd */ ) ; void colamd_l_set_defaults /* sets default parameters */ ( /* knobs argument is modified on output */ double knobs [COLAMD_KNOBS] /* parameter settings for colamd */ ) ; int colamd /* returns (1) if successful, (0) otherwise*/ ( /* A and p arguments are modified on output */ int n_row, /* number of rows in A */ int n_col, /* number of columns in A */ int Alen, /* size of the array A */ int A [], /* row indices of A, of size Alen */ int p [], /* column pointers of A, of size n_col+1 */ double knobs [COLAMD_KNOBS],/* parameter settings for colamd */ int stats [COLAMD_STATS] /* colamd output statistics and error codes */ ) ; SuiteSparse_long colamd_l /* returns (1) if successful, (0) otherwise*/ ( /* A and p arguments are modified on output */ SuiteSparse_long n_row, /* number of rows in A */ SuiteSparse_long n_col, /* number of columns in A */ SuiteSparse_long Alen, /* size of the array A */ SuiteSparse_long A [], /* row indices of A, of size Alen */ SuiteSparse_long p [], /* column pointers of A, of size n_col+1 */ double knobs [COLAMD_KNOBS],/* parameter settings for colamd */ SuiteSparse_long stats [COLAMD_STATS] /* colamd output statistics * and error codes */ ) ; int symamd /* return (1) if OK, (0) otherwise */ ( int n, /* number of rows and columns of A */ int A [], /* row indices of A */ int p [], /* column pointers of A */ int perm [], /* output permutation, size n_col+1 */ double knobs [COLAMD_KNOBS], /* parameters (uses defaults if NULL) */ int stats [COLAMD_STATS], /* output statistics and error codes */ void * (*allocate) (size_t, size_t), /* pointer to calloc (ANSI C) or */ /* mxCalloc (for MATLAB mexFunction) */ void (*release) (void *) /* pointer to free (ANSI C) or */ /* mxFree (for MATLAB mexFunction) */ ) ; SuiteSparse_long symamd_l /* return (1) if OK, (0) otherwise */ ( SuiteSparse_long n, /* number of rows and columns of A */ SuiteSparse_long A [], /* row indices of A */ SuiteSparse_long p [], /* column pointers of A */ SuiteSparse_long perm [], /* output permutation, size n_col+1 */ double knobs [COLAMD_KNOBS], /* parameters (uses defaults if NULL) */ SuiteSparse_long stats [COLAMD_STATS], /* output stats and error codes */ void * (*allocate) (size_t, size_t), /* pointer to calloc (ANSI C) or */ /* mxCalloc (for MATLAB mexFunction) */ void (*release) (void *) /* pointer to free (ANSI C) or */ /* mxFree (for MATLAB mexFunction) */ ) ; void colamd_report ( int stats [COLAMD_STATS] ) ; void colamd_l_report ( SuiteSparse_long stats [COLAMD_STATS] ) ; void symamd_report ( int stats [COLAMD_STATS] ) ; void symamd_l_report ( SuiteSparse_long stats [COLAMD_STATS] ) ; #ifndef EXTERN #define EXTERN extern #endif EXTERN int (*colamd_printf) (const char *, ...) ; #ifdef __cplusplus } #endif #endif /* COLAMD_H */ igraph/src/COLAMD/README.txt0000644000175100001440000001157313430770174015003 0ustar hornikusersCOLAMD, Copyright 1998-2012, Timothy A. Davis. http://www.suitesparse.com ------------------------------------------------------------------------------- The COLAMD column approximate minimum degree ordering algorithm computes a permutation vector P such that the LU factorization of A (:,P) tends to be sparser than that of A. The Cholesky factorization of (A (:,P))'*(A (:,P)) will also tend to be sparser than that of A'*A. SYMAMD is a symmetric minimum degree ordering method based on COLAMD, available as a MATLAB-callable function. It constructs a matrix M such that M'*M has the same pattern as A, and then uses COLAMD to compute a column ordering of M. Colamd and symamd tend to be faster and generate better orderings than their MATLAB counterparts, colmmd and symmmd. To compile and test the colamd m-files and mexFunctions, just unpack the COLAMD/ directory from the COLAMD.tar.gz file, and run MATLAB from within that directory. Next, type colamd_test to compile and test colamd and symamd. This will work on any computer with MATLAB (Unix, PC, or Mac). Alternatively, type "make" (in Unix) to compile and run a simple example C code, without using MATLAB. To compile and install the colamd m-files and mexFunctions, just cd to COLAMD/MATLAB and type colamd_install in the MATLAB command window. A short demo will run. Optionally, type colamd_test to run an extensive tests. Type "make" in Unix in the COLAMD directory to compile the C-callable library and to run a short demo. Colamd is a built-in routine in MATLAB, available from The Mathworks, Inc. Under most cases, the compiled COLAMD from Versions 2.0 to the current version do not differ. Colamd Versions 2.2 and 2.3 differ only in their mexFunction interaces to MATLAB. v2.4 fixes a bug in the symamd routine in v2.3. The bug (in v2.3 and earlier) has no effect on the MATLAB symamd mexFunction. v2.5 adds additional checks for integer overflow, so that the "int" version can be safely used with 64-bit pointers. Refer to the ChangeLog for more details. To use colamd and symamd within an application written in C, all you need are colamd.c, colamd_global.c, and colamd.h, which are the C-callable colamd/symamd codes. See colamd.c for more information on how to call colamd from a C program. Requires SuiteSparse_config, in the ../SuiteSparse_config directory relative to this directory. See the colamd.c file or http://www.suitesparse.com for the license to COLAMD. Related papers: T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, An approximate column minimum degree ordering algorithm, ACM Transactions on Mathematical Software, vol. 30, no. 3., pp. 353-376, 2004. T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, Algorithm 836: COLAMD, an approximate column minimum degree ordering algorithm, ACM Transactions on Mathematical Software, vol. 30, no. 3., pp. 377-380, 2004. "An approximate minimum degree column ordering algorithm", S. I. Larimore, MS Thesis, Dept. of Computer and Information Science and Engineering, University of Florida, Gainesville, FL, 1998. CISE Tech Report TR-98-016. Approximate Deficiency for Ordering the Columns of a Matrix, J. L. Kern, Senior Thesis, Dept. of Computer and Information Science and Engineering, University of Florida, Gainesville, FL, 1999. Authors: Stefan I. Larimore and Timothy A. Davis, in collaboration with John Gilbert, Xerox PARC (now at UC Santa Barbara), and Esmong Ng, Lawrence Berkeley National Laboratory (much of this work he did while at Oak Ridge National Laboratory). COLAMD files: Demo simple demo Doc additional documentation (see colamd.c for more) Include include file Lib compiled C-callable library Makefile primary Unix Makefile MATLAB MATLAB functions README.txt this file Source C source code ./Demo: colamd_example.c simple example colamd_example.out output of colamd_example.c colamd_l_example.c simple example, long integers colamd_l_example.out output of colamd_l_example.c Makefile Makefile for C demos ./Doc: ChangeLog change log lesser.txt license ./Include: colamd.h include file ./Lib: Makefile Makefile for C-callable library ./MATLAB: colamd2.m MATLAB interface for colamd2 colamd_demo.m simple demo colamd_install.m compile and install colamd2 and symamd2 colamd_make.m compile colamd2 and symamd2 colamdmex.ca MATLAB mexFunction for colamd2 colamd_test.m extensive test colamdtestmex.c test function for colamd Contents.m contents of the MATLAB directory luflops.m test code Makefile Makefile for MATLAB functions symamd2.m MATLAB interface for symamd2 symamdmex.c MATLAB mexFunction for symamd2 symamdtestmex.c test function for symamd ./Source: colamd.c primary source code colamd_global.c globally defined function pointers (malloc, free, ...) igraph/src/COLAMD/Makefile0000644000175100001440000000241613562737552014752 0ustar hornikusers#------------------------------------------------------------------------------ # COLAMD Makefile #------------------------------------------------------------------------------ VERSION = 2.8.0 default: all include ../SuiteSparse_config/SuiteSparse_config.mk demos: all # Compile all C code all: ( cd Lib ; $(MAKE) ) ( cd Demo ; $(MAKE) ) # compile just the C-callable libraries (not Demos) library: ( cd Lib ; $(MAKE) ) # remove object files, but keep the compiled programs and library archives clean: ( cd Lib ; $(MAKE) clean ) ( cd Demo ; $(MAKE) clean ) ( cd MATLAB ; $(RM) $(CLEAN) ) # clean, and then remove compiled programs and library archives purge: ( cd Lib ; $(MAKE) purge ) ( cd Demo ; $(MAKE) purge ) ( cd MATLAB ; $(RM) $(CLEAN) ; $(RM) *.mex* ) distclean: purge # get ready for distribution dist: purge ( cd Demo ; $(MAKE) dist ) ccode: library lib: library # install COLAMD install: $(CP) Lib/libcolamd.a $(INSTALL_LIB)/libcolamd.$(VERSION).a ( cd $(INSTALL_LIB) ; ln -sf libcolamd.$(VERSION).a libcolamd.a ) $(CP) Include/colamd.h $(INSTALL_INCLUDE) chmod 644 $(INSTALL_LIB)/libcolamd*.a chmod 644 $(INSTALL_INCLUDE)/colamd.h # uninstall COLAMD uninstall: $(RM) $(INSTALL_LIB)/libcolamd*.a $(RM) $(INSTALL_INCLUDE)/colamd.h igraph/src/COLAMD/Source/0000755000175100001440000000000013561251652014536 5ustar hornikusersigraph/src/COLAMD/Source/colamd_global.c0000644000175100001440000000154213431000472017447 0ustar hornikusers/* ========================================================================== */ /* === colamd_global.c ====================================================== */ /* ========================================================================== */ /* ---------------------------------------------------------------------------- * COLAMD, Copyright (C) 2007, Timothy A. Davis. * See License.txt for the Version 2.1 of the GNU Lesser General Public License * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Global variables for COLAMD */ #ifndef NPRINT #ifdef MATLAB_MEX_FILE #include "mex.h" int (*colamd_printf) (const char *, ...) = mexPrintf ; #else #include int (*colamd_printf) (const char *, ...) = printf ; #endif #else int (*colamd_printf) (const char *, ...) = ((void *) 0) ; #endif igraph/src/COLAMD/Source/colamd.c0000644000175100001440000032302413431000472016131 0ustar hornikusers/* ========================================================================== */ /* === colamd/symamd - a sparse matrix column ordering algorithm ============ */ /* ========================================================================== */ /* COLAMD / SYMAMD colamd: an approximate minimum degree column ordering algorithm, for LU factorization of symmetric or unsymmetric matrices, QR factorization, least squares, interior point methods for linear programming problems, and other related problems. symamd: an approximate minimum degree ordering algorithm for Cholesky factorization of symmetric matrices. Purpose: Colamd computes a permutation Q such that the Cholesky factorization of (AQ)'(AQ) has less fill-in and requires fewer floating point operations than A'A. This also provides a good ordering for sparse partial pivoting methods, P(AQ) = LU, where Q is computed prior to numerical factorization, and P is computed during numerical factorization via conventional partial pivoting with row interchanges. Colamd is the column ordering method used in SuperLU, part of the ScaLAPACK library. It is also available as built-in function in MATLAB Version 6, available from MathWorks, Inc. (http://www.mathworks.com). This routine can be used in place of colmmd in MATLAB. Symamd computes a permutation P of a symmetric matrix A such that the Cholesky factorization of PAP' has less fill-in and requires fewer floating point operations than A. Symamd constructs a matrix M such that M'M has the same nonzero pattern of A, and then orders the columns of M using colmmd. The column ordering of M is then returned as the row and column ordering P of A. Authors: The authors of the code itself are Stefan I. Larimore and Timothy A. Davis (DrTimothyAldenDavis@gmail.com). The algorithm was developed in collaboration with John Gilbert, Xerox PARC, and Esmond Ng, Oak Ridge National Laboratory. Acknowledgements: This work was supported by the National Science Foundation, under grants DMS-9504974 and DMS-9803599. Copyright and License: Copyright (c) 1998-2007, Timothy A. Davis, All Rights Reserved. COLAMD is also available under alternate licenses, contact T. Davis for details. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Permission is hereby granted to use or copy this program under the terms of the GNU LGPL, provided that the Copyright, this License, and the Availability of the original version is retained on all copies. User documentation of any code that uses this code or any modified version of this code must cite the Copyright, this License, the Availability note, and "Used by permission." Permission to modify the code and to distribute modified code is granted, provided the Copyright, this License, and the Availability note are retained, and a notice that the code was modified is included. Availability: The colamd/symamd library is available at http://www.suitesparse.com Appears as ACM Algorithm 836. See the ChangeLog file for changes since Version 1.0. References: T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, An approximate column minimum degree ordering algorithm, ACM Transactions on Mathematical Software, vol. 30, no. 3., pp. 353-376, 2004. T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, Algorithm 836: COLAMD, an approximate column minimum degree ordering algorithm, ACM Transactions on Mathematical Software, vol. 30, no. 3., pp. 377-380, 2004. */ /* ========================================================================== */ /* === Description of user-callable routines ================================ */ /* ========================================================================== */ /* COLAMD includes both int and SuiteSparse_long versions of all its routines. The description below is for the int version. For SuiteSparse_long, all int arguments become SuiteSparse_long. SuiteSparse_long is normally defined as long, except for WIN64. ---------------------------------------------------------------------------- colamd_recommended: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" size_t colamd_recommended (int nnz, int n_row, int n_col) ; size_t colamd_l_recommended (SuiteSparse_long nnz, SuiteSparse_long n_row, SuiteSparse_long n_col) ; Purpose: Returns recommended value of Alen for use by colamd. Returns 0 if any input argument is negative. The use of this routine is optional. Not needed for symamd, which dynamically allocates its own memory. Note that in v2.4 and earlier, these routines returned int or long. They now return a value of type size_t. Arguments (all input arguments): int nnz ; Number of nonzeros in the matrix A. This must be the same value as p [n_col] in the call to colamd - otherwise you will get a wrong value of the recommended memory to use. int n_row ; Number of rows in the matrix A. int n_col ; Number of columns in the matrix A. ---------------------------------------------------------------------------- colamd_set_defaults: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" colamd_set_defaults (double knobs [COLAMD_KNOBS]) ; colamd_l_set_defaults (double knobs [COLAMD_KNOBS]) ; Purpose: Sets the default parameters. The use of this routine is optional. Arguments: double knobs [COLAMD_KNOBS] ; Output only. NOTE: the meaning of the dense row/col knobs has changed in v2.4 knobs [0] and knobs [1] control dense row and col detection: Colamd: rows with more than max (16, knobs [COLAMD_DENSE_ROW] * sqrt (n_col)) entries are removed prior to ordering. Columns with more than max (16, knobs [COLAMD_DENSE_COL] * sqrt (MIN (n_row,n_col))) entries are removed prior to ordering, and placed last in the output column ordering. Symamd: uses only knobs [COLAMD_DENSE_ROW], which is knobs [0]. Rows and columns with more than max (16, knobs [COLAMD_DENSE_ROW] * sqrt (n)) entries are removed prior to ordering, and placed last in the output ordering. COLAMD_DENSE_ROW and COLAMD_DENSE_COL are defined as 0 and 1, respectively, in colamd.h. Default values of these two knobs are both 10. Currently, only knobs [0] and knobs [1] are used, but future versions may use more knobs. If so, they will be properly set to their defaults by the future version of colamd_set_defaults, so that the code that calls colamd will not need to change, assuming that you either use colamd_set_defaults, or pass a (double *) NULL pointer as the knobs array to colamd or symamd. knobs [2]: aggressive absorption knobs [COLAMD_AGGRESSIVE] controls whether or not to do aggressive absorption during the ordering. Default is TRUE. ---------------------------------------------------------------------------- colamd: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" int colamd (int n_row, int n_col, int Alen, int *A, int *p, double knobs [COLAMD_KNOBS], int stats [COLAMD_STATS]) ; SuiteSparse_long colamd_l (SuiteSparse_long n_row, SuiteSparse_long n_col, SuiteSparse_long Alen, SuiteSparse_long *A, SuiteSparse_long *p, double knobs [COLAMD_KNOBS], SuiteSparse_long stats [COLAMD_STATS]) ; Purpose: Computes a column ordering (Q) of A such that P(AQ)=LU or (AQ)'AQ=LL' have less fill-in and require fewer floating point operations than factorizing the unpermuted matrix A or A'A, respectively. Returns: TRUE (1) if successful, FALSE (0) otherwise. Arguments: int n_row ; Input argument. Number of rows in the matrix A. Restriction: n_row >= 0. Colamd returns FALSE if n_row is negative. int n_col ; Input argument. Number of columns in the matrix A. Restriction: n_col >= 0. Colamd returns FALSE if n_col is negative. int Alen ; Input argument. Restriction (see note): Alen >= 2*nnz + 6*(n_col+1) + 4*(n_row+1) + n_col Colamd returns FALSE if these conditions are not met. Note: this restriction makes an modest assumption regarding the size of the two typedef's structures in colamd.h. We do, however, guarantee that Alen >= colamd_recommended (nnz, n_row, n_col) will be sufficient. Note: the macro version does not check for integer overflow, and thus is not recommended. Use the colamd_recommended routine instead. int A [Alen] ; Input argument, undefined on output. A is an integer array of size Alen. Alen must be at least as large as the bare minimum value given above, but this is very low, and can result in excessive run time. For best performance, we recommend that Alen be greater than or equal to colamd_recommended (nnz, n_row, n_col), which adds nnz/5 to the bare minimum value given above. On input, the row indices of the entries in column c of the matrix are held in A [(p [c]) ... (p [c+1]-1)]. The row indices in a given column c need not be in ascending order, and duplicate row indices may be be present. However, colamd will work a little faster if both of these conditions are met (Colamd puts the matrix into this format, if it finds that the the conditions are not met). The matrix is 0-based. That is, rows are in the range 0 to n_row-1, and columns are in the range 0 to n_col-1. Colamd returns FALSE if any row index is out of range. The contents of A are modified during ordering, and are undefined on output. int p [n_col+1] ; Both input and output argument. p is an integer array of size n_col+1. On input, it holds the "pointers" for the column form of the matrix A. Column c of the matrix A is held in A [(p [c]) ... (p [c+1]-1)]. The first entry, p [0], must be zero, and p [c] <= p [c+1] must hold for all c in the range 0 to n_col-1. The value p [n_col] is thus the total number of entries in the pattern of the matrix A. Colamd returns FALSE if these conditions are not met. On output, if colamd returns TRUE, the array p holds the column permutation (Q, for P(AQ)=LU or (AQ)'(AQ)=LL'), where p [0] is the first column index in the new ordering, and p [n_col-1] is the last. That is, p [k] = j means that column j of A is the kth pivot column, in AQ, where k is in the range 0 to n_col-1 (p [0] = j means that column j of A is the first column in AQ). If colamd returns FALSE, then no permutation is returned, and p is undefined on output. double knobs [COLAMD_KNOBS] ; Input argument. See colamd_set_defaults for a description. int stats [COLAMD_STATS] ; Output argument. Statistics on the ordering, and error status. See colamd.h for related definitions. Colamd returns FALSE if stats is not present. stats [0]: number of dense or empty rows ignored. stats [1]: number of dense or empty columns ignored (and ordered last in the output permutation p) Note that a row can become "empty" if it contains only "dense" and/or "empty" columns, and similarly a column can become "empty" if it only contains "dense" and/or "empty" rows. stats [2]: number of garbage collections performed. This can be excessively high if Alen is close to the minimum required value. stats [3]: status code. < 0 is an error code. > 1 is a warning or notice. 0 OK. Each column of the input matrix contained row indices in increasing order, with no duplicates. 1 OK, but columns of input matrix were jumbled (unsorted columns or duplicate entries). Colamd had to do some extra work to sort the matrix first and remove duplicate entries, but it still was able to return a valid permutation (return value of colamd was TRUE). stats [4]: highest numbered column that is unsorted or has duplicate entries. stats [5]: last seen duplicate or unsorted row index. stats [6]: number of duplicate or unsorted row indices. -1 A is a null pointer -2 p is a null pointer -3 n_row is negative stats [4]: n_row -4 n_col is negative stats [4]: n_col -5 number of nonzeros in matrix is negative stats [4]: number of nonzeros, p [n_col] -6 p [0] is nonzero stats [4]: p [0] -7 A is too small stats [4]: required size stats [5]: actual size (Alen) -8 a column has a negative number of entries stats [4]: column with < 0 entries stats [5]: number of entries in col -9 a row index is out of bounds stats [4]: column with bad row index stats [5]: bad row index stats [6]: n_row, # of rows of matrx -10 (unused; see symamd.c) -999 (unused; see symamd.c) Future versions may return more statistics in the stats array. Example: See colamd_example.c for a complete example. To order the columns of a 5-by-4 matrix with 11 nonzero entries in the following nonzero pattern x 0 x 0 x 0 x x 0 x x 0 0 0 x x x x 0 0 with default knobs and no output statistics, do the following: #include "colamd.h" #define ALEN 100 int A [ALEN] = {0, 1, 4, 2, 4, 0, 1, 2, 3, 1, 3} ; int p [ ] = {0, 3, 5, 9, 11} ; int stats [COLAMD_STATS] ; colamd (5, 4, ALEN, A, p, (double *) NULL, stats) ; The permutation is returned in the array p, and A is destroyed. ---------------------------------------------------------------------------- symamd: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" int symamd (int n, int *A, int *p, int *perm, double knobs [COLAMD_KNOBS], int stats [COLAMD_STATS], void (*allocate) (size_t, size_t), void (*release) (void *)) ; SuiteSparse_long symamd_l (SuiteSparse_long n, SuiteSparse_long *A, SuiteSparse_long *p, SuiteSparse_long *perm, double knobs [COLAMD_KNOBS], SuiteSparse_long stats [COLAMD_STATS], void (*allocate) (size_t, size_t), void (*release) (void *)) ; Purpose: The symamd routine computes an ordering P of a symmetric sparse matrix A such that the Cholesky factorization PAP' = LL' remains sparse. It is based on a column ordering of a matrix M constructed so that the nonzero pattern of M'M is the same as A. The matrix A is assumed to be symmetric; only the strictly lower triangular part is accessed. You must pass your selected memory allocator (usually calloc/free or mxCalloc/mxFree) to symamd, for it to allocate memory for the temporary matrix M. Returns: TRUE (1) if successful, FALSE (0) otherwise. Arguments: int n ; Input argument. Number of rows and columns in the symmetrix matrix A. Restriction: n >= 0. Symamd returns FALSE if n is negative. int A [nnz] ; Input argument. A is an integer array of size nnz, where nnz = p [n]. The row indices of the entries in column c of the matrix are held in A [(p [c]) ... (p [c+1]-1)]. The row indices in a given column c need not be in ascending order, and duplicate row indices may be present. However, symamd will run faster if the columns are in sorted order with no duplicate entries. The matrix is 0-based. That is, rows are in the range 0 to n-1, and columns are in the range 0 to n-1. Symamd returns FALSE if any row index is out of range. The contents of A are not modified. int p [n+1] ; Input argument. p is an integer array of size n+1. On input, it holds the "pointers" for the column form of the matrix A. Column c of the matrix A is held in A [(p [c]) ... (p [c+1]-1)]. The first entry, p [0], must be zero, and p [c] <= p [c+1] must hold for all c in the range 0 to n-1. The value p [n] is thus the total number of entries in the pattern of the matrix A. Symamd returns FALSE if these conditions are not met. The contents of p are not modified. int perm [n+1] ; Output argument. On output, if symamd returns TRUE, the array perm holds the permutation P, where perm [0] is the first index in the new ordering, and perm [n-1] is the last. That is, perm [k] = j means that row and column j of A is the kth column in PAP', where k is in the range 0 to n-1 (perm [0] = j means that row and column j of A are the first row and column in PAP'). The array is used as a workspace during the ordering, which is why it must be of length n+1, not just n. double knobs [COLAMD_KNOBS] ; Input argument. See colamd_set_defaults for a description. int stats [COLAMD_STATS] ; Output argument. Statistics on the ordering, and error status. See colamd.h for related definitions. Symamd returns FALSE if stats is not present. stats [0]: number of dense or empty row and columns ignored (and ordered last in the output permutation perm). Note that a row/column can become "empty" if it contains only "dense" and/or "empty" columns/rows. stats [1]: (same as stats [0]) stats [2]: number of garbage collections performed. stats [3]: status code. < 0 is an error code. > 1 is a warning or notice. 0 OK. Each column of the input matrix contained row indices in increasing order, with no duplicates. 1 OK, but columns of input matrix were jumbled (unsorted columns or duplicate entries). Symamd had to do some extra work to sort the matrix first and remove duplicate entries, but it still was able to return a valid permutation (return value of symamd was TRUE). stats [4]: highest numbered column that is unsorted or has duplicate entries. stats [5]: last seen duplicate or unsorted row index. stats [6]: number of duplicate or unsorted row indices. -1 A is a null pointer -2 p is a null pointer -3 (unused, see colamd.c) -4 n is negative stats [4]: n -5 number of nonzeros in matrix is negative stats [4]: # of nonzeros (p [n]). -6 p [0] is nonzero stats [4]: p [0] -7 (unused) -8 a column has a negative number of entries stats [4]: column with < 0 entries stats [5]: number of entries in col -9 a row index is out of bounds stats [4]: column with bad row index stats [5]: bad row index stats [6]: n_row, # of rows of matrx -10 out of memory (unable to allocate temporary workspace for M or count arrays using the "allocate" routine passed into symamd). Future versions may return more statistics in the stats array. void * (*allocate) (size_t, size_t) A pointer to a function providing memory allocation. The allocated memory must be returned initialized to zero. For a C application, this argument should normally be a pointer to calloc. For a MATLAB mexFunction, the routine mxCalloc is passed instead. void (*release) (size_t, size_t) A pointer to a function that frees memory allocated by the memory allocation routine above. For a C application, this argument should normally be a pointer to free. For a MATLAB mexFunction, the routine mxFree is passed instead. ---------------------------------------------------------------------------- colamd_report: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" colamd_report (int stats [COLAMD_STATS]) ; colamd_l_report (SuiteSparse_long stats [COLAMD_STATS]) ; Purpose: Prints the error status and statistics recorded in the stats array on the standard error output (for a standard C routine) or on the MATLAB output (for a mexFunction). Arguments: int stats [COLAMD_STATS] ; Input only. Statistics from colamd. ---------------------------------------------------------------------------- symamd_report: ---------------------------------------------------------------------------- C syntax: #include "colamd.h" symamd_report (int stats [COLAMD_STATS]) ; symamd_l_report (SuiteSparse_long stats [COLAMD_STATS]) ; Purpose: Prints the error status and statistics recorded in the stats array on the standard error output (for a standard C routine) or on the MATLAB output (for a mexFunction). Arguments: int stats [COLAMD_STATS] ; Input only. Statistics from symamd. */ /* ========================================================================== */ /* === Scaffolding code definitions ======================================== */ /* ========================================================================== */ /* Ensure that debugging is turned off: */ #ifndef NDEBUG #define NDEBUG #endif /* turn on debugging by uncommenting the following line #undef NDEBUG */ /* Our "scaffolding code" philosophy: In our opinion, well-written library code should keep its "debugging" code, and just normally have it turned off by the compiler so as not to interfere with performance. This serves several purposes: (1) assertions act as comments to the reader, telling you what the code expects at that point. All assertions will always be true (unless there really is a bug, of course). (2) leaving in the scaffolding code assists anyone who would like to modify the code, or understand the algorithm (by reading the debugging output, one can get a glimpse into what the code is doing). (3) (gasp!) for actually finding bugs. This code has been heavily tested and "should" be fully functional and bug-free ... but you never know... The code will become outrageously slow when debugging is enabled. To control the level of debugging output, set an environment variable D to 0 (little), 1 (some), 2, 3, or 4 (lots). When debugging, you should see the following message on the standard output: colamd: debug version, D = 1 (THIS WILL BE SLOW!) or a similar message for symamd. If you don't, then debugging has not been enabled. */ /* ========================================================================== */ /* === Include files ======================================================== */ /* ========================================================================== */ #include "colamd.h" #include #include #ifdef MATLAB_MEX_FILE #include "mex.h" #include "matrix.h" #endif /* MATLAB_MEX_FILE */ #if !defined (NPRINT) || !defined (NDEBUG) #include #endif #ifndef NULL #define NULL ((void *) 0) #endif /* ========================================================================== */ /* === int or SuiteSparse_long ============================================== */ /* ========================================================================== */ #ifdef DLONG #define Int SuiteSparse_long #define ID SuiteSparse_long_id #define Int_MAX SuiteSparse_long_max #define COLAMD_recommended colamd_l_recommended #define COLAMD_set_defaults colamd_l_set_defaults #define COLAMD_MAIN colamd_l #define SYMAMD_MAIN symamd_l #define COLAMD_report colamd_l_report #define SYMAMD_report symamd_l_report #else #define Int int #define ID "%d" #define Int_MAX INT_MAX #define COLAMD_recommended colamd_recommended #define COLAMD_set_defaults colamd_set_defaults #define COLAMD_MAIN colamd #define SYMAMD_MAIN symamd #define COLAMD_report colamd_report #define SYMAMD_report symamd_report #endif /* ========================================================================== */ /* === Row and Column structures ============================================ */ /* ========================================================================== */ /* User code that makes use of the colamd/symamd routines need not directly */ /* reference these structures. They are used only for colamd_recommended. */ typedef struct Colamd_Col_struct { Int start ; /* index for A of first row in this column, or DEAD */ /* if column is dead */ Int length ; /* number of rows in this column */ union { Int thickness ; /* number of original columns represented by this */ /* col, if the column is alive */ Int parent ; /* parent in parent tree super-column structure, if */ /* the column is dead */ } shared1 ; union { Int score ; /* the score used to maintain heap, if col is alive */ Int order ; /* pivot ordering of this column, if col is dead */ } shared2 ; union { Int headhash ; /* head of a hash bucket, if col is at the head of */ /* a degree list */ Int hash ; /* hash value, if col is not in a degree list */ Int prev ; /* previous column in degree list, if col is in a */ /* degree list (but not at the head of a degree list) */ } shared3 ; union { Int degree_next ; /* next column, if col is in a degree list */ Int hash_next ; /* next column, if col is in a hash list */ } shared4 ; } Colamd_Col ; typedef struct Colamd_Row_struct { Int start ; /* index for A of first col in this row */ Int length ; /* number of principal columns in this row */ union { Int degree ; /* number of principal & non-principal columns in row */ Int p ; /* used as a row pointer in init_rows_cols () */ } shared1 ; union { Int mark ; /* for computing set differences and marking dead rows*/ Int first_column ;/* first column in row (used in garbage collection) */ } shared2 ; } Colamd_Row ; /* ========================================================================== */ /* === Definitions ========================================================== */ /* ========================================================================== */ /* Routines are either PUBLIC (user-callable) or PRIVATE (not user-callable) */ #define PUBLIC #define PRIVATE static #define DENSE_DEGREE(alpha,n) \ ((Int) MAX (16.0, (alpha) * sqrt ((double) (n)))) #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define ONES_COMPLEMENT(r) (-(r)-1) /* -------------------------------------------------------------------------- */ /* Change for version 2.1: define TRUE and FALSE only if not yet defined */ /* -------------------------------------------------------------------------- */ #ifndef TRUE #define TRUE (1) #endif #ifndef FALSE #define FALSE (0) #endif /* -------------------------------------------------------------------------- */ #define EMPTY (-1) /* Row and column status */ #define ALIVE (0) #define DEAD (-1) /* Column status */ #define DEAD_PRINCIPAL (-1) #define DEAD_NON_PRINCIPAL (-2) /* Macros for row and column status update and checking. */ #define ROW_IS_DEAD(r) ROW_IS_MARKED_DEAD (Row[r].shared2.mark) #define ROW_IS_MARKED_DEAD(row_mark) (row_mark < ALIVE) #define ROW_IS_ALIVE(r) (Row [r].shared2.mark >= ALIVE) #define COL_IS_DEAD(c) (Col [c].start < ALIVE) #define COL_IS_ALIVE(c) (Col [c].start >= ALIVE) #define COL_IS_DEAD_PRINCIPAL(c) (Col [c].start == DEAD_PRINCIPAL) #define KILL_ROW(r) { Row [r].shared2.mark = DEAD ; } #define KILL_PRINCIPAL_COL(c) { Col [c].start = DEAD_PRINCIPAL ; } #define KILL_NON_PRINCIPAL_COL(c) { Col [c].start = DEAD_NON_PRINCIPAL ; } /* ========================================================================== */ /* === Colamd reporting mechanism =========================================== */ /* ========================================================================== */ #if defined (MATLAB_MEX_FILE) || defined (MATHWORKS) /* In MATLAB, matrices are 1-based to the user, but 0-based internally */ #define INDEX(i) ((i)+1) #else /* In C, matrices are 0-based and indices are reported as such in *_report */ #define INDEX(i) (i) #endif /* All output goes through the PRINTF macro. */ #define PRINTF(params) { if (colamd_printf != NULL) (void) colamd_printf params ; } /* ========================================================================== */ /* === Prototypes of PRIVATE routines ======================================= */ /* ========================================================================== */ PRIVATE Int init_rows_cols ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int p [], Int stats [COLAMD_STATS] ) ; PRIVATE void init_scoring ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int head [], double knobs [COLAMD_KNOBS], Int *p_n_row2, Int *p_n_col2, Int *p_max_deg ) ; PRIVATE Int find_ordering ( Int n_row, Int n_col, Int Alen, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int head [], Int n_col2, Int max_deg, Int pfree, Int aggressive ) ; PRIVATE void order_children ( Int n_col, Colamd_Col Col [], Int p [] ) ; PRIVATE void detect_super_cols ( #ifndef NDEBUG Int n_col, Colamd_Row Row [], #endif /* NDEBUG */ Colamd_Col Col [], Int A [], Int head [], Int row_start, Int row_length ) ; PRIVATE Int garbage_collection ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int *pfree ) ; PRIVATE Int clear_mark ( Int tag_mark, Int max_mark, Int n_row, Colamd_Row Row [] ) ; PRIVATE void print_report ( char *method, Int stats [COLAMD_STATS] ) ; /* ========================================================================== */ /* === Debugging prototypes and definitions ================================= */ /* ========================================================================== */ #ifndef NDEBUG #include /* colamd_debug is the *ONLY* global variable, and is only */ /* present when debugging */ PRIVATE Int colamd_debug = 0 ; /* debug print level */ #define DEBUG0(params) { PRINTF (params) ; } #define DEBUG1(params) { if (colamd_debug >= 1) PRINTF (params) ; } #define DEBUG2(params) { if (colamd_debug >= 2) PRINTF (params) ; } #define DEBUG3(params) { if (colamd_debug >= 3) PRINTF (params) ; } #define DEBUG4(params) { if (colamd_debug >= 4) PRINTF (params) ; } #ifdef MATLAB_MEX_FILE #define ASSERT(expression) (mxAssert ((expression), "")) #else #define ASSERT(expression) (assert (expression)) #endif /* MATLAB_MEX_FILE */ PRIVATE void colamd_get_debug /* gets the debug print level from getenv */ ( char *method ) ; PRIVATE void debug_deg_lists ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int head [], Int min_score, Int should, Int max_deg ) ; PRIVATE void debug_mark ( Int n_row, Colamd_Row Row [], Int tag_mark, Int max_mark ) ; PRIVATE void debug_matrix ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [] ) ; PRIVATE void debug_structures ( Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int n_col2 ) ; #else /* NDEBUG */ /* === No debugging ========================================================= */ #define DEBUG0(params) ; #define DEBUG1(params) ; #define DEBUG2(params) ; #define DEBUG3(params) ; #define DEBUG4(params) ; #define ASSERT(expression) #endif /* NDEBUG */ /* ========================================================================== */ /* === USER-CALLABLE ROUTINES: ============================================== */ /* ========================================================================== */ /* ========================================================================== */ /* === colamd_recommended =================================================== */ /* ========================================================================== */ /* The colamd_recommended routine returns the suggested size for Alen. This value has been determined to provide good balance between the number of garbage collections and the memory requirements for colamd. If any argument is negative, or if integer overflow occurs, a 0 is returned as an error condition. 2*nnz space is required for the row and column indices of the matrix. COLAMD_C (n_col) + COLAMD_R (n_row) space is required for the Col and Row arrays, respectively, which are internal to colamd (roughly 6*n_col + 4*n_row). An additional n_col space is the minimal amount of "elbow room", and nnz/5 more space is recommended for run time efficiency. Alen is approximately 2.2*nnz + 7*n_col + 4*n_row + 10. This function is not needed when using symamd. */ /* add two values of type size_t, and check for integer overflow */ static size_t t_add (size_t a, size_t b, int *ok) { (*ok) = (*ok) && ((a + b) >= MAX (a,b)) ; return ((*ok) ? (a + b) : 0) ; } /* compute a*k where k is a small integer, and check for integer overflow */ static size_t t_mult (size_t a, size_t k, int *ok) { size_t i, s = 0 ; for (i = 0 ; i < k ; i++) { s = t_add (s, a, ok) ; } return (s) ; } /* size of the Col and Row structures */ #define COLAMD_C(n_col,ok) \ ((t_mult (t_add (n_col, 1, ok), sizeof (Colamd_Col), ok) / sizeof (Int))) #define COLAMD_R(n_row,ok) \ ((t_mult (t_add (n_row, 1, ok), sizeof (Colamd_Row), ok) / sizeof (Int))) PUBLIC size_t COLAMD_recommended /* returns recommended value of Alen. */ ( /* === Parameters ======================================================= */ Int nnz, /* number of nonzeros in A */ Int n_row, /* number of rows in A */ Int n_col /* number of columns in A */ ) { size_t s, c, r ; int ok = TRUE ; if (nnz < 0 || n_row < 0 || n_col < 0) { return (0) ; } s = t_mult (nnz, 2, &ok) ; /* 2*nnz */ c = COLAMD_C (n_col, &ok) ; /* size of column structures */ r = COLAMD_R (n_row, &ok) ; /* size of row structures */ s = t_add (s, c, &ok) ; s = t_add (s, r, &ok) ; s = t_add (s, n_col, &ok) ; /* elbow room */ s = t_add (s, nnz/5, &ok) ; /* elbow room */ ok = ok && (s < Int_MAX) ; return (ok ? s : 0) ; } /* ========================================================================== */ /* === colamd_set_defaults ================================================== */ /* ========================================================================== */ /* The colamd_set_defaults routine sets the default values of the user- controllable parameters for colamd and symamd: Colamd: rows with more than max (16, knobs [0] * sqrt (n_col)) entries are removed prior to ordering. Columns with more than max (16, knobs [1] * sqrt (MIN (n_row,n_col))) entries are removed prior to ordering, and placed last in the output column ordering. Symamd: Rows and columns with more than max (16, knobs [0] * sqrt (n)) entries are removed prior to ordering, and placed last in the output ordering. knobs [0] dense row control knobs [1] dense column control knobs [2] if nonzero, do aggresive absorption knobs [3..19] unused, but future versions might use this */ PUBLIC void COLAMD_set_defaults ( /* === Parameters ======================================================= */ double knobs [COLAMD_KNOBS] /* knob array */ ) { /* === Local variables ================================================== */ Int i ; if (!knobs) { return ; /* no knobs to initialize */ } for (i = 0 ; i < COLAMD_KNOBS ; i++) { knobs [i] = 0 ; } knobs [COLAMD_DENSE_ROW] = 10 ; knobs [COLAMD_DENSE_COL] = 10 ; knobs [COLAMD_AGGRESSIVE] = TRUE ; /* default: do aggressive absorption*/ } /* ========================================================================== */ /* === symamd =============================================================== */ /* ========================================================================== */ PUBLIC Int SYMAMD_MAIN /* return TRUE if OK, FALSE otherwise */ ( /* === Parameters ======================================================= */ Int n, /* number of rows and columns of A */ Int A [], /* row indices of A */ Int p [], /* column pointers of A */ Int perm [], /* output permutation, size n+1 */ double knobs [COLAMD_KNOBS], /* parameters (uses defaults if NULL) */ Int stats [COLAMD_STATS], /* output statistics and error codes */ void * (*allocate) (size_t, size_t), /* pointer to calloc (ANSI C) or */ /* mxCalloc (for MATLAB mexFunction) */ void (*release) (void *) /* pointer to free (ANSI C) or */ /* mxFree (for MATLAB mexFunction) */ ) { /* === Local variables ================================================== */ Int *count ; /* length of each column of M, and col pointer*/ Int *mark ; /* mark array for finding duplicate entries */ Int *M ; /* row indices of matrix M */ size_t Mlen ; /* length of M */ Int n_row ; /* number of rows in M */ Int nnz ; /* number of entries in A */ Int i ; /* row index of A */ Int j ; /* column index of A */ Int k ; /* row index of M */ Int mnz ; /* number of nonzeros in M */ Int pp ; /* index into a column of A */ Int last_row ; /* last row seen in the current column */ Int length ; /* number of nonzeros in a column */ double cknobs [COLAMD_KNOBS] ; /* knobs for colamd */ double default_knobs [COLAMD_KNOBS] ; /* default knobs for colamd */ #ifndef NDEBUG colamd_get_debug ("symamd") ; #endif /* NDEBUG */ /* === Check the input arguments ======================================== */ if (!stats) { DEBUG0 (("symamd: stats not present\n")) ; return (FALSE) ; } for (i = 0 ; i < COLAMD_STATS ; i++) { stats [i] = 0 ; } stats [COLAMD_STATUS] = COLAMD_OK ; stats [COLAMD_INFO1] = -1 ; stats [COLAMD_INFO2] = -1 ; if (!A) { stats [COLAMD_STATUS] = COLAMD_ERROR_A_not_present ; DEBUG0 (("symamd: A not present\n")) ; return (FALSE) ; } if (!p) /* p is not present */ { stats [COLAMD_STATUS] = COLAMD_ERROR_p_not_present ; DEBUG0 (("symamd: p not present\n")) ; return (FALSE) ; } if (n < 0) /* n must be >= 0 */ { stats [COLAMD_STATUS] = COLAMD_ERROR_ncol_negative ; stats [COLAMD_INFO1] = n ; DEBUG0 (("symamd: n negative %d\n", n)) ; return (FALSE) ; } nnz = p [n] ; if (nnz < 0) /* nnz must be >= 0 */ { stats [COLAMD_STATUS] = COLAMD_ERROR_nnz_negative ; stats [COLAMD_INFO1] = nnz ; DEBUG0 (("symamd: number of entries negative %d\n", nnz)) ; return (FALSE) ; } if (p [0] != 0) { stats [COLAMD_STATUS] = COLAMD_ERROR_p0_nonzero ; stats [COLAMD_INFO1] = p [0] ; DEBUG0 (("symamd: p[0] not zero %d\n", p [0])) ; return (FALSE) ; } /* === If no knobs, set default knobs =================================== */ if (!knobs) { COLAMD_set_defaults (default_knobs) ; knobs = default_knobs ; } /* === Allocate count and mark ========================================== */ count = (Int *) ((*allocate) (n+1, sizeof (Int))) ; if (!count) { stats [COLAMD_STATUS] = COLAMD_ERROR_out_of_memory ; DEBUG0 (("symamd: allocate count (size %d) failed\n", n+1)) ; return (FALSE) ; } mark = (Int *) ((*allocate) (n+1, sizeof (Int))) ; if (!mark) { stats [COLAMD_STATUS] = COLAMD_ERROR_out_of_memory ; (*release) ((void *) count) ; DEBUG0 (("symamd: allocate mark (size %d) failed\n", n+1)) ; return (FALSE) ; } /* === Compute column counts of M, check if A is valid ================== */ stats [COLAMD_INFO3] = 0 ; /* number of duplicate or unsorted row indices*/ for (i = 0 ; i < n ; i++) { mark [i] = -1 ; } for (j = 0 ; j < n ; j++) { last_row = -1 ; length = p [j+1] - p [j] ; if (length < 0) { /* column pointers must be non-decreasing */ stats [COLAMD_STATUS] = COLAMD_ERROR_col_length_negative ; stats [COLAMD_INFO1] = j ; stats [COLAMD_INFO2] = length ; (*release) ((void *) count) ; (*release) ((void *) mark) ; DEBUG0 (("symamd: col %d negative length %d\n", j, length)) ; return (FALSE) ; } for (pp = p [j] ; pp < p [j+1] ; pp++) { i = A [pp] ; if (i < 0 || i >= n) { /* row index i, in column j, is out of bounds */ stats [COLAMD_STATUS] = COLAMD_ERROR_row_index_out_of_bounds ; stats [COLAMD_INFO1] = j ; stats [COLAMD_INFO2] = i ; stats [COLAMD_INFO3] = n ; (*release) ((void *) count) ; (*release) ((void *) mark) ; DEBUG0 (("symamd: row %d col %d out of bounds\n", i, j)) ; return (FALSE) ; } if (i <= last_row || mark [i] == j) { /* row index is unsorted or repeated (or both), thus col */ /* is jumbled. This is a notice, not an error condition. */ stats [COLAMD_STATUS] = COLAMD_OK_BUT_JUMBLED ; stats [COLAMD_INFO1] = j ; stats [COLAMD_INFO2] = i ; (stats [COLAMD_INFO3]) ++ ; DEBUG1 (("symamd: row %d col %d unsorted/duplicate\n", i, j)) ; } if (i > j && mark [i] != j) { /* row k of M will contain column indices i and j */ count [i]++ ; count [j]++ ; } /* mark the row as having been seen in this column */ mark [i] = j ; last_row = i ; } } /* v2.4: removed free(mark) */ /* === Compute column pointers of M ===================================== */ /* use output permutation, perm, for column pointers of M */ perm [0] = 0 ; for (j = 1 ; j <= n ; j++) { perm [j] = perm [j-1] + count [j-1] ; } for (j = 0 ; j < n ; j++) { count [j] = perm [j] ; } /* === Construct M ====================================================== */ mnz = perm [n] ; n_row = mnz / 2 ; Mlen = COLAMD_recommended (mnz, n_row, n) ; M = (Int *) ((*allocate) (Mlen, sizeof (Int))) ; DEBUG0 (("symamd: M is %d-by-%d with %d entries, Mlen = %g\n", n_row, n, mnz, (double) Mlen)) ; if (!M) { stats [COLAMD_STATUS] = COLAMD_ERROR_out_of_memory ; (*release) ((void *) count) ; (*release) ((void *) mark) ; DEBUG0 (("symamd: allocate M (size %g) failed\n", (double) Mlen)) ; return (FALSE) ; } k = 0 ; if (stats [COLAMD_STATUS] == COLAMD_OK) { /* Matrix is OK */ for (j = 0 ; j < n ; j++) { ASSERT (p [j+1] - p [j] >= 0) ; for (pp = p [j] ; pp < p [j+1] ; pp++) { i = A [pp] ; ASSERT (i >= 0 && i < n) ; if (i > j) { /* row k of M contains column indices i and j */ M [count [i]++] = k ; M [count [j]++] = k ; k++ ; } } } } else { /* Matrix is jumbled. Do not add duplicates to M. Unsorted cols OK. */ DEBUG0 (("symamd: Duplicates in A.\n")) ; for (i = 0 ; i < n ; i++) { mark [i] = -1 ; } for (j = 0 ; j < n ; j++) { ASSERT (p [j+1] - p [j] >= 0) ; for (pp = p [j] ; pp < p [j+1] ; pp++) { i = A [pp] ; ASSERT (i >= 0 && i < n) ; if (i > j && mark [i] != j) { /* row k of M contains column indices i and j */ M [count [i]++] = k ; M [count [j]++] = k ; k++ ; mark [i] = j ; } } } /* v2.4: free(mark) moved below */ } /* count and mark no longer needed */ (*release) ((void *) count) ; (*release) ((void *) mark) ; /* v2.4: free (mark) moved here */ ASSERT (k == n_row) ; /* === Adjust the knobs for M =========================================== */ for (i = 0 ; i < COLAMD_KNOBS ; i++) { cknobs [i] = knobs [i] ; } /* there are no dense rows in M */ cknobs [COLAMD_DENSE_ROW] = -1 ; cknobs [COLAMD_DENSE_COL] = knobs [COLAMD_DENSE_ROW] ; /* === Order the columns of M =========================================== */ /* v2.4: colamd cannot fail here, so the error check is removed */ (void) COLAMD_MAIN (n_row, n, (Int) Mlen, M, perm, cknobs, stats) ; /* Note that the output permutation is now in perm */ /* === get the statistics for symamd from colamd ======================== */ /* a dense column in colamd means a dense row and col in symamd */ stats [COLAMD_DENSE_ROW] = stats [COLAMD_DENSE_COL] ; /* === Free M =========================================================== */ (*release) ((void *) M) ; DEBUG0 (("symamd: done.\n")) ; return (TRUE) ; } /* ========================================================================== */ /* === colamd =============================================================== */ /* ========================================================================== */ /* The colamd routine computes a column ordering Q of a sparse matrix A such that the LU factorization P(AQ) = LU remains sparse, where P is selected via partial pivoting. The routine can also be viewed as providing a permutation Q such that the Cholesky factorization (AQ)'(AQ) = LL' remains sparse. */ PUBLIC Int COLAMD_MAIN /* returns TRUE if successful, FALSE otherwise*/ ( /* === Parameters ======================================================= */ Int n_row, /* number of rows in A */ Int n_col, /* number of columns in A */ Int Alen, /* length of A */ Int A [], /* row indices of A */ Int p [], /* pointers to columns in A */ double knobs [COLAMD_KNOBS],/* parameters (uses defaults if NULL) */ Int stats [COLAMD_STATS] /* output statistics and error codes */ ) { /* === Local variables ================================================== */ Int i ; /* loop index */ Int nnz ; /* nonzeros in A */ size_t Row_size ; /* size of Row [], in integers */ size_t Col_size ; /* size of Col [], in integers */ size_t need ; /* minimum required length of A */ Colamd_Row *Row ; /* pointer into A of Row [0..n_row] array */ Colamd_Col *Col ; /* pointer into A of Col [0..n_col] array */ Int n_col2 ; /* number of non-dense, non-empty columns */ Int n_row2 ; /* number of non-dense, non-empty rows */ Int ngarbage ; /* number of garbage collections performed */ Int max_deg ; /* maximum row degree */ double default_knobs [COLAMD_KNOBS] ; /* default knobs array */ Int aggressive ; /* do aggressive absorption */ int ok ; #ifndef NDEBUG colamd_get_debug ("colamd") ; #endif /* NDEBUG */ /* === Check the input arguments ======================================== */ if (!stats) { DEBUG0 (("colamd: stats not present\n")) ; return (FALSE) ; } for (i = 0 ; i < COLAMD_STATS ; i++) { stats [i] = 0 ; } stats [COLAMD_STATUS] = COLAMD_OK ; stats [COLAMD_INFO1] = -1 ; stats [COLAMD_INFO2] = -1 ; if (!A) /* A is not present */ { stats [COLAMD_STATUS] = COLAMD_ERROR_A_not_present ; DEBUG0 (("colamd: A not present\n")) ; return (FALSE) ; } if (!p) /* p is not present */ { stats [COLAMD_STATUS] = COLAMD_ERROR_p_not_present ; DEBUG0 (("colamd: p not present\n")) ; return (FALSE) ; } if (n_row < 0) /* n_row must be >= 0 */ { stats [COLAMD_STATUS] = COLAMD_ERROR_nrow_negative ; stats [COLAMD_INFO1] = n_row ; DEBUG0 (("colamd: nrow negative %d\n", n_row)) ; return (FALSE) ; } if (n_col < 0) /* n_col must be >= 0 */ { stats [COLAMD_STATUS] = COLAMD_ERROR_ncol_negative ; stats [COLAMD_INFO1] = n_col ; DEBUG0 (("colamd: ncol negative %d\n", n_col)) ; return (FALSE) ; } nnz = p [n_col] ; if (nnz < 0) /* nnz must be >= 0 */ { stats [COLAMD_STATUS] = COLAMD_ERROR_nnz_negative ; stats [COLAMD_INFO1] = nnz ; DEBUG0 (("colamd: number of entries negative %d\n", nnz)) ; return (FALSE) ; } if (p [0] != 0) { stats [COLAMD_STATUS] = COLAMD_ERROR_p0_nonzero ; stats [COLAMD_INFO1] = p [0] ; DEBUG0 (("colamd: p[0] not zero %d\n", p [0])) ; return (FALSE) ; } /* === If no knobs, set default knobs =================================== */ if (!knobs) { COLAMD_set_defaults (default_knobs) ; knobs = default_knobs ; } aggressive = (knobs [COLAMD_AGGRESSIVE] != FALSE) ; /* === Allocate the Row and Col arrays from array A ===================== */ ok = TRUE ; Col_size = COLAMD_C (n_col, &ok) ; /* size of Col array of structs */ Row_size = COLAMD_R (n_row, &ok) ; /* size of Row array of structs */ /* need = 2*nnz + n_col + Col_size + Row_size ; */ need = t_mult (nnz, 2, &ok) ; need = t_add (need, n_col, &ok) ; need = t_add (need, Col_size, &ok) ; need = t_add (need, Row_size, &ok) ; if (!ok || need > (size_t) Alen || need > Int_MAX) { /* not enough space in array A to perform the ordering */ stats [COLAMD_STATUS] = COLAMD_ERROR_A_too_small ; stats [COLAMD_INFO1] = need ; stats [COLAMD_INFO2] = Alen ; DEBUG0 (("colamd: Need Alen >= %d, given only Alen = %d\n", need,Alen)); return (FALSE) ; } Alen -= Col_size + Row_size ; Col = (Colamd_Col *) &A [Alen] ; Row = (Colamd_Row *) &A [Alen + Col_size] ; /* === Construct the row and column data structures ===================== */ if (!init_rows_cols (n_row, n_col, Row, Col, A, p, stats)) { /* input matrix is invalid */ DEBUG0 (("colamd: Matrix invalid\n")) ; return (FALSE) ; } /* === Initialize scores, kill dense rows/columns ======================= */ init_scoring (n_row, n_col, Row, Col, A, p, knobs, &n_row2, &n_col2, &max_deg) ; /* === Order the supercolumns =========================================== */ ngarbage = find_ordering (n_row, n_col, Alen, Row, Col, A, p, n_col2, max_deg, 2*nnz, aggressive) ; /* === Order the non-principal columns ================================== */ order_children (n_col, Col, p) ; /* === Return statistics in stats ======================================= */ stats [COLAMD_DENSE_ROW] = n_row - n_row2 ; stats [COLAMD_DENSE_COL] = n_col - n_col2 ; stats [COLAMD_DEFRAG_COUNT] = ngarbage ; DEBUG0 (("colamd: done.\n")) ; return (TRUE) ; } /* ========================================================================== */ /* === colamd_report ======================================================== */ /* ========================================================================== */ PUBLIC void COLAMD_report ( Int stats [COLAMD_STATS] ) { print_report ("colamd", stats) ; } /* ========================================================================== */ /* === symamd_report ======================================================== */ /* ========================================================================== */ PUBLIC void SYMAMD_report ( Int stats [COLAMD_STATS] ) { print_report ("symamd", stats) ; } /* ========================================================================== */ /* === NON-USER-CALLABLE ROUTINES: ========================================== */ /* ========================================================================== */ /* There are no user-callable routines beyond this point in the file */ /* ========================================================================== */ /* === init_rows_cols ======================================================= */ /* ========================================================================== */ /* Takes the column form of the matrix in A and creates the row form of the matrix. Also, row and column attributes are stored in the Col and Row structs. If the columns are un-sorted or contain duplicate row indices, this routine will also sort and remove duplicate row indices from the column form of the matrix. Returns FALSE if the matrix is invalid, TRUE otherwise. Not user-callable. */ PRIVATE Int init_rows_cols /* returns TRUE if OK, or FALSE otherwise */ ( /* === Parameters ======================================================= */ Int n_row, /* number of rows of A */ Int n_col, /* number of columns of A */ Colamd_Row Row [], /* of size n_row+1 */ Colamd_Col Col [], /* of size n_col+1 */ Int A [], /* row indices of A, of size Alen */ Int p [], /* pointers to columns in A, of size n_col+1 */ Int stats [COLAMD_STATS] /* colamd statistics */ ) { /* === Local variables ================================================== */ Int col ; /* a column index */ Int row ; /* a row index */ Int *cp ; /* a column pointer */ Int *cp_end ; /* a pointer to the end of a column */ Int *rp ; /* a row pointer */ Int *rp_end ; /* a pointer to the end of a row */ Int last_row ; /* previous row */ /* === Initialize columns, and check column pointers ==================== */ for (col = 0 ; col < n_col ; col++) { Col [col].start = p [col] ; Col [col].length = p [col+1] - p [col] ; if (Col [col].length < 0) { /* column pointers must be non-decreasing */ stats [COLAMD_STATUS] = COLAMD_ERROR_col_length_negative ; stats [COLAMD_INFO1] = col ; stats [COLAMD_INFO2] = Col [col].length ; DEBUG0 (("colamd: col %d length %d < 0\n", col, Col [col].length)) ; return (FALSE) ; } Col [col].shared1.thickness = 1 ; Col [col].shared2.score = 0 ; Col [col].shared3.prev = EMPTY ; Col [col].shared4.degree_next = EMPTY ; } /* p [0..n_col] no longer needed, used as "head" in subsequent routines */ /* === Scan columns, compute row degrees, and check row indices ========= */ stats [COLAMD_INFO3] = 0 ; /* number of duplicate or unsorted row indices*/ for (row = 0 ; row < n_row ; row++) { Row [row].length = 0 ; Row [row].shared2.mark = -1 ; } for (col = 0 ; col < n_col ; col++) { last_row = -1 ; cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { row = *cp++ ; /* make sure row indices within range */ if (row < 0 || row >= n_row) { stats [COLAMD_STATUS] = COLAMD_ERROR_row_index_out_of_bounds ; stats [COLAMD_INFO1] = col ; stats [COLAMD_INFO2] = row ; stats [COLAMD_INFO3] = n_row ; DEBUG0 (("colamd: row %d col %d out of bounds\n", row, col)) ; return (FALSE) ; } if (row <= last_row || Row [row].shared2.mark == col) { /* row index are unsorted or repeated (or both), thus col */ /* is jumbled. This is a notice, not an error condition. */ stats [COLAMD_STATUS] = COLAMD_OK_BUT_JUMBLED ; stats [COLAMD_INFO1] = col ; stats [COLAMD_INFO2] = row ; (stats [COLAMD_INFO3]) ++ ; DEBUG1 (("colamd: row %d col %d unsorted/duplicate\n",row,col)); } if (Row [row].shared2.mark != col) { Row [row].length++ ; } else { /* this is a repeated entry in the column, */ /* it will be removed */ Col [col].length-- ; } /* mark the row as having been seen in this column */ Row [row].shared2.mark = col ; last_row = row ; } } /* === Compute row pointers ============================================= */ /* row form of the matrix starts directly after the column */ /* form of matrix in A */ Row [0].start = p [n_col] ; Row [0].shared1.p = Row [0].start ; Row [0].shared2.mark = -1 ; for (row = 1 ; row < n_row ; row++) { Row [row].start = Row [row-1].start + Row [row-1].length ; Row [row].shared1.p = Row [row].start ; Row [row].shared2.mark = -1 ; } /* === Create row form ================================================== */ if (stats [COLAMD_STATUS] == COLAMD_OK_BUT_JUMBLED) { /* if cols jumbled, watch for repeated row indices */ for (col = 0 ; col < n_col ; col++) { cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { row = *cp++ ; if (Row [row].shared2.mark != col) { A [(Row [row].shared1.p)++] = col ; Row [row].shared2.mark = col ; } } } } else { /* if cols not jumbled, we don't need the mark (this is faster) */ for (col = 0 ; col < n_col ; col++) { cp = &A [p [col]] ; cp_end = &A [p [col+1]] ; while (cp < cp_end) { A [(Row [*cp++].shared1.p)++] = col ; } } } /* === Clear the row marks and set row degrees ========================== */ for (row = 0 ; row < n_row ; row++) { Row [row].shared2.mark = 0 ; Row [row].shared1.degree = Row [row].length ; } /* === See if we need to re-create columns ============================== */ if (stats [COLAMD_STATUS] == COLAMD_OK_BUT_JUMBLED) { DEBUG0 (("colamd: reconstructing column form, matrix jumbled\n")) ; #ifndef NDEBUG /* make sure column lengths are correct */ for (col = 0 ; col < n_col ; col++) { p [col] = Col [col].length ; } for (row = 0 ; row < n_row ; row++) { rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { p [*rp++]-- ; } } for (col = 0 ; col < n_col ; col++) { ASSERT (p [col] == 0) ; } /* now p is all zero (different than when debugging is turned off) */ #endif /* NDEBUG */ /* === Compute col pointers ========================================= */ /* col form of the matrix starts at A [0]. */ /* Note, we may have a gap between the col form and the row */ /* form if there were duplicate entries, if so, it will be */ /* removed upon the first garbage collection */ Col [0].start = 0 ; p [0] = Col [0].start ; for (col = 1 ; col < n_col ; col++) { /* note that the lengths here are for pruned columns, i.e. */ /* no duplicate row indices will exist for these columns */ Col [col].start = Col [col-1].start + Col [col-1].length ; p [col] = Col [col].start ; } /* === Re-create col form =========================================== */ for (row = 0 ; row < n_row ; row++) { rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { A [(p [*rp++])++] = row ; } } } /* === Done. Matrix is not (or no longer) jumbled ====================== */ return (TRUE) ; } /* ========================================================================== */ /* === init_scoring ========================================================= */ /* ========================================================================== */ /* Kills dense or empty columns and rows, calculates an initial score for each column, and places all columns in the degree lists. Not user-callable. */ PRIVATE void init_scoring ( /* === Parameters ======================================================= */ Int n_row, /* number of rows of A */ Int n_col, /* number of columns of A */ Colamd_Row Row [], /* of size n_row+1 */ Colamd_Col Col [], /* of size n_col+1 */ Int A [], /* column form and row form of A */ Int head [], /* of size n_col+1 */ double knobs [COLAMD_KNOBS],/* parameters */ Int *p_n_row2, /* number of non-dense, non-empty rows */ Int *p_n_col2, /* number of non-dense, non-empty columns */ Int *p_max_deg /* maximum row degree */ ) { /* === Local variables ================================================== */ Int c ; /* a column index */ Int r, row ; /* a row index */ Int *cp ; /* a column pointer */ Int deg ; /* degree of a row or column */ Int *cp_end ; /* a pointer to the end of a column */ Int *new_cp ; /* new column pointer */ Int col_length ; /* length of pruned column */ Int score ; /* current column score */ Int n_col2 ; /* number of non-dense, non-empty columns */ Int n_row2 ; /* number of non-dense, non-empty rows */ Int dense_row_count ; /* remove rows with more entries than this */ Int dense_col_count ; /* remove cols with more entries than this */ Int min_score ; /* smallest column score */ Int max_deg ; /* maximum row degree */ Int next_col ; /* Used to add to degree list.*/ #ifndef NDEBUG Int debug_count ; /* debug only. */ #endif /* NDEBUG */ /* === Extract knobs ==================================================== */ /* Note: if knobs contains a NaN, this is undefined: */ if (knobs [COLAMD_DENSE_ROW] < 0) { /* only remove completely dense rows */ dense_row_count = n_col-1 ; } else { dense_row_count = DENSE_DEGREE (knobs [COLAMD_DENSE_ROW], n_col) ; } if (knobs [COLAMD_DENSE_COL] < 0) { /* only remove completely dense columns */ dense_col_count = n_row-1 ; } else { dense_col_count = DENSE_DEGREE (knobs [COLAMD_DENSE_COL], MIN (n_row, n_col)) ; } DEBUG1 (("colamd: densecount: %d %d\n", dense_row_count, dense_col_count)) ; max_deg = 0 ; n_col2 = n_col ; n_row2 = n_row ; /* === Kill empty columns =============================================== */ /* Put the empty columns at the end in their natural order, so that LU */ /* factorization can proceed as far as possible. */ for (c = n_col-1 ; c >= 0 ; c--) { deg = Col [c].length ; if (deg == 0) { /* this is a empty column, kill and order it last */ Col [c].shared2.order = --n_col2 ; KILL_PRINCIPAL_COL (c) ; } } DEBUG1 (("colamd: null columns killed: %d\n", n_col - n_col2)) ; /* === Kill dense columns =============================================== */ /* Put the dense columns at the end, in their natural order */ for (c = n_col-1 ; c >= 0 ; c--) { /* skip any dead columns */ if (COL_IS_DEAD (c)) { continue ; } deg = Col [c].length ; if (deg > dense_col_count) { /* this is a dense column, kill and order it last */ Col [c].shared2.order = --n_col2 ; /* decrement the row degrees */ cp = &A [Col [c].start] ; cp_end = cp + Col [c].length ; while (cp < cp_end) { Row [*cp++].shared1.degree-- ; } KILL_PRINCIPAL_COL (c) ; } } DEBUG1 (("colamd: Dense and null columns killed: %d\n", n_col - n_col2)) ; /* === Kill dense and empty rows ======================================== */ for (r = 0 ; r < n_row ; r++) { deg = Row [r].shared1.degree ; ASSERT (deg >= 0 && deg <= n_col) ; if (deg > dense_row_count || deg == 0) { /* kill a dense or empty row */ KILL_ROW (r) ; --n_row2 ; } else { /* keep track of max degree of remaining rows */ max_deg = MAX (max_deg, deg) ; } } DEBUG1 (("colamd: Dense and null rows killed: %d\n", n_row - n_row2)) ; /* === Compute initial column scores ==================================== */ /* At this point the row degrees are accurate. They reflect the number */ /* of "live" (non-dense) columns in each row. No empty rows exist. */ /* Some "live" columns may contain only dead rows, however. These are */ /* pruned in the code below. */ /* now find the initial matlab score for each column */ for (c = n_col-1 ; c >= 0 ; c--) { /* skip dead column */ if (COL_IS_DEAD (c)) { continue ; } score = 0 ; cp = &A [Col [c].start] ; new_cp = cp ; cp_end = cp + Col [c].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; /* skip if dead */ if (ROW_IS_DEAD (row)) { continue ; } /* compact the column */ *new_cp++ = row ; /* add row's external degree */ score += Row [row].shared1.degree - 1 ; /* guard against integer overflow */ score = MIN (score, n_col) ; } /* determine pruned column length */ col_length = (Int) (new_cp - &A [Col [c].start]) ; if (col_length == 0) { /* a newly-made null column (all rows in this col are "dense" */ /* and have already been killed) */ DEBUG2 (("Newly null killed: %d\n", c)) ; Col [c].shared2.order = --n_col2 ; KILL_PRINCIPAL_COL (c) ; } else { /* set column length and set score */ ASSERT (score >= 0) ; ASSERT (score <= n_col) ; Col [c].length = col_length ; Col [c].shared2.score = score ; } } DEBUG1 (("colamd: Dense, null, and newly-null columns killed: %d\n", n_col-n_col2)) ; /* At this point, all empty rows and columns are dead. All live columns */ /* are "clean" (containing no dead rows) and simplicial (no supercolumns */ /* yet). Rows may contain dead columns, but all live rows contain at */ /* least one live column. */ #ifndef NDEBUG debug_structures (n_row, n_col, Row, Col, A, n_col2) ; #endif /* NDEBUG */ /* === Initialize degree lists ========================================== */ #ifndef NDEBUG debug_count = 0 ; #endif /* NDEBUG */ /* clear the hash buckets */ for (c = 0 ; c <= n_col ; c++) { head [c] = EMPTY ; } min_score = n_col ; /* place in reverse order, so low column indices are at the front */ /* of the lists. This is to encourage natural tie-breaking */ for (c = n_col-1 ; c >= 0 ; c--) { /* only add principal columns to degree lists */ if (COL_IS_ALIVE (c)) { DEBUG4 (("place %d score %d minscore %d ncol %d\n", c, Col [c].shared2.score, min_score, n_col)) ; /* === Add columns score to DList =============================== */ score = Col [c].shared2.score ; ASSERT (min_score >= 0) ; ASSERT (min_score <= n_col) ; ASSERT (score >= 0) ; ASSERT (score <= n_col) ; ASSERT (head [score] >= EMPTY) ; /* now add this column to dList at proper score location */ next_col = head [score] ; Col [c].shared3.prev = EMPTY ; Col [c].shared4.degree_next = next_col ; /* if there already was a column with the same score, set its */ /* previous pointer to this new column */ if (next_col != EMPTY) { Col [next_col].shared3.prev = c ; } head [score] = c ; /* see if this score is less than current min */ min_score = MIN (min_score, score) ; #ifndef NDEBUG debug_count++ ; #endif /* NDEBUG */ } } #ifndef NDEBUG DEBUG1 (("colamd: Live cols %d out of %d, non-princ: %d\n", debug_count, n_col, n_col-debug_count)) ; ASSERT (debug_count == n_col2) ; debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2, max_deg) ; #endif /* NDEBUG */ /* === Return number of remaining columns, and max row degree =========== */ *p_n_col2 = n_col2 ; *p_n_row2 = n_row2 ; *p_max_deg = max_deg ; } /* ========================================================================== */ /* === find_ordering ======================================================== */ /* ========================================================================== */ /* Order the principal columns of the supercolumn form of the matrix (no supercolumns on input). Uses a minimum approximate column minimum degree ordering method. Not user-callable. */ PRIVATE Int find_ordering /* return the number of garbage collections */ ( /* === Parameters ======================================================= */ Int n_row, /* number of rows of A */ Int n_col, /* number of columns of A */ Int Alen, /* size of A, 2*nnz + n_col or larger */ Colamd_Row Row [], /* of size n_row+1 */ Colamd_Col Col [], /* of size n_col+1 */ Int A [], /* column form and row form of A */ Int head [], /* of size n_col+1 */ Int n_col2, /* Remaining columns to order */ Int max_deg, /* Maximum row degree */ Int pfree, /* index of first free slot (2*nnz on entry) */ Int aggressive ) { /* === Local variables ================================================== */ Int k ; /* current pivot ordering step */ Int pivot_col ; /* current pivot column */ Int *cp ; /* a column pointer */ Int *rp ; /* a row pointer */ Int pivot_row ; /* current pivot row */ Int *new_cp ; /* modified column pointer */ Int *new_rp ; /* modified row pointer */ Int pivot_row_start ; /* pointer to start of pivot row */ Int pivot_row_degree ; /* number of columns in pivot row */ Int pivot_row_length ; /* number of supercolumns in pivot row */ Int pivot_col_score ; /* score of pivot column */ Int needed_memory ; /* free space needed for pivot row */ Int *cp_end ; /* pointer to the end of a column */ Int *rp_end ; /* pointer to the end of a row */ Int row ; /* a row index */ Int col ; /* a column index */ Int max_score ; /* maximum possible score */ Int cur_score ; /* score of current column */ unsigned Int hash ; /* hash value for supernode detection */ Int head_column ; /* head of hash bucket */ Int first_col ; /* first column in hash bucket */ Int tag_mark ; /* marker value for mark array */ Int row_mark ; /* Row [row].shared2.mark */ Int set_difference ; /* set difference size of row with pivot row */ Int min_score ; /* smallest column score */ Int col_thickness ; /* "thickness" (no. of columns in a supercol) */ Int max_mark ; /* maximum value of tag_mark */ Int pivot_col_thickness ; /* number of columns represented by pivot col */ Int prev_col ; /* Used by Dlist operations. */ Int next_col ; /* Used by Dlist operations. */ Int ngarbage ; /* number of garbage collections performed */ #ifndef NDEBUG Int debug_d ; /* debug loop counter */ Int debug_step = 0 ; /* debug loop counter */ #endif /* NDEBUG */ /* === Initialization and clear mark ==================================== */ max_mark = INT_MAX - n_col ; /* INT_MAX defined in */ tag_mark = clear_mark (0, max_mark, n_row, Row) ; min_score = 0 ; ngarbage = 0 ; DEBUG1 (("colamd: Ordering, n_col2=%d\n", n_col2)) ; /* === Order the columns ================================================ */ for (k = 0 ; k < n_col2 ; /* 'k' is incremented below */) { #ifndef NDEBUG if (debug_step % 100 == 0) { DEBUG2 (("\n... Step k: %d out of n_col2: %d\n", k, n_col2)) ; } else { DEBUG3 (("\n----------Step k: %d out of n_col2: %d\n", k, n_col2)) ; } debug_step++ ; debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k, max_deg) ; debug_matrix (n_row, n_col, Row, Col, A) ; #endif /* NDEBUG */ /* === Select pivot column, and order it ============================ */ /* make sure degree list isn't empty */ ASSERT (min_score >= 0) ; ASSERT (min_score <= n_col) ; ASSERT (head [min_score] >= EMPTY) ; #ifndef NDEBUG for (debug_d = 0 ; debug_d < min_score ; debug_d++) { ASSERT (head [debug_d] == EMPTY) ; } #endif /* NDEBUG */ /* get pivot column from head of minimum degree list */ while (head [min_score] == EMPTY && min_score < n_col) { min_score++ ; } pivot_col = head [min_score] ; ASSERT (pivot_col >= 0 && pivot_col <= n_col) ; next_col = Col [pivot_col].shared4.degree_next ; head [min_score] = next_col ; if (next_col != EMPTY) { Col [next_col].shared3.prev = EMPTY ; } ASSERT (COL_IS_ALIVE (pivot_col)) ; /* remember score for defrag check */ pivot_col_score = Col [pivot_col].shared2.score ; /* the pivot column is the kth column in the pivot order */ Col [pivot_col].shared2.order = k ; /* increment order count by column thickness */ pivot_col_thickness = Col [pivot_col].shared1.thickness ; k += pivot_col_thickness ; ASSERT (pivot_col_thickness > 0) ; DEBUG3 (("Pivot col: %d thick %d\n", pivot_col, pivot_col_thickness)) ; /* === Garbage_collection, if necessary ============================= */ needed_memory = MIN (pivot_col_score, n_col - k) ; if (pfree + needed_memory >= Alen) { pfree = garbage_collection (n_row, n_col, Row, Col, A, &A [pfree]) ; ngarbage++ ; /* after garbage collection we will have enough */ ASSERT (pfree + needed_memory < Alen) ; /* garbage collection has wiped out the Row[].shared2.mark array */ tag_mark = clear_mark (0, max_mark, n_row, Row) ; #ifndef NDEBUG debug_matrix (n_row, n_col, Row, Col, A) ; #endif /* NDEBUG */ } /* === Compute pivot row pattern ==================================== */ /* get starting location for this new merged row */ pivot_row_start = pfree ; /* initialize new row counts to zero */ pivot_row_degree = 0 ; /* tag pivot column as having been visited so it isn't included */ /* in merged pivot row */ Col [pivot_col].shared1.thickness = -pivot_col_thickness ; /* pivot row is the union of all rows in the pivot column pattern */ cp = &A [Col [pivot_col].start] ; cp_end = cp + Col [pivot_col].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; DEBUG4 (("Pivot col pattern %d %d\n", ROW_IS_ALIVE (row), row)) ; /* skip if row is dead */ if (ROW_IS_ALIVE (row)) { rp = &A [Row [row].start] ; rp_end = rp + Row [row].length ; while (rp < rp_end) { /* get a column */ col = *rp++ ; /* add the column, if alive and untagged */ col_thickness = Col [col].shared1.thickness ; if (col_thickness > 0 && COL_IS_ALIVE (col)) { /* tag column in pivot row */ Col [col].shared1.thickness = -col_thickness ; ASSERT (pfree < Alen) ; /* place column in pivot row */ A [pfree++] = col ; pivot_row_degree += col_thickness ; } } } } /* clear tag on pivot column */ Col [pivot_col].shared1.thickness = pivot_col_thickness ; max_deg = MAX (max_deg, pivot_row_degree) ; #ifndef NDEBUG DEBUG3 (("check2\n")) ; debug_mark (n_row, Row, tag_mark, max_mark) ; #endif /* NDEBUG */ /* === Kill all rows used to construct pivot row ==================== */ /* also kill pivot row, temporarily */ cp = &A [Col [pivot_col].start] ; cp_end = cp + Col [pivot_col].length ; while (cp < cp_end) { /* may be killing an already dead row */ row = *cp++ ; DEBUG3 (("Kill row in pivot col: %d\n", row)) ; KILL_ROW (row) ; } /* === Select a row index to use as the new pivot row =============== */ pivot_row_length = pfree - pivot_row_start ; if (pivot_row_length > 0) { /* pick the "pivot" row arbitrarily (first row in col) */ pivot_row = A [Col [pivot_col].start] ; DEBUG3 (("Pivotal row is %d\n", pivot_row)) ; } else { /* there is no pivot row, since it is of zero length */ pivot_row = EMPTY ; ASSERT (pivot_row_length == 0) ; } ASSERT (Col [pivot_col].length > 0 || pivot_row_length == 0) ; /* === Approximate degree computation =============================== */ /* Here begins the computation of the approximate degree. The column */ /* score is the sum of the pivot row "length", plus the size of the */ /* set differences of each row in the column minus the pattern of the */ /* pivot row itself. The column ("thickness") itself is also */ /* excluded from the column score (we thus use an approximate */ /* external degree). */ /* The time taken by the following code (compute set differences, and */ /* add them up) is proportional to the size of the data structure */ /* being scanned - that is, the sum of the sizes of each column in */ /* the pivot row. Thus, the amortized time to compute a column score */ /* is proportional to the size of that column (where size, in this */ /* context, is the column "length", or the number of row indices */ /* in that column). The number of row indices in a column is */ /* monotonically non-decreasing, from the length of the original */ /* column on input to colamd. */ /* === Compute set differences ====================================== */ DEBUG3 (("** Computing set differences phase. **\n")) ; /* pivot row is currently dead - it will be revived later. */ DEBUG3 (("Pivot row: ")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { col = *rp++ ; ASSERT (COL_IS_ALIVE (col) && col != pivot_col) ; DEBUG3 (("Col: %d\n", col)) ; /* clear tags used to construct pivot row pattern */ col_thickness = -Col [col].shared1.thickness ; ASSERT (col_thickness > 0) ; Col [col].shared1.thickness = col_thickness ; /* === Remove column from degree list =========================== */ cur_score = Col [col].shared2.score ; prev_col = Col [col].shared3.prev ; next_col = Col [col].shared4.degree_next ; ASSERT (cur_score >= 0) ; ASSERT (cur_score <= n_col) ; ASSERT (cur_score >= EMPTY) ; if (prev_col == EMPTY) { head [cur_score] = next_col ; } else { Col [prev_col].shared4.degree_next = next_col ; } if (next_col != EMPTY) { Col [next_col].shared3.prev = prev_col ; } /* === Scan the column ========================================== */ cp = &A [Col [col].start] ; cp_end = cp + Col [col].length ; while (cp < cp_end) { /* get a row */ row = *cp++ ; row_mark = Row [row].shared2.mark ; /* skip if dead */ if (ROW_IS_MARKED_DEAD (row_mark)) { continue ; } ASSERT (row != pivot_row) ; set_difference = row_mark - tag_mark ; /* check if the row has been seen yet */ if (set_difference < 0) { ASSERT (Row [row].shared1.degree <= max_deg) ; set_difference = Row [row].shared1.degree ; } /* subtract column thickness from this row's set difference */ set_difference -= col_thickness ; ASSERT (set_difference >= 0) ; /* absorb this row if the set difference becomes zero */ if (set_difference == 0 && aggressive) { DEBUG3 (("aggressive absorption. Row: %d\n", row)) ; KILL_ROW (row) ; } else { /* save the new mark */ Row [row].shared2.mark = set_difference + tag_mark ; } } } #ifndef NDEBUG debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k-pivot_row_degree, max_deg) ; #endif /* NDEBUG */ /* === Add up set differences for each column ======================= */ DEBUG3 (("** Adding set differences phase. **\n")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { /* get a column */ col = *rp++ ; ASSERT (COL_IS_ALIVE (col) && col != pivot_col) ; hash = 0 ; cur_score = 0 ; cp = &A [Col [col].start] ; /* compact the column */ new_cp = cp ; cp_end = cp + Col [col].length ; DEBUG4 (("Adding set diffs for Col: %d.\n", col)) ; while (cp < cp_end) { /* get a row */ row = *cp++ ; ASSERT(row >= 0 && row < n_row) ; row_mark = Row [row].shared2.mark ; /* skip if dead */ if (ROW_IS_MARKED_DEAD (row_mark)) { DEBUG4 ((" Row %d, dead\n", row)) ; continue ; } DEBUG4 ((" Row %d, set diff %d\n", row, row_mark-tag_mark)); ASSERT (row_mark >= tag_mark) ; /* compact the column */ *new_cp++ = row ; /* compute hash function */ hash += row ; /* add set difference */ cur_score += row_mark - tag_mark ; /* integer overflow... */ cur_score = MIN (cur_score, n_col) ; } /* recompute the column's length */ Col [col].length = (Int) (new_cp - &A [Col [col].start]) ; /* === Further mass elimination ================================= */ if (Col [col].length == 0) { DEBUG4 (("further mass elimination. Col: %d\n", col)) ; /* nothing left but the pivot row in this column */ KILL_PRINCIPAL_COL (col) ; pivot_row_degree -= Col [col].shared1.thickness ; ASSERT (pivot_row_degree >= 0) ; /* order it */ Col [col].shared2.order = k ; /* increment order count by column thickness */ k += Col [col].shared1.thickness ; } else { /* === Prepare for supercolumn detection ==================== */ DEBUG4 (("Preparing supercol detection for Col: %d.\n", col)) ; /* save score so far */ Col [col].shared2.score = cur_score ; /* add column to hash table, for supercolumn detection */ hash %= n_col + 1 ; DEBUG4 ((" Hash = %d, n_col = %d.\n", hash, n_col)) ; ASSERT (((Int) hash) <= n_col) ; head_column = head [hash] ; if (head_column > EMPTY) { /* degree list "hash" is non-empty, use prev (shared3) of */ /* first column in degree list as head of hash bucket */ first_col = Col [head_column].shared3.headhash ; Col [head_column].shared3.headhash = col ; } else { /* degree list "hash" is empty, use head as hash bucket */ first_col = - (head_column + 2) ; head [hash] = - (col + 2) ; } Col [col].shared4.hash_next = first_col ; /* save hash function in Col [col].shared3.hash */ Col [col].shared3.hash = (Int) hash ; ASSERT (COL_IS_ALIVE (col)) ; } } /* The approximate external column degree is now computed. */ /* === Supercolumn detection ======================================== */ DEBUG3 (("** Supercolumn detection phase. **\n")) ; detect_super_cols ( #ifndef NDEBUG n_col, Row, #endif /* NDEBUG */ Col, A, head, pivot_row_start, pivot_row_length) ; /* === Kill the pivotal column ====================================== */ KILL_PRINCIPAL_COL (pivot_col) ; /* === Clear mark =================================================== */ tag_mark = clear_mark (tag_mark+max_deg+1, max_mark, n_row, Row) ; #ifndef NDEBUG DEBUG3 (("check3\n")) ; debug_mark (n_row, Row, tag_mark, max_mark) ; #endif /* NDEBUG */ /* === Finalize the new pivot row, and column scores ================ */ DEBUG3 (("** Finalize scores phase. **\n")) ; /* for each column in pivot row */ rp = &A [pivot_row_start] ; /* compact the pivot row */ new_rp = rp ; rp_end = rp + pivot_row_length ; while (rp < rp_end) { col = *rp++ ; /* skip dead columns */ if (COL_IS_DEAD (col)) { continue ; } *new_rp++ = col ; /* add new pivot row to column */ A [Col [col].start + (Col [col].length++)] = pivot_row ; /* retrieve score so far and add on pivot row's degree. */ /* (we wait until here for this in case the pivot */ /* row's degree was reduced due to mass elimination). */ cur_score = Col [col].shared2.score + pivot_row_degree ; /* calculate the max possible score as the number of */ /* external columns minus the 'k' value minus the */ /* columns thickness */ max_score = n_col - k - Col [col].shared1.thickness ; /* make the score the external degree of the union-of-rows */ cur_score -= Col [col].shared1.thickness ; /* make sure score is less or equal than the max score */ cur_score = MIN (cur_score, max_score) ; ASSERT (cur_score >= 0) ; /* store updated score */ Col [col].shared2.score = cur_score ; /* === Place column back in degree list ========================= */ ASSERT (min_score >= 0) ; ASSERT (min_score <= n_col) ; ASSERT (cur_score >= 0) ; ASSERT (cur_score <= n_col) ; ASSERT (head [cur_score] >= EMPTY) ; next_col = head [cur_score] ; Col [col].shared4.degree_next = next_col ; Col [col].shared3.prev = EMPTY ; if (next_col != EMPTY) { Col [next_col].shared3.prev = col ; } head [cur_score] = col ; /* see if this score is less than current min */ min_score = MIN (min_score, cur_score) ; } #ifndef NDEBUG debug_deg_lists (n_row, n_col, Row, Col, head, min_score, n_col2-k, max_deg) ; #endif /* NDEBUG */ /* === Resurrect the new pivot row ================================== */ if (pivot_row_degree > 0) { /* update pivot row length to reflect any cols that were killed */ /* during super-col detection and mass elimination */ Row [pivot_row].start = pivot_row_start ; Row [pivot_row].length = (Int) (new_rp - &A[pivot_row_start]) ; ASSERT (Row [pivot_row].length > 0) ; Row [pivot_row].shared1.degree = pivot_row_degree ; Row [pivot_row].shared2.mark = 0 ; /* pivot row is no longer dead */ DEBUG1 (("Resurrect Pivot_row %d deg: %d\n", pivot_row, pivot_row_degree)) ; } } /* === All principal columns have now been ordered ====================== */ return (ngarbage) ; } /* ========================================================================== */ /* === order_children ======================================================= */ /* ========================================================================== */ /* The find_ordering routine has ordered all of the principal columns (the representatives of the supercolumns). The non-principal columns have not yet been ordered. This routine orders those columns by walking up the parent tree (a column is a child of the column which absorbed it). The final permutation vector is then placed in p [0 ... n_col-1], with p [0] being the first column, and p [n_col-1] being the last. It doesn't look like it at first glance, but be assured that this routine takes time linear in the number of columns. Although not immediately obvious, the time taken by this routine is O (n_col), that is, linear in the number of columns. Not user-callable. */ PRIVATE void order_children ( /* === Parameters ======================================================= */ Int n_col, /* number of columns of A */ Colamd_Col Col [], /* of size n_col+1 */ Int p [] /* p [0 ... n_col-1] is the column permutation*/ ) { /* === Local variables ================================================== */ Int i ; /* loop counter for all columns */ Int c ; /* column index */ Int parent ; /* index of column's parent */ Int order ; /* column's order */ /* === Order each non-principal column ================================== */ for (i = 0 ; i < n_col ; i++) { /* find an un-ordered non-principal column */ ASSERT (COL_IS_DEAD (i)) ; if (!COL_IS_DEAD_PRINCIPAL (i) && Col [i].shared2.order == EMPTY) { parent = i ; /* once found, find its principal parent */ do { parent = Col [parent].shared1.parent ; } while (!COL_IS_DEAD_PRINCIPAL (parent)) ; /* now, order all un-ordered non-principal columns along path */ /* to this parent. collapse tree at the same time */ c = i ; /* get order of parent */ order = Col [parent].shared2.order ; do { ASSERT (Col [c].shared2.order == EMPTY) ; /* order this column */ Col [c].shared2.order = order++ ; /* collaps tree */ Col [c].shared1.parent = parent ; /* get immediate parent of this column */ c = Col [c].shared1.parent ; /* continue until we hit an ordered column. There are */ /* guarranteed not to be anymore unordered columns */ /* above an ordered column */ } while (Col [c].shared2.order == EMPTY) ; /* re-order the super_col parent to largest order for this group */ Col [parent].shared2.order = order ; } } /* === Generate the permutation ========================================= */ for (c = 0 ; c < n_col ; c++) { p [Col [c].shared2.order] = c ; } } /* ========================================================================== */ /* === detect_super_cols ==================================================== */ /* ========================================================================== */ /* Detects supercolumns by finding matches between columns in the hash buckets. Check amongst columns in the set A [row_start ... row_start + row_length-1]. The columns under consideration are currently *not* in the degree lists, and have already been placed in the hash buckets. The hash bucket for columns whose hash function is equal to h is stored as follows: if head [h] is >= 0, then head [h] contains a degree list, so: head [h] is the first column in degree bucket h. Col [head [h]].headhash gives the first column in hash bucket h. otherwise, the degree list is empty, and: -(head [h] + 2) is the first column in hash bucket h. For a column c in a hash bucket, Col [c].shared3.prev is NOT a "previous column" pointer. Col [c].shared3.hash is used instead as the hash number for that column. The value of Col [c].shared4.hash_next is the next column in the same hash bucket. Assuming no, or "few" hash collisions, the time taken by this routine is linear in the sum of the sizes (lengths) of each column whose score has just been computed in the approximate degree computation. Not user-callable. */ PRIVATE void detect_super_cols ( /* === Parameters ======================================================= */ #ifndef NDEBUG /* these two parameters are only needed when debugging is enabled: */ Int n_col, /* number of columns of A */ Colamd_Row Row [], /* of size n_row+1 */ #endif /* NDEBUG */ Colamd_Col Col [], /* of size n_col+1 */ Int A [], /* row indices of A */ Int head [], /* head of degree lists and hash buckets */ Int row_start, /* pointer to set of columns to check */ Int row_length /* number of columns to check */ ) { /* === Local variables ================================================== */ Int hash ; /* hash value for a column */ Int *rp ; /* pointer to a row */ Int c ; /* a column index */ Int super_c ; /* column index of the column to absorb into */ Int *cp1 ; /* column pointer for column super_c */ Int *cp2 ; /* column pointer for column c */ Int length ; /* length of column super_c */ Int prev_c ; /* column preceding c in hash bucket */ Int i ; /* loop counter */ Int *rp_end ; /* pointer to the end of the row */ Int col ; /* a column index in the row to check */ Int head_column ; /* first column in hash bucket or degree list */ Int first_col ; /* first column in hash bucket */ /* === Consider each column in the row ================================== */ rp = &A [row_start] ; rp_end = rp + row_length ; while (rp < rp_end) { col = *rp++ ; if (COL_IS_DEAD (col)) { continue ; } /* get hash number for this column */ hash = Col [col].shared3.hash ; ASSERT (hash <= n_col) ; /* === Get the first column in this hash bucket ===================== */ head_column = head [hash] ; if (head_column > EMPTY) { first_col = Col [head_column].shared3.headhash ; } else { first_col = - (head_column + 2) ; } /* === Consider each column in the hash bucket ====================== */ for (super_c = first_col ; super_c != EMPTY ; super_c = Col [super_c].shared4.hash_next) { ASSERT (COL_IS_ALIVE (super_c)) ; ASSERT (Col [super_c].shared3.hash == hash) ; length = Col [super_c].length ; /* prev_c is the column preceding column c in the hash bucket */ prev_c = super_c ; /* === Compare super_c with all columns after it ================ */ for (c = Col [super_c].shared4.hash_next ; c != EMPTY ; c = Col [c].shared4.hash_next) { ASSERT (c != super_c) ; ASSERT (COL_IS_ALIVE (c)) ; ASSERT (Col [c].shared3.hash == hash) ; /* not identical if lengths or scores are different */ if (Col [c].length != length || Col [c].shared2.score != Col [super_c].shared2.score) { prev_c = c ; continue ; } /* compare the two columns */ cp1 = &A [Col [super_c].start] ; cp2 = &A [Col [c].start] ; for (i = 0 ; i < length ; i++) { /* the columns are "clean" (no dead rows) */ ASSERT (ROW_IS_ALIVE (*cp1)) ; ASSERT (ROW_IS_ALIVE (*cp2)) ; /* row indices will same order for both supercols, */ /* no gather scatter nessasary */ if (*cp1++ != *cp2++) { break ; } } /* the two columns are different if the for-loop "broke" */ if (i != length) { prev_c = c ; continue ; } /* === Got it! two columns are identical =================== */ ASSERT (Col [c].shared2.score == Col [super_c].shared2.score) ; Col [super_c].shared1.thickness += Col [c].shared1.thickness ; Col [c].shared1.parent = super_c ; KILL_NON_PRINCIPAL_COL (c) ; /* order c later, in order_children() */ Col [c].shared2.order = EMPTY ; /* remove c from hash bucket */ Col [prev_c].shared4.hash_next = Col [c].shared4.hash_next ; } } /* === Empty this hash bucket ======================================= */ if (head_column > EMPTY) { /* corresponding degree list "hash" is not empty */ Col [head_column].shared3.headhash = EMPTY ; } else { /* corresponding degree list "hash" is empty */ head [hash] = EMPTY ; } } } /* ========================================================================== */ /* === garbage_collection =================================================== */ /* ========================================================================== */ /* Defragments and compacts columns and rows in the workspace A. Used when all avaliable memory has been used while performing row merging. Returns the index of the first free position in A, after garbage collection. The time taken by this routine is linear is the size of the array A, which is itself linear in the number of nonzeros in the input matrix. Not user-callable. */ PRIVATE Int garbage_collection /* returns the new value of pfree */ ( /* === Parameters ======================================================= */ Int n_row, /* number of rows */ Int n_col, /* number of columns */ Colamd_Row Row [], /* row info */ Colamd_Col Col [], /* column info */ Int A [], /* A [0 ... Alen-1] holds the matrix */ Int *pfree /* &A [0] ... pfree is in use */ ) { /* === Local variables ================================================== */ Int *psrc ; /* source pointer */ Int *pdest ; /* destination pointer */ Int j ; /* counter */ Int r ; /* a row index */ Int c ; /* a column index */ Int length ; /* length of a row or column */ #ifndef NDEBUG Int debug_rows ; DEBUG2 (("Defrag..\n")) ; for (psrc = &A[0] ; psrc < pfree ; psrc++) ASSERT (*psrc >= 0) ; debug_rows = 0 ; #endif /* NDEBUG */ /* === Defragment the columns =========================================== */ pdest = &A[0] ; for (c = 0 ; c < n_col ; c++) { if (COL_IS_ALIVE (c)) { psrc = &A [Col [c].start] ; /* move and compact the column */ ASSERT (pdest <= psrc) ; Col [c].start = (Int) (pdest - &A [0]) ; length = Col [c].length ; for (j = 0 ; j < length ; j++) { r = *psrc++ ; if (ROW_IS_ALIVE (r)) { *pdest++ = r ; } } Col [c].length = (Int) (pdest - &A [Col [c].start]) ; } } /* === Prepare to defragment the rows =================================== */ for (r = 0 ; r < n_row ; r++) { if (ROW_IS_DEAD (r) || (Row [r].length == 0)) { /* This row is already dead, or is of zero length. Cannot compact * a row of zero length, so kill it. NOTE: in the current version, * there are no zero-length live rows. Kill the row (for the first * time, or again) just to be safe. */ KILL_ROW (r) ; } else { /* save first column index in Row [r].shared2.first_column */ psrc = &A [Row [r].start] ; Row [r].shared2.first_column = *psrc ; ASSERT (ROW_IS_ALIVE (r)) ; /* flag the start of the row with the one's complement of row */ *psrc = ONES_COMPLEMENT (r) ; #ifndef NDEBUG debug_rows++ ; #endif /* NDEBUG */ } } /* === Defragment the rows ============================================== */ psrc = pdest ; while (psrc < pfree) { /* find a negative number ... the start of a row */ if (*psrc++ < 0) { psrc-- ; /* get the row index */ r = ONES_COMPLEMENT (*psrc) ; ASSERT (r >= 0 && r < n_row) ; /* restore first column index */ *psrc = Row [r].shared2.first_column ; ASSERT (ROW_IS_ALIVE (r)) ; ASSERT (Row [r].length > 0) ; /* move and compact the row */ ASSERT (pdest <= psrc) ; Row [r].start = (Int) (pdest - &A [0]) ; length = Row [r].length ; for (j = 0 ; j < length ; j++) { c = *psrc++ ; if (COL_IS_ALIVE (c)) { *pdest++ = c ; } } Row [r].length = (Int) (pdest - &A [Row [r].start]) ; ASSERT (Row [r].length > 0) ; #ifndef NDEBUG debug_rows-- ; #endif /* NDEBUG */ } } /* ensure we found all the rows */ ASSERT (debug_rows == 0) ; /* === Return the new value of pfree ==================================== */ return ((Int) (pdest - &A [0])) ; } /* ========================================================================== */ /* === clear_mark =========================================================== */ /* ========================================================================== */ /* Clears the Row [].shared2.mark array, and returns the new tag_mark. Return value is the new tag_mark. Not user-callable. */ PRIVATE Int clear_mark /* return the new value for tag_mark */ ( /* === Parameters ======================================================= */ Int tag_mark, /* new value of tag_mark */ Int max_mark, /* max allowed value of tag_mark */ Int n_row, /* number of rows in A */ Colamd_Row Row [] /* Row [0 ... n_row-1].shared2.mark is set to zero */ ) { /* === Local variables ================================================== */ Int r ; if (tag_mark <= 0 || tag_mark >= max_mark) { for (r = 0 ; r < n_row ; r++) { if (ROW_IS_ALIVE (r)) { Row [r].shared2.mark = 0 ; } } tag_mark = 1 ; } return (tag_mark) ; } /* ========================================================================== */ /* === print_report ========================================================= */ /* ========================================================================== */ PRIVATE void print_report ( char *method, Int stats [COLAMD_STATS] ) { Int i1, i2, i3 ; PRINTF (("\n%s version %d.%d, %s: ", method, COLAMD_MAIN_VERSION, COLAMD_SUB_VERSION, COLAMD_DATE)) ; if (!stats) { PRINTF (("No statistics available.\n")) ; return ; } i1 = stats [COLAMD_INFO1] ; i2 = stats [COLAMD_INFO2] ; i3 = stats [COLAMD_INFO3] ; if (stats [COLAMD_STATUS] >= 0) { PRINTF (("OK. ")) ; } else { PRINTF (("ERROR. ")) ; } switch (stats [COLAMD_STATUS]) { case COLAMD_OK_BUT_JUMBLED: PRINTF(("Matrix has unsorted or duplicate row indices.\n")) ; PRINTF(("%s: number of duplicate or out-of-order row indices: %d\n", method, i3)) ; PRINTF(("%s: last seen duplicate or out-of-order row index: %d\n", method, INDEX (i2))) ; PRINTF(("%s: last seen in column: %d", method, INDEX (i1))) ; /* no break - fall through to next case instead */ case COLAMD_OK: PRINTF(("\n")) ; PRINTF(("%s: number of dense or empty rows ignored: %d\n", method, stats [COLAMD_DENSE_ROW])) ; PRINTF(("%s: number of dense or empty columns ignored: %d\n", method, stats [COLAMD_DENSE_COL])) ; PRINTF(("%s: number of garbage collections performed: %d\n", method, stats [COLAMD_DEFRAG_COUNT])) ; break ; case COLAMD_ERROR_A_not_present: PRINTF(("Array A (row indices of matrix) not present.\n")) ; break ; case COLAMD_ERROR_p_not_present: PRINTF(("Array p (column pointers for matrix) not present.\n")) ; break ; case COLAMD_ERROR_nrow_negative: PRINTF(("Invalid number of rows (%d).\n", i1)) ; break ; case COLAMD_ERROR_ncol_negative: PRINTF(("Invalid number of columns (%d).\n", i1)) ; break ; case COLAMD_ERROR_nnz_negative: PRINTF(("Invalid number of nonzero entries (%d).\n", i1)) ; break ; case COLAMD_ERROR_p0_nonzero: PRINTF(("Invalid column pointer, p [0] = %d, must be zero.\n", i1)); break ; case COLAMD_ERROR_A_too_small: PRINTF(("Array A too small.\n")) ; PRINTF((" Need Alen >= %d, but given only Alen = %d.\n", i1, i2)) ; break ; case COLAMD_ERROR_col_length_negative: PRINTF (("Column %d has a negative number of nonzero entries (%d).\n", INDEX (i1), i2)) ; break ; case COLAMD_ERROR_row_index_out_of_bounds: PRINTF (("Row index (row %d) out of bounds (%d to %d) in column %d.\n", INDEX (i2), INDEX (0), INDEX (i3-1), INDEX (i1))) ; break ; case COLAMD_ERROR_out_of_memory: PRINTF(("Out of memory.\n")) ; break ; /* v2.4: internal-error case deleted */ } } /* ========================================================================== */ /* === colamd debugging routines ============================================ */ /* ========================================================================== */ /* When debugging is disabled, the remainder of this file is ignored. */ #ifndef NDEBUG /* ========================================================================== */ /* === debug_structures ===================================================== */ /* ========================================================================== */ /* At this point, all empty rows and columns are dead. All live columns are "clean" (containing no dead rows) and simplicial (no supercolumns yet). Rows may contain dead columns, but all live rows contain at least one live column. */ PRIVATE void debug_structures ( /* === Parameters ======================================================= */ Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [], Int n_col2 ) { /* === Local variables ================================================== */ Int i ; Int c ; Int *cp ; Int *cp_end ; Int len ; Int score ; Int r ; Int *rp ; Int *rp_end ; Int deg ; /* === Check A, Row, and Col ============================================ */ for (c = 0 ; c < n_col ; c++) { if (COL_IS_ALIVE (c)) { len = Col [c].length ; score = Col [c].shared2.score ; DEBUG4 (("initial live col %5d %5d %5d\n", c, len, score)) ; ASSERT (len > 0) ; ASSERT (score >= 0) ; ASSERT (Col [c].shared1.thickness == 1) ; cp = &A [Col [c].start] ; cp_end = cp + len ; while (cp < cp_end) { r = *cp++ ; ASSERT (ROW_IS_ALIVE (r)) ; } } else { i = Col [c].shared2.order ; ASSERT (i >= n_col2 && i < n_col) ; } } for (r = 0 ; r < n_row ; r++) { if (ROW_IS_ALIVE (r)) { i = 0 ; len = Row [r].length ; deg = Row [r].shared1.degree ; ASSERT (len > 0) ; ASSERT (deg > 0) ; rp = &A [Row [r].start] ; rp_end = rp + len ; while (rp < rp_end) { c = *rp++ ; if (COL_IS_ALIVE (c)) { i++ ; } } ASSERT (i > 0) ; } } } /* ========================================================================== */ /* === debug_deg_lists ====================================================== */ /* ========================================================================== */ /* Prints the contents of the degree lists. Counts the number of columns in the degree list and compares it to the total it should have. Also checks the row degrees. */ PRIVATE void debug_deg_lists ( /* === Parameters ======================================================= */ Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int head [], Int min_score, Int should, Int max_deg ) { /* === Local variables ================================================== */ Int deg ; Int col ; Int have ; Int row ; /* === Check the degree lists =========================================== */ if (n_col > 10000 && colamd_debug <= 0) { return ; } have = 0 ; DEBUG4 (("Degree lists: %d\n", min_score)) ; for (deg = 0 ; deg <= n_col ; deg++) { col = head [deg] ; if (col == EMPTY) { continue ; } DEBUG4 (("%d:", deg)) ; while (col != EMPTY) { DEBUG4 ((" %d", col)) ; have += Col [col].shared1.thickness ; ASSERT (COL_IS_ALIVE (col)) ; col = Col [col].shared4.degree_next ; } DEBUG4 (("\n")) ; } DEBUG4 (("should %d have %d\n", should, have)) ; ASSERT (should == have) ; /* === Check the row degrees ============================================ */ if (n_row > 10000 && colamd_debug <= 0) { return ; } for (row = 0 ; row < n_row ; row++) { if (ROW_IS_ALIVE (row)) { ASSERT (Row [row].shared1.degree <= max_deg) ; } } } /* ========================================================================== */ /* === debug_mark =========================================================== */ /* ========================================================================== */ /* Ensures that the tag_mark is less that the maximum and also ensures that each entry in the mark array is less than the tag mark. */ PRIVATE void debug_mark ( /* === Parameters ======================================================= */ Int n_row, Colamd_Row Row [], Int tag_mark, Int max_mark ) { /* === Local variables ================================================== */ Int r ; /* === Check the Row marks ============================================== */ ASSERT (tag_mark > 0 && tag_mark <= max_mark) ; if (n_row > 10000 && colamd_debug <= 0) { return ; } for (r = 0 ; r < n_row ; r++) { ASSERT (Row [r].shared2.mark < tag_mark) ; } } /* ========================================================================== */ /* === debug_matrix ========================================================= */ /* ========================================================================== */ /* Prints out the contents of the columns and the rows. */ PRIVATE void debug_matrix ( /* === Parameters ======================================================= */ Int n_row, Int n_col, Colamd_Row Row [], Colamd_Col Col [], Int A [] ) { /* === Local variables ================================================== */ Int r ; Int c ; Int *rp ; Int *rp_end ; Int *cp ; Int *cp_end ; /* === Dump the rows and columns of the matrix ========================== */ if (colamd_debug < 3) { return ; } DEBUG3 (("DUMP MATRIX:\n")) ; for (r = 0 ; r < n_row ; r++) { DEBUG3 (("Row %d alive? %d\n", r, ROW_IS_ALIVE (r))) ; if (ROW_IS_DEAD (r)) { continue ; } DEBUG3 (("start %d length %d degree %d\n", Row [r].start, Row [r].length, Row [r].shared1.degree)) ; rp = &A [Row [r].start] ; rp_end = rp + Row [r].length ; while (rp < rp_end) { c = *rp++ ; DEBUG4 ((" %d col %d\n", COL_IS_ALIVE (c), c)) ; } } for (c = 0 ; c < n_col ; c++) { DEBUG3 (("Col %d alive? %d\n", c, COL_IS_ALIVE (c))) ; if (COL_IS_DEAD (c)) { continue ; } DEBUG3 (("start %d length %d shared1 %d shared2 %d\n", Col [c].start, Col [c].length, Col [c].shared1.thickness, Col [c].shared2.score)) ; cp = &A [Col [c].start] ; cp_end = cp + Col [c].length ; while (cp < cp_end) { r = *cp++ ; DEBUG4 ((" %d row %d\n", ROW_IS_ALIVE (r), r)) ; } } } PRIVATE void colamd_get_debug ( char *method ) { FILE *f ; colamd_debug = 0 ; /* no debug printing */ f = fopen ("debug", "r") ; if (f == (FILE *) NULL) { colamd_debug = 0 ; } else { fscanf (f, "%d", &colamd_debug) ; fclose (f) ; } DEBUG0 (("%s: debug version, D = %d (THIS WILL BE SLOW!)\n", method, colamd_debug)) ; } #endif /* NDEBUG */ igraph/src/drl_parse.h0000644000175100001440000000501713431000472014452 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // The parse class contains the methods necessary to parse // the command line, print help, and do error checking #ifdef MUSE_MPI #include #endif namespace drl { class parse { public: // Methods parse ( int argc, char **argv ); ~parse () {} // user parameters string sim_file; // .sim file string coord_file; // .coord file string parms_file; // .parms file string real_file; // .real file int rand_seed; // random seed int >= 0 float edge_cut; // edge cutting real [0,1] int int_out; // intermediate output, int >= 1 int edges_out; // true if .edges file is requested int parms_in; // true if .parms file is to be read float real_in; // true if .real file is to be read private: void print_syntax ( const char *error_string ); }; } // namespace drl igraph/src/lsap.c0000644000175100001440000003007113431000472013427 0ustar hornikusers #include "igraph_lsap.h" #include "igraph_error.h" #include #include #include #include /* INT_MAX */ #include /* DBL_MAX */ #include #include /* constants used for improving readability of code */ #define COVERED 1 #define UNCOVERED 0 #define ASSIGNED 1 #define UNASSIGNED 0 #define TRUE 1 #define FALSE 0 #define MARKED 1 #define UNMARKED 0 #define REDUCE 1 #define NOREDUCE 0 typedef struct{ int n; /* order of problem */ double **C; /* cost matrix */ double **c; /* reduced cost matrix */ int *s; /* assignment */ int *f; /* column i is assigned to f[i] */ int na; /* number of assigned items; */ int runs; /* number of iterations */ double cost; /* minimum cost */ time_t rtime; /* time */ } AP; /* public interface */ /* constructors and destructor */ AP *ap_create_problem(double *t, int n); AP *ap_create_problem_from_matrix(double **t, int n); AP *ap_read_problem(char *file); void ap_free(AP *p); int ap_assignment(AP *p, int *res); int ap_costmatrix(AP *p, double **m); int ap_datamatrix(AP *p, double **m); int ap_iterations(AP *p); int ap_hungarian(AP *p); double ap_mincost(AP *p); void ap_print_solution(AP *p); void ap_show_data(AP *p); int ap_size(AP *p); int ap_time(AP *p); /* error reporting */ void ap_error(char *message); /* private functions */ void preprocess(AP *p); void preassign(AP *p); int cover(AP *p, int *ri, int *ci); void reduce(AP *p, int *ri, int *ci); int ap_hungarian(AP *p) { int n; /* size of problem */ int *ri; /* covered rows */ int *ci; /* covered columns */ time_t start, end; /* timer */ int i, j, ok; start = time(0); n = p->n; p->runs = 0; /* allocate memory */ p->s = calloc(1 + n, sizeof(int)); p->f = calloc(1 + n, sizeof(int)); ri = calloc(1 + n, sizeof(int)); ci = calloc(1 + n, sizeof(int)); if(ri == NULL || ci == NULL || p->s == NULL || p->f == NULL) IGRAPH_ERROR("ap_hungarian: could not allocate memory", IGRAPH_ENOMEM); preprocess(p); preassign(p); while(p->na < n){ if(REDUCE == cover(p, ri, ci)) reduce(p, ri, ci); ++p->runs; } end = time(0); p->rtime = end - start; /* check if assignment is a permutation of (1..n) */ for(i = 1; i <= n; i++){ ok = 0; for(j = 1; j <= n; j++) if(p->s[j] == i) ++ok; if(ok != 1) IGRAPH_ERROR("ap_hungarian: error in assigment, is not a permutation", IGRAPH_EINVAL); } /* calculate cost of assignment */ p->cost = 0; for(i = 1; i <= n; i++) p->cost+= p->C[i][p->s[i]]; /* reset result back to base-0 indexing */ for(i = 1; i <= n; i++) p->s[i - 1] = p->s[i] - 1; /* free memory */ free(ri); free(ci); return 0; } /* abbreviated interface */ int ap_assignment(AP *p, int *res) { int i; if(p->s == NULL) ap_hungarian(p); for(i = 0; i < p->n; i++) res[i] = p->s[i]; return p->n; } /*******************************************************************/ /* constructors */ /* read data from file */ /*******************************************************************/ AP *ap_read_problem(char *file) { FILE *f; int i,j,c; int m,n; double x; double **t; int nrow,ncol; AP *p; f = fopen(file,"r"); if(f==NULL) return NULL; t = (double **)malloc(sizeof(double*)); m = 0; n = 0; nrow = 0; ncol = 0; while(EOF != (i = fscanf(f, "%lf", &x))){ if(i == 1){ if(n == 0){ t = (double **) realloc(t,(m + 1) * sizeof(double *)); t[m] = (double *) malloc(sizeof(double)); }else t[m] = (double *) realloc(t[m], (n + 1) * sizeof(double)); t[m][n++] = x; ncol = (ncol < n) ? n : ncol; c=fgetc(f); if(c == '\n'){ n = 0; ++m; nrow = (nrow < m) ? m : nrow; } } } fclose(f); /* prepare data */ if(nrow != ncol){ /* fprintf(stderr,"ap_read_problem: problem not quadratic\nrows =%d, cols = %d\n",nrow,ncol); */ igraph_warningf("ap_read_problem: problem not quadratic\nrows = %d, cols = %d\n", __FILE__, __LINE__, -1, nrow, ncol); return NULL; } p = (AP*) malloc(sizeof(AP)); p->n = ncol; p->C = (double **) malloc((1 + nrow)*sizeof(double *)); p->c = (double **) malloc((1 + nrow)*sizeof(double *)); if(p->C == NULL || p->c == NULL) return NULL; for(i = 1; i <= nrow; i++){ p->C[i] = (double *) calloc(ncol + 1, sizeof(double)); p->c[i] = (double *) calloc(ncol + 1, sizeof(double)); if(p->C[i] == NULL || p->c[i] == NULL) return NULL; } for(i = 1; i <= nrow; i++) for( j = 1; j <= ncol; j++){ p->C[i][j] = t[i-1][j-1]; p->c[i][j] = t[i-1][j-1]; } for(i = 0; i < nrow; i++) free(t[i]); free(t); p->cost = 0; p->s = NULL; p->f = NULL; return p; } AP *ap_create_problem_from_matrix(double **t, int n) { int i,j; AP *p; p = (AP*) malloc(sizeof(AP)); if(p == NULL) return NULL; p->n = n; p->C = (double **) malloc((n + 1) * sizeof(double *)); p->c = (double **) malloc((n + 1) * sizeof(double *)); if(p->C == NULL || p->c == NULL) return NULL; for(i = 1; i <= n; i++){ p->C[i] = (double *) calloc(n + 1, sizeof(double)); p->c[i] = (double *) calloc(n + 1, sizeof(double)); if(p->C[i] == NULL || p->c[i] == NULL) return NULL; } for(i = 1; i <= n; i++) for( j = 1; j <= n; j++){ p->C[i][j] = t[i-1][j-1]; p->c[i][j] = t[i-1][j-1]; } p->cost = 0; p->s = NULL; p->f = NULL; return p; } /* read data from vector */ AP *ap_create_problem(double *t, int n) { int i,j; AP *p; p = (AP*) malloc(sizeof(AP)); if(p == NULL) return NULL; p->n = n; p->C = (double **) malloc((n + 1) * sizeof(double *)); p->c = (double **) malloc((n + 1) * sizeof(double *)); if(p->C == NULL || p->c == NULL) return NULL; for(i = 1; i <= n; i++){ p->C[i] = (double *) calloc(n + 1, sizeof(double)); p->c[i] = (double *) calloc(n + 1, sizeof(double)); if(p->C[i] == NULL || p->c[i] == NULL) return NULL; } for(i = 1; i <= n; i++) for( j = 1; j <= n; j++){ p->C[i][j] = t[n*(j - 1) + i - 1]; p->c[i][j] = t[n*(j - 1) + i - 1]; } p->cost = 0; p->s = NULL; p->f = NULL; return p; } /* destructor */ void ap_free(AP *p) { int i; free(p->s); free(p->f); for(i = 1; i <= p->n; i++){ free(p->C[i]); free(p->c[i]); } free(p->C); free(p->c); free(p); } /* set + get functions */ /* void ap_show_data(AP *p) { int i, j; for(i = 1; i <= p->n; i++){ for(j = 1; j <= p->n; j++) printf("%6.2f ", p->c[i][j]); printf("\n"); } } */ double ap_mincost(AP *p) { if(p->s == NULL) ap_hungarian(p); return p->cost; } int ap_size(AP *p) { return p->n; } int ap_time(AP *p) { return (int) p->rtime; } int ap_iterations(AP *p) { return p->runs; } /* void ap_print_solution(AP *p) { int i; printf("%d itertations, %d secs.\n",p->runs, (int)p->rtime); printf("Min Cost: %10.4f\n",p->cost); for(i = 0; i < p->n; i++) printf("%4d",p->s[i]); printf("\n"); } */ int ap_costmatrix(AP *p, double **m) { int i,j; for(i = 0; i < p->n; i++) for(j = 0; j < p->n; j++) m[i][j] = p->C[i + 1][j + 1]; return p->n; } int ap_datamatrix(AP *p, double **m) { int i,j; for(i = 0; i < p->n; i++) for(j = 0; j < p->n; j++) m[i][j] = p->c[i + 1][j + 1]; return p->n; } /* error reporting */ /* void ap_error(char *message) { fprintf(stderr,"%s\n",message); exit(1); } */ /*************************************************************/ /* these functions are used internally */ /* by ap_hungarian */ /*************************************************************/ int cover(AP *p, int *ri, int *ci) { int *mr, i, r; int n; n = p->n; mr = calloc(1 + p->n, sizeof(int)); /* reset cover indices */ for(i = 1; i <= n; i++){ if(p->s[i] == UNASSIGNED){ ri[i] = UNCOVERED; mr[i] = MARKED; } else ri[i] = COVERED; ci[i] = UNCOVERED; } while(TRUE){ /* find marked row */ r = 0; for(i = 1; i <= n; i++) if(mr[i] == MARKED){ r = i; break; } if(r == 0) break; for(i = 1; i <= n; i++) if(p->c[r][i] == 0 && ci[i] == UNCOVERED){ if(p->f[i]){ ri[p->f[i]] = UNCOVERED; mr[p->f[i]] = MARKED; ci[i] = COVERED; }else{ if(p->s[r] == UNASSIGNED) ++p->na; p->f[p->s[r]] = 0; p->f[i] = r; p->s[r] = i; free(mr); return NOREDUCE; } } mr[r] = UNMARKED; } free(mr); return REDUCE; } void reduce(AP *p, int *ri, int *ci) { int i, j, n; double min; n = p->n; /* find minimum in uncovered c-matrix */ min = DBL_MAX; for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) if(ri[i] == UNCOVERED && ci[j] == UNCOVERED){ if(p->c[i][j] < min) min = p->c[i][j]; } /* subtract min from each uncovered element and add it to each element */ /* which is covered twice */ for(i = 1; i <= n; i++) for(j = 1; j <= n; j++){ if(ri[i] == UNCOVERED && ci[j] == UNCOVERED) p->c[i][j]-= min; if(ri[i] == COVERED && ci[j] == COVERED) p->c[i][j]+= min; } } void preassign(AP *p) { int i, j, min, r, c, n, count; int *ri, *ci, *rz, *cz; n = p->n; p->na = 0; /* row and column markers */ ri = calloc(1 + n, sizeof(int)); ci = calloc(1 + n, sizeof(int)); /* row and column counts of zeroes */ rz = calloc(1 + n, sizeof(int)); cz = calloc(1 + n, sizeof(int)); for(i = 1; i <= n; i++){ count = 0; for(j = 1; j <= n; j++) if(p->c[i][j] == 0) ++count; rz[i] = count; } for(i = 1; i <= n; i++){ count = 0; for(j = 1; j <= n; j++) if(p->c[j][i] == 0) ++count; cz[i] = count; } while(TRUE){ /* find unassigned row with least number of zeroes > 0 */ min = INT_MAX; r = 0; for(i = 1; i <= n; i++) if(rz[i] > 0 && rz[i] < min && ri[i] == UNASSIGNED){ min = rz[i]; r = i; } /* check if we are done */ if(r == 0) break; /* find unassigned column in row r with least number of zeroes */ c = 0; min = INT_MAX; for(i = 1; i <= n; i++) if(p->c[r][i] == 0 && cz[i] < min && ci[i] == UNASSIGNED){ min = cz[i]; c = i; } if(c){ ++p->na; p->s[r] = c; p->f[c] = r; ri[r] = ASSIGNED; ci[c] = ASSIGNED; /* adjust zero counts */ cz[c] = 0; for(i = 1; i <= n; i++) if(p->c[i][c] == 0) --rz[i]; } } /* free memory */ free(ri); free(ci); free(rz); free(cz); } void preprocess(AP *p) { int i, j, n; double min; n = p->n; /* subtract column minima in each row */ for(i = 1; i <= n; i++){ min = p->c[i][1]; for(j = 2; j <= n; j++) if(p->c[i][j] < min) min = p->c[i][j]; for(j = 1; j <= n; j++) p->c[i][j]-= min; } /* subtract row minima in each column */ for(i = 1; i <= n; i++){ min = p->c[1][i]; for(j = 2; j <= n; j++) if(p->c[j][i] < min) min = p->c[j][i]; for(j = 1; j <= n; j++) p->c[j][i]-= min; } } int igraph_solve_lsap(igraph_matrix_t *c, igraph_integer_t n, igraph_vector_int_t *p) { AP *ap; IGRAPH_CHECK(igraph_vector_int_resize(p, n)); igraph_vector_int_null(p); ap = ap_create_problem(&MATRIX(*c, 0, 0), n); ap_hungarian(ap); ap_assignment(ap, VECTOR(*p)); ap_free(ap); return 0; } igraph/src/igraph_grid.c0000644000175100001440000003446013431000472014755 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph R package. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_memory.h" #include "config.h" #include /* internal function */ int igraph_2dgrid_which(igraph_2dgrid_t *grid, igraph_real_t xc, igraph_real_t yc, long int *x, long int *y) { if (xc <= grid->minx) { *x=0; } else if (xc >= grid->maxx) { *x=grid->stepsx-1; } else { *x=(long int) floor((xc-(grid->minx))/(grid->deltax)); } if (yc <= grid->miny) { *y=0; } else if (yc >= grid->maxy) { *y=grid->stepsy-1; } else { *y=(long int) floor((yc-(grid->miny))/(grid->deltay)); } return 0; } int igraph_2dgrid_init(igraph_2dgrid_t *grid, igraph_matrix_t *coords, igraph_real_t minx, igraph_real_t maxx, igraph_real_t deltax, igraph_real_t miny, igraph_real_t maxy, igraph_real_t deltay) { long int i; grid->coords=coords; grid->minx=minx; grid->maxx=maxx; grid->deltax=deltax; grid->miny=miny; grid->maxy=maxy; grid->deltay=deltay; grid->stepsx=(long int) ceil((maxx-minx)/deltax); grid->stepsy=(long int) ceil((maxy-miny)/deltay); IGRAPH_CHECK(igraph_matrix_init(&grid->startidx, grid->stepsx, grid->stepsy)); IGRAPH_FINALLY(igraph_matrix_destroy, &grid->startidx); IGRAPH_VECTOR_INIT_FINALLY(&grid->next, igraph_matrix_nrow(coords)); IGRAPH_VECTOR_INIT_FINALLY(&grid->prev, igraph_matrix_nrow(coords)); for (i=0; inext); i++) { VECTOR(grid->next)[i]=-1; } grid->massx=0; grid->massy=0; grid->vertices=0; IGRAPH_FINALLY_CLEAN(3); return 0; } void igraph_2dgrid_destroy(igraph_2dgrid_t *grid) { igraph_matrix_destroy(&grid->startidx); igraph_vector_destroy(&grid->next); igraph_vector_destroy(&grid->prev); } void igraph_2dgrid_add(igraph_2dgrid_t *grid, long int elem, igraph_real_t xc, igraph_real_t yc) { long int x, y; long int first; MATRIX(*grid->coords, elem, 0)=xc; MATRIX(*grid->coords, elem, 1)=yc; /* add to cell */ igraph_2dgrid_which(grid, xc, yc, &x, &y); first=(long int) MATRIX(grid->startidx, x, y); VECTOR(grid->prev)[elem]=0; VECTOR(grid->next)[elem]=first; if (first != 0) { VECTOR(grid->prev)[first-1]=elem+1; } MATRIX(grid->startidx, x, y)=elem+1; grid->massx += xc; grid->massy += yc; grid->vertices += 1; } void igraph_2dgrid_add2(igraph_2dgrid_t *grid, long int elem) { long int x, y; long int first; igraph_real_t xc, yc; xc=MATRIX(*grid->coords, elem, 0); yc=MATRIX(*grid->coords, elem, 1); /* add to cell */ igraph_2dgrid_which(grid, xc, yc, &x, &y); first=(long int) MATRIX(grid->startidx, x, y); VECTOR(grid->prev)[elem]=0; VECTOR(grid->next)[elem]=first; if (first != 0) { VECTOR(grid->prev)[first-1]=elem+1; } MATRIX(grid->startidx, x, y)=elem+1; grid->massx += xc; grid->massy += yc; grid->vertices += 1; } void igraph_2dgrid_move(igraph_2dgrid_t *grid, long int elem, igraph_real_t xc, igraph_real_t yc) { long int oldx, oldy; long int newx, newy; igraph_real_t oldxc=MATRIX(*grid->coords, elem, 0); igraph_real_t oldyc=MATRIX(*grid->coords, elem, 1); long int first; xc=oldxc+xc; yc=oldyc+yc; igraph_2dgrid_which(grid, oldxc, oldyc, &oldx, &oldy); igraph_2dgrid_which(grid, xc, yc, &newx, &newy); if (oldx != newx || oldy != newy) { /* remove from this cell */ if (VECTOR(grid->prev)[elem] != 0) { VECTOR(grid->next) [ (long int) VECTOR(grid->prev)[elem]-1 ] = VECTOR(grid->next)[elem]; } else { MATRIX(grid->startidx, oldx, oldy)=VECTOR(grid->next)[elem]; } if (VECTOR(grid->next)[elem] != 0) { VECTOR(grid->prev)[ (long int) VECTOR(grid->next)[elem]-1 ] = VECTOR(grid->prev)[elem]; } /* add to this cell */ first=(long int) MATRIX(grid->startidx, newx, newy); VECTOR(grid->prev)[elem]=0; VECTOR(grid->next)[elem]=first; if (first != 0) { VECTOR(grid->prev)[first-1]=elem+1; } MATRIX(grid->startidx, newx, newy)=elem+1; } grid->massx += -oldxc+xc; grid->massy += -oldyc+yc; MATRIX(*grid->coords, elem, 0)=xc; MATRIX(*grid->coords, elem, 1)=yc; } void igraph_2dgrid_getcenter(const igraph_2dgrid_t *grid, igraph_real_t *massx, igraph_real_t *massy) { *massx = (grid->massx)/(grid->vertices); *massy = (grid->massy)/(grid->vertices); } igraph_bool_t igraph_2dgrid_in(const igraph_2dgrid_t *grid, long int elem) { return VECTOR(grid->next)[elem] != -1; } igraph_real_t igraph_2dgrid_dist(const igraph_2dgrid_t *grid, long int e1, long int e2) { igraph_real_t x=MATRIX(*grid->coords, e1, 0)-MATRIX(*grid->coords, e2, 0); igraph_real_t y=MATRIX(*grid->coords, e1, 1)-MATRIX(*grid->coords, e2, 1); return sqrt(x*x + y*y); } igraph_real_t igraph_2dgrid_dist2(const igraph_2dgrid_t *grid, long int e1, long int e2) { igraph_real_t x=MATRIX(*grid->coords, e1, 0)-MATRIX(*grid->coords, e2, 0); igraph_real_t y=MATRIX(*grid->coords, e1, 1)-MATRIX(*grid->coords, e2, 1); return x*x + y*y; } int igraph_i_2dgrid_addvertices(igraph_2dgrid_t *grid, igraph_vector_t *eids, igraph_integer_t vid, igraph_real_t r, long int x, long int y) { long int act; igraph_real_t *v=VECTOR(grid->next); r=r*r; act=(long int) MATRIX(grid->startidx, x, y); while (act != 0) { if (igraph_2dgrid_dist2(grid, vid, act-1) < r) { IGRAPH_CHECK(igraph_vector_push_back(eids, act-1)); } act=(long int) v[act-1]; } return 0; } int igraph_2dgrid_neighbors(igraph_2dgrid_t *grid, igraph_vector_t *eids, igraph_integer_t vid, igraph_real_t r) { igraph_real_t xc=MATRIX(*grid->coords, (long int)vid, 0); igraph_real_t yc=MATRIX(*grid->coords, (long int)vid, 1); long int x, y; igraph_vector_clear(eids); igraph_2dgrid_which(grid, xc, yc, &x, &y); /* this cell */ igraph_i_2dgrid_addvertices(grid, eids, vid, r, x, y); /* left */ if (x!=0) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x-1, y); } /* right */ if (x!=grid->stepsx-1) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x+1, y); } /* up */ if (y!=0) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x, y-1); } /* down */ if (y!=grid->stepsy-1) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x, y+1); } /* up & left */ if (x != 0 && y != 0) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x-1, y-1); } /* up & right */ if (x != grid->stepsx-1 && y != 0) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x+1, y-1); } /* down & left */ if (x != 0 && y != grid->stepsy-1) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x-1, y+1); } /* down & right */ if (x != grid->stepsx-1 && y != grid->stepsy-1) { igraph_i_2dgrid_addvertices(grid, eids, vid, r, x-1, y+1); } return 0; } void igraph_2dgrid_reset(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it) { /* Search for the first cell containing a vertex */ it->x=0; it->y=0; it->vid=(long int) MATRIX(grid->startidx, 0, 0); while ( it->vid==0 && (it->x < grid->stepsx-1 || it->ystepsy-1)) { it->x += 1; if (it->x == grid->stepsx) { it->x=0; it->y += 1; } it->vid=(long int) MATRIX(grid->startidx, it->x, it->y); } } igraph_integer_t igraph_2dgrid_next(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it) { long int ret=it->vid; if (ret==0) { return 0; } /* First neighbor */ it->ncells=-1; if (it->x != grid->stepsx-1) { it->ncells += 1; it->nx[it->ncells]=it->x+1; it->ny[it->ncells]=it->y; } if (it->y != grid->stepsy-1) { it->ncells += 1; it->nx[it->ncells]=it->x; it->ny[it->ncells]=it->y+1; } if (it->ncells==1) { it->ncells += 1; it->nx[it->ncells]=it->x+1; it->ny[it->ncells]=it->y+1; } it->ncells+=1; it->nx[it->ncells]=it->x; it->ny[it->ncells]=it->y; it->nei=(long int) VECTOR(grid->next) [ ret-1 ]; while (it->ncells > 0 && it->nei==0 ) { it->ncells -= 1; it->nei=(long int) MATRIX(grid->startidx, it->nx[it->ncells], it->ny[it->ncells]); } /* Next vertex */ it->vid=(long int) VECTOR(grid->next)[ it->vid-1 ]; while ( (it->x < grid->stepsx-1 || it->ystepsy-1) && it->vid == 0) { it->x += 1; if (it->x == grid->stepsx) { it->x=0; it->y += 1; } it->vid=(long int) MATRIX(grid->startidx, it->x, it->y); } return (igraph_integer_t) ret; } igraph_integer_t igraph_2dgrid_next_nei(igraph_2dgrid_t *grid, igraph_2dgrid_iterator_t *it) { long int ret=it->nei; if (it->nei != 0) { it->nei=(long int) VECTOR(grid->next) [ ret-1 ]; } while (it->ncells > 0 && it->nei==0 ) { it->ncells -= 1; it->nei=(long int) MATRIX(grid->startidx, it->nx[it->ncells], it->ny[it->ncells]); } return (igraph_integer_t) ret; } /*-----------------------------------------------------------------------*/ int igraph_i_layout_mergegrid_which(igraph_i_layout_mergegrid_t *grid, igraph_real_t xc, igraph_real_t yc, long int *x, long int *y) { if (xc <= grid->minx) { *x=0; } else if (xc >= grid->maxx) { *x=grid->stepsx-1; } else { *x=(long int) floor((xc-(grid->minx))/(grid->deltax)); } if (yc <= grid->miny) { *y=0; } else if (yc >= grid->maxy) { *y=grid->stepsy-1; } else { *y=(long int) floor((yc-(grid->miny))/(grid->deltay)); } return 0; } int igraph_i_layout_mergegrid_init(igraph_i_layout_mergegrid_t *grid, igraph_real_t minx, igraph_real_t maxx, long int stepsx, igraph_real_t miny, igraph_real_t maxy, long int stepsy) { grid->minx=minx; grid->maxx=maxx; grid->stepsx=stepsx; grid->deltax=(maxx-minx)/stepsx; grid->miny=miny; grid->maxy=maxy; grid->stepsy=stepsy; grid->deltay=(maxy-miny)/stepsy; grid->data=igraph_Calloc(stepsx*stepsy, long int); if (grid->data==0) { IGRAPH_ERROR("Cannot create grid", IGRAPH_ENOMEM); } return 0; } void igraph_i_layout_mergegrid_destroy(igraph_i_layout_mergegrid_t *grid) { igraph_Free(grid->data); } #define MAT(i,j) (grid->data[(grid->stepsy)*(j)+(i)]) #define DIST2(x2,y2) (sqrt(pow(x-(x2),2)+pow(y-(y2), 2))) int igraph_i_layout_merge_place_sphere(igraph_i_layout_mergegrid_t *grid, igraph_real_t x, igraph_real_t y, igraph_real_t r, long int id) { long int cx, cy; long int i, j; igraph_i_layout_mergegrid_which(grid, x, y, &cx, &cy); MAT(cx, cy)=id+1; #define DIST(i,j) (DIST2(grid->minx+(cx+(i))*grid->deltax, \ grid->miny+(cy+(j))*grid->deltay)) for (i=0; cx+istepsx && DIST(i,0)stepsy && DIST(i,j)minx+(cx+(i))*grid->deltax, \ grid->miny+(cy-(j)+1)*grid->deltay)) for (i=0; cx+istepsx && DIST(i,0)0 && DIST(i,j)minx+(cx-(i)+1)*grid->deltax, \ grid->miny+(cy+(j))*grid->deltay)) for (i=1; cx-i>0 && DIST(i,0)stepsy && DIST(i,j)minx+(cx-(i)+1)*grid->deltax, \ grid->miny+(cy-(j)+1)*grid->deltay)) for (i=1; cx-i>0 && DIST(i,0)0 && DIST(i,j)minx || x >= grid->maxx || y <= grid->miny || y >= grid->maxy) { res=-1; } else { igraph_i_layout_mergegrid_which(grid, x, y, &cx, &cy); res=MAT(cx, cy)-1; } return res; } #define DIST2(x2,y2) (sqrt(pow(x-(x2),2)+pow(y-(y2), 2))) long int igraph_i_layout_mergegrid_get_sphere(igraph_i_layout_mergegrid_t *grid, igraph_real_t x, igraph_real_t y, igraph_real_t r) { long int cx, cy; long int i,j; long int ret; if (x-r <= grid->minx || x+r >= grid->maxx || y-r <= grid->miny || y+r >= grid->maxy) { ret=-1; } else { igraph_i_layout_mergegrid_which(grid, x, y, &cx, &cy); ret=MAT(cx, cy)-1; #define DIST(i,j) (DIST2(grid->minx+(cx+(i))*grid->deltax, \ grid->miny+(cy+(j))*grid->deltay)) for (i=0; ret<0 && cx+istepsx && DIST(i,0)stepsy && DIST(i,j)minx+(cx+(i))*grid->deltax, \ grid->miny+(cy-(j)+1)*grid->deltay)) for (i=0; ret<0 && cx+istepsx && DIST(i,0)0 && DIST(i,j)minx+(cx-(i)+1)*grid->deltax, \ grid->miny+(cy+(j))*grid->deltay)) for (i=1; ret<0 && cx-i>0 && DIST(i,0)stepsy && DIST(i,j)minx+(cx-(i)+1)*grid->deltax, \ grid->miny+(cy-(j)+1)*grid->deltay)) for (i=1; ret<0 && cx+i>0 && DIST(i,0)0 && DIST(i,j)stepsx; i++) { */ /* for (j=0; jstepsy; j++) { */ /* printf("%li ", MAT(i,j)-1); */ /* } */ /* printf("\n"); */ /* } */ /* } */ igraph/src/foreign-pajek-lexer.c0000644000175100001440000022473613431000472016343 0ustar hornikusers#line 2 "lex.yy.c" #line 4 "lex.yy.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE igraph_pajek_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via igraph_pajek_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void igraph_pajek_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void igraph_pajek_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_pajek_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void igraph_pajek_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_pajek_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_pajek_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void igraph_pajek_yypop_buffer_state (yyscan_t yyscanner ); static void igraph_pajek_yyensure_buffer_stack (yyscan_t yyscanner ); static void igraph_pajek_yy_load_buffer_state (yyscan_t yyscanner ); static void igraph_pajek_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER igraph_pajek_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE igraph_pajek_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_pajek_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_pajek_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *igraph_pajek_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *igraph_pajek_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void igraph_pajek_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer igraph_pajek_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ igraph_pajek_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_pajek_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ igraph_pajek_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_pajek_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define igraph_pajek_yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 48 #define YY_END_OF_BUFFER 49 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[160] = { 0, 1, 1, 49, 46, 1, 12, 12, 46, 46, 46, 46, 46, 15, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 1, 12, 46, 0, 13, 46, 0, 2, 3, 46, 0, 14, 46, 46, 46, 46, 46, 15, 46, 46, 29, 46, 46, 46, 46, 46, 26, 46, 46, 46, 46, 46, 46, 38, 46, 46, 46, 46, 27, 46, 23, 22, 28, 46, 46, 30, 46, 46, 13, 2, 2, 14, 46, 46, 46, 46, 46, 15, 46, 15, 33, 34, 37, 19, 20, 46, 46, 31, 32, 18, 35, 36, 43, 41, 39, 46, 42, 46, 46, 46, 46, 46, 3, 46, 46, 46, 4, 46, 46, 45, 46, 21, 46, 25, 46, 46, 7, 46, 46, 46, 46, 24, 40, 44, 46, 46, 46, 8, 46, 46, 46, 46, 46, 46, 46, 11, 46, 46, 16, 17, 46, 46, 5, 46, 9, 46, 6, 10, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 5, 1, 1, 6, 1, 1, 7, 8, 9, 10, 1, 11, 12, 1, 13, 14, 15, 13, 13, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 1, 1, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 1, 1, 1, 41, 1, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[42] = { 0, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int16_t yy_base[167] = { 0, 0, 0, 288, 0, 285, 282, 282, 40, 44, 47, 36, 44, 53, 67, 42, 72, 255, 39, 265, 47, 96, 81, 84, 87, 91, 250, 99, 240, 239, 0, 277, 289, 103, 273, 0, 107, 74, 273, 113, 116, 268, 0, 243, 255, 257, 252, 251, 117, 108, 125, 289, 139, 142, 145, 148, 151, 289, 128, 155, 160, 163, 166, 169, 289, 172, 175, 178, 181, 289, 246, 289, 289, 289, 229, 242, 289, 246, 245, 289, 261, 130, 289, 246, 241, 228, 227, 228, 173, 176, 181, 289, 289, 289, 289, 289, 225, 195, 289, 289, 289, 289, 289, 289, 289, 289, 234, 289, 200, 237, 203, 240, 239, 251, 220, 232, 219, 213, 215, 206, 289, 209, 289, 212, 289, 230, 229, 220, 212, 220, 214, 218, 289, 289, 289, 207, 206, 215, 212, 199, 204, 217, 215, 218, 167, 168, 0, 135, 107, 289, 289, 91, 80, 0, 63, 0, 58, 0, 0, 289, 79, 222, 224, 226, 228, 230, 232 } ; static yyconst flex_int16_t yy_def[167] = { 0, 159, 1, 159, 160, 159, 159, 159, 161, 162, 163, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 159, 159, 161, 164, 160, 162, 165, 159, 165, 163, 166, 160, 160, 160, 160, 160, 160, 160, 160, 160, 159, 160, 160, 160, 160, 160, 159, 160, 160, 160, 160, 160, 160, 159, 160, 160, 160, 160, 159, 160, 159, 159, 159, 160, 160, 159, 160, 160, 159, 159, 159, 159, 160, 160, 160, 160, 160, 160, 160, 160, 159, 159, 159, 159, 159, 160, 160, 159, 159, 159, 159, 159, 159, 159, 159, 160, 159, 160, 160, 160, 160, 160, 159, 160, 160, 160, 160, 160, 160, 159, 160, 159, 160, 159, 160, 160, 160, 160, 160, 160, 160, 159, 159, 159, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 159, 159, 160, 160, 160, 160, 160, 160, 160, 160, 0, 159, 159, 159, 159, 159, 159, 159 } ; static yyconst flex_int16_t yy_nxt[331] = { 0, 4, 5, 6, 7, 8, 9, 10, 4, 11, 4, 12, 4, 13, 13, 13, 14, 15, 16, 4, 4, 17, 4, 18, 19, 20, 21, 4, 4, 4, 22, 23, 24, 25, 4, 26, 4, 27, 28, 29, 4, 4, 34, 34, 34, 35, 37, 38, 39, 41, 41, 41, 43, 59, 60, 42, 44, 48, 48, 48, 55, 62, 63, 45, 46, 49, 48, 48, 48, 51, 51, 51, 47, 50, 57, 57, 57, 38, 39, 56, 30, 52, 53, 69, 69, 69, 71, 71, 71, 72, 72, 72, 158, 73, 73, 73, 157, 54, 64, 64, 64, 76, 76, 76, 70, 34, 34, 34, 35, 37, 38, 39, 65, 156, 66, 74, 81, 39, 41, 41, 41, 88, 88, 88, 42, 155, 67, 154, 68, 49, 48, 48, 48, 113, 80, 89, 89, 50, 90, 90, 90, 91, 91, 91, 92, 92, 92, 93, 93, 93, 94, 94, 94, 95, 95, 95, 96, 98, 98, 98, 153, 97, 99, 99, 99, 100, 100, 100, 101, 101, 101, 102, 102, 102, 103, 103, 103, 104, 104, 104, 105, 105, 105, 107, 107, 107, 88, 88, 88, 90, 90, 90, 152, 50, 90, 90, 90, 120, 120, 120, 151, 106, 122, 122, 122, 124, 124, 124, 132, 132, 132, 133, 133, 133, 134, 134, 134, 149, 149, 149, 150, 150, 150, 33, 33, 36, 36, 40, 40, 34, 34, 37, 37, 41, 41, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 131, 130, 129, 128, 127, 113, 126, 125, 123, 121, 119, 118, 117, 116, 115, 114, 80, 112, 111, 110, 109, 108, 87, 86, 85, 84, 83, 82, 80, 79, 31, 78, 77, 75, 61, 58, 32, 32, 31, 159, 3, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159 } ; static yyconst flex_int16_t yy_chk[331] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 18, 18, 10, 11, 12, 12, 12, 15, 20, 20, 11, 11, 13, 13, 13, 13, 14, 14, 14, 11, 13, 16, 16, 16, 37, 37, 15, 160, 14, 14, 22, 22, 22, 23, 23, 23, 24, 24, 24, 156, 25, 25, 25, 154, 14, 21, 21, 21, 27, 27, 27, 22, 33, 33, 33, 33, 36, 36, 36, 21, 152, 21, 25, 39, 39, 40, 40, 40, 49, 49, 49, 40, 151, 21, 148, 21, 48, 48, 48, 48, 81, 81, 50, 50, 48, 50, 50, 50, 52, 52, 52, 53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 56, 56, 58, 59, 59, 59, 147, 58, 60, 60, 60, 61, 61, 61, 62, 62, 62, 63, 63, 63, 65, 65, 65, 66, 66, 66, 67, 67, 67, 68, 68, 68, 88, 88, 88, 89, 89, 89, 145, 88, 90, 90, 90, 97, 97, 97, 144, 67, 108, 108, 108, 110, 110, 110, 119, 119, 119, 121, 121, 121, 123, 123, 123, 142, 142, 142, 143, 143, 143, 161, 161, 162, 162, 163, 163, 164, 164, 165, 165, 166, 166, 141, 140, 139, 138, 137, 136, 135, 131, 130, 129, 128, 127, 126, 125, 118, 117, 116, 115, 114, 113, 112, 111, 109, 106, 96, 87, 86, 85, 84, 83, 80, 78, 77, 75, 74, 70, 47, 46, 45, 44, 43, 41, 38, 34, 31, 29, 28, 26, 19, 17, 7, 6, 5, 3, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159, 159 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "src/foreign-pajek-lexer.l" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #line 24 "src/foreign-pajek-lexer.l" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include "foreign-pajek-header.h" #include "foreign-pajek-parser.h" #define YY_EXTRA_TYPE igraph_i_pajek_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); #define YY_NO_INPUT 1 #line 619 "lex.yy.c" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int igraph_pajek_yylex_init (yyscan_t* scanner); int igraph_pajek_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int igraph_pajek_yylex_destroy (yyscan_t yyscanner ); int igraph_pajek_yyget_debug (yyscan_t yyscanner ); void igraph_pajek_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE igraph_pajek_yyget_extra (yyscan_t yyscanner ); void igraph_pajek_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *igraph_pajek_yyget_in (yyscan_t yyscanner ); void igraph_pajek_yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *igraph_pajek_yyget_out (yyscan_t yyscanner ); void igraph_pajek_yyset_out (FILE * out_str ,yyscan_t yyscanner ); yy_size_t igraph_pajek_yyget_leng (yyscan_t yyscanner ); char *igraph_pajek_yyget_text (yyscan_t yyscanner ); int igraph_pajek_yyget_lineno (yyscan_t yyscanner ); void igraph_pajek_yyset_lineno (int line_number ,yyscan_t yyscanner ); YYSTYPE * igraph_pajek_yyget_lval (yyscan_t yyscanner ); void igraph_pajek_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); YYLTYPE *igraph_pajek_yyget_lloc (yyscan_t yyscanner ); void igraph_pajek_yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int igraph_pajek_yywrap (yyscan_t yyscanner ); #else extern int igraph_pajek_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int igraph_pajek_yylex \ (YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner); #define YY_DECL int igraph_pajek_yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; #line 78 "src/foreign-pajek-lexer.l" #line 861 "lex.yy.c" yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { igraph_pajek_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_pajek_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_pajek_yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 160 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 289 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 80 "src/foreign-pajek-lexer.l" { } YY_BREAK case 2: /* rule 2 can match eol */ YY_RULE_SETUP #line 81 "src/foreign-pajek-lexer.l" { } YY_BREAK case 3: /* rule 3 can match eol */ YY_RULE_SETUP #line 82 "src/foreign-pajek-lexer.l" { } YY_BREAK case 4: YY_RULE_SETUP #line 83 "src/foreign-pajek-lexer.l" { return NETWORKLINE; } YY_BREAK case 5: YY_RULE_SETUP #line 84 "src/foreign-pajek-lexer.l" { return NETWORKLINE; } YY_BREAK case 6: YY_RULE_SETUP #line 85 "src/foreign-pajek-lexer.l" { return VERTICESLINE; } YY_BREAK case 7: YY_RULE_SETUP #line 86 "src/foreign-pajek-lexer.l" { return ARCSLINE; } YY_BREAK case 8: YY_RULE_SETUP #line 87 "src/foreign-pajek-lexer.l" { return EDGESLINE; } YY_BREAK case 9: YY_RULE_SETUP #line 88 "src/foreign-pajek-lexer.l" { return ARCSLISTLINE; } YY_BREAK case 10: YY_RULE_SETUP #line 89 "src/foreign-pajek-lexer.l" { return EDGESLISTLINE; } YY_BREAK case 11: YY_RULE_SETUP #line 90 "src/foreign-pajek-lexer.l" { return MATRIXLINE; } YY_BREAK case 12: /* rule 12 can match eol */ YY_RULE_SETUP #line 91 "src/foreign-pajek-lexer.l" { yyextra->mode=0; return NEWLINE; } YY_BREAK case 13: /* rule 13 can match eol */ YY_RULE_SETUP #line 92 "src/foreign-pajek-lexer.l" { return QSTR; } YY_BREAK case 14: /* rule 14 can match eol */ YY_RULE_SETUP #line 93 "src/foreign-pajek-lexer.l" { return PSTR; } YY_BREAK case 15: YY_RULE_SETUP #line 94 "src/foreign-pajek-lexer.l" { return NUM; } YY_BREAK case 16: /* rule 16 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 97 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_X_FACT; } else { return ALNUM; } } YY_BREAK case 17: /* rule 17 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 6; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 98 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_Y_FACT; } else { return ALNUM; } } YY_BREAK case 18: /* rule 18 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 99 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_IC; } else { return ALNUM; } } YY_BREAK case 19: /* rule 19 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 100 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_BC; } else { return ALNUM; } } YY_BREAK case 20: /* rule 20 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 101 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_BW; } else { return ALNUM; } } YY_BREAK case 21: /* rule 21 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 102 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_PHI; } else { return ALNUM; } } YY_BREAK case 22: /* rule 22 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 103 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_R; } else { return ALNUM; } } YY_BREAK case 23: /* rule 23 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 104 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_Q; } else { return ALNUM; } } YY_BREAK case 24: /* rule 24 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 105 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_FONT; } else { return ALNUM; } } YY_BREAK case 25: /* rule 25 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 106 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_URL; } else { return ALNUM; } } YY_BREAK case 26: /* rule 26 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 108 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_C; } else { return ALNUM; } } YY_BREAK case 27: /* rule 27 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 109 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_P; } else { return ALNUM; } } YY_BREAK case 28: /* rule 28 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 110 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_S; } else { return ALNUM; } } YY_BREAK case 29: /* rule 29 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 111 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_A; } else { return ALNUM; } } YY_BREAK case 30: /* rule 30 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 112 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_W; } else { return ALNUM; } } YY_BREAK case 31: /* rule 31 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 113 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_H1; } else { return ALNUM; } } YY_BREAK case 32: /* rule 32 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 114 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_H2; } else { return ALNUM; } } YY_BREAK case 33: /* rule 33 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 115 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_A1; } else { return ALNUM; } } YY_BREAK case 34: /* rule 34 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 116 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_A2; } else { return ALNUM; } } YY_BREAK case 35: /* rule 35 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 117 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_K1; } else { return ALNUM; } } YY_BREAK case 36: /* rule 36 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 118 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_K2; } else { return ALNUM; } } YY_BREAK case 37: /* rule 37 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 119 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_AP; } else { return ALNUM; } } YY_BREAK case 38: /* rule 38 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 120 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_L; } else { return ALNUM; } } YY_BREAK case 39: /* rule 39 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 121 "src/foreign-pajek-lexer.l" { if (yyextra->mode==2) { return EP_LP; } else { return ALNUM; } } YY_BREAK case 40: /* rule 40 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 123 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_LPHI; } else if (yyextra->mode==2) { return EP_LPHI; } else { return ALNUM; } } YY_BREAK case 41: /* rule 41 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 125 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_LC; } else if (yyextra->mode==2) { return EP_LC; } else { return ALNUM; } } YY_BREAK case 42: /* rule 42 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 127 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_LR; } else if (yyextra->mode==2) { return EP_LR; } else { return ALNUM; } } YY_BREAK case 43: /* rule 43 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 2; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 129 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_LA; } else if (yyextra->mode==2) { return EP_LA; } else { return ALNUM; } } YY_BREAK case 44: /* rule 44 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 4; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 131 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_SIZE; } else if (yyextra->mode==2) { return EP_SIZE; } else { return ALNUM; } } YY_BREAK case 45: /* rule 45 can match eol */ *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp = yy_bp + 3; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 133 "src/foreign-pajek-lexer.l" { if (yyextra->mode==1) { return VP_FOS; } else if (yyextra->mode==2) { return EP_FOS; } else { return ALNUM; } } YY_BREAK case 46: YY_RULE_SETUP #line 136 "src/foreign-pajek-lexer.l" { return ALNUM; } YY_BREAK case YY_STATE_EOF(INITIAL): #line 138 "src/foreign-pajek-lexer.l" { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; return NEWLINE; } } YY_BREAK case 47: YY_RULE_SETUP #line 146 "src/foreign-pajek-lexer.l" { return ERROR; } YY_BREAK case 48: YY_RULE_SETUP #line 148 "src/foreign-pajek-lexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 1330 "lex.yy.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * igraph_pajek_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( igraph_pajek_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of igraph_pajek_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ igraph_pajek_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; igraph_pajek_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) igraph_pajek_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 160 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 160 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 159); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ igraph_pajek_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( igraph_pajek_yywrap(yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void igraph_pajek_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ igraph_pajek_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_pajek_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_pajek_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); igraph_pajek_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void igraph_pajek_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * igraph_pajek_yypop_buffer_state(); * igraph_pajek_yypush_buffer_state(new_buffer); */ igraph_pajek_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; igraph_pajek_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (igraph_pajek_yywrap()) processing, but the only time this flag * is looked at is after igraph_pajek_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void igraph_pajek_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE igraph_pajek_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) igraph_pajek_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) igraph_pajek_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yy_create_buffer()" ); b->yy_is_our_buffer = 1; igraph_pajek_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with igraph_pajek_yy_create_buffer() * @param yyscanner The scanner object. */ void igraph_pajek_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) igraph_pajek_yyfree((void *) b->yy_ch_buf ,yyscanner ); igraph_pajek_yyfree((void *) b ,yyscanner ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a igraph_pajek_yyrestart() or at EOF. */ static void igraph_pajek_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; igraph_pajek_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then igraph_pajek_yy_init_buffer was _probably_ * called from igraph_pajek_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void igraph_pajek_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) igraph_pajek_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void igraph_pajek_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; igraph_pajek_yyensure_buffer_stack(yyscanner); /* This block is copied from igraph_pajek_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from igraph_pajek_yy_switch_to_buffer. */ igraph_pajek_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void igraph_pajek_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; igraph_pajek_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { igraph_pajek_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void igraph_pajek_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_pajek_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_pajek_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_pajek_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) igraph_pajek_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; igraph_pajek_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to igraph_pajek_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * igraph_pajek_yy_scan_bytes() instead. */ YY_BUFFER_STATE igraph_pajek_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return igraph_pajek_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to igraph_pajek_yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_pajek_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) igraph_pajek_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_pajek_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = igraph_pajek_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in igraph_pajek_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE igraph_pajek_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int igraph_pajek_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int igraph_pajek_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *igraph_pajek_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *igraph_pajek_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t igraph_pajek_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *igraph_pajek_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void igraph_pajek_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void igraph_pajek_yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_pajek_yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void igraph_pajek_yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_pajek_yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see igraph_pajek_yy_switch_to_buffer */ void igraph_pajek_yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void igraph_pajek_yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int igraph_pajek_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void igraph_pajek_yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * igraph_pajek_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void igraph_pajek_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *igraph_pajek_yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void igraph_pajek_yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* igraph_pajek_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int igraph_pajek_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_pajek_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* igraph_pajek_yylex_init_extra has the same functionality as igraph_pajek_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to igraph_pajek_yyalloc in * the yyextra field. */ int igraph_pajek_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; igraph_pajek_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_pajek_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); igraph_pajek_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from igraph_pajek_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * igraph_pajek_yylex_init() */ return 0; } /* igraph_pajek_yylex_destroy is for both reentrant and non-reentrant scanners. */ int igraph_pajek_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ igraph_pajek_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; igraph_pajek_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ igraph_pajek_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ igraph_pajek_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * igraph_pajek_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ igraph_pajek_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *igraph_pajek_yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *igraph_pajek_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void igraph_pajek_yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see igraph_pajek_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 148 "src/foreign-pajek-lexer.l" igraph/src/igraph_marked_queue.h0000644000175100001440000000463113431000472016501 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_MARKED_QUEUE_H #define IGRAPH_MARKED_QUEUE_H #include "igraph_vector.h" #include "igraph_dqueue.h" #include /* This is essentially a double ended queue, with some extra features: (1) The is-element? operation is fast, O(1). This requires that we know a limit for the number of elements in the queue. (2) We can insert elements in batches, and the whole batch can be removed at once. Currently only the top-end operations are implemented, so the queue is essentially a stack. */ typedef struct igraph_marked_queue_t { igraph_dqueue_t Q; igraph_vector_long_t set; long int mark; long int size; } igraph_marked_queue_t; int igraph_marked_queue_init(igraph_marked_queue_t *q, long int size); void igraph_marked_queue_destroy(igraph_marked_queue_t *q); void igraph_marked_queue_reset(igraph_marked_queue_t *q); igraph_bool_t igraph_marked_queue_empty(const igraph_marked_queue_t *q); long int igraph_marked_queue_size(const igraph_marked_queue_t *q); int igraph_marked_queue_print(const igraph_marked_queue_t *q); int igraph_marked_queue_fprint(const igraph_marked_queue_t *q, FILE *file); igraph_bool_t igraph_marked_queue_iselement(const igraph_marked_queue_t *q, long int elem); int igraph_marked_queue_push(igraph_marked_queue_t *q, long int elem); int igraph_marked_queue_start_batch(igraph_marked_queue_t *q); void igraph_marked_queue_pop_back_batch(igraph_marked_queue_t *q); int igraph_marked_queue_as_vector(const igraph_marked_queue_t *q, igraph_vector_t *vec); #endif igraph/src/layout_dh.c0000644000175100001440000003404413431000472014464 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph R package. Copyright (C) 2014 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_layout.h" #include "igraph_interface.h" #include "igraph_random.h" #include "igraph_math.h" #include igraph_bool_t igraph_i_segments_intersect(float p0_x, float p0_y, float p1_x, float p1_y, float p2_x, float p2_y, float p3_x, float p3_y) { float s1_x = p1_x - p0_x; float s1_y = p1_y - p0_y; float s2_x = p3_x - p2_x; float s2_y = p3_y - p2_y; float s1, s2, t1, t2, s, t; s1 = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)); s2 = (-s2_x * s1_y + s1_x * s2_y); if (s2 == 0) { return 0; } t1 = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)); t2 = (-s2_x * s1_y + s1_x * s2_y); s = s1 / s2; t = t1 / t2; return s >= 0 && s <= 1 && t >= 0 && t <= 1 ? 1 : 0; } float igraph_i_point_segment_dist2(float v_x, float v_y, float u1_x, float u1_y, float u2_x, float u2_y) { float dx = u2_x - u1_x; float dy = u2_y - u1_y; float l2 = dx * dx + dy * dy; float t, p_x, p_y; if (l2 == 0) { return (v_x-u1_x) * (v_x-u1_x) + (v_y-u1_y) * (v_y-u1_y); } t = ((v_x - u1_x) * dx + (v_y - u1_y) * dy) / l2; if (t < 0.0) { return (v_x-u1_x) * (v_x-u1_x) + (v_y-u1_y) * (v_y-u1_y); } else if (t > 1.0) { return (v_x-u2_x) * (v_x-u2_x) + (v_y-u2_y) * (v_y-u2_y); } p_x = u1_x + t * dx; p_y = u1_y + t * dy; return (v_x-p_x) * (v_x-p_x) + (v_y-p_y) * (v_y-p_y); } /** * \function igraph_layout_davidson_harel * Davidson-Harel layout algorithm * * This function implements the algorithm by Davidson and Harel, * see Ron Davidson, David Harel: Drawing Graphs Nicely Using * Simulated Annealing. ACM Transactions on Graphics 15(4), * pp. 301-331, 1996. * * * The algorithm uses simulated annealing and a sophisticated * energy function, which is unfortunately hard to parameterize * for different graphs. The original publication did not disclose any * parameter values, and the ones below were determined by * experimentation. * * * The algorithm consists of two phases, an annealing phase, and a * fine-tuning phase. There is no simulated annealing in the second * phase. * * * Our implementation tries to follow the original publication, as * much as possible. The only major difference is that coordinates are * explicitly kept within the bounds of the rectangle of the layout. * * \param graph The input graph, edge directions are ignored. * \param res A matrix, the result is stored here. It can be used to * supply start coordinates, see \p use_seed. * \param use_seed Boolean, whether to use the supplied \p res as * start coordinates. * \param maxiter The maximum number of annealing iterations. A * reasonable value for smaller graphs is 10. * \param fineiter The number of fine tuning iterations. A reasonable * value is max(10, log2(n)) where n is the number of vertices. * \param cool_fact Cooling factor. A reasonable value is 0.75. * \param weight_node_dist Weight for the node-node distances * component of the energy function. Reasonable value: 1.0. * \param weight_border Weight for the distance from the border * component of the energy function. It can be set to zero, if * vertices are allowed to sit on the border. * \param weight_edge_lengths Weight for the edge length component * of the energy function, a reasonable value is the density of * the graph divided by 10. * \param weight_edge_crossings Weight for the edge crossing component * of the energy function, a reasonable default is 1 minus the * square root of the density of the graph. * \param weight_node_edge_dist Weight for the node-edge distance * component of the energy function. A reasonable value is * 1 minus the density, divided by 5. * \return Error code. * * Time complexity: one first phase iteration has time complexity * O(n^2+m^2), one fine tuning iteration has time complexity O(mn). * Time complexity might be smaller if some of the weights of the * components of the energy function are set to zero. * */ int igraph_layout_davidson_harel(const igraph_t *graph, igraph_matrix_t *res, igraph_bool_t use_seed, igraph_integer_t maxiter, igraph_integer_t fineiter, igraph_real_t cool_fact, igraph_real_t weight_node_dist, igraph_real_t weight_border, igraph_real_t weight_edge_lengths, igraph_real_t weight_edge_crossings, igraph_real_t weight_node_edge_dist) { igraph_integer_t no_nodes = igraph_vcount(graph); igraph_integer_t no_edges = igraph_ecount(graph); float width = sqrt(no_nodes) * 10, height = width; igraph_vector_int_t perm; igraph_bool_t fine_tuning=0; igraph_integer_t round, i; igraph_vector_float_t try_x, try_y; igraph_vector_int_t try_idx; float move_radius=width / 2; float fine_tuning_factor=0.01; igraph_vector_t neis; float min_x=width/2, max_x=-width/2, min_y=height/2, max_y=-height/2; igraph_integer_t no_tries = 30; float w_node_dist = weight_node_dist ; /* 1.0 */ float w_borderlines = weight_border; /* 0.0 */ float w_edge_lengths = weight_edge_lengths; /* 0.0001; */ float w_edge_crossings = weight_edge_crossings; /* 1.0 */ float w_node_edge_dist = weight_node_edge_dist; /* 0.2 */ if (use_seed && (igraph_matrix_nrow(res) != no_nodes || igraph_matrix_ncol(res) != 2)) { IGRAPH_ERROR("Invalid start position matrix size in " "Davidson-Harel layout", IGRAPH_EINVAL); } if (maxiter < 0) { IGRAPH_ERROR("Number of iterations must be non-negative in " "Davidson-Harel layout", IGRAPH_EINVAL); } if (fineiter < 0) { IGRAPH_ERROR("Number of fine tuning iterations must be non-negative in " "Davidson-Harel layout", IGRAPH_EINVAL); } if (cool_fact <= 0 || cool_fact >= 1) { IGRAPH_ERROR("Cooling factor must be in (0,1) in " "Davidson-Harel layout", IGRAPH_EINVAL); } if (no_nodes == 0) { return 0; } IGRAPH_CHECK(igraph_vector_int_init_seq(&perm, 0, no_nodes-1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &perm); IGRAPH_CHECK(igraph_vector_float_init(&try_x, no_tries)); IGRAPH_FINALLY(igraph_vector_float_destroy, &try_x); IGRAPH_CHECK(igraph_vector_float_init(&try_y, no_tries)); IGRAPH_FINALLY(igraph_vector_float_destroy, &try_y); IGRAPH_CHECK(igraph_vector_int_init_seq(&try_idx, 0, no_tries-1)); IGRAPH_FINALLY(igraph_vector_int_destroy, &try_idx); IGRAPH_VECTOR_INIT_FINALLY(&neis, 100); RNG_BEGIN(); if (!use_seed) { IGRAPH_CHECK(igraph_matrix_resize(res, no_nodes, 2)); for (i=0; i max_x) { max_x = x; } if (y < min_y) { min_y = y; } else if (y > max_y) { max_y = y; } } } else { min_x = IGRAPH_INFINITY; max_x = IGRAPH_NEGINFINITY; min_y = IGRAPH_INFINITY; max_y = IGRAPH_NEGINFINITY; for (i=0; i max_x) { max_x = x; } if (y < min_y) { min_y = y; } else if (y > max_y) { max_y = y; } } } for (i = 0; i < no_tries; i++) { float phi=2 * M_PI / no_tries * i; VECTOR(try_x)[i] = cos(phi); VECTOR(try_y)[i] = sin(phi); } for (round = 0; round < maxiter + fineiter; round++) { igraph_integer_t p; igraph_vector_int_shuffle(&perm); fine_tuning = round >= maxiter; if (fine_tuning) { float fx = fine_tuning_factor * (max_x - min_x); float fy = fine_tuning_factor * (max_y - min_y); move_radius = fx < fy ? fx : fy; } for (p = 0; p < no_nodes; p++) { igraph_integer_t t; igraph_integer_t v=VECTOR(perm)[p]; igraph_vector_int_shuffle(&try_idx); for (t = 0; t < no_tries; t++) { float diff_energy=0.0; int ti=VECTOR(try_idx)[t]; /* Try moving it */ float old_x = MATRIX(*res, v, 0); float old_y = MATRIX(*res, v, 1); float new_x = old_x + move_radius * VECTOR(try_x)[ti]; float new_y = old_y + move_radius * VECTOR(try_y)[ti]; if (new_x < -width /2) { new_x = -width/2 - 1e-6; } if (new_x > width /2) { new_x = width/2 - 1e-6; } if (new_y < -height/2) { new_y = -height/2 - 1e-6; } if (new_y > height/2) { new_y = height/2 - 1e-6; } if (w_node_dist != 0) { igraph_integer_t u; for (u = 0; u < no_nodes; u++) { float odx, ody, odist2, dx, dy, dist2; if (u == v) { continue; } odx = old_x - MATRIX(*res, u, 0); ody = old_y - MATRIX(*res, u, 1); dx = new_x - MATRIX(*res, u, 0); dy = new_y - MATRIX(*res, u, 1); odist2 = odx * odx + ody * ody; dist2 = dx * dx + dy * dy; diff_energy += w_node_dist / dist2 - w_node_dist / odist2; } } if (w_borderlines != 0) { float odx1 = width/2 - old_x, odx2 = old_x + width/2; float ody1 = height/2 - old_y, ody2 = old_y + height/2; float dx1 = width/2 - new_x, dx2 = new_x + width/2; float dy1 = height/2 - new_y, dy2 = new_y + height/2; if (odx1 < 0) { odx1 = 2; } if (odx2 < 0) { odx2 = 2; } if (ody1 < 0) { ody1 = 2; } if (ody2 < 0) { ody2 = 2; } if (dx1 < 0) { dx1 = 2; } if (dx2 < 0) { dx2 = 2; } if (dy1 < 0) { dy1 = 2; } if (dy2 < 0) { dy2 = 2; } diff_energy -= w_borderlines * (1.0 / (odx1 * odx1) + 1.0 / (odx2 * odx2) + 1.0 / (ody1 * ody1) + 1.0 / (ody2 * ody2)); diff_energy += w_borderlines * (1.0 / (dx1 * dx1) + 1.0 / (dx2 * dx2) + 1.0 / (dy1 * dy1) + 1.0 / (dy2 * dy2)); } if (w_edge_lengths != 0) { igraph_integer_t len, j; igraph_neighbors(graph, &neis, v, IGRAPH_ALL); len=igraph_vector_size(&neis); for (j = 0; j < len; j++) { igraph_integer_t u=VECTOR(neis)[j]; float odx = old_x - MATRIX(*res, u, 0); float ody = old_y - MATRIX(*res, u, 1); float odist2 = odx * odx + ody * ody; float dx = new_x - MATRIX(*res, u, 0); float dy = new_y - MATRIX(*res, u, 1); float dist2 = dx * dx + dy * dy; diff_energy += w_edge_lengths * (dist2 - odist2); } } if (w_edge_crossings != 0) { igraph_integer_t len, j, no=0; igraph_neighbors(graph, &neis, v, IGRAPH_ALL); len=igraph_vector_size(&neis); for (j = 0; j < len; j++) { igraph_integer_t u = VECTOR(neis)[j]; float u_x = MATRIX(*res, u, 0); float u_y = MATRIX(*res, u, 1); igraph_integer_t e; for (e = 0; e < no_edges; e++) { igraph_integer_t u1 = IGRAPH_FROM(graph, e); igraph_integer_t u2 = IGRAPH_TO(graph, e); float u1_x, u1_y, u2_x, u2_y; if (u1 == v || u2 == v || u1 == u || u2 == u) { continue; } u1_x = MATRIX(*res, u1, 0); u1_y = MATRIX(*res, u1, 1); u2_x = MATRIX(*res, u2, 0); u2_y = MATRIX(*res, u2, 1); no -= igraph_i_segments_intersect(old_x, old_y, u_x, u_y, u1_x, u1_y, u2_x, u2_y); no += igraph_i_segments_intersect(new_x, new_y, u_x, u_y, u1_x, u1_y, u2_x, u2_y); } } diff_energy += w_edge_crossings * no; } if (w_node_edge_dist != 0 && fine_tuning) { igraph_integer_t e, no; /* All non-incident edges from the moved 'v' */ for (e = 0; e < no_edges; e++) { igraph_integer_t u1 = IGRAPH_FROM(graph, e); igraph_integer_t u2 = IGRAPH_TO(graph, e); float u1_x, u1_y, u2_x, u2_y, d_ev; if (u1 == v || u2 == v) { continue; } u1_x = MATRIX(*res, u1, 0); u1_y = MATRIX(*res, u1, 1); u2_x = MATRIX(*res, u2, 0); u2_y = MATRIX(*res, u2, 1); d_ev = igraph_i_point_segment_dist2(old_x, old_y, u1_x, u1_y, u2_x, u2_y); diff_energy -= w_node_edge_dist / d_ev; d_ev = igraph_i_point_segment_dist2(new_x, new_y, u1_x, u1_y, u2_x, u2_y); diff_energy += w_node_edge_dist / d_ev; } /* All other nodes from all of v's incident edges */ igraph_incident(graph, &neis, v, IGRAPH_ALL); no=igraph_vector_size(&neis); for (e = 0; e < no; e++) { igraph_integer_t mye=VECTOR(neis)[e]; igraph_integer_t u=IGRAPH_OTHER(graph, mye, v); float u_x=MATRIX(*res, u, 0); float u_y=MATRIX(*res, u, 1); igraph_integer_t w; for (w = 0; w < no_nodes; w++) { float w_x, w_y, d_ev; if (w == v || w == u) { continue; } w_x=MATRIX(*res, w, 0); w_y=MATRIX(*res, w, 1); d_ev = igraph_i_point_segment_dist2(w_x, w_y, old_x, old_y, u_x, u_y); diff_energy -= w_node_edge_dist / d_ev; d_ev = igraph_i_point_segment_dist2(w_x, w_y, new_x, new_y, u_x, u_y); diff_energy += w_node_edge_dist / d_ev; } } } /* w_node_edge_dist != 0 && fine_tuning */ if (diff_energy < 0 || (!fine_tuning && RNG_UNIF01() < exp(-diff_energy/move_radius))) { MATRIX(*res, v, 0) = new_x; MATRIX(*res, v, 1) = new_y; if (new_x < min_x) { min_x = new_x; } else if (new_x > max_x) { max_x = new_x; } if (new_y < min_y) { min_y = new_y; } else if (new_y > max_y) { max_y = new_y; } } } /* t < no_tries */ } /* p < no_nodes */ move_radius *= cool_fact; } /* round < maxiter */ RNG_END(); igraph_vector_destroy(&neis); igraph_vector_int_destroy(&try_idx); igraph_vector_float_destroy(&try_x); igraph_vector_float_destroy(&try_y); igraph_vector_int_destroy(&perm); IGRAPH_FINALLY_CLEAN(5); return 0; } igraph/src/foreign-gml-parser.c0000644000175100001440000014466713431000472016211 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Using locations. */ #define YYLSP_NEEDED 1 /* Substitute the variable and function names. */ #define yyparse igraph_gml_yyparse #define yylex igraph_gml_yylex #define yyerror igraph_gml_yyerror #define yylval igraph_gml_yylval #define yychar igraph_gml_yychar #define yydebug igraph_gml_yydebug #define yynerrs igraph_gml_yynerrs #define yylloc igraph_gml_yylloc /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { STRING = 258, NUM = 259, KEYWORD = 260, LISTOPEN = 261, LISTCLOSE = 262, EOFF = 263, ERROR = 264 }; #endif /* Tokens. */ #define STRING 258 #define NUM 259 #define KEYWORD 260 #define LISTOPEN 261 #define LISTCLOSE 262 #define EOFF 263 #define ERROR 264 /* Copy the first part of user declarations. */ #line 23 "src/foreign-gml-parser.y" /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include "igraph_error.h" #include "igraph_memory.h" #include "config.h" #include "igraph_hacks_internal.h" #include "igraph_math.h" #include "igraph_gml_tree.h" #include "foreign-gml-header.h" #include "foreign-gml-parser.h" #define yyscan_t void* int igraph_gml_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void *scanner); int igraph_gml_yyerror(YYLTYPE* locp, igraph_i_gml_parsedata_t *context, const char *s); char *igraph_gml_yyget_text (yyscan_t yyscanner ); int igraph_gml_yyget_leng (yyscan_t yyscanner ); void igraph_i_gml_get_keyword(char *s, int len, void *res); void igraph_i_gml_get_string(char *s, int len, void *res); double igraph_i_gml_get_real(char *s, int len); igraph_gml_tree_t *igraph_i_gml_make_numeric(char* s, int len, double value); igraph_gml_tree_t *igraph_i_gml_make_numeric2(char* s, int len, char *v, int vlen); igraph_gml_tree_t *igraph_i_gml_make_string(char* s, int len, char *value, int valuelen); igraph_gml_tree_t *igraph_i_gml_make_list(char* s, int len, igraph_gml_tree_t *list); igraph_gml_tree_t *igraph_i_gml_merge(igraph_gml_tree_t *t1, igraph_gml_tree_t* t2); #define scanner context->scanner #define USE(x) /*(x)*/ /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 93 "src/foreign-gml-parser.y" { struct { char *s; int len; } str; void *tree; double real; } /* Line 193 of yacc.c. */ #line 192 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 217 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 6 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 14 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 10 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 7 /* YYNRULES -- Number of rules. */ #define YYNRULES 12 /* YYNRULES -- Number of states. */ #define YYNSTATES 17 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 264 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 5, 8, 10, 13, 16, 19, 24, 27, 29, 31 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 11, 0, -1, 12, -1, 12, 8, -1, 13, -1, 12, 13, -1, 14, 15, -1, 14, 16, -1, 14, 6, 12, 7, -1, 14, 14, -1, 5, -1, 4, -1, 3, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 121, 121, 122, 125, 126, 128, 130, 132, 134, 138, 141, 144 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "STRING", "NUM", "KEYWORD", "LISTOPEN", "LISTCLOSE", "EOFF", "ERROR", "$accept", "input", "list", "keyvalue", "key", "num", "string", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 10, 11, 11, 12, 12, 13, 13, 13, 13, 14, 15, 16 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 1, 2, 1, 2, 2, 2, 4, 2, 1, 1, 1 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 0, 10, 0, 2, 4, 0, 1, 3, 5, 12, 11, 0, 9, 6, 7, 0, 8 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 2, 3, 4, 5, 13, 14 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -4 static const yytype_int8 yypact[] = { 1, -4, 10, 0, -4, -2, -4, -4, -4, -4, -4, 1, -4, -4, -4, 2, -4 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -4, -4, 3, -3, 6, -4, -4 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 8, 9, 10, 1, 11, 1, 1, 1, 7, 16, 6, 12, 8, 0, 15 }; static const yytype_int8 yycheck[] = { 3, 3, 4, 5, 6, 5, 5, 5, 8, 7, 0, 5, 15, -1, 11 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 5, 11, 12, 13, 14, 0, 8, 13, 3, 4, 6, 14, 15, 16, 12, 7 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc, scanner) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_gml_parsedata_t* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_gml_parsedata_t* context; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_gml_parsedata_t* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_gml_parsedata_t* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, igraph_i_gml_parsedata_t* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; igraph_i_gml_parsedata_t* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, igraph_i_gml_parsedata_t* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; igraph_i_gml_parsedata_t* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { case 5: /* "KEYWORD" */ #line 116 "src/foreign-gml-parser.y" { igraph_Free((yyvaluep->str).s); }; #line 1121 "y.tab.c" break; case 12: /* "list" */ #line 117 "src/foreign-gml-parser.y" { igraph_gml_tree_destroy((yyvaluep->tree)); }; #line 1126 "y.tab.c" break; case 13: /* "keyvalue" */ #line 117 "src/foreign-gml-parser.y" { igraph_gml_tree_destroy((yyvaluep->tree)); }; #line 1131 "y.tab.c" break; case 14: /* "key" */ #line 116 "src/foreign-gml-parser.y" { igraph_Free((yyvaluep->str).s); }; #line 1136 "y.tab.c" break; case 16: /* "string" */ #line 116 "src/foreign-gml-parser.y" { igraph_Free((yyvaluep->str).s); }; #line 1141 "y.tab.c" break; default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (igraph_i_gml_parsedata_t* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (igraph_i_gml_parsedata_t* context) #else int yyparse (context) igraph_i_gml_parsedata_t* context; #endif #endif { /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 121 "src/foreign-gml-parser.y" { context->tree=(yyvsp[(1) - (1)].tree); ;} break; case 3: #line 122 "src/foreign-gml-parser.y" { context->tree=(yyvsp[(1) - (2)].tree); ;} break; case 4: #line 125 "src/foreign-gml-parser.y" { (yyval.tree)=(yyvsp[(1) - (1)].tree); ;} break; case 5: #line 126 "src/foreign-gml-parser.y" { (yyval.tree)=igraph_i_gml_merge((yyvsp[(1) - (2)].tree), (yyvsp[(2) - (2)].tree)); ;} break; case 6: #line 129 "src/foreign-gml-parser.y" { (yyval.tree)=igraph_i_gml_make_numeric((yyvsp[(1) - (2)].str).s, (yyvsp[(1) - (2)].str).len, (yyvsp[(2) - (2)].real)); ;} break; case 7: #line 131 "src/foreign-gml-parser.y" { (yyval.tree)=igraph_i_gml_make_string((yyvsp[(1) - (2)].str).s, (yyvsp[(1) - (2)].str).len, (yyvsp[(2) - (2)].str).s, (yyvsp[(2) - (2)].str).len); ;} break; case 8: #line 133 "src/foreign-gml-parser.y" { (yyval.tree)=igraph_i_gml_make_list((yyvsp[(1) - (4)].str).s, (yyvsp[(1) - (4)].str).len, (yyvsp[(3) - (4)].tree)); ;} break; case 9: #line 135 "src/foreign-gml-parser.y" { (yyval.tree)=igraph_i_gml_make_numeric2((yyvsp[(1) - (2)].str).s, (yyvsp[(1) - (2)].str).len, (yyvsp[(2) - (2)].str).s, (yyvsp[(2) - (2)].str).len); ;} break; case 10: #line 138 "src/foreign-gml-parser.y" { igraph_i_gml_get_keyword(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner), &(yyval.str)); USE((yyvsp[(1) - (1)].str)) ;} break; case 11: #line 141 "src/foreign-gml-parser.y" { (yyval.real)=igraph_i_gml_get_real(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner)); ;} break; case 12: #line 144 "src/foreign-gml-parser.y" { igraph_i_gml_get_string(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner), &(yyval.str)); ;} break; /* Line 1267 of yacc.c. */ #line 1525 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (&yylloc, context, yymsg); } else { yyerror (&yylloc, context, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 148 "src/foreign-gml-parser.y" int igraph_gml_yyerror(YYLTYPE* locp, igraph_i_gml_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in GML file, line %i (%s)", locp->first_line, s); return 0; } void igraph_i_gml_get_keyword(char *s, int len, void *res) { struct { char *s; int len; } *p=res; p->s=igraph_Calloc(len+1, char); if (!p->s) { igraph_error("Cannot read GML file", __FILE__, __LINE__, IGRAPH_PARSEERROR); } memcpy(p->s, s, sizeof(char)*len); p->s[len]='\0'; p->len=len; } void igraph_i_gml_get_string(char *s, int len, void *res) { struct { char *s; int len; } *p=res; p->s=igraph_Calloc(len-1, char); if (!p->s) { igraph_error("Cannot read GML file", __FILE__, __LINE__, IGRAPH_PARSEERROR); } memcpy(p->s, s+1, sizeof(char)*(len-2)); p->s[len-2]='\0'; p->len=len-2; } double igraph_i_gml_get_real(char *s, int len) { igraph_real_t num; char tmp=s[len]; s[len]='\0'; sscanf(s, "%lf", &num); s[len]=tmp; return num; } igraph_gml_tree_t *igraph_i_gml_make_numeric(char* s, int len, double value) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } if (floor(value)==value) { igraph_gml_tree_init_integer(t, s, len, value); } else { igraph_gml_tree_init_real(t, s, len, value); } return t; } igraph_gml_tree_t *igraph_i_gml_make_numeric2(char* s, int len, char *v, int vlen) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); char tmp=v[vlen]; igraph_real_t value=0; if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } v[vlen]='\0'; if (strcasecmp(v, "inf")) { value=IGRAPH_INFINITY; } else if (strcasecmp(v, "nan")) { value=IGRAPH_NAN; } else { igraph_error("Parse error", __FILE__, __LINE__, IGRAPH_PARSEERROR); } v[vlen]=tmp; igraph_gml_tree_init_real(t, s, len, value); return t; } igraph_gml_tree_t *igraph_i_gml_make_string(char* s, int len, char *value, int valuelen) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } igraph_gml_tree_init_string(t, s, len, value, valuelen); return t; } igraph_gml_tree_t *igraph_i_gml_make_list(char* s, int len, igraph_gml_tree_t *list) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } igraph_gml_tree_init_tree(t, s, len, list); return t; } igraph_gml_tree_t *igraph_i_gml_merge(igraph_gml_tree_t *t1, igraph_gml_tree_t* t2) { igraph_gml_tree_mergedest(t1, t2); igraph_Free(t2); return t1; } igraph/src/igraph_arpack_internal.h0000644000175100001440000001574113431000472017173 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ARPACK_INTERNAL_H #define ARPACK_INTERNAL_H /* Note: only files calling the arpack routines directly need to include this header. */ #include "igraph_types.h" #include "config.h" #ifndef INTERNAL_ARPACK #define igraphdsaupd_ dsaupd_ #define igraphdseupd_ dseupd_ #define igraphdsaup2_ dsaup2_ #define igraphdstats_ dstats_ #define igraphdsesrt_ dsesrt_ #define igraphdsortr_ dsortr_ #define igraphdsortc_ dsortc_ #define igraphdgetv0_ dgetv0_ #define igraphdsaitr_ dsaitr_ #define igraphdsapps_ dsapps_ #define igraphdsconv_ dsconv_ #define igraphdseigt_ dseigt_ #define igraphdsgets_ dsgets_ #define igraphdstqrb_ dstqrb_ #define igraphdmout_ dmout_ #define igraphivout_ ivout_ #define igraphsecond_ second_ #define igraphdvout_ dvout_ #define igraphdnaitr_ dnaitr_ #define igraphdnapps_ dnapps_ #define igraphdnaup2_ dnaup2_ #define igraphdnaupd_ dnaupd_ #define igraphdnconv_ dnconv_ #define igraphdlabad_ dlabad_ #define igraphdlanhs_ dlanhs_ #define igraphdsortc_ dsortc_ #define igraphdneigh_ dneigh_ #define igraphdngets_ dngets_ #define igraphdstatn_ dstatn_ #define igraphdlaqrb_ dlaqrb_ #define igraphdsaupd_ dsaupd_ #define igraphdseupd_ dseupd_ #define igraphdnaupd_ dnaupd_ #define igraphdneupd_ dneupd_ #endif #ifndef INTERNAL_LAPACK #define igraphdlarnv_ dlarnv_ #define igraphdlascl_ dlascl_ #define igraphdlartg_ dlartg_ #define igraphdlaset_ dlaset_ #define igraphdlae2_ dlae2_ #define igraphdlaev2_ dlaev2_ #define igraphdlasr_ dlasr_ #define igraphdlasrt_ dlasrt_ #define igraphdgeqr2_ dgeqr2_ #define igraphdlacpy_ dlacpy_ #define igraphdorm2r_ dorm2r_ #define igraphdsteqr_ dsteqr_ #define igraphdlanst_ dlanst_ #define igraphdlapy2_ dlapy2_ #define igraphdlamch_ dlamch_ #define igraphdlaruv_ dlaruv_ #define igraphdlarfg_ dlarfg_ #define igraphdlarf_ dlarf_ #define igraphdlassq_ dlassq_ #define igraphdlamc2_ dlamc2_ #define igraphdlamc1_ dlamc1_ #define igraphdlamc2_ dlamc2_ #define igraphdlamc3_ dlamc3_ #define igraphdlamc4_ dlamc4_ #define igraphdlamc5_ dlamc5_ #define igraphdlabad_ dlabad_ #define igraphdlanhs_ dlanhs_ #define igraphdtrevc_ dtrevc_ #define igraphdlanv2_ dlanv2_ #define igraphdlaln2_ dlaln2_ #define igraphdladiv_ dladiv_ #define igraphdtrsen_ dtrsen_ #define igraphdlahqr_ dlahqr_ #define igraphdtrsen_ dtrsen_ #define igraphdlacon_ dlacon_ #define igraphdtrsyl_ dtrsyl_ #define igraphdtrexc_ dtrexc_ #define igraphdlange_ dlange_ #define igraphdlaexc_ dlaexc_ #define igraphdlasy2_ dlasy2_ #define igraphdlarfx_ dlarfx_ #endif #if 0 /* internal f2c functions always used */ #define igraphd_sign d_sign #define igraphetime_ etime_ #define igraphpow_dd pow_dd #define igraphpow_di pow_di #define igraphs_cmp s_cmp #define igraphs_copy s_copy #define igraphd_lg10_ d_lg10_ #define igraphi_dnnt_ i_dnnt_ #endif #ifdef HAVE_GFORTRAN int igraphdsaupd_(int *ido, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info, int bmat_len, int which_len); int igraphdseupd_(int *rvec, char *howmny, int *select, igraph_real_t *d, igraph_real_t *z, int *ldz, igraph_real_t *sigma, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info, int howmny_len, int bmat_len, int which_len); int igraphdnaupd_(int *ido, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info, int bmat_len, int which_len); int igraphdneupd_(int *rvec, char *howmny, int *select, igraph_real_t *dr, igraph_real_t *di, igraph_real_t *z, int *ldz, igraph_real_t *sigmar, igraph_real_t *sigmai, igraph_real_t *workev, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info, int howmny_len, int bmat_len, int which_len); int igraphdsortr_(char *which, int *apply, int* n, igraph_real_t *x1, igraph_real_t *x2, int which_len); int igraphdsortc_(char *which, int *apply, int* n, igraph_real_t *xreal, igraph_real_t *ximag, igraph_real_t *y, int which_len); #else int igraphdsaupd_(int *ido, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info); int igraphdseupd_(int *rvec, char *howmny, int *select, igraph_real_t *d, igraph_real_t *z, int *ldz, igraph_real_t *sigma, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info); int igraphdnaupd_(int *ido, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info); int igraphdneupd_(int *rvec, char *howmny, int *select, igraph_real_t *dr, igraph_real_t *di, igraph_real_t *z, int *ldz, igraph_real_t *sigmar, igraph_real_t *sigmai, igraph_real_t *workev, char *bmat, int *n, char *which, int *nev, igraph_real_t *tol, igraph_real_t *resid, int *ncv, igraph_real_t *v, int *ldv, int *iparam, int *ipntr, igraph_real_t *workd, igraph_real_t *workl, int *lworkl, int *info); int igraphdsortr_(char *which, int *apply, int* n, igraph_real_t *x1, igraph_real_t *x2); int igraphdsortc_(char *which, int *apply, int* n, igraph_real_t *xreal, igraph_real_t *ximag, igraph_real_t *y); #endif #endif /* ARPACK_INTERNAL_H */ igraph/src/sbm.c0000644000175100001440000004472113431000472013260 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=8 sw=2 sts=2 et: */ /* IGraph R library. Copyright (C) 2003-2013 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interface.h" #include "igraph_vector.h" #include "igraph_matrix.h" #include "igraph_random.h" #include "igraph_constructors.h" #include "igraph_games.h" #include /* for DBL_EPSILON */ #include /* for sqrt */ /** * \function igraph_sbm_game * Sample from a stochastic block model * * This function samples graphs from a stochastic block * model by (doing the equivalent of) Bernoulli * trials for each potential edge with the probabilities * given by the Bernoulli rate matrix, \p pref_matrix. * See Faust, K., & Wasserman, S. (1992a). Blockmodels: * Interpretation and evaluation. Social Networks, 14, 5-–61. * * * The order of the vertex ids in the generated graph corresponds to * the \p block_sizes argument. * * \param graph The output graph. * \param n Number of vertices. * \param pref_matrix The matrix giving the Bernoulli rates. * This is a KxK matrix, where K is the number of groups. * The probability of creating an edge between vertices from * groups i and j is given by element (i,j). * \param block_sizes An integer vector giving the number of * vertices in each group. * \param directed Boolean, whether to create a directed graph. If * this argument is false, then \p pref_matrix must be symmetric. * \param loops Boolean, whether to create self-loops. * \return Error code. * * Time complexity: O(|V|+|E|+K^2), where |V| is the number of * vertices, |E| is the number of edges, and K is the number of * groups. * * \sa \ref igraph_erdos_renyi_game() for a simple Bernoulli graph. * */ int igraph_sbm_game(igraph_t *graph, igraph_integer_t n, const igraph_matrix_t *pref_matrix, const igraph_vector_int_t *block_sizes, igraph_bool_t directed, igraph_bool_t loops) { int no_blocks=igraph_matrix_nrow(pref_matrix); int from, to, fromoff=0; igraph_real_t minp, maxp; igraph_vector_t edges; /* ------------------------------------------------------------ */ /* Check arguments */ /* ------------------------------------------------------------ */ if (igraph_matrix_ncol(pref_matrix) != no_blocks) { IGRAPH_ERROR("Preference matrix is not square", IGRAPH_NONSQUARE); } igraph_matrix_minmax(pref_matrix, &minp, &maxp); if (minp < 0 || maxp > 1) { IGRAPH_ERROR("Connection probabilities must in [0,1]", IGRAPH_EINVAL); } if (n < 0) { IGRAPH_ERROR("Number of vertices must be non-negative", IGRAPH_EINVAL); } if (!directed && !igraph_matrix_is_symmetric(pref_matrix)) { IGRAPH_ERROR("Preference matrix must be symmetric for undirected graphs", IGRAPH_EINVAL); } if (igraph_vector_int_size(block_sizes) != no_blocks) { IGRAPH_ERROR("Invalid block size vector length", IGRAPH_EINVAL); } if (igraph_vector_int_min(block_sizes) < 0) { IGRAPH_ERROR("Block size must be non-negative", IGRAPH_EINVAL); } if (igraph_vector_int_sum(block_sizes) != n) { IGRAPH_ERROR("Block sizes must sum up to number of vertices", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); RNG_BEGIN(); for (from = 0; from < no_blocks; from++) { double fromsize = VECTOR(*block_sizes)[from]; int start = directed ? 0 : from; int i, tooff=0; for (i=0; i 1) { IGRAPH_ERROR("`C' must be between zero and one for HSBM", IGRAPH_EINVAL); } if (fabs(igraph_vector_sum(rho) - 1.0) > sq_dbl_epsilon) { IGRAPH_ERROR("`rho' must sum up to 1 for HSBM", IGRAPH_EINVAL); } if (igraph_matrix_nrow(C) != k || igraph_matrix_ncol(C) != k) { IGRAPH_ERROR("`C' dimensions must match `rho' dimensions in HSBM", IGRAPH_EINVAL); } if (!igraph_matrix_is_symmetric(C)) { IGRAPH_ERROR("`C' must be a symmetric matrix", IGRAPH_EINVAL); } if (p < 0 || p > 1) { IGRAPH_ERROR("`p' must be a probability for HSBM", IGRAPH_EINVAL); } for (i=0; i sq_dbl_epsilon) { IGRAPH_ERROR("`rho' * `m' is not integer in HSBM", IGRAPH_EINVAL); } } IGRAPH_VECTOR_INIT_FINALLY(&csizes, k); for (i=0; i 0) { int fromoff=0, tooff=m; for (b=0; b 1) { IGRAPH_ERROR("`p' must be a probability for HSBM", IGRAPH_EINVAL); } /* Checks for m's */ if (igraph_vector_int_sum(mlist) != n) { IGRAPH_ERROR("`m' must sum up to `n' for HSBM", IGRAPH_EINVAL); } if (igraph_vector_int_min(mlist) < 1) { IGRAPH_ERROR("`m' must be positive for HSBM", IGRAPH_EINVAL); } /* Checks for the rhos */ for (i=0; i sq_dbl_epsilon) { IGRAPH_ERROR("`rho' must sum up to 1 for HSBM", IGRAPH_EINVAL); } } /* Checks for the Cs */ for (i=0; i 1) { IGRAPH_ERROR("`C' must be between zero and one for HSBM", IGRAPH_EINVAL); } if (!igraph_matrix_is_symmetric(C)) { IGRAPH_ERROR("`C' must be a symmetric matrix", IGRAPH_EINVAL); } } /* Check that C and rho sizes match */ for (i=0; i sq_dbl_epsilon) { IGRAPH_ERROR("`rho' * `m' is not integer in HSBM", IGRAPH_EINVAL); } } } IGRAPH_VECTOR_INIT_FINALLY(&csizes, 0); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); RNG_BEGIN(); /* Block models first */ for (b=0; b 0) { int fromoff=0, tooff=VECTOR(*mlist)[0]; for (b=0; b #include #include #include #include using namespace std; #include "drl_Node.h" #include "DensityGrid.h" #include "igraph_error.h" #define GET_BIN(y, x) (Bins[y*GRID_SIZE+x]) namespace drl { //******************************************************* // Density Grid Destructor -- deallocates memory used // for Density matrix, fall_off matrix, and node deque. DensityGrid::~DensityGrid () { delete[] Density; delete[] fall_off; delete[] Bins; } /********************************************* * Function: Density_Grid::Reset * * Description: Reset the density grid * *********************************************/ // changed from reset to init since we will only // call this once in the parallel version of layout void DensityGrid::Init() { Density = new float[GRID_SIZE][GRID_SIZE]; fall_off = new float[RADIUS*2+1][RADIUS*2+1]; Bins = new deque[GRID_SIZE*GRID_SIZE]; // Clear Grid int i; for (i=0; i< GRID_SIZE; i++) for (int j=0; j< GRID_SIZE; j++) { Density[i][j] = 0; GET_BIN(i, j).erase(GET_BIN(i, j).begin(), GET_BIN(i, j).end()); } // Compute fall off for(i=-RADIUS; i<=RADIUS; i++) for(int j=-RADIUS; j<=RADIUS; j++) { fall_off[i+RADIUS][j+RADIUS] = (float)((RADIUS-fabs((float)i))/RADIUS) * (float)((RADIUS-fabs((float)j))/RADIUS); } } /*************************************************** * Function: DensityGrid::GetDensity * * Description: Get_Density from density grid * **************************************************/ float DensityGrid::GetDensity(float Nx, float Ny, bool fineDensity) { deque::iterator BI; int x_grid, y_grid; float x_dist, y_dist, distance, density=0; int boundary=10; // boundary around plane /* Where to look */ x_grid = (int)((Nx+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((Ny+HALF_VIEW+.5)*VIEW_TO_GRID); // Check for edges of density grid (10000 is arbitrary high density) if (x_grid > GRID_SIZE-boundary || x_grid < boundary) return 10000; if (y_grid > GRID_SIZE-boundary || y_grid < boundary) return 10000; // Fine density? if (fineDensity) { // Go through nearest bins for(int i=y_grid-1; i<=y_grid+1; i++) for(int j=x_grid-1; j<=x_grid+1; j++) { // Look through bin and add fine repulsions for(BI = GET_BIN(i, j).begin(); BI != GET_BIN(i, j).end(); ++BI) { x_dist = Nx-(BI->x); y_dist = Ny-(BI->y); distance = x_dist*x_dist+y_dist*y_dist; density += 1e-4/(distance + 1e-50); } } // Course density } else { // Add rough estimate density = Density[y_grid][x_grid]; density *= density; } return density; } /// Wrapper functions for the Add and subtract methods /// Nodes should all be passed by constant ref void DensityGrid::Add(Node &n, bool fineDensity) { if(fineDensity) fineAdd(n); else Add(n); } void DensityGrid::Subtract( Node &n, bool first_add, bool fine_first_add, bool fineDensity) { if ( fineDensity && !fine_first_add ) fineSubtract (n); else if ( !first_add ) Subtract(n); } /*************************************************** * Function: DensityGrid::Subtract * * Description: Subtract a node from density grid * **************************************************/ void DensityGrid::Subtract(Node &N) { int x_grid, y_grid, diam; float *den_ptr, *fall_ptr; /* Where to subtract */ x_grid = (int)((N.sub_x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.sub_y+HALF_VIEW+.5)*VIEW_TO_GRID); x_grid -= RADIUS; y_grid -= RADIUS; diam = 2*RADIUS; // check to see that we are inside grid if ( (x_grid >= GRID_SIZE) || (x_grid < 0) || (y_grid >= GRID_SIZE) || (y_grid < 0) ) { #ifdef MUSE_MPI MPI_Abort ( MPI_COMM_WORLD, 1 ); #else igraph_error("Exceeded density grid in DrL", __FILE__, __LINE__, IGRAPH_EDRL); return; #endif } /* Subtract density values */ den_ptr = &Density[y_grid][x_grid]; fall_ptr = &fall_off[0][0]; for(int i = 0; i <= diam; i++) { for(int j = 0; j <= diam; j++) *den_ptr++ -= *fall_ptr++; den_ptr += GRID_SIZE - (diam+1); } } /*************************************************** * Function: DensityGrid::Add * * Description: Add a node to the density grid * **************************************************/ void DensityGrid::Add(Node &N) { int x_grid, y_grid, diam; float *den_ptr, *fall_ptr; /* Where to add */ x_grid = (int)((N.x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.y+HALF_VIEW+.5)*VIEW_TO_GRID); N.sub_x = N.x; N.sub_y = N.y; x_grid -= RADIUS; y_grid -= RADIUS; diam = 2*RADIUS; // check to see that we are inside grid if ( (x_grid >= GRID_SIZE) || (x_grid < 0) || (y_grid >= GRID_SIZE) || (y_grid < 0) ) { #ifdef MUSE_MPI MPI_Abort ( MPI_COMM_WORLD, 1 ); #else igraph_error("Exceeded density grid in DrL", __FILE__, __LINE__, IGRAPH_EDRL); return; #endif } /* Add density values */ den_ptr = &Density[y_grid][x_grid]; fall_ptr = &fall_off[0][0]; for(int i = 0; i <= diam; i++) { for(int j = 0; j <= diam; j++) *den_ptr++ += *fall_ptr++; den_ptr += GRID_SIZE - (diam+1); } } /*************************************************** * Function: DensityGrid::fineSubtract * * Description: Subtract a node from bins * **************************************************/ void DensityGrid::fineSubtract(Node &N) { int x_grid, y_grid; /* Where to subtract */ x_grid = (int)((N.sub_x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.sub_y+HALF_VIEW+.5)*VIEW_TO_GRID); GET_BIN(y_grid, x_grid).pop_front(); } /*************************************************** * Function: DensityGrid::fineAdd * * Description: Add a node to the bins * **************************************************/ void DensityGrid::fineAdd(Node &N) { int x_grid, y_grid; /* Where to add */ x_grid = (int)((N.x+HALF_VIEW+.5)*VIEW_TO_GRID); y_grid = (int)((N.y+HALF_VIEW+.5)*VIEW_TO_GRID); N.sub_x = N.x; N.sub_y = N.y; GET_BIN(y_grid, x_grid).push_back(N); } } // namespace drl igraph/src/mixing.c0000644000175100001440000002361013431000472013764 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_mixing.h" #include "igraph_interface.h" /** * \function igraph_assortativity_nominal * Assortativity of a graph based on vertex categories * * Assuming the vertices of the input graph belong to different * categories, this function calculates the assortativity coefficient of * the graph. The assortativity coefficient is between minus one and one * and it is one if all connections stay within categories, it is * minus one, if the network is perfectly disassortative. For a * randomly connected network it is (asymptotically) zero. * * See equation (2) in M. E. J. Newman: Mixing patterns * in networks, Phys. Rev. E 67, 026126 (2003) * (http://arxiv.org/abs/cond-mat/0209450) for the proper * definition. * * \param graph The input graph, it can be directed or undirected. * \param types Vector giving the vertex types. They are assumed to be * integer numbers, starting with zero. * \param res Pointer to a real variable, the result is stored here. * \param directed Boolean, it gives whether to consider edge * directions in a directed graph. It is ignored for undirected * graphs. * \return Error code. * * Time complexity: O(|E|+t), |E| is the number of edges, t is the * number of vertex types. * * \sa \ref igraph_assortativity if the vertex types are defines by * numeric values (e.g. vertex degree), instead of categories. * * \example examples/simple/assortativity.c */ int igraph_assortativity_nominal(const igraph_t *graph, const igraph_vector_t *types, igraph_real_t *res, igraph_bool_t directed) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); long int no_of_types; igraph_vector_t ai, bi, eii; long int e, i; igraph_real_t sumaibi=0.0, sumeii=0.0; if (igraph_vector_size(types) != no_of_nodes) { IGRAPH_ERROR("Invalid `types' vector length", IGRAPH_EINVAL); } if (igraph_vector_min(types) < 0) { IGRAPH_ERROR("Invalid `types' vector", IGRAPH_EINVAL); } directed = directed && igraph_is_directed(graph); no_of_types=(long int) igraph_vector_max(types)+1; IGRAPH_VECTOR_INIT_FINALLY(&ai, no_of_types); IGRAPH_VECTOR_INIT_FINALLY(&bi, no_of_types); IGRAPH_VECTOR_INIT_FINALLY(&eii, no_of_types); for (e=0; eSee equation (21) in M. E. J. Newman: Mixing patterns * in networks, Phys. Rev. E 67, 026126 (2003) * (http://arxiv.org/abs/cond-mat/0209450) for the proper * definition. The actual calculation is performed using equation (26) * in the same paper for directed graphs, and equation (4) in * M. E. J. Newman: Assortative mixing in networks, * Phys. Rev. Lett. 89, 208701 (2002) * (http://arxiv.org/abs/cond-mat/0205405/) for undirected graphs. * * \param graph The input graph, it can be directed or undirected. * \param types1 The vertex values, these can be arbitrary numeric * values. * \param types2 A second value vector to be using for the incoming * edges when calculating assortativity for a directed graph. * Supply a null pointer here if you want to use the same values * for outgoing and incoming edges. This argument is ignored * (with a warning) if it is not a null pointer and undirected * assortativity coefficient is being calculated. * \param res Pointer to a real variable, the result is stored here. * \param directed Boolean, whether to consider edge directions for * directed graphs. It is ignored for undirected graphs. * \return Error code. * * Time complexity: O(|E|), linear in the number of edges of the * graph. * * \sa \ref igraph_assortativity_nominal() if you have discrete vertex * categories instead of numeric labels, and \ref * igraph_assortativity_degree() for the special case of assortativity * based on vertex degree. * * \example examples/simple/assortativity.c */ int igraph_assortativity(const igraph_t *graph, const igraph_vector_t *types1, const igraph_vector_t *types2, igraph_real_t *res, igraph_bool_t directed) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); long int e; directed = directed && igraph_is_directed(graph); if (!directed && types2) { IGRAPH_WARNING("Only `types1' is used for undirected case"); } if (igraph_vector_size(types1) != no_of_nodes) { IGRAPH_ERROR("Invalid `types1' vector length", IGRAPH_EINVAL); } if (types2 && igraph_vector_size(types2) != no_of_nodes) { IGRAPH_ERROR("Invalid `types2' vector length", IGRAPH_EINVAL); } if (!directed) { igraph_real_t num1=0.0, num2=0.0, den1=0.0; for (e=0; e header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the libxml2 libraries installed */ #undef HAVE_LIBXML /* Define to 1 if you have the `log1p' function. */ #undef HAVE_LOG1P /* Define to 1 if you have the `log2' function. */ #undef HAVE_LOG2 /* Define to 1 if you have the `logbl' function. */ #undef HAVE_LOGBL /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_NETINET_IN_H /* Define to 1 if you have the header file. */ #undef HAVE_NET_IF_DL_H /* Define to 1 if you have the header file. */ #undef HAVE_NET_IF_H /* Define to 1 if you have the `rint' function. */ #undef HAVE_RINT /* Define to 1 if you have the `rintf' function. */ #undef HAVE_RINTF /* Define to 1 if you have the `round' function. */ #undef HAVE_ROUND /* Define if struct sockaddr contains sa_len */ #undef HAVE_SA_LEN /* Define to 1 if you have the `snprintf' function. */ #undef HAVE_SNPRINTF /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `stpcpy' function. */ #undef HAVE_STPCPY /* Define to 1 if the stpcpy function has a signature */ #undef HAVE_STPCPY_SIGNATURE /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_FILE_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKET_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKIO_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_UN_H /* Define to 1 if you have the sys/times.h header */ #undef HAVE_TIMES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* We don't care about thread-local storage in R */ #undef IGRAPH_THREAD_LOCAL /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS igraph/src/structural_properties.c0000644000175100001440000070316113431000472017163 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_structural.h" #include "igraph_transitivity.h" #include "igraph_paths.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_adjlist.h" #include "igraph_interface.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #include "igraph_centrality.h" #include "igraph_components.h" #include "igraph_constructors.h" #include "igraph_conversion.h" #include "igraph_types_internal.h" #include "igraph_dqueue.h" #include "igraph_attributes.h" #include "igraph_neighborhood.h" #include "igraph_topology.h" #include "igraph_qsort.h" #include "config.h" #include "structural_properties_internal.h" #include #include #include /** * \section about_structural * * These functions usually calculate some structural property * of a graph, like its diameter, the degree of the nodes, etc. */ /** * \ingroup structural * \function igraph_diameter * \brief Calculates the diameter of a graph (longest geodesic). * * \param graph The graph object. * \param pres Pointer to an integer, if not \c NULL then it will contain * the diameter (the actual distance). * \param pfrom Pointer to an integer, if not \c NULL it will be set to the * source vertex of the diameter path. * \param pto Pointer to an integer, if not \c NULL it will be set to the * target vertex of the diameter path. * \param path Pointer to an initialized vector. If not \c NULL the actual * longest geodesic path will be stored here. The vector will be * resized as needed. * \param directed Boolean, whether to consider directed * paths. Ignored for undirected graphs. * \param unconn What to do if the graph is not connected. If * \c TRUE the longest geodesic within a component * will be returned, otherwise the number of vertices is * returned. (The rationale behind the latter is that this is * always longer than the longest possible diameter in a * graph.) * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * * Time complexity: O(|V||E|), the * number of vertices times the number of edges. * * \example examples/simple/igraph_diameter.c */ int igraph_diameter(const igraph_t *graph, igraph_integer_t *pres, igraph_integer_t *pfrom, igraph_integer_t *pto, igraph_vector_t *path, igraph_bool_t directed, igraph_bool_t unconn) { long int no_of_nodes=igraph_vcount(graph); long int i, j, n; long int *already_added; long int nodes_reached; long int from=0, to=0; long int res=0; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; igraph_vector_int_t *neis; igraph_neimode_t dirmode; igraph_adjlist_t allneis; if (directed) { dirmode=IGRAPH_OUT; } else { dirmode=IGRAPH_ALL; } already_added=igraph_Calloc(no_of_nodes, long int); if (already_added==0) { IGRAPH_ERROR("diameter failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, already_added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, dirmode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); for (i=0; ires) { res=actdist; from=i; to=actnode; } neis=igraph_adjlist_get(&allneis, actnode); n=igraph_vector_int_size(neis); for (j=0; j 0) { *res /= normfact; } else { *res = IGRAPH_NAN; } /* clean */ igraph_Free(already_added); igraph_dqueue_destroy(&q); igraph_adjlist_destroy(&allneis); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \function igraph_path_length_hist * Create a histogram of all shortest path lengths. * * This function calculates a histogram, by calculating the * shortest path length between each pair of vertices. For directed * graphs both directions might be considered and then every pair of vertices * appears twice in the histogram. * \param graph The input graph. * \param res Pointer to an initialized vector, the result is stored * here. The first (i.e. zeroth) element contains the number of * shortest paths of length 1, etc. The supplied vector is resized * as needed. * \param unconnected Pointer to a real number, the number of * pairs for which the second vertex is not reachable from the * first is stored here. * \param directed Whether to consider directed paths in a directed * graph (if not zero). This argument is ignored for undirected * graphs. * \return Error code. * * Time complexity: O(|V||E|), the number of vertices times the number * of edges. * * \sa \ref igraph_average_path_length() and \ref igraph_shortest_paths() */ int igraph_path_length_hist(const igraph_t *graph, igraph_vector_t *res, igraph_real_t *unconnected, igraph_bool_t directed) { long int no_of_nodes=igraph_vcount(graph); long int i,j,n; igraph_vector_long_t already_added; long int nodes_reached; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; igraph_vector_int_t *neis; igraph_neimode_t dirmode; igraph_adjlist_t allneis; igraph_real_t unconn = 0; long int ressize; if (directed) { dirmode=IGRAPH_OUT; } else { dirmode=IGRAPH_ALL; } IGRAPH_CHECK(igraph_vector_long_init(&already_added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &already_added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_adjlist_init(graph, &allneis, dirmode)); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); IGRAPH_CHECK(igraph_vector_resize(res, 0)); ressize=0; for (i=0; i ressize) { IGRAPH_CHECK(igraph_vector_resize(res, actdist+1)); for (; ressize * If there is more than one geodesic between two vertices, this * function gives only one of them. * \param graph The graph object. * \param vertices The result, the ids of the vertices along the paths. * This is a pointer vector, each element points to a vector * object. These should be initialized before passing them to * the function, which will properly clear and/or resize them * and fill the ids of the vertices along the geodesics from/to * the vertices. Supply a null pointer here if you don't need * these vectors. * \param edges The result, the ids of the edges along the paths. * This is a pointer vector, each element points to a vector * object. These should be initialized before passing them to * the function, which will properly clear and/or resize them * and fill the ids of the vertices along the geodesics from/to * the vertices. Supply a null pointer here if you don't need * these vectors. * \param from The id of the vertex from/to which the geodesics are * calculated. * \param to Vertex sequence with the ids of the vertices to/from which the * shortest paths will be calculated. A vertex might be given multiple * times. * \param mode The type of shortest paths to be used for the * calculation in directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing paths are calculated. * \cli IGRAPH_IN * the incoming paths are calculated. * \cli IGRAPH_ALL * the directed graph is considered as an * undirected one for the computation. * \endclist * \param predecessors A pointer to an initialized igraph vector or null. * If not null, a vector containing the predecessor of each vertex in * the single source shortest path tree is returned here. The * predecessor of vertex i in the tree is the vertex from which vertex i * was reached. The predecessor of the start vertex (in the \c from * argument) is itself by definition. If the predecessor is -1, it means * that the given vertex was not reached from the source during the * search. Note that the search terminates if all the vertices in * \c to are reached. * \param inbound_edges A pointer to an initialized igraph vector or null. * If not null, a vector containing the inbound edge of each vertex in * the single source shortest path tree is returned here. The * inbound edge of vertex i in the tree is the edge via which vertex i * was reached. The start vertex and vertices that were not reached * during the search will have -1 in the corresponding entry of the * vector. Note that the search terminates if all the vertices in * \c to are reached. * * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * \p from is invalid vertex id, or the length of \p to is * not the same as the length of \p res. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|V|+|E|), * |V| is the number of vertices, * |E| the number of edges in the * graph. * * \sa \ref igraph_shortest_paths() if you only need the path length but * not the paths themselves. * * \example examples/simple/igraph_get_shortest_paths.c */ int igraph_get_shortest_paths(const igraph_t *graph, igraph_vector_ptr_t *vertices, igraph_vector_ptr_t *edges, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode, igraph_vector_long_t *predecessors, igraph_vector_long_t *inbound_edges) { /* TODO: use inclist_t if to is long (longer than 1?) */ long int no_of_nodes=igraph_vcount(graph); long int *father; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; long int i, j; igraph_vector_t tmp=IGRAPH_VECTOR_NULL; igraph_vit_t vit; long int to_reach; long int reached=0; if (from<0 || from>=no_of_nodes) { IGRAPH_ERROR("cannot get shortest paths", IGRAPH_EINVVID); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("Invalid mode argument", IGRAPH_EINVMODE); } IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); if (vertices && IGRAPH_VIT_SIZE(vit) != igraph_vector_ptr_size(vertices)) { IGRAPH_ERROR("Size of the `vertices' and the `to' should match", IGRAPH_EINVAL); } if (edges && IGRAPH_VIT_SIZE(vit) != igraph_vector_ptr_size(edges)) { IGRAPH_ERROR("Size of the `edges' and the `to' should match", IGRAPH_EINVAL); } father=igraph_Calloc(no_of_nodes, long int); if (father==0) { IGRAPH_ERROR("cannot get shortest paths", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, father); IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); /* Mark the vertices we need to reach */ to_reach=IGRAPH_VIT_SIZE(vit); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { if (father[ (long int) IGRAPH_VIT_GET(vit) ] == 0) { father[ (long int) IGRAPH_VIT_GET(vit) ] = -1; } else { to_reach--; /* this node was given multiple times */ } } /* Meaning of father[i]: * * - If father[i] < 0, it means that vertex i has to be reached and has not * been reached yet. * * - If father[i] = 0, it means that vertex i does not have to be reached and * it has not been reached yet. * * - If father[i] = 1, it means that vertex i is the start vertex. * * - Otherwise, father[i] is the ID of the edge from which vertex i was * reached plus 2. */ IGRAPH_CHECK(igraph_dqueue_push(&q, from+1)); if (father[ (long int) from ] < 0) { reached++; } father[ (long int)from ] = 1; while (!igraph_dqueue_empty(&q) && reached < to_reach) { long int act=(long int) igraph_dqueue_pop(&q)-1; IGRAPH_CHECK(igraph_incident(graph, &tmp, (igraph_integer_t) act, mode)); for (j=0; j 0) { continue; } else if (father[neighbor] < 0) { reached++; } father[neighbor] = edge+2; IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor+1)); } } if (reached < to_reach) { IGRAPH_WARNING("Couldn't reach some vertices"); } /* Create `predecessors' if needed */ if (predecessors) { IGRAPH_CHECK(igraph_vector_long_resize(predecessors, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { if (father[i] <= 0) { /* i was not reached */ VECTOR(*predecessors)[i] = -1; } else if (father[i] == 1) { /* i is the start vertex */ VECTOR(*predecessors)[i] = i; } else { /* i was reached via the edge with ID = father[i] - 2 */ VECTOR(*predecessors)[i] = IGRAPH_OTHER(graph, father[i]-2, i); } } } /* Create `inbound_edges' if needed */ if (inbound_edges) { IGRAPH_CHECK(igraph_vector_long_resize(inbound_edges, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { if (father[i] <= 1) { /* i was not reached or i is the start vertex */ VECTOR(*inbound_edges)[i] = -1; } else { /* i was reached via the edge with ID = father[i] - 2 */ VECTOR(*inbound_edges)[i] = father[i]-2; } } } /* Create `vertices' and `edges' if needed */ if (vertices || edges) { for (IGRAPH_VIT_RESET(vit), j=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), j++) { long int node=IGRAPH_VIT_GET(vit); igraph_vector_t *vvec=0, *evec=0; if (vertices) { vvec=VECTOR(*vertices)[j]; igraph_vector_clear(vvec); } if (edges) { evec=VECTOR(*edges)[j]; igraph_vector_clear(evec); } IGRAPH_ALLOW_INTERRUPTION(); if (father[node]>0) { long int act=node; long int size=0; long int edge; while (father[act]>1) { size++; edge=father[act]-2; act=IGRAPH_OTHER(graph, edge, act); } if (vvec) { IGRAPH_CHECK(igraph_vector_resize(vvec, size+1)); VECTOR(*vvec)[size]=node; } if (evec) { IGRAPH_CHECK(igraph_vector_resize(evec, size)); } act=node; while (father[act]>1) { size--; edge=father[act]-2; act=IGRAPH_OTHER(graph, edge, act); if (vvec) { VECTOR(*vvec)[size]=act; } if (evec) { VECTOR(*evec)[size]=edge; } } } } } /* Clean */ igraph_Free(father); igraph_dqueue_destroy(&q); igraph_vector_destroy(&tmp); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(4); return 0; } /** * \function igraph_get_shortest_path * Shortest path from one vertex to another one. * * Calculates and returns a single unweighted shortest path from a * given vertex to another one. If there are more than one shortest * paths between the two vertices, then an arbitrary one is returned. * * This function is a wrapper to \ref * igraph_get_shortest_paths(), for the special case when only one * target vertex is considered. * \param graph The input graph, it can be directed or * undirected. Directed paths are considered in directed * graphs. * \param vertices Pointer to an initialized vector or a null * pointer. If not a null pointer, then the vertex ids along * the path are stored here, including the source and target * vertices. * \param edges Pointer to an uninitialized vector or a null * pointer. If not a null pointer, then the edge ids along the * path are stored here. * \param from The id of the source vertex. * \param to The id of the target vertex. * \param mode A constant specifying how edge directions are * considered in directed graphs. Valid modes are: * \c IGRAPH_OUT, follows edge directions; * \c IGRAPH_IN, follows the opposite directions; and * \c IGRAPH_ALL, ignores edge directions. This argument is * ignored for undirected graphs. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges in the graph. * * \sa \ref igraph_get_shortest_paths() for the version with more target * vertices. */ int igraph_get_shortest_path(const igraph_t *graph, igraph_vector_t *vertices, igraph_vector_t *edges, igraph_integer_t from, igraph_integer_t to, igraph_neimode_t mode) { igraph_vector_ptr_t vertices2, *vp=&vertices2; igraph_vector_ptr_t edges2, *ep=&edges2; if (vertices) { IGRAPH_CHECK(igraph_vector_ptr_init(&vertices2, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vertices2); VECTOR(vertices2)[0]=vertices; } else { vp=0; } if (edges) { IGRAPH_CHECK(igraph_vector_ptr_init(&edges2, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &edges2); VECTOR(edges2)[0]=edges; } else { ep=0; } IGRAPH_CHECK(igraph_get_shortest_paths(graph, vp, ep, from, igraph_vss_1(to), mode, 0, 0)); if (edges) { igraph_vector_ptr_destroy(&edges2); IGRAPH_FINALLY_CLEAN(1); } if (vertices) { igraph_vector_ptr_destroy(&vertices2); IGRAPH_FINALLY_CLEAN(1); } return 0; } void igraph_i_gasp_paths_destroy(igraph_vector_ptr_t *v); void igraph_i_gasp_paths_destroy(igraph_vector_ptr_t *v) { long int i; for (i=0; i * * Time complexity: O(|V|+|E|) for most graphs, O(|V|^2) in the worst * case. */ int igraph_get_all_shortest_paths(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vector_t *nrgeo, igraph_integer_t from, const igraph_vs_t to, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); long int *geodist; igraph_vector_ptr_t paths; igraph_dqueue_t q; igraph_vector_t *vptr; igraph_vector_t neis; igraph_vector_t ptrlist; igraph_vector_t ptrhead; long int n, j, i; long int to_reach, reached=0, maxdist=0; igraph_vit_t vit; if (from<0 || from>=no_of_nodes) { IGRAPH_ERROR("cannot get shortest paths", IGRAPH_EINVVID); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("Invalid mode argument", IGRAPH_EINVMODE); } IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); /* paths will store the shortest paths during the search */ IGRAPH_CHECK(igraph_vector_ptr_init(&paths, 0)); IGRAPH_FINALLY(igraph_i_gasp_paths_destroy, &paths); /* neis is a temporary vector holding the neighbors of the * node being examined */ IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); /* ptrlist stores indices into the paths vector, in the order * of how they were found. ptrhead is a second-level index that * will be used to find paths that terminate in a given vertex */ IGRAPH_VECTOR_INIT_FINALLY(&ptrlist, 0); /* ptrhead contains indices into ptrlist. * ptrhead[i] = j means that element #j-1 in ptrlist contains * the shortest path from the root to node i. ptrhead[i] = 0 * means that node i was not reached so far */ IGRAPH_VECTOR_INIT_FINALLY(&ptrhead, no_of_nodes); /* geodist[i] == 0 if i was not reached yet and it is not in the * target vertex sequence, or -1 if i was not reached yet and it * is in the target vertex sequence. Otherwise it is * one larger than the length of the shortest path from the * source */ geodist=igraph_Calloc(no_of_nodes, long int); if (geodist==0) { IGRAPH_ERROR("Cannot calculate shortest paths", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, geodist); /* dequeue to store the BFS queue -- odd elements are the vertex indices, * even elements are the distances from the root */ IGRAPH_CHECK(igraph_dqueue_init(&q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &q); if (nrgeo) { IGRAPH_CHECK(igraph_vector_resize(nrgeo, no_of_nodes)); igraph_vector_null(nrgeo); } /* use geodist to count how many vertices we have to reach */ to_reach=IGRAPH_VIT_SIZE(vit); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { if (geodist[ (long int) IGRAPH_VIT_GET(vit) ] == 0) { geodist[ (long int) IGRAPH_VIT_GET(vit) ] = -1; } else { to_reach--; /* this node was given multiple times */ } } if (geodist[ (long int) from ] < 0) { reached++; } /* from -> from */ vptr=igraph_Calloc(1, igraph_vector_t); /* TODO: dirty */ IGRAPH_CHECK(igraph_vector_ptr_push_back(&paths, vptr)); IGRAPH_CHECK(igraph_vector_init(vptr, 1)); VECTOR(*vptr)[0]=from; geodist[(long int)from]=1; VECTOR(ptrhead)[(long int)from]=1; IGRAPH_CHECK(igraph_vector_push_back(&ptrlist, 0)); if (nrgeo) { VECTOR(*nrgeo)[(long int)from]=1; } /* Init queue */ IGRAPH_CHECK(igraph_dqueue_push(&q, from)); IGRAPH_CHECK(igraph_dqueue_push(&q, 0.0)); while (!igraph_dqueue_empty(&q)) { long int actnode=(long int) igraph_dqueue_pop(&q); long int actdist=(long int) igraph_dqueue_pop(&q); IGRAPH_ALLOW_INTERRUPTION(); if (reached >= to_reach) { /* all nodes were reached. Since we need all the shortest paths * to all these nodes, we can stop the search only if the distance * of the current node to the root is larger than the distance of * any of the nodes we wanted to reach */ if (actdist > maxdist) { /* safety check, maxdist should have been set when we reached the last node */ if (maxdist < 0) { IGRAPH_ERROR("possible bug in igraph_get_all_shortest_paths, " "maxdist is negative", IGRAPH_EINVAL); } break; } } IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) actnode, mode)); n=igraph_vector_size(&neis); for (j=0; j 0 && geodist[neighbor]-1 < actdist+1) { /* this node was reached via a shorter path before */ continue; } /* yay, found another shortest path to neighbor */ if (nrgeo) { /* the number of geodesics leading to neighbor must be * increased by the number of geodesics leading to actnode */ VECTOR(*nrgeo)[neighbor] += VECTOR(*nrgeo)[actnode]; } if (geodist[neighbor] <= 0) { /* this node was not reached yet, push it into the queue */ IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor)); IGRAPH_CHECK(igraph_dqueue_push(&q, actdist+1)); if (geodist[neighbor] < 0) { reached++; } if (reached == to_reach) maxdist = actdist; } geodist[neighbor]=actdist+2; /* copy all existing paths to the parent */ fatherptr = (long int) VECTOR(ptrhead)[actnode]; while (fatherptr != 0) { /* allocate a new igraph_vector_t at the end of paths */ vptr=igraph_Calloc(1, igraph_vector_t); IGRAPH_CHECK(igraph_vector_ptr_push_back(&paths, vptr)); IGRAPH_CHECK(igraph_vector_copy(vptr, VECTOR(paths)[fatherptr-1])); IGRAPH_CHECK(igraph_vector_reserve(vptr, actdist+2)); IGRAPH_CHECK(igraph_vector_push_back(vptr, neighbor)); IGRAPH_CHECK(igraph_vector_push_back(&ptrlist, VECTOR(ptrhead)[neighbor])); VECTOR(ptrhead)[neighbor]=igraph_vector_size(&ptrlist); fatherptr=(long int) VECTOR(ptrlist)[fatherptr-1]; } } } igraph_dqueue_destroy(&q); IGRAPH_FINALLY_CLEAN(1); /* mark the nodes for which we need the result */ memset(geodist, 0, sizeof(long int) * (size_t) no_of_nodes); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { geodist[ (long int) IGRAPH_VIT_GET(vit) ] = 1; } /* count the number of paths in the result */ n=0; for (i=0; i 0) { while (fatherptr != 0) { n++; fatherptr=(long int) VECTOR(ptrlist)[fatherptr-1]; } } } IGRAPH_CHECK(igraph_vector_ptr_resize(res, n)); j=0; for (i=0; i 0) { /* yes, copy them to the result vector */ while (fatherptr != 0) { VECTOR(*res)[j++]=VECTOR(paths)[fatherptr-1]; fatherptr=(long int) VECTOR(ptrlist)[fatherptr-1]; } } else { /* no, free them */ while (fatherptr != 0) { igraph_vector_destroy(VECTOR(paths)[fatherptr-1]); igraph_Free(VECTOR(paths)[fatherptr-1]); fatherptr=(long int) VECTOR(ptrlist)[fatherptr-1]; } } } igraph_Free(geodist); igraph_vector_destroy(&ptrlist); igraph_vector_destroy(&ptrhead); igraph_vector_destroy(&neis); igraph_vector_ptr_destroy(&paths); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(6); return 0; } /** * \ingroup structural * \function igraph_subcomponent * \brief The vertices in the same component as a given vertex. * * \param graph The graph object. * \param res The result, vector with the ids of the vertices in the * same component. * \param vertex The id of the vertex of which the component is * searched. * \param mode Type of the component for directed graphs, possible * values: * \clist * \cli IGRAPH_OUT * the set of vertices reachable \em from the * \p vertex, * \cli IGRAPH_IN * the set of vertices from which the * \p vertex is reachable. * \cli IGRAPH_ALL * the graph is considered as an * undirected graph. Note that this is \em not the same * as the union of the previous two. * \endclist * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * \p vertex is an invalid vertex id * \cli IGRAPH_EINVMODE * invalid mode argument passed. * \endclist * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the graph. * * \sa \ref igraph_subgraph() if you want a graph object consisting only * a given set of vertices and the edges between them. */ int igraph_subcomponent(const igraph_t *graph, igraph_vector_t *res, igraph_real_t vertex, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; char *already_added; long int i; igraph_vector_t tmp=IGRAPH_VECTOR_NULL; if (!IGRAPH_FINITE(vertex) || vertex<0 || vertex>=no_of_nodes) { IGRAPH_ERROR("subcomponent failed", IGRAPH_EINVVID); } if (mode != IGRAPH_OUT && mode != IGRAPH_IN && mode != IGRAPH_ALL) { IGRAPH_ERROR("invalid mode argument", IGRAPH_EINVMODE); } already_added=igraph_Calloc(no_of_nodes, char); if (already_added==0) { IGRAPH_ERROR("subcomponent failed",IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, already_added); /* TODO: hack */ igraph_vector_clear(res); IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_dqueue_push(&q, vertex)); IGRAPH_CHECK(igraph_vector_push_back(res, vertex)); already_added[(long int)vertex]=1; while (!igraph_dqueue_empty(&q)) { long int actnode=(long int) igraph_dqueue_pop(&q); IGRAPH_ALLOW_INTERRUPTION(); IGRAPH_CHECK(igraph_neighbors(graph, &tmp, (igraph_integer_t) actnode, mode)); for (i=0; iThis is an old implementation, * it is provided for compatibility with igraph versions earlier than * 0.5. Please use the new implementation \ref igraph_pagerank() in * new projects. * * * From version 0.7 this function is deprecated and its use gives a * warning message. * * * Please note that the PageRank of a given vertex depends on the PageRank * of all other vertices, so even if you want to calculate the PageRank for * only some of the vertices, all of them must be calculated. Requesting * the PageRank for only some of the vertices does not result in any * performance increase at all. * * * Since the calculation is an iterative * process, the algorithm is stopped after a given count of iterations * or if the PageRank value differences between iterations are less than * a predefined value. * * * * For the explanation of the PageRank algorithm, see the following * webpage: * http://infolab.stanford.edu/~backrub/google.html , or the * following reference: * * * * Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual * Web Search Engine. Proceedings of the 7th World-Wide Web Conference, * Brisbane, Australia, April 1998. * * * \param graph The graph object. * \param res The result vector containing the PageRank values for the * given nodes. * \param vids Vector with the vertex ids * \param directed Logical, if true directed paths will be considered * for directed graphs. It is ignored for undirected graphs. * \param niter The maximum number of iterations to perform * \param eps The algorithm will consider the calculation as complete * if the difference of PageRank values between iterations change * less than this value for every node * \param damping The damping factor ("d" in the original paper) * \param old Boolean, whether to use the pre-igraph 0.5 way to * calculate page rank. Not recommended for new applications, * only included for compatibility. If this is non-zero then the damping * factor is not divided by the number of vertices before adding it * to the weighted page rank scores to calculate the * new scores. I.e. the formula in the original PageRank paper * is used. Furthermore, if this is non-zero then the PageRank * vector is renormalized after each iteration. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids. * * Time complexity: O(|V|+|E|) per iteration. A handful iterations * should be enough. Note that if the old-style dumping is used then * the iteration might not converge at all. * * \sa \ref igraph_pagerank() for the new implementation. */ int igraph_pagerank_old(const igraph_t *graph, igraph_vector_t *res, const igraph_vs_t vids, igraph_bool_t directed, igraph_integer_t niter, igraph_real_t eps, igraph_real_t damping, igraph_bool_t old) { long int no_of_nodes=igraph_vcount(graph); long int i, j, n, nodes_to_calc; igraph_real_t *prvec, *prvec_new, *prvec_aux, *prvec_scaled; igraph_vector_int_t *neis; igraph_vector_t outdegree; igraph_neimode_t dirmode; igraph_adjlist_t allneis; igraph_real_t maxdiff=eps; igraph_vit_t vit; IGRAPH_WARNING("igraph_pagerank_old is deprecated from igraph 0.7, " "use igraph_pagerank instead"); if (niter<=0) IGRAPH_ERROR("Invalid iteration count", IGRAPH_EINVAL); if (eps<=0) IGRAPH_ERROR("Invalid epsilon value", IGRAPH_EINVAL); if (damping<=0 || damping>=1) IGRAPH_ERROR("Invalid damping factor", IGRAPH_EINVAL); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); IGRAPH_CHECK(igraph_vector_resize(res, nodes_to_calc)); igraph_vector_null(res); IGRAPH_VECTOR_INIT_FINALLY(&outdegree, no_of_nodes); prvec=igraph_Calloc(no_of_nodes, igraph_real_t); if (prvec==0) { IGRAPH_ERROR("pagerank failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, prvec); prvec_new=igraph_Calloc(no_of_nodes, igraph_real_t); if (prvec_new==0) { IGRAPH_ERROR("pagerank failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, prvec_new); prvec_scaled=igraph_Calloc(no_of_nodes, igraph_real_t); if (prvec_scaled==0) { IGRAPH_ERROR("pagerank failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, prvec_scaled); if (directed) { dirmode=IGRAPH_IN; } else { dirmode=IGRAPH_ALL; } igraph_adjlist_init(graph, &allneis, dirmode); IGRAPH_FINALLY(igraph_adjlist_destroy, &allneis); /* Calculate outdegrees for every node */ igraph_degree(graph, &outdegree, igraph_vss_all(), directed?IGRAPH_OUT:IGRAPH_ALL, 0); /* Initialize PageRank values */ for (i=0; i0 && maxdiff >= eps) { igraph_real_t sumfrom=0, sum=0; niter--; maxdiff=0; /* Calculate the quotient of the actual PageRank value and the * outdegree for every node */ sumfrom=0.0; sum=0.0; for (i=0; imaxdiff) maxdiff=prvec_new[i]-prvec[i]; else if (prvec[i]-prvec_new[i]>maxdiff) maxdiff=prvec[i]-prvec_new[i]; } /* Swap the vectors */ prvec_aux=prvec_new; prvec_new=prvec; prvec=prvec_aux; } /* Copy results from prvec to res */ for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int vid=IGRAPH_VIT_GET(vit); VECTOR(*res)[i]=prvec[vid]; } igraph_adjlist_destroy(&allneis); igraph_vit_destroy(&vit); igraph_vector_destroy(&outdegree); igraph_Free(prvec); igraph_Free(prvec_new); igraph_Free(prvec_scaled); IGRAPH_FINALLY_CLEAN(6); return 0; } // Not declared static so that the testsuite can use it, but not part of the public API. int igraph_rewire_core(igraph_t *graph, igraph_integer_t n, igraph_rewiring_t mode, igraph_bool_t use_adjlist) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); char message[256]; igraph_integer_t a, b, c, d, dummy, num_swaps, num_successful_swaps; igraph_vector_t eids, edgevec, alledges; igraph_bool_t directed, loops, ok; igraph_es_t es; igraph_adjlist_t al; if (no_of_nodes<4) IGRAPH_ERROR("graph unsuitable for rewiring", IGRAPH_EINVAL); directed = igraph_is_directed(graph); loops = (mode & IGRAPH_REWIRING_SIMPLE_LOOPS); RNG_BEGIN(); IGRAPH_VECTOR_INIT_FINALLY(&eids, 2); if(use_adjlist) { /* As well as the sorted adjacency list, we maintain an unordered * list of edges for picking a random edge in constant time. */ IGRAPH_CHECK(igraph_adjlist_init(graph, &al, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_adjlist_destroy, &al); IGRAPH_VECTOR_INIT_FINALLY(&alledges, no_of_edges * 2); igraph_get_edgelist(graph, &alledges, /*bycol=*/ 0); } else { IGRAPH_VECTOR_INIT_FINALLY(&edgevec, 4); es = igraph_ess_vector(&eids); } /* We don't want the algorithm to get stuck in an infinite loop when * it can't choose two edges satisfying the conditions. Instead of * this, we choose two arbitrary edges and if they have endpoints * in common, we just decrease the number of trials left and continue * (so unsuccessful rewirings still count as a trial) */ num_swaps = num_successful_swaps = 0; while (num_swaps < n) { IGRAPH_ALLOW_INTERRUPTION(); if (num_swaps % 1000 == 0) { snprintf(message, sizeof(message), "Random rewiring (%.2f%% of the trials were successful)", num_swaps > 0 ? ((100.0 * num_successful_swaps) / num_swaps) : 0.0); IGRAPH_PROGRESS(message, (100.0 * num_swaps) / n, 0); } switch (mode) { case IGRAPH_REWIRING_SIMPLE: case IGRAPH_REWIRING_SIMPLE_LOOPS: ok = 1; /* Choose two edges randomly */ VECTOR(eids)[0]=RNG_INTEGER(0, no_of_edges-1); do { VECTOR(eids)[1]=RNG_INTEGER(0, no_of_edges-1); } while (VECTOR(eids)[0] == VECTOR(eids)[1]); /* Get the endpoints */ if(use_adjlist) { a = VECTOR(alledges)[((igraph_integer_t)VECTOR(eids)[0]) * 2]; b = VECTOR(alledges)[(((igraph_integer_t)VECTOR(eids)[0]) * 2) + 1]; c = VECTOR(alledges)[((igraph_integer_t)VECTOR(eids)[1]) * 2]; d = VECTOR(alledges)[(((igraph_integer_t)VECTOR(eids)[1]) * 2) + 1]; } else { IGRAPH_CHECK(igraph_edge(graph, (igraph_integer_t) VECTOR(eids)[0], &a, &b)); IGRAPH_CHECK(igraph_edge(graph, (igraph_integer_t) VECTOR(eids)[1], &c, &d)); } /* For an undirected graph, we have two "variants" of each edge, i.e. * a -- b and b -- a. Since some rewirings can be performed only when we * "swap" the endpoints, we do it now with probability 0.5 */ if (!directed && RNG_UNIF01() < 0.5) { dummy = c; c = d; d = dummy; if(use_adjlist) { /* Flip the edge in the unordered edge-list, so the update later on * hits the correct end. */ VECTOR(alledges)[((igraph_integer_t)VECTOR(eids)[1]) * 2] = c; VECTOR(alledges)[(((igraph_integer_t)VECTOR(eids)[1]) * 2) + 1] = d; } } /* If we do not touch loops, check whether a == b or c == d and disallow * the swap if needed */ if (!loops && (a == b || c == d)) { ok = 0; } else { /* Check whether they are suitable for rewiring */ if (a == c || b == d) { /* Swapping would have no effect */ ok = 0; } else { /* a != c && b != d */ /* If a == d or b == c, the swap would generate at least one loop, so * we disallow them unless we want to have loops */ ok = loops || (a != d && b != c); /* Also, if a == b and c == d and we allow loops, doing the swap * would result in a multiple edge if the graph is undirected */ ok = ok && (directed || a != b || c != d); } } /* All good so far. Now check for the existence of a --> d and c --> b to * disallow the creation of multiple edges */ if (ok) { if(use_adjlist) { if(igraph_adjlist_has_edge(&al, a, d, directed)) ok = 0; } else { IGRAPH_CHECK(igraph_are_connected(graph, a, d, &ok)); ok = !ok; } } if (ok) { if(use_adjlist) { if(igraph_adjlist_has_edge(&al, c, b, directed)) ok = 0; } else { IGRAPH_CHECK(igraph_are_connected(graph, c, b, &ok)); ok = !ok; } } /* If we are still okay, we can perform the rewiring */ if (ok) { /* printf("Deleting: %ld -> %ld, %ld -> %ld\n", (long)a, (long)b, (long)c, (long)d); */ if(use_adjlist) { // Replace entry in sorted adjlist: IGRAPH_CHECK(igraph_adjlist_replace_edge(&al, a, b, d, directed)); IGRAPH_CHECK(igraph_adjlist_replace_edge(&al, c, d, b, directed)); // Also replace in unsorted edgelist: VECTOR(alledges)[(((igraph_integer_t)VECTOR(eids)[0]) * 2) + 1] = d; VECTOR(alledges)[(((igraph_integer_t)VECTOR(eids)[1]) * 2) + 1] = b; } else { IGRAPH_CHECK(igraph_delete_edges(graph, es)); VECTOR(edgevec)[0]=a; VECTOR(edgevec)[1]=d; VECTOR(edgevec)[2]=c; VECTOR(edgevec)[3]=b; /* printf("Adding: %ld -> %ld, %ld -> %ld\n", (long)a, (long)d, (long)c, (long)b); */ igraph_add_edges(graph, &edgevec, 0); } num_successful_swaps++; } break; default: RNG_END(); IGRAPH_ERROR("unknown rewiring mode", IGRAPH_EINVMODE); } num_swaps++; } if(use_adjlist) { /* Replace graph edges with the adjlist current state */ IGRAPH_CHECK(igraph_delete_edges(graph, igraph_ess_all(IGRAPH_EDGEORDER_ID))); IGRAPH_CHECK(igraph_add_edges(graph, &alledges, 0)); } IGRAPH_PROGRESS("Random rewiring: ", 100.0, 0); if(use_adjlist) { igraph_vector_destroy(&alledges); igraph_adjlist_destroy(&al); } else { igraph_vector_destroy(&edgevec); } igraph_vector_destroy(&eids); IGRAPH_FINALLY_CLEAN(use_adjlist ? 3 : 2); RNG_END(); return 0; } /** * \ingroup structural * \function igraph_rewire * \brief Randomly rewires a graph while preserving the degree distribution. * * * This function generates a new graph based on the original one by randomly * rewiring edges while preserving the original graph's degree distribution. * Please note that the rewiring is done "in place", so no new graph will * be allocated. If you would like to keep the original graph intact, use * \ref igraph_copy() beforehand. * * \param graph The graph object to be rewired. * \param n Number of rewiring trials to perform. * \param mode The rewiring algorithm to be used. It can be one of the following flags: * \clist * \cli IGRAPH_REWIRING_SIMPLE * Simple rewiring algorithm which chooses two arbitrary edges * in each step (namely (a,b) and (c,d)) and substitutes them * with (a,d) and (c,b) if they don't exist. The method will * neither destroy nor create self-loops. * \cli IGRAPH_REWIRING_SIMPLE_LOOPS * Same as \c IGRAPH_REWIRING_SIMPLE but allows the creation or * destruction of self-loops. * \endclist * * \return Error code: * \clist * \cli IGRAPH_EINVMODE * Invalid rewiring mode. * \cli IGRAPH_EINVAL * Graph unsuitable for rewiring (e.g. it has * less than 4 nodes in case of \c IGRAPH_REWIRING_SIMPLE) * \cli IGRAPH_ENOMEM * Not enough memory for temporary data. * \endclist * * Time complexity: TODO. * * \example examples/simple/igraph_rewire.c */ #define REWIRE_ADJLIST_THRESHOLD 10 int igraph_rewire(igraph_t *graph, igraph_integer_t n, igraph_rewiring_t mode) { igraph_bool_t use_adjlist = n >= REWIRE_ADJLIST_THRESHOLD; return igraph_rewire_core(graph, n, mode, use_adjlist); } /** * Subgraph creation, old version: it copies the graph and then deletes * unneeded vertices. */ int igraph_i_subgraph_copy_and_delete(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_vector_t *map, igraph_vector_t *invmap) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t delete=IGRAPH_VECTOR_NULL; char *remain; long int i; igraph_vit_t vit; IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_VECTOR_INIT_FINALLY(&delete, 0); remain=igraph_Calloc(no_of_nodes, char); if (remain==0) { IGRAPH_ERROR("subgraph failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, remain); /* TODO: hack */ IGRAPH_CHECK(igraph_vector_reserve(&delete, no_of_nodes-IGRAPH_VIT_SIZE(vit))); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { remain[ (long int) IGRAPH_VIT_GET(vit) ] = 1; } for (i=0; iattr to 0 before calling igraph_copy */ res->attr=0; /* Why is this needed? TODO */ IGRAPH_CHECK(igraph_copy(res, graph)); IGRAPH_FINALLY(igraph_destroy, res); IGRAPH_CHECK(igraph_delete_vertices_idx(res, igraph_vss_vector(&delete), map, invmap)); igraph_vector_destroy(&delete); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * Subgraph creation, new version: creates the new graph instead of * copying the old one. */ int igraph_i_subgraph_create_from_scratch(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_vector_t *map, igraph_vector_t *invmap) { igraph_bool_t directed = igraph_is_directed(graph); long int no_of_nodes = igraph_vcount(graph); long int no_of_new_nodes = 0; long int i, j, n; long int to; igraph_integer_t eid; igraph_vector_t vids_old2new, vids_new2old; igraph_vector_t eids_new2old; igraph_vector_t nei_edges; igraph_vector_t new_edges; igraph_vit_t vit; igraph_vector_t *my_vids_old2new=&vids_old2new, *my_vids_new2old=&vids_new2old; /* The order of initialization is important here, they will be destroyed in the * opposite order */ IGRAPH_VECTOR_INIT_FINALLY(&eids_new2old, 0); if (invmap) { my_vids_new2old = invmap; igraph_vector_clear(my_vids_new2old); } else { IGRAPH_VECTOR_INIT_FINALLY(&vids_new2old, 0); } IGRAPH_VECTOR_INIT_FINALLY(&new_edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&nei_edges, 0); if (map) { my_vids_old2new = map; IGRAPH_CHECK(igraph_vector_resize(map, no_of_nodes)); igraph_vector_null(map); } else { IGRAPH_VECTOR_INIT_FINALLY(&vids_old2new, no_of_nodes); } IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); /* Calculate the mapping from the old node IDs to the new ones. The other * igraph_simplify implementation in igraph_i_simplify_copy_and_delete * ensures that the order of vertex IDs is kept during remapping (i.e. * if the old ID of vertex A is less than the old ID of vertex B, then * the same will also be true for the new IDs). To ensure compatibility * with the other implementation, we have to fetch the vertex IDs into * a vector first and then sort it. We temporarily use new_edges for that. */ IGRAPH_CHECK(igraph_vit_as_vector(&vit, &nei_edges)); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); igraph_vector_sort(&nei_edges); n = igraph_vector_size(&nei_edges); for (i = 0; i < n; i++) { long int vid = (long int) VECTOR(nei_edges)[i]; if (VECTOR(*my_vids_old2new)[vid] == 0) { IGRAPH_CHECK(igraph_vector_push_back(my_vids_new2old, vid)); no_of_new_nodes++; VECTOR(*my_vids_old2new)[vid] = no_of_new_nodes; } } /* Create the new edge list */ for (i = 0; i < no_of_new_nodes; i++) { long int old_vid = (long int) VECTOR(*my_vids_new2old)[i]; long int new_vid = i; IGRAPH_CHECK(igraph_incident(graph, &nei_edges, old_vid, IGRAPH_OUT)); n = igraph_vector_size(&nei_edges); if (directed) { for (j = 0; j < n; j++) { eid = (igraph_integer_t) VECTOR(nei_edges)[j]; to = (long int) VECTOR(*my_vids_old2new)[ (long int)IGRAPH_TO(graph, eid) ]; if (!to) continue; IGRAPH_CHECK(igraph_vector_push_back(&new_edges, new_vid)); IGRAPH_CHECK(igraph_vector_push_back(&new_edges, to-1)); IGRAPH_CHECK(igraph_vector_push_back(&eids_new2old, eid)); } } else { for (j = 0; j < n; j++) { eid = (igraph_integer_t) VECTOR(nei_edges)[j]; if (IGRAPH_FROM(graph, eid) != old_vid) /* avoid processing edges twice */ continue; to = (long int) VECTOR(*my_vids_old2new)[ (long int)IGRAPH_TO(graph, eid) ]; if (!to) continue; IGRAPH_CHECK(igraph_vector_push_back(&new_edges, new_vid)); IGRAPH_CHECK(igraph_vector_push_back(&new_edges, to-1)); IGRAPH_CHECK(igraph_vector_push_back(&eids_new2old, eid)); } } } /* Get rid of some vectors that are not needed anymore */ if (!map) { igraph_vector_destroy(&vids_old2new); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&nei_edges); IGRAPH_FINALLY_CLEAN(1); /* Create the new graph */ IGRAPH_CHECK(igraph_create(res, &new_edges, (igraph_integer_t) no_of_new_nodes, directed)); IGRAPH_I_ATTRIBUTE_DESTROY(res); /* Now we can also get rid of the new_edges vector */ igraph_vector_destroy(&new_edges); IGRAPH_FINALLY_CLEAN(1); /* Make sure that the newly created graph is destroyed if something happens from * now on */ IGRAPH_FINALLY(igraph_destroy, res); /* Copy the graph attributes */ IGRAPH_CHECK(igraph_i_attribute_copy(res, graph, /* ga = */ 1, /* va = */ 0, /* ea = */ 0)); /* Copy the vertex attributes */ IGRAPH_CHECK(igraph_i_attribute_permute_vertices(graph, res, my_vids_new2old)); /* Copy the edge attributes */ IGRAPH_CHECK(igraph_i_attribute_permute_edges(graph, res, &eids_new2old)); if (!invmap) { igraph_vector_destroy(my_vids_new2old); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&eids_new2old); IGRAPH_FINALLY_CLEAN(2); /* 1 + 1 since we don't need to destroy res */ return 0; } /** * \ingroup structural * \function igraph_subgraph * \brief Creates a subgraph induced by the specified vertices. * * * This function is an alias to \ref igraph_induced_subgraph(), it is * left here to ensure API compatibility with igraph versions prior to 0.6. * * * This function collects the specified vertices and all edges between * them to a new graph. * As the vertex ids in a graph always start with zero, this function * very likely needs to reassign ids to the vertices. * \param graph The graph object. * \param res The subgraph, another graph object will be stored here, * do \em not initialize this object before calling this * function, and call \ref igraph_destroy() on it if you don't need * it any more. * \param vids A vertex selector describing which vertices to keep. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids. * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the original graph. * * \sa \ref igraph_delete_vertices() to delete the specified set of * vertices from a graph, the opposite of this function. */ int igraph_subgraph(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids) { IGRAPH_WARNING("igraph_subgraph is deprecated from igraph 0.6, " "use igraph_induced_subgraph instead"); return igraph_induced_subgraph(graph, res, vids, IGRAPH_SUBGRAPH_AUTO); } /** * \ingroup structural * \function igraph_induced_subgraph * \brief Creates a subgraph induced by the specified vertices. * * * This function collects the specified vertices and all edges between * them to a new graph. * As the vertex ids in a graph always start with zero, this function * very likely needs to reassign ids to the vertices. * \param graph The graph object. * \param res The subgraph, another graph object will be stored here, * do \em not initialize this object before calling this * function, and call \ref igraph_destroy() on it if you don't need * it any more. * \param vids A vertex selector describing which vertices to keep. * \param impl This parameter selects which implementation should we * use when constructing the new graph. Basically there are two * possibilities: \c IGRAPH_SUBGRAPH_COPY_AND_DELETE copies the * existing graph and deletes the vertices that are not needed * in the new graph, while \c IGRAPH_SUBGRAPH_CREATE_FROM_SCRATCH * constructs the new graph from scratch without copying the old * one. The latter is more efficient if you are extracting a * relatively small subpart of a very large graph, while the * former is better if you want to extract a subgraph whose size * is comparable to the size of the whole graph. There is a third * possibility: \c IGRAPH_SUBGRAPH_AUTO will select one of the * two methods automatically based on the ratio of the number * of vertices in the new and the old graph. * * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVVID, invalid vertex id in * \p vids. * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the original graph. * * \sa \ref igraph_delete_vertices() to delete the specified set of * vertices from a graph, the opposite of this function. */ int igraph_induced_subgraph(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_subgraph_implementation_t impl) { return igraph_induced_subgraph_map(graph, res, vids, impl, /* map= */ 0, /* invmap= */ 0); } int igraph_i_induced_subgraph_suggest_implementation( const igraph_t *graph, const igraph_vs_t vids, igraph_subgraph_implementation_t *result) { double ratio; igraph_integer_t num_vs; if (igraph_vs_is_all(&vids)) { ratio = 1.0; } else { IGRAPH_CHECK(igraph_vs_size(graph, &vids, &num_vs)); ratio = (igraph_real_t) num_vs / igraph_vcount(graph); } /* TODO: needs benchmarking; threshold was chosen totally arbitrarily */ if (ratio > 0.5) { *result = IGRAPH_SUBGRAPH_COPY_AND_DELETE; } else { *result = IGRAPH_SUBGRAPH_CREATE_FROM_SCRATCH; } return 0; } int igraph_induced_subgraph_map(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_subgraph_implementation_t impl, igraph_vector_t *map, igraph_vector_t *invmap) { if (impl == IGRAPH_SUBGRAPH_AUTO) { IGRAPH_CHECK(igraph_i_induced_subgraph_suggest_implementation(graph, vids, &impl)); } switch (impl) { case IGRAPH_SUBGRAPH_COPY_AND_DELETE: return igraph_i_subgraph_copy_and_delete(graph, res, vids, map, invmap); case IGRAPH_SUBGRAPH_CREATE_FROM_SCRATCH: return igraph_i_subgraph_create_from_scratch(graph, res, vids, map, invmap); default: IGRAPH_ERROR("unknown subgraph implementation type", IGRAPH_EINVAL); } return 0; } /** * \ingroup structural * \function igraph_subgraph_edges * \brief Creates a subgraph with the specified edges and their endpoints. * * * This function collects the specified edges and their endpoints to a new * graph. * As the vertex ids in a graph always start with zero, this function * very likely needs to reassign ids to the vertices. * \param graph The graph object. * \param res The subgraph, another graph object will be stored here, * do \em not initialize this object before calling this * function, and call \ref igraph_destroy() on it if you don't need * it any more. * \param eids An edge selector describing which edges to keep. * \param delete_vertices Whether to delete the vertices not incident on any * of the specified edges as well. If \c FALSE, the number of vertices * in the result graph will always be equal to the number of vertices * in the input graph. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * \c IGRAPH_EINVEID, invalid edge id in * \p eids. * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the original graph. * * \sa \ref igraph_delete_edges() to delete the specified set of * edges from a graph, the opposite of this function. */ int igraph_subgraph_edges(const igraph_t *graph, igraph_t *res, const igraph_es_t eids, igraph_bool_t delete_vertices) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vector_t delete=IGRAPH_VECTOR_NULL; char *vremain, *eremain; long int i; igraph_eit_t eit; IGRAPH_CHECK(igraph_eit_create(graph, eids, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_VECTOR_INIT_FINALLY(&delete, 0); vremain=igraph_Calloc(no_of_nodes, char); if (vremain==0) { IGRAPH_ERROR("subgraph_edges failed", IGRAPH_ENOMEM); } eremain=igraph_Calloc(no_of_edges, char); if (eremain==0) { IGRAPH_ERROR("subgraph_edges failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(free, vremain); /* TODO: hack */ IGRAPH_FINALLY(free, eremain); /* TODO: hack */ IGRAPH_CHECK(igraph_vector_reserve(&delete, no_of_edges-IGRAPH_EIT_SIZE(eit))); /* Collect the vertex and edge IDs that will remain */ for (IGRAPH_EIT_RESET(eit); !IGRAPH_EIT_END(eit); IGRAPH_EIT_NEXT(eit)) { igraph_integer_t from, to; long int eid = (long int) IGRAPH_EIT_GET(eit); IGRAPH_CHECK(igraph_edge(graph, (igraph_integer_t) eid, &from, &to)); eremain[eid] = vremain[(long int)from] = vremain[(long int)to] = 1; } /* Collect the edge IDs to be deleted */ for (i=0; iattr to 0 before calling igraph_copy */ res->attr=0; /* Why is this needed? TODO */ IGRAPH_CHECK(igraph_copy(res, graph)); IGRAPH_FINALLY(igraph_destroy, res); IGRAPH_CHECK(igraph_delete_edges(res, igraph_ess_vector(&delete))); if (delete_vertices) { /* Collect the vertex IDs to be deleted */ igraph_vector_clear(&delete); for (i=0; i 0) { IGRAPH_CHECK(igraph_delete_edges(graph, igraph_ess_vector(&edges))); } igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return IGRAPH_SUCCESS; } if (attr) { IGRAPH_VECTOR_INIT_FINALLY(&mergeinto, no_of_edges); } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, no_of_edges*2)); IGRAPH_CHECK(igraph_es_all(&es, IGRAPH_EDGEORDER_FROM)); IGRAPH_FINALLY(igraph_es_destroy, &es); IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); for (actedge=-1; !IGRAPH_EIT_END(eit); IGRAPH_EIT_NEXT(eit)) { edge=IGRAPH_EIT_GET(eit); from=IGRAPH_FROM(graph, edge); to=IGRAPH_TO(graph, edge); if (loops && from==to) { /* Loop edge to be removed */ if (attr) { VECTOR(mergeinto)[edge] = -1; } } else if (multiple && from==pfrom && to==pto) { /* Multiple edge to be contracted */ if (attr) { VECTOR(mergeinto)[edge]=actedge; } } else { /* Edge to be kept */ igraph_vector_push_back(&edges, from); igraph_vector_push_back(&edges, to); if (attr) { actedge++; VECTOR(mergeinto)[edge]=actedge; } } pfrom=from; pto=to; } igraph_eit_destroy(&eit); igraph_es_destroy(&es); IGRAPH_FINALLY_CLEAN(2); IGRAPH_CHECK(igraph_create(&res, &edges, (igraph_integer_t) no_of_nodes, igraph_is_directed(graph))); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &res); IGRAPH_I_ATTRIBUTE_DESTROY(&res); IGRAPH_I_ATTRIBUTE_COPY(&res, graph, /*graph=*/ 1, /*vertex=*/ 1, /*edge=*/ 0); if (attr) { igraph_fixed_vectorlist_t vl; IGRAPH_CHECK(igraph_fixed_vectorlist_convert(&vl, &mergeinto, actedge+1)); IGRAPH_FINALLY(igraph_fixed_vectorlist_destroy, &vl); IGRAPH_CHECK(igraph_i_attribute_combine_edges(graph, &res, &vl.v, edge_comb)); igraph_fixed_vectorlist_destroy(&vl); igraph_vector_destroy(&mergeinto); IGRAPH_FINALLY_CLEAN(2); } IGRAPH_FINALLY_CLEAN(1); igraph_destroy(graph); *graph=res; return 0; } /** * \ingroup structural * \function igraph_reciprocity * \brief Calculates the reciprocity of a directed graph. * * * The measure of reciprocity defines the proportion of mutual * connections, in a directed graph. It is most commonly defined as * the probability that the opposite counterpart of a directed edge is * also included in the graph. In adjacency matrix notation: * sum(i, j, (A.*A')ij) / sum(i, j, Aij), where * A.*A' is the element-wise product of matrix * A and its transpose. This measure is * calculated if the \p mode argument is \c * IGRAPH_RECIPROCITY_DEFAULT. * * * Prior to igraph version 0.6, another measure was implemented, * defined as the probability of mutual connection between a vertex * pair if we know that there is a (possibly non-mutual) connection * between them. In other words, (unordered) vertex pairs are * classified into three groups: (1) disconnected, (2) * non-reciprocally connected, (3) reciprocally connected. * The result is the size of group (3), divided by the sum of group * sizes (2)+(3). This measure is calculated if \p mode is \c * IGRAPH_RECIPROCITY_RATIO. * * \param graph The graph object. * \param res Pointer to an \c igraph_real_t which will contain the result. * \param ignore_loops Whether to ignore loop edges. * \param mode Type of reciprocity to calculate, possible values are * \c IGRAPH_RECIPROCITY_DEFAULT and \c IGRAPH_RECIPROCITY_RATIO, * please see their description above. * \return Error code: * \c IGRAPH_EINVAL: graph has no edges * \c IGRAPH_ENOMEM: not enough memory for * temporary data. * * Time complexity: O(|V|+|E|), |V| is the number of vertices, * |E| is the number of edges. * * \example examples/simple/igraph_reciprocity.c */ int igraph_reciprocity(const igraph_t *graph, igraph_real_t *res, igraph_bool_t ignore_loops, igraph_reciprocity_t mode) { igraph_integer_t nonrec=0, rec=0, loops=0; igraph_vector_t inneis, outneis; long int i; long int no_of_nodes=igraph_vcount(graph); if (mode != IGRAPH_RECIPROCITY_DEFAULT && mode != IGRAPH_RECIPROCITY_RATIO) { IGRAPH_ERROR("Invalid reciprocity type", IGRAPH_EINVAL); } /* THIS IS AN EXIT HERE !!!!!!!!!!!!!! */ if (!igraph_is_directed(graph)) { *res=1.0; return 0; } IGRAPH_VECTOR_INIT_FINALLY(&inneis, 0); IGRAPH_VECTOR_INIT_FINALLY(&outneis, 0); for (i=0; i VECTOR(outneis)[op]) { nonrec += 1; op++; } else { /* loop edge? */ if (VECTOR(inneis)[ip]==i) { loops += 1; if (!ignore_loops) { rec += 1; } } else { rec += 1; } ip++; op++; } } nonrec += (igraph_vector_size(&inneis)-ip) + (igraph_vector_size(&outneis)-op); } if (mode==IGRAPH_RECIPROCITY_DEFAULT) { if (ignore_loops) { *res= (igraph_real_t) rec/(igraph_ecount(graph)-loops); } else { *res= (igraph_real_t) rec/(igraph_ecount(graph)); } } else if (mode==IGRAPH_RECIPROCITY_RATIO) { *res= (igraph_real_t) rec/(rec+nonrec); } igraph_vector_destroy(&inneis); igraph_vector_destroy(&outneis); IGRAPH_FINALLY_CLEAN(2); return 0; } /** * \function igraph_constraint * \brief Burt's constraint scores. * * * This function calculates Burt's constraint scores for the given * vertices, also known as structural holes. * * * Burt's constraint is higher if ego has less, or mutually stronger * related (i.e. more redundant) contacts. Burt's measure of * constraint, C[i], of vertex i's ego network V[i], is defined for * directed and valued graphs, *
* C[i] = sum( sum( (p[i,q] p[q,j])^2, q in V[i], q != i,j ), j in * V[], j != i) *
* for a graph of order (ie. number of vertices) N, where proportional * tie strengths are defined as *
* p[i,j]=(a[i,j]+a[j,i]) / sum(a[i,k]+a[k,i], k in V[i], k != i), *
* a[i,j] are elements of A and * the latter being the graph adjacency matrix. For isolated vertices, * constraint is undefined. * *
* Burt, R.S. (2004). Structural holes and good ideas. American * Journal of Sociology 110, 349-399. * * * The first R version of this function was contributed by Jeroen * Bruggeman. * \param graph A graph object. * \param res Pointer to an initialized vector, the result will be * stored here. The vector will be resized to have the * appropriate size for holding the result. * \param vids Vertex selector containing the vertices for which the * constraint should be calculated. * \param weights Vector giving the weights of the edges. If it is * \c NULL then each edge is supposed to have the same weight. * \return Error code. * * Time complexity: O(|V|+E|+n*d^2), n is the number of vertices for * which the constraint is calculated and d is the average degree, |V| * is the number of vertices, |E| the number of edges in the * graph. If the weights argument is \c NULL then the time complexity * is O(|V|+n*d^2). */ int igraph_constraint(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, const igraph_vector_t *weights) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vit_t vit; long int nodes_to_calc; long int a, b, c, i, j, q; igraph_integer_t edge, from, to, edge2, from2, to2; igraph_vector_t contrib; igraph_vector_t degree; igraph_vector_t ineis_in, ineis_out, jneis_in, jneis_out; if (weights != 0 && igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid length of weight vector", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&contrib, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(°ree, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&ineis_in, 0); IGRAPH_VECTOR_INIT_FINALLY(&ineis_out, 0); IGRAPH_VECTOR_INIT_FINALLY(&jneis_in, 0); IGRAPH_VECTOR_INIT_FINALLY(&jneis_out, 0); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); nodes_to_calc=IGRAPH_VIT_SIZE(vit); if (weights==0) { IGRAPH_CHECK(igraph_degree(graph, °ree, igraph_vss_all(), IGRAPH_ALL, IGRAPH_NO_LOOPS)); } else { for (a=0; a * The largest in-, out- or total degree of the specified vertices is * calculated. * \param graph The input graph. * \param res Pointer to an integer (\c igraph_integer_t), the result * will be stored here. * \param vids Vector giving the vertex IDs for which the maximum degree will * be calculated. * \param mode Defines the type of the degree. * \c IGRAPH_OUT, out-degree, * \c IGRAPH_IN, in-degree, * \c IGRAPH_ALL, total degree (sum of the * in- and out-degree). * This parameter is ignored for undirected graphs. * \param loops Boolean, gives whether the self-loops should be * counted. * \return Error code: * \c IGRAPH_EINVVID: invalid vertex id. * \c IGRAPH_EINVMODE: invalid mode argument. * * Time complexity: O(v) if * loops is * TRUE, and * O(v*d) * otherwise. v is the number * vertices for which the degree will be calculated, and * d is their (average) degree. */ int igraph_maxdegree(const igraph_t *graph, igraph_integer_t *res, igraph_vs_t vids, igraph_neimode_t mode, igraph_bool_t loops) { igraph_vector_t tmp; IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); igraph_degree(graph, &tmp, vids, mode, loops); *res=(igraph_integer_t) igraph_vector_max(&tmp); igraph_vector_destroy(&tmp); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_density * Calculate the density of a graph. * * The density of a graph is simply the ratio number of * edges and the number of possible edges. Note that density is * ill-defined for graphs with multiple and/or loop edges, so consider * calling \ref igraph_simplify() on the graph if you know that it * contains multiple or loop edges. * \param graph The input graph object. * \param res Pointer to a real number, the result will be stored * here. * \param loops Logical constant, whether to include loops in the * calculation. If this constant is TRUE then * loop edges are thought to be possible in the graph (this does not * necessarily mean that the graph really contains any loops). If * this is FALSE then the result is only correct if the graph does not * contain loops. * \return Error code. * * Time complexity: O(1). */ int igraph_density(const igraph_t *graph, igraph_real_t *res, igraph_bool_t loops) { igraph_integer_t no_of_nodes=igraph_vcount(graph); igraph_real_t no_of_edges=igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); if (no_of_nodes == 0) { *res = IGRAPH_NAN; return 0; } if (!loops) { if (no_of_nodes == 1) { *res = IGRAPH_NAN; } else if (directed) { *res = no_of_edges / no_of_nodes / (no_of_nodes-1); } else { *res = no_of_edges / no_of_nodes * 2.0 / (no_of_nodes-1); } } else { if (directed) { *res = no_of_edges / no_of_nodes / no_of_nodes; } else { *res = no_of_edges / no_of_nodes * 2.0 / (no_of_nodes+1); } } return 0; } /** * \function igraph_neighborhood_size * \brief Calculates the size of the neighborhood of a given vertex. * * The neighborhood of a given order of a vertex includes all vertices * which are closer to the vertex than the order. Ie. order 0 is * always the vertex itself, order 1 is the vertex plus its immediate * neighbors, order 2 is order 1 plus the immediate neighbors of the * vertices in order 1, etc. * * This function calculates the size of the neighborhood * of the given order for the given vertices. * \param graph The input graph. * \param res Pointer to an initialized vector, the result will be * stored here. It will be resized as needed. * \param vids The vertices for which the calculation is performed. * \param order Integer giving the order of the neighborhood. * \param mode Specifies how to use the direction of the edges if a * directed graph is analyzed. For \c IGRAPH_OUT only the outgoing * edges are followed, so all vertices reachable from the source * vertex in at most \c order steps are counted. For \c IGRAPH_IN * all vertices from which the source vertex is reachable in at most * \c order steps are counted. \c IGRAPH_ALL ignores the direction * of the edges. This argument is ignored for undirected graphs. * \param mindist The minimum distance to include a vertex in the counting. * If this is one, then the starting vertex is not counted. If this is * two, then its neighbors are not counted, either, etc. * \return Error code. * * \sa \ref igraph_neighborhood() for calculating the actual neighborhood, * \ref igraph_neighborhood_graphs() for creating separate graphs from * the neighborhoods. * * Time complexity: O(n*d*o), where n is the number vertices for which * the calculation is performed, d is the average degree, o is the order. */ int igraph_neighborhood_size(const igraph_t *graph, igraph_vector_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q; igraph_vit_t vit; long int i, j; long int *added; igraph_vector_t neis; if (order < 0) { IGRAPH_ERROR("Negative order in neighborhood size", IGRAPH_EINVAL); } if (mindist < 0 || mindist > order) { IGRAPH_ERROR("Minimum distance should be between zero and order", IGRAPH_EINVAL); } added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot calculate neighborhood size", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_vector_resize(res, IGRAPH_VIT_SIZE(vit))); for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int node=IGRAPH_VIT_GET(vit); long int size=mindist==0 ? 1 : 0; added[node]=i+1; igraph_dqueue_clear(&q); if (order > 0) { igraph_dqueue_push(&q, node); igraph_dqueue_push(&q, 0); } while (!igraph_dqueue_empty(&q)) { long int actnode=(long int) igraph_dqueue_pop(&q); long int actdist=(long int) igraph_dqueue_pop(&q); long int n; igraph_neighbors(graph, &neis, (igraph_integer_t) actnode, mode); n=igraph_vector_size(&neis); if (actdist= mindist) { size++; } } } } else { /* we just count them, but don't add them */ for (j=0; j= mindist) { size++; } } } } } /* while q not empty */ VECTOR(*res)[i]=size; } /* for VIT, i */ igraph_vector_destroy(&neis); igraph_vit_destroy(&vit); igraph_dqueue_destroy(&q); igraph_Free(added); IGRAPH_FINALLY_CLEAN(4); return 0; } /** * \function igraph_neighborhood * Calculate the neighborhood of vertices. * * The neighborhood of a given order of a vertex includes all vertices * which are closer to the vertex than the order. Ie. order 0 is * always the vertex itself, order 1 is the vertex plus its immediate * neighbors, order 2 is order 1 plus the immediate neighbors of the * vertices in order 1, etc. * * This function calculates the vertices within the * neighborhood of the specified vertices. * \param graph The input graph. * \param res An initialized pointer vector. Note that the objects * (pointers) in the vector will \em not be freed, but the pointer * vector will be resized as needed. The result of the calculation * will be stored here in \c vector_t objects. * \param vids The vertices for which the calculation is performed. * \param order Integer giving the order of the neighborhood. * \param mode Specifies how to use the direction of the edges if a * directed graph is analyzed. For \c IGRAPH_OUT only the outgoing * edges are followed, so all vertices reachable from the source * vertex in at most \c order steps are included. For \c IGRAPH_IN * all vertices from which the source vertex is reachable in at most * \c order steps are included. \c IGRAPH_ALL ignores the direction * of the edges. This argument is ignored for undirected graphs. * \param mindist The minimum distance to include a vertex in the counting. * If this is one, then the starting vertex is not counted. If this is * two, then its neighbors are not counted, either, etc. * \return Error code. * * \sa \ref igraph_neighborhood_size() to calculate the size of the * neighborhood, \ref igraph_neighborhood_graphs() for creating * graphs from the neighborhoods. * * Time complexity: O(n*d*o), n is the number of vertices for which * the calculation is performed, d is the average degree, o is the * order. */ int igraph_neighborhood(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q; igraph_vit_t vit; long int i, j; long int *added; igraph_vector_t neis; igraph_vector_t tmp; igraph_vector_t *newv; if (order < 0) { IGRAPH_ERROR("Negative order in neighborhood size", IGRAPH_EINVAL); } if (mindist < 0 || mindist > order) { IGRAPH_ERROR("Minimum distance should be between zero and order", IGRAPH_EINVAL); } added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot calculate neighborhood size", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_CHECK(igraph_vector_ptr_resize(res, IGRAPH_VIT_SIZE(vit))); for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int node=IGRAPH_VIT_GET(vit); added[node]=i+1; igraph_vector_clear(&tmp); if (mindist == 0) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, node)); } if (order > 0) { igraph_dqueue_push(&q, node); igraph_dqueue_push(&q, 0); } while (!igraph_dqueue_empty(&q)) { long int actnode=(long int) igraph_dqueue_pop(&q); long int actdist=(long int) igraph_dqueue_pop(&q); long int n; igraph_neighbors(graph, &neis, (igraph_integer_t) actnode, mode); n=igraph_vector_size(&neis); if (actdist= mindist) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, nei)); } } } } else { /* we just count them but don't add them to q */ for (j=0; j= mindist) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, nei)); } } } } } /* while q not empty */ newv=igraph_Calloc(1, igraph_vector_t); if (newv==0) { IGRAPH_ERROR("Cannot calculate neighborhood", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newv); IGRAPH_CHECK(igraph_vector_copy(newv, &tmp)); VECTOR(*res)[i]=newv; IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&tmp); igraph_vector_destroy(&neis); igraph_vit_destroy(&vit); igraph_dqueue_destroy(&q); igraph_Free(added); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_neighborhood_graphs * Create graphs from the neighborhood(s) of some vertex/vertices. * * The neighborhood of a given order of a vertex includes all vertices * which are closer to the vertex than the order. Ie. order 0 is * always the vertex itself, order 1 is the vertex plus its immediate * neighbors, order 2 is order 1 plus the immediate neighbors of the * vertices in order 1, etc. * * This function finds every vertex in the neighborhood * of a given parameter vertex and creates a graph from these * vertices. * * The first version of this function was written by * Vincent Matossian, thanks Vincent. * \param graph The input graph. * \param res Pointer to a pointer vector, the result will be stored * here, ie. \c res will contain pointers to \c igraph_t * objects. It will be resized if needed but note that the * objects in the pointer vector will not be freed. * \param vids The vertices for which the calculation is performed. * \param order Integer giving the order of the neighborhood. * \param mode Specifies how to use the direction of the edges if a * directed graph is analyzed. For \c IGRAPH_OUT only the outgoing * edges are followed, so all vertices reachable from the source * vertex in at most \c order steps are counted. For \c IGRAPH_IN * all vertices from which the source vertex is reachable in at most * \c order steps are counted. \c IGRAPH_ALL ignores the direction * of the edges. This argument is ignored for undirected graphs. * \param mindist The minimum distance to include a vertex in the counting. * If this is one, then the starting vertex is not counted. If this is * two, then its neighbors are not counted, either, etc. * \return Error code. * * \sa \ref igraph_neighborhood_size() for calculating the neighborhood * sizes only, \ref igraph_neighborhood() for calculating the * neighborhoods (but not creating graphs). * * Time complexity: O(n*(|V|+|E|)), where n is the number vertices for * which the calculation is performed, |V| and |E| are the number of * vertices and edges in the original input graph. */ int igraph_neighborhood_graphs(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vs_t vids, igraph_integer_t order, igraph_neimode_t mode, igraph_integer_t mindist) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q; igraph_vit_t vit; long int i, j; long int *added; igraph_vector_t neis; igraph_vector_t tmp; igraph_t *newg; if (order < 0) { IGRAPH_ERROR("Negative order in neighborhood size", IGRAPH_EINVAL); } if (mindist < 0 || mindist > order) { IGRAPH_ERROR("Minimum distance should be between zero and order", IGRAPH_EINVAL); } added=igraph_Calloc(no_of_nodes, long int); if (added==0) { IGRAPH_ERROR("Cannot calculate neighborhood size", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_CHECK(igraph_vector_ptr_resize(res, IGRAPH_VIT_SIZE(vit))); for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int node=IGRAPH_VIT_GET(vit); added[node]=i+1; igraph_vector_clear(&tmp); if (mindist == 0) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, node)); } if (order > 0) { igraph_dqueue_push(&q, node); igraph_dqueue_push(&q, 0); } while (!igraph_dqueue_empty(&q)) { long int actnode=(long int) igraph_dqueue_pop(&q); long int actdist=(long int) igraph_dqueue_pop(&q); long int n; igraph_neighbors(graph, &neis, (igraph_integer_t) actnode, mode); n=igraph_vector_size(&neis); if (actdist= mindist) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, nei)); } } } } else { /* we just count them but don't add them to q */ for (j=0; j= mindist) { IGRAPH_CHECK(igraph_vector_push_back(&tmp, nei)); } } } } } /* while q not empty */ newg=igraph_Calloc(1, igraph_t); if (newg==0) { IGRAPH_ERROR("Cannot create neighborhood graph", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, newg); if (igraph_vector_size(&tmp) < no_of_nodes) { IGRAPH_CHECK(igraph_induced_subgraph(graph, newg, igraph_vss_vector(&tmp), IGRAPH_SUBGRAPH_AUTO)); } else { IGRAPH_CHECK(igraph_copy(newg, graph)); } VECTOR(*res)[i]=newg; IGRAPH_FINALLY_CLEAN(1); } igraph_vector_destroy(&tmp); igraph_vector_destroy(&neis); igraph_vit_destroy(&vit); igraph_dqueue_destroy(&q); igraph_Free(added); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_topological_sorting * \brief Calculate a possible topological sorting of the graph. * * * A topological sorting of a directed acyclic graph is a linear ordering * of its nodes where each node comes before all nodes to which it has * edges. Every DAG has at least one topological sort, and may have many. * This function returns a possible topological sort among them. If the * graph is not acyclic (it has at least one cycle), a partial topological * sort is returned and a warning is issued. * * \param graph The input graph. * \param res Pointer to a vector, the result will be stored here. * It will be resized if needed. * \param mode Specifies how to use the direction of the edges. * For \c IGRAPH_OUT, the sorting order ensures that each node comes * before all nodes to which it has edges, so nodes with no incoming * edges go first. For \c IGRAPH_IN, it is quite the opposite: each * node comes before all nodes from which it receives edges. Nodes * with no outgoing edges go first. * \return Error code. * * Time complexity: O(|V|+|E|), where |V| and |E| are the number of * vertices and edges in the original input graph. * * \sa \ref igraph_is_dag() if you are only interested in whether a given * graph is a DAG or not, or \ref igraph_feedback_arc_set() to find a * set of edges whose removal makes the graph a DAG. * * \example examples/simple/igraph_topological_sorting.c */ int igraph_topological_sorting(const igraph_t* graph, igraph_vector_t *res, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t degrees, neis; igraph_dqueue_t sources; igraph_neimode_t deg_mode; long int node, i, j; if (mode == IGRAPH_ALL || !igraph_is_directed(graph)) { IGRAPH_ERROR("topological sorting does not make sense for undirected graphs", IGRAPH_EINVAL); } else if (mode == IGRAPH_OUT) { deg_mode = IGRAPH_IN; } else if (mode == IGRAPH_IN) { deg_mode = IGRAPH_OUT; } else { IGRAPH_ERROR("invalid mode", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(°rees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_dqueue_init(&sources, 0)); IGRAPH_FINALLY(igraph_dqueue_destroy, &sources); IGRAPH_CHECK(igraph_degree(graph, °rees, igraph_vss_all(), deg_mode, 0)); igraph_vector_clear(res); /* Do we have nodes with no incoming vertices? */ for (i=0; i * A directed acyclic graph (DAG) is a directed graph with no cycles. * * \param graph The input graph. * \param res Pointer to a boolean constant, the result * is stored here. * \return Error code. * * Time complexity: O(|V|+|E|), where |V| and |E| are the number of * vertices and edges in the original input graph. * * \sa \ref igraph_topological_sorting() to get a possible topological * sorting of a DAG. */ int igraph_is_dag(const igraph_t* graph, igraph_bool_t *res) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_t degrees, neis; igraph_dqueue_t sources; long int node, i, j, nei, vertices_left; if (!igraph_is_directed(graph)) { *res = 0; return IGRAPH_SUCCESS; } IGRAPH_VECTOR_INIT_FINALLY(°rees, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_dqueue_init(&sources, 0)); IGRAPH_FINALLY(igraph_dqueue_destroy, &sources); IGRAPH_CHECK(igraph_degree(graph, °rees, igraph_vss_all(), IGRAPH_OUT, 1)); vertices_left = no_of_nodes; /* Do we have nodes with no incoming edges? */ for (i=0; i * A graph is a simple graph if it does not contain loop edges and * multiple edges. * * \param graph The input graph. * \param res Pointer to a boolean constant, the result * is stored here. * \return Error code. * * \sa \ref igraph_is_loop() and \ref igraph_is_multiple() to * find the loops and multiple edges, \ref igraph_simplify() to * get rid of them, or \ref igraph_has_multiple() to decide whether * there is at least one multiple edge. * * Time complexity: O(|V|+|E|). */ int igraph_is_simple(const igraph_t *graph, igraph_bool_t *res) { long int vc=igraph_vcount(graph); long int ec=igraph_ecount(graph); if (vc==0 || ec==0) { *res=1; } else { igraph_vector_t neis; long int i, j, n; igraph_bool_t found = 0; IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); for (i=0; i < vc; i++) { igraph_neighbors(graph, &neis, (igraph_integer_t) i, IGRAPH_OUT); n=igraph_vector_size(&neis); for (j=0; j < n; j++) { if (VECTOR(neis)[j]==i) { found=1; break; } if (j>0 && VECTOR(neis)[j-1]==VECTOR(neis)[j]) { found=1; break; } } } *res=!found; igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_has_loop * \brief Returns whether the graph has at least one loop edge. * * * A loop edge is an edge from a vertex to itself. * \param graph The input graph. * \param res Pointer to an initialized boolean vector for storing the result. * * \sa \ref igraph_simplify() to get rid of loop edges. * * Time complexity: O(e), the number of edges to check. * * \example examples/simple/igraph_has_loop.c */ int igraph_has_loop(const igraph_t *graph, igraph_bool_t *res) { long int i, m = igraph_ecount(graph); *res = 0; for (i = 0; i < m; i++) { if (IGRAPH_FROM(graph, i) == IGRAPH_TO(graph, i)) { *res = 1; break; } } return 0; } /** * \function igraph_is_loop * \brief Find the loop edges in a graph. * * * A loop edge is an edge from a vertex to itself. * \param graph The input graph. * \param res Pointer to an initialized boolean vector for storing the result, * it will be resized as needed. * \param es The edges to check, for all edges supply \ref igraph_ess_all() here. * \return Error code. * * \sa \ref igraph_simplify() to get rid of loop edges. * * Time complexity: O(e), the number of edges to check. * * \example examples/simple/igraph_is_loop.c */ int igraph_is_loop(const igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es) { igraph_eit_t eit; long int i; IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_CHECK(igraph_vector_bool_resize(res, IGRAPH_EIT_SIZE(eit))); for (i=0; !IGRAPH_EIT_END(eit); i++, IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); VECTOR(*res)[i] = (IGRAPH_FROM(graph, e)==IGRAPH_TO(graph, e)) ? 1 : 0; } igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \function igraph_has_multiple * \brief Check whether the graph has at least one multiple edge. * * * An edge is a multiple edge if there is another * edge with the same head and tail vertices in the graph. * * \param graph The input graph. * \param res Pointer to a boolean variable, the result will be stored here. * \return Error code. * * \sa \ref igraph_count_multiple(), \ref igraph_is_multiple() and \ref igraph_simplify(). * * Time complexity: O(e*d), e is the number of edges to check and d is the * average degree (out-degree in directed graphs) of the vertices at the * tail of the edges. * * \example examples/simple/igraph_has_multiple.c */ int igraph_has_multiple(const igraph_t *graph, igraph_bool_t *res) { long int vc=igraph_vcount(graph); long int ec=igraph_ecount(graph); igraph_bool_t directed=igraph_is_directed(graph); if (vc==0 || ec==0) { *res=0; } else { igraph_vector_t neis; long int i, j, n; igraph_bool_t found=0; IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); for (i=0; i < vc && !found; i++) { IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) i, IGRAPH_OUT)); n = igraph_vector_size(&neis); for (j=1; j < n; j++) { if (VECTOR(neis)[j-1] == VECTOR(neis)[j]) { /* If the graph is undirected, loop edges appear twice in the neighbor * list, so check the next item as well */ if (directed) { /* Directed, so this is a real multiple edge */ found=1; break; } else if (VECTOR(neis)[j-1] != i) { /* Undirected, but not a loop edge */ found=1; break; } else if (j < n-1 && VECTOR(neis)[j] == VECTOR(neis)[j+1]) { /* Undirected, loop edge, multiple times */ found=1; break; } } } } *res=found; igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(1); } return 0; } /** * \function igraph_is_multiple * \brief Find the multiple edges in a graph. * * * An edge is a multiple edge if there is another * edge with the same head and tail vertices in the graph. * * * Note that this function returns true only for the second or more * appearances of the multiple edges. * \param graph The input graph. * \param res Pointer to a boolean vector, the result will be stored * here. It will be resized as needed. * \param es The edges to check. Supply \ref igraph_ess_all() if you want * to check all edges. * \return Error code. * * \sa \ref igraph_count_multiple(), \ref igraph_has_multiple() and \ref igraph_simplify(). * * Time complexity: O(e*d), e is the number of edges to check and d is the * average degree (out-degree in directed graphs) of the vertices at the * tail of the edges. * * \example examples/simple/igraph_is_multiple.c */ int igraph_is_multiple(const igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es) { igraph_eit_t eit; long int i; igraph_lazy_inclist_t inclist; IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_vector_bool_resize(res, IGRAPH_EIT_SIZE(eit))); for (i=0; !IGRAPH_EIT_END(eit); i++, IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); long int from=IGRAPH_FROM(graph, e); long int to=IGRAPH_TO(graph, e); igraph_vector_t *neis=igraph_lazy_inclist_get(&inclist, (igraph_integer_t) from); long int j, n=igraph_vector_size(neis); VECTOR(*res)[i]=0; for (j=0; j * If the graph has no multiple edges then the result vector will be * filled with ones. * (An edge is a multiple edge if there is another * edge with the same head and tail vertices in the graph.) * * * \param graph The input graph. * \param res Pointer to a vector, the result will be stored * here. It will be resized as needed. * \param es The edges to check. Supply \ref igraph_ess_all() if you want * to check all edges. * \return Error code. * * \sa \ref igraph_is_multiple() and \ref igraph_simplify(). * * Time complexity: O(e*d), e is the number of edges to check and d is the * average degree (out-degree in directed graphs) of the vertices at the * tail of the edges. */ int igraph_count_multiple(const igraph_t *graph, igraph_vector_t *res, igraph_es_t es) { igraph_eit_t eit; long int i; igraph_lazy_inclist_t inclist; IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, IGRAPH_OUT)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_vector_resize(res, IGRAPH_EIT_SIZE(eit))); for (i=0; !IGRAPH_EIT_END(eit); i++, IGRAPH_EIT_NEXT(eit)) { long int e=IGRAPH_EIT_GET(eit); long int from=IGRAPH_FROM(graph, e); long int to=IGRAPH_TO(graph, e); igraph_vector_t *neis=igraph_lazy_inclist_get(&inclist, (igraph_integer_t) from); long int j, n=igraph_vector_size(neis); VECTOR(*res)[i] = 0; for (j=0; j * The current implementation works for undirected graphs only, * directed graphs are treated as undirected graphs. Loop edges and * multiple edges are ignored. * * If the graph is a forest (ie. acyclic), then zero is returned. * * This implementation is based on Alon Itai and Michael Rodeh: * Finding a minimum circuit in a graph * \emb Proceedings of the ninth annual ACM symposium on Theory of * computing \eme, 1-10, 1977. The first implementation of this * function was done by Keith Briggs, thanks Keith. * \param graph The input graph. * \param girth Pointer to an integer, if not \c NULL then the result * will be stored here. * \param circle Pointer to an initialized vector, the vertex ids in * the shortest circle will be stored here. If \c NULL then it is * ignored. * \return Error code. * * Time complexity: O((|V|+|E|)^2), |V| is the number of vertices, |E| * is the number of edges in the general case. If the graph has no * circles at all then the function needs O(|V|+|E|) time to realize * this and then it stops. * * \example examples/simple/igraph_girth.c */ int igraph_girth(const igraph_t *graph, igraph_integer_t *girth, igraph_vector_t *circle) { long int no_of_nodes=igraph_vcount(graph); igraph_dqueue_t q; igraph_lazy_adjlist_t adjlist; long int mincirc=LONG_MAX, minvertex=0; long int node; igraph_bool_t triangle=0; igraph_vector_t *neis; igraph_vector_long_t level; long int stoplevel=no_of_nodes+1; igraph_bool_t anycircle=0; long int t1=0, t2=0; IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, IGRAPH_ALL, IGRAPH_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); IGRAPH_CHECK(igraph_vector_long_init(&level, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &level); for (node=0; !triangle && node=stoplevel) { break; } neis=igraph_lazy_adjlist_get(&adjlist, (igraph_integer_t) actnode); n=igraph_vector_size(neis); for (i=0; i * The line graph L(G) of a G directed graph is slightly different, * L(G) has one vertex for each edge in G and two vertices in L(G) are connected * by a directed edge if the target of the first vertex's corresponding edge * is the same as the source of the second vertex's corresponding edge. * * * Edge \em i in the original graph will correspond to vertex \em i * in the line graph. * * * The first version of this function was contributed by Vincent Matossian, * thanks. * \param graph The input graph, may be directed or undirected. * \param linegraph Pointer to an uninitialized graph object, the * result is stored here. * \return Error code. * * Time complexity: O(|V|+|E|), the number of edges plus the number of vertices. */ int igraph_linegraph(const igraph_t *graph, igraph_t *linegraph) { if (igraph_is_directed(graph)) { return igraph_i_linegraph_directed(graph, linegraph); } else { return igraph_i_linegraph_undirected(graph, linegraph); } } /** * \function igraph_add_edge * \brief Adds a single edge to a graph. * * * For directed graphs the edge points from \p from to \p to. * * * Note that if you want to add many edges to a big graph, then it is * inefficient to add them one by one, it is better to collect them into * a vector and add all of them via a single \ref igraph_add_edges() call. * \param igraph The graph. * \param from The id of the first vertex of the edge. * \param to The id of the second vertex of the edge. * \return Error code. * * \sa \ref igraph_add_edges() to add many edges, \ref * igraph_delete_edges() to remove edges and \ref * igraph_add_vertices() to add vertices. * * Time complexity: O(|V|+|E|), the number of edges plus the number of * vertices. */ int igraph_add_edge(igraph_t *graph, igraph_integer_t from, igraph_integer_t to) { igraph_vector_t edges; int ret; IGRAPH_VECTOR_INIT_FINALLY(&edges, 2); VECTOR(edges)[0]=from; VECTOR(edges)[1]=to; IGRAPH_CHECK(ret=igraph_add_edges(graph, &edges, 0)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return ret; } /* * \example examples/simple/graph_convergence_degree.c */ int igraph_convergence_degree(const igraph_t *graph, igraph_vector_t *result, igraph_vector_t *ins, igraph_vector_t *outs) { long int no_of_nodes = igraph_vcount(graph); long int no_of_edges = igraph_ecount(graph); long int i, j, k, n; long int *geodist; igraph_vector_int_t *eids; igraph_vector_t *ins_p, *outs_p, ins_v, outs_v; igraph_dqueue_t q; igraph_inclist_t inclist; igraph_bool_t directed = igraph_is_directed(graph); if (result != 0) IGRAPH_CHECK(igraph_vector_resize(result, no_of_edges)); IGRAPH_CHECK(igraph_dqueue_init(&q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &q); if (ins == 0) { ins_p = &ins_v; IGRAPH_VECTOR_INIT_FINALLY(ins_p, no_of_edges); } else { ins_p = ins; IGRAPH_CHECK(igraph_vector_resize(ins_p, no_of_edges)); igraph_vector_null(ins_p); } if (outs == 0) { outs_p = &outs_v; IGRAPH_VECTOR_INIT_FINALLY(outs_p, no_of_edges); } else { outs_p = outs; IGRAPH_CHECK(igraph_vector_resize(outs_p, no_of_edges)); igraph_vector_null(outs_p); } geodist=igraph_Calloc(no_of_nodes, long int); if (geodist==0) { IGRAPH_ERROR("Cannot calculate convergence degrees", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, geodist); /* Collect shortest paths originating from/to every node to correctly * determine input field sizes */ for (k=0; k<(directed?2:1); k++) { igraph_neimode_t neimode = (k==0)?IGRAPH_OUT:IGRAPH_IN; igraph_real_t *vec; IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, neimode)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); vec = (k==0)?VECTOR(*ins_p):VECTOR(*outs_p); for (i=0; i * If there is more than one path with the smallest weight between two vertices, this * function gives only one of them. * \param graph The graph object. * \param vertices The result, the ids of the vertices along the paths. * This is a pointer vector, each element points to a vector * object. These should be initialized before passing them to * the function, which will properly clear and/or resize them * and fill the ids of the vertices along the geodesics from/to * the vertices. Supply a null pointer here if you don't need * these vectors. Normally, either this argument, or the \c * edges should be non-null, but no error or warning is given * if they are both null pointers. * \param edges The result, the ids of the edges along the paths. * This is a pointer vector, each element points to a vector * object. These should be initialized before passing them to * the function, which will properly clear and/or resize them * and fill the ids of the vertices along the geodesics from/to * the vertices. Supply a null pointer here if you don't need * these vectors. Normally, either this argument, or the \c * vertices should be non-null, but no error or warning is given * if they are both null pointers. * \param from The id of the vertex from/to which the geodesics are * calculated. * \param to Vertex sequence with the ids of the vertices to/from which the * shortest paths will be calculated. A vertex might be given multiple * times. * \param weights a vector holding the edge weights. All weights must be * positive. * \param mode The type of shortest paths to be use for the * calculation in directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing paths are calculated. * \cli IGRAPH_IN * the incoming paths are calculated. * \cli IGRAPH_ALL * the directed graph is considered as an * undirected one for the computation. * \endclist * \param predecessors A pointer to an initialized igraph vector or null. * If not null, a vector containing the predecessor of each vertex in * the single source shortest path tree is returned here. The * predecessor of vertex i in the tree is the vertex from which vertex i * was reached. The predecessor of the start vertex (in the \c from * argument) is itself by definition. If the predecessor is -1, it means * that the given vertex was not reached from the source during the * search. Note that the search terminates if all the vertices in * \c to are reached. * \param inbound_edges A pointer to an initialized igraph vector or null. * If not null, a vector containing the inbound edge of each vertex in * the single source shortest path tree is returned here. The * inbound edge of vertex i in the tree is the edge via which vertex i * was reached. The start vertex and vertices that were not reached * during the search will have -1 in the corresponding entry of the * vector. Note that the search terminates if all the vertices in * \c to are reached. * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * \p from is invalid vertex id, or the length of \p to is * not the same as the length of \p res. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|E|log|E|+|V|), where |V| is the number of * vertices and |E| is the number of edges * * \sa \ref igraph_shortest_paths_dijkstra() if you only need the path length but * not the paths themselves, \ref igraph_get_shortest_paths() if all edge * weights are equal. * * \example examples/simple/igraph_get_shortest_paths_dijkstra.c */ int igraph_get_shortest_paths_dijkstra(const igraph_t *graph, igraph_vector_ptr_t *vertices, igraph_vector_ptr_t *edges, igraph_integer_t from, igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode, igraph_vector_long_t *predecessors, igraph_vector_long_t *inbound_edges) { /* Implementation details. This is the basic Dijkstra algorithm, with a binary heap. The heap is indexed, i.e. it stores not only the distances, but also which vertex they belong to. The other mapping, i.e. getting the distance for a vertex is not in the heap (that would by the double-indexed heap), but in the result matrix. Dirty tricks: - the opposite of the distance is stored in the heap, as it is a maximum heap and we need a minimum heap. - we don't use IGRAPH_INFINITY in the distance vector during the computation, as IGRAPH_FINITE() might involve a function call and we want to spare that. So we store distance+1.0 instead of distance, and zero denotes infinity. - `parents' assigns the inbound edge IDs of all vertices in the shortest path tree to the vertices. In this implementation, the edge ID + 1 is stored, zero means unreachable vertices. */ long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vit_t vit; igraph_2wheap_t Q; igraph_lazy_inclist_t inclist; igraph_vector_t dists; long int *parents; igraph_bool_t *is_target; long int i,to_reach; if (!weights) { return igraph_get_shortest_paths(graph, vertices, edges, from, to, mode, predecessors, inbound_edges); } if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Weight vector length does not match", IGRAPH_EINVAL); } if (igraph_vector_min(weights) < 0) { IGRAPH_ERROR("Weight vector must be non-negative", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); if (vertices && IGRAPH_VIT_SIZE(vit) != igraph_vector_ptr_size(vertices)) { IGRAPH_ERROR("Size of `vertices' and `to' should match", IGRAPH_EINVAL); } if (edges && IGRAPH_VIT_SIZE(vit) != igraph_vector_ptr_size(edges)) { IGRAPH_ERROR("Size of `edges' and `to' should match", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_2wheap_init(&Q, no_of_nodes)); IGRAPH_FINALLY(igraph_2wheap_destroy, &Q); IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, mode)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); IGRAPH_VECTOR_INIT_FINALLY(&dists, no_of_nodes); igraph_vector_fill(&dists, -1.0); parents = igraph_Calloc(no_of_nodes, long int); if (parents == 0) IGRAPH_ERROR("Can't calculate shortest paths", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, parents); is_target = igraph_Calloc(no_of_nodes, igraph_bool_t); if (is_target == 0) IGRAPH_ERROR("Can't calculate shortest paths", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, is_target); /* Mark the vertices we need to reach */ to_reach=IGRAPH_VIT_SIZE(vit); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { if (!is_target[ (long int) IGRAPH_VIT_GET(vit) ]) { is_target[ (long int) IGRAPH_VIT_GET(vit) ] = 1; } else { to_reach--; /* this node was given multiple times */ } } VECTOR(dists)[(long int)from] = 0.0; /* zero distance */ parents[(long int)from] = 0; igraph_2wheap_push_with_index(&Q, from, 0); while (!igraph_2wheap_empty(&Q) && to_reach > 0) { long int nlen, minnei=igraph_2wheap_max_index(&Q); igraph_real_t mindist=-igraph_2wheap_delete_max(&Q); igraph_vector_t *neis; IGRAPH_ALLOW_INTERRUPTION(); if (is_target[minnei]) { is_target[minnei] = 0; to_reach--; } /* Now check all neighbors of 'minnei' for a shorter path */ neis=igraph_lazy_inclist_get(&inclist, (igraph_integer_t) minnei); nlen=igraph_vector_size(neis); for (i=0; i 0) IGRAPH_WARNING("Couldn't reach some vertices"); /* Create `predecessors' if needed */ if (predecessors) { IGRAPH_CHECK(igraph_vector_long_resize(predecessors, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { if (i == from) { /* i is the start vertex */ VECTOR(*predecessors)[i] = i; } else if (parents[i] <= 0) { /* i was not reached */ VECTOR(*predecessors)[i] = -1; } else { /* i was reached via the edge with ID = parents[i] - 1 */ VECTOR(*predecessors)[i] = IGRAPH_OTHER(graph, parents[i]-1, i); } } } /* Create `inbound_edges' if needed */ if (inbound_edges) { IGRAPH_CHECK(igraph_vector_long_resize(inbound_edges, no_of_nodes)); for (i = 0; i < no_of_nodes; i++) { if (parents[i] <= 0) { /* i was not reached */ VECTOR(*inbound_edges)[i] = -1; } else { /* i was reached via the edge with ID = parents[i] - 1 */ VECTOR(*inbound_edges)[i] = parents[i]-1; } } } /* Reconstruct the shortest paths based on vertex and/or edge IDs */ if (vertices || edges) { for (IGRAPH_VIT_RESET(vit), i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { long int node=IGRAPH_VIT_GET(vit); long int size, act, edge; igraph_vector_t *vvec=0, *evec=0; if (vertices) { vvec=VECTOR(*vertices)[i]; igraph_vector_clear(vvec); } if (edges) { evec=VECTOR(*edges)[i]; igraph_vector_clear(evec); } IGRAPH_ALLOW_INTERRUPTION(); size=0; act=node; while (parents[act]) { size++; edge=parents[act]-1; act=IGRAPH_OTHER(graph, edge, act); } if (vvec) { IGRAPH_CHECK(igraph_vector_resize(vvec, size+1)); VECTOR(*vvec)[size]=node; } if (evec) { IGRAPH_CHECK(igraph_vector_resize(evec, size)); } act=node; while (parents[act]) { edge=parents[act]-1; act=IGRAPH_OTHER(graph, edge, act); size--; if (vvec) { VECTOR(*vvec)[size]=act; } if (evec) { VECTOR(*evec)[size]=edge; } } } } igraph_lazy_inclist_destroy(&inclist); igraph_2wheap_destroy(&Q); igraph_vector_destroy(&dists); igraph_Free(is_target); igraph_Free(parents); igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(6); return 0; } /** * \function igraph_get_shortest_path_dijkstra * Weighted shortest path from one vertex to another one. * * Calculates a single (positively) weighted shortest path from * a single vertex to another one, using Dijkstra's algorithm. * * This function is a special case (and a wrapper) to * \ref igraph_get_shortest_paths_dijkstra(). * * \param graph The input graph, it can be directed or undirected. * \param vertices Pointer to an initialized vector or a null * pointer. If not a null pointer, then the vertex ids along * the path are stored here, including the source and target * vertices. * \param edges Pointer to an uninitialized vector or a null * pointer. If not a null pointer, then the edge ids along the * path are stored here. * \param from The id of the source vertex. * \param to The id of the target vertex. * \param weights Vector of edge weights, in the order of edge * ids. They must be non-negative, otherwise the algorithm does * not work. * \param mode A constant specifying how edge directions are * considered in directed graphs. \c IGRAPH_OUT follows edge * directions, \c IGRAPH_IN follows the opposite directions, * and \c IGRAPH_ALL ignores edge directions. This argument is * ignored for undirected graphs. * \return Error code. * * Time complexity: O(|E|log|E|+|V|), |V| is the number of vertices, * |E| is the number of edges in the graph. * * \sa \ref igraph_get_shortest_paths_dijkstra() for the version with * more target vertices. */ int igraph_get_shortest_path_dijkstra(const igraph_t *graph, igraph_vector_t *vertices, igraph_vector_t *edges, igraph_integer_t from, igraph_integer_t to, const igraph_vector_t *weights, igraph_neimode_t mode) { igraph_vector_ptr_t vertices2, *vp=&vertices2; igraph_vector_ptr_t edges2, *ep=&edges2; if (vertices) { IGRAPH_CHECK(igraph_vector_ptr_init(&vertices2, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vertices2); VECTOR(vertices2)[0]=vertices; } else { vp=0; } if (edges) { IGRAPH_CHECK(igraph_vector_ptr_init(&edges2, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &edges2); VECTOR(edges2)[0]=edges; } else { ep=0; } IGRAPH_CHECK(igraph_get_shortest_paths_dijkstra(graph, vp, ep, from, igraph_vss_1(to), weights, mode, 0, 0)); if (edges) { igraph_vector_ptr_destroy(&edges2); IGRAPH_FINALLY_CLEAN(1); } if (vertices) { igraph_vector_ptr_destroy(&vertices2); IGRAPH_FINALLY_CLEAN(1); } return 0; } int igraph_i_vector_tail_cmp(const void* path1, const void* path2); /* Compares two paths based on their last elements. Required by * igraph_get_all_shortest_paths_dijkstra to put the final result * in order. Assumes that both paths are pointers to igraph_vector_t * objects and that they are not empty */ int igraph_i_vector_tail_cmp(const void* path1, const void* path2) { return (int) (igraph_vector_tail(*(const igraph_vector_t**)path1) - igraph_vector_tail(*(const igraph_vector_t**)path2)); } /** * \ingroup structural * \function igraph_get_all_shortest_paths_dijkstra * \brief Finds all shortest paths (geodesics) from a vertex to all other vertices. * * \param graph The graph object. * \param res Pointer to an initialized pointer vector, the result * will be stored here in igraph_vector_t objects. Each vector * object contains the vertices along a shortest path from \p from * to another vertex. The vectors are ordered according to their * target vertex: first the shortest paths to vertex 0, then to * vertex 1, etc. No data is included for unreachable vertices. * \param nrgeo Pointer to an initialized igraph_vector_t object or * NULL. If not NULL the number of shortest paths from \p from are * stored here for every vertex in the graph. Note that the values * will be accurate only for those vertices that are in the target * vertex sequence (see \p to), since the search terminates as soon * as all the target vertices have been found. * \param from The id of the vertex from/to which the geodesics are * calculated. * \param to Vertex sequence with the ids of the vertices to/from which the * shortest paths will be calculated. A vertex might be given multiple * times. * \param weights a vector holding the edge weights. All weights must be * non-negative. * \param mode The type of shortest paths to be use for the * calculation in directed graphs. Possible values: * \clist * \cli IGRAPH_OUT * the outgoing paths are calculated. * \cli IGRAPH_IN * the incoming paths are calculated. * \cli IGRAPH_ALL * the directed graph is considered as an * undirected one for the computation. * \endclist * \return Error code: * \clist * \cli IGRAPH_ENOMEM * not enough memory for temporary data. * \cli IGRAPH_EINVVID * \p from is invalid vertex id, or the length of \p to is * not the same as the length of \p res. * \cli IGRAPH_EINVMODE * invalid mode argument. * \endclist * * Time complexity: O(|E|log|E|+|V|), where |V| is the number of * vertices and |E| is the number of edges * * \sa \ref igraph_shortest_paths_dijkstra() if you only need the path * length but not the paths themselves, \ref igraph_get_all_shortest_paths() * if all edge weights are equal. * * \example examples/simple/igraph_get_all_shortest_paths_dijkstra.c */ int igraph_get_all_shortest_paths_dijkstra(const igraph_t *graph, igraph_vector_ptr_t *res, igraph_vector_t *nrgeo, igraph_integer_t from, igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode) { /* Implementation details: see igraph_get_shortest_paths_dijkstra, it's basically the same. */ long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vit_t vit; igraph_2wheap_t Q; igraph_lazy_inclist_t inclist; igraph_vector_t dists, order; igraph_vector_ptr_t parents; unsigned char *is_target; long int i, n, to_reach; if (!weights) { return igraph_get_all_shortest_paths(graph, res, nrgeo, from, to, mode); } if (res == 0 && nrgeo == 0) return IGRAPH_SUCCESS; if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Weight vector length does not match", IGRAPH_EINVAL); } if (igraph_vector_min(weights) < 0) { IGRAPH_ERROR("Weight vector must be non-negative", IGRAPH_EINVAL); } /* parents stores a vector for each vertex, listing the parent vertices * of each vertex in the traversal */ IGRAPH_CHECK(igraph_vector_ptr_init(&parents, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_ptr_destroy_all, &parents); igraph_vector_ptr_set_item_destructor(&parents, (igraph_finally_func_t*)igraph_vector_destroy); for (i = 0; i < no_of_nodes; i++) { igraph_vector_t* parent_vec; parent_vec = igraph_Calloc(1, igraph_vector_t); if (parent_vec == 0) IGRAPH_ERROR("cannot run igraph_get_all_shortest_paths", IGRAPH_ENOMEM); IGRAPH_CHECK(igraph_vector_init(parent_vec, 0)); VECTOR(parents)[i] = parent_vec; } /* distance of each vertex from the root */ IGRAPH_VECTOR_INIT_FINALLY(&dists, no_of_nodes); igraph_vector_fill(&dists, -1.0); /* order lists the order of vertices in which they were found during * the traversal */ IGRAPH_VECTOR_INIT_FINALLY(&order, 0); /* boolean array to mark whether a given vertex is a target or not */ is_target = igraph_Calloc(no_of_nodes, unsigned char); if (is_target == 0) IGRAPH_ERROR("Can't calculate shortest paths", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, is_target); /* two-way heap storing vertices and distances */ IGRAPH_CHECK(igraph_2wheap_init(&Q, no_of_nodes)); IGRAPH_FINALLY(igraph_2wheap_destroy, &Q); /* lazy adjacency edge list to query neighbours efficiently */ IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, mode)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); /* Mark the vertices we need to reach */ IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); to_reach=IGRAPH_VIT_SIZE(vit); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { if (!is_target[ (long int) IGRAPH_VIT_GET(vit) ]) { is_target[ (long int) IGRAPH_VIT_GET(vit) ] = 1; } else { to_reach--; /* this node was given multiple times */ } } igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); VECTOR(dists)[(long int)from] = 0.0; /* zero distance */ igraph_2wheap_push_with_index(&Q, from, 0); while (!igraph_2wheap_empty(&Q) && to_reach > 0) { long int nlen, minnei=igraph_2wheap_max_index(&Q); igraph_real_t mindist=-igraph_2wheap_delete_max(&Q); igraph_vector_t *neis; IGRAPH_ALLOW_INTERRUPTION(); /* printf("Reached vertex %ld, is_target[%ld] = %d, %ld to go\n", minnei, minnei, (int)is_target[minnei], to_reach - is_target[minnei]); */ if (is_target[minnei]) { is_target[minnei] = 0; to_reach--; } /* Mark that we have reached this vertex */ IGRAPH_CHECK(igraph_vector_push_back(&order, minnei)); /* Now check all neighbors of 'minnei' for a shorter path */ neis=igraph_lazy_inclist_get(&inclist, (igraph_integer_t) minnei); nlen=igraph_vector_size(neis); for (i=0; i 0) { /* This is an alternative path with exactly the same length. * Note that we consider this case only if the edge via which we * reached the node has a nonzero weight; otherwise we could create * infinite loops in undirected graphs by traversing zero-weight edges * back-and-forth */ parent_vec = (igraph_vector_t*)VECTOR(parents)[tto]; IGRAPH_CHECK(igraph_vector_push_back(parent_vec, minnei)); } else if (altdist < curdist) { /* This is a shorter path */ VECTOR(dists)[tto] = altdist; parent_vec = (igraph_vector_t*)VECTOR(parents)[tto]; igraph_vector_clear(parent_vec); IGRAPH_CHECK(igraph_vector_push_back(parent_vec, minnei)); IGRAPH_CHECK(igraph_2wheap_modify(&Q, tto, -altdist)); } } } /* !igraph_2wheap_empty(&Q) */ if (to_reach > 0) IGRAPH_WARNING("Couldn't reach some vertices"); /* we don't need these anymore */ igraph_lazy_inclist_destroy(&inclist); igraph_2wheap_destroy(&Q); IGRAPH_FINALLY_CLEAN(2); /* printf("Order:\n"); igraph_vector_print(&order); printf("Parent vertices:\n"); for (i = 0; i < no_of_nodes; i++) { if (igraph_vector_size(VECTOR(parents)[i]) > 0) { printf("[%ld]: ", (long int)i); igraph_vector_print(VECTOR(parents)[i]); } } */ if (nrgeo) { IGRAPH_CHECK(igraph_vector_resize(nrgeo, no_of_nodes)); igraph_vector_null(nrgeo); /* Theoretically, we could calculate nrgeo in parallel with the traversal. * However, that way we would have to check whether nrgeo is null or not * every time we want to update some element in nrgeo. Since we need the * order vector anyway for building the final result, we could just as well * build nrgeo here. */ VECTOR(*nrgeo)[(long int)from] = 1; n = igraph_vector_size(&order); for (i = 1; i < n; i++) { long int node, j, k; igraph_vector_t *parent_vec; node = (long int)VECTOR(order)[i]; /* now, take the parent vertices */ parent_vec = (igraph_vector_t*)VECTOR(parents)[node]; k = igraph_vector_size(parent_vec); for (j = 0; j < k; j++) { VECTOR(*nrgeo)[node] += VECTOR(*nrgeo)[(long int)VECTOR(*parent_vec)[j]]; } } } if (res) { igraph_vector_t *path, *paths_index, *parent_vec; igraph_stack_t stack; long int j, node; /* a shortest path from the starting vertex to vertex i can be * obtained by calculating the shortest paths from the "parents" * of vertex i in the traversal. Knowing which of the vertices * are "targets" (see is_target), we can collect for which other * vertices do we need to calculate the shortest paths. We reuse * is_target for that; is_target = 0 means that we don't need the * vertex, is_target = 1 means that the vertex is a target (hence * we need it), is_target = 2 means that the vertex is not a target * but it stands between a shortest path between the root and one * of the targets */ if (igraph_vs_is_all(&to)) { memset(is_target, 1, sizeof(unsigned char) * (size_t) no_of_nodes); } else { memset(is_target, 0, sizeof(unsigned char) * (size_t) no_of_nodes); IGRAPH_CHECK(igraph_stack_init(&stack, 0)); IGRAPH_FINALLY(igraph_stack_destroy, &stack); /* Add the target vertices to the queue */ IGRAPH_CHECK(igraph_vit_create(graph, to, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); for (IGRAPH_VIT_RESET(vit); !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit)) { i = (long int) IGRAPH_VIT_GET(vit); if (!is_target[i]) { is_target[i] = 1; IGRAPH_CHECK(igraph_stack_push(&stack, i)); } } igraph_vit_destroy(&vit); IGRAPH_FINALLY_CLEAN(1); while (!igraph_stack_empty(&stack)) { /* For each parent of node i, get its parents */ igraph_real_t el=igraph_stack_pop(&stack); parent_vec = (igraph_vector_t*)VECTOR(parents)[(long int) el]; i = igraph_vector_size(parent_vec); for (j = 0; j < i; j++) { /* For each parent, check if it's already in the stack. * If not, push it and mark it in is_target */ n = (long int) VECTOR(*parent_vec)[j]; if (!is_target[n]) { is_target[n] = 2; IGRAPH_CHECK(igraph_stack_push(&stack, n)); } } } igraph_stack_destroy(&stack); IGRAPH_FINALLY_CLEAN(1); } /* now, reconstruct the shortest paths from the parent list in the * order we've found the nodes during the traversal. * dists is being re-used as a vector where element i tells the * index in res where the shortest paths leading to vertex i * start, plus one (so that zero means that there are no paths * for a given vertex). */ paths_index = &dists; n = igraph_vector_size(&order); igraph_vector_null(paths_index); /* clear the paths vector */ igraph_vector_ptr_clear(res); igraph_vector_ptr_set_item_destructor(res, (igraph_finally_func_t*)igraph_vector_destroy); /* by definition, the shortest path leading to the starting vertex * consists of the vertex itself only */ path = igraph_Calloc(1, igraph_vector_t); if (path == 0) IGRAPH_ERROR("cannot run igraph_get_all_shortest_paths_dijkstra", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, path); IGRAPH_CHECK(igraph_vector_init(path, 1)); IGRAPH_CHECK(igraph_vector_ptr_push_back(res, path)); IGRAPH_FINALLY_CLEAN(1); /* ownership of path passed to res */ VECTOR(*path)[0] = from; VECTOR(*paths_index)[(long int)from] = 1; for (i = 1; i < n; i++) { long int m, path_count; igraph_vector_t *parent_path; node = (long int) VECTOR(order)[i]; /* if we don't need the shortest paths for this node (because * it is not standing in a shortest path between the source * node and any of the target nodes), skip it */ if (!is_target[node]) continue; IGRAPH_ALLOW_INTERRUPTION(); /* we are calculating the shortest paths of node now. */ /* first, we update the paths_index */ path_count = igraph_vector_ptr_size(res); VECTOR(*paths_index)[node] = path_count+1; /* res_end = (igraph_vector_t*)&(VECTOR(*res)[path_count]); */ /* now, take the parent vertices */ parent_vec = (igraph_vector_t*)VECTOR(parents)[node]; m = igraph_vector_size(parent_vec); /* printf("Calculating shortest paths to vertex %ld\n", node); printf("Parents are: "); igraph_vector_print(parent_vec); */ for (j = 0; j < m; j++) { /* for each parent, copy the shortest paths leading to that parent * and add the current vertex in the end */ long int parent_node = (long int) VECTOR(*parent_vec)[j]; long int parent_path_idx = (long int) VECTOR(*paths_index)[parent_node] - 1; /* printf(" Considering parent: %ld\n", parent_node); printf(" Paths to parent start at index %ld in res\n", parent_path_idx); */ assert(parent_path_idx >= 0); for (; parent_path_idx < path_count; parent_path_idx++) { parent_path = (igraph_vector_t*)VECTOR(*res)[parent_path_idx]; if (igraph_vector_tail(parent_path) != parent_node) break; path = igraph_Calloc(1, igraph_vector_t); if (path == 0) IGRAPH_ERROR("cannot run igraph_get_all_shortest_paths_dijkstra", IGRAPH_ENOMEM); IGRAPH_FINALLY(igraph_free, path); IGRAPH_CHECK(igraph_vector_copy(path, parent_path)); IGRAPH_CHECK(igraph_vector_ptr_push_back(res, path)); IGRAPH_FINALLY_CLEAN(1); /* ownership of path passed to res */ IGRAPH_CHECK(igraph_vector_push_back(path, node)); } } } /* remove the destructor from the path vector */ igraph_vector_ptr_set_item_destructor(res, 0); /* free those paths from the result vector which we won't need */ n = igraph_vector_ptr_size(res); j = 0; for (i = 0; i < n; i++) { igraph_real_t tmp; path = (igraph_vector_t*)VECTOR(*res)[i]; tmp=igraph_vector_tail(path); if (is_target[(long int)tmp] == 1) { /* we need this path, keep it */ VECTOR(*res)[j] = path; j++; } else { /* we don't need this path, free it */ igraph_vector_destroy(path); free(path); } } IGRAPH_CHECK(igraph_vector_ptr_resize(res, j)); /* sort the paths by the target vertices */ igraph_vector_ptr_sort(res, igraph_i_vector_tail_cmp); } /* free the allocated memory */ igraph_vector_destroy(&order); igraph_Free(is_target); igraph_vector_destroy(&dists); igraph_vector_ptr_destroy_all(&parents); IGRAPH_FINALLY_CLEAN(4); return 0; } /** * \function igraph_shortest_paths_bellman_ford * Weighted shortest paths from some sources allowing negative weights. * * This function is the Bellman-Ford algorithm to find the weighted * shortest paths to all vertices from a single source. (It is run * independently for the given sources.). If there are no negative * weights, you are better off with \ref igraph_shortest_paths_dijkstra() . * * \param graph The input graph, can be directed. * \param res The result, a matrix. A pointer to an initialized matrix * should be passed here, the matrix will be resized if needed. * Each row contains the distances from a single source, to all * vertices in the graph, in the order of vertex ids. For unreachable * vertices the matrix contains \c IGRAPH_INFINITY. * \param from The source vertices. * \param weights The edge weights. There mustn't be any closed loop in * the graph that has a negative total weight (since this would allow * us to decrease the weight of any path containing at least a single * vertex of this loop infinitely). If this is a null pointer, then the * unweighted version, \ref igraph_shortest_paths() is called. * \param mode For directed graphs; whether to follow paths along edge * directions (\c IGRAPH_OUT), or the opposite (\c IGRAPH_IN), or * ignore edge directions completely (\c IGRAPH_ALL). It is ignored * for undirected graphs. * \return Error code. * * Time complexity: O(s*|E|*|V|), where |V| is the number of * vertices, |E| the number of edges and s the number of sources. * * \sa \ref igraph_shortest_paths() for a faster unweighted version * or \ref igraph_shortest_paths_dijkstra() if you do not have negative * edge weights. * * \example examples/simple/bellman_ford.c */ int igraph_shortest_paths_bellman_ford(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, const igraph_vector_t *weights, igraph_neimode_t mode) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_lazy_inclist_t inclist; long int i,j,k; long int no_of_from, no_of_to; igraph_dqueue_t Q; igraph_vector_t clean_vertices; igraph_vector_t num_queued; igraph_vit_t fromvit, tovit; igraph_real_t my_infinity=IGRAPH_INFINITY; igraph_bool_t all_to; igraph_vector_t dist; /* - speedup: a vertex is marked clean if its distance from the source did not change during the last phase. Neighbors of a clean vertex are not relaxed again, since it would mean no change in the shortest path values. Dirty vertices are queued. Negative loops can be detected by checking whether a vertex has been queued at least n times. */ if (!weights) { return igraph_shortest_paths(graph, res, from, to, mode); } if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Weight vector length does not match", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vit_create(graph, from, &fromvit)); IGRAPH_FINALLY(igraph_vit_destroy, &fromvit); no_of_from=IGRAPH_VIT_SIZE(fromvit); IGRAPH_DQUEUE_INIT_FINALLY(&Q, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&clean_vertices, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&num_queued, no_of_nodes); IGRAPH_CHECK(igraph_lazy_inclist_init(graph, &inclist, mode)); IGRAPH_FINALLY(igraph_lazy_inclist_destroy, &inclist); if ( (all_to=igraph_vs_is_all(&to)) ) { no_of_to=no_of_nodes; } else { IGRAPH_CHECK(igraph_vit_create(graph, to, &tovit)); IGRAPH_FINALLY(igraph_vit_destroy, &tovit); no_of_to=IGRAPH_VIT_SIZE(tovit); } IGRAPH_VECTOR_INIT_FINALLY(&dist, no_of_nodes); IGRAPH_CHECK(igraph_matrix_resize(res, no_of_from, no_of_to)); for (IGRAPH_VIT_RESET(fromvit), i=0; !IGRAPH_VIT_END(fromvit); IGRAPH_VIT_NEXT(fromvit), i++) { long int source=IGRAPH_VIT_GET(fromvit); igraph_vector_fill(&dist, my_infinity); VECTOR(dist)[source] = 0; igraph_vector_null(&clean_vertices); igraph_vector_null(&num_queued); /* Fill the queue with vertices to be checked */ for (j=0; j no_of_nodes) IGRAPH_ERROR("cannot run Bellman-Ford algorithm", IGRAPH_ENEGLOOP); /* If we cannot get to j in finite time yet, there is no need to relax * its edges */ if (!IGRAPH_FINITE(VECTOR(dist)[j])) continue; neis = igraph_lazy_inclist_get(&inclist, (igraph_integer_t) j); nlen = igraph_vector_size(neis); for (k=0; k VECTOR(dist)[j] + VECTOR(*weights)[nei]) { /* relax the edge */ VECTOR(dist)[target] = VECTOR(dist)[j] + VECTOR(*weights)[nei]; if (VECTOR(clean_vertices)[target]) { VECTOR(clean_vertices)[target] = 0; IGRAPH_CHECK(igraph_dqueue_push(&Q, target)); } } } } /* Copy it to the result */ if (all_to) { igraph_matrix_set_row(res, &dist, i); } else { for (IGRAPH_VIT_RESET(tovit), j=0; !IGRAPH_VIT_END(tovit); IGRAPH_VIT_NEXT(tovit), j++) { long int v=IGRAPH_VIT_GET(tovit); MATRIX(*res, i, j) = VECTOR(dist)[v]; } } } igraph_vector_destroy(&dist); IGRAPH_FINALLY_CLEAN(1); if (!all_to) { igraph_vit_destroy(&tovit); IGRAPH_FINALLY_CLEAN(1); } igraph_vit_destroy(&fromvit); igraph_dqueue_destroy(&Q); igraph_vector_destroy(&clean_vertices); igraph_vector_destroy(&num_queued); igraph_lazy_inclist_destroy(&inclist); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_shortest_paths_johnson * Calculate shortest paths from some sources using Johnson's algorithm. * * See Wikipedia at http://en.wikipedia.org/wiki/Johnson's_algorithm * for Johnson's algorithm. This algorithm works even if the graph * contains negative edge weights, and it is worth using it if we * calculate the shortest paths from many sources. * * If no edge weights are supplied, then the unweighted * version, \ref igraph_shortest_paths() is called. * * If all the supplied edge weights are non-negative, * then Dijkstra's algorithm is used by calling * \ref igraph_shortest_paths_dijkstra(). * * \param graph The input graph, typically it is directed. * \param res Pointer to an initialized matrix, the result will be * stored here, one line for each source vertex, one column for each * target vertex. * \param from The source vertices. * \param to The target vertices. It is not allowed to include a * vertex twice or more. * \param weights Optional edge weights. If it is a null-pointer, then * the unweighted breadth-first search based \ref * igraph_shortest_paths() will be called. * \return Error code. * * Time complexity: O(s|V|log|V|+|V||E|), |V| and |E| are the number * of vertices and edges, s is the number of source vertices. * * \sa \ref igraph_shortest_paths() for a faster unweighted version * or \ref igraph_shortest_paths_dijkstra() if you do not have negative * edge weights, \ref igraph_shortest_paths_bellman_ford() if you only * need to calculate shortest paths from a couple of sources. */ int igraph_shortest_paths_johnson(const igraph_t *graph, igraph_matrix_t *res, const igraph_vs_t from, const igraph_vs_t to, const igraph_vector_t *weights) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_t newgraph; igraph_vector_t edges, newweights; igraph_matrix_t bfres; long int i, ptr; long int nr, nc; igraph_vit_t fromvit; /* If no weights, then we can just run the unweighted version */ if (!weights) { return igraph_shortest_paths(graph, res, from, to, IGRAPH_OUT); } if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Weight vector length does not match", IGRAPH_EINVAL); } /* If no negative weights, then we can run Dijkstra's algorithm */ if (igraph_vector_min(weights) >= 0) { return igraph_shortest_paths_dijkstra(graph, res, from, to, weights, IGRAPH_OUT); } if (!igraph_is_directed(graph)) { IGRAPH_ERROR("Johnson's shortest path: undirected graph and negative weight", IGRAPH_EINVAL); } /* ------------------------------------------------------------ */ /* -------------------- Otherwise proceed --------------------- */ IGRAPH_MATRIX_INIT_FINALLY(&bfres, 0, 0); IGRAPH_VECTOR_INIT_FINALLY(&newweights, 0); IGRAPH_CHECK(igraph_empty(&newgraph, (igraph_integer_t) no_of_nodes+1, igraph_is_directed(graph))); IGRAPH_FINALLY(igraph_destroy, &newgraph); /* Add a new node to the graph, plus edges from it to all the others. */ IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges*2 + no_of_nodes*2); igraph_get_edgelist(graph, &edges, /*bycol=*/ 0); igraph_vector_resize(&edges, no_of_edges * 2 + no_of_nodes * 2); for (i=0, ptr=no_of_edges*2; i * * An undirected graph only has mutual edges, by definition. * * * Edge multiplicity is not considered here, e.g. if there are two * (A,B) edges and one (B,A) edge, then all three are considered to be * mutual. * * \param graph The input graph. * \param res Pointer to an initialized vector, the result is stored * here. * \param es The sequence of edges to check. Supply * igraph_ess_all() for all edges, see \ref * igraph_ess_all(). * \return Error code. * * Time complexity: O(n log(d)), n is the number of edges supplied, d * is the maximum in-degree of the vertices that are targets of the * supplied edges. An upper limit of the time complexity is O(n log(|E|)), * |E| is the number of edges in the graph. */ int igraph_is_mutual(igraph_t *graph, igraph_vector_bool_t *res, igraph_es_t es) { igraph_eit_t eit; igraph_lazy_adjlist_t adjlist; long int i; /* How many edges do we have? */ IGRAPH_CHECK(igraph_eit_create(graph, es, &eit)); IGRAPH_FINALLY(igraph_eit_destroy, &eit); IGRAPH_CHECK(igraph_vector_bool_resize(res, IGRAPH_EIT_SIZE(eit))); /* An undirected graph has mutual edges by definition, res is already properly resized */ if (! igraph_is_directed(graph)) { igraph_vector_bool_fill(res, 1); igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(1); return 0; } IGRAPH_CHECK(igraph_lazy_adjlist_init(graph, &adjlist, IGRAPH_OUT, IGRAPH_DONT_SIMPLIFY)); IGRAPH_FINALLY(igraph_lazy_adjlist_destroy, &adjlist); for (i=0; ! IGRAPH_EIT_END(eit); i++, IGRAPH_EIT_NEXT(eit)) { long int edge=IGRAPH_EIT_GET(eit); long int from=IGRAPH_FROM(graph, edge); long int to=IGRAPH_TO(graph, edge); /* Check whether there is a to->from edge, search for from in the out-list of to. We don't search an empty vector, because vector_binsearch seems to have a bug with this. */ igraph_vector_t *neis=igraph_lazy_adjlist_get(&adjlist, (igraph_integer_t) to); if (igraph_vector_empty(neis)) { VECTOR(*res)[i]=0; } else { VECTOR(*res)[i]=igraph_vector_binsearch2(neis, from); } } igraph_lazy_adjlist_destroy(&adjlist); igraph_eit_destroy(&eit); IGRAPH_FINALLY_CLEAN(2); return 0; } int igraph_i_avg_nearest_neighbor_degree_weighted(const igraph_t *graph, igraph_vs_t vids, igraph_vector_t *knn, igraph_vector_t *knnk, const igraph_vector_t *weights); int igraph_i_avg_nearest_neighbor_degree_weighted(const igraph_t *graph, igraph_vs_t vids, igraph_vector_t *knn, igraph_vector_t *knnk, const igraph_vector_t *weights) { long int no_of_nodes = igraph_vcount(graph); igraph_vector_t neis; long int i, j, no_vids; igraph_vit_t vit; igraph_vector_t my_knn_v, *my_knn=knn; igraph_vector_t deg; long int maxdeg; igraph_integer_t maxdeg2; igraph_vector_t deghist; igraph_real_t mynan=IGRAPH_NAN; if (igraph_vector_size(weights) != igraph_ecount(graph)) { IGRAPH_ERROR("Invalid weight vector size", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); no_vids=IGRAPH_VIT_SIZE(vit); if (!knn) { IGRAPH_VECTOR_INIT_FINALLY(&my_knn_v, no_vids); my_knn=&my_knn_v; } else { IGRAPH_CHECK(igraph_vector_resize(knn, no_vids)); } IGRAPH_VECTOR_INIT_FINALLY(°, no_of_nodes); IGRAPH_CHECK(igraph_strength(graph, °, igraph_vss_all(), /*mode=*/ IGRAPH_ALL, /*loops=*/ 1, weights)); IGRAPH_CHECK(igraph_maxdegree(graph, &maxdeg2, igraph_vss_all(), /*mode=*/ IGRAPH_ALL, /*loops=*/ 1)); maxdeg=maxdeg2; IGRAPH_VECTOR_INIT_FINALLY(&neis, maxdeg); igraph_vector_resize(&neis, 0); if (knnk) { IGRAPH_CHECK(igraph_vector_resize(knnk, maxdeg)); igraph_vector_null(knnk); IGRAPH_VECTOR_INIT_FINALLY(°hist, maxdeg); } for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { igraph_real_t sum=0.0; long int v=IGRAPH_VIT_GET(vit); long int nv; igraph_real_t str=VECTOR(deg)[v]; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) v, IGRAPH_ALL)); nv=igraph_vector_size(&neis); for (j=0; jFor isolate vertices \p knn is set to \c * IGRAPH_NAN. The same is done in \p knnk for vertex degrees that * don't appear in the graph. * * \param graph The input graph, it can be directed but the * directedness of the edges is ignored. * \param vids The vertices for which the calculation is performed. * \param knn Pointer to an initialized vector, the result will be * stored here. It will be resized as needed. Supply a NULL pointer * here, if you only want to calculate \c knnk. * \param knnk Pointer to an initialized vector, the average nearest * neighbor degree in the function of vertex degree is stored * here. The first (zeroth) element is for degree one vertices, * etc. Supply a NULL pointer here if you don't want to calculate * this. * \param weights Optional edge weights. Supply a null pointer here * for the non-weighted version. If this is not a null pointer, then * the calculated quantity will be the sum of the strengths of the * neighbors of a given vertex (see \ref igraph_strength() ), divided * by the strength of the vertex itself. Note that the denominator is * \em not the unweighted degree of the vertex so the quantity is not * really an "average" in this case. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges. * * \example examples/simple/igraph_knn.c */ int igraph_avg_nearest_neighbor_degree(const igraph_t *graph, igraph_vs_t vids, igraph_vector_t *knn, igraph_vector_t *knnk, const igraph_vector_t *weights) { long int no_of_nodes = igraph_vcount(graph); igraph_vector_t neis; long int i, j, no_vids; igraph_vit_t vit; igraph_vector_t my_knn_v, *my_knn=knn; igraph_vector_t deg; long int maxdeg; igraph_vector_t deghist; igraph_real_t mynan=IGRAPH_NAN; igraph_bool_t simple; IGRAPH_CHECK(igraph_is_simple(graph, &simple)); if (!simple) { IGRAPH_ERROR("Average nearest neighbor degree Works only with " "simple graphs", IGRAPH_EINVAL); } if (weights) { return igraph_i_avg_nearest_neighbor_degree_weighted(graph, vids, knn, knnk, weights); } IGRAPH_CHECK(igraph_vit_create(graph, vids, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); no_vids=IGRAPH_VIT_SIZE(vit); if (!knn) { IGRAPH_VECTOR_INIT_FINALLY(&my_knn_v, no_vids); my_knn=&my_knn_v; } else { IGRAPH_CHECK(igraph_vector_resize(knn, no_vids)); } IGRAPH_VECTOR_INIT_FINALLY(°, no_of_nodes); IGRAPH_CHECK(igraph_degree(graph, °, igraph_vss_all(), /*mode=*/ IGRAPH_ALL, /*loops*/ 1)); maxdeg=(long int) igraph_vector_max(°); IGRAPH_VECTOR_INIT_FINALLY(&neis, maxdeg); igraph_vector_resize(&neis, 0); if (knnk) { IGRAPH_CHECK(igraph_vector_resize(knnk, maxdeg)); igraph_vector_null(knnk); IGRAPH_VECTOR_INIT_FINALLY(°hist, maxdeg); } for (i=0; !IGRAPH_VIT_END(vit); IGRAPH_VIT_NEXT(vit), i++) { igraph_real_t sum=0.0; long int v=IGRAPH_VIT_GET(vit); long int nv=(long int) VECTOR(deg)[v]; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) v, IGRAPH_ALL)); for (j=0; j res) { res=mindist; from=source; to=minnei; } nodes_reached++; /* Now check all neighbors of 'minnei' for a shorter path */ neis=igraph_inclist_get(&inclist, minnei); nlen=igraph_vector_int_size(neis); for (j=0; j 0) last = (long int) igraph_vector_max(mapping); for (e=0; e last) { last = nfrom; } if (nto > last) { last = nto; } } no_new_vertices = last+1; IGRAPH_CHECK(igraph_create(&res, &edges, (igraph_integer_t) no_new_vertices, igraph_is_directed(graph))); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); IGRAPH_FINALLY(igraph_destroy, &res); IGRAPH_I_ATTRIBUTE_DESTROY(&res); IGRAPH_I_ATTRIBUTE_COPY(&res, graph, /*graph=*/ 1, /*vertex=*/ 0, /*edge=*/ 1); if (vattr) { long int i; igraph_vector_ptr_t merges; igraph_vector_t sizes; igraph_vector_t *vecs; vecs=igraph_Calloc(no_new_vertices, igraph_vector_t); if (!vecs) { IGRAPH_ERROR("Cannot combine attributes while contracting" " vertices", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, vecs); IGRAPH_CHECK(igraph_vector_ptr_init(&merges, no_new_vertices)); IGRAPH_FINALLY(igraph_i_simplify_free, &merges); IGRAPH_VECTOR_INIT_FINALLY(&sizes, no_new_vertices); for (i=0; i * It is simply the (normalized) Shannon entropy of the * incident edges' weights. D(i)=H(i)/log(k[i]), and * H(i) = -sum(p[i,j] log(p[i,j]), j=1..k[i]), * where p[i,j]=w[i,j]/sum(w[i,l], l=1..k[i]), k[i] is the (total) * degree of vertex i, and w[i,j] is the weight of the edge(s) between * vertex i and j. * \param graph The input graph, edge directions are ignored. * \param weights The edge weights, in the order of the edge ids, must * have appropriate length. * \param res An initialized vector, the results are stored here. * \param vids Vector with the vertex ids for which to calculate the * measure. * \return Error code. * * Time complexity: O(|V|+|E|), linear. * */ int igraph_diversity(igraph_t *graph, const igraph_vector_t *weights, igraph_vector_t *res, const igraph_vs_t vids) { int no_of_nodes=igraph_vcount(graph); int no_of_edges=igraph_ecount(graph); igraph_vector_t incident; igraph_vit_t vit; igraph_real_t s, ent, w; int i, j, k; if (!weights) { IGRAPH_ERROR("Edge weights must be given", IGRAPH_EINVAL); } if (igraph_vector_size(weights) != no_of_edges) { IGRAPH_ERROR("Invalid edge weight vector length", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(&incident, 10); if (igraph_vs_is_all(&vids)) { IGRAPH_CHECK(igraph_vector_resize(res, no_of_nodes)); for (i=0; i * In particular, the function checks whether all the degrees are non-negative. * For undirected graphs, it also checks whether the sum of degrees is even. * For directed graphs, the function checks whether the lengths of the two * degree vectors are equal and whether their sums are also equal. These are * known sufficient and necessary conditions for a degree sequence to be * valid. * * \param out_degrees an integer vector specifying the degree sequence for * undirected graphs or the out-degree sequence for directed graphs. * \param in_degrees an integer vector specifying the in-degrees of the * vertices for directed graphs. For undirected graphs, this must be null. * \param res pointer to a boolean variable, the result will be stored here * \return Error code. * * Time complexity: O(n), where n is the length of the degree sequence. */ int igraph_is_degree_sequence(const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res) { /* degrees must be non-negative */ if (igraph_vector_any_smaller(out_degrees, 0)) FAIL; if (in_degrees && igraph_vector_any_smaller(in_degrees, 0)) FAIL; if (in_degrees == 0) { /* sum of degrees must be even */ if (((long int)igraph_vector_sum(out_degrees) % 2) != 0) FAIL; } else { /* length of the two degree vectors must be equal */ if (igraph_vector_size(out_degrees) != igraph_vector_size(in_degrees)) FAIL; /* sum of in-degrees must be equal to sum of out-degrees */ if (igraph_vector_sum(out_degrees) != igraph_vector_sum(in_degrees)) FAIL; } SUCCEED; return 0; } int igraph_i_is_graphical_degree_sequence_undirected( const igraph_vector_t *degrees, igraph_bool_t *res); int igraph_i_is_graphical_degree_sequence_directed( const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res); /** * \function igraph_is_graphical_degree_sequence * Determines whether a sequence of integers can be a degree sequence of some * simple graph. * * * References: * * * Hakimi SL: On the realizability of a set of integers as degrees of the * vertices of a simple graph. J SIAM Appl Math 10:496-506, 1962. * * * PL Erdos, I Miklos and Z Toroczkai: A simple Havel-Hakimi type algorithm * to realize graphical degree sequences of directed graphs. The Electronic * Journal of Combinatorics 17(1):R66, 2010. * * \param out_degrees an integer vector specifying the degree sequence for * undirected graphs or the out-degree sequence for directed graphs. * \param in_degrees an integer vector specifying the in-degrees of the * vertices for directed graphs. For undirected graphs, this must be null. * \param res pointer to a boolean variable, the result will be stored here * \return Error code. * * Time complexity: O(n^2 log n) where n is the length of the degree sequence. */ int igraph_is_graphical_degree_sequence(const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res) { IGRAPH_CHECK(igraph_is_degree_sequence(out_degrees, in_degrees, res)); if (!*res) FAIL; if (igraph_vector_size(out_degrees) == 0) SUCCEED; if (in_degrees == 0) { return igraph_i_is_graphical_degree_sequence_undirected(out_degrees, res); } else { return igraph_i_is_graphical_degree_sequence_directed(out_degrees, in_degrees, res); } } int igraph_i_is_graphical_degree_sequence_undirected( const igraph_vector_t *degrees, igraph_bool_t *res) { igraph_vector_t work; igraph_integer_t degree; long int i, vcount; IGRAPH_CHECK(igraph_vector_copy(&work, degrees)); IGRAPH_FINALLY(igraph_vector_destroy, &work); vcount = igraph_vector_size(&work); *res = 0; while (vcount) { /* RFE: theoretically, a counting sort would be only O(n) here and not * O(n log n) since the degrees are bounded from above by n. I am not sure * whether it's worth the fuss, though, sort() in the C library is highly * optimized */ igraph_vector_sort(&work); if (VECTOR(work)[0] < 0) break; degree = (igraph_integer_t) igraph_vector_pop_back(&work); vcount--; if (degree == 0) { *res = 1; break; } if (degree > vcount) break; for (i = vcount-degree; i < vcount; i++) { VECTOR(work)[i]--; } } igraph_vector_destroy(&work); IGRAPH_FINALLY_CLEAN(1); return 0; } typedef struct { igraph_vector_t* first; igraph_vector_t* second; } igraph_i_qsort_dual_vector_cmp_data_t; int igraph_i_qsort_dual_vector_cmp_asc(void* data, const void *p1, const void *p2) { igraph_i_qsort_dual_vector_cmp_data_t* sort_data = (igraph_i_qsort_dual_vector_cmp_data_t*)data; long int index1 = *((long int*)p1); long int index2 = *((long int*)p2); if (VECTOR(*sort_data->first)[index1] < VECTOR(*sort_data->first)[index2]) return -1; if (VECTOR(*sort_data->first)[index1] > VECTOR(*sort_data->first)[index2]) return 1; if (VECTOR(*sort_data->second)[index1] < VECTOR(*sort_data->second)[index2]) return -1; if (VECTOR(*sort_data->second)[index1] > VECTOR(*sort_data->second)[index2]) return 1; return 0; } int igraph_i_is_graphical_degree_sequence_directed( const igraph_vector_t *out_degrees, const igraph_vector_t *in_degrees, igraph_bool_t *res) { igraph_vector_t work_in; igraph_vector_t work_out; igraph_vector_long_t out_vertices; igraph_vector_long_t index_array; long int i, vcount, u, v, degree; long int index_array_unused_prefix_length, nonzero_indegree_count; igraph_i_qsort_dual_vector_cmp_data_t sort_data; IGRAPH_CHECK(igraph_vector_copy(&work_in, in_degrees)); IGRAPH_FINALLY(igraph_vector_destroy, &work_in); IGRAPH_CHECK(igraph_vector_copy(&work_out, out_degrees)); IGRAPH_FINALLY(igraph_vector_destroy, &work_in); IGRAPH_CHECK(igraph_vector_long_init(&out_vertices, 0)); IGRAPH_FINALLY(igraph_vector_long_destroy, &out_vertices); vcount = igraph_vector_size(&work_out); IGRAPH_CHECK(igraph_vector_long_reserve(&out_vertices, vcount)); IGRAPH_CHECK(igraph_vector_long_init(&index_array, vcount)); IGRAPH_FINALLY(igraph_vector_long_destroy, &index_array); /* Set up the auxiliary struct for sorting */ sort_data.first = &work_in; sort_data.second = &work_out; /* Fill the index array. This will contain the indices of the "active" vertices, * i.e. those that have a non-zero in- or out-degree */ nonzero_indegree_count = 0; for (i = 0; i < vcount; i++) { if (VECTOR(work_in)[i] > 0) { VECTOR(index_array)[i] = i; nonzero_indegree_count++; } if (VECTOR(work_out)[i] > 0) { IGRAPH_CHECK(igraph_vector_long_push_back(&out_vertices, i)); } } *res = 0; index_array_unused_prefix_length = 0; while (!igraph_vector_long_empty(&out_vertices)) { /* Find a vertex with non-zero out-degree. */ u = igraph_vector_long_pop_back(&out_vertices); /* printf("Using vertex %ld\n", (long int)u); printf(" Degree vectors:\n "); igraph_vector_print(&work_out); printf(" "); igraph_vector_print(&work_in); */ /* Remember the degree of u and clear the degree itself */ degree = (long int) VECTOR(work_out)[u]; VECTOR(work_out)[u] = 0; /* printf(" Out-degree: %ld\n", (long int)degree); */ /* Is the degree larger than the number of vertices with nonzero in-degree? * (Make sure that u is excluded from the vertices with nonzero in-degree). */ if (degree > nonzero_indegree_count - (VECTOR(work_in)[u] > 0 ? 1 : 0)) { /* Put u back into the queue to detect the failure even if u was the * last vertex. See Github bug #851 */ IGRAPH_CHECK(igraph_vector_long_push_back(&out_vertices, u)); break; } /* Find the prefix of index_array that consists solely of vertices with * zero indegree. We don't need to sort these */ while (index_array_unused_prefix_length < vcount && VECTOR(work_in)[VECTOR(index_array)[index_array_unused_prefix_length]] == 0) { index_array_unused_prefix_length++; nonzero_indegree_count--; } /* Sort work_in first and then sort work_out for equal indegrees only. This * is done by sorting an index vector first; indexing work_out and work_in by * the sorted index vector would then give the sorted order of these vectors. */ igraph_qsort_r(VECTOR(index_array) + index_array_unused_prefix_length, (size_t) nonzero_indegree_count, sizeof(long int), &sort_data, igraph_i_qsort_dual_vector_cmp_asc); /* printf(" Sorted index array:\n "); igraph_vector_long_print(&index_array); */ /* Create edges from u to the vertices with the largest in-degrees */ i = vcount; while (degree > 0) { v = VECTOR(index_array)[--i]; if (u == v) { /* Avoid creating a loop edge */ continue; } VECTOR(work_in)[v]--; /* printf(" Created edge from %ld to %ld, in-degree is now %ld\n", (long int)u, (long int)v, (long int)VECTOR(work_in)[v]); */ degree--; } } if (igraph_vector_long_empty(&out_vertices)) { /* No more vertices with non-zero outdegree, so we were successful */ *res = 1; } igraph_vector_long_destroy(&index_array); igraph_vector_long_destroy(&out_vertices); igraph_vector_destroy(&work_out); igraph_vector_destroy(&work_in); IGRAPH_FINALLY_CLEAN(4); return IGRAPH_SUCCESS; } #undef SUCCEED #undef FAIL igraph/src/foreign-ncol-parser.y0000644000175100001440000001002013430770201016365 0ustar hornikusers/* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include "foreign-ncol-header.h" #include "foreign-ncol-parser.h" #define yyscan_t void* int igraph_ncol_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_ncol_yyerror(YYLTYPE* locp, igraph_i_ncol_parsedata_t *context, const char *s); char *igraph_ncol_yyget_text (yyscan_t yyscanner ); int igraph_ncol_yyget_leng (yyscan_t yyscanner ); igraph_real_t igraph_ncol_get_number(const char *str, long int len); #define scanner context->scanner %} %pure-parser %output="y.tab.c" %name-prefix="igraph_ncol_yy" %defines %locations %error-verbose %parse-param { igraph_i_ncol_parsedata_t* context } %lex-param { void *scanner } %union { long int edgenum; double weightnum; } %type edgeid %type weight %token ALNUM %token NEWLINE %token ERROR %% input : /* empty */ | input NEWLINE | input edge ; edge : edgeid edgeid NEWLINE { igraph_vector_push_back(context->vector, $1); igraph_vector_push_back(context->vector, $2); igraph_vector_push_back(context->weights, 0); } | edgeid edgeid weight NEWLINE { igraph_vector_push_back(context->vector, $1); igraph_vector_push_back(context->vector, $2); igraph_vector_push_back(context->weights, $3); context->has_weights = 1; } ; edgeid : ALNUM { igraph_trie_get2(context->trie, igraph_ncol_yyget_text(scanner), igraph_ncol_yyget_leng(scanner), &$$); }; weight : ALNUM { $$=igraph_ncol_get_number(igraph_ncol_yyget_text(scanner), igraph_ncol_yyget_leng(scanner)); } ; %% int igraph_ncol_yyerror(YYLTYPE* locp, igraph_i_ncol_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in NCOL file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_ncol_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } igraph/src/rinterface.h0000644000175100001440000000202013431000472014610 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010 Gabor Csardi Rue de l'Industrie 5, Lausanne 1005, Switzerland This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "uuid/uuid.h" #define R_IGRAPH_TYPE_VERSION "0.8.0" #define R_IGRAPH_VERSION_VAR ".__igraph_version__." SEXP R_igraph_add_env(SEXP graph); igraph/src/vector.pmt0000644000175100001440000021704313430770206014366 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_memory.h" #include "igraph_error.h" #include "igraph_random.h" #include "igraph_qsort.h" #include #include /* memcpy & co. */ #include #include /* va_start & co */ #include /** * \ingroup vector * \section about_igraph_vector_t_objects About \type igraph_vector_t objects * * The \type igraph_vector_t data type is a simple and efficient * interface to arrays containing numbers. It is something * similar as (but much simpler than) the \type vector template * in the C++ standard library. * * Vectors are used extensively in \a igraph, all * functions which expect or return a list of numbers use * igraph_vector_t to achieve this. * * The \type igraph_vector_t type usually uses * O(n) space * to store n elements. Sometimes it * uses more, this is because vectors can shrink, but even if they * shrink, the current implementation does not free a single bit of * memory. * * The elements in an \type igraph_vector_t * object are indexed from zero, we follow the usual C convention * here. * * The elements of a vector always occupy a single block of * memory, the starting address of this memory block can be queried * with the \ref VECTOR macro. This way, vector objects can be used * with standard mathematical libraries, like the GNU Scientific * Library. */ /** * \ingroup vector * \section igraph_vector_constructors_and_destructors Constructors and * Destructors * * \type igraph_vector_t objects have to be initialized before using * them, this is analogous to calling a constructor on them. There are a * number of \type igraph_vector_t constructors, for your * convenience. \ref igraph_vector_init() is the basic constructor, it * creates a vector of the given length, filled with zeros. * \ref igraph_vector_copy() creates a new identical copy * of an already existing and initialized vector. \ref * igraph_vector_init_copy() creates a vector by copying a regular C array. * \ref igraph_vector_init_seq() creates a vector containing a regular * sequence with increment one. * * \ref igraph_vector_view() is a special constructor, it allows you to * handle a regular C array as a \type vector without copying * its elements. * * * If a \type igraph_vector_t object is not needed any more, it * should be destroyed to free its allocated memory by calling the * \type igraph_vector_t destructor, \ref igraph_vector_destroy(). * * Note that vectors created by \ref igraph_vector_view() are special, * you mustn't call \ref igraph_vector_destroy() on these. */ /** * \ingroup vector * \function igraph_vector_init * \brief Initializes a vector object (constructor). * * * Every vector needs to be initialized before it can be used, and * there are a number of initialization functions or otherwise called * constructors. This function constructs a vector of the given size and * initializes each entry to 0. Note that \ref igraph_vector_null() can be * used to set each element of a vector to zero. However, if you want a * vector of zeros, it is much faster to use this function than to create a * vector and then invoke \ref igraph_vector_null(). * * * Every vector object initialized by this function should be * destroyed (ie. the memory allocated for it should be freed) when it * is not needed anymore, the \ref igraph_vector_destroy() function is * responsible for this. * \param v Pointer to a not yet initialized vector object. * \param size The size of the vector. * \return error code: * \c IGRAPH_ENOMEM if there is not enough memory. * * Time complexity: operating system dependent, the amount of * \quote time \endquote required to allocate * O(n) elements, * n is the number of elements. */ int FUNCTION(igraph_vector,init) (TYPE(igraph_vector)* v, int long size) { long int alloc_size= size > 0 ? size : 1; if (size < 0) { size=0; } v->stor_begin=igraph_Calloc(alloc_size, BASE); if (v->stor_begin==0) { IGRAPH_ERROR("cannot init vector", IGRAPH_ENOMEM); } v->stor_end=v->stor_begin + alloc_size; v->end=v->stor_begin+size; return 0; } /** * \ingroup vector * \function igraph_vector_view * \brief Handle a regular C array as a \type igraph_vector_t. * * * This is a special \type igraph_vector_t constructor. It allows to * handle a regular C array as a \type igraph_vector_t temporarily. * Be sure that you \em don't ever call the destructor (\ref * igraph_vector_destroy()) on objects created by this constructor. * \param v Pointer to an uninitialized \type igraph_vector_t object. * \param data Pointer, the C array. It may not be \c NULL. * \param length The length of the C array. * \return Pointer to the vector object, the same as the * \p v parameter, for convenience. * * Time complexity: O(1) */ const TYPE(igraph_vector)*FUNCTION(igraph_vector,view) (const TYPE(igraph_vector) *v, const BASE *data, long int length) { TYPE(igraph_vector) *v2=(TYPE(igraph_vector)*)v; assert(data != 0); v2->stor_begin=(BASE*)data; v2->stor_end=(BASE*)data+length; v2->end=v2->stor_end; return v; } #ifndef BASE_COMPLEX /** * \ingroup vector * \function igraph_vector_init_real * \brief Create an \type igraph_vector_t from the parameters. * * * Because of how C and the C library handles variable length argument * lists, it is required that you supply real constants to this * function. This means that * \verbatim igraph_vector_t v; * igraph_vector_init_real(&v, 5, 1,2,3,4,5); \endverbatim * is an error at runtime and the results are undefined. This is * the proper way: * \verbatim igraph_vector_t v; * igraph_vector_init_real(&v, 5, 1.0,2.0,3.0,4.0,5.0); \endverbatim * \param v Pointer to an uninitialized \type igraph_vector_t object. * \param no Positive integer, the number of \type igraph_real_t * parameters to follow. * \param ... The elements of the vector. * \return Error code, this can be \c IGRAPH_ENOMEM * if there isn't enough memory to allocate the vector. * * \sa \ref igraph_vector_init_real_end(), \ref igraph_vector_init_int() for similar * functions. * * Time complexity: depends on the time required to allocate memory, * but at least O(n), the number of * elements in the vector. */ int FUNCTION(igraph_vector,init_real)(TYPE(igraph_vector) *v, int no, ...) { int i=0; va_list ap; IGRAPH_CHECK(FUNCTION(igraph_vector,init)(v, no)); va_start(ap, no); for (i=0; i * This constructor is similar to \ref igraph_vector_init_real(), the only * difference is that instead of giving the number of elements in the * vector, a special marker element follows the last real vector * element. * \param v Pointer to an uninitialized \type igraph_vector_t object. * \param endmark This element will signal the end of the vector. It * will \em not be part of the vector. * \param ... The elements of the vector. * \return Error code, \c IGRAPH_ENOMEM if there * isn't enough memory. * * \sa \ref igraph_vector_init_real() and \ref igraph_vector_init_int_end() for * similar functions. * * Time complexity: at least O(n) for * n elements plus the time * complexity of the memory allocation. */ int FUNCTION(igraph_vector,init_real_end)(TYPE(igraph_vector) *v, BASE endmark, ...) { int i=0, n=0; va_list ap; va_start(ap, endmark); while (1) { BASE num = (BASE) va_arg(ap, double); if (num == endmark) { break; } n++; } va_end(ap); IGRAPH_CHECK(FUNCTION(igraph_vector,init)(v,n)); IGRAPH_FINALLY(FUNCTION(igraph_vector,destroy), v); va_start(ap, endmark); for (i=0; i * This function is similar to \ref igraph_vector_init_real(), but it expects * \type int parameters. It is important that all parameters * should be of this type, otherwise the result of the function call * is undefined. * \param v Pointer to an uninitialized \type igraph_vector_t object. * \param no The number of \type int parameters to follow. * \param ... The elements of the vector. * \return Error code, \c IGRAPH_ENOMEM if there is * not enough memory. * \sa \ref igraph_vector_init_real() and igraph_vector_init_int_end(), these are * similar functions. * * Time complexity: at least O(n) for * n elements plus the time * complexity of the memory allocation. */ int FUNCTION(igraph_vector,init_int)(TYPE(igraph_vector) *v, int no, ...) { int i=0; va_list ap; IGRAPH_CHECK(FUNCTION(igraph_vector,init)(v, no)); va_start(ap, no); for (i=0; i * This constructor is similar to \ref igraph_vector_init_int(), the only * difference is that instead of giving the number of elements in the * vector, a special marker element follows the last real vector * element. * \param v Pointer to an uninitialized \type igraph_vector_t object. * \param endmark This element will signal the end of the vector. It * will \em not be part of the vector. * \param ... The elements of the vector. * \return Error code, \c IGRAPH_ENOMEM if there * isn't enough memory. * * \sa \ref igraph_vector_init_int() and \ref igraph_vector_init_real_end() for * similar functions. * * Time complexity: at least O(n) for * n elements plus the time * complexity of the memory allocation. */ int FUNCTION(igraph_vector_init,int_end)(TYPE(igraph_vector) *v, int endmark, ...) { int i=0, n=0; va_list ap; va_start(ap, endmark); while (1) { int num = va_arg(ap, int); if (num == endmark) { break; } n++; } va_end(ap); IGRAPH_CHECK(FUNCTION(igraph_vector,init)(v, n)); IGRAPH_FINALLY(FUNCTION(igraph_vector,destroy), v); va_start(ap, endmark); for (i=0; i * All vectors initialized by \ref igraph_vector_init() should be properly * destroyed by this function. A destroyed vector needs to be * reinitialized by \ref igraph_vector_init(), \ref igraph_vector_init_copy() or * another constructor. * \param v Pointer to the (previously initialized) vector object to * destroy. * * Time complexity: operating system dependent. */ void FUNCTION(igraph_vector,destroy) (TYPE(igraph_vector)* v) { assert(v != 0); if (v->stor_begin != 0) { igraph_Free(v->stor_begin); v->stor_begin = NULL; } } /** * \ingroup vector * \function igraph_vector_capacity * \brief Returns the allocated capacity of the vector * * Note that this might be different from the size of the vector (as * queried by \ref igraph_vector_size(), and specifies how many elements * the vector can hold, without reallocation. * \param v Pointer to the (previously initialized) vector object * to query. * \return The allocated capacity. * * \sa \ref igraph_vector_size(). * * Time complexity: O(1). */ long int FUNCTION(igraph_vector,capacity)(const TYPE(igraph_vector)*v) { return v->stor_end - v->stor_begin; } /** * \ingroup vector * \function igraph_vector_reserve * \brief Reserves memory for a vector. * * * \a igraph vectors are flexible, they can grow and * shrink. Growing * however occasionally needs the data in the vector to be copied. * In order to avoid this, you can call this function to reserve space for * future growth of the vector. * * * Note that this function does \em not change the size of the * vector. Let us see a small example to clarify things: if you * reserve space for 100 elements and the size of your * vector was (and still is) 60, then you can surely add additional 40 * elements to your vector before it will be copied. * \param v The vector object. * \param size The new \em allocated size of the vector. * \return Error code: * \c IGRAPH_ENOMEM if there is not enough memory. * * Time complexity: operating system dependent, should be around * O(n), n * is the new allocated size of the vector. */ int FUNCTION(igraph_vector,reserve) (TYPE(igraph_vector)* v, long int size) { long int actual_size=FUNCTION(igraph_vector,size)(v); BASE *tmp; assert(v != NULL); assert(v->stor_begin != NULL); if (size <= FUNCTION(igraph_vector,size)(v)) { return 0; } tmp=igraph_Realloc(v->stor_begin, (size_t) size, BASE); if (tmp==0) { IGRAPH_ERROR("cannot reserve space for vector", IGRAPH_ENOMEM); } v->stor_begin=tmp; v->stor_end=v->stor_begin + size; v->end=v->stor_begin+actual_size; return 0; } /** * \ingroup vector * \function igraph_vector_empty * \brief Decides whether the size of the vector is zero. * * \param v The vector object. * \return Non-zero number (true) if the size of the vector is zero and * zero (false) otherwise. * * Time complexity: O(1). */ igraph_bool_t FUNCTION(igraph_vector,empty) (const TYPE(igraph_vector)* v) { assert(v != NULL); assert(v->stor_begin != NULL); return v->stor_begin == v->end; } /** * \ingroup vector * \function igraph_vector_size * \brief Gives the size (=length) of the vector. * * \param v The vector object * \return The size of the vector. * * Time complexity: O(1). */ long int FUNCTION(igraph_vector,size) (const TYPE(igraph_vector)* v) { assert(v != NULL); assert(v->stor_begin != NULL); return v->end - v->stor_begin; } /** * \ingroup vector * \function igraph_vector_clear * \brief Removes all elements from a vector. * * * This function simply sets the size of the vector to zero, it does * not free any allocated memory. For that you have to call * \ref igraph_vector_destroy(). * \param v The vector object. * * Time complexity: O(1). */ void FUNCTION(igraph_vector,clear) (TYPE(igraph_vector)* v) { assert(v != NULL); assert(v->stor_begin != NULL); v->end = v->stor_begin; } /** * \ingroup vector * \function igraph_vector_push_back * \brief Appends one element to a vector. * * * This function resizes the vector to be one element longer and * sets the very last element in the vector to \p e. * \param v The vector object. * \param e The element to append to the vector. * \return Error code: * \c IGRAPH_ENOMEM: not enough memory. * * Time complexity: operating system dependent. What is important is that * a sequence of n * subsequent calls to this function has time complexity * O(n), even if there * hadn't been any space reserved for the new elements by * \ref igraph_vector_reserve(). This is implemented by a trick similar to the C++ * \type vector class: each time more memory is allocated for a * vector, the size of the additionally allocated memory is the same * as the vector's current length. (We assume here that the time * complexity of memory allocation is at most linear.) */ int FUNCTION(igraph_vector,push_back) (TYPE(igraph_vector)* v, BASE e) { assert(v != NULL); assert(v->stor_begin != NULL); /* full, allocate more storage */ if (v->stor_end == v->end) { long int new_size = FUNCTION(igraph_vector,size)(v) * 2; if (new_size == 0) { new_size = 1; } IGRAPH_CHECK(FUNCTION(igraph_vector,reserve)(v, new_size)); } *(v->end) = e; v->end += 1; return 0; } /** * \ingroup vector * \function igraph_vector_insert * \brief Inserts a single element into a vector. * * Note that this function does not do range checking. Insertion will shift the * elements from the position given to the end of the vector one position to the * right, and the new element will be inserted in the empty space created at * the given position. The size of the vector will increase by one. * * \param v The vector object. * \param pos The position where the new element is to be inserted. * \param value The new element to be inserted. */ int FUNCTION(igraph_vector,insert)(TYPE(igraph_vector) *v, long int pos, BASE value) { size_t size = (size_t) FUNCTION(igraph_vector,size)(v); IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(v, (long) size+1)); if (posstor_begin+pos+1, v->stor_begin+pos, sizeof(BASE)*(size - (size_t) pos)); } v->stor_begin[pos] = value; return 0; } /** * \ingroup vector * \section igraph_vector_accessing_elements Accessing elements * * The simplest way to access an element of a vector is to use the * \ref VECTOR macro. This macro can be used both for querying and setting * \type igraph_vector_t elements. If you need a function, \ref * igraph_vector_e() queries and \ref igraph_vector_set() sets an element of a * vector. \ref igraph_vector_e_ptr() returns the address of an element. * * \ref igraph_vector_tail() returns the last element of a non-empty * vector. There is no igraph_vector_head() function * however, as it is easy to write VECTOR(v)[0] * instead. */ /** * \ingroup vector * \function igraph_vector_e * \brief Access an element of a vector. * \param v The \type igraph_vector_t object. * \param pos The position of the element, the index of the first * element is zero. * \return The desired element. * \sa \ref igraph_vector_e_ptr() and the \ref VECTOR macro. * * Time complexity: O(1). */ BASE FUNCTION(igraph_vector,e) (const TYPE(igraph_vector)* v, long int pos) { assert(v != NULL); assert(v->stor_begin != NULL); return * (v->stor_begin + pos); } /** * \ingroup vector * \function igraph_vector_e_ptr * \brief Get the address of an element of a vector * \param v The \type igraph_vector_t object. * \param pos The position of the element, the position of the first * element is zero. * \return Pointer to the desired element. * \sa \ref igraph_vector_e() and the \ref VECTOR macro. * * Time complexity: O(1). */ BASE* FUNCTION(igraph_vector,e_ptr) (const TYPE(igraph_vector)* v, long int pos) { assert(v!=NULL); assert(v->stor_begin != NULL); return v->stor_begin+pos; } /** * \ingroup vector * \function igraph_vector_set * \brief Assignment to an element of a vector. * \param v The \type igraph_vector_t element. * \param pos Position of the element to set. * \param value New value of the element. * \sa \ref igraph_vector_e(). */ void FUNCTION(igraph_vector,set) (TYPE(igraph_vector)* v, long int pos, BASE value) { assert(v != NULL); assert(v->stor_begin != NULL); *(v->stor_begin + pos) = value; } /** * \ingroup vector * \function igraph_vector_null * \brief Sets each element in the vector to zero. * * * Note that \ref igraph_vector_init() sets the elements to zero as well, so * it makes no sense to call this function on a just initialized * vector. Thus if you want to construct a vector of zeros, then you should * use \ref igraph_vector_init(). * \param v The vector object. * * Time complexity: O(n), the size of * the vector. */ void FUNCTION(igraph_vector,null) (TYPE(igraph_vector)* v) { assert(v != NULL); assert(v->stor_begin != NULL); if (FUNCTION(igraph_vector,size)(v)>0) { memset(v->stor_begin, 0, sizeof(BASE)*(size_t) FUNCTION(igraph_vector,size)(v)); } } /** * \function igraph_vector_fill * \brief Fill a vector with a constant element * * Sets each element of the vector to the supplied constant. * \param vector The vector to work on. * \param e The element to fill with. * * Time complexity: O(n), the size of the vector. */ void FUNCTION(igraph_vector,fill) (TYPE(igraph_vector)* v, BASE e) { BASE *ptr; assert(v != NULL); assert(v->stor_begin != NULL); for (ptr = v->stor_begin; ptr < v->end; ptr++) { *ptr = e; } } /** * \ingroup vector * \function igraph_vector_tail * \brief Returns the last element in a vector. * * * It is an error to call this function on an empty vector, the result * is undefined. * \param v The vector object. * \return The last element. * * Time complexity: O(1). */ BASE FUNCTION(igraph_vector,tail)(const TYPE(igraph_vector) *v) { assert(v!=NULL); assert(v->stor_begin != NULL); return *((v->end)-1); } /** * \ingroup vector * \function igraph_vector_pop_back * \brief Removes and returns the last element of a vector. * * * It is an error to call this function with an empty vector. * \param v The vector object. * \return The removed last element. * * Time complexity: O(1). */ BASE FUNCTION(igraph_vector,pop_back)(TYPE(igraph_vector)* v) { BASE tmp; assert(v!=NULL); assert(v->stor_begin != NULL); assert(v->end != v->stor_begin); tmp=FUNCTION(igraph_vector,e)(v, FUNCTION(igraph_vector,size)(v)-1); v->end -= 1; return tmp; } #ifndef NOTORDERED /** * \ingroup vector * \function igraph_vector_sort_cmp * \brief Internal comparison function of vector elements, used by * \ref igraph_vector_sort(). */ int FUNCTION(igraph_vector,sort_cmp)(const void *a, const void *b) { const BASE *da = (const BASE *) a; const BASE *db = (const BASE *) b; return (*da > *db) - (*da < *db); } /** * \ingroup vector * \function igraph_vector_sort * \brief Sorts the elements of the vector into ascending order. * * * This function uses the built-in sort function of the C library. * \param v Pointer to an initialized vector object. * * Time complexity: should be * O(nlogn) for * n * elements. */ void FUNCTION(igraph_vector,sort)(TYPE(igraph_vector) *v) { assert(v != NULL); assert(v->stor_begin != NULL); igraph_qsort(v->stor_begin, (size_t) FUNCTION(igraph_vector,size)(v), sizeof(BASE), FUNCTION(igraph_vector,sort_cmp)); } /** * Ascending comparison function passed to qsort from igraph_vector_qsort_ind */ int FUNCTION(igraph_vector,i_qsort_ind_cmp_asc)(const void *p1 , const void *p2) { BASE **pa = (BASE **) p1; BASE **pb = (BASE **) p2; if( **pa < **pb ) return -1; if( **pa > **pb) return 1; return 0; } /** * Descending comparison function passed to qsort from igraph_vector_qsort_ind */ int FUNCTION(igraph_vector,i_qsort_ind_cmp_desc)(const void *p1 , const void *p2) { BASE **pa = (BASE **) p1; BASE **pb = (BASE **) p2; if( **pa < **pb ) return 1; if( **pa > **pb) return -1; return 0; } /** * \function igraph_vector_qsort_ind * \brief Return a permutation of indices that sorts a vector * * Takes an unsorted array \c v as input and computes an array of * indices inds such that v[ inds[i] ], with i increasing from 0, is * an ordered array (either ascending or descending, depending on * \v order). The order of indices for identical elements is not * defined. * * \param v the array to be sorted * \param inds the output array of indices. this must be initialized, * but will be resized * \param descending whether the output array should be sorted in descending * order. * \return Error code. * * This routine uses the C library qsort routine. * Algorithm: 1) create an array of pointers to the elements of v. 2) * Pass this array to qsort. 3) after sorting the difference between * the pointer value and the first pointer value gives its original * position in the array. Use this to set the values of inds. * * Some tests show that this routine is faster than * igraph_vector_heapsort_ind by about 10 percent * for small vectors to a factor of two for large vectors. */ long int FUNCTION(igraph_vector,qsort_ind)(TYPE(igraph_vector) *v, igraph_vector_t *inds, igraph_bool_t descending) { long int i; BASE **vind, *first; size_t n = (size_t) FUNCTION(igraph_vector,size)(v); IGRAPH_CHECK(igraph_vector_resize(inds, (long) n)); if (n==0) { return 0; } vind = igraph_Calloc(n, BASE*); if (vind == 0) { IGRAPH_ERROR("igraph_vector_qsort_ind failed", IGRAPH_ENOMEM); } for(i=0; i * Note that this function does not free any memory, just sets the * size of the vector to the given one. It can on the other hand * allocate more memory if the new size is larger than the previous * one. In this case the newly appeared elements in the vector are * \em not set to zero, they are uninitialized. * \param v The vector object * \param newsize The new size of the vector. * \return Error code, * \c IGRAPH_ENOMEM if there is not enough * memory. Note that this function \em never returns an error * if the vector is made smaller. * \sa \ref igraph_vector_reserve() for allocating memory for future * extensions of a vector. \ref igraph_vector_resize_min() for * deallocating the unnneded memory for a vector. * * Time complexity: O(1) if the new * size is smaller, operating system dependent if it is larger. In the * latter case it is usually around * O(n), * n is the new size of the vector. */ int FUNCTION(igraph_vector,resize)(TYPE(igraph_vector)* v, long int newsize) { assert(v != NULL); assert(v->stor_begin != NULL); IGRAPH_CHECK(FUNCTION(igraph_vector,reserve)(v, newsize)); v->end = v->stor_begin+newsize; return 0; } /** * \ingroup vector * \function igraph_vector_resize_min * \brief Deallocate the unused memory of a vector. * * * Note that this function involves additional memory allocation and * may result an out-of-memory error. * \param v Pointer to an initialized vector. * \return Error code. * * \sa \ref igraph_vector_resize(), \ref igraph_vector_reserve(). * * Time complexity: operating system dependent. */ int FUNCTION(igraph_vector,resize_min)(TYPE(igraph_vector)*v) { size_t size; BASE *tmp; if (v->stor_end == v->end) { return 0; } size = (size_t) (v->end - v->stor_begin); tmp=igraph_Realloc(v->stor_begin, size, BASE); if (tmp==0) { IGRAPH_ERROR("cannot resize vector", IGRAPH_ENOMEM); } else { v->stor_begin = tmp; v->stor_end = v->end = v->stor_begin + size; } return 0; } #ifndef NOTORDERED /** * \ingroup vector * \function igraph_vector_max * \brief Gives the maximum element of the vector. * * * If the size of the vector is zero, an arbitrary number is * returned. * \param v The vector object. * \return The maximum element. * * Time complexity: O(n), * n is the size of the vector. */ BASE FUNCTION(igraph_vector,max)(const TYPE(igraph_vector)* v) { BASE max; BASE *ptr; assert(v != NULL); assert(v->stor_begin != NULL); max=*(v->stor_begin); ptr=v->stor_begin+1; while (ptr < v->end) { if ((*ptr) > max) { max=*ptr; } ptr++; } return max; } /** * \ingroup vector * \function igraph_vector_which_max * \brief Gives the position of the maximum element of the vector. * * * If the size of the vector is zero, -1 is * returned. * \param v The vector object. * \return The position of the first maximum element. * * Time complexity: O(n), * n is the size of the vector. */ long int FUNCTION(igraph_vector,which_max)(const TYPE(igraph_vector)* v) { long int which=-1; if (!FUNCTION(igraph_vector,empty)(v)) { BASE max; BASE *ptr; long int pos; assert(v != NULL); assert(v->stor_begin != NULL); max=*(v->stor_begin); which=0; ptr=v->stor_begin+1; pos=1; while (ptr < v->end) { if ((*ptr) > max) { max=*ptr; which=pos; } ptr++; pos++; } } return which; } /** * \function igraph_vector_min * \brief Smallest element of a vector. * * The vector must be non-empty. * \param v The input vector. * \return The smallest element of \p v. * * Time complexity: O(n), the number of elements. */ BASE FUNCTION(igraph_vector,min)(const TYPE(igraph_vector)* v) { BASE min; BASE *ptr; assert(v != NULL); assert(v->stor_begin != NULL); min=*(v->stor_begin); ptr=v->stor_begin+1; while (ptr < v->end) { if ((*ptr) < min) { min=*ptr; } ptr++; } return min; } /** * \function igraph_vector_which_min * \brief Index of the smallest element. * * The vector must be non-empty. * If the smallest element is not unique, then the index of the first * is returned. * \param v The input vector. * \return Index of the smallest element. * * Time complexity: O(n), the number of elements. */ long int FUNCTION(igraph_vector,which_min)(const TYPE(igraph_vector)* v) { long int which=-1; if (!FUNCTION(igraph_vector,empty)(v)) { BASE min; BASE *ptr; long int pos; assert(v != NULL); assert(v->stor_begin != NULL); min=*(v->stor_begin); which=0; ptr=v->stor_begin+1; pos=1; while (ptr < v->end) { if ((*ptr) < min) { min=*ptr; which=pos; } ptr++; pos++; } } return which; } #endif /** * \ingroup vector * \function igraph_vector_init_copy * \brief Initializes a vector from an ordinary C array (constructor). * * \param v Pointer to an uninitialized vector object. * \param data A regular C array. * \param length The length of the C array. * \return Error code: * \c IGRAPH_ENOMEM if there is not enough memory. * * Time complexity: operating system specific, usually * O(\p length). */ int FUNCTION(igraph_vector,init_copy)(TYPE(igraph_vector) *v, BASE *data, long int length) { v->stor_begin=igraph_Calloc(length, BASE); if (v->stor_begin==0) { IGRAPH_ERROR("cannot init vector from array", IGRAPH_ENOMEM); } v->stor_end=v->stor_begin+length; v->end=v->stor_end; memcpy(v->stor_begin, data, (size_t) length * sizeof(BASE)); return 0; } /** * \ingroup vector * \function igraph_vector_copy_to * \brief Copies the contents of a vector to a C array. * * * The C array should have sufficient length. * \param v The vector object. * \param to The C array. * * Time complexity: O(n), * n is the size of the vector. */ void FUNCTION(igraph_vector,copy_to)(const TYPE(igraph_vector) *v, BASE *to) { assert(v != NULL); assert(v->stor_begin != NULL); if (v->end != v->stor_begin) { memcpy(to, v->stor_begin, sizeof(BASE) * (size_t) (v->end - v->stor_begin)); } } /** * \ingroup vector * \function igraph_vector_copy * \brief Initializes a vector from another vector object (constructor). * * * The contents of the existing vector object will be copied to * the new one. * \param to Pointer to a not yet initialized vector object. * \param from The original vector object to copy. * \return Error code: * \c IGRAPH_ENOMEM if there is not enough memory. * * Time complexity: operating system dependent, usually * O(n), * n is the size of the vector. */ int FUNCTION(igraph_vector,copy)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from) { assert(from != NULL); assert(from->stor_begin != NULL); to->stor_begin=igraph_Calloc(FUNCTION(igraph_vector,size)(from), BASE); if (to->stor_begin==0) { IGRAPH_ERROR("cannot copy vector", IGRAPH_ENOMEM); } to->stor_end=to->stor_begin+FUNCTION(igraph_vector,size)(from); to->end=to->stor_end; memcpy(to->stor_begin, from->stor_begin, (size_t) FUNCTION(igraph_vector,size)(from) * sizeof(BASE)); return 0; } /** * \ingroup vector * \function igraph_vector_sum * \brief Calculates the sum of the elements in the vector. * * * For the empty vector 0.0 is returned. * \param v The vector object. * \return The sum of the elements. * * Time complexity: O(n), the size of * the vector. */ BASE FUNCTION(igraph_vector,sum)(const TYPE(igraph_vector) *v) { BASE res=ZERO; BASE *p; assert(v != NULL); assert(v->stor_begin != NULL); for (p=v->stor_begin; pend; p++) { #ifdef SUM SUM(res,res,*p); #else res += *p; #endif } return res; } igraph_real_t FUNCTION(igraph_vector,sumsq)(const TYPE(igraph_vector) *v) { igraph_real_t res=0.0; BASE *p; assert(v != NULL); assert(v->stor_begin != NULL); for (p=v->stor_begin; pend; p++) { #ifdef SQ res += SQ(*p); #else res += (*p) * (*p); #endif } return res; } /** * \ingroup vector * \function igraph_vector_prod * \brief Calculates the product of the elements in the vector. * * * For the empty vector one (1) is returned. * \param v The vector object. * \return The product of the elements. * * Time complexity: O(n), the size of * the vector. */ BASE FUNCTION(igraph_vector,prod)(const TYPE(igraph_vector) *v) { BASE res=ONE; BASE *p; assert(v != NULL); assert(v->stor_begin != NULL); for (p=v->stor_begin; pend; p++) { #ifdef PROD PROD(res,res,*p); #else res *= *p; #endif } return res; } /** * \ingroup vector * \function igraph_vector_cumsum * \brief Calculates the cumulative sum of the elements in the vector. * * * \param to An initialized vector object that will store the cumulative * sums. Element i of this vector will store the sum of the elements * of the 'from' vector, up to and including element i. * \param from The input vector. * \return Error code. * * Time complexity: O(n), the size of the vector. */ int FUNCTION(igraph_vector,cumsum)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from) { BASE res=ZERO; BASE *p, *p2; assert(from != NULL); assert(from->stor_begin != NULL); assert(to != NULL); assert(to->stor_begin != NULL); IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(to, FUNCTION(igraph_vector,size)(from))); for (p = from->stor_begin, p2 = to->stor_begin; p < from->end; p++, p2++) { #ifdef SUM SUM(res,res,*p); #else res += *p; #endif *p2 = res; } return 0; } #ifndef NOTORDERED /** * \ingroup vector * \function igraph_vector_init_seq * \brief Initializes a vector with a sequence. * * * The vector will contain the numbers \p from, * \p from+1, ..., \p to. * \param v Pointer to an uninitialized vector object. * \param from The lower limit in the sequence (inclusive). * \param to The upper limit in the sequence (inclusive). * \return Error code: * \c IGRAPH_ENOMEM: out of memory. * * Time complexity: O(n), the number * of elements in the vector. */ int FUNCTION(igraph_vector,init_seq)(TYPE(igraph_vector) *v, BASE from, BASE to) { BASE *p; IGRAPH_CHECK(FUNCTION(igraph_vector,init)(v, (long int) (to-from+1))); for (p=v->stor_begin; pend; p++) { *p = from++; } return 0; } #endif /** * \ingroup vector * \function igraph_vector_remove_section * \brief Deletes a section from a vector. * * * Note that this function does not do range checking. The result is * undefined if you supply invalid limits. * \param v The vector object. * \param from The position of the first element to remove. * \param to The position of the first element \em not to remove. * * Time complexity: O(n-from), * n is the number of elements in the * vector. */ void FUNCTION(igraph_vector,remove_section)(TYPE(igraph_vector) *v, long int from, long int to) { assert(v != NULL); assert(v->stor_begin != NULL); /* Not removing from the end? */ if (to < FUNCTION(igraph_vector,size)(v)) { memmove(v->stor_begin+from, v->stor_begin+to, sizeof(BASE) * (size_t) (v->end-v->stor_begin-to)); } v->end -= (to-from); } /** * \ingroup vector * \function igraph_vector_remove * \brief Removes a single element from a vector. * * Note that this function does not do range checking. * \param v The vector object. * \param elem The position of the element to remove. * * Time complexity: O(n-elem), * n is the number of elements in the * vector. */ void FUNCTION(igraph_vector,remove)(TYPE(igraph_vector) *v, long int elem) { assert(v != NULL); assert(v->stor_begin != NULL); FUNCTION(igraph_vector,remove_section)(v, elem, elem+1); } /** * \ingroup vector * \function igraph_vector_move_interval * \brief Copies a section of a vector. * * * The result of this function is undefined if the source and target * intervals overlap. * \param v The vector object. * \param begin The position of the first element to move. * \param end The position of the first element \em not to move. * \param to The target position. * \return Error code, the current implementation always returns with * success. * * Time complexity: O(end-begin). */ int FUNCTION(igraph_vector,move_interval)(TYPE(igraph_vector) *v, long int begin, long int end, long int to) { assert(v != NULL); assert(v->stor_begin != NULL); memcpy(v->stor_begin+to, v->stor_begin+begin, sizeof(BASE) * (size_t) (end-begin)); return 0; } int FUNCTION(igraph_vector,move_interval2)(TYPE(igraph_vector) *v, long int begin, long int end, long int to) { assert(v != NULL); assert(v->stor_begin != NULL); memmove(v->stor_begin+to, v->stor_begin+begin, sizeof(BASE) * (size_t) (end-begin)); return 0; } /** * \ingroup vector * \function igraph_vector_permdelete * \brief Remove elements of a vector (for internal use). */ void FUNCTION(igraph_vector,permdelete)(TYPE(igraph_vector) *v, const igraph_vector_t *index, long int nremove) { long int i, n; assert(v != NULL); assert(v->stor_begin != NULL); n = FUNCTION(igraph_vector,size)(v); for (i=0; iend -= nremove; } #ifndef NOTORDERED /** * \ingroup vector * \function igraph_vector_isininterval * \brief Checks if all elements of a vector are in the given * interval. * * \param v The vector object. * \param low The lower limit of the interval (inclusive). * \param high The higher limit of the interval (inclusive). * \return True (positive integer) if all vector elements are in the * interval, false (zero) otherwise. * * Time complexity: O(n), the number * of elements in the vector. */ igraph_bool_t FUNCTION(igraph_vector,isininterval)(const TYPE(igraph_vector) *v, BASE low, BASE high) { BASE *ptr; assert(v != NULL); assert(v->stor_begin != NULL); for (ptr=v->stor_begin; ptrend; ptr++) { if (*ptr < low || *ptr >high) { return 0; } } return 1; } /** * \ingroup vector * \function igraph_vector_any_smaller * \brief Checks if any element of a vector is smaller than a limit. * * \param v The \type igraph_vector_t object. * \param limit The limit. * \return True (positive integer) if the vector contains at least one * smaller element than \p limit, false (zero) * otherwise. * * Time complexity: O(n), the number * of elements in the vector. */ igraph_bool_t FUNCTION(igraph_vector,any_smaller)(const TYPE(igraph_vector) *v, BASE limit) { BASE *ptr; assert(v != NULL); assert(v->stor_begin != NULL); for (ptr=v->stor_begin; ptrend; ptr++) { if (*ptr < limit) { return 1; } } return 0; } #endif /** * \ingroup vector * \function igraph_vector_all_e * \brief Are all elements equal? * * \param lhs The first vector. * \param rhs The second vector. * \return Positive integer (=true) if the elements in the \p lhs are all * equal to the corresponding elements in \p rhs. Returns \c 0 * (=false) if the lengths of the vectors don't match. * * Time complexity: O(n), the length of the vectors. */ igraph_bool_t FUNCTION(igraph_vector,all_e)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs) { long int i, s; assert(lhs != 0); assert(rhs != 0); assert(lhs->stor_begin != 0); assert(rhs->stor_begin != 0); s=FUNCTION(igraph_vector,size)(lhs); if (s != FUNCTION(igraph_vector,size)(rhs)) { return 0; } else { for (i=0; istor_begin != 0); assert(rhs->stor_begin != 0); s=FUNCTION(igraph_vector,size)(lhs); if (s != FUNCTION(igraph_vector,size)(rhs)) { return 0; } else { for (i=0; i=r) { return 0; } } return 1; } } /** * \ingroup vector * \function igraph_vector_all_g * \brief Are all elements greater? * * \param lhs The first vector. * \param rhs The second vector. * \return Positive integer (=true) if the elements in the \p lhs are all * greater than the corresponding elements in \p rhs. Returns \c 0 * (=false) if the lengths of the vectors don't match. * * Time complexity: O(n), the length of the vectors. */ igraph_bool_t FUNCTION(igraph_vector,all_g)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs) { long int i, s; assert(lhs != 0); assert(rhs != 0); assert(lhs->stor_begin != 0); assert(rhs->stor_begin != 0); s=FUNCTION(igraph_vector,size)(lhs); if (s != FUNCTION(igraph_vector,size)(rhs)) { return 0; } else { for (i=0; istor_begin != 0); assert(rhs->stor_begin != 0); s=FUNCTION(igraph_vector,size)(lhs); if (s != FUNCTION(igraph_vector,size)(rhs)) { return 0; } else { for (i=0; ir) { return 0; } } return 1; } } /** * \ingroup vector * \function igraph_vector_all_ge * \brief Are all elements greater or equal? * * \param lhs The first vector. * \param rhs The second vector. * \return Positive integer (=true) if the elements in the \p lhs are all * greater than or equal to the corresponding elements in \p * rhs. Returns \c 0 (=false) if the lengths of the vectors don't * match. * * Time complexity: O(n), the length of the vectors. */ igraph_bool_t FUNCTION(igraph_vector,all_ge)(const TYPE(igraph_vector) *lhs, const TYPE(igraph_vector) *rhs) { long int i, s; assert(lhs != 0); assert(rhs != 0); assert(lhs->stor_begin != 0); assert(rhs->stor_begin != 0); s=FUNCTION(igraph_vector,size)(lhs); if (s != FUNCTION(igraph_vector,size)(rhs)) { return 0; } else { for (i=0; i * It is assumed that the vector is sorted. If the specified element * (\p what) is not in the vector, then the * position of where it should be inserted (to keep the vector sorted) * is returned. * \param v The \type igraph_vector_t object. * \param what The element to search for. * \param pos Pointer to a \type long int. This is set to the * position of an instance of \p what in the * vector if it is present. If \p v does not * contain \p what then * \p pos is set to the position to which it * should be inserted (to keep the the vector sorted of course). * \return Positive integer (true) if \p what is * found in the vector, zero (false) otherwise. * * Time complexity: O(log(n)), * n is the number of elements in * \p v. */ igraph_bool_t FUNCTION(igraph_vector,binsearch)(const TYPE(igraph_vector) *v, BASE what, long int *pos) { return FUNCTION(igraph_i_vector,binsearch_slice)(v, what, pos, 0, FUNCTION(igraph_vector,size)(v)); } igraph_bool_t FUNCTION(igraph_i_vector,binsearch_slice)(const TYPE(igraph_vector) *v, BASE what, long int *pos, long int start, long int end) { long int left = start; long int right = end-1; while (left <= right) { /* (right + left) / 2 could theoretically overflow for long vectors */ long int middle = left + ((right - left) >> 1); if (VECTOR(*v)[middle] > what) { right = middle - 1; } else if (VECTOR(*v)[middle] < what) { left = middle + 1; } else { if (pos != 0) { *pos = middle; } return 1; } } /* if we are here, the element was not found */ if (pos != 0) { *pos = left; } return 0; } /** * \ingroup vector * \function igraph_vector_binsearch2 * \brief Binary search, without returning the index. * * * It is assumed that the vector is sorted. * \param v The \type igraph_vector_t object. * \param what The element to search for. * \return Positive integer (true) if \p what is * found in the vector, zero (false) otherwise. * * Time complexity: O(log(n)), * n is the number of elements in * \p v. */ igraph_bool_t FUNCTION(igraph_vector,binsearch2)(const TYPE(igraph_vector) *v, BASE what) { long int left=0; long int right=FUNCTION(igraph_vector,size)(v)-1; while (left <= right) { /* (right + left) / 2 could theoretically overflow for long vectors */ long int middle = left + ((right - left) >> 1); if (what < VECTOR(*v)[middle]) { right = middle - 1; } else if (what > VECTOR(*v)[middle]) { left = middle + 1; } else { return 1; } } return 0; } #endif /** * \function igraph_vector_scale * \brief Multiply all elements of a vector by a constant * * \param v The vector. * \param by The constant. * \return Error code. The current implementation always returns with success. * * Added in version 0.2. * * Time complexity: O(n), the number of elements in a vector. */ void FUNCTION(igraph_vector,scale)(TYPE(igraph_vector) *v, BASE by) { long int i; for (i=0; istor_begin; while (pend) { #ifdef EQ if (EQ(*p,e)) { #else if (*p==e) { #endif return 1; } p++; } return 0; } /** * \function igraph_vector_search * \brief Search from a given position * * The supplied element \p what is searched in vector \p v, starting * from element index \p from. If found then the index of the first * instance (after \p from) is stored in \p pos. * \param v The input vector. * \param from The index to start searching from. No range checking is * performed. * \param what The element to find. * \param pos If not \c NULL then the index of the found element is * stored here. * \return Boolean, \c TRUE if the element was found, \c FALSE * otherwise. * * Time complexity: O(m), the number of elements to search, the length * of the vector minus the \p from argument. */ igraph_bool_t FUNCTION(igraph_vector,search)(const TYPE(igraph_vector) *v, long int from, BASE what, long int *pos) { long int i, n=FUNCTION(igraph_vector,size)(v); for (i=from; istor_begin+tosize, from->stor_begin, sizeof(BASE) * (size_t) fromsize); to->end=to->stor_begin+tosize+fromsize; return 0; } /** * \function igraph_vector_get_interval */ int FUNCTION(igraph_vector,get_interval)(const TYPE(igraph_vector) *v, TYPE(igraph_vector) *res, long int from, long int to) { IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(res, to-from)); memcpy(res->stor_begin, v->stor_begin+from, (size_t) (to-from) * sizeof(BASE)); return 0; } #ifndef NOTORDERED /** * \function igraph_vector_maxdifference * \brief The maximum absolute difference of \p m1 and \p m2 * * The element with the largest absolute value in \p m1 - \p m2 is * returned. Both vectors must be non-empty, but they not need to have * the same length, the extra elements in the longer vector are ignored. * \param m1 The first vector. * \param m2 The second vector. * \return The maximum absolute difference of \p m1 and \p m2. * * Time complexity: O(n), the number of elements in the shorter * vector. */ igraph_real_t FUNCTION(igraph_vector,maxdifference)(const TYPE(igraph_vector) *m1, const TYPE(igraph_vector) *m2) { long int n1=FUNCTION(igraph_vector,size)(m1); long int n2=FUNCTION(igraph_vector,size)(m2); long int n= n1 < n2 ? n1 : n2; long int i; igraph_real_t diff=0.0; for (i=0; i diff) { diff=d; } } return diff; } #endif /** * \function igraph_vector_update * \brief Update a vector from another one. * * After this operation the contents of \p to will be exactly the same * \p from. \p to will be resized if it was originally shorter or * longer than \p from. * \param to The vector to update. * \param from The vector to update from. * \return Error code. * * Time complexity: O(n), the number of elements in \p from. */ int FUNCTION(igraph_vector,update)(TYPE(igraph_vector) *to, const TYPE(igraph_vector) *from) { size_t n=(size_t) FUNCTION(igraph_vector,size)(from); FUNCTION(igraph_vector,resize)(to, (long) n); memcpy(to->stor_begin, from->stor_begin, sizeof(BASE)*n); return 0; } /** * \function igraph_vector_swap * \brief Swap elements of two vectors. * * The two vectors must have the same length, otherwise an error * happens. * \param v1 The first vector. * \param v2 The second vector. * \return Error code. * * Time complexity: O(n), the length of the vectors. */ int FUNCTION(igraph_vector,swap)(TYPE(igraph_vector) *v1, TYPE(igraph_vector) *v2) { long int i, n1=FUNCTION(igraph_vector,size)(v1); long int n2=FUNCTION(igraph_vector,size)(v2); if (n1 != n2) { IGRAPH_ERROR("Vectors must have the same number of elements for swapping", IGRAPH_EINVAL); } for (i=0; i * The Fisher-Yates shuffle ensures that every implementation is * equally probable when using a proper randomness source. Of course * this does not apply to pseudo-random generators as the cycle of * these generators is less than the number of possible permutations * of the vector if the vector is long enough. * \param v The vector object. * \return Error code, currently always \c IGRAPH_SUCCESS. * * Time complexity: O(n), * n is the number of elements in the * vector. * * * References: * \clist * \cli (Fisher & Yates 1963) * R. A. Fisher and F. Yates. \emb Statistical Tables for Biological, * Agricultural and Medical Research. \eme Oliver and Boyd, 6th edition, * 1963, page 37. * \cli (Knuth 1998) * D. E. Knuth. \emb Seminumerical Algorithms, \eme volume 2 of \emb The Art * of Computer Programming. \eme Addison-Wesley, 3rd edition, 1998, page 145. * \endclist * * \example examples/simple/igraph_fisher_yates_shuffle.c */ int FUNCTION(igraph_vector,shuffle)(TYPE(igraph_vector) *v) { long int n = FUNCTION(igraph_vector,size)(v); long int k; BASE dummy; RNG_BEGIN(); while (n > 1) { k = RNG_INTEGER(0, n-1); n--; dummy = VECTOR(*v)[n]; VECTOR(*v)[n] = VECTOR(*v)[k]; VECTOR(*v)[k] = dummy; } RNG_END(); return IGRAPH_SUCCESS; } /** * \function igraph_vector_add * \brief Add two vectors. * * Add the elements of \p v2 to \p v1, the result is stored in \p * v1. The two vectors must have the same length. * \param v1 The first vector, the result will be stored here. * \param v2 The second vector, its contents will be unchanged. * \return Error code. * * Time complexity: O(n), the number of elements. */ int FUNCTION(igraph_vector,add)(TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2) { long int n1=FUNCTION(igraph_vector,size)(v1); long int n2=FUNCTION(igraph_vector,size)(v2); long int i; if (n1 != n2) { IGRAPH_ERROR("Vectors must have the same number of elements for swapping", IGRAPH_EINVAL); } for (i=0; i= 0 ? VECTOR(*v)[i] : -VECTOR(*v)[i]; } #endif return 0; } #endif #ifndef NOTORDERED /** * \function igraph_vector_minmax * \brief Minimum and maximum elements of a vector. * * Handy if you want to have both the smallest and largest element of * a vector. The vector is only traversed once. The vector must by non-empty. * \param v The input vector. It must contain at least one element. * \param min Pointer to a base type variable, the minimum is stored * here. * \param max Pointer to a base type variable, the maximum is stored * here. * \return Error code. * * Time complexity: O(n), the number of elements. */ int FUNCTION(igraph_vector,minmax)(const TYPE(igraph_vector) *v, BASE *min, BASE *max) { long int n=FUNCTION(igraph_vector,size)(v); long int i; *min=*max=VECTOR(*v)[0]; for (i=1; i *max) { *max=tmp; } else if (tmp < *min) { *min=tmp; } } return 0; } /** * \function igraph_vector_which_minmax * \brief Index of the minimum and maximum elements * * Handy if you need the indices of the smallest and largest * elements. The vector is traversed only once. The vector must to * non-empty. * \param v The input vector. It must contain at least one element. * \param which_min The index of the minimum element will be stored * here. * \param which_max The index of the maximum element will be stored * here. * \return Error code. * * Time complexity: O(n), the number of elements. */ int FUNCTION(igraph_vector,which_minmax)(const TYPE(igraph_vector) *v, long int *which_min, long int *which_max) { long int n=FUNCTION(igraph_vector,size)(v); long int i; BASE min, max; *which_min=*which_max=0; min=max=VECTOR(*v)[0]; for (i=1; i max) { max=tmp; *which_max=i; } else if (tmp < min) { min=tmp; *which_min=i; } } return 0; } #endif /** * \function igraph_vector_isnull * \brief Are all elements zero? * * Checks whether all elements of a vector are zero. * \param v The input vector * \return Boolean, \c TRUE if the vector contains only zeros, \c * FALSE otherwise. * * Time complexity: O(n), the number of elements. */ igraph_bool_t FUNCTION(igraph_vector,isnull)(const TYPE(igraph_vector) *v) { long int n=FUNCTION(igraph_vector,size)(v); long int i=0; #ifdef EQ while (i * Instead of the naive intersection which takes O(n), this function uses * the set intersection method of Ricardo Baeza-Yates, which is more efficient * when one of the vectors is significantly smaller than the other, and * gives similar performance on average when the two vectors are equal. * * * The algorithm keeps the multiplicities of the elements: if an element appears * k1 times in the first vector and k2 times in the second, the result * will include that element min(k1, k2) times. * * * Reference: Baeza-Yates R: A fast set intersection algorithm for sorted * sequences. In: Lecture Notes in Computer Science, vol. 3109/2004, pp. * 400--408, 2004. Springer Berlin/Heidelberg. ISBN: 978-3-540-22341-2. * * \param v1 the first vector * \param v2 the second vector * \param result the result vector, which will also be sorted. * * Time complexity: O(m log(n)) where m is the size of the smaller vector * and n is the size of the larger one. */ int FUNCTION(igraph_vector,intersect_sorted)(const TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2, TYPE(igraph_vector) *result) { long int size1, size2; size1 = FUNCTION(igraph_vector,size)(v1); size2 = FUNCTION(igraph_vector,size)(v2); FUNCTION(igraph_vector,clear)(result); if (size1 == 0 || size2 == 0) return 0; IGRAPH_CHECK(FUNCTION(igraph_i_vector,intersect_sorted)( v1, 0, size1, v2, 0, size2, result)); return 0; } int FUNCTION(igraph_i_vector,intersect_sorted)( const TYPE(igraph_vector) *v1, long int begin1, long int end1, const TYPE(igraph_vector) *v2, long int begin2, long int end2, TYPE(igraph_vector) *result) { long int size1, size2, probe1, probe2; if (begin1 == end1 || begin2 == end2) return 0; size1 = end1 - begin1; size2 = end2 - begin2; if (size1 < size2) { probe1 = begin1 + (size1 >> 1); /* pick the median element */ FUNCTION(igraph_i_vector,binsearch_slice)(v2, VECTOR(*v1)[probe1], &probe2, begin2, end2); IGRAPH_CHECK(FUNCTION(igraph_i_vector,intersect_sorted)( v1, begin1, probe1, v2, begin2, probe2, result )); if (!(probe2 == end2 || VECTOR(*v1)[probe1] < VECTOR(*v2)[probe2])) { IGRAPH_CHECK(FUNCTION(igraph_vector,push_back)(result, VECTOR(*v2)[probe2])); probe2++; } IGRAPH_CHECK(FUNCTION(igraph_i_vector,intersect_sorted)( v1, probe1+1, end1, v2, probe2, end2, result )); } else { probe2 = begin2 + (size2 >> 1); /* pick the median element */ FUNCTION(igraph_i_vector,binsearch_slice)(v1, VECTOR(*v2)[probe2], &probe1, begin1, end1); IGRAPH_CHECK(FUNCTION(igraph_i_vector,intersect_sorted)( v1, begin1, probe1, v2, begin2, probe2, result )); if (!(probe1 == end1 || VECTOR(*v2)[probe2] < VECTOR(*v1)[probe1])) { IGRAPH_CHECK(FUNCTION(igraph_vector,push_back)(result, VECTOR(*v2)[probe2])); probe1++; } IGRAPH_CHECK(FUNCTION(igraph_i_vector,intersect_sorted)( v1, probe1, end1, v2, probe2+1, end2, result )); } return 0; } /** * \function igraph_vector_difference_sorted * \brief Calculates the difference between two sorted vectors (considered as sets) * * The elements that are contained in only the first vector but not the second are * stored in the result vector. All three vectors must be initialized. * * \param v1 the first vector * \param v2 the second vector * \param result the result vector */ int FUNCTION(igraph_vector,difference_sorted)(const TYPE(igraph_vector) *v1, const TYPE(igraph_vector) *v2, TYPE(igraph_vector) *result) { long int i, j, i0, j0; i0 = FUNCTION(igraph_vector,size)(v1); j0 = FUNCTION(igraph_vector,size)(v2); i = j = 0; if (i0 == 0) { /* v1 is empty, this is easy */ FUNCTION(igraph_vector,clear)(result); return IGRAPH_SUCCESS; } if (j0 == 0) { /* v2 is empty, this is easy */ IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(result, i0)); memcpy(result->stor_begin, v1->stor_begin, sizeof(BASE) * (size_t) i0); return IGRAPH_SUCCESS; } FUNCTION(igraph_vector,clear)(result); /* Copy the part of v1 that is less than the first element of v2 */ while (i < i0 && VECTOR(*v1)[i] < VECTOR(*v2)[j]) { i++; } if (i > 0) { IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(result, i)); memcpy(result->stor_begin, v1->stor_begin, sizeof(BASE) * (size_t) i); } while (i < i0 && j < j0) { BASE element = VECTOR(*v1)[i]; if (element == VECTOR(*v2)[j]) { i++; j++; while (i < i0 && VECTOR(*v1)[i] == element) { i++; } while (j < j0 && VECTOR(*v2)[j] == element) { j++; } } else if (element < VECTOR(*v2)[j]) { IGRAPH_CHECK(FUNCTION(igraph_vector,push_back)(result, element)); i++; } else j++; } if (i < i0) { long int oldsize = FUNCTION(igraph_vector,size)(result); IGRAPH_CHECK(FUNCTION(igraph_vector,resize)(result, oldsize+i0-i)); memcpy(result->stor_begin+oldsize, v1->stor_begin+i, sizeof(BASE)* (size_t) (i0-i)); } return 0; } #endif #if defined(OUT_FORMAT) #ifndef USING_R int FUNCTION(igraph_vector,print)(const TYPE(igraph_vector) *v) { long int i, n=FUNCTION(igraph_vector,size)(v); if (n!=0) { #ifdef PRINTFUNC PRINTFUNC(VECTOR(*v)[0]); #else printf(OUT_FORMAT, VECTOR(*v)[0]); #endif } for (i=1; istor_begin); v->stor_begin = tmp; v->stor_end = v->end = tmp + n; return 0; } igraph/src/structural_properties_internal.h0000644000175100001440000000301313431000472021051 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-2016 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef STRUCTURAL_PROPERTIES_INTERNAL_H #define STRUCTURAL_PROPERTIES_INTERNAL_H #include "igraph_constants.h" #include "igraph_types.h" int igraph_i_induced_subgraph_suggest_implementation( const igraph_t *graph, const igraph_vs_t vids, igraph_subgraph_implementation_t* result ); int igraph_i_subgraph_copy_and_delete(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_vector_t *map, igraph_vector_t *invmap); int igraph_i_subgraph_create_from_scratch(const igraph_t *graph, igraph_t *res, const igraph_vs_t vids, igraph_vector_t *map, igraph_vector_t *invmap); #endif igraph/src/walktrap_heap.h0000644000175100001440000001037413431000472015323 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* The original version of this file was written by Pascal Pons The original copyright notice follows here. The FSF address was fixed by Tamas Nepusz */ // File: heap.h //----------------------------------------------------------------------------- // Walktrap v0.2 -- Finds community structure of networks using random walks // Copyright (C) 2004-2005 Pascal Pons // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA // 02110-1301 USA //----------------------------------------------------------------------------- // Author : Pascal Pons // Email : pons@liafa.jussieu.fr // Web page : http://www.liafa.jussieu.fr/~pons/ // Location : Paris, France // Time : June 2005 //----------------------------------------------------------------------------- // see readme.txt for more details #ifndef HEAP_H #define HEAP_H namespace igraph { namespace walktrap { class Neighbor { public: int community1; // the two adjacent communities int community2; // community1 < community2 float delta_sigma; // the delta sigma between the two communities float weight; // the total weight of the edges between the two communities bool exact; // true if delta_sigma is exact, false if it is only a lower bound Neighbor* next_community1; // pointers of two double Neighbor* previous_community1; // chained lists containing Neighbor* next_community2; // all the neighbors of Neighbor* previous_community2; // each communities. int heap_index; // Neighbor(); }; class Neighbor_heap { private: int size; int max_size; Neighbor** H; // the heap that contains a pointer to each Neighbor object stored void move_up(int index); void move_down(int index); public: void add(Neighbor* N); // add a new distance void update(Neighbor* N); // update a distance void remove(Neighbor* N); // remove a distance Neighbor* get_first(); // get the first item long memory(); bool is_empty(); Neighbor_heap(int max_size); ~Neighbor_heap(); }; class Min_delta_sigma_heap { private: int size; int max_size; int* H; // the heap that contains the number of each community int* I; // the index of each community in the heap (-1 = not stored) void move_up(int index); void move_down(int index); public: int get_max_community(); // return the community with the maximal delta_sigma void remove_community(int community); // remove a community; void update(int community); // update (or insert if necessary) the community long memory(); // the memory used in Bytes. bool is_empty(); float* delta_sigma; // the delta_sigma of the stored communities Min_delta_sigma_heap(int max_size); ~Min_delta_sigma_heap(); }; } } /* end of namespaces */ #endif igraph/src/gengraph_box_list.h0000644000175100001440000000504613431000472016177 0ustar hornikusers/* * * gengraph - generation of random simple connected graphs with prescribed * degree sequence * * Copyright (C) 2006 Fabien Viger * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ // This class allows to maintain a list of vertices, // sorted by degree (largest degrees first) // Operations allowed : // - get the vertex having max degree -> Cost = O(1) // - remove any vertex from the graph -> Cost = Sum(degrees of neighbours) // [ could be O(degree) if optimized ] #ifndef _BOX_LIST_H #define _BOX_LIST_H #ifndef _MSC_VER #ifndef register #define register #endif #endif namespace gengraph { class box_list { private: int n; // INITIAL number of vertices int dmax; // CURRENT Maximum degree int *deg; // CURRENT Degrees (points directly to the deg[] of the graph // Vertices are grouped by degree: one double-chained lists for each degree int *list; // list[d-1] is the head of list of vertices of degree d int *next; // next[v]/prev[v] are the vertices next/previous to v int *prev; // in the list where v belongs void pop(int); // pop(v) just removes v from its list void insert(int); // insert(v) insert v at the head of its list public: // Ctor. Takes O(n) time. box_list(int n0, int *deg0); // Dtor ~box_list(); // Self-explaining inline routines inline bool is_empty() { return dmax<1; }; inline int get_max() { return list[dmax-1]; }; inline int get_one() { return list[0]; }; inline int get_min() { int i=0; while(list[i]<0) i++; return list[i]; }; // Remove v from box_list // Also, semi-remove vertex v from graph: all neighbours of v will swap // their last neighbour wit hv, and then decrease their degree, so // that any arc w->v virtually disappear // Actually, adjacency lists are just permuted, and deg[] is changed void pop_vertex(int v, int **neigh); }; } // namespace gengraph #endif //_BOX_LIST_H igraph/src/forestfire.c0000644000175100001440000002132013431000472014635 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_games.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_progress.h" #include "igraph_interrupt_internal.h" #include "igraph_interface.h" #include "igraph_constructors.h" #include "igraph_dqueue.h" #include "config.h" typedef struct igraph_i_forest_fire_data_t { igraph_vector_t *inneis; igraph_vector_t *outneis; long int no_of_nodes; } igraph_i_forest_fire_data_t; void igraph_i_forest_fire_free(igraph_i_forest_fire_data_t *data) { long int i; for (i=0; ino_of_nodes; i++) { igraph_vector_destroy(data->inneis+i); igraph_vector_destroy(data->outneis+i); } } /** * \function igraph_forest_fire_game * \brief Generates a network according to the \quote forest fire game \endquote * * The forest fire model intends to reproduce the following network * characteristics, observed in real networks: * \ilist * \ili Heavy-tailed in-degree distribution. * \ili Heavy-tailed out-degree distribution. * \ili Communities. * \ili Densification power-law. The network is densifying in time, * according to a power-law rule. * \ili Shrinking diameter. The diameter of the network decreases in * time. * \endilist * * * The network is generated in the following way. One vertex is added at * a time. This vertex connects to (cites) ambs vertices already * present in the network, chosen uniformly random. Now, for each cited * vertex v we do the following procedure: * \olist * \oli We generate two random number, x and y, that are * geometrically distributed with means p/(1-p) and * rp(1-rp). (p is fw_prob, r is * bw_factor.) The new vertex cites x outgoing neighbors * and y incoming neighbors of v, from those which are * not yet cited by the new vertex. If there are less than x or * y such vertices available then we cite all of them. * \oli The same procedure is applied to all the newly cited * vertices. * \endolist * * See also: * Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs over time: * densification laws, shrinking diameters and possible explanations. * \emb KDD '05: Proceeding of the eleventh ACM SIGKDD international * conference on Knowledge discovery in data mining \eme, 177--187, 2005. * * Note however, that the version of the model in the published paper is incorrect * in the sense that it cannot generate the kind of graphs the authors * claim. A corrected version is available from * http://cs.stanford.edu/people/jure/pubs/powergrowth-tkdd.pdf , our * implementation is based on this. * * \param graph Pointer to an uninitialized graph object. * \param nodes The number of vertices in the graph. * \param fw_prob The forward burning probability. * \param bw_factor The backward burning ratio. The backward burning probability is calculated as bw.factor*fw.prob. * \param pambs The number of ambassador vertices. * \param directed Whether to create a directed graph. * \return Error code. * * Time complexity: TODO. */ int igraph_forest_fire_game(igraph_t *graph, igraph_integer_t nodes, igraph_real_t fw_prob, igraph_real_t bw_factor, igraph_integer_t pambs, igraph_bool_t directed) { igraph_vector_long_t visited; long int no_of_nodes=nodes, actnode, i; igraph_vector_t edges; igraph_vector_t *inneis, *outneis; igraph_i_forest_fire_data_t data; igraph_dqueue_t neiq; long int ambs=pambs; igraph_real_t param_geom_out=1-fw_prob; igraph_real_t param_geom_in=1-fw_prob*bw_factor; if (fw_prob < 0) { IGRAPH_ERROR("Forest fire model: 'fw_prob' should be between non-negative", IGRAPH_EINVAL); } if (bw_factor < 0) { IGRAPH_ERROR("Forest fire model: 'bw_factor' should be non-negative", IGRAPH_EINVAL); } if (ambs < 0) { IGRAPH_ERROR("Number of ambassadors ('ambs') should be non-negative", IGRAPH_EINVAL); } if (fw_prob == 0 || ambs == 0) { IGRAPH_WARNING("'fw_prob or ambs is zero, creating empty graph"); IGRAPH_CHECK(igraph_empty(graph, nodes, directed)); return 0; } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); inneis=igraph_Calloc(no_of_nodes, igraph_vector_t); if (!inneis) { IGRAPH_ERROR("Cannot run forest fire model", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, inneis); outneis=igraph_Calloc(no_of_nodes, igraph_vector_t); if (!outneis) { IGRAPH_ERROR("Cannot run forest fire model", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, outneis); data.inneis=inneis; data.outneis=outneis; data.no_of_nodes=no_of_nodes; IGRAPH_FINALLY(igraph_i_forest_fire_free, &data); for (i=0; i= no_out) { for (i=0; i 0; ) { long int which=RNG_INTEGER(0, oleft-1); long int nei=(long int) VECTOR(*outv)[which]; VECTOR(*outv)[which] = VECTOR(*outv)[oleft-1]; VECTOR(*outv)[oleft-1] = nei; if (VECTOR(visited)[nei] != actnode+1) { ADD_EDGE_TO(nei); i++; } oleft--; } } /* incoming neighbors */ if (neis_in >= no_in) { for (i=0; i 0; ) { long int which=RNG_INTEGER(0, ileft-1); long int nei=(long int) VECTOR(*inv)[which]; VECTOR(*inv)[which] = VECTOR(*inv)[ileft-1]; VECTOR(*inv)[ileft-1] = nei; if (VECTOR(visited)[nei] != actnode+1) { ADD_EDGE_TO(nei); i++; } ileft--; } } } /* while neiq not empty */ } /* actnode < no_of_nodes */ #undef ADD_EDGE_TO RNG_END(); IGRAPH_PROGRESS("Forest fire: ", 100.0, NULL); igraph_dqueue_destroy(&neiq); igraph_vector_long_destroy(&visited); igraph_i_forest_fire_free(&data); igraph_free(outneis); igraph_free(inneis); IGRAPH_FINALLY_CLEAN(5); IGRAPH_CHECK(igraph_create(graph, &edges, nodes, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } igraph/src/igraph_buckets.c0000644000175100001440000001322713431000472015466 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_types_internal.h" #include "config.h" #include /* The igraph_buckets_t data structure can store at most 'size' * unique integers in 'bsize' buckets. It has the following simple * operations (in addition to _init() and _destroy(): * - _add() adding an element to the given bucket. * - _popmax() removing an element from the bucket with the highest * id. * Currently buckets work as stacks, last-in-first-out mode. * - _empty() queries whether the buckets is empty. * * Internal representation: we use a vector to create single linked * lists, and another vector that points to the starting element of * each bucket. Zero means the end of the chain. So bucket i contains * elements bptr[i], buckets[bptr[i]], buckets[buckets[bptr[i]]], * etc., until a zero is found. * * We also keep the total number of elements in the buckets and the * id of the non-empty bucket with the highest id, to facilitate the * _empty() and _popmax() operations. */ int igraph_buckets_init(igraph_buckets_t *b, long int bsize, long int size) { IGRAPH_VECTOR_LONG_INIT_FINALLY(&b->bptr, bsize); IGRAPH_VECTOR_LONG_INIT_FINALLY(&b->buckets, size); b->max=-1; b->no=0; IGRAPH_FINALLY_CLEAN(2); return 0; } void igraph_buckets_destroy(igraph_buckets_t *b) { igraph_vector_long_destroy(&b->bptr); igraph_vector_long_destroy(&b->buckets); } long int igraph_buckets_popmax(igraph_buckets_t *b) { /* Precondition: there is at least a non-empty bucket */ /* Search for the highest bucket first */ long int max; while ( (max=(long int) VECTOR(b->bptr)[(long int) b->max]) == 0) { b->max --; } VECTOR(b->bptr)[(long int) b->max] = VECTOR(b->buckets)[max-1]; b->no--; return max-1; } long int igraph_buckets_pop(igraph_buckets_t *b, long int bucket) { long int ret=VECTOR(b->bptr)[bucket]-1; VECTOR(b->bptr)[bucket] = VECTOR(b->buckets)[ret]; b->no--; return ret; } igraph_bool_t igraph_buckets_empty(const igraph_buckets_t *b) { return (b->no == 0); } igraph_bool_t igraph_buckets_empty_bucket(const igraph_buckets_t *b, long int bucket) { return VECTOR(b->bptr)[bucket] == 0; } void igraph_buckets_add(igraph_buckets_t *b, long int bucket, long int elem) { VECTOR(b->buckets)[(long int) elem] = VECTOR(b->bptr)[(long int) bucket]; VECTOR(b->bptr)[(long int) bucket] = elem+1; if (bucket > b->max) { b->max = (int) bucket; } b->no++; } void igraph_buckets_clear(igraph_buckets_t *b) { igraph_vector_long_null(&b->bptr); igraph_vector_long_null(&b->buckets); b->max = -1; b->no = 0; } int igraph_dbuckets_init(igraph_dbuckets_t *b, long int bsize, long int size) { IGRAPH_VECTOR_LONG_INIT_FINALLY(&b->bptr, bsize); IGRAPH_VECTOR_LONG_INIT_FINALLY(&b->next, size); IGRAPH_VECTOR_LONG_INIT_FINALLY(&b->prev, size); b->max=-1; b->no=0; IGRAPH_FINALLY_CLEAN(3); return 0; } void igraph_dbuckets_destroy(igraph_dbuckets_t *b) { igraph_vector_long_destroy(&b->bptr); igraph_vector_long_destroy(&b->next); igraph_vector_long_destroy(&b->prev); } void igraph_dbuckets_clear(igraph_dbuckets_t *b) { igraph_vector_long_null(&b->bptr); igraph_vector_long_null(&b->next); igraph_vector_long_null(&b->prev); b->max = -1; b->no = 0; } long int igraph_dbuckets_popmax(igraph_dbuckets_t *b) { long int max; while ( (max=(long int) VECTOR(b->bptr)[(long int) b->max]) == 0) { b->max --; } return igraph_dbuckets_pop(b, b->max); } long int igraph_dbuckets_pop(igraph_dbuckets_t *b, long int bucket) { long int ret=VECTOR(b->bptr)[bucket]-1; long int next=VECTOR(b->next)[ret]; VECTOR(b->bptr)[bucket] = next; if (next != 0) { VECTOR(b->prev)[next-1] = 0; } b->no--; return ret; } igraph_bool_t igraph_dbuckets_empty(const igraph_dbuckets_t *b) { return (b->no == 0); } igraph_bool_t igraph_dbuckets_empty_bucket(const igraph_dbuckets_t *b, long int bucket) { return VECTOR(b->bptr)[bucket] == 0; } void igraph_dbuckets_add(igraph_dbuckets_t *b, long int bucket, long int elem) { long int oldfirst=VECTOR(b->bptr)[bucket]; VECTOR(b->bptr)[bucket] = elem+1; VECTOR(b->next)[elem] = oldfirst; if (oldfirst != 0) { VECTOR(b->prev)[oldfirst-1] = elem+1; } if (bucket > b->max) { b->max = (int) bucket; } b->no++; } /* Remove an arbitrary element */ void igraph_dbuckets_delete(igraph_dbuckets_t *b, long int bucket, long int elem) { if (VECTOR(b->bptr)[bucket] == elem+1) { /* First element in bucket */ long int next=VECTOR(b->next)[elem]; if (next != 0) { VECTOR(b->prev)[next-1] = 0; } VECTOR(b->bptr)[bucket] = next; } else { long int next=VECTOR(b->next)[elem]; long int prev=VECTOR(b->prev)[elem]; if (next != 0) { VECTOR(b->prev)[next-1] = prev; } if (prev != 0) { VECTOR(b->next)[prev-1] = next; } } b->no--; } igraph/src/foreign-lgl-parser.c0000644000175100001440000013367313431000472016203 0ustar hornikusers/* A Bison parser, made by GNU Bison 2.3. */ /* Skeleton implementation for Bison's Yacc-like parsers in C Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.3" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Using locations. */ #define YYLSP_NEEDED 1 /* Substitute the variable and function names. */ #define yyparse igraph_lgl_yyparse #define yylex igraph_lgl_yylex #define yyerror igraph_lgl_yyerror #define yylval igraph_lgl_yylval #define yychar igraph_lgl_yychar #define yydebug igraph_lgl_yydebug #define yynerrs igraph_lgl_yynerrs #define yylloc igraph_lgl_yylloc /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ALNUM = 258, NEWLINE = 259, HASH = 260, ERROR = 261 }; #endif /* Tokens. */ #define ALNUM 258 #define NEWLINE 259 #define HASH 260 #define ERROR 261 /* Copy the first part of user declarations. */ #line 23 "src/foreign-lgl-parser.y" /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "igraph_hacks_internal.h" #include "igraph_types.h" #include "igraph_types_internal.h" #include "igraph_math.h" #include "igraph_memory.h" #include "igraph_error.h" #include "config.h" #include "foreign-lgl-header.h" #include "foreign-lgl-parser.h" #define yyscan_t void* int igraph_lgl_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void* scanner); int igraph_lgl_yyerror(YYLTYPE* locp, igraph_i_lgl_parsedata_t *context, const char *s); char *igraph_lgl_yyget_text (yyscan_t yyscanner ); int igraph_lgl_yyget_leng (yyscan_t yyscanner ); igraph_real_t igraph_lgl_get_number(const char *str, long int len); #define scanner context->scanner /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE #line 81 "src/foreign-lgl-parser.y" { long int edgenum; double weightnum; } /* Line 193 of yacc.c. */ #line 170 "y.tab.c" YYSTYPE; # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 # define YYSTYPE_IS_TRIVIAL 1 #endif #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; } YYLTYPE; # define yyltype YYLTYPE /* obsolescent; will be withdrawn */ # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif /* Copy the second part of user declarations. */ /* Line 216 of yacc.c. */ #line 195 "y.tab.c" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int i) #else static int YYID (i) int i; #endif { return i; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined _STDLIB_H \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef _STDLIB_H # define _STDLIB_H 1 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \ && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss; YYSTYPE yyvs; YYLTYPE yyls; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \ + 2 * YYSTACK_GAP_MAXIMUM) /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack, Stack, yysize); \ Stack = &yyptr->Stack; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif /* YYFINAL -- State number of the termination state. */ #define YYFINAL 2 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 10 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 7 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 8 /* YYNRULES -- Number of rules. */ #define YYNRULES 12 /* YYNRULES -- Number of states. */ #define YYNSTATES 17 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 261 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint8 yyprhs[] = { 0, 0, 3, 4, 7, 10, 13, 17, 18, 21, 24, 28, 30 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int8 yyrhs[] = { 8, 0, -1, -1, 8, 4, -1, 8, 9, -1, 10, 11, -1, 5, 13, 4, -1, -1, 11, 12, -1, 13, 4, -1, 13, 14, 4, -1, 3, -1, 3, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint8 yyrline[] = { 0, 96, 96, 97, 98, 101, 103, 105, 105, 107, 112, 121, 126 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "ALNUM", "NEWLINE", "HASH", "ERROR", "$accept", "input", "vertex", "vertexdef", "edges", "edge", "edgeid", "weight", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 7, 8, 8, 8, 9, 10, 11, 11, 12, 12, 13, 14 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 0, 2, 2, 2, 3, 0, 2, 2, 3, 1, 1 }; /* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state STATE-NUM when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 2, 0, 1, 3, 0, 4, 7, 11, 0, 5, 6, 8, 0, 12, 9, 0, 10 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 1, 5, 6, 9, 11, 8, 15 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -3 static const yytype_int8 yypact[] = { -3, 0, -3, -3, 3, -3, -3, -3, -1, 3, -3, -3, -2, -3, -3, 4, -3 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -3, -3, -3, -3, -3, -3, 1, -3 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If zero, do what YYDEFACT says. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -1 static const yytype_uint8 yytable[] = { 2, 13, 14, 10, 3, 4, 7, 0, 16, 0, 12 }; static const yytype_int8 yycheck[] = { 0, 3, 4, 4, 4, 5, 3, -1, 4, -1, 9 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 8, 0, 4, 5, 9, 10, 3, 13, 11, 4, 12, 13, 3, 4, 14, 4 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. */ #define YYFAIL goto yyerrlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ yytoken = YYTRANSLATE (yychar); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (&yylloc, context, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* YY_LOCATION_PRINT -- Print the location on the stream. This macro was not mandated originally: define only if we know we won't break user code: when these are the locations we know. */ #ifndef YY_LOCATION_PRINT # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL # define YY_LOCATION_PRINT(File, Loc) \ fprintf (File, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column) # else # define YY_LOCATION_PRINT(File, Loc) ((void) 0) # endif #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, &yylloc, scanner) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, Location, context); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_lgl_parsedata_t* context) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_lgl_parsedata_t* context; #endif { if (!yyvaluep) return; YYUSE (yylocationp); YYUSE (context); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, igraph_i_lgl_parsedata_t* context) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, context) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; YYLTYPE const * const yylocationp; igraph_i_lgl_parsedata_t* context; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); YY_LOCATION_PRINT (yyoutput, *yylocationp); YYFPRINTF (yyoutput, ": "); yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, context); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *bottom, yytype_int16 *top) #else static void yy_stack_print (bottom, top) yytype_int16 *bottom; yytype_int16 *top; #endif { YYFPRINTF (stderr, "Stack now"); for (; bottom <= top; ++bottom) YYFPRINTF (stderr, " %d", *bottom); YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, igraph_i_lgl_parsedata_t* context) #else static void yy_reduce_print (yyvsp, yylsp, yyrule, context) YYSTYPE *yyvsp; YYLTYPE *yylsp; int yyrule; igraph_i_lgl_parsedata_t* context; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { fprintf (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , &(yylsp[(yyi + 1) - (yynrhs)]) , context); fprintf (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, yylsp, Rule, context); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into YYRESULT an error message about the unexpected token YYCHAR while in state YYSTATE. Return the number of bytes copied, including the terminating null byte. If YYRESULT is null, do not copy anything; just return the number of bytes that would be copied. As a special case, return 0 if an ordinary "syntax error" message will do. Return YYSIZE_MAXIMUM if overflow occurs during size calculation. */ static YYSIZE_T yysyntax_error (char *yyresult, int yystate, int yychar) { int yyn = yypact[yystate]; if (! (YYPACT_NINF < yyn && yyn <= YYLAST)) return 0; else { int yytype = YYTRANSLATE (yychar); YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; int yysize_overflow = 0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; int yyx; # if 0 /* This is so xgettext sees the translatable formats that are constructed on the fly. */ YY_("syntax error, unexpected %s"); YY_("syntax error, unexpected %s, expecting %s"); YY_("syntax error, unexpected %s, expecting %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s"); YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"); # endif char *yyfmt; char const *yyf; static char const yyunexpected[] = "syntax error, unexpected %s"; static char const yyexpecting[] = ", expecting %s"; static char const yyor[] = " or %s"; char yyformat[sizeof yyunexpected + sizeof yyexpecting - 1 + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2) * (sizeof yyor - 1))]; char const *yyprefix = yyexpecting; /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yycount = 1; yyarg[0] = yytname[yytype]; yyfmt = yystpcpy (yyformat, yyunexpected); for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; yyformat[sizeof yyunexpected - 1] = '\0'; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; yyfmt = yystpcpy (yyfmt, yyprefix); yyprefix = yyor; } yyf = YY_(yyformat); yysize1 = yysize + yystrlen (yyf); yysize_overflow |= (yysize1 < yysize); yysize = yysize1; if (yysize_overflow) return YYSIZE_MAXIMUM; if (yyresult) { /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ char *yyp = yyresult; int yyi = 0; while ((*yyp = *yyf) != '\0') { if (*yyp == '%' && yyf[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyf += 2; } else { yyp++; yyf++; } } } return yysize; } } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, igraph_i_lgl_parsedata_t* context) #else static void yydestruct (yymsg, yytype, yyvaluep, yylocationp, context) const char *yymsg; int yytype; YYSTYPE *yyvaluep; YYLTYPE *yylocationp; igraph_i_lgl_parsedata_t* context; #endif { YYUSE (yyvaluep); YYUSE (yylocationp); YYUSE (context); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (igraph_i_lgl_parsedata_t* context); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (igraph_i_lgl_parsedata_t* context) #else int yyparse (context) igraph_i_lgl_parsedata_t* context; #endif #endif { /* The look-ahead symbol. */ int yychar; /* The semantic value of the look-ahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /* Location data for the look-ahead symbol. */ YYLTYPE yylloc; int yystate; int yyn; int yyresult; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* Look-ahead token as an internal (translated) token number. */ int yytoken = 0; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif /* Three stacks and their tools: `yyss': related to states, `yyvs': related to semantic values, `yyls': related to locations. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss = yyssa; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs = yyvsa; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls = yylsa; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[2]; #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) YYSIZE_T yystacksize = YYINITDEPTH; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; yylsp = yyls; #if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL /* Initialize the default location before parsing starts. */ yylloc.first_line = yylloc.last_line = 1; yylloc.first_column = yylloc.last_column = 0; #endif goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyls = yyls1; yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss); YYSTACK_RELOCATE (yyvs); YYSTACK_RELOCATE (yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a look-ahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to look-ahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a look-ahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } if (yyn == YYFINAL) YYACCEPT; /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the look-ahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token unless it is eof. */ if (yychar != YYEOF) yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); YY_REDUCE_PRINT (yyn); switch (yyn) { case 6: #line 103 "src/foreign-lgl-parser.y" { context->actvertex=(yyvsp[(2) - (3)].edgenum); ;} break; case 9: #line 107 "src/foreign-lgl-parser.y" { igraph_vector_push_back(context->vector, context->actvertex); igraph_vector_push_back(context->vector, (yyvsp[(1) - (2)].edgenum)); igraph_vector_push_back(context->weights, 0); ;} break; case 10: #line 112 "src/foreign-lgl-parser.y" { igraph_vector_push_back(context->vector, context->actvertex); igraph_vector_push_back(context->vector, (yyvsp[(1) - (3)].edgenum)); igraph_vector_push_back(context->weights, (yyvsp[(2) - (3)].weightnum)); context->has_weights = 1; ;} break; case 11: #line 121 "src/foreign-lgl-parser.y" { igraph_trie_get2(context->trie, igraph_lgl_yyget_text(scanner), igraph_lgl_yyget_leng(scanner), &(yyval.edgenum)); ;} break; case 12: #line 126 "src/foreign-lgl-parser.y" { (yyval.weightnum)=igraph_lgl_get_number(igraph_lgl_yyget_text(scanner), igraph_lgl_yyget_leng(scanner)); ;} break; /* Line 1267 of yacc.c. */ #line 1456 "y.tab.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, context, YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (&yylloc, context, yymsg); } else { yyerror (&yylloc, context, YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } yyerror_range[0] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse look-ahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, context); yychar = YYEMPTY; } } /* Else will try to reuse look-ahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; yyerror_range[0] = yylsp[1-yylen]; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[0] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, context); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } if (yyn == YYFINAL) YYACCEPT; *++yyvsp = yylval; yyerror_range[1] = yylloc; /* Using YYLLOC is tempting, but would change the location of the look-ahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #ifndef yyoverflow /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, context, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEOF && yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, context); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, context); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } #line 129 "src/foreign-lgl-parser.y" int igraph_lgl_yyerror(YYLTYPE* locp, igraph_i_lgl_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char), "Parse error in LGL file, line %i (%s)", locp->first_line, s); return 0; } igraph_real_t igraph_lgl_get_number(const char *str, long int length) { igraph_real_t num; char *tmp=igraph_Calloc(length+1, char); strncpy(tmp, str, length); tmp[length]='\0'; sscanf(tmp, "%lf", &num); igraph_Free(tmp); return num; } igraph/src/cs/0000755000175100001440000000000013561251636012746 5ustar hornikusersigraph/src/cs/cs_usolve.c0000644000175100001440000000261713431000472015104 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* solve Ux=b where x and b are dense. x=b on input, solution on output. */ CS_INT cs_usolve (const cs *U, CS_ENTRY *x) { CS_INT p, j, n, *Up, *Ui ; CS_ENTRY *Ux ; if (!CS_CSC (U) || !x) return (0) ; /* check inputs */ n = U->n ; Up = U->p ; Ui = U->i ; Ux = U->x ; for (j = n-1 ; j >= 0 ; j--) { x [j] /= Ux [Up [j+1]-1] ; for (p = Up [j] ; p < Up [j+1]-1 ; p++) { x [Ui [p]] -= Ux [p] * x [j] ; } } return (1) ; } igraph/src/cs/cs_schol.c0000644000175100001440000000401513431000472014671 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* ordering and symbolic analysis for a Cholesky factorization */ css *cs_schol (CS_INT order, const cs *A) { CS_INT n, *c, *post, *P ; cs *C ; css *S ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ n = A->n ; S = cs_calloc (1, sizeof (css)) ; /* allocate result S */ if (!S) return (NULL) ; /* out of memory */ P = cs_amd (order, A) ; /* P = amd(A+A'), or natural */ S->pinv = cs_pinv (P, n) ; /* find inverse permutation */ cs_free (P) ; if (order && !S->pinv) return (cs_sfree (S)) ; C = cs_symperm (A, S->pinv, 0) ; /* C = spones(triu(A(P,P))) */ S->parent = cs_etree (C, 0) ; /* find etree of C */ post = cs_post (S->parent, n) ; /* postorder the etree */ c = cs_counts (C, S->parent, post, 0) ; /* find column counts of chol(C) */ cs_free (post) ; cs_spfree (C) ; S->cp = cs_malloc (n+1, sizeof (CS_INT)) ; /* allocate result S->cp */ S->unz = S->lnz = cs_cumsum (S->cp, c, n) ; /* find column pointers for L */ cs_free (c) ; return ((S->lnz >= 0) ? S : cs_sfree (S)) ; } igraph/src/cs/cs_dmperm.c0000644000175100001440000001622413431000472015052 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* breadth-first search for coarse decomposition (C0,C1,R1 or R0,R3,C3) */ static CS_INT cs_bfs (const cs *A, CS_INT n, CS_INT *wi, CS_INT *wj, CS_INT *queue, const CS_INT *imatch, const CS_INT *jmatch, CS_INT mark) { CS_INT *Ap, *Ai, head = 0, tail = 0, j, i, p, j2 ; cs *C ; for (j = 0 ; j < n ; j++) /* place all unmatched nodes in queue */ { if (imatch [j] >= 0) continue ; /* skip j if matched */ wj [j] = 0 ; /* j in set C0 (R0 if transpose) */ queue [tail++] = j ; /* place unmatched col j in queue */ } if (tail == 0) return (1) ; /* quick return if no unmatched nodes */ C = (mark == 1) ? ((cs *) A) : cs_transpose (A, 0) ; if (!C) return (0) ; /* bfs of C=A' to find R3,C3 from R0 */ Ap = C->p ; Ai = C->i ; while (head < tail) /* while queue is not empty */ { j = queue [head++] ; /* get the head of the queue */ for (p = Ap [j] ; p < Ap [j+1] ; p++) { i = Ai [p] ; if (wi [i] >= 0) continue ; /* skip if i is marked */ wi [i] = mark ; /* i in set R1 (C3 if transpose) */ j2 = jmatch [i] ; /* traverse alternating path to j2 */ if (wj [j2] >= 0) continue ;/* skip j2 if it is marked */ wj [j2] = mark ; /* j2 in set C1 (R3 if transpose) */ queue [tail++] = j2 ; /* add j2 to queue */ } } if (mark != 1) cs_spfree (C) ; /* free A' if it was created */ return (1) ; } /* collect matched rows and columns into p and q */ static void cs_matched (CS_INT n, const CS_INT *wj, const CS_INT *imatch, CS_INT *p, CS_INT *q, CS_INT *cc, CS_INT *rr, CS_INT set, CS_INT mark) { CS_INT kc = cc [set], j ; CS_INT kr = rr [set-1] ; for (j = 0 ; j < n ; j++) { if (wj [j] != mark) continue ; /* skip if j is not in C set */ p [kr++] = imatch [j] ; q [kc++] = j ; } cc [set+1] = kc ; rr [set] = kr ; } /* collect unmatched rows into the permutation vector p */ static void cs_unmatched (CS_INT m, const CS_INT *wi, CS_INT *p, CS_INT *rr, CS_INT set) { CS_INT i, kr = rr [set] ; for (i = 0 ; i < m ; i++) if (wi [i] == 0) p [kr++] = i ; rr [set+1] = kr ; } /* return 1 if row i is in R2 */ static CS_INT cs_rprune (CS_INT i, CS_INT j, CS_ENTRY aij, void *other) { CS_INT *rr = (CS_INT *) other ; return (i >= rr [1] && i < rr [2]) ; } /* Given A, compute coarse and then fine dmperm */ csd *cs_dmperm (const cs *A, CS_INT seed) { CS_INT m, n, i, j, k, cnz, nc, *jmatch, *imatch, *wi, *wj, *pinv, *Cp, *Ci, *ps, *rs, nb1, nb2, *p, *q, *cc, *rr, *r, *s, ok ; cs *C ; csd *D, *scc ; /* --- Maximum matching ------------------------------------------------- */ if (!CS_CSC (A)) return (NULL) ; /* check inputs */ m = A->m ; n = A->n ; D = cs_dalloc (m, n) ; /* allocate result */ if (!D) return (NULL) ; p = D->p ; q = D->q ; r = D->r ; s = D->s ; cc = D->cc ; rr = D->rr ; jmatch = cs_maxtrans (A, seed) ; /* max transversal */ imatch = jmatch + m ; /* imatch = inverse of jmatch */ if (!jmatch) return (cs_ddone (D, NULL, jmatch, 0)) ; /* --- Coarse decomposition --------------------------------------------- */ wi = r ; wj = s ; /* use r and s as workspace */ for (j = 0 ; j < n ; j++) wj [j] = -1 ; /* unmark all cols for bfs */ for (i = 0 ; i < m ; i++) wi [i] = -1 ; /* unmark all rows for bfs */ cs_bfs (A, n, wi, wj, q, imatch, jmatch, 1) ; /* find C1, R1 from C0*/ ok = cs_bfs (A, m, wj, wi, p, jmatch, imatch, 3) ; /* find R3, C3 from R0*/ if (!ok) return (cs_ddone (D, NULL, jmatch, 0)) ; cs_unmatched (n, wj, q, cc, 0) ; /* unmatched set C0 */ cs_matched (n, wj, imatch, p, q, cc, rr, 1, 1) ; /* set R1 and C1 */ cs_matched (n, wj, imatch, p, q, cc, rr, 2, -1) ; /* set R2 and C2 */ cs_matched (n, wj, imatch, p, q, cc, rr, 3, 3) ; /* set R3 and C3 */ cs_unmatched (m, wi, p, rr, 3) ; /* unmatched set R0 */ cs_free (jmatch) ; /* --- Fine decomposition ----------------------------------------------- */ pinv = cs_pinv (p, m) ; /* pinv=p' */ if (!pinv) return (cs_ddone (D, NULL, NULL, 0)) ; C = cs_permute (A, pinv, q, 0) ;/* C=A(p,q) (it will hold A(R2,C2)) */ cs_free (pinv) ; if (!C) return (cs_ddone (D, NULL, NULL, 0)) ; Cp = C->p ; nc = cc [3] - cc [2] ; /* delete cols C0, C1, and C3 from C */ if (cc [2] > 0) for (j = cc [2] ; j <= cc [3] ; j++) Cp [j-cc[2]] = Cp [j] ; C->n = nc ; if (rr [2] - rr [1] < m) /* delete rows R0, R1, and R3 from C */ { cs_fkeep (C, cs_rprune, rr) ; cnz = Cp [nc] ; Ci = C->i ; if (rr [1] > 0) for (k = 0 ; k < cnz ; k++) Ci [k] -= rr [1] ; } C->m = nc ; scc = cs_scc (C) ; /* find strongly connected components of C*/ if (!scc) return (cs_ddone (D, C, NULL, 0)) ; /* --- Combine coarse and fine decompositions --------------------------- */ ps = scc->p ; /* C(ps,ps) is the permuted matrix */ rs = scc->r ; /* kth block is rs[k]..rs[k+1]-1 */ nb1 = scc->nb ; /* # of blocks of A(R2,C2) */ for (k = 0 ; k < nc ; k++) wj [k] = q [ps [k] + cc [2]] ; for (k = 0 ; k < nc ; k++) q [k + cc [2]] = wj [k] ; for (k = 0 ; k < nc ; k++) wi [k] = p [ps [k] + rr [1]] ; for (k = 0 ; k < nc ; k++) p [k + rr [1]] = wi [k] ; nb2 = 0 ; /* create the fine block partitions */ r [0] = s [0] = 0 ; if (cc [2] > 0) nb2++ ; /* leading coarse block A (R1, [C0 C1]) */ for (k = 0 ; k < nb1 ; k++) /* coarse block A (R2,C2) */ { r [nb2] = rs [k] + rr [1] ; /* A (R2,C2) splits into nb1 fine blocks */ s [nb2] = rs [k] + cc [2] ; nb2++ ; } if (rr [2] < m) { r [nb2] = rr [2] ; /* trailing coarse block A ([R3 R0], C3) */ s [nb2] = cc [3] ; nb2++ ; } r [nb2] = m ; s [nb2] = n ; D->nb = nb2 ; cs_dfree (scc) ; return (cs_ddone (D, C, NULL, 1)) ; } igraph/src/cs/cs_lusol.c0000644000175100001440000000334713431000472014726 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x=A\b where A is unsymmetric; b overwritten with solution */ CS_INT cs_lusol (CS_INT order, const cs *A, CS_ENTRY *b, double tol) { CS_ENTRY *x ; css *S ; csn *N ; CS_INT n, ok ; if (!CS_CSC (A) || !b) return (0) ; /* check inputs */ n = A->n ; S = cs_sqr (order, A, 0) ; /* ordering and symbolic analysis */ N = cs_lu (A, S, tol) ; /* numeric LU factorization */ x = cs_malloc (n, sizeof (CS_ENTRY)) ; /* get workspace */ ok = (S && N && x) ; if (ok) { cs_ipvec (N->pinv, b, x, n) ; /* x = b(p) */ cs_lsolve (N->L, x) ; /* x = L\x */ cs_usolve (N->U, x) ; /* x = U\x */ cs_ipvec (S->q, x, b, n) ; /* b(q) = x */ } cs_free (x) ; cs_sfree (S) ; cs_nfree (N) ; return (ok) ; } igraph/src/cs/cs_entry.c0000644000175100001440000000251113431000472014721 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* add an entry to a triplet matrix; return 1 if ok, 0 otherwise */ CS_INT cs_entry (cs *T, CS_INT i, CS_INT j, CS_ENTRY x) { if (!CS_TRIPLET (T) || i < 0 || j < 0) return (0) ; /* check inputs */ if (T->nz >= T->nzmax && !cs_sprealloc (T,2*(T->nzmax))) return (0) ; if (T->x) T->x [T->nz] = x ; T->i [T->nz] = i ; T->p [T->nz++] = j ; T->m = CS_MAX (T->m, i+1) ; T->n = CS_MAX (T->n, j+1) ; return (1) ; } igraph/src/cs/cs_cholsol.c0000644000175100001440000000334313431000472015227 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x=A\b where A is symmetric positive definite; b overwritten with solution */ CS_INT cs_cholsol (CS_INT order, const cs *A, CS_ENTRY *b) { CS_ENTRY *x ; css *S ; csn *N ; CS_INT n, ok ; if (!CS_CSC (A) || !b) return (0) ; /* check inputs */ n = A->n ; S = cs_schol (order, A) ; /* ordering and symbolic analysis */ N = cs_chol (A, S) ; /* numeric Cholesky factorization */ x = cs_malloc (n, sizeof (CS_ENTRY)) ; /* get workspace */ ok = (S && N && x) ; if (ok) { cs_ipvec (S->pinv, b, x, n) ; /* x = P*b */ cs_lsolve (N->L, x) ; /* x = L\x */ cs_ltsolve (N->L, x) ; /* x = L'\x */ cs_pvec (S->pinv, x, b, n) ; /* b = P'*x */ } cs_free (x) ; cs_sfree (S) ; cs_nfree (N) ; return (ok) ; } igraph/src/cs/cs_counts.c0000644000175100001440000000730113431000472015075 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* column counts of LL'=A or LL'=A'A, given parent & post ordering */ #define HEAD(k,j) (ata ? head [k] : j) #define NEXT(J) (ata ? next [J] : -1) static void init_ata (cs *AT, const CS_INT *post, CS_INT *w, CS_INT **head, CS_INT **next) { CS_INT i, k, p, m = AT->n, n = AT->m, *ATp = AT->p, *ATi = AT->i ; *head = w+4*n, *next = w+5*n+1 ; for (k = 0 ; k < n ; k++) w [post [k]] = k ; /* invert post */ for (i = 0 ; i < m ; i++) { for (k = n, p = ATp[i] ; p < ATp[i+1] ; p++) k = CS_MIN (k, w [ATi[p]]); (*next) [i] = (*head) [k] ; /* place row i in linked list k */ (*head) [k] = i ; } } CS_INT *cs_counts (const cs *A, const CS_INT *parent, const CS_INT *post, CS_INT ata) { CS_INT i, j, k, n, m, J, s, p, q, jleaf, *ATp, *ATi, *maxfirst, *prevleaf, *ancestor, *head = NULL, *next = NULL, *colcount, *w, *first, *delta ; cs *AT ; if (!CS_CSC (A) || !parent || !post) return (NULL) ; /* check inputs */ m = A->m ; n = A->n ; s = 4*n + (ata ? (n+m+1) : 0) ; delta = colcount = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result */ w = cs_malloc (s, sizeof (CS_INT)) ; /* get workspace */ AT = cs_transpose (A, 0) ; /* AT = A' */ if (!AT || !colcount || !w) return (cs_idone (colcount, AT, w, 0)) ; ancestor = w ; maxfirst = w+n ; prevleaf = w+2*n ; first = w+3*n ; for (k = 0 ; k < s ; k++) w [k] = -1 ; /* clear workspace w [0..s-1] */ for (k = 0 ; k < n ; k++) /* find first [j] */ { j = post [k] ; delta [j] = (first [j] == -1) ? 1 : 0 ; /* delta[j]=1 if j is a leaf */ for ( ; j != -1 && first [j] == -1 ; j = parent [j]) first [j] = k ; } ATp = AT->p ; ATi = AT->i ; if (ata) init_ata (AT, post, w, &head, &next) ; for (i = 0 ; i < n ; i++) ancestor [i] = i ; /* each node in its own set */ for (k = 0 ; k < n ; k++) { j = post [k] ; /* j is the kth node in postordered etree */ if (parent [j] != -1) delta [parent [j]]-- ; /* j is not a root */ for (J = HEAD (k,j) ; J != -1 ; J = NEXT (J)) /* J=j for LL'=A case */ { for (p = ATp [J] ; p < ATp [J+1] ; p++) { i = ATi [p] ; q = cs_leaf (i, j, first, maxfirst, prevleaf, ancestor, &jleaf); if (jleaf >= 1) delta [j]++ ; /* A(i,j) is in skeleton */ if (jleaf == 2) delta [q]-- ; /* account for overlap in q */ } } if (parent [j] != -1) ancestor [j] = parent [j] ; } for (j = 0 ; j < n ; j++) /* sum up delta's of each child */ { if (parent [j] != -1) colcount [parent [j]] += colcount [j] ; } return (cs_idone (colcount, AT, w, 1)) ; /* success: free workspace */ } igraph/src/cs/cs_transpose.c0000644000175100001440000000363313431000472015604 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = A' */ cs *cs_transpose (const cs *A, CS_INT values) { CS_INT p, q, j, *Cp, *Ci, n, m, *Ap, *Ai, *w ; CS_ENTRY *Cx, *Ax ; cs *C ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; C = cs_spalloc (n, m, Ap [n], values && Ax, 0) ; /* allocate result */ w = cs_calloc (m, sizeof (CS_INT)) ; /* get workspace */ if (!C || !w) return (cs_done (C, w, NULL, 0)) ; /* out of memory */ Cp = C->p ; Ci = C->i ; Cx = C->x ; for (p = 0 ; p < Ap [n] ; p++) w [Ai [p]]++ ; /* row counts */ cs_cumsum (Cp, w, m) ; /* row pointers */ for (j = 0 ; j < n ; j++) { for (p = Ap [j] ; p < Ap [j+1] ; p++) { Ci [q = w [Ai [p]]++] = j ; /* place A(i,j) as entry C(j,i) */ if (Cx) Cx [q] = (values > 0) ? CS_CONJ (Ax [p]) : Ax [p] ; } } return (cs_done (C, w, NULL, 1)) ; /* success; free w and return C */ } igraph/src/cs/cs_multiply.c0000644000175100001440000000464713431000472015453 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = A*B */ cs *cs_multiply (const cs *A, const cs *B) { CS_INT p, j, nz = 0, anz, *Cp, *Ci, *Bp, m, n, bnz, *w, values, *Bi ; CS_ENTRY *x, *Bx, *Cx ; cs *C ; if (!CS_CSC (A) || !CS_CSC (B)) return (NULL) ; /* check inputs */ if (A->n != B->m) return (NULL) ; m = A->m ; anz = A->p [A->n] ; n = B->n ; Bp = B->p ; Bi = B->i ; Bx = B->x ; bnz = Bp [n] ; w = cs_calloc (m, sizeof (CS_INT)) ; /* get workspace */ values = (A->x != NULL) && (Bx != NULL) ; x = values ? cs_malloc (m, sizeof (CS_ENTRY)) : NULL ; /* get workspace */ C = cs_spalloc (m, n, anz + bnz, values, 0) ; /* allocate result */ if (!C || !w || (values && !x)) return (cs_done (C, w, x, 0)) ; Cp = C->p ; for (j = 0 ; j < n ; j++) { if (nz + m > C->nzmax && !cs_sprealloc (C, 2*(C->nzmax)+m)) { return (cs_done (C, w, x, 0)) ; /* out of memory */ } Ci = C->i ; Cx = C->x ; /* C->i and C->x may be reallocated */ Cp [j] = nz ; /* column j of C starts here */ for (p = Bp [j] ; p < Bp [j+1] ; p++) { nz = cs_scatter (A, Bi [p], Bx ? Bx [p] : 1, w, x, j+1, C, nz) ; } if (values) for (p = Cp [j] ; p < nz ; p++) Cx [p] = x [Ci [p]] ; } Cp [n] = nz ; /* finalize the last column of C */ cs_sprealloc (C, 0) ; /* remove extra space from C */ return (cs_done (C, w, x, 1)) ; /* success; free workspace, return C */ } igraph/src/cs/cs_post.c0000644000175100001440000000370113431000472014547 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* post order a forest */ CS_INT *cs_post (const CS_INT *parent, CS_INT n) { CS_INT j, k = 0, *post, *w, *head, *next, *stack ; if (!parent) return (NULL) ; /* check inputs */ post = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result */ w = cs_malloc (3*n, sizeof (CS_INT)) ; /* get workspace */ if (!w || !post) return (cs_idone (post, NULL, w, 0)) ; head = w ; next = w + n ; stack = w + 2*n ; for (j = 0 ; j < n ; j++) head [j] = -1 ; /* empty linked lists */ for (j = n-1 ; j >= 0 ; j--) /* traverse nodes in reverse order*/ { if (parent [j] == -1) continue ; /* j is a root */ next [j] = head [parent [j]] ; /* add j to list of its parent */ head [parent [j]] = j ; } for (j = 0 ; j < n ; j++) { if (parent [j] != -1) continue ; /* skip j if it is not a root */ k = cs_tdfs (j, k, head, next, post, stack) ; } return (cs_idone (post, NULL, w, 1)) ; /* success; free w, return post */ } igraph/src/cs/cs_fkeep.c0000644000175100001440000000347713431000472014666 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* drop entries for which fkeep(A(i,j)) is false; return nz if OK, else -1 */ CS_INT cs_fkeep (cs *A, CS_INT (*fkeep) (CS_INT, CS_INT, CS_ENTRY, void *), void *other) { CS_INT j, p, nz = 0, n, *Ap, *Ai ; CS_ENTRY *Ax ; if (!CS_CSC (A) || !fkeep) return (-1) ; /* check inputs */ n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; for (j = 0 ; j < n ; j++) { p = Ap [j] ; /* get current location of col j */ Ap [j] = nz ; /* record new location of col j */ for ( ; p < Ap [j+1] ; p++) { if (fkeep (Ai [p], j, Ax ? Ax [p] : 1, other)) { if (Ax) Ax [nz] = Ax [p] ; /* keep A(i,j) */ Ai [nz++] = Ai [p] ; } } } Ap [n] = nz ; /* finalize A */ cs_sprealloc (A, 0) ; /* remove extra space from A */ return (nz) ; } igraph/src/cs/cs_print.c0000644000175100001440000000534113431000472014720 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* print a sparse matrix */ /* CS_INT cs_print (const cs *A, CS_INT brief) */ /* { */ /* CS_INT p, j, m, n, nzmax, nz, *Ap, *Ai ; */ /* CS_ENTRY *Ax ; */ /* if (!A) { printf ("(null)\n") ; return (0) ; } */ /* m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; */ /* nzmax = A->nzmax ; nz = A->nz ; */ /* printf ("CXSparse Version %d.%d.%d, %s. %s\n", CS_VER, CS_SUBVER, */ /* CS_SUBSUB, CS_DATE, CS_COPYRIGHT) ; */ /* if (nz < 0) */ /* { */ /* printf (""CS_ID"-by-"CS_ID", nzmax: "CS_ID" nnz: "CS_ID", 1-norm: %g\n", m, n, nzmax, */ /* Ap [n], cs_norm (A)) ; */ /* for (j = 0 ; j < n ; j++) */ /* { */ /* printf (" col "CS_ID" : locations "CS_ID" to "CS_ID"\n", j, Ap [j], Ap [j+1]-1); */ /* for (p = Ap [j] ; p < Ap [j+1] ; p++) */ /* { */ /* #ifdef CS_COMPLEX */ /* printf (" "CS_ID" : (%g, %g)\n", Ai [p], */ /* Ax ? CS_REAL (Ax [p]) : 1, Ax ? CS_IMAG (Ax [p]) : 0) ; */ /* #else */ /* printf (" "CS_ID" : %g\n", Ai [p], Ax ? Ax [p] : 1) ; */ /* #endif */ /* if (brief && p > 20) { printf (" ...\n") ; return (1) ; } */ /* } */ /* } */ /* } */ /* else */ /* { */ /* printf ("triplet: "CS_ID"-by-"CS_ID", nzmax: "CS_ID" nnz: "CS_ID"\n", m, n, nzmax, nz) ; */ /* for (p = 0 ; p < nz ; p++) */ /* { */ /* #ifdef CS_COMPLEX */ /* printf (" "CS_ID" "CS_ID" : (%g, %g)\n", Ai [p], Ap [p], */ /* Ax ? CS_REAL (Ax [p]) : 1, Ax ? CS_IMAG (Ax [p]) : 0) ; */ /* #else */ /* printf (" "CS_ID" "CS_ID" : %g\n", Ai [p], Ap [p], Ax ? Ax [p] : 1) ; */ /* #endif */ /* if (brief && p > 20) { printf (" ...\n") ; return (1) ; } */ /* } */ /* } */ /* return (1) ; */ /* } */ igraph/src/cs/cs.h0000644000175100001440000007620513431000472013520 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _CXS_H #define _CXS_H #include #include #include #include #ifdef MATLAB_MEX_FILE #include "mex.h" #endif #ifdef __cplusplus #ifndef NCOMPLEX #include typedef std::complex cs_complex_t ; #endif extern "C" { #else #ifndef NCOMPLEX #include #define cs_complex_t double _Complex #endif #endif #define CS_VER 2 /* CXSparse Version 2.2.3 */ #define CS_SUBVER 2 #define CS_SUBSUB 3 #define CS_DATE "Mar 24, 2009" /* CXSparse release date */ #define CS_COPYRIGHT "Copyright (c) Timothy A. Davis, 2006-2009" #define CXSPARSE /* define UF_long */ #include "UFconfig.h" /* -------------------------------------------------------------------------- */ /* double/int version of CXSparse */ /* -------------------------------------------------------------------------- */ /* --- primary CSparse routines and data structures ------------------------- */ typedef struct cs_di_sparse /* matrix in compressed-column or triplet form */ { int nzmax ; /* maximum number of entries */ int m ; /* number of rows */ int n ; /* number of columns */ int *p ; /* column pointers (size n+1) or col indices (size nzmax) */ int *i ; /* row indices, size nzmax */ double *x ; /* numerical values, size nzmax */ int nz ; /* # of entries in triplet matrix, -1 for compressed-col */ } cs_di ; cs_di *cs_di_add (const cs_di *A, const cs_di *B, double alpha, double beta) ; int cs_di_cholsol (int order, const cs_di *A, double *b) ; int cs_di_dupl (cs_di *A) ; int cs_di_entry (cs_di *T, int i, int j, double x) ; int cs_di_lusol (int order, const cs_di *A, double *b, double tol) ; int cs_di_gaxpy (const cs_di *A, const double *x, double *y) ; cs_di *cs_di_multiply (const cs_di *A, const cs_di *B) ; int cs_di_qrsol (int order, const cs_di *A, double *b) ; cs_di *cs_di_transpose (const cs_di *A, int values) ; cs_di *cs_di_compress (const cs_di *T) ; double cs_di_norm (const cs_di *A) ; int cs_di_print (const cs_di *A, int brief) ; cs_di *cs_di_load (FILE *f) ; /* utilities */ void *cs_di_calloc (int n, size_t size) ; void *cs_di_free (void *p) ; void *cs_di_realloc (void *p, int n, size_t size, int *ok) ; cs_di *cs_di_spalloc (int m, int n, int nzmax, int values, int t) ; cs_di *cs_di_spfree (cs_di *A) ; int cs_di_sprealloc (cs_di *A, int nzmax) ; void *cs_di_malloc (int n, size_t size) ; /* --- secondary CSparse routines and data structures ----------------------- */ typedef struct cs_di_symbolic /* symbolic Cholesky, LU, or QR analysis */ { int *pinv ; /* inverse row perm. for QR, fill red. perm for Chol */ int *q ; /* fill-reducing column permutation for LU and QR */ int *parent ; /* elimination tree for Cholesky and QR */ int *cp ; /* column pointers for Cholesky, row counts for QR */ int *leftmost ; /* leftmost[i] = min(find(A(i,:))), for QR */ int m2 ; /* # of rows for QR, after adding fictitious rows */ double lnz ; /* # entries in L for LU or Cholesky; in V for QR */ double unz ; /* # entries in U for LU; in R for QR */ } cs_dis ; typedef struct cs_di_numeric /* numeric Cholesky, LU, or QR factorization */ { cs_di *L ; /* L for LU and Cholesky, V for QR */ cs_di *U ; /* U for LU, r for QR, not used for Cholesky */ int *pinv ; /* partial pivoting for LU */ double *B ; /* beta [0..n-1] for QR */ } cs_din ; typedef struct cs_di_dmperm_results /* cs_di_dmperm or cs_di_scc output */ { int *p ; /* size m, row permutation */ int *q ; /* size n, column permutation */ int *r ; /* size nb+1, block k is rows r[k] to r[k+1]-1 in A(p,q) */ int *s ; /* size nb+1, block k is cols s[k] to s[k+1]-1 in A(p,q) */ int nb ; /* # of blocks in fine dmperm decomposition */ int rr [5] ; /* coarse row decomposition */ int cc [5] ; /* coarse column decomposition */ } cs_did ; int *cs_di_amd (int order, const cs_di *A) ; cs_din *cs_di_chol (const cs_di *A, const cs_dis *S) ; cs_did *cs_di_dmperm (const cs_di *A, int seed) ; int cs_di_droptol (cs_di *A, double tol) ; int cs_di_dropzeros (cs_di *A) ; int cs_di_happly (const cs_di *V, int i, double beta, double *x) ; int cs_di_ipvec (const int *p, const double *b, double *x, int n) ; int cs_di_lsolve (const cs_di *L, double *x) ; int cs_di_ltsolve (const cs_di *L, double *x) ; cs_din *cs_di_lu (const cs_di *A, const cs_dis *S, double tol) ; cs_di *cs_di_permute (const cs_di *A, const int *pinv, const int *q, int values) ; int *cs_di_pinv (const int *p, int n) ; int cs_di_pvec (const int *p, const double *b, double *x, int n) ; cs_din *cs_di_qr (const cs_di *A, const cs_dis *S) ; cs_dis *cs_di_schol (int order, const cs_di *A) ; cs_dis *cs_di_sqr (int order, const cs_di *A, int qr) ; cs_di *cs_di_symperm (const cs_di *A, const int *pinv, int values) ; int cs_di_usolve (const cs_di *U, double *x) ; int cs_di_utsolve (const cs_di *U, double *x) ; int cs_di_updown (cs_di *L, int sigma, const cs_di *C, const int *parent) ; /* utilities */ cs_dis *cs_di_sfree (cs_dis *S) ; cs_din *cs_di_nfree (cs_din *N) ; cs_did *cs_di_dfree (cs_did *D) ; /* --- tertiary CSparse routines -------------------------------------------- */ int *cs_di_counts (const cs_di *A, const int *parent, const int *post, int ata) ; double cs_di_cumsum (int *p, int *c, int n) ; int cs_di_dfs (int j, cs_di *G, int top, int *xi, int *pstack, const int *pinv) ; int *cs_di_etree (const cs_di *A, int ata) ; int cs_di_fkeep (cs_di *A, int (*fkeep) (int, int, double, void *), void *other) ; double cs_di_house (double *x, double *beta, int n) ; int *cs_di_maxtrans (const cs_di *A, int seed) ; int *cs_di_post (const int *parent, int n) ; cs_did *cs_di_scc (cs_di *A) ; int cs_di_scatter (const cs_di *A, int j, double beta, int *w, double *x, int mark, cs_di *C, int nz) ; int cs_di_tdfs (int j, int k, int *head, const int *next, int *post, int *stack) ; int cs_di_leaf (int i, int j, const int *first, int *maxfirst, int *prevleaf, int *ancestor, int *jleaf) ; int cs_di_reach (cs_di *G, const cs_di *B, int k, int *xi, const int *pinv) ; int cs_di_spsolve (cs_di *L, const cs_di *B, int k, int *xi, double *x, const int *pinv, int lo) ; int cs_di_ereach (const cs_di *A, int k, const int *parent, int *s, int *w) ; int *cs_di_randperm (int n, int seed) ; /* utilities */ cs_did *cs_di_dalloc (int m, int n) ; cs_di *cs_di_done (cs_di *C, void *w, void *x, int ok) ; int *cs_di_idone (int *p, cs_di *C, void *w, int ok) ; cs_din *cs_di_ndone (cs_din *N, cs_di *C, void *w, void *x, int ok) ; cs_did *cs_di_ddone (cs_did *D, cs_di *C, void *w, int ok) ; /* -------------------------------------------------------------------------- */ /* double/UF_long version of CXSparse */ /* -------------------------------------------------------------------------- */ /* --- primary CSparse routines and data structures ------------------------- */ typedef struct cs_dl_sparse /* matrix in compressed-column or triplet form */ { UF_long nzmax ; /* maximum number of entries */ UF_long m ; /* number of rows */ UF_long n ; /* number of columns */ UF_long *p ; /* column pointers (size n+1) or col indlces (size nzmax) */ UF_long *i ; /* row indices, size nzmax */ double *x ; /* numerical values, size nzmax */ UF_long nz ; /* # of entries in triplet matrix, -1 for compressed-col */ } cs_dl ; cs_dl *cs_dl_add (const cs_dl *A, const cs_dl *B, double alpha, double beta) ; UF_long cs_dl_cholsol (UF_long order, const cs_dl *A, double *b) ; UF_long cs_dl_dupl (cs_dl *A) ; UF_long cs_dl_entry (cs_dl *T, UF_long i, UF_long j, double x) ; UF_long cs_dl_lusol (UF_long order, const cs_dl *A, double *b, double tol) ; UF_long cs_dl_gaxpy (const cs_dl *A, const double *x, double *y) ; cs_dl *cs_dl_multiply (const cs_dl *A, const cs_dl *B) ; UF_long cs_dl_qrsol (UF_long order, const cs_dl *A, double *b) ; cs_dl *cs_dl_transpose (const cs_dl *A, UF_long values) ; cs_dl *cs_dl_compress (const cs_dl *T) ; double cs_dl_norm (const cs_dl *A) ; UF_long cs_dl_print (const cs_dl *A, UF_long brief) ; cs_dl *cs_dl_load (FILE *f) ; /* utilities */ void *cs_dl_calloc (UF_long n, size_t size) ; void *cs_dl_free (void *p) ; void *cs_dl_realloc (void *p, UF_long n, size_t size, UF_long *ok) ; cs_dl *cs_dl_spalloc (UF_long m, UF_long n, UF_long nzmax, UF_long values, UF_long t) ; cs_dl *cs_dl_spfree (cs_dl *A) ; UF_long cs_dl_sprealloc (cs_dl *A, UF_long nzmax) ; void *cs_dl_malloc (UF_long n, size_t size) ; /* --- secondary CSparse routines and data structures ----------------------- */ typedef struct cs_dl_symbolic /* symbolic Cholesky, LU, or QR analysis */ { UF_long *pinv ; /* inverse row perm. for QR, fill red. perm for Chol */ UF_long *q ; /* fill-reducing column permutation for LU and QR */ UF_long *parent ; /* elimination tree for Cholesky and QR */ UF_long *cp ; /* column pointers for Cholesky, row counts for QR */ UF_long *leftmost ; /* leftmost[i] = min(find(A(i,:))), for QR */ UF_long m2 ; /* # of rows for QR, after adding fictitious rows */ double lnz ; /* # entries in L for LU or Cholesky; in V for QR */ double unz ; /* # entries in U for LU; in R for QR */ } cs_dls ; typedef struct cs_dl_numeric /* numeric Cholesky, LU, or QR factorization */ { cs_dl *L ; /* L for LU and Cholesky, V for QR */ cs_dl *U ; /* U for LU, r for QR, not used for Cholesky */ UF_long *pinv ; /* partial pivoting for LU */ double *B ; /* beta [0..n-1] for QR */ } cs_dln ; typedef struct cs_dl_dmperm_results /* cs_dl_dmperm or cs_dl_scc output */ { UF_long *p ; /* size m, row permutation */ UF_long *q ; /* size n, column permutation */ UF_long *r ; /* size nb+1, block k is rows r[k] to r[k+1]-1 in A(p,q) */ UF_long *s ; /* size nb+1, block k is cols s[k] to s[k+1]-1 in A(p,q) */ UF_long nb ; /* # of blocks in fine dmperm decomposition */ UF_long rr [5] ; /* coarse row decomposition */ UF_long cc [5] ; /* coarse column decomposition */ } cs_dld ; UF_long *cs_dl_amd (UF_long order, const cs_dl *A) ; cs_dln *cs_dl_chol (const cs_dl *A, const cs_dls *S) ; cs_dld *cs_dl_dmperm (const cs_dl *A, UF_long seed) ; UF_long cs_dl_droptol (cs_dl *A, double tol) ; UF_long cs_dl_dropzeros (cs_dl *A) ; UF_long cs_dl_happly (const cs_dl *V, UF_long i, double beta, double *x) ; UF_long cs_dl_ipvec (const UF_long *p, const double *b, double *x, UF_long n) ; UF_long cs_dl_lsolve (const cs_dl *L, double *x) ; UF_long cs_dl_ltsolve (const cs_dl *L, double *x) ; cs_dln *cs_dl_lu (const cs_dl *A, const cs_dls *S, double tol) ; cs_dl *cs_dl_permute (const cs_dl *A, const UF_long *pinv, const UF_long *q, UF_long values) ; UF_long *cs_dl_pinv (const UF_long *p, UF_long n) ; UF_long cs_dl_pvec (const UF_long *p, const double *b, double *x, UF_long n) ; cs_dln *cs_dl_qr (const cs_dl *A, const cs_dls *S) ; cs_dls *cs_dl_schol (UF_long order, const cs_dl *A) ; cs_dls *cs_dl_sqr (UF_long order, const cs_dl *A, UF_long qr) ; cs_dl *cs_dl_symperm (const cs_dl *A, const UF_long *pinv, UF_long values) ; UF_long cs_dl_usolve (const cs_dl *U, double *x) ; UF_long cs_dl_utsolve (const cs_dl *U, double *x) ; UF_long cs_dl_updown (cs_dl *L, UF_long sigma, const cs_dl *C, const UF_long *parent) ; /* utilities */ cs_dls *cs_dl_sfree (cs_dls *S) ; cs_dln *cs_dl_nfree (cs_dln *N) ; cs_dld *cs_dl_dfree (cs_dld *D) ; /* --- tertiary CSparse routines -------------------------------------------- */ UF_long *cs_dl_counts (const cs_dl *A, const UF_long *parent, const UF_long *post, UF_long ata) ; double cs_dl_cumsum (UF_long *p, UF_long *c, UF_long n) ; UF_long cs_dl_dfs (UF_long j, cs_dl *G, UF_long top, UF_long *xi, UF_long *pstack, const UF_long *pinv) ; UF_long *cs_dl_etree (const cs_dl *A, UF_long ata) ; UF_long cs_dl_fkeep (cs_dl *A, UF_long (*fkeep) (UF_long, UF_long, double, void *), void *other) ; double cs_dl_house (double *x, double *beta, UF_long n) ; UF_long *cs_dl_maxtrans (const cs_dl *A, UF_long seed) ; UF_long *cs_dl_post (const UF_long *parent, UF_long n) ; cs_dld *cs_dl_scc (cs_dl *A) ; UF_long cs_dl_scatter (const cs_dl *A, UF_long j, double beta, UF_long *w, double *x, UF_long mark,cs_dl *C, UF_long nz) ; UF_long cs_dl_tdfs (UF_long j, UF_long k, UF_long *head, const UF_long *next, UF_long *post, UF_long *stack) ; UF_long cs_dl_leaf (UF_long i, UF_long j, const UF_long *first, UF_long *maxfirst, UF_long *prevleaf, UF_long *ancestor, UF_long *jleaf) ; UF_long cs_dl_reach (cs_dl *G, const cs_dl *B, UF_long k, UF_long *xi, const UF_long *pinv) ; UF_long cs_dl_spsolve (cs_dl *L, const cs_dl *B, UF_long k, UF_long *xi, double *x, const UF_long *pinv, UF_long lo) ; UF_long cs_dl_ereach (const cs_dl *A, UF_long k, const UF_long *parent, UF_long *s, UF_long *w) ; UF_long *cs_dl_randperm (UF_long n, UF_long seed) ; /* utilities */ cs_dld *cs_dl_dalloc (UF_long m, UF_long n) ; cs_dl *cs_dl_done (cs_dl *C, void *w, void *x, UF_long ok) ; UF_long *cs_dl_idone (UF_long *p, cs_dl *C, void *w, UF_long ok) ; cs_dln *cs_dl_ndone (cs_dln *N, cs_dl *C, void *w, void *x, UF_long ok) ; cs_dld *cs_dl_ddone (cs_dld *D, cs_dl *C, void *w, UF_long ok) ; /* -------------------------------------------------------------------------- */ /* complex/int version of CXSparse */ /* -------------------------------------------------------------------------- */ #ifndef NCOMPLEX /* --- primary CSparse routines and data structures ------------------------- */ typedef struct cs_ci_sparse /* matrix in compressed-column or triplet form */ { int nzmax ; /* maximum number of entries */ int m ; /* number of rows */ int n ; /* number of columns */ int *p ; /* column pointers (size n+1) or col indices (size nzmax) */ int *i ; /* row indices, size nzmax */ cs_complex_t *x ; /* numerical values, size nzmax */ int nz ; /* # of entries in triplet matrix, -1 for compressed-col */ } cs_ci ; cs_ci *cs_ci_add (const cs_ci *A, const cs_ci *B, cs_complex_t alpha, cs_complex_t beta) ; int cs_ci_cholsol (int order, const cs_ci *A, cs_complex_t *b) ; int cs_ci_dupl (cs_ci *A) ; int cs_ci_entry (cs_ci *T, int i, int j, cs_complex_t x) ; int cs_ci_lusol (int order, const cs_ci *A, cs_complex_t *b, double tol) ; int cs_ci_gaxpy (const cs_ci *A, const cs_complex_t *x, cs_complex_t *y) ; cs_ci *cs_ci_multiply (const cs_ci *A, const cs_ci *B) ; int cs_ci_qrsol (int order, const cs_ci *A, cs_complex_t *b) ; cs_ci *cs_ci_transpose (const cs_ci *A, int values) ; cs_ci *cs_ci_compress (const cs_ci *T) ; double cs_ci_norm (const cs_ci *A) ; int cs_ci_print (const cs_ci *A, int brief) ; cs_ci *cs_ci_load (FILE *f) ; /* utilities */ void *cs_ci_calloc (int n, size_t size) ; void *cs_ci_free (void *p) ; void *cs_ci_realloc (void *p, int n, size_t size, int *ok) ; cs_ci *cs_ci_spalloc (int m, int n, int nzmax, int values, int t) ; cs_ci *cs_ci_spfree (cs_ci *A) ; int cs_ci_sprealloc (cs_ci *A, int nzmax) ; void *cs_ci_malloc (int n, size_t size) ; /* --- secondary CSparse routines and data structures ----------------------- */ typedef struct cs_ci_symbolic /* symbolic Cholesky, LU, or QR analysis */ { int *pinv ; /* inverse row perm. for QR, fill red. perm for Chol */ int *q ; /* fill-reducing column permutation for LU and QR */ int *parent ; /* elimination tree for Cholesky and QR */ int *cp ; /* column pointers for Cholesky, row counts for QR */ int *leftmost ; /* leftmost[i] = min(find(A(i,:))), for QR */ int m2 ; /* # of rows for QR, after adding fictitious rows */ double lnz ; /* # entries in L for LU or Cholesky; in V for QR */ double unz ; /* # entries in U for LU; in R for QR */ } cs_cis ; typedef struct cs_ci_numeric /* numeric Cholesky, LU, or QR factorization */ { cs_ci *L ; /* L for LU and Cholesky, V for QR */ cs_ci *U ; /* U for LU, r for QR, not used for Cholesky */ int *pinv ; /* partial pivoting for LU */ double *B ; /* beta [0..n-1] for QR */ } cs_cin ; typedef struct cs_ci_dmperm_results /* cs_ci_dmperm or cs_ci_scc output */ { int *p ; /* size m, row permutation */ int *q ; /* size n, column permutation */ int *r ; /* size nb+1, block k is rows r[k] to r[k+1]-1 in A(p,q) */ int *s ; /* size nb+1, block k is cols s[k] to s[k+1]-1 in A(p,q) */ int nb ; /* # of blocks in fine dmperm decomposition */ int rr [5] ; /* coarse row decomposition */ int cc [5] ; /* coarse column decomposition */ } cs_cid ; int *cs_ci_amd (int order, const cs_ci *A) ; cs_cin *cs_ci_chol (const cs_ci *A, const cs_cis *S) ; cs_cid *cs_ci_dmperm (const cs_ci *A, int seed) ; int cs_ci_droptol (cs_ci *A, double tol) ; int cs_ci_dropzeros (cs_ci *A) ; int cs_ci_happly (const cs_ci *V, int i, double beta, cs_complex_t *x) ; int cs_ci_ipvec (const int *p, const cs_complex_t *b, cs_complex_t *x, int n) ; int cs_ci_lsolve (const cs_ci *L, cs_complex_t *x) ; int cs_ci_ltsolve (const cs_ci *L, cs_complex_t *x) ; cs_cin *cs_ci_lu (const cs_ci *A, const cs_cis *S, double tol) ; cs_ci *cs_ci_permute (const cs_ci *A, const int *pinv, const int *q, int values) ; int *cs_ci_pinv (const int *p, int n) ; int cs_ci_pvec (const int *p, const cs_complex_t *b, cs_complex_t *x, int n) ; cs_cin *cs_ci_qr (const cs_ci *A, const cs_cis *S) ; cs_cis *cs_ci_schol (int order, const cs_ci *A) ; cs_cis *cs_ci_sqr (int order, const cs_ci *A, int qr) ; cs_ci *cs_ci_symperm (const cs_ci *A, const int *pinv, int values) ; int cs_ci_usolve (const cs_ci *U, cs_complex_t *x) ; int cs_ci_utsolve (const cs_ci *U, cs_complex_t *x) ; int cs_ci_updown (cs_ci *L, int sigma, const cs_ci *C, const int *parent) ; /* utilities */ cs_cis *cs_ci_sfree (cs_cis *S) ; cs_cin *cs_ci_nfree (cs_cin *N) ; cs_cid *cs_ci_dfree (cs_cid *D) ; /* --- tertiary CSparse routines -------------------------------------------- */ int *cs_ci_counts (const cs_ci *A, const int *parent, const int *post, int ata) ; double cs_ci_cumsum (int *p, int *c, int n) ; int cs_ci_dfs (int j, cs_ci *G, int top, int *xi, int *pstack, const int *pinv) ; int *cs_ci_etree (const cs_ci *A, int ata) ; int cs_ci_fkeep (cs_ci *A, int (*fkeep) (int, int, cs_complex_t, void *), void *other) ; cs_complex_t cs_ci_house (cs_complex_t *x, double *beta, int n) ; int *cs_ci_maxtrans (const cs_ci *A, int seed) ; int *cs_ci_post (const int *parent, int n) ; cs_cid *cs_ci_scc (cs_ci *A) ; int cs_ci_scatter (const cs_ci *A, int j, cs_complex_t beta, int *w, cs_complex_t *x, int mark,cs_ci *C, int nz) ; int cs_ci_tdfs (int j, int k, int *head, const int *next, int *post, int *stack) ; int cs_ci_leaf (int i, int j, const int *first, int *maxfirst, int *prevleaf, int *ancestor, int *jleaf) ; int cs_ci_reach (cs_ci *G, const cs_ci *B, int k, int *xi, const int *pinv) ; int cs_ci_spsolve (cs_ci *L, const cs_ci *B, int k, int *xi, cs_complex_t *x, const int *pinv, int lo) ; int cs_ci_ereach (const cs_ci *A, int k, const int *parent, int *s, int *w) ; int *cs_ci_randperm (int n, int seed) ; /* utilities */ cs_cid *cs_ci_dalloc (int m, int n) ; cs_ci *cs_ci_done (cs_ci *C, void *w, void *x, int ok) ; int *cs_ci_idone (int *p, cs_ci *C, void *w, int ok) ; cs_cin *cs_ci_ndone (cs_cin *N, cs_ci *C, void *w, void *x, int ok) ; cs_cid *cs_ci_ddone (cs_cid *D, cs_ci *C, void *w, int ok) ; /* -------------------------------------------------------------------------- */ /* complex/UF_long version of CXSparse */ /* -------------------------------------------------------------------------- */ /* --- primary CSparse routines and data structures ------------------------- */ typedef struct cs_cl_sparse /* matrix in compressed-column or triplet form */ { UF_long nzmax ; /* maximum number of entries */ UF_long m ; /* number of rows */ UF_long n ; /* number of columns */ UF_long *p ; /* column pointers (size n+1) or col indlces (size nzmax) */ UF_long *i ; /* row indices, size nzmax */ cs_complex_t *x ; /* numerical values, size nzmax */ UF_long nz ; /* # of entries in triplet matrix, -1 for compressed-col */ } cs_cl ; cs_cl *cs_cl_add (const cs_cl *A, const cs_cl *B, cs_complex_t alpha, cs_complex_t beta) ; UF_long cs_cl_cholsol (UF_long order, const cs_cl *A, cs_complex_t *b) ; UF_long cs_cl_dupl (cs_cl *A) ; UF_long cs_cl_entry (cs_cl *T, UF_long i, UF_long j, cs_complex_t x) ; UF_long cs_cl_lusol (UF_long order, const cs_cl *A, cs_complex_t *b, double tol) ; UF_long cs_cl_gaxpy (const cs_cl *A, const cs_complex_t *x, cs_complex_t *y) ; cs_cl *cs_cl_multiply (const cs_cl *A, const cs_cl *B) ; UF_long cs_cl_qrsol (UF_long order, const cs_cl *A, cs_complex_t *b) ; cs_cl *cs_cl_transpose (const cs_cl *A, UF_long values) ; cs_cl *cs_cl_compress (const cs_cl *T) ; double cs_cl_norm (const cs_cl *A) ; UF_long cs_cl_print (const cs_cl *A, UF_long brief) ; cs_cl *cs_cl_load (FILE *f) ; /* utilities */ void *cs_cl_calloc (UF_long n, size_t size) ; void *cs_cl_free (void *p) ; void *cs_cl_realloc (void *p, UF_long n, size_t size, UF_long *ok) ; cs_cl *cs_cl_spalloc (UF_long m, UF_long n, UF_long nzmax, UF_long values, UF_long t) ; cs_cl *cs_cl_spfree (cs_cl *A) ; UF_long cs_cl_sprealloc (cs_cl *A, UF_long nzmax) ; void *cs_cl_malloc (UF_long n, size_t size) ; /* --- secondary CSparse routines and data structures ----------------------- */ typedef struct cs_cl_symbolic /* symbolic Cholesky, LU, or QR analysis */ { UF_long *pinv ; /* inverse row perm. for QR, fill red. perm for Chol */ UF_long *q ; /* fill-reducing column permutation for LU and QR */ UF_long *parent ; /* elimination tree for Cholesky and QR */ UF_long *cp ; /* column pointers for Cholesky, row counts for QR */ UF_long *leftmost ; /* leftmost[i] = min(find(A(i,:))), for QR */ UF_long m2 ; /* # of rows for QR, after adding fictitious rows */ double lnz ; /* # entries in L for LU or Cholesky; in V for QR */ double unz ; /* # entries in U for LU; in R for QR */ } cs_cls ; typedef struct cs_cl_numeric /* numeric Cholesky, LU, or QR factorization */ { cs_cl *L ; /* L for LU and Cholesky, V for QR */ cs_cl *U ; /* U for LU, r for QR, not used for Cholesky */ UF_long *pinv ; /* partial pivoting for LU */ double *B ; /* beta [0..n-1] for QR */ } cs_cln ; typedef struct cs_cl_dmperm_results /* cs_cl_dmperm or cs_cl_scc output */ { UF_long *p ; /* size m, row permutation */ UF_long *q ; /* size n, column permutation */ UF_long *r ; /* size nb+1, block k is rows r[k] to r[k+1]-1 in A(p,q) */ UF_long *s ; /* size nb+1, block k is cols s[k] to s[k+1]-1 in A(p,q) */ UF_long nb ; /* # of blocks in fine dmperm decomposition */ UF_long rr [5] ; /* coarse row decomposition */ UF_long cc [5] ; /* coarse column decomposition */ } cs_cld ; UF_long *cs_cl_amd (UF_long order, const cs_cl *A) ; cs_cln *cs_cl_chol (const cs_cl *A, const cs_cls *S) ; cs_cld *cs_cl_dmperm (const cs_cl *A, UF_long seed) ; UF_long cs_cl_droptol (cs_cl *A, double tol) ; UF_long cs_cl_dropzeros (cs_cl *A) ; UF_long cs_cl_happly (const cs_cl *V, UF_long i, double beta, cs_complex_t *x) ; UF_long cs_cl_ipvec (const UF_long *p, const cs_complex_t *b, cs_complex_t *x, UF_long n) ; UF_long cs_cl_lsolve (const cs_cl *L, cs_complex_t *x) ; UF_long cs_cl_ltsolve (const cs_cl *L, cs_complex_t *x) ; cs_cln *cs_cl_lu (const cs_cl *A, const cs_cls *S, double tol) ; cs_cl *cs_cl_permute (const cs_cl *A, const UF_long *pinv, const UF_long *q, UF_long values) ; UF_long *cs_cl_pinv (const UF_long *p, UF_long n) ; UF_long cs_cl_pvec (const UF_long *p, const cs_complex_t *b, cs_complex_t *x, UF_long n) ; cs_cln *cs_cl_qr (const cs_cl *A, const cs_cls *S) ; cs_cls *cs_cl_schol (UF_long order, const cs_cl *A) ; cs_cls *cs_cl_sqr (UF_long order, const cs_cl *A, UF_long qr) ; cs_cl *cs_cl_symperm (const cs_cl *A, const UF_long *pinv, UF_long values) ; UF_long cs_cl_usolve (const cs_cl *U, cs_complex_t *x) ; UF_long cs_cl_utsolve (const cs_cl *U, cs_complex_t *x) ; UF_long cs_cl_updown (cs_cl *L, UF_long sigma, const cs_cl *C, const UF_long *parent) ; /* utilities */ cs_cls *cs_cl_sfree (cs_cls *S) ; cs_cln *cs_cl_nfree (cs_cln *N) ; cs_cld *cs_cl_dfree (cs_cld *D) ; /* --- tertiary CSparse routines -------------------------------------------- */ UF_long *cs_cl_counts (const cs_cl *A, const UF_long *parent, const UF_long *post, UF_long ata) ; double cs_cl_cumsum (UF_long *p, UF_long *c, UF_long n) ; UF_long cs_cl_dfs (UF_long j, cs_cl *G, UF_long top, UF_long *xi, UF_long *pstack, const UF_long *pinv) ; UF_long *cs_cl_etree (const cs_cl *A, UF_long ata) ; UF_long cs_cl_fkeep (cs_cl *A, UF_long (*fkeep) (UF_long, UF_long, cs_complex_t, void *), void *other) ; cs_complex_t cs_cl_house (cs_complex_t *x, double *beta, UF_long n) ; UF_long *cs_cl_maxtrans (const cs_cl *A, UF_long seed) ; UF_long *cs_cl_post (const UF_long *parent, UF_long n) ; cs_cld *cs_cl_scc (cs_cl *A) ; UF_long cs_cl_scatter (const cs_cl *A, UF_long j, cs_complex_t beta, UF_long *w, cs_complex_t *x, UF_long mark,cs_cl *C, UF_long nz) ; UF_long cs_cl_tdfs (UF_long j, UF_long k, UF_long *head, const UF_long *next, UF_long *post, UF_long *stack) ; UF_long cs_cl_leaf (UF_long i, UF_long j, const UF_long *first, UF_long *maxfirst, UF_long *prevleaf, UF_long *ancestor, UF_long *jleaf) ; UF_long cs_cl_reach (cs_cl *G, const cs_cl *B, UF_long k, UF_long *xi, const UF_long *pinv) ; UF_long cs_cl_spsolve (cs_cl *L, const cs_cl *B, UF_long k, UF_long *xi, cs_complex_t *x, const UF_long *pinv, UF_long lo) ; UF_long cs_cl_ereach (const cs_cl *A, UF_long k, const UF_long *parent, UF_long *s, UF_long *w) ; UF_long *cs_cl_randperm (UF_long n, UF_long seed) ; /* utilities */ cs_cld *cs_cl_dalloc (UF_long m, UF_long n) ; cs_cl *cs_cl_done (cs_cl *C, void *w, void *x, UF_long ok) ; UF_long *cs_cl_idone (UF_long *p, cs_cl *C, void *w, UF_long ok) ; cs_cln *cs_cl_ndone (cs_cln *N, cs_cl *C, void *w, void *x, UF_long ok) ; cs_cld *cs_cl_ddone (cs_cld *D, cs_cl *C, void *w, UF_long ok) ; #endif /* -------------------------------------------------------------------------- */ /* Macros for constructing each version of CSparse */ /* -------------------------------------------------------------------------- */ #ifdef CS_LONG #define CS_INT UF_long #define CS_INT_MAX UF_long_max #define CS_ID UF_long_id #ifdef CS_COMPLEX #define CS_ENTRY cs_complex_t #define CS_NAME(nm) cs_cl ## nm #define cs cs_cl #else #define CS_ENTRY double #define CS_NAME(nm) cs_dl ## nm #define cs cs_dl #endif #else #define CS_INT int #define CS_INT_MAX INT_MAX #define CS_ID "%d" #ifdef CS_COMPLEX #define CS_ENTRY cs_complex_t #define CS_NAME(nm) cs_ci ## nm #define cs cs_ci #else #define CS_ENTRY double #define CS_NAME(nm) cs_di ## nm #define cs cs_di #endif #endif #ifdef CS_COMPLEX #define CS_REAL(x) creal(x) #define CS_IMAG(x) cimag(x) #define CS_CONJ(x) conj(x) #define CS_ABS(x) cabs(x) #else #define CS_REAL(x) (x) #define CS_IMAG(x) (0.) #define CS_CONJ(x) (x) #define CS_ABS(x) fabs(x) #endif #define CS_MAX(a,b) (((a) > (b)) ? (a) : (b)) #define CS_MIN(a,b) (((a) < (b)) ? (a) : (b)) #define CS_FLIP(i) (-(i)-2) #define CS_UNFLIP(i) (((i) < 0) ? CS_FLIP(i) : (i)) #define CS_MARKED(w,j) (w [j] < 0) #define CS_MARK(w,j) { w [j] = CS_FLIP (w [j]) ; } #define CS_CSC(A) (A && (A->nz == -1)) #define CS_TRIPLET(A) (A && (A->nz >= 0)) /* --- primary CSparse routines and data structures ------------------------- */ #define cs_add CS_NAME (_add) #define cs_cholsol CS_NAME (_cholsol) #define cs_dupl CS_NAME (_dupl) #define cs_entry CS_NAME (_entry) #define cs_lusol CS_NAME (_lusol) #define cs_gaxpy CS_NAME (_gaxpy) #define cs_multiply CS_NAME (_multiply) #define cs_qrsol CS_NAME (_qrsol) #define cs_transpose CS_NAME (_transpose) #define cs_compress CS_NAME (_compress) #define cs_norm CS_NAME (_norm) #define cs_print CS_NAME (_print) #define cs_load CS_NAME (_load) /* utilities */ #define cs_calloc CS_NAME (_calloc) #define cs_free CS_NAME (_free) #define cs_realloc CS_NAME (_realloc) #define cs_spalloc CS_NAME (_spalloc) #define cs_spfree CS_NAME (_spfree) #define cs_sprealloc CS_NAME (_sprealloc) #define cs_malloc CS_NAME (_malloc) /* --- secondary CSparse routines and data structures ----------------------- */ #define css CS_NAME (s) #define csn CS_NAME (n) #define csd CS_NAME (d) #define cs_amd CS_NAME (_amd) #define cs_chol CS_NAME (_chol) #define cs_dmperm CS_NAME (_dmperm) #define cs_droptol CS_NAME (_droptol) #define cs_dropzeros CS_NAME (_dropzeros) #define cs_happly CS_NAME (_happly) #define cs_ipvec CS_NAME (_ipvec) #define cs_lsolve CS_NAME (_lsolve) #define cs_ltsolve CS_NAME (_ltsolve) #define cs_lu CS_NAME (_lu) #define cs_permute CS_NAME (_permute) #define cs_pinv CS_NAME (_pinv) #define cs_pvec CS_NAME (_pvec) #define cs_qr CS_NAME (_qr) #define cs_schol CS_NAME (_schol) #define cs_sqr CS_NAME (_sqr) #define cs_symperm CS_NAME (_symperm) #define cs_usolve CS_NAME (_usolve) #define cs_utsolve CS_NAME (_utsolve) #define cs_updown CS_NAME (_updown) /* utilities */ #define cs_sfree CS_NAME (_sfree) #define cs_nfree CS_NAME (_nfree) #define cs_dfree CS_NAME (_dfree) /* --- tertiary CSparse routines -------------------------------------------- */ #define cs_counts CS_NAME (_counts) #define cs_cumsum CS_NAME (_cumsum) #define cs_dfs CS_NAME (_dfs) #define cs_etree CS_NAME (_etree) #define cs_fkeep CS_NAME (_fkeep) #define cs_house CS_NAME (_house) #define cs_invmatch CS_NAME (_invmatch) #define cs_maxtrans CS_NAME (_maxtrans) #define cs_post CS_NAME (_post) #define cs_scc CS_NAME (_scc) #define cs_scatter CS_NAME (_scatter) #define cs_tdfs CS_NAME (_tdfs) #define cs_reach CS_NAME (_reach) #define cs_spsolve CS_NAME (_spsolve) #define cs_ereach CS_NAME (_ereach) #define cs_randperm CS_NAME (_randperm) #define cs_leaf CS_NAME (_leaf) /* utilities */ #define cs_dalloc CS_NAME (_dalloc) #define cs_done CS_NAME (_done) #define cs_idone CS_NAME (_idone) #define cs_ndone CS_NAME (_ndone) #define cs_ddone CS_NAME (_ddone) /* -------------------------------------------------------------------------- */ /* Conversion routines */ /* -------------------------------------------------------------------------- */ #ifndef NCOMPLEX cs_di *cs_i_real (cs_ci *A, int real) ; cs_ci *cs_i_complex (cs_di *A, int real) ; cs_dl *cs_l_real (cs_cl *A, UF_long real) ; cs_cl *cs_l_complex (cs_dl *A, UF_long real) ; #endif #ifdef __cplusplus } #endif #endif igraph/src/cs/cs_pvec.c0000644000175100001440000000231113431000472014513 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x = b(p), for dense vectors x and b; p=NULL denotes identity */ CS_INT cs_pvec (const CS_INT *p, const CS_ENTRY *b, CS_ENTRY *x, CS_INT n) { CS_INT k ; if (!x || !b) return (0) ; /* check inputs */ for (k = 0 ; k < n ; k++) x [k] = b [p ? p [k] : k] ; return (1) ; } igraph/src/cs/cs_load.c0000644000175100001440000000304613431000472014503 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* load a triplet matrix from a file */ cs *cs_load (FILE *f) { CS_INT i, j ; double x ; #ifdef CS_COMPLEX double xi ; #endif cs *T ; if (!f) return (NULL) ; /* check inputs */ T = cs_spalloc (0, 0, 1, 1, 1) ; /* allocate result */ #ifdef CS_COMPLEX while (fscanf (f, ""CS_ID" "CS_ID" %lg %lg\n", &i, &j, &x, &xi) == 4) #else while (fscanf (f, ""CS_ID" "CS_ID" %lg\n", &i, &j, &x) == 3) #endif { #ifdef CS_COMPLEX if (!cs_entry (T, i, j, x + xi*I)) return (cs_spfree (T)) ; #else if (!cs_entry (T, i, j, x)) return (cs_spfree (T)) ; #endif } return (T) ; } igraph/src/cs/cs_etree.c0000644000175100001440000000433513431000472014672 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* compute the etree of A (using triu(A), or A'A without forming A'A */ CS_INT *cs_etree (const cs *A, CS_INT ata) { CS_INT i, k, p, m, n, inext, *Ap, *Ai, *w, *parent, *ancestor, *prev ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; parent = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result */ w = cs_malloc (n + (ata ? m : 0), sizeof (CS_INT)) ; /* get workspace */ if (!w || !parent) return (cs_idone (parent, NULL, w, 0)) ; ancestor = w ; prev = w + n ; if (ata) for (i = 0 ; i < m ; i++) prev [i] = -1 ; for (k = 0 ; k < n ; k++) { parent [k] = -1 ; /* node k has no parent yet */ ancestor [k] = -1 ; /* nor does k have an ancestor */ for (p = Ap [k] ; p < Ap [k+1] ; p++) { i = ata ? (prev [Ai [p]]) : (Ai [p]) ; for ( ; i != -1 && i < k ; i = inext) /* traverse from i to k */ { inext = ancestor [i] ; /* inext = ancestor of i */ ancestor [i] = k ; /* path compression */ if (inext == -1) parent [i] = k ; /* no anc., parent is k */ } if (ata) prev [Ai [p]] = k ; } } return (cs_idone (parent, NULL, w, 1)) ; } igraph/src/cs/cs_norm.c0000644000175100001440000000253513431000472014541 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* 1-norm of a sparse matrix = max (sum (abs (A))), largest column sum */ double cs_norm (const cs *A) { CS_INT p, j, n, *Ap ; CS_ENTRY *Ax ; double norm = 0, s ; if (!CS_CSC (A) || !A->x) return (-1) ; /* check inputs */ n = A->n ; Ap = A->p ; Ax = A->x ; for (j = 0 ; j < n ; j++) { for (s = 0, p = Ap [j] ; p < Ap [j+1] ; p++) s += CS_ABS (Ax [p]) ; norm = CS_MAX (norm, s) ; } return (norm) ; } igraph/src/cs/cs_dropzeros.c0000644000175100001440000000214313431000472015610 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" static CS_INT cs_nonzero (CS_INT i, CS_INT j, CS_ENTRY aij, void *other) { return (aij != 0) ; } CS_INT cs_dropzeros (cs *A) { return (cs_fkeep (A, &cs_nonzero, NULL)) ; /* keep all nonzero entries */ } igraph/src/cs/cs_ltsolve.c0000644000175100001440000000264113431000472015254 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* solve L'x=b where x and b are dense. x=b on input, solution on output. */ CS_INT cs_ltsolve (const cs *L, CS_ENTRY *x) { CS_INT p, j, n, *Lp, *Li ; CS_ENTRY *Lx ; if (!CS_CSC (L) || !x) return (0) ; /* check inputs */ n = L->n ; Lp = L->p ; Li = L->i ; Lx = L->x ; for (j = n-1 ; j >= 0 ; j--) { for (p = Lp [j]+1 ; p < Lp [j+1] ; p++) { x [j] -= CS_CONJ (Lx [p]) * x [Li [p]] ; } x [j] /= CS_CONJ (Lx [Lp [j]]) ; } return (1) ; } igraph/src/cs/cs_lsolve.c0000644000175100001440000000261013431000472015064 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* solve Lx=b where x and b are dense. x=b on input, solution on output. */ CS_INT cs_lsolve (const cs *L, CS_ENTRY *x) { CS_INT p, j, n, *Lp, *Li ; CS_ENTRY *Lx ; if (!CS_CSC (L) || !x) return (0) ; /* check inputs */ n = L->n ; Lp = L->p ; Li = L->i ; Lx = L->x ; for (j = 0 ; j < n ; j++) { x [j] /= Lx [Lp [j]] ; for (p = Lp [j]+1 ; p < Lp [j+1] ; p++) { x [Li [p]] -= Lx [p] * x [j] ; } } return (1) ; } igraph/src/cs/cs_compress.c0000644000175100001440000000355313431000472015422 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = compressed-column form of a triplet matrix T */ cs *cs_compress (const cs *T) { CS_INT m, n, nz, p, k, *Cp, *Ci, *w, *Ti, *Tj ; CS_ENTRY *Cx, *Tx ; cs *C ; if (!CS_TRIPLET (T)) return (NULL) ; /* check inputs */ m = T->m ; n = T->n ; Ti = T->i ; Tj = T->p ; Tx = T->x ; nz = T->nz ; C = cs_spalloc (m, n, nz, Tx != NULL, 0) ; /* allocate result */ w = cs_calloc (n, sizeof (CS_INT)) ; /* get workspace */ if (!C || !w) return (cs_done (C, w, NULL, 0)) ; /* out of memory */ Cp = C->p ; Ci = C->i ; Cx = C->x ; for (k = 0 ; k < nz ; k++) w [Tj [k]]++ ; /* column counts */ cs_cumsum (Cp, w, n) ; /* column pointers */ for (k = 0 ; k < nz ; k++) { Ci [p = w [Tj [k]]++] = Ti [k] ; /* A(i,j) is the pth entry in C */ if (Cx) Cx [p] = Tx [k] ; } return (cs_done (C, w, NULL, 1)) ; /* success; free w and return C */ } igraph/src/cs/cs_amd.c0000644000175100001440000004201113431000472014320 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* clear w */ static CS_INT cs_wclear (CS_INT mark, CS_INT lemax, CS_INT *w, CS_INT n) { CS_INT k ; if (mark < 2 || (mark + lemax < 0)) { for (k = 0 ; k < n ; k++) if (w [k] != 0) w [k] = 1 ; mark = 2 ; } return (mark) ; /* at this point, w [0..n-1] < mark holds */ } /* keep off-diagonal entries; drop diagonal entries */ static CS_INT cs_diag (CS_INT i, CS_INT j, CS_ENTRY aij, void *other) { return (i != j) ; } /* p = amd(A+A') if symmetric is true, or amd(A'A) otherwise */ CS_INT *cs_amd (CS_INT order, const cs *A) /* order 0:natural, 1:Chol, 2:LU, 3:QR */ { cs *C, *A2, *AT ; CS_INT *Cp, *Ci, *last, *W, *len, *nv, *next, *P, *head, *elen, *degree, *w, *hhead, *ATp, *ATi, d, dk, dext, lemax = 0, e, elenk, eln, i, j, k, k1, k2, k3, jlast, ln, dense, nzmax, mindeg = 0, nvi, nvj, nvk, mark, wnvi, ok, cnz, nel = 0, p, p1, p2, p3, p4, pj, pk, pk1, pk2, pn, q, n, m, t ; unsigned CS_INT h ; /* --- Construct matrix C ----------------------------------------------- */ if (!CS_CSC (A) || order <= 0 || order > 3) return (NULL) ; /* check */ AT = cs_transpose (A, 0) ; /* compute A' */ if (!AT) return (NULL) ; m = A->m ; n = A->n ; dense = CS_MAX (16, 10 * sqrt ((double) n)) ; /* find dense threshold */ dense = CS_MIN (n-2, dense) ; if (order == 1 && n == m) { C = cs_add (A, AT, 0, 0) ; /* C = A+A' */ } else if (order == 2) { ATp = AT->p ; /* drop dense columns from AT */ ATi = AT->i ; for (p2 = 0, j = 0 ; j < m ; j++) { p = ATp [j] ; /* column j of AT starts here */ ATp [j] = p2 ; /* new column j starts here */ if (ATp [j+1] - p > dense) continue ; /* skip dense col j */ for ( ; p < ATp [j+1] ; p++) ATi [p2++] = ATi [p] ; } ATp [m] = p2 ; /* finalize AT */ A2 = cs_transpose (AT, 0) ; /* A2 = AT' */ C = A2 ? cs_multiply (AT, A2) : NULL ; /* C=A'*A with no dense rows */ cs_spfree (A2) ; } else { C = cs_multiply (AT, A) ; /* C=A'*A */ } cs_spfree (AT) ; if (!C) return (NULL) ; cs_fkeep (C, &cs_diag, NULL) ; /* drop diagonal entries */ Cp = C->p ; cnz = Cp [n] ; P = cs_malloc (n+1, sizeof (CS_INT)) ; /* allocate result */ W = cs_malloc (8*(n+1), sizeof (CS_INT)) ; /* get workspace */ t = cnz + cnz/5 + 2*n ; /* add elbow room to C */ if (!P || !W || !cs_sprealloc (C, t)) return (cs_idone (P, C, W, 0)) ; len = W ; nv = W + (n+1) ; next = W + 2*(n+1) ; head = W + 3*(n+1) ; elen = W + 4*(n+1) ; degree = W + 5*(n+1) ; w = W + 6*(n+1) ; hhead = W + 7*(n+1) ; last = P ; /* use P as workspace for last */ /* --- Initialize quotient graph ---------------------------------------- */ for (k = 0 ; k < n ; k++) len [k] = Cp [k+1] - Cp [k] ; len [n] = 0 ; nzmax = C->nzmax ; Ci = C->i ; for (i = 0 ; i <= n ; i++) { head [i] = -1 ; /* degree list i is empty */ last [i] = -1 ; next [i] = -1 ; hhead [i] = -1 ; /* hash list i is empty */ nv [i] = 1 ; /* node i is just one node */ w [i] = 1 ; /* node i is alive */ elen [i] = 0 ; /* Ek of node i is empty */ degree [i] = len [i] ; /* degree of node i */ } mark = cs_wclear (0, 0, w, n) ; /* clear w */ elen [n] = -2 ; /* n is a dead element */ Cp [n] = -1 ; /* n is a root of assembly tree */ w [n] = 0 ; /* n is a dead element */ /* --- Initialize degree lists ------------------------------------------ */ for (i = 0 ; i < n ; i++) { d = degree [i] ; if (d == 0) /* node i is empty */ { elen [i] = -2 ; /* element i is dead */ nel++ ; Cp [i] = -1 ; /* i is a root of assembly tree */ w [i] = 0 ; } else if (d > dense) /* node i is dense */ { nv [i] = 0 ; /* absorb i into element n */ elen [i] = -1 ; /* node i is dead */ nel++ ; Cp [i] = CS_FLIP (n) ; nv [n]++ ; } else { if (head [d] != -1) last [head [d]] = i ; next [i] = head [d] ; /* put node i in degree list d */ head [d] = i ; } } while (nel < n) /* while (selecting pivots) do */ { /* --- Select node of minimum approximate degree -------------------- */ for (k = -1 ; mindeg < n && (k = head [mindeg]) == -1 ; mindeg++) ; if (next [k] != -1) last [next [k]] = -1 ; head [mindeg] = next [k] ; /* remove k from degree list */ elenk = elen [k] ; /* elenk = |Ek| */ nvk = nv [k] ; /* # of nodes k represents */ nel += nvk ; /* nv[k] nodes of A eliminated */ /* --- Garbage collection ------------------------------------------- */ if (elenk > 0 && cnz + mindeg >= nzmax) { for (j = 0 ; j < n ; j++) { if ((p = Cp [j]) >= 0) /* j is a live node or element */ { Cp [j] = Ci [p] ; /* save first entry of object */ Ci [p] = CS_FLIP (j) ; /* first entry is now CS_FLIP(j) */ } } for (q = 0, p = 0 ; p < cnz ; ) /* scan all of memory */ { if ((j = CS_FLIP (Ci [p++])) >= 0) /* found object j */ { Ci [q] = Cp [j] ; /* restore first entry of object */ Cp [j] = q++ ; /* new pointer to object j */ for (k3 = 0 ; k3 < len [j]-1 ; k3++) Ci [q++] = Ci [p++] ; } } cnz = q ; /* Ci [cnz...nzmax-1] now free */ } /* --- Construct new element ---------------------------------------- */ dk = 0 ; nv [k] = -nvk ; /* flag k as in Lk */ p = Cp [k] ; pk1 = (elenk == 0) ? p : cnz ; /* do in place if elen[k] == 0 */ pk2 = pk1 ; for (k1 = 1 ; k1 <= elenk + 1 ; k1++) { if (k1 > elenk) { e = k ; /* search the nodes in k */ pj = p ; /* list of nodes starts at Ci[pj]*/ ln = len [k] - elenk ; /* length of list of nodes in k */ } else { e = Ci [p++] ; /* search the nodes in e */ pj = Cp [e] ; ln = len [e] ; /* length of list of nodes in e */ } for (k2 = 1 ; k2 <= ln ; k2++) { i = Ci [pj++] ; if ((nvi = nv [i]) <= 0) continue ; /* node i dead, or seen */ dk += nvi ; /* degree[Lk] += size of node i */ nv [i] = -nvi ; /* negate nv[i] to denote i in Lk*/ Ci [pk2++] = i ; /* place i in Lk */ if (next [i] != -1) last [next [i]] = last [i] ; if (last [i] != -1) /* remove i from degree list */ { next [last [i]] = next [i] ; } else { head [degree [i]] = next [i] ; } } if (e != k) { Cp [e] = CS_FLIP (k) ; /* absorb e into k */ w [e] = 0 ; /* e is now a dead element */ } } if (elenk != 0) cnz = pk2 ; /* Ci [cnz...nzmax] is free */ degree [k] = dk ; /* external degree of k - |Lk\i| */ Cp [k] = pk1 ; /* element k is in Ci[pk1..pk2-1] */ len [k] = pk2 - pk1 ; elen [k] = -2 ; /* k is now an element */ /* --- Find set differences ----------------------------------------- */ mark = cs_wclear (mark, lemax, w, n) ; /* clear w if necessary */ for (pk = pk1 ; pk < pk2 ; pk++) /* scan 1: find |Le\Lk| */ { i = Ci [pk] ; if ((eln = elen [i]) <= 0) continue ;/* skip if elen[i] empty */ nvi = -nv [i] ; /* nv [i] was negated */ wnvi = mark - nvi ; for (p = Cp [i] ; p <= Cp [i] + eln - 1 ; p++) /* scan Ei */ { e = Ci [p] ; if (w [e] >= mark) { w [e] -= nvi ; /* decrement |Le\Lk| */ } else if (w [e] != 0) /* ensure e is a live element */ { w [e] = degree [e] + wnvi ; /* 1st time e seen in scan 1 */ } } } /* --- Degree update ------------------------------------------------ */ for (pk = pk1 ; pk < pk2 ; pk++) /* scan2: degree update */ { i = Ci [pk] ; /* consider node i in Lk */ p1 = Cp [i] ; p2 = p1 + elen [i] - 1 ; pn = p1 ; for (h = 0, d = 0, p = p1 ; p <= p2 ; p++) /* scan Ei */ { e = Ci [p] ; if (w [e] != 0) /* e is an unabsorbed element */ { dext = w [e] - mark ; /* dext = |Le\Lk| */ if (dext > 0) { d += dext ; /* sum up the set differences */ Ci [pn++] = e ; /* keep e in Ei */ h += e ; /* compute the hash of node i */ } else { Cp [e] = CS_FLIP (k) ; /* aggressive absorb. e->k */ w [e] = 0 ; /* e is a dead element */ } } } elen [i] = pn - p1 + 1 ; /* elen[i] = |Ei| */ p3 = pn ; p4 = p1 + len [i] ; for (p = p2 + 1 ; p < p4 ; p++) /* prune edges in Ai */ { j = Ci [p] ; if ((nvj = nv [j]) <= 0) continue ; /* node j dead or in Lk */ d += nvj ; /* degree(i) += |j| */ Ci [pn++] = j ; /* place j in node list of i */ h += j ; /* compute hash for node i */ } if (d == 0) /* check for mass elimination */ { Cp [i] = CS_FLIP (k) ; /* absorb i into k */ nvi = -nv [i] ; dk -= nvi ; /* |Lk| -= |i| */ nvk += nvi ; /* |k| += nv[i] */ nel += nvi ; nv [i] = 0 ; elen [i] = -1 ; /* node i is dead */ } else { degree [i] = CS_MIN (degree [i], d) ; /* update degree(i) */ Ci [pn] = Ci [p3] ; /* move first node to end */ Ci [p3] = Ci [p1] ; /* move 1st el. to end of Ei */ Ci [p1] = k ; /* add k as 1st element in of Ei */ len [i] = pn - p1 + 1 ; /* new len of adj. list of node i */ h %= n ; /* finalize hash of i */ next [i] = hhead [h] ; /* place i in hash bucket */ hhead [h] = i ; last [i] = h ; /* save hash of i in last[i] */ } } /* scan2 is done */ degree [k] = dk ; /* finalize |Lk| */ lemax = CS_MAX (lemax, dk) ; mark = cs_wclear (mark+lemax, lemax, w, n) ; /* clear w */ /* --- Supernode detection ------------------------------------------ */ for (pk = pk1 ; pk < pk2 ; pk++) { i = Ci [pk] ; if (nv [i] >= 0) continue ; /* skip if i is dead */ h = last [i] ; /* scan hash bucket of node i */ i = hhead [h] ; hhead [h] = -1 ; /* hash bucket will be empty */ for ( ; i != -1 && next [i] != -1 ; i = next [i], mark++) { ln = len [i] ; eln = elen [i] ; for (p = Cp [i]+1 ; p <= Cp [i] + ln-1 ; p++) w [Ci [p]] = mark; jlast = i ; for (j = next [i] ; j != -1 ; ) /* compare i with all j */ { ok = (len [j] == ln) && (elen [j] == eln) ; for (p = Cp [j] + 1 ; ok && p <= Cp [j] + ln - 1 ; p++) { if (w [Ci [p]] != mark) ok = 0 ; /* compare i and j*/ } if (ok) /* i and j are identical */ { Cp [j] = CS_FLIP (i) ; /* absorb j into i */ nv [i] += nv [j] ; nv [j] = 0 ; elen [j] = -1 ; /* node j is dead */ j = next [j] ; /* delete j from hash bucket */ next [jlast] = j ; } else { jlast = j ; /* j and i are different */ j = next [j] ; } } } } /* --- Finalize new element------------------------------------------ */ for (p = pk1, pk = pk1 ; pk < pk2 ; pk++) /* finalize Lk */ { i = Ci [pk] ; if ((nvi = -nv [i]) <= 0) continue ;/* skip if i is dead */ nv [i] = nvi ; /* restore nv[i] */ d = degree [i] + dk - nvi ; /* compute external degree(i) */ d = CS_MIN (d, n - nel - nvi) ; if (head [d] != -1) last [head [d]] = i ; next [i] = head [d] ; /* put i back in degree list */ last [i] = -1 ; head [d] = i ; mindeg = CS_MIN (mindeg, d) ; /* find new minimum degree */ degree [i] = d ; Ci [p++] = i ; /* place i in Lk */ } nv [k] = nvk ; /* # nodes absorbed into k */ if ((len [k] = p-pk1) == 0) /* length of adj list of element k*/ { Cp [k] = -1 ; /* k is a root of the tree */ w [k] = 0 ; /* k is now a dead element */ } if (elenk != 0) cnz = p ; /* free unused space in Lk */ } /* --- Postordering ----------------------------------------------------- */ for (i = 0 ; i < n ; i++) Cp [i] = CS_FLIP (Cp [i]) ;/* fix assembly tree */ for (j = 0 ; j <= n ; j++) head [j] = -1 ; for (j = n ; j >= 0 ; j--) /* place unordered nodes in lists */ { if (nv [j] > 0) continue ; /* skip if j is an element */ next [j] = head [Cp [j]] ; /* place j in list of its parent */ head [Cp [j]] = j ; } for (e = n ; e >= 0 ; e--) /* place elements in lists */ { if (nv [e] <= 0) continue ; /* skip unless e is an element */ if (Cp [e] != -1) { next [e] = head [Cp [e]] ; /* place e in list of its parent */ head [Cp [e]] = e ; } } for (k = 0, i = 0 ; i <= n ; i++) /* postorder the assembly tree */ { if (Cp [i] == -1) k = cs_tdfs (i, k, head, next, P, w) ; } return (cs_idone (P, C, W, 1)) ; } igraph/src/cs/cs_randperm.c0000644000175100001440000000357113431000472015377 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_random.h" #include "cs.h" /* return a random permutation vector, the identity perm, or p = n-1:-1:0. * seed = -1 means p = n-1:-1:0. seed = 0 means p = identity. otherwise * p = random permutation. */ CS_INT *cs_randperm (CS_INT n, CS_INT seed) { CS_INT *p, k, j, t ; if (seed == 0) return (NULL) ; /* return p = NULL (identity) */ p = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result */ if (!p) return (NULL) ; /* out of memory */ for (k = 0 ; k < n ; k++) p [k] = n-k-1 ; if (seed == -1) return (p) ; /* return reverse permutation */ /* srand (seed) ; /\* get new random number seed *\/ */ RNG_BEGIN(); for (k = 0 ; k < n ; k++) { /* j = k + (rand ( ) % (n-k)) ; /\* j = rand CS_INT in range k to n-1 *\/ */ j = k + RNG_INTEGER(k, n-1) ; t = p [j] ; /* swap p[k] and p[j] */ p [j] = p [k] ; p [k] = t ; } RNG_END(); return (p) ; } igraph/src/cs/cs_cumsum.c0000644000175100001440000000270113431000472015072 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* p [0..n] = cumulative sum of c [0..n-1], and then copy p [0..n-1] into c */ double cs_cumsum (CS_INT *p, CS_INT *c, CS_INT n) { CS_INT i, nz = 0 ; double nz2 = 0 ; if (!p || !c) return (-1) ; /* check inputs */ for (i = 0 ; i < n ; i++) { p [i] = nz ; nz += c [i] ; nz2 += c [i] ; /* also in double to avoid CS_INT overflow */ c [i] = p [i] ; /* also copy p[0..n-1] back into c[0..n-1]*/ } p [n] = nz ; return (nz2) ; /* return sum (c [0..n-1]) */ } igraph/src/cs/cs_tdfs.c0000644000175100001440000000345313431000472014526 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* depth-first search and postorder of a tree rooted at node j */ CS_INT cs_tdfs (CS_INT j, CS_INT k, CS_INT *head, const CS_INT *next, CS_INT *post, CS_INT *stack) { CS_INT i, p, top = 0 ; if (!head || !next || !post || !stack) return (-1) ; /* check inputs */ stack [0] = j ; /* place j on the stack */ while (top >= 0) /* while (stack is not empty) */ { p = stack [top] ; /* p = top of stack */ i = head [p] ; /* i = youngest child of p */ if (i == -1) { top-- ; /* p has no unordered children left */ post [k++] = p ; /* node p is the kth postordered node */ } else { head [p] = next [i] ; /* remove i from children of p */ stack [++top] = i ; /* start dfs on child node i */ } } return (k) ; } igraph/src/cs/cs_util.c0000644000175100001440000001160413431000472014540 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* allocate a sparse matrix (triplet form or compressed-column form) */ cs *cs_spalloc (CS_INT m, CS_INT n, CS_INT nzmax, CS_INT values, CS_INT triplet) { cs *A = cs_calloc (1, sizeof (cs)) ; /* allocate the cs struct */ if (!A) return (NULL) ; /* out of memory */ A->m = m ; /* define dimensions and nzmax */ A->n = n ; A->nzmax = nzmax = CS_MAX (nzmax, 1) ; A->nz = triplet ? 0 : -1 ; /* allocate triplet or comp.col */ A->p = cs_malloc (triplet ? nzmax : n+1, sizeof (CS_INT)) ; A->i = cs_malloc (nzmax, sizeof (CS_INT)) ; A->x = values ? cs_malloc (nzmax, sizeof (CS_ENTRY)) : NULL ; return ((!A->p || !A->i || (values && !A->x)) ? cs_spfree (A) : A) ; } /* change the max # of entries sparse matrix */ CS_INT cs_sprealloc (cs *A, CS_INT nzmax) { CS_INT ok, oki, okj = 1, okx = 1 ; if (!A) return (0) ; if (nzmax <= 0) nzmax = (CS_CSC (A)) ? (A->p [A->n]) : A->nz ; A->i = cs_realloc (A->i, nzmax, sizeof (CS_INT), &oki) ; if (CS_TRIPLET (A)) A->p = cs_realloc (A->p, nzmax, sizeof (CS_INT), &okj) ; if (A->x) A->x = cs_realloc (A->x, nzmax, sizeof (CS_ENTRY), &okx) ; ok = (oki && okj && okx) ; if (ok) A->nzmax = nzmax ; return (ok) ; } /* free a sparse matrix */ cs *cs_spfree (cs *A) { if (!A) return (NULL) ; /* do nothing if A already NULL */ cs_free (A->p) ; cs_free (A->i) ; cs_free (A->x) ; return (cs_free (A)) ; /* free the cs struct and return NULL */ } /* free a numeric factorization */ csn *cs_nfree (csn *N) { if (!N) return (NULL) ; /* do nothing if N already NULL */ cs_spfree (N->L) ; cs_spfree (N->U) ; cs_free (N->pinv) ; cs_free (N->B) ; return (cs_free (N)) ; /* free the csn struct and return NULL */ } /* free a symbolic factorization */ css *cs_sfree (css *S) { if (!S) return (NULL) ; /* do nothing if S already NULL */ cs_free (S->pinv) ; cs_free (S->q) ; cs_free (S->parent) ; cs_free (S->cp) ; cs_free (S->leftmost) ; return (cs_free (S)) ; /* free the css struct and return NULL */ } /* allocate a cs_dmperm or cs_scc result */ csd *cs_dalloc (CS_INT m, CS_INT n) { csd *D ; D = cs_calloc (1, sizeof (csd)) ; if (!D) return (NULL) ; D->p = cs_malloc (m, sizeof (CS_INT)) ; D->r = cs_malloc (m+6, sizeof (CS_INT)) ; D->q = cs_malloc (n, sizeof (CS_INT)) ; D->s = cs_malloc (n+6, sizeof (CS_INT)) ; return ((!D->p || !D->r || !D->q || !D->s) ? cs_dfree (D) : D) ; } /* free a cs_dmperm or cs_scc result */ csd *cs_dfree (csd *D) { if (!D) return (NULL) ; /* do nothing if D already NULL */ cs_free (D->p) ; cs_free (D->q) ; cs_free (D->r) ; cs_free (D->s) ; return (cs_free (D)) ; } /* free workspace and return a sparse matrix result */ cs *cs_done (cs *C, void *w, void *x, CS_INT ok) { cs_free (w) ; /* free workspace */ cs_free (x) ; return (ok ? C : cs_spfree (C)) ; /* return result if OK, else free it */ } /* free workspace and return CS_INT array result */ CS_INT *cs_idone (CS_INT *p, cs *C, void *w, CS_INT ok) { cs_spfree (C) ; /* free temporary matrix */ cs_free (w) ; /* free workspace */ return (ok ? p : cs_free (p)) ; /* return result if OK, else free it */ } /* free workspace and return a numeric factorization (Cholesky, LU, or QR) */ csn *cs_ndone (csn *N, cs *C, void *w, void *x, CS_INT ok) { cs_spfree (C) ; /* free temporary matrix */ cs_free (w) ; /* free workspace */ cs_free (x) ; return (ok ? N : cs_nfree (N)) ; /* return result if OK, else free it */ } /* free workspace and return a csd result */ csd *cs_ddone (csd *D, cs *C, void *w, CS_INT ok) { cs_spfree (C) ; /* free temporary matrix */ cs_free (w) ; /* free workspace */ return (ok ? D : cs_dfree (D)) ; /* return result if OK, else free it */ } igraph/src/cs/cs_dfs.c0000644000175100001440000000475313431000472014346 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* depth-first-search of the graph of a matrix, starting at node j */ CS_INT cs_dfs (CS_INT j, cs *G, CS_INT top, CS_INT *xi, CS_INT *pstack, const CS_INT *pinv) { CS_INT i, p, p2, done, jnew, head = 0, *Gp, *Gi ; if (!CS_CSC (G) || !xi || !pstack) return (-1) ; /* check inputs */ Gp = G->p ; Gi = G->i ; xi [0] = j ; /* initialize the recursion stack */ while (head >= 0) { j = xi [head] ; /* get j from the top of the recursion stack */ jnew = pinv ? (pinv [j]) : j ; if (!CS_MARKED (Gp, j)) { CS_MARK (Gp, j) ; /* mark node j as visited */ pstack [head] = (jnew < 0) ? 0 : CS_UNFLIP (Gp [jnew]) ; } done = 1 ; /* node j done if no unvisited neighbors */ p2 = (jnew < 0) ? 0 : CS_UNFLIP (Gp [jnew+1]) ; for (p = pstack [head] ; p < p2 ; p++) /* examine all neighbors of j */ { i = Gi [p] ; /* consider neighbor node i */ if (CS_MARKED (Gp, i)) continue ; /* skip visited node i */ pstack [head] = p ; /* pause depth-first search of node j */ xi [++head] = i ; /* start dfs at node i */ done = 0 ; /* node j is not done */ break ; /* break, to start dfs (i) */ } if (done) /* depth-first search at node j is done */ { head-- ; /* remove j from the recursion stack */ xi [--top] = j ; /* and place in the output stack */ } } return (top) ; } igraph/src/cs/cs_ipvec.c0000644000175100001440000000231213431000472014665 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x(p) = b, for dense vectors x and b; p=NULL denotes identity */ CS_INT cs_ipvec (const CS_INT *p, const CS_ENTRY *b, CS_ENTRY *x, CS_INT n) { CS_INT k ; if (!x || !b) return (0) ; /* check inputs */ for (k = 0 ; k < n ; k++) x [p ? p [k] : k] = b [k] ; return (1) ; } igraph/src/cs/cs_chol.c0000644000175100001440000000727313431000472014517 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* L = chol (A, [pinv parent cp]), pinv is optional */ csn *cs_chol (const cs *A, const css *S) { CS_ENTRY d, lki, *Lx, *x, *Cx ; CS_INT top, i, p, k, n, *Li, *Lp, *cp, *pinv, *s, *c, *parent, *Cp, *Ci ; cs *L, *C, *E ; csn *N ; if (!CS_CSC (A) || !S || !S->cp || !S->parent) return (NULL) ; n = A->n ; N = cs_calloc (1, sizeof (csn)) ; /* allocate result */ c = cs_malloc (2*n, sizeof (CS_INT)) ; /* get CS_INT workspace */ x = cs_malloc (n, sizeof (CS_ENTRY)) ; /* get CS_ENTRY workspace */ cp = S->cp ; pinv = S->pinv ; parent = S->parent ; C = pinv ? cs_symperm (A, pinv, 1) : ((cs *) A) ; E = pinv ? C : NULL ; /* E is alias for A, or a copy E=A(p,p) */ if (!N || !c || !x || !C) return (cs_ndone (N, E, c, x, 0)) ; s = c + n ; Cp = C->p ; Ci = C->i ; Cx = C->x ; N->L = L = cs_spalloc (n, n, cp [n], 1, 0) ; /* allocate result */ if (!L) return (cs_ndone (N, E, c, x, 0)) ; Lp = L->p ; Li = L->i ; Lx = L->x ; for (k = 0 ; k < n ; k++) Lp [k] = c [k] = cp [k] ; for (k = 0 ; k < n ; k++) /* compute L(k,:) for L*L' = C */ { /* --- Nonzero pattern of L(k,:) ------------------------------------ */ top = cs_ereach (C, k, parent, s, c) ; /* find pattern of L(k,:) */ x [k] = 0 ; /* x (0:k) is now zero */ for (p = Cp [k] ; p < Cp [k+1] ; p++) /* x = full(triu(C(:,k))) */ { if (Ci [p] <= k) x [Ci [p]] = Cx [p] ; } d = x [k] ; /* d = C(k,k) */ x [k] = 0 ; /* clear x for k+1st iteration */ /* --- Triangular solve --------------------------------------------- */ for ( ; top < n ; top++) /* solve L(0:k-1,0:k-1) * x = C(:,k) */ { i = s [top] ; /* s [top..n-1] is pattern of L(k,:) */ lki = x [i] / Lx [Lp [i]] ; /* L(k,i) = x (i) / L(i,i) */ x [i] = 0 ; /* clear x for k+1st iteration */ for (p = Lp [i] + 1 ; p < c [i] ; p++) { x [Li [p]] -= Lx [p] * lki ; } d -= lki * CS_CONJ (lki) ; /* d = d - L(k,i)*L(k,i) */ p = c [i]++ ; Li [p] = k ; /* store L(k,i) in column i */ Lx [p] = CS_CONJ (lki) ; } /* --- Compute L(k,k) ----------------------------------------------- */ if (CS_REAL (d) <= 0 || CS_IMAG (d) != 0) return (cs_ndone (N, E, c, x, 0)) ; /* not pos def */ p = c [k]++ ; Li [p] = k ; /* store L(k,k) = sqrt (d) in column k */ Lx [p] = sqrt (d) ; } Lp [n] = cp [n] ; /* finalize L */ return (cs_ndone (N, E, c, x, 1)) ; /* success: free E,s,x; return N */ } igraph/src/cs/cs_qr.c0000644000175100001440000001052313431000472014204 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* sparse QR factorization [V,beta,pinv,R] = qr (A) */ csn *cs_qr (const cs *A, const css *S) { CS_ENTRY *Rx, *Vx, *Ax, *x ; double *Beta ; CS_INT i, k, p, m, n, vnz, p1, top, m2, len, col, rnz, *s, *leftmost, *Ap, *Ai, *parent, *Rp, *Ri, *Vp, *Vi, *w, *pinv, *q ; cs *R, *V ; csn *N ; if (!CS_CSC (A) || !S) return (NULL) ; m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; q = S->q ; parent = S->parent ; pinv = S->pinv ; m2 = S->m2 ; vnz = S->lnz ; rnz = S->unz ; leftmost = S->leftmost ; w = cs_malloc (m2+n, sizeof (CS_INT)) ; /* get CS_INT workspace */ x = cs_malloc (m2, sizeof (CS_ENTRY)) ; /* get CS_ENTRY workspace */ N = cs_calloc (1, sizeof (csn)) ; /* allocate result */ if (!w || !x || !N) return (cs_ndone (N, NULL, w, x, 0)) ; s = w + m2 ; /* s is size n */ for (k = 0 ; k < m2 ; k++) x [k] = 0 ; /* clear workspace x */ N->L = V = cs_spalloc (m2, n, vnz, 1, 0) ; /* allocate result V */ N->U = R = cs_spalloc (m2, n, rnz, 1, 0) ; /* allocate result R */ N->B = Beta = cs_malloc (n, sizeof (double)) ; /* allocate result Beta */ if (!R || !V || !Beta) return (cs_ndone (N, NULL, w, x, 0)) ; Rp = R->p ; Ri = R->i ; Rx = R->x ; Vp = V->p ; Vi = V->i ; Vx = V->x ; for (i = 0 ; i < m2 ; i++) w [i] = -1 ; /* clear w, to mark nodes */ rnz = 0 ; vnz = 0 ; for (k = 0 ; k < n ; k++) /* compute V and R */ { Rp [k] = rnz ; /* R(:,k) starts here */ Vp [k] = p1 = vnz ; /* V(:,k) starts here */ w [k] = k ; /* add V(k,k) to pattern of V */ Vi [vnz++] = k ; top = n ; col = q ? q [k] : k ; for (p = Ap [col] ; p < Ap [col+1] ; p++) /* find R(:,k) pattern */ { i = leftmost [Ai [p]] ; /* i = min(find(A(i,q))) */ for (len = 0 ; w [i] != k ; i = parent [i]) /* traverse up to k */ { s [len++] = i ; w [i] = k ; } while (len > 0) s [--top] = s [--len] ; /* push path on stack */ i = pinv [Ai [p]] ; /* i = permuted row of A(:,col) */ x [i] = Ax [p] ; /* x (i) = A(:,col) */ if (i > k && w [i] < k) /* pattern of V(:,k) = x (k+1:m) */ { Vi [vnz++] = i ; /* add i to pattern of V(:,k) */ w [i] = k ; } } for (p = top ; p < n ; p++) /* for each i in pattern of R(:,k) */ { i = s [p] ; /* R(i,k) is nonzero */ cs_happly (V, i, Beta [i], x) ; /* apply (V(i),Beta(i)) to x */ Ri [rnz] = i ; /* R(i,k) = x(i) */ Rx [rnz++] = x [i] ; x [i] = 0 ; if (parent [i] == k) vnz = cs_scatter (V, i, 0, w, NULL, k, V, vnz); } for (p = p1 ; p < vnz ; p++) /* gather V(:,k) = x */ { Vx [p] = x [Vi [p]] ; x [Vi [p]] = 0 ; } Ri [rnz] = k ; /* R(k,k) = norm (x) */ Rx [rnz++] = cs_house (Vx+p1, Beta+k, vnz-p1) ; /* [v,beta]=house(x) */ } Rp [n] = rnz ; /* finalize R */ Vp [n] = vnz ; /* finalize V */ return (cs_ndone (N, NULL, w, x, 1)) ; /* success */ } igraph/src/cs/cs_happly.c0000644000175100001440000000273313431000472015063 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* apply the ith Householder vector to x */ CS_INT cs_happly (const cs *V, CS_INT i, double beta, CS_ENTRY *x) { CS_INT p, *Vp, *Vi ; CS_ENTRY *Vx, tau = 0 ; if (!CS_CSC (V) || !x) return (0) ; /* check inputs */ Vp = V->p ; Vi = V->i ; Vx = V->x ; for (p = Vp [i] ; p < Vp [i+1] ; p++) /* tau = v'*x */ { tau += CS_CONJ (Vx [p]) * x [Vi [p]] ; } tau *= beta ; /* tau = beta*(v'*x) */ for (p = Vp [i] ; p < Vp [i+1] ; p++) /* x = x - v*tau */ { x [Vi [p]] -= Vx [p] * tau ; } return (1) ; } igraph/src/cs/UFconfig.h0000644000175100001440000001021113431000472014574 0ustar hornikusers/* ========================================================================== */ /* === UFconfig.h =========================================================== */ /* ========================================================================== */ /* Configuration file for SuiteSparse: a Suite of Sparse matrix packages * (AMD, COLAMD, CCOLAMD, CAMD, CHOLMOD, UMFPACK, CXSparse, and others). * * UFconfig.h provides the definition of the long integer. On most systems, * a C program can be compiled in LP64 mode, in which long's and pointers are * both 64-bits, and int's are 32-bits. Windows 64, however, uses the LLP64 * model, in which int's and long's are 32-bits, and long long's and pointers * are 64-bits. * * SuiteSparse packages that include long integer versions are * intended for the LP64 mode. However, as a workaround for Windows 64 * (and perhaps other systems), the long integer can be redefined. * * If _WIN64 is defined, then the __int64 type is used instead of long. * * The long integer can also be defined at compile time. For example, this * could be added to UFconfig.mk: * * CFLAGS = -O -D'UF_long=long long' -D'UF_long_max=9223372036854775801' \ * -D'UF_long_id="%lld"' * * This file defines UF_long as either long (on all but _WIN64) or * __int64 on Windows 64. The intent is that a UF_long is always a 64-bit * integer in a 64-bit code. ptrdiff_t might be a better choice than long; * it is always the same size as a pointer. * * This file also defines the SUITESPARSE_VERSION and related definitions. * * Copyright (c) 2007, University of Florida. No licensing restrictions * apply to this file or to the UFconfig directory. Author: Timothy A. Davis. */ #ifndef _UFCONFIG_H #define _UFCONFIG_H #ifdef __cplusplus extern "C" { #endif #include /* ========================================================================== */ /* === UF_long ============================================================== */ /* ========================================================================== */ #ifndef UF_long #ifdef _WIN64 #define UF_long __int64 #define UF_long_max _I64_MAX #define UF_long_id "%I64d" #else #define UF_long long #define UF_long_max LONG_MAX #define UF_long_id "%ld" #endif #endif /* ========================================================================== */ /* === SuiteSparse version ================================================== */ /* ========================================================================== */ /* SuiteSparse is not a package itself, but a collection of packages, some of * which must be used together (UMFPACK requires AMD, CHOLMOD requires AMD, * COLAMD, CAMD, and CCOLAMD, etc). A version number is provided here for the * collection itself. The versions of packages within each version of * SuiteSparse are meant to work together. Combining one packge from one * version of SuiteSparse, with another package from another version of * SuiteSparse, may or may not work. * * SuiteSparse Version 3.3.0 contains the following packages: * * AMD version 2.2.0 * CAMD version 2.2.0 * COLAMD version 2.7.1 * CCOLAMD version 2.7.1 * CHOLMOD version 1.7.1 * CSparse version 2.2.3 * CXSparse version 2.2.3 * KLU version 1.1.0 * BTF version 1.0.1 * LDL version 2.0.1 * UFconfig version number is the same as SuiteSparse * UMFPACK version 5.3.0 * RBio version 1.1.1 * UFcollection version 1.2.0 * LINFACTOR version 1.1.0 * MESHND version 1.1.1 * SSMULT version 2.0.0 * MATLAB_Tools no specific version number * SuiteSparseQR version 1.1.1 * * Other package dependencies: * BLAS required by CHOLMOD and UMFPACK * LAPACK required by CHOLMOD * METIS 4.0.1 required by CHOLMOD (optional) and KLU (optional) */ #define SUITESPARSE_DATE "Mar 24, 2009" #define SUITESPARSE_VER_CODE(main,sub) ((main) * 1000 + (sub)) #define SUITESPARSE_MAIN_VERSION 3 #define SUITESPARSE_SUB_VERSION 3 #define SUITESPARSE_SUBSUB_VERSION 0 #define SUITESPARSE_VERSION \ SUITESPARSE_VER_CODE(SUITESPARSE_MAIN_VERSION,SUITESPARSE_SUB_VERSION) #ifdef __cplusplus } #endif #endif igraph/src/cs/cs_lu.c0000644000175100001440000001152113431000472014201 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* [L,U,pinv]=lu(A, [q lnz unz]). lnz and unz can be guess */ csn *cs_lu (const cs *A, const css *S, double tol) { cs *L, *U ; csn *N ; CS_ENTRY pivot, *Lx, *Ux, *x ; double a, t ; CS_INT *Lp, *Li, *Up, *Ui, *pinv, *xi, *q, n, ipiv, k, top, p, i, col, lnz,unz; if (!CS_CSC (A) || !S) return (NULL) ; /* check inputs */ n = A->n ; q = S->q ; lnz = S->lnz ; unz = S->unz ; x = cs_malloc (n, sizeof (CS_ENTRY)) ; /* get CS_ENTRY workspace */ xi = cs_malloc (2*n, sizeof (CS_INT)) ; /* get CS_INT workspace */ N = cs_calloc (1, sizeof (csn)) ; /* allocate result */ if (!x || !xi || !N) return (cs_ndone (N, NULL, xi, x, 0)) ; N->L = L = cs_spalloc (n, n, lnz, 1, 0) ; /* allocate result L */ N->U = U = cs_spalloc (n, n, unz, 1, 0) ; /* allocate result U */ N->pinv = pinv = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result pinv */ if (!L || !U || !pinv) return (cs_ndone (N, NULL, xi, x, 0)) ; Lp = L->p ; Up = U->p ; for (i = 0 ; i < n ; i++) x [i] = 0 ; /* clear workspace */ for (i = 0 ; i < n ; i++) pinv [i] = -1 ; /* no rows pivotal yet */ for (k = 0 ; k <= n ; k++) Lp [k] = 0 ; /* no cols of L yet */ lnz = unz = 0 ; for (k = 0 ; k < n ; k++) /* compute L(:,k) and U(:,k) */ { /* --- Triangular solve --------------------------------------------- */ Lp [k] = lnz ; /* L(:,k) starts here */ Up [k] = unz ; /* U(:,k) starts here */ if ((lnz + n > L->nzmax && !cs_sprealloc (L, 2*L->nzmax + n)) || (unz + n > U->nzmax && !cs_sprealloc (U, 2*U->nzmax + n))) { return (cs_ndone (N, NULL, xi, x, 0)) ; } Li = L->i ; Lx = L->x ; Ui = U->i ; Ux = U->x ; col = q ? (q [k]) : k ; top = cs_spsolve (L, A, col, xi, x, pinv, 1) ; /* x = L\A(:,col) */ /* --- Find pivot --------------------------------------------------- */ ipiv = -1 ; a = -1 ; for (p = top ; p < n ; p++) { i = xi [p] ; /* x(i) is nonzero */ if (pinv [i] < 0) /* row i is not yet pivotal */ { if ((t = CS_ABS (x [i])) > a) { a = t ; /* largest pivot candidate so far */ ipiv = i ; } } else /* x(i) is the entry U(pinv[i],k) */ { Ui [unz] = pinv [i] ; Ux [unz++] = x [i] ; } } if (ipiv == -1 || a <= 0) return (cs_ndone (N, NULL, xi, x, 0)) ; if (pinv [col] < 0 && CS_ABS (x [col]) >= a*tol) ipiv = col ; /* --- Divide by pivot ---------------------------------------------- */ pivot = x [ipiv] ; /* the chosen pivot */ Ui [unz] = k ; /* last entry in U(:,k) is U(k,k) */ Ux [unz++] = pivot ; pinv [ipiv] = k ; /* ipiv is the kth pivot row */ Li [lnz] = ipiv ; /* first entry in L(:,k) is L(k,k) = 1 */ Lx [lnz++] = 1 ; for (p = top ; p < n ; p++) /* L(k+1:n,k) = x / pivot */ { i = xi [p] ; if (pinv [i] < 0) /* x(i) is an entry in L(:,k) */ { Li [lnz] = i ; /* save unpermuted row in L */ Lx [lnz++] = x [i] / pivot ; /* scale pivot column */ } x [i] = 0 ; /* x [0..n-1] = 0 for next k */ } } /* --- Finalize L and U ------------------------------------------------- */ Lp [n] = lnz ; Up [n] = unz ; Li = L->i ; /* fix row indices of L for final pinv */ for (p = 0 ; p < lnz ; p++) Li [p] = pinv [Li [p]] ; cs_sprealloc (L, 0) ; /* remove extra space from L and U */ cs_sprealloc (U, 0) ; return (cs_ndone (N, NULL, xi, x, 1)) ; /* success */ } igraph/src/cs/cs_spsolve.c0000644000175100001440000000435013431000472015256 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* solve Gx=b(:,k), where G is either upper (lo=0) or lower (lo=1) triangular */ CS_INT cs_spsolve (cs *G, const cs *B, CS_INT k, CS_INT *xi, CS_ENTRY *x, const CS_INT *pinv, CS_INT lo) { CS_INT j, J, p, q, px, top, n, *Gp, *Gi, *Bp, *Bi ; CS_ENTRY *Gx, *Bx ; if (!CS_CSC (G) || !CS_CSC (B) || !xi || !x) return (-1) ; Gp = G->p ; Gi = G->i ; Gx = G->x ; n = G->n ; Bp = B->p ; Bi = B->i ; Bx = B->x ; top = cs_reach (G, B, k, xi, pinv) ; /* xi[top..n-1]=Reach(B(:,k)) */ for (p = top ; p < n ; p++) x [xi [p]] = 0 ; /* clear x */ for (p = Bp [k] ; p < Bp [k+1] ; p++) x [Bi [p]] = Bx [p] ; /* scatter B */ for (px = top ; px < n ; px++) { j = xi [px] ; /* x(j) is nonzero */ J = pinv ? (pinv [j]) : j ; /* j maps to col J of G */ if (J < 0) continue ; /* column J is empty */ x [j] /= Gx [lo ? (Gp [J]) : (Gp [J+1]-1)] ;/* x(j) /= G(j,j) */ p = lo ? (Gp [J]+1) : (Gp [J]) ; /* lo: L(j,j) 1st entry */ q = lo ? (Gp [J+1]) : (Gp [J+1]-1) ; /* up: U(j,j) last entry */ for ( ; p < q ; p++) { x [Gi [p]] -= Gx [p] * x [j] ; /* x(i) -= G(i,j) * x(j) */ } } return (top) ; /* return top of stack */ } igraph/src/cs/cs_add.c0000644000175100001440000000441113431000472014311 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = alpha*A + beta*B */ cs *cs_add (const cs *A, const cs *B, CS_ENTRY alpha, CS_ENTRY beta) { CS_INT p, j, nz = 0, anz, *Cp, *Ci, *Bp, m, n, bnz, *w, values ; CS_ENTRY *x, *Bx, *Cx ; cs *C ; if (!CS_CSC (A) || !CS_CSC (B)) return (NULL) ; /* check inputs */ if (A->m != B->m || A->n != B->n) return (NULL) ; m = A->m ; anz = A->p [A->n] ; n = B->n ; Bp = B->p ; Bx = B->x ; bnz = Bp [n] ; w = cs_calloc (m, sizeof (CS_INT)) ; /* get workspace */ values = (A->x != NULL) && (Bx != NULL) ; x = values ? cs_malloc (m, sizeof (CS_ENTRY)) : NULL ; /* get workspace */ C = cs_spalloc (m, n, anz + bnz, values, 0) ; /* allocate result*/ if (!C || !w || (values && !x)) return (cs_done (C, w, x, 0)) ; Cp = C->p ; Ci = C->i ; Cx = C->x ; for (j = 0 ; j < n ; j++) { Cp [j] = nz ; /* column j of C starts here */ nz = cs_scatter (A, j, alpha, w, x, j+1, C, nz) ; /* alpha*A(:,j)*/ nz = cs_scatter (B, j, beta, w, x, j+1, C, nz) ; /* beta*B(:,j) */ if (values) for (p = Cp [j] ; p < nz ; p++) Cx [p] = x [Ci [p]] ; } Cp [n] = nz ; /* finalize the last column of C */ cs_sprealloc (C, 0) ; /* remove extra space from C */ return (cs_done (C, w, x, 1)) ; /* success; free workspace, return C */ } igraph/src/cs/cs_scc.c0000644000175100001440000000534213431000472014335 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* find the strongly connected components of a square matrix */ csd *cs_scc (cs *A) /* matrix A temporarily modified, then restored */ { CS_INT n, i, k, b, nb = 0, top, *xi, *pstack, *p, *r, *Ap, *ATp, *rcopy, *Blk ; cs *AT ; csd *D ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ n = A->n ; Ap = A->p ; D = cs_dalloc (n, 0) ; /* allocate result */ AT = cs_transpose (A, 0) ; /* AT = A' */ xi = cs_malloc (2*n+1, sizeof (CS_INT)) ; /* get workspace */ if (!D || !AT || !xi) return (cs_ddone (D, AT, xi, 0)) ; Blk = xi ; rcopy = pstack = xi + n ; p = D->p ; r = D->r ; ATp = AT->p ; top = n ; for (i = 0 ; i < n ; i++) /* first dfs(A) to find finish times (xi) */ { if (!CS_MARKED (Ap, i)) top = cs_dfs (i, A, top, xi, pstack, NULL) ; } for (i = 0 ; i < n ; i++) CS_MARK (Ap, i) ; /* restore A; unmark all nodes*/ top = n ; nb = n ; for (k = 0 ; k < n ; k++) /* dfs(A') to find strongly connnected comp */ { i = xi [k] ; /* get i in reverse order of finish times */ if (CS_MARKED (ATp, i)) continue ; /* skip node i if already ordered */ r [nb--] = top ; /* node i is the start of a component in p */ top = cs_dfs (i, AT, top, p, pstack, NULL) ; } r [nb] = 0 ; /* first block starts at zero; shift r up */ for (k = nb ; k <= n ; k++) r [k-nb] = r [k] ; D->nb = nb = n-nb ; /* nb = # of strongly connected components */ for (b = 0 ; b < nb ; b++) /* sort each block in natural order */ { for (k = r [b] ; k < r [b+1] ; k++) Blk [p [k]] = b ; } for (b = 0 ; b <= nb ; b++) rcopy [b] = r [b] ; for (i = 0 ; i < n ; i++) p [rcopy [Blk [i]]++] = i ; return (cs_ddone (D, AT, xi, 1)) ; } igraph/src/cs/cs_ereach.c0000644000175100001440000000373413431000472015017 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* find nonzero pattern of Cholesky L(k,1:k-1) using etree and triu(A(:,k)) */ CS_INT cs_ereach (const cs *A, CS_INT k, const CS_INT *parent, CS_INT *s, CS_INT *w) { CS_INT i, p, n, len, top, *Ap, *Ai ; if (!CS_CSC (A) || !parent || !s || !w) return (-1) ; /* check inputs */ top = n = A->n ; Ap = A->p ; Ai = A->i ; CS_MARK (w, k) ; /* mark node k as visited */ for (p = Ap [k] ; p < Ap [k+1] ; p++) { i = Ai [p] ; /* A(i,k) is nonzero */ if (i > k) continue ; /* only use upper triangular part of A */ for (len = 0 ; !CS_MARKED (w,i) ; i = parent [i]) /* traverse up etree*/ { s [len++] = i ; /* L(k,i) is nonzero */ CS_MARK (w, i) ; /* mark i as visited */ } while (len > 0) s [--top] = s [--len] ; /* push path onto stack */ } for (p = top ; p < n ; p++) CS_MARK (w, s [p]) ; /* unmark all nodes */ CS_MARK (w, k) ; /* unmark node k */ return (top) ; /* s [top..n-1] contains pattern of L(k,:)*/ } igraph/src/cs/cs_sqr.c0000644000175100001440000001131013431000472014362 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* compute nnz(V) = S->lnz, S->pinv, S->leftmost, S->m2 from A and S->parent */ static CS_INT cs_vcount (const cs *A, css *S) { CS_INT i, k, p, pa, n = A->n, m = A->m, *Ap = A->p, *Ai = A->i, *next, *head, *tail, *nque, *pinv, *leftmost, *w, *parent = S->parent ; S->pinv = pinv = cs_malloc (m+n, sizeof (CS_INT)) ; /* allocate pinv, */ S->leftmost = leftmost = cs_malloc (m, sizeof (CS_INT)) ; /* and leftmost */ w = cs_malloc (m+3*n, sizeof (CS_INT)) ; /* get workspace */ if (!pinv || !w || !leftmost) { cs_free (w) ; /* pinv and leftmost freed later */ return (0) ; /* out of memory */ } next = w ; head = w + m ; tail = w + m + n ; nque = w + m + 2*n ; for (k = 0 ; k < n ; k++) head [k] = -1 ; /* queue k is empty */ for (k = 0 ; k < n ; k++) tail [k] = -1 ; for (k = 0 ; k < n ; k++) nque [k] = 0 ; for (i = 0 ; i < m ; i++) leftmost [i] = -1 ; for (k = n-1 ; k >= 0 ; k--) { for (p = Ap [k] ; p < Ap [k+1] ; p++) { leftmost [Ai [p]] = k ; /* leftmost[i] = min(find(A(i,:)))*/ } } for (i = m-1 ; i >= 0 ; i--) /* scan rows in reverse order */ { pinv [i] = -1 ; /* row i is not yet ordered */ k = leftmost [i] ; if (k == -1) continue ; /* row i is empty */ if (nque [k]++ == 0) tail [k] = i ; /* first row in queue k */ next [i] = head [k] ; /* put i at head of queue k */ head [k] = i ; } S->lnz = 0 ; S->m2 = m ; for (k = 0 ; k < n ; k++) /* find row permutation and nnz(V)*/ { i = head [k] ; /* remove row i from queue k */ S->lnz++ ; /* count V(k,k) as nonzero */ if (i < 0) i = S->m2++ ; /* add a fictitious row */ pinv [i] = k ; /* associate row i with V(:,k) */ if (--nque [k] <= 0) continue ; /* skip if V(k+1:m,k) is empty */ S->lnz += nque [k] ; /* nque [k] is nnz (V(k+1:m,k)) */ if ((pa = parent [k]) != -1) /* move all rows to parent of k */ { if (nque [pa] == 0) tail [pa] = tail [k] ; next [tail [k]] = head [pa] ; head [pa] = next [i] ; nque [pa] += nque [k] ; } } for (i = 0 ; i < m ; i++) if (pinv [i] < 0) pinv [i] = k++ ; cs_free (w) ; return (1) ; } /* symbolic ordering and analysis for QR or LU */ css *cs_sqr (CS_INT order, const cs *A, CS_INT qr) { CS_INT n, k, ok = 1, *post ; css *S ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ n = A->n ; S = cs_calloc (1, sizeof (css)) ; /* allocate result S */ if (!S) return (NULL) ; /* out of memory */ S->q = cs_amd (order, A) ; /* fill-reducing ordering */ if (order && !S->q) return (cs_sfree (S)) ; if (qr) /* QR symbolic analysis */ { cs *C = order ? cs_permute (A, NULL, S->q, 0) : ((cs *) A) ; S->parent = cs_etree (C, 1) ; /* etree of C'*C, where C=A(:,q) */ post = cs_post (S->parent, n) ; S->cp = cs_counts (C, S->parent, post, 1) ; /* col counts chol(C'*C) */ cs_free (post) ; ok = C && S->parent && S->cp && cs_vcount (C, S) ; if (ok) for (S->unz = 0, k = 0 ; k < n ; k++) S->unz += S->cp [k] ; ok = ok && S->lnz >= 0 && S->unz >= 0 ; /* CS_INT overflow guard */ if (order) cs_spfree (C) ; } else { S->unz = 4*(A->p [n]) + n ; /* for LU factorization only, */ S->lnz = S->unz ; /* guess nnz(L) and nnz(U) */ } return (ok ? S : cs_sfree (S)) ; /* return result S */ } igraph/src/cs/cs_permute.c0000644000175100001440000000362513431000472015250 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = A(p,q) where p and q are permutations of 0..m-1 and 0..n-1. */ cs *cs_permute (const cs *A, const CS_INT *pinv, const CS_INT *q, CS_INT values) { CS_INT t, j, k, nz = 0, m, n, *Ap, *Ai, *Cp, *Ci ; CS_ENTRY *Cx, *Ax ; cs *C ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; C = cs_spalloc (m, n, Ap [n], values && Ax != NULL, 0) ; /* alloc result */ if (!C) return (cs_done (C, NULL, NULL, 0)) ; /* out of memory */ Cp = C->p ; Ci = C->i ; Cx = C->x ; for (k = 0 ; k < n ; k++) { Cp [k] = nz ; /* column k of C is column q[k] of A */ j = q ? (q [k]) : k ; for (t = Ap [j] ; t < Ap [j+1] ; t++) { if (Cx) Cx [nz] = Ax [t] ; /* row i of A is row pinv[i] of C */ Ci [nz++] = pinv ? (pinv [Ai [t]]) : Ai [t] ; } } Cp [n] = nz ; /* finalize the last column of C */ return (cs_done (C, NULL, NULL, 1)) ; } igraph/src/cs/cs_utsolve.c0000644000175100001440000000264213431000472015266 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* solve U'x=b where x and b are dense. x=b on input, solution on output. */ CS_INT cs_utsolve (const cs *U, CS_ENTRY *x) { CS_INT p, j, n, *Up, *Ui ; CS_ENTRY *Ux ; if (!CS_CSC (U) || !x) return (0) ; /* check inputs */ n = U->n ; Up = U->p ; Ui = U->i ; Ux = U->x ; for (j = 0 ; j < n ; j++) { for (p = Up [j] ; p < Up [j+1]-1 ; p++) { x [j] -= CS_CONJ (Ux [p]) * x [Ui [p]] ; } x [j] /= CS_CONJ (Ux [Up [j+1]-1]) ; } return (1) ; } igraph/src/cs/cs_maxtrans.c0000644000175100001440000001243113431000472015417 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* find an augmenting path starting at column k and extend the match if found */ static void cs_augment (CS_INT k, const cs *A, CS_INT *jmatch, CS_INT *cheap, CS_INT *w, CS_INT *js, CS_INT *is, CS_INT *ps) { CS_INT found = 0, p, i = -1, *Ap = A->p, *Ai = A->i, head = 0, j ; js [0] = k ; /* start with just node k in jstack */ while (head >= 0) { /* --- Start (or continue) depth-first-search at node j ------------- */ j = js [head] ; /* get j from top of jstack */ if (w [j] != k) /* 1st time j visited for kth path */ { w [j] = k ; /* mark j as visited for kth path */ for (p = cheap [j] ; p < Ap [j+1] && !found ; p++) { i = Ai [p] ; /* try a cheap assignment (i,j) */ found = (jmatch [i] == -1) ; } cheap [j] = p ; /* start here next time j is traversed*/ if (found) { is [head] = i ; /* column j matched with row i */ break ; /* end of augmenting path */ } ps [head] = Ap [j] ; /* no cheap match: start dfs for j */ } /* --- Depth-first-search of neighbors of j ------------------------- */ for (p = ps [head] ; p < Ap [j+1] ; p++) { i = Ai [p] ; /* consider row i */ if (w [jmatch [i]] == k) continue ; /* skip jmatch [i] if marked */ ps [head] = p + 1 ; /* pause dfs of node j */ is [head] = i ; /* i will be matched with j if found */ js [++head] = jmatch [i] ; /* start dfs at column jmatch [i] */ break ; } if (p == Ap [j+1]) head-- ; /* node j is done; pop from stack */ } /* augment the match if path found: */ if (found) for (p = head ; p >= 0 ; p--) jmatch [is [p]] = js [p] ; } /* find a maximum transveral */ CS_INT *cs_maxtrans (const cs *A, CS_INT seed) /*[jmatch [0..m-1]; imatch [0..n-1]]*/ { CS_INT i, j, k, n, m, p, n2 = 0, m2 = 0, *Ap, *jimatch, *w, *cheap, *js, *is, *ps, *Ai, *Cp, *jmatch, *imatch, *q ; cs *C ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ n = A->n ; m = A->m ; Ap = A->p ; Ai = A->i ; w = jimatch = cs_calloc (m+n, sizeof (CS_INT)) ; /* allocate result */ if (!jimatch) return (NULL) ; for (k = 0, j = 0 ; j < n ; j++) /* count nonempty rows and columns */ { n2 += (Ap [j] < Ap [j+1]) ; for (p = Ap [j] ; p < Ap [j+1] ; p++) { w [Ai [p]] = 1 ; k += (j == Ai [p]) ; /* count entries already on diagonal */ } } if (k == CS_MIN (m,n)) /* quick return if diagonal zero-free */ { jmatch = jimatch ; imatch = jimatch + m ; for (i = 0 ; i < k ; i++) jmatch [i] = i ; for ( ; i < m ; i++) jmatch [i] = -1 ; for (j = 0 ; j < k ; j++) imatch [j] = j ; for ( ; j < n ; j++) imatch [j] = -1 ; return (cs_idone (jimatch, NULL, NULL, 1)) ; } for (i = 0 ; i < m ; i++) m2 += w [i] ; C = (m2 < n2) ? cs_transpose (A,0) : ((cs *) A) ; /* transpose if needed */ if (!C) return (cs_idone (jimatch, (m2 < n2) ? C : NULL, NULL, 0)) ; n = C->n ; m = C->m ; Cp = C->p ; jmatch = (m2 < n2) ? jimatch + n : jimatch ; imatch = (m2 < n2) ? jimatch : jimatch + m ; w = cs_malloc (5*n, sizeof (CS_INT)) ; /* get workspace */ if (!w) return (cs_idone (jimatch, (m2 < n2) ? C : NULL, w, 0)) ; cheap = w + n ; js = w + 2*n ; is = w + 3*n ; ps = w + 4*n ; for (j = 0 ; j < n ; j++) cheap [j] = Cp [j] ; /* for cheap assignment */ for (j = 0 ; j < n ; j++) w [j] = -1 ; /* all columns unflagged */ for (i = 0 ; i < m ; i++) jmatch [i] = -1 ; /* nothing matched yet */ q = cs_randperm (n, seed) ; /* q = random permutation */ for (k = 0 ; k < n ; k++) /* augment, starting at column q[k] */ { cs_augment (q ? q [k]: k, C, jmatch, cheap, w, js, is, ps) ; } cs_free (q) ; for (j = 0 ; j < n ; j++) imatch [j] = -1 ; /* find row match */ for (i = 0 ; i < m ; i++) if (jmatch [i] >= 0) imatch [jmatch [i]] = i ; return (cs_idone (jimatch, (m2 < n2) ? C : NULL, w, 1)) ; } igraph/src/cs/cs_malloc.c0000644000175100001440000000340413431000472015031 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" #ifdef MATLAB_MEX_FILE #define malloc mxMalloc #define free mxFree #define realloc mxRealloc #define calloc mxCalloc #endif /* wrapper for malloc */ void *cs_malloc (CS_INT n, size_t size) { return (malloc (CS_MAX (n,1) * size)) ; } /* wrapper for calloc */ void *cs_calloc (CS_INT n, size_t size) { return (calloc (CS_MAX (n,1), size)) ; } /* wrapper for free */ void *cs_free (void *p) { if (p) free (p) ; /* free p if it is not already NULL */ return (NULL) ; /* return NULL to simplify the use of cs_free */ } /* wrapper for realloc */ void *cs_realloc (void *p, CS_INT n, size_t size, CS_INT *ok) { void *pnew ; pnew = realloc (p, CS_MAX (n,1) * size) ; /* realloc the block */ *ok = (pnew != NULL) ; /* realloc fails if pnew is NULL */ return ((*ok) ? pnew : p) ; /* return original p if failure */ } igraph/src/cs/cs_house.c0000644000175100001440000000334013431000472014704 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* create a Householder reflection [v,beta,s]=house(x), overwrite x with v, * where (I-beta*v*v')*x = s*e1 and e1 = [1 0 ... 0]'. * Note that this CXSparse version is different than CSparse. See Higham, * Accuracy & Stability of Num Algorithms, 2nd ed, 2002, page 357. */ CS_ENTRY cs_house (CS_ENTRY *x, double *beta, CS_INT n) { CS_ENTRY s = 0 ; CS_INT i ; if (!x || !beta) return (-1) ; /* check inputs */ /* s = norm(x) */ for (i = 0 ; i < n ; i++) s += x [i] * CS_CONJ (x [i]) ; s = sqrt (s) ; if (s == 0) { (*beta) = 0 ; x [0] = 1 ; } else { /* s = sign(x[0]) * norm (x) ; */ if (x [0] != 0) { s *= x [0] / CS_ABS (x [0]) ; } x [0] += s ; (*beta) = 1. / CS_REAL (CS_CONJ (s) * x [0]) ; } return (-s) ; } igraph/src/cs/cs_leaf.c0000644000175100001440000000361513431000472014475 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* consider A(i,j), node j in ith row subtree and return lca(jprev,j) */ CS_INT cs_leaf (CS_INT i, CS_INT j, const CS_INT *first, CS_INT *maxfirst, CS_INT *prevleaf, CS_INT *ancestor, CS_INT *jleaf) { CS_INT q, s, sparent, jprev ; if (!first || !maxfirst || !prevleaf || !ancestor || !jleaf) return (-1) ; *jleaf = 0 ; if (i <= j || first [j] <= maxfirst [i]) return (-1) ; /* j not a leaf */ maxfirst [i] = first [j] ; /* update max first[j] seen so far */ jprev = prevleaf [i] ; /* jprev = previous leaf of ith subtree */ prevleaf [i] = j ; *jleaf = (jprev == -1) ? 1: 2 ; /* j is first or subsequent leaf */ if (*jleaf == 1) return (i) ; /* if 1st leaf, q = root of ith subtree */ for (q = jprev ; q != ancestor [q] ; q = ancestor [q]) ; for (s = jprev ; s != q ; s = sparent) { sparent = ancestor [s] ; /* path compression */ ancestor [s] = q ; } return (q) ; /* q = least common ancester (jprev,j) */ } igraph/src/cs/cs_dupl.c0000644000175100001440000000437313431000472014534 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* remove duplicate entries from A */ CS_INT cs_dupl (cs *A) { CS_INT i, j, p, q, nz = 0, n, m, *Ap, *Ai, *w ; CS_ENTRY *Ax ; if (!CS_CSC (A)) return (0) ; /* check inputs */ m = A->m ; n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; w = cs_malloc (m, sizeof (CS_INT)) ; /* get workspace */ if (!w) return (0) ; /* out of memory */ for (i = 0 ; i < m ; i++) w [i] = -1 ; /* row i not yet seen */ for (j = 0 ; j < n ; j++) { q = nz ; /* column j will start at q */ for (p = Ap [j] ; p < Ap [j+1] ; p++) { i = Ai [p] ; /* A(i,j) is nonzero */ if (w [i] >= q) { Ax [w [i]] += Ax [p] ; /* A(i,j) is a duplicate */ } else { w [i] = nz ; /* record where row i occurs */ Ai [nz] = i ; /* keep A(i,j) */ Ax [nz++] = Ax [p] ; } } Ap [j] = q ; /* record start of column j */ } Ap [n] = nz ; /* finalize A */ cs_free (w) ; /* free workspace */ return (cs_sprealloc (A, 0)) ; /* remove extra space from A */ } igraph/src/cs/cs_gaxpy.c0000644000175100001440000000246413431000472014717 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* y = A*x+y */ CS_INT cs_gaxpy (const cs *A, const CS_ENTRY *x, CS_ENTRY *y) { CS_INT p, j, n, *Ap, *Ai ; CS_ENTRY *Ax ; if (!CS_CSC (A) || !x || !y) return (0) ; /* check inputs */ n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; for (j = 0 ; j < n ; j++) { for (p = Ap [j] ; p < Ap [j+1] ; p++) { y [Ai [p]] += Ax [p] * x [j] ; } } return (1) ; } igraph/src/cs/cs_droptol.c0000644000175100001440000000217213431000472015246 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" static CS_INT cs_tol (CS_INT i, CS_INT j, CS_ENTRY aij, void *tol) { return (CS_ABS (aij) > *((double *) tol)) ; } CS_INT cs_droptol (cs *A, double tol) { return (cs_fkeep (A, &cs_tol, &tol)) ; /* keep all large entries */ } igraph/src/cs/cs_pinv.c0000644000175100001440000000254013431000472014536 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* pinv = p', or p = pinv' */ CS_INT *cs_pinv (CS_INT const *p, CS_INT n) { CS_INT k, *pinv ; if (!p) return (NULL) ; /* p = NULL denotes identity */ pinv = cs_malloc (n, sizeof (CS_INT)) ; /* allocate result */ if (!pinv) return (NULL) ; /* out of memory */ for (k = 0 ; k < n ; k++) pinv [p [k]] = k ;/* invert the permutation */ return (pinv) ; /* return result */ } igraph/src/cs/cs_qrsol.c0000644000175100001440000000533113431000472014723 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x=A\b where A can be rectangular; b overwritten with solution */ CS_INT cs_qrsol (CS_INT order, const cs *A, CS_ENTRY *b) { CS_ENTRY *x ; css *S ; csn *N ; cs *AT = NULL ; CS_INT k, m, n, ok ; if (!CS_CSC (A) || !b) return (0) ; /* check inputs */ n = A->n ; m = A->m ; if (m >= n) { S = cs_sqr (order, A, 1) ; /* ordering and symbolic analysis */ N = cs_qr (A, S) ; /* numeric QR factorization */ x = cs_calloc (S ? S->m2 : 1, sizeof (CS_ENTRY)) ; /* get workspace */ ok = (S && N && x) ; if (ok) { cs_ipvec (S->pinv, b, x, m) ; /* x(0:m-1) = b(p(0:m-1) */ for (k = 0 ; k < n ; k++) /* apply Householder refl. to x */ { cs_happly (N->L, k, N->B [k], x) ; } cs_usolve (N->U, x) ; /* x = R\x */ cs_ipvec (S->q, x, b, n) ; /* b(q(0:n-1)) = x(0:n-1) */ } } else { AT = cs_transpose (A, 1) ; /* Ax=b is underdetermined */ S = cs_sqr (order, AT, 1) ; /* ordering and symbolic analysis */ N = cs_qr (AT, S) ; /* numeric QR factorization of A' */ x = cs_calloc (S ? S->m2 : 1, sizeof (CS_ENTRY)) ; /* get workspace */ ok = (AT && S && N && x) ; if (ok) { cs_pvec (S->q, b, x, m) ; /* x(q(0:m-1)) = b(0:m-1) */ cs_utsolve (N->U, x) ; /* x = R'\x */ for (k = m-1 ; k >= 0 ; k--) /* apply Householder refl. to x */ { cs_happly (N->L, k, N->B [k], x) ; } cs_pvec (S->pinv, x, b, n) ; /* b(0:n-1) = x(p(0:n-1)) */ } } cs_free (x) ; cs_sfree (S) ; cs_nfree (N) ; cs_spfree (AT) ; return (ok) ; } igraph/src/cs/cs_scatter.c0000644000175100001440000000340313431000472015226 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* x = x + beta * A(:,j), where x is a dense vector and A(:,j) is sparse */ CS_INT cs_scatter (const cs *A, CS_INT j, CS_ENTRY beta, CS_INT *w, CS_ENTRY *x, CS_INT mark, cs *C, CS_INT nz) { CS_INT i, p, *Ap, *Ai, *Ci ; CS_ENTRY *Ax ; if (!CS_CSC (A) || !w || !CS_CSC (C)) return (-1) ; /* check inputs */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Ci = C->i ; for (p = Ap [j] ; p < Ap [j+1] ; p++) { i = Ai [p] ; /* A(i,j) is nonzero */ if (w [i] < mark) { w [i] = mark ; /* i is new entry in column j */ Ci [nz++] = i ; /* add i to pattern of C(:,j) */ if (x) x [i] = beta * Ax [p] ; /* x(i) = beta*A(i,j) */ } else if (x) x [i] += beta * Ax [p] ; /* i exists in C(:,j) already */ } return (nz) ; } igraph/src/cs/cs_symperm.c0000644000175100001440000000516513431000472015264 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* C = A(p,p) where A and C are symmetric the upper part stored; pinv not p */ cs *cs_symperm (const cs *A, const CS_INT *pinv, CS_INT values) { CS_INT i, j, p, q, i2, j2, n, *Ap, *Ai, *Cp, *Ci, *w ; CS_ENTRY *Cx, *Ax ; cs *C ; if (!CS_CSC (A)) return (NULL) ; /* check inputs */ n = A->n ; Ap = A->p ; Ai = A->i ; Ax = A->x ; C = cs_spalloc (n, n, Ap [n], values && (Ax != NULL), 0) ; /* alloc result*/ w = cs_calloc (n, sizeof (CS_INT)) ; /* get workspace */ if (!C || !w) return (cs_done (C, w, NULL, 0)) ; /* out of memory */ Cp = C->p ; Ci = C->i ; Cx = C->x ; for (j = 0 ; j < n ; j++) /* count entries in each column of C */ { j2 = pinv ? pinv [j] : j ; /* column j of A is column j2 of C */ for (p = Ap [j] ; p < Ap [j+1] ; p++) { i = Ai [p] ; if (i > j) continue ; /* skip lower triangular part of A */ i2 = pinv ? pinv [i] : i ; /* row i of A is row i2 of C */ w [CS_MAX (i2, j2)]++ ; /* column count of C */ } } cs_cumsum (Cp, w, n) ; /* compute column pointers of C */ for (j = 0 ; j < n ; j++) { j2 = pinv ? pinv [j] : j ; /* column j of A is column j2 of C */ for (p = Ap [j] ; p < Ap [j+1] ; p++) { i = Ai [p] ; if (i > j) continue ; /* skip lower triangular part of A*/ i2 = pinv ? pinv [i] : i ; /* row i of A is row i2 of C */ Ci [q = w [CS_MAX (i2, j2)]++] = CS_MIN (i2, j2) ; if (Cx) Cx [q] = (i2 <= j2) ? Ax [p] : CS_CONJ (Ax [p]) ; } } return (cs_done (C, w, NULL, 1)) ; /* success; free workspace, return C */ } igraph/src/cs/cs_reach.c0000644000175100001440000000306713431000472014651 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* xi [top...n-1] = nodes reachable from graph of G*P' via nodes in B(:,k). * xi [n...2n-1] used as workspace */ CS_INT cs_reach (cs *G, const cs *B, CS_INT k, CS_INT *xi, const CS_INT *pinv) { CS_INT p, n, top, *Bp, *Bi, *Gp ; if (!CS_CSC (G) || !CS_CSC (B) || !xi) return (-1) ; /* check inputs */ n = G->n ; Bp = B->p ; Bi = B->i ; Gp = G->p ; top = n ; for (p = Bp [k] ; p < Bp [k+1] ; p++) { if (!CS_MARKED (Gp, Bi [p])) /* start a dfs at unmarked node i */ { top = cs_dfs (Bi [p], G, top, xi, xi+n, pinv) ; } } for (p = top ; p < n ; p++) CS_MARK (Gp, xi [p]) ; /* restore G */ return (top) ; } igraph/src/cs/cs_updown.c0000644000175100001440000000567013431000472015105 0ustar hornikusers/* * CXSPARSE: a Concise Sparse Matrix package - Extended. * Copyright (c) 2006-2009, Timothy A. Davis. * http://www.cise.ufl.edu/research/sparse/CXSparse * * CXSparse is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * CXSparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this Module; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cs.h" /* sparse Cholesky update/downdate, L*L' + sigma*w*w' (sigma = +1 or -1) */ CS_INT cs_updown (cs *L, CS_INT sigma, const cs *C, const CS_INT *parent) { CS_INT n, p, f, j, *Lp, *Li, *Cp, *Ci ; CS_ENTRY *Lx, *Cx, alpha, gamma, w1, w2, *w ; double beta = 1, beta2 = 1, delta ; #ifdef CS_COMPLEX cs_complex_t phase ; #endif if (!CS_CSC (L) || !CS_CSC (C) || !parent) return (0) ; /* check inputs */ Lp = L->p ; Li = L->i ; Lx = L->x ; n = L->n ; Cp = C->p ; Ci = C->i ; Cx = C->x ; if ((p = Cp [0]) >= Cp [1]) return (1) ; /* return if C empty */ w = cs_malloc (n, sizeof (CS_ENTRY)) ; /* get workspace */ if (!w) return (0) ; /* out of memory */ f = Ci [p] ; for ( ; p < Cp [1] ; p++) f = CS_MIN (f, Ci [p]) ; /* f = min (find (C)) */ for (j = f ; j != -1 ; j = parent [j]) w [j] = 0 ; /* clear workspace w */ for (p = Cp [0] ; p < Cp [1] ; p++) w [Ci [p]] = Cx [p] ; /* w = C */ for (j = f ; j != -1 ; j = parent [j]) /* walk path f up to root */ { p = Lp [j] ; alpha = w [j] / Lx [p] ; /* alpha = w(j) / L(j,j) */ beta2 = beta*beta + sigma*alpha*CS_CONJ(alpha) ; if (beta2 <= 0) break ; /* not positive definite */ beta2 = sqrt (beta2) ; delta = (sigma > 0) ? (beta / beta2) : (beta2 / beta) ; gamma = sigma * CS_CONJ(alpha) / (beta2 * beta) ; Lx [p] = delta * Lx [p] + ((sigma > 0) ? (gamma * w [j]) : 0) ; beta = beta2 ; #ifdef CS_COMPLEX phase = CS_ABS (Lx [p]) / Lx [p] ; /* phase = abs(L(j,j))/L(j,j)*/ Lx [p] *= phase ; /* L(j,j) = L(j,j) * phase */ #endif for (p++ ; p < Lp [j+1] ; p++) { w1 = w [Li [p]] ; w [Li [p]] = w2 = w1 - alpha * Lx [p] ; Lx [p] = delta * Lx [p] + gamma * ((sigma > 0) ? w1 : w2) ; #ifdef CS_COMPLEX Lx [p] *= phase ; /* L(i,j) = L(i,j) * phase */ #endif } } cs_free (w) ; return (beta2 > 0) ; } igraph/src/igraph_heap.c0000644000175100001440000000333213431000472014737 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_heap.h" #define BASE_IGRAPH_REAL #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_IGRAPH_REAL #define BASE_LONG #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_LONG #define BASE_CHAR #define HEAP_TYPE_MAX #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MAX #define HEAP_TYPE_MIN #include "igraph_pmt.h" #include "heap.pmt" #include "igraph_pmt_off.h" #undef HEAP_TYPE_MIN #undef BASE_CHAR igraph/src/dvout.f0000644000175100001440000001031213431000472013630 0ustar hornikusers*----------------------------------------------------------------------- * Routine: DVOUT * * Purpose: Real vector output routine. * * Usage: CALL DVOUT (LOUT, N, SX, IDIGIT, IFMT) * * Arguments * N - Length of array SX. (Input) * SX - Real array to be printed. (Input) * IFMT - Format to be used in printing array SX. (Input) * IDIGIT - Print up to IABS(IDIGIT) decimal digits per number. (In) * If IDIGIT .LT. 0, printing is done with 72 columns. * If IDIGIT .GT. 0, printing is done with 132 columns. * *----------------------------------------------------------------------- * SUBROUTINE IGRAPHDVOUT( LOUT, N, SX, IDIGIT, IFMT ) * ... * ... SPECIFICATIONS FOR ARGUMENTS * ... * ... SPECIFICATIONS FOR LOCAL VARIABLES * .. Scalar Arguments .. CHARACTER*( * ) IFMT INTEGER IDIGIT, LOUT, N * .. * .. Array Arguments .. DOUBLE PRECISION SX( * ) * .. * .. Local Scalars .. CHARACTER*80 LINE INTEGER I, K1, K2, LLL, NDIGIT * .. * .. Intrinsic Functions .. INTRINSIC LEN, MIN, MIN0 * .. * .. Executable Statements .. * ... * ... FIRST EXECUTABLE STATEMENT * * c$$$ LLL = MIN( LEN( IFMT ), 80 ) c$$$ DO 10 I = 1, LLL c$$$ LINE( I: I ) = '-' c$$$ 10 CONTINUE c$$$* c$$$ DO 20 I = LLL + 1, 80 c$$$ LINE( I: I ) = ' ' c$$$ 20 CONTINUE c$$$* c$$$ WRITE( LOUT, FMT = 9999 )IFMT, LINE( 1: LLL ) c$$$ 9999 FORMAT( / 1X, A, / 1X, A ) c$$$* c$$$ IF( N.LE.0 ) c$$$ $ RETURN c$$$ NDIGIT = IDIGIT c$$$ IF( IDIGIT.EQ.0 ) c$$$ $ NDIGIT = 4 c$$$* c$$$*======================================================================= c$$$* CODE FOR OUTPUT USING 72 COLUMNS FORMAT c$$$*======================================================================= c$$$* c$$$ IF( IDIGIT.LT.0 ) THEN c$$$ NDIGIT = -IDIGIT c$$$ IF( NDIGIT.LE.4 ) THEN c$$$ DO 30 K1 = 1, N, 5 c$$$ K2 = MIN0( N, K1+4 ) c$$$ WRITE( LOUT, FMT = 9998 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 30 CONTINUE c$$$ ELSE IF( NDIGIT.LE.6 ) THEN c$$$ DO 40 K1 = 1, N, 4 c$$$ K2 = MIN0( N, K1+3 ) c$$$ WRITE( LOUT, FMT = 9997 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 40 CONTINUE c$$$ ELSE IF( NDIGIT.LE.10 ) THEN c$$$ DO 50 K1 = 1, N, 3 c$$$ K2 = MIN0( N, K1+2 ) c$$$ WRITE( LOUT, FMT = 9996 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 50 CONTINUE c$$$ ELSE c$$$ DO 60 K1 = 1, N, 2 c$$$ K2 = MIN0( N, K1+1 ) c$$$ WRITE( LOUT, FMT = 9995 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 60 CONTINUE c$$$ END IF c$$$* c$$$*======================================================================= c$$$* CODE FOR OUTPUT USING 132 COLUMNS FORMAT c$$$*======================================================================= c$$$* c$$$ ELSE c$$$ IF( NDIGIT.LE.4 ) THEN c$$$ DO 70 K1 = 1, N, 10 c$$$ K2 = MIN0( N, K1+9 ) c$$$ WRITE( LOUT, FMT = 9998 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 70 CONTINUE c$$$ ELSE IF( NDIGIT.LE.6 ) THEN c$$$ DO 80 K1 = 1, N, 8 c$$$ K2 = MIN0( N, K1+7 ) c$$$ WRITE( LOUT, FMT = 9997 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 80 CONTINUE c$$$ ELSE IF( NDIGIT.LE.10 ) THEN c$$$ DO 90 K1 = 1, N, 6 c$$$ K2 = MIN0( N, K1+5 ) c$$$ WRITE( LOUT, FMT = 9996 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 90 CONTINUE c$$$ ELSE c$$$ DO 100 K1 = 1, N, 5 c$$$ K2 = MIN0( N, K1+4 ) c$$$ WRITE( LOUT, FMT = 9995 )K1, K2, ( SX( I ), I = K1, K2 ) c$$$ 100 CONTINUE c$$$ END IF c$$$ END IF c$$$ WRITE( LOUT, FMT = 9994 ) c$$$ RETURN c$$$ 9998 FORMAT( 1X, I4, ' - ', I4, ':', 1P, 10D12.3 ) c$$$ 9997 FORMAT( 1X, I4, ' - ', I4, ':', 1X, 1P, 8D14.5 ) c$$$ 9996 FORMAT( 1X, I4, ' - ', I4, ':', 1X, 1P, 6D18.9 ) c$$$ 9995 FORMAT( 1X, I4, ' - ', I4, ':', 1X, 1P, 5D24.13 ) c$$$ 9994 FORMAT( 1X, ' ' ) END igraph/src/igraph_version.h0000644000175100001440000000252613431000472015520 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_VERSION_H #define IGRAPH_VERSION_H #include "igraph_decls.h" __BEGIN_DECLS #define IGRAPH_VERSION "1.2.4" #define IGRAPH_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@ #define IGRAPH_VERSION_MINOR @PACKAGE_VERSION_MINOR@ #define IGRAPH_VERSION_PATCH @PACKAGE_VERSION_PATCH@ #define IGRAPH_VERSION_PRERELEASE "@PACKAGE_VERSION_PRERELEASE@" int igraph_version(const char **version_string, int *major, int *minor, int *subminor); __END_DECLS #endif igraph/src/igraph_glpk_support.h0000644000175100001440000000267413431000472016570 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_GLPK_SUPPORT_H #define IGRAPH_GLPK_SUPPORT_H #include "config.h" /* Note: only files calling the GLPK routines directly need to include this header. */ #ifdef HAVE_GLPK #include int igraph_i_glpk_check(int retval, const char* message); void igraph_i_glpk_interruption_hook(glp_tree *tree, void *info); #define IGRAPH_GLPK_CHECK(func, message) do {\ int igraph_i_ret = igraph_i_glpk_check(func, message); \ if (IGRAPH_UNLIKELY(igraph_i_ret != 0)) {\ return igraph_i_ret; \ } } while (0) #endif #endif igraph/src/drl_Node.h0000644000175100001440000000437713431000472014235 0ustar hornikusers/* * Copyright 2007 Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains * certain rights in this software. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sandia National Laboratories nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __NODE_H__ #define __NODE_H__ // The node class contains information about a given node for // use by the density server process. // structure coord used to pass position information between // density server and graph class namespace drl { class Node { public: bool fixed; // if true do not change the // position of this node int id; float x,y; float sub_x,sub_y; float energy; public: Node( int node_id ) { x = y = 0.0; fixed = false; id = node_id; } ~Node() { } }; } // namespace drl #endif //__NODE_H__ igraph/src/statusbar.c0000644000175100001440000001052413431000472014501 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "igraph_types.h" #include "igraph_statusbar.h" #include "igraph_error.h" #include #include static IGRAPH_THREAD_LOCAL igraph_status_handler_t *igraph_i_status_handler=0; /** * \function igraph_status * Report status from an igraph function. * * It calls the installed status handler function, if there is * one. Otherwise it does nothing. Note that the standard way to * report the status from an igraph function is the * \ref IGRAPH_STATUS or \ref IGRAPH_STATUSF macro, as these * take care of the termination of the calling function if the * status handler returns with \c IGRAPH_INTERRUPTED. * \param message The status message. * \param data Additional context, with user-defined semantics. * Existing igraph functions pass a null pointer here. * \return Error code. If a status handler function was called * and it did not return with \c IGRAPH_SUCCESS, then * \c IGRAPH_INTERRUPTED is returned by \c igraph_status(). * * Time complexity: O(1). */ int igraph_status(const char *message, void *data) { if (igraph_i_status_handler) { if (igraph_i_status_handler(message, data) != IGRAPH_SUCCESS) { return IGRAPH_INTERRUPTED; } } return IGRAPH_SUCCESS; } /** * \function igraph_statusf * Report status, more flexible printf-like version. * * This is the more flexible version of \ref igraph_status(), * that has a syntax similar to the \c printf standard C library function. * It substitutes the values of the additional arguments into the * \p message template string and calls \ref igraph_status(). * \param message Status message template string, the syntax is the same * as for the \c printf function. * \param data Additional context, with user-defined semantics. * Existing igraph functions pass a null pointer here. * \param ... The additional arguments to fill the template given in the * \p message argument. * \return Error code. If a status handler function was called * and it did not return with \c IGRAPH_SUCCESS, then * \c IGRAPH_INTERRUPTED is returned by \c igraph_status(). */ int igraph_statusf(const char *message, void *data, ...) { char buffer[300]; va_list ap; va_start(ap, data); vsnprintf(buffer, sizeof(buffer)-1, message, ap); return igraph_status(buffer, data); } #ifndef USING_R /** * \function igraph_status_handler_stderr * A simple predefined status handler function. * * A simple status handler function, that writes the status * message to the standard errror. * \param message The status message. * \param data Additional context, with user-defined semantics. * Existing igraph functions pass a null pointer here. * \return Error code. * * Time complexity: O(1). */ int igraph_status_handler_stderr(const char *message, void *data) { IGRAPH_UNUSED(data); fputs(message, stderr); return 0; } #endif /** * \function igraph_set_status_handler * Install of uninstall a status handler function. * * To uninstall the currently installed status handler, call * this function with a null pointer. * \param new_handler The status handler function to install. * \return The previously installed status handler function. * * Time complexity: O(1). */ igraph_status_handler_t * igraph_set_status_handler(igraph_status_handler_t new_handler) { igraph_status_handler_t *previous_handler=igraph_i_status_handler; igraph_i_status_handler = new_handler; return previous_handler; } igraph/src/foreign.c0000644000175100001440000033761413431000472014136 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph R package. Copyright (C) 2005-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_foreign.h" #include "config.h" #include "igraph_math.h" #include "igraph_gml_tree.h" #include "igraph_memory.h" #include "igraph_attributes.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "igraph_constructors.h" #include "igraph_types_internal.h" #include /* isspace */ #include #include /** * \section about_loadsave * * These functions can write a graph to a file, or read a graph * from a file. * * Note that as \a igraph uses the traditional C streams, it is * possible to read/write files from/to memory, at least on GNU * operating systems supporting \quote non-standard\endquote streams. */ /** * \ingroup loadsave * \function igraph_read_graph_edgelist * \brief Reads an edge list from a file and creates a graph. * * * This format is simply a series of even number integers separated by * whitespace. The one edge (ie. two integers) per line format is thus * not required (but recommended for readability). Edges of directed * graphs are assumed to be in from, to order. * \param graph Pointer to an uninitialized graph object. * \param instream Pointer to a stream, it should be readable. * \param n The number of vertices in the graph. If smaller than the * largest integer in the file it will be ignored. It is thus * safe to supply zero here. * \param directed Logical, if true the graph is directed, if false it * will be undirected. * \return Error code: * \c IGRAPH_PARSEERROR: if there is a * problem reading the file, or the file is syntactically * incorrect. * * Time complexity: O(|V|+|E|), the * number of vertices plus the number of edges. It is assumed that * reading an integer requires O(1) * time. */ int igraph_read_graph_edgelist(igraph_t *graph, FILE *instream, igraph_integer_t n, igraph_bool_t directed) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; long int from, to; int c; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_CHECK(igraph_vector_reserve(&edges, 100)); /* skip all whitespace */ do { c = getc (instream); } while (isspace (c)); ungetc (c, instream); while (!feof(instream)) { int read; IGRAPH_ALLOW_INTERRUPTION(); read=fscanf(instream, "%li", &from); if (read != 1) { IGRAPH_ERROR("parsing edgelist file failed", IGRAPH_PARSEERROR); } read=fscanf(instream, "%li", &to); if (read != 1) { IGRAPH_ERROR("parsing edgelist file failed", IGRAPH_PARSEERROR); } IGRAPH_CHECK(igraph_vector_push_back(&edges, from)); IGRAPH_CHECK(igraph_vector_push_back(&edges, to)); /* skip all whitespace */ do { c = getc (instream); } while (isspace (c)); ungetc (c, instream); } IGRAPH_CHECK(igraph_create(graph, &edges, n, directed)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } #include "foreign-ncol-header.h" int igraph_ncol_yylex_init_extra (igraph_i_ncol_parsedata_t* user_defined, void* scanner); int igraph_ncol_yylex_destroy (void *scanner ); int igraph_ncol_yyparse (igraph_i_ncol_parsedata_t* context); void igraph_ncol_yyset_in (FILE * in_str, void* yyscanner ); /** * \ingroup loadsave * \function igraph_read_graph_ncol * \brief Reads a .ncol file used by LGL. * * Also useful for creating graphs from \quote named\endquote (and * optionally weighted) edge lists. * * * This format is used by the Large Graph Layout program * (http://lgl.sourceforge.net), and it is simply a * symbolic weighted edge list. It is a simple text file with one edge * per line. An edge is defined by two symbolic vertex names separated * by whitespace. (The symbolic vertex names themselves cannot contain * whitespace. They might follow by an optional number, this will be * the weight of the edge; the number can be negative and can be in * scientific notation. If there is no weight specified to an edge it * is assumed to be zero. * * * The resulting graph is always undirected. * LGL cannot deal with files which contain multiple or loop edges, * this is however not checked here, as \a igraph is happy with * these. * \param graph Pointer to an uninitialized graph object. * \param instream Pointer to a stream, it should be readable. * \param predefnames Pointer to the symbolic names of the vertices in * the file. If \c NULL is given here then vertex ids will be * assigned to vertex names in the order of their appearance in * the \c .ncol file. If it is not \c NULL and some unknown * vertex names are found in the \c .ncol file then new vertex * ids will be assigned to them. * \param names Logical value, if TRUE the symbolic names of the * vertices will be added to the graph as a vertex attribute * called \quote name\endquote. * \param weights Whether to add the weights of the edges to the * graph as an edge attribute called \quote weight\endquote. * \c IGRAPH_ADD_WEIGHTS_YES adds the weights (even if they * are not present in the file, in this case they are assumed * to be zero). \c IGRAPH_ADD_WEIGHTS_NO does not add any * edge attribute. \c IGRAPH_ADD_WEIGHTS_IF_PRESENT adds the * attribute if and only if there is at least one explicit * edge weight in the input file. * \param directed Whether to create a directed graph. As this format * was originally used only for undirected graphs there is no * information in the file about the directedness of the graph. * Set this parameter to \c IGRAPH_DIRECTED or \c * IGRAPH_UNDIRECTED to create a directed or undirected graph. * \return Error code: * \c IGRAPH_PARSEERROR: if there is a * problem reading * the file, or the file is syntactically incorrect. * * Time complexity: * O(|V|+|E|log(|V|)) if we neglect * the time required by the parsing. As usual * |V| is the number of vertices, * while |E| is the number of edges. * * \sa \ref igraph_read_graph_lgl(), \ref igraph_write_graph_ncol() */ int igraph_read_graph_ncol(igraph_t *graph, FILE *instream, igraph_strvector_t *predefnames, igraph_bool_t names, igraph_add_weights_t weights, igraph_bool_t directed) { igraph_vector_t edges, ws; igraph_trie_t trie=IGRAPH_TRIE_NULL; igraph_integer_t no_of_nodes; long int no_predefined=0; igraph_vector_ptr_t name, weight; igraph_vector_ptr_t *pname=0, *pweight=0; igraph_attribute_record_t namerec, weightrec; const char *namestr="name", *weightstr="weight"; igraph_i_ncol_parsedata_t context; IGRAPH_CHECK(igraph_empty(graph, 0, directed)); IGRAPH_FINALLY(igraph_destroy, graph); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_TRIE_INIT_FINALLY(&trie, names); IGRAPH_VECTOR_INIT_FINALLY(&ws, 0); /* Add the predefined names, if any */ if (predefnames != 0) { long int i, id, n; char *key; n=no_predefined=igraph_strvector_size(predefnames); for (i=0; i.lgl
file * *
* The .lgl format is used by the Large Graph * Layout visualization software * (http://lgl.sourceforge.net), it can * describe undirected optionally weighted graphs. From the LGL * manual: * * \blockquote The second format is the LGL file format * (.lgl file * suffix). This is yet another graph file format that tries to be as * stingy as possible with space, yet keeping the edge file in a human * readable (not binary) format. The format itself is like the * following: * \verbatim # vertex1name vertex2name [optionalWeight] vertex3name [optionalWeight] \endverbatim * Here, the first vertex of an edge is preceded with a pound sign * '#'. Then each vertex that shares an edge with that vertex is * listed one per line on subsequent lines. \endblockquote * * * LGL cannot handle loop and multiple edges or directed graphs, but * in \a igraph it is not an error to have multiple and loop edges. * \param graph Pointer to an uninitialized graph object. * \param instream A stream, it should be readable. * \param names Logical value, if TRUE the symbolic names of the * vertices will be added to the graph as a vertex attribute * called \quote name\endquote. * \param weights Whether to add the weights of the edges to the * graph as an edge attribute called \quote weight\endquote. * \c IGRAPH_ADD_WEIGHTS_YES adds the weights (even if they * are not present in the file, in this case they are assumed * to be zero). \c IGRAPH_ADD_WEIGHTS_NO does not add any * edge attribute. \c IGRAPH_ADD_WEIGHTS_IF_PRESENT adds the * attribute if and only if there is at least one explicit * edge weight in the input file. * \param directed Whether to create a directed graph. As this format * was originally used only for undirected graphs there is no * information in the file about the directedness of the graph. * Set this parameter to \c IGRAPH_DIRECTED or \c * IGRAPH_UNDIRECTED to create a directed or undirected graph. * \return Error code: * \c IGRAPH_PARSEERROR: if there is a * problem reading the file, or the file is syntactically * incorrect. * * Time complexity: * O(|V|+|E|log(|V|)) if we neglect * the time required by the parsing. As usual * |V| is the number of vertices, * while |E| is the number of edges. * * \sa \ref igraph_read_graph_ncol(), \ref igraph_write_graph_lgl() * * \example examples/simple/igraph_read_graph_lgl.c */ int igraph_read_graph_lgl(igraph_t *graph, FILE *instream, igraph_bool_t names, igraph_add_weights_t weights, igraph_bool_t directed) { igraph_vector_t edges=IGRAPH_VECTOR_NULL, ws=IGRAPH_VECTOR_NULL; igraph_trie_t trie=IGRAPH_TRIE_NULL; igraph_vector_ptr_t name, weight; igraph_vector_ptr_t *pname=0, *pweight=0; igraph_attribute_record_t namerec, weightrec; const char *namestr="name", *weightstr="weight"; igraph_i_lgl_parsedata_t context; IGRAPH_VECTOR_INIT_FINALLY(&ws, 0); IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_TRIE_INIT_FINALLY(&trie, names); context.has_weights=0; context.vector=&edges; context.weights=&ws; context.trie=≜ context.eof=0; igraph_lgl_yylex_init_extra(&context, &context.scanner); IGRAPH_FINALLY(igraph_lgl_yylex_destroy, context.scanner); igraph_lgl_yyset_in(instream, context.scanner); if (igraph_lgl_yyparse(&context)) { if (context.errmsg) { IGRAPH_ERROR(context.errmsg, IGRAPH_PARSEERROR); } else { IGRAPH_ERROR("Cannot read LGL file", IGRAPH_PARSEERROR); } } IGRAPH_CHECK(igraph_empty(graph, 0, directed)); IGRAPH_FINALLY(igraph_destroy, graph); if (names) { const igraph_strvector_t *namevec; IGRAPH_CHECK(igraph_vector_ptr_init(&name, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &name); pname=&name; igraph_trie_getkeys(&trie, &namevec); /* dirty */ namerec.name=namestr; namerec.type=IGRAPH_ATTRIBUTE_STRING; namerec.value=namevec; VECTOR(name)[0]=&namerec; } if (weights == IGRAPH_ADD_WEIGHTS_YES || (weights == IGRAPH_ADD_WEIGHTS_IF_PRESENT && context.has_weights)) { IGRAPH_CHECK(igraph_vector_ptr_init(&weight, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &weight); pweight=&weight; weightrec.name=weightstr; weightrec.type=IGRAPH_ATTRIBUTE_NUMERIC; weightrec.value=&ws; VECTOR(weight)[0]=&weightrec; } IGRAPH_CHECK(igraph_add_vertices(graph, (igraph_integer_t) igraph_trie_size(&trie), pname)); IGRAPH_CHECK(igraph_add_edges(graph, &edges, pweight)); if (pweight) { igraph_vector_ptr_destroy(pweight); IGRAPH_FINALLY_CLEAN(1); } if (pname) { igraph_vector_ptr_destroy(pname); IGRAPH_FINALLY_CLEAN(1); } igraph_trie_destroy(&trie); igraph_vector_destroy(&edges); igraph_vector_destroy(&ws); igraph_lgl_yylex_destroy(context.scanner); IGRAPH_FINALLY_CLEAN(5); return 0; } #include "foreign-pajek-header.h" int igraph_pajek_yylex_init_extra(igraph_i_pajek_parsedata_t* user_defined, void* scanner); int igraph_pajek_yylex_destroy (void *scanner ); int igraph_pajek_yyparse (igraph_i_pajek_parsedata_t* context); void igraph_pajek_yyset_in (FILE * in_str, void* yyscanner ); /** * \function igraph_read_graph_pajek * \brief Reads a file in Pajek format * * \param graph Pointer to an uninitialized graph object. * \param file An already opened file handler. * \return Error code. * * * Only a subset of the Pajek format is implemented. This is partially * because this format is not very well documented, but also because * igraph does not support some Pajek features, like * multigraphs. * * * Starting from version 0.6.1 igraph reads bipartite (two-mode) * graphs from Pajek files and add the \c type vertex attribute for them. * Warnings are given for invalid edges, i.e. edges connecting * vertices of the same type. * * * The list of the current limitations: * \olist * \oli Only .net files are supported, Pajek * project files (.paj) are not. These might be * supported in the future if there is need for it. * \oli Time events networks are not supported. * \oli Hypergraphs (ie. graphs with non-binary edges) are not * supported. * \oli Graphs with both directed and non-directed edges are not * supported, are they cannot be represented in * igraph. * \oli Only Pajek networks are supported, permutations, hierarchies, * clusters and vectors are not. * \oli Graphs with multiple edge sets are not supported. * \endolist * * * If there are attribute handlers installed, * igraph also reads the vertex and edge attributes * from the file. Most attributes are renamed to be more informative: * `\c color' instead of `\c c', `\c xfact' instead of `\c x_fact', * `\c yfact' instead of `y_fact', `\c labeldist' instead of `\c lr', * `\c labeldegree2' instead of `\c lphi', `\c framewidth' instead of `\c bw', * `\c fontsize' * instead of `\c fos', `\c rotation' instead of `\c phi', `\c radius' instead * of `\c r', * `\c diamondratio' instead of `\c q', `\c labeldegree' instead of `\c la', * `\c vertexsize' * instead of `\c size', `\c color' instead of `\c ic', `\c framecolor' instead of * `\c bc', `\c labelcolor' instead of `\c lc', these belong to vertices. * * * Edge attributes are also renamed, `\c s' to `\c arrowsize', `\c w' * to `\c edgewidth', `\c h1' to `\c hook1', `\c h2' to `\c hook2', * `\c a1' to `\c angle1', `\c a2' to `\c angle2', `\c k1' to * `\c velocity1', `\c k2' to `\c velocity2', `\c ap' to `\c * arrowpos', `\c lp' to `\c labelpos', `\c lr' to * `\c labelangle', `\c lphi' to `\c labelangle2', `\c la' to `\c * labeldegree', `\c fos' to * `\c fontsize', `\c a' to `\c arrowtype', `\c p' to `\c * linepattern', `\c l' to `\c label', `\c lc' to * `\c labelcolor', `\c c' to `\c color'. * * * In addition the following vertex attributes might be added: `\c id' * if there are vertex ids in the file, `\c x' and `\c y' or `\c x' * and `\c y' and `\c z' if there are vertex coordinates in the file. * * The `\c weight' edge attribute might be * added if there are edge weights present. * * * See the pajek homepage: * http://vlado.fmf.uni-lj.si/pub/networks/pajek/ for more info on * Pajek and the Pajek manual: * http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/pajekman.pdf for * information on the Pajek file format. * * * Time complexity: O(|V|+|E|+|A|), |V| is the number of vertices, |E| * the number of edges, |A| the number of attributes (vertex + edge) * in the graph if there are attribute handlers installed. * * \sa \ref igraph_write_graph_pajek() for writing Pajek files, \ref * igraph_read_graph_graphml() for reading GraphML files. * * \example examples/simple/foreign.c */ int igraph_read_graph_pajek(igraph_t *graph, FILE *instream) { igraph_vector_t edges; igraph_trie_t vattrnames; igraph_vector_ptr_t vattrs; igraph_trie_t eattrnames; igraph_vector_ptr_t eattrs; long int i, j; igraph_i_pajek_parsedata_t context; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); IGRAPH_TRIE_INIT_FINALLY(&vattrnames, 1); IGRAPH_VECTOR_PTR_INIT_FINALLY(&vattrs, 0); IGRAPH_TRIE_INIT_FINALLY(&eattrnames, 1); IGRAPH_VECTOR_PTR_INIT_FINALLY(&eattrs, 0); context.vector=&edges; context.mode=0; context.vcount=-1; context.vertexid=0; context.vertex_attribute_names=&vattrnames; context.vertex_attributes=&vattrs; context.edge_attribute_names=&eattrnames; context.edge_attributes=&eattrs; context.actedge=0; context.eof=0; igraph_pajek_yylex_init_extra(&context, &context.scanner); IGRAPH_FINALLY(igraph_pajek_yylex_destroy, context.scanner); igraph_pajek_yyset_in(instream, context.scanner); if (igraph_pajek_yyparse(&context)) { if (context.errmsg) { IGRAPH_ERROR(context.errmsg, IGRAPH_PARSEERROR); } else { IGRAPH_ERROR("Cannot read Pajek file", IGRAPH_PARSEERROR); } } if (context.vcount < 0) IGRAPH_ERROR("invalid vertex count in Pajek file", IGRAPH_EINVAL); if (context.vcount2 < 0) IGRAPH_ERROR("invalid 2-mode vertex count in Pajek file", IGRAPH_EINVAL); for (i=0; itype==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*)rec->value; long int origsize=igraph_vector_size(vec); igraph_vector_resize(vec, context.actedge); for (j=origsize; jtype==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t*)rec->value; long int origsize=igraph_strvector_size(strvec); igraph_strvector_resize(strvec, context.actedge); for (j=origsize; jtype == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*) rec->value; igraph_vector_destroy(vec); igraph_Free(vec); } else if (rec->type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t *)rec->value; igraph_strvector_destroy(strvec); igraph_Free(strvec); } igraph_free( (char*)(rec->name)); igraph_Free(rec); } for (i=0; itype == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *vec=(igraph_vector_t*) rec->value; igraph_vector_destroy(vec); igraph_Free(vec); } else if (rec->type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *strvec=(igraph_strvector_t *)rec->value; igraph_strvector_destroy(strvec); igraph_Free(strvec); } igraph_free( (char*)(rec->name)); igraph_Free(rec); } igraph_vector_destroy(&edges); igraph_vector_ptr_destroy(&eattrs); igraph_trie_destroy(&eattrnames); igraph_vector_ptr_destroy(&vattrs); igraph_trie_destroy(&vattrnames); igraph_pajek_yylex_destroy(context.scanner); IGRAPH_FINALLY_CLEAN(7); return 0; } /** * \function igraph_read_graph_dimacs * \brief Read a graph in DIMACS format. * * This function reads the DIMACS file format, more specifically the * version for network flow problems, see the files at * ftp://dimacs.rutgers.edu/pub/netflow/general-info/ * * * This is a line-oriented text file (ASCII) format. The first * character of each line defines the type of the line. If the first * character is c the line is a comment line and it is * ignored. There is one problem line (p in the file, it * must appear before any node and arc descriptor lines. The problem * line has three fields separated by spaces: the problem type * (min, max or asn), the * number of vertices and number of edges in the graph. * Exactly two node identification lines are expected * (n), one for the source, one for the target vertex. * These have two fields: the id of the vertex and the type of the * vertex, either s (=source) or t * (=target). Arc lines start with a and have three * fields: the source vertex, the target vertex and the edge capacity. * * * Vertex ids are numbered from 1. * \param graph Pointer to an uninitialized graph object. * \param instream The file to read from. * \param source Pointer to an integer, the id of the source node will * be stored here. (The igraph vertex id, which is one less than * the actual number in the file.) It is ignored if * NULL. * \param target Pointer to an integer, the (igraph) id of the target * node will be stored here. It is ignored if NULL. * \param capacity Pointer to an initialized vector, the capacity of * the edges will be stored here if not NULL. * \param directed Boolean, whether to create a directed graph. * \return Error code. * * Time complexity: O(|V|+|E|+c), the number of vertices plus the * number of edges, plus the size of the file in characters. * * \sa \ref igraph_write_graph_dimacs() */ int igraph_read_graph_dimacs(igraph_t *graph, FILE *instream, igraph_strvector_t *problem, igraph_vector_t *label, igraph_integer_t *source, igraph_integer_t *target, igraph_vector_t *capacity, igraph_bool_t directed) { igraph_vector_t edges; long int no_of_nodes=-1; long int no_of_edges=-1; long int tsource=-1; long int ttarget=-1; char prob[21]; char c; int problem_type=0; #define PROBLEM_EDGE 1 #define PROBLEM_MAX 2 IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); if (capacity) { igraph_vector_clear(capacity); } while (!feof(instream)) { int read; char str[3]; IGRAPH_ALLOW_INTERRUPTION(); read=fscanf(instream, "%2c", str); if (feof(instream)) { break; } if (read != 1) { IGRAPH_ERROR("parsing dimacs file failed", IGRAPH_PARSEERROR); } switch (str[0]) { long int tmp, tmp2; long int from, to; igraph_real_t cap; case 'c': /* comment */ break; case 'p': if (no_of_nodes != -1) { IGRAPH_ERROR("reading dimacs file failed, double 'p' line", IGRAPH_PARSEERROR); } read=fscanf(instream, "%20s %li %li", prob, &no_of_nodes, &no_of_edges); if (read != 3) { IGRAPH_ERROR("reading dimacs file failed", IGRAPH_PARSEERROR); } if (!strcmp(prob, "edge")) { /* edge list */ problem_type=PROBLEM_EDGE; if (label) { long int i; IGRAPH_CHECK(igraph_vector_resize(label, no_of_nodes)); for (i=0; i * * \blockquote * The graphs are stored in a compact binary format, one graph per * file. The file is composed of 16 bit words, which are represented * using the so-called little-endian convention, i.e. the least * significant byte of the word is stored first. * * * Then, for each node, the file contains the list of edges coming * out of the node itself. The list is represented by a word encoding * its length, followed by a word for each edge, representing the * destination node of the edge. Node numeration is 0-based, so the * first node of the graph has index 0. \endblockquote * * * Only unlabelled graphs are implemented. * \param graph Pointer to an uninitialized graph object. * \param instream The stream to read from. * \param directed Logical scalar, whether to create a directed graph. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices plus the * number of edges. * * \example examples/simple/igraph_read_graph_graphdb.c */ int igraph_read_graph_graphdb(igraph_t *graph, FILE *instream, igraph_bool_t directed) { igraph_vector_t edges; long int nodes; long int i, j; igraph_bool_t end=0; IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); nodes=igraph_i_read_graph_graphdb_getword(instream); if (nodes<0) { IGRAPH_ERROR("Can't read from file", IGRAPH_EFILE); } for (i=0; !end && itype == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *value=(igraph_vector_t*)atrec->value; if (value != 0) { igraph_vector_destroy(value); igraph_Free(value); } } else { igraph_strvector_t *value=(igraph_strvector_t*)atrec->value; if (value != 0) { igraph_strvector_destroy(value); igraph_Free(value); } } igraph_Free(atrec->name); igraph_Free(atrec); } igraph_vector_ptr_destroy(vec); } } igraph_real_t igraph_i_gml_toreal(igraph_gml_tree_t *node, long int pos) { igraph_real_t value=0.0; int type=igraph_gml_tree_type(node, pos); switch (type) { case IGRAPH_I_GML_TREE_INTEGER: value=igraph_gml_tree_get_integer(node, pos); break; case IGRAPH_I_GML_TREE_REAL: value=igraph_gml_tree_get_real(node, pos); break; default: IGRAPH_ERROR("Internal error while parsing GML file", IGRAPH_FAILURE); break; } return value; } const char *igraph_i_gml_tostring(igraph_gml_tree_t *node, long int pos) { int type=igraph_gml_tree_type(node, pos); char tmp[256]; const char *p=tmp; long int i; igraph_real_t d; switch (type) { case IGRAPH_I_GML_TREE_INTEGER: i=igraph_gml_tree_get_integer(node, pos); snprintf(tmp, sizeof(tmp)/sizeof(char), "%li", i); break; case IGRAPH_I_GML_TREE_REAL: d=igraph_gml_tree_get_real(node, pos); igraph_real_snprintf_precise(tmp, sizeof(tmp)/sizeof(char), d); break; case IGRAPH_I_GML_TREE_STRING: p=igraph_gml_tree_get_string(node, pos); break; default: break; } return p; } /** * \function igraph_read_graph_gml * \brief Read a graph in GML format. * * GML is a simple textual format, see * http://www.fim.uni-passau.de/en/fim/faculty/chairs/theoretische-informatik/projects.html for details. * * * Although all syntactically correct GML can be parsed, * we implement only a subset of this format, some attributes might be * ignored. Here is a list of all the differences: * \olist * \oli Only node and edge attributes are * used, and only if they have a simple type: integer, real or * string. So if an attribute is an array or a record, then it is * ignored. This is also true if only some values of the * attribute are complex. * \oli Top level attributes except for Version and the * first graph attribute are completely ignored. * \oli Graph attributes except for node and * edge are completely ignored. * \oli There is no maximum line length. * \oli There is no maximum keyword length. * \oli Character entities in strings are not interpreted. * \oli We allow inf (infinity) and nan * (not a number) as a real number. This is case insensitive, so * nan, NaN and NAN are equal. * \endolist * * Please contact us if you cannot live with these * limitations of the GML parser. * \param graph Pointer to an uninitialized graph object. * \param instream The stream to read the GML file from. * \return Error code. * * Time complexity: should be proportional to the length of the file. * * \sa \ref igraph_read_graph_graphml() for a more modern format, * \ref igraph_write_graph_gml() for writing GML files. * * \example examples/simple/gml.c */ int igraph_read_graph_gml(igraph_t *graph, FILE *instream) { long int i, p; long int no_of_nodes=0, no_of_edges=0; igraph_trie_t trie; igraph_vector_t edges; igraph_bool_t directed=IGRAPH_UNDIRECTED; igraph_gml_tree_t *gtree; long int gidx; igraph_trie_t vattrnames; igraph_trie_t eattrnames; igraph_trie_t gattrnames; igraph_vector_ptr_t gattrs=IGRAPH_VECTOR_PTR_NULL, vattrs=IGRAPH_VECTOR_PTR_NULL, eattrs=IGRAPH_VECTOR_PTR_NULL; igraph_vector_ptr_t *attrs[3]; long int edgeptr=0; igraph_i_gml_parsedata_t context; attrs[0]=&gattrs; attrs[1]=&vattrs; attrs[2]=&eattrs; context.eof=0; context.tree=0; igraph_gml_yylex_init_extra(&context, &context.scanner); IGRAPH_FINALLY(igraph_gml_yylex_destroy, context.scanner); igraph_gml_yyset_in(instream, context.scanner); i=igraph_gml_yyparse(&context); if (i != 0) { if (context.errmsg) { IGRAPH_ERROR(context.errmsg, IGRAPH_PARSEERROR); } else { IGRAPH_ERROR("Cannot read GML file", IGRAPH_PARSEERROR); } } IGRAPH_VECTOR_INIT_FINALLY(&edges, 0); /* Check version, if present, integer and not '1' then ignored */ i=igraph_gml_tree_find(context.tree, "Version", 0); if (i>=0 && igraph_gml_tree_type(context.tree, i)==IGRAPH_I_GML_TREE_INTEGER && igraph_gml_tree_get_integer(context.tree, i) != 1) { igraph_gml_tree_destroy(context.tree); IGRAPH_ERROR("Unknown GML version", IGRAPH_UNIMPLEMENTED); /* RETURN HERE!!!! */ } /* get the graph */ gidx=igraph_gml_tree_find(context.tree, "graph", 0); if (gidx==-1) { IGRAPH_ERROR("No 'graph' object in GML file", IGRAPH_PARSEERROR); } if (igraph_gml_tree_type(context.tree, gidx) != IGRAPH_I_GML_TREE_TREE) { IGRAPH_ERROR("Invalid type for 'graph' object in GML file", IGRAPH_PARSEERROR); } gtree=igraph_gml_tree_get_tree(context.tree, gidx); IGRAPH_FINALLY(igraph_i_gml_destroy_attrs, &attrs); igraph_vector_ptr_init(&gattrs, 0); igraph_vector_ptr_init(&vattrs, 0); igraph_vector_ptr_init(&eattrs, 0); IGRAPH_TRIE_INIT_FINALLY(&trie, 0); IGRAPH_TRIE_INIT_FINALLY(&vattrnames, 0); IGRAPH_TRIE_INIT_FINALLY(&eattrnames, 0); IGRAPH_TRIE_INIT_FINALLY(&gattrnames, 0); /* Is is directed? */ i=igraph_gml_tree_find(gtree, "directed", 0); if (i>=0 && igraph_gml_tree_type(gtree, i)==IGRAPH_I_GML_TREE_INTEGER) { if (igraph_gml_tree_get_integer(gtree, i) == 1) { directed=IGRAPH_DIRECTED; } } /* Now we go over all objects in the graph and collect the attribute names and types. Plus we collect node ids. We also do some checks. */ for (i=0; iname=strdup(name); if (type==IGRAPH_I_GML_TREE_INTEGER || type==IGRAPH_I_GML_TREE_REAL) { atrec->type=IGRAPH_ATTRIBUTE_NUMERIC; } else { atrec->type=IGRAPH_ATTRIBUTE_STRING; } } else { /* already seen, should we update type? */ igraph_attribute_record_t *atrec=VECTOR(vattrs)[trieid]; int type1=atrec->type; int type2=igraph_gml_tree_type(node, j); if (type1==IGRAPH_ATTRIBUTE_NUMERIC && type2==IGRAPH_I_GML_TREE_STRING) { atrec->type=IGRAPH_ATTRIBUTE_STRING; } } /* check id */ if (!hasid && !strcmp(name, "id")) { long int id; if (igraph_gml_tree_type(node, j) != IGRAPH_I_GML_TREE_INTEGER) { IGRAPH_ERROR("Non-integer node id in GML file", IGRAPH_PARSEERROR); } id=igraph_gml_tree_get_integer(node, j); snprintf(cname, sizeof(cname)/sizeof(char)-1, "%li", id); IGRAPH_CHECK(igraph_trie_get(&trie, cname, &id)); hasid=1; } } if (!hasid) { IGRAPH_ERROR("Node without 'id' while parsing GML file", IGRAPH_PARSEERROR); } } else if (!strcmp(name, "edge")) { igraph_gml_tree_t *edge; igraph_bool_t has_source=0, has_target=0; no_of_edges++; if (igraph_gml_tree_type(gtree, i) != IGRAPH_I_GML_TREE_TREE) { IGRAPH_ERROR("'edge' is not a list", IGRAPH_PARSEERROR); } edge=igraph_gml_tree_get_tree(gtree, i); has_source=has_target=0; for (j=0; jname=strdup(name); if (type==IGRAPH_I_GML_TREE_INTEGER || type==IGRAPH_I_GML_TREE_REAL) { atrec->type=IGRAPH_ATTRIBUTE_NUMERIC; } else { atrec->type=IGRAPH_ATTRIBUTE_STRING; } } else { /* already seen, should we update type? */ igraph_attribute_record_t *atrec=VECTOR(eattrs)[trieid]; int type1=atrec->type; int type2=igraph_gml_tree_type(edge, j); if (type1==IGRAPH_ATTRIBUTE_NUMERIC && type2==IGRAPH_I_GML_TREE_STRING) { atrec->type=IGRAPH_ATTRIBUTE_STRING; } } } } /* for */ if (!has_source) { IGRAPH_ERROR("No 'source' for edge in GML file", IGRAPH_PARSEERROR); } if (!has_target) { IGRAPH_ERROR("No 'target' for edge in GML file", IGRAPH_PARSEERROR); } } else { /* anything to do? Maybe add as graph attribute.... */ } } /* check vertex id uniqueness */ if (igraph_trie_size(&trie) != no_of_nodes) { IGRAPH_ERROR("Node 'id' not unique", IGRAPH_PARSEERROR); } /* now we allocate the vectors and strvectors for the attributes */ for (i=0; itype; if (type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *p=igraph_Calloc(1, igraph_vector_t); atrec->value=p; IGRAPH_CHECK(igraph_vector_init(p, no_of_nodes)); } else if (type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *p=igraph_Calloc(1, igraph_strvector_t); atrec->value=p; IGRAPH_CHECK(igraph_strvector_init(p, no_of_nodes)); } else { IGRAPH_WARNING("A composite attribute ignored"); } } for (i=0; itype; if (type == IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *p=igraph_Calloc(1, igraph_vector_t); atrec->value=p; IGRAPH_CHECK(igraph_vector_init(p, no_of_edges)); } else if (type == IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *p=igraph_Calloc(1, igraph_strvector_t); atrec->value=p; IGRAPH_CHECK(igraph_strvector_init(p, no_of_edges)); } else { IGRAPH_WARNING("A composite attribute ignored"); } } /* Ok, now the edges, attributes too */ IGRAPH_CHECK(igraph_vector_resize(&edges, no_of_edges*2)); p=-1; while ( (p=igraph_gml_tree_find(gtree, "edge", p+1)) != -1) { igraph_gml_tree_t *edge; long int from, to, fromidx=0, toidx=0; char name[100]; long int j; edge=igraph_gml_tree_get_tree(gtree, p); for (j=0; jtype; if (type==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *v=(igraph_vector_t *)atrec->value; VECTOR(*v)[edgeid]=igraph_i_gml_toreal(edge, j); } else if (type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *v=(igraph_strvector_t *)atrec->value; const char *value=igraph_i_gml_tostring(edge, j); IGRAPH_CHECK(igraph_strvector_set(v, edgeid, value)); } } } from=igraph_gml_tree_get_integer(edge, fromidx); to=igraph_gml_tree_get_integer(edge, toidx); snprintf(name, sizeof(name)/sizeof(char)-1, "%li", from); IGRAPH_CHECK(igraph_trie_get(&trie, name, &from)); snprintf(name, sizeof(name)/sizeof(char)-1, "%li", to); IGRAPH_CHECK(igraph_trie_get(&trie, name, &to)); if (igraph_trie_size(&trie) != no_of_nodes) { IGRAPH_ERROR("Unknown node id found at an edge", IGRAPH_PARSEERROR); } VECTOR(edges)[edgeptr++]=from; VECTOR(edges)[edgeptr++]=to; } /* and add vertex attributes */ for (i=0; itype; if (type==IGRAPH_ATTRIBUTE_NUMERIC) { igraph_vector_t *v=(igraph_vector_t *)atrec->value; VECTOR(*v)[id]=igraph_i_gml_toreal(node, j); } else if (type==IGRAPH_ATTRIBUTE_STRING) { igraph_strvector_t *v=(igraph_strvector_t *)atrec->value; const char *value=igraph_i_gml_tostring(node, j); IGRAPH_CHECK(igraph_strvector_set(v, id, value)); } } } } igraph_gml_tree_destroy(context.tree); igraph_trie_destroy(&trie); igraph_trie_destroy(&gattrnames); igraph_trie_destroy(&vattrnames); igraph_trie_destroy(&eattrnames); IGRAPH_FINALLY_CLEAN(4); IGRAPH_CHECK(igraph_empty_attrs(graph, 0, directed, 0)); /* TODO */ IGRAPH_CHECK(igraph_add_vertices(graph, (igraph_integer_t) no_of_nodes, &vattrs)); IGRAPH_CHECK(igraph_add_edges(graph, &edges, &eattrs)); igraph_i_gml_destroy_attrs(attrs); igraph_vector_destroy(&edges); igraph_gml_yylex_destroy(context.scanner); IGRAPH_FINALLY_CLEAN(3); return 0; } /** * \ingroup loadsave * \function igraph_write_graph_edgelist * \brief Writes the edge list of a graph to a file. * * * One edge is written per line, separated by a single space. * For directed graphs edges are written in from, to order. * \param graph The graph object to write. * \param outstream Pointer to a stream, it should be writable. * \return Error code: * \c IGRAPH_EFILE if there is an error writing the * file. * * Time complexity: O(|E|), the * number of edges in the graph. It is assumed that writing an * integer to the file requires O(1) * time. */ int igraph_write_graph_edgelist(const igraph_t *graph, FILE *outstream) { igraph_eit_t it; IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_FROM), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); while (!IGRAPH_EIT_END(it)) { igraph_integer_t from, to; int ret; igraph_edge(graph, IGRAPH_EIT_GET(it), &from, &to); ret=fprintf(outstream, "%li %li\n", (long int) from, (long int) to); if (ret < 0) { IGRAPH_ERROR("Write error", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup loadsave * \function igraph_write_graph_ncol * \brief Writes the graph to a file in .ncol format * * * .ncol is a format used by LGL, see \ref * igraph_read_graph_ncol() for details. * * * Note that having multiple or loop edges in an * .ncol file breaks the LGL software but * \a igraph does not check for this condition. * \param graph The graph to write. * \param outstream The stream object to write to, it should be * writable. * \param names The name of the vertex attribute, if symbolic names * are written to the file. If not, supply 0 here. * \param weights The name of the edge attribute, if they are also * written to the file. If you don't want weights, supply 0 * here. * \return Error code: * \c IGRAPH_EFILE if there is an error writing the * file. * * Time complexity: O(|E|), the * number of edges. All file operations are expected to have time * complexity O(1). * * \sa \ref igraph_read_graph_ncol(), \ref igraph_write_graph_lgl() */ int igraph_write_graph_ncol(const igraph_t *graph, FILE *outstream, const char *names, const char *weights) { igraph_eit_t it; igraph_attribute_type_t nametype, weighttype; IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_FROM), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); /* Check if we have the names attribute */ if (names && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_VERTEX, names)) { names=0; IGRAPH_WARNING("names attribute does not exists"); } if (names) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &nametype, IGRAPH_ATTRIBUTE_VERTEX, names)); } if (names && nametype != IGRAPH_ATTRIBUTE_NUMERIC && nametype != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_WARNING("ignoring names attribute, unknown attribute type"); names=0; } /* Check the weights as well */ if (weights && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_EDGE, weights)) { weights=0; IGRAPH_WARNING("weights attribute does not exists"); } if (weights) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &weighttype, IGRAPH_ATTRIBUTE_EDGE, weights)); } if (weights && weighttype != IGRAPH_ATTRIBUTE_NUMERIC) { IGRAPH_WARNING("ignoring weights attribute, unknown attribute type"); weights=0; } if (names==0 && weights ==0) { /* No names, no weights */ while (!IGRAPH_EIT_END(it)) { igraph_integer_t from, to; int ret; igraph_edge(graph, IGRAPH_EIT_GET(it), &from, &to); ret=fprintf(outstream, "%li %li\n", (long int) from, (long int) to); if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } } else if (weights==0) { /* No weights, but use names */ igraph_strvector_t nvec; IGRAPH_CHECK(igraph_strvector_init(&nvec, igraph_vcount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &nvec); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, names, igraph_vss_all(), &nvec)); while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret=0; char *str1, *str2; igraph_edge(graph, edge, &from, &to); igraph_strvector_get(&nvec, from, &str1); igraph_strvector_get(&nvec, to, &str2); ret=fprintf(outstream, "%s %s\n", str1, str2); if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_strvector_destroy(&nvec); IGRAPH_FINALLY_CLEAN(1); } else if (names==0) { /* No names but weights */ igraph_vector_t wvec; IGRAPH_VECTOR_INIT_FINALLY(&wvec, igraph_ecount(graph)); IGRAPH_CHECK(igraph_i_attribute_get_numeric_edge_attr(graph, weights, igraph_ess_all(IGRAPH_EDGEORDER_ID), &wvec)); while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret1, ret2, ret3; igraph_edge(graph, edge, &from, &to); ret1=fprintf(outstream, "%li %li ", (long int)from, (long int)to); ret2=igraph_real_fprintf_precise(outstream, VECTOR(wvec)[(long int)edge]); ret3=fputc('\n', outstream); if (ret1 < 0 || ret2 < 0 || ret3 == EOF) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_vector_destroy(&wvec); IGRAPH_FINALLY_CLEAN(1); } else { /* Both names and weights */ igraph_strvector_t nvec; igraph_vector_t wvec; IGRAPH_VECTOR_INIT_FINALLY(&wvec, igraph_ecount(graph)); IGRAPH_CHECK(igraph_strvector_init(&nvec, igraph_vcount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &nvec); IGRAPH_CHECK(igraph_i_attribute_get_numeric_edge_attr(graph, weights, igraph_ess_all(IGRAPH_EDGEORDER_ID), &wvec)); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, names, igraph_vss_all(), &nvec)); while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret=0, ret2=0; char *str1, *str2; igraph_edge(graph, edge, &from, &to); igraph_strvector_get(&nvec, from, &str1); igraph_strvector_get(&nvec, to, &str2); ret=fprintf(outstream, "%s %s ", str1, str2); if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } ret=igraph_real_fprintf_precise(outstream, VECTOR(wvec)[(long int)edge]); ret2=fputc('\n', outstream); if (ret < 0 || ret2 == EOF) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_strvector_destroy(&nvec); igraph_vector_destroy(&wvec); IGRAPH_FINALLY_CLEAN(2); } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup loadsave * \function igraph_write_graph_lgl * \brief Writes the graph to a file in .lgl format * * * .lgl is a format used by LGL, see \ref * igraph_read_graph_lgl() for details. * * * Note that having multiple or loop edges in an * .lgl file breaks the LGL software but \a igraph * does not check for this condition. * \param graph The graph to write. * \param outstream The stream object to write to, it should be * writable. * \param names The name of the vertex attribute, if symbolic names * are written to the file. If not supply 0 here. * \param weights The name of the edge attribute, if they are also * written to the file. If you don't want weights supply 0 * here. * \param isolates Logical, if TRUE isolated vertices are also written * to the file. If FALSE they will be omitted. * \return Error code: * \c IGRAPH_EFILE if there is an error * writing the file. * * Time complexity: O(|E|), the * number of edges if \p isolates is * FALSE, O(|V|+|E|) otherwise. All * file operations are expected to have time complexity * O(1). * * \sa \ref igraph_read_graph_lgl(), \ref igraph_write_graph_ncol() * * \example examples/simple/igraph_write_graph_lgl.c */ int igraph_write_graph_lgl(const igraph_t *graph, FILE *outstream, const char *names, const char *weights, igraph_bool_t isolates) { igraph_eit_t it; long int actvertex=-1; igraph_attribute_type_t nametype, weighttype; IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_FROM), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); /* Check if we have the names attribute */ if (names && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_VERTEX, names)) { names=0; IGRAPH_WARNING("names attribute does not exists"); } if (names) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &nametype, IGRAPH_ATTRIBUTE_VERTEX, names)); } if (names && nametype != IGRAPH_ATTRIBUTE_NUMERIC && nametype != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_WARNING("ignoring names attribute, unknown attribute type"); names=0; } /* Check the weights as well */ if (weights && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_EDGE, weights)) { weights=0; IGRAPH_WARNING("weights attribute does not exists"); } if (weights) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &weighttype, IGRAPH_ATTRIBUTE_EDGE, weights)); } if (weights && weighttype != IGRAPH_ATTRIBUTE_NUMERIC && weighttype != IGRAPH_ATTRIBUTE_STRING) { IGRAPH_WARNING("ignoring weights attribute, unknown attribute type"); weights=0; } if (names==0 && weights==0) { /* No names, no weights */ while (!IGRAPH_EIT_END(it)) { igraph_integer_t from, to; int ret; igraph_edge(graph, IGRAPH_EIT_GET(it), &from, &to); if (from==actvertex) { ret=fprintf(outstream, "%li\n", (long int)to); } else { actvertex=from; ret=fprintf(outstream, "# %li\n%li\n", (long int)from, (long int)to); } if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } } else if (weights==0) { /* No weights but use names */ igraph_strvector_t nvec; IGRAPH_CHECK(igraph_strvector_init(&nvec, igraph_vcount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &nvec); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, names, igraph_vss_all(), &nvec)); while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret=0; char *str1, *str2; igraph_edge(graph, edge, &from, &to); igraph_strvector_get(&nvec, to, &str2); if (from==actvertex) { ret=fprintf(outstream, "%s\n", str2); } else { actvertex=from; igraph_strvector_get(&nvec, from, &str1); ret=fprintf(outstream, "# %s\n%s\n", str1, str2); } if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } IGRAPH_FINALLY_CLEAN(1); } else if (names==0) { igraph_strvector_t wvec; IGRAPH_CHECK(igraph_strvector_init(&wvec, igraph_ecount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &wvec); IGRAPH_CHECK(igraph_i_attribute_get_string_edge_attr(graph, weights, igraph_ess_all(IGRAPH_EDGEORDER_ID), &wvec)); /* No names but weights */ while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret=0; char *str1; igraph_edge(graph, edge, &from, &to); igraph_strvector_get(&wvec, edge, &str1); if (from==actvertex) { ret=fprintf(outstream, "%li %s\n", (long)to, str1); } else { actvertex=from; ret=fprintf(outstream, "# %li\n%li %s\n", (long)from, (long)to, str1); } if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_strvector_destroy(&wvec); IGRAPH_FINALLY_CLEAN(1); } else { /* Both names and weights */ igraph_strvector_t nvec, wvec; IGRAPH_CHECK(igraph_strvector_init(&wvec, igraph_ecount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &wvec); IGRAPH_CHECK(igraph_strvector_init(&nvec, igraph_vcount(graph))); IGRAPH_FINALLY(igraph_strvector_destroy, &nvec); IGRAPH_CHECK(igraph_i_attribute_get_string_edge_attr(graph, weights, igraph_ess_all(IGRAPH_EDGEORDER_ID), &wvec)); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr(graph, names, igraph_vss_all(), &nvec)); while (!IGRAPH_EIT_END(it)) { igraph_integer_t edge=IGRAPH_EIT_GET(it); igraph_integer_t from, to; int ret=0; char *str1, *str2, *str3; igraph_edge(graph, edge, &from, &to); igraph_strvector_get(&nvec, to, &str2); igraph_strvector_get(&wvec, edge, &str3); if (from==actvertex) { ret=fprintf(outstream, "%s ", str2); } else { actvertex=from; igraph_strvector_get(&nvec, from, &str1); ret=fprintf(outstream, "# %s\n%s ", str1, str2); } if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } ret=fprintf(outstream, "%s\n", str3); if (ret<0) { IGRAPH_ERROR("Write failed", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_strvector_destroy(&nvec); igraph_strvector_destroy(&wvec); IGRAPH_FINALLY_CLEAN(2); } if (isolates) { long int nov=igraph_vcount(graph); long int i; int ret=0; igraph_vector_t deg; igraph_strvector_t nvec; char *str; IGRAPH_VECTOR_INIT_FINALLY(°, 1); IGRAPH_CHECK(igraph_strvector_init(&nvec, 1)); IGRAPH_FINALLY(igraph_strvector_destroy, &nvec); for (i=0; i * The Pajek vertex and edge parameters (like color) are determined by * the attributes of the vertices and edges, of course this requires * an attribute handler to be installed. The names of the * corresponding vertex and edge attributes are listed at \ref * igraph_read_graph_pajek(), eg. the `\c color' vertex attributes * determines the color (`\c c' in Pajek) parameter. * * * As of version 0.6.1 igraph writes bipartite graphs into Pajek files * correctly, i.e. they will be also bipartite when read into Pajek. * As Pajek is less flexible for bipartite graphs (the numeric ids of * the vertices must be sorted according to vertex type), igraph might * need to reorder the vertices when writing a bipartite Pajek file. * This effectively means that numeric vertex ids usually change when * a bipartite graph is written to a Pajek file, and then read back * into igraph. * \param graph The graph object to write. * \param outstream The file to write to. It should be opened and * writable. Make sure that you open the file in binary format if you use MS Windows, * otherwise end of line characters will be messed up. (igraph will be able * to read back these messed up files, but Pajek won't.) * \return Error code. * * Time complexity: O(|V|+|E|+|A|), |V| is the number of vertices, |E| * is the number of edges, |A| the number of attributes (vertex + * edge) in the graph if there are attribute handlers installed. * * \sa \ref igraph_read_graph_pajek() for reading Pajek graphs, \ref * igraph_write_graph_graphml() for writing a graph in GraphML format, * this suites igraph graphs better. * * \example examples/simple/igraph_write_graph_pajek.c */ int igraph_write_graph_pajek(const igraph_t *graph, FILE *outstream) { long int no_of_nodes=igraph_vcount(graph); long int i, j; igraph_attribute_type_t vtypes[V_LAST], etypes[E_LAST]; igraph_bool_t write_vertex_attrs=0; /* Same order as the #define's */ const char *vnames[] = { "id", "x", "y", "z", "shape", "xfact", "yfact", "", "", "", "", "", "", "", "", "", "labeldist", "labeldegree2", "framewidth", "fontsize", "rotation", "radius", "diamondratio", "labeldegree", "vertexsize", "font", "url", "color", "framecolor", "labelcolor" }; const char *vnumnames[] = { "xfact", "yfact", "labeldist", "labeldegree2", "framewidth", "fontsize", "rotation", "radius", "diamondratio", "labeldegree", "vertexsize" }; const char *vnumnames2[]= { "x_fact", "y_fact", "lr", "lphi", "bw", "fos", "phi", "r", "q", "la", "size" }; const char *vstrnames[] = { "font", "url", "color", "framecolor", "labelcolor" }; const char *vstrnames2[]= { "font", "url", "ic", "bc", "lc" }; const char *enames[] = { "weight", "", "", "", "arrowsize", "edgewidth", "hook1", "hook2", "angle1", "angle2", "velocity1", "velocity2", "arrowpos", "labelpos", "labelangle", "labelangle2", "labeldegree", "fontsize", "arrowtype", "linepattern", "label", "labelcolor", "color" }; const char *enumnames[] = { "arrowsize", "edgewidth", "hook1", "hook2", "angle1", "angle2", "velocity1", "velocity2", "arrowpos", "labelpos", "labelangle", "labelangle2", "labeldegree", "fontsize" }; const char *enumnames2[]= { "s", "w", "h1", "h2", "a1", "a2", "k1", "k2", "ap", "lp", "lr", "lphi", "la", "fos" }; const char *estrnames[] = { "arrowtype", "linepattern", "label", "labelcolor", "color" }; const char *estrnames2[]= { "a", "p", "l", "lc", "c" }; const char *newline="\x0d\x0a"; igraph_es_t es; igraph_eit_t eit; igraph_vector_t numv; igraph_strvector_t strv; igraph_vector_t ex_numa; igraph_vector_t ex_stra; igraph_vector_t vx_numa; igraph_vector_t vx_stra; char *s, *escaped; igraph_bool_t bipartite=0; igraph_vector_int_t bip_index, bip_index2; igraph_vector_bool_t bvec; long int notop=0, nobottom=0; IGRAPH_VECTOR_INIT_FINALLY(&numv, 1); IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1); IGRAPH_VECTOR_INIT_FINALLY(&ex_numa, 0); IGRAPH_VECTOR_INIT_FINALLY(&ex_stra, 0); IGRAPH_VECTOR_INIT_FINALLY(&vx_numa, 0); IGRAPH_VECTOR_INIT_FINALLY(&vx_stra, 0); /* Check if graph is bipartite */ if (igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_VERTEX, "type")) { igraph_attribute_type_t type_type; igraph_i_attribute_gettype(graph, &type_type, IGRAPH_ATTRIBUTE_VERTEX, "type"); if (type_type == IGRAPH_ATTRIBUTE_BOOLEAN) { int bptr=0, tptr=0; bipartite = 1; write_vertex_attrs = 1; /* Count top and bottom vertices, we go over them twice, because we want to keep their original order */ IGRAPH_CHECK(igraph_vector_int_init(&bip_index, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &bip_index); IGRAPH_CHECK(igraph_vector_int_init(&bip_index2, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_int_destroy, &bip_index2); IGRAPH_CHECK(igraph_vector_bool_init(&bvec, 1)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &bvec); for (i=0; i * This file format is discussed in the documentation of \ref * igraph_read_graph_dimacs(), see that for more information. * * \param graph The graph to write to the stream. * \param outstream The stream. * \param source Integer, the id of the source vertex for the maximum * flow. * \param target Integer, the id of the target vertex. * \param capacity Pointer to an initialized vector containing the * edge capacity values. * \return Error code. * * Time complexity: O(|E|), the number of edges in the graph. * * \sa igraph_read_graph_dimacs() */ int igraph_write_graph_dimacs(const igraph_t *graph, FILE *outstream, long int source, long int target, const igraph_vector_t *capacity) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_eit_t it; long int i=0; int ret, ret1, ret2, ret3; if (igraph_vector_size(capacity) != no_of_edges) { IGRAPH_ERROR("invalid capacity vector length", IGRAPH_EINVAL); } IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_ID), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); ret=fprintf(outstream, "c created by igraph\np max %li %li\nn %li s\nn %li t\n", no_of_nodes, no_of_edges, source+1, target+1); if (ret < 0) { IGRAPH_ERROR("Write error", IGRAPH_EFILE); } while (!IGRAPH_EIT_END(it)) { igraph_integer_t from, to; igraph_real_t cap; igraph_edge(graph, IGRAPH_EIT_GET(it), &from, &to); cap=VECTOR(*capacity)[i++]; ret1=fprintf(outstream, "a %li %li ", (long int) from+1, (long int) to+1); ret2=igraph_real_fprintf_precise(outstream, cap); ret3=fputc('\n', outstream); if (ret1 < 0 || ret2 < 0 || ret3==EOF) { IGRAPH_ERROR("Write error", IGRAPH_EFILE); } IGRAPH_EIT_NEXT(it); } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_gml_convert_to_key(const char *orig, char **key) { int no=1; char strno[50]; size_t i, len = strlen(orig), newlen = 0, plen = 0; /* do we need a prefix? */ if (len==0 || !isalpha(orig[0])) { no++; snprintf(strno, sizeof(strno)-1, "igraph"); plen=newlen=strlen(strno); } for (i=0; i The graph, vertex and edges attributes are written to the * file as well, if they are numeric or string. * * As igraph is more forgiving about attribute names, it might * be necessary to simplify the them before writing to the GML file. * This way we'll have a syntactically correct GML file. The following * simple procedure is performed on each attribute name: first the alphanumeric * characters are extracted, the others are ignored. Then if the first character * is not a letter then the attribute name is prefixed with igraph. * Note that this might result identical names for two attributes, igraph * does not check this. * * The id vertex attribute is treated specially. * If the id argument is not 0 then it should be a numeric * vector with the vertex ids and the id vertex attribute is * ignored (if there is one). If id is 0 and there is a * numeric id vertex attribute that is used instead. If ids * are not specified in either way then the regular igraph vertex ids are used. * * Note that whichever way vertex ids are specified, their * uniqueness is not checked. * * If the graph has edge attributes named source * or target they're silently ignored. GML uses these attributes * to specify the edges, so we cannot write them to the file. Rename them * before calling this function if you want to preserve them. * \param graph The graph to write to the stream. * \param outstream The stream to write the file to. * \param id Either NULL or a numeric vector with the vertex ids. * See details above. * \param creator An optional string to write to the stream in the creator line. * If this is 0 then the current date and time is added. * \return Error code. * * Time complexity: should be proportional to the number of characters written * to the file. * * \sa \ref igraph_read_graph_gml() for reading GML files, * \ref igraph_read_graph_graphml() for a more modern format. * * \example examples/simple/gml.c */ int igraph_write_graph_gml(const igraph_t *graph, FILE *outstream, const igraph_vector_t *id, const char *creator) { int ret; igraph_strvector_t gnames, vnames, enames; igraph_vector_t gtypes, vtypes, etypes; igraph_vector_t numv; igraph_strvector_t strv; igraph_vector_bool_t boolv; long int i; long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_vector_t v_myid; const igraph_vector_t *myid=id; time_t curtime=time(0); char *timestr=ctime(&curtime); timestr[strlen(timestr)-1]='\0'; /* nicely remove \n */ CHECK(fprintf(outstream, "Creator \"igraph version %s %s\"\nVersion 1\ngraph\n[\n", PACKAGE_VERSION, creator ? creator : timestr)); IGRAPH_STRVECTOR_INIT_FINALLY(&gnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&vnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&enames, 0); IGRAPH_VECTOR_INIT_FINALLY(>ypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&vtypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&etypes, 0); IGRAPH_CHECK(igraph_i_attribute_get_info(graph, &gnames, >ypes, &vnames, &vtypes, &enames, &etypes)); IGRAPH_VECTOR_INIT_FINALLY(&numv, 1); IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1); IGRAPH_VECTOR_BOOL_INIT_FINALLY(&boolv, 1); /* Check whether there is an 'id' node attribute if the supplied is 0 */ if (!id) { igraph_bool_t found=0; for (i=0; iThis is only a preliminary implementation, only the vertices * and the edges are written but not the attributes or any visualization * information. * * \param graph The graph to write to the stream. * \param outstream The stream to write the file to. * * Time complexity: should be proportional to the number of characters written * to the file. * * \sa \ref igraph_write_graph_graphml() for a more modern format. * * \example examples/simple/dot.c */ int igraph_write_graph_dot(const igraph_t *graph, FILE* outstream) { int ret; long int i, j; long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); char edgeop[3]; igraph_strvector_t gnames, vnames, enames; igraph_vector_t gtypes, vtypes, etypes; igraph_vector_t numv; igraph_strvector_t strv; igraph_vector_bool_t boolv; IGRAPH_STRVECTOR_INIT_FINALLY(&gnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&vnames, 0); IGRAPH_STRVECTOR_INIT_FINALLY(&enames, 0); IGRAPH_VECTOR_INIT_FINALLY(>ypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&vtypes, 0); IGRAPH_VECTOR_INIT_FINALLY(&etypes, 0); IGRAPH_CHECK(igraph_i_attribute_get_info(graph, &gnames, >ypes, &vnames, &vtypes, &enames, &etypes)); IGRAPH_VECTOR_INIT_FINALLY(&numv, 1); IGRAPH_STRVECTOR_INIT_FINALLY(&strv, 1); IGRAPH_VECTOR_BOOL_INIT_FINALLY(&boolv, 1); CHECK(fprintf(outstream, "/* Created by igraph %s */\n", PACKAGE_VERSION)); if (igraph_is_directed(graph)) { CHECK(fprintf(outstream, "digraph {\n")); strcpy(edgeop, "->"); } else { CHECK(fprintf(outstream, "graph {\n")); strcpy(edgeop, "--"); } /* Write the graph attributes */ if (igraph_vector_size(>ypes)>0) { CHECK(fprintf(outstream, " graph [\n")); for (i=0; i 0) { for (i=0; i 0) { for (i=0; i Note the specification does not mention whether the * format is case sensitive or not. For igraph DL files are case * sensitive, i.e. \c Larry and \c larry are not the same. * \param graph Pointer to an uninitialized graph object. * \param instream The stream to read the DL file from. * \param directed Logical scalar, whether to create a directed file. * \return Error code. * * Time complexity: linear in terms of the number of edges and * vertices, except for the matrix format, which is quadratic in the * number of vertices. * * \example examples/simple/igraph_read_graph_dl.c */ int igraph_read_graph_dl(igraph_t *graph, FILE *instream, igraph_bool_t directed) { int i; long int n, n2; const igraph_strvector_t *namevec=0; igraph_vector_ptr_t name, weight; igraph_vector_ptr_t *pname=0, *pweight=0; igraph_attribute_record_t namerec, weightrec; const char *namestr="name", *weightstr="weight"; igraph_i_dl_parsedata_t context; context.eof=0; context.mode=0; context.n=-1; context.from=0; context.to=0; IGRAPH_VECTOR_INIT_FINALLY(&context.edges, 0); IGRAPH_VECTOR_INIT_FINALLY(&context.weights, 0); IGRAPH_CHECK(igraph_strvector_init(&context.labels, 0)); IGRAPH_FINALLY(igraph_strvector_destroy, &context.labels); IGRAPH_TRIE_INIT_FINALLY(&context.trie, /*names=*/ 1); igraph_dl_yylex_init_extra(&context, &context.scanner); IGRAPH_FINALLY(igraph_dl_yylex_destroy, context.scanner); igraph_dl_yyset_in(instream, context.scanner); i=igraph_dl_yyparse(&context); if (i != 0) { if (context.errmsg) { IGRAPH_ERROR(context.errmsg, IGRAPH_PARSEERROR); } else { IGRAPH_ERROR("Cannot read DL file", IGRAPH_PARSEERROR); } } /* Extend the weight vector, if needed */ n=igraph_vector_size(&context.weights); n2=igraph_vector_size(&context.edges) / 2; if (n != 0) { igraph_vector_resize(&context.weights, n2); for (; n 0) { n = (long int) igraph_vector_max(&context.edges); } else { n = 0; } if (n >= context.n) { IGRAPH_WARNING("More vertices than specified in `DL' file"); context.n=n; } /* OK, everything is ready, create the graph */ IGRAPH_CHECK(igraph_empty(graph, 0, directed)); IGRAPH_FINALLY(igraph_destroy, graph); /* Labels */ if (igraph_strvector_size(&context.labels) != 0) { namevec=(const igraph_strvector_t*) &context.labels; } else if (igraph_trie_size(&context.trie) != 0) { igraph_trie_getkeys(&context.trie, &namevec); } if (namevec) { IGRAPH_CHECK(igraph_vector_ptr_init(&name, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &name); pname=&name; namerec.name=namestr; namerec.type=IGRAPH_ATTRIBUTE_STRING; namerec.value=namevec; VECTOR(name)[0]=&namerec; } /* Weights */ if (igraph_vector_size(&context.weights) != 0) { IGRAPH_CHECK(igraph_vector_ptr_init(&weight, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &weight); pweight=&weight; weightrec.name=weightstr; weightrec.type=IGRAPH_ATTRIBUTE_NUMERIC; weightrec.value=&context.weights; VECTOR(weight)[0]=&weightrec; } IGRAPH_CHECK(igraph_add_vertices(graph, (igraph_integer_t) context.n, pname)); IGRAPH_CHECK(igraph_add_edges(graph, &context.edges, pweight)); if (pweight) { igraph_vector_ptr_destroy(pweight); IGRAPH_FINALLY_CLEAN(1); } if (pname) { igraph_vector_ptr_destroy(pname); IGRAPH_FINALLY_CLEAN(1); } /* don't destroy the graph itself but pop it from the finally stack */ IGRAPH_FINALLY_CLEAN(1); igraph_trie_destroy(&context.trie); igraph_strvector_destroy(&context.labels); igraph_vector_destroy(&context.edges); igraph_vector_destroy(&context.weights); igraph_dl_yylex_destroy(context.scanner); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_write_graph_leda * \brief Write a graph in LEDA native graph format. * * This function writes a graph to an output stream in LEDA format. * See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html * * * The support for the LEDA format is very basic at the moment; igraph * writes only the LEDA graph section which supports one selected vertex * and edge attribute and no layout information or visual attributes. * * \param graph The graph to write to the stream. * \param outstream The stream. * \param vertex_attr_name The name of the vertex attribute whose values * are to be stored in the output or \c NULL if no * vertex attribute has to be stored. * \param edge_attr_name The name of the edge attribute whose values * are to be stored in the output or \c NULL if no * edge attribute has to be stored. * \return Error code. * * Time complexity: O(|V|+|E|), the number of vertices and edges in the * graph. * * \example examples/simple/igraph_write_graph_leda.c */ int igraph_write_graph_leda(const igraph_t *graph, FILE *outstream, const char* vertex_attr_name, const char* edge_attr_name) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_eit_t it; long int i=0; int ret; igraph_attribute_type_t vertex_attr_type = IGRAPH_ATTRIBUTE_DEFAULT; igraph_attribute_type_t edge_attr_type = IGRAPH_ATTRIBUTE_DEFAULT; igraph_integer_t from, to, rev; IGRAPH_CHECK(igraph_eit_create(graph, igraph_ess_all(IGRAPH_EDGEORDER_FROM), &it)); IGRAPH_FINALLY(igraph_eit_destroy, &it); /* Check if we have the vertex attribute */ if (vertex_attr_name && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_VERTEX, vertex_attr_name)) { vertex_attr_name=0; IGRAPH_WARNING("specified vertex attribute does not exist"); } if (vertex_attr_name) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &vertex_attr_type, IGRAPH_ATTRIBUTE_VERTEX, vertex_attr_name)); if (vertex_attr_type != IGRAPH_ATTRIBUTE_NUMERIC && vertex_attr_type != IGRAPH_ATTRIBUTE_STRING) { vertex_attr_name=0; vertex_attr_type = IGRAPH_ATTRIBUTE_DEFAULT; IGRAPH_WARNING("specified vertex attribute must be numeric or string"); } } /* Check if we have the edge attribute */ if (edge_attr_name && !igraph_i_attribute_has_attr(graph, IGRAPH_ATTRIBUTE_EDGE, edge_attr_name)) { edge_attr_name=0; IGRAPH_WARNING("specified edge attribute does not exist"); } if (edge_attr_name) { IGRAPH_CHECK(igraph_i_attribute_gettype(graph, &edge_attr_type, IGRAPH_ATTRIBUTE_EDGE, edge_attr_name)); if (edge_attr_type != IGRAPH_ATTRIBUTE_NUMERIC && edge_attr_type != IGRAPH_ATTRIBUTE_STRING) { edge_attr_name=0; edge_attr_type = IGRAPH_ATTRIBUTE_DEFAULT; IGRAPH_WARNING("specified edge attribute must be numeric or string"); } } /* Start writing header */ CHECK(fprintf(outstream, "LEDA.GRAPH\n")); switch (vertex_attr_type) { case IGRAPH_ATTRIBUTE_NUMERIC: CHECK(fprintf(outstream, "float\n")); break; case IGRAPH_ATTRIBUTE_STRING: CHECK(fprintf(outstream, "string\n")); break; default: CHECK(fprintf(outstream, "void\n")); } switch (edge_attr_type) { case IGRAPH_ATTRIBUTE_NUMERIC: CHECK(fprintf(outstream, "float\n")); break; case IGRAPH_ATTRIBUTE_STRING: CHECK(fprintf(outstream, "string\n")); break; default: CHECK(fprintf(outstream, "void\n")); } CHECK(fprintf(outstream, "%d\n", (igraph_is_directed(graph) ? -1 : -2))); /* Start writing vertices */ CHECK(fprintf(outstream, "# Vertices\n")); CHECK(fprintf(outstream, "%ld\n", no_of_nodes)); if (vertex_attr_type == IGRAPH_ATTRIBUTE_NUMERIC) { /* Vertices with numeric attributes */ igraph_vector_t values; IGRAPH_VECTOR_INIT_FINALLY(&values, no_of_nodes); IGRAPH_CHECK(igraph_i_attribute_get_numeric_vertex_attr( graph, vertex_attr_name, igraph_vss_all(), &values)); for (i = 0; i < no_of_nodes; i++) { CHECK(fprintf(outstream, "|{")); CHECK(igraph_real_fprintf_precise(outstream, VECTOR(values)[i])); CHECK(fprintf(outstream, "}|\n")); } igraph_vector_destroy(&values); IGRAPH_FINALLY_CLEAN(1); } else if (vertex_attr_type == IGRAPH_ATTRIBUTE_STRING) { /* Vertices with string attributes */ igraph_strvector_t values; IGRAPH_CHECK(igraph_strvector_init(&values, no_of_nodes)); IGRAPH_FINALLY(igraph_strvector_destroy, &values); IGRAPH_CHECK(igraph_i_attribute_get_string_vertex_attr( graph, vertex_attr_name, igraph_vss_all(), &values)); for (i = 0; i < no_of_nodes; i++) { const char* str = STR(values, i); if (strchr(str, '\n') != 0) { IGRAPH_ERROR("edge attribute values cannot contain newline characters", IGRAPH_EINVAL); } CHECK(fprintf(outstream, "|{%s}|\n", str)); } igraph_strvector_destroy(&values); IGRAPH_FINALLY_CLEAN(1); } else { /* Vertices with no attributes */ for (i = 0; i < no_of_nodes; i++) CHECK(fprintf(outstream, "|{}|\n")); } CHECK(fprintf(outstream, "# Edges\n")); CHECK(fprintf(outstream, "%ld\n", no_of_edges)); if (edge_attr_type == IGRAPH_ATTRIBUTE_NUMERIC) { /* Edges with numeric attributes */ igraph_vector_t values; IGRAPH_VECTOR_INIT_FINALLY(&values, no_of_nodes); IGRAPH_CHECK(igraph_i_attribute_get_numeric_edge_attr( graph, edge_attr_name, igraph_ess_all(IGRAPH_EDGEORDER_ID), &values)); while (!IGRAPH_EIT_END(it)) { long int eid = IGRAPH_EIT_GET(it); igraph_edge(graph, (igraph_integer_t) eid, &from, &to); igraph_get_eid(graph, &rev, to, from, 1, 0); if (rev == IGRAPH_EIT_GET(it)) rev = -1; CHECK(fprintf(outstream, "%ld %ld %ld |{", (long int) from+1, (long int) to+1, (long int) rev+1)); CHECK(igraph_real_fprintf_precise(outstream, VECTOR(values)[eid])); CHECK(fprintf(outstream, "}|\n")); IGRAPH_EIT_NEXT(it); } igraph_vector_destroy(&values); IGRAPH_FINALLY_CLEAN(1); } else if (edge_attr_type == IGRAPH_ATTRIBUTE_STRING) { /* Edges with string attributes */ igraph_strvector_t values; IGRAPH_CHECK(igraph_strvector_init(&values, no_of_nodes)); IGRAPH_FINALLY(igraph_strvector_destroy, &values); IGRAPH_CHECK(igraph_i_attribute_get_string_edge_attr( graph, edge_attr_name, igraph_ess_all(IGRAPH_EDGEORDER_ID), &values)); while (!IGRAPH_EIT_END(it)) { long int eid = IGRAPH_EIT_GET(it); const char* str = STR(values, eid); igraph_edge(graph, (igraph_integer_t) eid, &from, &to); igraph_get_eid(graph, &rev, to, from, 1, 0); if (rev == IGRAPH_EIT_GET(it)) rev = -1; if (strchr(str, '\n') != 0) { IGRAPH_ERROR("edge attribute values cannot contain newline characters", IGRAPH_EINVAL); } CHECK(fprintf(outstream, "%ld %ld %ld |{%s}|\n", (long int) from+1, (long int) to+1, (long int) rev+1, str)); IGRAPH_EIT_NEXT(it); } igraph_strvector_destroy(&values); IGRAPH_FINALLY_CLEAN(1); } else { /* Edges with no attributes */ while (!IGRAPH_EIT_END(it)) { igraph_edge(graph, IGRAPH_EIT_GET(it), &from, &to); igraph_get_eid(graph, &rev, to, from, 1, 0); if (rev == IGRAPH_EIT_GET(it)) rev = -1; CHECK(fprintf(outstream, "%ld %ld %ld |{}|\n", (long int) from+1, (long int) to+1, (long int) rev+1)); IGRAPH_EIT_NEXT(it); } } igraph_eit_destroy(&it); IGRAPH_FINALLY_CLEAN(1); return 0; } #undef CHECK igraph/src/dsortr.f0000644000175100001440000001240413431000472014010 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsortr c c\Description: c Sort the array X1 in the order specified by WHICH and optionally c applies the permutation to the array X2. c c\Usage: c call igraphdsortr c ( WHICH, APPLY, N, X1, X2 ) c c\Arguments c WHICH Character*2. (Input) c 'LM' -> X1 is sorted into increasing order of magnitude. c 'SM' -> X1 is sorted into decreasing order of magnitude. c 'LA' -> X1 is sorted into increasing order of algebraic. c 'SA' -> X1 is sorted into decreasing order of algebraic. c c APPLY Logical. (Input) c APPLY = .TRUE. -> apply the sorted order to X2. c APPLY = .FALSE. -> do not apply the sorted order to X2. c c N Integer. (INPUT) c Size of the arrays. c c X1 Double precision array of length N. (INPUT/OUTPUT) c The array to be sorted. c c X2 Double precision array of length N. (INPUT/OUTPUT) c Only referenced if APPLY = .TRUE. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/16/93: Version ' 2.1'. c Adapted from the sort routine in LANSO. c c\SCCS Information: @(#) c FILE: sortr.F SID: 2.3 DATE OF SID: 4/19/96 RELEASE: 2 c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsortr (which, apply, n, x1, x2) c c %------------------% c | Scalar Arguments | c %------------------% c character*2 which logical apply integer n c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & x1(0:n-1), x2(0:n-1) c c %---------------% c | Local Scalars | c %---------------% c integer i, igap, j Double precision & temp c c %-----------------------% c | Executable Statements | c %-----------------------% c igap = n / 2 c if (which .eq. 'SA') then c c X1 is sorted into decreasing order of algebraic. c 10 continue if (igap .eq. 0) go to 9000 do 30 i = igap, n-1 j = i-igap 20 continue c if (j.lt.0) go to 30 c if (x1(j).lt.x1(j+igap)) then temp = x1(j) x1(j) = x1(j+igap) x1(j+igap) = temp if (apply) then temp = x2(j) x2(j) = x2(j+igap) x2(j+igap) = temp end if else go to 30 endif j = j-igap go to 20 30 continue igap = igap / 2 go to 10 c else if (which .eq. 'SM') then c c X1 is sorted into decreasing order of magnitude. c 40 continue if (igap .eq. 0) go to 9000 do 60 i = igap, n-1 j = i-igap 50 continue c if (j.lt.0) go to 60 c if (abs(x1(j)).lt.abs(x1(j+igap))) then temp = x1(j) x1(j) = x1(j+igap) x1(j+igap) = temp if (apply) then temp = x2(j) x2(j) = x2(j+igap) x2(j+igap) = temp end if else go to 60 endif j = j-igap go to 50 60 continue igap = igap / 2 go to 40 c else if (which .eq. 'LA') then c c X1 is sorted into increasing order of algebraic. c 70 continue if (igap .eq. 0) go to 9000 do 90 i = igap, n-1 j = i-igap 80 continue c if (j.lt.0) go to 90 c if (x1(j).gt.x1(j+igap)) then temp = x1(j) x1(j) = x1(j+igap) x1(j+igap) = temp if (apply) then temp = x2(j) x2(j) = x2(j+igap) x2(j+igap) = temp end if else go to 90 endif j = j-igap go to 80 90 continue igap = igap / 2 go to 70 c else if (which .eq. 'LM') then c c X1 is sorted into increasing order of magnitude. c 100 continue if (igap .eq. 0) go to 9000 do 120 i = igap, n-1 j = i-igap 110 continue c if (j.lt.0) go to 120 c if (abs(x1(j)).gt.abs(x1(j+igap))) then temp = x1(j) x1(j) = x1(j+igap) x1(j+igap) = temp if (apply) then temp = x2(j) x2(j) = x2(j+igap) x2(j+igap) = temp end if else go to 120 endif j = j-igap go to 110 120 continue igap = igap / 2 go to 100 end if c 9000 continue return c c %---------------% c | End of igraphdsortr | c %---------------% c end igraph/src/matching.c0000644000175100001440000011173513431000472014271 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2012 Tamas Nepusz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include "config.h" #include "igraph_adjlist.h" #include "igraph_constructors.h" #include "igraph_conversion.h" #include "igraph_dqueue.h" #include "igraph_flow.h" #include "igraph_interface.h" #include "igraph_matching.h" #include "igraph_structural.h" /* #define MATCHING_DEBUG */ #ifdef _MSC_VER /* MSVC does not support variadic macros */ #include static void debug(const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef MATCHING_DEBUG vfprintf(stderr, fmt, args); #endif va_end(args); } #else # ifdef MATCHING_DEBUG # define debug(...) fprintf(stderr, __VA_ARGS__) # else # define debug(...) # endif #endif /** * \function igraph_is_matching * Checks whether the given matching is valid for the given graph. * * This function checks a matching vector and verifies whether its length * matches the number of vertices in the given graph, its values are between * -1 (inclusive) and the number of vertices (exclusive), and whether there * exists a corresponding edge in the graph for every matched vertex pair. * For bipartite graphs, it also verifies whether the matched vertices are * in different parts of the graph. * * \param graph The input graph. It can be directed but the edge directions * will be ignored. * \param types If the graph is bipartite and you are interested in bipartite * matchings only, pass the vertex types here. If the graph is * non-bipartite, simply pass \c NULL. * \param matching The matching itself. It must be a vector where element i * contains the ID of the vertex that vertex i is matched to, * or -1 if vertex i is unmatched. * \param result Pointer to a boolean variable, the result will be returned * here. * * \sa \ref igraph_is_maximal_matching() if you are also interested in whether * the matching is maximal (i.e. non-extendable). * * Time complexity: O(|V|+|E|) where |V| is the number of vertices and * |E| is the number of edges. * * \example examples/simple/igraph_maximum_bipartite_matching.c */ int igraph_is_matching(const igraph_t* graph, const igraph_vector_bool_t* types, const igraph_vector_long_t* matching, igraph_bool_t* result) { long int i, j, no_of_nodes = igraph_vcount(graph); igraph_bool_t conn; /* Checking match vector length */ if (igraph_vector_long_size(matching) != no_of_nodes) { *result = 0; return IGRAPH_SUCCESS; } for (i = 0; i < no_of_nodes; i++) { j = VECTOR(*matching)[i]; /* Checking range of each element in the match vector */ if (j < -1 || j >= no_of_nodes) { *result = 0; return IGRAPH_SUCCESS; } /* When i is unmatched, we're done */ if (j == -1) continue; /* Matches must be mutual */ if (VECTOR(*matching)[j] != i) { *result = 0; return IGRAPH_SUCCESS; } /* Matched vertices must be connected */ IGRAPH_CHECK(igraph_are_connected(graph, (igraph_integer_t) i, (igraph_integer_t) j, &conn)); if (!conn) { /* Try the other direction -- for directed graphs */ IGRAPH_CHECK(igraph_are_connected(graph, (igraph_integer_t) j, (igraph_integer_t) i, &conn)); if (!conn) { *result = 0; return IGRAPH_SUCCESS; } } } if (types != 0) { /* Matched vertices must be of different types */ for (i = 0; i < no_of_nodes; i++) { j = VECTOR(*matching)[i]; if (j == -1) continue; if (VECTOR(*types)[i] == VECTOR(*types)[j]) { *result = 0; return IGRAPH_SUCCESS; } } } *result = 1; return IGRAPH_SUCCESS; } /** * \function igraph_is_maximal_matching * Checks whether a matching in a graph is maximal. * * A matching is maximal if and only if there exists no unmatched vertex in a * graph such that one of its neighbors is also unmatched. * * \param graph The input graph. It can be directed but the edge directions * will be ignored. * \param types If the graph is bipartite and you are interested in bipartite * matchings only, pass the vertex types here. If the graph is * non-bipartite, simply pass \c NULL. * \param matching The matching itself. It must be a vector where element i * contains the ID of the vertex that vertex i is matched to, * or -1 if vertex i is unmatched. * \param result Pointer to a boolean variable, the result will be returned * here. * * \sa \ref igraph_is_matching() if you are only interested in whether a * matching vector is valid for a given graph. * * Time complexity: O(|V|+|E|) where |V| is the number of vertices and * |E| is the number of edges. * * \example examples/simple/igraph_maximum_bipartite_matching.c */ int igraph_is_maximal_matching(const igraph_t* graph, const igraph_vector_bool_t* types, const igraph_vector_long_t* matching, igraph_bool_t* result) { long int i, j, n, no_of_nodes = igraph_vcount(graph); igraph_vector_t neis; igraph_bool_t valid; IGRAPH_CHECK(igraph_is_matching(graph, types, matching, &valid)); if (!valid) { *result = 0; return IGRAPH_SUCCESS; } IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); valid = 1; for (i = 0; i < no_of_nodes; i++) { j = VECTOR(*matching)[i]; if (j != -1) continue; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) i, IGRAPH_ALL)); n = igraph_vector_size(&neis); for (j = 0; j < n; j++) { if (VECTOR(*matching)[(long int)VECTOR(neis)[j]] == -1) { if (types == 0 || VECTOR(*types)[i] != VECTOR(*types)[(long int)VECTOR(neis)[j]]) { valid = 0; break; } } } } igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(1); *result = valid; return IGRAPH_SUCCESS; } int igraph_i_maximum_bipartite_matching_unweighted(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_vector_long_t* matching); int igraph_i_maximum_bipartite_matching_weighted(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights, igraph_real_t eps); #define MATCHED(v) (VECTOR(match)[v] != -1) #define UNMATCHED(v) (!MATCHED(v)) /** * \function igraph_maximum_bipartite_matching * Calculates a maximum matching in a bipartite graph. * * A matching in a bipartite graph is a partial assignment of vertices * of the first kind to vertices of the second kind such that each vertex of * the first kind is matched to at most one vertex of the second kind and * vice versa, and matched vertices must be connected by an edge in the graph. * The size (or cardinality) of a matching is the number of edges. * A matching is a maximum matching if there exists no other matching with * larger cardinality. For weighted graphs, a maximum matching is a matching * whose edges have the largest possible total weight among all possible * matchings. * * * Maximum matchings in bipartite graphs are found by the push-relabel algorithm * with greedy initialization and a global relabeling after every n/2 steps where * n is the number of vertices in the graph. * * * References: Cherkassky BV, Goldberg AV, Martin P, Setubal JC and Stolfi J: * Augment or push: A computational study of bipartite matching and * unit-capacity flow algorithms. ACM Journal of Experimental Algorithmics 3, * 1998. * * * Kaya K, Langguth J, Manne F and Ucar B: Experiments on push-relabel-based * maximum cardinality matching algorithms for bipartite graphs. Technical * Report TR/PA/11/33 of the Centre Europeen de Recherche et de Formation * Avancee en Calcul Scientifique, 2011. * * \param graph The input graph. It can be directed but the edge directions * will be ignored. * \param types Boolean vector giving the vertex types of the graph. * \param matching_size The size of the matching (i.e. the number of matched * vertex pairs will be returned here). It may be \c NULL * if you don't need this. * \param matching_weight The weight of the matching if the edges are weighted, * or the size of the matching again if the edges are * unweighted. It may be \c NULL if you don't need this. * \param matching The matching itself. It must be a vector where element i * contains the ID of the vertex that vertex i is matched to, * or -1 if vertex i is unmatched. * \param weights A null pointer (=no edge weights), or a vector giving the * weights of the edges. Note that the algorithm is stable * only for integer weights. * \param eps A small real number used in equality tests in the weighted * bipartite matching algorithm. Two real numbers are considered * equal in the algorithm if their difference is smaller than * \c eps. This is required to avoid the accumulation of numerical * errors. It is advised to pass a value derived from the * \c DBL_EPSILON constant in \c float.h here. If you are * running the algorithm with no \c weights vector, this argument * is ignored. * \return Error code. * * Time complexity: O(sqrt(|V|) |E|) for unweighted graphs (according to the * technical report referenced above), O(|V||E|) for weighted graphs. * * \example examples/simple/igraph_maximum_bipartite_matching.c */ int igraph_maximum_bipartite_matching(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights, igraph_real_t eps) { /* Sanity checks */ if (igraph_vector_bool_size(types) < igraph_vcount(graph)) { IGRAPH_ERROR("types vector too short", IGRAPH_EINVAL); } if (weights && igraph_vector_size(weights) < igraph_ecount(graph)) { IGRAPH_ERROR("weights vector too short", IGRAPH_EINVAL); } if (weights == 0) { IGRAPH_CHECK(igraph_i_maximum_bipartite_matching_unweighted(graph, types, matching_size, matching)); if (matching_weight != 0) { *matching_weight = *matching_size; } return IGRAPH_SUCCESS; } else { return igraph_i_maximum_bipartite_matching_weighted(graph, types, matching_size, matching_weight, matching, weights, eps); } } int igraph_i_maximum_bipartite_matching_unweighted_relabel(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_vector_t* labels, igraph_vector_long_t* matching, igraph_bool_t smaller_set); /** * Finding maximum bipartite matchings on bipartite graphs using the * push-relabel algorithm. * * The implementation follows the pseudocode in Algorithm 1 of the * following paper: * * Kaya K, Langguth J, Manne F and Ucar B: Experiments on push-relabel-based * maximum cardinality matching algorithms for bipartite graphs. Technical * Report TR/PA/11/33 of CERFACS (Centre Européen de Recherche et de Formation * Avancée en Calcul Scientifique). * http://www.cerfacs.fr/algor/reports/2011/TR_PA_11_33.pdf */ int igraph_i_maximum_bipartite_matching_unweighted(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_vector_long_t* matching) { long int i, j, k, n, no_of_nodes = igraph_vcount(graph); long int num_matched; /* number of matched vertex pairs */ igraph_vector_long_t match; /* will store the matching */ igraph_vector_t labels; /* will store the labels */ igraph_vector_t neis; /* used to retrieve the neighbors of a node */ igraph_dqueue_long_t q; /* a FIFO for push ordering */ igraph_bool_t smaller_set; /* denotes which part of the bipartite graph is smaller */ long int label_changed = 0; /* Counter to decide when to run a global relabeling */ long int relabeling_freq = no_of_nodes / 2; /* We will use: * - FIFO push ordering * - global relabeling frequency: n/2 steps where n is the number of nodes * - simple greedy matching for initialization */ /* (1) Initialize data structures */ IGRAPH_CHECK(igraph_vector_long_init(&match, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &match); IGRAPH_VECTOR_INIT_FINALLY(&labels, no_of_nodes); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); IGRAPH_CHECK(igraph_dqueue_long_init(&q, 0)); IGRAPH_FINALLY(igraph_dqueue_long_destroy, &q); /* (2) Initially, every node is unmatched */ igraph_vector_long_fill(&match, -1); /* (3) Find an initial matching in a greedy manner. * At the same time, find which side of the graph is smaller. */ num_matched = 0; j = 0; for (i = 0; i < no_of_nodes; i++) { if (VECTOR(*types)[i]) j++; if (MATCHED(i)) continue; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) i, IGRAPH_ALL)); n = igraph_vector_size(&neis); for (j = 0; j < n; j++) { k = (long int) VECTOR(neis)[j]; if (UNMATCHED(k)) { /* We match vertex i to vertex VECTOR(neis)[j] */ VECTOR(match)[k] = i; VECTOR(match)[i] = k; num_matched++; break; } } } smaller_set = (j <= no_of_nodes/2); /* (4) Set the initial labeling -- lines 1 and 2 in the tech report */ IGRAPH_CHECK(igraph_i_maximum_bipartite_matching_unweighted_relabel( graph, types, &labels, &match, smaller_set)); /* (5) Fill the push queue with the unmatched nodes from the smaller set. */ for (i = 0; i < no_of_nodes; i++) { if (UNMATCHED(i) && VECTOR(*types)[i] == smaller_set) IGRAPH_CHECK(igraph_dqueue_long_push(&q, i)); } /* (6) Main loop from the referenced tech report -- lines 4--13 */ label_changed = 0; while (!igraph_dqueue_long_empty(&q)) { long int v = igraph_dqueue_long_pop(&q); /* Line 13 */ long int u = -1, label_u = 2 * no_of_nodes; long int w; if (label_changed >= relabeling_freq) { /* Run global relabeling */ IGRAPH_CHECK(igraph_i_maximum_bipartite_matching_unweighted_relabel( graph, types, &labels, &match, smaller_set)); label_changed = 0; } debug("Considering vertex %ld\n", v); /* Line 5: find row u among the neighbors of v s.t. label(u) is minimal */ IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) v, IGRAPH_ALL)); n = igraph_vector_size(&neis); for (i = 0; i < n; i++) { if (VECTOR(labels)[(long int)VECTOR(neis)[i]] < label_u) { u = (long int) VECTOR(neis)[i]; label_u = (long int) VECTOR(labels)[u]; label_changed++; } } debug(" Neighbor with smallest label: %ld (label=%ld)\n", u, label_u); if (label_u < no_of_nodes) { /* Line 6 */ VECTOR(labels)[v] = VECTOR(labels)[u] + 1; /* Line 7 */ if (MATCHED(u)) { /* Line 8 */ w = VECTOR(match)[u]; debug(" Vertex %ld is matched to %ld, performing a double push\n", u, w); if (w != v) { VECTOR(match)[u] = -1; VECTOR(match)[w] = -1; /* Line 9 */ IGRAPH_CHECK(igraph_dqueue_long_push(&q, w)); /* Line 10 */ debug(" Unmatching & activating vertex %ld\n", w); num_matched--; } } VECTOR(match)[u] = v; VECTOR(match)[v] = u; /* Line 11 */ num_matched++; VECTOR(labels)[u] += 2; /* Line 12 */ label_changed++; } } /* Fill the output parameters */ if (matching != 0) { IGRAPH_CHECK(igraph_vector_long_update(matching, &match)); } if (matching_size != 0) { *matching_size = (igraph_integer_t) num_matched; } /* Release everything */ igraph_dqueue_long_destroy(&q); igraph_vector_destroy(&neis); igraph_vector_destroy(&labels); igraph_vector_long_destroy(&match); IGRAPH_FINALLY_CLEAN(4); return IGRAPH_SUCCESS; } int igraph_i_maximum_bipartite_matching_unweighted_relabel(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_vector_t* labels, igraph_vector_long_t* match, igraph_bool_t smaller_set) { long int i, j, n, no_of_nodes = igraph_vcount(graph), matched_to; igraph_dqueue_long_t q; igraph_vector_t neis; debug("Running global relabeling.\n"); /* Set all the labels to no_of_nodes first */ igraph_vector_fill(labels, no_of_nodes); /* Allocate vector for neighbors */ IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); /* Create a FIFO for the BFS and initialize it with the unmatched rows * (i.e. members of the larger set) */ IGRAPH_CHECK(igraph_dqueue_long_init(&q, 0)); IGRAPH_FINALLY(igraph_dqueue_long_destroy, &q); for (i = 0; i < no_of_nodes; i++) { if (VECTOR(*types)[i] != smaller_set && VECTOR(*match)[i] == -1) { IGRAPH_CHECK(igraph_dqueue_long_push(&q, i)); VECTOR(*labels)[i] = 0; } } /* Run the BFS */ while (!igraph_dqueue_long_empty(&q)) { long int v = igraph_dqueue_long_pop(&q); long int w; IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) v, IGRAPH_ALL)); n = igraph_vector_size(&neis); for (j = 0; j < n; j++) { w = (long int) VECTOR(neis)[j]; if (VECTOR(*labels)[w] == no_of_nodes) { VECTOR(*labels)[w] = VECTOR(*labels)[v] + 1; matched_to = VECTOR(*match)[w]; if (matched_to != -1 && VECTOR(*labels)[matched_to] == no_of_nodes) { IGRAPH_CHECK(igraph_dqueue_long_push(&q, matched_to)); VECTOR(*labels)[matched_to] = VECTOR(*labels)[w] + 1; } } } } igraph_dqueue_long_destroy(&q); igraph_vector_destroy(&neis); IGRAPH_FINALLY_CLEAN(2); return IGRAPH_SUCCESS; } /** * Finding maximum bipartite matchings on bipartite graphs using the * Hungarian algorithm (a.k.a. Kuhn-Munkres algorithm). * * The algorithm uses a maximum cardinality matching on a subset of * tight edges as a starting point. This is achieved by * \c igraph_i_maximum_bipartite_matching_unweighted on the restricted * graph. * * The algorithm works reliably only if the weights are integers. The * \c eps parameter should specity a very small number; if the slack on * an edge falls below \c eps, it will be considered tight. If all your * weights are integers, you can safely set \c eps to zero. */ int igraph_i_maximum_bipartite_matching_weighted(const igraph_t* graph, const igraph_vector_bool_t* types, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights, igraph_real_t eps) { long int i, j, k, n, no_of_nodes, no_of_edges; igraph_integer_t u, v, w, msize; igraph_t newgraph; igraph_vector_long_t match; /* will store the matching */ igraph_vector_t slack; /* will store the slack on each edge */ igraph_vector_t parent; /* parent vertices during a BFS */ igraph_vector_t vec1, vec2; /* general temporary vectors */ igraph_vector_t labels; /* will store the labels */ igraph_dqueue_long_t q; /* a FIFO for BST */ igraph_bool_t smaller_set_type; /* denotes which part of the bipartite graph is smaller */ igraph_vector_t smaller_set; /* stores the vertex IDs of the smaller set */ igraph_vector_t larger_set; /* stores the vertex IDs of the larger set */ long int smaller_set_size; /* size of the smaller set */ long int larger_set_size; /* size of the larger set */ igraph_real_t dual; /* solution of the dual problem */ igraph_adjlist_t tight_phantom_edges; /* adjacency list to manage tight phantom edges */ igraph_integer_t alternating_path_endpoint; igraph_vector_int_t* neis; igraph_vector_int_t *neis2; igraph_inclist_t inclist; /* incidence list of the original graph */ /* The Hungarian algorithm is originally for complete bipartite graphs. * For non-complete bipartite graphs, a phantom edge of weight zero must be * added between every pair of non-connected vertices. We don't do this * explicitly of course. See the comments below about how phantom edges * are taken into account. */ no_of_nodes = igraph_vcount(graph); no_of_edges = igraph_ecount(graph); if (eps < 0) { IGRAPH_WARNING("negative epsilon given, clamping to zero"); eps = 0; } /* (1) Initialize data structures */ IGRAPH_CHECK(igraph_vector_long_init(&match, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &match); IGRAPH_CHECK(igraph_vector_init(&slack, no_of_edges)); IGRAPH_FINALLY(igraph_vector_destroy, &slack); IGRAPH_VECTOR_INIT_FINALLY(&vec1, 0); IGRAPH_VECTOR_INIT_FINALLY(&vec2, 0); IGRAPH_VECTOR_INIT_FINALLY(&labels, no_of_nodes); IGRAPH_CHECK(igraph_dqueue_long_init(&q, 0)); IGRAPH_FINALLY(igraph_dqueue_long_destroy, &q); IGRAPH_VECTOR_INIT_FINALLY(&parent, no_of_nodes); IGRAPH_CHECK(igraph_adjlist_init_empty(&tight_phantom_edges, (igraph_integer_t) no_of_nodes)); IGRAPH_FINALLY(igraph_adjlist_destroy, &tight_phantom_edges); IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); IGRAPH_VECTOR_INIT_FINALLY(&smaller_set, 0); IGRAPH_VECTOR_INIT_FINALLY(&larger_set, 0); /* (2) Find which set is the smaller one */ j = 0; for (i = 0; i < no_of_nodes; i++) { if (VECTOR(*types)[i] == 0) { j++; } } smaller_set_type = (j > no_of_nodes / 2); smaller_set_size = smaller_set_type ? (no_of_nodes - j) : j; larger_set_size = no_of_nodes - smaller_set_size; IGRAPH_CHECK(igraph_vector_reserve(&smaller_set, smaller_set_size)); IGRAPH_CHECK(igraph_vector_reserve(&larger_set, larger_set_size)); for (i = 0; i < no_of_nodes; i++) { if (VECTOR(*types)[i] == smaller_set_type) { IGRAPH_CHECK(igraph_vector_push_back(&smaller_set, i)); } else { IGRAPH_CHECK(igraph_vector_push_back(&larger_set, i)); } } /* (3) Calculate the initial labeling and the set of tight edges. Use the * smaller set only. Here we can assume that there are no phantom edges * among the tight ones. */ dual = 0; for (i = 0; i < no_of_nodes; i++) { igraph_real_t max_weight = 0; if (VECTOR(*types)[i] != smaller_set_type) { VECTOR(labels)[i] = 0; continue; } neis = igraph_inclist_get(&inclist, i); n = igraph_vector_int_size(neis); for (j = 0, k = 0; j < n; j++) { if (VECTOR(*weights)[(long int)VECTOR(*neis)[j]] > max_weight) { k = (long int) VECTOR(*neis)[j]; max_weight = VECTOR(*weights)[k]; } } VECTOR(labels)[i] = max_weight; dual += max_weight; } igraph_vector_clear(&vec1); IGRAPH_CHECK(igraph_get_edgelist(graph, &vec2, 0)); #define IS_TIGHT(i) (VECTOR(slack)[i] <= eps) for (i = 0, j = 0; i < no_of_edges; i++, j+=2) { u = (igraph_integer_t) VECTOR(vec2)[j]; v = (igraph_integer_t) VECTOR(vec2)[j+1]; VECTOR(slack)[i] = VECTOR(labels)[u] + VECTOR(labels)[v] - VECTOR(*weights)[i]; if (IS_TIGHT(i)) { IGRAPH_CHECK(igraph_vector_push_back(&vec1, u)); IGRAPH_CHECK(igraph_vector_push_back(&vec1, v)); } } igraph_vector_clear(&vec2); /* (4) Construct a temporary graph on which the initial maximum matching * will be calculated (only on the subset of tight edges) */ IGRAPH_CHECK(igraph_create(&newgraph, &vec1, (igraph_integer_t) no_of_nodes, 0)); IGRAPH_FINALLY(igraph_destroy, &newgraph); IGRAPH_CHECK(igraph_maximum_bipartite_matching(&newgraph, types, &msize, 0, &match, 0, 0)); igraph_destroy(&newgraph); IGRAPH_FINALLY_CLEAN(1); /* (5) Main loop until the matching becomes maximal */ while (msize < smaller_set_size) { igraph_real_t min_slack, min_slack_2; igraph_integer_t min_slack_u, min_slack_v; /* (7) Fill the push queue with the unmatched nodes from the smaller set. */ igraph_vector_clear(&vec1); igraph_vector_clear(&vec2); igraph_vector_fill(&parent, -1); for (j = 0; j < smaller_set_size; j++) { i = VECTOR(smaller_set)[j]; if (UNMATCHED(i)) { IGRAPH_CHECK(igraph_dqueue_long_push(&q, i)); VECTOR(parent)[i] = i; IGRAPH_CHECK(igraph_vector_push_back(&vec1, i)); } } #ifdef MATCHING_DEBUG debug("Matching:"); igraph_vector_long_print(&match); debug("Unmatched vertices are marked by non-negative numbers:\n"); igraph_vector_print(&parent); debug("Labeling:"); igraph_vector_print(&labels); debug("Slacks:"); igraph_vector_print(&slack); #endif /* (8) Run the BFS */ alternating_path_endpoint = -1; while (!igraph_dqueue_long_empty(&q)) { v = (int) igraph_dqueue_long_pop(&q); debug("Considering vertex %ld\n", (long int)v); /* v is always in the smaller set. Find the neighbors of v, which * are all in the larger set. Find the pairs of these nodes in * the smaller set and push them to the queue. Mark the traversed * nodes as seen. * * Here we have to be careful as there are two types of incident * edges on v: real edges and phantom ones. Real edges are * given by igraph_inclist_get. Phantom edges are not given so we * (ab)use an adjacency list data structure that lists the * vertices connected to v by phantom edges only. */ neis = igraph_inclist_get(&inclist, v); n = igraph_vector_int_size(neis); for (i = 0; i < n; i++) { j = (long int) VECTOR(*neis)[i]; /* We only care about tight edges */ if (!IS_TIGHT(j)) continue; /* Have we seen the other endpoint already? */ u = IGRAPH_OTHER(graph, j, v); if (VECTOR(parent)[u] >= 0) continue; debug(" Reached vertex %ld via edge %ld\n", (long)u, (long)j); VECTOR(parent)[u] = v; IGRAPH_CHECK(igraph_vector_push_back(&vec2, u)); w = (int) VECTOR(match)[u]; if (w == -1) { /* u is unmatched and it is in the larger set. Therefore, we * could improve the matching by following the parents back * from u to the root. */ alternating_path_endpoint = u; break; /* since we don't need any more endpoints that come from v */ } else { IGRAPH_CHECK(igraph_dqueue_long_push(&q, w)); VECTOR(parent)[w] = u; } IGRAPH_CHECK(igraph_vector_push_back(&vec1, w)); } /* Now do the same with the phantom edges */ neis2 = igraph_adjlist_get(&tight_phantom_edges, v); n = igraph_vector_int_size(neis2); for (i = 0; i < n; i++) { u = (igraph_integer_t) VECTOR(*neis2)[i]; /* Have we seen u already? */ if (VECTOR(parent)[u] >= 0) continue; /* Check if the edge is really tight; it might have happened that the * edge became non-tight in the meanwhile. We do not remove these from * tight_phantom_edges at the moment, so we check them once again here. */ if (fabs(VECTOR(labels)[(long int)v] + VECTOR(labels)[(long int)u]) > eps) continue; debug(" Reached vertex %ld via tight phantom edge\n", (long)u); VECTOR(parent)[u] = v; IGRAPH_CHECK(igraph_vector_push_back(&vec2, u)); w = (int) VECTOR(match)[u]; if (w == -1) { /* u is unmatched and it is in the larger set. Therefore, we * could improve the matching by following the parents back * from u to the root. */ alternating_path_endpoint = u; break; /* since we don't need any more endpoints that come from v */ } else { IGRAPH_CHECK(igraph_dqueue_long_push(&q, w)); VECTOR(parent)[w] = u; } IGRAPH_CHECK(igraph_vector_push_back(&vec1, w)); } } /* Okay; did we have an alternating path? */ if (alternating_path_endpoint != -1) { #ifdef MATCHING_DEBUG debug("BFS parent tree:"); igraph_vector_print(&parent); #endif /* Increase the size of the matching with the alternating path. */ v = alternating_path_endpoint; u = (igraph_integer_t) VECTOR(parent)[v]; debug("Extending matching with alternating path ending in %ld.\n", (long int)v); while (u != v) { w = (int) VECTOR(match)[v]; if (w != -1) VECTOR(match)[w] = -1; VECTOR(match)[v] = u; VECTOR(match)[v] = u; w = (int) VECTOR(match)[u]; if (w != -1) VECTOR(match)[w] = -1; VECTOR(match)[u] = v; v = (igraph_integer_t) VECTOR(parent)[u]; u = (igraph_integer_t) VECTOR(parent)[v]; } msize++; #ifdef MATCHING_DEBUG debug("New matching after update:"); igraph_vector_long_print(&match); debug("Matching size is now: %ld\n", (long)msize); #endif continue; } #ifdef MATCHING_DEBUG debug("Vertices reachable from unmatched ones via tight edges:\n"); igraph_vector_print(&vec1); igraph_vector_print(&vec2); #endif /* At this point, vec1 contains the nodes in the smaller set (A) * reachable from unmatched nodes in A via tight edges only, while vec2 * contains the nodes in the larger set (B) reachable from unmatched * nodes in A via tight edges only. Also, parent[i] >= 0 if node i * is reachable */ /* Check the edges between reachable nodes in A and unreachable * nodes in B, and find the minimum slack on them. * * Since the weights are positive, we do no harm if we first * assume that there are no "real" edges between the two sets * mentioned above and determine an upper bound for min_slack * based on this. */ min_slack = IGRAPH_INFINITY; min_slack_u = min_slack_v = 0; n = igraph_vector_size(&vec1); for (j = 0; j < larger_set_size; j++) { i = VECTOR(larger_set)[j]; if (VECTOR(labels)[i] < min_slack) { min_slack = VECTOR(labels)[i]; min_slack_v = (igraph_integer_t) i; } } min_slack_2 = IGRAPH_INFINITY; for (i = 0; i < n; i++) { u = (igraph_integer_t) VECTOR(vec1)[i]; /* u is surely from the smaller set, but we are interested in it * only if it is reachable from an unmatched vertex */ if (VECTOR(parent)[u] < 0) continue; if (VECTOR(labels)[u] < min_slack_2) { min_slack_2 = VECTOR(labels)[u]; min_slack_u = u; } } min_slack += min_slack_2; debug("Starting approximation for min_slack = %.4f (based on vertex pair %ld--%ld)\n", min_slack, (long int)min_slack_u, (long int)min_slack_v); n = igraph_vector_size(&vec1); for (i = 0; i < n; i++) { u = (igraph_integer_t) VECTOR(vec1)[i]; /* u is a reachable node in A; get its incident edges. * * There are two types of incident edges: 1) real edges, * 2) phantom edges. Phantom edges were treated earlier * when we determined the initial value for min_slack. */ debug("Trying to expand along vertex %ld\n", (long int)u); neis = igraph_inclist_get(&inclist, u); k = igraph_vector_int_size(neis); for (j = 0; j < k; j++) { /* v is the vertex sitting at the other end of an edge incident * on u; check whether it was reached */ v = IGRAPH_OTHER(graph, VECTOR(*neis)[j], u); debug(" Edge %ld -- %ld (ID=%ld)\n", (long int)u, (long int)v, (long int)VECTOR(*neis)[j]); if (VECTOR(parent)[v] >= 0) { /* v was reached, so we are not interested in it */ debug(" %ld was reached, so we are not interested in it\n", (long int)v); continue; } /* v is the ID of the edge from now on */ v = (igraph_integer_t) VECTOR(*neis)[j]; if (VECTOR(slack)[v] < min_slack) { min_slack = VECTOR(slack)[v]; min_slack_u = u; min_slack_v = IGRAPH_OTHER(graph, v, u); } debug(" Slack of this edge: %.4f, min slack is now: %.4f\n", VECTOR(slack)[v], min_slack); } } debug("Minimum slack: %.4f on edge %d--%d\n", min_slack, (int)min_slack_u, (int)min_slack_v); if (min_slack > 0) { /* Decrease the label of reachable nodes in A by min_slack. * Also update the dual solution */ n = igraph_vector_size(&vec1); for (i = 0; i < n; i++) { u = (igraph_integer_t) VECTOR(vec1)[i]; VECTOR(labels)[u] -= min_slack; neis = igraph_inclist_get(&inclist, u); k = igraph_vector_int_size(neis); for (j = 0; j < k; j++) { debug(" Decreasing slack of edge %ld (%ld--%ld) by %.4f\n", (long)VECTOR(*neis)[j], (long)u, (long)IGRAPH_OTHER(graph, VECTOR(*neis)[j], u), min_slack); VECTOR(slack)[(long int)VECTOR(*neis)[j]] -= min_slack; } dual -= min_slack; } /* Increase the label of reachable nodes in B by min_slack. * Also update the dual solution */ n = igraph_vector_size(&vec2); for (i = 0; i < n; i++) { u = (igraph_integer_t) VECTOR(vec2)[i]; VECTOR(labels)[u] += min_slack; neis = igraph_inclist_get(&inclist, u); k = igraph_vector_int_size(neis); for (j = 0; j < k; j++) { debug(" Increasing slack of edge %ld (%ld--%ld) by %.4f\n", (long)VECTOR(*neis)[j], (long)u, (long)IGRAPH_OTHER(graph, (long)VECTOR(*neis)[j], u), min_slack); VECTOR(slack)[(long int)VECTOR(*neis)[j]] += min_slack; } dual += min_slack; } } /* Update the set of tight phantom edges. * Note that we must do it even if min_slack is zero; the reason is that * it can happen that min_slack is zero in the first step if there are * isolated nodes in the input graph. * * TODO: this is O(n^2) here. Can we do it faster? */ for (i = 0; i < smaller_set_size; i++) { u = VECTOR(smaller_set)[i]; for (j = 0; j < larger_set_size; j++) { v = VECTOR(larger_set)[j]; if (VECTOR(labels)[(long int)u] + VECTOR(labels)[(long int)v] <= eps) { /* Tight phantom edge found. Note that we don't have to check whether * u and v are connected; if they were, then the slack of this edge * would be negative. */ neis2 = igraph_adjlist_get(&tight_phantom_edges, u); if (!igraph_vector_int_binsearch(neis2, v, &k)) { debug("New tight phantom edge: %ld -- %ld\n", (long)u, (long)v); IGRAPH_CHECK(igraph_vector_int_insert(neis2, k, v)); } } } } #ifdef MATCHING_DEBUG debug("New labels:"); igraph_vector_print(&labels); debug("Slacks after updating with min_slack:"); igraph_vector_print(&slack); #endif } /* Cleanup: remove phantom edges from the matching */ for (i = 0; i < smaller_set_size; i++) { u = VECTOR(smaller_set)[i]; v = VECTOR(match)[u]; if (v != -1) { neis2 = igraph_adjlist_get(&tight_phantom_edges, u); if (igraph_vector_int_binsearch(neis2, v, 0)) { VECTOR(match)[u] = VECTOR(match)[v] = -1; msize--; } } } /* Fill the output parameters */ if (matching != 0) { IGRAPH_CHECK(igraph_vector_long_update(matching, &match)); } if (matching_size != 0) { *matching_size = msize; } if (matching_weight != 0) { *matching_weight = 0; for (i = 0; i < no_of_edges; i++) { if (IS_TIGHT(i)) { IGRAPH_CHECK(igraph_edge(graph, (igraph_integer_t) i, &u, &v)); if (VECTOR(match)[u] == v) *matching_weight += VECTOR(*weights)[i]; } } } /* Release everything */ #undef IS_TIGHT igraph_vector_destroy(&larger_set); igraph_vector_destroy(&smaller_set); igraph_inclist_destroy(&inclist); igraph_adjlist_destroy(&tight_phantom_edges); igraph_vector_destroy(&parent); igraph_dqueue_long_destroy(&q); igraph_vector_destroy(&labels); igraph_vector_destroy(&vec1); igraph_vector_destroy(&vec2); igraph_vector_destroy(&slack); igraph_vector_long_destroy(&match); IGRAPH_FINALLY_CLEAN(11); return IGRAPH_SUCCESS; } int igraph_maximum_matching(const igraph_t* graph, igraph_integer_t* matching_size, igraph_real_t* matching_weight, igraph_vector_long_t* matching, const igraph_vector_t* weights) { IGRAPH_UNUSED(graph); IGRAPH_UNUSED(matching_size); IGRAPH_UNUSED(matching_weight); IGRAPH_UNUSED(matching); IGRAPH_UNUSED(weights); IGRAPH_ERROR("maximum matching on general graphs not implemented yet", IGRAPH_UNIMPLEMENTED); } #ifdef MATCHING_DEBUG #undef MATCHING_DEBUG #endif igraph/src/spanning_trees.c0000644000175100001440000003056413431000472015516 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sts=2 sw=2 et: */ /* IGraph library. Copyright (C) 2011 Gabor Csardi Rue de l'Industrie 5, Lausanne 1005, Switzerland This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_structural.h" #include "igraph_dqueue.h" #include "igraph_interface.h" #include "igraph_interrupt_internal.h" #include "igraph_memory.h" #include "igraph_progress.h" #include "igraph_types_internal.h" int igraph_i_minimum_spanning_tree_unweighted(const igraph_t *graph, igraph_vector_t *result); int igraph_i_minimum_spanning_tree_prim(const igraph_t *graph, igraph_vector_t *result, const igraph_vector_t *weights); /** * \ingroup structural * \function igraph_minimum_spanning_tree * \brief Calculates one minimum spanning tree of a graph. * * * If the graph has more minimum spanning trees (this is always the * case, except if it is a forest) this implementation returns only * the same one. * * * Directed graphs are considered as undirected for this computation. * * * If the graph is not connected then its minimum spanning forest is * returned. This is the set of the minimum spanning trees of each * component. * * \param graph The graph object. * \param res An initialized vector, the IDs of the edges that constitute * a spanning tree will be returned here. Use * \ref igraph_subgraph_edges() to extract the spanning tree as * a separate graph object. * \param weights A vector containing the weights of the edges * in the same order as the simple edge iterator visits them * (i.e. in increasing order of edge IDs). * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * * Time complexity: O(|V|+|E|) for the unweighted case, O(|E| log |V|) * for the weighted case. |V| is the number of vertices, |E| the * number of edges in the graph. * * \sa \ref igraph_minimum_spanning_tree_unweighted() and * \ref igraph_minimum_spanning_tree_prim() if you only need the * tree as a separate graph object. * * \example examples/simple/igraph_minimum_spanning_tree.c */ int igraph_minimum_spanning_tree(const igraph_t* graph, igraph_vector_t* res, const igraph_vector_t* weights) { if (weights == 0) IGRAPH_CHECK(igraph_i_minimum_spanning_tree_unweighted(graph, res)); else IGRAPH_CHECK(igraph_i_minimum_spanning_tree_prim(graph, res, weights)); return IGRAPH_SUCCESS; } /** * \ingroup structural * \function igraph_minimum_spanning_tree_unweighted * \brief Calculates one minimum spanning tree of an unweighted graph. * * * If the graph has more minimum spanning trees (this is always the * case, except if it is a forest) this implementation returns only * the same one. * * * Directed graphs are considered as undirected for this computation. * * * If the graph is not connected then its minimum spanning forest is * returned. This is the set of the minimum spanning trees of each * component. * \param graph The graph object. * \param mst The minimum spanning tree, another graph object. Do * \em not initialize this object before passing it to * this function, but be sure to call \ref igraph_destroy() on it if * you don't need it any more. * \return Error code: * \c IGRAPH_ENOMEM, not enough memory for * temporary data. * * Time complexity: O(|V|+|E|), * |V| is the * number of vertices, |E| the number * of edges in the graph. * * \sa \ref igraph_minimum_spanning_tree_prim() for weighted graphs, * \ref igraph_minimum_spanning_tree() if you need the IDs of the * edges that constitute the spanning tree. */ int igraph_minimum_spanning_tree_unweighted(const igraph_t *graph, igraph_t *mst) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; IGRAPH_VECTOR_INIT_FINALLY(&edges, igraph_vcount(graph)-1); IGRAPH_CHECK(igraph_i_minimum_spanning_tree_unweighted(graph, &edges)); IGRAPH_CHECK(igraph_subgraph_edges(graph, mst, igraph_ess_vector(&edges), /* delete_vertices = */ 0)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } /** * \ingroup structural * \function igraph_minimum_spanning_tree_prim * \brief Calculates one minimum spanning tree of a weighted graph. * * * This function uses Prim's method for carrying out the computation, * see Prim, R.C.: Shortest connection networks and some * generalizations, Bell System Technical * Journal, Vol. 36, * 1957, 1389--1401. * * * If the graph has more than one minimum spanning tree, the current * implementation returns always the same one. * * * Directed graphs are considered as undirected for this computation. * * * If the graph is not connected then its minimum spanning forest is * returned. This is the set of the minimum spanning trees of each * component. * * \param graph The graph object. * \param mst The result of the computation, a graph object containing * the minimum spanning tree of the graph. * Do \em not initialize this object before passing it to * this function, but be sure to call \ref igraph_destroy() on it if * you don't need it any more. * \param weights A vector containing the weights of the edges * in the same order as the simple edge iterator visits them * (i.e. in increasing order of edge IDs). * \return Error code: * \c IGRAPH_ENOMEM, not enough memory. * \c IGRAPH_EINVAL, length of weight vector does not * match number of edges. * * Time complexity: O(|E| log |V|), * |V| is the number of vertices, * |E| the number of edges in the * graph. * * \sa \ref igraph_minimum_spanning_tree_unweighted() for unweighted graphs, * \ref igraph_minimum_spanning_tree() if you need the IDs of the * edges that constitute the spanning tree. * * \example examples/simple/igraph_minimum_spanning_tree.c */ int igraph_minimum_spanning_tree_prim(const igraph_t *graph, igraph_t *mst, const igraph_vector_t *weights) { igraph_vector_t edges=IGRAPH_VECTOR_NULL; IGRAPH_VECTOR_INIT_FINALLY(&edges, igraph_vcount(graph)-1); IGRAPH_CHECK(igraph_i_minimum_spanning_tree_prim(graph, &edges, weights)); IGRAPH_CHECK(igraph_subgraph_edges(graph, mst, igraph_ess_vector(&edges), /* delete_vertices = */ 0)); igraph_vector_destroy(&edges); IGRAPH_FINALLY_CLEAN(1); return 0; } int igraph_i_minimum_spanning_tree_unweighted(const igraph_t* graph, igraph_vector_t* res) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); char *already_added; char *added_edges; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; igraph_vector_t tmp=IGRAPH_VECTOR_NULL; long int i, j; igraph_vector_clear(res); added_edges=igraph_Calloc(no_of_edges, char); if (added_edges==0) { IGRAPH_ERROR("unweighted spanning tree failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, added_edges); already_added=igraph_Calloc(no_of_nodes, char); if (already_added==0) { IGRAPH_ERROR("unweighted spanning tree failed", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, already_added); IGRAPH_VECTOR_INIT_FINALLY(&tmp, 0); IGRAPH_DQUEUE_INIT_FINALLY(&q, 100); for (i=0; i0) { continue; } IGRAPH_ALLOW_INTERRUPTION(); already_added[i]=1; IGRAPH_CHECK(igraph_dqueue_push(&q, i)); while (! igraph_dqueue_empty(&q)) { long int act_node=(long int) igraph_dqueue_pop(&q); IGRAPH_CHECK(igraph_incident(graph, &tmp, (igraph_integer_t) act_node, IGRAPH_ALL)); for (j=0; j0) { continue; } IGRAPH_ALLOW_INTERRUPTION(); already_added[i]=1; /* add all edges of the first vertex */ igraph_incident(graph, &adj, (igraph_integer_t) i, (igraph_neimode_t) mode); for (j=0; j 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_interface.h" #include "igraph_community.h" #include "igraph_memory.h" #include "igraph_constructors.h" #include "igraph_attributes.h" #include "igraph_foreign.h" #include "igraph_hrg.h" #include "igraph_random.h" #include "hrg_dendro.h" #include "hrg_graph.h" #include "hrg_graph_simp.h" using namespace fitHRG; /** * \section hrg_intro Introduction * * A hierarchical random graph is an ensemble of undirected * graphs with \c n vertices. It is defined via a binary tree with \c * n leaf and \c n-1 internal vertices, where the * internal vertices are labeled with probabilities. * The probability that two vertices are connected in the random graph * is given by the probability label at their closest common * ancestor. * * * Please read the following two articles for more about * hierarchical random graphs: A. Clauset, C. Moore, and M.E.J. Newman. * Hierarchical structure and the prediction of missing links in networks. * Nature 453, 98 - 101 (2008); and A. Clauset, C. Moore, and M.E.J. Newman. * Structural Inference of Hierarchies in Networks. In E. M. Airoldi * et al. (Eds.): ICML 2006 Ws, Lecture Notes in Computer Science * 4503, 1-13. Springer-Verlag, Berlin Heidelberg (2007). * * * * igraph contains functions for fitting HRG models to a given network * (\ref igraph_hrg_fit), for generating networks from a given HRG * ensemble (\ref igraph_hrg_game, \ref igraph_hrg_sample), converting * an igraph graph to a HRG and back (\ref igraph_hrg_create, \ref * igraph_hrg_dendrogram), for calculating a consensus tree from a * set of sampled HRGs (\ref igraph_hrg_consensus) and for predicting * missing edges in a network based on its HRG models (\ref * igraph_hrg_predict). * * * The igraph HRG implementation is heavily based on the code * published by Aaron Clauset, at his website, * http://tuvalu.santafe.edu/~aaronc/hierarchy/ * */ namespace fitHRG { struct pblock { double L; int i; int j; }; } int markovChainMonteCarlo(dendro *d, unsigned int period, igraph_hrg_t *hrg) { igraph_real_t bestL=d->getLikelihood(); double dL; bool flag_taken; // Because moves in the dendrogram space are chosen (Monte // Carlo) so that we sample dendrograms with probability // proportional to their likelihood, a likelihood-proportional // sampling of the dendrogram models would be equivalent to a // uniform sampling of the walk itself. We would still have to // decide how often to sample the walk (at most once every n // steps is recommended) but for simplicity, the code here // simply runs the MCMC itself. To actually compute something // over the set of sampled dendrogram models (in a Bayesian // model averaging sense), you'll need to code that yourself. // do 'period' MCMC moves before doing anything else for (unsigned int i=0; imonteCarloMove(dL, flag_taken, 1.0)); // get likelihood of this D given G igraph_real_t cl= d->getLikelihood(); if (cl > bestL) { // store the current best likelihood bestL = cl; // record the HRG structure d->recordDendrogramStructure(hrg); } } // corrects floating-point errors O(n) d->refreshLikelihood(); return 0; } int markovChainMonteCarlo2(dendro *d, int num_samples) { bool flag_taken; double dL, ptest = 1.0/(50.0*(double)(d->g->numNodes())); int sample_num=0, t=1, thresh = 200 * d->g->numNodes(); // Since we're sampling uniformly at random over the equilibrium // walk, we just need to do a bunch of MCMC moves and let the // sampling happen on its own. while (sample_num < num_samples) { // Make a single MCMC move d->monteCarloMove(dL, flag_taken, 1.0); // We sample the dendrogram space once every n MCMC moves (on // average). Depending on the flags on the command line, we sample // different aspects of the dendrograph structure. if (t > thresh && RNG_UNIF01() < ptest) { sample_num++; d->sampleSplitLikelihoods(sample_num); } t++; // correct floating-point errors O(n) d->refreshLikelihood(); // TODO: less frequently } return 0; } int MCMCEquilibrium_Find(dendro *d, igraph_hrg_t *hrg) { // We want to run the MCMC until we've found equilibrium; we // use the heuristic of the average log-likelihood (which is // exactly the entropy) over X steps being very close to the // average log-likelihood (entropy) over the X steps that // preceded those. In other words, we look for an apparent // local convergence of the entropy measure of the MCMC. bool flag_taken; igraph_real_t dL, Likeli; igraph_real_t oldMeanL; igraph_real_t newMeanL=-1e-49; while (1) { oldMeanL = newMeanL; newMeanL = 0.0; for (int i=0; i<65536; i++) { IGRAPH_CHECK(! d->monteCarloMove(dL, flag_taken, 1.0)); Likeli = d->getLikelihood(); newMeanL += Likeli; } // corrects floating-point errors O(n) d->refreshLikelihood(); if (fabs(newMeanL-oldMeanL)/65536.0 < 1.0) { break; } } // Record the result if (hrg) { d->recordDendrogramStructure(hrg); } return 0; } int igraph_i_hrg_getgraph(const igraph_t *igraph, dendro *d) { int no_of_nodes = igraph_vcount(igraph); int no_of_edges = igraph_ecount(igraph); int i; // Create graph d->g=new graph(no_of_nodes); // Add edges for (i=0; ig->doesLinkExist(from, to)) { d->g->addLink(from, to); } if (!d->g->doesLinkExist(to, from)) { d->g->addLink(to, from); } } d->buildDendrogram(); return 0; } int igraph_i_hrg_getsimplegraph(const igraph_t *igraph, dendro *d, simpleGraph **sg, int num_bins) { int no_of_nodes = igraph_vcount(igraph); int no_of_edges = igraph_ecount(igraph); int i; // Create graphs d->g = new graph(no_of_nodes, true); d->g->setAdjacencyHistograms(num_bins); (*sg) = new simpleGraph(no_of_nodes); for (i=0; ig->doesLinkExist(from, to)) { d->g->addLink(from, to); } if (!d->g->doesLinkExist(to, from)) { d->g->addLink(to, from); } if (!(*sg)->doesLinkExist(from, to)) { (*sg)->addLink(from, to); } if (!(*sg)->doesLinkExist(to, from)) { (*sg)->addLink(to, from); } } d->buildDendrogram(); return 0; } /** * \function igraph_hrg_init * Allocate memory for a HRG. * * This function must be called before passing an \ref igraph_hrg_t to * an igraph function. * \param hrg Pointer to the HRG data structure to initialize. * \param n The number of vertices in the graph that is modeled by * this HRG. It can be zero, if this is not yet known. * \return Error code. * * Time complexity: O(n), the number of vertices in the graph. */ int igraph_hrg_init(igraph_hrg_t *hrg, int n) { IGRAPH_VECTOR_INIT_FINALLY(&hrg->left, n-1); IGRAPH_VECTOR_INIT_FINALLY(&hrg->right, n-1); IGRAPH_VECTOR_INIT_FINALLY(&hrg->prob, n-1); IGRAPH_VECTOR_INIT_FINALLY(&hrg->edges, n-1); IGRAPH_VECTOR_INIT_FINALLY(&hrg->vertices, n-1); IGRAPH_FINALLY_CLEAN(5); return 0; } /** * \function igraph_hrg_destroy * Deallocate memory for an HRG. * * The HRG data structure can be reinitialized again with an \ref * igraph_hrg_destroy call. * \param hrg Pointer to the HRG data structure to deallocate. * * Time complexity: operating system dependent. */ void igraph_hrg_destroy(igraph_hrg_t *hrg) { igraph_vector_destroy(&hrg->left); igraph_vector_destroy(&hrg->right); igraph_vector_destroy(&hrg->prob); igraph_vector_destroy(&hrg->edges); igraph_vector_destroy(&hrg->vertices); } /** * \function igraph_hrg_size * Returns the size of the HRG, the number of leaf nodes. * * \param hrg Pointer to the HRG. * \return The number of leaf nodes in the HRG. * * Time complexity: O(1). */ int igraph_hrg_size(const igraph_hrg_t *hrg) { return igraph_vector_size(&hrg->left)+1; } /** * \function igraph_hrg_resize * Resize a HRG. * * \param hrg Pointer to an initialized (see \ref igraph_hrg_init) * HRG. * \param newsize The new size, i.e. the number of leaf nodes. * \return Error code. * * Time complexity: O(n), n is the new size. */ int igraph_hrg_resize(igraph_hrg_t *hrg, int newsize) { int origsize=igraph_hrg_size(hrg); int ret=0; igraph_error_handler_t *oldhandler = igraph_set_error_handler(igraph_error_handler_ignore); ret = igraph_vector_resize(&hrg->left, newsize-1); ret |= igraph_vector_resize(&hrg->right, newsize-1); ret |= igraph_vector_resize(&hrg->prob, newsize-1); ret |= igraph_vector_resize(&hrg->edges, newsize-1); ret |= igraph_vector_resize(&hrg->vertices, newsize-1); igraph_set_error_handler(oldhandler); if (ret) { igraph_vector_resize(&hrg->left, origsize); igraph_vector_resize(&hrg->right, origsize); igraph_vector_resize(&hrg->prob, origsize); igraph_vector_resize(&hrg->edges, origsize); igraph_vector_resize(&hrg->vertices, origsize); IGRAPH_ERROR("Cannot resize HRG", ret); } return 0; } /** * \function igraph_hrg_fit * Fit a hierarchical random graph model to a network * * \param graph The igraph graph to fit the model to. Edge directions * are ignored in directed graphs. * \param hrg Pointer to an initialized HRG, the result of the fitting * is stored here. It can also be used to pass a HRG to the * function, that can be used as the starting point of the Markov * Chain Monte Carlo fitting, if the \c start argument is true. * \param start Logical, whether to start the fitting from the given * HRG. * \param steps Integer, the number of MCMC steps to take in the * fitting procedure. If this is zero, then the fitting stop is a * convergence criteria is fulfilled. * \return Error code. * * Time complexity: TODO. */ int igraph_hrg_fit(const igraph_t *graph, igraph_hrg_t *hrg, igraph_bool_t start, int steps) { int no_of_nodes=igraph_vcount(graph); dendro *d; RNG_BEGIN(); d = new dendro; // If we want to start from HRG if (start) { d->clearDendrograph(); if (igraph_hrg_size(hrg) != no_of_nodes) { delete d; IGRAPH_ERROR("Invalid HRG to start from", IGRAPH_EINVAL); } // Convert the igraph graph IGRAPH_CHECK(igraph_i_hrg_getgraph(graph, d)); d->importDendrogramStructure(hrg); } else { // Convert the igraph graph IGRAPH_CHECK(igraph_i_hrg_getgraph(graph, d)); IGRAPH_CHECK(igraph_hrg_resize(hrg, no_of_nodes)); } // Run fixed number of steps, or until convergence if (steps > 0) { IGRAPH_CHECK(markovChainMonteCarlo(d, steps, hrg)); } else { IGRAPH_CHECK(MCMCEquilibrium_Find(d, hrg)); } delete d; RNG_END(); return 0; } /** * \function igraph_hrg_sample * Sample from a hierarchical random graph model * * Sample from a hierarchical random graph ensemble. The ensemble can * be given as a graph (\c input_graph), or as a HRG object (\c hrg). * If a graph is given, then first an MCMC optimization is performed * to find the optimal fitting model; then the MCMC is used to sample * the graph(s). * \param input_graph An igraph graph, or a null pointer. If not a * null pointer, then a HRG is first fitted to the graph, possibly * starting from the given HRG, if the \c start argument is true. If * is is a null pointer, then the given HRG is used as a starting * point, to find the optimum of the Markov chain, before the * sampling. * \param sample Pointer to an uninitialized graph, or a null * pointer. If only one sample is requested, and it is not a null * pointer, then the sample is stored here. * \param samples An initialized vector of pointers. If more than one * samples are requested, then they are stored here. Note that to * free this data structure, you need to call \ref igraph_destroy on * each graph first, then \c free() on all pointers, and finally * \ref igraph_vector_ptr_destroy. * \param no_samples The number of samples to generate. * \param hrg A HRG. It is modified during the sampling. * \param start Logical, whether to start the MCMC from the given * HRG. * \return Error code. * * Time complexity: TODO. */ int igraph_hrg_sample(const igraph_t *input_graph, igraph_t *sample, igraph_vector_ptr_t *samples, int no_samples, igraph_hrg_t *hrg, igraph_bool_t start) { int i; dendro *d; if (no_samples < 0) { IGRAPH_ERROR("Number of samples must be non-negative", IGRAPH_EINVAL); } if (!sample && !samples) { IGRAPH_ERROR("Give at least one of `sample' and `samples'", IGRAPH_EINVAL); } if (no_samples != 1 && sample) { IGRAPH_ERROR("Number of samples should be one if `sample' is given", IGRAPH_EINVAL); } if (no_samples > 1 && !samples) { IGRAPH_ERROR("`samples' must be non-null if number of samples " "is larger than 1", IGRAPH_EINVAL); } if (!start && !input_graph) { IGRAPH_ERROR("Input graph must be given if initial HRG is not used", IGRAPH_EINVAL); } if (!start) { IGRAPH_CHECK(igraph_hrg_resize(hrg, igraph_vcount(input_graph))); } if (input_graph && igraph_hrg_size(hrg) != igraph_vcount(input_graph)) { IGRAPH_ERROR("Invalid HRG size, should match number of nodes", IGRAPH_EINVAL); } RNG_BEGIN(); d = new dendro; // Need to find equilibrium first? if (start) { d->clearDendrograph(); d->importDendrogramStructure(hrg); } else { IGRAPH_CHECK(MCMCEquilibrium_Find(d, hrg)); } // TODO: free on error if (sample) { // A single graph d->makeRandomGraph(); d->recordGraphStructure(sample); if (samples) { igraph_t *G=igraph_Calloc(1, igraph_t); if (!G) { IGRAPH_ERROR("Cannot sample HRG graphs", IGRAPH_ENOMEM); } d->recordGraphStructure(G); IGRAPH_CHECK(igraph_vector_ptr_resize(samples, 1)); VECTOR(*samples)[0]=G; } } else { // Sample many IGRAPH_CHECK(igraph_vector_ptr_resize(samples, no_samples)); for (i=0; imakeRandomGraph(); d->recordGraphStructure(G); VECTOR(*samples)[i]=G; } } delete d; RNG_END(); return 0; } /** * \function igraph_hrg_game * Generate a hierarchical random graph * * This function is a simple shortcut to \ref igraph_hrg_sample. * It creates a single graph, from the given HRG. * \param graph Pointer to an uninitialized graph, the new graph is * created here. * \param hrg The hierarchical random graph model to sample from. It * is modified during the MCMC process. * \return Error code. * * Time complexity: TODO. */ int igraph_hrg_game(igraph_t *graph, const igraph_hrg_t *hrg) { return igraph_hrg_sample(/* input_graph= */ 0, /* sample= */ graph, /* samples= */ 0, /* no_samples=*/ 1, /* hrg= */ (igraph_hrg_t*) hrg, /* start= */ 1); } /** * \function igraph_hrg_dendrogram * Create a dendrogram from a hierarchical random graph. * * Creates the igraph graph equivalent of an \ref igraph_hrg_t data * structure. * \param graph Pointer to an uninitialized graph, the result is * stored here. * \param hrg The hierarchical random graph to convert. * \return Error code. * * Time complexity: O(n), the number of vertices in the graph. */ int igraph_hrg_dendrogram(igraph_t *graph, const igraph_hrg_t *hrg) { int orig_nodes=igraph_hrg_size(hrg); int no_of_nodes=orig_nodes * 2 - 1; int no_of_edges=no_of_nodes-1; igraph_vector_t edges; int i, idx=0; igraph_vector_ptr_t vattrs; igraph_vector_t prob; igraph_attribute_record_t rec = { "probability", IGRAPH_ATTRIBUTE_NUMERIC, &prob }; // Probability labels, for leaf nodes they are IGRAPH_NAN IGRAPH_VECTOR_INIT_FINALLY(&prob, no_of_nodes); for (i=0; iprob)[i]; } IGRAPH_VECTOR_INIT_FINALLY(&edges, no_of_edges * 2); IGRAPH_CHECK(igraph_vector_ptr_init(&vattrs, 1)); IGRAPH_FINALLY(igraph_vector_ptr_destroy, &vattrs); VECTOR(vattrs)[0] = &rec; for (i=0; ileft)[i]; int right=VECTOR(hrg->right)[i]; VECTOR(edges)[idx++] = orig_nodes+i; VECTOR(edges)[idx++] = left < 0 ? orig_nodes-left-1 : left; VECTOR(edges)[idx++] = orig_nodes+i; VECTOR(edges)[idx++] = right < 0 ? orig_nodes-right-1 : right; } IGRAPH_CHECK(igraph_empty(graph, 0, IGRAPH_DIRECTED)); IGRAPH_FINALLY(igraph_destroy, graph); IGRAPH_CHECK(igraph_add_vertices(graph, no_of_nodes, &vattrs)); IGRAPH_CHECK(igraph_add_edges(graph, &edges, 0)); igraph_vector_ptr_destroy(&vattrs); igraph_vector_destroy(&edges); igraph_vector_destroy(&prob); IGRAPH_FINALLY_CLEAN(4); // + 1 for graph return 0; } /** * \function igraph_hrg_consensus * Calculate a consensus tree for a HRG. * * The calculation can be started from the given HRG (\c hrg), or (if * \c start is false), a HRG is first fitted to the given graph. * * \param graph The input graph. * \param parents An initialized vector, the results are stored * here. For each vertex, the id of its parent vertex is stored, or * -1, if the vertex is the root vertex in the tree. The first n * vertex ids (from 0) refer to the original vertices of the graph, * the other ids refer to vertex groups. * \param weights Numeric vector, counts the number of times a given * tree split occured in the generated network samples, for each * internal vertices. The order is the same as in \c parents. * \param hrg A hierarchical random graph. It is used as a starting * point for the sampling, if the \c start argument is true. It is * modified along the MCMC. * \param start Logical, whether to use the supplied HRG (in \c hrg) * as a starting point for the MCMC. * \param num_samples The number of samples to generate for creating * the consensus tree. * \return Error code. * * Time complexity: TODO. */ int igraph_hrg_consensus(const igraph_t *graph, igraph_vector_t *parents, igraph_vector_t *weights, igraph_hrg_t *hrg, igraph_bool_t start, int num_samples) { dendro *d; if (start && !hrg) { IGRAPH_ERROR("`hrg' must be given is `start' is true", IGRAPH_EINVAL); } RNG_BEGIN(); d = new dendro; if (start) { d->clearDendrograph(); IGRAPH_CHECK(igraph_i_hrg_getgraph(graph, d)); d->importDendrogramStructure(hrg); } else { IGRAPH_CHECK(igraph_i_hrg_getgraph(graph, d)); if (hrg) { igraph_hrg_resize(hrg, igraph_vcount(graph)); } IGRAPH_CHECK(MCMCEquilibrium_Find(d, hrg)); } IGRAPH_CHECK(markovChainMonteCarlo2(d, num_samples)); d->recordConsensusTree(parents, weights); delete d; RNG_END(); return 0; } int MCMCEquilibrium_Sample(dendro *d, int num_samples) { // Because moves in the dendrogram space are chosen (Monte // Carlo) so that we sample dendrograms with probability // proportional to their likelihood, a likelihood-proportional // sampling of the dendrogram models would be equivalent to a // uniform sampling of the walk itself. We would still have to // decide how often to sample the walk (at most once every n steps // is recommended) but for simplicity, the code here simply runs the // MCMC itself. To actually compute something over the set of // sampled dendrogram models (in a Bayesian model averaging sense), // you'll need to code that yourself. double dL; bool flag_taken; int sample_num=0; int t=1, thresh=100 * d->g->numNodes(); double ptest=1.0/10.0/d->g->numNodes(); while (sample_num < num_samples) { d->monteCarloMove(dL, flag_taken, 1.0); if (t > thresh && RNG_UNIF01() < ptest) { sample_num++; d->sampleAdjacencyLikelihoods(); } d->refreshLikelihood(); // TODO: less frequently t++; } return 0; } int QsortPartition (pblock* array, int left, int right, int index) { pblock p_value, temp; p_value.L = array[index].L; p_value.i = array[index].i; p_value.j = array[index].j; // swap(array[p_value], array[right]) temp.L = array[right].L; temp.i = array[right].i; temp.j = array[right].j; array[right].L = array[index].L; array[right].i = array[index].i; array[right].j = array[index].j; array[index].L = temp.L; array[index].i = temp.i; array[index].j = temp.j; int stored = left; for (int i=left; i left) { int pivot = left; int part = QsortPartition(array, left, right, pivot); QsortMain(array, left, part-1); QsortMain(array, part+1, right ); } return; } int rankCandidatesByProbability(simpleGraph *sg, dendro *d, pblock *br_list, int mk) { int mkk=0; int n=sg->getNumNodes(); for (int i=0; igetAdjacency(i, j) < 0.5) { double temp=d->g->getAdjacencyAverage(i, j); br_list[mkk].L = temp * (1.0 + RNG_UNIF01()/1000.0); br_list[mkk].i = i; br_list[mkk].j = j; mkk++; } } } // Sort the candidates by their average probability QsortMain(br_list, 0, mk-1); return 0; } int recordPredictions(pblock *br_list, igraph_vector_t *edges, igraph_vector_t *prob, int mk) { IGRAPH_CHECK(igraph_vector_resize(edges, mk*2)); IGRAPH_CHECK(igraph_vector_resize(prob, mk)); for (int i=mk-1, idx=0, idx2=0; i>=0; i--) { VECTOR(*edges)[idx++] = br_list[i].i; VECTOR(*edges)[idx++] = br_list[i].j; VECTOR(*prob)[idx2++] = br_list[i].L; } return 0; } /** * \function igraph_hrg_predict * Predict missing edges in a graph, based on HRG models * * Samples HRG models for a network, and estimated the probability * that an edge was falsely observed as non-existent in the network. * \param graph The input graph. * \param edges The list of missing edges is stored here, the first * two elements are the first edge, the next two the second edge, * etc. * \param prob Vector of probabilies for the existence of missing * edges, in the order corresponding to \c edges. * \param hrg A HRG, it is used as a starting point if \c start is * true. It is also modified during the MCMC sampling. * \param start Logical, whether to start the MCMC from the given HRG. * \param num_samples The number of samples to generate. * \param num_bins Controls the resolution of the edge * probabilities. Higher numbers result higher resolution. * \return Error code. * * Time complexity: TODO. */ int igraph_hrg_predict(const igraph_t *graph, igraph_vector_t *edges, igraph_vector_t *prob, igraph_hrg_t *hrg, igraph_bool_t start, int num_samples, int num_bins) { dendro *d; pblock *br_list; int mk; simpleGraph *sg; if (start && !hrg) { IGRAPH_ERROR("`hrg' must be given is `start' is true", IGRAPH_EINVAL); } RNG_BEGIN(); d = new dendro; IGRAPH_CHECK(igraph_i_hrg_getsimplegraph(graph, d, &sg, num_bins)); mk = sg->getNumNodes() * (sg->getNumNodes()-1) / 2 - sg->getNumLinks()/2; br_list = new pblock[mk]; for (int i=0; iclearDendrograph(); // this has cleared the graph as well.... bug? IGRAPH_CHECK(igraph_i_hrg_getsimplegraph(graph, d, &sg, num_bins)); d->importDendrogramStructure(hrg); } else { if (hrg) { igraph_hrg_resize(hrg, igraph_vcount(graph)); } IGRAPH_CHECK(MCMCEquilibrium_Find(d, hrg)); } IGRAPH_CHECK(MCMCEquilibrium_Sample(d, num_samples)); IGRAPH_CHECK(rankCandidatesByProbability(sg, d, br_list, mk)); IGRAPH_CHECK(recordPredictions(br_list, edges, prob, mk)); delete d; delete sg; delete [] br_list; RNG_END(); return 0; } /** * \function igraph_hrg_create * Create a HRG from an igraph graph. * * \param hrg Pointer to an initialized \ref igraph_hrg_t. The result * is stored here. * \param graph The igraph graph to convert. It must be a directed * binary tree, with n-1 internal and n leaf vertices. The root * vertex must have in-degree zero. * \param prob The vector of probabilities, this is used to label the * internal nodes of the hierarchical random graph. The values * corresponding to the leaves are ignored. * \return Error code. * * Time complexity: O(n), the number of vertices in the tree. */ int igraph_hrg_create(igraph_hrg_t *hrg, const igraph_t *graph, const igraph_vector_t *prob) { int no_of_nodes=igraph_vcount(graph); int no_of_internal=(no_of_nodes-1)/2; igraph_vector_t deg, idx; int root=0; int d0=0, d1=0, d2=0; int ii=0, il=0; igraph_vector_t neis; igraph_vector_t path; // -------------------------------------------------------- // CHECKS // -------------------------------------------------------- // At least three vertices are required if (no_of_nodes < 3) { IGRAPH_ERROR("HRG tree must have at least three vertices", IGRAPH_EINVAL); } // Prob vector was given if (!prob) { IGRAPH_ERROR("Probability vector must be given for HRG", IGRAPH_EINVAL); } // Length of prob vector if (igraph_vector_size(prob) != no_of_nodes) { IGRAPH_ERROR("HRG probability vector of wrong size", IGRAPH_EINVAL); } // Must be a directed graph if (!igraph_is_directed(graph)) { IGRAPH_ERROR("HRG graph must be directed", IGRAPH_EINVAL); } // Number of nodes must be odd if (no_of_nodes % 2 == 0) { IGRAPH_ERROR("Complete HRG graph must have odd number of vertices", IGRAPH_EINVAL); } IGRAPH_VECTOR_INIT_FINALLY(°, 0); // Every vertex, except for the root must have in-degree one. IGRAPH_CHECK(igraph_degree(graph, °, igraph_vss_all(), IGRAPH_IN, IGRAPH_LOOPS)); for (int i=0; i= 0) { continue; } IGRAPH_CHECK(igraph_neighbors(graph, &neis, i, IGRAPH_OUT)); VECTOR(hrg->left )[-ri-1] = VECTOR(idx)[ (int) VECTOR(neis)[0] ]; VECTOR(hrg->right)[-ri-1] = VECTOR(idx)[ (int) VECTOR(neis)[1] ]; VECTOR(hrg->prob )[-ri-1] = VECTOR(*prob)[i]; } // Calculate the number of vertices and edges in each subtree igraph_vector_null(&hrg->edges); igraph_vector_null(&hrg->vertices); IGRAPH_VECTOR_INIT_FINALLY(&path, 0); IGRAPH_CHECK(igraph_vector_push_back(&path, VECTOR(idx)[root])); while (!igraph_vector_empty(&path)) { int ri=igraph_vector_tail(&path); int lc=VECTOR(hrg->left)[-ri-1]; int rc=VECTOR(hrg->right)[-ri-1]; if (lc < 0 && VECTOR(hrg->vertices)[-lc-1]==0) { // Go left IGRAPH_CHECK(igraph_vector_push_back(&path, lc)); } else if (rc < 0 && VECTOR(hrg->vertices)[-rc-1]==0) { // Go right IGRAPH_CHECK(igraph_vector_push_back(&path, rc)); } else { // Subtrees are done, update node and go up VECTOR(hrg->vertices)[-ri-1] += lc < 0 ? VECTOR(hrg->vertices)[-lc-1] : 1; VECTOR(hrg->vertices)[-ri-1] += rc < 0 ? VECTOR(hrg->vertices)[-rc-1] : 1; VECTOR(hrg->edges)[-ri-1] += lc < 0 ? VECTOR(hrg->edges)[-lc-1]+1 : 1; VECTOR(hrg->edges)[-ri-1] += rc < 0 ? VECTOR(hrg->edges)[-rc-1]+1 : 1; igraph_vector_pop_back(&path); } } igraph_vector_destroy(&path); igraph_vector_destroy(&neis); igraph_vector_destroy(&idx); igraph_vector_destroy(°); IGRAPH_FINALLY_CLEAN(4); return 0; } igraph/src/foreign-gml-parser.y0000644000175100001440000001641513430770201016227 0ustar hornikusers/* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ %{ /* IGraph library. Copyright (C) 2009-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include "igraph_error.h" #include "igraph_memory.h" #include "config.h" #include "igraph_hacks_internal.h" #include "igraph_math.h" #include "igraph_gml_tree.h" #include "foreign-gml-header.h" #include "foreign-gml-parser.h" #define yyscan_t void* int igraph_gml_yylex(YYSTYPE* lvalp, YYLTYPE* llocp, void *scanner); int igraph_gml_yyerror(YYLTYPE* locp, igraph_i_gml_parsedata_t *context, const char *s); char *igraph_gml_yyget_text (yyscan_t yyscanner ); int igraph_gml_yyget_leng (yyscan_t yyscanner ); void igraph_i_gml_get_keyword(char *s, int len, void *res); void igraph_i_gml_get_string(char *s, int len, void *res); double igraph_i_gml_get_real(char *s, int len); igraph_gml_tree_t *igraph_i_gml_make_numeric(char* s, int len, double value); igraph_gml_tree_t *igraph_i_gml_make_numeric2(char* s, int len, char *v, int vlen); igraph_gml_tree_t *igraph_i_gml_make_string(char* s, int len, char *value, int valuelen); igraph_gml_tree_t *igraph_i_gml_make_list(char* s, int len, igraph_gml_tree_t *list); igraph_gml_tree_t *igraph_i_gml_merge(igraph_gml_tree_t *t1, igraph_gml_tree_t* t2); #define scanner context->scanner #define USE(x) /*(x)*/ %} %pure-parser %output="y.tab.c" %name-prefix="igraph_gml_yy" %defines %locations %error-verbose %parse-param { igraph_i_gml_parsedata_t* context } %lex-param { void *scanner } %union { struct { char *s; int len; } str; void *tree; double real; } %type list; %type keyvalue; %type key; %type num; %type string; %token STRING %token NUM %token KEYWORD %token LISTOPEN %token LISTCLOSE %token EOFF %token ERROR %destructor { igraph_Free($$.s); } string key KEYWORD; %destructor { igraph_gml_tree_destroy($$); } list keyvalue; %% input: list { context->tree=$1; } | list EOFF { context->tree=$1; } ; list: keyvalue { $$=$1; } | list keyvalue { $$=igraph_i_gml_merge($1, $2); }; keyvalue: key num { $$=igraph_i_gml_make_numeric($1.s, $1.len, $2); } | key string { $$=igraph_i_gml_make_string($1.s, $1.len, $2.s, $2.len); } | key LISTOPEN list LISTCLOSE { $$=igraph_i_gml_make_list($1.s, $1.len, $3); } | key key { $$=igraph_i_gml_make_numeric2($1.s, $1.len, $2.s, $2.len); } ; key: KEYWORD { igraph_i_gml_get_keyword(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner), &$$); USE($1) }; num : NUM { $$=igraph_i_gml_get_real(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner)); }; string: STRING { igraph_i_gml_get_string(igraph_gml_yyget_text(scanner), igraph_gml_yyget_leng(scanner), &$$); }; %% int igraph_gml_yyerror(YYLTYPE* locp, igraph_i_gml_parsedata_t *context, const char *s) { snprintf(context->errmsg, sizeof(context->errmsg)/sizeof(char)-1, "Parse error in GML file, line %i (%s)", locp->first_line, s); return 0; } void igraph_i_gml_get_keyword(char *s, int len, void *res) { struct { char *s; int len; } *p=res; p->s=igraph_Calloc(len+1, char); if (!p->s) { igraph_error("Cannot read GML file", __FILE__, __LINE__, IGRAPH_PARSEERROR); } memcpy(p->s, s, sizeof(char)*len); p->s[len]='\0'; p->len=len; } void igraph_i_gml_get_string(char *s, int len, void *res) { struct { char *s; int len; } *p=res; p->s=igraph_Calloc(len-1, char); if (!p->s) { igraph_error("Cannot read GML file", __FILE__, __LINE__, IGRAPH_PARSEERROR); } memcpy(p->s, s+1, sizeof(char)*(len-2)); p->s[len-2]='\0'; p->len=len-2; } double igraph_i_gml_get_real(char *s, int len) { igraph_real_t num; char tmp=s[len]; s[len]='\0'; sscanf(s, "%lf", &num); s[len]=tmp; return num; } igraph_gml_tree_t *igraph_i_gml_make_numeric(char* s, int len, double value) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } if (floor(value)==value) { igraph_gml_tree_init_integer(t, s, len, value); } else { igraph_gml_tree_init_real(t, s, len, value); } return t; } igraph_gml_tree_t *igraph_i_gml_make_numeric2(char* s, int len, char *v, int vlen) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); char tmp=v[vlen]; igraph_real_t value=0; if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } v[vlen]='\0'; if (strcasecmp(v, "inf")) { value=IGRAPH_INFINITY; } else if (strcasecmp(v, "nan")) { value=IGRAPH_NAN; } else { igraph_error("Parse error", __FILE__, __LINE__, IGRAPH_PARSEERROR); } v[vlen]=tmp; igraph_gml_tree_init_real(t, s, len, value); return t; } igraph_gml_tree_t *igraph_i_gml_make_string(char* s, int len, char *value, int valuelen) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } igraph_gml_tree_init_string(t, s, len, value, valuelen); return t; } igraph_gml_tree_t *igraph_i_gml_make_list(char* s, int len, igraph_gml_tree_t *list) { igraph_gml_tree_t *t=igraph_Calloc(1, igraph_gml_tree_t); if (!t) { igraph_error("Cannot build GML tree", __FILE__, __LINE__, IGRAPH_ENOMEM); return 0; } igraph_gml_tree_init_tree(t, s, len, list); return t; } igraph_gml_tree_t *igraph_i_gml_merge(igraph_gml_tree_t *t1, igraph_gml_tree_t* t2) { igraph_gml_tree_mergedest(t1, t2); igraph_Free(t2); return t1; } igraph/src/dqueue.c0000644000175100001440000000274213431000472013764 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_dqueue.h" #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "dqueue.pmt" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "dqueue.pmt" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_CHAR #include "igraph_pmt.h" #include "dqueue.pmt" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "dqueue.pmt" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_INT #include "igraph_pmt.h" #include "dqueue.pmt" #include "igraph_pmt_off.h" #undef BASE_INT igraph/src/CHOLMOD/0000755000175100001440000000000013567553110013424 5ustar hornikusersigraph/src/CHOLMOD/Core/0000755000175100001440000000000013561251652014314 5ustar hornikusersigraph/src/CHOLMOD/Core/cholmod_common.c0000644000175100001440000005452013431000472017447 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_common ================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_common object: * * Primary routines: * ----------------- * cholmod_start the first call to CHOLMOD * cholmod_finish the last call to CHOLMOD * * Secondary routines: * ------------------- * cholmod_defaults restore (most) default control parameters * cholmod_allocate_work allocate (or reallocate) workspace in Common * cholmod_free_work free workspace in Common * cholmod_clear_flag clear Common->Flag in workspace * cholmod_maxrank column dimension of Common->Xwork workspace * * The Common object is unique. It cannot be allocated or deallocated by * CHOLMOD, since it contains the definition of the memory management routines * used (pointers to malloc, free, realloc, and calloc, or their equivalent). * The Common object contains workspace that is used between calls to * CHOLMOD routines. This workspace allocated by CHOLMOD as needed, by * cholmod_allocate_work and cholmod_free_work. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === cholmod_start ======================================================== */ /* ========================================================================== */ /* Initialize Common default parameters and statistics. Sets workspace * pointers to NULL. * * This routine must be called just once, prior to calling any other CHOLMOD * routine. Do not call this routine after any other CHOLMOD routine (except * cholmod_finish, to start a new CHOLMOD session), or a memory leak will * occur. * * workspace: none */ int CHOLMOD(start) ( cholmod_common *Common ) { int k ; if (Common == NULL) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* user error handling routine */ /* ---------------------------------------------------------------------- */ Common->error_handler = NULL ; /* ---------------------------------------------------------------------- */ /* integer and numerical types */ /* ---------------------------------------------------------------------- */ Common->itype = ITYPE ; Common->dtype = DTYPE ; /* ---------------------------------------------------------------------- */ /* default control parameters */ /* ---------------------------------------------------------------------- */ CHOLMOD(defaults) (Common) ; Common->try_catch = FALSE ; /* ---------------------------------------------------------------------- */ /* memory management routines */ /* ---------------------------------------------------------------------- */ /* The user can replace cholmod's memory management routines by redefining * these function pointers. */ #ifndef NMALLOC /* stand-alone ANSI C program */ Common->malloc_memory = malloc ; Common->free_memory = free ; Common->realloc_memory = realloc ; Common->calloc_memory = calloc ; #else /* no memory manager defined at compile-time; MUST define one at run-time */ Common->malloc_memory = NULL ; Common->free_memory = NULL ; Common->realloc_memory = NULL ; Common->calloc_memory = NULL ; #endif /* ---------------------------------------------------------------------- */ /* complex arithmetic routines */ /* ---------------------------------------------------------------------- */ Common->complex_divide = CHOLMOD(divcomplex) ; Common->hypotenuse = CHOLMOD(hypot) ; /* ---------------------------------------------------------------------- */ /* print routine */ /* ---------------------------------------------------------------------- */ #ifndef NPRINT /* stand-alone ANSI C program */ Common->print_function = printf ; #else /* printing disabled */ Common->print_function = NULL ; #endif /* ---------------------------------------------------------------------- */ /* workspace */ /* ---------------------------------------------------------------------- */ /* This code assumes the workspace held in Common is not initialized. If * it is, then a memory leak will occur because the pointers are * overwritten with NULL. */ Common->nrow = 0 ; Common->mark = EMPTY ; Common->xworksize = 0 ; Common->iworksize = 0 ; Common->Flag = NULL ; Common->Head = NULL ; Common->Iwork = NULL ; Common->Xwork = NULL ; Common->no_workspace_reallocate = FALSE ; /* ---------------------------------------------------------------------- */ /* statistics */ /* ---------------------------------------------------------------------- */ /* fl and lnz are computed in cholmod_analyze and cholmod_rowcolcounts */ Common->fl = EMPTY ; Common->lnz = EMPTY ; /* modfl is computed in cholmod_updown, cholmod_rowadd, and cholmod_rowdel*/ Common->modfl = EMPTY ; /* all routines use status as their error-report code */ Common->status = CHOLMOD_OK ; Common->malloc_count = 0 ; /* # calls to malloc minus # calls to free */ Common->memory_usage = 0 ; /* peak memory usage (in bytes) */ Common->memory_inuse = 0 ; /* current memory in use (in bytes) */ Common->nrealloc_col = 0 ; Common->nrealloc_factor = 0 ; Common->ndbounds_hit = 0 ; Common->rowfacfl = 0 ; Common->aatfl = EMPTY ; /* Common->called_nd is TRUE if cholmod_analyze called or NESDIS */ Common->called_nd = FALSE ; Common->blas_ok = TRUE ; /* false if BLAS int overflow occurs */ /* ---------------------------------------------------------------------- */ /* default SuiteSparseQR knobs and statististics */ /* ---------------------------------------------------------------------- */ for (k = 0 ; k < 4 ; k++) Common->SPQR_xstat [k] = 0 ; for (k = 0 ; k < 10 ; k++) Common->SPQR_istat [k] = 0 ; for (k = 0 ; k < 10 ; k++) Common->other1 [k] = 0 ; for (k = 0 ; k < 6 ; k++) Common->other2 [k] = 0 ; for (k = 0 ; k < 10 ; k++) Common->other3 [k] = 0 ; for (k = 0 ; k < 16 ; k++) Common->other4 [k] = 0 ; for (k = 0 ; k < 16 ; k++) Common->other5 [k] = (void *) NULL ; Common->SPQR_grain = 1 ; /* no Intel TBB multitasking, by default */ Common->SPQR_small = 1e6 ; /* target min task size for TBB */ Common->SPQR_shrink = 1 ; /* controls SPQR shrink realloc */ Common->SPQR_nthreads = 0 ; /* 0: let TBB decide how many threads to use */ /* ---------------------------------------------------------------------- */ /* GPU initializations */ /* ---------------------------------------------------------------------- */ #ifdef GPU_BLAS Common->cublasHandle = NULL ; Common->cudaStreamSyrk = NULL ; Common->cudaStreamGemm = NULL ; Common->cudaStreamTrsm = NULL ; Common->cudaStreamPotrf [0] = NULL ; Common->cudaStreamPotrf [1] = NULL ; Common->cudaStreamPotrf [2] = NULL ; Common->cublasEventPotrf [0] = NULL ; Common->cublasEventPotrf [1] = NULL ; Common->HostPinnedMemory = NULL ; Common->devPotrfWork = NULL ; Common->devSyrkGemmPtrLx = NULL ; Common->devSyrkGemmPtrC = NULL ; Common->GemmUsed = 0 ; Common->SyrkUsed = 0 ; Common->syrkStart = 0 ; #endif DEBUG_INIT ("cholmod start", Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_defaults ===================================================== */ /* ========================================================================== */ /* Set Common default parameters, except for the function pointers. * * workspace: none */ int CHOLMOD(defaults) ( cholmod_common *Common ) { Int i ; RETURN_IF_NULL_COMMON (FALSE) ; /* ---------------------------------------------------------------------- */ /* default control parameters */ /* ---------------------------------------------------------------------- */ Common->dbound = 0.0 ; Common->grow0 = 1.2 ; Common->grow1 = 1.2 ; Common->grow2 = 5 ; Common->maxrank = 8 ; Common->final_asis = TRUE ; Common->final_super = TRUE ; Common->final_ll = FALSE ; Common->final_pack = TRUE ; Common->final_monotonic = TRUE ; Common->final_resymbol = FALSE ; /* use simplicial factorization if flop/nnz(L) < 40, supernodal otherwise */ Common->supernodal = CHOLMOD_AUTO ; Common->supernodal_switch = 40 ; Common->nrelax [0] = 4 ; Common->nrelax [1] = 16 ; Common->nrelax [2] = 48 ; Common->zrelax [0] = 0.8 ; Common->zrelax [1] = 0.1 ; Common->zrelax [2] = 0.05 ; Common->prefer_zomplex = FALSE ; Common->prefer_upper = TRUE ; Common->prefer_binary = FALSE ; Common->quick_return_if_not_posdef = FALSE ; /* METIS workarounds */ Common->metis_memory = 0.0 ; /* > 0 for memory guard (2 is reasonable) */ Common->metis_nswitch = 3000 ; Common->metis_dswitch = 0.66 ; Common->print = 3 ; Common->precise = FALSE ; /* ---------------------------------------------------------------------- */ /* default ordering methods */ /* ---------------------------------------------------------------------- */ /* Note that if the Partition module is not installed, the CHOLMOD_METIS * and CHOLMOD_NESDIS methods will not be available. cholmod_analyze will * report the CHOLMOD_NOT_INSTALLED error, and safely skip over them. */ #if (CHOLMOD_MAXMETHODS < 9) #error "CHOLMOD_MAXMETHODS must be 9 or more (defined in cholmod_core.h)." #endif /* default strategy: try given, AMD, and then METIS if AMD reports high * fill-in. NESDIS can be used instead, if Common->default_nesdis is TRUE. */ Common->nmethods = 0 ; /* use default strategy */ Common->default_nesdis = FALSE ; /* use METIS in default strategy */ Common->current = 0 ; /* current method being tried */ Common->selected = 0 ; /* the best method selected */ /* first, fill each method with default parameters */ for (i = 0 ; i <= CHOLMOD_MAXMETHODS ; i++) { /* CHOLMOD's default method is AMD for A or AA' */ Common->method [i].ordering = CHOLMOD_AMD ; /* CHOLMOD nested dissection and minimum degree parameter */ Common->method [i].prune_dense = 10.0 ; /* dense row/col control */ /* min degree parameters (AMD, COLAMD, SYMAMD, CAMD, CCOLAMD, CSYMAMD)*/ Common->method [i].prune_dense2 = -1 ; /* COLAMD dense row control */ Common->method [i].aggressive = TRUE ; /* aggressive absorption */ Common->method [i].order_for_lu = FALSE ;/* order for Cholesky not LU */ /* CHOLMOD's nested dissection (METIS + constrained AMD) */ Common->method [i].nd_small = 200 ; /* small graphs aren't cut */ Common->method [i].nd_compress = TRUE ; /* compress graph & subgraphs */ Common->method [i].nd_camd = 1 ; /* use CAMD */ Common->method [i].nd_components = FALSE ; /* lump connected comp. */ Common->method [i].nd_oksep = 1.0 ; /* sep ok if < oksep*n */ /* statistics for each method are not yet computed */ Common->method [i].fl = EMPTY ; Common->method [i].lnz = EMPTY ; } Common->postorder = TRUE ; /* follow ordering with weighted postorder */ /* Next, define some methods. The first five use default parameters. */ Common->method [0].ordering = CHOLMOD_GIVEN ; /* skip if UserPerm NULL */ Common->method [1].ordering = CHOLMOD_AMD ; Common->method [2].ordering = CHOLMOD_METIS ; Common->method [3].ordering = CHOLMOD_NESDIS ; Common->method [4].ordering = CHOLMOD_NATURAL ; /* CHOLMOD's nested dissection with large leaves of separator tree */ Common->method [5].ordering = CHOLMOD_NESDIS ; Common->method [5].nd_small = 20000 ; /* CHOLMOD's nested dissection with tiny leaves, and no AMD ordering */ Common->method [6].ordering = CHOLMOD_NESDIS ; Common->method [6].nd_small = 4 ; Common->method [6].nd_camd = 0 ; /* no CSYMAMD or CAMD */ /* CHOLMOD's nested dissection with no dense node removal */ Common->method [7].ordering = CHOLMOD_NESDIS ; Common->method [7].prune_dense = -1. ; /* COLAMD for A*A', AMD for A */ Common->method [8].ordering = CHOLMOD_COLAMD ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_finish ======================================================= */ /* ========================================================================== */ /* The last call to CHOLMOD must be cholmod_finish. You may call this routine * more than once, and can safely call any other CHOLMOD routine after calling * it (including cholmod_start). * * The statistics and parameter settings in Common are preserved. The * workspace in Common is freed. This routine is just another name for * cholmod_free_work. */ int CHOLMOD(finish) ( cholmod_common *Common ) { return (CHOLMOD(free_work) (Common)) ; } /* ========================================================================== */ /* === cholmod_allocate_work ================================================ */ /* ========================================================================== */ /* Allocate and initialize workspace for CHOLMOD routines, or increase the size * of already-allocated workspace. If enough workspace is already allocated, * then nothing happens. * * workspace: Flag (nrow), Head (nrow+1), Iwork (iworksize), Xwork (xworksize) */ int CHOLMOD(allocate_work) ( /* ---- input ---- */ size_t nrow, /* # of rows in the matrix A */ size_t iworksize, /* size of Iwork */ size_t xworksize, /* size of Xwork */ /* --------------- */ cholmod_common *Common ) { double *W ; Int *Head ; Int i ; size_t nrow1 ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* Allocate Flag (nrow) and Head (nrow+1) */ /* ---------------------------------------------------------------------- */ nrow = MAX (1, nrow) ; /* nrow1 = nrow + 1 */ nrow1 = CHOLMOD(add_size_t) (nrow, 1, &ok) ; if (!ok) { /* nrow+1 causes size_t overflow ; problem is too large */ Common->status = CHOLMOD_TOO_LARGE ; CHOLMOD(free_work) (Common) ; return (FALSE) ; } if (nrow > Common->nrow) { if (Common->no_workspace_reallocate) { /* CHOLMOD is not allowed to change the workspace here */ Common->status = CHOLMOD_INVALID ; return (FALSE) ; } /* free the old workspace (if any) and allocate new space */ Common->Flag = CHOLMOD(free) (Common->nrow, sizeof (Int), Common->Flag, Common) ; Common->Head = CHOLMOD(free) (Common->nrow+1,sizeof (Int), Common->Head, Common) ; Common->Flag = CHOLMOD(malloc) (nrow, sizeof (Int), Common) ; Common->Head = CHOLMOD(malloc) (nrow1, sizeof (Int), Common) ; /* record the new size of Flag and Head */ Common->nrow = nrow ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_work) (Common) ; return (FALSE) ; } /* initialize Flag and Head */ Common->mark = EMPTY ; CHOLMOD(clear_flag) (Common) ; Head = Common->Head ; for (i = 0 ; i <= (Int) (nrow) ; i++) { Head [i] = EMPTY ; } } /* ---------------------------------------------------------------------- */ /* Allocate Iwork (iworksize) */ /* ---------------------------------------------------------------------- */ iworksize = MAX (1, iworksize) ; if (iworksize > Common->iworksize) { if (Common->no_workspace_reallocate) { /* CHOLMOD is not allowed to change the workspace here */ Common->status = CHOLMOD_INVALID ; return (FALSE) ; } /* free the old workspace (if any) and allocate new space. * integer overflow safely detected in cholmod_malloc */ CHOLMOD(free) (Common->iworksize, sizeof (Int), Common->Iwork, Common) ; Common->Iwork = CHOLMOD(malloc) (iworksize, sizeof (Int), Common) ; /* record the new size of Iwork */ Common->iworksize = iworksize ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_work) (Common) ; return (FALSE) ; } /* note that Iwork does not need to be initialized */ } /* ---------------------------------------------------------------------- */ /* Allocate Xwork (xworksize) and set it to ((double) 0.) */ /* ---------------------------------------------------------------------- */ /* make sure xworksize is >= 1 */ xworksize = MAX (1, xworksize) ; if (xworksize > Common->xworksize) { if (Common->no_workspace_reallocate) { /* CHOLMOD is not allowed to change the workspace here */ Common->status = CHOLMOD_INVALID ; return (FALSE) ; } /* free the old workspace (if any) and allocate new space */ CHOLMOD(free) (Common->xworksize, sizeof (double), Common->Xwork, Common) ; Common->Xwork = CHOLMOD(malloc) (xworksize, sizeof (double), Common) ; /* record the new size of Xwork */ Common->xworksize = xworksize ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_work) (Common) ; return (FALSE) ; } /* initialize Xwork */ W = Common->Xwork ; for (i = 0 ; i < (Int) xworksize ; i++) { W [i] = 0. ; } } return (TRUE) ; } /* ========================================================================== */ /* === cholmod_free_work ==================================================== */ /* ========================================================================== */ /* Deallocate the CHOLMOD workspace. * * workspace: deallocates all workspace in Common */ int CHOLMOD(free_work) ( cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->Flag = CHOLMOD(free) (Common->nrow, sizeof (Int), Common->Flag, Common) ; Common->Head = CHOLMOD(free) (Common->nrow+1, sizeof (Int), Common->Head, Common) ; Common->Iwork = CHOLMOD(free) (Common->iworksize, sizeof (Int), Common->Iwork, Common) ; Common->Xwork = CHOLMOD(free) (Common->xworksize, sizeof (double), Common->Xwork, Common) ; Common->nrow = 0 ; Common->iworksize = 0 ; Common->xworksize = 0 ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_clear_flag =================================================== */ /* ========================================================================== */ /* Increment mark to ensure Flag [0..nrow-1] < mark. If integer overflow * occurs, or mark was initially negative, reset the entire array. This is * not an error condition, but an intended function of the Flag workspace. * * workspace: Flag (nrow). Does not modify Flag if nrow is zero. */ SuiteSparse_long CHOLMOD(clear_flag) ( cholmod_common *Common ) { Int i, nrow, *Flag ; RETURN_IF_NULL_COMMON (-1) ; Common->mark++ ; if (Common->mark <= 0) { nrow = Common->nrow ; Flag = Common->Flag ; PRINT2 (("reset Flag: nrow "ID"\n", nrow)) ; PRINT2 (("reset Flag: mark %ld\n", Common->mark)) ; for (i = 0 ; i < nrow ; i++) { Flag [i] = EMPTY ; } Common->mark = 0 ; } return (Common->mark) ; } /* ========================================================================== */ /* ==== cholmod_maxrank ===================================================== */ /* ========================================================================== */ /* Find a valid value of Common->maxrank. Returns 0 if error, or 2, 4, or 8 * if successful. */ size_t CHOLMOD(maxrank) /* returns validated value of Common->maxrank */ ( /* ---- input ---- */ size_t n, /* A and L will have n rows */ /* --------------- */ cholmod_common *Common ) { size_t maxrank ; RETURN_IF_NULL_COMMON (0) ; maxrank = Common->maxrank ; if (n > 0) { /* Ensure maxrank*n*sizeof(double) does not result in integer overflow. * If n is so large that 2*n*sizeof(double) results in integer overflow * (n = 268,435,455 if an Int is 32 bits), then maxrank will be 0 or 1, * but maxrank will be set to 2 below. 2*n will not result in integer * overflow, and CHOLMOD will run out of memory or safely detect integer * overflow elsewhere. */ maxrank = MIN (maxrank, Size_max / (n * sizeof (double))) ; } if (maxrank <= 2) { maxrank = 2 ; } else if (maxrank <= 4) { maxrank = 4 ; } else { maxrank = 8 ; } return (maxrank) ; } /* ========================================================================== */ /* === cholmod_dbound ======================================================= */ /* ========================================================================== */ /* Ensure the absolute value of a diagonal entry, D (j,j), is greater than * Common->dbound. This routine is not meant for the user to call. It is used * by the various LDL' factorization and update/downdate routines. The * default value of Common->dbound is zero, and in that case this routine is not * called at all. No change is made if D (j,j) is NaN. CHOLMOD does not call * this routine if Common->dbound is NaN. */ double CHOLMOD(dbound) /* returns modified diagonal entry of D */ ( /* ---- input ---- */ double dj, /* diagonal entry of D, for LDL' factorization */ /* --------------- */ cholmod_common *Common ) { double dbound ; RETURN_IF_NULL_COMMON (0) ; if (!IS_NAN (dj)) { dbound = Common->dbound ; if (dj < 0) { if (dj > -dbound) { dj = -dbound ; Common->ndbounds_hit++ ; if (Common->status == CHOLMOD_OK) { ERROR (CHOLMOD_DSMALL, "diagonal below threshold") ; } } } else { if (dj < dbound) { dj = dbound ; Common->ndbounds_hit++ ; if (Common->status == CHOLMOD_OK) { ERROR (CHOLMOD_DSMALL, "diagonal below threshold") ; } } } } return (dj) ; } igraph/src/CHOLMOD/Core/cholmod_aat.c0000644000175100001440000002071513431000472016723 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_aat ===================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* C = A*A' or C = A(:,f)*A(:,f)' * * A can be packed or unpacked, sorted or unsorted, but must be stored with * both upper and lower parts (A->stype of zero). C is returned as packed, * C->stype of zero (both upper and lower parts present), and unsorted. See * cholmod_ssmult in the MatrixOps Module for a more general matrix-matrix * multiply. * * You can trivially convert C into a symmetric upper/lower matrix by * changing C->stype = 1 or -1 after calling this routine. * * workspace: * Flag (A->nrow), * Iwork (max (A->nrow, A->ncol)) if fset present, * Iwork (A->nrow) if no fset, * W (A->nrow) if mode > 0, * allocates temporary copy for A'. * * A can be pattern or real. Complex or zomplex cases are supported only * if the mode is <= 0 (in which case the numerical values are ignored). */ #include "cholmod_internal.h" #include "cholmod_core.h" cholmod_sparse *CHOLMOD(aat) ( /* ---- input ---- */ cholmod_sparse *A, /* input matrix; C=A*A' is constructed */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) * -2: pattern only, no diagonal, add 50% + n extra * space to C */ /* --------------- */ cholmod_common *Common ) { double fjt ; double *Ax, *Fx, *Cx, *W ; Int *Ap, *Anz, *Ai, *Fp, *Fi, *Cp, *Ci, *Flag ; cholmod_sparse *C, *F ; Int packed, j, i, pa, paend, pf, pfend, n, mark, cnz, t, p, values, diag, extra ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; values = (mode > 0) && (A->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->stype) { ERROR (CHOLMOD_INVALID, "matrix cannot be symmetric") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ diag = (mode >= 0) ; n = A->nrow ; CHOLMOD(allocate_work) (n, MAX (A->ncol, A->nrow), values ? n : 0, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n : 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (A, "A", Common) >= 0) ; /* get the A matrix */ Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; packed = A->packed ; /* get workspace */ W = Common->Xwork ; /* size n, unused if values is FALSE */ Flag = Common->Flag ; /* size n, Flag [0..n-1] < mark on input*/ /* ---------------------------------------------------------------------- */ /* F = A' or A(:,f)' */ /* ---------------------------------------------------------------------- */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ F = CHOLMOD(ptranspose) (A, values, NULL, fset, fsize, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } Fp = F->p ; Fi = F->i ; Fx = F->x ; /* ---------------------------------------------------------------------- */ /* count the number of entries in the result C */ /* ---------------------------------------------------------------------- */ cnz = 0 ; for (j = 0 ; j < n ; j++) { /* clear the Flag array */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* exclude the diagonal, if requested */ if (!diag) { Flag [j] = mark ; } /* for each nonzero F(t,j) in column j, do: */ pfend = Fp [j+1] ; for (pf = Fp [j] ; pf < pfend ; pf++) { /* F(t,j) is nonzero */ t = Fi [pf] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) */ pa = Ap [t] ; paend = (packed) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; cnz++ ; } } } if (cnz < 0) { break ; /* integer overflow case */ } } extra = (mode == -2) ? (cnz/2 + n) : 0 ; mark = CHOLMOD(clear_flag) (Common) ; /* ---------------------------------------------------------------------- */ /* check for integer overflow */ /* ---------------------------------------------------------------------- */ if (cnz < 0 || (cnz + extra) < 0) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; CHOLMOD(clear_flag) (Common) ; CHOLMOD(free_sparse) (&F, Common) ; return (NULL) ; /* problem too large */ } /* ---------------------------------------------------------------------- */ /* allocate C */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_sparse) (n, n, cnz + extra, FALSE, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&F, Common) ; return (NULL) ; /* out of memory */ } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* C = A*A' */ /* ---------------------------------------------------------------------- */ cnz = 0 ; if (values) { /* pattern and values */ for (j = 0 ; j < n ; j++) { /* clear the Flag array */ mark = CHOLMOD(clear_flag) (Common) ; /* start column j of C */ Cp [j] = cnz ; /* for each nonzero F(t,j) in column j, do: */ pfend = Fp [j+1] ; for (pf = Fp [j] ; pf < pfend ; pf++) { /* F(t,j) is nonzero */ t = Fi [pf] ; fjt = Fx [pf] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) * and scatter the values into W */ pa = Ap [t] ; paend = (packed) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; Ci [cnz++] = i ; } W [i] += Ax [pa] * fjt ; } } /* gather the values into C(:,j) */ for (p = Cp [j] ; p < cnz ; p++) { i = Ci [p] ; Cx [p] = W [i] ; W [i] = 0 ; } } } else { /* pattern only */ for (j = 0 ; j < n ; j++) { /* clear the Flag array */ mark = CHOLMOD(clear_flag) (Common) ; /* exclude the diagonal, if requested */ if (!diag) { Flag [j] = mark ; } /* start column j of C */ Cp [j] = cnz ; /* for each nonzero F(t,j) in column j, do: */ pfend = Fp [j+1] ; for (pf = Fp [j] ; pf < pfend ; pf++) { /* F(t,j) is nonzero */ t = Fi [pf] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) */ pa = Ap [t] ; paend = (packed) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; Ci [cnz++] = i ; } } } } } Cp [n] = cnz ; ASSERT (IMPLIES (mode != -2, MAX (1,cnz) == C->nzmax)) ; /* ---------------------------------------------------------------------- */ /* clear workspace and free temporary matrices and return result */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&F, Common) ; CHOLMOD(clear_flag) (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n : 0, Common)) ; DEBUG (i = CHOLMOD(dump_sparse) (C, "aat", Common)) ; ASSERT (IMPLIES (mode < 0, i == 0)) ; return (C) ; } igraph/src/CHOLMOD/Core/cholmod_complex.c0000644000175100001440000003775113431000472017635 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_complex ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* If you convert a matrix that contains uninitialized data, valgrind will * complain. This can occur in a factor L which has gaps (a partial * factorization, or after updates that change the nonzero pattern), an * unpacked sparse matrix, a dense matrix with leading dimension d > # of rows, * or any matrix (dense, sparse, triplet, or factor) with more space allocated * than is used. You can safely ignore any of these complaints by valgrind. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === cholmod_hypot ======================================================== */ /* ========================================================================== */ /* There is an equivalent routine called hypot in , which conforms * to ANSI C99. However, CHOLMOD does not assume that ANSI C99 is available. * You can use the ANSI C99 hypot routine with: * * #include * Common->hypotenuse = hypot ; * * Default value of the Common->hypotenuse pointer is cholmod_hypot. * * s = hypot (x,y) computes s = sqrt (x*x + y*y) but does so more accurately. * The NaN cases for the double relops x >= y and x+y == x are safely ignored. * * Source: Algorithm 312, "Absolute value and square root of a complex number," * P. Friedland, Comm. ACM, vol 10, no 10, October 1967, page 665. */ double CHOLMOD(hypot) (double x, double y) { double s, r ; x = fabs (x) ; y = fabs (y) ; if (x >= y) { if (x + y == x) { s = x ; } else { r = y / x ; s = x * sqrt (1.0 + r*r) ; } } else { if (y + x == y) { s = y ; } else { r = x / y ; s = y * sqrt (1.0 + r*r) ; } } return (s) ; } /* ========================================================================== */ /* === cholmod_divcomplex =================================================== */ /* ========================================================================== */ /* c = a/b where c, a, and b are complex. The real and imaginary parts are * passed as separate arguments to this routine. The NaN case is ignored * for the double relop br >= bi. Returns 1 if the denominator is zero, * 0 otherwise. Note that this return value is the single exception to the * rule that all CHOLMOD routines that return int return TRUE if successful * or FALSE otherise. * * This uses ACM Algo 116, by R. L. Smith, 1962, which tries to avoid * underflow and overflow. * * c can be the same variable as a or b. * * Default value of the Common->complex_divide pointer is cholmod_divcomplex. */ int CHOLMOD(divcomplex) ( double ar, double ai, /* real and imaginary parts of a */ double br, double bi, /* real and imaginary parts of b */ double *cr, double *ci /* real and imaginary parts of c */ ) { double tr, ti, r, den ; if (fabs (br) >= fabs (bi)) { r = bi / br ; den = br + r * bi ; tr = (ar + ai * r) / den ; ti = (ai - ar * r) / den ; } else { r = br / bi ; den = r * br + bi ; tr = (ar * r + ai) / den ; ti = (ai * r - ar) / den ; } *cr = tr ; *ci = ti ; return (IS_ZERO (den)) ; } /* ========================================================================== */ /* === change_complexity ==================================================== */ /* ========================================================================== */ /* X and Z represent an array of size nz, with numeric xtype given by xtype_in. * * If xtype_in is: * CHOLMOD_PATTERN: X and Z must be NULL. * CHOLMOD_REAL: X is of size nz, Z must be NULL. * CHOLMOD_COMPLEX: X is of size 2*nz, Z must be NULL. * CHOLMOD_ZOMPLEX: X is of size nz, Z is of size nz. * * The array is changed into the numeric xtype given by xtype_out, with the * same definitions of X and Z above. Note that the input conditions, above, * are not checked. These are checked in the caller routine. * * Returns TRUE if successful, FALSE otherwise. X and Z are not modified if * not successful. */ static int change_complexity ( /* ---- input ---- */ Int nz, /* size of X and/or Z */ int xtype_in, /* xtype of X and Z on input */ int xtype_out, /* requested xtype of X and Z on output */ int xtype1, /* xtype_out must be in the range [xtype1 .. xtype2] */ int xtype2, /* ---- in/out --- */ void **XX, /* old X on input, new X on output */ void **ZZ, /* old Z on input, new Z on output */ /* --------------- */ cholmod_common *Common ) { double *Xold, *Zold, *Xnew, *Znew ; Int k ; size_t nz2 ; if (xtype_out < xtype1 || xtype_out > xtype2) { ERROR (CHOLMOD_INVALID, "invalid xtype") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; Xold = *XX ; Zold = *ZZ ; switch (xtype_in) { /* ------------------------------------------------------------------ */ /* converting from pattern */ /* ------------------------------------------------------------------ */ case CHOLMOD_PATTERN: switch (xtype_out) { /* ---------------------------------------------------------- */ /* pattern -> real */ /* ---------------------------------------------------------- */ case CHOLMOD_REAL: /* allocate X and set to all ones */ Xnew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [k] = 1 ; } *XX = Xnew ; break ; /* ---------------------------------------------------------- */ /* pattern -> complex */ /* ---------------------------------------------------------- */ case CHOLMOD_COMPLEX: /* allocate X and set to all ones */ Xnew = CHOLMOD(malloc) (nz, 2*sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [2*k ] = 1 ; Xnew [2*k+1] = 0 ; } *XX = Xnew ; break ; /* ---------------------------------------------------------- */ /* pattern -> zomplex */ /* ---------------------------------------------------------- */ case CHOLMOD_ZOMPLEX: /* allocate X and Z and set to all ones */ Xnew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; Znew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (nz, sizeof (double), Xnew, Common) ; CHOLMOD(free) (nz, sizeof (double), Znew, Common) ; return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [k] = 1 ; Znew [k] = 0 ; } *XX = Xnew ; *ZZ = Znew ; break ; } break ; /* ------------------------------------------------------------------ */ /* converting from real */ /* ------------------------------------------------------------------ */ case CHOLMOD_REAL: switch (xtype_out) { /* ---------------------------------------------------------- */ /* real -> pattern */ /* ---------------------------------------------------------- */ case CHOLMOD_PATTERN: /* free X */ *XX = CHOLMOD(free) (nz, sizeof (double), *XX, Common) ; break ; /* ---------------------------------------------------------- */ /* real -> complex */ /* ---------------------------------------------------------- */ case CHOLMOD_COMPLEX: /* allocate a new X and copy the old X */ Xnew = CHOLMOD(malloc) (nz, 2*sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [2*k ] = Xold [k] ; Xnew [2*k+1] = 0 ; } CHOLMOD(free) (nz, sizeof (double), *XX, Common) ; *XX = Xnew ; break ; /* ---------------------------------------------------------- */ /* real -> zomplex */ /* ---------------------------------------------------------- */ case CHOLMOD_ZOMPLEX: /* allocate a new Z and set it to zero */ Znew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Znew [k] = 0 ; } *ZZ = Znew ; break ; } break ; /* ------------------------------------------------------------------ */ /* converting from complex */ /* ------------------------------------------------------------------ */ case CHOLMOD_COMPLEX: switch (xtype_out) { /* ---------------------------------------------------------- */ /* complex -> pattern */ /* ---------------------------------------------------------- */ case CHOLMOD_PATTERN: /* free X */ *XX = CHOLMOD(free) (nz, 2*sizeof (double), *XX, Common) ; break ; /* ---------------------------------------------------------- */ /* complex -> real */ /* ---------------------------------------------------------- */ case CHOLMOD_REAL: /* pack the real part of X, discarding the imaginary part */ for (k = 0 ; k < nz ; k++) { Xold [k] = Xold [2*k] ; } /* shrink X in half (this cannot fail) */ nz2 = 2*nz ; *XX = CHOLMOD(realloc) (nz, sizeof (double), *XX, &nz2, Common) ; break ; /* ---------------------------------------------------------- */ /* complex -> zomplex */ /* ---------------------------------------------------------- */ case CHOLMOD_ZOMPLEX: /* allocate X and Z and copy the old X into them */ Xnew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; Znew = CHOLMOD(malloc) (nz, sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (nz, sizeof (double), Xnew, Common) ; CHOLMOD(free) (nz, sizeof (double), Znew, Common) ; return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [k] = Xold [2*k ] ; Znew [k] = Xold [2*k+1] ; } CHOLMOD(free) (nz, 2*sizeof (double), *XX, Common) ; *XX = Xnew ; *ZZ = Znew ; break ; } break ; /* ------------------------------------------------------------------ */ /* converting from zomplex */ /* ------------------------------------------------------------------ */ case CHOLMOD_ZOMPLEX: switch (xtype_out) { /* ---------------------------------------------------------- */ /* zomplex -> pattern */ /* ---------------------------------------------------------- */ case CHOLMOD_PATTERN: /* free X and Z */ *XX = CHOLMOD(free) (nz, sizeof (double), *XX, Common) ; *ZZ = CHOLMOD(free) (nz, sizeof (double), *ZZ, Common) ; break ; /* ---------------------------------------------------------- */ /* zomplex -> real */ /* ---------------------------------------------------------- */ case CHOLMOD_REAL: /* free the imaginary part */ *ZZ = CHOLMOD(free) (nz, sizeof (double), *ZZ, Common) ; break ; /* ---------------------------------------------------------- */ /* zomplex -> complex */ /* ---------------------------------------------------------- */ case CHOLMOD_COMPLEX: Xnew = CHOLMOD(malloc) (nz, 2*sizeof (double), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } for (k = 0 ; k < nz ; k++) { Xnew [2*k ] = Xold [k] ; Xnew [2*k+1] = Zold [k] ; } CHOLMOD(free) (nz, sizeof (double), *XX, Common) ; CHOLMOD(free) (nz, sizeof (double), *ZZ, Common) ; *XX = Xnew ; *ZZ = NULL ; break ; } break ; } return (TRUE) ; } /* ========================================================================== */ /* === cholmod_sparse_xtype ================================================= */ /* ========================================================================== */ /* Change the numeric xtype of a sparse matrix. Supports any type on input * and output (pattern, real, complex, or zomplex). */ int CHOLMOD(sparse_xtype) ( /* ---- input ---- */ int to_xtype, /* requested xtype */ /* ---- in/out --- */ cholmod_sparse *A, /* sparse matrix to change */ /* --------------- */ cholmod_common *Common ) { Int ok ; RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; ok = change_complexity (A->nzmax, A->xtype, to_xtype, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, &(A->x), &(A->z), Common) ; if (ok) { A->xtype = to_xtype ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_triplet_xtype ================================================ */ /* ========================================================================== */ /* Change the numeric xtype of a triplet matrix. Supports any type on input * and output (pattern, real, complex, or zomplex). */ int CHOLMOD(triplet_xtype) ( /* ---- input ---- */ int to_xtype, /* requested xtype */ /* ---- in/out --- */ cholmod_triplet *T, /* triplet matrix to change */ /* --------------- */ cholmod_common *Common ) { Int ok ; RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (T, FALSE) ; RETURN_IF_XTYPE_INVALID (T, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; ok = change_complexity (T->nzmax, T->xtype, to_xtype, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, &(T->x), &(T->z), Common) ; if (ok) { T->xtype = to_xtype ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_dense_xtype ================================================= */ /* ========================================================================== */ /* Change the numeric xtype of a dense matrix. Supports real, complex or * zomplex on input and output */ int CHOLMOD(dense_xtype) ( /* ---- input ---- */ int to_xtype, /* requested xtype */ /* ---- in/out --- */ cholmod_dense *X, /* dense matrix to change */ /* --------------- */ cholmod_common *Common ) { Int ok ; RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (X, FALSE) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; ok = change_complexity (X->nzmax, X->xtype, to_xtype, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, &(X->x), &(X->z), Common) ; if (ok) { X->xtype = to_xtype ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_factor_xtype ================================================= */ /* ========================================================================== */ /* Change the numeric xtype of a factor. Supports real, complex or zomplex on * input and output. Supernodal zomplex factors are not supported. */ int CHOLMOD(factor_xtype) ( /* ---- input ---- */ int to_xtype, /* requested xtype */ /* ---- in/out --- */ cholmod_factor *L, /* factor to change */ /* --------------- */ cholmod_common *Common ) { Int ok ; RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; if (L->is_super && (L->xtype == CHOLMOD_ZOMPLEX || to_xtype == CHOLMOD_ZOMPLEX)) { ERROR (CHOLMOD_INVALID, "invalid xtype for supernodal L") ; return (FALSE) ; } ok = change_complexity ((L->is_super ? L->xsize : L->nzmax), L->xtype, to_xtype, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, &(L->x), &(L->z), Common) ; if (ok) { L->xtype = to_xtype ; } return (ok) ; } igraph/src/CHOLMOD/Core/lesser.txt0000644000175100001440000006350013430770173016355 0ustar hornikusers GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! igraph/src/CHOLMOD/Core/t_cholmod_transpose.c0000644000175100001440000002124413431000472020515 0ustar hornikusers/* ========================================================================== */ /* === Core/t_cholmod_transpose ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine for cholmod_transpose. All xtypes are supported. For * complex matrices, either the array tranpose or complex conjugate transpose * can be computed. */ #include "cholmod_template.h" /* ========================================================================== */ /* === t_cholmod_transpose_unsym ============================================ */ /* ========================================================================== */ /* Compute F = A', A (:,f)', or A (p,f)', where A is unsymmetric and F is * already allocated. The complex case performs either the array transpose * or complex conjugate transpose. * * workspace: * Iwork (MAX (nrow,ncol)) if fset is present * Iwork (nrow) if fset is NULL */ static int TEMPLATE (cholmod_transpose_unsym) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ Int *Perm, /* size nrow, if present (can be NULL) */ Int *fset, /* subset of 0:(A->ncol)-1 */ Int nf, /* size of fset */ /* ---- output --- */ cholmod_sparse *F, /* F = A', A(:,f)', or A(p,f)' */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Az, *Fx, *Fz ; Int *Ap, *Anz, *Ai, *Fp, *Fnz, *Fj, *Wi, *Iwork ; Int j, p, pend, nrow, ncol, Apacked, use_fset, fp, Fpacked, jj, permute ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ /* ensure the xtype of A and F match (ignored if this is pattern version) */ if (!XTYPE_OK (A->xtype)) { ERROR (CHOLMOD_INVALID, "real/complex mismatch") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ use_fset = (fset != NULL) ; nrow = A->nrow ; ncol = A->ncol ; Ap = A->p ; /* size A->ncol+1, column pointers of A */ Ai = A->i ; /* size nz = Ap [A->ncol], row indices of A */ Ax = A->x ; /* size nz, real values of A */ Az = A->z ; /* size nz, imag values of A */ Anz = A->nz ; Apacked = A->packed ; ASSERT (IMPLIES (!Apacked, Anz != NULL)) ; permute = (Perm != NULL) ; Fp = F->p ; /* size A->nrow+1, row pointers of F */ Fj = F->i ; /* size nz, column indices of F */ Fx = F->x ; /* size nz, real values of F */ Fz = F->z ; /* size nz, imag values of F */ Fnz = F->nz ; Fpacked = F->packed ; ASSERT (IMPLIES (!Fpacked, Fnz != NULL)) ; nf = (use_fset) ? nf : ncol ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Wi = Iwork ; /* size nrow (i/l/l) */ /* ---------------------------------------------------------------------- */ /* construct the transpose */ /* ---------------------------------------------------------------------- */ for (jj = 0 ; jj < nf ; jj++) { j = (use_fset) ? (fset [jj]) : jj ; p = Ap [j] ; pend = (Apacked) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { fp = Wi [Ai [p]]++ ; Fj [fp] = j ; #ifdef NCONJUGATE ASSIGN (Fx, Fz, fp, Ax, Az, p) ; #else ASSIGN_CONJ (Fx, Fz, fp, Ax, Az, p) ; #endif } } return (TRUE) ; } /* ========================================================================== */ /* === t_cholmod_transpose_sym ============================================== */ /* ========================================================================== */ /* Compute F = A' or A (p,p)', where A is symmetric and F is already allocated. * The complex case performs either the array transpose or complex conjugate * transpose. * * workspace: Iwork (nrow) if Perm NULL, Iwork (2*nrow) if Perm non-NULL. */ static int TEMPLATE (cholmod_transpose_sym) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ Int *Perm, /* size n, if present (can be NULL) */ /* ---- output --- */ cholmod_sparse *F, /* F = A' or A(p,p)' */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Az, *Fx, *Fz ; Int *Ap, *Anz, *Ai, *Fp, *Fj, *Wi, *Pinv, *Iwork ; Int p, pend, packed, fp, upper, permute, jold, n, i, j, iold ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ /* ensure the xtype of A and F match (ignored if this is pattern version) */ if (!XTYPE_OK (A->xtype)) { ERROR (CHOLMOD_INVALID, "real/complex mismatch") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ permute = (Perm != NULL) ; n = A->nrow ; Ap = A->p ; /* size A->ncol+1, column pointers of A */ Ai = A->i ; /* size nz = Ap [A->ncol], row indices of A */ Ax = A->x ; /* size nz, real values of A */ Az = A->z ; /* size nz, imag values of A */ Anz = A->nz ; packed = A->packed ; ASSERT (IMPLIES (!packed, Anz != NULL)) ; upper = (A->stype > 0) ; Fp = F->p ; /* size A->nrow+1, row pointers of F */ Fj = F->i ; /* size nz, column indices of F */ Fx = F->x ; /* size nz, real values of F */ Fz = F->z ; /* size nz, imag values of F */ /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Wi = Iwork ; /* size n (i/l/l) */ Pinv = Iwork + n ; /* size n (i/i/l) , unused if Perm NULL */ /* ---------------------------------------------------------------------- */ /* construct the transpose */ /* ---------------------------------------------------------------------- */ if (permute) { if (upper) { /* permuted, upper */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; p = Ap [jold] ; pend = (packed) ? Ap [jold+1] : p + Anz [jold] ; for ( ; p < pend ; p++) { iold = Ai [p] ; if (iold <= jold) { i = Pinv [iold] ; if (i < j) { fp = Wi [i]++ ; Fj [fp] = j ; #ifdef NCONJUGATE ASSIGN (Fx, Fz, fp, Ax, Az, p) ; #else ASSIGN_CONJ (Fx, Fz, fp, Ax, Az, p) ; #endif } else { fp = Wi [j]++ ; Fj [fp] = i ; ASSIGN (Fx, Fz, fp, Ax, Az, p) ; } } } } } else { /* permuted, lower */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; p = Ap [jold] ; pend = (packed) ? Ap [jold+1] : p + Anz [jold] ; for ( ; p < pend ; p++) { iold = Ai [p] ; if (iold >= jold) { i = Pinv [iold] ; if (i > j) { fp = Wi [i]++ ; Fj [fp] = j ; #ifdef NCONJUGATE ASSIGN (Fx, Fz, fp, Ax, Az, p) ; #else ASSIGN_CONJ (Fx, Fz, fp, Ax, Az, p) ; #endif } else { fp = Wi [j]++ ; Fj [fp] = i ; ASSIGN (Fx, Fz, fp, Ax, Az, p) ; } } } } } } else { if (upper) { /* unpermuted, upper */ for (j = 0 ; j < n ; j++) { p = Ap [j] ; pend = (packed) ? Ap [j+1] : p + Anz [j] ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i <= j) { fp = Wi [i]++ ; Fj [fp] = j ; #ifdef NCONJUGATE ASSIGN (Fx, Fz, fp, Ax, Az, p) ; #else ASSIGN_CONJ (Fx, Fz, fp, Ax, Az, p) ; #endif } } } } else { /* unpermuted, lower */ for (j = 0 ; j < n ; j++) { p = Ap [j] ; pend = (packed) ? Ap [j+1] : p + Anz [j] ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= j) { fp = Wi [i]++ ; Fj [fp] = j ; #ifdef NCONJUGATE ASSIGN (Fx, Fz, fp, Ax, Az, p) ; #else ASSIGN_CONJ (Fx, Fz, fp, Ax, Az, p) ; #endif } } } } } return (TRUE) ; } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX #undef NCONJUGATE igraph/src/CHOLMOD/Core/cholmod_version.c0000644000175100001440000000262113431000472017637 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_version ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2013, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Return the current version of CHOLMOD. Unlike all other functions in CHOLMOD, this function does not require the CHOLMOD Common. */ #include "cholmod_internal.h" #include "cholmod_core.h" int CHOLMOD(version) /* returns CHOLMOD_VERSION */ ( /* output, contents not defined on input. Not used if NULL. version [0] = CHOLMOD_MAIN_VERSION ; version [1] = CHOLMOD_SUB_VERSION ; version [2] = CHOLMOD_SUBSUB_VERSION ; */ int version [3] ) { if (version != NULL) { version [0] = CHOLMOD_MAIN_VERSION ; version [1] = CHOLMOD_SUB_VERSION ; version [2] = CHOLMOD_SUBSUB_VERSION ; } return (CHOLMOD_VERSION) ; } igraph/src/CHOLMOD/Core/t_cholmod_triplet.c0000644000175100001440000001110313431000472020153 0ustar hornikusers/* ========================================================================== */ /* === Core/t_cholmod_triplet =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine for cholmod_triplet. All xtypes supported */ #include "cholmod_template.h" /* ========================================================================== */ /* === t_cholmod_triplet_to_sparse ========================================== */ /* ========================================================================== */ static size_t TEMPLATE (cholmod_triplet_to_sparse) ( /* ---- input ---- */ cholmod_triplet *T, /* matrix to copy */ /* ---- in/out --- */ cholmod_sparse *R, /* output matrix */ /* --------------- */ cholmod_common *Common ) { double *Rx, *Rz, *Tx, *Tz ; Int *Wj, *Rp, *Ri, *Rnz, *Ti, *Tj ; Int i, j, p, p1, p2, pdest, pj, k, stype, nrow, ncol, nz ; size_t anz ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* Wj contains a copy of Rp on input [ */ Wj = Common->Iwork ; /* size MAX (nrow,ncol). (i/l/l) */ Rp = R->p ; Ri = R->i ; Rnz = R->nz ; Rx = R->x ; Rz = R->z ; Ti = T->i ; Tj = T->j ; Tx = T->x ; Tz = T->z ; nz = T->nnz ; nrow = T->nrow ; ncol = T->ncol ; stype = SIGN (T->stype) ; /* ---------------------------------------------------------------------- */ /* construct the row form */ /* ---------------------------------------------------------------------- */ /* if Ti is jumbled, this part dominates the run time */ if (stype > 0) { for (k = 0 ; k < nz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i < j) { /* place triplet (j,i,x) in column i of R */ p = Wj [i]++ ; Ri [p] = j ; } else { /* place triplet (i,j,x) in column j of R */ p = Wj [j]++ ; Ri [p] = i ; } ASSIGN (Rx, Rz, p, Tx, Tz, k) ; } } else if (stype < 0) { for (k = 0 ; k < nz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i > j) { /* place triplet (j,i,x) in column i of R */ p = Wj [i]++ ; Ri [p] = j ; } else { /* place triplet (i,j,x) in column j of R */ p = Wj [j]++ ; Ri [p] = i ; } ASSIGN (Rx, Rz, p, Tx, Tz, k) ; } } else { for (k = 0 ; k < nz ; k++) { /* place triplet (i,j,x) in column i of R */ p = Wj [Ti [k]]++ ; Ri [p] = Tj [k] ; ASSIGN (Rx, Rz, p, Tx, Tz, k) ; } } /* done using Wj (i/l/l) as temporary row pointers ] */ /* ---------------------------------------------------------------------- */ /* sum up duplicates */ /* ---------------------------------------------------------------------- */ /* use Wj (i/l/l) of size ncol to keep track of duplicates in each row [ */ for (j = 0 ; j < ncol ; j++) { Wj [j] = EMPTY ; } anz = 0 ; for (i = 0 ; i < nrow ; i++) { p1 = Rp [i] ; p2 = Rp [i+1] ; pdest = p1 ; /* at this point Wj [j] < p1 holds true for all columns j, because * Ri/Rx is stored in row oriented manner */ for (p = p1 ; p < p2 ; p++) { j = Ri [p] ; pj = Wj [j] ; if (pj >= p1) { /* this column index j is already in row i at position pj; * sum up the duplicate entry */ /* Rx [pj] += Rx [p] ; */ ASSEMBLE (Rx, Rz, pj, Rx, Rz, p) ; } else { /* keep the entry and keep track in Wj [j] for case above */ Wj [j] = pdest ; if (pdest != p) { Ri [pdest] = j ; ASSIGN (Rx, Rz, pdest, Rx, Rz, p) ; } pdest++ ; } } Rnz [i] = pdest - p1 ; anz += (pdest - p1) ; } /* done using Wj to keep track of duplicate entries in each row ] */ /* ---------------------------------------------------------------------- */ /* return number of entries after summing up duplicates */ /* ---------------------------------------------------------------------- */ return (anz) ; } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Core/cholmod_sparse.c0000644000175100001440000004277213431000472017462 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_sparse ================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_sparse object: * * A sparse matrix is held in compressed column form. In the basic type * ("packed", which corresponds to a MATLAB sparse matrix), an n-by-n matrix * with nz entries is held in three arrays: p of size n+1, i of size nz, and x * of size nz. Row indices of column j are held in i [p [j] ... p [j+1]-1] and * in the same locations in x. There may be no duplicate entries in a column. * Row indices in each column may be sorted or unsorted (CHOLMOD keeps track). * * Primary routines: * ----------------- * cholmod_allocate_sparse allocate a sparse matrix * cholmod_free_sparse free a sparse matrix * * Secondary routines: * ------------------- * cholmod_reallocate_sparse change the size (# entries) of sparse matrix * cholmod_nnz number of nonzeros in a sparse matrix * cholmod_speye sparse identity matrix * cholmod_spzeros sparse zero matrix * cholmod_copy_sparse create a copy of a sparse matrix * * All xtypes are supported (pattern, real, complex, and zomplex) */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === cholmod_allocate_sparse ============================================== */ /* ========================================================================== */ /* Allocate space for a matrix. A->i and A->x are not initialized. A->p * (and A->nz if A is not packed) are set to zero, so a matrix containing no * entries (all zero) is returned. See also cholmod_spzeros. * * workspace: none */ cholmod_sparse *CHOLMOD(allocate_sparse) ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ size_t nzmax, /* max # of nonzeros of A */ int sorted, /* TRUE if columns of A sorted, FALSE otherwise */ int packed, /* TRUE if A will be packed, FALSE otherwise */ int stype, /* stype of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *A ; Int *Ap, *Anz ; size_t nzmax0 ; Int j ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; if (stype != 0 && nrow != ncol) { ERROR (CHOLMOD_INVALID, "rectangular matrix with stype != 0 invalid") ; return (NULL) ; } if (xtype < CHOLMOD_PATTERN || xtype > CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "xtype invalid") ; return (NULL) ; } /* ensure the dimensions do not cause integer overflow */ (void) CHOLMOD(add_size_t) (ncol, 2, &ok) ; if (!ok || nrow > Int_max || ncol > Int_max || nzmax > Int_max) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate header */ /* ---------------------------------------------------------------------- */ A = CHOLMOD(malloc) (sizeof (cholmod_sparse), 1, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } PRINT1 (("cholmod_allocate_sparse %d-by-%d nzmax %d sorted %d packed %d" " xtype %d\n", nrow, ncol, nzmax, sorted, packed, xtype)) ; nzmax = MAX (1, nzmax) ; A->nrow = nrow ; A->ncol = ncol ; A->nzmax = nzmax ; A->packed = packed ; /* default is packed (A->nz not present) */ A->stype = stype ; A->itype = ITYPE ; A->xtype = xtype ; A->dtype = DTYPE ; A->nz = NULL ; A->p = NULL ; A->i = NULL ; A->x = NULL ; A->z = NULL ; /* A 1-by-m matrix always has sorted columns */ A->sorted = (nrow <= 1) ? TRUE : sorted ; /* ---------------------------------------------------------------------- */ /* allocate the matrix itself */ /* ---------------------------------------------------------------------- */ /* allocate O(ncol) space */ A->p = CHOLMOD(malloc) (((size_t) ncol)+1, sizeof (Int), Common) ; if (!packed) { A->nz = CHOLMOD(malloc) (ncol, sizeof (Int), Common) ; } /* allocate O(nz) space */ nzmax0 = 0 ; CHOLMOD(realloc_multiple) (nzmax, 1, xtype, &(A->i), NULL, &(A->x), &(A->z), &nzmax0, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&A, Common) ; return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* initialize A->p and A->nz so that A is an empty matrix */ /* ---------------------------------------------------------------------- */ Ap = A->p ; for (j = 0 ; j <= (Int) ncol ; j++) { Ap [j] = 0 ; } if (!packed) { Anz = A->nz ; for (j = 0 ; j < (Int) ncol ; j++) { Anz [j] = 0 ; } } return (A) ; } /* ========================================================================== */ /* === cholmod_free_sparse ================================================== */ /* ========================================================================== */ /* free a sparse matrix * * workspace: none */ int CHOLMOD(free_sparse) ( /* ---- in/out --- */ cholmod_sparse **AHandle, /* matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) { Int n, nz ; cholmod_sparse *A ; RETURN_IF_NULL_COMMON (FALSE) ; if (AHandle == NULL) { /* nothing to do */ return (TRUE) ; } A = *AHandle ; if (A == NULL) { /* nothing to do */ return (TRUE) ; } n = A->ncol ; nz = A->nzmax ; A->p = CHOLMOD(free) (n+1, sizeof (Int), A->p, Common) ; A->i = CHOLMOD(free) (nz, sizeof (Int), A->i, Common) ; A->nz = CHOLMOD(free) (n, sizeof (Int), A->nz, Common) ; switch (A->xtype) { case CHOLMOD_REAL: A->x = CHOLMOD(free) (nz, sizeof (double), A->x, Common) ; break ; case CHOLMOD_COMPLEX: A->x = CHOLMOD(free) (nz, 2*sizeof (double), A->x, Common) ; break ; case CHOLMOD_ZOMPLEX: A->x = CHOLMOD(free) (nz, sizeof (double), A->x, Common) ; A->z = CHOLMOD(free) (nz, sizeof (double), A->z, Common) ; break ; } *AHandle = CHOLMOD(free) (1, sizeof (cholmod_sparse), (*AHandle), Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_reallocate_sparse ============================================ */ /* ========================================================================== */ /* Change the size of A->i, A->x, and A->z, or allocate them if their current * size is zero. A->x and A->z are not modified if A->xtype is CHOLMOD_PATTERN. * A->z is not modified unless A->xtype is CHOLMOD_ZOMPLEX. * * workspace: none */ int CHOLMOD(reallocate_sparse) ( /* ---- input ---- */ size_t nznew, /* new # of entries in A */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to reallocate */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; PRINT1 (("realloc matrix %d to %d, xtype: %d\n", A->nzmax, nznew, A->xtype)) ; /* ---------------------------------------------------------------------- */ /* resize the matrix */ /* ---------------------------------------------------------------------- */ CHOLMOD(realloc_multiple) (MAX (1,nznew), 1, A->xtype, &(A->i), NULL, &(A->x), &(A->z), &(A->nzmax), Common) ; return (Common->status == CHOLMOD_OK) ; } /* ========================================================================== */ /* === cholmod_speye ======================================================== */ /* ========================================================================== */ /* Return a sparse identity matrix. */ cholmod_sparse *CHOLMOD(speye) ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Az ; cholmod_sparse *A ; Int *Ap, *Ai ; Int j, n ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate the matrix */ /* ---------------------------------------------------------------------- */ n = MIN (nrow, ncol) ; A = CHOLMOD(allocate_sparse) (nrow, ncol, n, TRUE, TRUE, 0, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory or inputs invalid */ } /* ---------------------------------------------------------------------- */ /* create the identity matrix */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; for (j = 0 ; j < n ; j++) { Ap [j] = j ; } for (j = n ; j <= ((Int) ncol) ; j++) { Ap [j] = n ; } for (j = 0 ; j < n ; j++) { Ai [j] = j ; } switch (xtype) { case CHOLMOD_REAL: for (j = 0 ; j < n ; j++) { Ax [j] = 1 ; } break ; case CHOLMOD_COMPLEX: for (j = 0 ; j < n ; j++) { Ax [2*j ] = 1 ; Ax [2*j+1] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for (j = 0 ; j < n ; j++) { Ax [j] = 1 ; } for (j = 0 ; j < n ; j++) { Az [j] = 0 ; } break ; } return (A) ; } /* ========================================================================== */ /* === cholmod_spzeros ====================================================== */ /* ========================================================================== */ /* Return a sparse zero matrix. */ cholmod_sparse *CHOLMOD(spzeros) ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ size_t nzmax, /* max # of nonzeros of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate the matrix */ /* ---------------------------------------------------------------------- */ return (CHOLMOD(allocate_sparse) (nrow, ncol, nzmax, TRUE, TRUE, 0, xtype, Common)) ; } /* ========================================================================== */ /* === cholmod_nnz ========================================================== */ /* ========================================================================== */ /* Return the number of entries in a sparse matrix. * * workspace: none * integer overflow cannot occur, since the matrix is already allocated. */ SuiteSparse_long CHOLMOD(nnz) ( /* ---- input ---- */ cholmod_sparse *A, /* --------------- */ cholmod_common *Common ) { Int *Ap, *Anz ; size_t nz ; Int j, ncol ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* return nnz (A) */ /* ---------------------------------------------------------------------- */ ncol = A->ncol ; if (A->packed) { Ap = A->p ; RETURN_IF_NULL (Ap, EMPTY) ; nz = Ap [ncol] ; } else { Anz = A->nz ; RETURN_IF_NULL (Anz, EMPTY) ; nz = 0 ; for (j = 0 ; j < ncol ; j++) { nz += MAX (0, Anz [j]) ; } } return (nz) ; } /* ========================================================================== */ /* === cholmod_copy_sparse ================================================== */ /* ========================================================================== */ /* C = A. Create an exact copy of a sparse matrix, with one exception. * Entries in unused space are not copied (they might not be initialized, * and copying them would cause program checkers such as purify and * valgrind to complain). The xtype of the resulting matrix C is the same as * the xtype of the input matrix A. * * See also Core/cholmod_copy, which copies a matrix with possible changes * in stype, presence of diagonal entries, pattern vs. numerical values, * real and/or imaginary parts, and so on. */ cholmod_sparse *CHOLMOD(copy_sparse) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Cx, *Az, *Cz ; Int *Ap, *Ai, *Anz, *Cp, *Ci, *Cnz ; cholmod_sparse *C ; Int p, pend, j, ncol, packed, nzmax, nz, xtype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; if (A->stype != 0 && A->nrow != A->ncol) { ERROR (CHOLMOD_INVALID, "rectangular matrix with stype != 0 invalid") ; return (NULL) ; } Common->status = CHOLMOD_OK ; ASSERT (CHOLMOD(dump_sparse) (A, "A original", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = A->ncol ; nzmax = A->nzmax ; packed = A->packed ; Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; xtype = A->xtype ; /* ---------------------------------------------------------------------- */ /* allocate the copy */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_sparse) (A->nrow, A->ncol, A->nzmax, A->sorted, A->packed, A->stype, A->xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } Cp = C->p ; Ci = C->i ; Cx = C->x ; Cz = C->z ; Cnz = C->nz ; /* ---------------------------------------------------------------------- */ /* copy the matrix */ /* ---------------------------------------------------------------------- */ for (j = 0 ; j <= ncol ; j++) { Cp [j] = Ap [j] ; } if (packed) { nz = Ap [ncol] ; for (p = 0 ; p < nz ; p++) { Ci [p] = Ai [p] ; } switch (xtype) { case CHOLMOD_REAL: for (p = 0 ; p < nz ; p++) { Cx [p] = Ax [p] ; } break ; case CHOLMOD_COMPLEX: for (p = 0 ; p < 2*nz ; p++) { Cx [p] = Ax [p] ; } break ; case CHOLMOD_ZOMPLEX: for (p = 0 ; p < nz ; p++) { Cx [p] = Ax [p] ; Cz [p] = Az [p] ; } break ; } } else { for (j = 0 ; j < ncol ; j++) { Cnz [j] = Anz [j] ; } switch (xtype) { case CHOLMOD_PATTERN: for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { Ci [p] = Ai [p] ; } } break ; case CHOLMOD_REAL: for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { Ci [p] = Ai [p] ; Cx [p] = Ax [p] ; } } break ; case CHOLMOD_COMPLEX: for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { Ci [p] = Ai [p] ; Cx [2*p ] = Ax [2*p ] ; Cx [2*p+1] = Ax [2*p+1] ; } } break ; case CHOLMOD_ZOMPLEX: for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { Ci [p] = Ai [p] ; Cx [p] = Ax [p] ; Cz [p] = Az [p] ; } } break ; } } /* ---------------------------------------------------------------------- */ /* return the result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (C, "C copy", Common) >= 0) ; return (C) ; } igraph/src/CHOLMOD/Core/cholmod_factor.c0000644000175100001440000006552113431000472017440 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_factor ================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2013, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_factor object: * * The data structure for an LL' or LDL' factorization is too complex to * describe in one sentence. This object can hold the symbolic analysis alone, * or in combination with a "simplicial" (similar to a sparse matrix) or * "supernodal" form of the numerical factorization. Only the routine to free * a factor is primary, since a factor object is created by the factorization * routine (cholmod_factorize). It must be freed with cholmod_free_factor. * * Primary routine: * ---------------- * cholmod_free_factor free a factor * * Secondary routines: * ------------------- * cholmod_allocate_factor allocate a symbolic factor (LL' or LDL') * cholmod_reallocate_factor change the # entries in a factor * cholmod_change_factor change the type of factor (e.g., LDL' to LL') * cholmod_pack_factor pack the columns of a factor * cholmod_reallocate_column resize a single column of a factor * cholmod_factor_to_sparse create a sparse matrix copy of a factor * cholmod_copy_factor create a copy of a factor * * Note that there is no cholmod_sparse_to_factor routine to create a factor * as a copy of a sparse matrix. It could be done, after a fashion, but a * lower triangular sparse matrix would not necessarily have a chordal graph, * which would break the many CHOLMOD routines that rely on this property. * * The cholmod_factor_to_sparse routine is provided so that matrix operations * in the MatrixOps module may be applied to L. Those operations operate on * cholmod_sparse objects, and they are not guaranteed to maintain the chordal * property of L. Such a modified L cannot be safely converted back to a * cholmod_factor object. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === cholmod_allocate_factor ============================================== */ /* ========================================================================== */ /* Allocate a simplicial symbolic factor, with L->Perm and L->ColCount allocated * and initialized to "empty" values (Perm [k] = k, and ColCount[k] = 1). * The integer and numerical parts of L are not allocated. L->xtype is returned * as CHOLMOD_PATTERN and L->is_super are returned as FALSE. L->is_ll is also * returned FALSE, but this may be modified when the matrix is factorized. * * This is sufficient (but far from ideal) for input to cholmod_factorize, * since the simplicial LL' or LDL' factorization (cholmod_rowfac) can * reallocate the columns of L as needed. The primary purpose of this routine * is to allocate space for a symbolic factorization, for the "expert" user to * do his or her own symbolic analysis. The typical user should use * cholmod_analyze instead of this routine. * * workspace: none */ cholmod_factor *CHOLMOD(allocate_factor) ( /* ---- input ---- */ size_t n, /* L is n-by-n */ /* --------------- */ cholmod_common *Common ) { Int j ; Int *Perm, *ColCount ; cholmod_factor *L ; int ok = TRUE ; RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; /* ensure the dimension does not cause integer overflow */ (void) CHOLMOD(add_size_t) (n, 2, &ok) ; if (!ok || n > Int_max) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } L = CHOLMOD(malloc) (sizeof (cholmod_factor), 1, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } L->n = n ; L->is_ll = FALSE ; L->is_super = FALSE ; L->is_monotonic = TRUE ; L->itype = ITYPE ; L->xtype = CHOLMOD_PATTERN ; L->dtype = DTYPE ; /* allocate the purely symbolic part of L */ L->ordering = CHOLMOD_NATURAL ; L->Perm = CHOLMOD(malloc) (n, sizeof (Int), Common) ; L->IPerm = NULL ; /* only created by cholmod_solve2 when needed */ L->ColCount = CHOLMOD(malloc) (n, sizeof (Int), Common) ; /* simplicial part of L is empty */ L->nzmax = 0 ; L->p = NULL ; L->i = NULL ; L->x = NULL ; L->z = NULL ; L->nz = NULL ; L->next = NULL ; L->prev = NULL ; /* supernodal part of L is also empty */ L->nsuper = 0 ; L->ssize = 0 ; L->xsize = 0 ; L->maxesize = 0 ; L->maxcsize = 0 ; L->super = NULL ; L->pi = NULL ; L->px = NULL ; L->s = NULL ; /* L has not been factorized */ L->minor = n ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_factor) (&L, Common) ; return (NULL) ; /* out of memory */ } /* initialize Perm and ColCount */ Perm = L->Perm ; for (j = 0 ; j < ((Int) n) ; j++) { Perm [j] = j ; } ColCount = L->ColCount ; for (j = 0 ; j < ((Int) n) ; j++) { ColCount [j] = 1 ; } return (L) ; } /* ========================================================================== */ /* === cholmod_free_factor ================================================== */ /* ========================================================================== */ /* Free a factor object. * * workspace: none */ int CHOLMOD(free_factor) ( /* ---- in/out --- */ cholmod_factor **LHandle, /* factor to free, NULL on output */ /* --------------- */ cholmod_common *Common ) { Int n, lnz, xs, ss, s ; cholmod_factor *L ; RETURN_IF_NULL_COMMON (FALSE) ; if (LHandle == NULL) { /* nothing to do */ return (TRUE) ; } L = *LHandle ; if (L == NULL) { /* nothing to do */ return (TRUE) ; } n = L->n ; lnz = L->nzmax ; s = L->nsuper + 1 ; xs = (L->is_super) ? ((Int) (L->xsize)) : (lnz) ; ss = L->ssize ; /* symbolic part of L */ CHOLMOD(free) (n, sizeof (Int), L->Perm, Common) ; CHOLMOD(free) (n, sizeof (Int), L->IPerm, Common) ; CHOLMOD(free) (n, sizeof (Int), L->ColCount, Common) ; /* simplicial form of L */ CHOLMOD(free) (n+1, sizeof (Int), L->p, Common) ; CHOLMOD(free) (lnz, sizeof (Int), L->i, Common) ; CHOLMOD(free) (n, sizeof (Int), L->nz, Common) ; CHOLMOD(free) (n+2, sizeof (Int), L->next, Common) ; CHOLMOD(free) (n+2, sizeof (Int), L->prev, Common) ; /* supernodal form of L */ CHOLMOD(free) (s, sizeof (Int), L->pi, Common) ; CHOLMOD(free) (s, sizeof (Int), L->px, Common) ; CHOLMOD(free) (s, sizeof (Int), L->super, Common) ; CHOLMOD(free) (ss, sizeof (Int), L->s, Common) ; /* numerical values for both simplicial and supernodal L */ if (L->xtype == CHOLMOD_REAL) { CHOLMOD(free) (xs, sizeof (double), L->x, Common) ; } else if (L->xtype == CHOLMOD_COMPLEX) { CHOLMOD(free) (xs, 2*sizeof (double), L->x, Common) ; } else if (L->xtype == CHOLMOD_ZOMPLEX) { CHOLMOD(free) (xs, sizeof (double), L->x, Common) ; CHOLMOD(free) (xs, sizeof (double), L->z, Common) ; } *LHandle = CHOLMOD(free) (1, sizeof (cholmod_factor), (*LHandle), Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_reallocate_factor ============================================ */ /* ========================================================================== */ /* Change the size of L->i and L->x, or allocate them if their current size * is zero. L must be simplicial. * * workspace: none */ int CHOLMOD(reallocate_factor) ( /* ---- input ---- */ size_t nznew, /* new # of entries in L */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; PRINT1 (("realloc factor: xtype %d\n", L->xtype)) ; if (L->is_super) { /* L must be simplicial, and not symbolic */ ERROR (CHOLMOD_INVALID, "L invalid") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; PRINT1 (("realloc factor %g to %g\n", (double) L->nzmax, (double) nznew)) ; /* ---------------------------------------------------------------------- */ /* resize (or allocate) the L->i and L->x components of the factor */ /* ---------------------------------------------------------------------- */ CHOLMOD(realloc_multiple) (nznew, 1, L->xtype, &(L->i), NULL, &(L->x), &(L->z), &(L->nzmax), Common) ; return (Common->status == CHOLMOD_OK) ; } /* ========================================================================== */ /* === cholmod_reallocate_column =========================================== */ /* ========================================================================== */ /* Column j needs more space, reallocate it at the end of L->i and L->x. * If the reallocation fails, the factor is converted to a simplicial * symbolic factor (no pattern, just L->Perm and L->ColCount). * * workspace: none */ int CHOLMOD(reallocate_column) ( /* ---- input ---- */ size_t j, /* the column to reallocate */ size_t need, /* required size of column j */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { double xneed ; double *Lx, *Lz ; Int *Lp, *Lprev, *Lnext, *Li, *Lnz ; Int n, pold, pnew, len, k, tail ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; if (L->is_super) { ERROR (CHOLMOD_INVALID, "L must be simplicial") ; return (FALSE) ; } n = L->n ; if (j >= L->n || need == 0) { ERROR (CHOLMOD_INVALID, "j invalid") ; return (FALSE) ; /* j out of range */ } Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_factor) (L, "start colrealloc", Common)) ; /* ---------------------------------------------------------------------- */ /* increase the size of L if needed */ /* ---------------------------------------------------------------------- */ /* head = n+1 ; */ tail = n ; Lp = L->p ; Lnz = L->nz ; Lprev = L->prev ; Lnext = L->next ; ASSERT (Lnz != NULL) ; ASSERT (Lnext != NULL && Lprev != NULL) ; PRINT1 (("col %g need %g\n", (double) j, (double) need)) ; /* column j cannot have more than n-j entries if all entries are present */ need = MIN (need, n-j) ; /* compute need in double to avoid integer overflow */ if (Common->grow1 >= 1.0) { xneed = (double) need ; xneed = Common->grow1 * xneed + Common->grow2 ; xneed = MIN (xneed, n-j) ; need = (Int) xneed ; } PRINT1 (("really new need %g current %g\n", (double) need, (double) (Lp [Lnext [j]] - Lp [j]))) ; ASSERT (need >= 1 && need <= n-j) ; if (Lp [Lnext [j]] - Lp [j] >= (Int) need) { /* no need to reallocate the column, it's already big enough */ PRINT1 (("colrealloc: quick return %g %g\n", (double) (Lp [Lnext [j]] - Lp [j]), (double) need)) ; return (TRUE) ; } if (Lp [tail] + need > L->nzmax) { /* use double to avoid integer overflow */ xneed = (double) need ; if (Common->grow0 < 1.2) /* fl. pt. compare, false if NaN */ { /* if grow0 is less than 1.2 or NaN, don't use it */ xneed = 1.2 * (((double) L->nzmax) + xneed + 1) ; } else { xneed = Common->grow0 * (((double) L->nzmax) + xneed + 1) ; } if (xneed > Size_max || !CHOLMOD(reallocate_factor) ((Int) xneed, L, Common)) { /* out of memory, convert to simplicial symbolic */ CHOLMOD(change_factor) (CHOLMOD_PATTERN, L->is_ll, FALSE, TRUE, TRUE, L, Common) ; ERROR (CHOLMOD_OUT_OF_MEMORY, "out of memory; L now symbolic") ; return (FALSE) ; /* out of memory */ } PRINT1 (("\n=== GROW L from %g to %g\n", (double) L->nzmax, (double) xneed)) ; /* pack all columns so that each column has at most grow2 free space */ CHOLMOD(pack_factor) (L, Common) ; ASSERT (Common->status == CHOLMOD_OK) ; Common->nrealloc_factor++ ; } /* ---------------------------------------------------------------------- */ /* reallocate the column */ /* ---------------------------------------------------------------------- */ Common->nrealloc_col++ ; Li = L->i ; Lx = L->x ; Lz = L->z ; /* remove j from its current position in the list */ Lnext [Lprev [j]] = Lnext [j] ; Lprev [Lnext [j]] = Lprev [j] ; /* place j at the end of the list */ Lnext [Lprev [tail]] = j ; Lprev [j] = Lprev [tail] ; Lnext [j] = n ; Lprev [tail] = j ; /* L is no longer monotonic; columns are out-of-order */ L->is_monotonic = FALSE ; /* allocate space for column j */ pold = Lp [j] ; pnew = Lp [tail] ; Lp [j] = pnew ; Lp [tail] += need ; /* copy column j to the new space */ len = Lnz [j] ; for (k = 0 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; } if (L->xtype == CHOLMOD_REAL) { for (k = 0 ; k < len ; k++) { Lx [pnew + k] = Lx [pold + k] ; } } else if (L->xtype == CHOLMOD_COMPLEX) { for (k = 0 ; k < len ; k++) { Lx [2*(pnew + k) ] = Lx [2*(pold + k) ] ; Lx [2*(pnew + k)+1] = Lx [2*(pold + k)+1] ; } } else if (L->xtype == CHOLMOD_ZOMPLEX) { for (k = 0 ; k < len ; k++) { Lx [pnew + k] = Lx [pold + k] ; Lz [pnew + k] = Lz [pold + k] ; } } DEBUG (CHOLMOD(dump_factor) (L, "colrealloc done", Common)) ; /* successful reallocation of column j of L */ return (TRUE) ; } /* ========================================================================== */ /* === cholmod_pack_factor ================================================== */ /* ========================================================================== */ /* Pack the columns of a simplicial LDL' or LL' factor. This can be followed * by a call to cholmod_reallocate_factor to reduce the size of L to the exact * size required by the factor, if desired. Alternatively, you can leave the * size of L->i and L->x the same, to allow space for future updates/rowadds. * * Each column is reduced in size so that it has at most Common->grow2 free * space at the end of the column. * * Does nothing and returns silently if given any other type of factor. * * Does NOT force the columns of L to be monotonic. It thus differs from * cholmod_change_factor (xtype, -, FALSE, TRUE, TRUE, L, Common), which * packs the columns and ensures that they appear in monotonic order. */ int CHOLMOD(pack_factor) ( /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { double *Lx, *Lz ; Int *Lp, *Li, *Lnz, *Lnext ; Int pnew, j, k, pold, len, n, head, tail, grow2 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_factor) (L, "start pack", Common)) ; PRINT1 (("PACK factor %d\n", L->is_super)) ; if (L->xtype == CHOLMOD_PATTERN || L->is_super) { /* nothing to do unless L is simplicial numeric */ return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* pack */ /* ---------------------------------------------------------------------- */ grow2 = Common->grow2 ; PRINT1 (("\nPACK grow2 "ID"\n", grow2)) ; pnew = 0 ; n = L->n ; Lp = L->p ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lnz = L->nz ; Lnext = L->next ; head = n+1 ; tail = n ; for (j = Lnext [head] ; j != tail ; j = Lnext [j]) { /* pack column j */ pold = Lp [j] ; len = Lnz [j] ; ASSERT (len > 0) ; PRINT2 (("col "ID" pnew "ID" pold "ID"\n", j, pnew, pold)) ; if (pnew < pold) { PRINT2 ((" pack this column\n")) ; for (k = 0 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; } if (L->xtype == CHOLMOD_REAL) { for (k = 0 ; k < len ; k++) { Lx [pnew + k] = Lx [pold + k] ; } } else if (L->xtype == CHOLMOD_COMPLEX) { for (k = 0 ; k < len ; k++) { Lx [2*(pnew + k) ] = Lx [2*(pold + k) ] ; Lx [2*(pnew + k)+1] = Lx [2*(pold + k)+1] ; } } else if (L->xtype == CHOLMOD_ZOMPLEX) { for (k = 0 ; k < len ; k++) { Lx [pnew + k] = Lx [pold + k] ; Lz [pnew + k] = Lz [pold + k] ; } } Lp [j] = pnew ; } len = MIN (len + grow2, n - j) ; pnew = MIN (Lp [j] + len, Lp [Lnext [j]]) ; } PRINT2 (("final pnew = "ID"\n", pnew)) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_factor_to_sparse ============================================= */ /* ========================================================================== */ /* Constructs a column-oriented sparse matrix containing the pattern and values * of a simplicial or supernodal numerical factor, and then converts the factor * into a simplicial symbolic factor. If L is already packed, monotonic, * and simplicial (which is the case when cholmod_factorize uses the simplicial * Cholesky factorization algorithm) then this routine requires only O(1) * memory and takes O(1) time. * * Only operates on numeric factors (real, complex, or zomplex). Does not * change the numeric L->xtype (the resulting sparse matrix has the same xtype * as L). If this routine fails, L is left unmodified. */ cholmod_sparse *CHOLMOD(factor_to_sparse) ( /* ---- in/out --- */ cholmod_factor *L, /* factor to copy, converted to symbolic on output */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *Lsparse ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (L, NULL) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, NULL) ; Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_factor) (L, "start convert to matrix", Common)) ; /* ---------------------------------------------------------------------- */ /* convert to packed, monotonic, simplicial, numeric */ /* ---------------------------------------------------------------------- */ /* leave as LL or LDL' */ if (!CHOLMOD(change_factor) (L->xtype, L->is_ll, FALSE, TRUE, TRUE, L, Common)) { ERROR (CHOLMOD_INVALID, "cannot convert L") ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* create Lsparse */ /* ---------------------------------------------------------------------- */ /* allocate the header for Lsparse, the sparse matrix version of L */ Lsparse = CHOLMOD(malloc) (sizeof (cholmod_sparse), 1, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* transfer the contents from L to Lsparse */ Lsparse->nrow = L->n ; Lsparse->ncol = L->n ; Lsparse->p = L->p ; Lsparse->i = L->i ; Lsparse->x = L->x ; Lsparse->z = L->z ; Lsparse->nz = NULL ; Lsparse->stype = 0 ; Lsparse->itype = L->itype ; Lsparse->xtype = L->xtype ; Lsparse->dtype = L->dtype ; Lsparse->sorted = TRUE ; Lsparse->packed = TRUE ; Lsparse->nzmax = L->nzmax ; ASSERT (CHOLMOD(dump_sparse) (Lsparse, "Lsparse", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* convert L to symbolic, but do not free contents transfered to Lsparse */ /* ---------------------------------------------------------------------- */ L->p = NULL ; L->i = NULL ; L->x = NULL ; L->z = NULL ; L->xtype = CHOLMOD_PATTERN ; CHOLMOD(change_factor) (CHOLMOD_PATTERN, FALSE, FALSE, TRUE, TRUE, L, Common) ; return (Lsparse) ; } /* ========================================================================== */ /* === cholmod_copy_factor ================================================== */ /* ========================================================================== */ /* Create an exact copy of a factor, with one exception: * * Entries in unused space are not copied (they might not be initialized, * and copying them would cause program checkers such as purify and * valgrind to complain). * * Note that a supernodal L cannot be zomplex. */ cholmod_factor *CHOLMOD(copy_factor) ( /* ---- input ---- */ cholmod_factor *L, /* factor to copy */ /* --------------- */ cholmod_common *Common ) { cholmod_factor *L2 ; double *Lx, *L2x, *Lz, *L2z ; Int *Perm, *ColCount, *Lp, *Li, *Lnz, *Lnext, *Lprev, *Lsuper, *Lpi, *Lpx, *Ls, *Perm2, *ColCount2, *L2p, *L2i, *L2nz, *L2next, *L2prev, *L2super, *L2pi, *L2px, *L2s ; Int n, j, p, pend, s, xsize, ssize, nsuper ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (L, NULL) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_factor) (L, "start copy", Common)) ; n = L->n ; /* ---------------------------------------------------------------------- */ /* allocate a simplicial symbolic factor */ /* ---------------------------------------------------------------------- */ /* allocates L2->Perm and L2->ColCount */ L2 = CHOLMOD(allocate_factor) (n, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } ASSERT (L2->xtype == CHOLMOD_PATTERN && !(L2->is_super)) ; Perm = L->Perm ; ColCount = L->ColCount ; Perm2 = L2->Perm ; ColCount2 = L2->ColCount ; L2->ordering = L->ordering ; for (j = 0 ; j < n ; j++) { Perm2 [j] = Perm [j] ; } for (j = 0 ; j < n ; j++) { ColCount2 [j] = ColCount [j] ; } L2->is_ll = L->is_ll ; /* ---------------------------------------------------------------------- */ /* copy the rest of the factor */ /* ---------------------------------------------------------------------- */ if (L->xtype != CHOLMOD_PATTERN && !(L->super)) { /* ------------------------------------------------------------------ */ /* allocate a simplicial numeric factor */ /* ------------------------------------------------------------------ */ /* allocate L2->p, L2->nz, L2->prev, L2->next, L2->i, and L2->x. * packed = -1 so that cholmod_change_factor allocates space of * size L2->nzmax */ L2->nzmax = L->nzmax ; if (!CHOLMOD(change_factor) (L->xtype, L->is_ll, FALSE, -1, TRUE, L2, Common)) { CHOLMOD(free_factor) (&L2, Common) ; return (NULL) ; /* out of memory */ } ASSERT (MAX (1, L->nzmax) == L2->nzmax) ; /* ------------------------------------------------------------------ */ /* copy the contents of a simplicial numeric factor */ /* ------------------------------------------------------------------ */ Lp = L->p ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lnz = L->nz ; Lnext = L->next ; Lprev = L->prev ; L2p = L2->p ; L2i = L2->i ; L2x = L2->x ; L2z = L2->z ; L2nz = L2->nz ; L2next = L2->next ; L2prev = L2->prev ; L2->xtype = L->xtype ; L2->dtype = L->dtype ; for (j = 0 ; j <= n ; j++) { L2p [j] = Lp [j] ; } for (j = 0 ; j < n+2 ; j++) { L2prev [j] = Lprev [j] ; } for (j = 0 ; j < n+2 ; j++) { L2next [j] = Lnext [j] ; } for (j = 0 ; j < n ; j++) { L2nz [j] = Lnz [j] ; } for (j = 0 ; j < n ; j++) { p = Lp [j] ; pend = p + Lnz [j] ; for ( ; p < pend ; p++) { L2i [p] = Li [p] ; } p = Lp [j] ; if (L->xtype == CHOLMOD_REAL) { for ( ; p < pend ; p++) { L2x [p] = Lx [p] ; } } else if (L->xtype == CHOLMOD_COMPLEX) { for ( ; p < pend ; p++) { L2x [2*p ] = Lx [2*p ] ; L2x [2*p+1] = Lx [2*p+1] ; } } else if (L->xtype == CHOLMOD_ZOMPLEX) { for ( ; p < pend ; p++) { L2x [p] = Lx [p] ; L2z [p] = Lz [p] ; } } } } else if (L->is_super) { /* ------------------------------------------------------------------ */ /* copy a supernodal factor */ /* ------------------------------------------------------------------ */ xsize = L->xsize ; ssize = L->ssize ; nsuper = L->nsuper ; L2->xsize = xsize ; L2->ssize = ssize ; L2->nsuper = nsuper ; /* allocate L2->super, L2->pi, L2->px, and L2->s. Allocate L2->x if * L is numeric */ if (!CHOLMOD(change_factor) (L->xtype, TRUE, TRUE, TRUE, TRUE, L2, Common)) { CHOLMOD(free_factor) (&L2, Common) ; return (NULL) ; /* out of memory */ } ASSERT (L2->s != NULL) ; /* ------------------------------------------------------------------ */ /* copy the contents of a supernodal factor */ /* ------------------------------------------------------------------ */ Lsuper = L->super ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Lx = L->x ; L2super = L2->super ; L2pi = L2->pi ; L2px = L2->px ; L2s = L2->s ; L2x = L2->x ; L2->maxcsize = L->maxcsize ; L2->maxesize = L->maxesize ; for (s = 0 ; s <= nsuper ; s++) { L2super [s] = Lsuper [s] ; } for (s = 0 ; s <= nsuper ; s++) { L2pi [s] = Lpi [s] ; } for (s = 0 ; s <= nsuper ; s++) { L2px [s] = Lpx [s] ; } L2s [0] = 0 ; for (p = 0 ; p < ssize ; p++) { L2s [p] = Ls [p] ; } if (L->xtype == CHOLMOD_REAL) { for (p = 0 ; p < xsize ; p++) { L2x [p] = Lx [p] ; } } else if (L->xtype == CHOLMOD_COMPLEX) { for (p = 0 ; p < 2*xsize ; p++) { L2x [p] = Lx [p] ; } } } L2->minor = L->minor ; L2->is_monotonic = L->is_monotonic ; DEBUG (CHOLMOD(dump_factor) (L2, "L2 got copied", Common)) ; ASSERT (L2->xtype == L->xtype && L2->is_super == L->is_super) ; return (L2) ; } igraph/src/CHOLMOD/Core/t_cholmod_dense.c0000644000175100001440000001621113431000472017573 0ustar hornikusers/* ========================================================================== */ /* === Core/t_cholmod_dense ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine for cholmod_dense. All xtypes supported, except that there * are no dense matrices with an xtype of pattern. */ #include "cholmod_template.h" /* ========================================================================== */ /* === t_cholmod_sparse_to_dense ============================================ */ /* ========================================================================== */ static cholmod_dense *TEMPLATE (cholmod_sparse_to_dense) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Xx, *Az, *Xz ; Int *Ap, *Ai, *Anz ; cholmod_dense *X ; Int i, j, p, pend, nrow, ncol, packed ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; packed = A->packed ; Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; /* ---------------------------------------------------------------------- */ /* allocate result */ /* ---------------------------------------------------------------------- */ X = CHOLMOD(zeros) (nrow, ncol, XTYPE2, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } Xx = X->x ; Xz = X->z ; /* ---------------------------------------------------------------------- */ /* copy into dense matrix */ /* ---------------------------------------------------------------------- */ if (A->stype < 0) { /* A is symmetric with lower stored, but both parts of X are present */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= j) { ASSIGN2 (Xx, Xz, i+j*nrow, Ax, Az, p) ; ASSIGN2_CONJ (Xx, Xz, j+i*nrow, Ax, Az, p) ; } } } } else if (A->stype > 0) { /* A is symmetric with upper stored, but both parts of X are present */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i <= j) { ASSIGN2 (Xx, Xz, i+j*nrow, Ax, Az, p) ; ASSIGN2_CONJ (Xx, Xz, j+i*nrow, Ax, Az, p) ; } } } } else { /* both parts of A and X are present */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; ASSIGN2 (Xx, Xz, i+j*nrow, Ax, Az, p) ; } } } return (X) ; } #ifndef PATTERN /* There are no dense matrices of xtype CHOLMOD_PATTERN */ /* ========================================================================== */ /* === t_cholmod_dense_to_sparse ============================================ */ /* ========================================================================== */ static cholmod_sparse *TEMPLATE (cholmod_dense_to_sparse) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ int values, /* TRUE if values to be copied, FALSE otherwise */ /* --------------- */ cholmod_common *Common ) { double *Xx, *Cx, *Xz, *Cz ; Int *Ci, *Cp ; cholmod_sparse *C ; Int i, j, p, d, nrow, ncol, nz ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = X->nrow ; ncol = X->ncol ; d = X->d ; Xx = X->x ; Xz = X->z ; /* ---------------------------------------------------------------------- */ /* count the number of nonzeros in the result */ /* ---------------------------------------------------------------------- */ nz = 0 ; for (j = 0 ; j < ncol ; j++) { for (i = 0 ; i < nrow ; i++) { if (ENTRY_IS_NONZERO (Xx, Xz, i+j*d)) { nz++ ; } } } /* ---------------------------------------------------------------------- */ /* allocate the result C */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_sparse) (nrow, ncol, nz, TRUE, TRUE, 0, values ? XTYPE : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } Cp = C->p ; Ci = C->i ; Cx = C->x ; Cz = C->z ; /* ---------------------------------------------------------------------- */ /* copy the dense matrix X into the sparse matrix C */ /* ---------------------------------------------------------------------- */ p = 0 ; for (j = 0 ; j < ncol ; j++) { Cp [j] = p ; for (i = 0 ; i < nrow ; i++) { if (ENTRY_IS_NONZERO (Xx, Xz, i+j*d)) { Ci [p] = i ; if (values) { ASSIGN (Cx, Cz, p, Xx, Xz, i+j*d) ; } p++ ; } } } ASSERT (p == nz) ; Cp [ncol] = nz ; /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (C, "C", Common) >= 0) ; return (C) ; } /* ========================================================================== */ /* === t_cholmod_copy_dense2 ================================================ */ /* ========================================================================== */ /* Y = X, where X and Y are both already allocated. */ static int TEMPLATE (cholmod_copy_dense2) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ /* ---- output --- */ cholmod_dense *Y /* copy of matrix X */ ) { double *Xx, *Xz, *Yx, *Yz ; Int i, j, nrow, ncol, dy, dx ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Xx = X->x ; Xz = X->z ; Yx = Y->x ; Yz = Y->z ; dx = X->d ; dy = Y->d ; nrow = X->nrow ; ncol = X->ncol ; /* ---------------------------------------------------------------------- */ /* copy */ /* ---------------------------------------------------------------------- */ CLEAR (Yx, Yz, 0) ; for (j = 0 ; j < ncol ; j++) { for (i = 0 ; i < nrow ; i++) { ASSIGN (Yx, Yz, i+j*dy, Xx, Xz, i+j*dx) ; } } return (TRUE) ; } #endif #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Core/License.txt0000644000175100001440000000207213430770172016436 0ustar hornikusersCHOLMOD/Core Module. Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Core module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA igraph/src/CHOLMOD/Core/cholmod_memory.c0000644000175100001440000004301113431000472017460 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_memory ================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2013, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core memory management routines: * * Primary routines: * ----------------- * cholmod_malloc malloc wrapper * cholmod_free free wrapper * * Secondary routines: * ------------------- * cholmod_calloc calloc wrapper * cholmod_realloc realloc wrapper * cholmod_realloc_multiple realloc wrapper for multiple objects * * The user may make use of these, just like malloc and free. You can even * malloc an object and safely free it with cholmod_free, and visa versa * (except that the memory usage statistics will be corrupted). These routines * do differ from malloc and free. If cholmod_free is given a NULL pointer, * for example, it does nothing (unlike the ANSI free). cholmod_realloc does * not return NULL if given a non-NULL pointer and a nonzero size, even if it * fails (it sets an error code in Common->status instead). * * CHOLMOD keeps track of the amount of memory it has allocated, and so the * cholmod_free routine includes as a parameter the size of the object being * freed. This is only used for memory usage statistics, which are very useful * in finding memory leaks in your program. If you, the user of CHOLMOD, pass * the wrong size, the only consequence is that the memory usage statistics * will be invalid. This will causes assertions to fail if CHOLMOD is * compiled with debugging enabled, but otherwise it will cause no errors. * * The cholmod_free_* routines for each CHOLMOD object keep track of the size * of the blocks they free, so they do not require you to pass their sizes * as a parameter. * * If a block of size zero is requested, these routines allocate a block of * size one instead. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === cholmod_add_size_t =================================================== */ /* ========================================================================== */ /* Safely compute a+b, and check for integer overflow. If overflow occurs, * return 0 and set OK to FALSE. Also return 0 if OK is FALSE on input. */ size_t CHOLMOD(add_size_t) (size_t a, size_t b, int *ok) { size_t s = a + b ; (*ok) = (*ok) && (s >= a) ; return ((*ok) ? s : 0) ; } /* ========================================================================== */ /* === cholmod_mult_size_t ================================================== */ /* ========================================================================== */ /* Safely compute a*k, where k should be small, and check for integer overflow. * If overflow occurs, return 0 and set OK to FALSE. Also return 0 if OK is * FALSE on input. */ size_t CHOLMOD(mult_size_t) (size_t a, size_t k, int *ok) { size_t p = 0, s ; while (*ok) { if (k % 2) { p = p + a ; (*ok) = (*ok) && (p >= a) ; } k = k / 2 ; if (!k) return (p) ; s = a + a ; (*ok) = (*ok) && (s >= a) ; a = s ; } return (0) ; } /* ========================================================================== */ /* === cholmod_malloc ======================================================= */ /* ========================================================================== */ /* Wrapper around malloc routine. Allocates space of size MAX(1,n)*size, where * size is normally a sizeof (...). * * This routine, cholmod_calloc, and cholmod_realloc do not set Common->status * to CHOLMOD_OK on success, so that a sequence of cholmod_malloc's, _calloc's, * or _realloc's can be used. If any of them fails, the Common->status will * hold the most recent error status. * * Usage, for a pointer to int: * * p = cholmod_malloc (n, sizeof (int), Common) * * Uses a pointer to the malloc routine (or its equivalent) defined in Common. */ void *CHOLMOD(malloc) /* returns pointer to the newly malloc'd block */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* --------------- */ cholmod_common *Common ) { void *p ; size_t s ; int ok = TRUE ; RETURN_IF_NULL_COMMON (NULL) ; if (size == 0) { ERROR (CHOLMOD_INVALID, "sizeof(item) must be > 0") ; p = NULL ; } else if (n >= (Size_max / size) || n >= Int_max) { /* object is too big to allocate without causing integer overflow */ ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; p = NULL ; } else { /* call malloc, or its equivalent */ s = CHOLMOD(mult_size_t) (MAX (1,n), size, &ok) ; p = ok ? ((Common->malloc_memory) (s)) : NULL ; if (p == NULL) { /* failure: out of memory */ ERROR (CHOLMOD_OUT_OF_MEMORY, "out of memory") ; } else { /* success: increment the count of objects allocated */ Common->malloc_count++ ; Common->memory_inuse += (n * size) ; Common->memory_usage = MAX (Common->memory_usage, Common->memory_inuse) ; PRINTM (("cholmod_malloc %p %g cnt: %g inuse %g\n", p, (double) n*size, (double) Common->malloc_count, (double) Common->memory_inuse)) ; } } return (p) ; } /* ========================================================================== */ /* === cholmod_free ========================================================= */ /* ========================================================================== */ /* Wrapper around free routine. Returns NULL, which can be assigned to the * pointer being freed, as in: * * p = cholmod_free (n, sizeof (int), p, Common) ; * * In CHOLMOD, the syntax: * * cholmod_free (n, sizeof (int), p, Common) ; * * is used if p is a local pointer and the routine is returning shortly. * Uses a pointer to the free routine (or its equivalent) defined in Common. * Nothing is freed if the pointer is NULL. */ void *CHOLMOD(free) /* always returns NULL */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* ---- in/out --- */ void *p, /* block of memory to free */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (NULL) ; if (p != NULL) { /* only free the object if the pointer is not NULL */ /* call free, or its equivalent */ (Common->free_memory) (p) ; Common->malloc_count-- ; Common->memory_inuse -= (n * size) ; PRINTM (("cholmod_free %p %g cnt: %g inuse %g\n", p, (double) n*size, (double) Common->malloc_count, (double) Common->memory_inuse)) ; /* This assertion will fail if the user calls cholmod_malloc and * cholmod_free with mismatched memory sizes. It shouldn't fail * otherwise. */ ASSERT (IMPLIES (Common->malloc_count == 0, Common->memory_inuse == 0)); } /* return NULL, and the caller should assign this to p. This avoids * freeing the same pointer twice. */ return (NULL) ; } /* ========================================================================== */ /* === cholmod_calloc ======================================================= */ /* ========================================================================== */ /* Wrapper around calloc routine. * * Uses a pointer to the calloc routine (or its equivalent) defined in Common. * This routine is identical to malloc, except that it zeros the newly allocated * block to zero. */ void *CHOLMOD(calloc) /* returns pointer to the newly calloc'd block */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* --------------- */ cholmod_common *Common ) { void *p ; RETURN_IF_NULL_COMMON (NULL) ; if (size == 0) { ERROR (CHOLMOD_INVALID, "sizeof(item) must be > 0") ; p = NULL ; } else if (n >= (Size_max / size) || n >= Int_max) { /* object is too big to allocate without causing integer overflow */ ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; p = NULL ; } else { /* call calloc, or its equivalent */ p = (Common->calloc_memory) (MAX (1,n), size) ; if (p == NULL) { /* failure: out of memory */ ERROR (CHOLMOD_OUT_OF_MEMORY, "out of memory") ; } else { /* success: increment the count of objects allocated */ Common->malloc_count++ ; Common->memory_inuse += (n * size) ; Common->memory_usage = MAX (Common->memory_usage, Common->memory_inuse) ; PRINTM (("cholmod_malloc %p %g cnt: %g inuse %g\n", p, (double) n*size, (double) Common->malloc_count, (double) Common->memory_inuse)) ; } } return (p) ; } /* ========================================================================== */ /* === cholmod_realloc ====================================================== */ /* ========================================================================== */ /* Wrapper around realloc routine. Given a pointer p to a block of size * (*n)*size memory, it changes the size of the block pointed to by p to be * MAX(1,nnew)*size in size. It may return a pointer different than p. This * should be used as (for a pointer to int): * * p = cholmod_realloc (nnew, sizeof (int), p, *n, Common) ; * * If p is NULL, this is the same as p = cholmod_malloc (...). * A size of nnew=0 is treated as nnew=1. * * If the realloc fails, p is returned unchanged and Common->status is set * to CHOLMOD_OUT_OF_MEMORY. If successful, Common->status is not modified, * and p is returned (possibly changed) and pointing to a large block of memory. * * Uses a pointer to the realloc routine (or its equivalent) defined in Common. */ void *CHOLMOD(realloc) /* returns pointer to reallocated block */ ( /* ---- input ---- */ size_t nnew, /* requested # of items in reallocated block */ size_t size, /* size of each item */ /* ---- in/out --- */ void *p, /* block of memory to realloc */ size_t *n, /* current size on input, nnew on output if successful*/ /* --------------- */ cholmod_common *Common ) { size_t nold = (*n) ; void *pnew ; size_t s ; int ok = TRUE ; RETURN_IF_NULL_COMMON (NULL) ; if (size == 0) { ERROR (CHOLMOD_INVALID, "sizeof(item) must be > 0") ; p = NULL ; } else if (p == NULL) { /* A fresh object is being allocated. */ PRINT1 (("realloc fresh: %d %d\n", nnew, size)) ; p = CHOLMOD(malloc) (nnew, size, Common) ; *n = (p == NULL) ? 0 : nnew ; } else if (nold == nnew) { /* Nothing to do. Do not change p or n. */ PRINT1 (("realloc nothing: %d %d\n", nnew, size)) ; } else if (nnew >= (Size_max / size) || nnew >= Int_max) { /* failure: nnew is too big. Do not change p or n. */ ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; } else { /* The object exists, and is changing to some other nonzero size. */ /* call realloc, or its equivalent */ PRINT1 (("realloc : %d to %d, %d\n", nold, nnew, size)) ; pnew = NULL ; s = CHOLMOD(mult_size_t) (MAX (1,nnew), size, &ok) ; pnew = ok ? ((Common->realloc_memory) (p, s)) : NULL ; if (pnew == NULL) { /* Do not change p, since it still points to allocated memory */ if (nnew <= nold) { /* The attempt to reduce the size of the block from n to * nnew has failed. The current block is not modified, so * pretend to succeed, but do not change p. Do change * CHOLMOD's notion of the size of the block, however. */ *n = nnew ; PRINTM (("nnew <= nold failed, pretend to succeed\n")) ; PRINTM (("cholmod_free %p %g cnt: %g inuse %g\n" "cholmod_malloc %p %g cnt: %g inuse %g\n", p, (double) nold*size, (double) Common->malloc_count-1, (double) (Common->memory_inuse - nold*size), p, (double) nnew*size, (double) Common->malloc_count, (double) (Common->memory_inuse + (nnew-nold)*size))) ; Common->memory_inuse += ((nnew-nold) * size) ; } else { /* Increasing the size of the block has failed. * Do not change n. */ ERROR (CHOLMOD_OUT_OF_MEMORY, "out of memory") ; } } else { /* success: return revised p and change the size of the block */ PRINTM (("cholmod_free %p %g cnt: %g inuse %g\n" "cholmod_malloc %p %g cnt: %g inuse %g\n", p, (double) nold*size, (double) Common->malloc_count-1, (double) (Common->memory_inuse - nold*size), pnew, (double) nnew*size, (double) Common->malloc_count, (double) (Common->memory_inuse + (nnew-nold)*size))) ; p = pnew ; *n = nnew ; Common->memory_inuse += ((nnew-nold) * size) ; } Common->memory_usage = MAX (Common->memory_usage, Common->memory_inuse); } return (p) ; } /* ========================================================================== */ /* === cholmod_realloc_multiple ============================================= */ /* ========================================================================== */ /* reallocate multiple blocks of memory, all of the same size (up to two integer * and two real blocks). Either reallocations all succeed, or all are returned * in the original size (they are freed if the original size is zero). The nnew * blocks are of size 1 or more. */ int CHOLMOD(realloc_multiple) ( /* ---- input ---- */ size_t nnew, /* requested # of items in reallocated blocks */ int nint, /* number of int/SuiteSparse_long blocks */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* ---- in/out --- */ void **Iblock, /* int or SuiteSparse_long block */ void **Jblock, /* int or SuiteSparse_long block */ void **Xblock, /* complex or double block */ void **Zblock, /* zomplex case only: double block */ size_t *nold_p, /* current size of the I,J,X,Z blocks on input, * nnew on output if successful */ /* --------------- */ cholmod_common *Common ) { double *xx, *zz ; size_t i, j, x, z, nold ; RETURN_IF_NULL_COMMON (FALSE) ; if (xtype < CHOLMOD_PATTERN || xtype > CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "invalid xtype") ; return (FALSE) ; } nold = *nold_p ; if (nint < 1 && xtype == CHOLMOD_PATTERN) { /* nothing to do */ return (TRUE) ; } i = nold ; j = nold ; x = nold ; z = nold ; if (nint > 0) { *Iblock = CHOLMOD(realloc) (nnew, sizeof (Int), *Iblock, &i, Common) ; } if (nint > 1) { *Jblock = CHOLMOD(realloc) (nnew, sizeof (Int), *Jblock, &j, Common) ; } switch (xtype) { case CHOLMOD_REAL: *Xblock = CHOLMOD(realloc) (nnew, sizeof (double), *Xblock, &x, Common) ; break ; case CHOLMOD_COMPLEX: *Xblock = CHOLMOD(realloc) (nnew, 2*sizeof (double), *Xblock, &x, Common) ; break ; case CHOLMOD_ZOMPLEX: *Xblock = CHOLMOD(realloc) (nnew, sizeof (double), *Xblock, &x, Common) ; *Zblock = CHOLMOD(realloc) (nnew, sizeof (double), *Zblock, &z, Common) ; break ; } if (Common->status < CHOLMOD_OK) { /* one or more realloc's failed. Resize all back down to nold. */ if (nold == 0) { if (nint > 0) { *Iblock = CHOLMOD(free) (i, sizeof (Int), *Iblock, Common) ; } if (nint > 1) { *Jblock = CHOLMOD(free) (j, sizeof (Int), *Jblock, Common) ; } switch (xtype) { case CHOLMOD_REAL: *Xblock = CHOLMOD(free) (x, sizeof (double), *Xblock, Common) ; break ; case CHOLMOD_COMPLEX: *Xblock = CHOLMOD(free) (x, 2*sizeof (double), *Xblock, Common) ; break ; case CHOLMOD_ZOMPLEX: *Xblock = CHOLMOD(free) (x, sizeof (double), *Xblock, Common) ; *Zblock = CHOLMOD(free) (x, sizeof (double), *Zblock, Common) ; break ; } } else { if (nint > 0) { *Iblock = CHOLMOD(realloc) (nold, sizeof (Int), *Iblock, &i, Common) ; } if (nint > 1) { *Jblock = CHOLMOD(realloc) (nold, sizeof (Int), *Jblock, &j, Common) ; } switch (xtype) { case CHOLMOD_REAL: *Xblock = CHOLMOD(realloc) (nold, sizeof (double), *Xblock, &x, Common) ; break ; case CHOLMOD_COMPLEX: *Xblock = CHOLMOD(realloc) (nold, 2*sizeof (double), *Xblock, &x, Common) ; break ; case CHOLMOD_ZOMPLEX: *Xblock = CHOLMOD(realloc) (nold, sizeof (double), *Xblock, &x, Common) ; *Zblock = CHOLMOD(realloc) (nold, sizeof (double), *Zblock, &z, Common) ; break ; } } return (FALSE) ; } if (nold == 0) { /* New space was allocated. Clear the first entry so that valgrind * doesn't complain about its access in change_complexity * (Core/cholmod_complex.c). */ xx = *Xblock ; zz = *Zblock ; switch (xtype) { case CHOLMOD_REAL: xx [0] = 0 ; break ; case CHOLMOD_COMPLEX: xx [0] = 0 ; xx [1] = 0 ; break ; case CHOLMOD_ZOMPLEX: xx [0] = 0 ; zz [0] = 0 ; break ; } } /* all realloc's succeeded, change size to reflect realloc'ed size. */ *nold_p = nnew ; return (TRUE) ; } igraph/src/CHOLMOD/Core/cholmod_add.c0000644000175100001440000002024013431000472016677 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_add ===================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* C = alpha*A + beta*B, or spones(A+B). Result is packed, with sorted or * unsorted columns. This routine is much faster and takes less memory if C * is allowed to have unsorted columns. * * If A and B are both symmetric (in upper form) then C is the same. Likewise, * if A and B are both symmetric (in lower form) then C is the same. * Otherwise, C is unsymmetric. A and B must have the same dimension. * * workspace: Flag (nrow), W (nrow) if values, Iwork (max (nrow,ncol)). * allocates temporary copies for A and B if they are symmetric. * allocates temporary copy of C if it is to be returned sorted. * * A and B can have an xtype of pattern or real. Complex or zomplex cases * are supported only if the "values" input parameter is FALSE. */ #include "cholmod_internal.h" #include "cholmod_core.h" cholmod_sparse *CHOLMOD(add) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to add */ cholmod_sparse *B, /* matrix to add */ double alpha [2], /* scale factor for A */ double beta [2], /* scale factor for B */ int values, /* if TRUE compute the numerical values of C */ int sorted, /* if TRUE, sort columns of C */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Bx, *Cx, *W ; Int apacked, up, lo, nrow, ncol, bpacked, nzmax, pa, paend, pb, pbend, i, j, p, mark, nz ; Int *Ap, *Ai, *Anz, *Bp, *Bi, *Bnz, *Flag, *Cp, *Ci ; cholmod_sparse *A2, *B2, *C ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_NULL (B, NULL) ; values = values && (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->nrow != B->nrow || A->ncol != B->ncol) { /* A and B must have the same dimensions */ ERROR (CHOLMOD_INVALID, "A and B dimesions do not match") ; return (NULL) ; } /* A and B must have the same numerical type if values is TRUE (both must * be CHOLMOD_REAL, this is implicitly checked above) */ Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; CHOLMOD(allocate_work) (nrow, MAX (nrow,ncol), values ? nrow : 0, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ if (nrow <= 1) { /* C will be implicitly sorted, so no need to sort it here */ sorted = FALSE ; } /* convert A or B to unsymmetric, if necessary */ A2 = NULL ; B2 = NULL ; if (A->stype != B->stype) { if (A->stype) { /* workspace: Iwork (max (nrow,ncol)) */ A2 = CHOLMOD(copy) (A, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } A = A2 ; } if (B->stype) { /* workspace: Iwork (max (nrow,ncol)) */ B2 = CHOLMOD(copy) (B, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&A2, Common) ; return (NULL) ; /* out of memory */ } B = B2 ; } } /* get the A matrix */ ASSERT (A->stype == B->stype) ; up = (A->stype > 0) ; lo = (A->stype < 0) ; Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; apacked = A->packed ; /* get the B matrix */ Bp = B->p ; Bnz = B->nz ; Bi = B->i ; Bx = B->x ; bpacked = B->packed ; /* get workspace */ W = Common->Xwork ; /* size nrow, used if values is TRUE */ Flag = Common->Flag ; /* size nrow, Flag [0..nrow-1] < mark on input */ /* ---------------------------------------------------------------------- */ /* allocate the result C */ /* ---------------------------------------------------------------------- */ /* If integer overflow occurs, nzmax < 0 and the allocate fails properly * (likewise in most other matrix manipulation routines). */ nzmax = CHOLMOD(nnz) (A, Common) + CHOLMOD(nnz) (B, Common) ; C = CHOLMOD(allocate_sparse) (nrow, ncol, nzmax, FALSE, TRUE, SIGN (A->stype), values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; return (NULL) ; /* out of memory */ } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* compute C = alpha*A + beta*B */ /* ---------------------------------------------------------------------- */ nz = 0 ; for (j = 0 ; j < ncol ; j++) { Cp [j] = nz ; /* clear the Flag array */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* scatter B into W */ pb = Bp [j] ; pbend = (bpacked) ? (Bp [j+1]) : (pb + Bnz [j]) ; for (p = pb ; p < pbend ; p++) { i = Bi [p] ; if ((up && i > j) || (lo && i < j)) { continue ; } Flag [i] = mark ; if (values) { W [i] = beta [0] * Bx [p] ; } } /* add A and gather from W into C(:,j) */ pa = Ap [j] ; paend = (apacked) ? (Ap [j+1]) : (pa + Anz [j]) ; for (p = pa ; p < paend ; p++) { i = Ai [p] ; if ((up && i > j) || (lo && i < j)) { continue ; } Flag [i] = EMPTY ; Ci [nz] = i ; if (values) { Cx [nz] = W [i] + alpha [0] * Ax [p] ; W [i] = 0 ; } nz++ ; } /* gather remaining entries into C(:,j), using pattern of B */ for (p = pb ; p < pbend ; p++) { i = Bi [p] ; if ((up && i > j) || (lo && i < j)) { continue ; } if (Flag [i] == mark) { Ci [nz] = i ; if (values) { Cx [nz] = W [i] ; W [i] = 0 ; } nz++ ; } } } Cp [ncol] = nz ; /* ---------------------------------------------------------------------- */ /* reduce C in size and free temporary matrices */ /* ---------------------------------------------------------------------- */ ASSERT (MAX (1,nz) <= C->nzmax) ; CHOLMOD(reallocate_sparse) (nz, C, Common) ; ASSERT (Common->status >= CHOLMOD_OK) ; /* clear the Flag array */ mark = CHOLMOD(clear_flag) (Common) ; CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; /* ---------------------------------------------------------------------- */ /* sort C, if requested */ /* ---------------------------------------------------------------------- */ if (sorted) { /* workspace: Iwork (max (nrow,ncol)) */ if (!CHOLMOD(sort) (C, Common)) { CHOLMOD(free_sparse) (&C, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } } } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (C, "add", Common) >= 0) ; return (C) ; } igraph/src/CHOLMOD/Core/cholmod_transpose.c0000644000175100001440000007533713431000472020206 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_transpose =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_sparse object to * compute the transpose or permuted transpose of a matrix: * * Primary routines: * ----------------- * cholmod_transpose transpose sparse matrix * cholmod_ptranspose transpose and permute sparse matrix * cholmod_sort sort row indices in each column of sparse matrix * * Secondary routines: * ------------------- * cholmod_transpose_unsym transpose unsymmetric sparse matrix * cholmod_transpose_sym transpose symmetric sparse matrix * * All xtypes (pattern, real, complex, and zomplex) are supported. * * --------------------------------------- * Unsymmetric case: A->stype is zero. * --------------------------------------- * * Computes F = A', F = A (:,f)' or F = A (p,f)', except that the indexing by * f does not work the same as the MATLAB notation (see below). A->stype * is zero, which denotes that both the upper and lower triangular parts of * A are present (and used). A may in fact be symmetric in pattern and/or * value; A->stype just denotes which part of A are stored. A may be * rectangular. * * p is a permutation of 0:m-1, and f is a subset of 0:n-1, where A is m-by-n. * There can be no duplicate entries in p or f. * * The set f is held in fset and fsize. * fset = NULL means ":" in MATLAB. fsize is ignored. * fset != NULL means f = fset [0..fsize-1]. * fset != NULL and fsize = 0 means f is the empty set. * * Columns not in the set f are considered to be zero. That is, * if A is 5-by-10 then F = A (:,[3 4])' is not 2-by-5, but 10-by-5, and rows * 3 and 4 of F are equal to columns 3 and 4 of A (the other rows of F are * zero). More precisely, in MATLAB notation: * * [m n] = size (A) ; * F = A ; * notf = ones (1,n) ; * notf (f) = 0 ; * F (:, find (notf)) = 0 * F = F' * * If you want the MATLAB equivalent F=A(p,f) operation, use cholmod_submatrix * instead (which does not compute the transpose). * * F->nzmax must be large enough to hold the matrix F. It is not modified. * If F->nz is present then F->nz [j] = # of entries in column j of F. * * A can be sorted or unsorted, with packed or unpacked columns. * * If f is present and not sorted in ascending order, then F is unsorted * (that is, it may contain columns whose row indices do not appear in * ascending order). Otherwise, F is sorted (the row indices in each * column of F appear in strictly ascending order). * * F is returned in packed or unpacked form, depending on F->packed on input. * If F->packed is false, then F is returned in unpacked form (F->nz must be * present). Each row i of F is large enough to hold all the entries in row i * of A, even if f is provided. That is, F->i and * F->x [F->p [i] .. F->p [i] + F->nz [i] - 1] contain all entries in A (i,f), * but F->p [i+1] - F->p [i] is equal to the number of nonzeros in A (i,:), * not just A (i,f). * * The cholmod_transpose_unsym routine is the only operation in CHOLMOD that * can produce an unpacked matrix. * * --------------------------------------- * Symmetric case: A->stype is nonzero. * --------------------------------------- * * Computes F = A' or F = A(p,p)', the transpose or permuted transpose, where * A->stype is nonzero. * * If A->stype > 0, then A is a symmetric matrix where just the upper part * of the matrix is stored. Entries in the lower triangular part may be * present, but are ignored. A must be square. If F=A', then F is returned * sorted; otherwise F is unsorted for the F=A(p,p)' case. * * There can be no duplicate entries in p. * The fset and fsize parameters are not used. * * Three kinds of transposes are available, depending on the "values" parameter: * 0: do not transpose the numerical values; create a CHOLMOD_PATTERN matrix * 1: array transpose * 2: complex conjugate transpose (same as 2 if input is real or pattern) * * ----------------------------------------------------------------------------- * * For cholmod_transpose_unsym and cholmod_transpose_sym, the output matrix * F must already be pre-allocated by the caller, with the correct dimensions. * If F is not valid or has the wrong dimensions, it is not modified. * Otherwise, if F is too small, the transpose is not computed; the contents * of F->p contain the column pointers of the resulting matrix, where * F->p [F->ncol] > F->nzmax. In this case, the remaining contents of F are * not modified. F can still be properly free'd with cholmod_free_sparse. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define PATTERN #include "t_cholmod_transpose.c" #define REAL #include "t_cholmod_transpose.c" #define COMPLEX #include "t_cholmod_transpose.c" #define COMPLEX #define NCONJUGATE #include "t_cholmod_transpose.c" #define ZOMPLEX #include "t_cholmod_transpose.c" #define ZOMPLEX #define NCONJUGATE #include "t_cholmod_transpose.c" /* ========================================================================== */ /* === cholmod_transpose_unsym ============================================== */ /* ========================================================================== */ /* Compute F = A', A (:,f)', or A (p,f)', where A is unsymmetric and F is * already allocated. See cholmod_transpose for a simpler routine. * * workspace: * Iwork (MAX (nrow,ncol)) if fset is present * Iwork (nrow) if fset is NULL * * The xtype of A and F must match, unless values is zero or F->xtype is * CHOLMOD_PATTERN (in which case only the pattern of A is transpose into F). */ int CHOLMOD(transpose_unsym) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 2: complex conj. transpose, 1: array transpose, 0: do not transpose the numerical values */ Int *Perm, /* size nrow, if present (can be NULL) */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ cholmod_sparse *F, /* F = A', A(:,f)', or A(p,f)' */ /* --------------- */ cholmod_common *Common ) { Int *Fp, *Fnz, *Ap, *Ai, *Anz, *Wi ; Int nrow, ncol, permute, use_fset, Apacked, Fpacked, p, pend, i, j, k, Fsorted, nf, jj, jlast ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (F, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (F, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (A->nrow != F->ncol || A->ncol != F->nrow) { ERROR (CHOLMOD_INVALID, "F has the wrong dimensions") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nf = fsize ; use_fset = (fset != NULL) ; nrow = A->nrow ; ncol = A->ncol ; Ap = A->p ; /* size A->ncol+1, column pointers of A */ Ai = A->i ; /* size nz = Ap [A->ncol], row indices of A */ Anz = A->nz ; Apacked = A->packed ; ASSERT (IMPLIES (!Apacked, Anz != NULL)) ; permute = (Perm != NULL) ; Fp = F->p ; /* size A->nrow+1, row pointers of F */ Fnz = F->nz ; Fpacked = F->packed ; ASSERT (IMPLIES (!Fpacked, Fnz != NULL)) ; nf = (use_fset) ? nf : ncol ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = nrow + ((fset != NULL) ? ncol : 0) */ s = CHOLMOD(add_size_t) (nrow, ((fset != NULL) ? ncol : 0), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } Wi = Common->Iwork ; /* size nrow (i/l/l) */ /* ---------------------------------------------------------------------- */ /* check Perm and fset */ /* ---------------------------------------------------------------------- */ if (permute) { for (i = 0 ; i < nrow ; i++) { Wi [i] = 1 ; } for (k = 0 ; k < nrow ; k++) { i = Perm [k] ; if (i < 0 || i > nrow || Wi [i] == 0) { ERROR (CHOLMOD_INVALID, "invalid permutation") ; return (FALSE) ; } Wi [i] = 0 ; } } if (use_fset) { for (j = 0 ; j < ncol ; j++) { Wi [j] = 1 ; } for (k = 0 ; k < nf ; k++) { j = fset [k] ; if (j < 0 || j > ncol || Wi [j] == 0) { ERROR (CHOLMOD_INVALID, "invalid fset") ; return (FALSE) ; } Wi [j] = 0 ; } } /* Perm and fset are now valid */ ASSERT (CHOLMOD(dump_perm) (Perm, nrow, nrow, "Perm", Common)) ; ASSERT (CHOLMOD(dump_perm) (fset, nf, ncol, "fset", Common)) ; /* ---------------------------------------------------------------------- */ /* count the entries in each row of A or A(:,f) */ /* ---------------------------------------------------------------------- */ for (i = 0 ; i < nrow ; i++) { Wi [i] = 0 ; } jlast = EMPTY ; Fsorted = TRUE ; if (use_fset) { /* count entries in each row of A(:,f) */ for (jj = 0 ; jj < nf ; jj++) { j = fset [jj] ; if (j <= jlast) { Fsorted = FALSE ; } p = Ap [j] ; pend = (Apacked) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Wi [Ai [p]]++ ; } jlast = j ; } /* save the nz counts if F is unpacked, and recount all of A */ if (!Fpacked) { if (permute) { for (i = 0 ; i < nrow ; i++) { Fnz [i] = Wi [Perm [i]] ; } } else { for (i = 0 ; i < nrow ; i++) { Fnz [i] = Wi [i] ; } } for (i = 0 ; i < nrow ; i++) { Wi [i] = 0 ; } /* count entries in each row of A */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (Apacked) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Wi [Ai [p]]++ ; } } } } else { /* count entries in each row of A */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (Apacked) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Wi [Ai [p]]++ ; } } /* save the nz counts if F is unpacked */ if (!Fpacked) { if (permute) { for (i = 0 ; i < nrow ; i++) { Fnz [i] = Wi [Perm [i]] ; } } else { for (i = 0 ; i < nrow ; i++) { Fnz [i] = Wi [i] ; } } } } /* ---------------------------------------------------------------------- */ /* compute the row pointers */ /* ---------------------------------------------------------------------- */ p = 0 ; if (permute) { for (i = 0 ; i < nrow ; i++) { Fp [i] = p ; p += Wi [Perm [i]] ; } for (i = 0 ; i < nrow ; i++) { Wi [Perm [i]] = Fp [i] ; } } else { for (i = 0 ; i < nrow ; i++) { Fp [i] = p ; p += Wi [i] ; } for (i = 0 ; i < nrow ; i++) { Wi [i] = Fp [i] ; } } Fp [nrow] = p ; if (p > (Int) (F->nzmax)) { ERROR (CHOLMOD_INVALID, "F is too small") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* transpose matrix, using template routine */ /* ---------------------------------------------------------------------- */ ok = FALSE ; if (values == 0 || F->xtype == CHOLMOD_PATTERN) { ok = p_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } else if (F->xtype == CHOLMOD_REAL) { ok = r_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } else if (F->xtype == CHOLMOD_COMPLEX) { if (values == 1) { /* array transpose */ ok = ct_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } else { /* complex conjugate transpose */ ok = c_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } } else if (F->xtype == CHOLMOD_ZOMPLEX) { if (values == 1) { /* array transpose */ ok = zt_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } else { /* complex conjugate transpose */ ok = z_cholmod_transpose_unsym (A, Perm, fset, nf, F, Common) ; } } /* ---------------------------------------------------------------------- */ /* finalize result F */ /* ---------------------------------------------------------------------- */ if (ok) { F->sorted = Fsorted ; } ASSERT (CHOLMOD(dump_sparse) (F, "output F unsym", Common) >= 0) ; return (ok) ; } /* ========================================================================== */ /* === cholmod_transpose_sym ================================================ */ /* ========================================================================== */ /* Compute F = A' or A (p,p)', where A is symmetric and F is already allocated. * See cholmod_transpose for a simpler routine. * * workspace: Iwork (nrow) if Perm NULL, Iwork (2*nrow) if Perm non-NULL. */ int CHOLMOD(transpose_sym) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 2: complex conj. transpose, 1: array transpose, 0: do not transpose the numerical values */ Int *Perm, /* size nrow, if present (can be NULL) */ /* ---- output --- */ cholmod_sparse *F, /* F = A' or A(p,p)' */ /* --------------- */ cholmod_common *Common ) { Int *Ap, *Anz, *Ai, *Fp, *Wi, *Pinv, *Iwork ; Int p, pend, packed, upper, permute, jold, n, i, j, k, iold ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (F, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (F, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (A->nrow != A->ncol || A->stype == 0) { /* this routine handles square symmetric matrices only */ ERROR (CHOLMOD_INVALID, "matrix must be symmetric") ; return (FALSE) ; } if (A->nrow != F->ncol || A->ncol != F->nrow) { ERROR (CHOLMOD_INVALID, "F has the wrong dimensions") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ permute = (Perm != NULL) ; n = A->nrow ; Ap = A->p ; /* size A->ncol+1, column pointers of A */ Ai = A->i ; /* size nz = Ap [A->ncol], row indices of A */ Anz = A->nz ; packed = A->packed ; ASSERT (IMPLIES (!packed, Anz != NULL)) ; upper = (A->stype > 0) ; Fp = F->p ; /* size A->nrow+1, row pointers of F */ /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = (Perm != NULL) ? 2*n : n */ s = CHOLMOD(add_size_t) (n, ((Perm != NULL) ? n : 0), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Wi = Iwork ; /* size n (i/l/l) */ Pinv = Iwork + n ; /* size n (i/i/l) , unused if Perm NULL */ /* ---------------------------------------------------------------------- */ /* check Perm and construct inverse permutation */ /* ---------------------------------------------------------------------- */ if (permute) { for (i = 0 ; i < n ; i++) { Pinv [i] = EMPTY ; } for (k = 0 ; k < n ; k++) { i = Perm [k] ; if (i < 0 || i > n || Pinv [i] != EMPTY) { ERROR (CHOLMOD_INVALID, "invalid permutation") ; return (FALSE) ; } Pinv [i] = k ; } } /* Perm is now valid */ ASSERT (CHOLMOD(dump_perm) (Perm, n, n, "Perm", Common)) ; /* ---------------------------------------------------------------------- */ /* count the entries in each row of F */ /* ---------------------------------------------------------------------- */ for (i = 0 ; i < n ; i++) { Wi [i] = 0 ; } if (packed) { if (permute) { if (upper) { /* packed, permuted, upper */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; pend = Ap [jold+1] ; for (p = Ap [jold] ; p < pend ; p++) { iold = Ai [p] ; if (iold <= jold) { i = Pinv [iold] ; Wi [MIN (i, j)]++ ; } } } } else { /* packed, permuted, lower */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; pend = Ap [jold+1] ; for (p = Ap [jold] ; p < pend ; p++) { iold = Ai [p] ; if (iold >= jold) { i = Pinv [iold] ; Wi [MAX (i, j)]++ ; } } } } } else { if (upper) { /* packed, unpermuted, upper */ for (j = 0 ; j < n ; j++) { pend = Ap [j+1] ; for (p = Ap [j] ; p < pend ; p++) { i = Ai [p] ; if (i <= j) { Wi [i]++ ; } } } } else { /* packed, unpermuted, lower */ for (j = 0 ; j < n ; j++) { pend = Ap [j+1] ; for (p = Ap [j] ; p < pend ; p++) { i = Ai [p] ; if (i >= j) { Wi [i]++ ; } } } } } } else { if (permute) { if (upper) { /* unpacked, permuted, upper */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; p = Ap [jold] ; pend = p + Anz [jold] ; for ( ; p < pend ; p++) { iold = Ai [p] ; if (iold <= jold) { i = Pinv [iold] ; Wi [MIN (i, j)]++ ; } } } } else { /* unpacked, permuted, lower */ for (j = 0 ; j < n ; j++) { jold = Perm [j] ; p = Ap [jold] ; pend = p + Anz [jold] ; for ( ; p < pend ; p++) { iold = Ai [p] ; if (iold >= jold) { i = Pinv [iold] ; Wi [MAX (i, j)]++ ; } } } } } else { if (upper) { /* unpacked, unpermuted, upper */ for (j = 0 ; j < n ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i <= j) { Wi [i]++ ; } } } } else { /* unpacked, unpermuted, lower */ for (j = 0 ; j < n ; j++) { p = Ap [j] ; pend = p + Anz [j] ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= j) { Wi [i]++ ; } } } } } } /* ---------------------------------------------------------------------- */ /* compute the row pointers */ /* ---------------------------------------------------------------------- */ p = 0 ; for (i = 0 ; i < n ; i++) { Fp [i] = p ; p += Wi [i] ; } Fp [n] = p ; for (i = 0 ; i < n ; i++) { Wi [i] = Fp [i] ; } if (p > (Int) (F->nzmax)) { ERROR (CHOLMOD_INVALID, "F is too small") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* transpose matrix, using template routine */ /* ---------------------------------------------------------------------- */ ok = FALSE ; if (values == 0 || F->xtype == CHOLMOD_PATTERN) { PRINT2 (("\n:::: p_transpose_sym Perm %p\n", Perm)) ; ok = p_cholmod_transpose_sym (A, Perm, F, Common) ; } else if (F->xtype == CHOLMOD_REAL) { PRINT2 (("\n:::: r_transpose_sym Perm %p\n", Perm)) ; ok = r_cholmod_transpose_sym (A, Perm, F, Common) ; } else if (F->xtype == CHOLMOD_COMPLEX) { if (values == 1) { /* array transpose */ PRINT2 (("\n:::: ct_transpose_sym Perm %p\n", Perm)) ; ok = ct_cholmod_transpose_sym (A, Perm, F, Common) ; } else { /* complex conjugate transpose */ PRINT2 (("\n:::: c_transpose_sym Perm %p\n", Perm)) ; ok = c_cholmod_transpose_sym (A, Perm, F, Common) ; } } else if (F->xtype == CHOLMOD_ZOMPLEX) { if (values == 1) { /* array transpose */ PRINT2 (("\n:::: zt_transpose_sym Perm %p\n", Perm)) ; ok = zt_cholmod_transpose_sym (A, Perm, F, Common) ; } else { /* complex conjugate transpose */ PRINT2 (("\n:::: z_transpose_sym Perm %p\n", Perm)) ; ok = z_cholmod_transpose_sym (A, Perm, F, Common) ; } } /* ---------------------------------------------------------------------- */ /* finalize result F */ /* ---------------------------------------------------------------------- */ /* F is sorted if there is no permutation vector */ if (ok) { F->sorted = !permute ; F->packed = TRUE ; F->stype = - SIGN (A->stype) ; /* flip the stype */ ASSERT (CHOLMOD(dump_sparse) (F, "output F sym", Common) >= 0) ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_transpose ==================================================== */ /* ========================================================================== */ /* Returns A'. See also cholmod_ptranspose below. */ cholmod_sparse *CHOLMOD(transpose) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 2: complex conj. transpose, 1: array transpose, 0: do not transpose the numerical values (returns its result as CHOLMOD_PATTERN) */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(ptranspose) (A, values, NULL, NULL, 0, Common)) ; } /* ========================================================================== */ /* === cholmod_ptranspose =================================================== */ /* ========================================================================== */ /* Return A' or A(p,p)' if A is symmetric. Return A', A(:,f)', or A(p,f)' if * A is unsymmetric. * * workspace: * Iwork (MAX (nrow,ncol)) if unsymmetric and fset is non-NULL * Iwork (nrow) if unsymmetric and fset is NULL * Iwork (2*nrow) if symmetric and Perm is non-NULL. * Iwork (nrow) if symmetric and Perm is NULL. * * A simple worst-case upper bound on the workspace is nrow+ncol. */ cholmod_sparse *CHOLMOD(ptranspose) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 2: complex conj. transpose, 1: array transpose, 0: do not transpose the numerical values */ Int *Perm, /* if non-NULL, F = A(p,f) or A(p,p) */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) { Int *Ap, *Anz ; cholmod_sparse *F ; Int nrow, ncol, use_fset, j, jj, fnz, packed, stype, nf, xtype ; size_t ineed ; int ok = TRUE ; nf = fsize ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; stype = A->stype ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; if (stype != 0) { use_fset = FALSE ; if (Perm != NULL) { ineed = CHOLMOD(mult_size_t) (A->nrow, 2, &ok) ; } else { ineed = A->nrow ; } } else { use_fset = (fset != NULL) ; if (use_fset) { ineed = MAX (A->nrow, A->ncol) ; } else { ineed = A->nrow ; } } if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } CHOLMOD(allocate_work) (0, ineed, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Anz = A->nz ; packed = A->packed ; ASSERT (IMPLIES (!packed, Anz != NULL)) ; xtype = values ? A->xtype : CHOLMOD_PATTERN ; /* ---------------------------------------------------------------------- */ /* allocate F */ /* ---------------------------------------------------------------------- */ /* determine # of nonzeros in F */ if (stype != 0) { /* F=A' or F=A(p,p)', fset is ignored */ fnz = CHOLMOD(nnz) (A, Common) ; } else { nf = (use_fset) ? nf : ncol ; if (use_fset) { fnz = 0 ; /* F=A(:,f)' or F=A(p,f)' */ for (jj = 0 ; jj < nf ; jj++) { /* The fset is not yet checked; it will be thoroughly checked * in cholmod_transpose_unsym. For now, just make sure we don't * access Ap and Anz out of bounds. */ j = fset [jj] ; if (j >= 0 && j < ncol) { fnz += packed ? (Ap [j+1] - Ap [j]) : MAX (0, Anz [j]) ; } } } else { /* F=A' or F=A(p,:)' */ fnz = CHOLMOD(nnz) (A, Common) ; } } /* F is ncol-by-nrow, fnz nonzeros, sorted unless f is present and unsorted, * packed, of opposite stype as A, and with/without numerical values */ F = CHOLMOD(allocate_sparse) (ncol, nrow, fnz, TRUE, TRUE, -SIGN(stype), xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* transpose and optionally permute the matrix A */ /* ---------------------------------------------------------------------- */ if (stype != 0) { /* F = A (p,p)', using upper or lower triangular part of A only */ ok = CHOLMOD(transpose_sym) (A, values, Perm, F, Common) ; } else { /* F = A (p,f)' */ ok = CHOLMOD(transpose_unsym) (A, values, Perm, fset, nf, F, Common) ; } /* ---------------------------------------------------------------------- */ /* return the matrix F, or NULL if an error occured */ /* ---------------------------------------------------------------------- */ if (!ok) { CHOLMOD(free_sparse) (&F, Common) ; } return (F) ; } /* ========================================================================== */ /* === cholmod_sort ========================================================= */ /* ========================================================================== */ /* Sort the columns of A, in place. Returns A in packed form, even if it * starts as unpacked. Removes entries in the ignored part of a symmetric * matrix. * * workspace: Iwork (max (nrow,ncol)). Allocates additional workspace for a * temporary copy of A'. */ int CHOLMOD(sort) ( /* ---- in/out --- */ cholmod_sparse *A, /* matrix to sort */ /* --------------- */ cholmod_common *Common ) { Int *Ap ; cholmod_sparse *F ; Int anz, ncol, nrow, stype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; nrow = A->nrow ; if (nrow <= 1) { /* a 1-by-n sparse matrix must be sorted */ A->sorted = TRUE ; return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ ncol = A->ncol ; CHOLMOD(allocate_work) (0, MAX (nrow, ncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ anz = CHOLMOD(nnz) (A, Common) ; stype = A->stype ; /* ---------------------------------------------------------------------- */ /* sort the columns of the matrix */ /* ---------------------------------------------------------------------- */ /* allocate workspace for transpose: ncol-by-nrow, same # of nonzeros as A, * sorted, packed, same stype as A, and of the same numeric type as A. */ F = CHOLMOD(allocate_sparse) (ncol, nrow, anz, TRUE, TRUE, stype, A->xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } if (stype != 0) { /* F = A', upper or lower triangular part only */ CHOLMOD(transpose_sym) (A, 1, NULL, F, Common) ; A->packed = TRUE ; /* A = F' */ CHOLMOD(transpose_sym) (F, 1, NULL, A, Common) ; } else { /* F = A' */ CHOLMOD(transpose_unsym) (A, 1, NULL, NULL, 0, F, Common) ; A->packed = TRUE ; /* A = F' */ CHOLMOD(transpose_unsym) (F, 1, NULL, NULL, 0, A, Common) ; } ASSERT (A->sorted && A->packed) ; ASSERT (CHOLMOD(dump_sparse) (A, "Asorted", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* reduce A in size, if needed. This must succeed. */ /* ---------------------------------------------------------------------- */ Ap = A->p ; anz = Ap [ncol] ; ASSERT ((size_t) anz <= A->nzmax) ; CHOLMOD(reallocate_sparse) (anz, A, Common) ; ASSERT (Common->status >= CHOLMOD_OK) ; /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&F, Common) ; return (TRUE) ; } igraph/src/CHOLMOD/Core/cholmod_triplet.c0000644000175100001440000005605113431000472017643 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_triplet ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_triplet object: * * A sparse matrix held in triplet form is the simplest one for a user to * create. It consists of a list of nz entries in arbitrary order, held in * three arrays: i, j, and x, each of length nk. The kth entry is in row i[k], * column j[k], with value x[k]. There may be duplicate values; if A(i,j) * appears more than once, its value is the sum of the entries with those row * and column indices. * * Primary routines: * ----------------- * cholmod_allocate_triplet allocate a triplet matrix * cholmod_free_triplet free a triplet matrix * * Secondary routines: * ------------------- * cholmod_reallocate_triplet reallocate a triplet matrix * cholmod_sparse_to_triplet create a triplet matrix copy of a sparse matrix * cholmod_triplet_to_sparse create a sparse matrix copy of a triplet matrix * cholmod_copy_triplet create a copy of a triplet matrix * * The relationship between an m-by-n cholmod_sparse matrix A and a * cholmod_triplet matrix (i, j, and x) is identical to how they are used in * the MATLAB "sparse" and "find" functions: * * [i j x] = find (A) * [m n] = size (A) * A = sparse (i,j,x,m,n) * * with the exception that the cholmod_sparse matrix may be "unpacked", may * have either sorted or unsorted columns (depending on the option selected), * and may be symmetric with just the upper or lower triangular part stored. * Likewise, the cholmod_triplet matrix may contain just the entries in the * upper or lower triangular part of a symmetric matrix. * * MATLAB sparse matrices are always "packed", always have sorted columns, * and always store both parts of a symmetric matrix. In some cases, MATLAB * behaves like CHOLMOD by ignoring entries in the upper or lower triangular * part of a matrix that is otherwise assumed to be symmetric (such as the * input to chol). In CHOLMOD, that option is a characteristic of the object. * In MATLAB, that option is based on how a matrix is used as the input to * a function. * * The triplet matrix is provided to give the user a simple way of constructing * a sparse matrix. There are very few operations supported for triplet * matrices. The assumption is that they will be converted to cholmod_sparse * matrix form first. * * Adding two triplet matrices simply involves concatenating the contents of * the three arrays (i, j, and x). To permute a triplet matrix, just replace * the row and column indices with their permuted values. For example, if * P is a permutation vector, then P [k] = j means row/column j is the kth * row/column in C=P*A*P'. In MATLAB notation, C=A(p,p). If Pinv is an array * of size n and T is the triplet form of A, then: * * Ti = T->i ; * Tj = T->j ; * for (k = 0 ; k < n ; k++) Pinv [P [k]] = k ; * for (k = 0 ; k < nz ; k++) Ti [k] = Pinv [Ti [k]] ; * for (k = 0 ; k < nz ; k++) Tj [k] = Pinv [Tj [k]] ; * * overwrites T with the triplet form of C=P*A*P'. The conversion * * C = cholmod_triplet_to_sparse (T, 0, &Common) ; * * will then return the matrix C = P*A*P'. * * Note that T->stype > 0 means that entries in the lower triangular part of * T are transposed into the upper triangular part when T is converted to * sparse matrix (cholmod_sparse) form with cholmod_triplet_to_sparse. The * opposite is true for T->stype < 0. * * Since the triplet matrix T is so simple to generate, it's quite easy * to remove entries that you do not want, prior to converting T to the * cholmod_sparse form. So if you include these entries in T, CHOLMOD * assumes that there must be a reason (such as the one above). Thus, * no entry in a triplet matrix is ever ignored. * * Other operations, such as extacting a submatrix, horizontal and vertical * concatenation, multiply a triplet matrix times a dense matrix, are also * simple. Multiplying two triplet matrices is not trivial; the simplest * method is to convert them to cholmod_sparse matrices first. * * Supports all xtypes (pattern, real, complex, and zomplex). */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define PATTERN #include "t_cholmod_triplet.c" #define REAL #include "t_cholmod_triplet.c" #define COMPLEX #include "t_cholmod_triplet.c" #define ZOMPLEX #include "t_cholmod_triplet.c" /* ========================================================================== */ /* === cholmod_allocate_triplet ============================================= */ /* ========================================================================== */ /* allocate space for a triplet matrix * * workspace: none */ cholmod_triplet *CHOLMOD(allocate_triplet) ( /* ---- input ---- */ size_t nrow, /* # of rows of T */ size_t ncol, /* # of columns of T */ size_t nzmax, /* max # of nonzeros of T */ int stype, /* stype of T */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_triplet *T ; size_t nzmax0 ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; if (xtype < CHOLMOD_PATTERN || xtype > CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "xtype invalid") ; return (NULL) ; } /* ensure the dimensions do not cause integer overflow */ (void) CHOLMOD(add_size_t) (ncol, 2, &ok) ; if (!ok || nrow > Int_max || ncol > Int_max || nzmax > Int_max) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate header */ /* ---------------------------------------------------------------------- */ T = CHOLMOD(malloc) (sizeof (cholmod_triplet), 1, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } PRINT1 (("cholmod_allocate_triplet %d-by-%d nzmax %d xtype %d\n", nrow, ncol, nzmax, xtype)) ; nzmax = MAX (1, nzmax) ; T->nrow = nrow ; T->ncol = ncol ; T->nzmax = nzmax ; T->nnz = 0 ; T->stype = stype ; T->itype = ITYPE ; T->xtype = xtype ; T->dtype = DTYPE ; T->j = NULL ; T->i = NULL ; T->x = NULL ; T->z = NULL ; /* ---------------------------------------------------------------------- */ /* allocate the matrix itself */ /* ---------------------------------------------------------------------- */ nzmax0 = 0 ; CHOLMOD(realloc_multiple) (nzmax, 2, xtype, &(T->i), &(T->j), &(T->x), &(T->z), &nzmax0, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_triplet) (&T, Common) ; return (NULL) ; /* out of memory */ } return (T) ; } /* ========================================================================== */ /* === cholmod_free_triplet ================================================= */ /* ========================================================================== */ /* free a triplet matrix * * workspace: none */ int CHOLMOD(free_triplet) ( /* ---- in/out --- */ cholmod_triplet **THandle, /* matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) { Int nz ; cholmod_triplet *T ; RETURN_IF_NULL_COMMON (FALSE) ; if (THandle == NULL) { /* nothing to do */ return (TRUE) ; } T = *THandle ; if (T == NULL) { /* nothing to do */ return (TRUE) ; } nz = T->nzmax ; T->j = CHOLMOD(free) (nz, sizeof (Int), T->j, Common) ; T->i = CHOLMOD(free) (nz, sizeof (Int), T->i, Common) ; if (T->xtype == CHOLMOD_REAL) { T->x = CHOLMOD(free) (nz, sizeof (double), T->x, Common) ; } else if (T->xtype == CHOLMOD_COMPLEX) { T->x = CHOLMOD(free) (nz, 2*sizeof (double), T->x, Common) ; } else if (T->xtype == CHOLMOD_ZOMPLEX) { T->x = CHOLMOD(free) (nz, sizeof (double), T->x, Common) ; T->z = CHOLMOD(free) (nz, sizeof (double), T->z, Common) ; } *THandle = CHOLMOD(free) (1, sizeof (cholmod_triplet), (*THandle), Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_reallocate_triplet =========================================== */ /* ========================================================================== */ /* Change the size of T->i, T->j, and T->x, or allocate them if their current * size is zero. T->x is not modified if T->xtype is CHOLMOD_PATTERN. * * workspace: none */ int CHOLMOD(reallocate_triplet) ( /* ---- input ---- */ size_t nznew, /* new # of entries in T */ /* ---- in/out --- */ cholmod_triplet *T, /* triplet matrix to modify */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (T, FALSE) ; RETURN_IF_XTYPE_INVALID (T, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; PRINT1 (("realloc triplet %d to %d, xtype: %d\n", T->nzmax, nznew, T->xtype)) ; /* ---------------------------------------------------------------------- */ /* resize the matrix */ /* ---------------------------------------------------------------------- */ CHOLMOD(realloc_multiple) (MAX (1,nznew), 2, T->xtype, &(T->i), &(T->j), &(T->x), &(T->z), &(T->nzmax), Common) ; return (Common->status == CHOLMOD_OK) ; } /* ========================================================================== */ /* === cholmod_triplet_to_sparse ============================================ */ /* ========================================================================== */ /* Convert a set of triplets into a cholmod_sparse matrix. In MATLAB notation, * for unsymmetric matrices: * * A = sparse (Ti, Tj, Tx, nrow, ncol, nzmax) ; * * For the symmetric upper case: * * A = sparse (min(Ti,Tj), max(Ti,Tj), Tx, nrow, ncol, nzmax) ; * * For the symmetric lower case: * * A = sparse (max(Ti,Tj), min(Ti,Tj), Tx, nrow, ncol, nzmax) ; * * If Tx is NULL, then A->x is not allocated, and only the pattern of A is * computed. A is returned in packed form, and can be of any stype * (upper/lower/unsymmetric). It has enough space to hold the values in T, * or nzmax, whichever is larger. * * workspace: Iwork (max (nrow,ncol)) * allocates a temporary copy of its output matrix. * * The resulting sparse matrix has the same xtype as the input triplet matrix. */ cholmod_sparse *CHOLMOD(triplet_to_sparse) ( /* ---- input ---- */ cholmod_triplet *T, /* matrix to copy */ size_t nzmax, /* allocate at least this much space in output matrix */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *R, *A = NULL ; Int *Wj, *Rp, *Ri, *Rnz, *Ti, *Tj ; Int i, j, p, k, stype, nrow, ncol, nz, ok ; size_t anz = 0 ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (T, NULL) ; Ti = T->i ; Tj = T->j ; RETURN_IF_NULL (Ti, NULL) ; RETURN_IF_NULL (Tj, NULL) ; RETURN_IF_XTYPE_INVALID (T, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; stype = SIGN (T->stype) ; if (stype && T->nrow != T->ncol) { /* inputs invalid */ ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_triplet) (T, "T", Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = T->nrow ; ncol = T->ncol ; nz = T->nnz ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(allocate_work) (0, MAX (nrow, ncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* allocate temporary matrix R */ /* ---------------------------------------------------------------------- */ R = CHOLMOD(allocate_sparse) (ncol, nrow, nz, FALSE, FALSE, -stype, T->xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } Rp = R->p ; Ri = R->i ; Rnz = R->nz ; /* ---------------------------------------------------------------------- */ /* count the entries in each row of A (also counting duplicates) */ /* ---------------------------------------------------------------------- */ for (i = 0 ; i < nrow ; i++) { Rnz [i] = 0 ; } if (stype > 0) { for (k = 0 ; k < nz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i < 0 || i >= nrow || j < 0 || j >= ncol) { ERROR (CHOLMOD_INVALID, "index out of range") ; break ; } /* A will be symmetric with just the upper triangular part stored. * Create a matrix R that is lower triangular. Entries in the * upper part of R are transposed to the lower part. */ Rnz [MIN (i,j)]++ ; } } else if (stype < 0) { for (k = 0 ; k < nz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i < 0 || i >= nrow || j < 0 || j >= ncol) { ERROR (CHOLMOD_INVALID, "index out of range") ; break ; } /* A will be symmetric with just the lower triangular part stored. * Create a matrix R that is upper triangular. Entries in the * lower part of R are transposed to the upper part. */ Rnz [MAX (i,j)]++ ; } } else { for (k = 0 ; k < nz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i < 0 || i >= nrow || j < 0 || j >= ncol) { ERROR (CHOLMOD_INVALID, "index out of range") ; break ; } /* constructing an unsymmetric matrix */ Rnz [i]++ ; } } if (Common->status < CHOLMOD_OK) { /* triplet matrix is invalid */ CHOLMOD(free_sparse) (&R, Common) ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* construct the row pointers */ /* ---------------------------------------------------------------------- */ p = 0 ; for (i = 0 ; i < nrow ; i++) { Rp [i] = p ; p += Rnz [i] ; } Rp [nrow] = p ; /* use Wj (i/l/l) as temporary row pointers */ Wj = Common->Iwork ; /* size MAX (nrow,ncol) FUTURE WORK: (i/l/l) */ for (i = 0 ; i < nrow ; i++) { Wj [i] = Rp [i] ; } /* ---------------------------------------------------------------------- */ /* construct triplet matrix, using template routine */ /* ---------------------------------------------------------------------- */ switch (T->xtype) { case CHOLMOD_PATTERN: anz = p_cholmod_triplet_to_sparse (T, R, Common) ; break ; case CHOLMOD_REAL: anz = r_cholmod_triplet_to_sparse (T, R, Common) ; break ; case CHOLMOD_COMPLEX: anz = c_cholmod_triplet_to_sparse (T, R, Common) ; break ; case CHOLMOD_ZOMPLEX: anz = z_cholmod_triplet_to_sparse (T, R, Common) ; break ; } /* ---------------------------------------------------------------------- */ /* A = R' (array transpose, not complex conjugate transpose) */ /* ---------------------------------------------------------------------- */ /* workspace: Iwork (R->nrow), which is A->ncol */ ASSERT (CHOLMOD(dump_sparse) (R, "R", Common) >= 0) ; A = CHOLMOD(allocate_sparse) (nrow, ncol, MAX (anz, nzmax), TRUE, TRUE, stype, T->xtype, Common) ; if (stype) { ok = CHOLMOD(transpose_sym) (R, 1, NULL, A, Common) ; } else { ok = CHOLMOD(transpose_unsym) (R, 1, NULL, NULL, 0, A, Common) ; } CHOLMOD(free_sparse) (&R, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&A, Common) ; } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (A, "A = triplet(T) result", Common) >= 0) ; return (A) ; } /* ========================================================================== */ /* === cholmod_sparse_to_triplet ============================================ */ /* ========================================================================== */ /* Converts a sparse column-oriented matrix to triplet form. * The resulting triplet matrix has the same xtype as the sparse matrix. * * workspace: none */ cholmod_triplet *CHOLMOD(sparse_to_triplet) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Az, *Tx, *Tz ; Int *Ap, *Ai, *Ti, *Tj, *Anz ; cholmod_triplet *T ; Int i, xtype, p, pend, k, j, nrow, ncol, nz, stype, packed, up, lo, both ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; stype = SIGN (A->stype) ; nrow = A->nrow ; ncol = A->ncol ; if (stype && nrow != ncol) { /* inputs invalid */ ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } Ax = A->x ; Az = A->z ; xtype = A->xtype ; Common->status = CHOLMOD_OK ; ASSERT (CHOLMOD(dump_sparse) (A, "A", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* allocate triplet matrix */ /* ---------------------------------------------------------------------- */ nz = CHOLMOD(nnz) (A, Common) ; T = CHOLMOD(allocate_triplet) (nrow, ncol, nz, A->stype, A->xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* convert to a sparse matrix */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Anz = A->nz ; packed = A->packed ; Ti = T->i ; Tj = T->j ; Tx = T->x ; Tz = T->z ; T->stype = A->stype ; both = (A->stype == 0) ; up = (A->stype > 0) ; lo = (A->stype < 0) ; k = 0 ; for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (both || (up && i <= j) || (lo && i >= j)) { Ti [k] = Ai [p] ; Tj [k] = j ; if (xtype == CHOLMOD_REAL) { Tx [k] = Ax [p] ; } else if (xtype == CHOLMOD_COMPLEX) { Tx [2*k ] = Ax [2*p ] ; Tx [2*k+1] = Ax [2*p+1] ; } else if (xtype == CHOLMOD_ZOMPLEX) { Tx [k] = Ax [p] ; Tz [k] = Az [p] ; } k++ ; ASSERT (k <= nz) ; } } } T->nnz = k ; /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_triplet) (T, "T", Common)) ; return (T) ; } /* ========================================================================== */ /* === cholmod_copy_triplet ================================================= */ /* ========================================================================== */ /* Create an exact copy of a triplet matrix, except that entries in unused * space are not copied (they might not be initialized, and copying them would * cause program checkers such as purify and valgrind to complain). * The output triplet matrix has the same xtype as the input triplet matrix. */ cholmod_triplet *CHOLMOD(copy_triplet) ( /* ---- input ---- */ cholmod_triplet *T, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { double *Tx, *Tz, *Cx, *Cz ; Int *Ci, *Cj, *Ti, *Tj ; cholmod_triplet *C ; Int xtype, k, nz ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (T, NULL) ; RETURN_IF_XTYPE_INVALID (T, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; nz = T->nnz ; Ti = T->i ; Tj = T->j ; Tx = T->x ; Tz = T->z ; xtype = T->xtype ; RETURN_IF_NULL (Ti, NULL) ; RETURN_IF_NULL (Tj, NULL) ; Common->status = CHOLMOD_OK ; DEBUG (CHOLMOD(dump_triplet) (T, "T input", Common)) ; /* ---------------------------------------------------------------------- */ /* allocate copy */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_triplet) (T->nrow, T->ncol, T->nzmax, T->stype, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* copy the triplet matrix */ /* ---------------------------------------------------------------------- */ Ci = C->i ; Cj = C->j ; Cx = C->x ; Cz = C->z ; C->nnz = nz ; for (k = 0 ; k < nz ; k++) { Ci [k] = Ti [k] ; } for (k = 0 ; k < nz ; k++) { Cj [k] = Tj [k] ; } if (xtype == CHOLMOD_REAL) { for (k = 0 ; k < nz ; k++) { Cx [k] = Tx [k] ; } } else if (xtype == CHOLMOD_COMPLEX) { for (k = 0 ; k < nz ; k++) { Cx [2*k ] = Tx [2*k ] ; Cx [2*k+1] = Tx [2*k+1] ; } } else if (xtype == CHOLMOD_ZOMPLEX) { for (k = 0 ; k < nz ; k++) { Cx [k] = Tx [k] ; Cz [k] = Tz [k] ; } } /* ---------------------------------------------------------------------- */ /* return the result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_triplet) (C, "C triplet copy", Common)) ; return (C) ; } igraph/src/CHOLMOD/Core/t_cholmod_change_factor.c0000644000175100001440000003751313431000472021270 0ustar hornikusers/* ========================================================================== */ /* === Core/t_cholmod_change_factor ========================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine for cholmod_change_factor. All xtypes supported. */ #include "cholmod_template.h" /* ========================================================================== */ /* === t_change_simplicial_numeric ========================================== */ /* ========================================================================== */ static void TEMPLATE (change_simplicial_numeric) ( cholmod_factor *L, Int to_ll, Int to_packed, Int *newLi, double *newLx, double *newLz, Int lnz, Int grow, double grow1, Int grow2, Int make_ll, Int make_monotonic, Int make_ldl, cholmod_common *Common ) { double xlen, dj [1], ljj [1], lj2 [1] ; double *Lx, *Lz ; Int *Lp, *Li, *Lnz ; Int n, j, len, pnew, pold, k, p, pend ; n = L->n ; Lp = L->p ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lnz = L->nz ; if (make_ll) { L->minor = n ; } if (make_monotonic) { /* ------------------------------------------------------------------ */ /* reorder the columns to make them monotonic */ /* ------------------------------------------------------------------ */ pnew = 0 ; for (j = 0 ; j < n ; j++) { /* copy and pack column j */ len = Lnz [j] ; PRINT2 (("j: "ID" Lnz[j] "ID" len "ID" p "ID"\n", j, Lnz [j], len, pnew)) ; pold = Lp [j] ; ASSERT (Li [pold] == j) ; if (make_ll) { /* ---------------------------------------------------------- */ /* copy and convert LDL' to LL' */ /* ---------------------------------------------------------- */ /* dj = Lx [pold] ; */ ASSIGN_REAL (dj,0, Lx,pold) ; if (IS_LE_ZERO (dj [0])) { /* Conversion has failed; matrix is not positive definite. * Do not modify the column so that the LDL' factorization * can be restored if desired, by converting back to LDL'. * Continue the conversion, but flag the error. */ if (L->minor == (size_t) n) { ERROR (CHOLMOD_NOT_POSDEF, "L not positive definite") ; L->minor = j ; } for (k = 0 ; k < len ; k++) { newLi [pnew + k] = Li [pold + k] ; /* newLx [pnew + k] = Lx [pold + k] ; */ ASSIGN (newLx, newLz, pnew+k, Lx, Lz, pold+k) ; } } else { ljj [0] = sqrt (dj [0]) ; newLi [pnew] = j ; /* newLx [pnew] = ljj ; */ ASSIGN_REAL (newLx, pnew, ljj, 0) ; CLEAR_IMAG (newLx, newLz, pnew) ; for (k = 1 ; k < len ; k++) { newLi [pnew + k] = Li [pold + k] ; /* newLx [pnew + k] = Lx [pold + k] * ljj ; */ MULT_REAL (newLx, newLz, pnew+k, Lx, Lz, pold+k, ljj,0); } } } else if (make_ldl) { /* ---------------------------------------------------------- */ /* copy and convert LL' to LDL' */ /* ---------------------------------------------------------- */ /* ljj = Lx [pold] ; */ ASSIGN_REAL (ljj, 0, Lx, pold) ; if (ljj [0] <= 0) { /* matrix is not positive-definite; copy column as-is */ for (k = 0 ; k < len ; k++) { newLi [pnew + k] = Li [pold + k] ; /* newLx [pnew + k] = Lx [pold + k] ; */ ASSIGN (newLx, newLz, pnew+k, Lx, Lz, pold+k) ; } } else { newLi [pnew] = j ; /* newLx [pnew] = ljj*ljj ; */ lj2 [0] = ljj [0] * ljj [0] ; ASSIGN_REAL (newLx, pnew, lj2, 0) ; CLEAR_IMAG (newLx, newLz, pnew) ; for (k = 1 ; k < len ; k++) { newLi [pnew + k] = Li [pold + k] ; /* newLx [pnew + k] = Lx [pold + k] / ljj ; */ DIV_REAL (newLx, newLz, pnew+k, Lx, Lz, pold+k, ljj,0) ; } } } else { /* ---------------------------------------------------------- */ /* copy and leave LL' or LDL' as-is */ /* ---------------------------------------------------------- */ for (k = 0 ; k < len ; k++) { newLi [pnew + k] = Li [pold + k] ; /* newLx [pnew + k] = Lx [pold + k] ; */ ASSIGN (newLx, newLz, pnew+k, Lx, Lz, pold+k) ; } } Lp [j] = pnew ; /* compute len in double to avoid integer overflow */ if (grow) { xlen = (double) len ; xlen = grow1 * xlen + grow2 ; xlen = MIN (xlen, n-j) ; len = (Int) xlen ; } ASSERT (len >= Lnz [j] && len <= n-j) ; pnew += len ; ASSERT (pnew > 0) ; /* integer overflow case already covered */ } Lp [n] = pnew ; PRINT1 (("final pnew = "ID", lnz "ID" lnzmax %g\n", pnew, lnz, (double) L->nzmax)) ; ASSERT (pnew <= lnz) ; /* free the old L->i and L->x and replace with the new ones */ CHOLMOD(free) (L->nzmax, sizeof (Int), L->i, Common) ; #ifdef REAL CHOLMOD(free) (L->nzmax, sizeof (double), L->x, Common) ; #elif defined (COMPLEX) CHOLMOD(free) (L->nzmax, 2*sizeof (double), L->x, Common) ; #else CHOLMOD(free) (L->nzmax, sizeof (double), L->x, Common) ; CHOLMOD(free) (L->nzmax, sizeof (double), L->z, Common) ; #endif L->i = newLi ; L->x = newLx ; L->z = newLz ; L->nzmax = lnz ; /* reconstruct the link list */ natural_list (L) ; } else if (to_packed) { /* ------------------------------------------------------------------ */ /* already monotonic, just pack the columns of L */ /* ------------------------------------------------------------------ */ pnew = 0 ; if (make_ll) { /* -------------------------------------------------------------- */ /* pack and convert LDL' to LL' */ /* -------------------------------------------------------------- */ for (j = 0 ; j < n ; j++) { /* pack column j */ pold = Lp [j] ; len = Lnz [j] ; ASSERT (len > 0) ; ASSERT (Li [pold] == j) ; PRINT2 (("col "ID" pnew "ID" pold "ID"\n", j, pnew, pold)) ; /* dj = Lx [pold] ; */ ASSIGN_REAL (dj,0, Lx,pold) ; if (IS_LE_ZERO (dj [0])) { /* Conversion has failed; matrix is not positive definite. * Do not modify the column so that the LDL' factorization * can be restored if desired, by converting back to LDL'. * Continue the conversion, but flag the error. */ if (L->minor == (size_t) n) { ERROR (CHOLMOD_NOT_POSDEF, "L not positive definite") ; L->minor = j ; } for (k = 0 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; /* Lx [pnew + k] = Lx [pold + k] ; */ ASSIGN (Lx, Lz, pnew+k, Lx, Lz, pold+k) ; } } else { ljj [0] = sqrt (dj [0]) ; Li [pnew] = j ; /* Lx [pnew] = ljj ; */ ASSIGN_REAL (Lx, pnew, ljj, 0) ; CLEAR_IMAG (Lx, Lz, pnew) ; for (k = 1 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; /* Lx [pnew + k] = Lx [pold + k] * ljj ; */ MULT_REAL (Lx, Lz, pnew+k, Lx, Lz, pold+k, ljj,0) ; } } Lp [j] = pnew ; pnew += len ; } } else if (make_ldl) { /* -------------------------------------------------------------- */ /* pack and convert LL' to LDL' */ /* -------------------------------------------------------------- */ for (j = 0 ; j < n ; j++) { /* pack column j */ pold = Lp [j] ; len = Lnz [j] ; /* ljj = Lx [pold] ; */ ASSIGN_REAL (ljj, 0, Lx, pold) ; ASSERT (len > 0) ; PRINT2 (("col "ID" pnew "ID" pold "ID"\n", j, pnew, pold)) ; if (ljj [0] <= 0) { /* matrix is not positive-definite; pack column as-is */ for (k = 0 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; /* Lx [pnew + k] = Lx [pold + k] ; */ ASSIGN (Lx, Lz, pnew+k, Lx, Lz, pold+k) ; } } else { Li [pnew] = Li [pold] ; /* Lx [pnew] = ljj*ljj ; */ lj2 [0] = ljj [0] * ljj [0] ; ASSIGN_REAL (Lx, pnew, lj2, 0) ; CLEAR_IMAG (Lx, Lz, pnew) ; for (k = 1 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; /* Lx [pnew + k] = Lx [pold + k] / ljj ; */ DIV_REAL (Lx, Lz, pnew+k, Lx, Lz, pold+k, ljj,0) ; } } Lp [j] = pnew ; pnew += len ; } } else { /* ---------------------------------------------------------- */ /* pack and leave LL' or LDL' as-is */ /* ---------------------------------------------------------- */ for (j = 0 ; j < n ; j++) { /* pack column j */ pold = Lp [j] ; len = Lnz [j] ; ASSERT (len > 0) ; PRINT2 (("col "ID" pnew "ID" pold "ID"\n", j, pnew, pold)) ; if (pnew < pold) { PRINT2 ((" pack this column\n")) ; for (k = 0 ; k < len ; k++) { Li [pnew + k] = Li [pold + k] ; /* Lx [pnew + k] = Lx [pold + k] ; */ ASSIGN (Lx, Lz, pnew+k, Lx, Lz, pold+k) ; } Lp [j] = pnew ; } pnew += len ; } } Lp [n] = pnew ; PRINT2 (("Lp [n] = "ID"\n", pnew)) ; } else if (make_ll) { /* ------------------------------------------------------------------ */ /* convert LDL' to LL', but do so in-place */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < n ; j++) { p = Lp [j] ; pend = p + Lnz [j] ; /* dj = Lx [p] ; */ ASSIGN_REAL (dj,0, Lx,p) ; if (IS_LE_ZERO (dj [0])) { /* Conversion has failed; matrix is not positive definite. * Do not modify the column so that the LDL' factorization * can be restored if desired, by converting back to LDL'. * Continue the conversion, but flag the error. */ if (L->minor == (size_t) n) { ERROR (CHOLMOD_NOT_POSDEF, "L not positive definite") ; L->minor = j ; } } else { ljj [0] = sqrt (dj [0]) ; /* Lx [p] = ljj ; */ ASSIGN_REAL (Lx,p, ljj,0) ; CLEAR_IMAG (Lx, Lz, p) ; for (p++ ; p < pend ; p++) { /* Lx [p] *= ljj ; */ MULT_REAL (Lx,Lz,p, Lx,Lz,p, ljj,0) ; } } } } else if (make_ldl) { /* ------------------------------------------------------------------ */ /* convert LL' to LDL', but do so in-place */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < n ; j++) { p = Lp [j] ; pend = p + Lnz [j] ; /* ljj = Lx [p] ; */ ASSIGN_REAL (ljj, 0, Lx, p) ; if (ljj [0] > 0) { /* Lx [p] = ljj*ljj ; */ lj2 [0] = ljj [0] * ljj [0] ; ASSIGN_REAL (Lx, p, lj2, 0) ; CLEAR_IMAG (Lx, Lz, p) ; for (p++ ; p < pend ; p++) { /* Lx [p] /= ljj ; */ DIV_REAL (Lx,Lz,p, Lx,Lz,p, ljj,0) ; } } } } L->is_ll = to_ll ; DEBUG (CHOLMOD(dump_factor) (L, "done change simplicial numeric", Common)) ; } /* ========================================================================== */ /* === t_ll_super_to_simplicial_numeric ===================================== */ /* ========================================================================== */ /* A supernodal L can only be real or complex, not zomplex */ #ifndef ZOMPLEX static void TEMPLATE (ll_super_to_simplicial_numeric) ( cholmod_factor *L, Int to_packed, Int to_ll, cholmod_common *Common ) { double ljj [1], lj2 [1] ; double *Lx ; Int *Ls, *Lpi, *Lpx, *Super, *Lp, *Li, *Lnz ; Int n, lnz, s, nsuper, p, psi, psx, psend, nsrow, nscol, ii, jj, j, k1, k2, q ; L->is_ll = to_ll ; Lp = L->p ; Li = L->i ; Lx = L->x ; Lnz = L->nz ; lnz = L->nzmax ; n = L->n ; nsuper = L->nsuper ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Super = L->super ; p = 0 ; for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; psx = Lpx [s] ; nsrow = psend - psi ; nscol = k2 - k1 ; for (jj = 0 ; jj < nscol ; jj++) { /* column j of L starts here */ j = jj + k1 ; if (to_ll) { if (to_packed) { /* ------------------------------------------------------ */ /* convert to LL' packed */ /* ------------------------------------------------------ */ Lp [j] = p ; PRINT2 (("Col j "ID" p "ID"\n", j, p)) ; for (ii = jj ; ii < nsrow ; ii++) { /* get L(i,j) from supernode and store in column j */ ASSERT (p < (Int) (L->xsize) && p <= psx+ii+jj*nsrow) ; Li [p] = Ls [psi + ii] ; /* Lx [p] = Lx [psx + ii + jj*nsrow] ; */ q = psx + ii + jj*nsrow ; ASSIGN (Lx,-,p, Lx,-,q) ; PRINT2 ((" i "ID" ", Li [p])) ; XPRINT2 (Lx,-,q) ; PRINT2 (("\n")) ; p++ ; } Lnz [j] = p - Lp [j] ; } else { /* ------------------------------------------------------ */ /* convert to LL' unpacked */ /* ------------------------------------------------------ */ p = psx + jj + jj*nsrow ; Lp [j] = p ; Li [p] = j ; Lnz [j] = nsrow - jj ; p++ ; for (ii = jj + 1 ; ii < nsrow ; ii++) { /* get L(i,j) from supernode and store in column j */ Li [psx + ii + jj*nsrow] = Ls [psi + ii] ; } } } else { if (to_packed) { /* ------------------------------------------------------ */ /* convert to LDL' packed */ /* ------------------------------------------------------ */ Lp [j] = p ; PRINT2 (("Col j "ID" p "ID"\n", Lp [j], p)) ; /* ljj = Lx [psx + jj + jj*nsrow] ; */ ASSIGN_REAL (ljj, 0, Lx, psx + jj + jj*nsrow) ; if (ljj [0] <= 0) { /* the matrix is not positive definite; do not divide */ /* Lx [p] = ljj ; */ ASSIGN_REAL (Lx, p, ljj, 0) ; CLEAR_IMAG (Lx, Lz, p) ; ljj [0] = 1 ; } else { lj2 [0] = ljj [0] * ljj [0] ; /* Lx [p] = ljj*ljj ; */ ASSIGN_REAL (Lx, p, lj2, 0) ; CLEAR_IMAG (Lx, Lz, p) ; } Li [p] = j ; p++ ; for (ii = jj + 1 ; ii < nsrow ; ii++) { /* get L(i,j) from supernode and store in column j */ ASSERT (p < (Int) (L->xsize) && p <= psx+ii+jj*nsrow) ; Li [p] = Ls [psi + ii] ; /* Lx [p] = Lx [psx + ii + jj*nsrow] / ljj ; */ q = psx + ii + jj*nsrow ; DIV_REAL (Lx, Lz, p, Lx, Lz, q, ljj,0) ; PRINT2 ((" i "ID" %g\n", Li [p], Lx [p])) ; p++ ; } Lnz [j] = p - Lp [j] ; } else { /* ------------------------------------------------------ */ /* convert to LDL' unpacked */ /* ------------------------------------------------------ */ p = psx + jj + jj*nsrow ; Lp [j] = p ; /* ljj = Lx [p] ; */ ASSIGN_REAL (ljj,0, Lx,p) ; if (ljj [0] <= 0) { /* the matrix is not positive definite; do not divide */ /* Lx [p] = ljj ; */ ASSIGN_REAL (Lx, p, ljj, 0) ; CLEAR_IMAG (Lx, Lz, p) ; ljj [0] = 1 ; } else { lj2 [0] = ljj [0] * ljj [0] ; /* Lx [p] = ljj*ljj ; */ ASSIGN_REAL (Lx, p, lj2, 0) ; CLEAR_IMAG (Lx, Lz, p) ; } Li [p] = j ; Lnz [j] = nsrow - jj ; p++ ; for (ii = jj + 1 ; ii < nsrow ; ii++) { /* get L(i,j) from supernode and store in column j */ Li [psx + ii + jj*nsrow] = Ls [psi + ii] ; /* Lx [psx + ii + jj*nsrow] /= ljj ; */ q = psx + ii + jj*nsrow ; DIV_REAL (Lx, Lz, q, Lx, Lz, q, ljj,0) ; } } } } } if (to_packed) { Lp [n] = p ; PRINT1 (("Final Lp "ID" n "ID" lnz "ID"\n", p, n, lnz)) ; ASSERT (Lp [n] == lnz) ; ASSERT (lnz <= (Int) (L->xsize)) ; /* reduce size of L->x to match L->i. This cannot fail. */ L->x = CHOLMOD(realloc) (lnz, #ifdef COMPLEX 2 * #endif sizeof (double), L->x, &(L->xsize), Common) ; ASSERT (lnz == (Int) (L->xsize)) ; Common->status = CHOLMOD_OK ; } else { Lp [n] = Lpx [nsuper] ; ASSERT (MAX (1,Lp [n]) == (Int) (L->xsize)) ; ASSERT (MAX (1,Lp [n]) == (Int) (L->nzmax)) ; } } #endif #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Core/cholmod_error.c0000644000175100001440000000531413431000472017305 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_error =================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD error-handling routine. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* ==== cholmod_error ======================================================= */ /* ========================================================================== */ /* An error has occurred. Set the status, optionally print an error message, * and call the user error-handling routine (if it exists). If * Common->try_catch is TRUE, then CHOLMOD is inside a try/catch block. * The status is set, but no message is printed and the user error handler * is not called. This is not (yet) an error, since CHOLMOD may recover. * * In the current version, this try/catch mechanism is used internally only in * cholmod_analyze, which tries multiple ordering methods and picks the best * one. If one or more ordering method fails, it keeps going. Only one * ordering needs to succeed for cholmod_analyze to succeed. */ int CHOLMOD(error) ( /* ---- input ---- */ int status, /* error status */ const char *file, /* name of source code file where error occured */ int line, /* line number in source code file where error occured*/ const char *message, /* error message */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = status ; if (!(Common->try_catch)) { #ifndef NPRINT /* print a warning or error message */ if (Common->print_function != NULL) { if (status > 0 && Common->print > 1) { (Common->print_function) ("CHOLMOD warning: %s\n", message) ; fflush (stdout) ; fflush (stderr) ; } else if (Common->print > 0) { (Common->print_function) ("CHOLMOD error: %s\n", message) ; fflush (stdout) ; fflush (stderr) ; } } #endif /* call the user error handler, if it exists */ if (Common->error_handler != NULL) { Common->error_handler (status, file, line, message) ; } } return (TRUE) ; } igraph/src/CHOLMOD/Core/cholmod_change_factor.c0000644000175100001440000011335513431000472020744 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_change_factor =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Change the numeric/symbolic, LL/LDL, simplicial/super, packed/unpacked, * monotonic/non-monotonic status of a cholmod_factor object. * * There are four basic classes of factor types: * * (1) simplicial symbolic: Consists of two size-n arrays: the fill-reducing * permutation (L->Perm) and the nonzero count for each column of L * (L->ColCount). All other factor types also include this information. * L->ColCount may be exact (obtained from the analysis routines), or * it may be a guess. During factorization, and certainly after update/ * downdate, the columns of L can have a different number of nonzeros. * L->ColCount is used to allocate space. L->ColCount is exact for the * supernodal factorizations. The nonzero pattern of L is not kept. * * (2) simplicial numeric: These represent L in a compressed column form. The * variants of this type are: * * LDL': L is unit diagonal. Row indices in column j are located in * L->i [L->p [j] ... L->p [j] + L->nz [j]], and corresponding numeric * values are in the same locations in L->x. The total number of * entries is the sum of L->nz [j]. The unit diagonal is not stored; * D is stored on the diagonal of L instead. L->p may or may not be * monotonic. The order of storage of the columns in L->i and L->x is * given by a doubly-linked list (L->prev and L->next). L->p is of * size n+1, but only the first n entries are used (it is used if L * is converted to a sparse matrix via cholmod_factor_to_sparse). * * For the complex case, L->x is stored interleaved with real/imag * parts, and is of size 2*lnz*sizeof(double). For the zomplex case, * L->x is of size lnz*sizeof(double) and holds the real part; L->z * is the same size and holds the imaginary part. * * LL': This is identical to the LDL' form, except that the non-unit * diagonal of L is stored as the first entry in each column of L. * * (3) supernodal symbolic: A representation of the nonzero pattern of the * supernodes for a supernodal factorization. There are L->nsuper * supernodes. Columns L->super [k] to L->super [k+1]-1 are in the kth * supernode. The row indices for the kth supernode are in * L->s [L->pi [k] ... L->pi [k+1]-1]. The numerical values are not * allocated (L->x), but when they are they will be located in * L->x [L->px [k] ... L->px [k+1]-1], and the L->px array is defined * in this factor type. * * For the complex case, L->x is stored interleaved with real/imag parts, * and is of size 2*L->xsize*sizeof(double). The zomplex supernodal case * is not supported, since it is not compatible with LAPACK and the BLAS. * * (4) supernodal numeric: Always an LL' factorization. L is non-unit * diagonal. L->x contains the numerical values of the supernodes, as * described above for the supernodal symbolic factor. * For the complex case, L->x is stored interleaved, and is of size * 2*L->xsize*sizeof(double). The zomplex supernodal case is not * supported, since it is not compatible with LAPACK and the BLAS. * * FUTURE WORK: support a supernodal LDL' factor. * * * In all cases, the row indices in each column (L->i for simplicial L and * L->s for supernodal L) are kept sorted from low indices to high indices. * This means the diagonal of L (or D for LDL' factors) is always kept as the * first entry in each column. * * The cholmod_change_factor routine can do almost all possible conversions. * It cannot do the following conversions: * * (1) Simplicial numeric types cannot be converted to a supernodal * symbolic type. This would simultaneously deallocate the * simplicial pattern and numeric values and reallocate uninitialized * space for the supernodal pattern. This isn't useful for the user, * and not needed by CHOLMOD's own routines either. * * (2) Only a symbolic factor (simplicial to supernodal) can be converted * to a supernodal numeric factor. * * Some conversions are meant only to be used internally by other CHOLMOD * routines, and should not be performed by the end user. They allocate space * whose contents are undefined: * * (1) converting from simplicial symbolic to supernodal symbolic. * (2) converting any factor to supernodal numeric. * * workspace: no conversion routine uses workspace in Common. No temporary * workspace is allocated. * * Supports all xtypes, except that there is no supernodal zomplex L. * * The to_xtype parameter is used only when converting from symbolic to numeric * or numeric to symbolic. It cannot be used to convert a numeric xtype (real, * complex, or zomplex) to a different numeric xtype. For that conversion, * use cholmod_factor_xtype instead. */ #include "cholmod_internal.h" #include "cholmod_core.h" static void natural_list (cholmod_factor *L) ; /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define REAL #include "t_cholmod_change_factor.c" #define COMPLEX #include "t_cholmod_change_factor.c" #define ZOMPLEX #include "t_cholmod_change_factor.c" /* ========================================================================== */ /* === L_is_packed ========================================================== */ /* ========================================================================== */ /* Return TRUE if the columns of L are packed, FALSE otherwise. For debugging * only. */ #ifndef NDEBUG static int L_is_packed (cholmod_factor *L, cholmod_common *Common) { Int j ; Int *Lnz = L->nz ; Int *Lp = L->p ; Int n = L->n ; if (L->xtype == CHOLMOD_PATTERN || L->is_super) { return (TRUE) ; } if (Lnz == NULL || Lp == NULL) { return (TRUE) ; } for (j = 0 ; j < n ; j++) { PRINT3 (("j: "ID" Lnz "ID" Lp[j+1] "ID" Lp[j] "ID"\n", j, Lnz [j], Lp [j+1], Lp [j])) ; if (Lnz [j] != (Lp [j+1] - Lp [j])) { PRINT2 (("L is not packed\n")) ; return (FALSE) ; } } return (TRUE) ; } #endif /* ========================================================================== */ /* === natural_list ========================================================= */ /* ========================================================================== */ /* Create a naturally-ordered doubly-linked list of columns. */ static void natural_list (cholmod_factor *L) { Int head, tail, n, j ; Int *Lnext, *Lprev ; Lnext = L->next ; Lprev = L->prev ; ASSERT (Lprev != NULL && Lnext != NULL) ; n = L->n ; head = n+1 ; tail = n ; Lnext [head] = 0 ; Lprev [head] = EMPTY ; Lnext [tail] = EMPTY ; Lprev [tail] = n-1 ; for (j = 0 ; j < n ; j++) { Lnext [j] = j+1 ; Lprev [j] = j-1 ; } Lprev [0] = head ; L->is_monotonic = TRUE ; } /* ========================================================================== */ /* === allocate_simplicial_numeric ========================================== */ /* ========================================================================== */ /* Allocate O(n) arrays for simplicial numeric factorization. Initializes * the link lists only. Does not allocate the L->i, L->x, or L->z arrays. */ static int allocate_simplicial_numeric ( cholmod_factor *L, cholmod_common *Common ) { Int n ; Int *Lp, *Lnz, *Lprev, *Lnext ; size_t n1, n2 ; PRINT1 (("Allocate simplicial\n")) ; ASSERT (L->xtype == CHOLMOD_PATTERN || L->is_super) ; ASSERT (L->p == NULL) ; ASSERT (L->nz == NULL) ; ASSERT (L->prev == NULL) ; ASSERT (L->next == NULL) ; n = L->n ; /* this cannot cause size_t overflow */ n1 = ((size_t) n) + 1 ; n2 = ((size_t) n) + 2 ; Lp = CHOLMOD(malloc) (n1, sizeof (Int), Common) ; Lnz = CHOLMOD(malloc) (n, sizeof (Int), Common) ; Lprev = CHOLMOD(malloc) (n2, sizeof (Int), Common) ; Lnext = CHOLMOD(malloc) (n2, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (n1, sizeof (Int), Lp, Common) ; CHOLMOD(free) (n, sizeof (Int), Lnz, Common) ; CHOLMOD(free) (n2, sizeof (Int), Lprev, Common) ; CHOLMOD(free) (n2, sizeof (Int), Lnext, Common) ; PRINT1 (("Allocate simplicial failed\n")) ; return (FALSE) ; /* out of memory */ } /* ============================================== commit the changes to L */ L->p = Lp ; L->nz = Lnz ; L->prev = Lprev ; L->next = Lnext ; /* initialize a doubly linked list for columns in natural order */ natural_list (L) ; PRINT1 (("Allocate simplicial done\n")) ; return (TRUE) ; } /* ========================================================================== */ /* === simplicial_symbolic_to_super_symbolic ================================ */ /* ========================================================================== */ /* Convert a simplicial symbolic factor supernodal symbolic factor. Does not * initialize the new space. */ static int simplicial_symbolic_to_super_symbolic ( cholmod_factor *L, cholmod_common *Common ) { Int nsuper, xsize, ssize ; Int *Lsuper, *Lpi, *Lpx, *Ls ; size_t nsuper1 ; ASSERT (L->xtype == CHOLMOD_PATTERN && !(L->is_super)) ; xsize = L->xsize ; ssize = L->ssize ; nsuper = L->nsuper ; nsuper1 = ((size_t) nsuper) + 1 ; PRINT1 (("simple sym to super sym: ssize "ID" xsize "ID" nsuper "ID"" " status %d\n", ssize, xsize, nsuper, Common->status)) ; /* O(nsuper) arrays, where nsuper <= n */ Lsuper = CHOLMOD(malloc) (nsuper1, sizeof (Int), Common) ; Lpi = CHOLMOD(malloc) (nsuper1, sizeof (Int), Common) ; Lpx = CHOLMOD(malloc) (nsuper1, sizeof (Int), Common) ; /* O(ssize) array, where ssize <= nnz(L), and usually much smaller */ Ls = CHOLMOD(malloc) (ssize, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (nsuper1, sizeof (Int), Lsuper, Common) ; CHOLMOD(free) (nsuper1, sizeof (Int), Lpi, Common) ; CHOLMOD(free) (nsuper1, sizeof (Int), Lpx, Common) ; CHOLMOD(free) (ssize, sizeof (Int), Ls, Common) ; return (FALSE) ; /* out of memory */ } /* ============================================== commit the changes to L */ ASSERT (Lsuper != NULL && Lpi != NULL && Lpx != NULL && Ls != NULL) ; L->maxcsize = 0 ; L->maxesize = 0 ; L->super = Lsuper ; L->pi = Lpi ; L->px = Lpx ; L->s = Ls ; Ls [0] = EMPTY ; /* supernodal pattern undefined */ L->is_super = TRUE ; L->is_ll = TRUE ; /* supernodal LDL' not supported */ L->xtype = CHOLMOD_PATTERN ; L->dtype = DTYPE ; L->minor = L->n ; return (TRUE) ; } /* ========================================================================== */ /* === any_to_simplicial_symbolic =========================================== */ /* ========================================================================== */ /* Convert any factor L to a simplicial symbolic factor, leaving only L->Perm * and L->ColCount. Cannot fail. Any of the components of L (except Perm and * ColCount) may already be free'd. */ static void any_to_simplicial_symbolic ( cholmod_factor *L, int to_ll, cholmod_common *Common ) { Int n, lnz, xs, ss, s, e ; size_t n1, n2 ; /* ============================================== commit the changes to L */ n = L->n ; lnz = L->nzmax ; s = L->nsuper + 1 ; xs = (L->is_super) ? ((Int) (L->xsize)) : (lnz) ; e = (L->xtype == CHOLMOD_COMPLEX ? 2 : 1) ; ss = L->ssize ; /* this cannot cause size_t overflow */ n1 = ((size_t) n) + 1 ; n2 = ((size_t) n) + 2 ; /* free all but the symbolic analysis (Perm and ColCount) */ L->p = CHOLMOD(free) (n1, sizeof (Int), L->p, Common) ; L->i = CHOLMOD(free) (lnz, sizeof (Int), L->i, Common) ; L->x = CHOLMOD(free) (xs, e*sizeof (double), L->x, Common) ; L->z = CHOLMOD(free) (lnz, sizeof (double), L->z, Common) ; L->nz = CHOLMOD(free) (n, sizeof (Int), L->nz, Common) ; L->next = CHOLMOD(free) (n2, sizeof (Int), L->next, Common) ; L->prev = CHOLMOD(free) (n2, sizeof (Int), L->prev, Common) ; L->super = CHOLMOD(free) (s, sizeof (Int), L->super, Common) ; L->pi = CHOLMOD(free) (s, sizeof (Int), L->pi, Common) ; L->px = CHOLMOD(free) (s, sizeof (Int), L->px, Common) ; L->s = CHOLMOD(free) (ss, sizeof (Int), L->s, Common) ; L->nzmax = 0 ; L->is_super = FALSE ; L->xtype = CHOLMOD_PATTERN ; L->dtype = DTYPE ; L->minor = n ; L->is_ll = to_ll ; } /* ========================================================================== */ /* === ll_super_to_super_symbolic =========================================== */ /* ========================================================================== */ /* Convert a numerical supernodal L to symbolic supernodal. Cannot fail. */ static void ll_super_to_super_symbolic ( cholmod_factor *L, cholmod_common *Common ) { /* ============================================== commit the changes to L */ /* free all but the supernodal numerical factor */ ASSERT (L->xtype != CHOLMOD_PATTERN && L->is_super && L->is_ll) ; DEBUG (CHOLMOD(dump_factor) (L, "start to super symbolic", Common)) ; L->x = CHOLMOD(free) (L->xsize, (L->xtype == CHOLMOD_COMPLEX ? 2 : 1) * sizeof (double), L->x, Common) ; L->xtype = CHOLMOD_PATTERN ; L->dtype = DTYPE ; L->minor = L->n ; L->is_ll = TRUE ; /* supernodal LDL' not supported */ DEBUG (CHOLMOD(dump_factor) (L, "done to super symbolic", Common)) ; } /* ========================================================================== */ /* === simplicial_symbolic_to_simplicial_numeric ============================ */ /* ========================================================================== */ /* Convert a simplicial symbolic L to a simplicial numeric L; allocate space * for L using L->ColCount from symbolic analysis, and set L to identity. * * If packed < 0, then this routine is creating a copy of another factor * (via cholmod_copy_factor). In this case, the space is not initialized. */ static void simplicial_symbolic_to_simplicial_numeric ( cholmod_factor *L, int to_ll, int packed, int to_xtype, cholmod_common *Common ) { double grow0, grow1, xlen, xlnz ; double *Lx, *Lz ; Int *Li, *Lp, *Lnz, *ColCount ; Int n, grow, grow2, p, j, lnz, len, ok, e ; ASSERT (L->xtype == CHOLMOD_PATTERN && !(L->is_super)) ; if (!allocate_simplicial_numeric (L, Common)) { PRINT1 (("out of memory, allocate simplicial numeric\n")) ; return ; /* out of memory */ } ASSERT (L->ColCount != NULL && L->nz != NULL && L->p != NULL) ; ASSERT (L->x == NULL && L->z == NULL && L->i == NULL) ; ColCount = L->ColCount ; Lnz = L->nz ; Lp = L->p ; ok = TRUE ; n = L->n ; if (packed < 0) { /* ------------------------------------------------------------------ */ /* used by cholmod_copy_factor to allocate a copy of a factor object */ /* ------------------------------------------------------------------ */ lnz = L->nzmax ; L->nzmax = 0 ; } else if (packed) { /* ------------------------------------------------------------------ */ /* LDL' or LL' packed */ /* ------------------------------------------------------------------ */ PRINT1 (("convert to packed LL' or LDL'\n")) ; lnz = 0 ; for (j = 0 ; ok && j < n ; j++) { /* ensure len is in the range 1 to n-j */ len = ColCount [j] ; len = MAX (1, len) ; len = MIN (len, n-j) ; lnz += len ; ok = (lnz >= 0) ; } for (j = 0 ; j <= n ; j++) { Lp [j] = j ; } for (j = 0 ; j < n ; j++) { Lnz [j] = 1 ; } } else { /* ------------------------------------------------------------------ */ /* LDL' unpacked */ /* ------------------------------------------------------------------ */ PRINT1 (("convert to unpacked\n")) ; /* compute new lnzmax */ /* if any parameter is NaN, grow is false */ grow0 = Common->grow0 ; grow1 = Common->grow1 ; grow2 = Common->grow2 ; grow0 = IS_NAN (grow0) ? 1 : grow0 ; grow1 = IS_NAN (grow1) ? 1 : grow1 ; /* fl.pt. compare, but no NaN's: */ grow = (grow0 >= 1.0) && (grow1 >= 1.0) && (grow2 > 0) ; PRINT1 (("init, grow1 %g grow2 "ID"\n", grow1, grow2)) ; /* initialize Lp and Lnz for each column */ lnz = 0 ; for (j = 0 ; ok && j < n ; j++) { Lp [j] = lnz ; Lnz [j] = 1 ; /* ensure len is in the range 1 to n-j */ len = ColCount [j] ; len = MAX (1, len) ; len = MIN (len, n-j) ; /* compute len in double to avoid integer overflow */ PRINT1 (("ColCount ["ID"] = "ID"\n", j, len)) ; if (grow) { xlen = (double) len ; xlen = grow1 * xlen + grow2 ; xlen = MIN (xlen, n-j) ; len = (Int) xlen ; } ASSERT (len >= 1 && len <= n-j) ; lnz += len ; ok = (lnz >= 0) ; } if (ok) { Lp [n] = lnz ; if (grow) { /* add extra space */ xlnz = (double) lnz ; xlnz *= grow0 ; xlnz = MIN (xlnz, Size_max) ; xlnz = MIN (xlnz, ((double) n * (double) n + (double) n) / 2) ; lnz = (Int) xlnz ; } } } lnz = MAX (1, lnz) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; } /* allocate L->i, L->x, and L->z */ PRINT1 (("resizing from zero size to lnz "ID"\n", lnz)) ; ASSERT (L->nzmax == 0) ; e = (to_xtype == CHOLMOD_COMPLEX ? 2 : 1) ; if (!ok || !CHOLMOD(realloc_multiple) (lnz, 1, to_xtype, &(L->i), NULL, &(L->x), &(L->z), &(L->nzmax), Common)) { L->p = CHOLMOD(free) (n+1, sizeof (Int), L->p, Common) ; L->nz = CHOLMOD(free) (n, sizeof (Int), L->nz, Common) ; L->prev = CHOLMOD(free) (n+2, sizeof (Int), L->prev, Common) ; L->next = CHOLMOD(free) (n+2, sizeof (Int), L->next, Common) ; L->i = CHOLMOD(free) (lnz, sizeof (Int), L->i, Common) ; L->x = CHOLMOD(free) (lnz, e*sizeof (double), L->x, Common) ; L->z = CHOLMOD(free) (lnz, sizeof (double), L->z, Common) ; PRINT1 (("cannot realloc simplicial numeric\n")) ; return ; /* out of memory */ } /* ============================================== commit the changes to L */ /* initialize L to be the identity matrix */ L->xtype = to_xtype ; L->dtype = DTYPE ; L->minor = n ; Li = L->i ; Lx = L->x ; Lz = L->z ; #if 0 if (lnz == 1) { /* the user won't expect to access this entry, but some CHOLMOD * routines may. Set it to zero so that valgrind doesn't complain. */ switch (to_xtype) { case CHOLMOD_REAL: Lx [0] = 0 ; break ; case CHOLMOD_COMPLEX: Lx [0] = 0 ; Lx [1] = 0 ; break ; case CHOLMOD_ZOMPLEX: Lx [0] = 0 ; Lz [0] = 0 ; break ; } } #endif if (packed >= 0) { /* create the unit diagonal for either the LL' or LDL' case */ switch (L->xtype) { case CHOLMOD_REAL: for (j = 0 ; j < n ; j++) { ASSERT (Lp [j] < Lp [j+1]) ; p = Lp [j] ; Li [p] = j ; Lx [p] = 1 ; } break ; case CHOLMOD_COMPLEX: for (j = 0 ; j < n ; j++) { ASSERT (Lp [j] < Lp [j+1]) ; p = Lp [j] ; Li [p] = j ; Lx [2*p ] = 1 ; Lx [2*p+1] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for (j = 0 ; j < n ; j++) { ASSERT (Lp [j] < Lp [j+1]) ; p = Lp [j] ; Li [p] = j ; Lx [p] = 1 ; Lz [p] = 0 ; } break ; } } L->is_ll = to_ll ; PRINT1 (("done convert simplicial symbolic to numeric\n")) ; } /* ========================================================================== */ /* === change_simplicial_numeric ============================================ */ /* ========================================================================== */ /* Change LL' to LDL', LDL' to LL', or leave as-is. * * If to_packed is TRUE, then the columns of L are packed and made monotonic * (to_monotonic is ignored; it is implicitly TRUE). * * If to_monotonic is TRUE but to_packed is FALSE, the columns of L are made * monotonic but not packed. * * If both to_packed and to_monotonic are FALSE, then the columns of L are * left as-is, and the conversion is done in place. * * If L is already monotonic, or if it is to be left non-monotonic, then this * conversion always succeeds. * * When converting an LDL' to LL' factorization, any column with a negative * or zero diagonal entry is not modified so that conversion back to LDL' will * succeed. This can result in a matrix L with a negative entry on the diagonal * If the kth entry on the diagonal of D is negative, it and the kth column of * L are left unchanged. A subsequent conversion back to an LDL' form will also * leave the column unchanged, so the correct LDL' factorization will be * restored. L->minor is set to the smallest k for which D (k,k) is negative. */ static void change_simplicial_numeric ( cholmod_factor *L, int to_ll, int to_packed, int to_monotonic, cholmod_common *Common ) { double grow0, grow1, xlen, xlnz ; void *newLi, *newLx, *newLz ; double *Lx, *Lz ; Int *Lp, *Li, *Lnz ; Int make_monotonic, grow2, n, j, lnz, len, grow, ok, make_ll, make_ldl ; size_t nzmax0 ; PRINT1 (("\n===Change simplicial numeric: %d %d %d\n", to_ll, to_packed, to_monotonic)) ; DEBUG (CHOLMOD(dump_factor) (L, "change simplicial numeric", Common)) ; ASSERT (L->xtype != CHOLMOD_PATTERN && !(L->is_super)) ; make_monotonic = ((to_packed || to_monotonic) && !(L->is_monotonic)) ; make_ll = (to_ll && !(L->is_ll)) ; make_ldl = (!to_ll && L->is_ll) ; n = L->n ; Lp = L->p ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lnz = L->nz ; grow = FALSE ; grow0 = Common->grow0 ; grow1 = Common->grow1 ; grow2 = Common->grow2 ; grow0 = IS_NAN (grow0) ? 1 : grow0 ; grow1 = IS_NAN (grow1) ? 1 : grow1 ; ok = TRUE ; newLi = NULL ; newLx = NULL ; newLz = NULL ; lnz = 0 ; if (make_monotonic) { /* ------------------------------------------------------------------ */ /* Columns out of order, but will be reordered and optionally packed. */ /* ------------------------------------------------------------------ */ PRINT1 (("L is non-monotonic\n")) ; /* compute new L->nzmax */ if (!to_packed) { /* if any parameter is NaN, grow is false */ /* fl.pt. comparisons below are false if any parameter is NaN */ grow = (grow0 >= 1.0) && (grow1 >= 1.0) && (grow2 > 0) ; } for (j = 0 ; ok && j < n ; j++) { len = Lnz [j] ; ASSERT (len >= 1 && len <= n-j) ; /* compute len in double to avoid integer overflow */ if (grow) { xlen = (double) len ; xlen = grow1 * xlen + grow2 ; xlen = MIN (xlen, n-j) ; len = (Int) xlen ; } ASSERT (len >= Lnz [j] && len <= n-j) ; PRINT2 (("j: "ID" Lnz[j] "ID" len "ID" p "ID"\n", j, Lnz [j], len, lnz)) ; lnz += len ; ok = (lnz >= 0) ; } if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return ; } if (grow) { xlnz = (double) lnz ; xlnz *= grow0 ; xlnz = MIN (xlnz, Size_max) ; xlnz = MIN (xlnz, ((double) n * (double) n + (double) n) / 2) ; lnz = (Int) xlnz ; } lnz = MAX (1, lnz) ; PRINT1 (("final lnz "ID"\n", lnz)) ; nzmax0 = 0 ; CHOLMOD(realloc_multiple) (lnz, 1, L->xtype, &newLi, NULL, &newLx, &newLz, &nzmax0, Common) ; if (Common->status < CHOLMOD_OK) { return ; /* out of memory */ } } /* ============================================== commit the changes to L */ /* ---------------------------------------------------------------------- */ /* convert the simplicial L, using template routine */ /* ---------------------------------------------------------------------- */ switch (L->xtype) { case CHOLMOD_REAL: r_change_simplicial_numeric (L, to_ll, to_packed, newLi, newLx, newLz, lnz, grow, grow1, grow2, make_ll, make_monotonic, make_ldl, Common) ; break ; case CHOLMOD_COMPLEX: c_change_simplicial_numeric (L, to_ll, to_packed, newLi, newLx, newLz, lnz, grow, grow1, grow2, make_ll, make_monotonic, make_ldl, Common) ; break ; case CHOLMOD_ZOMPLEX: z_change_simplicial_numeric (L, to_ll, to_packed, newLi, newLx, newLz, lnz, grow, grow1, grow2, make_ll, make_monotonic, make_ldl, Common) ; break ; } DEBUG (CHOLMOD(dump_factor) (L, "L simplicial changed", Common)) ; } /* ========================================================================== */ /* === ll_super_to_simplicial_numeric ======================================= */ /* ========================================================================== */ /* Convert a supernodal numeric factorization to any simplicial numeric one. * Leaves L->xtype unchanged (real or complex, not zomplex since there is * no supernodal zomplex L). */ static void ll_super_to_simplicial_numeric ( cholmod_factor *L, int to_packed, int to_ll, cholmod_common *Common ) { Int *Ls, *Lpi, *Lpx, *Super, *Li ; Int n, lnz, s, nsuper, psi, psend, nsrow, nscol, k1, k2, erows ; DEBUG (CHOLMOD(dump_factor) (L, "start LL super to simplicial", Common)) ; PRINT1 (("super -> simplicial (%d %d)\n", to_packed, to_ll)) ; ASSERT (L->xtype != CHOLMOD_PATTERN && L->is_ll && L->is_super) ; ASSERT (L->x != NULL && L->i == NULL) ; n = L->n ; nsuper = L->nsuper ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Super = L->super ; /* Int overflow cannot occur since supernodal L already exists */ if (to_packed) { /* count the number of nonzeros in L. Each supernode is of the form * * l . . . For this example, nscol = 4 (# columns). nsrow = 9. * l l . . The "." entries are allocated in the supernodal * l l l . factor, but not used. They are not copied to the * l l l l simplicial factor. Some "l" and "e" entries may be * e e e e numerically zero and even symbolically zero if a * e e e e tight simplicial factorization or resymbol were * e e e e done, because of numerical cancellation and relaxed * e e e e supernode amalgamation, respectively. * e e e e */ lnz = 0 ; for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; nsrow = psend - psi ; nscol = k2 - k1 ; ASSERT (nsrow >= nscol) ; erows = nsrow - nscol ; /* lower triangular part, including the diagonal, * counting the "l" terms in the figure above. */ lnz += nscol * (nscol+1) / 2 ; /* rectangular part, below the diagonal block (the "e" terms) */ lnz += nscol * erows ; } ASSERT (lnz <= (Int) (L->xsize)) ; } else { /* Li will be the same size as Lx */ lnz = L->xsize ; } ASSERT (lnz >= 0) ; PRINT1 (("simplicial lnz = "ID" to_packed: %d to_ll: %d L->xsize %g\n", lnz, to_ll, to_packed, (double) L->xsize)) ; Li = CHOLMOD(malloc) (lnz, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { return ; /* out of memory */ } if (!allocate_simplicial_numeric (L, Common)) { CHOLMOD(free) (lnz, sizeof (Int), Li, Common) ; return ; /* out of memory */ } /* ============================================== commit the changes to L */ L->i = Li ; L->nzmax = lnz ; /* ---------------------------------------------------------------------- */ /* convert the supernodal L, using template routine */ /* ---------------------------------------------------------------------- */ switch (L->xtype) { case CHOLMOD_REAL: r_ll_super_to_simplicial_numeric (L, to_packed, to_ll, Common) ; break ; case CHOLMOD_COMPLEX: c_ll_super_to_simplicial_numeric (L, to_packed, to_ll, Common) ; break ; } /* ---------------------------------------------------------------------- */ /* free unused parts of L */ /* ---------------------------------------------------------------------- */ L->super = CHOLMOD(free) (nsuper+1, sizeof (Int), L->super, Common) ; L->pi = CHOLMOD(free) (nsuper+1, sizeof (Int), L->pi, Common) ; L->px = CHOLMOD(free) (nsuper+1, sizeof (Int), L->px, Common) ; L->s = CHOLMOD(free) (L->ssize, sizeof (Int), L->s, Common) ; L->ssize = 0 ; L->xsize = 0 ; L->nsuper = 0 ; L->maxesize = 0 ; L->maxcsize = 0 ; L->is_super = FALSE ; DEBUG (CHOLMOD(dump_factor) (L, "done LL super to simplicial", Common)) ; } /* ========================================================================== */ /* === super_symbolic_to_ll_super =========================================== */ /* ========================================================================== */ /* Convert a supernodal symbolic factorization to a supernodal numeric * factorization by allocating L->x. Contents of L->x are undefined. */ static int super_symbolic_to_ll_super ( int to_xtype, cholmod_factor *L, cholmod_common *Common ) { double *Lx ; Int wentry = (to_xtype == CHOLMOD_REAL) ? 1 : 2 ; PRINT1 (("convert super sym to num\n")) ; ASSERT (L->xtype == CHOLMOD_PATTERN && L->is_super) ; Lx = CHOLMOD(malloc) (L->xsize, wentry * sizeof (double), Common) ; PRINT1 (("xsize %g\n", (double) L->xsize)) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } /* ============================================== commit the changes to L */ if (L->xsize == 1) { /* the caller won't expect to access this entry, but some CHOLMOD * routines may. Set it to zero so that valgrind doesn't complain. */ switch (to_xtype) { case CHOLMOD_REAL: Lx [0] = 0 ; break ; case CHOLMOD_COMPLEX: Lx [0] = 0 ; Lx [1] = 0 ; break ; } } L->x = Lx ; L->xtype = to_xtype ; L->dtype = DTYPE ; L->minor = L->n ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_change_factor ================================================ */ /* ========================================================================== */ /* Convert a factor L. Some conversions simply allocate uninitialized space * that meant to be filled later. * * If the conversion fails, the factor is left in its original form, with one * exception. Converting a supernodal symbolic factor to a simplicial numeric * one (with L=D=I) may leave the factor in simplicial symbolic form. * * Memory allocated for each conversion is listed below. */ int CHOLMOD(change_factor) ( /* ---- input ---- */ int to_xtype, /* convert to CHOLMOD_PATTERN, _REAL, _COMPLEX, or * _ZOMPLEX */ int to_ll, /* TRUE: convert to LL', FALSE: LDL' */ int to_super, /* TRUE: convert to supernodal, FALSE: simplicial */ int to_packed, /* TRUE: pack simplicial columns, FALSE: do not pack */ int to_monotonic, /* TRUE: put simplicial columns in order, FALSE: not */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (to_xtype < CHOLMOD_PATTERN || to_xtype > CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "xtype invalid") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; PRINT1 (("-----convert from (%d,%d,%d,%d,%d) to (%d,%d,%d,%d,%d)\n", L->xtype, L->is_ll, L->is_super, L_is_packed (L, Common), L->is_monotonic, to_xtype, to_ll, to_super, to_packed, to_monotonic)) ; /* ensure all parameters are TRUE/FALSE */ to_ll = BOOLEAN (to_ll) ; to_super = BOOLEAN (to_super) ; ASSERT (BOOLEAN (L->is_ll) == L->is_ll) ; ASSERT (BOOLEAN (L->is_super) == L->is_super) ; if (to_super && to_xtype == CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "supernodal zomplex L not supported") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* convert */ /* ---------------------------------------------------------------------- */ if (to_xtype == CHOLMOD_PATTERN) { /* ------------------------------------------------------------------ */ /* convert to symbolic */ /* ------------------------------------------------------------------ */ if (!to_super) { /* -------------------------------------------------------------- */ /* convert any factor into a simplicial symbolic factor */ /* -------------------------------------------------------------- */ any_to_simplicial_symbolic (L, to_ll, Common) ; /* cannot fail */ } else { /* -------------------------------------------------------------- */ /* convert to a supernodal symbolic factor */ /* -------------------------------------------------------------- */ if (L->xtype != CHOLMOD_PATTERN && L->is_super) { /* convert from supernodal numeric to supernodal symbolic. * this preserves symbolic pattern of L, discards numeric * values */ ll_super_to_super_symbolic (L, Common) ; /* cannot fail */ } else if (L->xtype == CHOLMOD_PATTERN && !(L->is_super)) { /* convert from simplicial symbolic to supernodal symbolic. * contents of supernodal pattern are uninitialized. Not meant * for the end user. */ simplicial_symbolic_to_super_symbolic (L, Common) ; } else { /* cannot convert from simplicial numeric to supernodal * symbolic */ ERROR (CHOLMOD_INVALID, "cannot convert L to supernodal symbolic") ; } } } else { /* ------------------------------------------------------------------ */ /* convert to numeric */ /* ------------------------------------------------------------------ */ if (to_super) { /* -------------------------------------------------------------- */ /* convert to supernodal numeric factor */ /* -------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN) { if (L->is_super) { /* Convert supernodal symbolic to supernodal numeric. * Contents of supernodal numeric values are uninitialized. * This is used by cholmod_super_numeric. Not meant for * the end user. */ super_symbolic_to_ll_super (to_xtype, L, Common) ; } else { /* Convert simplicial symbolic to supernodal numeric. * Contents not defined. This is used by * Core/cholmod_copy_factor only. Not meant for the end * user. */ if (!simplicial_symbolic_to_super_symbolic (L, Common)) { /* failure, convert back to simplicial symbolic */ any_to_simplicial_symbolic (L, to_ll, Common) ; } else { /* conversion to super symbolic OK, allocate numeric * part */ super_symbolic_to_ll_super (to_xtype, L, Common) ; } } } else { /* nothing to do if L is already in supernodal numeric form */ if (!(L->is_super)) { ERROR (CHOLMOD_INVALID, "cannot convert simplicial L to supernodal") ; } /* FUTURE WORK: convert to/from supernodal LL' and LDL' */ } } else { /* -------------------------------------------------------------- */ /* convert any factor to simplicial numeric */ /* -------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN && !(L->is_super)) { /* ---------------------------------------------------------- */ /* convert simplicial symbolic to simplicial numeric (L=I,D=I)*/ /* ---------------------------------------------------------- */ simplicial_symbolic_to_simplicial_numeric (L, to_ll, to_packed, to_xtype, Common) ; } else if (L->xtype != CHOLMOD_PATTERN && L->is_super) { /* ---------------------------------------------------------- */ /* convert a supernodal LL' to simplicial numeric */ /* ---------------------------------------------------------- */ ll_super_to_simplicial_numeric (L, to_packed, to_ll, Common) ; } else if (L->xtype == CHOLMOD_PATTERN && L->is_super) { /* ---------------------------------------------------------- */ /* convert a supernodal symbolic to simplicial numeric (L=D=I)*/ /* ---------------------------------------------------------- */ any_to_simplicial_symbolic (L, to_ll, Common) ; /* if the following fails, it leaves the factor in simplicial * symbolic form */ simplicial_symbolic_to_simplicial_numeric (L, to_ll, to_packed, to_xtype, Common) ; } else { /* ---------------------------------------------------------- */ /* change a simplicial numeric factor */ /* ---------------------------------------------------------- */ /* change LL' to LDL', LDL' to LL', or leave as-is. pack the * columns of L, or leave as-is. Ensure the columns are * monotonic, or leave as-is. */ change_simplicial_numeric (L, to_ll, to_packed, to_monotonic, Common) ; } } } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ return (Common->status >= CHOLMOD_OK) ; } igraph/src/CHOLMOD/Core/cholmod_band.c0000644000175100001440000002332013431000472017055 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_band ==================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* C = tril (triu (A,k1), k2) * * C is a matrix consisting of the diagonals of A from k1 to k2. * * k=0 is the main diagonal of A, k=1 is the superdiagonal, k=-1 is the * subdiagonal, and so on. If A is m-by-n, then: * * k1=-m C = tril (A,k2) * k2=n C = triu (A,k1) * k1=0 and k2=0 C = diag(A), except C is a matrix, not a vector * * Values of k1 and k2 less than -m are treated as -m, and values greater * than n are treated as n. * * A can be of any symmetry (upper, lower, or unsymmetric); C is returned in * the same form, and packed. If A->stype > 0, entries in the lower * triangular part of A are ignored, and the opposite is true if * A->stype < 0. If A has sorted columns, then so does C. * C has the same size as A. * * If inplace is TRUE, then the matrix A is modified in place. * Only packed matrices can be converted in place. * * C can be returned as a numerical valued matrix (if A has numerical values * and mode > 0), as a pattern-only (mode == 0), or as a pattern-only but with * the diagonal entries removed (mode < 0). * * workspace: none * * A can have an xtype of pattern or real. Complex and zomplex cases supported * only if mode <= 0 (in which case the numerical values are ignored). */ #include "cholmod_internal.h" #include "cholmod_core.h" static cholmod_sparse *band /* returns C, or NULL if failure */ ( /* ---- input or in/out if inplace is TRUE --- */ cholmod_sparse *A, /* ---- input ---- */ SuiteSparse_long k1, /* ignore entries below the k1-st diagonal */ SuiteSparse_long k2, /* ignore entries above the k2-nd diagonal */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diagonal) */ int inplace, /* if TRUE, then convert A in place */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Cx ; Int packed, nz, j, p, pend, i, ncol, nrow, jlo, jhi, ilo, ihi, sorted, values, diag ; Int *Ap, *Anz, *Ai, *Cp, *Ci ; cholmod_sparse *C ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; values = (mode > 0) && (A->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; packed = A->packed ; diag = (mode >= 0) ; if (inplace && !packed) { /* cannot operate on an unpacked matrix in place */ ERROR (CHOLMOD_INVALID, "cannot operate on unpacked matrix in-place") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ PRINT1 (("k1 %ld k2 %ld\n", k1, k2)) ; Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; sorted = A->sorted ; if (A->stype > 0) { /* ignore any entries in strictly lower triangular part of A */ k1 = MAX (k1, 0) ; } if (A->stype < 0) { /* ignore any entries in strictly upper triangular part of A */ k2 = MIN (k2, 0) ; } ncol = A->ncol ; nrow = A->nrow ; /* ensure k1 and k2 are in the range -nrow to +ncol to * avoid possible integer overflow if k1 and k2 are huge */ k1 = MAX (-nrow, k1) ; k1 = MIN (k1, ncol) ; k2 = MAX (-nrow, k2) ; k2 = MIN (k2, ncol) ; /* consider columns jlo to jhi. columns outside this range are empty */ jlo = MAX (k1, 0) ; jhi = MIN (k2+nrow, ncol) ; if (k1 > k2) { /* nothing to do */ jlo = ncol ; jhi = ncol ; } /* ---------------------------------------------------------------------- */ /* allocate C, or operate on A in place */ /* ---------------------------------------------------------------------- */ if (inplace) { /* convert A in place */ C = A ; } else { /* count the number of entries in the result C */ nz = 0 ; if (sorted) { for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i > ihi) { break ; } if (i >= ilo && (diag || i != j)) { nz++ ; } } } } else { for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= ilo && i <= ihi && (diag || i != j)) { nz++ ; } } } } /* allocate C; A will not be modified. C is sorted if A is sorted */ C = CHOLMOD(allocate_sparse) (A->nrow, ncol, nz, sorted, TRUE, A->stype, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* construct C */ /* ---------------------------------------------------------------------- */ /* columns 0 to jlo-1 are empty */ for (j = 0 ; j < jlo ; j++) { Cp [j] = 0 ; } nz = 0 ; if (sorted) { if (values) { /* pattern and values */ ASSERT (diag) ; for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i > ihi) { break ; } if (i >= ilo) { Ci [nz] = i ; Cx [nz] = Ax [p] ; nz++ ; } } } } else { /* pattern only, perhaps with no diagonal */ for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i > ihi) { break ; } if (i >= ilo && (diag || i != j)) { Ci [nz++] = i ; } } } } } else { if (values) { /* pattern and values */ ASSERT (diag) ; for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= ilo && i <= ihi) { Ci [nz] = i ; Cx [nz] = Ax [p] ; nz++ ; } } } } else { /* pattern only, perhaps with no diagonal */ for (j = jlo ; j < jhi ; j++) { ilo = j-k2 ; ihi = j-k1 ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= ilo && i <= ihi && (diag || i != j)) { Ci [nz++] = i ; } } } } } /* columns jhi to ncol-1 are empty */ for (j = jhi ; j <= ncol ; j++) { Cp [j] = nz ; } /* ---------------------------------------------------------------------- */ /* reduce A in size if done in place */ /* ---------------------------------------------------------------------- */ if (inplace) { /* free the unused parts of A, and reduce A->i and A->x in size */ ASSERT (MAX (1,nz) <= A->nzmax) ; CHOLMOD(reallocate_sparse) (nz, A, Common) ; ASSERT (Common->status >= CHOLMOD_OK) ; } /* ---------------------------------------------------------------------- */ /* return the result C */ /* ---------------------------------------------------------------------- */ DEBUG (i = CHOLMOD(dump_sparse) (C, "band", Common)) ; ASSERT (IMPLIES (mode < 0, i == 0)) ; return (C) ; } /* ========================================================================== */ /* === cholmod_band ========================================================= */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(band) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to extract band matrix from */ SuiteSparse_long k1, /* ignore entries below the k1-st diagonal */ SuiteSparse_long k2, /* ignore entries above the k2-nd diagonal */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* --------------- */ cholmod_common *Common ) { return (band (A, k1, k2, mode, FALSE, Common)) ; } /* ========================================================================== */ /* === cholmod_band_inplace ================================================= */ /* ========================================================================== */ int CHOLMOD(band_inplace) ( /* ---- input ---- */ SuiteSparse_long k1, /* ignore entries below the k1-st diagonal */ SuiteSparse_long k2, /* ignore entries above the k2-nd diagonal */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix from which entries not in band are removed */ /* --------------- */ cholmod_common *Common ) { return (band (A, k1, k2, mode, TRUE, Common) != NULL) ; } igraph/src/CHOLMOD/Core/cholmod_dense.c0000644000175100001440000005042513431000472017255 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_dense =================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2013, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Core utility routines for the cholmod_dense object: * * The solve routines and some of the MatrixOps and Modify routines use dense * matrices as inputs. These are held in column-major order. With a leading * dimension of d, the entry in row i and column j is held in x [i+j*d]. * * Primary routines: * ----------------- * cholmod_allocate_dense allocate a dense matrix * cholmod_free_dense free a dense matrix * * Secondary routines: * ------------------- * cholmod_zeros allocate a dense matrix of all zeros * cholmod_ones allocate a dense matrix of all ones * cholmod_eye allocate a dense identity matrix * cholmod_sparse_to_dense create a dense matrix copy of a sparse matrix * cholmod_dense_to_sparse create a sparse matrix copy of a dense matrix * cholmod_copy_dense create a copy of a dense matrix * cholmod_copy_dense2 copy a dense matrix (pre-allocated) * * All routines in this file can handle the real, complex, and zomplex cases. * Pattern-only dense matrices are not supported. cholmod_sparse_to_dense can * take a pattern-only input sparse matrix, however, and cholmod_dense_to_sparse * can generate a pattern-only output sparse matrix. */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define PATTERN #include "t_cholmod_dense.c" #define REAL #include "t_cholmod_dense.c" #define COMPLEX #include "t_cholmod_dense.c" #define ZOMPLEX #include "t_cholmod_dense.c" /* ========================================================================== */ /* === cholmod_allocate_dense =============================================== */ /* ========================================================================== */ /* Allocate a dense matrix with leading dimension d. The space is not * initialized. */ cholmod_dense *CHOLMOD(allocate_dense) ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ size_t d, /* leading dimension */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; size_t nzmax, nzmax0 ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; if (d < nrow) { ERROR (CHOLMOD_INVALID, "leading dimension invalid") ; return (NULL) ; } if (xtype < CHOLMOD_REAL || xtype > CHOLMOD_ZOMPLEX) { ERROR (CHOLMOD_INVALID, "xtype invalid") ; return (NULL) ; } /* ensure the dimensions do not cause integer overflow */ (void) CHOLMOD(add_size_t) (ncol, 2, &ok) ; /* nzmax = MAX (1, d*ncol) ; */ nzmax = CHOLMOD(mult_size_t) (d, ncol, &ok) ; nzmax = MAX (1, nzmax) ; if (!ok || nrow > Int_max || ncol > Int_max || nzmax > Int_max) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate header */ /* ---------------------------------------------------------------------- */ X = CHOLMOD(malloc) (sizeof (cholmod_dense), 1, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } PRINT1 (("cholmod_allocate_dense %d-by-%d nzmax %d xtype %d\n", nrow, ncol, nzmax, xtype)) ; X->nrow = nrow ; X->ncol = ncol ; X->nzmax = nzmax ; X->xtype = xtype ; X->dtype = DTYPE ; X->x = NULL ; X->z = NULL ; X->d = d ; /* ---------------------------------------------------------------------- */ /* allocate the matrix itself */ /* ---------------------------------------------------------------------- */ nzmax0 = 0 ; CHOLMOD(realloc_multiple) (nzmax, 0, xtype, NULL, NULL, &(X->x), &(X->z), &nzmax0, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_dense) (&X, Common) ; return (NULL) ; /* out of memory */ } return (X) ; } /* ========================================================================== */ /* === cholmod_zeros ======================================================== */ /* ========================================================================== */ /* Allocate a dense matrix and set it to zero */ cholmod_dense *CHOLMOD(zeros) ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; double *Xx, *Xz ; Int i, nz ; /* ---------------------------------------------------------------------- */ /* allocate a dense matrix and set it to zero */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; X = CHOLMOD(allocate_dense) (nrow, ncol, nrow, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* NULL Common, out of memory, or inputs invalid */ } Xx = X->x ; Xz = X->z ; nz = MAX (1, X->nzmax) ; switch (xtype) { case CHOLMOD_REAL: for (i = 0 ; i < nz ; i++) { Xx [i] = 0 ; } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < 2*nz ; i++) { Xx [i] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for (i = 0 ; i < nz ; i++) { Xx [i] = 0 ; } for (i = 0 ; i < nz ; i++) { Xz [i] = 0 ; } break ; } return (X) ; } /* ========================================================================== */ /* === cholmod_ones ========================================================= */ /* ========================================================================== */ /* Allocate a dense matrix and set it to zero */ cholmod_dense *CHOLMOD(ones) ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; double *Xx, *Xz ; Int i, nz ; /* ---------------------------------------------------------------------- */ /* allocate a dense matrix and set it to all ones */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; X = CHOLMOD(allocate_dense) (nrow, ncol, nrow, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* NULL Common, out of memory, or inputs invalid */ } Xx = X->x ; Xz = X->z ; nz = MAX (1, X->nzmax) ; switch (xtype) { case CHOLMOD_REAL: for (i = 0 ; i < nz ; i++) { Xx [i] = 1 ; } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < nz ; i++) { Xx [2*i ] = 1 ; Xx [2*i+1] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for (i = 0 ; i < nz ; i++) { Xx [i] = 1 ; } for (i = 0 ; i < nz ; i++) { Xz [i] = 0 ; } break ; } return (X) ; } /* ========================================================================== */ /* === cholmod_eye ========================================================== */ /* ========================================================================== */ /* Allocate a dense matrix and set it to the identity matrix */ cholmod_dense *CHOLMOD(eye) ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; double *Xx, *Xz ; Int i, n, nz ; /* ---------------------------------------------------------------------- */ /* allocate a dense matrix and set it to the identity matrix */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; X = CHOLMOD(zeros) (nrow, ncol, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* NULL Common, out of memory, or inputs invalid */ } nz = MAX (1, nrow*ncol) ; Xx = X->x ; Xz = X->z ; n = MIN (nrow, ncol) ; switch (xtype) { case CHOLMOD_REAL: case CHOLMOD_ZOMPLEX: for (i = 0 ; i < n ; i++) { Xx [i + i*nrow] = 1 ; } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < n ; i++) { Xx [2 * (i + i*nrow)] = 1 ; } break ; } return (X) ; } /* ========================================================================== */ /* === cholmod_free_dense =================================================== */ /* ========================================================================== */ /* free a dense matrix * * workspace: none */ int CHOLMOD(free_dense) ( /* ---- in/out --- */ cholmod_dense **XHandle, /* dense matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; RETURN_IF_NULL_COMMON (FALSE) ; if (XHandle == NULL) { /* nothing to do */ return (TRUE) ; } X = *XHandle ; if (X == NULL) { /* nothing to do */ return (TRUE) ; } switch (X->xtype) { case CHOLMOD_REAL: X->x = CHOLMOD(free) (X->nzmax, sizeof (double), X->x, Common) ; break ; case CHOLMOD_COMPLEX: X->x = CHOLMOD(free) (X->nzmax, 2*sizeof (double), X->x, Common) ; break ; case CHOLMOD_ZOMPLEX: X->x = CHOLMOD(free) (X->nzmax, sizeof (double), X->x, Common) ; X->z = CHOLMOD(free) (X->nzmax, sizeof (double), X->z, Common) ; break ; } *XHandle = CHOLMOD(free) (1, sizeof (cholmod_dense), (*XHandle), Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_ensure_dense ================================================= */ /* ========================================================================== */ /* Ensure that the input matrix has a certain size and type. If not, free * the existing matrix and reallocate one of the right size and type. * Returns a pointer to the cholmod_dense matrix, possibly reallocated. * Also modifies the input matrix handle, XHandle, if necessary. */ cholmod_dense *CHOLMOD(ensure_dense) ( /* ---- input/output ---- */ cholmod_dense **XHandle, /* matrix handle to check */ /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ size_t d, /* leading dimension */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X ; RETURN_IF_NULL_COMMON (NULL) ; if (XHandle == NULL) { ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } X = *XHandle ; if (X == NULL || X->nrow != nrow || X->ncol != ncol || X->d != d || X->xtype != xtype) { /* Matrix X is not allocated, or has the wrong size. Free it and * reallocate it in the right size and shape. If an error occurs * (out of memory or inputs nrow, etc invalid), then the error is * set in cholmod_allocate_dense and X is returned as NULL. */ #if 0 if (X == NULL) { printf ("oops, X was null\n") ; } else { printf ("oops, nrow %g %g ncol %g %g d %g %g xtype %g %g\n", (double) X->nrow, (double) nrow, (double) X->ncol, (double) ncol, (double) X->d, (double) d, (double) X->xtype, (double) xtype ) ; } #endif CHOLMOD(free_dense) (XHandle, Common) ; X = CHOLMOD(allocate_dense) (nrow, ncol, d, xtype, Common) ; *XHandle = X ; } return (X) ; } /* ========================================================================== */ /* === cholmod_sparse_to_dense ============================================== */ /* ========================================================================== */ /* Convert a sparse matrix to a dense matrix. * The output dense matrix has the same xtype as the input sparse matrix, * except that a pattern-only sparse matrix A is converted into a real dense * matrix X, with 1's and 0's. All xtypes are supported. */ cholmod_dense *CHOLMOD(sparse_to_dense) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *X = NULL ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; if (A->stype && A->nrow != A->ncol) { ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } Common->status = CHOLMOD_OK ; ASSERT (CHOLMOD(dump_sparse) (A, "A", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* convert the matrix, using template routine */ /* ---------------------------------------------------------------------- */ switch (A->xtype) { case CHOLMOD_PATTERN: X = p_cholmod_sparse_to_dense (A, Common) ; break ; case CHOLMOD_REAL: X = r_cholmod_sparse_to_dense (A, Common) ; break ; case CHOLMOD_COMPLEX: X = c_cholmod_sparse_to_dense (A, Common) ; break ; case CHOLMOD_ZOMPLEX: X = z_cholmod_sparse_to_dense (A, Common) ; break ; } return (X) ; } /* ========================================================================== */ /* === cholmod_dense_to_sparse ============================================== */ /* ========================================================================== */ /* Convert a dense matrix to a sparse matrix, similar to the MATLAB statements: * * C = sparse (X) values = TRUE * C = spones (sparse (X)) values = FALSE * * except that X must be double (it can be of many different types in MATLAB) * * The resulting sparse matrix C has the same numeric xtype as the input dense * matrix X, unless "values" is FALSE (in which case C is real, where C(i,j)=1 * if (i,j) is an entry in X. */ cholmod_sparse *CHOLMOD(dense_to_sparse) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ int values, /* TRUE if values to be copied, FALSE otherwise */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *C = NULL ; DEBUG (CHOLMOD(dump_dense) (X, "X", Common)) ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (X, NULL) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, NULL) ; if (X->d < X->nrow) { ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* convert the matrix, using template routine */ /* ---------------------------------------------------------------------- */ switch (X->xtype) { case CHOLMOD_REAL: C = r_cholmod_dense_to_sparse (X, values, Common) ; break ; case CHOLMOD_COMPLEX: C = c_cholmod_dense_to_sparse (X, values, Common) ; break ; case CHOLMOD_ZOMPLEX: C = z_cholmod_dense_to_sparse (X, values, Common) ; break ; } return (C) ; } /* ========================================================================== */ /* === cholmod_copy_dense2 ================================================== */ /* ========================================================================== */ /* Y = X, where X and Y are both already allocated. The leading dimensions of * X and Y may differ, but both must be >= the # of rows in X and Y. * Entries in rows nrow to d-1 are not copied from X, since the space might not * be initialized. Y->nzmax is unchanged. X->nzmax is typically * (X->d)*(X->ncol), but a user might modify that condition outside of any * CHOLMOD routine. * * The two dense matrices X and Y must have the same numeric xtype. */ int CHOLMOD(copy_dense2) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ /* ---- output --- */ cholmod_dense *Y, /* copy of matrix X */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (X, FALSE) ; RETURN_IF_NULL (Y, FALSE) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (Y, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; if (X->nrow != Y->nrow || X->ncol != Y->ncol || X->xtype != Y->xtype) { ERROR (CHOLMOD_INVALID, "X and Y must have same dimensions and xtype") ; return (FALSE) ; } if (X->d < X->nrow || Y->d < Y->nrow || (X->d * X->ncol) > X->nzmax || (Y->d * Y->ncol) > Y->nzmax) { ERROR (CHOLMOD_INVALID, "X and/or Y invalid") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* copy the matrix, using template routine */ /* ---------------------------------------------------------------------- */ switch (X->xtype) { case CHOLMOD_REAL: r_cholmod_copy_dense2 (X, Y) ; break ; case CHOLMOD_COMPLEX: c_cholmod_copy_dense2 (X, Y) ; break ; case CHOLMOD_ZOMPLEX: z_cholmod_copy_dense2 (X, Y) ; break ; } return (TRUE) ; } /* ========================================================================== */ /* === cholmod_copy_dense =================================================== */ /* ========================================================================== */ /* Y = X, copy a dense matrix */ cholmod_dense *CHOLMOD(copy_dense) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *Y ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (X, NULL) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate result */ /* ---------------------------------------------------------------------- */ Y = CHOLMOD(allocate_dense) (X->nrow, X->ncol, X->d, X->xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory or X invalid */ } /* ---------------------------------------------------------------------- */ /* Y = X */ /* ---------------------------------------------------------------------- */ /* This cannot fail (X and Y are allocated, and have the same nrow, ncol * d, and xtype) */ CHOLMOD(copy_dense2) (X, Y, Common) ; /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ return (Y) ; } igraph/src/CHOLMOD/Core/cholmod_copy.c0000644000175100001440000002731513431000472017133 0ustar hornikusers/* ========================================================================== */ /* === Core/cholmod_copy ==================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Core Module. Copyright (C) 2005-2006, * Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Core Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* C = A, which allocates C and copies A into C, with possible change of * stype. The diagonal can optionally be removed. The numerical entries * can optionally be copied. This routine differs from cholmod_copy_sparse, * which makes an exact copy of a sparse matrix. * * A can be of any type (packed/unpacked, upper/lower/unsymmetric). C is * packed and can be of any stype (upper/lower/unsymmetric), except that if * A is rectangular C can only be unsymmetric. If the stype of A and C * differ, then the appropriate conversion is made. * * Symmetry of A (A->stype): * <0: lower: assume A is symmetric with just tril(A); the rest of A is ignored * 0 unsym: assume A is unsymmetric; consider all entries in A * >0 upper: assume A is symmetric with just triu(A); the rest of A is ignored * * Symmetry of C (stype parameter): * <0 lower: return just tril(C) * 0 unsym: return all of C * >0 upper: return just triu(C) * * In MATLAB: Using cholmod_copy: * ---------- ---------------------------- * C = A ; A unsymmetric, C unsymmetric * C = tril (A) ; A unsymmetric, C lower * C = triu (A) ; A unsymmetric, C upper * U = triu (A) ; L = tril (U',-1) ; C = L+U ; A upper, C unsymmetric * C = triu (A)' ; A upper, C lower * C = triu (A) ; A upper, C upper * L = tril (A) ; U = triu (L',1) ; C = L+U ; A lower, C unsymmetric * C = tril (A) ; A lower, C lower * C = tril (A)' ; A lower, C upper * * workspace: Iwork (max (nrow,ncol)) * * A can have an xtype of pattern or real. Complex and zomplex cases only * supported when mode <= 0 (in which case the numerical values are ignored). */ #include "cholmod_internal.h" #include "cholmod_core.h" /* ========================================================================== */ /* === copy_sym_to_unsym ==================================================== */ /* ========================================================================== */ /* Construct an unsymmetric copy of a symmetric sparse matrix. This does the * work for as C = cholmod_copy (A, 0, mode, Common) when A is symmetric. * In this case, extra space can be added to C. */ static cholmod_sparse *copy_sym_to_unsym ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) * -2: pattern only, no diagonal, add 50% + n extra * space to C */ /* --------------- */ cholmod_common *Common ) { double aij ; double *Ax, *Cx ; Int *Ap, *Ai, *Anz, *Cp, *Ci, *Wj, *Iwork ; cholmod_sparse *C ; Int nrow, ncol, nz, packed, j, p, pend, i, pc, up, lo, values, diag, astype, extra ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; packed = A->packed ; values = (mode > 0) && (A->xtype != CHOLMOD_PATTERN) ; diag = (mode >= 0) ; astype = SIGN (A->stype) ; up = (astype > 0) ; lo = (astype < 0) ; ASSERT (astype != 0) ; /* ---------------------------------------------------------------------- */ /* create an unsymmetric copy of a symmetric matrix */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Wj = Iwork ; /* size ncol (i/i/l) */ /* In MATLAB notation, for converting a symmetric/upper matrix: * U = triu (A) ; * L = tril (U',-1) ; * C = L + U ; * * For converting a symmetric/lower matrix to unsymmetric: * L = tril (A) ; * U = triu (L',1) ; * C = L + U ; */ ASSERT (up || lo) ; PRINT1 (("copy: convert symmetric to unsym\n")) ; /* count the number of entries in each column of C */ for (j = 0 ; j < ncol ; j++) { Wj [j] = 0 ; } for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* the diagonal entry A(i,i) will appear just once * (unless it is excluded with mode < 0) */ if (diag) { Wj [j]++ ; } } else if ((up && i < j) || (lo && i > j)) { /* upper case: A(i,j) is in the strictly upper part; * A(j,i) will be added to the strictly lower part of C. * lower case is the opposite. */ Wj [j]++ ; Wj [i]++ ; } } } nz = 0 ; for (j = 0 ; j < ncol ; j++) { nz += Wj [j] ; } extra = (mode == -2) ? (nz/2 + ncol) : 0 ; /* allocate C. C is sorted if and only if A is sorted */ C = CHOLMOD(allocate_sparse) (nrow, ncol, nz + extra, A->sorted, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* construct the column pointers for C */ p = 0 ; for (j = 0 ; j < ncol ; j++) { Cp [j] = p ; p += Wj [j] ; } Cp [ncol] = p ; for (j = 0 ; j < ncol ; j++) { Wj [j] = Cp [j] ; } /* construct C */ if (values) { /* pattern and values */ ASSERT (diag) ; for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; aij = Ax [p] ; if (i == j) { /* add diagonal entry A(i,i) to column i */ pc = Wj [i]++ ; Ci [pc] = i ; Cx [pc] = aij ; } else if ((up && i < j) || (lo && i > j)) { /* add A(i,j) to column j */ pc = Wj [j]++ ; Ci [pc] = i ; Cx [pc] = aij ; /* add A(j,i) to column i */ pc = Wj [i]++ ; Ci [pc] = j ; Cx [pc] = aij ; } } } } else { /* pattern only, possibly excluding the diagonal */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* add diagonal entry A(i,i) to column i * (unless it is excluded with mode < 0) */ if (diag) { Ci [Wj [i]++] = i ; } } else if ((up && i < j) || (lo && i > j)) { /* add A(i,j) to column j */ Ci [Wj [j]++] = i ; /* add A(j,i) to column i */ Ci [Wj [i]++] = j ; } } } } /* ---------------------------------------------------------------------- */ /* return the result */ /* ---------------------------------------------------------------------- */ DEBUG (i = CHOLMOD(dump_sparse) (C, "copy_sym_to_unsym", Common)) ; PRINT1 (("mode %d nnzdiag "ID"\n", mode, i)) ; ASSERT (IMPLIES (mode < 0, i == 0)) ; return (C) ; } /* ========================================================================== */ /* === cholmod_copy ========================================================= */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(copy) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ int stype, /* requested stype of C */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *C ; Int nrow, ncol, up, lo, values, diag, astype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; values = (mode > 0) && (A->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; nrow = A->nrow ; ncol = A->ncol ; if ((stype || A->stype) && nrow != ncol) { /* inputs invalid */ ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(allocate_work) (0, MAX (nrow,ncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ diag = (mode >= 0) ; astype = SIGN (A->stype) ; stype = SIGN (stype) ; up = (astype > 0) ; lo = (astype < 0) ; /* ---------------------------------------------------------------------- */ /* copy the matrix */ /* ---------------------------------------------------------------------- */ if (astype == stype) { /* ------------------------------------------------------------------ */ /* symmetry of A and C are the same */ /* ------------------------------------------------------------------ */ /* copy A into C, keeping the same symmetry. If A is symmetric * entries in the ignored part of A are not copied into C */ C = CHOLMOD(band) (A, -nrow, ncol, mode, Common) ; } else if (!astype) { /* ------------------------------------------------------------------ */ /* convert unsymmetric matrix A into a symmetric matrix C */ /* ------------------------------------------------------------------ */ if (stype > 0) { /* C = triu (A) */ C = CHOLMOD(band) (A, 0, ncol, mode, Common) ; } else { /* C = tril (A) */ C = CHOLMOD(band) (A, -nrow, 0, mode, Common) ; } if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } C->stype = stype ; } else if (astype == -stype) { /* ------------------------------------------------------------------ */ /* transpose a symmetric matrix */ /* ------------------------------------------------------------------ */ /* converting upper to lower or lower to upper */ /* workspace: Iwork (nrow) */ C = CHOLMOD(transpose) (A, values, Common) ; if (!diag) { /* remove diagonal, if requested */ CHOLMOD(band_inplace) (-nrow, ncol, -1, C, Common) ; } } else { /* ------------------------------------------------------------------ */ /* create an unsymmetric copy of a symmetric matrix */ /* ------------------------------------------------------------------ */ C = copy_sym_to_unsym (A, mode, Common) ; } /* ---------------------------------------------------------------------- */ /* return if error */ /* ---------------------------------------------------------------------- */ if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } /* ---------------------------------------------------------------------- */ /* return the result */ /* ---------------------------------------------------------------------- */ DEBUG (diag = CHOLMOD(dump_sparse) (C, "copy", Common)) ; PRINT1 (("mode %d nnzdiag "ID"\n", mode, diag)) ; ASSERT (IMPLIES (mode < 0, diag == 0)) ; return (C) ; } igraph/src/CHOLMOD/Include/0000755000175100001440000000000013430770173015006 5ustar hornikusersigraph/src/CHOLMOD/Include/cholmod_core.h0000644000175100001440000030506713431000472017614 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_core.h =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_core.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_core.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD Core module: basic CHOLMOD objects and routines. * Required by all CHOLMOD modules. Requires no other module or package. * * The CHOLMOD modules are: * * Core basic data structures and definitions * Check check/print the 5 CHOLMOD objects, & 3 types of integer vectors * Cholesky sparse Cholesky factorization * Modify sparse Cholesky update/downdate/row-add/row-delete * MatrixOps sparse matrix functions (add, multiply, norm, ...) * Supernodal supernodal sparse Cholesky factorization * Partition graph-partitioning based orderings * * The CHOLMOD objects: * -------------------- * * cholmod_common parameters, statistics, and workspace * cholmod_sparse a sparse matrix in compressed column form * cholmod_factor an LL' or LDL' factorization * cholmod_dense a dense matrix * cholmod_triplet a sparse matrix in "triplet" form * * The Core module described here defines the CHOLMOD data structures, and * basic operations on them. To create and solve a sparse linear system Ax=b, * the user must create A and b, populate them with values, and then pass them * to the routines in the CHOLMOD Cholesky module. There are two primary * methods for creating A: (1) allocate space for a column-oriented sparse * matrix and fill it with pattern and values, or (2) create a triplet form * matrix and convert it to a sparse matrix. The latter option is simpler. * * The matrices b and x are typically dense matrices, but can also be sparse. * You can allocate and free them as dense matrices with the * cholmod_allocate_dense and cholmod_free_dense routines. * * The cholmod_factor object contains the symbolic and numeric LL' or LDL' * factorization of sparse symmetric matrix. The matrix must be positive * definite for an LL' factorization. It need only be symmetric and have well- * conditioned leading submatrices for it to have an LDL' factorization * (CHOLMOD does not pivot for numerical stability). It is typically created * with the cholmod_factorize routine in the Cholesky module, but can also * be initialized to L=D=I in the Core module and then modified by the Modify * module. It must be freed with cholmod_free_factor, defined below. * * The Core routines for each object are described below. Each list is split * into two parts: the primary routines and secondary routines. * * ============================================================================ * === cholmod_common ========================================================= * ============================================================================ * * The Common object contains control parameters, statistics, and * You must call cholmod_start before calling any other CHOLMOD routine, and * must call cholmod_finish as your last call to CHOLMOD, with two exceptions: * you may call cholmod_print_common and cholmod_check_common in the Check * module after calling cholmod_finish. * * cholmod_start first call to CHOLMOD * cholmod_finish last call to CHOLMOD * ----------------------------- * cholmod_defaults restore default parameters * cholmod_maxrank maximum rank for update/downdate * cholmod_allocate_work allocate workspace in Common * cholmod_free_work free workspace in Common * cholmod_clear_flag clear Flag workspace in Common * cholmod_error called when CHOLMOD encounters an error * cholmod_dbound for internal use in CHOLMOD only * cholmod_hypot compute sqrt (x*x + y*y) accurately * cholmod_divcomplex complex division, c = a/b * * ============================================================================ * === cholmod_sparse ========================================================= * ============================================================================ * * A sparse matrix is held in compressed column form. In the basic type * ("packed", which corresponds to a MATLAB sparse matrix), an n-by-n matrix * with nz entries is held in three arrays: p of size n+1, i of size nz, and x * of size nz. Row indices of column j are held in i [p [j] ... p [j+1]-1] and * in the same locations in x. There may be no duplicate entries in a column. * Row indices in each column may be sorted or unsorted (CHOLMOD keeps track). * A->stype determines the storage mode: 0 if both upper/lower parts are stored, * -1 if A is symmetric and just tril(A) is stored, +1 if symmetric and triu(A) * is stored. * * cholmod_allocate_sparse allocate a sparse matrix * cholmod_free_sparse free a sparse matrix * ----------------------------- * cholmod_reallocate_sparse change the size (# entries) of sparse matrix * cholmod_nnz number of nonzeros in a sparse matrix * cholmod_speye sparse identity matrix * cholmod_spzeros sparse zero matrix * cholmod_transpose transpose a sparse matrix * cholmod_ptranspose transpose/permute a sparse matrix * cholmod_transpose_unsym transpose/permute an unsymmetric sparse matrix * cholmod_transpose_sym transpose/permute a symmetric sparse matrix * cholmod_sort sort row indices in each column of sparse matrix * cholmod_band C = tril (triu (A,k1), k2) * cholmod_band_inplace A = tril (triu (A,k1), k2) * cholmod_aat C = A*A' * cholmod_copy_sparse C = A, create an exact copy of a sparse matrix * cholmod_copy C = A, with possible change of stype * cholmod_add C = alpha*A + beta*B * cholmod_sparse_xtype change the xtype of a sparse matrix * * ============================================================================ * === cholmod_factor ========================================================= * ============================================================================ * * The data structure for an LL' or LDL' factorization is too complex to * describe in one sentence. This object can hold the symbolic analysis alone, * or in combination with a "simplicial" (similar to a sparse matrix) or * "supernodal" form of the numerical factorization. Only the routine to free * a factor is primary, since a factor object is created by the factorization * routine (cholmod_factorize). It must be freed with cholmod_free_factor. * * cholmod_free_factor free a factor * ----------------------------- * cholmod_allocate_factor allocate a factor (LL' or LDL') * cholmod_reallocate_factor change the # entries in a factor * cholmod_change_factor change the type of factor (e.g., LDL' to LL') * cholmod_pack_factor pack the columns of a factor * cholmod_reallocate_column resize a single column of a factor * cholmod_factor_to_sparse create a sparse matrix copy of a factor * cholmod_copy_factor create a copy of a factor * cholmod_factor_xtype change the xtype of a factor * * Note that there is no cholmod_sparse_to_factor routine to create a factor * as a copy of a sparse matrix. It could be done, after a fashion, but a * lower triangular sparse matrix would not necessarily have a chordal graph, * which would break the many CHOLMOD routines that rely on this property. * * ============================================================================ * === cholmod_dense ========================================================== * ============================================================================ * * The solve routines and some of the MatrixOps and Modify routines use dense * matrices as inputs. These are held in column-major order. With a leading * dimension of d, the entry in row i and column j is held in x [i+j*d]. * * cholmod_allocate_dense allocate a dense matrix * cholmod_free_dense free a dense matrix * ----------------------------- * cholmod_zeros allocate a dense matrix of all zeros * cholmod_ones allocate a dense matrix of all ones * cholmod_eye allocate a dense identity matrix * cholmod_sparse_to_dense create a dense matrix copy of a sparse matrix * cholmod_dense_to_sparse create a sparse matrix copy of a dense matrix * cholmod_copy_dense create a copy of a dense matrix * cholmod_copy_dense2 copy a dense matrix (pre-allocated) * cholmod_dense_xtype change the xtype of a dense matrix * cholmod_ensure_dense ensure a dense matrix has a given size and type * * ============================================================================ * === cholmod_triplet ======================================================== * ============================================================================ * * A sparse matrix held in triplet form is the simplest one for a user to * create. It consists of a list of nz entries in arbitrary order, held in * three arrays: i, j, and x, each of length nk. The kth entry is in row i[k], * column j[k], with value x[k]. There may be duplicate values; if A(i,j) * appears more than once, its value is the sum of the entries with those row * and column indices. * * cholmod_allocate_triplet allocate a triplet matrix * cholmod_triplet_to_sparse create a sparse matrix copy of a triplet matrix * cholmod_free_triplet free a triplet matrix * ----------------------------- * cholmod_reallocate_triplet change the # of entries in a triplet matrix * cholmod_sparse_to_triplet create a triplet matrix copy of a sparse matrix * cholmod_copy_triplet create a copy of a triplet matrix * cholmod_triplet_xtype change the xtype of a triplet matrix * * ============================================================================ * === memory management ====================================================== * ============================================================================ * * cholmod_malloc malloc wrapper * cholmod_calloc calloc wrapper * cholmod_free free wrapper * cholmod_realloc realloc wrapper * cholmod_realloc_multiple realloc wrapper for multiple objects * * ============================================================================ * === Core CHOLMOD prototypes ================================================ * ============================================================================ * * All CHOLMOD routines (in all modules) use the following protocol for return * values, with one exception: * * int TRUE (1) if successful, or FALSE (0) otherwise. * (exception: cholmod_divcomplex) * SuiteSparse_long a value >= 0 if successful, or -1 otherwise. * double a value >= 0 if successful, or -1 otherwise. * size_t a value > 0 if successful, or 0 otherwise. * void * a non-NULL pointer to newly allocated memory if * successful, or NULL otherwise. * cholmod_sparse * a non-NULL pointer to a newly allocated matrix * if successful, or NULL otherwise. * cholmod_factor * a non-NULL pointer to a newly allocated factor * if successful, or NULL otherwise. * cholmod_triplet * a non-NULL pointer to a newly allocated triplet * matrix if successful, or NULL otherwise. * cholmod_dense * a non-NULL pointer to a newly allocated triplet * matrix if successful, or NULL otherwise. * * The last parameter to all routines is always a pointer to the CHOLMOD * Common object. * * TRUE and FALSE are not defined here, since they may conflict with the user * program. A routine that described here returning TRUE or FALSE returns 1 * or 0, respectively. Any TRUE/FALSE parameter is true if nonzero, false if * zero. */ #ifndef CHOLMOD_CORE_H #define CHOLMOD_CORE_H /* ========================================================================== */ /* === CHOLMOD version ====================================================== */ /* ========================================================================== */ /* All versions of CHOLMOD will include the following definitions. * As an example, to test if the version you are using is 1.3 or later: * * if (CHOLMOD_VERSION >= CHOLMOD_VER_CODE (1,3)) ... * * This also works during compile-time: * * #if CHOLMOD_VERSION >= CHOLMOD_VER_CODE (1,3) * printf ("This is version 1.3 or later\n") ; * #else * printf ("This is version is earlier than 1.3\n") ; * #endif */ #define CHOLMOD_HAS_VERSION_FUNCTION #define CHOLMOD_DATE "April 25, 2013" #define CHOLMOD_VER_CODE(main,sub) ((main) * 1000 + (sub)) #define CHOLMOD_MAIN_VERSION 2 #define CHOLMOD_SUB_VERSION 1 #define CHOLMOD_SUBSUB_VERSION 2 #define CHOLMOD_VERSION \ CHOLMOD_VER_CODE(CHOLMOD_MAIN_VERSION,CHOLMOD_SUB_VERSION) /* ========================================================================== */ /* === non-CHOLMOD include files ============================================ */ /* ========================================================================== */ /* This is the only non-CHOLMOD include file imposed on the user program. * It required for size_t definition used here. CHOLMOD itself includes other * ANSI C89 standard #include files, but does not expose them to the user. * * CHOLMOD assumes that your C compiler is ANSI C89 compliant. It does not make * use of ANSI C99 features. */ #include #include /* ========================================================================== */ /* === CUDA BLAS for the GPU ================================================ */ /* ========================================================================== */ #ifdef GPU_BLAS #include #include #endif /* ========================================================================== */ /* === CHOLMOD objects ====================================================== */ /* ========================================================================== */ /* Each CHOLMOD object has its own type code. */ #define CHOLMOD_COMMON 0 #define CHOLMOD_SPARSE 1 #define CHOLMOD_FACTOR 2 #define CHOLMOD_DENSE 3 #define CHOLMOD_TRIPLET 4 /* ========================================================================== */ /* === CHOLMOD Common ======================================================= */ /* ========================================================================== */ /* itype defines the types of integer used: */ #define CHOLMOD_INT 0 /* all integer arrays are int */ #define CHOLMOD_INTLONG 1 /* most are int, some are SuiteSparse_long */ #define CHOLMOD_LONG 2 /* all integer arrays are SuiteSparse_long */ /* The itype of all parameters for all CHOLMOD routines must match. * FUTURE WORK: CHOLMOD_INTLONG is not yet supported. */ /* dtype defines what the numerical type is (double or float): */ #define CHOLMOD_DOUBLE 0 /* all numerical values are double */ #define CHOLMOD_SINGLE 1 /* all numerical values are float */ /* The dtype of all parameters for all CHOLMOD routines must match. * * Scalar floating-point values are always passed as double arrays of size 2 * (for the real and imaginary parts). They are typecast to float as needed. * FUTURE WORK: the float case is not supported yet. */ /* xtype defines the kind of numerical values used: */ #define CHOLMOD_PATTERN 0 /* pattern only, no numerical values */ #define CHOLMOD_REAL 1 /* a real matrix */ #define CHOLMOD_COMPLEX 2 /* a complex matrix (ANSI C99 compatible) */ #define CHOLMOD_ZOMPLEX 3 /* a complex matrix (MATLAB compatible) */ /* The xtype of all parameters for all CHOLMOD routines must match. * * CHOLMOD_PATTERN: x and z are ignored. * CHOLMOD_DOUBLE: x is non-null of size nzmax, z is ignored. * CHOLMOD_COMPLEX: x is non-null of size 2*nzmax doubles, z is ignored. * CHOLMOD_ZOMPLEX: x and z are non-null of size nzmax * * In the real case, z is ignored. The kth entry in the matrix is x [k]. * There are two methods for the complex case. In the ANSI C99-compatible * CHOLMOD_COMPLEX case, the real and imaginary parts of the kth entry * are in x [2*k] and x [2*k+1], respectively. z is ignored. In the * MATLAB-compatible CHOLMOD_ZOMPLEX case, the real and imaginary * parts of the kth entry are in x [k] and z [k]. * * Scalar floating-point values are always passed as double arrays of size 2 * (real and imaginary parts). The imaginary part of a scalar is ignored if * the routine operates on a real matrix. * * These Modules support complex and zomplex matrices, with a few exceptions: * * Check all routines * Cholesky all routines * Core all except cholmod_aat, add, band, copy * Demo all routines * Partition all routines * Supernodal all routines support any real, complex, or zomplex input. * There will never be a supernodal zomplex L; a complex * supernodal L is created if A is zomplex. * Tcov all routines * Valgrind all routines * * These Modules provide partial support for complex and zomplex matrices: * * MATLAB all routines support real and zomplex only, not complex, * with the exception of ldlupdate, which supports * real matrices only. This is a minor constraint since * MATLAB's matrices are all real or zomplex. * MatrixOps only norm_dense, norm_sparse, and sdmult support complex * and zomplex * * These Modules do not support complex and zomplex matrices at all: * * Modify all routines support real matrices only */ /* Definitions for cholmod_common: */ #define CHOLMOD_MAXMETHODS 9 /* maximum number of different methods that */ /* cholmod_analyze can try. Must be >= 9. */ /* Common->status values. zero means success, negative means a fatal error, * positive is a warning. */ #define CHOLMOD_OK 0 /* success */ #define CHOLMOD_NOT_INSTALLED (-1) /* failure: method not installed */ #define CHOLMOD_OUT_OF_MEMORY (-2) /* failure: out of memory */ #define CHOLMOD_TOO_LARGE (-3) /* failure: integer overflow occured */ #define CHOLMOD_INVALID (-4) /* failure: invalid input */ #define CHOLMOD_GPU_PROBLEM (-5) /* failure: GPU fatal error */ #define CHOLMOD_NOT_POSDEF (1) /* warning: matrix not pos. def. */ #define CHOLMOD_DSMALL (2) /* warning: D for LDL' or diag(L) or */ /* LL' has tiny absolute value */ /* ordering method (also used for L->ordering) */ #define CHOLMOD_NATURAL 0 /* use natural ordering */ #define CHOLMOD_GIVEN 1 /* use given permutation */ #define CHOLMOD_AMD 2 /* use minimum degree (AMD) */ #define CHOLMOD_METIS 3 /* use METIS' nested dissection */ #define CHOLMOD_NESDIS 4 /* use CHOLMOD's version of nested dissection:*/ /* node bisector applied recursively, followed * by constrained minimum degree (CSYMAMD or * CCOLAMD) */ #define CHOLMOD_COLAMD 5 /* use AMD for A, COLAMD for A*A' */ /* POSTORDERED is not a method, but a result of natural ordering followed by a * weighted postorder. It is used for L->ordering, not method [ ].ordering. */ #define CHOLMOD_POSTORDERED 6 /* natural ordering, postordered. */ /* supernodal strategy (for Common->supernodal) */ #define CHOLMOD_SIMPLICIAL 0 /* always do simplicial */ #define CHOLMOD_AUTO 1 /* select simpl/super depending on matrix */ #define CHOLMOD_SUPERNODAL 2 /* always do supernodal */ typedef struct cholmod_common_struct { /* ---------------------------------------------------------------------- */ /* parameters for symbolic/numeric factorization and update/downdate */ /* ---------------------------------------------------------------------- */ double dbound ; /* Smallest absolute value of diagonal entries of D * for LDL' factorization and update/downdate/rowadd/ * rowdel, or the diagonal of L for an LL' factorization. * Entries in the range 0 to dbound are replaced with dbound. * Entries in the range -dbound to 0 are replaced with -dbound. No * changes are made to the diagonal if dbound <= 0. Default: zero */ double grow0 ; /* For a simplicial factorization, L->i and L->x can * grow if necessary. grow0 is the factor by which * it grows. For the initial space, L is of size MAX (1,grow0) times * the required space. If L runs out of space, the new size of L is * MAX(1.2,grow0) times the new required space. If you do not plan on * modifying the LDL' factorization in the Modify module, set grow0 to * zero (or set grow2 to 0, see below). Default: 1.2 */ double grow1 ; size_t grow2 ; /* For a simplicial factorization, each column j of L * is initialized with space equal to * grow1*L->ColCount[j] + grow2. If grow0 < 1, grow1 < 1, or grow2 == 0, * then the space allocated is exactly equal to L->ColCount[j]. If the * column j runs out of space, it increases to grow1*need + grow2 in * size, where need is the total # of nonzeros in that column. If you do * not plan on modifying the factorization in the Modify module, set * grow2 to zero. Default: grow1 = 1.2, grow2 = 5. */ size_t maxrank ; /* rank of maximum update/downdate. Valid values: * 2, 4, or 8. A value < 2 is set to 2, and a * value > 8 is set to 8. It is then rounded up to the next highest * power of 2, if not already a power of 2. Workspace (Xwork, below) of * size nrow-by-maxrank double's is allocated for the update/downdate. * If an update/downdate of rank-k is requested, with k > maxrank, * it is done in steps of maxrank. Default: 8, which is fastest. * Memory usage can be reduced by setting maxrank to 2 or 4. */ double supernodal_switch ; /* supernodal vs simplicial factorization */ int supernodal ; /* If Common->supernodal <= CHOLMOD_SIMPLICIAL * (0) then cholmod_analyze performs a * simplicial analysis. If >= CHOLMOD_SUPERNODAL (2), then a supernodal * analysis is performed. If == CHOLMOD_AUTO (1) and * flop/nnz(L) < Common->supernodal_switch, then a simplicial analysis * is done. A supernodal analysis done otherwise. * Default: CHOLMOD_AUTO. Default supernodal_switch = 40 */ int final_asis ; /* If TRUE, then ignore the other final_* parameters * (except for final_pack). * The factor is left as-is when done. Default: TRUE.*/ int final_super ; /* If TRUE, leave a factor in supernodal form when * supernodal factorization is finished. If FALSE, * then convert to a simplicial factor when done. * Default: TRUE */ int final_ll ; /* If TRUE, leave factor in LL' form when done. * Otherwise, leave in LDL' form. Default: FALSE */ int final_pack ; /* If TRUE, pack the columns when done. If TRUE, and * cholmod_factorize is called with a symbolic L, L is * allocated with exactly the space required, using L->ColCount. If you * plan on modifying the factorization, set Common->final_pack to FALSE, * and each column will be given a little extra slack space for future * growth in fill-in due to updates. Default: TRUE */ int final_monotonic ; /* If TRUE, ensure columns are monotonic when done. * Default: TRUE */ int final_resymbol ;/* if cholmod_factorize performed a supernodal * factorization, final_resymbol is true, and * final_super is FALSE (convert a simplicial numeric factorization), * then numerically zero entries that resulted from relaxed supernodal * amalgamation are removed. This does not remove entries that are zero * due to exact numeric cancellation, since doing so would break the * update/downdate rowadd/rowdel routines. Default: FALSE. */ /* supernodal relaxed amalgamation parameters: */ double zrelax [3] ; size_t nrelax [3] ; /* Let ns be the total number of columns in two adjacent supernodes. * Let z be the fraction of zero entries in the two supernodes if they * are merged (z includes zero entries from prior amalgamations). The * two supernodes are merged if: * (ns <= nrelax [0]) || (no new zero entries added) || * (ns <= nrelax [1] && z < zrelax [0]) || * (ns <= nrelax [2] && z < zrelax [1]) || (z < zrelax [2]) * * Default parameters result in the following rule: * (ns <= 4) || (no new zero entries added) || * (ns <= 16 && z < 0.8) || (ns <= 48 && z < 0.1) || (z < 0.05) */ int prefer_zomplex ; /* X = cholmod_solve (sys, L, B, Common) computes * x=A\b or solves a related system. If L and B are * both real, then X is real. Otherwise, X is returned as * CHOLMOD_COMPLEX if Common->prefer_zomplex is FALSE, or * CHOLMOD_ZOMPLEX if Common->prefer_zomplex is TRUE. This parameter * is needed because there is no supernodal zomplex L. Suppose the * caller wants all complex matrices to be stored in zomplex form * (MATLAB, for example). A supernodal L is returned in complex form * if A is zomplex. B can be real, and thus X = cholmod_solve (L,B) * should return X as zomplex. This cannot be inferred from the input * arguments L and B. Default: FALSE, since all data types are * supported in CHOLMOD_COMPLEX form and since this is the native type * of LAPACK and the BLAS. Note that the MATLAB/cholmod.c mexFunction * sets this parameter to TRUE, since MATLAB matrices are in * CHOLMOD_ZOMPLEX form. */ int prefer_upper ; /* cholmod_analyze and cholmod_factorize work * fastest when a symmetric matrix is stored in * upper triangular form when a fill-reducing ordering is used. In * MATLAB, this corresponds to how x=A\b works. When the matrix is * ordered as-is, they work fastest when a symmetric matrix is in lower * triangular form. In MATLAB, R=chol(A) does the opposite. This * parameter affects only how cholmod_read returns a symmetric matrix. * If TRUE (the default case), a symmetric matrix is always returned in * upper-triangular form (A->stype = 1). */ int quick_return_if_not_posdef ; /* if TRUE, the supernodal numeric * factorization will return quickly if * the matrix is not positive definite. Default: FALSE. */ /* ---------------------------------------------------------------------- */ /* printing and error handling options */ /* ---------------------------------------------------------------------- */ int print ; /* print level. Default: 3 */ int precise ; /* if TRUE, print 16 digits. Otherwise print 5 */ int (*print_function) (const char *, ...) ; /* pointer to printf */ int try_catch ; /* if TRUE, then ignore errors; CHOLMOD is in the middle * of a try/catch block. No error message is printed * and the Common->error_handler function is not called. */ void (*error_handler) (int status, const char *file, int line, const char *message) ; /* Common->error_handler is the user's error handling routine. If not * NULL, this routine is called if an error occurs in CHOLMOD. status * can be CHOLMOD_OK (0), negative for a fatal error, and positive for * a warning. file is a string containing the name of the source code * file where the error occured, and line is the line number in that * file. message is a string describing the error in more detail. */ /* ---------------------------------------------------------------------- */ /* ordering options */ /* ---------------------------------------------------------------------- */ /* The cholmod_analyze routine can try many different orderings and select * the best one. It can also try one ordering method multiple times, with * different parameter settings. The default is to use three orderings, * the user's permutation (if provided), AMD which is the fastest ordering * and generally gives good fill-in, and METIS. CHOLMOD's nested dissection * (METIS with a constrained AMD) usually gives a better ordering than METIS * alone (by about 5% to 10%) but it takes more time. * * If you know the method that is best for your matrix, set Common->nmethods * to 1 and set Common->method [0] to the set of parameters for that method. * If you set it to 1 and do not provide a permutation, then only AMD will * be called. * * If METIS is not available, the default # of methods tried is 2 (the user * permutation, if any, and AMD). * * To try other methods, set Common->nmethods to the number of methods you * want to try. The suite of default methods and their parameters is * described in the cholmod_defaults routine, and summarized here: * * Common->method [i]: * i = 0: user-provided ordering (cholmod_analyze_p only) * i = 1: AMD (for both A and A*A') * i = 2: METIS * i = 3: CHOLMOD's nested dissection (NESDIS), default parameters * i = 4: natural * i = 5: NESDIS with nd_small = 20000 * i = 6: NESDIS with nd_small = 4, no constrained minimum degree * i = 7: NESDIS with no dense node removal * i = 8: AMD for A, COLAMD for A*A' * * You can modify the suite of methods you wish to try by modifying * Common.method [...] after calling cholmod_start or cholmod_defaults. * * For example, to use AMD, followed by a weighted postordering: * * Common->nmethods = 1 ; * Common->method [0].ordering = CHOLMOD_AMD ; * Common->postorder = TRUE ; * * To use the natural ordering (with no postordering): * * Common->nmethods = 1 ; * Common->method [0].ordering = CHOLMOD_NATURAL ; * Common->postorder = FALSE ; * * If you are going to factorize hundreds or more matrices with the same * nonzero pattern, you may wish to spend a great deal of time finding a * good permutation. In this case, try setting Common->nmethods to 9. * The time spent in cholmod_analysis will be very high, but you need to * call it only once. * * cholmod_analyze sets Common->current to a value between 0 and nmethods-1. * Each ordering method uses the set of options defined by this parameter. */ int nmethods ; /* The number of ordering methods to try. Default: 0. * nmethods = 0 is a special case. cholmod_analyze * will try the user-provided ordering (if given) and AMD. Let fl and * lnz be the flop count and nonzeros in L from AMD's ordering. Let * anz be the number of nonzeros in the upper or lower triangular part * of the symmetric matrix A. If fl/lnz < 500 or lnz/anz < 5, then this * is a good ordering, and METIS is not attempted. Otherwise, METIS is * tried. The best ordering found is used. If nmethods > 0, the * methods used are given in the method[ ] array, below. The first * three methods in the default suite of orderings is (1) use the given * permutation (if provided), (2) use AMD, and (3) use METIS. Maximum * allowed value is CHOLMOD_MAXMETHODS. */ int current ; /* The current method being tried. Default: 0. Valid * range is 0 to nmethods-1. */ int selected ; /* The best method found. */ /* The suite of ordering methods and parameters: */ struct cholmod_method_struct { /* statistics for this method */ double lnz ; /* nnz(L) excl. zeros from supernodal amalgamation, * for a "pure" L */ double fl ; /* flop count for a "pure", real simplicial LL' * factorization, with no extra work due to * amalgamation. Subtract n to get the LDL' flop count. Multiply * by about 4 if the matrix is complex or zomplex. */ /* ordering method parameters */ double prune_dense ;/* dense row/col control for AMD, SYMAMD, CSYMAMD, * and NESDIS (cholmod_nested_dissection). For a * symmetric n-by-n matrix, rows/columns with more than * MAX (16, prune_dense * sqrt (n)) entries are removed prior to * ordering. They appear at the end of the re-ordered matrix. * * If prune_dense < 0, only completely dense rows/cols are removed. * * This paramater is also the dense column control for COLAMD and * CCOLAMD. For an m-by-n matrix, columns with more than * MAX (16, prune_dense * sqrt (MIN (m,n))) entries are removed prior * to ordering. They appear at the end of the re-ordered matrix. * CHOLMOD factorizes A*A', so it calls COLAMD and CCOLAMD with A', * not A. Thus, this parameter affects the dense *row* control for * CHOLMOD's matrix, and the dense *column* control for COLAMD and * CCOLAMD. * * Removing dense rows and columns improves the run-time of the * ordering methods. It has some impact on ordering quality * (usually minimal, sometimes good, sometimes bad). * * Default: 10. */ double prune_dense2 ;/* dense row control for COLAMD and CCOLAMD. * Rows with more than MAX (16, dense2 * sqrt (n)) * for an m-by-n matrix are removed prior to ordering. CHOLMOD's * matrix is transposed before ordering it with COLAMD or CCOLAMD, * so this controls the dense *columns* of CHOLMOD's matrix, and * the dense *rows* of COLAMD's or CCOLAMD's matrix. * * If prune_dense2 < 0, only completely dense rows/cols are removed. * * Default: -1. Note that this is not the default for COLAMD and * CCOLAMD. -1 is best for Cholesky. 10 is best for LU. */ double nd_oksep ; /* in NESDIS, when a node separator is computed, it * discarded if nsep >= nd_oksep*n, where nsep is * the number of nodes in the separator, and n is the size of the * graph being cut. Valid range is 0 to 1. If 1 or greater, the * separator is discarded if it consists of the entire graph. * Default: 1 */ double other_1 [4] ; /* future expansion */ size_t nd_small ; /* do not partition graphs with fewer nodes than * nd_small, in NESDIS. Default: 200 (same as * METIS) */ size_t other_2 [4] ; /* future expansion */ int aggressive ; /* Aggresive absorption in AMD, COLAMD, SYMAMD, * CCOLAMD, and CSYMAMD. Default: TRUE */ int order_for_lu ; /* CCOLAMD can be optimized to produce an ordering * for LU or Cholesky factorization. CHOLMOD only * performs a Cholesky factorization. However, you may wish to use * CHOLMOD as an interface for CCOLAMD but use it for your own LU * factorization. In this case, order_for_lu should be set to FALSE. * When factorizing in CHOLMOD itself, you should *** NEVER *** set * this parameter FALSE. Default: TRUE. */ int nd_compress ; /* If TRUE, compress the graph and subgraphs before * partitioning them in NESDIS. Default: TRUE */ int nd_camd ; /* If 1, follow the nested dissection ordering * with a constrained minimum degree ordering that * respects the partitioning just found (using CAMD). If 2, use * CSYMAMD instead. If you set nd_small very small, you may not need * this ordering, and can save time by setting it to zero (no * constrained minimum degree ordering). Default: 1. */ int nd_components ; /* The nested dissection ordering finds a node * separator that splits the graph into two parts, * which may be unconnected. If nd_components is TRUE, each of * these connected components is split independently. If FALSE, * each part is split as a whole, even if it consists of more than * one connected component. Default: FALSE */ /* fill-reducing ordering to use */ int ordering ; size_t other_3 [4] ; /* future expansion */ } method [CHOLMOD_MAXMETHODS + 1] ; int postorder ; /* If TRUE, cholmod_analyze follows the ordering with a * weighted postorder of the elimination tree. Improves * supernode amalgamation. Does not affect fundamental nnz(L) and * flop count. Default: TRUE. */ /* ---------------------------------------------------------------------- */ /* memory management routines */ /* ---------------------------------------------------------------------- */ void *(*malloc_memory) (size_t) ; /* pointer to malloc */ void *(*realloc_memory) (void *, size_t) ; /* pointer to realloc */ void (*free_memory) (void *) ; /* pointer to free */ void *(*calloc_memory) (size_t, size_t) ; /* pointer to calloc */ /* ---------------------------------------------------------------------- */ /* routines for complex arithmetic */ /* ---------------------------------------------------------------------- */ int (*complex_divide) (double ax, double az, double bx, double bz, double *cx, double *cz) ; /* flag = complex_divide (ax, az, bx, bz, &cx, &cz) computes the complex * division c = a/b, where ax and az hold the real and imaginary part * of a, and b and c are stored similarly. flag is returned as 1 if * a divide-by-zero occurs, or 0 otherwise. By default, the function * pointer Common->complex_divide is set equal to cholmod_divcomplex. */ double (*hypotenuse) (double x, double y) ; /* s = hypotenuse (x,y) computes s = sqrt (x*x + y*y), but does so more * accurately. By default, the function pointer Common->hypotenuse is * set equal to cholmod_hypot. See also the hypot function in the C99 * standard, which has an identical syntax and function. If you have * a C99-compliant compiler, you can set Common->hypotenuse = hypot. */ /* ---------------------------------------------------------------------- */ /* METIS workarounds */ /* ---------------------------------------------------------------------- */ double metis_memory ; /* This is a parameter for CHOLMOD's interface to * METIS, not a parameter to METIS itself. METIS * uses an amount of memory that is difficult to estimate precisely * beforehand. If it runs out of memory, it terminates your program. * All routines in CHOLMOD except for CHOLMOD's interface to METIS * return an error status and safely return to your program if they run * out of memory. To mitigate this problem, the CHOLMOD interface * can allocate a single block of memory equal in size to an empirical * upper bound of METIS's memory usage times the Common->metis_memory * parameter, and then immediately free it. It then calls METIS. If * this pre-allocation fails, it is possible that METIS will fail as * well, and so CHOLMOD returns with an out-of-memory condition without * calling METIS. * * METIS_NodeND (used in the CHOLMOD_METIS ordering option) with its * default parameter settings typically uses about (4*nz+40n+4096) * times sizeof(int) memory, where nz is equal to the number of entries * in A for the symmetric case or AA' if an unsymmetric matrix is * being ordered (where nz includes both the upper and lower parts * of A or AA'). The observed "upper bound" (with 2 exceptions), * measured in an instrumented copy of METIS 4.0.1 on thousands of * matrices, is (10*nz+50*n+4096) * sizeof(int). Two large matrices * exceeded this bound, one by almost a factor of 2 (Gupta/gupta2). * * If your program is terminated by METIS, try setting metis_memory to * 2.0, or even higher if needed. By default, CHOLMOD assumes that METIS * does not have this problem (so that CHOLMOD will work correctly when * this issue is fixed in METIS). Thus, the default value is zero. * This work-around is not guaranteed anyway. * * If a matrix exceeds this predicted memory usage, AMD is attempted * instead. It, too, may run out of memory, but if it does so it will * not terminate your program. */ double metis_dswitch ; /* METIS_NodeND in METIS 4.0.1 gives a seg */ size_t metis_nswitch ; /* fault with one matrix of order n = 3005 and * nz = 6,036,025. This is a very dense graph. * The workaround is to use AMD instead of METIS for matrices of dimension * greater than Common->metis_nswitch (default 3000) or more and with * density of Common->metis_dswitch (default 0.66) or more. * cholmod_nested_dissection has no problems with the same matrix, even * though it uses METIS_NodeComputeSeparator on this matrix. If this * seg fault does not affect you, set metis_nswitch to zero or less, * and CHOLMOD will not switch to AMD based just on the density of the * matrix (it will still switch to AMD if the metis_memory parameter * causes the switch). */ /* ---------------------------------------------------------------------- */ /* workspace */ /* ---------------------------------------------------------------------- */ /* CHOLMOD has several routines that take less time than the size of * workspace they require. Allocating and initializing the workspace would * dominate the run time, unless workspace is allocated and initialized * just once. CHOLMOD allocates this space when needed, and holds it here * between calls to CHOLMOD. cholmod_start sets these pointers to NULL * (which is why it must be the first routine called in CHOLMOD). * cholmod_finish frees the workspace (which is why it must be the last * call to CHOLMOD). */ size_t nrow ; /* size of Flag and Head */ SuiteSparse_long mark ; /* mark value for Flag array */ size_t iworksize ; /* size of Iwork. Upper bound: 6*nrow+ncol */ size_t xworksize ; /* size of Xwork, in bytes. * maxrank*nrow*sizeof(double) for update/downdate. * 2*nrow*sizeof(double) otherwise */ /* initialized workspace: contents needed between calls to CHOLMOD */ void *Flag ; /* size nrow, an integer array. Kept cleared between * calls to cholmod rouines (Flag [i] < mark) */ void *Head ; /* size nrow+1, an integer array. Kept cleared between * calls to cholmod routines (Head [i] = EMPTY) */ void *Xwork ; /* a double array. Its size varies. It is nrow for * most routines (cholmod_rowfac, cholmod_add, * cholmod_aat, cholmod_norm, cholmod_ssmult) for the real case, twice * that when the input matrices are complex or zomplex. It is of size * 2*nrow for cholmod_rowadd and cholmod_rowdel. For cholmod_updown, * its size is maxrank*nrow where maxrank is 2, 4, or 8. Kept cleared * between calls to cholmod (set to zero). */ /* uninitialized workspace, contents not needed between calls to CHOLMOD */ void *Iwork ; /* size iworksize, 2*nrow+ncol for most routines, * up to 6*nrow+ncol for cholmod_analyze. */ int itype ; /* If CHOLMOD_LONG, Flag, Head, and Iwork are * SuiteSparse_long. Otherwise all three are int. */ int dtype ; /* double or float */ /* Common->itype and Common->dtype are used to define the types of all * sparse matrices, triplet matrices, dense matrices, and factors * created using this Common struct. The itypes and dtypes of all * parameters to all CHOLMOD routines must match. */ int no_workspace_reallocate ; /* this is an internal flag, used as a * precaution by cholmod_analyze. It is normally false. If true, * cholmod_allocate_work is not allowed to reallocate any workspace; * they must use the existing workspace in Common (Iwork, Flag, Head, * and Xwork). Added for CHOLMOD v1.1 */ /* ---------------------------------------------------------------------- */ /* statistics */ /* ---------------------------------------------------------------------- */ /* fl and lnz are set only in cholmod_analyze and cholmod_rowcolcounts, * in the Cholesky modudle. modfl is set only in the Modify module. */ int status ; /* error code */ double fl ; /* LL' flop count from most recent analysis */ double lnz ; /* fundamental nz in L */ double anz ; /* nonzeros in tril(A) if A is symmetric/lower, * triu(A) if symmetric/upper, or tril(A*A') if * unsymmetric, in last call to cholmod_analyze. */ double modfl ; /* flop count from most recent update/downdate/ * rowadd/rowdel (excluding flops to modify the * solution to Lx=b, if computed) */ size_t malloc_count ; /* # of objects malloc'ed minus the # free'd*/ size_t memory_usage ; /* peak memory usage in bytes */ size_t memory_inuse ; /* current memory usage in bytes */ double nrealloc_col ; /* # of column reallocations */ double nrealloc_factor ;/* # of factor reallocations due to col. reallocs */ double ndbounds_hit ; /* # of times diagonal modified by dbound */ double rowfacfl ; /* # of flops in last call to cholmod_rowfac */ double aatfl ; /* # of flops to compute A(:,f)*A(:,f)' */ /* ---------------------------------------------------------------------- */ /* statistics, parameters, and future expansion */ /* ---------------------------------------------------------------------- */ /* The goal for future expansion is to keep sizeof(Common) unchanged. */ double other1 [10] ; /* [0..9] for CHOLMOD GPU/CPU numerical factorization statistics, and [0..3] used by SuiteSparseQR statistics */ double SPQR_xstat [4] ; /* for SuiteSparseQR statistics */ /* SuiteSparseQR control parameters: */ double SPQR_grain ; /* task size is >= max (total flops / grain) */ double SPQR_small ; /* task size is >= small */ /* ---------------------------------------------------------------------- */ SuiteSparse_long SPQR_istat [10] ; /* for SuiteSparseQR statistics */ SuiteSparse_long other2 [6] ; /* unused (for future expansion) */ /* ---------------------------------------------------------------------- */ int other3 [10] ; /* unused (for future expansion) */ int prefer_binary ; /* cholmod_read_triplet converts a symmetric * pattern-only matrix into a real matrix. If * prefer_binary is FALSE, the diagonal entries are set to 1 + the degree * of the row/column, and off-diagonal entries are set to -1 (resulting * in a positive definite matrix if the diagonal is zero-free). Most * symmetric patterns are the pattern a positive definite matrix. If * this parameter is TRUE, then the matrix is returned with a 1 in each * entry, instead. Default: FALSE. Added in v1.3. */ /* control parameter (added for v1.2): */ int default_nesdis ; /* Default: FALSE. If FALSE, then the default * ordering strategy (when Common->nmethods == 0) * is to try the given ordering (if present), AMD, and then METIS if AMD * reports high fill-in. If Common->default_nesdis is TRUE then NESDIS * is used instead in the default strategy. */ /* statistic (added for v1.2): */ int called_nd ; /* TRUE if the last call to * cholmod_analyze called NESDIS or METIS. */ int blas_ok ; /* FALSE if BLAS int overflow; TRUE otherwise */ /* SuiteSparseQR control parameters: */ int SPQR_shrink ; /* controls stack realloc method */ int SPQR_nthreads ; /* number of TBB threads, 0 = auto */ /* ---------------------------------------------------------------------- */ size_t other4 [16] ; /* [0..7] for CHOLMOD GPU/CPU numerical factorization statistics, remainder unused (for future expansion) */ /* ---------------------------------------------------------------------- */ void *other5 [16] ; /* unused (for future expansion) */ /* ---------------------------------------------------------------------- */ /* GPU configuration */ /* ---------------------------------------------------------------------- */ #ifdef GPU_BLAS /* gpuConfig_t gpuConfig ; */ cublasHandle_t cublasHandle ; cudaStream_t cudaStreamSyrk ; cudaStream_t cudaStreamGemm ; cudaStream_t cudaStreamTrsm ; cudaStream_t cudaStreamPotrf [3] ; cudaEvent_t cublasEventPotrf [2] ; void *HostPinnedMemory ; void *devPotrfWork ; void *devSyrkGemmPtrLx ; void *devSyrkGemmPtrC ; int GemmUsed ; /* TRUE if cuda dgemm used, false otherwise */ int SyrkUsed ; /* TRUE if cuda dsyrk used, false otherwise */ double syrkStart ; /* time syrk started */ #endif } cholmod_common ; /* size_t BLAS statistcs in Common: */ #define CHOLMOD_CPU_GEMM_CALLS other4 [0] #define CHOLMOD_CPU_SYRK_CALLS other4 [1] #define CHOLMOD_CPU_TRSM_CALLS other4 [2] #define CHOLMOD_CPU_POTRF_CALLS other4 [3] #define CHOLMOD_GPU_GEMM_CALLS other4 [4] #define CHOLMOD_GPU_SYRK_CALLS other4 [5] #define CHOLMOD_GPU_TRSM_CALLS other4 [6] #define CHOLMOD_GPU_POTRF_CALLS other4 [7] /* double BLAS statistics in Common: */ #define CHOLMOD_CPU_GEMM_TIME other1 [0] #define CHOLMOD_CPU_SYRK_TIME other1 [1] #define CHOLMOD_CPU_TRSM_TIME other1 [2] #define CHOLMOD_CPU_POTRF_TIME other1 [3] #define CHOLMOD_GPU_GEMM_TIME other1 [4] #define CHOLMOD_GPU_SYRK_TIME other1 [5] #define CHOLMOD_GPU_TRSM_TIME other1 [6] #define CHOLMOD_GPU_POTRF_TIME other1 [7] #define CHOLMOD_ASSEMBLE_TIME other1 [8] #define CHOLMOD_ASSEMBLE_TIME2 other1 [9] /* -------------------------------------------------------------------------- */ /* cholmod_start: first call to CHOLMOD */ /* -------------------------------------------------------------------------- */ int cholmod_start ( cholmod_common *Common ) ; int cholmod_l_start (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_finish: last call to CHOLMOD */ /* -------------------------------------------------------------------------- */ int cholmod_finish ( cholmod_common *Common ) ; int cholmod_l_finish (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_defaults: restore default parameters */ /* -------------------------------------------------------------------------- */ int cholmod_defaults ( cholmod_common *Common ) ; int cholmod_l_defaults (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_maxrank: return valid maximum rank for update/downdate */ /* -------------------------------------------------------------------------- */ size_t cholmod_maxrank /* returns validated value of Common->maxrank */ ( /* ---- input ---- */ size_t n, /* A and L will have n rows */ /* --------------- */ cholmod_common *Common ) ; size_t cholmod_l_maxrank (size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_allocate_work: allocate workspace in Common */ /* -------------------------------------------------------------------------- */ int cholmod_allocate_work ( /* ---- input ---- */ size_t nrow, /* size: Common->Flag (nrow), Common->Head (nrow+1) */ size_t iworksize, /* size of Common->Iwork */ size_t xworksize, /* size of Common->Xwork */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_allocate_work (size_t, size_t, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_free_work: free workspace in Common */ /* -------------------------------------------------------------------------- */ int cholmod_free_work ( cholmod_common *Common ) ; int cholmod_l_free_work (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_clear_flag: clear Flag workspace in Common */ /* -------------------------------------------------------------------------- */ /* use a macro for speed */ #define CHOLMOD_CLEAR_FLAG(Common) \ { \ Common->mark++ ; \ if (Common->mark <= 0) \ { \ Common->mark = EMPTY ; \ CHOLMOD (clear_flag) (Common) ; \ } \ } SuiteSparse_long cholmod_clear_flag ( cholmod_common *Common ) ; SuiteSparse_long cholmod_l_clear_flag (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_error: called when CHOLMOD encounters an error */ /* -------------------------------------------------------------------------- */ int cholmod_error ( /* ---- input ---- */ int status, /* error status */ const char *file, /* name of source code file where error occured */ int line, /* line number in source code file where error occured*/ const char *message,/* error message */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_error (int, const char *, int, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_dbound: for internal use in CHOLMOD only */ /* -------------------------------------------------------------------------- */ double cholmod_dbound /* returns modified diagonal entry of D or L */ ( /* ---- input ---- */ double dj, /* diagonal entry of D for LDL' or L for LL' */ /* --------------- */ cholmod_common *Common ) ; double cholmod_l_dbound (double, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_hypot: compute sqrt (x*x + y*y) accurately */ /* -------------------------------------------------------------------------- */ double cholmod_hypot ( /* ---- input ---- */ double x, double y ) ; double cholmod_l_hypot (double, double) ; /* -------------------------------------------------------------------------- */ /* cholmod_divcomplex: complex division, c = a/b */ /* -------------------------------------------------------------------------- */ int cholmod_divcomplex /* return 1 if divide-by-zero, 0 otherise */ ( /* ---- input ---- */ double ar, double ai, /* real and imaginary parts of a */ double br, double bi, /* real and imaginary parts of b */ /* ---- output --- */ double *cr, double *ci /* real and imaginary parts of c */ ) ; int cholmod_l_divcomplex (double, double, double, double, double *, double *) ; /* ========================================================================== */ /* === Core/cholmod_sparse ================================================== */ /* ========================================================================== */ /* A sparse matrix stored in compressed-column form. */ typedef struct cholmod_sparse_struct { size_t nrow ; /* the matrix is nrow-by-ncol */ size_t ncol ; size_t nzmax ; /* maximum number of entries in the matrix */ /* pointers to int or SuiteSparse_long: */ void *p ; /* p [0..ncol], the column pointers */ void *i ; /* i [0..nzmax-1], the row indices */ /* for unpacked matrices only: */ void *nz ; /* nz [0..ncol-1], the # of nonzeros in each col. In * packed form, the nonzero pattern of column j is in * A->i [A->p [j] ... A->p [j+1]-1]. In unpacked form, column j is in * A->i [A->p [j] ... A->p [j]+A->nz[j]-1] instead. In both cases, the * numerical values (if present) are in the corresponding locations in * the array x (or z if A->xtype is CHOLMOD_ZOMPLEX). */ /* pointers to double or float: */ void *x ; /* size nzmax or 2*nzmax, if present */ void *z ; /* size nzmax, if present */ int stype ; /* Describes what parts of the matrix are considered: * * 0: matrix is "unsymmetric": use both upper and lower triangular parts * (the matrix may actually be symmetric in pattern and value, but * both parts are explicitly stored and used). May be square or * rectangular. * >0: matrix is square and symmetric, use upper triangular part. * Entries in the lower triangular part are ignored. * <0: matrix is square and symmetric, use lower triangular part. * Entries in the upper triangular part are ignored. * * Note that stype>0 and stype<0 are different for cholmod_sparse and * cholmod_triplet. See the cholmod_triplet data structure for more * details. */ int itype ; /* CHOLMOD_INT: p, i, and nz are int. * CHOLMOD_INTLONG: p is SuiteSparse_long, * i and nz are int. * CHOLMOD_LONG: p, i, and nz are SuiteSparse_long */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z are double or float */ int sorted ; /* TRUE if columns are sorted, FALSE otherwise */ int packed ; /* TRUE if packed (nz ignored), FALSE if unpacked * (nz is required) */ } cholmod_sparse ; /* -------------------------------------------------------------------------- */ /* cholmod_allocate_sparse: allocate a sparse matrix */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_allocate_sparse ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ size_t nzmax, /* max # of nonzeros of A */ int sorted, /* TRUE if columns of A sorted, FALSE otherwise */ int packed, /* TRUE if A will be packed, FALSE otherwise */ int stype, /* stype of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_allocate_sparse (size_t, size_t, size_t, int, int, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_free_sparse: free a sparse matrix */ /* -------------------------------------------------------------------------- */ int cholmod_free_sparse ( /* ---- in/out --- */ cholmod_sparse **A, /* matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_free_sparse (cholmod_sparse **, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_reallocate_sparse: change the size (# entries) of sparse matrix */ /* -------------------------------------------------------------------------- */ int cholmod_reallocate_sparse ( /* ---- input ---- */ size_t nznew, /* new # of entries in A */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to reallocate */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_reallocate_sparse ( size_t, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_nnz: return number of nonzeros in a sparse matrix */ /* -------------------------------------------------------------------------- */ SuiteSparse_long cholmod_nnz ( /* ---- input ---- */ cholmod_sparse *A, /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_nnz (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_speye: sparse identity matrix */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_speye ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_speye (size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_spzeros: sparse zero matrix */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_spzeros ( /* ---- input ---- */ size_t nrow, /* # of rows of A */ size_t ncol, /* # of columns of A */ size_t nzmax, /* max # of nonzeros of A */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_spzeros (size_t, size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_transpose: transpose a sparse matrix */ /* -------------------------------------------------------------------------- */ /* Return A' or A.' The "values" parameter is 0, 1, or 2 to denote the pattern * transpose, the array transpose (A.'), and the complex conjugate transpose * (A'). */ cholmod_sparse *cholmod_transpose ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 0: pattern, 1: array transpose, 2: conj. transpose */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_transpose (cholmod_sparse *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_transpose_unsym: transpose an unsymmetric sparse matrix */ /* -------------------------------------------------------------------------- */ /* Compute F = A', A (:,f)', or A (p,f)', where A is unsymmetric and F is * already allocated. See cholmod_transpose for a simpler routine. */ int cholmod_transpose_unsym ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 0: pattern, 1: array transpose, 2: conj. transpose */ int *Perm, /* size nrow, if present (can be NULL) */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ cholmod_sparse *F, /* F = A', A(:,f)', or A(p,f)' */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_transpose_unsym (cholmod_sparse *, int, SuiteSparse_long *, SuiteSparse_long *, size_t, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_transpose_sym: transpose a symmetric sparse matrix */ /* -------------------------------------------------------------------------- */ /* Compute F = A' or A (p,p)', where A is symmetric and F is already allocated. * See cholmod_transpose for a simpler routine. */ int cholmod_transpose_sym ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 0: pattern, 1: array transpose, 2: conj. transpose */ int *Perm, /* size nrow, if present (can be NULL) */ /* ---- output --- */ cholmod_sparse *F, /* F = A' or A(p,p)' */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_transpose_sym (cholmod_sparse *, int, SuiteSparse_long *, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_ptranspose: transpose a sparse matrix */ /* -------------------------------------------------------------------------- */ /* Return A' or A(p,p)' if A is symmetric. Return A', A(:,f)', or A(p,f)' if * A is unsymmetric. */ cholmod_sparse *cholmod_ptranspose ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to transpose */ int values, /* 0: pattern, 1: array transpose, 2: conj. transpose */ int *Perm, /* if non-NULL, F = A(p,f) or A(p,p) */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_ptranspose (cholmod_sparse *, int, SuiteSparse_long *, SuiteSparse_long *, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_sort: sort row indices in each column of sparse matrix */ /* -------------------------------------------------------------------------- */ int cholmod_sort ( /* ---- in/out --- */ cholmod_sparse *A, /* matrix to sort */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_sort (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_band: C = tril (triu (A,k1), k2) */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_band ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to extract band matrix from */ SuiteSparse_long k1, /* ignore entries below the k1-st diagonal */ SuiteSparse_long k2, /* ignore entries above the k2-nd diagonal */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_band (cholmod_sparse *, SuiteSparse_long, SuiteSparse_long, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_band_inplace: A = tril (triu (A,k1), k2) */ /* -------------------------------------------------------------------------- */ int cholmod_band_inplace ( /* ---- input ---- */ SuiteSparse_long k1, /* ignore entries below the k1-st diagonal */ SuiteSparse_long k2, /* ignore entries above the k2-nd diagonal */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix from which entries not in band are removed */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_band_inplace (SuiteSparse_long, SuiteSparse_long, int, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_aat: C = A*A' or A(:,f)*A(:,f)' */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_aat ( /* ---- input ---- */ cholmod_sparse *A, /* input matrix; C=A*A' is constructed */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag), * -2: pattern only, no diagonal, add 50%+n extra * space to C */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_aat (cholmod_sparse *, SuiteSparse_long *, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy_sparse: C = A, create an exact copy of a sparse matrix */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_copy_sparse ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_copy_sparse (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy: C = A, with possible change of stype */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_copy ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ int stype, /* requested stype of C */ int mode, /* >0: numerical, 0: pattern, <0: pattern (no diag) */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_copy (cholmod_sparse *, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_add: C = alpha*A + beta*B */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_add ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to add */ cholmod_sparse *B, /* matrix to add */ double alpha [2], /* scale factor for A */ double beta [2], /* scale factor for B */ int values, /* if TRUE compute the numerical values of C */ int sorted, /* if TRUE, sort columns of C */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_add (cholmod_sparse *, cholmod_sparse *, double *, double *, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_sparse_xtype: change the xtype of a sparse matrix */ /* -------------------------------------------------------------------------- */ int cholmod_sparse_xtype ( /* ---- input ---- */ int to_xtype, /* requested xtype (pattern, real, complex, zomplex) */ /* ---- in/out --- */ cholmod_sparse *A, /* sparse matrix to change */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_sparse_xtype (int, cholmod_sparse *, cholmod_common *) ; /* ========================================================================== */ /* === Core/cholmod_factor ================================================== */ /* ========================================================================== */ /* A symbolic and numeric factorization, either simplicial or supernodal. * In all cases, the row indices in the columns of L are kept sorted. */ typedef struct cholmod_factor_struct { /* ---------------------------------------------------------------------- */ /* for both simplicial and supernodal factorizations */ /* ---------------------------------------------------------------------- */ size_t n ; /* L is n-by-n */ size_t minor ; /* If the factorization failed, L->minor is the column * at which it failed (in the range 0 to n-1). A value * of n means the factorization was successful or * the matrix has not yet been factorized. */ /* ---------------------------------------------------------------------- */ /* symbolic ordering and analysis */ /* ---------------------------------------------------------------------- */ void *Perm ; /* size n, permutation used */ void *ColCount ; /* size n, column counts for simplicial L */ void *IPerm ; /* size n, inverse permutation. Only created by * cholmod_solve2 if Bset is used. */ /* ---------------------------------------------------------------------- */ /* simplicial factorization */ /* ---------------------------------------------------------------------- */ size_t nzmax ; /* size of i and x */ void *p ; /* p [0..ncol], the column pointers */ void *i ; /* i [0..nzmax-1], the row indices */ void *x ; /* x [0..nzmax-1], the numerical values */ void *z ; void *nz ; /* nz [0..ncol-1], the # of nonzeros in each column. * i [p [j] ... p [j]+nz[j]-1] contains the row indices, * and the numerical values are in the same locatins * in x. The value of i [p [k]] is always k. */ void *next ; /* size ncol+2. next [j] is the next column in i/x */ void *prev ; /* size ncol+2. prev [j] is the prior column in i/x. * head of the list is ncol+1, and the tail is ncol. */ /* ---------------------------------------------------------------------- */ /* supernodal factorization */ /* ---------------------------------------------------------------------- */ /* Note that L->x is shared with the simplicial data structure. L->x has * size L->nzmax for a simplicial factor, and size L->xsize for a supernodal * factor. */ size_t nsuper ; /* number of supernodes */ size_t ssize ; /* size of s, integer part of supernodes */ size_t xsize ; /* size of x, real part of supernodes */ size_t maxcsize ; /* size of largest update matrix */ size_t maxesize ; /* max # of rows in supernodes, excl. triangular part */ void *super ; /* size nsuper+1, first col in each supernode */ void *pi ; /* size nsuper+1, pointers to integer patterns */ void *px ; /* size nsuper+1, pointers to real parts */ void *s ; /* size ssize, integer part of supernodes */ /* ---------------------------------------------------------------------- */ /* factorization type */ /* ---------------------------------------------------------------------- */ int ordering ; /* ordering method used */ int is_ll ; /* TRUE if LL', FALSE if LDL' */ int is_super ; /* TRUE if supernodal, FALSE if simplicial */ int is_monotonic ; /* TRUE if columns of L appear in order 0..n-1. * Only applicable to simplicial numeric types. */ /* There are 8 types of factor objects that cholmod_factor can represent * (only 6 are used): * * Numeric types (xtype is not CHOLMOD_PATTERN) * -------------------------------------------- * * simplicial LDL': (is_ll FALSE, is_super FALSE). Stored in compressed * column form, using the simplicial components above (nzmax, p, i, * x, z, nz, next, and prev). The unit diagonal of L is not stored, * and D is stored in its place. There are no supernodes. * * simplicial LL': (is_ll TRUE, is_super FALSE). Uses the same storage * scheme as the simplicial LDL', except that D does not appear. * The first entry of each column of L is the diagonal entry of * that column of L. * * supernodal LDL': (is_ll FALSE, is_super TRUE). Not used. * FUTURE WORK: add support for supernodal LDL' * * supernodal LL': (is_ll TRUE, is_super TRUE). A supernodal factor, * using the supernodal components described above (nsuper, ssize, * xsize, maxcsize, maxesize, super, pi, px, s, x, and z). * * * Symbolic types (xtype is CHOLMOD_PATTERN) * ----------------------------------------- * * simplicial LDL': (is_ll FALSE, is_super FALSE). Nothing is present * except Perm and ColCount. * * simplicial LL': (is_ll TRUE, is_super FALSE). Identical to the * simplicial LDL', except for the is_ll flag. * * supernodal LDL': (is_ll FALSE, is_super TRUE). Not used. * FUTURE WORK: add support for supernodal LDL' * * supernodal LL': (is_ll TRUE, is_super TRUE). A supernodal symbolic * factorization. The simplicial symbolic information is present * (Perm and ColCount), as is all of the supernodal factorization * except for the numerical values (x and z). */ int itype ; /* The integer arrays are Perm, ColCount, p, i, nz, * next, prev, super, pi, px, and s. If itype is * CHOLMOD_INT, all of these are int arrays. * CHOLMOD_INTLONG: p, pi, px are SuiteSparse_long, others int. * CHOLMOD_LONG: all integer arrays are SuiteSparse_long. */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z double or float */ } cholmod_factor ; /* -------------------------------------------------------------------------- */ /* cholmod_allocate_factor: allocate a factor (symbolic LL' or LDL') */ /* -------------------------------------------------------------------------- */ cholmod_factor *cholmod_allocate_factor ( /* ---- input ---- */ size_t n, /* L is n-by-n */ /* --------------- */ cholmod_common *Common ) ; cholmod_factor *cholmod_l_allocate_factor (size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_free_factor: free a factor */ /* -------------------------------------------------------------------------- */ int cholmod_free_factor ( /* ---- in/out --- */ cholmod_factor **L, /* factor to free, NULL on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_free_factor (cholmod_factor **, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_reallocate_factor: change the # entries in a factor */ /* -------------------------------------------------------------------------- */ int cholmod_reallocate_factor ( /* ---- input ---- */ size_t nznew, /* new # of entries in L */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_reallocate_factor (size_t, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_change_factor: change the type of factor (e.g., LDL' to LL') */ /* -------------------------------------------------------------------------- */ int cholmod_change_factor ( /* ---- input ---- */ int to_xtype, /* to CHOLMOD_PATTERN, _REAL, _COMPLEX, _ZOMPLEX */ int to_ll, /* TRUE: convert to LL', FALSE: LDL' */ int to_super, /* TRUE: convert to supernodal, FALSE: simplicial */ int to_packed, /* TRUE: pack simplicial columns, FALSE: do not pack */ int to_monotonic, /* TRUE: put simplicial columns in order, FALSE: not */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_change_factor ( int, int, int, int, int, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_pack_factor: pack the columns of a factor */ /* -------------------------------------------------------------------------- */ /* Pack the columns of a simplicial factor. Unlike cholmod_change_factor, * it can pack the columns of a factor even if they are not stored in their * natural order (non-monotonic). */ int cholmod_pack_factor ( /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_pack_factor (cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_reallocate_column: resize a single column of a factor */ /* -------------------------------------------------------------------------- */ int cholmod_reallocate_column ( /* ---- input ---- */ size_t j, /* the column to reallocate */ size_t need, /* required size of column j */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_reallocate_column (size_t, size_t, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_factor_to_sparse: create a sparse matrix copy of a factor */ /* -------------------------------------------------------------------------- */ /* Only operates on numeric factors, not symbolic ones */ cholmod_sparse *cholmod_factor_to_sparse ( /* ---- in/out --- */ cholmod_factor *L, /* factor to copy, converted to symbolic on output */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_factor_to_sparse (cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy_factor: create a copy of a factor */ /* -------------------------------------------------------------------------- */ cholmod_factor *cholmod_copy_factor ( /* ---- input ---- */ cholmod_factor *L, /* factor to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_factor *cholmod_l_copy_factor (cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_factor_xtype: change the xtype of a factor */ /* -------------------------------------------------------------------------- */ int cholmod_factor_xtype ( /* ---- input ---- */ int to_xtype, /* requested xtype (real, complex, or zomplex) */ /* ---- in/out --- */ cholmod_factor *L, /* factor to change */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_factor_xtype (int, cholmod_factor *, cholmod_common *) ; /* ========================================================================== */ /* === Core/cholmod_dense =================================================== */ /* ========================================================================== */ /* A dense matrix in column-oriented form. It has no itype since it contains * no integers. Entry in row i and column j is located in x [i+j*d]. */ typedef struct cholmod_dense_struct { size_t nrow ; /* the matrix is nrow-by-ncol */ size_t ncol ; size_t nzmax ; /* maximum number of entries in the matrix */ size_t d ; /* leading dimension (d >= nrow must hold) */ void *x ; /* size nzmax or 2*nzmax, if present */ void *z ; /* size nzmax, if present */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z double or float */ } cholmod_dense ; /* -------------------------------------------------------------------------- */ /* cholmod_allocate_dense: allocate a dense matrix (contents uninitialized) */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_allocate_dense ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ size_t d, /* leading dimension */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_allocate_dense (size_t, size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_zeros: allocate a dense matrix and set it to zero */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_zeros ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_zeros (size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_ones: allocate a dense matrix and set it to all ones */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_ones ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_ones (size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_eye: allocate a dense matrix and set it to the identity matrix */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_eye ( /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_eye (size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_free_dense: free a dense matrix */ /* -------------------------------------------------------------------------- */ int cholmod_free_dense ( /* ---- in/out --- */ cholmod_dense **X, /* dense matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_free_dense (cholmod_dense **, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_ensure_dense: ensure a dense matrix has a given size and type */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_ensure_dense ( /* ---- input/output ---- */ cholmod_dense **XHandle, /* matrix handle to check */ /* ---- input ---- */ size_t nrow, /* # of rows of matrix */ size_t ncol, /* # of columns of matrix */ size_t d, /* leading dimension */ int xtype, /* CHOLMOD_REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_ensure_dense (cholmod_dense **, size_t, size_t, size_t, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_sparse_to_dense: create a dense matrix copy of a sparse matrix */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_sparse_to_dense ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_sparse_to_dense (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_dense_to_sparse: create a sparse matrix copy of a dense matrix */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_dense_to_sparse ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ int values, /* TRUE if values to be copied, FALSE otherwise */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_dense_to_sparse (cholmod_dense *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy_dense: create a copy of a dense matrix */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_copy_dense ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_copy_dense (cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy_dense2: copy a dense matrix (pre-allocated) */ /* -------------------------------------------------------------------------- */ int cholmod_copy_dense2 ( /* ---- input ---- */ cholmod_dense *X, /* matrix to copy */ /* ---- output --- */ cholmod_dense *Y, /* copy of matrix X */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_copy_dense2 (cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_dense_xtype: change the xtype of a dense matrix */ /* -------------------------------------------------------------------------- */ int cholmod_dense_xtype ( /* ---- input ---- */ int to_xtype, /* requested xtype (real, complex,or zomplex) */ /* ---- in/out --- */ cholmod_dense *X, /* dense matrix to change */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_dense_xtype (int, cholmod_dense *, cholmod_common *) ; /* ========================================================================== */ /* === Core/cholmod_triplet ================================================= */ /* ========================================================================== */ /* A sparse matrix stored in triplet form. */ typedef struct cholmod_triplet_struct { size_t nrow ; /* the matrix is nrow-by-ncol */ size_t ncol ; size_t nzmax ; /* maximum number of entries in the matrix */ size_t nnz ; /* number of nonzeros in the matrix */ void *i ; /* i [0..nzmax-1], the row indices */ void *j ; /* j [0..nzmax-1], the column indices */ void *x ; /* size nzmax or 2*nzmax, if present */ void *z ; /* size nzmax, if present */ int stype ; /* Describes what parts of the matrix are considered: * * 0: matrix is "unsymmetric": use both upper and lower triangular parts * (the matrix may actually be symmetric in pattern and value, but * both parts are explicitly stored and used). May be square or * rectangular. * >0: matrix is square and symmetric. Entries in the lower triangular * part are transposed and added to the upper triangular part when * the matrix is converted to cholmod_sparse form. * <0: matrix is square and symmetric. Entries in the upper triangular * part are transposed and added to the lower triangular part when * the matrix is converted to cholmod_sparse form. * * Note that stype>0 and stype<0 are different for cholmod_sparse and * cholmod_triplet. The reason is simple. You can permute a symmetric * triplet matrix by simply replacing a row and column index with their * new row and column indices, via an inverse permutation. Suppose * P = L->Perm is your permutation, and Pinv is an array of size n. * Suppose a symmetric matrix A is represent by a triplet matrix T, with * entries only in the upper triangular part. Then the following code: * * Ti = T->i ; * Tj = T->j ; * for (k = 0 ; k < n ; k++) Pinv [P [k]] = k ; * for (k = 0 ; k < nz ; k++) Ti [k] = Pinv [Ti [k]] ; * for (k = 0 ; k < nz ; k++) Tj [k] = Pinv [Tj [k]] ; * * creates the triplet form of C=P*A*P'. However, if T initially * contains just the upper triangular entries (T->stype = 1), after * permutation it has entries in both the upper and lower triangular * parts. These entries should be transposed when constructing the * cholmod_sparse form of A, which is what cholmod_triplet_to_sparse * does. Thus: * * C = cholmod_triplet_to_sparse (T, 0, &Common) ; * * will return the matrix C = P*A*P'. * * Since the triplet matrix T is so simple to generate, it's quite easy * to remove entries that you do not want, prior to converting T to the * cholmod_sparse form. So if you include these entries in T, CHOLMOD * assumes that there must be a reason (such as the one above). Thus, * no entry in a triplet matrix is ever ignored. */ int itype ; /* CHOLMOD_LONG: i and j are SuiteSparse_long. Otherwise int */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z are double or float */ } cholmod_triplet ; /* -------------------------------------------------------------------------- */ /* cholmod_allocate_triplet: allocate a triplet matrix */ /* -------------------------------------------------------------------------- */ cholmod_triplet *cholmod_allocate_triplet ( /* ---- input ---- */ size_t nrow, /* # of rows of T */ size_t ncol, /* # of columns of T */ size_t nzmax, /* max # of nonzeros of T */ int stype, /* stype of T */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* --------------- */ cholmod_common *Common ) ; cholmod_triplet *cholmod_l_allocate_triplet (size_t, size_t, size_t, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_free_triplet: free a triplet matrix */ /* -------------------------------------------------------------------------- */ int cholmod_free_triplet ( /* ---- in/out --- */ cholmod_triplet **T, /* triplet matrix to deallocate, NULL on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_free_triplet (cholmod_triplet **, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_reallocate_triplet: change the # of entries in a triplet matrix */ /* -------------------------------------------------------------------------- */ int cholmod_reallocate_triplet ( /* ---- input ---- */ size_t nznew, /* new # of entries in T */ /* ---- in/out --- */ cholmod_triplet *T, /* triplet matrix to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_reallocate_triplet (size_t, cholmod_triplet *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_sparse_to_triplet: create a triplet matrix copy of a sparse matrix*/ /* -------------------------------------------------------------------------- */ cholmod_triplet *cholmod_sparse_to_triplet ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_triplet *cholmod_l_sparse_to_triplet (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_triplet_to_sparse: create a sparse matrix copy of a triplet matrix*/ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_triplet_to_sparse ( /* ---- input ---- */ cholmod_triplet *T, /* matrix to copy */ size_t nzmax, /* allocate at least this much space in output matrix */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_triplet_to_sparse (cholmod_triplet *, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_copy_triplet: create a copy of a triplet matrix */ /* -------------------------------------------------------------------------- */ cholmod_triplet *cholmod_copy_triplet ( /* ---- input ---- */ cholmod_triplet *T, /* matrix to copy */ /* --------------- */ cholmod_common *Common ) ; cholmod_triplet *cholmod_l_copy_triplet (cholmod_triplet *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_triplet_xtype: change the xtype of a triplet matrix */ /* -------------------------------------------------------------------------- */ int cholmod_triplet_xtype ( /* ---- input ---- */ int to_xtype, /* requested xtype (pattern, real, complex,or zomplex)*/ /* ---- in/out --- */ cholmod_triplet *T, /* triplet matrix to change */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_triplet_xtype (int, cholmod_triplet *, cholmod_common *) ; /* ========================================================================== */ /* === Core/cholmod_memory ================================================== */ /* ========================================================================== */ /* The user may make use of these, just like malloc and free. You can even * malloc an object and safely free it with cholmod_free, and visa versa * (except that the memory usage statistics will be corrupted). These routines * do differ from malloc and free. If cholmod_free is given a NULL pointer, * for example, it does nothing (unlike the ANSI free). cholmod_realloc does * not return NULL if given a non-NULL pointer and a nonzero size, even if it * fails (it returns the original pointer and sets an error code in * Common->status instead). * * CHOLMOD keeps track of the amount of memory it has allocated, and so the * cholmod_free routine also takes the size of the object being freed. This * is only used for statistics. If you, the user of CHOLMOD, pass the wrong * size, the only consequence is that the memory usage statistics will be * corrupted. */ void *cholmod_malloc /* returns pointer to the newly malloc'd block */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* --------------- */ cholmod_common *Common ) ; void *cholmod_l_malloc (size_t, size_t, cholmod_common *) ; void *cholmod_calloc /* returns pointer to the newly calloc'd block */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* --------------- */ cholmod_common *Common ) ; void *cholmod_l_calloc (size_t, size_t, cholmod_common *) ; void *cholmod_free /* always returns NULL */ ( /* ---- input ---- */ size_t n, /* number of items */ size_t size, /* size of each item */ /* ---- in/out --- */ void *p, /* block of memory to free */ /* --------------- */ cholmod_common *Common ) ; void *cholmod_l_free (size_t, size_t, void *, cholmod_common *) ; void *cholmod_realloc /* returns pointer to reallocated block */ ( /* ---- input ---- */ size_t nnew, /* requested # of items in reallocated block */ size_t size, /* size of each item */ /* ---- in/out --- */ void *p, /* block of memory to realloc */ size_t *n, /* current size on input, nnew on output if successful*/ /* --------------- */ cholmod_common *Common ) ; void *cholmod_l_realloc (size_t, size_t, void *, size_t *, cholmod_common *) ; int cholmod_realloc_multiple ( /* ---- input ---- */ size_t nnew, /* requested # of items in reallocated blocks */ int nint, /* number of int/SuiteSparse_long blocks */ int xtype, /* CHOLMOD_PATTERN, _REAL, _COMPLEX, or _ZOMPLEX */ /* ---- in/out --- */ void **Iblock, /* int or SuiteSparse_long block */ void **Jblock, /* int or SuiteSparse_long block */ void **Xblock, /* complex, double, or float block */ void **Zblock, /* zomplex case only: double or float block */ size_t *n, /* current size of the I,J,X,Z blocks on input, * nnew on output if successful */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_realloc_multiple (size_t, int, int, void **, void **, void **, void **, size_t *, cholmod_common *) ; /* ========================================================================== */ /* === version control ====================================================== */ /* ========================================================================== */ int cholmod_version /* returns CHOLMOD_VERSION */ ( /* output, contents not defined on input. Not used if NULL. version [0] = CHOLMOD_MAIN_VERSION version [1] = CHOLMOD_SUB_VERSION version [2] = CHOLMOD_SUBSUB_VERSION */ int version [3] ) ; int cholmod_l_version (int version [3]) ; /* Versions prior to 2.1.1 do not have the above function. The following code fragment will work with any version of CHOLMOD: #ifdef CHOLMOD_HAS_VERSION_FUNCTION v = cholmod_version (NULL) ; #else v = CHOLMOD_VERSION ; #endif */ /* ========================================================================== */ /* === symmetry types ======================================================= */ /* ========================================================================== */ #define CHOLMOD_MM_RECTANGULAR 1 #define CHOLMOD_MM_UNSYMMETRIC 2 #define CHOLMOD_MM_SYMMETRIC 3 #define CHOLMOD_MM_HERMITIAN 4 #define CHOLMOD_MM_SKEW_SYMMETRIC 5 #define CHOLMOD_MM_SYMMETRIC_POSDIAG 6 #define CHOLMOD_MM_HERMITIAN_POSDIAG 7 /* ========================================================================== */ /* === Numerical relop macros =============================================== */ /* ========================================================================== */ /* These macros correctly handle the NaN case. * * CHOLMOD_IS_NAN(x): * True if x is NaN. False otherwise. The commonly-existing isnan(x) * function could be used, but it's not in Kernighan & Ritchie 2nd edition * (ANSI C89). It may appear in , but I'm not certain about * portability. The expression x != x is true if and only if x is NaN, * according to the IEEE 754 floating-point standard. * * CHOLMOD_IS_ZERO(x): * True if x is zero. False if x is nonzero, NaN, or +/- Inf. * This is (x == 0) if the compiler is IEEE 754 compliant. * * CHOLMOD_IS_NONZERO(x): * True if x is nonzero, NaN, or +/- Inf. False if x zero. * This is (x != 0) if the compiler is IEEE 754 compliant. * * CHOLMOD_IS_LT_ZERO(x): * True if x is < zero or -Inf. False if x is >= 0, NaN, or +Inf. * This is (x < 0) if the compiler is IEEE 754 compliant. * * CHOLMOD_IS_GT_ZERO(x): * True if x is > zero or +Inf. False if x is <= 0, NaN, or -Inf. * This is (x > 0) if the compiler is IEEE 754 compliant. * * CHOLMOD_IS_LE_ZERO(x): * True if x is <= zero or -Inf. False if x is > 0, NaN, or +Inf. * This is (x <= 0) if the compiler is IEEE 754 compliant. */ #ifdef CHOLMOD_WINDOWS /* Yes, this is exceedingly ugly. Blame Microsoft, which hopelessly */ /* violates the IEEE 754 floating-point standard in a bizarre way. */ /* If you're using an IEEE 754-compliant compiler, then x != x is true */ /* iff x is NaN. For Microsoft, (x < x) is true iff x is NaN. */ /* So either way, this macro safely detects a NaN. */ #define CHOLMOD_IS_NAN(x) (((x) != (x)) || (((x) < (x)))) #define CHOLMOD_IS_ZERO(x) (((x) == 0.) && !CHOLMOD_IS_NAN(x)) #define CHOLMOD_IS_NONZERO(x) (((x) != 0.) || CHOLMOD_IS_NAN(x)) #define CHOLMOD_IS_LT_ZERO(x) (((x) < 0.) && !CHOLMOD_IS_NAN(x)) #define CHOLMOD_IS_GT_ZERO(x) (((x) > 0.) && !CHOLMOD_IS_NAN(x)) #define CHOLMOD_IS_LE_ZERO(x) (((x) <= 0.) && !CHOLMOD_IS_NAN(x)) #else /* These all work properly, according to the IEEE 754 standard ... except on */ /* a PC with windows. Works fine in Linux on the same PC... */ #define CHOLMOD_IS_NAN(x) ((x) != (x)) #define CHOLMOD_IS_ZERO(x) ((x) == 0.) #define CHOLMOD_IS_NONZERO(x) ((x) != 0.) #define CHOLMOD_IS_LT_ZERO(x) ((x) < 0.) #define CHOLMOD_IS_GT_ZERO(x) ((x) > 0.) #define CHOLMOD_IS_LE_ZERO(x) ((x) <= 0.) #endif #endif igraph/src/CHOLMOD/Include/cholmod_internal.h0000644000175100001440000003531713431000472020476 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_internal.h =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_internal.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_internal.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD internal include file. * * This file contains internal definitions for CHOLMOD, not meant to be included * in user code. They define macros that are not prefixed with CHOLMOD_. This * file can safely #include'd in user code if you want to make use of the * macros defined here, and don't mind the possible name conflicts with your * code, however. * * Required by all CHOLMOD routines. Not required by any user routine that * uses CHOLMOMD. Unless debugging is enabled, this file does not require any * CHOLMOD module (not even the Core module). * * If debugging is enabled, all CHOLMOD modules require the Check module. * Enabling debugging requires that this file be editted. Debugging cannot be * enabled with a compiler flag. This is because CHOLMOD is exceedingly slow * when debugging is enabled. Debugging is meant for development of CHOLMOD * itself, not by users of CHOLMOD. */ #ifndef CHOLMOD_INTERNAL_H #define CHOLMOD_INTERNAL_H /* ========================================================================== */ /* === large file I/O ======================================================= */ /* ========================================================================== */ /* Definitions for large file I/O must come before any other #includes. If * this causes problems (may not be portable to all platforms), then compile * CHOLMOD with -DNLARGEFILE. You must do this for MATLAB 6.5 and earlier, * for example. */ #include "cholmod_io64.h" /* ========================================================================== */ /* === debugging and basic includes ========================================= */ /* ========================================================================== */ /* turn off debugging */ #ifndef NDEBUG #define NDEBUG #endif /* Uncomment this line to enable debugging. CHOLMOD will be very slow. #undef NDEBUG */ #ifdef MATLAB_MEX_FILE #include "mex.h" #endif #if !defined(NPRINT) || !defined(NDEBUG) #include #endif #include #include #include #include #include /* ========================================================================== */ /* === basic definitions ==================================================== */ /* ========================================================================== */ /* Some non-conforming compilers insist on defining TRUE and FALSE. */ #undef TRUE #undef FALSE #define TRUE 1 #define FALSE 0 #define BOOLEAN(x) ((x) ? TRUE : FALSE) /* NULL should already be defined, but ensure it is here. */ #ifndef NULL #define NULL ((void *) 0) #endif /* FLIP is a "negation about -1", and is used to mark an integer i that is * normally non-negative. FLIP (EMPTY) is EMPTY. FLIP of a number > EMPTY * is negative, and FLIP of a number < EMTPY is positive. FLIP (FLIP (i)) = i * for all integers i. UNFLIP (i) is >= EMPTY. */ #define EMPTY (-1) #define FLIP(i) (-(i)-2) #define UNFLIP(i) (((i) < EMPTY) ? FLIP (i) : (i)) /* MAX and MIN are not safe to use for NaN's */ #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #define MAX3(a,b,c) (((a) > (b)) ? (MAX (a,c)) : (MAX (b,c))) #define MAX4(a,b,c,d) (((a) > (b)) ? (MAX3 (a,c,d)) : (MAX3 (b,c,d))) #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define IMPLIES(p,q) (!(p) || (q)) /* find the sign: -1 if x < 0, 1 if x > 0, zero otherwise. * Not safe for NaN's */ #define SIGN(x) (((x) < 0) ? (-1) : (((x) > 0) ? 1 : 0)) /* round up an integer x to a multiple of s */ #define ROUNDUP(x,s) ((s) * (((x) + ((s) - 1)) / (s))) #define ERROR(status,msg) \ CHOLMOD(error) (status, __FILE__, __LINE__, msg, Common) /* Check a pointer and return if null. Set status to invalid, unless the * status is already "out of memory" */ #define RETURN_IF_NULL(A,result) \ { \ if ((A) == NULL) \ { \ if (Common->status != CHOLMOD_OUT_OF_MEMORY) \ { \ ERROR (CHOLMOD_INVALID, "argument missing") ; \ } \ return (result) ; \ } \ } /* Return if Common is NULL or invalid */ #define RETURN_IF_NULL_COMMON(result) \ { \ if (Common == NULL) \ { \ return (result) ; \ } \ if (Common->itype != ITYPE || Common->dtype != DTYPE) \ { \ Common->status = CHOLMOD_INVALID ; \ return (result) ; \ } \ } #define IS_NAN(x) CHOLMOD_IS_NAN(x) #define IS_ZERO(x) CHOLMOD_IS_ZERO(x) #define IS_NONZERO(x) CHOLMOD_IS_NONZERO(x) #define IS_LT_ZERO(x) CHOLMOD_IS_LT_ZERO(x) #define IS_GT_ZERO(x) CHOLMOD_IS_GT_ZERO(x) #define IS_LE_ZERO(x) CHOLMOD_IS_LE_ZERO(x) /* 1e308 is a huge number that doesn't take many characters to print in a * file, in CHOLMOD/Check/cholmod_read and _write. Numbers larger than this * are interpretted as Inf, since sscanf doesn't read in Inf's properly. * This assumes IEEE double precision arithmetic. DBL_MAX would be a little * better, except that it takes too many digits to print in a file. */ #define HUGE_DOUBLE 1e308 /* ========================================================================== */ /* === int/long and double/float definitions ================================ */ /* ========================================================================== */ /* CHOLMOD is designed for 3 types of integer variables: * * (1) all integers are int * (2) most integers are int, some are SuiteSparse_long * (3) all integers are SuiteSparse_long * * and two kinds of floating-point values: * * (1) double * (2) float * * the complex types (ANSI-compatible complex, and MATLAB-compatable zomplex) * are based on the double or float type, and are not selected here. They * are typically selected via template routines. * * This gives 6 different modes in which CHOLMOD can be compiled (only the * first two are currently supported): * * DINT double, int prefix: cholmod_ * DLONG double, SuiteSparse_long prefix: cholmod_l_ * DMIX double, mixed int/SuiteSparse_long prefix: cholmod_m_ * SINT float, int prefix: cholmod_si_ * SLONG float, SuiteSparse_long prefix: cholmod_sl_ * SMIX float, mixed int/log prefix: cholmod_sm_ * * These are selected with compile time flags (-DDLONG, for example). If no * flag is selected, the default is DINT. * * All six versions use the same include files. The user-visible include files * are completely independent of which int/long/double/float version is being * used. The integer / real types in all data structures (sparse, triplet, * dense, common, and triplet) are defined at run-time, not compile-time, so * there is only one "cholmod_sparse" data type. Void pointers are used inside * that data structure to point to arrays of the proper type. Each data * structure has an itype and dtype field which determines the kind of basic * types used. These are defined in Include/cholmod_core.h. * * FUTURE WORK: support all six types (float, and mixed int/long) * * SuiteSparse_long is normally defined as long. However, for WIN64 it is * __int64. It can also be redefined for other platforms, by modifying * SuiteSparse_config.h. */ #include "SuiteSparse_config.h" /* -------------------------------------------------------------------------- */ /* Size_max: the largest value of size_t */ /* -------------------------------------------------------------------------- */ #define Size_max ((size_t) (-1)) /* routines for doing arithmetic on size_t, and checking for overflow */ size_t cholmod_add_size_t (size_t a, size_t b, int *ok) ; size_t cholmod_mult_size_t (size_t a, size_t k, int *ok) ; size_t cholmod_l_add_size_t (size_t a, size_t b, int *ok) ; size_t cholmod_l_mult_size_t (size_t a, size_t k, int *ok) ; /* -------------------------------------------------------------------------- */ /* double (also complex double), SuiteSparse_long */ /* -------------------------------------------------------------------------- */ #ifdef DLONG #define Real double #define Int SuiteSparse_long #define Int_max SuiteSparse_long_max #define CHOLMOD(name) cholmod_l_ ## name #define LONG #define DOUBLE #define ITYPE CHOLMOD_LONG #define DTYPE CHOLMOD_DOUBLE #define ID SuiteSparse_long_id /* -------------------------------------------------------------------------- */ /* double, int/SuiteSparse_long */ /* -------------------------------------------------------------------------- */ #elif defined (DMIX) #error "mixed int/SuiteSparse_long not yet supported" /* -------------------------------------------------------------------------- */ /* single, int */ /* -------------------------------------------------------------------------- */ #elif defined (SINT) #error "single-precision not yet supported" /* -------------------------------------------------------------------------- */ /* single, SuiteSparse_long */ /* -------------------------------------------------------------------------- */ #elif defined (SLONG) #error "single-precision not yet supported" /* -------------------------------------------------------------------------- */ /* single, int/SuiteSparse_long */ /* -------------------------------------------------------------------------- */ #elif defined (SMIX) #error "single-precision not yet supported" /* -------------------------------------------------------------------------- */ /* double (also complex double), int: this is the default */ /* -------------------------------------------------------------------------- */ #else #ifndef DINT #define DINT #endif #define INT #define DOUBLE #define Real double #define Int int #define Int_max INT_MAX #define CHOLMOD(name) cholmod_ ## name #define ITYPE CHOLMOD_INT #define DTYPE CHOLMOD_DOUBLE #define ID "%d" #endif /* ========================================================================== */ /* === real/complex arithmetic ============================================== */ /* ========================================================================== */ #include "cholmod_complexity.h" /* ========================================================================== */ /* === Architecture and BLAS ================================================ */ /* ========================================================================== */ #define BLAS_OK Common->blas_ok #include "cholmod_blas.h" /* ========================================================================== */ /* === debugging definitions ================================================ */ /* ========================================================================== */ #ifndef NDEBUG #include #include "cholmod.h" /* The cholmod_dump routines are in the Check module. No CHOLMOD routine * calls the cholmod_check_* or cholmod_print_* routines in the Check module, * since they use Common workspace that may already be in use. Instead, they * use the cholmod_dump_* routines defined there, which allocate their own * workspace if they need it. */ #ifndef EXTERN #define EXTERN extern #endif /* double, int */ EXTERN int cholmod_dump ; EXTERN int cholmod_dump_malloc ; SuiteSparse_long cholmod_dump_sparse (cholmod_sparse *, const char *, cholmod_common *) ; int cholmod_dump_factor (cholmod_factor *, const char *, cholmod_common *) ; int cholmod_dump_triplet (cholmod_triplet *, const char *, cholmod_common *) ; int cholmod_dump_dense (cholmod_dense *, const char *, cholmod_common *) ; int cholmod_dump_subset (int *, size_t, size_t, const char *, cholmod_common *) ; int cholmod_dump_perm (int *, size_t, size_t, const char *, cholmod_common *) ; int cholmod_dump_parent (int *, size_t, const char *, cholmod_common *) ; void cholmod_dump_init (const char *, cholmod_common *) ; int cholmod_dump_mem (const char *, SuiteSparse_long, cholmod_common *) ; void cholmod_dump_real (const char *, Real *, SuiteSparse_long, SuiteSparse_long, int, int, cholmod_common *) ; void cholmod_dump_super (SuiteSparse_long, int *, int *, int *, int *, double *, int, cholmod_common *) ; int cholmod_dump_partition (SuiteSparse_long, int *, int *, int *, int *, SuiteSparse_long, cholmod_common *) ; int cholmod_dump_work(int, int, SuiteSparse_long, cholmod_common *) ; /* double, SuiteSparse_long */ EXTERN int cholmod_l_dump ; EXTERN int cholmod_l_dump_malloc ; SuiteSparse_long cholmod_l_dump_sparse (cholmod_sparse *, const char *, cholmod_common *) ; int cholmod_l_dump_factor (cholmod_factor *, const char *, cholmod_common *) ; int cholmod_l_dump_triplet (cholmod_triplet *, const char *, cholmod_common *); int cholmod_l_dump_dense (cholmod_dense *, const char *, cholmod_common *) ; int cholmod_l_dump_subset (SuiteSparse_long *, size_t, size_t, const char *, cholmod_common *) ; int cholmod_l_dump_perm (SuiteSparse_long *, size_t, size_t, const char *, cholmod_common *) ; int cholmod_l_dump_parent (SuiteSparse_long *, size_t, const char *, cholmod_common *) ; void cholmod_l_dump_init (const char *, cholmod_common *) ; int cholmod_l_dump_mem (const char *, SuiteSparse_long, cholmod_common *) ; void cholmod_l_dump_real (const char *, Real *, SuiteSparse_long, SuiteSparse_long, int, int, cholmod_common *) ; void cholmod_l_dump_super (SuiteSparse_long, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, double *, int, cholmod_common *) ; int cholmod_l_dump_partition (SuiteSparse_long, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long, cholmod_common *) ; int cholmod_l_dump_work(int, int, SuiteSparse_long, cholmod_common *) ; #define DEBUG_INIT(s,Common) { CHOLMOD(dump_init)(s, Common) ; } #define ASSERT(expression) (assert (expression)) #define PRK(k,params) \ { \ if (CHOLMOD(dump) >= (k) && Common->print_function != NULL) \ { \ (Common->print_function) params ; \ } \ } #define PRINT0(params) PRK (0, params) #define PRINT1(params) PRK (1, params) #define PRINT2(params) PRK (2, params) #define PRINT3(params) PRK (3, params) #define PRINTM(params) \ { \ if (CHOLMOD(dump_malloc) > 0) \ { \ printf params ; \ } \ } #define DEBUG(statement) statement #else /* Debugging disabled (the normal case) */ #define PRK(k,params) #define DEBUG_INIT(s,Common) #define PRINT0(params) #define PRINT1(params) #define PRINT2(params) #define PRINT3(params) #define PRINTM(params) #define ASSERT(expression) #define DEBUG(statement) #endif #endif igraph/src/CHOLMOD/Include/cholmod_camd.h0000644000175100001440000000717713431000472017571 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_camd.h =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_camd.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_partition.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD Partition module, interface to CAMD, CCOLAMD, and CSYMAMD * * An interface to CCOLAMD and CSYMAMD, constrained minimum degree ordering * methods which order a matrix following constraints determined via nested * dissection. * * These functions do not require METIS. They are installed unless NCAMD * is defined: * cholmod_ccolamd interface to CCOLAMD ordering * cholmod_csymamd interface to CSYMAMD ordering * cholmod_camd interface to CAMD ordering * * Requires the Core and Cholesky modules, and two packages: CAMD, * and CCOLAMD. Used by functions in the Partition Module. */ #ifndef CHOLMOD_CAMD_H #define CHOLMOD_CAMD_H #include "cholmod_core.h" /* -------------------------------------------------------------------------- */ /* cholmod_ccolamd */ /* -------------------------------------------------------------------------- */ /* Order AA' or A(:,f)*A(:,f)' using CCOLAMD. */ int cholmod_ccolamd ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int *Cmember, /* size A->nrow. Cmember [i] = c if row i is in the * constraint set c. c must be >= 0. The # of * constraint sets is max (Cmember) + 1. If Cmember is * NULL, then it is interpretted as Cmember [i] = 0 for * all i */ /* ---- output --- */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_ccolamd (cholmod_sparse *, SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_csymamd */ /* -------------------------------------------------------------------------- */ /* Order A using CSYMAMD. */ int cholmod_csymamd ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ /* ---- output --- */ int *Cmember, /* size nrow. see cholmod_ccolamd above */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_csymamd (cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_camd */ /* -------------------------------------------------------------------------- */ /* Order A using CAMD. */ int cholmod_camd ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ int *Cmember, /* size nrow. see cholmod_ccolamd above */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_camd (cholmod_sparse *, SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/README.txt0000644000175100001440000000240513430770173016505 0ustar hornikusersCHOLMOD: a sparse Cholesky factorization package. http://www.suitesparse.com The Include/*.h files in this directory provide a basic documentation of all user-callable routines and user-visible data structures in the CHOLMOD package. Start with cholmod.h, which describes the general structure of the parameter lists of CHOLMOD routines. cholmod_core.h describes the data structures and basic operations on them (creating and deleting them). cholmod.h single include file for all user programs cholmod_config.h CHOLMOD compile-time configuration cholmod_core.h Core module: data structures and basic support routines cholmod_check.h Check module: check/print CHOLMOD data structures cholmod_cholesky.h Cholesky module: LL' and LDL' factorization cholmod_matrixops.h MatrixOps module: sparse matrix operators (add, mult,..) cholmod_modify.h Modify module: update/downdate/... cholmod_partition.h Partition module: nested dissection ordering cholmod_supernodal.h Supernodal module: supernodal Cholesky These include files are not used in user programs, but in CHOLMOD only: cholmod_blas.h BLAS definitions cholmod_complexity.h complex arithmetic cholmod_template.h complex arithmetic for template routines cholmod_internal.h internal definitions, not visible to user program igraph/src/CHOLMOD/Include/cholmod.h0000644000175100001440000000746313431000472016603 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod.h ==================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * * Portions of CHOLMOD (the Core and Partition Modules) are copyrighted by the * University of Florida. The Modify Module is co-authored by William W. * Hager, Univ. of Florida. * * Acknowledgements: this work was supported in part by the National Science * Foundation (NFS CCR-0203270 and DMS-9803599), and a grant from Sandia * National Laboratories (Dept. of Energy) which supported the development of * CHOLMOD's Partition Module. * -------------------------------------------------------------------------- */ /* CHOLMOD include file, for inclusion user programs. * * The include files listed below include a short description of each user- * callable routine. Each routine in CHOLMOD has a consistent interface. * More details about the CHOLMOD data types is in the cholmod_core.h file. * * Naming convention: * ------------------ * * All routine names, data types, and CHOLMOD library files use the * cholmod_ prefix. All macros and other #define's use the CHOLMOD * prefix. * * Return value: * ------------- * * Most CHOLMOD routines return an int (TRUE (1) if successful, or FALSE * (0) otherwise. A SuiteSparse_long or double return value is >= 0 if * successful, or -1 otherwise. A size_t return value is > 0 if * successful, or 0 otherwise. * * If a routine returns a pointer, it is a pointer to a newly allocated * object or NULL if a failure occured, with one exception. cholmod_free * always returns NULL. * * "Common" parameter: * ------------------ * * The last parameter in all CHOLMOD routines is a pointer to the CHOLMOD * "Common" object. This contains control parameters, statistics, and * workspace used between calls to CHOLMOD. It is always an input/output * parameter. * * Input, Output, and Input/Output parameters: * ------------------------------------------- * * Input parameters are listed first. They are not modified by CHOLMOD. * * Input/output are listed next. They must be defined on input, and * are modified on output. * * Output parameters are listed next. If they are pointers, they must * point to allocated space on input, but their contents are not defined * on input. * * Workspace parameters appear next. They are used in only two routines * in the Supernodal module. * * The cholmod_common *Common parameter always appears as the last * parameter. It is always an input/output parameter. */ #ifndef CHOLMOD_H #define CHOLMOD_H /* make it easy for C++ programs to include CHOLMOD */ #ifdef __cplusplus extern "C" { #endif /* assume large file support. If problems occur, compile with -DNLARGEFILE */ #include "cholmod_io64.h" #include "SuiteSparse_config.h" #include "cholmod_config.h" /* CHOLMOD always includes the Core module. */ #include "cholmod_core.h" #ifndef NCHECK #include "cholmod_check.h" #endif #ifndef NCHOLESKY #include "cholmod_cholesky.h" #endif #ifndef NMATRIXOPS #include "cholmod_matrixops.h" #endif #ifndef NMODIFY #include "cholmod_modify.h" #endif #ifndef NCAMD #include "cholmod_camd.h" #endif #ifndef NPARTITION #include "cholmod_partition.h" #endif #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif #ifdef __cplusplus } #endif #endif igraph/src/CHOLMOD/Include/cholmod_io64.h0000644000175100001440000000320213431000472017427 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_io64 ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_io64.h. * Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_io64.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Definitions required for large file I/O, which must come before any other * #includes. These are not used if -DNLARGEFILE is defined at compile time. * Large file support may not be portable across all platforms and compilers; * if you encounter an error here, compile your code with -DNLARGEFILE. In * particular, you must use -DNLARGEFILE for MATLAB 6.5 or earlier (which does * not have the io64.h include file). */ #ifndef CHOLMOD_IO_H #define CHOLMOD_IO_H /* skip all of this if NLARGEFILE is defined at the compiler command line */ #ifndef NLARGEFILE #if defined(MATLAB_MEX_FILE) || defined(MATHWORKS) /* CHOLMOD is being compiled as a MATLAB mexFunction, or for use in MATLAB */ #include "io64.h" #else /* CHOLMOD is being compiled in a stand-alone library */ #undef _LARGEFILE64_SOURCE #define _LARGEFILE64_SOURCE #undef _FILE_OFFSET_BITS #define _FILE_OFFSET_BITS 64 #endif #endif #endif igraph/src/CHOLMOD/Include/cholmod_template.h0000644000175100001440000002200113431000472020457 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_template.h =========================================== */ /* ========================================================================== */ /* -------------------------------------------------------------------------- */ /* undefine current xtype macros, and then define macros for current type */ /* -------------------------------------------------------------------------- */ #undef TEMPLATE #undef XTYPE #undef XTYPE2 #undef XTYPE_OK #undef ENTRY_IS_NONZERO #undef ENTRY_IS_ZERO #undef ENTRY_IS_ONE #undef IMAG_IS_NONZERO #undef ASSEMBLE #undef ASSIGN #undef ASSIGN_CONJ #undef ASSIGN2 #undef ASSIGN2_CONJ #undef ASSIGN_REAL #undef MULT #undef MULTADD #undef ADD #undef ADD_REAL #undef MULTSUB #undef MULTADDCONJ #undef MULTSUBCONJ #undef LLDOT #undef CLEAR #undef DIV #undef DIV_REAL #undef MULT_REAL #undef CLEAR_IMAG #undef LDLDOT #undef PREFIX #undef ENTRY_SIZE #undef XPRINT0 #undef XPRINT1 #undef XPRINT2 #undef XPRINT3 /* -------------------------------------------------------------------------- */ /* pattern */ /* -------------------------------------------------------------------------- */ #ifdef PATTERN #define PREFIX p_ #define TEMPLATE(name) P_TEMPLATE(name) #define XTYPE CHOLMOD_PATTERN #define XTYPE2 CHOLMOD_REAL #define XTYPE_OK(type) (TRUE) #define ENTRY_IS_NONZERO(ax,az,q) (TRUE) #define ENTRY_IS_ZERO(ax,az,q) (FALSE) #define ENTRY_IS_ONE(ax,az,q) (TRUE) #define IMAG_IS_NONZERO(ax,az,q) (FALSE) #define ENTRY_SIZE 0 #define ASSEMBLE(x,z,p,ax,az,q) #define ASSIGN(x,z,p,ax,az,q) #define ASSIGN_CONJ(x,z,p,ax,az,q) #define ASSIGN2(x,z,p,ax,az,q) P_ASSIGN2(x,z,p,ax,az,q) #define ASSIGN2_CONJ(x,z,p,ax,az,q) P_ASSIGN2(x,z,p,ax,az,q) #define ASSIGN_REAL(x,p,ax,q) #define MULT(x,z,p,ax,az,q,bx,bz,pb) #define MULTADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD_REAL(x,p, ax,q, bx,r) #define MULTSUB(x,z,p,ax,az,q,bx,bz,pb) #define MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) #define MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) #define LLDOT(x,p,ax,az,q) #define CLEAR(x,z,p) #define CLEAR_IMAG(x,z,p) #define DIV(x,z,p,ax,az,q) #define DIV_REAL(x,z,p, ax,az,q, bx,r) #define MULT_REAL(x,z,p, ax,az,q, bx,r) #define LDLDOT(x,p, ax,az,q, bx,r) #define XPRINT0(x,z,p) P_PRINT(0,x,z,p) #define XPRINT1(x,z,p) P_PRINT(1,x,z,p) #define XPRINT2(x,z,p) P_PRINT(2,x,z,p) #define XPRINT3(x,z,p) P_PRINT(3,x,z,p) /* -------------------------------------------------------------------------- */ /* real */ /* -------------------------------------------------------------------------- */ #elif defined (REAL) #define PREFIX r_ #define TEMPLATE(name) R_TEMPLATE(name) #define XTYPE CHOLMOD_REAL #define XTYPE2 CHOLMOD_REAL #define XTYPE_OK(type) R_XTYPE_OK(type) #define ENTRY_IS_NONZERO(ax,az,q) R_IS_NONZERO(ax,az,q) #define ENTRY_IS_ZERO(ax,az,q) R_IS_ZERO(ax,az,q) #define ENTRY_IS_ONE(ax,az,q) R_IS_ONE(ax,az,q) #define IMAG_IS_NONZERO(ax,az,q) (FALSE) #define ENTRY_SIZE 1 #define ASSEMBLE(x,z,p,ax,az,q) R_ASSEMBLE(x,z,p,ax,az,q) #define ASSIGN(x,z,p,ax,az,q) R_ASSIGN(x,z,p,ax,az,q) #define ASSIGN_CONJ(x,z,p,ax,az,q) R_ASSIGN(x,z,p,ax,az,q) #define ASSIGN2(x,z,p,ax,az,q) R_ASSIGN(x,z,p,ax,az,q) #define ASSIGN2_CONJ(x,z,p,ax,az,q) R_ASSIGN(x,z,p,ax,az,q) #define ASSIGN_REAL(x,p,ax,q) R_ASSIGN_REAL(x,p,ax,q) #define MULT(x,z,p,ax,az,q,bx,bz,pb) R_MULT(x,z,p,ax,az,q,bx,bz,pb) #define MULTADD(x,z,p,ax,az,q,bx,bz,pb) R_MULTADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD(x,z,p,ax,az,q,bx,bz,pb) R_ADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD_REAL(x,p, ax,q, bx,r) R_ADD_REAL(x,p, ax,q, bx,r) #define MULTSUB(x,z,p,ax,az,q,bx,bz,pb) R_MULTSUB(x,z,p,ax,az,q,bx,bz,pb) #define MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) \ R_MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) #define MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) \ R_MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) #define LLDOT(x,p,ax,az,q) R_LLDOT(x,p,ax,az,q) #define CLEAR(x,z,p) R_CLEAR(x,z,p) #define CLEAR_IMAG(x,z,p) R_CLEAR_IMAG(x,z,p) #define DIV(x,z,p,ax,az,q) R_DIV(x,z,p,ax,az,q) #define DIV_REAL(x,z,p, ax,az,q, bx,r) R_DIV_REAL(x,z,p, ax,az,q, bx,r) #define MULT_REAL(x,z,p, ax,az,q, bx,r) R_MULT_REAL(x,z,p, ax,az,q, bx,r) #define LDLDOT(x,p, ax,az,q, bx,r) R_LDLDOT(x,p, ax,az,q, bx,r) #define XPRINT0(x,z,p) R_PRINT(0,x,z,p) #define XPRINT1(x,z,p) R_PRINT(1,x,z,p) #define XPRINT2(x,z,p) R_PRINT(2,x,z,p) #define XPRINT3(x,z,p) R_PRINT(3,x,z,p) /* -------------------------------------------------------------------------- */ /* complex */ /* -------------------------------------------------------------------------- */ #elif defined (COMPLEX) #define PREFIX c_ #ifdef NCONJUGATE #define TEMPLATE(name) CT_TEMPLATE(name) #else #define TEMPLATE(name) C_TEMPLATE(name) #endif #define ASSEMBLE(x,z,p,ax,az,q) C_ASSEMBLE(x,z,p,ax,az,q) #define ASSIGN(x,z,p,ax,az,q) C_ASSIGN(x,z,p,ax,az,q) #define ASSIGN_CONJ(x,z,p,ax,az,q) C_ASSIGN_CONJ(x,z,p,ax,az,q) #define ASSIGN2(x,z,p,ax,az,q) C_ASSIGN(x,z,p,ax,az,q) #define ASSIGN2_CONJ(x,z,p,ax,az,q) C_ASSIGN_CONJ(x,z,p,ax,az,q) #define ASSIGN_REAL(x,p,ax,q) C_ASSIGN_REAL(x,p,ax,q) #define XTYPE CHOLMOD_COMPLEX #define XTYPE2 CHOLMOD_COMPLEX #define XTYPE_OK(type) C_XTYPE_OK(type) #define ENTRY_IS_NONZERO(ax,az,q) C_IS_NONZERO(ax,az,q) #define ENTRY_IS_ZERO(ax,az,q) C_IS_ZERO(ax,az,q) #define ENTRY_IS_ONE(ax,az,q) C_IS_ONE(ax,az,q) #define IMAG_IS_NONZERO(ax,az,q) C_IMAG_IS_NONZERO(ax,az,q) #define ENTRY_SIZE 2 #define MULTADD(x,z,p,ax,az,q,bx,bz,pb) C_MULTADD(x,z,p,ax,az,q,bx,bz,pb) #define MULT(x,z,p,ax,az,q,bx,bz,pb) C_MULT(x,z,p,ax,az,q,bx,bz,pb) #define ADD(x,z,p,ax,az,q,bx,bz,pb) C_ADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD_REAL(x,p, ax,q, bx,r) C_ADD_REAL(x,p, ax,q, bx,r) #define MULTSUB(x,z,p,ax,az,q,bx,bz,pb) C_MULTSUB(x,z,p,ax,az,q,bx,bz,pb) #define MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) \ C_MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) #define MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) \ C_MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) #define LLDOT(x,p,ax,az,q) C_LLDOT(x,p,ax,az,q) #define CLEAR(x,z,p) C_CLEAR(x,z,p) #define CLEAR_IMAG(x,z,p) C_CLEAR_IMAG(x,z,p) #define DIV(x,z,p,ax,az,q) C_DIV(x,z,p,ax,az,q) #define DIV_REAL(x,z,p, ax,az,q, bx,r) C_DIV_REAL(x,z,p, ax,az,q, bx,r) #define MULT_REAL(x,z,p, ax,az,q, bx,r) C_MULT_REAL(x,z,p, ax,az,q, bx,r) #define LDLDOT(x,p, ax,az,q, bx,r) C_LDLDOT(x,p, ax,az,q, bx,r) #define XPRINT0(x,z,p) C_PRINT(0,x,z,p) #define XPRINT1(x,z,p) C_PRINT(1,x,z,p) #define XPRINT2(x,z,p) C_PRINT(2,x,z,p) #define XPRINT3(x,z,p) C_PRINT(3,x,z,p) /* -------------------------------------------------------------------------- */ /* zomplex */ /* -------------------------------------------------------------------------- */ #elif defined (ZOMPLEX) #define PREFIX z_ #ifdef NCONJUGATE #define TEMPLATE(name) ZT_TEMPLATE(name) #else #define TEMPLATE(name) Z_TEMPLATE(name) #endif #define ASSEMBLE(x,z,p,ax,az,q) Z_ASSEMBLE(x,z,p,ax,az,q) #define ASSIGN(x,z,p,ax,az,q) Z_ASSIGN(x,z,p,ax,az,q) #define ASSIGN_CONJ(x,z,p,ax,az,q) Z_ASSIGN_CONJ(x,z,p,ax,az,q) #define ASSIGN2(x,z,p,ax,az,q) Z_ASSIGN(x,z,p,ax,az,q) #define ASSIGN2_CONJ(x,z,p,ax,az,q) Z_ASSIGN_CONJ(x,z,p,ax,az,q) #define ASSIGN_REAL(x,p,ax,q) Z_ASSIGN_REAL(x,p,ax,q) #define XTYPE CHOLMOD_ZOMPLEX #define XTYPE2 CHOLMOD_ZOMPLEX #define XTYPE_OK(type) Z_XTYPE_OK(type) #define ENTRY_IS_NONZERO(ax,az,q) Z_IS_NONZERO(ax,az,q) #define ENTRY_IS_ZERO(ax,az,q) Z_IS_ZERO(ax,az,q) #define ENTRY_IS_ONE(ax,az,q) Z_IS_ONE(ax,az,q) #define IMAG_IS_NONZERO(ax,az,q) Z_IMAG_IS_NONZERO(ax,az,q) #define ENTRY_SIZE 1 #define MULTADD(x,z,p,ax,az,q,bx,bz,pb) Z_MULTADD(x,z,p,ax,az,q,bx,bz,pb) #define MULT(x,z,p,ax,az,q,bx,bz,pb) Z_MULT(x,z,p,ax,az,q,bx,bz,pb) #define ADD(x,z,p,ax,az,q,bx,bz,pb) Z_ADD(x,z,p,ax,az,q,bx,bz,pb) #define ADD_REAL(x,p, ax,q, bx,r) Z_ADD_REAL(x,p, ax,q, bx,r) #define MULTSUB(x,z,p,ax,az,q,bx,bz,pb) Z_MULTSUB(x,z,p,ax,az,q,bx,bz,pb) #define MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) \ Z_MULTADDCONJ(x,z,p,ax,az,q,bx,bz,pb) #define MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) \ Z_MULTSUBCONJ(x,z,p,ax,az,q,bx,bz,pb) #define LLDOT(x,p,ax,az,q) Z_LLDOT(x,p,ax,az,q) #define CLEAR(x,z,p) Z_CLEAR(x,z,p) #define CLEAR_IMAG(x,z,p) Z_CLEAR_IMAG(x,z,p) #define DIV(x,z,p,ax,az,q) Z_DIV(x,z,p,ax,az,q) #define DIV_REAL(x,z,p, ax,az,q, bx,r) Z_DIV_REAL(x,z,p, ax,az,q, bx,r) #define MULT_REAL(x,z,p, ax,az,q, bx,r) Z_MULT_REAL(x,z,p, ax,az,q, bx,r) #define LDLDOT(x,p, ax,az,q, bx,r) Z_LDLDOT(x,p, ax,az,q, bx,r) #define XPRINT0(x,z,p) Z_PRINT(0,x,z,p) #define XPRINT1(x,z,p) Z_PRINT(1,x,z,p) #define XPRINT2(x,z,p) Z_PRINT(2,x,z,p) #define XPRINT3(x,z,p) Z_PRINT(3,x,z,p) #endif igraph/src/CHOLMOD/Include/cholmod_supernodal.h0000644000175100001440000001445013431000472021031 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_supernodal.h ========================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_supernodal.h. * Copyright (C) 2005-2006, Timothy A. Davis * CHOLMOD/Include/cholmod_supernodal.h is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD Supernodal module. * * Supernodal analysis, factorization, and solve. The simplest way to use * these routines is via the Cholesky module. It does not provide any * fill-reducing orderings, but does accept the orderings computed by the * Cholesky module. It does not require the Cholesky module itself, however. * * Primary routines: * ----------------- * cholmod_super_symbolic supernodal symbolic analysis * cholmod_super_numeric supernodal numeric factorization * cholmod_super_lsolve supernodal Lx=b solve * cholmod_super_ltsolve supernodal L'x=b solve * * Prototypes for the BLAS and LAPACK routines that CHOLMOD uses are listed * below, including how they are used in CHOLMOD. * * BLAS routines: * -------------- * dtrsv solve Lx=b or L'x=b, L non-unit diagonal, x and b stride-1 * dtrsm solve LX=B or L'X=b, L non-unit diagonal * dgemv y=y-A*x or y=y-A'*x (x and y stride-1) * dgemm C=A*B', C=C-A*B, or C=C-A'*B * dsyrk C=tril(A*A') * * LAPACK routines: * ---------------- * dpotrf LAPACK: A=chol(tril(A)) * * Requires the Core module, and two external packages: LAPACK and the BLAS. * Optionally used by the Cholesky module. */ #ifndef CHOLMOD_SUPERNODAL_H #define CHOLMOD_SUPERNODAL_H #include "cholmod_core.h" /* -------------------------------------------------------------------------- */ /* cholmod_super_symbolic */ /* -------------------------------------------------------------------------- */ /* Analyzes A, AA', or A(:,f)*A(:,f)' in preparation for a supernodal numeric * factorization. The user need not call this directly; cholmod_analyze is * a "simple" wrapper for this routine. */ int cholmod_super_symbolic ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* F = A' or A(:,f)' */ int *Parent, /* elimination tree */ /* ---- in/out --- */ cholmod_factor *L, /* simplicial symbolic on input, * supernodal symbolic on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_super_symbolic (cholmod_sparse *, cholmod_sparse *, SuiteSparse_long *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_super_symbolic2 */ /* -------------------------------------------------------------------------- */ /* Analyze for supernodal Cholesky or multifrontal QR. CHOLMOD itself always * analyzes for supernodal Cholesky, of course. This "for_cholesky = TRUE" * option is used by SuiteSparseQR only. Added for V1.7 */ int cholmod_super_symbolic2 ( /* ---- input ---- */ int for_cholesky, /* Cholesky if TRUE, QR if FALSE */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* F = A' or A(:,f)' */ int *Parent, /* elimination tree */ /* ---- in/out --- */ cholmod_factor *L, /* simplicial symbolic on input, * supernodal symbolic on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_super_symbolic2 (int, cholmod_sparse *, cholmod_sparse *, SuiteSparse_long *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_super_numeric */ /* -------------------------------------------------------------------------- */ /* Computes the numeric LL' factorization of A, AA', or A(:,f)*A(:,f)' using * a BLAS-based supernodal method. The user need not call this directly; * cholmod_factorize is a "simple" wrapper for this routine. */ int cholmod_super_numeric ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* F = A' or A(:,f)' */ double beta [2], /* beta*I is added to diagonal of matrix to factorize */ /* ---- in/out --- */ cholmod_factor *L, /* factorization */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_super_numeric (cholmod_sparse *, cholmod_sparse *, double *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_super_lsolve */ /* -------------------------------------------------------------------------- */ /* Solve Lx=b where L is from a supernodal numeric factorization. The user * need not call this routine directly. cholmod_solve is a "simple" wrapper * for this routine. */ int cholmod_super_lsolve ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the forward solve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to Lx=b on output */ /* ---- workspace */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_super_lsolve (cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_super_ltsolve */ /* -------------------------------------------------------------------------- */ /* Solve L'x=b where L is from a supernodal numeric factorization. The user * need not call this routine directly. cholmod_solve is a "simple" wrapper * for this routine. */ int cholmod_super_ltsolve ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the backsolve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to L'x=b on output */ /* ---- workspace */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_super_ltsolve (cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/cholmod_cholesky.h0000644000175100001440000005330713431000472020502 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_cholesky.h =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_cholesky.h. Copyright (C) 2005-2013, Timothy A. Davis * CHOLMOD/Include/cholmod_cholesky.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD Cholesky module. * * Sparse Cholesky routines: analysis, factorization, and solve. * * The primary routines are all that a user requires to order, analyze, and * factorize a sparse symmetric positive definite matrix A (or A*A'), and * to solve Ax=b (or A*A'x=b). The primary routines rely on the secondary * routines, the CHOLMOD Core module, and the AMD and COLAMD packages. They * make optional use of the CHOLMOD Supernodal and Partition modules, the * METIS package, and the CCOLAMD package. * * Primary routines: * ----------------- * * cholmod_analyze order and analyze (simplicial or supernodal) * cholmod_factorize simplicial or supernodal Cholesky factorization * cholmod_solve solve a linear system (simplicial or supernodal) * cholmod_solve2 like cholmod_solve, but reuse workspace * cholmod_spsolve solve a linear system (sparse x and b) * * Secondary routines: * ------------------ * * cholmod_analyze_p analyze, with user-provided permutation or f set * cholmod_factorize_p factorize, with user-provided permutation or f * cholmod_analyze_ordering analyze a fill-reducing ordering * cholmod_etree find the elimination tree * cholmod_rowcolcounts compute the row/column counts of L * cholmod_amd order using AMD * cholmod_colamd order using COLAMD * cholmod_rowfac incremental simplicial factorization * cholmod_rowfac_mask rowfac, specific to LPDASA * cholmod_row_subtree find the nonzero pattern of a row of L * cholmod_resymbol recompute the symbolic pattern of L * cholmod_resymbol_noperm recompute the symbolic pattern of L, no L->Perm * cholmod_postorder postorder a tree * * Requires the Core module, and two packages: AMD and COLAMD. * Optionally uses the Supernodal and Partition modules. * Required by the Partition module. */ #ifndef CHOLMOD_CHOLESKY_H #define CHOLMOD_CHOLESKY_H #include "cholmod_config.h" #include "cholmod_core.h" #ifndef NPARTITION #include "cholmod_partition.h" #endif #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif /* -------------------------------------------------------------------------- */ /* cholmod_analyze: order and analyze (simplicial or supernodal) */ /* -------------------------------------------------------------------------- */ /* Orders and analyzes A, AA', PAP', or PAA'P' and returns a symbolic factor * that can later be passed to cholmod_factorize. */ cholmod_factor *cholmod_analyze ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order and analyze */ /* --------------- */ cholmod_common *Common ) ; cholmod_factor *cholmod_l_analyze (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_analyze_p: analyze, with user-provided permutation or f set */ /* -------------------------------------------------------------------------- */ /* Orders and analyzes A, AA', PAP', PAA'P', FF', or PFF'P and returns a * symbolic factor that can later be passed to cholmod_factorize, where * F = A(:,fset) if fset is not NULL and A->stype is zero. * UserPerm is tried if non-NULL. */ cholmod_factor *cholmod_analyze_p ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order and analyze */ int *UserPerm, /* user-provided permutation, size A->nrow */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) ; cholmod_factor *cholmod_l_analyze_p (cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long *, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_analyze_p2: analyze for sparse Cholesky or sparse QR */ /* -------------------------------------------------------------------------- */ cholmod_factor *cholmod_analyze_p2 ( /* ---- input ---- */ int for_cholesky, /* if TRUE, then analyze for Cholesky; else for QR */ cholmod_sparse *A, /* matrix to order and analyze */ int *UserPerm, /* user-provided permutation, size A->nrow */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) ; cholmod_factor *cholmod_l_analyze_p2 (int, cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long *, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_factorize: simplicial or supernodal Cholesky factorization */ /* -------------------------------------------------------------------------- */ /* Factorizes PAP' (or PAA'P' if A->stype is 0), using a factor obtained * from cholmod_analyze. The analysis can be re-used simply by calling this * routine a second time with another matrix. A must have the same nonzero * pattern as that passed to cholmod_analyze. */ int cholmod_factorize ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ /* ---- in/out --- */ cholmod_factor *L, /* resulting factorization */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_factorize (cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_factorize_p: factorize, with user-provided permutation or fset */ /* -------------------------------------------------------------------------- */ /* Same as cholmod_factorize, but with more options. */ int cholmod_factorize_p ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ double beta [2], /* factorize beta*I+A or beta*I+A'*A */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- in/out --- */ cholmod_factor *L, /* resulting factorization */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_factorize_p (cholmod_sparse *, double *, SuiteSparse_long *, size_t, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_solve: solve a linear system (simplicial or supernodal) */ /* -------------------------------------------------------------------------- */ /* Solves one of many linear systems with a dense right-hand-side, using the * factorization from cholmod_factorize (or as modified by any other CHOLMOD * routine). D is identity for LL' factorizations. */ #define CHOLMOD_A 0 /* solve Ax=b */ #define CHOLMOD_LDLt 1 /* solve LDL'x=b */ #define CHOLMOD_LD 2 /* solve LDx=b */ #define CHOLMOD_DLt 3 /* solve DL'x=b */ #define CHOLMOD_L 4 /* solve Lx=b */ #define CHOLMOD_Lt 5 /* solve L'x=b */ #define CHOLMOD_D 6 /* solve Dx=b */ #define CHOLMOD_P 7 /* permute x=Px */ #define CHOLMOD_Pt 8 /* permute x=P'x */ cholmod_dense *cholmod_solve /* returns the solution X */ ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_dense *B, /* right-hand-side */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_solve (int, cholmod_factor *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_solve2: like cholmod_solve, but with reusable workspace */ /* -------------------------------------------------------------------------- */ int cholmod_solve2 /* returns TRUE on success, FALSE on failure */ ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_dense *B, /* right-hand-side */ cholmod_sparse *Bset, /* ---- output --- */ cholmod_dense **X_Handle, /* solution, allocated if need be */ cholmod_sparse **Xset_Handle, /* ---- workspace */ cholmod_dense **Y_Handle, /* workspace, or NULL */ cholmod_dense **E_Handle, /* workspace, or NULL */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_solve2 (int, cholmod_factor *, cholmod_dense *, cholmod_sparse *, cholmod_dense **, cholmod_sparse **, cholmod_dense **, cholmod_dense **, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_spsolve: solve a linear system with a sparse right-hand-side */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_spsolve ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_sparse *B, /* right-hand-side */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_spsolve (int, cholmod_factor *, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_etree: find the elimination tree of A or A'*A */ /* -------------------------------------------------------------------------- */ int cholmod_etree ( /* ---- input ---- */ cholmod_sparse *A, /* ---- output --- */ int *Parent, /* size ncol. Parent [j] = p if p is the parent of j */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_etree (cholmod_sparse *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowcolcounts: compute the row/column counts of L */ /* -------------------------------------------------------------------------- */ int cholmod_rowcolcounts ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int *Parent, /* size nrow. Parent [i] = p if p is the parent of i */ int *Post, /* size nrow. Post [k] = i if i is the kth node in * the postordered etree. */ /* ---- output --- */ int *RowCount, /* size nrow. RowCount [i] = # entries in the ith row of * L, including the diagonal. */ int *ColCount, /* size nrow. ColCount [i] = # entries in the ith * column of L, including the diagonal. */ int *First, /* size nrow. First [i] = k is the least postordering * of any descendant of i. */ int *Level, /* size nrow. Level [i] is the length of the path from * i to the root, with Level [root] = 0. */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowcolcounts (cholmod_sparse *, SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_analyze_ordering: analyze a fill-reducing ordering */ /* -------------------------------------------------------------------------- */ int cholmod_analyze_ordering ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int ordering, /* ordering method used */ int *Perm, /* size n, fill-reducing permutation to analyze */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ int *Parent, /* size n, elimination tree */ int *Post, /* size n, postordering of elimination tree */ int *ColCount, /* size n, nnz in each column of L */ /* ---- workspace */ int *First, /* size nworkspace for cholmod_postorder */ int *Level, /* size n workspace for cholmod_postorder */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_analyze_ordering (cholmod_sparse *, int, SuiteSparse_long *, SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_amd: order using AMD */ /* -------------------------------------------------------------------------- */ /* Finds a permutation P to reduce fill-in in the factorization of P*A*P' * or P*A*A'P' */ int cholmod_amd ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_amd (cholmod_sparse *, SuiteSparse_long *, size_t, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_colamd: order using COLAMD */ /* -------------------------------------------------------------------------- */ /* Finds a permutation P to reduce fill-in in the factorization of P*A*A'*P'. * Orders F*F' where F = A (:,fset) if fset is not NULL */ int cholmod_colamd ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int postorder, /* if TRUE, follow with a coletree postorder */ /* ---- output --- */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_colamd (cholmod_sparse *, SuiteSparse_long *, size_t, int, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowfac: incremental simplicial factorization */ /* -------------------------------------------------------------------------- */ /* Partial or complete simplicial factorization. Rows and columns kstart:kend-1 * of L and D must be initially equal to rows/columns kstart:kend-1 of the * identity matrix. Row k can only be factorized if all descendants of node * k in the elimination tree have been factorized. */ int cholmod_rowfac ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,fset)' */ double beta [2], /* factorize beta*I+A or beta*I+A'*A */ size_t kstart, /* first row to factorize */ size_t kend, /* last row to factorize is kend-1 */ /* ---- in/out --- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowfac (cholmod_sparse *, cholmod_sparse *, double *, size_t, size_t, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowfac_mask: incremental simplicial factorization */ /* -------------------------------------------------------------------------- */ /* cholmod_rowfac_mask is a version of cholmod_rowfac that is specific to * LPDASA. It is unlikely to be needed by any other application. */ int cholmod_rowfac_mask ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,fset)' */ double beta [2], /* factorize beta*I+A or beta*I+A'*A */ size_t kstart, /* first row to factorize */ size_t kend, /* last row to factorize is kend-1 */ int *mask, /* if mask[i] >= 0, then set row i to zero */ int *RLinkUp, /* link list of rows to compute */ /* ---- in/out --- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowfac_mask (cholmod_sparse *, cholmod_sparse *, double *, size_t, size_t, SuiteSparse_long *, SuiteSparse_long *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_row_subtree: find the nonzero pattern of a row of L */ /* -------------------------------------------------------------------------- */ /* Find the nonzero pattern of x for the system Lx=b where L = (0:k-1,0:k-1) * and b = kth column of A or A*A' (rows 0 to k-1 only) */ int cholmod_row_subtree ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,fset)' */ size_t k, /* row k of L */ int *Parent, /* elimination tree */ /* ---- output --- */ cholmod_sparse *R, /* pattern of L(k,:), n-by-1 with R->nzmax >= n */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_row_subtree (cholmod_sparse *, cholmod_sparse *, size_t, SuiteSparse_long *, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_lsolve_pattern: find the nonzero pattern of x=L\b */ /* -------------------------------------------------------------------------- */ int cholmod_lsolve_pattern ( /* ---- input ---- */ cholmod_sparse *B, /* sparse right-hand-side (a single sparse column) */ cholmod_factor *L, /* the factor L from which parent(i) is derived */ /* ---- output --- */ cholmod_sparse *X, /* pattern of X=L\B, n-by-1 with X->nzmax >= n */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_lsolve_pattern (cholmod_sparse *, cholmod_factor *, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_row_lsubtree: find the nonzero pattern of a row of L */ /* -------------------------------------------------------------------------- */ /* Identical to cholmod_row_subtree, except that it finds the elimination tree * from L itself. */ int cholmod_row_lsubtree ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int *Fi, size_t fnz, /* nonzero pattern of kth row of A', not required * for the symmetric case. Need not be sorted. */ size_t k, /* row k of L */ cholmod_factor *L, /* the factor L from which parent(i) is derived */ /* ---- output --- */ cholmod_sparse *R, /* pattern of L(k,:), n-by-1 with R->nzmax >= n */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_row_lsubtree (cholmod_sparse *, SuiteSparse_long *, size_t, size_t, cholmod_factor *, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_resymbol: recompute the symbolic pattern of L */ /* -------------------------------------------------------------------------- */ /* Remove entries from L that are not in the factorization of P*A*P', P*A*A'*P', * or P*F*F'*P' (depending on A->stype and whether fset is NULL or not). * * cholmod_resymbol is the same as cholmod_resymbol_noperm, except that it * first permutes A according to L->Perm. A can be upper/lower/unsymmetric, * in contrast to cholmod_resymbol_noperm (which can be lower or unsym). */ int cholmod_resymbol ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int pack, /* if TRUE, pack the columns of L */ /* ---- in/out --- */ cholmod_factor *L, /* factorization, entries pruned on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_resymbol (cholmod_sparse *, SuiteSparse_long *, size_t, int, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_resymbol_noperm: recompute the symbolic pattern of L, no L->Perm */ /* -------------------------------------------------------------------------- */ /* Remove entries from L that are not in the factorization of A, A*A', * or F*F' (depending on A->stype and whether fset is NULL or not). */ int cholmod_resymbol_noperm ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int pack, /* if TRUE, pack the columns of L */ /* ---- in/out --- */ cholmod_factor *L, /* factorization, entries pruned on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_resymbol_noperm (cholmod_sparse *, SuiteSparse_long *, size_t, int, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rcond: compute rough estimate of reciprocal of condition number */ /* -------------------------------------------------------------------------- */ double cholmod_rcond /* return min(diag(L)) / max(diag(L)) */ ( /* ---- input ---- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) ; double cholmod_l_rcond (cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_postorder: Compute the postorder of a tree */ /* -------------------------------------------------------------------------- */ SuiteSparse_long cholmod_postorder /* return # of nodes postordered */ ( /* ---- input ---- */ int *Parent, /* size n. Parent [j] = p if p is the parent of j */ size_t n, int *Weight_p, /* size n, optional. Weight [j] is weight of node j */ /* ---- output --- */ int *Post, /* size n. Post [k] = j is kth in postordered tree */ /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_postorder (SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/cholmod_modify.h0000644000175100001440000003132113431000472020140 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_modify.h ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_modify.h. * Copyright (C) 2005-2006, Timothy A. Davis and William W. Hager * CHOLMOD/Include/cholmod_modify.h is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD Modify module. * * Sparse Cholesky modification routines: update / downdate / rowadd / rowdel. * Can also modify a corresponding solution to Lx=b when L is modified. This * module is most useful when applied on a Cholesky factorization computed by * the Cholesky module, but it does not actually require the Cholesky module. * The Core module can create an identity Cholesky factorization (LDL' where * L=D=I) that can then by modified by these routines. * * Primary routines: * ----------------- * * cholmod_updown multiple rank update/downdate * cholmod_rowadd add a row to an LDL' factorization * cholmod_rowdel delete a row from an LDL' factorization * * Secondary routines: * ------------------- * * cholmod_updown_solve update/downdate, and modify solution to Lx=b * cholmod_updown_mark update/downdate, and modify solution to partial Lx=b * cholmod_updown_mask update/downdate for LPDASA * cholmod_rowadd_solve add a row, and update solution to Lx=b * cholmod_rowadd_mark add a row, and update solution to partial Lx=b * cholmod_rowdel_solve delete a row, and downdate Lx=b * cholmod_rowdel_mark delete a row, and downdate solution to partial Lx=b * * Requires the Core module. Not required by any other CHOLMOD module. */ #ifndef CHOLMOD_MODIFY_H #define CHOLMOD_MODIFY_H #include "cholmod_core.h" /* -------------------------------------------------------------------------- */ /* cholmod_updown: multiple rank update/downdate */ /* -------------------------------------------------------------------------- */ /* Compute the new LDL' factorization of LDL'+CC' (an update) or LDL'-CC' * (a downdate). The factor object L need not be an LDL' factorization; it * is converted to one if it isn't. */ int cholmod_updown ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown (int, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_solve: update/downdate, and modify solution to Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown, except that it also updates/downdates the * solution to Lx=b+DeltaB. x and b must be n-by-1 dense matrices. b is not * need as input to this routine, but a sparse change to b is (DeltaB). Only * entries in DeltaB corresponding to columns modified in L are accessed; the * rest must be zero. */ int cholmod_updown_solve ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_solve (int, cholmod_sparse *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_mark: update/downdate, and modify solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. See cholmod_updown.c for * a description of colmark. */ int cholmod_updown_mark ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_mark (int, cholmod_sparse *, SuiteSparse_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_updown_mask: update/downdate, for LPDASA */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_updown_mark, except has an additional "mask" * argument. This routine is an "expert" routine. It is meant for use in * LPDASA only. See cholmod_updown.c for a description of mask. */ int cholmod_updown_mask ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ int *colmark, /* int array of size n. See cholmod_updown.c */ int *mask, /* size n */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_updown_mask (int, cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd: add a row to an LDL' factorization (a rank-2 update) */ /* -------------------------------------------------------------------------- */ /* cholmod_rowadd adds a row to the LDL' factorization. It computes the kth * row and kth column of L, and then updates the submatrix L (k+1:n,k+1:n) * accordingly. The kth row and column of L must originally be equal to the * kth row and column of the identity matrix. The kth row/column of L is * computed as the factorization of the kth row/column of the matrix to * factorize, which is provided as a single n-by-1 sparse matrix R. */ int cholmod_rowadd ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd (size_t, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd_solve: add a row, and update solution to Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowadd, and also updates the solution to Lx=b * See cholmod_updown for a description of how Lx=b is updated. There is on * additional parameter: bk specifies the new kth entry of b. */ int cholmod_rowadd_solve ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right-hand-side b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd_solve (size_t, cholmod_sparse *, double *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowadd_mark: add a row, and update solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowadd_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. */ int cholmod_rowadd_mark ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right hand side, b */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowadd_mark (size_t, cholmod_sparse *, double *, SuiteSparse_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel: delete a row from an LDL' factorization (a rank-2 update) */ /* -------------------------------------------------------------------------- */ /* Sets the kth row and column of L to be the kth row and column of the identity * matrix, and updates L(k+1:n,k+1:n) accordingly. To reduce the running time, * the caller can optionally provide the nonzero pattern (or an upper bound) of * kth row of L, as the sparse n-by-1 vector R. Provide R as NULL if you want * CHOLMOD to determine this itself, which is easier for the caller, but takes * a little more time. */ int cholmod_rowdel ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel (size_t, cholmod_sparse *, cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel_solve: delete a row, and downdate Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowdel, but also downdates the solution to Lx=b. * When row/column k of A is "deleted" from the system A*y=b, this can induce * a change to x, in addition to changes arising when L and b are modified. * If this is the case, the kth entry of y is required as input (yk) */ int cholmod_rowdel_solve ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel_solve (size_t, cholmod_sparse *, double *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_rowdel_mark: delete a row, and downdate solution to partial Lx=b */ /* -------------------------------------------------------------------------- */ /* Does the same as cholmod_rowdel_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. */ int cholmod_rowdel_mark ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ int *colmark, /* int array of size n. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_rowdel_mark (size_t, cholmod_sparse *, double *, SuiteSparse_long *, cholmod_factor *, cholmod_dense *, cholmod_dense *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/License.txt0000644000175100001440000000041213430770173017126 0ustar hornikusersCHOLMOD/Include/* files. Copyright (C) 2005-2006, either Univ. of Florida or T. Davis, depending on the file. Refer to each include file in this directory; each file is licensed separately, according to the Module for which it contains definitions and prototypes. igraph/src/CHOLMOD/Include/cholmod_blas.h0000644000175100001440000003334413431000472017601 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_blas.h =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_blas.h. * Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_blas.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* This does not need to be included in the user's program. */ #ifndef CHOLMOD_BLAS_H #define CHOLMOD_BLAS_H /* ========================================================================== */ /* === Architecture ========================================================= */ /* ========================================================================== */ #if defined (__sun) || defined (MSOL2) || defined (ARCH_SOL2) #define CHOLMOD_SOL2 #define CHOLMOD_ARCHITECTURE "Sun Solaris" #elif defined (__sgi) || defined (MSGI) || defined (ARCH_SGI) #define CHOLMOD_SGI #define CHOLMOD_ARCHITECTURE "SGI Irix" #elif defined (__linux) || defined (MGLNX86) || defined (ARCH_GLNX86) #define CHOLMOD_LINUX #define CHOLMOD_ARCHITECTURE "Linux" #elif defined (__APPLE__) #define CHOLMOD_MAC #define CHOLMOD_ARCHITECTURE "Mac" #elif defined (_AIX) || defined (MIBM_RS) || defined (ARCH_IBM_RS) #define CHOLMOD_AIX #define CHOLMOD_ARCHITECTURE "IBM AIX" /* recent reports from IBM AIX seem to indicate that this is not needed: */ /* #define BLAS_NO_UNDERSCORE */ #elif defined (__alpha) || defined (MALPHA) || defined (ARCH_ALPHA) #define CHOLMOD_ALPHA #define CHOLMOD_ARCHITECTURE "Compaq Alpha" #elif defined (_WIN32) || defined (WIN32) || defined (_WIN64) || defined (WIN64) #if defined (__MINGW32__) || defined (__MINGW32__) #define CHOLMOD_MINGW #elif defined (__CYGWIN32__) || defined (__CYGWIN32__) #define CHOLMOD_CYGWIN #else #define CHOLMOD_WINDOWS //#define BLAS_NO_UNDERSCORE #endif #define CHOLMOD_ARCHITECTURE "Microsoft Windows" #elif defined (__hppa) || defined (__hpux) || defined (MHPUX) || defined (ARCH_HPUX) #define CHOLMOD_HP #define CHOLMOD_ARCHITECTURE "HP Unix" #define BLAS_NO_UNDERSCORE #elif defined (__hp700) || defined (MHP700) || defined (ARCH_HP700) #define CHOLMOD_HP #define CHOLMOD_ARCHITECTURE "HP 700 Unix" #define BLAS_NO_UNDERSCORE #else /* If the architecture is unknown, and you call the BLAS, you may need to */ /* define BLAS_BY_VALUE, BLAS_NO_UNDERSCORE, and/or BLAS_CHAR_ARG yourself. */ #define CHOLMOD_ARCHITECTURE "unknown" #endif /* ========================================================================== */ /* === BLAS and LAPACK names ================================================ */ /* ========================================================================== */ /* Prototypes for the various versions of the BLAS. */ /* Determine if the 64-bit Sun Performance BLAS is to be used */ #if defined(CHOLMOD_SOL2) && !defined(NSUNPERF) && defined(BLAS64) #define SUN64 #endif #ifdef SUN64 #define BLAS_DTRSV dtrsv_64_ #define BLAS_DGEMV dgemv_64_ #define BLAS_DTRSM dtrsm_64_ #define BLAS_DGEMM dgemm_64_ #define BLAS_DSYRK dsyrk_64_ #define BLAS_DGER dger_64_ #define BLAS_DSCAL dscal_64_ #define LAPACK_DPOTRF dpotrf_64_ #define BLAS_ZTRSV ztrsv_64_ #define BLAS_ZGEMV zgemv_64_ #define BLAS_ZTRSM ztrsm_64_ #define BLAS_ZGEMM zgemm_64_ #define BLAS_ZHERK zherk_64_ #define BLAS_ZGER zgeru_64_ #define BLAS_ZSCAL zscal_64_ #define LAPACK_ZPOTRF zpotrf_64_ #elif defined (BLAS_NO_UNDERSCORE) #define BLAS_DTRSV igraphdtrsv #define BLAS_DGEMV igraphdgemv #define BLAS_DTRSM igraphdtrsm #define BLAS_DGEMM igraphdgemm #define BLAS_DSYRK igraphdsyrk #define BLAS_DGER igraphdger #define BLAS_DSCAL igraphdscal #define LAPACK_DPOTRF igraphdpotrf #define BLAS_ZTRSV ztrsv #define BLAS_ZGEMV zgemv #define BLAS_ZTRSM ztrsm #define BLAS_ZGEMM zgemm #define BLAS_ZHERK zherk #define BLAS_ZGER zgeru #define BLAS_ZSCAL zscal #define LAPACK_ZPOTRF zpotrf #else #define BLAS_DTRSV igraphdtrsv_ #define BLAS_DGEMV igraphdgemv_ #define BLAS_DTRSM igraphdtrsm_ #define BLAS_DGEMM igraphdgemm_ #define BLAS_DSYRK igraphdsyrk_ #define BLAS_DGER igraphdger_ #define BLAS_DSCAL igraphdscal_ #define LAPACK_DPOTRF igraphdpotrf_ #define BLAS_ZTRSV ztrsv_ #define BLAS_ZGEMV zgemv_ #define BLAS_ZTRSM ztrsm_ #define BLAS_ZGEMM zgemm_ #define BLAS_ZHERK zherk_ #define BLAS_ZGER zgeru_ #define BLAS_ZSCAL zscal_ #define LAPACK_ZPOTRF zpotrf_ #endif /* ========================================================================== */ /* === BLAS and LAPACK integer arguments ==================================== */ /* ========================================================================== */ /* Compile CHOLMOD, UMFPACK, and SPQR with -DBLAS64 if you have a BLAS that * uses 64-bit integers */ #if defined (LONGBLAS) || defined (BLAS64) #define BLAS_INT SuiteSparse_long #else #define BLAS_INT int #endif /* If the BLAS integer is smaller than the basic CHOLMOD integer, then we need * to check for integer overflow when converting from Int to BLAS_INT. If * any integer overflows, the externally-defined BLAS_OK variable is * set to FALSE. BLAS_OK should be set to TRUE before calling any * BLAS_* macro. */ #define CHECK_BLAS_INT (sizeof (BLAS_INT) < sizeof (Int)) #define EQ(K,k) (((BLAS_INT) K) == ((Int) k)) /* ========================================================================== */ /* === BLAS and LAPACK prototypes and macros ================================ */ /* ========================================================================== */ int BLAS_DGEMV (char *trans, BLAS_INT *m, BLAS_INT *n, double *alpha, double *A, BLAS_INT *lda, double *X, BLAS_INT *incx, double *beta, double *Y, BLAS_INT *incy) ; #define BLAS_dgemv(trans,m,n,alpha,A,lda,X,incx,beta,Y,incy) \ { \ BLAS_INT M = m, N = n, LDA = lda, INCX = incx, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (INCX,incx) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DGEMV (trans, &M, &N, alpha, A, &LDA, X, &INCX, beta, Y, &INCY) ; \ } \ } void BLAS_ZGEMV (char *trans, BLAS_INT *m, BLAS_INT *n, double *alpha, double *A, BLAS_INT *lda, double *X, BLAS_INT *incx, double *beta, double *Y, BLAS_INT *incy) ; #define BLAS_zgemv(trans,m,n,alpha,A,lda,X,incx,beta,Y,incy) \ { \ BLAS_INT M = m, N = n, LDA = lda, INCX = incx, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (INCX,incx) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZGEMV (trans, &M, &N, alpha, A, &LDA, X, &INCX, beta, Y, &INCY) ; \ } \ } void BLAS_DTRSV (char *uplo, char *trans, char *diag, BLAS_INT *n, double *A, BLAS_INT *lda, double *X, BLAS_INT *incx) ; #define BLAS_dtrsv(uplo,trans,diag,n,A,lda,X,incx) \ { \ BLAS_INT N = n, LDA = lda, INCX = incx ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (LDA,lda) && EQ (INCX,incx))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DTRSV (uplo, trans, diag, &N, A, &LDA, X, &INCX) ; \ } \ } void BLAS_ZTRSV (char *uplo, char *trans, char *diag, BLAS_INT *n, double *A, BLAS_INT *lda, double *X, BLAS_INT *incx) ; #define BLAS_ztrsv(uplo,trans,diag,n,A,lda,X,incx) \ { \ BLAS_INT N = n, LDA = lda, INCX = incx ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (LDA,lda) && EQ (INCX,incx))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZTRSV (uplo, trans, diag, &N, A, &LDA, X, &INCX) ; \ } \ } void BLAS_DTRSM (char *side, char *uplo, char *transa, char *diag, BLAS_INT *m, BLAS_INT *n, double *alpha, double *A, BLAS_INT *lda, double *B, BLAS_INT *ldb) ; #define BLAS_dtrsm(side,uplo,transa,diag,m,n,alpha,A,lda,B,ldb) \ { \ BLAS_INT M = m, N = n, LDA = lda, LDB = ldb ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (LDB,ldb))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DTRSM (side, uplo, transa, diag, &M, &N, alpha, A, &LDA, B, &LDB);\ } \ } void BLAS_ZTRSM (char *side, char *uplo, char *transa, char *diag, BLAS_INT *m, BLAS_INT *n, double *alpha, double *A, BLAS_INT *lda, double *B, BLAS_INT *ldb) ; #define BLAS_ztrsm(side,uplo,transa,diag,m,n,alpha,A,lda,B,ldb) \ { \ BLAS_INT M = m, N = n, LDA = lda, LDB = ldb ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (LDB,ldb))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZTRSM (side, uplo, transa, diag, &M, &N, alpha, A, &LDA, B, &LDB);\ } \ } int BLAS_DGEMM (char *transa, char *transb, BLAS_INT *m, BLAS_INT *n, BLAS_INT *k, double *alpha, double *A, BLAS_INT *lda, double *B, BLAS_INT *ldb, double *beta, double *C, BLAS_INT *ldc) ; #define BLAS_dgemm(transa,transb,m,n,k,alpha,A,lda,B,ldb,beta,C,ldc) \ { \ BLAS_INT M = m, N = n, K = k, LDA = lda, LDB = ldb, LDC = ldc ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (K,k) && \ EQ (LDA,lda) && EQ (LDB,ldb) && EQ (LDC,ldc))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DGEMM (transa, transb, &M, &N, &K, alpha, A, &LDA, B, &LDB, beta, \ C, &LDC) ; \ } \ } void BLAS_ZGEMM (char *transa, char *transb, BLAS_INT *m, BLAS_INT *n, BLAS_INT *k, double *alpha, double *A, BLAS_INT *lda, double *B, BLAS_INT *ldb, double *beta, double *C, BLAS_INT *ldc) ; #define BLAS_zgemm(transa,transb,m,n,k,alpha,A,lda,B,ldb,beta,C,ldc) \ { \ BLAS_INT M = m, N = n, K = k, LDA = lda, LDB = ldb, LDC = ldc ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (K,k) && \ EQ (LDA,lda) && EQ (LDB,ldb) && EQ (LDC,ldc))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZGEMM (transa, transb, &M, &N, &K, alpha, A, &LDA, B, &LDB, beta, \ C, &LDC) ; \ } \ } void BLAS_DSYRK (char *uplo, char *trans, BLAS_INT *n, BLAS_INT *k, double *alpha, double *A, BLAS_INT *lda, double *beta, double *C, BLAS_INT *ldc) ; #define BLAS_dsyrk(uplo,trans,n,k,alpha,A,lda,beta,C,ldc) \ { \ BLAS_INT N = n, K = k, LDA = lda, LDC = ldc ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (K,k) && EQ (LDA,lda) && \ EQ (LDC,ldc))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DSYRK (uplo, trans, &N, &K, alpha, A, &LDA, beta, C, &LDC) ; \ } \ } \ void BLAS_ZHERK (char *uplo, char *trans, BLAS_INT *n, BLAS_INT *k, double *alpha, double *A, BLAS_INT *lda, double *beta, double *C, BLAS_INT *ldc) ; #define BLAS_zherk(uplo,trans,n,k,alpha,A,lda,beta,C,ldc) \ { \ BLAS_INT N = n, K = k, LDA = lda, LDC = ldc ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (K,k) && EQ (LDA,lda) && \ EQ (LDC,ldc))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZHERK (uplo, trans, &N, &K, alpha, A, &LDA, beta, C, &LDC) ; \ } \ } \ void LAPACK_DPOTRF (char *uplo, BLAS_INT *n, double *A, BLAS_INT *lda, BLAS_INT *info) ; #define LAPACK_dpotrf(uplo,n,A,lda,info) \ { \ BLAS_INT N = n, LDA = lda, INFO = 1 ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (LDA,lda))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ LAPACK_DPOTRF (uplo, &N, A, &LDA, &INFO) ; \ } \ info = INFO ; \ } void LAPACK_ZPOTRF (char *uplo, BLAS_INT *n, double *A, BLAS_INT *lda, BLAS_INT *info) ; #define LAPACK_zpotrf(uplo,n,A,lda,info) \ { \ BLAS_INT N = n, LDA = lda, INFO = 1 ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (LDA,lda))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ LAPACK_ZPOTRF (uplo, &N, A, &LDA, &INFO) ; \ } \ info = INFO ; \ } /* ========================================================================== */ void BLAS_DSCAL (BLAS_INT *n, double *alpha, double *Y, BLAS_INT *incy) ; #define BLAS_dscal(n,alpha,Y,incy) \ { \ BLAS_INT N = n, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DSCAL (&N, alpha, Y, &INCY) ; \ } \ } void BLAS_ZSCAL (BLAS_INT *n, double *alpha, double *Y, BLAS_INT *incy) ; #define BLAS_zscal(n,alpha,Y,incy) \ { \ BLAS_INT N = n, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (N,n) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZSCAL (&N, alpha, Y, &INCY) ; \ } \ } void BLAS_DGER (BLAS_INT *m, BLAS_INT *n, double *alpha, double *X, BLAS_INT *incx, double *Y, BLAS_INT *incy, double *A, BLAS_INT *lda) ; #define BLAS_dger(m,n,alpha,X,incx,Y,incy,A,lda) \ { \ BLAS_INT M = m, N = n, LDA = lda, INCX = incx, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (INCX,incx) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_DGER (&M, &N, alpha, X, &INCX, Y, &INCY, A, &LDA) ; \ } \ } void BLAS_ZGER (BLAS_INT *m, BLAS_INT *n, double *alpha, double *X, BLAS_INT *incx, double *Y, BLAS_INT *incy, double *A, BLAS_INT *lda) ; #define BLAS_zgeru(m,n,alpha,X,incx,Y,incy,A,lda) \ { \ BLAS_INT M = m, N = n, LDA = lda, INCX = incx, INCY = incy ; \ if (CHECK_BLAS_INT && !(EQ (M,m) && EQ (N,n) && EQ (LDA,lda) && \ EQ (INCX,incx) && EQ (INCY,incy))) \ { \ BLAS_OK = FALSE ; \ } \ if (!CHECK_BLAS_INT || BLAS_OK) \ { \ BLAS_ZGER (&M, &N, alpha, X, &INCX, Y, &INCY, A, &LDA) ; \ } \ } #endif igraph/src/CHOLMOD/Include/cholmod_partition.h0000644000175100001440000001512713431000472020670 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_partition.h ========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_partition.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_partition.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD Partition module. * * Graph partitioning and graph-partition-based orderings. Includes an * interface to CCOLAMD and CSYMAMD, constrained minimum degree ordering * methods which order a matrix following constraints determined via nested * dissection. * * These functions require METIS: * cholmod_nested_dissection CHOLMOD nested dissection ordering * cholmod_metis METIS nested dissection ordering (METIS_NodeND) * cholmod_bisect graph partitioner (currently based on METIS) * cholmod_metis_bisector direct interface to METIS_NodeComputeSeparator * * Requires the Core and Cholesky modules, and three packages: METIS, CAMD, * and CCOLAMD. Optionally used by the Cholesky module. * * Note that METIS does not have a version that uses SuiteSparse_long integers. * If you try to use cholmod_nested_dissection, cholmod_metis, cholmod_bisect, * or cholmod_metis_bisector on a matrix that is too large, an error code will * be returned. METIS does have an "idxtype", which could be redefined as * SuiteSparse_long, if you wish to edit METIS or use compile-time flags to * redefine idxtype. */ #ifndef CHOLMOD_PARTITION_H #define CHOLMOD_PARTITION_H #include "cholmod_core.h" #include "cholmod_camd.h" /* -------------------------------------------------------------------------- */ /* cholmod_nested_dissection */ /* -------------------------------------------------------------------------- */ /* Order A, AA', or A(:,f)*A(:,f)' using CHOLMOD's nested dissection method * (METIS's node bisector applied recursively to compute the separator tree * and constraint sets, followed by CCOLAMD using the constraints). Usually * finds better orderings than METIS_NodeND, but takes longer. */ SuiteSparse_long cholmod_nested_dissection /* returns # of components */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ int *Perm, /* size A->nrow, output permutation */ int *CParent, /* size A->nrow. On output, CParent [c] is the parent * of component c, or EMPTY if c is a root, and where * c is in the range 0 to # of components minus 1 */ int *Cmember, /* size A->nrow. Cmember [j] = c if node j of A is * in component c */ /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_nested_dissection (cholmod_sparse *, SuiteSparse_long *, size_t, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_metis */ /* -------------------------------------------------------------------------- */ /* Order A, AA', or A(:,f)*A(:,f)' using METIS_NodeND. */ int cholmod_metis ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int postorder, /* if TRUE, follow with etree or coletree postorder */ /* ---- output --- */ int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_metis (cholmod_sparse *, SuiteSparse_long *, size_t, int, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_bisect */ /* -------------------------------------------------------------------------- */ /* Finds a node bisector of A, A*A', A(:,f)*A(:,f)'. */ SuiteSparse_long cholmod_bisect /* returns # of nodes in separator */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to bisect */ int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int compress, /* if TRUE, compress the graph first */ /* ---- output --- */ int *Partition, /* size A->nrow. Node i is in the left graph if * Partition [i] = 0, the right graph if 1, and in the * separator if 2. */ /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_bisect (cholmod_sparse *, SuiteSparse_long *, size_t, int, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_metis_bisector */ /* -------------------------------------------------------------------------- */ /* Find a set of nodes that bisects the graph of A or AA' (direct interface * to METIS_NodeComputeSeparator). */ SuiteSparse_long cholmod_metis_bisector /* returns separator size */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to bisect */ int *Anw, /* size A->nrow, node weights */ int *Aew, /* size nz, edge weights */ /* ---- output --- */ int *Partition, /* size A->nrow. see cholmod_bisect above. */ /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_metis_bisector (cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_collapse_septree */ /* -------------------------------------------------------------------------- */ /* Collapse nodes in a separator tree. */ SuiteSparse_long cholmod_collapse_septree ( /* ---- input ---- */ size_t n, /* # of nodes in the graph */ size_t ncomponents, /* # of nodes in the separator tree (must be <= n) */ double nd_oksep, /* collapse if #sep >= nd_oksep * #nodes in subtree */ size_t nd_small, /* collapse if #nodes in subtree < nd_small */ /* ---- in/out --- */ int *CParent, /* size ncomponents; from cholmod_nested_dissection */ int *Cmember, /* size n; from cholmod_nested_dissection */ /* --------------- */ cholmod_common *Common ) ; SuiteSparse_long cholmod_l_collapse_septree (size_t, size_t, double, size_t, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/cholmod_matrixops.h0000644000175100001440000002076313431000472020707 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_matrixops.h ========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_matrixops.h. * Copyright (C) 2005-2006, Timothy A. Davis * CHOLMOD/Include/cholmod_matrixops.h is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD MatrixOps module. * * Basic operations on sparse and dense matrices. * * cholmod_drop A = entries in A with abs. value >= tol * cholmod_norm_dense s = norm (X), 1-norm, inf-norm, or 2-norm * cholmod_norm_sparse s = norm (A), 1-norm or inf-norm * cholmod_horzcat C = [A,B] * cholmod_scale A = diag(s)*A, A*diag(s), s*A or diag(s)*A*diag(s) * cholmod_sdmult Y = alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y * cholmod_ssmult C = A*B * cholmod_submatrix C = A (i,j), where i and j are arbitrary vectors * cholmod_vertcat C = [A ; B] * * A, B, C: sparse matrices (cholmod_sparse) * X, Y: dense matrices (cholmod_dense) * s: scalar or vector * * Requires the Core module. Not required by any other CHOLMOD module. */ #ifndef CHOLMOD_MATRIXOPS_H #define CHOLMOD_MATRIXOPS_H #include "cholmod_core.h" /* -------------------------------------------------------------------------- */ /* cholmod_drop: drop entries with small absolute value */ /* -------------------------------------------------------------------------- */ int cholmod_drop ( /* ---- input ---- */ double tol, /* keep entries with absolute value > tol */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to drop entries from */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_drop (double, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_norm_dense: s = norm (X), 1-norm, inf-norm, or 2-norm */ /* -------------------------------------------------------------------------- */ double cholmod_norm_dense ( /* ---- input ---- */ cholmod_dense *X, /* matrix to compute the norm of */ int norm, /* type of norm: 0: inf. norm, 1: 1-norm, 2: 2-norm */ /* --------------- */ cholmod_common *Common ) ; double cholmod_l_norm_dense (cholmod_dense *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_norm_sparse: s = norm (A), 1-norm or inf-norm */ /* -------------------------------------------------------------------------- */ double cholmod_norm_sparse ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to compute the norm of */ int norm, /* type of norm: 0: inf. norm, 1: 1-norm */ /* --------------- */ cholmod_common *Common ) ; double cholmod_l_norm_sparse (cholmod_sparse *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_horzcat: C = [A,B] */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_horzcat ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to concatenate */ cholmod_sparse *B, /* right matrix to concatenate */ int values, /* if TRUE compute the numerical values of C */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_horzcat (cholmod_sparse *, cholmod_sparse *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_scale: A = diag(s)*A, A*diag(s), s*A or diag(s)*A*diag(s) */ /* -------------------------------------------------------------------------- */ /* scaling modes, selected by the scale input parameter: */ #define CHOLMOD_SCALAR 0 /* A = s*A */ #define CHOLMOD_ROW 1 /* A = diag(s)*A */ #define CHOLMOD_COL 2 /* A = A*diag(s) */ #define CHOLMOD_SYM 3 /* A = diag(s)*A*diag(s) */ int cholmod_scale ( /* ---- input ---- */ cholmod_dense *S, /* scale factors (scalar or vector) */ int scale, /* type of scaling to compute */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to scale */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_scale (cholmod_dense *, int, cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_sdmult: Y = alpha*(A*X) + beta*Y or alpha*(A'*X) + beta*Y */ /* -------------------------------------------------------------------------- */ /* Sparse matrix times dense matrix */ int cholmod_sdmult ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to multiply */ int transpose, /* use A if 0, or A' otherwise */ double alpha [2], /* scale factor for A */ double beta [2], /* scale factor for Y */ cholmod_dense *X, /* dense matrix to multiply */ /* ---- in/out --- */ cholmod_dense *Y, /* resulting dense matrix */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_sdmult (cholmod_sparse *, int, double *, double *, cholmod_dense *, cholmod_dense *Y, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_ssmult: C = A*B */ /* -------------------------------------------------------------------------- */ /* Sparse matrix times sparse matrix */ cholmod_sparse *cholmod_ssmult ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to multiply */ cholmod_sparse *B, /* right matrix to multiply */ int stype, /* requested stype of C */ int values, /* TRUE: do numerical values, FALSE: pattern only */ int sorted, /* if TRUE then return C with sorted columns */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_ssmult (cholmod_sparse *, cholmod_sparse *, int, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_submatrix: C = A (r,c), where i and j are arbitrary vectors */ /* -------------------------------------------------------------------------- */ /* rsize < 0 denotes ":" in MATLAB notation, or more precisely 0:(A->nrow)-1. * In this case, r can be NULL. An rsize of zero, or r = NULL and rsize >= 0, * denotes "[ ]" in MATLAB notation (the empty set). * Similar rules hold for csize. */ cholmod_sparse *cholmod_submatrix ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to subreference */ int *rset, /* set of row indices, duplicates OK */ SuiteSparse_long rsize, /* size of r; rsize < 0 denotes ":" */ int *cset, /* set of column indices, duplicates OK */ SuiteSparse_long csize, /* size of c; csize < 0 denotes ":" */ int values, /* if TRUE compute the numerical values of C */ int sorted, /* if TRUE then return C with sorted columns */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_submatrix (cholmod_sparse *, SuiteSparse_long *, SuiteSparse_long, SuiteSparse_long *, SuiteSparse_long, int, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_vertcat: C = [A ; B] */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_vertcat ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to concatenate */ cholmod_sparse *B, /* right matrix to concatenate */ int values, /* if TRUE compute the numerical values of C */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_vertcat (cholmod_sparse *, cholmod_sparse *, int, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_symmetry: determine if a sparse matrix is symmetric */ /* -------------------------------------------------------------------------- */ int cholmod_symmetry ( /* ---- input ---- */ cholmod_sparse *A, int option, /* ---- output ---- */ int *xmatched, int *pmatched, int *nzoffdiag, int *nzdiag, /* --------------- */ cholmod_common *Common ) ; int cholmod_l_symmetry (cholmod_sparse *, int, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/cholmod_check.h0000644000175100001440000003535413431000472017740 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_check.h ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_check.h. Copyright (C) 2005-2006, Timothy A. Davis * CHOLMOD/Include/cholmod_check.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD Check module. * * Routines that check and print the 5 basic data types in CHOLMOD, and 3 kinds * of integer vectors (subset, perm, and parent), and read in matrices from a * file: * * cholmod_check_common check/print the Common object * cholmod_print_common * * cholmod_check_sparse check/print a sparse matrix in column-oriented form * cholmod_print_sparse * * cholmod_check_dense check/print a dense matrix * cholmod_print_dense * * cholmod_check_factor check/print a Cholesky factorization * cholmod_print_factor * * cholmod_check_triplet check/print a sparse matrix in triplet form * cholmod_print_triplet * * cholmod_check_subset check/print a subset (integer vector in given range) * cholmod_print_subset * * cholmod_check_perm check/print a permutation (an integer vector) * cholmod_print_perm * * cholmod_check_parent check/print an elimination tree (an integer vector) * cholmod_print_parent * * cholmod_read_triplet read a matrix in triplet form (any Matrix Market * "coordinate" format, or a generic triplet format). * * cholmod_read_sparse read a matrix in sparse form (same file format as * cholmod_read_triplet). * * cholmod_read_dense read a dense matrix (any Matrix Market "array" * format, or a generic dense format). * * cholmod_write_sparse write a sparse matrix to a Matrix Market file. * * cholmod_write_dense write a dense matrix to a Matrix Market file. * * cholmod_print_common and cholmod_check_common are the only two routines that * you may call after calling cholmod_finish. * * Requires the Core module. Not required by any CHOLMOD module, except when * debugging is enabled (in which case all modules require the Check module). * * See cholmod_read.c for a description of the file formats supported by the * cholmod_read_* routines. */ #ifndef CHOLMOD_CHECK_H #define CHOLMOD_CHECK_H #include "cholmod_core.h" #include /* -------------------------------------------------------------------------- */ /* cholmod_check_common: check the Common object */ /* -------------------------------------------------------------------------- */ int cholmod_check_common ( cholmod_common *Common ) ; int cholmod_l_check_common (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_common: print the Common object */ /* -------------------------------------------------------------------------- */ int cholmod_print_common ( /* ---- input ---- */ const char *name, /* printed name of Common object */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_common (const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_gpu_stats: print the GPU / CPU statistics */ /* -------------------------------------------------------------------------- */ int cholmod_gpu_stats (cholmod_common *) ; int cholmod_l_gpu_stats (cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_sparse: check a sparse matrix */ /* -------------------------------------------------------------------------- */ int cholmod_check_sparse ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to check */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_sparse (cholmod_sparse *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_sparse */ /* -------------------------------------------------------------------------- */ int cholmod_print_sparse ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to print */ const char *name, /* printed name of sparse matrix */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_sparse (cholmod_sparse *, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_dense: check a dense matrix */ /* -------------------------------------------------------------------------- */ int cholmod_check_dense ( /* ---- input ---- */ cholmod_dense *X, /* dense matrix to check */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_dense (cholmod_dense *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_dense: print a dense matrix */ /* -------------------------------------------------------------------------- */ int cholmod_print_dense ( /* ---- input ---- */ cholmod_dense *X, /* dense matrix to print */ const char *name, /* printed name of dense matrix */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_dense (cholmod_dense *, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_factor: check a factor */ /* -------------------------------------------------------------------------- */ int cholmod_check_factor ( /* ---- input ---- */ cholmod_factor *L, /* factor to check */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_factor (cholmod_factor *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_factor: print a factor */ /* -------------------------------------------------------------------------- */ int cholmod_print_factor ( /* ---- input ---- */ cholmod_factor *L, /* factor to print */ const char *name, /* printed name of factor */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_factor (cholmod_factor *, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_triplet: check a sparse matrix in triplet form */ /* -------------------------------------------------------------------------- */ int cholmod_check_triplet ( /* ---- input ---- */ cholmod_triplet *T, /* triplet matrix to check */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_triplet (cholmod_triplet *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_triplet: print a triplet matrix */ /* -------------------------------------------------------------------------- */ int cholmod_print_triplet ( /* ---- input ---- */ cholmod_triplet *T, /* triplet matrix to print */ const char *name, /* printed name of triplet matrix */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_triplet (cholmod_triplet *, const char *, cholmod_common *); /* -------------------------------------------------------------------------- */ /* cholmod_check_subset: check a subset */ /* -------------------------------------------------------------------------- */ int cholmod_check_subset ( /* ---- input ---- */ int *Set, /* Set [0:len-1] is a subset of 0:n-1. Duplicates OK */ SuiteSparse_long len, /* size of Set (an integer array) */ size_t n, /* 0:n-1 is valid range */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_subset (SuiteSparse_long *, SuiteSparse_long, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_subset: print a subset */ /* -------------------------------------------------------------------------- */ int cholmod_print_subset ( /* ---- input ---- */ int *Set, /* Set [0:len-1] is a subset of 0:n-1. Duplicates OK */ SuiteSparse_long len, /* size of Set (an integer array) */ size_t n, /* 0:n-1 is valid range */ const char *name, /* printed name of Set */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_subset (SuiteSparse_long *, SuiteSparse_long, size_t, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_perm: check a permutation */ /* -------------------------------------------------------------------------- */ int cholmod_check_perm ( /* ---- input ---- */ int *Perm, /* Perm [0:len-1] is a permutation of subset of 0:n-1 */ size_t len, /* size of Perm (an integer array) */ size_t n, /* 0:n-1 is valid range */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_perm (SuiteSparse_long *, size_t, size_t, cholmod_common *); /* -------------------------------------------------------------------------- */ /* cholmod_print_perm: print a permutation vector */ /* -------------------------------------------------------------------------- */ int cholmod_print_perm ( /* ---- input ---- */ int *Perm, /* Perm [0:len-1] is a permutation of subset of 0:n-1 */ size_t len, /* size of Perm (an integer array) */ size_t n, /* 0:n-1 is valid range */ const char *name, /* printed name of Perm */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_perm (SuiteSparse_long *, size_t, size_t, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_check_parent: check an elimination tree */ /* -------------------------------------------------------------------------- */ int cholmod_check_parent ( /* ---- input ---- */ int *Parent, /* Parent [0:n-1] is an elimination tree */ size_t n, /* size of Parent */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_check_parent (SuiteSparse_long *, size_t, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_print_parent */ /* -------------------------------------------------------------------------- */ int cholmod_print_parent ( /* ---- input ---- */ int *Parent, /* Parent [0:n-1] is an elimination tree */ size_t n, /* size of Parent */ const char *name, /* printed name of Parent */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_print_parent (SuiteSparse_long *, size_t, const char *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_read_sparse: read a sparse matrix from a file */ /* -------------------------------------------------------------------------- */ cholmod_sparse *cholmod_read_sparse ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) ; cholmod_sparse *cholmod_l_read_sparse (FILE *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_read_triplet: read a triplet matrix from a file */ /* -------------------------------------------------------------------------- */ cholmod_triplet *cholmod_read_triplet ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) ; cholmod_triplet *cholmod_l_read_triplet (FILE *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_read_dense: read a dense matrix from a file */ /* -------------------------------------------------------------------------- */ cholmod_dense *cholmod_read_dense ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) ; cholmod_dense *cholmod_l_read_dense (FILE *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_read_matrix: read a sparse or dense matrix from a file */ /* -------------------------------------------------------------------------- */ void *cholmod_read_matrix ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ int prefer, /* If 0, a sparse matrix is always return as a * cholmod_triplet form. It can have any stype * (symmetric-lower, unsymmetric, or * symmetric-upper). * If 1, a sparse matrix is returned as an unsymmetric * cholmod_sparse form (A->stype == 0), with both * upper and lower triangular parts present. * This is what the MATLAB mread mexFunction does, * since MATLAB does not have an stype. * If 2, a sparse matrix is returned with an stype of 0 * or 1 (unsymmetric, or symmetric with upper part * stored). * This argument has no effect for dense matrices. */ /* ---- output---- */ int *mtype, /* CHOLMOD_TRIPLET, CHOLMOD_SPARSE or CHOLMOD_DENSE */ /* --------------- */ cholmod_common *Common ) ; void *cholmod_l_read_matrix (FILE *, int, int *, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_write_sparse: write a sparse matrix to a file */ /* -------------------------------------------------------------------------- */ int cholmod_write_sparse ( /* ---- input ---- */ FILE *f, /* file to write to, must already be open */ cholmod_sparse *A, /* matrix to print */ cholmod_sparse *Z, /* optional matrix with pattern of explicit zeros */ const char *comments, /* optional filename of comments to include */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_write_sparse (FILE *, cholmod_sparse *, cholmod_sparse *, const char *c, cholmod_common *) ; /* -------------------------------------------------------------------------- */ /* cholmod_write_dense: write a dense matrix to a file */ /* -------------------------------------------------------------------------- */ int cholmod_write_dense ( /* ---- input ---- */ FILE *f, /* file to write to, must already be open */ cholmod_dense *X, /* matrix to print */ const char *comments, /* optional filename of comments to include */ /* --------------- */ cholmod_common *Common ) ; int cholmod_l_write_dense (FILE *, cholmod_dense *, const char *, cholmod_common *) ; #endif igraph/src/CHOLMOD/Include/cholmod_complexity.h0000644000175100001440000002224413431000472021052 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_complexity.h ========================================= */ /* ========================================================================== */ /* Define operations on pattern, real, complex, and zomplex objects. * * The xtype of an object defines it numerical type. A qttern object has no * numerical values (A->x and A->z are NULL). A real object has no imaginary * qrt (A->x is used, A->z is NULL). A complex object has an imaginary qrt * that is stored interleaved with its real qrt (A->x is of size 2*nz, A->z * is NULL). A zomplex object has both real and imaginary qrts, which are * stored seqrately, as in MATLAB (A->x and A->z are both used). * * XTYPE is CHOLMOD_PATTERN, _REAL, _COMPLEX or _ZOMPLEX, and is the xtype of * the template routine under construction. XTYPE2 is equal to XTYPE, except * if XTYPE is CHOLMOD_PATTERN, in which case XTYPE is CHOLMOD_REAL. * XTYPE and XTYPE2 are defined in cholmod_template.h. */ /* -------------------------------------------------------------------------- */ /* pattern */ /* -------------------------------------------------------------------------- */ #define P_TEMPLATE(name) p_ ## name #define P_ASSIGN2(x,z,p,ax,az,q) x [p] = 1 #define P_PRINT(k,x,z,p) PRK(k, ("1")) /* -------------------------------------------------------------------------- */ /* real */ /* -------------------------------------------------------------------------- */ #define R_TEMPLATE(name) r_ ## name #define R_ASSEMBLE(x,z,p,ax,az,q) x [p] += ax [q] #define R_ASSIGN(x,z,p,ax,az,q) x [p] = ax [q] #define R_ASSIGN_CONJ(x,z,p,ax,az,q) x [p] = ax [q] #define R_ASSIGN_REAL(x,p,ax,q) x [p] = ax [q] #define R_XTYPE_OK(type) ((type) == CHOLMOD_REAL) #define R_IS_NONZERO(ax,az,q) IS_NONZERO (ax [q]) #define R_IS_ZERO(ax,az,q) IS_ZERO (ax [q]) #define R_IS_ONE(ax,az,q) (ax [q] == 1) #define R_MULT(x,z,p, ax,az,q, bx,bz,r) x [p] = ax [q] * bx [r] #define R_MULTADD(x,z,p, ax,az,q, bx,bz,r) x [p] += ax [q] * bx [r] #define R_MULTSUB(x,z,p, ax,az,q, bx,bz,r) x [p] -= ax [q] * bx [r] #define R_MULTADDCONJ(x,z,p, ax,az,q, bx,bz,r) x [p] += ax [q] * bx [r] #define R_MULTSUBCONJ(x,z,p, ax,az,q, bx,bz,r) x [p] -= ax [q] * bx [r] #define R_ADD(x,z,p, ax,az,q, bx,bz,r) x [p] = ax [q] + bx [r] #define R_ADD_REAL(x,p, ax,q, bx,r) x [p] = ax [q] + bx [r] #define R_CLEAR(x,z,p) x [p] = 0 #define R_CLEAR_IMAG(x,z,p) #define R_DIV(x,z,p,ax,az,q) x [p] /= ax [q] #define R_LLDOT(x,p, ax,az,q) x [p] -= ax [q] * ax [q] #define R_PRINT(k,x,z,p) PRK(k, ("%24.16e", x [p])) #define R_DIV_REAL(x,z,p, ax,az,q, bx,r) x [p] = ax [q] / bx [r] #define R_MULT_REAL(x,z,p, ax,az,q, bx,r) x [p] = ax [q] * bx [r] #define R_LDLDOT(x,p, ax,az,q, bx,r) x [p] -=(ax[q] * ax[q])/ bx[r] /* -------------------------------------------------------------------------- */ /* complex */ /* -------------------------------------------------------------------------- */ #define C_TEMPLATE(name) c_ ## name #define CT_TEMPLATE(name) ct_ ## name #define C_ASSEMBLE(x,z,p,ax,az,q) \ x [2*(p) ] += ax [2*(q) ] ; \ x [2*(p)+1] += ax [2*(q)+1] #define C_ASSIGN(x,z,p,ax,az,q) \ x [2*(p) ] = ax [2*(q) ] ; \ x [2*(p)+1] = ax [2*(q)+1] #define C_ASSIGN_REAL(x,p,ax,q) x [2*(p)] = ax [2*(q)] #define C_ASSIGN_CONJ(x,z,p,ax,az,q) \ x [2*(p) ] = ax [2*(q) ] ; \ x [2*(p)+1] = -ax [2*(q)+1] #define C_XTYPE_OK(type) ((type) == CHOLMOD_COMPLEX) #define C_IS_NONZERO(ax,az,q) \ (IS_NONZERO (ax [2*(q)]) || IS_NONZERO (ax [2*(q)+1])) #define C_IS_ZERO(ax,az,q) \ (IS_ZERO (ax [2*(q)]) && IS_ZERO (ax [2*(q)+1])) #define C_IS_ONE(ax,az,q) \ ((ax [2*(q)] == 1) && IS_ZERO (ax [2*(q)+1])) #define C_IMAG_IS_NONZERO(ax,az,q) (IS_NONZERO (ax [2*(q)+1])) #define C_MULT(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] = ax [2*(q) ] * bx [2*(r)] - ax [2*(q)+1] * bx [2*(r)+1] ; \ x [2*(p)+1] = ax [2*(q)+1] * bx [2*(r)] + ax [2*(q) ] * bx [2*(r)+1] #define C_MULTADD(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] += ax [2*(q) ] * bx [2*(r)] - ax [2*(q)+1] * bx [2*(r)+1] ; \ x [2*(p)+1] += ax [2*(q)+1] * bx [2*(r)] + ax [2*(q) ] * bx [2*(r)+1] #define C_MULTSUB(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] -= ax [2*(q) ] * bx [2*(r)] - ax [2*(q)+1] * bx [2*(r)+1] ; \ x [2*(p)+1] -= ax [2*(q)+1] * bx [2*(r)] + ax [2*(q) ] * bx [2*(r)+1] /* s += conj(a)*b */ #define C_MULTADDCONJ(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] += ax [2*(q) ] * bx [2*(r)] + ax [2*(q)+1] * bx [2*(r)+1] ; \ x [2*(p)+1] += (-ax [2*(q)+1]) * bx [2*(r)] + ax [2*(q) ] * bx [2*(r)+1] /* s -= conj(a)*b */ #define C_MULTSUBCONJ(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] -= ax [2*(q) ] * bx [2*(r)] + ax [2*(q)+1] * bx [2*(r)+1] ; \ x [2*(p)+1] -= (-ax [2*(q)+1]) * bx [2*(r)] + ax [2*(q) ] * bx [2*(r)+1] #define C_ADD(x,z,p, ax,az,q, bx,bz,r) \ x [2*(p) ] = ax [2*(q) ] + bx [2*(r) ] ; \ x [2*(p)+1] = ax [2*(q)+1] + bx [2*(r)+1] #define C_ADD_REAL(x,p, ax,q, bx,r) \ x [2*(p)] = ax [2*(q)] + bx [2*(r)] #define C_CLEAR(x,z,p) \ x [2*(p) ] = 0 ; \ x [2*(p)+1] = 0 #define C_CLEAR_IMAG(x,z,p) \ x [2*(p)+1] = 0 /* s = s / a */ #define C_DIV(x,z,p,ax,az,q) \ Common->complex_divide ( \ x [2*(p)], x [2*(p)+1], \ ax [2*(q)], ax [2*(q)+1], \ &x [2*(p)], &x [2*(p)+1]) /* s -= conj(a)*a ; note that the result of conj(a)*a is real */ #define C_LLDOT(x,p, ax,az,q) \ x [2*(p)] -= ax [2*(q)] * ax [2*(q)] + ax [2*(q)+1] * ax [2*(q)+1] #define C_PRINT(k,x,z,p) PRK(k, ("(%24.16e,%24.16e)", x [2*(p)], x [2*(p)+1])) #define C_DIV_REAL(x,z,p, ax,az,q, bx,r) \ x [2*(p) ] = ax [2*(q) ] / bx [2*(r)] ; \ x [2*(p)+1] = ax [2*(q)+1] / bx [2*(r)] #define C_MULT_REAL(x,z,p, ax,az,q, bx,r) \ x [2*(p) ] = ax [2*(q) ] * bx [2*(r)] ; \ x [2*(p)+1] = ax [2*(q)+1] * bx [2*(r)] /* s -= conj(a)*a/t */ #define C_LDLDOT(x,p, ax,az,q, bx,r) \ x [2*(p)] -= (ax [2*(q)] * ax [2*(q)] + ax [2*(q)+1] * ax [2*(q)+1]) / bx[r] /* -------------------------------------------------------------------------- */ /* zomplex */ /* -------------------------------------------------------------------------- */ #define Z_TEMPLATE(name) z_ ## name #define ZT_TEMPLATE(name) zt_ ## name #define Z_ASSEMBLE(x,z,p,ax,az,q) \ x [p] += ax [q] ; \ z [p] += az [q] #define Z_ASSIGN(x,z,p,ax,az,q) \ x [p] = ax [q] ; \ z [p] = az [q] #define Z_ASSIGN_REAL(x,p,ax,q) x [p] = ax [q] #define Z_ASSIGN_CONJ(x,z,p,ax,az,q) \ x [p] = ax [q] ; \ z [p] = -az [q] #define Z_XTYPE_OK(type) ((type) == CHOLMOD_ZOMPLEX) #define Z_IS_NONZERO(ax,az,q) \ (IS_NONZERO (ax [q]) || IS_NONZERO (az [q])) #define Z_IS_ZERO(ax,az,q) \ (IS_ZERO (ax [q]) && IS_ZERO (az [q])) #define Z_IS_ONE(ax,az,q) \ ((ax [q] == 1) && IS_ZERO (az [q])) #define Z_IMAG_IS_NONZERO(ax,az,q) (IS_NONZERO (az [q])) #define Z_MULT(x,z,p, ax,az,q, bx,bz,r) \ x [p] = ax [q] * bx [r] - az [q] * bz [r] ; \ z [p] = az [q] * bx [r] + ax [q] * bz [r] #define Z_MULTADD(x,z,p, ax,az,q, bx,bz,r) \ x [p] += ax [q] * bx [r] - az [q] * bz [r] ; \ z [p] += az [q] * bx [r] + ax [q] * bz [r] #define Z_MULTSUB(x,z,p, ax,az,q, bx,bz,r) \ x [p] -= ax [q] * bx [r] - az [q] * bz [r] ; \ z [p] -= az [q] * bx [r] + ax [q] * bz [r] #define Z_MULTADDCONJ(x,z,p, ax,az,q, bx,bz,r) \ x [p] += ax [q] * bx [r] + az [q] * bz [r] ; \ z [p] += (-az [q]) * bx [r] + ax [q] * bz [r] #define Z_MULTSUBCONJ(x,z,p, ax,az,q, bx,bz,r) \ x [p] -= ax [q] * bx [r] + az [q] * bz [r] ; \ z [p] -= (-az [q]) * bx [r] + ax [q] * bz [r] #define Z_ADD(x,z,p, ax,az,q, bx,bz,r) \ x [p] = ax [q] + bx [r] ; \ z [p] = az [q] + bz [r] #define Z_ADD_REAL(x,p, ax,q, bx,r) \ x [p] = ax [q] + bx [r] #define Z_CLEAR(x,z,p) \ x [p] = 0 ; \ z [p] = 0 #define Z_CLEAR_IMAG(x,z,p) \ z [p] = 0 /* s = s/a */ #define Z_DIV(x,z,p,ax,az,q) \ Common->complex_divide (x [p], z [p], ax [q], az [q], &x [p], &z [p]) /* s -= conj(a)*a ; note that the result of conj(a)*a is real */ #define Z_LLDOT(x,p, ax,az,q) \ x [p] -= ax [q] * ax [q] + az [q] * az [q] #define Z_PRINT(k,x,z,p) PRK(k, ("(%24.16e,%24.16e)", x [p], z [p])) #define Z_DIV_REAL(x,z,p, ax,az,q, bx,r) \ x [p] = ax [q] / bx [r] ; \ z [p] = az [q] / bx [r] #define Z_MULT_REAL(x,z,p, ax,az,q, bx,r) \ x [p] = ax [q] * bx [r] ; \ z [p] = az [q] * bx [r] /* s -= conj(a)*a/t */ #define Z_LDLDOT(x,p, ax,az,q, bx,r) \ x [p] -= (ax [q] * ax [q] + az [q] * az [q]) / bx[r] /* -------------------------------------------------------------------------- */ /* all classes */ /* -------------------------------------------------------------------------- */ /* Check if A->xtype and the two arrays A->x and A->z are valid. Set status to * invalid, unless status is already "out of memory". A can be a sparse matrix, * dense matrix, factor, or triplet. */ #define RETURN_IF_XTYPE_INVALID(A,xtype1,xtype2,result) \ { \ if ((A)->xtype < (xtype1) || (A)->xtype > (xtype2) || \ ((A)->xtype != CHOLMOD_PATTERN && ((A)->x) == NULL) || \ ((A)->xtype == CHOLMOD_ZOMPLEX && ((A)->z) == NULL)) \ { \ if (Common->status != CHOLMOD_OUT_OF_MEMORY) \ { \ ERROR (CHOLMOD_INVALID, "invalid xtype") ; \ } \ return (result) ; \ } \ } igraph/src/CHOLMOD/Include/cholmod_config.h0000644000175100001440000000630613431000472020123 0ustar hornikusers/* ========================================================================== */ /* === Include/cholmod_config.h ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Include/cholmod_config.h. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * CHOLMOD/Include/cholmod_config.h is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD configuration file, for inclusion in user programs. * * You do not have to edit any CHOLMOD files to compile and install CHOLMOD. * However, if you do not use all of CHOLMOD's modules, you need to compile * with the appropriate flag, or edit this file to add the appropriate #define. * * If you wish to use CHOLMOD under the GNU LGPL license only, then you must * compile CHOLMOD with -DNMATRIXOPS -DNSUPERNODAL and -DNMODIFY. This can * be done using just -DNGPL. * * Compiler flags for CHOLMOD: * * -DNCHECK do not include the Check module. License: GNU LGPL * -DNCHOLESKY do not include the Cholesky module. License: GNU LGPL * -DNPARTITION do not include the Partition module. License: GNU LGPL * -DNCAMD do not include the interfaces to CAMD, * CCOLAMD, CSYMAND in Partition module. License: GNU LGPL * * -DNGPL do not include any GNU GPL Modules in the CHOLMOD library. * -DNMATRIXOPS do not include the MatrixOps module. License: GNU GPL * -DNMODIFY do not include the Modify module. License: GNU GPL * -DNSUPERNODAL do not include the Supernodal module. License: GNU GPL * * -DNPRINT do not print anything * * -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by * LAPACK and the BLAS. Use LONGBLAS=long on Solaris to use * the 64-bit Sun Performance BLAS in cholmod_l_* routines. * You may need to use -D'LONGBLAS=long long' on the SGI * (this is not tested). * * -DNSUNPERF for Solaris only. If defined, do not use the Sun * Performance Library. The default is to use SunPerf. * You must compile CHOLMOD with -xlic_lib=sunperf. * * The Core Module (License GNU LGPL) is always included in the CHOLMOD library. */ #ifndef CHOLMOD_CONFIG_H #define CHOLMOD_CONFIG_H /* Use the compiler flag, or uncomment the definition(s), if you want to use * one or more non-default installation options: */ /* #define NCHECK #define NCHOLESKY #define NCAMD #define NPARTITION #define NGPL #define NMATRIXOPS #define NMODIFY #define NSUPERNODAL #define NPRINT #define LONGBLAS long #define LONGBLAS long long #define NSUNPERF */ /* -------------------------------------------------------------------------- */ /* if NGPL is defined, disable all GNU GPL Modules */ /* -------------------------------------------------------------------------- */ #ifdef NGPL #define NMATRIXOPS #define NMODIFY #define NSUPERNODAL #endif #endif igraph/src/CHOLMOD/Cholesky/0000755000175100001440000000000013561251652015205 5ustar hornikusersigraph/src/CHOLMOD/Cholesky/cholmod_solve.c0000644000175100001440000014160513431000472020201 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_solve =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Solve one of the following systems. D is identity for an LL' factorization, * in which the D operation is skipped: * * Ax=b 0: CHOLMOD_A x = P' * (L' \ (D \ (L \ (P * b)))) * LDL'x=b 1: CHOLMOD_LDLt x = (L' \ (D \ (L \ ( b)))) * LDx=b 2: CHOLMOD_LD x = ( (D \ (L \ ( b)))) * DL'x=b 3: CHOLMOD_DLt x = (L' \ (D \ ( ( b)))) * Lx=b 4: CHOLMOD_L x = ( ( (L \ ( b)))) * L'x=b 5: CHOLMOD_Lt x = (L' \ ( ( ( b)))) * Dx=b 6: CHOLMOD_D x = ( (D \ ( ( b)))) * x=Pb 7: CHOLMOD_P x = ( ( ( (P * b)))) * x=P'b 8: CHOLMOD_Pt x = P' * ( ( ( ( b)))) * * The factorization can be simplicial LDL', simplicial LL', or supernodal LL'. * For an LL' factorization, D is the identity matrix. Thus CHOLMOD_LD and * CHOLMOD_L solve the same system if an LL' factorization was performed, * for example. * * The supernodal solver uses BLAS routines dtrsv, dgemv, dtrsm, and dgemm, * or their complex counterparts ztrsv, zgemv, ztrsm, and zgemm. * * If both L and B are real, then X is returned real. If either is complex * or zomplex, X is returned as either complex or zomplex, depending on the * Common->prefer_zomplex parameter. * * Supports any numeric xtype (pattern-only matrices not supported). * * This routine does not check to see if the diagonal of L or D is zero, * because sometimes a partial solve can be done with indefinite or singular * matrix. If you wish to check in your own code, test L->minor. If * L->minor == L->n, then the matrix has no zero diagonal entries. * If k = L->minor < L->n, then L(k,k) is zero for an LL' factorization, or * D(k,k) is zero for an LDL' factorization. * * This routine returns X as NULL only if it runs out of memory. If L is * indefinite or singular, then X may contain Inf's or NaN's, but it will * exist on output. */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define REAL #include "t_cholmod_solve.c" #define COMPLEX #include "t_cholmod_solve.c" #define ZOMPLEX #include "t_cholmod_solve.c" /* ========================================================================== */ /* === Permutation macro ==================================================== */ /* ========================================================================== */ /* If Perm is NULL, it is interpretted as the identity permutation */ #define P(k) ((Perm == NULL) ? (k) : Perm [k]) /* ========================================================================== */ /* === perm ================================================================= */ /* ========================================================================== */ /* Y = B (P (1:nrow), k1 : min (k1+ncols,ncol)-1) where B is nrow-by-ncol. * * Creates a permuted copy of a contiguous set of columns of B. * Y is already allocated on input. Y must be of sufficient size. Let nk be * the number of columns accessed in B. Y->xtype determines the complexity of * the result. * * If B is real and Y is complex (or zomplex), only the real part of B is * copied into Y. The imaginary part of Y is set to zero. * * If B is complex (or zomplex) and Y is real, both the real and imaginary and * parts of B are returned in Y. Y is returned as nrow-by-2*nk. The even * columns of Y contain the real part of B and the odd columns contain the * imaginary part of B. Y->nzmax must be >= 2*nrow*nk. Otherise, Y is * returned as nrow-by-nk with leading dimension nrow. Y->nzmax must be >= * nrow*nk. * * The case where the input (B) is real and the output (Y) is zomplex is * not used. */ static void perm ( /* ---- input ---- */ cholmod_dense *B, /* input matrix B */ Int *Perm, /* optional input permutation (can be NULL) */ Int k1, /* first column of B to copy */ Int ncols, /* last column to copy is min(k1+ncols,B->ncol)-1 */ /* ---- in/out --- */ cholmod_dense *Y /* output matrix Y, already allocated */ ) { double *Yx, *Yz, *Bx, *Bz ; Int k2, nk, p, k, j, nrow, ncol, d, dual, dj, j2 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = B->ncol ; nrow = B->nrow ; k2 = MIN (k1+ncols, ncol) ; nk = MAX (k2 - k1, 0) ; dual = (Y->xtype == CHOLMOD_REAL && B->xtype != CHOLMOD_REAL) ? 2 : 1 ; d = B->d ; Bx = B->x ; Bz = B->z ; Yx = Y->x ; Yz = Y->z ; Y->nrow = nrow ; Y->ncol = dual*nk ; Y->d = nrow ; ASSERT (((Int) Y->nzmax) >= nrow*nk*dual) ; /* ---------------------------------------------------------------------- */ /* Y = B (P (1:nrow), k1:k2-1) */ /* ---------------------------------------------------------------------- */ switch (Y->xtype) { case CHOLMOD_REAL: switch (B->xtype) { case CHOLMOD_REAL: /* Y real, B real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [k + j2] = Bx [p] ; /* real */ } } break ; case CHOLMOD_COMPLEX: /* Y real, B complex. Y is nrow-by-2*nk */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [k + j2 ] = Bx [2*p ] ; /* real */ Yx [k + j2 + nrow] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y real, B zomplex. Y is nrow-by-2*nk */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [k + j2 ] = Bx [p] ; /* real */ Yx [k + j2 + nrow] = Bz [p] ; /* imag */ } } break ; } break ; case CHOLMOD_COMPLEX: switch (B->xtype) { case CHOLMOD_REAL: /* Y complex, B real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [2*k + j2] = Bx [p] ; /* real */ Yx [2*k+1 + j2] = 0 ; /* imag */ } } break ; case CHOLMOD_COMPLEX: /* Y complex, B complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [2*k + j2] = Bx [2*p ] ; /* real */ Yx [2*k+1 + j2] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y complex, B zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [2*k + j2] = Bx [p] ; /* real */ Yx [2*k+1 + j2] = Bz [p] ; /* imag */ } } break ; } break ; case CHOLMOD_ZOMPLEX: switch (B->xtype) { #if 0 case CHOLMOD_REAL: /* this case is not used */ break ; #endif case CHOLMOD_COMPLEX: /* Y zomplex, B complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [k + j2] = Bx [2*p ] ; /* real */ Yz [k + j2] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y zomplex, B zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [k + j2] = Bx [p] ; /* real */ Yz [k + j2] = Bz [p] ; /* imag */ } } break ; } break ; } } /* ========================================================================== */ /* === iperm ================================================================ */ /* ========================================================================== */ /* X (P (1:nrow), k1 : min (k1+ncols,ncol)-1) = Y where X is nrow-by-ncol. * * Copies and permutes Y into a contiguous set of columns of X. X is already * allocated on input. Y must be of sufficient size. Let nk be the number * of columns accessed in X. X->xtype determines the complexity of the result. * * If X is real and Y is complex (or zomplex), only the real part of B is * copied into X. The imaginary part of Y is ignored. * * If X is complex (or zomplex) and Y is real, both the real and imaginary and * parts of Y are returned in X. Y is nrow-by-2*nk. The even * columns of Y contain the real part of B and the odd columns contain the * imaginary part of B. Y->nzmax must be >= 2*nrow*nk. Otherise, Y is * nrow-by-nk with leading dimension nrow. Y->nzmax must be >= nrow*nk. * * The case where the input (Y) is complex and the output (X) is real, * and the case where the input (Y) is zomplex and the output (X) is real, * are not used. */ static void iperm ( /* ---- input ---- */ cholmod_dense *Y, /* input matrix Y */ Int *Perm, /* optional input permutation (can be NULL) */ Int k1, /* first column of B to copy */ Int ncols, /* last column to copy is min(k1+ncols,B->ncol)-1 */ /* ---- in/out --- */ cholmod_dense *X /* output matrix X, already allocated */ ) { double *Yx, *Yz, *Xx, *Xz ; Int k2, nk, p, k, j, nrow, ncol, d, dj, j2 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = X->ncol ; nrow = X->nrow ; k2 = MIN (k1+ncols, ncol) ; nk = MAX (k2 - k1, 0) ; d = X->d ; Xx = X->x ; Xz = X->z ; Yx = Y->x ; Yz = Y->z ; ASSERT (((Int) Y->nzmax) >= nrow*nk* ((X->xtype != CHOLMOD_REAL && Y->xtype == CHOLMOD_REAL) ? 2:1)) ; /* ---------------------------------------------------------------------- */ /* X (P (1:nrow), k1:k2-1) = Y */ /* ---------------------------------------------------------------------- */ switch (Y->xtype) { case CHOLMOD_REAL: switch (X->xtype) { case CHOLMOD_REAL: /* Y real, X real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [k + j2] ; /* real */ } } break ; case CHOLMOD_COMPLEX: /* Y real, X complex. Y is nrow-by-2*nk */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [k + j2 ] ; /* real */ Xx [2*p+1] = Yx [k + j2 + nrow] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y real, X zomplex. Y is nrow-by-2*nk */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [k + j2 ] ; /* real */ Xz [p] = Yx [k + j2 + nrow] ; /* imag */ } } break ; } break ; case CHOLMOD_COMPLEX: switch (X->xtype) { #if 0 case CHOLMOD_REAL: /* this case is not used */ break ; #endif case CHOLMOD_COMPLEX: /* Y complex, X complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [2*k + j2] ; /* real */ Xx [2*p+1] = Yx [2*k+1 + j2] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y complex, X zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * 2 * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [2*k + j2] ; /* real */ Xz [p] = Yx [2*k+1 + j2] ; /* imag */ } } break ; } break ; case CHOLMOD_ZOMPLEX: switch (X->xtype) { #if 0 case CHOLMOD_REAL: /* this case is not used */ break ; #endif case CHOLMOD_COMPLEX: /* Y zomplex, X complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [k + j2] ; /* real */ Xx [2*p+1] = Yz [k + j2] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y zomplex, X zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = nrow * (j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [k + j2] ; /* real */ Xz [p] = Yz [k + j2] ; /* imag */ } } break ; } break ; } } /* ========================================================================== */ /* === ptrans =============================================================== */ /* ========================================================================== */ /* Y = B (P (1:nrow), k1 : min (k1+ncols,ncol)-1)' where B is nrow-by-ncol. * * Creates a permuted and transposed copy of a contiguous set of columns of B. * Y is already allocated on input. Y must be of sufficient size. Let nk be * the number of columns accessed in B. Y->xtype determines the complexity of * the result. * * If B is real and Y is complex (or zomplex), only the real part of B is * copied into Y. The imaginary part of Y is set to zero. * * If B is complex (or zomplex) and Y is real, both the real and imaginary and * parts of B are returned in Y. Y is returned as 2*nk-by-nrow. The even * rows of Y contain the real part of B and the odd rows contain the * imaginary part of B. Y->nzmax must be >= 2*nrow*nk. Otherise, Y is * returned as nk-by-nrow with leading dimension nk. Y->nzmax must be >= * nrow*nk. * * The array transpose is performed, not the complex conjugate transpose. */ static void ptrans ( /* ---- input ---- */ cholmod_dense *B, /* input matrix B */ Int *Perm, /* optional input permutation (can be NULL) */ Int k1, /* first column of B to copy */ Int ncols, /* last column to copy is min(k1+ncols,B->ncol)-1 */ /* ---- in/out --- */ cholmod_dense *Y /* output matrix Y, already allocated */ ) { double *Yx, *Yz, *Bx, *Bz ; Int k2, nk, p, k, j, nrow, ncol, d, dual, dj, j2 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = B->ncol ; nrow = B->nrow ; k2 = MIN (k1+ncols, ncol) ; nk = MAX (k2 - k1, 0) ; dual = (Y->xtype == CHOLMOD_REAL && B->xtype != CHOLMOD_REAL) ? 2 : 1 ; d = B->d ; Bx = B->x ; Bz = B->z ; Yx = Y->x ; Yz = Y->z ; Y->nrow = dual*nk ; Y->ncol = nrow ; Y->d = dual*nk ; ASSERT (((Int) Y->nzmax) >= nrow*nk*dual) ; /* ---------------------------------------------------------------------- */ /* Y = B (P (1:nrow), k1:k2-1)' */ /* ---------------------------------------------------------------------- */ switch (Y->xtype) { case CHOLMOD_REAL: switch (B->xtype) { case CHOLMOD_REAL: /* Y real, B real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*nk] = Bx [p] ; /* real */ } } break ; case CHOLMOD_COMPLEX: /* Y real, B complex. Y is 2*nk-by-nrow */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*2*nk] = Bx [2*p ] ; /* real */ Yx [j2+1 + k*2*nk] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y real, B zomplex. Y is 2*nk-by-nrow */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*2*nk] = Bx [p] ; /* real */ Yx [j2+1 + k*2*nk] = Bz [p] ; /* imag */ } } break ; } break ; case CHOLMOD_COMPLEX: switch (B->xtype) { case CHOLMOD_REAL: /* Y complex, B real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*2*nk] = Bx [p] ; /* real */ Yx [j2+1 + k*2*nk] = 0 ; /* imag */ } } break ; case CHOLMOD_COMPLEX: /* Y complex, B complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*2*nk] = Bx [2*p ] ; /* real */ Yx [j2+1 + k*2*nk] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y complex, B zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*2*nk] = Bx [p] ; /* real */ Yx [j2+1 + k*2*nk] = Bz [p] ; /* imag */ } } break ; } break ; case CHOLMOD_ZOMPLEX: switch (B->xtype) { case CHOLMOD_REAL: /* Y zomplex, B real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*nk] = Bx [p] ; /* real */ Yz [j2 + k*nk] = 0 ; /* imag */ } } break ; case CHOLMOD_COMPLEX: /* Y zomplex, B complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*nk] = Bx [2*p ] ; /* real */ Yz [j2 + k*nk] = Bx [2*p+1] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y zomplex, B zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Yx [j2 + k*nk] = Bx [p] ; /* real */ Yz [j2 + k*nk] = Bz [p] ; /* imag */ } } break ; } break ; } } /* ========================================================================== */ /* === iptrans ============================================================== */ /* ========================================================================== */ /* X (P (1:nrow), k1 : min (k1+ncols,ncol)-1) = Y' where X is nrow-by-ncol. * * Copies into a permuted and transposed contiguous set of columns of X. * X is already allocated on input. Y must be of sufficient size. Let nk be * the number of columns accessed in X. X->xtype determines the complexity of * the result. * * If X is real and Y is complex (or zomplex), only the real part of Y is * copied into X. The imaginary part of Y is ignored. * * If X is complex (or zomplex) and Y is real, both the real and imaginary and * parts of X are returned in Y. Y is 2*nk-by-nrow. The even * rows of Y contain the real part of X and the odd rows contain the * imaginary part of X. Y->nzmax must be >= 2*nrow*nk. Otherise, Y is * nk-by-nrow with leading dimension nk. Y->nzmax must be >= nrow*nk. * * The case where Y is complex or zomplex, and X is real, is not used. * * The array transpose is performed, not the complex conjugate transpose. */ static void iptrans ( /* ---- input ---- */ cholmod_dense *Y, /* input matrix Y */ Int *Perm, /* optional input permutation (can be NULL) */ Int k1, /* first column of X to copy into */ Int ncols, /* last column to copy is min(k1+ncols,X->ncol)-1 */ /* ---- in/out --- */ cholmod_dense *X /* output matrix X, already allocated */ ) { double *Yx, *Yz, *Xx, *Xz ; Int k2, nk, p, k, j, nrow, ncol, d, dj, j2 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = X->ncol ; nrow = X->nrow ; k2 = MIN (k1+ncols, ncol) ; nk = MAX (k2 - k1, 0) ; d = X->d ; Xx = X->x ; Xz = X->z ; Yx = Y->x ; Yz = Y->z ; ASSERT (((Int) Y->nzmax) >= nrow*nk* ((X->xtype != CHOLMOD_REAL && Y->xtype == CHOLMOD_REAL) ? 2:1)) ; /* ---------------------------------------------------------------------- */ /* X (P (1:nrow), k1:k2-1) = Y' */ /* ---------------------------------------------------------------------- */ switch (Y->xtype) { case CHOLMOD_REAL: switch (X->xtype) { case CHOLMOD_REAL: /* Y real, X real */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [j2 + k*nk] ; /* real */ } } break ; case CHOLMOD_COMPLEX: /* Y real, X complex. Y is 2*nk-by-nrow */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [j2 + k*2*nk] ; /* real */ Xx [2*p+1] = Yx [j2+1 + k*2*nk] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y real, X zomplex. Y is 2*nk-by-nrow */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [j2 + k*2*nk] ; /* real */ Xz [p] = Yx [j2+1 + k*2*nk] ; /* imag */ } } break ; } break ; case CHOLMOD_COMPLEX: switch (X->xtype) { #if 0 case CHOLMOD_REAL: /* this case is not used */ break ; #endif case CHOLMOD_COMPLEX: /* Y complex, X complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [j2 + k*2*nk] ; /* real */ Xx [2*p+1] = Yx [j2+1 + k*2*nk] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y complex, X zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = 2*(j-k1) ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [j2 + k*2*nk] ; /* real */ Xz [p] = Yx [j2+1 + k*2*nk] ; /* imag */ } } break ; } break ; case CHOLMOD_ZOMPLEX: switch (X->xtype) { #if 0 case CHOLMOD_REAL: /* this case is not used */ break ; #endif case CHOLMOD_COMPLEX: /* Y zomplex, X complex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [2*p ] = Yx [j2 + k*nk] ; /* real */ Xx [2*p+1] = Yz [j2 + k*nk] ; /* imag */ } } break ; case CHOLMOD_ZOMPLEX: /* Y zomplex, X zomplex */ for (j = k1 ; j < k2 ; j++) { dj = d*j ; j2 = j-k1 ; for (k = 0 ; k < nrow ; k++) { p = P(k) + dj ; Xx [p] = Yx [j2 + k*nk] ; /* real */ Xz [p] = Yz [j2 + k*nk] ; /* imag */ } } break ; } break ; } } /* ========================================================================== */ /* === cholmod_solve ======================================================== */ /* ========================================================================== */ /* Solve a linear system. * * The factorization can be simplicial LDL', simplicial LL', or supernodal LL'. * The Dx=b solve returns silently for the LL' factorizations (it is implicitly * identity). */ cholmod_dense *CHOLMOD(solve) ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_dense *B, /* right-hand-side */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *Y = NULL, *X = NULL ; cholmod_dense *E = NULL ; int ok ; /* do the solve, allocating workspaces as needed */ ok = CHOLMOD (solve2) (sys, L, B, NULL, &X, NULL, &Y, &E, Common) ; /* free workspaces if allocated, and free result if an error occured */ CHOLMOD(free_dense) (&Y, Common) ; CHOLMOD(free_dense) (&E, Common) ; if (!ok) { CHOLMOD(free_dense) (&X, Common) ; } return (X) ; } /* ========================================================================== */ /* === cholmod_solve2 ======================================================= */ /* ========================================================================== */ /* This function acts just like cholmod_solve, except that the solution X and * the internal workspace (Y and E) can be passed in preallocated. If the * solution X or any required workspaces are not allocated on input, or if they * are the wrong size or type, then this function frees them and reallocates * them as the proper size and type. Thus, if you have a sequence of solves to * do, you can let this function allocate X, Y, and E on the first call. * Subsequent calls to cholmod_solve2 can then reuse this space. You must * then free the workspaces Y and E (and X if desired) when you are finished. * For example, the first call to cholmod_l_solve2, below, will solve the * requested system. The next 2 calls (with different right-hand-sides but * the same value of "sys") will resuse the workspace and solution X from the * first call. Finally, when all solves are done, you must free the workspaces * Y and E (otherwise you will have a memory leak), and you should also free X * when you are done with it. Note that on input, X, Y, and E must be either * valid cholmod_dense matrices, or initialized to NULL. You cannot pass in an * uninitialized X, Y, or E. * * cholmod_dense *X = NULL, *Y = NULL, *E = NULL ; * ... * cholmod_l_solve2 (sys, L, B1, NULL, &X, NULL, &Y, &E, Common) ; * cholmod_l_solve2 (sys, L, B2, NULL, &X, NULL, &Y, &E, Common) ; * cholmod_l_solve2 (sys, L, B3, NULL, &X, NULL, &Y, &E, Common) ; * cholmod_l_free_dense (&X, Common) ; * cholmod_l_free_dense (&Y, Common) ; * cholmod_l_free_dense (&E, Common) ; * * The equivalent when using cholmod_l_solve is: * * cholmod_dense *X = NULL, *Y = NULL, *E = NULL ; * ... * X = cholmod_l_solve (sys, L, B1, Common) ; * cholmod_l_free_dense (&X, Common) ; * X = cholmod_l_solve (sys, L, B2, Common) ; * cholmod_l_free_dense (&X, Common) ; * X = cholmod_l_solve (sys, L, B3, Common) ; * cholmod_l_free_dense (&X, Common) ; * * Both methods work fine, but in the 2nd method with cholmod_solve, the * internal workspaces (Y and E) are allocated and freed on each call. * * Bset is an optional sparse column (pattern only) that specifies a set * of row indices. It is ignored if NULL, or if sys is CHOLMOD_P or * CHOLMOD_Pt. If it is present and not ignored, B must be a dense column * vector, and only entries B(i) where i is in the pattern of Bset are * considered. All others are treated as if they were zero (they are not * accessed). L must be a simplicial factorization, not supernodal. L is * converted from supernodal to simplicial if necessary. The solution X is * defined only for entries in the output sparse pattern of Xset. * The xtype (real/complex/zomplex) of L and B must match. * * NOTE: If Bset is present and L is supernodal, it is converted to simplicial * on output. */ int CHOLMOD(solve2) /* returns TRUE on success, FALSE on failure */ ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_dense *B, /* right-hand-side */ cholmod_sparse *Bset, /* ---- output --- */ cholmod_dense **X_Handle, /* solution, allocated if need be */ cholmod_sparse **Xset_Handle, /* ---- workspace */ cholmod_dense **Y_Handle, /* workspace, or NULL */ cholmod_dense **E_Handle, /* workspace, or NULL */ /* --------------- */ cholmod_common *Common ) { double *Yx, *Yz, *Bx, *Bz, *Xx, *Xz ; cholmod_dense *Y = NULL, *X = NULL ; cholmod_sparse *C, *Yset, C_header, Yset_header, *Xset ; Int *Perm = NULL, *IPerm = NULL ; Int n, nrhs, ncols, ctype, xtype, k1, nr, ytype, k, blen, p, i, d, nrow ; Int Cp [2], Ysetp [2], *Ci, *Yseti, ysetlen ; Int *Bsetp, *Bseti, *Bsetnz, *Xseti, *Xsetp, *Iwork ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (B, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; if (sys < CHOLMOD_A || sys > CHOLMOD_Pt) { ERROR (CHOLMOD_INVALID, "invalid system") ; return (FALSE) ; } DEBUG (CHOLMOD(dump_factor) (L, "L", Common)) ; DEBUG (CHOLMOD(dump_dense) (B, "B", Common)) ; nrhs = B->ncol ; n = (Int) L->n ; d = (Int) B->d ; nrow = (Int) B->nrow ; if (d < n || nrow != n) { ERROR (CHOLMOD_INVALID, "dimensions of L and B do not match") ; return (FALSE) ; } if (Bset) { if (nrhs != 1) { ERROR (CHOLMOD_INVALID, "Bset requires a single right-hand side") ; return (FALSE) ; } if (L->xtype != B->xtype) { ERROR (CHOLMOD_INVALID, "Bset requires xtype of L and B to match") ; return (FALSE) ; } DEBUG (CHOLMOD(dump_sparse) (Bset, "Bset", Common)) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ if ((sys == CHOLMOD_P || sys == CHOLMOD_Pt || sys == CHOLMOD_A) && L->ordering != CHOLMOD_NATURAL) { /* otherwise, Perm is NULL, and the identity permutation is used */ Perm = L->Perm ; } /* ---------------------------------------------------------------------- */ /* allocate the result X (or resuse the space from a prior call) */ /* ---------------------------------------------------------------------- */ ctype = (Common->prefer_zomplex) ? CHOLMOD_ZOMPLEX : CHOLMOD_COMPLEX ; if (Bset) { xtype = L->xtype ; } else if (sys == CHOLMOD_P || sys == CHOLMOD_Pt) { /* x=Pb and x=P'b return X real if B is real; X is the preferred * complex/zcomplex type if B is complex or zomplex */ xtype = (B->xtype == CHOLMOD_REAL) ? CHOLMOD_REAL : ctype ; } else if (L->xtype == CHOLMOD_REAL && B->xtype == CHOLMOD_REAL) { /* X is real if both L and B are real */ xtype = CHOLMOD_REAL ; } else { /* X is complex, use the preferred complex/zomplex type */ xtype = ctype ; } /* ensure X has the right size and type */ X = CHOLMOD(ensure_dense) (X_Handle, n, nrhs, n, xtype, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* solve using L, D, L', P, or some combination */ /* ---------------------------------------------------------------------- */ if (Bset) { /* ------------------------------------------------------------------ */ /* solve for a subset of x, with a sparse b */ /* ------------------------------------------------------------------ */ Int save_realloc_state ; #ifndef NSUPERNODAL /* convert a supernodal L to simplicial when using Bset */ if (L->is_super) { /* Can only use Bset on a simplicial factorization. The supernodal * factor L is converted to simplicial, leaving the xtype unchanged * (real, complex, or zomplex). Since the supernodal factorization * is already LL', it is left in that form. This conversion uses * the ll_super_to_simplicial_numeric function in * cholmod_change_factor. */ CHOLMOD(change_factor) ( CHOLMOD_REAL, /* ignored, since L is already numeric */ TRUE, /* convert to LL' (no change to num. values) */ FALSE, /* convert to simplicial */ FALSE, /* do not pack the columns of L */ FALSE, /* (ignored) */ L, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory, L is returned unchanged */ return (FALSE) ; } } #endif /* L, X, and B are all the same xtype */ /* ensure Y is the the right size */ Y = CHOLMOD(ensure_dense) (Y_Handle, 1, n, 1, L->xtype, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } /* ------------------------------------------------------------------ */ /* get the inverse permutation, constructing it if needed */ /* ------------------------------------------------------------------ */ DEBUG (CHOLMOD (dump_perm) (Perm, n,n, "Perm", Common)) ; if ((sys == CHOLMOD_A || sys == CHOLMOD_P) && Perm != NULL) { /* The inverse permutation IPerm is used for the c=Pb step, which is needed only for solving Ax=b or x=Pb. No other steps should use IPerm */ if (L->IPerm == NULL) { /* construct the inverse permutation. This is done only once * and then stored in L permanently. */ L->IPerm = CHOLMOD(malloc) (n, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } IPerm = L->IPerm ; for (k = 0 ; k < n ; k++) { IPerm [Perm [k]] = k ; } } /* x=A\b and x=Pb both need IPerm */ IPerm = L->IPerm ; } if (sys == CHOLMOD_P) { /* x=Pb needs to turn off the subsequent x=P'b permutation */ Perm = NULL ; } DEBUG (CHOLMOD (dump_perm) (Perm, n,n, "Perm", Common)) ; DEBUG (CHOLMOD (dump_perm) (IPerm, n,n, "IPerm", Common)) ; /* ------------------------------------------------------------------ */ /* ensure Xset is the right size and type */ /* ------------------------------------------------------------------ */ /* Xset is n-by-1, nzmax >= n, pattern-only, packed, unsorted */ Xset = *Xset_Handle ; if (Xset == NULL || (Int) Xset->nrow != n || (Int) Xset->ncol != 1 || (Int) Xset->nzmax < n || Xset->itype != CHOLMOD_PATTERN) { /* this is done only once, for the 1st call to cholmod_solve */ CHOLMOD(free_sparse) (Xset_Handle, Common) ; Xset = CHOLMOD(allocate_sparse) (n, 1, n, FALSE, TRUE, 0, CHOLMOD_PATTERN, Common) ; *Xset_Handle = Xset ; } Xset->sorted = FALSE ; Xset->stype = 0 ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } /* -------------------------------------------------------------- */ /* ensure Flag of size n, and 3*n Int workspace is available */ /* -------------------------------------------------------------- */ /* does no work if prior calls already allocated enough space */ CHOLMOD(allocate_work) (n, 3*n, 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } /* [ use Iwork (n:3n-1) for Ci and Yseti */ Iwork = Common->Iwork ; /* Iwork (0:n-1) is not used because it is used by check_perm, print_perm, check_sparse, and print_sparse */ Ci = Iwork + n ; Yseti = Ci + n ; /* reallocating workspace would break Ci and Yseti */ save_realloc_state = Common->no_workspace_reallocate ; Common->no_workspace_reallocate = TRUE ; /* -------------------------------------------------------------- */ /* C = permuted Bset, to correspond to the permutation of L */ /* -------------------------------------------------------------- */ /* C = IPerm (Bset) */ DEBUG (CHOLMOD(dump_sparse) (Bset, "Bset", Common)) ; Bsetp = Bset->p ; Bseti = Bset->i ; Bsetnz = Bset->nz ; blen = (Bset->packed) ? Bsetp [1] : Bsetnz [0] ; /* C = spones (P*B) or C = spones (B) if IPerm is NULL */ C = &C_header ; C->nrow = n ; C->ncol = 1 ; C->nzmax = n ; C->packed = TRUE ; C->stype = 0 ; C->itype = ITYPE ; C->xtype = CHOLMOD_PATTERN ; C->dtype = CHOLMOD_DOUBLE ; C->nz = NULL ; C->p = Cp ; C->i = Ci ; C->x = NULL ; C->z = NULL ; C->sorted = FALSE ; Cp [0] = 0 ; Cp [1] = blen ; for (p = 0 ; p < blen ; p++) { Int iold = Bseti [p] ; Ci [p] = IPerm ? IPerm [iold] : iold ; } DEBUG (CHOLMOD (dump_sparse) (C, "C", Common)) ; /* create a sparse column Yset from Iwork (n:2n-1) */ Yset = &Yset_header ; Yset->nrow = n ; Yset->ncol = 1 ; Yset->nzmax = n ; Yset->packed = TRUE ; Yset->stype = 0 ; Yset->itype = ITYPE ; Yset->xtype = CHOLMOD_PATTERN ; Yset->dtype = CHOLMOD_DOUBLE ; Yset->nz = NULL ; Yset->p = Ysetp ; Yset->i = Yseti ; Yset->x = NULL ; Yset->z = NULL ; Yset->sorted = FALSE ; Ysetp [0] = 0 ; Ysetp [1] = 0 ; DEBUG (CHOLMOD (dump_sparse) (Yset, "Yset empty", Common)) ; /* -------------------------------------------------------------- */ /* Yset = nonzero pattern of L\C, or just C itself */ /* -------------------------------------------------------------- */ /* this takes O(ysetlen) time */ if (sys == CHOLMOD_P || sys == CHOLMOD_Pt || sys == CHOLMOD_D) { Ysetp [1] = blen ; for (p = 0 ; p < blen ; p++) { Yseti [p] = Ci [p] ; } } else { if (!CHOLMOD(lsolve_pattern) (C, L, Yset, Common)) { Common->no_workspace_reallocate = save_realloc_state ; return (FALSE) ; } } DEBUG (CHOLMOD (dump_sparse) (Yset, "Yset", Common)) ; /* -------------------------------------------------------------- */ /* clear the parts of Y that we will use in the solve */ /* -------------------------------------------------------------- */ Yx = Y->x ; Yz = Y->z ; ysetlen = Ysetp [1] ; switch (L->xtype) { case CHOLMOD_REAL: for (p = 0 ; p < ysetlen ; p++) { i = Yseti [p] ; Yx [i] = 0 ; } break ; case CHOLMOD_COMPLEX: for (p = 0 ; p < ysetlen ; p++) { i = Yseti [p] ; Yx [2*i ] = 0 ; Yx [2*i+1] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for (p = 0 ; p < ysetlen ; p++) { i = Yseti [p] ; Yx [i] = 0 ; Yz [i] = 0 ; } break ; } DEBUG (CHOLMOD (dump_dense) (Y, "Y (Yset) = 0", Common)) ; /* -------------------------------------------------------------- */ /* scatter and permute B into Y */ /* -------------------------------------------------------------- */ /* Y (C) = B (Bset) */ Bx = B->x ; Bz = B->z ; switch (L->xtype) { case CHOLMOD_REAL: for (p = 0 ; p < blen ; p++) { Int iold = Bseti [p] ; Int inew = Ci [p] ; Yx [inew] = Bx [iold] ; } break ; case CHOLMOD_COMPLEX: for (p = 0 ; p < blen ; p++) { Int iold = Bseti [p] ; Int inew = Ci [p] ; Yx [2*inew ] = Bx [2*iold ] ; Yx [2*inew+1] = Bx [2*iold+1] ; } break ; case CHOLMOD_ZOMPLEX: for (p = 0 ; p < blen ; p++) { Int iold = Bseti [p] ; Int inew = Ci [p] ; Yx [inew] = Bx [iold] ; Yz [inew] = Bz [iold] ; } break ; } DEBUG (CHOLMOD (dump_dense) (Y, "Y (C) = B (Bset)", Common)) ; /* -------------------------------------------------------------- */ /* solve Y = (L' \ (L \ Y'))', or other system, with template */ /* -------------------------------------------------------------- */ /* the solve only iterates over columns in Yseti [0...ysetlen-1] */ if (! (sys == CHOLMOD_P || sys == CHOLMOD_Pt)) { switch (L->xtype) { case CHOLMOD_REAL: r_simplicial_solver (sys, L, Y, Yseti, ysetlen) ; break ; case CHOLMOD_COMPLEX: c_simplicial_solver (sys, L, Y, Yseti, ysetlen) ; break ; case CHOLMOD_ZOMPLEX: z_simplicial_solver (sys, L, Y, Yseti, ysetlen) ; break ; } } DEBUG (CHOLMOD (dump_dense) (Y, "Y after solve", Common)) ; /* -------------------------------------------------------------- */ /* X = P'*Y, but only for rows in Yset, and create Xset */ /* -------------------------------------------------------------- */ /* X (Perm (Yset)) = Y (Yset) */ Xx = X->x ; Xz = X->z ; Xseti = Xset->i ; Xsetp = Xset->p ; switch (L->xtype) { case CHOLMOD_REAL: for (p = 0 ; p < ysetlen ; p++) { Int inew = Yseti [p] ; Int iold = Perm ? Perm [inew] : inew ; Xx [iold] = Yx [inew] ; Xseti [p] = iold ; } break ; case CHOLMOD_COMPLEX: for (p = 0 ; p < ysetlen ; p++) { Int inew = Yseti [p] ; Int iold = Perm ? Perm [inew] : inew ; Xx [2*iold ] = Yx [2*inew] ; Xx [2*iold+1] = Yx [2*inew+1] ; Xseti [p] = iold ; } break ; case CHOLMOD_ZOMPLEX: for (p = 0 ; p < ysetlen ; p++) { Int inew = Yseti [p] ; Int iold = Perm ? Perm [inew] : inew ; Xx [iold] = Yx [inew] ; Xz [iold] = Yz [inew] ; Xseti [p] = iold ; } break ; } Xsetp [0] = 0 ; Xsetp [1] = ysetlen ; DEBUG (CHOLMOD(dump_sparse) (Xset, "Xset", Common)) ; DEBUG (CHOLMOD(dump_dense) (X, "X", Common)) ; Common->no_workspace_reallocate = save_realloc_state ; /* done using Iwork (n:3n-1) for Ci and Yseti ] */ } else if (sys == CHOLMOD_P) { /* ------------------------------------------------------------------ */ /* x = P*b */ /* ------------------------------------------------------------------ */ perm (B, Perm, 0, nrhs, X) ; } else if (sys == CHOLMOD_Pt) { /* ------------------------------------------------------------------ */ /* x = P'*b */ /* ------------------------------------------------------------------ */ iperm (B, Perm, 0, nrhs, X) ; } else if (L->is_super) { /* ------------------------------------------------------------------ */ /* solve using a supernodal LL' factorization */ /* ------------------------------------------------------------------ */ #ifndef NSUPERNODAL /* allocate workspace */ cholmod_dense *E ; Int dual ; Common->blas_ok = TRUE ; dual = (L->xtype == CHOLMOD_REAL && B->xtype != CHOLMOD_REAL) ? 2 : 1 ; Y = CHOLMOD(ensure_dense) (Y_Handle, n, dual*nrhs, n, L->xtype, Common); E = CHOLMOD(ensure_dense) (E_Handle, dual*nrhs, L->maxesize, dual*nrhs, L->xtype, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } perm (B, Perm, 0, nrhs, Y) ; /* Y = P*B */ if (sys == CHOLMOD_A || sys == CHOLMOD_LDLt) { CHOLMOD(super_lsolve) (L, Y, E, Common) ; /* Y = L\Y */ CHOLMOD(super_ltsolve) (L, Y, E, Common) ; /* Y = L'\Y*/ } else if (sys == CHOLMOD_L || sys == CHOLMOD_LD) { CHOLMOD(super_lsolve) (L, Y, E, Common) ; /* Y = L\Y */ } else if (sys == CHOLMOD_Lt || sys == CHOLMOD_DLt) { CHOLMOD(super_ltsolve) (L, Y, E, Common) ; /* Y = L'\Y*/ } iperm (Y, Perm, 0, nrhs, X) ; /* X = P'*Y */ if (CHECK_BLAS_INT && !Common->blas_ok) { /* Integer overflow in the BLAS. This is probably impossible, * since the BLAS were used to create the supernodal factorization. * It might be possible for the calls to the BLAS to differ between * factorization and forward/backsolves, however. This statement * is untested; it does not appear in the compiled code if * CHECK_BLAS_INT is true (when the same integer is used in * CHOLMOD and the BLAS. */ return (FALSE) ; } #else /* CHOLMOD Supernodal module not installed */ ERROR (CHOLMOD_NOT_INSTALLED,"Supernodal module not installed") ; #endif } else { /* ------------------------------------------------------------------ */ /* solve using a simplicial LL' or LDL' factorization */ /* ------------------------------------------------------------------ */ if (L->xtype == CHOLMOD_REAL && B->xtype == CHOLMOD_REAL) { /* L, B, and Y are all real */ /* solve with up to 4 columns of B at a time */ ncols = 4 ; nr = MAX (4, nrhs) ; ytype = CHOLMOD_REAL ; } else if (L->xtype == CHOLMOD_REAL) { /* L is real and B is complex or zomplex */ /* solve with one column of B (real/imag), at a time */ ncols = 1 ; nr = 2 ; ytype = CHOLMOD_REAL ; } else { /* L is complex or zomplex, B is real/complex/zomplex, Y has the * same complexity as L. Solve with one column of B at a time. */ ncols = 1 ; nr = 1 ; ytype = L->xtype ; } Y = CHOLMOD(ensure_dense) (Y_Handle, nr, n, nr, ytype, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } for (k1 = 0 ; k1 < nrhs ; k1 += ncols) { /* -------------------------------------------------------------- */ /* Y = B (P, k1:k1+ncols-1)' = (P * B (:,...))' */ /* -------------------------------------------------------------- */ ptrans (B, Perm, k1, ncols, Y) ; /* -------------------------------------------------------------- */ /* solve Y = (L' \ (L \ Y'))', or other system, with template */ /* -------------------------------------------------------------- */ switch (L->xtype) { case CHOLMOD_REAL: r_simplicial_solver (sys, L, Y, NULL, 0) ; break ; case CHOLMOD_COMPLEX: c_simplicial_solver (sys, L, Y, NULL, 0) ; break ; case CHOLMOD_ZOMPLEX: z_simplicial_solver (sys, L, Y, NULL, 0) ; break ; } /* -------------------------------------------------------------- */ /* X (P, k1:k2+ncols-1) = Y' */ /* -------------------------------------------------------------- */ iptrans (Y, Perm, k1, ncols, X) ; } } /* printf ("bye from solve2\n") ; */ DEBUG (CHOLMOD(dump_dense) (X, "X result", Common)) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/Cholesky/t_cholmod_ltsolve.c0000644000175100001440000005463313431000472021070 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/t_cholmod_ltsolve =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine to solve L'x=b with unit or non-unit diagonal, or * solve DL'x=b. * * The numeric xtype of L and Y must match. Y contains b on input and x on * output, stored in row-form. Y is nrow-by-n, where nrow must equal 1 for the * complex or zomplex cases, and nrow <= 4 for the real case. * * This file is not compiled separately. It is included in t_cholmod_solve.c * instead. It contains no user-callable routines. * * workspace: none * * Supports real, complex, and zomplex factors. */ /* undefine all prior definitions */ #undef FORM_NAME #undef LSOLVE #undef DIAG /* -------------------------------------------------------------------------- */ /* define the method */ /* -------------------------------------------------------------------------- */ #ifdef LL /* LL': solve Lx=b with non-unit diagonal */ #define FORM_NAME(prefix,rank) prefix ## ll_ltsolve_ ## rank #define DIAG #elif defined (LD) /* LDL': solve LDx=b */ #define FORM_NAME(prefix,rank) prefix ## ldl_dltsolve_ ## rank #define DIAG #else /* LDL': solve Lx=b with unit diagonal */ #define FORM_NAME(prefix,rank) prefix ## ldl_ltsolve_ ## rank #endif /* LSOLVE(k) defines the name of a routine for an n-by-k right-hand-side. */ #define LSOLVE(prefix,rank) FORM_NAME(prefix,rank) #ifdef REAL /* ========================================================================== */ /* === LSOLVE (1) =========================================================== */ /* ========================================================================== */ /* Solve L'x=b, where b has 1 column */ static void LSOLVE (PREFIX,1) ( cholmod_factor *L, double X [ ] /* n-by-1 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = n-1 ; j >= 0 ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j-1, and j-2) */ if (j < 4 || lnz != Lnz [j-1] - 1 || Li [Lp [j-1]+1] != j) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y = X [j] ; #ifdef DIAG double d = Lx [p] ; #endif #ifdef LD y /= d ; #endif for (p++ ; p < pend ; p++) { y -= Lx [p] * X [Li [p]] ; } #ifdef LL X [j] = y / d ; #else X [j] = y ; #endif j-- ; /* advance to the next column of L */ } else if (lnz != Lnz [j-2]-2 || Li [Lp [j-2]+2] != j) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2], t ; Int q = Lp [j-1] ; #ifdef DIAG double d [2] ; d [0] = Lx [p] ; d [1] = Lx [q] ; #endif t = Lx [q+1] ; #ifdef LD y [0] = X [j ] / d [0] ; y [1] = X [j-1] / d [1] ; #else y [0] = X [j ] ; y [1] = X [j-1] ; #endif for (p++, q += 2 ; p < pend ; p++, q++) { Int i = Li [p] ; y [0] -= Lx [p] * X [i] ; y [1] -= Lx [q] * X [i] ; } #ifdef LL y [0] /= d [0] ; y [1] = (y [1] - t * y [0]) / d [1] ; #else y [1] -= t * y [0] ; #endif X [j ] = y [0] ; X [j-1] = y [1] ; j -= 2 ; /* advance to the next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3], t [3] ; Int q = Lp [j-1] ; Int r = Lp [j-2] ; #ifdef DIAG double d [3] ; d [0] = Lx [p] ; d [1] = Lx [q] ; d [2] = Lx [r] ; #endif t [0] = Lx [q+1] ; t [1] = Lx [r+1] ; t [2] = Lx [r+2] ; #ifdef LD y [0] = X [j] / d [0] ; y [1] = X [j-1] / d [1] ; y [2] = X [j-2] / d [2] ; #else y [0] = X [j] ; y [1] = X [j-1] ; y [2] = X [j-2] ; #endif for (p++, q += 2, r += 3 ; p < pend ; p++, q++, r++) { Int i = Li [p] ; y [0] -= Lx [p] * X [i] ; y [1] -= Lx [q] * X [i] ; y [2] -= Lx [r] * X [i] ; } #ifdef LL y [0] /= d [0] ; y [1] = (y [1] - t [0] * y [0]) / d [1] ; y [2] = (y [2] - t [2] * y [0] - t [1] * y [1]) / d [2] ; #else y [1] -= t [0] * y [0] ; y [2] -= t [2] * y [0] + t [1] * y [1] ; #endif X [j-2] = y [2] ; X [j-1] = y [1] ; X [j ] = y [0] ; j -= 3 ; /* advance to the next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (2) =========================================================== */ /* ========================================================================== */ /* Solve L'x=b, where b has 2 columns */ static void LSOLVE (PREFIX,2) ( cholmod_factor *L, double X [ ][2] /* n-by-2 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = n-1 ; j >= 0 ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j-1, and j-2) */ if (j < 4 || lnz != Lnz [j-1] - 1 || Li [Lp [j-1]+1] != j) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [2] ; #ifdef DIAG double d = Lx [p] ; #endif #ifdef LD y [0] = X [j][0] / d ; y [1] = X [j][1] / d ; #else y [0] = X [j][0] ; y [1] = X [j][1] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; y [0] -= Lx [p] * X [i][0] ; y [1] -= Lx [p] * X [i][1] ; } #ifdef LL X [j][0] = y [0] / d ; X [j][1] = y [1] / d ; #else X [j][0] = y [0] ; X [j][1] = y [1] ; #endif j-- ; /* advance to the next column of L */ } else if (lnz != Lnz [j-2]-2 || Li [Lp [j-2]+2] != j) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][2], t ; Int q = Lp [j-1] ; #ifdef DIAG double d [2] ; d [0] = Lx [p] ; d [1] = Lx [q] ; #endif t = Lx [q+1] ; #ifdef LD y [0][0] = X [j ][0] / d [0] ; y [0][1] = X [j ][1] / d [0] ; y [1][0] = X [j-1][0] / d [1] ; y [1][1] = X [j-1][1] / d [1] ; #else y [0][0] = X [j ][0] ; y [0][1] = X [j ][1] ; y [1][0] = X [j-1][0] ; y [1][1] = X [j-1][1] ; #endif for (p++, q += 2 ; p < pend ; p++, q++) { Int i = Li [p] ; y [0][0] -= Lx [p] * X [i][0] ; y [0][1] -= Lx [p] * X [i][1] ; y [1][0] -= Lx [q] * X [i][0] ; y [1][1] -= Lx [q] * X [i][1] ; } #ifdef LL y [0][0] /= d [0] ; y [0][1] /= d [0] ; y [1][0] = (y [1][0] - t * y [0][0]) / d [1] ; y [1][1] = (y [1][1] - t * y [0][1]) / d [1] ; #else y [1][0] -= t * y [0][0] ; y [1][1] -= t * y [0][1] ; #endif X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j-1][0] = y [1][0] ; X [j-1][1] = y [1][1] ; j -= 2 ; /* advance to the next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3][2], t [3] ; Int q = Lp [j-1] ; Int r = Lp [j-2] ; #ifdef DIAG double d [3] ; d [0] = Lx [p] ; d [1] = Lx [q] ; d [2] = Lx [r] ; #endif t [0] = Lx [q+1] ; t [1] = Lx [r+1] ; t [2] = Lx [r+2] ; #ifdef LD y [0][0] = X [j ][0] / d [0] ; y [0][1] = X [j ][1] / d [0] ; y [1][0] = X [j-1][0] / d [1] ; y [1][1] = X [j-1][1] / d [1] ; y [2][0] = X [j-2][0] / d [2] ; y [2][1] = X [j-2][1] / d [2] ; #else y [0][0] = X [j ][0] ; y [0][1] = X [j ][1] ; y [1][0] = X [j-1][0] ; y [1][1] = X [j-1][1] ; y [2][0] = X [j-2][0] ; y [2][1] = X [j-2][1] ; #endif for (p++, q += 2, r += 3 ; p < pend ; p++, q++, r++) { Int i = Li [p] ; y [0][0] -= Lx [p] * X [i][0] ; y [0][1] -= Lx [p] * X [i][1] ; y [1][0] -= Lx [q] * X [i][0] ; y [1][1] -= Lx [q] * X [i][1] ; y [2][0] -= Lx [r] * X [i][0] ; y [2][1] -= Lx [r] * X [i][1] ; } #ifdef LL y [0][0] /= d [0] ; y [0][1] /= d [0] ; y [1][0] = (y [1][0] - t [0] * y [0][0]) / d [1] ; y [1][1] = (y [1][1] - t [0] * y [0][1]) / d [1] ; y [2][0] = (y [2][0] - t [2] * y [0][0] - t [1] * y [1][0]) / d [2]; y [2][1] = (y [2][1] - t [2] * y [0][1] - t [1] * y [1][1]) / d [2]; #else y [1][0] -= t [0] * y [0][0] ; y [1][1] -= t [0] * y [0][1] ; y [2][0] -= t [2] * y [0][0] + t [1] * y [1][0] ; y [2][1] -= t [2] * y [0][1] + t [1] * y [1][1] ; #endif X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j-1][0] = y [1][0] ; X [j-1][1] = y [1][1] ; X [j-2][0] = y [2][0] ; X [j-2][1] = y [2][1] ; j -= 3 ; /* advance to the next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (3) =========================================================== */ /* ========================================================================== */ /* Solve L'x=b, where b has 3 columns */ static void LSOLVE (PREFIX,3) ( cholmod_factor *L, double X [ ][3] /* n-by-3 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = n-1 ; j >= 0 ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j-1, and j-2) */ if (j < 4 || lnz != Lnz [j-1] - 1 || Li [Lp [j-1]+1] != j) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [3] ; #ifdef DIAG double d = Lx [p] ; #endif #ifdef LD y [0] = X [j][0] / d ; y [1] = X [j][1] / d ; y [2] = X [j][2] / d ; #else y [0] = X [j][0] ; y [1] = X [j][1] ; y [2] = X [j][2] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; y [0] -= Lx [p] * X [i][0] ; y [1] -= Lx [p] * X [i][1] ; y [2] -= Lx [p] * X [i][2] ; } #ifdef LL X [j][0] = y [0] / d ; X [j][1] = y [1] / d ; X [j][2] = y [2] / d ; #else X [j][0] = y [0] ; X [j][1] = y [1] ; X [j][2] = y [2] ; #endif j-- ; /* advance to the next column of L */ } else if (lnz != Lnz [j-2]-2 || Li [Lp [j-2]+2] != j) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][3], t ; Int q = Lp [j-1] ; #ifdef DIAG double d [2] ; d [0] = Lx [p] ; d [1] = Lx [q] ; #endif t = Lx [q+1] ; #ifdef LD y [0][0] = X [j ][0] / d [0] ; y [0][1] = X [j ][1] / d [0] ; y [0][2] = X [j ][2] / d [0] ; y [1][0] = X [j-1][0] / d [1] ; y [1][1] = X [j-1][1] / d [1] ; y [1][2] = X [j-1][2] / d [1] ; #else y [0][0] = X [j ][0] ; y [0][1] = X [j ][1] ; y [0][2] = X [j ][2] ; y [1][0] = X [j-1][0] ; y [1][1] = X [j-1][1] ; y [1][2] = X [j-1][2] ; #endif for (p++, q += 2 ; p < pend ; p++, q++) { Int i = Li [p] ; y [0][0] -= Lx [p] * X [i][0] ; y [0][1] -= Lx [p] * X [i][1] ; y [0][2] -= Lx [p] * X [i][2] ; y [1][0] -= Lx [q] * X [i][0] ; y [1][1] -= Lx [q] * X [i][1] ; y [1][2] -= Lx [q] * X [i][2] ; } #ifdef LL y [0][0] /= d [0] ; y [0][1] /= d [0] ; y [0][2] /= d [0] ; y [1][0] = (y [1][0] - t * y [0][0]) / d [1] ; y [1][1] = (y [1][1] - t * y [0][1]) / d [1] ; y [1][2] = (y [1][2] - t * y [0][2]) / d [1] ; #else y [1][0] -= t * y [0][0] ; y [1][1] -= t * y [0][1] ; y [1][2] -= t * y [0][2] ; #endif X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j-1][0] = y [1][0] ; X [j-1][1] = y [1][1] ; X [j-1][2] = y [1][2] ; j -= 2 ; /* advance to the next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3][3], t [3] ; Int q = Lp [j-1] ; Int r = Lp [j-2] ; #ifdef DIAG double d [3] ; d [0] = Lx [p] ; d [1] = Lx [q] ; d [2] = Lx [r] ; #endif t [0] = Lx [q+1] ; t [1] = Lx [r+1] ; t [2] = Lx [r+2] ; #ifdef LD y [0][0] = X [j ][0] / d [0] ; y [0][1] = X [j ][1] / d [0] ; y [0][2] = X [j ][2] / d [0] ; y [1][0] = X [j-1][0] / d [1] ; y [1][1] = X [j-1][1] / d [1] ; y [1][2] = X [j-1][2] / d [1] ; y [2][0] = X [j-2][0] / d [2] ; y [2][1] = X [j-2][1] / d [2] ; y [2][2] = X [j-2][2] / d [2] ; #else y [0][0] = X [j ][0] ; y [0][1] = X [j ][1] ; y [0][2] = X [j ][2] ; y [1][0] = X [j-1][0] ; y [1][1] = X [j-1][1] ; y [1][2] = X [j-1][2] ; y [2][0] = X [j-2][0] ; y [2][1] = X [j-2][1] ; y [2][2] = X [j-2][2] ; #endif for (p++, q += 2, r += 3 ; p < pend ; p++, q++, r++) { Int i = Li [p] ; y [0][0] -= Lx [p] * X [i][0] ; y [0][1] -= Lx [p] * X [i][1] ; y [0][2] -= Lx [p] * X [i][2] ; y [1][0] -= Lx [q] * X [i][0] ; y [1][1] -= Lx [q] * X [i][1] ; y [1][2] -= Lx [q] * X [i][2] ; y [2][0] -= Lx [r] * X [i][0] ; y [2][1] -= Lx [r] * X [i][1] ; y [2][2] -= Lx [r] * X [i][2] ; } #ifdef LL y [0][0] /= d [0] ; y [0][1] /= d [0] ; y [0][2] /= d [0] ; y [1][0] = (y [1][0] - t [0] * y [0][0]) / d [1] ; y [1][1] = (y [1][1] - t [0] * y [0][1]) / d [1] ; y [1][2] = (y [1][2] - t [0] * y [0][2]) / d [1] ; y [2][0] = (y [2][0] - t [2] * y [0][0] - t [1] * y [1][0]) / d [2]; y [2][1] = (y [2][1] - t [2] * y [0][1] - t [1] * y [1][1]) / d [2]; y [2][2] = (y [2][2] - t [2] * y [0][2] - t [1] * y [1][2]) / d [2]; #else y [1][0] -= t [0] * y [0][0] ; y [1][1] -= t [0] * y [0][1] ; y [1][2] -= t [0] * y [0][2] ; y [2][0] -= t [2] * y [0][0] + t [1] * y [1][0] ; y [2][1] -= t [2] * y [0][1] + t [1] * y [1][1] ; y [2][2] -= t [2] * y [0][2] + t [1] * y [1][2] ; #endif X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j-1][0] = y [1][0] ; X [j-1][1] = y [1][1] ; X [j-1][2] = y [1][2] ; X [j-2][0] = y [2][0] ; X [j-2][1] = y [2][1] ; X [j-2][2] = y [2][2] ; j -= 3 ; /* advance to the next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (4) =========================================================== */ /* ========================================================================== */ /* Solve L'x=b, where b has 4 columns */ static void LSOLVE (PREFIX,4) ( cholmod_factor *L, double X [ ][4] /* n-by-4 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = n-1 ; j >= 0 ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j-1, and j-2) */ if (j < 4 || lnz != Lnz [j-1] - 1 || Li [Lp [j-1]+1] != j) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [4] ; #ifdef DIAG double d = Lx [p] ; #endif #ifdef LD y [0] = X [j][0] / d ; y [1] = X [j][1] / d ; y [2] = X [j][2] / d ; y [3] = X [j][3] / d ; #else y [0] = X [j][0] ; y [1] = X [j][1] ; y [2] = X [j][2] ; y [3] = X [j][3] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; y [0] -= Lx [p] * X [i][0] ; y [1] -= Lx [p] * X [i][1] ; y [2] -= Lx [p] * X [i][2] ; y [3] -= Lx [p] * X [i][3] ; } #ifdef LL X [j][0] = y [0] / d ; X [j][1] = y [1] / d ; X [j][2] = y [2] / d ; X [j][3] = y [3] / d ; #else X [j][0] = y [0] ; X [j][1] = y [1] ; X [j][2] = y [2] ; X [j][3] = y [3] ; #endif j-- ; /* advance to the next column of L */ } else /* if (j == 1 || lnz != Lnz [j-2]-2 || Li [Lp [j-2]+2] != j) */ { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][4], t ; Int q = Lp [j-1] ; #ifdef DIAG double d [2] ; d [0] = Lx [p] ; d [1] = Lx [q] ; #endif t = Lx [q+1] ; #ifdef LD y [0][0] = X [j ][0] / d [0] ; y [0][1] = X [j ][1] / d [0] ; y [0][2] = X [j ][2] / d [0] ; y [0][3] = X [j ][3] / d [0] ; y [1][0] = X [j-1][0] / d [1] ; y [1][1] = X [j-1][1] / d [1] ; y [1][2] = X [j-1][2] / d [1] ; y [1][3] = X [j-1][3] / d [1] ; #else y [0][0] = X [j ][0] ; y [0][1] = X [j ][1] ; y [0][2] = X [j ][2] ; y [0][3] = X [j ][3] ; y [1][0] = X [j-1][0] ; y [1][1] = X [j-1][1] ; y [1][2] = X [j-1][2] ; y [1][3] = X [j-1][3] ; #endif for (p++, q += 2 ; p < pend ; p++, q++) { Int i = Li [p] ; y [0][0] -= Lx [p] * X [i][0] ; y [0][1] -= Lx [p] * X [i][1] ; y [0][2] -= Lx [p] * X [i][2] ; y [0][3] -= Lx [p] * X [i][3] ; y [1][0] -= Lx [q] * X [i][0] ; y [1][1] -= Lx [q] * X [i][1] ; y [1][2] -= Lx [q] * X [i][2] ; y [1][3] -= Lx [q] * X [i][3] ; } #ifdef LL y [0][0] /= d [0] ; y [0][1] /= d [0] ; y [0][2] /= d [0] ; y [0][3] /= d [0] ; y [1][0] = (y [1][0] - t * y [0][0]) / d [1] ; y [1][1] = (y [1][1] - t * y [0][1]) / d [1] ; y [1][2] = (y [1][2] - t * y [0][2]) / d [1] ; y [1][3] = (y [1][3] - t * y [0][3]) / d [1] ; #else y [1][0] -= t * y [0][0] ; y [1][1] -= t * y [0][1] ; y [1][2] -= t * y [0][2] ; y [1][3] -= t * y [0][3] ; #endif X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j ][3] = y [0][3] ; X [j-1][0] = y [1][0] ; X [j-1][1] = y [1][1] ; X [j-1][2] = y [1][2] ; X [j-1][3] = y [1][3] ; j -= 2 ; /* advance to the next column of L */ } /* NOTE: with 4 right-hand-sides, it suffices to exploit dynamic * supernodes of just size 1 and 2. 3-column supernodes are not * needed. */ } } #endif /* ========================================================================== */ /* === LSOLVE (k) =========================================================== */ /* ========================================================================== */ static void LSOLVE (PREFIX,k) ( cholmod_factor *L, cholmod_dense *Y, /* nr-by-n where nr is 1 to 4 */ Int *Yseti, Int ysetlen ) { #ifdef DIAG double d [1] ; #endif double yx [2] ; #ifdef ZOMPLEX double yz [1] ; double *Lz = L->z ; double *Xz = Y->z ; #endif double *Lx = L->x ; double *Xx = Y->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int n = L->n, jj, jjiters ; ASSERT (L->xtype == Y->xtype) ; /* L and Y must have the same xtype */ ASSERT (L->n == Y->ncol) ; /* dimensions must match */ ASSERT (Y->nrow == Y->d) ; /* leading dimension of Y = # rows of Y */ ASSERT (L->xtype != CHOLMOD_PATTERN) ; /* L is not symbolic */ ASSERT (!(L->is_super)) ; /* L is simplicial LL' or LDL' */ #ifdef REAL if (Yseti == NULL) { /* ------------------------------------------------------------------ */ /* real case, no Yseti, with 1 to 4 RHS's and dynamic supernodes */ /* ------------------------------------------------------------------ */ ASSERT (Y->nrow <= 4) ; switch (Y->nrow) { case 1: LSOLVE (PREFIX,1) (L, Y->x) ; break ; case 2: LSOLVE (PREFIX,2) (L, Y->x) ; break ; case 3: LSOLVE (PREFIX,3) (L, Y->x) ; break ; case 4: LSOLVE (PREFIX,4) (L, Y->x) ; break ; } } else #endif { /* ------------------------------------------------------------------ */ /* solve a complex linear system or solve with Yseti */ /* ------------------------------------------------------------------ */ ASSERT (Y->nrow == 1) ; jjiters = Yseti ? ysetlen : n ; for (jj = jjiters-1 ; jj >= 0 ; jj--) { Int j = Yseti ? Yseti [jj] : jj ; /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* y = X [j] ; */ ASSIGN (yx,yz,0, Xx,Xz,j) ; #ifdef DIAG /* d = Lx [p] ; */ ASSIGN_REAL (d,0, Lx,p) ; #endif #ifdef LD /* y /= d ; */ DIV_REAL (yx,yz,0, yx,yz,0, d,0) ; #endif for (p++ ; p < pend ; p++) { /* y -= conj (Lx [p]) * X [Li [p]] ; */ Int i = Li [p] ; MULTSUBCONJ (yx,yz,0, Lx,Lz,p, Xx,Xz,i) ; } #ifdef LL /* X [j] = y / d ; */ DIV_REAL (Xx,Xz,j, yx,yz,0, d,0) ; #else /* X [j] = y ; */ ASSIGN (Xx,Xz,j, yx,yz,0) ; #endif } } } /* prepare for the next inclusion of this file in cholmod_solve.c */ #undef LL #undef LD igraph/src/CHOLMOD/Cholesky/cholmod_etree.c0000644000175100001440000001577013431000472020160 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_etree =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Compute the elimination tree of A or A'*A * * In the symmetric case, the upper triangular part of A is used. Entries not * in this part of the matrix are ignored. Computing the etree of a symmetric * matrix from just its lower triangular entries is not supported. * * In the unsymmetric case, all of A is used, and the etree of A'*A is computed. * * References: * * J. Liu, "A compact row storage scheme for Cholesky factors", ACM Trans. * Math. Software, vol 12, 1986, pp. 127-148. * * J. Liu, "The role of elimination trees in sparse factorization", SIAM J. * Matrix Analysis & Applic., vol 11, 1990, pp. 134-172. * * J. Gilbert, X. Li, E. Ng, B. Peyton, "Computing row and column counts for * sparse QR and LU factorization", BIT, vol 41, 2001, pp. 693-710. * * workspace: symmetric: Iwork (nrow), unsymmetric: Iwork (nrow+ncol) * * Supports any xtype (pattern, real, complex, or zomplex) */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === update_etree ========================================================= */ /* ========================================================================== */ static void update_etree ( /* inputs, not modified */ Int k, /* process the edge (k,i) in the input graph */ Int i, /* inputs, modified on output */ Int Parent [ ], /* Parent [t] = p if p is the parent of t */ Int Ancestor [ ] /* Ancestor [t] is the ancestor of node t in the partially-constructed etree */ ) { Int a ; for ( ; ; ) /* traverse the path from k to the root of the tree */ { a = Ancestor [k] ; if (a == i) { /* final ancestor reached; no change to tree */ return ; } /* perform path compression */ Ancestor [k] = i ; if (a == EMPTY) { /* final ancestor undefined; this is a new edge in the tree */ Parent [k] = i ; return ; } /* traverse up to the ancestor of k */ k = a ; } } /* ========================================================================== */ /* === cholmod_etree ======================================================== */ /* ========================================================================== */ /* Find the elimination tree of A or A'*A */ int CHOLMOD(etree) ( /* ---- input ---- */ cholmod_sparse *A, /* ---- output --- */ Int *Parent, /* size ncol. Parent [j] = p if p is the parent of j */ /* --------------- */ cholmod_common *Common ) { Int *Ap, *Ai, *Anz, *Ancestor, *Prev, *Iwork ; Int i, j, jprev, p, pend, nrow, ncol, packed, stype ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ stype = A->stype ; /* s = A->nrow + (stype ? 0 : A->ncol) */ s = CHOLMOD(add_size_t) (A->nrow, (stype ? 0 : A->ncol), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } ASSERT (CHOLMOD(dump_sparse) (A, "etree", Common) >= 0) ; Iwork = Common->Iwork ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ ncol = A->ncol ; /* the number of columns of A */ nrow = A->nrow ; /* the number of rows of A */ Ap = A->p ; /* size ncol+1, column pointers for A */ Ai = A->i ; /* the row indices of A */ Anz = A->nz ; /* number of nonzeros in each column of A */ packed = A->packed ; Ancestor = Iwork ; /* size ncol (i/i/l) */ for (j = 0 ; j < ncol ; j++) { Parent [j] = EMPTY ; Ancestor [j] = EMPTY ; } /* ---------------------------------------------------------------------- */ /* compute the etree */ /* ---------------------------------------------------------------------- */ if (stype > 0) { /* ------------------------------------------------------------------ */ /* symmetric (upper) case: compute etree (A) */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { /* for each row i in column j of triu(A), excluding the diagonal */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i < j) { update_etree (i, j, Parent, Ancestor) ; } } } } else if (stype == 0) { /* ------------------------------------------------------------------ */ /* unsymmetric case: compute etree (A'*A) */ /* ------------------------------------------------------------------ */ Prev = Iwork + ncol ; /* size nrow (i/i/l) */ for (i = 0 ; i < nrow ; i++) { Prev [i] = EMPTY ; } for (j = 0 ; j < ncol ; j++) { /* for each row i in column j of A */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* a graph is constructed dynamically with one path per row * of A. If the ith row of A contains column indices * (j1,j2,j3,j4) then the new graph has edges (j1,j2), (j2,j3), * and (j3,j4). When at node i of this path-graph, all edges * (jprev,j) are considered, where jprevxtype == Y->xtype) ; /* L and Y must have the same xtype */ ASSERT (L->n == Y->ncol) ; /* dimensions must match */ ASSERT (Y->nrow == Y->d) ; /* leading dimension of Y = # rows of Y */ ASSERT (L->xtype != CHOLMOD_PATTERN) ; /* L is not symbolic */ ASSERT (!(L->is_super) && !(L->is_ll)) ; /* L is simplicial LDL' */ nrhs = Y->nrow ; n = L->n ; Lp = L->p ; Lx = L->x ; Yx = Y->x ; Yz = Y->z ; kkiters = Yseti ? ysetlen : n ; for (kk = 0 ; kk < kkiters ; kk++) { k = Yseti ? Yseti [kk] : kk ; k1 = k*nrhs ; k2 = (k+1)*nrhs ; ASSIGN_REAL (d,0, Lx,Lp[k]) ; for (p = k1 ; p < k2 ; p++) { DIV_REAL (Yx,Yz,p, Yx,Yz,p, d,0) ; } } } /* ========================================================================== */ /* === t_simplicial_solver ================================================== */ /* ========================================================================== */ /* Solve a linear system, where Y' contains the (array-transposed) right-hand * side on input, and the solution on output. No permutations are applied; * these must have already been applied to Y on input. * * Yseti [0..ysetlen-1] is an optional list of indices from * cholmod_lsolve_pattern. The solve is performed only on the columns of L * corresponding to entries in Yseti. Ignored if NULL. If present, most * functions require that Y' consist of a single dense column. */ static void TEMPLATE (simplicial_solver) ( int sys, /* system to solve */ cholmod_factor *L, /* factor to use, a simplicial LL' or LDL' */ cholmod_dense *Y, /* right-hand-side on input, solution on output */ Int *Yseti, Int ysetlen ) { if (L->is_ll) { /* The factorization is LL' */ if (sys == CHOLMOD_A || sys == CHOLMOD_LDLt) { /* Solve Ax=b or LL'x=b */ TEMPLATE (ll_lsolve_k) (L, Y, Yseti, ysetlen) ; TEMPLATE (ll_ltsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_L || sys == CHOLMOD_LD) { /* Solve Lx=b */ TEMPLATE (ll_lsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_Lt || sys == CHOLMOD_DLt) { /* Solve L'x=b */ TEMPLATE (ll_ltsolve_k) (L, Y, Yseti, ysetlen) ; } } else { /* The factorization is LDL' */ if (sys == CHOLMOD_A || sys == CHOLMOD_LDLt) { /* Solve Ax=b or LDL'x=b */ TEMPLATE (ldl_lsolve_k) (L, Y, Yseti, ysetlen) ; TEMPLATE (ldl_dltsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_LD) { /* Solve LDx=b */ TEMPLATE (ldl_ldsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_L) { /* Solve Lx=b */ TEMPLATE (ldl_lsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_Lt) { /* Solve L'x=b */ TEMPLATE (ldl_ltsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_DLt) { /* Solve DL'x=b */ TEMPLATE (ldl_dltsolve_k) (L, Y, Yseti, ysetlen) ; } else if (sys == CHOLMOD_D) { /* Solve Dx=b */ TEMPLATE (ldl_dsolve) (L, Y, Yseti, ysetlen) ; } } } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Cholesky/t_cholmod_rowfac.c0000644000175100001440000003227013431000472020652 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/t_cholmod_rowfac ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine for cholmod_rowfac. Supports any numeric xtype * (real, complex, or zomplex). * * workspace: Iwork (n), Flag (n), Xwork (n if real, 2*n if complex) */ #include "cholmod_template.h" #ifdef MASK static int TEMPLATE (cholmod_rowfac_mask) #else static int TEMPLATE (cholmod_rowfac) #endif ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,f)' */ double beta [2], /* factorize beta*I+A or beta*I+AA' (beta [0] only) */ size_t kstart, /* first row to factorize */ size_t kend, /* last row to factorize is kend-1 */ #ifdef MASK /* These inputs are used for cholmod_rowfac_mask only */ Int *mask, /* size A->nrow. if mask[i] then W(i) is set to zero */ Int *RLinkUp, /* size A->nrow. link list of rows to compute */ #endif /* ---- in/out --- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) { double yx [2], lx [2], fx [2], dk [1], di [1], fl = 0 ; #ifdef ZOMPLEX double yz [1], lz [1], fz [1] ; #endif double *Ax, *Az, *Lx, *Lz, *Wx, *Wz, *Fx, *Fz ; Int *Ap, *Anz, *Ai, *Lp, *Lnz, *Li, *Lnext, *Flag, *Stack, *Fp, *Fi, *Fnz, *Iwork ; Int i, p, k, t, pf, pfend, top, s, mark, pend, n, lnz, is_ll, multadds, use_dbound, packed, stype, Fpacked, sorted, nzmax, len, parent ; #ifndef REAL Int dk_imaginary ; #endif /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ PRINT1 (("\nin cholmod_rowfac, kstart %d kend %d stype %d\n", kstart, kend, A->stype)) ; DEBUG (CHOLMOD(dump_factor) (L, "Initial L", Common)) ; n = A->nrow ; stype = A->stype ; if (stype > 0) { /* symmetric upper case: F is not needed. It may be NULL */ Fp = NULL ; Fi = NULL ; Fx = NULL ; Fz = NULL ; Fnz = NULL ; Fpacked = TRUE ; } else { /* unsymmetric case: F is required. */ Fp = F->p ; Fi = F->i ; Fx = F->x ; Fz = F->z ; Fnz = F->nz ; Fpacked = F->packed ; } Ap = A->p ; /* size A->ncol+1, column pointers of A */ Ai = A->i ; /* size nz = Ap [A->ncol], row indices of A */ Ax = A->x ; /* size nz, numeric values of A */ Az = A->z ; Anz = A->nz ; packed = A->packed ; sorted = A->sorted ; use_dbound = IS_GT_ZERO (Common->dbound) ; /* get the current factors L (and D for LDL'); allocate space if needed */ is_ll = L->is_ll ; if (L->xtype == CHOLMOD_PATTERN) { /* ------------------------------------------------------------------ */ /* L is symbolic only; allocate and initialize L (and D for LDL') */ /* ------------------------------------------------------------------ */ /* workspace: none */ CHOLMOD(change_factor) (A->xtype, is_ll, FALSE, FALSE, TRUE, L, Common); if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } ASSERT (L->minor == (size_t) n) ; } else if (kstart == 0 && kend == (size_t) n) { /* ------------------------------------------------------------------ */ /* refactorization; reset L->nz and L->minor to restart factorization */ /* ------------------------------------------------------------------ */ L->minor = n ; Lnz = L->nz ; for (k = 0 ; k < n ; k++) { Lnz [k] = 1 ; } } ASSERT (is_ll == L->is_ll) ; ASSERT (L->xtype != CHOLMOD_PATTERN) ; DEBUG (CHOLMOD(dump_factor) (L, "L ready", Common)) ; DEBUG (CHOLMOD(dump_sparse) (A, "A ready", Common)) ; DEBUG (if (stype == 0) CHOLMOD(dump_sparse) (F, "F ready", Common)) ; /* inputs, can be modified on output: */ Lp = L->p ; /* size n+1 */ ASSERT (Lp != NULL) ; /* outputs, contents defined on input for incremental case only: */ Lnz = L->nz ; /* size n */ Lnext = L->next ; /* size n+2 */ Li = L->i ; /* size L->nzmax, can change in size */ Lx = L->x ; /* size L->nzmax or 2*L->nzmax, can change in size */ Lz = L->z ; /* size L->nzmax for zomplex case, can change in size */ nzmax = L->nzmax ; ASSERT (Lnz != NULL && Li != NULL && Lx != NULL) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Stack = Iwork ; /* size n (i/i/l) */ Flag = Common->Flag ; /* size n, Flag [i] < mark must hold */ Wx = Common->Xwork ; /* size n if real, 2*n if complex or * zomplex. Xwork [i] == 0 must hold. */ Wz = Wx + n ; /* size n for zomplex case only */ mark = Common->mark ; ASSERT ((Int) Common->xworksize >= (L->xtype == CHOLMOD_REAL ? 1:2)*n) ; /* ---------------------------------------------------------------------- */ /* compute LDL' or LL' factorization by rows */ /* ---------------------------------------------------------------------- */ #ifdef MASK #define NEXT(k) k = RLinkUp [k] #else #define NEXT(k) k++ #endif for (k = kstart ; k < ((Int) kend) ; NEXT(k)) { PRINT1 (("\n===============K "ID" Lnz [k] "ID"\n", k, Lnz [k])) ; /* ------------------------------------------------------------------ */ /* compute pattern of kth row of L and scatter kth input column */ /* ------------------------------------------------------------------ */ /* column k of L is currently empty */ ASSERT (Lnz [k] == 1) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 2*n, Common)) ; top = n ; /* Stack is empty */ Flag [k] = mark ; /* do not include diagonal entry in Stack */ /* use Li [Lp [i]+1] for etree */ #define PARENT(i) (Lnz [i] > 1) ? (Li [Lp [i] + 1]) : EMPTY if (stype > 0) { /* scatter kth col of triu (beta*I+AA'), get pattern L(k,:) */ p = Ap [k] ; pend = (packed) ? (Ap [k+1]) : (p + Anz [k]) ; /* W [i] = Ax [i] ; scatter column of A */ #define SCATTER ASSIGN(Wx,Wz,i, Ax,Az,p) SUBTREE ; #undef SCATTER } else { /* scatter kth col of triu (beta*I+AA'), get pattern L(k,:) */ pf = Fp [k] ; pfend = (Fpacked) ? (Fp [k+1]) : (pf + Fnz [k]) ; for ( ; pf < pfend ; pf++) { /* get nonzero entry F (t,k) */ t = Fi [pf] ; /* fk = Fx [pf] */ ASSIGN (fx, fz, 0, Fx, Fz, pf) ; p = Ap [t] ; pend = (packed) ? (Ap [t+1]) : (p + Anz [t]) ; multadds = 0 ; /* W [i] += Ax [p] * fx ; scatter column of A*A' */ #define SCATTER MULTADD (Wx,Wz,i, Ax,Az,p, fx,fz,0) ; multadds++ ; SUBTREE ; #undef SCATTER #ifdef REAL fl += 2 * ((double) multadds) ; #else fl += 8 * ((double) multadds) ; #endif } } #undef PARENT /* ------------------------------------------------------------------ */ /* if mask is present, set the corresponding entries in W to zero */ /* ------------------------------------------------------------------ */ #ifdef MASK /* remove the dead element of Wx */ if (mask != NULL) { #if 0 /* older version */ for (p = n; p > top;) { i = Stack [--p] ; if ( mask [i] >= 0 ) { CLEAR (Wx,Wz,i) ; /* set W(i) to zero */ } } #endif for (s = top ; s < n ; s++) { i = Stack [s] ; if (mask [i] >= 0) { CLEAR (Wx,Wz,i) ; /* set W(i) to zero */ } } } #endif /* nonzero pattern of kth row of L is now in Stack [top..n-1]. * Flag [Stack [top..n-1]] is equal to mark, but no longer needed */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* ------------------------------------------------------------------ */ /* compute kth row of L and store in column form */ /* ------------------------------------------------------------------ */ /* Solve L (0:k-1, 0:k-1) * y (0:k-1) = b (0:k-1) where * b (0:k) = A (0:k,k) or A(0:k,:) * F(:,k) is in W and Stack. * * For LDL' factorization: * L (k, 0:k-1) = y (0:k-1) ./ D (0:k-1) * D (k) = b (k) - L (k, 0:k-1) * y (0:k-1) * * For LL' factorization: * L (k, 0:k-1) = y (0:k-1) * L (k,k) = sqrt (b (k) - L (k, 0:k-1) * L (0:k-1, k)) */ /* dk = W [k] + beta */ ADD_REAL (dk,0, Wx,k, beta,0) ; #ifndef REAL /* In the unsymmetric case, the imaginary part of W[k] must be real, * since F is assumed to be the complex conjugate transpose of A. In * the symmetric case, W[k] is the diagonal of A. If the imaginary part * of W[k] is nonzero, then the Cholesky factorization cannot be * computed; A is not positive definite */ dk_imaginary = (stype > 0) ? (IMAG_IS_NONZERO (Wx,Wz,k)) : FALSE ; #endif /* W [k] = 0.0 ; */ CLEAR (Wx,Wz,k) ; for (s = top ; s < n ; s++) { /* get i for each nonzero entry L(k,i) */ i = Stack [s] ; /* y = W [i] ; */ ASSIGN (yx,yz,0, Wx,Wz,i) ; /* W [i] = 0.0 ; */ CLEAR (Wx,Wz,i) ; lnz = Lnz [i] ; p = Lp [i] ; ASSERT (lnz > 0 && Li [p] == i) ; pend = p + lnz ; /* di = Lx [p] ; the diagonal entry L or D(i,i), which is real */ ASSIGN_REAL (di,0, Lx,p) ; if (i >= (Int) L->minor || IS_ZERO (di [0])) { /* For the LL' factorization, L(i,i) is zero. For the LDL', * D(i,i) is zero. Skip column i of L, and set L(k,i) = 0. */ CLEAR (lx,lz,0) ; p = pend ; } else if (is_ll) { #ifdef REAL fl += 2 * ((double) (pend - p - 1)) + 3 ; #else fl += 8 * ((double) (pend - p - 1)) + 6 ; #endif /* forward solve using L (i:(k-1),i) */ /* divide by L(i,i), which must be real and nonzero */ /* y /= di [0] */ DIV_REAL (yx,yz,0, yx,yz,0, di,0) ; for (p++ ; p < pend ; p++) { /* W [Li [p]] -= Lx [p] * y ; */ MULTSUB (Wx,Wz,Li[p], Lx,Lz,p, yx,yz,0) ; } /* do not scale L; compute dot product for L(k,k) */ /* L(k,i) = conj(y) ; */ ASSIGN_CONJ (lx,lz,0, yx,yz,0) ; /* d -= conj(y) * y ; */ LLDOT (dk,0, yx,yz,0) ; } else { #ifdef REAL fl += 2 * ((double) (pend - p - 1)) + 3 ; #else fl += 8 * ((double) (pend - p - 1)) + 6 ; #endif /* forward solve using D (i,i) and L ((i+1):(k-1),i) */ for (p++ ; p < pend ; p++) { /* W [Li [p]] -= Lx [p] * y ; */ MULTSUB (Wx,Wz,Li[p], Lx,Lz,p, yx,yz,0) ; } /* Scale L (k,0:k-1) for LDL' factorization, compute D (k,k)*/ #ifdef REAL /* L(k,i) = y/d */ lx [0] = yx [0] / di [0] ; /* d -= L(k,i) * y */ dk [0] -= lx [0] * yx [0] ; #else /* L(k,i) = conj(y) ; */ ASSIGN_CONJ (lx,lz,0, yx,yz,0) ; /* L(k,i) /= di ; */ DIV_REAL (lx,lz,0, lx,lz,0, di,0) ; /* d -= conj(y) * y / di */ LDLDOT (dk,0, yx,yz,0, di,0) ; #endif } /* determine if column i of L can hold the new L(k,i) entry */ if (p >= Lp [Lnext [i]]) { /* column i needs to grow */ PRINT1 (("Factor Colrealloc "ID", old Lnz "ID"\n", i, Lnz [i])); if (!CHOLMOD(reallocate_column) (i, lnz + 1, L, Common)) { /* out of memory, L is now simplicial symbolic */ for (i = 0 ; i < n ; i++) { /* W [i] = 0 ; */ CLEAR (Wx,Wz,i) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, n, Common)) ; return (FALSE) ; } Li = L->i ; /* L->i, L->x, L->z may have moved */ Lx = L->x ; Lz = L->z ; p = Lp [i] + lnz ; /* contents of L->p changed */ ASSERT (p < Lp [Lnext [i]]) ; } /* store L (k,i) in the column form matrix of L */ Li [p] = k ; /* Lx [p] = L(k,i) ; */ ASSIGN (Lx,Lz,p, lx,lz,0) ; Lnz [i]++ ; } /* ------------------------------------------------------------------ */ /* ensure abs (d) >= dbound if dbound is given, and store it in L */ /* ------------------------------------------------------------------ */ p = Lp [k] ; Li [p] = k ; if (k >= (Int) L->minor) { /* the matrix is already not positive definite */ dk [0] = 0 ; } else if (use_dbound) { /* modify the diagonal to force LL' or LDL' to exist */ dk [0] = CHOLMOD(dbound) (is_ll ? fabs (dk [0]) : dk [0], Common) ; } else if ((is_ll ? (IS_LE_ZERO (dk [0])) : (IS_ZERO (dk [0]))) #ifndef REAL || dk_imaginary #endif ) { /* the matrix has just been found to be not positive definite */ dk [0] = 0 ; L->minor = k ; ERROR (CHOLMOD_NOT_POSDEF, "not positive definite") ; } if (is_ll) { /* this is counted as one flop, below */ dk [0] = sqrt (dk [0]) ; } /* Lx [p] = D(k,k) = d ; real part only */ ASSIGN_REAL (Lx,p, dk,0) ; CLEAR_IMAG (Lx,Lz,p) ; } #undef NEXT if (is_ll) fl += MAX ((Int) kend - (Int) kstart, 0) ; /* count sqrt's */ Common->rowfacfl = fl ; DEBUG (CHOLMOD(dump_factor) (L, "final cholmod_rowfac", Common)) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, n, Common)) ; return (TRUE) ; } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Cholesky/lesser.txt0000644000175100001440000006350013430770172017245 0ustar hornikusers GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! igraph/src/CHOLMOD/Cholesky/cholmod_rowcolcounts.c0000644000175100001440000004365613431000472021621 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_rowcolcounts ======================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Compute the row and column counts of the Cholesky factor L of the matrix * A or A*A'. The etree and its postordering must already be computed (see * cholmod_etree and cholmod_postorder) and given as inputs to this routine. * * For the symmetric case (LL'=A), A is accessed by column. Only the lower * triangular part of A is used. Entries not in this part of the matrix are * ignored. This is the same as storing the upper triangular part of A by * rows, with entries in the lower triangular part being ignored. NOTE: this * representation is the TRANSPOSE of the input to cholmod_etree. * * For the unsymmetric case (LL'=AA'), A is accessed by column. Equivalently, * if A is viewed as a matrix in compressed-row form, this routine computes * the row and column counts for L where LL'=A'A. If the input vector f is * present, then F*F' is analyzed instead, where F = A(:,f). * * The set f is held in fset and fsize. * fset = NULL means ":" in MATLAB. fset is ignored. * fset != NULL means f = fset [0..fset-1]. * fset != NULL and fsize = 0 means f is the empty set. * Common->status is set to CHOLMOD_INVALID if fset is invalid. * * In both cases, the columns of A need not be sorted. * A can be packed or unpacked. * * References: * J. Gilbert, E. Ng, B. Peyton, "An efficient algorithm to compute row and * column counts for sparse Cholesky factorization", SIAM J. Matrix Analysis & * Applic., vol 15, 1994, pp. 1075-1091. * * J. Gilbert, X. Li, E. Ng, B. Peyton, "Computing row and column counts for * sparse QR and LU factorization", BIT, vol 41, 2001, pp. 693-710. * * workspace: * if symmetric: Flag (nrow), Iwork (2*nrow) * if unsymmetric: Flag (nrow), Iwork (2*nrow+ncol), Head (nrow+1) * * Supports any xtype (pattern, real, complex, or zomplex). */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === initialize_node ====================================================== */ /* ========================================================================== */ static int initialize_node /* initial work for kth node in postordered etree */ ( Int k, /* at the kth step of the algorithm (and kth node) */ Int Post [ ], /* Post [k] = i, the kth node in postordered etree */ Int Parent [ ], /* Parent [i] is the parent of i in the etree */ Int ColCount [ ], /* ColCount [c] is the current weight of node c */ Int PrevNbr [ ] /* PrevNbr [u] = k if u was last considered at step k */ ) { Int p, parent ; /* determine p, the kth node in the postordered etree */ p = Post [k] ; /* adjust the weight if p is not a root of the etree */ parent = Parent [p] ; if (parent != EMPTY) { ColCount [parent]-- ; } /* flag node p to exclude self edges (p,p) */ PrevNbr [p] = k ; return (p) ; } /* ========================================================================== */ /* === process_edge ========================================================= */ /* ========================================================================== */ /* edge (p,u) is being processed. p < u is a descendant of its ancestor u in * the etree. node p is the kth node in the postordered etree. */ static void process_edge ( Int p, /* process edge (p,u) of the matrix */ Int u, Int k, /* we are at the kth node in the postordered etree */ Int First [ ], /* First [i] = k if the postordering of first * descendent of node i is k */ Int PrevNbr [ ], /* u was last considered at step k = PrevNbr [u] */ Int ColCount [ ], /* ColCount [c] is the current weight of node c */ Int PrevLeaf [ ], /* s = PrevLeaf [u] means that s was the last leaf * seen in the subtree rooted at u. */ Int RowCount [ ], /* RowCount [i] is # of nonzeros in row i of L, * including the diagonal. Not computed if NULL. */ Int SetParent [ ], /* the FIND/UNION data structure, which forms a set * of trees. A root i has i = SetParent [i]. Following * a path from i to the root q of the subtree containing * i means that q is the SetParent representative of i. * All nodes in the tree could have their SetParent * equal to the root q; the tree representation is used * to save time. When a path is traced from i to its * root q, the path is re-traversed to set the SetParent * of the whole path to be the root q. */ Int Level [ ] /* Level [i] = length of path from node i to root */ ) { Int prevleaf, q, s, sparent ; if (First [p] > PrevNbr [u]) { /* p is a leaf of the subtree of u */ ColCount [p]++ ; prevleaf = PrevLeaf [u] ; if (prevleaf == EMPTY) { /* p is the first leaf of subtree of u; RowCount will be incremented * by the length of the path in the etree from p up to u. */ q = u ; } else { /* q = FIND (prevleaf): find the root q of the * SetParent tree containing prevleaf */ for (q = prevleaf ; q != SetParent [q] ; q = SetParent [q]) { ; } /* the root q has been found; re-traverse the path and * perform path compression */ s = prevleaf ; for (s = prevleaf ; s != q ; s = sparent) { sparent = SetParent [s] ; SetParent [s] = q ; } /* adjust the RowCount and ColCount; RowCount will be incremented by * the length of the path from p to the SetParent root q, and * decrement the ColCount of q by one. */ ColCount [q]-- ; } if (RowCount != NULL) { /* if RowCount is being computed, increment it by the length of * the path from p to q */ RowCount [u] += (Level [p] - Level [q]) ; } /* p is a leaf of the subtree of u, so mark PrevLeaf [u] to be p */ PrevLeaf [u] = p ; } /* flag u has having been processed at step k */ PrevNbr [u] = k ; } /* ========================================================================== */ /* === finalize_node ======================================================== */ /* ========================================================================== */ static void finalize_node /* compute UNION (p, Parent [p]) */ ( Int p, Int Parent [ ], /* Parent [p] is the parent of p in the etree */ Int SetParent [ ] /* see process_edge, above */ ) { /* all nodes in the SetParent tree rooted at p now have as their final * root the node Parent [p]. This computes UNION (p, Parent [p]) */ if (Parent [p] != EMPTY) { SetParent [p] = Parent [p] ; } } /* ========================================================================== */ /* === cholmod_rowcolcounts ================================================= */ /* ========================================================================== */ int CHOLMOD(rowcolcounts) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ Int *Parent, /* size nrow. Parent [i] = p if p is the parent of i */ Int *Post, /* size nrow. Post [k] = i if i is the kth node in * the postordered etree. */ /* ---- output --- */ Int *RowCount, /* size nrow. RowCount [i] = # entries in the ith row of * L, including the diagonal. */ Int *ColCount, /* size nrow. ColCount [i] = # entries in the ith * column of L, including the diagonal. */ Int *First, /* size nrow. First [i] = k is the least postordering * of any descendant of i. */ Int *Level, /* size nrow. Level [i] is the length of the path from * i to the root, with Level [root] = 0. */ /* --------------- */ cholmod_common *Common ) { double fl, ff ; Int *Ap, *Ai, *Anz, *PrevNbr, *SetParent, *Head, *PrevLeaf, *Anext, *Ipost, *Iwork ; Int i, j, r, k, len, s, p, pend, inew, stype, nf, anz, inode, parent, nrow, ncol, packed, use_fset, jj ; size_t w ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_NULL (Post, FALSE) ; RETURN_IF_NULL (ColCount, FALSE) ; RETURN_IF_NULL (First, FALSE) ; RETURN_IF_NULL (Level, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; stype = A->stype ; if (stype > 0) { /* symmetric with upper triangular part not supported */ ERROR (CHOLMOD_INVALID, "symmetric upper not supported") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; /* the number of rows of A */ ncol = A->ncol ; /* the number of columns of A */ /* w = 2*nrow + (stype ? 0 : ncol) */ w = CHOLMOD(mult_size_t) (nrow, 2, &ok) ; w = CHOLMOD(add_size_t) (w, (stype ? 0 : ncol), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (nrow, w, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_perm) (Post, nrow, nrow, "Post", Common)) ; ASSERT (CHOLMOD(dump_parent) (Parent, nrow, "Parent", Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; /* size ncol+1, column pointers for A */ Ai = A->i ; /* the row indices of A, of size nz=Ap[ncol+1] */ Anz = A->nz ; packed = A->packed ; ASSERT (IMPLIES (!packed, Anz != NULL)) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; SetParent = Iwork ; /* size nrow (i/i/l) */ PrevNbr = Iwork + nrow ; /* size nrow (i/i/l) */ Anext = Iwork + 2*((size_t) nrow) ; /* size ncol (i/i/l) (unsym only) */ PrevLeaf = Common->Flag ; /* size nrow */ Head = Common->Head ; /* size nrow+1 (unsym only)*/ /* ---------------------------------------------------------------------- */ /* find the first descendant and level of each node in the tree */ /* ---------------------------------------------------------------------- */ /* First [i] = k if the postordering of first descendent of node i is k */ /* Level [i] = length of path from node i to the root (Level [root] = 0) */ for (i = 0 ; i < nrow ; i++) { First [i] = EMPTY ; } /* postorder traversal of the etree */ for (k = 0 ; k < nrow ; k++) { /* node i of the etree is the kth node in the postordered etree */ i = Post [k] ; /* i is a leaf if First [i] is still EMPTY */ /* ColCount [i] starts at 1 if i is a leaf, zero otherwise */ ColCount [i] = (First [i] == EMPTY) ? 1 : 0 ; /* traverse the path from node i to the root, stopping if we find a * node r whose First [r] is already defined. */ len = 0 ; for (r = i ; (r != EMPTY) && (First [r] == EMPTY) ; r = Parent [r]) { First [r] = k ; len++ ; } if (r == EMPTY) { /* we hit a root node, the level of which is zero */ len-- ; } else { /* we stopped at node r, where Level [r] is already defined */ len += Level [r] ; } /* re-traverse the path from node i to r; set the level of each node */ for (s = i ; s != r ; s = Parent [s]) { Level [s] = len-- ; } } /* ---------------------------------------------------------------------- */ /* AA' case: sort columns of A according to first postordered row index */ /* ---------------------------------------------------------------------- */ fl = 0.0 ; if (stype == 0) { /* [ use PrevNbr [0..nrow-1] as workspace for Ipost */ Ipost = PrevNbr ; /* Ipost [i] = k if i is the kth node in the postordered etree. */ for (k = 0 ; k < nrow ; k++) { Ipost [Post [k]] = k ; } use_fset = (fset != NULL) ; if (use_fset) { nf = fsize ; /* clear Anext to check fset */ for (j = 0 ; j < ncol ; j++) { Anext [j] = -2 ; } /* find the first postordered row in each column of A (post,f) * and place the column in the corresponding link list */ for (jj = 0 ; jj < nf ; jj++) { j = fset [jj] ; if (j < 0 || j > ncol || Anext [j] != -2) { /* out-of-range or duplicate entry in fset */ ERROR (CHOLMOD_INVALID, "fset invalid") ; return (FALSE) ; } /* flag column j as having been seen */ Anext [j] = EMPTY ; } /* fset is now valid */ ASSERT (CHOLMOD(dump_perm) (fset, nf, ncol, "fset", Common)) ; } else { nf = ncol ; } for (jj = 0 ; jj < nf ; jj++) { j = (use_fset) ? (fset [jj]) : jj ; /* column j is in the fset; find the smallest row (if any) */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; ff = (double) MAX (0, pend - p) ; fl += ff*ff + ff ; if (pend > p) { k = Ipost [Ai [p]] ; for ( ; p < pend ; p++) { inew = Ipost [Ai [p]] ; k = MIN (k, inew) ; } /* place column j in link list k */ ASSERT (k >= 0 && k < nrow) ; Anext [j] = Head [k] ; Head [k] = j ; } } /* Ipost no longer needed for inverse postordering ] * Head [k] contains a link list of all columns whose first * postordered row index is equal to k, for k = 0 to nrow-1. */ } /* ---------------------------------------------------------------------- */ /* compute the row counts and node weights */ /* ---------------------------------------------------------------------- */ if (RowCount != NULL) { for (i = 0 ; i < nrow ; i++) { RowCount [i] = 1 ; } } for (i = 0 ; i < nrow ; i++) { PrevLeaf [i] = EMPTY ; PrevNbr [i] = EMPTY ; SetParent [i] = i ; /* every node is in its own set, by itself */ } if (stype != 0) { /* ------------------------------------------------------------------ */ /* symmetric case: LL' = A */ /* ------------------------------------------------------------------ */ /* also determine the number of entries in triu(A) */ anz = nrow ; for (k = 0 ; k < nrow ; k++) { /* j is the kth node in the postordered etree */ j = initialize_node (k, Post, Parent, ColCount, PrevNbr) ; /* for all nonzeros A(i,j) below the diagonal, in column j of A */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i > j) { /* j is a descendant of i in etree(A) */ anz++ ; process_edge (j, i, k, First, PrevNbr, ColCount, PrevLeaf, RowCount, SetParent, Level) ; } } /* update SetParent: UNION (j, Parent [j]) */ finalize_node (j, Parent, SetParent) ; } Common->anz = anz ; } else { /* ------------------------------------------------------------------ */ /* unsymmetric case: LL' = AA' */ /* ------------------------------------------------------------------ */ for (k = 0 ; k < nrow ; k++) { /* inode is the kth node in the postordered etree */ inode = initialize_node (k, Post, Parent, ColCount, PrevNbr) ; /* for all cols j whose first postordered row is k: */ for (j = Head [k] ; j != EMPTY ; j = Anext [j]) { /* k is the first postordered row in column j of A */ /* for all rows i in column j: */ p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* has i already been considered at this step k */ if (PrevNbr [i] < k) { /* inode is a descendant of i in etree(AA') */ /* process edge (inode,i) and set PrevNbr[i] to k */ process_edge (inode, i, k, First, PrevNbr, ColCount, PrevLeaf, RowCount, SetParent, Level) ; } } } /* clear link list k */ Head [k] = EMPTY ; /* update SetParent: UNION (inode, Parent [inode]) */ finalize_node (inode, Parent, SetParent) ; } } /* ---------------------------------------------------------------------- */ /* finish computing the column counts */ /* ---------------------------------------------------------------------- */ for (j = 0 ; j < nrow ; j++) { parent = Parent [j] ; if (parent != EMPTY) { /* add the ColCount of j to its parent */ ColCount [parent] += ColCount [j] ; } } /* ---------------------------------------------------------------------- */ /* clear workspace */ /* ---------------------------------------------------------------------- */ Common->mark = EMPTY ; /* CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* flop count and nnz(L) for subsequent LL' numerical factorization */ /* ---------------------------------------------------------------------- */ /* use double to avoid integer overflow. lnz cannot be NaN. */ Common->aatfl = fl ; Common->lnz = 0. ; fl = 0 ; for (j = 0 ; j < nrow ; j++) { ff = (double) (ColCount [j]) ; Common->lnz += ff ; fl += ff*ff ; } Common->fl = fl ; PRINT1 (("rowcol fl %g lnz %g\n", Common->fl, Common->lnz)) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_resymbol.c0000644000175100001440000004441413431000472020705 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_resymbol ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Recompute the symbolic pattern of L. Entries not in the symbolic pattern * are dropped. L->Perm can be used (or not) to permute the input matrix A. * * These routines are used after a supernodal factorization is converted into * a simplicial one, to remove zero entries that were added due to relaxed * supernode amalgamation. They can also be used after a series of downdates * to remove entries that would no longer be present if the matrix were * factorized from scratch. A downdate (cholmod_updown) does not remove any * entries from L. * * workspace: Flag (nrow), Head (nrow+1), * if symmetric: Iwork (2*nrow) * if unsymmetric: Iwork (2*nrow+ncol). * Allocates up to 2 copies of its input matrix A (pattern only). */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === cholmod_resymbol ===================================================== */ /* ========================================================================== */ /* Remove entries from L that are not in the factorization of P*A*P', P*A*A'*P', * or P*F*F'*P' (depending on A->stype and whether fset is NULL or not). * * cholmod_resymbol is the same as cholmod_resymbol_noperm, except that it * first permutes A according to L->Perm. A can be upper/lower/unsymmetric, * in contrast to cholmod_resymbol_noperm (which can be lower or unsym). */ int CHOLMOD(resymbol) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int pack, /* if TRUE, pack the columns of L */ /* ---- in/out --- */ cholmod_factor *L, /* factorization, entries pruned on output */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *H, *F, *G ; Int stype, nrow, ncol ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; if (L->is_super) { /* cannot operate on a supernodal factorization */ ERROR (CHOLMOD_INVALID, "cannot operate on supernodal L") ; return (FALSE) ; } if (L->n != A->nrow) { /* dimensions must agree */ ERROR (CHOLMOD_INVALID, "A and L dimensions do not match") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ stype = A->stype ; nrow = A->nrow ; ncol = A->ncol ; /* s = 2*nrow + (stype ? 0 : ncol) */ s = CHOLMOD(mult_size_t) (nrow, 2, &ok) ; s = CHOLMOD(add_size_t) (s, (stype ? 0 : ncol), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (nrow, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* permute the input matrix if necessary */ /* ---------------------------------------------------------------------- */ H = NULL ; G = NULL ; if (stype > 0) { if (L->ordering == CHOLMOD_NATURAL) { /* F = triu(A)' */ /* workspace: Iwork (nrow) */ G = CHOLMOD(ptranspose) (A, 0, NULL, NULL, 0, Common) ; } else { /* F = triu(A(p,p))' */ /* workspace: Iwork (2*nrow) */ G = CHOLMOD(ptranspose) (A, 0, L->Perm, NULL, 0, Common) ; } F = G ; } else if (stype < 0) { if (L->ordering == CHOLMOD_NATURAL) { F = A ; } else { /* G = triu(A(p,p))' */ /* workspace: Iwork (2*nrow) */ G = CHOLMOD(ptranspose) (A, 0, L->Perm, NULL, 0, Common) ; /* H = G' */ /* workspace: Iwork (nrow) */ H = CHOLMOD(ptranspose) (G, 0, NULL, NULL, 0, Common) ; F = H ; } } else { if (L->ordering == CHOLMOD_NATURAL) { F = A ; } else { /* G = A(p,f)' */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ G = CHOLMOD(ptranspose) (A, 0, L->Perm, fset, fsize, Common) ; /* H = G' */ /* workspace: Iwork (ncol) */ H = CHOLMOD(ptranspose) (G, 0, NULL, NULL, 0, Common) ; F = H ; } } /* No need to check for failure here. cholmod_resymbol_noperm will return * FALSE if F is NULL. */ /* ---------------------------------------------------------------------- */ /* resymbol */ /* ---------------------------------------------------------------------- */ ok = CHOLMOD(resymbol_noperm) (F, fset, fsize, pack, L, Common) ; /* ---------------------------------------------------------------------- */ /* free the temporary matrices, if they exist */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&H, Common) ; CHOLMOD(free_sparse) (&G, Common) ; return (ok) ; } /* ========================================================================== */ /* === cholmod_resymbol_noperm ============================================== */ /* ========================================================================== */ /* Redo symbolic LDL' or LL' factorization of I + F*F' or I+A, where F=A(:,f). * * L already exists, but is a superset of the true dynamic pattern (simple * column downdates and row deletions haven't pruned anything). Just redo the * symbolic factorization and drop entries that are no longer there. The * diagonal is not modified. The number of nonzeros in column j of L * (L->nz[j]) can decrease. The column pointers (L->p[j]) remain unchanged if * pack is FALSE or if L is not monotonic. Otherwise, the columns of L are * packed in place. * * For the symmetric case, the columns of the lower triangular part of A * are accessed by column. NOTE that this the transpose of the general case. * * For the unsymmetric case, F=A(:,f) is accessed by column. * * A need not be sorted, and can be packed or unpacked. If L->Perm is not * identity, then A must already be permuted according to the permutation used * to factorize L. The advantage of using this routine is that it does not * need to create permuted copies of A first. * * This routine can be called if L is only partially factored via cholmod_rowfac * since all it does is prune. If an entry is in F*F' or A, but not in L, it * isn't added to L. * * L must be simplicial LDL' or LL'; it cannot be supernodal or symbolic. * * The set f is held in fset and fsize. * fset = NULL means ":" in MATLAB. fset is ignored. * fset != NULL means f = fset [0..fset-1]. * fset != NULL and fsize = 0 means f is the empty set. * There can be no duplicates in fset. * Common->status is set to CHOLMOD_INVALID if fset is invalid. * * workspace: Flag (nrow), Head (nrow+1), * if symmetric: Iwork (2*nrow) * if unsymmetric: Iwork (2*nrow+ncol). * Unlike cholmod_resymbol, this routine does not allocate any temporary * copies of its input matrix. */ int CHOLMOD(resymbol_noperm) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int pack, /* if TRUE, pack the columns of L */ /* ---- in/out --- */ cholmod_factor *L, /* factorization, entries pruned on output */ /* --------------- */ cholmod_common *Common ) { double *Lx, *Lz ; Int i, j, k, row, parent, p, pend, pdest, ncol, apacked, sorted, nrow, nf, use_fset, mark, jj, stype, xtype ; Int *Ap, *Ai, *Anz, *Li, *Lp, *Lnz, *Flag, *Head, *Link, *Anext, *Iwork ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; ncol = A->ncol ; nrow = A->nrow ; stype = A->stype ; ASSERT (IMPLIES (stype != 0, nrow == ncol)) ; if (stype > 0) { /* symmetric, with upper triangular part, not supported */ ERROR (CHOLMOD_INVALID, "symmetric upper not supported ") ; return (FALSE) ; } if (L->is_super) { /* cannot operate on a supernodal or symbolic factorization */ ERROR (CHOLMOD_INVALID, "cannot operate on supernodal L") ; return (FALSE) ; } if (L->n != A->nrow) { /* dimensions must agree */ ERROR (CHOLMOD_INVALID, "A and L dimensions do not match") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 2*nrow + (stype ? 0 : ncol) */ s = CHOLMOD(mult_size_t) (nrow, 2, &ok) ; if (stype != 0) { s = CHOLMOD(add_size_t) (s, ncol, &ok) ; } if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (nrow, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ai = A->i ; Ap = A->p ; Anz = A->nz ; apacked = A->packed ; sorted = A->sorted ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lp = L->p ; Lnz = L->nz ; xtype = L->xtype ; /* If L is monotonic on input, then it can be packed or * unpacked on output, depending on the pack input parameter. */ /* cannot pack a non-monotonic matrix */ if (!(L->is_monotonic)) { pack = FALSE ; } ASSERT (L->nzmax >= (size_t) (Lp [L->n])) ; pdest = 0 ; PRINT1 (("\n\n===================== Resymbol pack %d Apacked %d\n", pack, A->packed)) ; ASSERT (CHOLMOD(dump_sparse) (A, "ReSymbol A:", Common) >= 0) ; DEBUG (CHOLMOD(dump_factor) (L, "ReSymbol initial L (i, x):", Common)) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size nrow */ Head = Common->Head ; /* size nrow+1 */ Iwork = Common->Iwork ; Link = Iwork ; /* size nrow (i/i/l) [ */ Lnz = Iwork + nrow ; /* size nrow (i/i/l), if L not packed */ Anext = Iwork + 2*((size_t) nrow) ; /* size ncol (i/i/l), unsym. only */ for (j = 0 ; j < nrow ; j++) { Link [j] = EMPTY ; } /* use Lnz in L itself */ Lnz = L->nz ; ASSERT (Lnz != NULL) ; /* ---------------------------------------------------------------------- */ /* for the unsymmetric case, queue each column of A (:,f) */ /* ---------------------------------------------------------------------- */ /* place each column of the basis set on the link list corresponding to */ /* the smallest row index in that column */ if (stype == 0) { use_fset = (fset != NULL) ; if (use_fset) { nf = fsize ; /* This is the only O(ncol) loop in cholmod_resymbol. * It is required only to check the fset. */ for (j = 0 ; j < ncol ; j++) { Anext [j] = -2 ; } for (jj = 0 ; jj < nf ; jj++) { j = fset [jj] ; if (j < 0 || j > ncol || Anext [j] != -2) { /* out-of-range or duplicate entry in fset */ ERROR (CHOLMOD_INVALID, "fset invalid") ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (FALSE) ; } /* flag column j as having been seen */ Anext [j] = EMPTY ; } /* the fset is now valid */ ASSERT (CHOLMOD(dump_perm) (fset, nf, ncol, "fset", Common)) ; } else { nf = ncol ; } for (jj = 0 ; jj < nf ; jj++) { j = (use_fset) ? (fset [jj]) : jj ; /* column j is the fset; find the smallest row (if any) */ p = Ap [j] ; pend = (apacked) ? (Ap [j+1]) : (p + Anz [j]) ; if (pend > p) { k = Ai [p] ; if (!sorted) { for ( ; p < pend ; p++) { k = MIN (k, Ai [p]) ; } } /* place column j on link list k */ ASSERT (k >= 0 && k < nrow) ; Anext [j] = Head [k] ; Head [k] = j ; } } } /* ---------------------------------------------------------------------- */ /* recompute symbolic LDL' factorization */ /* ---------------------------------------------------------------------- */ for (k = 0 ; k < nrow ; k++) { #ifndef NDEBUG PRINT1 (("\n\n================== Initial column k = "ID"\n", k)) ; for (p = Lp [k] ; p < Lp [k] + Lnz [k] ; p++) { PRINT1 ((" row: "ID" value: ", Li [p])) ; PRINT1 (("\n")) ; } PRINT1 (("Recomputing LDL, column k = "ID"\n", k)) ; #endif /* ------------------------------------------------------------------ */ /* compute column k of I+F*F' or I+A */ /* ------------------------------------------------------------------ */ /* flag the diagonal entry */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; Flag [k] = mark ; PRINT1 ((" row: "ID" (diagonal)\n", k)) ; if (stype != 0) { /* merge column k of A into Flag (lower triangular part only) */ p = Ap [k] ; pend = (apacked) ? (Ap [k+1]) : (p + Anz [k]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i > k) { Flag [i] = mark ; } } } else { /* for each column j whos first row index is in row k */ for (j = Head [k] ; j != EMPTY ; j = Anext [j]) { /* merge column j of A into Flag */ PRINT1 ((" ---- A column "ID"\n", j)) ; p = Ap [j] ; pend = (apacked) ? (Ap [j+1]) : (p + Anz [j]) ; PRINT1 ((" length "ID" adding\n", pend-p)) ; for ( ; p < pend ; p++) { #ifndef NDEBUG ASSERT (Ai [p] >= k && Ai [p] < nrow) ; if (Flag [Ai [p]] < mark) PRINT1 ((" row "ID"\n", Ai [p])) ; #endif Flag [Ai [p]] = mark ; } } /* clear the kth link list */ Head [k] = EMPTY ; } /* ------------------------------------------------------------------ */ /* compute pruned pattern of kth column of L = union of children */ /* ------------------------------------------------------------------ */ /* for each column j of L whose parent is k */ for (j = Link [k] ; j != EMPTY ; j = Link [j]) { /* merge column j of L into Flag */ PRINT1 ((" ---- L column "ID"\n", k)) ; ASSERT (j < k) ; ASSERT (Lnz [j] > 0) ; p = Lp [j] ; pend = p + Lnz [j] ; ASSERT (Li [p] == j && Li [p+1] == k) ; p++ ; /* skip past the diagonal entry */ for ( ; p < pend ; p++) { /* add to pattern */ ASSERT (Li [p] >= k && Li [p] < nrow) ; Flag [Li [p]] = mark ; } } /* ------------------------------------------------------------------ */ /* prune the kth column of L */ /* ------------------------------------------------------------------ */ PRINT1 (("Final column of L:\n")) ; p = Lp [k] ; pend = p + Lnz [k] ; if (pack) { /* shift column k upwards */ Lp [k] = pdest ; } else { /* leave column k in place, just reduce Lnz [k] */ pdest = p ; } for ( ; p < pend ; p++) { ASSERT (pdest < pend) ; ASSERT (pdest <= p) ; row = Li [p] ; ASSERT (row >= k && row < nrow) ; if (Flag [row] == mark) { /* keep this entry */ Li [pdest] = row ; if (xtype == CHOLMOD_REAL) { Lx [pdest] = Lx [p] ; } else if (xtype == CHOLMOD_COMPLEX) { Lx [2*pdest ] = Lx [2*p ] ; Lx [2*pdest+1] = Lx [2*p+1] ; } else if (xtype == CHOLMOD_ZOMPLEX) { Lx [pdest] = Lx [p] ; Lz [pdest] = Lz [p] ; } pdest++ ; } } /* ------------------------------------------------------------------ */ /* prepare this column for its parent */ /* ------------------------------------------------------------------ */ Lnz [k] = pdest - Lp [k] ; PRINT1 ((" L("ID") length "ID"\n", k, Lnz [k])) ; ASSERT (Lnz [k] > 0) ; /* parent is the first entry in the column after the diagonal */ parent = (Lnz [k] > 1) ? (Li [Lp [k] + 1]) : EMPTY ; PRINT1 (("parent ("ID") = "ID"\n", k, parent)) ; ASSERT ((parent > k && parent < nrow) || (parent == EMPTY)) ; if (parent != EMPTY) { Link [k] = Link [parent] ; Link [parent] = k ; } } /* done using Iwork for Link, Lnz (if needed), and Anext ] */ /* ---------------------------------------------------------------------- */ /* convert L to packed, if requested */ /* ---------------------------------------------------------------------- */ if (pack) { /* finalize Lp */ Lp [nrow] = pdest ; /* Shrink L to be just large enough. It cannot fail. */ /* workspace: none */ ASSERT ((size_t) (Lp [nrow]) <= L->nzmax) ; CHOLMOD(reallocate_factor) (Lp [nrow], L, Common) ; ASSERT (Common->status >= CHOLMOD_OK) ; } /* ---------------------------------------------------------------------- */ /* clear workspace */ /* ---------------------------------------------------------------------- */ /* CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; DEBUG (CHOLMOD(dump_factor) (L, "ReSymbol final L (i, x):", Common)) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_spsolve.c0000644000175100001440000002364313431000472020545 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_spsolve ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Given an LL' or LDL' factorization of A, solve one of the following systems: * * Ax=b 0: CHOLMOD_A also applies the permutation L->Perm * LDL'x=b 1: CHOLMOD_LDLt does not apply L->Perm * LDx=b 2: CHOLMOD_LD * DL'x=b 3: CHOLMOD_DLt * Lx=b 4: CHOLMOD_L * L'x=b 5: CHOLMOD_Lt * Dx=b 6: CHOLMOD_D * x=Pb 7: CHOLMOD_P apply a permutation (P is L->Perm) * x=P'b 8: CHOLMOD_Pt apply an inverse permutation * * where b and x are sparse. If L and b are real, then x is real. Otherwise, * x is complex or zomplex, depending on the Common->prefer_zomplex parameter. * All xtypes of x and b are supported (real, complex, and zomplex). */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === EXPAND_AS_NEEDED ===================================================== */ /* ========================================================================== */ /* Double the size of the sparse matrix X, if we have run out of space. */ #define EXPAND_AS_NEEDED \ if (xnz >= nzmax) \ { \ nzmax *= 2 ; \ CHOLMOD(reallocate_sparse) (nzmax, X, Common) ; \ if (Common->status < CHOLMOD_OK) \ { \ CHOLMOD(free_sparse) (&X, Common) ; \ CHOLMOD(free_dense) (&X4, Common) ; \ CHOLMOD(free_dense) (&B4, Common) ; \ return (NULL) ; \ } \ Xi = X->i ; \ Xx = X->x ; \ Xz = X->z ; \ } /* ========================================================================== */ /* === cholmod_spolve ======================================================= */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(spsolve) /* returns the sparse solution X */ ( /* ---- input ---- */ int sys, /* system to solve */ cholmod_factor *L, /* factorization to use */ cholmod_sparse *B, /* right-hand-side */ /* --------------- */ cholmod_common *Common ) { double x, z ; cholmod_dense *X4, *B4 ; cholmod_sparse *X ; double *Bx, *Bz, *Xx, *Xz, *B4x, *B4z, *X4x, *X4z ; Int *Bi, *Bp, *Xp, *Xi, *Bnz ; Int n, nrhs, q, p, i, j, jfirst, jlast, packed, block, pend, j_n, xtype ; size_t xnz, nzmax ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (L, NULL) ; RETURN_IF_NULL (B, NULL) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, NULL) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, NULL) ; if (L->n != B->nrow) { ERROR (CHOLMOD_INVALID, "dimensions of L and B do not match") ; return (NULL) ; } if (B->stype) { ERROR (CHOLMOD_INVALID, "B cannot be stored in symmetric mode") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace B4 and initial result X */ /* ---------------------------------------------------------------------- */ n = L->n ; nrhs = B->ncol ; /* X is real if both L and B are real, complex/zomplex otherwise */ xtype = (L->xtype == CHOLMOD_REAL && B->xtype == CHOLMOD_REAL) ? CHOLMOD_REAL : (Common->prefer_zomplex ? CHOLMOD_ZOMPLEX : CHOLMOD_COMPLEX) ; /* solve up to 4 columns at a time */ block = MIN (nrhs, 4) ; /* initial size of X is at most 4*n */ nzmax = n*block ; X = CHOLMOD(spzeros) (n, nrhs, nzmax, xtype, Common) ; B4 = CHOLMOD(zeros) (n, block, B->xtype, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&X, Common) ; CHOLMOD(free_dense) (&B4, Common) ; return (NULL) ; } Bp = B->p ; Bi = B->i ; Bx = B->x ; Bz = B->z ; Bnz = B->nz ; packed = B->packed ; Xp = X->p ; Xi = X->i ; Xx = X->x ; Xz = X->z ; xnz = 0 ; B4x = B4->x ; B4z = B4->z ; /* ---------------------------------------------------------------------- */ /* solve in chunks of 4 columns at a time */ /* ---------------------------------------------------------------------- */ for (jfirst = 0 ; jfirst < nrhs ; jfirst += block) { /* ------------------------------------------------------------------ */ /* adjust the number of columns of B4 */ /* ------------------------------------------------------------------ */ jlast = MIN (nrhs, jfirst + block) ; B4->ncol = jlast - jfirst ; /* ------------------------------------------------------------------ */ /* scatter B(jfirst:jlast-1) into B4 */ /* ------------------------------------------------------------------ */ for (j = jfirst ; j < jlast ; j++) { p = Bp [j] ; pend = (packed) ? (Bp [j+1]) : (p + Bnz [j]) ; j_n = (j-jfirst)*n ; switch (B->xtype) { case CHOLMOD_REAL: for ( ; p < pend ; p++) { B4x [Bi [p] + j_n] = Bx [p] ; } break ; case CHOLMOD_COMPLEX: for ( ; p < pend ; p++) { q = Bi [p] + j_n ; B4x [2*q ] = Bx [2*p ] ; B4x [2*q+1] = Bx [2*p+1] ; } break ; case CHOLMOD_ZOMPLEX: for ( ; p < pend ; p++) { q = Bi [p] + j_n ; B4x [q] = Bx [p] ; B4z [q] = Bz [p] ; } break ; } } /* ------------------------------------------------------------------ */ /* solve the system (X4 = A\B4 or other system) */ /* ------------------------------------------------------------------ */ X4 = CHOLMOD(solve) (sys, L, B4, Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free_sparse) (&X, Common) ; CHOLMOD(free_dense) (&B4, Common) ; CHOLMOD(free_dense) (&X4, Common) ; return (NULL) ; } ASSERT (X4->xtype == xtype) ; X4x = X4->x ; X4z = X4->z ; /* ------------------------------------------------------------------ */ /* append the solution onto X */ /* ------------------------------------------------------------------ */ for (j = jfirst ; j < jlast ; j++) { Xp [j] = xnz ; j_n = (j-jfirst)*n ; if ( xnz + n <= nzmax) { /* ---------------------------------------------------------- */ /* X is guaranteed to be large enough */ /* ---------------------------------------------------------- */ switch (xtype) { case CHOLMOD_REAL: for (i = 0 ; i < n ; i++) { x = X4x [i + j_n] ; if (IS_NONZERO (x)) { Xi [xnz] = i ; Xx [xnz] = x ; xnz++ ; } } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < n ; i++) { x = X4x [2*(i + j_n) ] ; z = X4x [2*(i + j_n)+1] ; if (IS_NONZERO (x) || IS_NONZERO (z)) { Xi [xnz] = i ; Xx [2*xnz ] = x ; Xx [2*xnz+1] = z ; xnz++ ; } } break ; case CHOLMOD_ZOMPLEX: for (i = 0 ; i < n ; i++) { x = X4x [i + j_n] ; z = X4z [i + j_n] ; if (IS_NONZERO (x) || IS_NONZERO (z)) { Xi [xnz] = i ; Xx [xnz] = x ; Xz [xnz] = z ; xnz++ ; } } break ; } } else { /* ---------------------------------------------------------- */ /* X may need to increase in size */ /* ---------------------------------------------------------- */ switch (xtype) { case CHOLMOD_REAL: for (i = 0 ; i < n ; i++) { x = X4x [i + j_n] ; if (IS_NONZERO (x)) { EXPAND_AS_NEEDED ; Xi [xnz] = i ; Xx [xnz] = x ; xnz++ ; } } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < n ; i++) { x = X4x [2*(i + j_n) ] ; z = X4x [2*(i + j_n)+1] ; if (IS_NONZERO (x) || IS_NONZERO (z)) { EXPAND_AS_NEEDED ; Xi [xnz] = i ; Xx [2*xnz ] = x ; Xx [2*xnz+1] = z ; xnz++ ; } } break ; case CHOLMOD_ZOMPLEX: for (i = 0 ; i < n ; i++) { x = X4x [i + j_n] ; z = X4z [i + j_n] ; if (IS_NONZERO (x) || IS_NONZERO (z)) { EXPAND_AS_NEEDED ; Xi [xnz] = i ; Xx [xnz] = x ; Xz [xnz] = z ; xnz++ ; } } break ; } } } CHOLMOD(free_dense) (&X4, Common) ; /* ------------------------------------------------------------------ */ /* clear B4 for next iteration */ /* ------------------------------------------------------------------ */ if (jlast < nrhs) { for (j = jfirst ; j < jlast ; j++) { p = Bp [j] ; pend = (packed) ? (Bp [j+1]) : (p + Bnz [j]) ; j_n = (j-jfirst)*n ; switch (B->xtype) { case CHOLMOD_REAL: for ( ; p < pend ; p++) { B4x [Bi [p] + j_n] = 0 ; } break ; case CHOLMOD_COMPLEX: for ( ; p < pend ; p++) { q = Bi [p] + j_n ; B4x [2*q ] = 0 ; B4x [2*q+1] = 0 ; } break ; case CHOLMOD_ZOMPLEX: for ( ; p < pend ; p++) { q = Bi [p] + j_n ; B4x [q] = 0 ; B4z [q] = 0 ; } break ; } } } } Xp [nrhs] = xnz ; /* ---------------------------------------------------------------------- */ /* reduce X in size, free workspace, and return result */ /* ---------------------------------------------------------------------- */ ASSERT (xnz <= X->nzmax) ; CHOLMOD(reallocate_sparse) (xnz, X, Common) ; ASSERT (Common->status == CHOLMOD_OK) ; CHOLMOD(free_dense) (&B4, Common) ; return (X) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_postorder.c0000644000175100001440000002275013431000472021071 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_postorder =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Compute the postorder of a tree. */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === dfs ================================================================== */ /* ========================================================================== */ /* The code below includes both a recursive and non-recursive depth-first-search * of a tree. The recursive code is simpler, but can lead to stack overflow. * It is left here for reference, to understand what the non-recursive code * is computing. To try the recursive version, uncomment the following * #define, or compile the code with -DRECURSIVE. Be aware that stack * overflow may occur. #define RECURSIVE */ #ifdef RECURSIVE /* recursive version: a working code for reference only, not actual use */ static Int dfs /* return the new value of k */ ( Int p, /* start a DFS at node p */ Int k, /* start the node numbering at k */ Int Post [ ], /* Post ordering, modified on output */ Int Head [ ], /* Head [p] = youngest child of p; EMPTY on output */ Int Next [ ], /* Next [j] = sibling of j; unmodified */ Int Pstack [ ] /* unused */ ) { Int j ; /* start a DFS at each child of node p */ for (j = Head [p] ; j != EMPTY ; j = Next [j]) { /* start a DFS at child node j */ k = dfs (j, k, Post, Head, Next, Pstack) ; } Post [k++] = p ; /* order node p as the kth node */ Head [p] = EMPTY ; /* link list p no longer needed */ return (k) ; /* the next node will be numbered k */ } #else /* non-recursive version for actual use */ static Int dfs /* return the new value of k */ ( Int p, /* start the DFS at a root node p */ Int k, /* start the node numbering at k */ Int Post [ ], /* Post ordering, modified on output */ Int Head [ ], /* Head [p] = youngest child of p; EMPTY on output */ Int Next [ ], /* Next [j] = sibling of j; unmodified */ Int Pstack [ ] /* workspace of size n, undefined on input or output */ ) { Int j, phead ; /* put the root node on the stack */ Pstack [0] = p ; phead = 0 ; /* while the stack is not empty, do: */ while (phead >= 0) { /* grab the node p from top of the stack and get its youngest child j */ p = Pstack [phead] ; j = Head [p] ; if (j == EMPTY) { /* all children of p ordered. remove p from stack and order it */ phead-- ; Post [k++] = p ; /* order node p as the kth node */ } else { /* leave p on the stack. Start a DFS at child node j by putting * j on the stack and removing j from the list of children of p. */ Head [p] = Next [j] ; Pstack [++phead] = j ; } } return (k) ; /* the next node will be numbered k */ } #endif /* ========================================================================== */ /* === cholmod_postorder ==================================================== */ /* ========================================================================== */ /* Postorder a tree. The tree is either an elimination tree (the output from * from cholmod_etree) or a component tree (from cholmod_nested_dissection). * * An elimination tree is a complete tree of n nodes with Parent [j] > j or * Parent [j] = EMPTY if j is a root. On output Post [0..n-1] is a complete * permutation vector. * * A component tree is a subset of 0..n-1. Parent [j] = -2 if node j is not * in the component tree. Parent [j] = EMPTY if j is a root of the component * tree, and Parent [j] is in the range 0 to n-1 if j is in the component * tree but not a root. On output, Post [k] is defined only for nodes in * the component tree. Post [k] = j if node j is the kth node in the * postordered component tree, where k is in the range 0 to the number of * components minus 1. * * Node j is ignored and not included in the postorder if Parent [j] < EMPTY. * * As a result, check_parent (Parent, n,...) may fail on input, since * cholmod_check_parent assumes Parent is an elimination tree. Similarly, * cholmod_check_perm (Post, ...) may fail on output, since Post is a partial * permutation if Parent is a component tree. * * An optional node weight can be given. When starting a postorder at node j, * the children of j are ordered in increasing order of their weight. * If no weights are given (Weight is NULL) then children are ordered in * increasing order of their node number. The weight of a node must be in the * range 0 to n-1. Weights outside that range are silently converted to that * range (weights < 0 are treated as zero, and weights >= n are treated as n-1). * * * workspace: Head (n), Iwork (2*n) */ SuiteSparse_long CHOLMOD(postorder) /* return # of nodes postordered */ ( /* ---- input ---- */ Int *Parent, /* size n. Parent [j] = p if p is the parent of j */ size_t n, Int *Weight, /* size n, optional. Weight [j] is weight of node j */ /* ---- output --- */ Int *Post, /* size n. Post [k] = j is kth in postordered tree */ /* --------------- */ cholmod_common *Common ) { Int *Head, *Next, *Pstack, *Iwork ; Int j, p, k, w, nextj ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (Parent, EMPTY) ; RETURN_IF_NULL (Post, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 2*n */ s = CHOLMOD(mult_size_t) (n, 2, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (EMPTY) ; } CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Head = Common->Head ; /* size n+1, initially all EMPTY */ Iwork = Common->Iwork ; Next = Iwork ; /* size n (i/i/l) */ Pstack = Iwork + n ; /* size n (i/i/l) */ /* ---------------------------------------------------------------------- */ /* construct a link list of children for each node */ /* ---------------------------------------------------------------------- */ if (Weight == NULL) { /* in reverse order so children are in ascending order in each list */ for (j = n-1 ; j >= 0 ; j--) { p = Parent [j] ; if (p >= 0 && p < ((Int) n)) { /* add j to the list of children for node p */ Next [j] = Head [p] ; Head [p] = j ; } } /* Head [p] = j if j is the youngest (least-numbered) child of p */ /* Next [j1] = j2 if j2 is the next-oldest sibling of j1 */ } else { /* First, construct a set of link lists according to Weight. * * Whead [w] = j if node j is the first node in bucket w. * Next [j1] = j2 if node j2 follows j1 in a link list. */ Int *Whead = Pstack ; /* use Pstack as workspace for Whead [ */ for (w = 0 ; w < ((Int) n) ; w++) { Whead [w] = EMPTY ; } /* do in forward order, so nodes that ties are ordered by node index */ for (j = 0 ; j < ((Int) n) ; j++) { p = Parent [j] ; if (p >= 0 && p < ((Int) n)) { w = Weight [j] ; w = MAX (0, w) ; w = MIN (w, ((Int) n) - 1) ; /* place node j at the head of link list for weight w */ Next [j] = Whead [w] ; Whead [w] = j ; } } /* traverse weight buckets, placing each node in its parent's list */ for (w = n-1 ; w >= 0 ; w--) { for (j = Whead [w] ; j != EMPTY ; j = nextj) { nextj = Next [j] ; /* put node j in the link list of its parent */ p = Parent [j] ; ASSERT (p >= 0 && p < ((Int) n)) ; Next [j] = Head [p] ; Head [p] = j ; } } /* Whead no longer needed ] */ /* Head [p] = j if j is the lightest child of p */ /* Next [j1] = j2 if j2 is the next-heaviest sibling of j1 */ } /* ---------------------------------------------------------------------- */ /* start a DFS at each root node of the etree */ /* ---------------------------------------------------------------------- */ k = 0 ; for (j = 0 ; j < ((Int) n) ; j++) { if (Parent [j] == EMPTY) { /* j is the root of a tree; start a DFS here */ k = dfs (j, k, Post, Head, Next, Pstack) ; } } /* this would normally be EMPTY already, unless Parent is invalid */ for (j = 0 ; j < ((Int) n) ; j++) { Head [j] = EMPTY ; } PRINT1 (("postordered "ID" nodes\n", k)) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (k) ; } #endif igraph/src/CHOLMOD/Cholesky/t_cholmod_lsolve.c0000644000175100001440000006371213431000472020702 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/t_cholmod_lsolve ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Template routine to solve Lx=b with unit or non-unit diagonal, or * solve LDx=b. * * The numeric xtype of L and Y must match. Y contains b on input and x on * output, stored in row-form. Y is nrow-by-n, where nrow must equal 1 for the * complex or zomplex cases, and nrow <= 4 for the real case. * * This file is not compiled separately. It is included in t_cholmod_solve.c * instead. It contains no user-callable routines. * * workspace: none * * Supports real, complex, and zomplex factors. */ /* undefine all prior definitions */ #undef FORM_NAME #undef LSOLVE /* -------------------------------------------------------------------------- */ /* define the method */ /* -------------------------------------------------------------------------- */ #ifdef LL /* LL': solve Lx=b with non-unit diagonal */ #define FORM_NAME(prefix,rank) prefix ## ll_lsolve_ ## rank #elif defined (LD) /* LDL': solve LDx=b */ #define FORM_NAME(prefix,rank) prefix ## ldl_ldsolve_ ## rank #else /* LDL': solve Lx=b with unit diagonal */ #define FORM_NAME(prefix,rank) prefix ## ldl_lsolve_ ## rank #endif /* LSOLVE(k) defines the name of a routine for an n-by-k right-hand-side. */ #define LSOLVE(prefix,rank) FORM_NAME(prefix,rank) #ifdef REAL /* ========================================================================== */ /* === LSOLVE (1) =========================================================== */ /* ========================================================================== */ /* Solve Lx=b, where b has 1 column */ static void LSOLVE (PREFIX,1) ( cholmod_factor *L, double X [ ] /* n-by-1 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = 0 ; j < n ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j+1, and j+2) */ if (lnz < 4 || lnz != Lnz [j+1] + 1 || Li [p+1] != j+1) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y = X [j] ; #ifdef LL y /= Lx [p] ; X [j] = y ; #elif defined (LD) X [j] = y / Lx [p] ; #endif for (p++ ; p < pend ; p++) { X [Li [p]] -= Lx [p] * y ; } j++ ; /* advance to next column of L */ } else if (lnz != Lnz [j+2] + 2 || Li [p+2] != j+2) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2] ; Int q = Lp [j+1] ; #ifdef LL y [0] = X [j] / Lx [p] ; y [1] = (X [j+1] - Lx [p+1] * y [0]) / Lx [q] ; X [j ] = y [0] ; X [j+1] = y [1] ; #elif defined (LD) y [0] = X [j] ; y [1] = X [j+1] - Lx [p+1] * y [0] ; X [j ] = y [0] / Lx [p] ; X [j+1] = y [1] / Lx [q] ; #else y [0] = X [j] ; y [1] = X [j+1] - Lx [p+1] * y [0] ; X [j+1] = y [1] ; #endif for (p += 2, q++ ; p < pend ; p++, q++) { X [Li [p]] -= Lx [p] * y [0] + Lx [q] * y [1] ; } j += 2 ; /* advance to next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3] ; Int q = Lp [j+1] ; Int r = Lp [j+2] ; #ifdef LL y [0] = X [j] / Lx [p] ; y [1] = (X [j+1] - Lx [p+1] * y [0]) / Lx [q] ; y [2] = (X [j+2] - Lx [p+2] * y [0] - Lx [q+1] * y [1]) / Lx [r] ; X [j ] = y [0] ; X [j+1] = y [1] ; X [j+2] = y [2] ; #elif defined (LD) y [0] = X [j] ; y [1] = X [j+1] - Lx [p+1] * y [0] ; y [2] = X [j+2] - Lx [p+2] * y [0] - Lx [q+1] * y [1] ; X [j ] = y [0] / Lx [p] ; X [j+1] = y [1] / Lx [q] ; X [j+2] = y [2] / Lx [r] ; #else y [0] = X [j] ; y [1] = X [j+1] - Lx [p+1] * y [0] ; y [2] = X [j+2] - Lx [p+2] * y [0] - Lx [q+1] * y [1] ; X [j+1] = y [1] ; X [j+2] = y [2] ; #endif for (p += 3, q += 2, r++ ; p < pend ; p++, q++, r++) { X [Li [p]] -= Lx [p] * y [0] + Lx [q] * y [1] + Lx [r] * y [2] ; } j += 3 ; /* advance to next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (2) =========================================================== */ /* ========================================================================== */ /* Solve Lx=b, where b has 2 columns */ static void LSOLVE (PREFIX,2) ( cholmod_factor *L, double X [ ][2] /* n-by-2 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = 0 ; j < n ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j+1, and j+2) */ if (lnz < 4 || lnz != Lnz [j+1] + 1 || Li [p+1] != j+1) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [2] ; y [0] = X [j][0] ; y [1] = X [j][1] ; #ifdef LL y [0] /= Lx [p] ; y [1] /= Lx [p] ; X [j][0] = y [0] ; X [j][1] = y [1] ; #elif defined (LD) X [j][0] = y [0] / Lx [p] ; X [j][1] = y [1] / Lx [p] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; X [i][0] -= Lx [p] * y [0] ; X [i][1] -= Lx [p] * y [1] ; } j++ ; /* advance to next column of L */ } else if (lnz != Lnz [j+2] + 2 || Li [p+2] != j+2) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][2] ; Int q = Lp [j+1] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx [p+1] * y [0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx [p+1] * y [0][1]) / Lx [q] ; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; #endif for (p += 2, q++ ; p < pend ; p++, q++) { Int i = Li [p] ; X [i][0] -= Lx [p] * y [0][0] + Lx [q] * y [1][0] ; X [i][1] -= Lx [p] * y [0][1] + Lx [q] * y [1][1] ; } j += 2 ; /* advance to next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3][2] ; Int q = Lp [j+1] ; Int r = Lp [j+2] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx[p+1] * y[0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx[p+1] * y[0][1]) / Lx [q] ; y [2][0] = (X [j+2][0] - Lx[p+2] * y[0][0] - Lx[q+1]*y[1][0])/Lx[r]; y [2][1] = (X [j+2][1] - Lx[p+2] * y[0][1] - Lx[q+1]*y[1][1])/Lx[r]; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; X [j+2][0] = y [2][0] / Lx [r] ; X [j+2][1] = y [2][1] / Lx [r] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; #endif for (p += 3, q += 2, r++ ; p < pend ; p++, q++, r++) { Int i = Li [p] ; X[i][0] -= Lx[p] * y[0][0] + Lx[q] * y[1][0] + Lx[r] * y[2][0] ; X[i][1] -= Lx[p] * y[0][1] + Lx[q] * y[1][1] + Lx[r] * y[2][1] ; } j += 3 ; /* advance to next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (3) =========================================================== */ /* ========================================================================== */ /* Solve Lx=b, where b has 3 columns */ static void LSOLVE (PREFIX,3) ( cholmod_factor *L, double X [ ][3] /* n-by-3 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = 0 ; j < n ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j+1, and j+2) */ if (lnz < 4 || lnz != Lnz [j+1] + 1 || Li [p+1] != j+1) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [3] ; y [0] = X [j][0] ; y [1] = X [j][1] ; y [2] = X [j][2] ; #ifdef LL y [0] /= Lx [p] ; y [1] /= Lx [p] ; y [2] /= Lx [p] ; X [j][0] = y [0] ; X [j][1] = y [1] ; X [j][2] = y [2] ; #elif defined (LD) X [j][0] = y [0] / Lx [p] ; X [j][1] = y [1] / Lx [p] ; X [j][2] = y [2] / Lx [p] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; double lx = Lx [p] ; X [i][0] -= lx * y [0] ; X [i][1] -= lx * y [1] ; X [i][2] -= lx * y [2] ; } j++ ; /* advance to next column of L */ } else if (lnz != Lnz [j+2] + 2 || Li [p+2] != j+2) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][3] ; Int q = Lp [j+1] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; y [0][2] = X [j][2] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [0][2] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx [p+1] * y [0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx [p+1] * y [0][1]) / Lx [q] ; y [1][2] = (X [j+1][2] - Lx [p+1] * y [0][2]) / Lx [q] ; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j ][2] = y [0][2] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; X [j+1][2] = y [1][2] / Lx [q] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; #endif for (p += 2, q++ ; p < pend ; p++, q++) { Int i = Li [p] ; double lx [2] ; lx [0] = Lx [p] ; lx [1] = Lx [q] ; X [i][0] -= lx [0] * y [0][0] + lx [1] * y [1][0] ; X [i][1] -= lx [0] * y [0][1] + lx [1] * y [1][1] ; X [i][2] -= lx [0] * y [0][2] + lx [1] * y [1][2] ; } j += 2 ; /* advance to next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3][3] ; Int q = Lp [j+1] ; Int r = Lp [j+2] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; y [0][2] = X [j][2] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [0][2] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx[p+1] * y[0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx[p+1] * y[0][1]) / Lx [q] ; y [1][2] = (X [j+1][2] - Lx[p+1] * y[0][2]) / Lx [q] ; y [2][0] = (X [j+2][0] - Lx[p+2] * y[0][0] - Lx[q+1]*y[1][0])/Lx[r]; y [2][1] = (X [j+2][1] - Lx[p+2] * y[0][1] - Lx[q+1]*y[1][1])/Lx[r]; y [2][2] = (X [j+2][2] - Lx[p+2] * y[0][2] - Lx[q+1]*y[1][2])/Lx[r]; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; X [j+2][2] = y [2][2] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; y [2][2] = X [j+2][2] - Lx [p+2] * y [0][2] - Lx [q+1] * y [1][2] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j ][2] = y [0][2] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; X [j+1][2] = y [1][2] / Lx [q] ; X [j+2][0] = y [2][0] / Lx [r] ; X [j+2][1] = y [2][1] / Lx [r] ; X [j+2][2] = y [2][2] / Lx [r] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; y [2][2] = X [j+2][2] - Lx [p+2] * y [0][2] - Lx [q+1] * y [1][2] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; X [j+2][2] = y [2][2] ; #endif for (p += 3, q += 2, r++ ; p < pend ; p++, q++, r++) { Int i = Li [p] ; double lx [3] ; lx [0] = Lx [p] ; lx [1] = Lx [q] ; lx [2] = Lx [r] ; X [i][0] -= lx[0] * y[0][0] + lx[1] * y[1][0] + lx[2] * y[2][0]; X [i][1] -= lx[0] * y[0][1] + lx[1] * y[1][1] + lx[2] * y[2][1]; X [i][2] -= lx[0] * y[0][2] + lx[1] * y[1][2] + lx[2] * y[2][2]; } j += 3 ; /* advance to next column of L */ } } } /* ========================================================================== */ /* === LSOLVE (4) =========================================================== */ /* ========================================================================== */ /* Solve Lx=b, where b has 4 columns */ static void LSOLVE (PREFIX,4) ( cholmod_factor *L, double X [ ][4] /* n-by-4 in row form */ ) { double *Lx = L->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int j, n = L->n ; for (j = 0 ; j < n ; ) { /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* find a chain of supernodes (up to j, j+1, and j+2) */ if (lnz < 4 || lnz != Lnz [j+1] + 1 || Li [p+1] != j+1) { /* -------------------------------------------------------------- */ /* solve with a single column of L */ /* -------------------------------------------------------------- */ double y [4] ; y [0] = X [j][0] ; y [1] = X [j][1] ; y [2] = X [j][2] ; y [3] = X [j][3] ; #ifdef LL y [0] /= Lx [p] ; y [1] /= Lx [p] ; y [2] /= Lx [p] ; y [3] /= Lx [p] ; X [j][0] = y [0] ; X [j][1] = y [1] ; X [j][2] = y [2] ; X [j][3] = y [3] ; #elif defined (LD) X [j][0] = y [0] / Lx [p] ; X [j][1] = y [1] / Lx [p] ; X [j][2] = y [2] / Lx [p] ; X [j][3] = y [3] / Lx [p] ; #endif for (p++ ; p < pend ; p++) { Int i = Li [p] ; double lx = Lx [p] ; X [i][0] -= lx * y [0] ; X [i][1] -= lx * y [1] ; X [i][2] -= lx * y [2] ; X [i][3] -= lx * y [3] ; } j++ ; /* advance to next column of L */ } else if (lnz != Lnz [j+2] + 2 || Li [p+2] != j+2) { /* -------------------------------------------------------------- */ /* solve with a supernode of two columns of L */ /* -------------------------------------------------------------- */ double y [2][4] ; Int q = Lp [j+1] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; y [0][2] = X [j][2] ; y [0][3] = X [j][3] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [0][2] /= Lx [p] ; y [0][3] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx [p+1] * y [0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx [p+1] * y [0][1]) / Lx [q] ; y [1][2] = (X [j+1][2] - Lx [p+1] * y [0][2]) / Lx [q] ; y [1][3] = (X [j+1][3] - Lx [p+1] * y [0][3]) / Lx [q] ; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j ][3] = y [0][3] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+1][3] = y [1][3] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [1][3] = X [j+1][3] - Lx [p+1] * y [0][3] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j ][2] = y [0][2] / Lx [p] ; X [j ][3] = y [0][3] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; X [j+1][2] = y [1][2] / Lx [q] ; X [j+1][3] = y [1][3] / Lx [q] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [1][3] = X [j+1][3] - Lx [p+1] * y [0][3] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+1][3] = y [1][3] ; #endif for (p += 2, q++ ; p < pend ; p++, q++) { Int i = Li [p] ; double lx [2] ; lx [0] = Lx [p] ; lx [1] = Lx [q] ; X [i][0] -= lx [0] * y [0][0] + lx [1] * y [1][0] ; X [i][1] -= lx [0] * y [0][1] + lx [1] * y [1][1] ; X [i][2] -= lx [0] * y [0][2] + lx [1] * y [1][2] ; X [i][3] -= lx [0] * y [0][3] + lx [1] * y [1][3] ; } j += 2 ; /* advance to next column of L */ } else { /* -------------------------------------------------------------- */ /* solve with a supernode of three columns of L */ /* -------------------------------------------------------------- */ double y [3][4] ; Int q = Lp [j+1] ; Int r = Lp [j+2] ; y [0][0] = X [j][0] ; y [0][1] = X [j][1] ; y [0][2] = X [j][2] ; y [0][3] = X [j][3] ; #ifdef LL y [0][0] /= Lx [p] ; y [0][1] /= Lx [p] ; y [0][2] /= Lx [p] ; y [0][3] /= Lx [p] ; y [1][0] = (X [j+1][0] - Lx[p+1] * y[0][0]) / Lx [q] ; y [1][1] = (X [j+1][1] - Lx[p+1] * y[0][1]) / Lx [q] ; y [1][2] = (X [j+1][2] - Lx[p+1] * y[0][2]) / Lx [q] ; y [1][3] = (X [j+1][3] - Lx[p+1] * y[0][3]) / Lx [q] ; y [2][0] = (X [j+2][0] - Lx[p+2] * y[0][0] - Lx[q+1]*y[1][0])/Lx[r]; y [2][1] = (X [j+2][1] - Lx[p+2] * y[0][1] - Lx[q+1]*y[1][1])/Lx[r]; y [2][2] = (X [j+2][2] - Lx[p+2] * y[0][2] - Lx[q+1]*y[1][2])/Lx[r]; y [2][3] = (X [j+2][3] - Lx[p+2] * y[0][3] - Lx[q+1]*y[1][3])/Lx[r]; X [j ][0] = y [0][0] ; X [j ][1] = y [0][1] ; X [j ][2] = y [0][2] ; X [j ][3] = y [0][3] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+1][3] = y [1][3] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; X [j+2][2] = y [2][2] ; X [j+2][3] = y [2][3] ; #elif defined (LD) y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [1][3] = X [j+1][3] - Lx [p+1] * y [0][3] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; y [2][2] = X [j+2][2] - Lx [p+2] * y [0][2] - Lx [q+1] * y [1][2] ; y [2][3] = X [j+2][3] - Lx [p+2] * y [0][3] - Lx [q+1] * y [1][3] ; X [j ][0] = y [0][0] / Lx [p] ; X [j ][1] = y [0][1] / Lx [p] ; X [j ][2] = y [0][2] / Lx [p] ; X [j ][3] = y [0][3] / Lx [p] ; X [j+1][0] = y [1][0] / Lx [q] ; X [j+1][1] = y [1][1] / Lx [q] ; X [j+1][2] = y [1][2] / Lx [q] ; X [j+1][3] = y [1][3] / Lx [q] ; X [j+2][0] = y [2][0] / Lx [r] ; X [j+2][1] = y [2][1] / Lx [r] ; X [j+2][2] = y [2][2] / Lx [r] ; X [j+2][3] = y [2][3] / Lx [r] ; #else y [1][0] = X [j+1][0] - Lx [p+1] * y [0][0] ; y [1][1] = X [j+1][1] - Lx [p+1] * y [0][1] ; y [1][2] = X [j+1][2] - Lx [p+1] * y [0][2] ; y [1][3] = X [j+1][3] - Lx [p+1] * y [0][3] ; y [2][0] = X [j+2][0] - Lx [p+2] * y [0][0] - Lx [q+1] * y [1][0] ; y [2][1] = X [j+2][1] - Lx [p+2] * y [0][1] - Lx [q+1] * y [1][1] ; y [2][2] = X [j+2][2] - Lx [p+2] * y [0][2] - Lx [q+1] * y [1][2] ; y [2][3] = X [j+2][3] - Lx [p+2] * y [0][3] - Lx [q+1] * y [1][3] ; X [j+1][0] = y [1][0] ; X [j+1][1] = y [1][1] ; X [j+1][2] = y [1][2] ; X [j+1][3] = y [1][3] ; X [j+2][0] = y [2][0] ; X [j+2][1] = y [2][1] ; X [j+2][2] = y [2][2] ; X [j+2][3] = y [2][3] ; #endif for (p += 3, q += 2, r++ ; p < pend ; p++, q++, r++) { Int i = Li [p] ; double lx [3] ; lx [0] = Lx [p] ; lx [1] = Lx [q] ; lx [2] = Lx [r] ; X [i][0] -= lx[0] * y[0][0] + lx[1] * y[1][0] + lx[2] * y[2][0]; X [i][1] -= lx[0] * y[0][1] + lx[1] * y[1][1] + lx[2] * y[2][1]; X [i][2] -= lx[0] * y[0][2] + lx[1] * y[1][2] + lx[2] * y[2][2]; X [i][3] -= lx[0] * y[0][3] + lx[1] * y[1][3] + lx[2] * y[2][3]; } j += 3 ; /* advance to next column of L */ } } } #endif /* ========================================================================== */ /* === LSOLVE (k) =========================================================== */ /* ========================================================================== */ static void LSOLVE (PREFIX,k) ( cholmod_factor *L, cholmod_dense *Y, /* nr-by-n where nr is 1 to 4 */ Int *Yseti, Int ysetlen ) { double yx [2] ; #ifdef ZOMPLEX double yz [1] ; double *Lz = L->z ; double *Xz = Y->z ; #endif double *Lx = L->x ; double *Xx = Y->x ; Int *Li = L->i ; Int *Lp = L->p ; Int *Lnz = L->nz ; Int n = L->n, jj, jjiters ; ASSERT (L->xtype == Y->xtype) ; /* L and Y must have the same xtype */ ASSERT (L->n == Y->ncol) ; /* dimensions must match */ ASSERT (Y->nrow == Y->d) ; /* leading dimension of Y = # rows of Y */ ASSERT (L->xtype != CHOLMOD_PATTERN) ; /* L is not symbolic */ ASSERT (!(L->is_super)) ; /* L is simplicial LL' or LDL' */ #ifdef REAL if (Yseti == NULL) { /* ------------------------------------------------------------------ */ /* real case, no Yseti, with 1 to 4 RHS's and dynamic supernodes */ /* ------------------------------------------------------------------ */ ASSERT (Y->nrow <= 4) ; switch (Y->nrow) { case 1: LSOLVE (PREFIX,1) (L, Y->x) ; break ; case 2: LSOLVE (PREFIX,2) (L, Y->x) ; break ; case 3: LSOLVE (PREFIX,3) (L, Y->x) ; break ; case 4: LSOLVE (PREFIX,4) (L, Y->x) ; break ; } } else #endif { /* ------------------------------------------------------------------ */ /* solve a complex linear system or solve with Yseti */ /* ------------------------------------------------------------------ */ ASSERT (Y->nrow == 1) ; jjiters = Yseti ? ysetlen : n ; for (jj = 0 ; jj < jjiters ; jj++) { Int j = Yseti ? Yseti [jj] : jj ; /* get the start, end, and length of column j */ Int p = Lp [j] ; Int lnz = Lnz [j] ; Int pend = p + lnz ; /* y = X [j] ; */ ASSIGN (yx,yz,0, Xx,Xz,j) ; #ifdef LL /* y /= Lx [p] ; */ /* X [j] = y ; */ DIV_REAL (yx,yz,0, yx,yz,0, Lx,p) ; ASSIGN (Xx,Xz,j, yx,yz,0) ; #elif defined (LD) /* X [j] = y / Lx [p] ; */ DIV_REAL (Xx,Xz,j, yx,yz,0, Lx,p) ; #endif for (p++ ; p < pend ; p++) { /* X [Li [p]] -= Lx [p] * y ; */ Int i = Li [p] ; MULTSUB (Xx,Xz,i, Lx,Lz,p, yx,yz,0) ; } } } } /* prepare for the next inclusion of this file in cholmod_solve.c */ #undef LL #undef LD igraph/src/CHOLMOD/Cholesky/License.txt0000644000175100001440000000204713430770172017331 0ustar hornikusersCHOLMOD/Cholesky module, Copyright (C) 2005-2006, Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Cholesky module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA igraph/src/CHOLMOD/Cholesky/cholmod_analyze.c0000644000175100001440000010023013431000472020501 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_analyze ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Order and analyze a matrix (either simplicial or supernodal), in prepartion * for numerical factorization via cholmod_factorize or via the "expert" * routines cholmod_rowfac and cholmod_super_numeric. * * symmetric case: A or A(p,p) * unsymmetric case: AA', A(p,:)*A(p,:)', A(:,f)*A(:,f)', or A(p,f)*A(p,f)' * * For the symmetric case, only the upper or lower triangular part of A is * accessed (depending on the type of A). LL'=A (or permuted A) is analzed. * For the unsymmetric case (LL'=AA' or permuted A). * * There can be no duplicate entries in p or f. p is of length m if A is * m-by-n. f can be length 0 to n. * * In both cases, the columns of A need not be sorted. A can be in packed * or unpacked form. * * Ordering options include: * * natural: A is not permuted to reduce fill-in * given: a permutation can be provided to this routine (UserPerm) * AMD: approximate minumum degree (AMD for the symmetric case, * COLAMD for the AA' case). * METIS: nested dissection with METIS_NodeND * NESDIS: nested dissection using METIS_NodeComputeSeparator, * typically followed by a constrained minimum degree * (CAMD for the symmetric case, CCOLAMD for the AA' case). * * Multiple ordering options can be tried (up to 9 of them), and the best one * is selected (the one that gives the smallest number of nonzeros in the * simplicial factor L). If one method fails, cholmod_analyze keeps going, and * picks the best among the methods that succeeded. This routine fails (and * returns NULL) if either initial memory allocation fails, all ordering methods * fail, or the supernodal analysis (if requested) fails. By default, the 9 * methods available are: * * 1) given permutation (skipped if UserPerm is NULL) * 2) AMD (symmetric case) or COLAMD (unsymmetric case) * 3) METIS with default parameters * 4) NESDIS with default parameters (stopping the partitioning when * the graph is of size nd_small = 200 or less, remove nodes with * more than max (16, prune_dense * sqrt (n)) nodes where * prune_dense = 10, and follow partitioning with CCOLAMD, a * constrained minimum degree ordering). * 5) natural * 6) NESDIS, nd_small = 20000, prune_dense = 10 * 7) NESDIS, nd_small = 4, prune_dense = 10, no min degree * 8) NESDIS, nd_small = 200, prune_dense = 0 * 9) COLAMD for A*A' or AMD for A * * By default, the first two are tried, and METIS is tried if AMD reports a high * flop count and fill-in. Let fl denote the flop count for the AMD, ordering, * nnz(L) the # of nonzeros in L, and nnz(tril(A)) (or A*A'). If * fl/nnz(L) >= 500 and nnz(L)/nnz(tril(A)) >= 5, then METIS is attempted. The * best ordering is used (UserPerm if given, AMD, and METIS if attempted). If * you do not have METIS, only the first two will be tried (user permutation, * if provided, and AMD/COLAMD). This default behavior is obtained when * Common->nmethods is zero. In this case, methods 0, 1, and 2 in * Common->method [..] are reset to User-provided, AMD, and METIS (or NESDIS * if Common->default_nesdis is set to the non-default value of TRUE), * respectively. * * You can modify these 9 methods and the number of methods tried by changing * parameters in the Common argument. If you know the best ordering for your * matrix, set Common->nmethods to 1 and set Common->method[0].ordering to the * requested ordering method. Parameters for each method can also be modified * (refer to cholmod.h for details). * * Note that it is possible for METIS to terminate your program if it runs out * of memory. This is not the case for any CHOLMOD or minimum degree ordering * routine (AMD, COLAMD, CAMD, CCOLAMD, or CSYMAMD). Since NESDIS relies on * METIS, it too can terminate your program. * * The factor L is returned as simplicial symbolic (L->is_super FALSE) if * Common->supernodal <= CHOLMOD_SIMPLICIAL (0) or as supernodal symbolic if * Common->supernodal >= CHOLMOD_SUPERNODAL (2). If Common->supernodal is * equal to CHOLMOD_AUTO (1), then L is simplicial if the flop count per * nonzero in L is less than Common->supernodal_switch (default: 40), and * is returned as a supernodal factor otherwise. * * In both cases, L->xtype is CHOLMOD_PATTERN. * A subsequent call to cholmod_factorize will perform a * simplicial or supernodal factorization, depending on the type of L. * * For the simplicial case, L contains the fill-reducing permutation (L->Perm) * and the counts of nonzeros in each column of L (L->ColCount). For the * supernodal case, L also contains the nonzero pattern of each supernode. * * workspace: Flag (nrow), Head (nrow+1) * if symmetric: Iwork (6*nrow) * if unsymmetric: Iwork (6*nrow+ncol). * calls various ordering routines, which typically allocate O(nnz(A)) * temporary workspace ((2 to 3)*nnz(A) * sizeof (Int) is typical, but it * can be much higher if A*A' must be explicitly formed for METIS). Also * allocates up to 2 temporary (permuted/transpose) copies of the nonzero * pattern of A, and up to 3*n*sizeof(Int) additional workspace. * * Supports any xtype (pattern, real, complex, or zomplex) */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif #ifndef NPARTITION #include "cholmod_partition.h" #endif /* ========================================================================== */ /* === cholmod_analyze ====================================================== */ /* ========================================================================== */ /* Orders and analyzes A, AA', PAP', or PAA'P' and returns a symbolic factor * that can later be passed to cholmod_factorize. */ cholmod_factor *CHOLMOD(analyze) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order and analyze */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(analyze_p2) (TRUE, A, NULL, NULL, 0, Common)) ; } /* ========================================================================== */ /* === cholmod_analyze_p ==================================================== */ /* ========================================================================== */ /* Orders and analyzes A, AA', PAP', PAA'P', FF', or PFF'P and returns a * symbolic factor that can later be passed to cholmod_factorize, where * F = A(:,fset) if fset is not NULL and A->stype is zero. * UserPerm is tried if non-NULL. */ cholmod_factor *CHOLMOD(analyze_p) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order and analyze */ Int *UserPerm, /* user-provided permutation, size A->nrow */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(analyze_p2) (TRUE, A, UserPerm, fset, fsize, Common)) ; } /* ========================================================================== */ /* === permute_matrices ===================================================== */ /* ========================================================================== */ /* Permute and transpose a matrix. Allocates the A1 and A2 matrices, if needed, * or returns them as NULL if not needed. */ static int permute_matrices ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to permute */ Int ordering, /* ordering method used */ Int *Perm, /* fill-reducing permutation */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ Int do_rowcolcounts,/* if TRUE, compute both S and F. If FALSE, only * S is needed for the symmetric case, and only F for * the unsymmetric case */ /* ---- output --- */ cholmod_sparse **A1_handle, /* see comments below for A1, A2, S, F */ cholmod_sparse **A2_handle, cholmod_sparse **S_handle, cholmod_sparse **F_handle, /* --------------- */ cholmod_common *Common ) { cholmod_sparse *A1, *A2, *S, *F ; *A1_handle = NULL ; *A2_handle = NULL ; *S_handle = NULL ; *F_handle = NULL ; A1 = NULL ; A2 = NULL ; if (ordering == CHOLMOD_NATURAL) { /* ------------------------------------------------------------------ */ /* natural ordering of A */ /* ------------------------------------------------------------------ */ if (A->stype < 0) { /* symmetric lower case: A already in lower form, so S=A' */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (A, 0, NULL, NULL, 0, Common) ; F = A ; S = A2 ; } else if (A->stype > 0) { /* symmetric upper case: F = pattern of triu (A)', S = A */ /* workspace: Iwork (nrow) */ if (do_rowcolcounts) { /* F not needed for symmetric case if do_rowcolcounts FALSE */ A1 = CHOLMOD(ptranspose) (A, 0, NULL, fset, fsize, Common) ; } F = A1 ; S = A ; } else { /* unsymmetric case: F = pattern of A (:,f)', S = A */ /* workspace: Iwork (nrow if no fset, MAX(nrow,ncol) if fset) */ A1 = CHOLMOD(ptranspose) (A, 0, NULL, fset, fsize, Common) ; F = A1 ; S = A ; } } else { /* ------------------------------------------------------------------ */ /* A is permuted */ /* ------------------------------------------------------------------ */ if (A->stype < 0) { /* symmetric lower case: S = tril (A (p,p))' and F = S' */ /* workspace: Iwork (2*nrow) */ A2 = CHOLMOD(ptranspose) (A, 0, Perm, NULL, 0, Common) ; S = A2 ; /* workspace: Iwork (nrow) */ if (do_rowcolcounts) { /* F not needed for symmetric case if do_rowcolcounts FALSE */ A1 = CHOLMOD(ptranspose) (A2, 0, NULL, NULL, 0, Common) ; } F = A1 ; } else if (A->stype > 0) { /* symmetric upper case: F = triu (A (p,p))' and S = F' */ /* workspace: Iwork (2*nrow) */ A1 = CHOLMOD(ptranspose) (A, 0, Perm, NULL, 0, Common) ; F = A1 ; /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (A1, 0, NULL, NULL, 0, Common) ; S = A2 ; } else { /* unsymmetric case: F = A (p,f)' and S = F' */ /* workspace: Iwork (nrow if no fset, MAX(nrow,ncol) if fset) */ A1 = CHOLMOD(ptranspose) (A, 0, Perm, fset, fsize, Common) ; F = A1 ; if (do_rowcolcounts) { /* S not needed for unsymmetric case if do_rowcolcounts FALSE */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (A1, 0, NULL, NULL, 0, Common) ; } S = A2 ; } } /* If any cholmod_*transpose fails, one or more matrices will be NULL */ *A1_handle = A1 ; *A2_handle = A2 ; *S_handle = S ; *F_handle = F ; return (Common->status == CHOLMOD_OK) ; } /* ========================================================================== */ /* === cholmod_analyze_ordering ============================================= */ /* ========================================================================== */ /* Given a matrix A and its fill-reducing permutation, compute the elimination * tree, its (non-weighted) postordering, and the number of nonzeros in each * column of L. Also computes the flop count, the total nonzeros in L, and * the nonzeros in A (Common->fl, Common->lnz, and Common->anz). * * The column counts of L, flop count, and other statistics from * cholmod_rowcolcounts are not computed if ColCount is NULL. * * workspace: Iwork (2*nrow if symmetric, 2*nrow+ncol if unsymmetric), * Flag (nrow), Head (nrow+1) */ int CHOLMOD(analyze_ordering) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ int ordering, /* ordering method used */ Int *Perm, /* size n, fill-reducing permutation to analyze */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ Int *Parent, /* size n, elimination tree */ Int *Post, /* size n, postordering of elimination tree */ Int *ColCount, /* size n, nnz in each column of L */ /* ---- workspace */ Int *First, /* size n workspace for cholmod_postorder */ Int *Level, /* size n workspace for cholmod_postorder */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *A1, *A2, *S, *F ; Int n, ok, do_rowcolcounts ; /* check inputs */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; n = A->nrow ; do_rowcolcounts = (ColCount != NULL) ; /* permute A according to Perm and fset */ ok = permute_matrices (A, ordering, Perm, fset, fsize, do_rowcolcounts, &A1, &A2, &S, &F, Common) ; /* find etree of S (symmetric upper/lower case) or F (unsym case) */ /* workspace: symmmetric: Iwork (nrow), unsym: Iwork (nrow+ncol) */ ok = ok && CHOLMOD(etree) (A->stype ? S:F, Parent, Common) ; /* postorder the etree (required by cholmod_rowcolcounts) */ /* workspace: Iwork (2*nrow) */ ok = ok && (CHOLMOD(postorder) (Parent, n, NULL, Post, Common) == n) ; /* cholmod_postorder doesn't set Common->status if it returns < n */ Common->status = (!ok && Common->status == CHOLMOD_OK) ? CHOLMOD_INVALID : Common->status ; /* analyze LL'=S or SS' or S(:,f)*S(:,f)' */ /* workspace: * if symmetric: Flag (nrow), Iwork (2*nrow) * if unsymmetric: Flag (nrow), Iwork (2*nrow+ncol), Head (nrow+1) */ if (do_rowcolcounts) { ok = ok && CHOLMOD(rowcolcounts) (A->stype ? F:S, fset, fsize, Parent, Post, NULL, ColCount, First, Level, Common) ; } /* free temporary matrices and return result */ CHOLMOD(free_sparse) (&A1, Common) ; CHOLMOD(free_sparse) (&A2, Common) ; return (ok) ; } /* ========================================================================== */ /* === Free workspace and return L ========================================== */ /* ========================================================================== */ #define FREE_WORKSPACE_AND_RETURN \ { \ Common->no_workspace_reallocate = FALSE ; \ CHOLMOD(free) (n, sizeof (Int), Lparent, Common) ; \ CHOLMOD(free) (n, sizeof (Int), Perm, Common) ; \ CHOLMOD(free) (n, sizeof (Int), ColCount, Common) ; \ if (Common->status < CHOLMOD_OK) \ { \ CHOLMOD(free_factor) (&L, Common) ; \ } \ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; \ return (L) ; \ } /* ========================================================================== */ /* === cholmod_analyze_p2 =================================================== */ /* ========================================================================== */ /* Ordering and analysis for sparse Cholesky or sparse QR. CHOLMOD itself * always uses for_cholesky = TRUE. The for_cholesky = FALSE option is * for SuiteSparseQR only. */ cholmod_factor *CHOLMOD(analyze_p2) ( /* ---- input ---- */ int for_cholesky, /* if TRUE, then analyze for Cholesky; else for QR */ cholmod_sparse *A, /* matrix to order and analyze */ Int *UserPerm, /* user-provided permutation, size A->nrow */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* --------------- */ cholmod_common *Common ) { double lnz_best ; Int *First, *Level, *Work4n, *Cmember, *CParent, *ColCount, *Lperm, *Parent, *Post, *Perm, *Lparent, *Lcolcount ; cholmod_factor *L ; Int k, n, ordering, method, nmethods, status, default_strategy, ncol, uncol, skip_analysis, skip_best ; Int amd_backup ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, NULL) ; Common->status = CHOLMOD_OK ; status = CHOLMOD_OK ; Common->selected = EMPTY ; Common->called_nd = FALSE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ n = A->nrow ; ncol = A->ncol ; uncol = (A->stype == 0) ? (A->ncol) : 0 ; /* ---------------------------------------------------------------------- */ /* set the default strategy */ /* ---------------------------------------------------------------------- */ lnz_best = (double) EMPTY ; skip_best = FALSE ; nmethods = MIN (Common->nmethods, CHOLMOD_MAXMETHODS) ; nmethods = MAX (0, nmethods) ; #ifndef NDEBUG PRINT1 (("cholmod_analyze_p2 :: nmethods "ID"\n", nmethods)) ; for (method = 0 ; method < nmethods ; method++) { PRINT1 ((" "ID": ordering "ID"\n", method, Common->method [method].ordering)) ; } #endif default_strategy = (nmethods == 0) ; if (default_strategy) { /* default strategy: try UserPerm, if given. Try AMD for A, or AMD * to order A*A'. Try METIS for the symmetric case only if AMD reports * a high degree of fill-in and flop count. METIS is not tried if the * Partition Module isn't installed. If Common->default_nesdis is * TRUE, then NESDIS is used as the 3rd ordering instead. */ Common->method [0].ordering = CHOLMOD_GIVEN ;/* skip if UserPerm NULL */ Common->method [1].ordering = CHOLMOD_AMD ; Common->method [2].ordering = (Common->default_nesdis ? CHOLMOD_NESDIS : CHOLMOD_METIS) ; amd_backup = FALSE ; #ifndef NPARTITION nmethods = 3 ; #else nmethods = 2 ; #endif } else { /* If only METIS and NESDIS are selected, or if 2 or more methods are * being tried, then enable AMD backup */ amd_backup = (nmethods > 1) || (nmethods == 1 && (Common->method [0].ordering == CHOLMOD_METIS || Common->method [0].ordering == CHOLMOD_NESDIS)) ; } #ifdef NSUPERNODAL /* CHOLMOD Supernodal module not installed, just do simplicial analysis */ Common->supernodal = CHOLMOD_SIMPLICIAL ; #endif /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* Note: enough space needs to be allocated here so that routines called by * cholmod_analyze do not reallocate the space. */ /* s = 6*n + uncol */ s = CHOLMOD(mult_size_t) (n, 6, &ok) ; s = CHOLMOD(add_size_t) (s, uncol, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (NULL) ; /* out of memory */ } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ensure that subsequent routines, called by cholmod_analyze, do not * reallocate any workspace. This is set back to FALSE in the * FREE_WORKSPACE_AND_RETURN macro, which is the only way this function * returns to its caller. */ Common->no_workspace_reallocate = TRUE ; /* Use the last 4*n Int's in Iwork for Parent, First, Level, and Post, since * other CHOLMOD routines will use the first 2n+uncol space. The ordering * routines (cholmod_amd, cholmod_colamd, cholmod_ccolamd, cholmod_metis) * are an exception. They can use all 6n + ncol space, since the contents * of Parent, First, Level, and Post are not needed across calls to those * routines. */ Work4n = Common->Iwork ; Work4n += 2*((size_t) n) + uncol ; Parent = Work4n ; First = Work4n + n ; Level = Work4n + 2*((size_t) n) ; Post = Work4n + 3*((size_t) n) ; /* note that this assignment means that cholmod_nested_dissection, * cholmod_ccolamd, and cholmod_camd can use only the first 4n+uncol * space in Common->Iwork */ Cmember = Post ; CParent = Level ; /* ---------------------------------------------------------------------- */ /* allocate more workspace, and an empty simplicial symbolic factor */ /* ---------------------------------------------------------------------- */ L = CHOLMOD(allocate_factor) (n, Common) ; Lparent = CHOLMOD(malloc) (n, sizeof (Int), Common) ; Perm = CHOLMOD(malloc) (n, sizeof (Int), Common) ; ColCount = CHOLMOD(malloc) (n, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ FREE_WORKSPACE_AND_RETURN ; } Lperm = L->Perm ; Lcolcount = L->ColCount ; Common->anz = EMPTY ; /* ---------------------------------------------------------------------- */ /* try all the requested ordering options and backup to AMD if needed */ /* ---------------------------------------------------------------------- */ /* turn off error handling [ */ Common->try_catch = TRUE ; for (method = 0 ; method <= nmethods ; method++) { /* ------------------------------------------------------------------ */ /* determine the method to try */ /* ------------------------------------------------------------------ */ Common->fl = EMPTY ; Common->lnz = EMPTY ; skip_analysis = FALSE ; if (method == nmethods) { /* All methods failed: backup to AMD */ if (Common->selected == EMPTY && amd_backup) { PRINT1 (("All methods requested failed: backup to AMD\n")) ; ordering = CHOLMOD_AMD ; } else { break ; } } else { ordering = Common->method [method].ordering ; } Common->current = method ; PRINT1 (("method "ID": Try method: "ID"\n", method, ordering)) ; /* ------------------------------------------------------------------ */ /* find the fill-reducing permutation */ /* ------------------------------------------------------------------ */ if (ordering == CHOLMOD_NATURAL) { /* -------------------------------------------------------------- */ /* natural ordering */ /* -------------------------------------------------------------- */ for (k = 0 ; k < n ; k++) { Perm [k] = k ; } } else if (ordering == CHOLMOD_GIVEN) { /* -------------------------------------------------------------- */ /* use given ordering of A, if provided */ /* -------------------------------------------------------------- */ if (UserPerm == NULL) { /* this is not an error condition */ PRINT1 (("skip, no user perm given\n")) ; continue ; } for (k = 0 ; k < n ; k++) { /* UserPerm is checked in cholmod_ptranspose */ Perm [k] = UserPerm [k] ; } } else if (ordering == CHOLMOD_AMD) { /* -------------------------------------------------------------- */ /* AMD ordering of A, A*A', or A(:,f)*A(:,f)' */ /* -------------------------------------------------------------- */ amd_backup = FALSE ; /* no need to try AMD twice ... */ CHOLMOD(amd) (A, fset, fsize, Perm, Common) ; skip_analysis = TRUE ; } else if (ordering == CHOLMOD_COLAMD) { /* -------------------------------------------------------------- */ /* AMD for symmetric case, COLAMD for A*A' or A(:,f)*A(:,f)' */ /* -------------------------------------------------------------- */ if (A->stype) { CHOLMOD(amd) (A, fset, fsize, Perm, Common) ; skip_analysis = TRUE ; } else { /* Alternative: CHOLMOD(ccolamd) (A, fset, fsize, NULL, Perm, Common) ; */ /* do not postorder, it is done later, below */ /* workspace: Iwork (4*nrow+uncol), Flag (nrow), Head (nrow+1)*/ CHOLMOD(colamd) (A, fset, fsize, FALSE, Perm, Common) ; } } else if (ordering == CHOLMOD_METIS) { /* -------------------------------------------------------------- */ /* use METIS_NodeND directly (via a CHOLMOD wrapper) */ /* -------------------------------------------------------------- */ #ifndef NPARTITION /* postorder parameter is false, because it will be later, below */ /* workspace: Iwork (4*nrow+uncol), Flag (nrow), Head (nrow+1) */ Common->called_nd = TRUE ; CHOLMOD(metis) (A, fset, fsize, FALSE, Perm, Common) ; #else Common->status = CHOLMOD_NOT_INSTALLED ; #endif } else if (ordering == CHOLMOD_NESDIS) { /* -------------------------------------------------------------- */ /* use CHOLMOD's nested dissection */ /* -------------------------------------------------------------- */ /* this method is based on METIS' node bissection routine * (METIS_NodeComputeSeparator). In contrast to METIS_NodeND, * it calls CAMD or CCOLAMD on the whole graph, instead of MMD * on just the leaves. */ #ifndef NPARTITION /* workspace: Flag (nrow), Head (nrow+1), Iwork (2*nrow) */ Common->called_nd = TRUE ; CHOLMOD(nested_dissection) (A, fset, fsize, Perm, CParent, Cmember, Common) ; #else Common->status = CHOLMOD_NOT_INSTALLED ; #endif } else { /* -------------------------------------------------------------- */ /* invalid ordering method */ /* -------------------------------------------------------------- */ Common->status = CHOLMOD_INVALID ; PRINT1 (("No such ordering: "ID"\n", ordering)) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; if (Common->status < CHOLMOD_OK) { /* out of memory, or method failed */ status = MIN (status, Common->status) ; Common->status = CHOLMOD_OK ; continue ; } /* ------------------------------------------------------------------ */ /* analyze the ordering */ /* ------------------------------------------------------------------ */ if (!skip_analysis) { if (!CHOLMOD(analyze_ordering) (A, ordering, Perm, fset, fsize, Parent, Post, ColCount, First, Level, Common)) { /* ordering method failed; clear status and try next method */ status = MIN (status, Common->status) ; Common->status = CHOLMOD_OK ; continue ; } } ASSERT (Common->fl >= 0 && Common->lnz >= 0) ; Common->method [method].fl = Common->fl ; Common->method [method].lnz = Common->lnz ; PRINT1 (("lnz %g fl %g\n", Common->lnz, Common->fl)) ; /* ------------------------------------------------------------------ */ /* pick the best method */ /* ------------------------------------------------------------------ */ /* fl.pt. compare, but lnz can never be NaN */ if (Common->selected == EMPTY || Common->lnz < lnz_best) { Common->selected = method ; PRINT1 (("this is best so far, method "ID"\n", method)) ; L->ordering = ordering ; lnz_best = Common->lnz ; for (k = 0 ; k < n ; k++) { Lperm [k] = Perm [k] ; } /* save the results of cholmod_analyze_ordering, if it was called */ skip_best = skip_analysis ; if (!skip_analysis) { /* save the column count; becomes permanent part of L */ for (k = 0 ; k < n ; k++) { Lcolcount [k] = ColCount [k] ; } /* Parent is needed for weighted postordering and for supernodal * analysis. Does not become a permanent part of L */ for (k = 0 ; k < n ; k++) { Lparent [k] = Parent [k] ; } } } /* ------------------------------------------------------------------ */ /* determine if METIS is to be skipped */ /* ------------------------------------------------------------------ */ if (default_strategy && ordering == CHOLMOD_AMD) { if ((Common->fl < 500 * Common->lnz) || (Common->lnz < 5 * Common->anz)) { /* AMD found an ordering with less than 500 flops per nonzero in * L, or one with a fill-in ratio (nnz(L)/nnz(A)) of less than * 5. This is pretty good, and it's unlikely that METIS will do * better (this heuristic is based on tests on all symmetric * positive definite matrices in the UF sparse matrix * collection, and it works well across a wide range of * problems). METIS can take much more time than AMD. */ break ; } } } /* turn error printing back on ] */ Common->try_catch = FALSE ; /* ---------------------------------------------------------------------- */ /* return if no ordering method succeeded */ /* ---------------------------------------------------------------------- */ if (Common->selected == EMPTY) { /* All methods failed. * If two or more methods failed, they may have failed for different * reasons. Both would clear Common->status and skip to the next * method. Common->status needs to be restored here to the worst error * obtained in any of the methods. CHOLMOD_INVALID is worse * than CHOLMOD_OUT_OF_MEMORY, since the former implies something may * be wrong with the user's input. CHOLMOD_OUT_OF_MEMORY is simply an * indication of lack of resources. */ if (status >= CHOLMOD_OK) { /* this can occur if nmethods = 1, ordering = CHOLMOD_GIVEN, but UserPerm is NULL */ status = CHOLMOD_INVALID ; } ERROR (status, "all methods failed") ; FREE_WORKSPACE_AND_RETURN ; } /* ---------------------------------------------------------------------- */ /* do the analysis for AMD, if skipped */ /* ---------------------------------------------------------------------- */ Common->fl = Common->method [Common->selected].fl ; Common->lnz = Common->method [Common->selected].lnz ; ASSERT (Common->lnz >= 0) ; if (skip_best) { if (!CHOLMOD(analyze_ordering) (A, L->ordering, Lperm, fset, fsize, Lparent, Post, Lcolcount, First, Level, Common)) { /* out of memory, or method failed */ FREE_WORKSPACE_AND_RETURN ; } } /* ---------------------------------------------------------------------- */ /* postorder the etree, weighted by the column counts */ /* ---------------------------------------------------------------------- */ if (Common->postorder) { /* combine the fill-reducing ordering with the weighted postorder */ /* workspace: Iwork (2*nrow) */ if (CHOLMOD(postorder) (Lparent, n, Lcolcount, Post, Common) == n) { /* use First and Level as workspace [ */ Int *Wi = First, *InvPost = Level ; Int newchild, oldchild, newparent, oldparent ; for (k = 0 ; k < n ; k++) { Wi [k] = Lperm [Post [k]] ; } for (k = 0 ; k < n ; k++) { Lperm [k] = Wi [k] ; } for (k = 0 ; k < n ; k++) { Wi [k] = Lcolcount [Post [k]] ; } for (k = 0 ; k < n ; k++) { Lcolcount [k] = Wi [k] ; } for (k = 0 ; k < n ; k++) { InvPost [Post [k]] = k ; } /* updated Lparent needed only for supernodal case */ for (newchild = 0 ; newchild < n ; newchild++) { oldchild = Post [newchild] ; oldparent = Lparent [oldchild] ; newparent = (oldparent == EMPTY) ? EMPTY : InvPost [oldparent] ; Wi [newchild] = newparent ; } for (k = 0 ; k < n ; k++) { Lparent [k] = Wi [k] ; } /* done using Iwork as workspace ] */ /* L is now postordered, no longer in natural ordering */ if (L->ordering == CHOLMOD_NATURAL) { L->ordering = CHOLMOD_POSTORDERED ; } } } /* ---------------------------------------------------------------------- */ /* supernodal analysis, if requested or if selected automatically */ /* ---------------------------------------------------------------------- */ #ifndef NSUPERNODAL if (Common->supernodal > CHOLMOD_AUTO || (Common->supernodal == CHOLMOD_AUTO && Common->lnz > 0 && (Common->fl / Common->lnz) >= Common->supernodal_switch)) { cholmod_sparse *S, *F, *A2, *A1 ; permute_matrices (A, L->ordering, Lperm, fset, fsize, TRUE, &A1, &A2, &S, &F, Common) ; /* workspace: Flag (nrow), Head (nrow), Iwork (5*nrow) */ CHOLMOD(super_symbolic2) (for_cholesky, S, F, Lparent, L, Common) ; PRINT1 (("status %d\n", Common->status)) ; CHOLMOD(free_sparse) (&A1, Common) ; CHOLMOD(free_sparse) (&A2, Common) ; } #endif /* ---------------------------------------------------------------------- */ /* free temporary matrices and workspace, and return result L */ /* ---------------------------------------------------------------------- */ FREE_WORKSPACE_AND_RETURN ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_amd.c0000644000175100001440000001606213431000472017610 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_amd ================================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the AMD ordering routine. Orders A if the matrix is * symmetric. On output, Perm [k] = i if row/column i of A is the kth * row/column of P*A*P'. This corresponds to A(p,p) in MATLAB notation. * * If A is unsymmetric, cholmod_amd orders A*A'. On output, Perm [k] = i if * row/column i of A*A' is the kth row/column of P*A*A'*P'. This corresponds to * A(p,:)*A(p,:)' in MATLAB notation. If f is present, A(p,f)*A(p,f)' is * ordered. * * Computes the flop count for a subsequent LL' factorization, the number * of nonzeros in L, and the number of nonzeros in the matrix ordered (A, * A*A' or A(:,f)*A(:,f)'). * * workspace: Iwork (6*nrow). Head (nrow). * * Allocates a temporary copy of A+A' or A*A' (with * both upper and lower triangular parts) as input to AMD. * * Supports any xtype (pattern, real, complex, or zomplex) */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "amd.h" #include "cholmod_cholesky.h" #if (!defined (AMD_VERSION) || (AMD_VERSION < AMD_VERSION_CODE (2,0))) #error "AMD v2.0 or later is required" #endif /* ========================================================================== */ /* === cholmod_amd ========================================================== */ /* ========================================================================== */ int CHOLMOD(amd) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { double Info [AMD_INFO], Control2 [AMD_CONTROL], *Control ; Int *Cp, *Len, *Nv, *Head, *Elen, *Degree, *Wi, *Iwork, *Next ; cholmod_sparse *C ; Int j, n, cnz ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; n = A->nrow ; RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; if (n == 0) { /* nothing to do */ Common->fl = 0 ; Common->lnz = 0 ; Common->anz = 0 ; return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ /* Note: this is less than the space used in cholmod_analyze, so if * cholmod_amd is being called by that routine, no space will be * allocated. */ /* s = MAX (6*n, A->ncol) */ s = CHOLMOD(mult_size_t) (n, 6, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } s = MAX (s, A->ncol) ; CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } Iwork = Common->Iwork ; Degree = Iwork ; /* size n */ Wi = Iwork + n ; /* size n */ Len = Iwork + 2*((size_t) n) ; /* size n */ Nv = Iwork + 3*((size_t) n) ; /* size n */ Next = Iwork + 4*((size_t) n) ; /* size n */ Elen = Iwork + 5*((size_t) n) ; /* size n */ Head = Common->Head ; /* size n+1, but only n is used */ /* ---------------------------------------------------------------------- */ /* construct the input matrix for AMD */ /* ---------------------------------------------------------------------- */ if (A->stype == 0) { /* C = A*A' or A(:,f)*A(:,f)', add extra space of nnz(C)/2+n to C */ C = CHOLMOD(aat) (A, fset, fsize, -2, Common) ; } else { /* C = A+A', but use only the upper triangular part of A if A->stype = 1 * and only the lower part of A if A->stype = -1. Add extra space of * nnz(C)/2+n to C. */ C = CHOLMOD(copy) (A, 0, -2, Common) ; } if (Common->status < CHOLMOD_OK) { /* out of memory, fset invalid, or other error */ return (FALSE) ; } Cp = C->p ; for (j = 0 ; j < n ; j++) { Len [j] = Cp [j+1] - Cp [j] ; } /* C does not include the diagonal, and both upper and lower parts. * Common->anz includes the diagonal, and just the lower part of C */ cnz = Cp [n] ; Common->anz = cnz / 2 + n ; /* ---------------------------------------------------------------------- */ /* order C using AMD */ /* ---------------------------------------------------------------------- */ /* get parameters */ if (Common->current < 0 || Common->current >= CHOLMOD_MAXMETHODS) { /* use AMD defaults */ Control = NULL ; } else { Control = Control2 ; Control [AMD_DENSE] = Common->method [Common->current].prune_dense ; Control [AMD_AGGRESSIVE] = Common->method [Common->current].aggressive ; } /* AMD_2 does not use amd_malloc and amd_free, but set these pointers just * be safe. */ amd_malloc = Common->malloc_memory ; amd_free = Common->free_memory ; amd_calloc = Common->calloc_memory ; amd_realloc = Common->realloc_memory ; /* AMD_2 doesn't print anything either, but future versions might, * so set the amd_printf pointer too. */ amd_printf = Common->print_function ; #ifdef LONG amd_l2 (n, C->p, C->i, Len, C->nzmax, cnz, Nv, Next, Perm, Head, Elen, Degree, Wi, Control, Info) ; #else amd_2 (n, C->p, C->i, Len, C->nzmax, cnz, Nv, Next, Perm, Head, Elen, Degree, Wi, Control, Info) ; #endif /* LL' flop count. Need to subtract n for LL' flop count. Note that this * is a slight upper bound which is often exact (see AMD/Source/amd_2.c for * details). cholmod_analyze computes an exact flop count and fill-in. */ Common->fl = Info [AMD_NDIV] + 2 * Info [AMD_NMULTSUBS_LDL] + n ; /* Info [AMD_LNZ] excludes the diagonal */ Common->lnz = n + Info [AMD_LNZ] ; /* ---------------------------------------------------------------------- */ /* free the AMD workspace and clear the persistent workspace in Common */ /* ---------------------------------------------------------------------- */ ASSERT (IMPLIES (Common->status == CHOLMOD_OK, CHOLMOD(dump_perm) (Perm, n, n, "AMD2 perm", Common))) ; CHOLMOD(free_sparse) (&C, Common) ; for (j = 0 ; j <= n ; j++) { Head [j] = EMPTY ; } return (TRUE) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_rcond.c0000644000175100001440000001144213431000472020151 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_rcond =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Return a rough estimate of the reciprocal of the condition number: * the minimum entry on the diagonal of L (or absolute entry of D for an LDL' * factorization) divided by the maximum entry (squared for LL'). L can be * real, complex, or zomplex. Returns -1 on error, 0 if the matrix is singular * or has a zero entry on the diagonal of L, 1 if the matrix is 0-by-0, or * min(diag(L))/max(diag(L)) otherwise. Never returns NaN; if L has a NaN on * the diagonal it returns zero instead. * * For an LL' factorization, (min(diag(L))/max(diag(L)))^2 is returned. * For an LDL' factorization, (min(diag(D))/max(diag(D))) is returned. */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === LMINMAX ============================================================== */ /* ========================================================================== */ /* Update lmin and lmax for one entry L(j,j) */ #define FIRST_LMINMAX(Ljj,lmin,lmax) \ { \ double ljj = Ljj ; \ if (IS_NAN (ljj)) \ { \ return (0) ; \ } \ lmin = ljj ; \ lmax = ljj ; \ } #define LMINMAX(Ljj,lmin,lmax) \ { \ double ljj = Ljj ; \ if (IS_NAN (ljj)) \ { \ return (0) ; \ } \ if (ljj < lmin) \ { \ lmin = ljj ; \ } \ else if (ljj > lmax) \ { \ lmax = ljj ; \ } \ } /* ========================================================================== */ /* === cholmod_rcond ======================================================== */ /* ========================================================================== */ double CHOLMOD(rcond) /* return min(diag(L)) / max(diag(L)) */ ( /* ---- input ---- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) { double lmin, lmax, rcond ; double *Lx ; Int *Lpi, *Lpx, *Super, *Lp ; Int n, e, nsuper, s, k1, k2, psi, psend, psx, nsrow, nscol, jj, j ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (L, EMPTY) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ n = L->n ; if (n == 0) { return (1) ; } if (L->minor < L->n) { return (0) ; } e = (L->xtype == CHOLMOD_COMPLEX) ? 2 : 1 ; if (L->is_super) { /* L is supernodal */ nsuper = L->nsuper ; /* number of supernodes in L */ Lpi = L->pi ; /* column pointers for integer pattern */ Lpx = L->px ; /* column pointers for numeric values */ Super = L->super ; /* supernode sizes */ Lx = L->x ; /* numeric values */ FIRST_LMINMAX (Lx [0], lmin, lmax) ; /* first diagonal entry of L */ for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; /* first column in supernode s */ k2 = Super [s+1] ; /* last column in supernode is k2-1 */ psi = Lpi [s] ; /* first row index is L->s [psi] */ psend = Lpi [s+1] ; /* last row index is L->s [psend-1] */ psx = Lpx [s] ; /* first numeric entry is Lx [psx] */ nsrow = psend - psi ; /* supernode is nsrow-by-nscol */ nscol = k2 - k1 ; for (jj = 0 ; jj < nscol ; jj++) { LMINMAX (Lx [e * (psx + jj + jj*nsrow)], lmin, lmax) ; } } } else { /* L is simplicial */ Lp = L->p ; Lx = L->x ; if (L->is_ll) { /* LL' factorization */ FIRST_LMINMAX (Lx [Lp [0]], lmin, lmax) ; for (j = 1 ; j < n ; j++) { LMINMAX (Lx [e * Lp [j]], lmin, lmax) ; } } else { /* LDL' factorization, the diagonal might be negative */ FIRST_LMINMAX (fabs (Lx [Lp [0]]), lmin, lmax) ; for (j = 1 ; j < n ; j++) { LMINMAX (fabs (Lx [e * Lp [j]]), lmin, lmax) ; } } } rcond = lmin / lmax ; if (L->is_ll) { rcond = rcond*rcond ; } return (rcond) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_factorize.c0000644000175100001440000003430113431000472021031 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_factorize =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Computes the numerical factorization of a symmetric matrix. The primary * inputs to this routine are a sparse matrix A and the symbolic factor L from * cholmod_analyze or a prior numerical factor L. If A is symmetric, this * routine factorizes A(p,p)+beta*I (beta can be zero), where p is the * fill-reducing permutation (L->Perm). If A is unsymmetric, either * A(p,:)*A(p,:)'+beta*I or A(p,f)*A(p,f)'+beta*I is factorized. The set f and * the nonzero pattern of the matrix A must be the same as the matrix passed to * cholmod_analyze for the supernodal case. For the simplicial case, it can * be different, but it should be the same for best performance. beta is real. * * A simplicial factorization or supernodal factorization is chosen, based on * the type of the factor L. If L->is_super is TRUE, a supernodal LL' * factorization is computed. Otherwise, a simplicial numeric factorization * is computed, either LL' or LDL', depending on Common->final_ll. * * Once the factorization is complete, it can be left as is or optionally * converted into any simplicial numeric type, depending on the * Common->final_* parameters. If converted from a supernodal to simplicial * type, and the Common->final_resymbol parameter is true, then numerically * zero entries in L due to relaxed supernodal amalgamation are removed from * the simplicial factor (they are always left in the supernodal form of L). * Entries that are numerically zero but present in the simplicial symbolic * pattern of L are left in place (that is, the graph of L remains chordal). * This is required for the update/downdate/rowadd/rowdel routines to work * properly. * * workspace: Flag (nrow), Head (nrow+1), * if symmetric: Iwork (2*nrow+2*nsuper) * if unsymmetric: Iwork (2*nrow+MAX(2*nsuper,ncol)) * where nsuper is 0 if simplicial, or the # of relaxed supernodes in * L otherwise (nsuper <= nrow). * if simplicial: W (nrow). * Allocates up to two temporary copies of its input matrix (including * both pattern and numerical values). * * If the matrix is not positive definite the routine returns TRUE, but * sets Common->status to CHOLMOD_NOT_POSDEF and L->minor is set to the * column at which the failure occurred. Columns L->minor to L->n-1 are * set to zero. * * Supports any xtype (pattern, real, complex, or zomplex), except that the * input matrix A cannot be pattern-only. If L is simplicial, its numeric * xtype matches A on output. If L is supernodal, its xtype is real if A is * real, or complex if A is complex or zomplex. */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" #ifndef NSUPERNODAL #include "cholmod_supernodal.h" #endif /* ========================================================================== */ /* === cholmod_factorize ==================================================== */ /* ========================================================================== */ /* Factorizes PAP' (or PAA'P' if A->stype is 0), using a factor obtained * from cholmod_analyze. The analysis can be re-used simply by calling this * routine a second time with another matrix. A must have the same nonzero * pattern as that passed to cholmod_analyze. */ int CHOLMOD(factorize) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ /* ---- in/out --- */ cholmod_factor *L, /* resulting factorization */ /* --------------- */ cholmod_common *Common ) { double zero [2] ; zero [0] = 0 ; zero [1] = 0 ; return (CHOLMOD(factorize_p) (A, zero, NULL, 0, L, Common)) ; } /* ========================================================================== */ /* === cholmod_factorize_p ================================================== */ /* ========================================================================== */ /* Same as cholmod_factorize, but with more options. */ int CHOLMOD(factorize_p) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ double beta [2], /* factorize beta*I+A or beta*I+A'*A */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- in/out --- */ cholmod_factor *L, /* resulting factorization */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *S, *F, *A1, *A2 ; Int nrow, ncol, stype, convert, n, nsuper, grow2, status ; size_t s, t, uncol ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; nrow = A->nrow ; ncol = A->ncol ; n = L->n ; stype = A->stype ; if (L->n != A->nrow) { ERROR (CHOLMOD_INVALID, "A and L dimensions do not match") ; return (FALSE) ; } if (stype != 0 && nrow != ncol) { ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (FALSE) ; } DEBUG (CHOLMOD(dump_sparse) (A, "A for cholmod_factorize", Common)) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ nsuper = (L->is_super ? L->nsuper : 0) ; uncol = ((stype != 0) ? 0 : ncol) ; /* s = 2*nrow + MAX (uncol, 2*nsuper) */ s = CHOLMOD(mult_size_t) (nsuper, 2, &ok) ; s = MAX (uncol, s) ; t = CHOLMOD(mult_size_t) (nrow, 2, &ok) ; s = CHOLMOD(add_size_t) (s, t, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (nrow, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } S = NULL ; F = NULL ; A1 = NULL ; A2 = NULL ; /* convert to another form when done, if requested */ convert = !(Common->final_asis) ; /* ---------------------------------------------------------------------- */ /* perform supernodal LL' or simplicial LDL' factorization */ /* ---------------------------------------------------------------------- */ if (L->is_super) { #ifndef NSUPERNODAL /* ------------------------------------------------------------------ */ /* supernodal factorization */ /* ------------------------------------------------------------------ */ if (L->ordering == CHOLMOD_NATURAL) { /* -------------------------------------------------------------- */ /* natural ordering */ /* -------------------------------------------------------------- */ if (stype > 0) { /* S = tril (A'), F not needed */ /* workspace: Iwork (nrow) */ A1 = CHOLMOD(ptranspose) (A, 2, NULL, NULL, 0, Common) ; S = A1 ; } else if (stype < 0) { /* This is the fastest option for the natural ordering */ /* S = A; F not needed */ S = A ; } else { /* F = A(:,f)' */ /* workspace: Iwork (nrow) */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ A1 = CHOLMOD(ptranspose) (A, 2, NULL, fset, fsize, Common) ; F = A1 ; /* S = A */ S = A ; } } else { /* -------------------------------------------------------------- */ /* permute the input matrix before factorization */ /* -------------------------------------------------------------- */ if (stype > 0) { /* This is the fastest option for factoring a permuted matrix */ /* S = tril (PAP'); F not needed */ /* workspace: Iwork (2*nrow) */ A1 = CHOLMOD(ptranspose) (A, 2, L->Perm, NULL, 0, Common) ; S = A1 ; } else if (stype < 0) { /* A2 = triu (PAP') */ /* workspace: Iwork (2*nrow) */ A2 = CHOLMOD(ptranspose) (A, 2, L->Perm, NULL, 0, Common) ; /* S = tril (A2'); F not needed */ /* workspace: Iwork (nrow) */ A1 = CHOLMOD(ptranspose) (A2, 2, NULL, NULL, 0, Common) ; S = A1 ; CHOLMOD(free_sparse) (&A2, Common) ; ASSERT (A2 == NULL) ; } else { /* F = A(p,f)' */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ A1 = CHOLMOD(ptranspose) (A, 2, L->Perm, fset, fsize, Common) ; F = A1 ; /* S = F' */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (F, 2, NULL, NULL, 0, Common) ; S = A2 ; } } /* ------------------------------------------------------------------ */ /* supernodal factorization */ /* ------------------------------------------------------------------ */ /* workspace: Flag (nrow), Head (nrow+1), Iwork (2*nrow+2*nsuper) */ if (Common->status == CHOLMOD_OK) { CHOLMOD(super_numeric) (S, F, beta, L, Common) ; } status = Common->status ; ASSERT (IMPLIES (status >= CHOLMOD_OK, L->xtype != CHOLMOD_PATTERN)) ; /* ------------------------------------------------------------------ */ /* convert to final form, if requested */ /* ------------------------------------------------------------------ */ if (Common->status >= CHOLMOD_OK && convert) { /* workspace: none */ ok = CHOLMOD(change_factor) (L->xtype, Common->final_ll, Common->final_super, Common->final_pack, Common->final_monotonic, L, Common) ; if (ok && Common->final_resymbol && !(L->is_super)) { /* workspace: Flag (nrow), Head (nrow+1), * if symmetric: Iwork (2*nrow) * if unsymmetric: Iwork (2*nrow+ncol) */ CHOLMOD(resymbol_noperm) (S, fset, fsize, Common->final_pack, L, Common) ; } } #else /* ------------------------------------------------------------------ */ /* CHOLMOD Supernodal module not installed */ /* ------------------------------------------------------------------ */ status = CHOLMOD_NOT_INSTALLED ; ERROR (CHOLMOD_NOT_INSTALLED,"Supernodal module not installed") ; #endif } else { /* ------------------------------------------------------------------ */ /* simplicial LDL' factorization */ /* ------------------------------------------------------------------ */ /* Permute the input matrix A if necessary. cholmod_rowfac requires * triu(A) in column form for the symmetric case, and A in column form * for the unsymmetric case (the matrix S). The unsymmetric case * requires A in row form, or equivalently A' in column form (the * matrix F). */ if (L->ordering == CHOLMOD_NATURAL) { /* -------------------------------------------------------------- */ /* natural ordering */ /* -------------------------------------------------------------- */ if (stype > 0) { /* F is not needed, S = A */ S = A ; } else if (stype < 0) { /* F is not needed, S = A' */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (A, 2, NULL, NULL, 0, Common) ; S = A2 ; } else { /* F = A (:,f)' */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ A1 = CHOLMOD(ptranspose) (A, 2, NULL, fset, fsize, Common) ; F = A1 ; S = A ; } } else { /* -------------------------------------------------------------- */ /* permute the input matrix before factorization */ /* -------------------------------------------------------------- */ if (stype > 0) { /* F = tril (A (p,p)') */ /* workspace: Iwork (2*nrow) */ A1 = CHOLMOD(ptranspose) (A, 2, L->Perm, NULL, 0, Common) ; /* A2 = triu (F') */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (A1, 2, NULL, NULL, 0, Common) ; /* the symmetric case does not need F, free it and set to NULL*/ CHOLMOD(free_sparse) (&A1, Common) ; } else if (stype < 0) { /* A2 = triu (A (p,p)'), F not needed. This is the fastest * way to factorize a matrix using the simplicial routine * (cholmod_rowfac). */ /* workspace: Iwork (2*nrow) */ A2 = CHOLMOD(ptranspose) (A, 2, L->Perm, NULL, 0, Common) ; } else { /* F = A (p,f)' */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset)*/ A1 = CHOLMOD(ptranspose) (A, 2, L->Perm, fset, fsize, Common) ; F = A1 ; /* A2 = F' */ /* workspace: Iwork (nrow) */ A2 = CHOLMOD(ptranspose) (F, 2, NULL, NULL, 0, Common) ; } S = A2 ; } /* ------------------------------------------------------------------ */ /* simplicial LDL' or LL' factorization */ /* ------------------------------------------------------------------ */ /* factorize beta*I+S (symmetric) or beta*I+F*F' (unsymmetric) */ /* workspace: Flag (nrow), W (nrow), Iwork (2*nrow) */ if (Common->status == CHOLMOD_OK) { grow2 = Common->grow2 ; L->is_ll = BOOLEAN (Common->final_ll) ; if (L->xtype == CHOLMOD_PATTERN && Common->final_pack) { /* allocate a factor with exactly the space required */ Common->grow2 = 0 ; } CHOLMOD(rowfac) (S, F, beta, 0, nrow, L, Common) ; Common->grow2 = grow2 ; } status = Common->status ; /* ------------------------------------------------------------------ */ /* convert to final form, if requested */ /* ------------------------------------------------------------------ */ if (Common->status >= CHOLMOD_OK && convert) { /* workspace: none */ CHOLMOD(change_factor) (L->xtype, L->is_ll, FALSE, Common->final_pack, Common->final_monotonic, L, Common) ; } } /* ---------------------------------------------------------------------- */ /* free A1 and A2 if they exist */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&A1, Common) ; CHOLMOD(free_sparse) (&A2, Common) ; Common->status = MAX (Common->status, status) ; return (Common->status >= CHOLMOD_OK) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_rowfac.c0000644000175100001440000005652513431000472020340 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_rowfac ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Full or incremental numerical LDL' or LL' factorization (simplicial, not * supernodal) cholmod_factorize is the "easy" wrapper for this code, but it * does not provide access to incremental factorization. * * cholmod_rowfac computes the full or incremental LDL' or LL' factorization of * A+beta*I (where A is symmetric) or A*F+beta*I (where A and F are unsymmetric * and only the upper triangular part of A*F+beta*I is used). It computes * L (and D, for LDL') one row at a time. beta is real. * * A is nrow-by-ncol or nrow-by-nrow. In "packed" form it is a conventional * column-oriented sparse matrix. Row indices of column j are in * Ai [Ap [j] ... Ap [j+1]-1] and values in the same locations of Ax. * will be faster if A has sorted columns. In "unpacked" form the column * of A ends at Ap [j] + Anz [j] - 1 instead of Ap [j+1] - 1. * * Row indices in each column of A can be sorted or unsorted, but the routine * routine works fastest if A is sorted, or if only triu(A) is provided * for the symmetric case. * * The unit-diagonal nrow-by-nrow output matrix L is returned in "unpacked" * column form, with row indices of column j in Li [Lp [j] ... * Lp [j] + Lnz [j] - 1] and values in the same location in Lx. The row * indices in each column of L are in sorted order. The unit diagonal of L * is not stored. * * L can be a simplicial symbolic or numeric (L->is_super must be FALSE). * A symbolic factor is converted immediately into a numeric factor containing * the identity matrix. * * For a full factorization, kstart = 0 and kend = nrow. The existing nonzero * entries (numerical values in L->x and L->z for the zomplex case, and indices * in L->i), if any, are overwritten. * * To compute an incremental factorization, select kstart and kend as the range * of rows of L you wish to compute. A correct factorization will be computed * only if all descendants of all nodes k = kstart to kend-1 in the etree have * been factorized by a prior call to this routine, and if rows kstart to kend-1 * have not been factorized. This condition is NOT checked on input. * * --------------- * Symmetric case: * --------------- * * The factorization (in MATLAB notation) is: * * S = beta*I + A * S = triu (S) + triu (S,1)' * L*D*L' = S, or L*L' = S * * A is a conventional sparse matrix in compressed column form. Only the * diagonal and upper triangular part of A is accessed; the lower * triangular part is ignored and assumed to be equal to the upper * triangular part. For an incremental factorization, only columns kstart * to kend-1 of A are accessed. F is not used. * * --------------- * Unsymmetric case: * --------------- * * The factorization (in MATLAB notation) is: * * S = beta*I + A*F * S = triu (S) + triu (S,1)' * L*D*L' = S, or L*L' = S * * The typical case is F=A'. Alternatively, if F=A(:,f)', then this * routine factorizes S = beta*I + A(:,f)*A(:,f)'. * * All of A and F are accessed, but only the upper triangular part of A*F * is used. F must be of size A->ncol by A->nrow. F is used for the * unsymmetric case only. F can be packed or unpacked and it need not be * sorted. * * For a complete factorization of beta*I + A*A', * this routine performs a number of flops exactly equal to: * * sum (for each column j of A) of (Anz (j)^2 + Anz (j)), to form S * + * sum (for each column j of L) of (Lnz (j)^2 + 3*Lnz (j)), to factorize S * * where Anz (j) is the number of nonzeros in column j of A, and Lnz (j) * is the number of nonzero in column j of L below the diagonal. * * * workspace: Flag (nrow), W (nrow if real, 2*nrow if complex/zomplex), * Iwork (nrow) * * Supports any xtype, except a pattern-only input matrix A cannot be * factorized. */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === subtree ============================================================== */ /* ========================================================================== */ /* Compute the nonzero pattern of the sparse triangular solve Lx=b, where L in * this case is L(0:k-1,0:k-1), and b is a column of A. This is done by * traversing the kth row-subtree of the elimination tree of L, starting from * each nonzero entry in b. The pattern is returned postordered, and is valid * for a subsequent numerical triangular solve of Lx=b. The elimination tree * can be provided in a Parent array, or extracted from the pattern of L itself. * * The pattern of x = inv(L)*b is returned in Stack [top...]. * Also scatters b, or a multiple of b, into the work vector W. * * The SCATTER macro is defines how the numerical values of A or A*A' are to be * scattered. * * PARENT(i) is a macro the defines how the etree is accessed. It is either: * #define PARENT(i) Parent [i] * #define PARENT(i) (Lnz [i] > 1) ? (Li [Lp [i] + 1]) : EMPTY */ #define SUBTREE \ for ( ; p < pend ; p++) \ { \ i = Ai [p] ; \ if (i <= k) \ { \ /* scatter the column of A, or A*A' into Wx and Wz */ \ SCATTER ; \ /* start at node i and traverse up the subtree, stop at node k */ \ for (len = 0 ; i < k && i != EMPTY && Flag [i] < mark ; i = parent) \ { \ /* L(k,i) is nonzero, and seen for the first time */ \ Stack [len++] = i ; /* place i on the stack */ \ Flag [i] = mark ; /* mark i as visited */ \ parent = PARENT (i) ; /* traverse up the etree to the parent */ \ } \ /* move the path down to the bottom of the stack */ \ while (len > 0) \ { \ Stack [--top] = Stack [--len] ; \ } \ } \ else if (sorted) \ { \ break ; \ } \ } /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define REAL #include "t_cholmod_rowfac.c" #define COMPLEX #include "t_cholmod_rowfac.c" #define ZOMPLEX #include "t_cholmod_rowfac.c" #define MASK #define REAL #include "t_cholmod_rowfac.c" #define COMPLEX #include "t_cholmod_rowfac.c" #define ZOMPLEX #include "t_cholmod_rowfac.c" #undef MASK /* ========================================================================== */ /* === cholmod_row_subtree ================================================== */ /* ========================================================================== */ /* Compute the nonzero pattern of the solution to the lower triangular system * L(0:k-1,0:k-1) * x = A (0:k-1,k) if A is symmetric, or * L(0:k-1,0:k-1) * x = A (0:k-1,:) * A (:,k)' if A is unsymmetric. * This gives the nonzero pattern of row k of L (excluding the diagonal). * The pattern is returned postordered. * * The symmetric case requires A to be in symmetric-upper form. * * The result is returned in R, a pre-allocated sparse matrix of size nrow-by-1, * with R->nzmax >= nrow. R is assumed to be packed (Rnz [0] is not updated); * the number of entries in R is given by Rp [0]. * * FUTURE WORK: a very minor change to this routine could allow it to compute * the nonzero pattern of x for any system Lx=b. The SUBTREE macro would need * to change, to eliminate its dependence on k. * * workspace: Flag (nrow) */ int CHOLMOD(row_subtree) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,f)' */ size_t krow, /* row k of L */ Int *Parent, /* elimination tree */ /* ---- output --- */ cholmod_sparse *R, /* pattern of L(k,:), 1-by-n with R->nzmax >= n */ /* --------------- */ cholmod_common *Common ) { Int *Rp, *Stack, *Flag, *Ap, *Ai, *Anz, *Fp, *Fi, *Fnz ; Int p, pend, parent, t, stype, nrow, k, pf, pfend, Fpacked, packed, sorted, top, len, i, mark ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (R, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (R, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; stype = A->stype ; if (stype == 0) { RETURN_IF_NULL (F, FALSE) ; RETURN_IF_XTYPE_INVALID (F, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; } if (krow >= A->nrow) { ERROR (CHOLMOD_INVALID, "subtree: k invalid") ; return (FALSE) ; } if (R->ncol != 1 || A->nrow != R->nrow || A->nrow > R->nzmax) { ERROR (CHOLMOD_INVALID, "subtree: R invalid") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; CHOLMOD(allocate_work) (nrow, 0, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ if (stype > 0) { /* symmetric upper case: F is not needed. It may be NULL */ Fp = NULL ; Fi = NULL ; Fnz = NULL ; Fpacked = TRUE ; } else if (stype == 0) { /* unsymmetric case: F is required. */ Fp = F->p ; Fi = F->i ; Fnz = F->nz ; Fpacked = F->packed ; } else { /* symmetric lower triangular form not supported */ ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE) ; } Ap = A->p ; Ai = A->i ; Anz = A->nz ; packed = A->packed ; sorted = A->sorted ; k = krow ; Stack = R->i ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size nrow, Flag [i] < mark must hold */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* ---------------------------------------------------------------------- */ /* compute the pattern of L(k,:) */ /* ---------------------------------------------------------------------- */ top = nrow ; /* Stack is empty */ Flag [k] = mark ; /* do not include diagonal entry in Stack */ #define SCATTER /* do not scatter numerical values */ #define PARENT(i) Parent [i] /* use Parent for etree */ if (stype != 0) { /* scatter kth col of triu (A), get pattern L(k,:) */ p = Ap [k] ; pend = (packed) ? (Ap [k+1]) : (p + Anz [k]) ; SUBTREE ; } else { /* scatter kth col of triu (beta*I+AA'), get pattern L(k,:) */ pf = Fp [k] ; pfend = (Fpacked) ? (Fp [k+1]) : (pf + Fnz [k]) ; for ( ; pf < pfend ; pf++) { /* get nonzero entry F (t,k) */ t = Fi [pf] ; p = Ap [t] ; pend = (packed) ? (Ap [t+1]) : (p + Anz [t]) ; SUBTREE ; } } #undef SCATTER #undef PARENT /* shift the stack upwards, to the first part of R */ len = nrow - top ; for (i = 0 ; i < len ; i++) { Stack [i] = Stack [top + i] ; } Rp = R->p ; Rp [0] = 0 ; Rp [1] = len ; R->sorted = FALSE ; CHOLMOD(clear_flag) (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_lsolve_pattern =============================================== */ /* ========================================================================== */ /* Compute the nonzero pattern of Y=L\B. L must be simplicial, and B * must be a single sparse column vector with B->stype = 0. The values of * B are not used; it just specifies a nonzero pattern. The pattern of * Y is not sorted, but is in topological order instead (suitable for a * sparse forward/backsolve). */ int CHOLMOD(lsolve_pattern) ( /* ---- input ---- */ cholmod_sparse *B, /* sparse right-hand-side (a single sparse column) */ cholmod_factor *L, /* the factor L from which parent(i) is derived */ /* ---- output --- */ cholmod_sparse *Yset, /* pattern of Y=L\B, n-by-1 with Y->nzmax >= n */ /* --------------- */ cholmod_common *Common ) { size_t krow ; RETURN_IF_NULL (B, FALSE) ; krow = B->nrow ; return (CHOLMOD(row_lsubtree) (B, NULL, 0, krow, L, Yset, Common)) ; } /* ========================================================================== */ /* === cholmod_row_lsubtree ================================================= */ /* ========================================================================== */ /* Identical to cholmod_row_subtree, except that the elimination tree is * obtained from L itself, as the first off-diagonal entry in each column. * L must be simplicial, not supernodal. * * If krow = A->nrow, then A must be a single sparse column vector, (A->stype * must be zero), and the nonzero pattern of x=L\b is computed, where b=A(:,0) * is the single sparse right-hand-side. The inputs Fi and fnz are ignored. * See CHOLMOD(lsolve_pattern) above for a simpler interface for this case. */ int CHOLMOD(row_lsubtree) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ Int *Fi, size_t fnz, /* nonzero pattern of kth row of A', not required * for the symmetric case. Need not be sorted. */ size_t krow, /* row k of L */ cholmod_factor *L, /* the factor L from which parent(i) is derived */ /* ---- output --- */ cholmod_sparse *R, /* pattern of L(k,:), n-by-1 with R->nzmax >= n */ /* --------------- */ cholmod_common *Common ) { Int *Rp, *Stack, *Flag, *Ap, *Ai, *Anz, *Lp, *Li, *Lnz ; Int p, pend, parent, t, stype, nrow, k, pf, packed, sorted, top, len, i, mark, ka ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (R, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (R, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; nrow = A->nrow ; stype = A->stype ; if (stype < 0) { /* symmetric lower triangular form not supported */ ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE) ; } if (krow > nrow) { ERROR (CHOLMOD_INVALID, "lsubtree: krow invalid") ; return (FALSE) ; } else if (krow == nrow) { /* find pattern of x=L\b where b=A(:,0) */ k = nrow ; /* compute all of the result; don't stop in SUBTREE */ ka = 0 ; /* use column A(:,0) */ if (stype != 0 || A->ncol != 1) { /* A must be unsymmetric (it's a single sparse column vector) */ ERROR (CHOLMOD_INVALID, "lsubtree: A invalid") ; return (FALSE) ; } } else { /* find pattern of L(k,:) using A(:,k) and Fi if A unsymmetric */ k = krow ; /* which row of L to compute */ ka = k ; /* which column of A to use */ if (stype == 0) { RETURN_IF_NULL (Fi, FALSE) ; } } if (R->ncol != 1 || nrow != R->nrow || nrow > R->nzmax || ka >= A->ncol) { ERROR (CHOLMOD_INVALID, "lsubtree: R invalid") ; return (FALSE) ; } if (L->is_super) { ERROR (CHOLMOD_INVALID, "lsubtree: L invalid (cannot be supernodal)") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(allocate_work) (nrow, 0, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Anz = A->nz ; packed = A->packed ; sorted = A->sorted ; Stack = R->i ; Lp = L->p ; Li = L->i ; Lnz = L->nz ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size nrow, Flag [i] < mark must hold */ mark = CHOLMOD(clear_flag) (Common) ; /* ---------------------------------------------------------------------- */ /* compute the pattern of L(k,:) */ /* ---------------------------------------------------------------------- */ top = nrow ; /* Stack is empty */ if (k < nrow) { Flag [k] = mark ; /* do not include diagonal entry in Stack */ } #define SCATTER /* do not scatter numerical values */ #define PARENT(i) (Lnz [i] > 1) ? (Li [Lp [i] + 1]) : EMPTY if (krow == nrow || stype != 0) { /* scatter kth col of triu (A), get pattern L(k,:) */ p = Ap [ka] ; pend = (packed) ? (Ap [ka+1]) : (p + Anz [ka]) ; SUBTREE ; } else { /* scatter kth col of triu (beta*I+AA'), get pattern L(k,:) */ for (pf = 0 ; pf < (Int) fnz ; pf++) { /* get nonzero entry F (t,k) */ t = Fi [pf] ; p = Ap [t] ; pend = (packed) ? (Ap [t+1]) : (p + Anz [t]) ; SUBTREE ; } } #undef SCATTER #undef PARENT /* shift the stack upwards, to the first part of R */ len = nrow - top ; for (i = 0 ; i < len ; i++) { Stack [i] = Stack [top + i] ; } Rp = R->p ; Rp [0] = 0 ; Rp [1] = len ; R->sorted = FALSE ; CHOLMOD(clear_flag) (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_rowfac ======================================================= */ /* ========================================================================== */ /* This is the incremental factorization for general purpose usage. */ int CHOLMOD(rowfac) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,f)' */ double beta [2], /* factorize beta*I+A or beta*I+AA' */ size_t kstart, /* first row to factorize */ size_t kend, /* last row to factorize is kend-1 */ /* ---- in/out --- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(rowfac_mask) (A, F, beta, kstart, kend, NULL, NULL, L, Common)) ; } /* ========================================================================== */ /* === cholmod_rowfac_mask ================================================== */ /* ========================================================================== */ /* This is meant for use in LPDASA only. */ int CHOLMOD(rowfac_mask) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* used for A*A' case only. F=A' or A(:,f)' */ double beta [2], /* factorize beta*I+A or beta*I+AA' */ size_t kstart, /* first row to factorize */ size_t kend, /* last row to factorize is kend-1 */ Int *mask, /* size A->nrow. if mask[i] >= 0 row i is set to zero */ Int *RLinkUp, /* size A->nrow. link list of rows to compute */ /* ---- in/out --- */ cholmod_factor *L, /* --------------- */ cholmod_common *Common ) { Int n ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (L->xtype != CHOLMOD_PATTERN && A->xtype != L->xtype) { ERROR (CHOLMOD_INVALID, "xtype of A and L do not match") ; return (FALSE) ; } if (L->is_super) { ERROR (CHOLMOD_INVALID, "can only do simplicial factorization"); return (FALSE) ; } if (A->stype == 0) { RETURN_IF_NULL (F, FALSE) ; if (A->xtype != F->xtype) { ERROR (CHOLMOD_INVALID, "xtype of A and F do not match") ; return (FALSE) ; } } if (A->stype < 0) { /* symmetric lower triangular form not supported */ ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE) ; } if (kend > L->n) { ERROR (CHOLMOD_INVALID, "kend invalid") ; return (FALSE) ; } if (A->nrow != L->n) { ERROR (CHOLMOD_INVALID, "dimensions of A and L do not match") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; Common->rowfacfl = 0 ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* Xwork is of size n for the real case, 2*n for complex/zomplex */ n = L->n ; /* s = ((A->xtype != CHOLMOD_REAL) ? 2:1)*n */ s = CHOLMOD(mult_size_t) (n, ((A->xtype != CHOLMOD_REAL) ? 2:1), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, n, s, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, A->nrow, Common)) ; /* ---------------------------------------------------------------------- */ /* factorize the matrix, using template routine */ /* ---------------------------------------------------------------------- */ if (RLinkUp == NULL) { switch (A->xtype) { case CHOLMOD_REAL: ok = r_cholmod_rowfac (A, F, beta, kstart, kend, L, Common) ; break ; case CHOLMOD_COMPLEX: ok = c_cholmod_rowfac (A, F, beta, kstart, kend, L, Common) ; break ; case CHOLMOD_ZOMPLEX: ok = z_cholmod_rowfac (A, F, beta, kstart, kend, L, Common) ; break ; } } else { switch (A->xtype) { case CHOLMOD_REAL: ok = r_cholmod_rowfac_mask (A, F, beta, kstart, kend, mask, RLinkUp, L, Common) ; break ; case CHOLMOD_COMPLEX: ok = c_cholmod_rowfac_mask (A, F, beta, kstart, kend, mask, RLinkUp, L, Common) ; break ; case CHOLMOD_ZOMPLEX: ok = z_cholmod_rowfac_mask (A, F, beta, kstart, kend, mask, RLinkUp, L, Common) ; break ; } } return (ok) ; } #endif igraph/src/CHOLMOD/Cholesky/cholmod_colamd.c0000644000175100001440000001560713431000472020312 0ustar hornikusers/* ========================================================================== */ /* === Cholesky/cholmod_colamd ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Cholesky Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Cholesky Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the COLAMD ordering routine (version 2.4 or later). * Finds a permutation p such that the Cholesky factorization of PAA'P' is * sparser than AA' using colamd. If the postorder input parameter is TRUE, * the column etree is found and postordered, and the colamd ordering is then * combined with its postordering. A must be unsymmetric. * * There can be no duplicate entries in f. * f can be length 0 to n if A is m-by-n. * * workspace: Iwork (4*nrow+ncol), Head (nrow+1), Flag (nrow) * Allocates a copy of its input matrix, which * is then used as CCOLAMD's workspace. * * Supports any xtype (pattern, real, complex, or zomplex) */ #ifndef NCHOLESKY #include "cholmod_internal.h" #include "colamd.h" #include "cholmod_cholesky.h" #if (!defined (COLAMD_VERSION) || (COLAMD_VERSION < COLAMD_VERSION_CODE (2,5))) #error "COLAMD v2.5 or later is required" #endif /* ========================================================================== */ /* === cholmod_colamd ======================================================= */ /* ========================================================================== */ int CHOLMOD(colamd) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int postorder, /* if TRUE, follow with a coletree postorder */ /* ---- output --- */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { double knobs [COLAMD_KNOBS] ; cholmod_sparse *C ; Int *NewPerm, *Parent, *Post, *Work2n ; Int k, nrow, ncol ; size_t s, alen ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (A->stype != 0) { ERROR (CHOLMOD_INVALID, "matrix must be unsymmetric") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* Note: this is less than the space used in cholmod_analyze, so if * cholmod_colamd is being called by that routine, no space will be * allocated. */ /* s = 4*nrow + ncol */ s = CHOLMOD(mult_size_t) (nrow, 4, &ok) ; s = CHOLMOD(add_size_t) (s, ncol, &ok) ; #ifdef LONG alen = colamd_l_recommended (A->nzmax, ncol, nrow) ; colamd_l_set_defaults (knobs) ; #else alen = colamd_recommended (A->nzmax, ncol, nrow) ; colamd_set_defaults (knobs) ; #endif if (!ok || alen == 0) { ERROR (CHOLMOD_TOO_LARGE, "matrix invalid or too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* allocate COLAMD workspace */ /* ---------------------------------------------------------------------- */ /* colamd_printf is only available in colamd v2.4 or later */ colamd_printf = Common->print_function ; C = CHOLMOD(allocate_sparse) (ncol, nrow, alen, TRUE, TRUE, 0, CHOLMOD_PATTERN, Common) ; /* ---------------------------------------------------------------------- */ /* copy (and transpose) the input matrix A into the colamd workspace */ /* ---------------------------------------------------------------------- */ /* C = A (:,f)', which also packs A if needed. */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset) */ ok = CHOLMOD(transpose_unsym) (A, 0, NULL, fset, fsize, C, Common) ; /* ---------------------------------------------------------------------- */ /* order the matrix (destroys the contents of C->i and C->p) */ /* ---------------------------------------------------------------------- */ /* get parameters */ if (Common->current < 0 || Common->current >= CHOLMOD_MAXMETHODS) { /* this is the CHOLMOD default, not the COLAMD default */ knobs [COLAMD_DENSE_ROW] = -1 ; } else { /* get the knobs from the Common parameters */ knobs [COLAMD_DENSE_COL] = Common->method[Common->current].prune_dense ; knobs [COLAMD_DENSE_ROW] = Common->method[Common->current].prune_dense2; knobs [COLAMD_AGGRESSIVE] = Common->method[Common->current].aggressive ; } if (ok) { Int *Cp ; Int stats [COLAMD_STATS] ; Cp = C->p ; #ifdef LONG colamd_l (ncol, nrow, alen, C->i, Cp, knobs, stats) ; #else colamd (ncol, nrow, alen, C->i, Cp, knobs, stats) ; #endif ok = stats [COLAMD_STATUS] ; ok = (ok == COLAMD_OK || ok == COLAMD_OK_BUT_JUMBLED) ; /* permutation returned in C->p, if the ordering succeeded */ for (k = 0 ; k < nrow ; k++) { Perm [k] = Cp [k] ; } } CHOLMOD(free_sparse) (&C, Common) ; /* ---------------------------------------------------------------------- */ /* column etree postordering */ /* ---------------------------------------------------------------------- */ if (postorder) { /* use the last 2*n space in Iwork for Parent and Post */ Work2n = Common->Iwork ; Work2n += 2*((size_t) nrow) + ncol ; Parent = Work2n ; /* size nrow (i/i/l) */ Post = Work2n + nrow ; /* size nrow (i/i/l) */ /* workspace: Iwork (2*nrow+ncol), Flag (nrow), Head (nrow+1) */ ok = ok && CHOLMOD(analyze_ordering) (A, CHOLMOD_COLAMD, Perm, fset, fsize, Parent, Post, NULL, NULL, NULL, Common) ; /* combine the colamd permutation with its postordering */ if (ok) { NewPerm = Common->Iwork ; /* size nrow (i/i/l) */ for (k = 0 ; k < nrow ; k++) { NewPerm [k] = Perm [Post [k]] ; } for (k = 0 ; k < nrow ; k++) { Perm [k] = NewPerm [k] ; } } } return (ok) ; } #endif igraph/src/CHOLMOD/README.txt0000644000175100001440000001002113430770174015114 0ustar hornikusersCHOLMOD: a sparse CHOLesky MODification package, Copyright (c) 2005-2012. http://www.suitesparse.com ----------------------------------------------- CHOLMOD is a set of routines for factorizing sparse symmetric positive definite matrices of the form A or AA', updating/downdating a sparse Cholesky factorization, solving linear systems, updating/downdating the solution to the triangular system Lx=b, and many other sparse matrix functions for both symmetric and unsymmetric matrices. Its supernodal Cholesky factorization relies on LAPACK and the Level-3 BLAS, and obtains a substantial fraction of the peak performance of the BLAS. Both real and complex matrices are supported. CHOLMOD is written in ANSI/ISO C, with both C and MATLAB interfaces. This code works on Microsoft Windows and many versions of Unix and Linux. Some Modules of CHOLMOD are copyrighted by the University of Florida (the Core and Partition Modules). The rest are copyrighted by the authors: Timothy A. Davis (all of them), and William W. Hager (the Modify Module). CHOLMOD relies on several other packages: AMD, CAMD, COLAMD, CCOLAMD, SuiteSparse_config, METIS, the BLAS, and LAPACK. All but METIS, the BLAS, and LAPACK are part of SuiteSparse. AMD is authored by T. Davis, Iain Duff, and Patrick Amestoy. COLAMD is authored by T. Davis and Stefan Larimore, with algorithmic design in collaboration with John Gilbert and Esmond Ng. CCOLAMD is authored by T. Davis and Siva Rajamanickam. CAMD is authored by T. Davis and Y. Chen. LAPACK and the BLAS are authored by Jack Dongarra and many others. LAPACK is available at http://www.netlib.org/lapack METIS is authored by George Karypis, Univ. of Minnesota. Its use in CHOLMOD is optional. See http://www-users.cs.umn.edu/~karypis/metis. Place a copy of the metis-4.0 directory in the same directory that contains the CHOLMOD, AMD, COLAMD, and CCOLAMD directories prior to compiling with "make". If you do not wish to use METIS, you must edit SuiteSparse_config and change the line: CHOLMOD_CONFIG = to CHOLMOD_CONFIG = -DNPARTITION The CHOLMOD, AMD, COLAMD, CCOLAMD, and SuiteSparse)config directories must all reside in a common parent directory. To compile all these libraries, edit SuiteSparse)config/SuiteSparse)config.mk to reflect your environment (C compiler, location of the BLAS, and so on) and then type "make" in either the CHOLMOD directory or in the parent directory of CHOLMOD. See each package for more details on how to compile them. For use in MATLAB (on any system, including Windows): start MATLAB, cd to the CHOLMOD/MATLAB directory, and type cholmod_make in the MATLAB Command Window. This is the best way to compile CHOLMOD for MATLAB; it provides a workaround for a METIS design feature, in which METIS terminates your program (and thus MATLAB) if it runs out of memory. Using cholmod_make also ensures your mexFunctions are compiled with -fexceptions, so that exceptions are handled properly (when hitting control-C in the MATLAB command window, for example). On the Pentium, do NOT use the Intel MKL BLAS prior to MKL Version 8.0 with CHOLMOD. Older versions (prior to 8.0) have a bug in dgemm when computing A*B'. The bug generates a NaN result, when the inputs are well-defined. Use the Goto BLAS or the MKL v8.0 BLAS instead. The Goto BLAS is faster and more reliable. See http://www.tacc.utexas.edu/~kgoto/ or http://www.cs.utexas.edu/users/flame/goto/. Sadly, the Intel MKL BLAS 7.x is the default for MATLAB 7.0.4. See http://www.mathworks.com/support/bugreports/details.html?rp=252103 for more details. To workaround this problem on Linux, set environment variable BLAS_VERSION to libmkl_p3.so:libguide.so. On Windows, set environment variable BLAS_VERSION to mkl_p3.dll. Better yet, get MATLAB 7sp3 (MATLAB 7.1) or later. Acknowledgements: this work was supported in part by the National Science Foundation (NFS CCR-0203270 and DMS-9803599), and a grant from Sandia National Laboratories (Dept. of Energy) which supported the development of CHOLMOD's Partition Module. igraph/src/CHOLMOD/MatrixOps/0000755000175100001440000000000013561251652015352 5ustar hornikusersigraph/src/CHOLMOD/MatrixOps/cholmod_norm.c0000644000175100001440000002637513431000472020177 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_norm =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* r = norm (A), compute the infinity-norm, 1-norm, or 2-norm of a sparse or * dense matrix. Can compute the 2-norm only for a dense column vector. * Returns -1 if an error occurs. * * Pattern, real, complex, and zomplex sparse matrices are supported. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === abs_value ============================================================ */ /* ========================================================================== */ /* Compute the absolute value of a real, complex, or zomplex value */ static double abs_value ( int xtype, double *Ax, double *Az, Int p, cholmod_common *Common ) { double s = 0 ; switch (xtype) { case CHOLMOD_PATTERN: s = 1 ; break ; case CHOLMOD_REAL: s = fabs (Ax [p]) ; break ; case CHOLMOD_COMPLEX: s = Common->hypotenuse (Ax [2*p], Ax [2*p+1]) ; break ; case CHOLMOD_ZOMPLEX: s = Common->hypotenuse (Ax [p], Az [p]) ; break ; } return (s) ; } /* ========================================================================== */ /* === cholmod_norm_dense =================================================== */ /* ========================================================================== */ double CHOLMOD(norm_dense) ( /* ---- input ---- */ cholmod_dense *X, /* matrix to compute the norm of */ int norm, /* type of norm: 0: inf. norm, 1: 1-norm, 2: 2-norm */ /* --------------- */ cholmod_common *Common ) { double xnorm, s, x, z ; double *Xx, *Xz, *W ; Int nrow, ncol, d, i, j, use_workspace, xtype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (X, EMPTY) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; ncol = X->ncol ; if (norm < 0 || norm > 2 || (norm == 2 && ncol > 1)) { ERROR (CHOLMOD_INVALID, "invalid norm") ; return (EMPTY) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = X->nrow ; d = X->d ; Xx = X->x ; Xz = X->z ; xtype = X->xtype ; /* ---------------------------------------------------------------------- */ /* allocate workspace, if needed */ /* ---------------------------------------------------------------------- */ W = NULL ; use_workspace = (norm == 0 && ncol > 4) ; if (use_workspace) { CHOLMOD(allocate_work) (0, 0, nrow, Common) ; W = Common->Xwork ; if (Common->status < CHOLMOD_OK) { /* oops, no workspace */ use_workspace = FALSE ; } } /* ---------------------------------------------------------------------- */ /* compute the norm */ /* ---------------------------------------------------------------------- */ xnorm = 0 ; if (use_workspace) { /* ------------------------------------------------------------------ */ /* infinity-norm = max row sum, using stride-1 access of X */ /* ------------------------------------------------------------------ */ DEBUG (for (i = 0 ; i < nrow ; i++) ASSERT (W [i] == 0)) ; /* this is faster than stride-d, but requires O(nrow) workspace */ for (j = 0 ; j < ncol ; j++) { for (i = 0 ; i < nrow ; i++) { W [i] += abs_value (xtype, Xx, Xz, i+j*d, Common) ; } } for (i = 0 ; i < nrow ; i++) { s = W [i] ; if ((IS_NAN (s) || s > xnorm) && !IS_NAN (xnorm)) { xnorm = s ; } W [i] = 0 ; } } else if (norm == 0) { /* ------------------------------------------------------------------ */ /* infinity-norm = max row sum, using stride-d access of X */ /* ------------------------------------------------------------------ */ for (i = 0 ; i < nrow ; i++) { s = 0 ; for (j = 0 ; j < ncol ; j++) { s += abs_value (xtype, Xx, Xz, i+j*d, Common) ; } if ((IS_NAN (s) || s > xnorm) && !IS_NAN (xnorm)) { xnorm = s ; } } } else if (norm == 1) { /* ------------------------------------------------------------------ */ /* 1-norm = max column sum */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { s = 0 ; for (i = 0 ; i < nrow ; i++) { s += abs_value (xtype, Xx, Xz, i+j*d, Common) ; } if ((IS_NAN (s) || s > xnorm) && !IS_NAN (xnorm)) { xnorm = s ; } } } else { /* ------------------------------------------------------------------ */ /* 2-norm = sqrt (sum (X.^2)) */ /* ------------------------------------------------------------------ */ switch (xtype) { case CHOLMOD_REAL: for (i = 0 ; i < nrow ; i++) { x = Xx [i] ; xnorm += x*x ; } break ; case CHOLMOD_COMPLEX: for (i = 0 ; i < nrow ; i++) { x = Xx [2*i ] ; z = Xx [2*i+1] ; xnorm += x*x + z*z ; } break ; case CHOLMOD_ZOMPLEX: for (i = 0 ; i < nrow ; i++) { x = Xx [i] ; z = Xz [i] ; xnorm += x*x + z*z ; } break ; } xnorm = sqrt (xnorm) ; } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ return (xnorm) ; } /* ========================================================================== */ /* === cholmod_norm_sparse ================================================== */ /* ========================================================================== */ double CHOLMOD(norm_sparse) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to compute the norm of */ int norm, /* type of norm: 0: inf. norm, 1: 1-norm */ /* --------------- */ cholmod_common *Common ) { double anorm, s ; double *Ax, *Az, *W ; Int *Ap, *Ai, *Anz ; Int i, j, p, pend, nrow, ncol, packed, xtype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; ncol = A->ncol ; nrow = A->nrow ; if (norm < 0 || norm > 1) { ERROR (CHOLMOD_INVALID, "invalid norm") ; return (EMPTY) ; } if (A->stype && nrow != ncol) { ERROR (CHOLMOD_INVALID, "matrix invalid") ; return (EMPTY) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; packed = A->packed ; xtype = A->xtype ; /* ---------------------------------------------------------------------- */ /* allocate workspace, if needed */ /* ---------------------------------------------------------------------- */ W = NULL ; if (A->stype || norm == 0) { CHOLMOD(allocate_work) (0, 0, nrow, Common) ; W = Common->Xwork ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (EMPTY) ; } DEBUG (for (i = 0 ; i < nrow ; i++) ASSERT (W [i] == 0)) ; } /* ---------------------------------------------------------------------- */ /* compute the norm */ /* ---------------------------------------------------------------------- */ anorm = 0 ; if (A->stype > 0) { /* ------------------------------------------------------------------ */ /* A is symmetric with upper triangular part stored */ /* ------------------------------------------------------------------ */ /* infinity-norm = 1-norm = max row/col sum */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; s = abs_value (xtype, Ax, Az, p, Common) ; if (i == j) { W [i] += s ; } else if (i < j) { W [i] += s ; W [j] += s ; } } } } else if (A->stype < 0) { /* ------------------------------------------------------------------ */ /* A is symmetric with lower triangular part stored */ /* ------------------------------------------------------------------ */ /* infinity-norm = 1-norm = max row/col sum */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; s = abs_value (xtype, Ax, Az, p, Common) ; if (i == j) { W [i] += s ; } else if (i > j) { W [i] += s ; W [j] += s ; } } } } else if (norm == 0) { /* ------------------------------------------------------------------ */ /* A is unsymmetric, compute the infinity-norm */ /* ------------------------------------------------------------------ */ /* infinity-norm = max row sum */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { W [Ai [p]] += abs_value (xtype, Ax, Az, p, Common) ; } } } else { /* ------------------------------------------------------------------ */ /* A is unsymmetric, compute the 1-norm */ /* ------------------------------------------------------------------ */ /* 1-norm = max column sum */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; if (xtype == CHOLMOD_PATTERN) { s = pend - p ; } else { s = 0 ; for ( ; p < pend ; p++) { s += abs_value (xtype, Ax, Az, p, Common) ; } } if ((IS_NAN (s) || s > anorm) && !IS_NAN (anorm)) { anorm = s ; } } } /* ---------------------------------------------------------------------- */ /* compute the max row sum */ /* ---------------------------------------------------------------------- */ if (A->stype || norm == 0) { for (i = 0 ; i < nrow ; i++) { s = W [i] ; if ((IS_NAN (s) || s > anorm) && !IS_NAN (anorm)) { anorm = s ; } W [i] = 0 ; } } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ return (anorm) ; } #endif igraph/src/CHOLMOD/MatrixOps/cholmod_horzcat.c0000644000175100001440000001422213431000472020662 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_horzcat ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Horizontal concatenation, C = [A , B] in MATLAB notation. * * A and B can be up/lo/unsym; C is unsymmetric and packed. * A and B must have the same number of rows. * C is sorted if both A and B are sorted. * * workspace: Iwork (max (A->nrow, A->ncol, B->nrow, B->ncol)). * allocates temporary copies of A and B if they are symmetric. * * A and B must have the same numeric xtype, unless values is FALSE. * A and B cannot be complex or zomplex, unless values is FALSE. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === cholmod_horzcat ====================================================== */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(horzcat) ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to concatenate */ cholmod_sparse *B, /* right matrix to concatenate */ int values, /* if TRUE compute the numerical values of C */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Bx, *Cx ; Int *Ap, *Ai, *Anz, *Bp, *Bi, *Bnz, *Cp, *Ci ; cholmod_sparse *C, *A2, *B2 ; Int apacked, bpacked, ancol, bncol, ncol, nrow, anz, bnz, nz, j, p, pend, pdest ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_NULL (B, NULL) ; values = values && (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->nrow != B->nrow) { /* A and B must have the same number of rows */ ERROR (CHOLMOD_INVALID, "A and B must have same # rows") ; return (NULL) ; } /* A and B must have the same numerical type if values is TRUE (both must * be CHOLMOD_REAL, this is implicitly checked above) */ Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ ancol = A->ncol ; bncol = B->ncol ; nrow = A->nrow ; CHOLMOD(allocate_work) (0, MAX3 (nrow, ancol, bncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* convert A to unsymmetric, if necessary */ A2 = NULL ; if (A->stype != 0) { /* workspace: Iwork (max (A->nrow,A->ncol)) */ A2 = CHOLMOD(copy) (A, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } A = A2 ; } /* convert B to unsymmetric, if necessary */ B2 = NULL ; if (B->stype != 0) { /* workspace: Iwork (max (B->nrow,B->ncol)) */ B2 = CHOLMOD(copy) (B, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; return (NULL) ; } B = B2 ; } Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; apacked = A->packed ; Bp = B->p ; Bnz = B->nz ; Bi = B->i ; Bx = B->x ; bpacked = B->packed ; /* ---------------------------------------------------------------------- */ /* allocate C */ /* ---------------------------------------------------------------------- */ anz = CHOLMOD(nnz) (A, Common) ; bnz = CHOLMOD(nnz) (B, Common) ; ncol = ancol + bncol ; nz = anz + bnz ; C = CHOLMOD(allocate_sparse) (nrow, ncol, nz, A->sorted && B->sorted, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; return (NULL) ; } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* C = [A , B] */ /* ---------------------------------------------------------------------- */ pdest = 0 ; /* copy A as the first A->ncol columns of C */ for (j = 0 ; j < ancol ; j++) { /* A(:,j) is the jth column of C */ p = Ap [j] ; pend = (apacked) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = pdest ; for ( ; p < pend ; p++) { Ci [pdest] = Ai [p] ; if (values) Cx [pdest] = Ax [p] ; pdest++ ; } } /* copy B as the next B->ncol columns of C */ for (j = 0 ; j < bncol ; j++) { /* B(:,j) is the (ancol+j)th column of C */ p = Bp [j] ; pend = (bpacked) ? (Bp [j+1]) : (p + Bnz [j]) ; Cp [ancol + j] = pdest ; for ( ; p < pend ; p++) { Ci [pdest] = Bi [p] ; if (values) Cx [pdest] = Bx [p] ; pdest++ ; } } Cp [ncol] = pdest ; ASSERT (pdest == anz + bnz) ; /* ---------------------------------------------------------------------- */ /* free the unsymmetric copies of A and B, and return C */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; return (C) ; } #endif igraph/src/CHOLMOD/MatrixOps/cholmod_symmetry.c0000644000175100001440000004020413431000472021100 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_symmetry =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Determines if a sparse matrix is rectangular, unsymmetric, symmetric, * skew-symmetric, or Hermitian. It does so by looking at its numerical values * of both upper and lower triangular parts of a CHOLMOD "unsymmetric" * matrix, where A->stype == 0. The transpose of A is NOT constructed. * * If not unsymmetric, it also determines if the matrix has a diagonal whose * entries are all real and positive (and thus a candidate for sparse Cholesky * if A->stype is changed to a nonzero value). * * Note that a Matrix Market "general" matrix is either rectangular or * unsymmetric. * * The row indices in the column of each matrix MUST be sorted for this function * to work properly (A->sorted must be TRUE). This routine returns EMPTY if * A->stype is not zero, or if A->sorted is FALSE. The exception to this rule * is if A is rectangular. * * If option == 0, then this routine returns immediately when it finds a * non-positive diagonal entry (or one with nonzero imaginary part). If the * matrix is not a candidate for sparse Cholesky, it returns the value * CHOLMOD_MM_UNSYMMETRIC, even if the matrix might in fact be symmetric or * Hermitian. * * This routine is useful inside the MATLAB backslash, which must look at an * arbitrary matrix (A->stype == 0) and determine if it is a candidate for * sparse Cholesky. In that case, option should be 0. * * This routine is also useful when writing a MATLAB matrix to a file in * Rutherford/Boeing or Matrix Market format. Those formats require a * determination as to the symmetry of the matrix, and thus this routine should * not return upon encountering the first non-positive diagonal. In this case, * option should be 1. * * If option is 2, this function can be used to compute the numerical and * pattern symmetry, where 0 is a completely unsymmetric matrix, and 1 is a * perfectly symmetric matrix. This option is used when computing the following * statistics for the matrices in the UF Sparse Matrix Collection. * * numerical symmetry: number of matched offdiagonal nonzeros over * the total number of offdiagonal entries. A real entry A(i,j), i ~= j, * is matched if A (j,i) == A (i,j), but this is only counted if both * A(j,i) and A(i,j) are nonzero. This does not depend on Z. * (If A is complex, then the above test is modified; A (i,j) is matched * if conj (A (j,i)) == A (i,j)). * * Then numeric symmetry = xmatched / nzoffdiag, or 1 if nzoffdiag = 0. * * pattern symmetry: number of matched offdiagonal entries over the * total number of offdiagonal entries. An entry A(i,j), i ~= j, is * matched if A (j,i) is also an entry. * * Then pattern symmetry = pmatched / nzoffdiag, or 1 if nzoffdiag = 0. * * The symmetry of a matrix with no offdiagonal entries is equal to 1. * * A workspace of size ncol integers is allocated; EMPTY is returned if this * allocation fails. * * Summary of return values: * * EMPTY (-1) out of memory, stype not zero, A not sorted * CHOLMOD_MM_RECTANGULAR 1 A is rectangular * CHOLMOD_MM_UNSYMMETRIC 2 A is unsymmetric * CHOLMOD_MM_SYMMETRIC 3 A is symmetric, but with non-pos. diagonal * CHOLMOD_MM_HERMITIAN 4 A is Hermitian, but with non-pos. diagonal * CHOLMOD_MM_SKEW_SYMMETRIC 5 A is skew symmetric * CHOLMOD_MM_SYMMETRIC_POSDIAG 6 A is symmetric with positive diagonal * CHOLMOD_MM_HERMITIAN_POSDIAG 7 A is Hermitian with positive diagonal * * See also the spsym mexFunction, which is a MATLAB interface for this code. * * If the matrix is a candidate for sparse Cholesky, it will return a result * CHOLMOD_MM_SYMMETRIC_POSDIAG if real, or CHOLMOD_MM_HERMITIAN_POSDIAG if * complex. Otherwise, it will return a value less than this. This is true * regardless of the value of the option parameter. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === get_value ============================================================ */ /* ========================================================================== */ /* Get the pth value in the matrix. */ static void get_value ( double *Ax, /* real values, or real/imag. for CHOLMOD_COMPLEX type */ double *Az, /* imaginary values for CHOLMOD_ZOMPLEX type */ Int p, /* get the pth entry */ Int xtype, /* A->xtype: pattern, real, complex, or zomplex */ double *x, /* the real part */ double *z /* the imaginary part */ ) { switch (xtype) { case CHOLMOD_PATTERN: *x = 1 ; *z = 0 ; break ; case CHOLMOD_REAL: *x = Ax [p] ; *z = 0 ; break ; case CHOLMOD_COMPLEX: *x = Ax [2*p] ; *z = Ax [2*p+1] ; break ; case CHOLMOD_ZOMPLEX: *x = Ax [p] ; *z = Az [p] ; break ; } } /* ========================================================================== */ /* === cholmod_symmetry ===================================================== */ /* ========================================================================== */ /* Determine the symmetry of a matrix, and check its diagonal. * * option 0: Do not count # of matched pairs. Quick return if the * the matrix has a zero, negative, or imaginary diagonal entry. * * option 1: Do not count # of matched pairs. Do not return quickly if * the matrix has a zero, negative, or imaginary diagonal entry. * The result 1 to 7 is accurately computed: * * EMPTY (-1) out of memory, stype not zero, A not sorted * CHOLMOD_MM_RECTANGULAR 1 A is rectangular * CHOLMOD_MM_UNSYMMETRIC 2 A is unsymmetric * CHOLMOD_MM_SYMMETRIC 3 A is symmetric, with non-pos. diagonal * CHOLMOD_MM_HERMITIAN 4 A is Hermitian, with non-pos. diagonal * CHOLMOD_MM_SKEW_SYMMETRIC 5 A is skew symmetric * CHOLMOD_MM_SYMMETRIC_POSDIAG 6 is symmetric with positive diagonal * CHOLMOD_MM_HERMITIAN_POSDIAG 7 A is Hermitian with positive diagonal * * The routine returns as soon as the above is determined (that is, it * can return as soon as it determines the matrix is unsymmetric). * * option 2: All of the above, but also compute the number of matched off- * diagonal entries (of two types). xmatched is the number of * nonzero entries for which A(i,j) = conj(A(j,i)). pmatched is * the number of entries (i,j) for which A(i,j) and A(j,i) are both in * the pattern of A (the value doesn't matter). nzoffdiag is the total * number of off-diagonal entries in the pattern. nzdiag is the number of * diagonal entries in the pattern. * * With option 0 or 1, or if the matrix is rectangular, xmatched, pmatched, * nzoffdiag, and nzdiag are not computed. * * Note that a matched pair, A(i,j) and A(j,i) for i != j, is counted twice * (once per entry). */ int CHOLMOD(symmetry) ( /* ---- input ---- */ cholmod_sparse *A, int option, /* option 0, 1, or 2 (see above) */ /* ---- output --- */ /* outputs ignored if any are NULL */ Int *p_xmatched, /* # of matched numerical entries */ Int *p_pmatched, /* # of matched entries in pattern */ Int *p_nzoffdiag, /* # of off diagonal entries */ Int *p_nzdiag, /* # of diagonal entries */ /* --------------- */ cholmod_common *Common ) { double aij_real = 0, aij_imag = 0, aji_real = 0, aji_imag = 0 ; double *Ax, *Az ; Int *Ap, *Ai, *Anz, *munch ; Int packed, nrow, ncol, xtype, is_symmetric, is_skew, is_hermitian, posdiag, j, p, pend, i, piend, result, xmatched, pmatched, nzdiag, i2, found ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; ASSERT (CHOLMOD(dump_sparse) (A, "cholmod_symmetry", Common) >= 0) ; if (p_xmatched == NULL || p_pmatched == NULL || p_nzoffdiag == NULL || p_nzdiag == NULL) { /* option 2 is not performed if any output parameter is NULL */ option = MAX (option, 1) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; packed = A->packed ; ncol = A->ncol ; nrow = A->nrow ; xtype = A->xtype ; /* ---------------------------------------------------------------------- */ /* check if rectangular, unsorted, or stype is not zero */ /* ---------------------------------------------------------------------- */ if (nrow != ncol) { /* matrix is rectangular */ return (CHOLMOD_MM_RECTANGULAR) ; } if (!(A->sorted) || A->stype != 0) { /* this function cannot determine the type or symmetry */ return (EMPTY) ; } /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* this function requires uninitialized Int workspace of size ncol */ CHOLMOD(allocate_work) (0, ncol, 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (EMPTY) ; } munch = Common->Iwork ; /* the munch array is size ncol */ /* ---------------------------------------------------------------------- */ /* determine symmetry of a square matrix */ /* ---------------------------------------------------------------------- */ /* a complex or zomplex matrix is Hermitian until proven otherwise */ is_hermitian = (xtype >= CHOLMOD_COMPLEX) ; /* any matrix is symmetric until proven otherwise */ is_symmetric = TRUE ; /* a non-pattern matrix is skew-symmetric until proven otherwise */ is_skew = (xtype != CHOLMOD_PATTERN) ; /* a matrix has positive diagonal entries until proven otherwise */ posdiag = TRUE ; /* munch pointers start at the top of each column */ for (j = 0 ; j < ncol ; j++) { munch [j] = Ap [j] ; } xmatched = 0 ; pmatched = 0 ; nzdiag = 0 ; for (j = 0 ; j < ncol ; j++) /* examine each column of A */ { /* ------------------------------------------------------------------ */ /* look at the entire munch column j */ /* ------------------------------------------------------------------ */ /* start at the munch point of column j, and go to end of the column */ p = munch [j] ; pend = (packed) ? (Ap [j+1]) : (Ap [j] + Anz [j]) ; for ( ; p < pend ; p++) { /* get the row index of A(i,j) */ i = Ai [p] ; if (i < j) { /* ---------------------------------------------------------- */ /* A(i,j) in triu(A), but matching A(j,i) not in tril(A) */ /* ---------------------------------------------------------- */ /* entry A(i,j) is unmatched; it appears in the upper triangular * part, but not the lower triangular part. The matrix is * unsymmetric. */ is_hermitian = FALSE ; is_symmetric = FALSE ; is_skew = FALSE ; } else if (i == j) { /* ---------------------------------------------------------- */ /* the diagonal A(j,j) is present; check its value */ /* ---------------------------------------------------------- */ get_value (Ax, Az, p, xtype, &aij_real, &aij_imag) ; if (aij_real != 0. || aij_imag != 0.) { /* diagonal is nonzero; matrix is not skew-symmetric */ nzdiag++ ; is_skew = FALSE ; } if (aij_real <= 0. || aij_imag != 0.) { /* diagonal negative or imaginary; not chol candidate */ posdiag = FALSE ; } if (aij_imag != 0.) { /* imaginary part is present; not Hermitian */ is_hermitian = FALSE ; } } else /* i > j */ { /* ---------------------------------------------------------- */ /* consider column i, up to and including row j */ /* ---------------------------------------------------------- */ /* munch the entry at top of column i up to and incl row j */ piend = (packed) ? (Ap [i+1]) : (Ap [i] + Anz [i]) ; found = FALSE ; for ( ; munch [i] < piend ; munch [i]++) { i2 = Ai [munch [i]] ; if (i2 < j) { /* -------------------------------------------------- */ /* A(i2,i) in triu(A) but A(i,i2) not in tril(A) */ /* -------------------------------------------------- */ /* The matrix is unsymmetric. */ is_hermitian = FALSE ; is_symmetric = FALSE ; is_skew = FALSE ; } else if (i2 == j) { /* -------------------------------------------------- */ /* both A(i,j) and A(j,i) exist in the matrix */ /* -------------------------------------------------- */ /* this is one more matching entry in the pattern */ pmatched += 2 ; found = TRUE ; /* get the value of A(i,j) */ get_value (Ax, Az, p, xtype, &aij_real, &aij_imag) ; /* get the value of A(j,i) */ get_value (Ax, Az, munch [i], xtype, &aji_real, &aji_imag) ; /* compare A(i,j) with A(j,i) */ if (aij_real != aji_real || aij_imag != aji_imag) { /* the matrix cannot be symmetric */ is_symmetric = FALSE ; } if (aij_real != -aji_real || aij_imag != aji_imag) { /* the matrix cannot be skew-symmetric */ is_skew = FALSE ; } if (aij_real != aji_real || aij_imag != -aji_imag) { /* the matrix cannot be Hermitian */ is_hermitian = FALSE ; } else { /* A(i,j) and A(j,i) are numerically matched */ xmatched += 2 ; } } else /* i2 > j */ { /* -------------------------------------------------- */ /* entry A(i2,i) is not munched; consider it later */ /* -------------------------------------------------- */ break ; } } if (!found) { /* A(i,j) in tril(A) but A(j,i) not in triu(A). * The matrix is unsymmetric. */ is_hermitian = FALSE ; is_symmetric = FALSE ; is_skew = FALSE ; } } if (option < 2 && !(is_symmetric || is_skew || is_hermitian)) { /* matrix is unsymmetric; terminate the test */ return (CHOLMOD_MM_UNSYMMETRIC) ; } } /* ------------------------------------------------------------------ */ /* quick return if not Cholesky candidate */ /* ------------------------------------------------------------------ */ if (option < 1 && (!posdiag || nzdiag < ncol)) { /* Diagonal entry not present, or present but negative or with * nonzero imaginary part. Quick return for option 0. */ return (CHOLMOD_MM_UNSYMMETRIC) ; } } /* ---------------------------------------------------------------------- */ /* return the results */ /* ---------------------------------------------------------------------- */ if (nzdiag < ncol) { /* not all diagonal entries are present */ posdiag = FALSE ; } if (option >= 2) { *p_xmatched = xmatched ; *p_pmatched = pmatched ; *p_nzoffdiag = CHOLMOD(nnz) (A, Common) - nzdiag ; *p_nzdiag = nzdiag ; } result = CHOLMOD_MM_UNSYMMETRIC ; if (is_hermitian) { /* complex Hermitian matrix, with either pos. or non-pos. diagonal */ result = posdiag ? CHOLMOD_MM_HERMITIAN_POSDIAG : CHOLMOD_MM_HERMITIAN ; } else if (is_symmetric) { /* real or complex symmetric matrix, with pos. or non-pos. diagonal */ result = posdiag ? CHOLMOD_MM_SYMMETRIC_POSDIAG : CHOLMOD_MM_SYMMETRIC ; } else if (is_skew) { /* real or complex skew-symmetric matrix */ result = CHOLMOD_MM_SKEW_SYMMETRIC ; } return (result) ; } #endif igraph/src/CHOLMOD/MatrixOps/cholmod_ssmult.c0000644000175100001440000003400013431000472020533 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_ssmult ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* C = A*B. Multiply two sparse matrices. * * A and B can be packed or unpacked, sorted or unsorted, and of any stype. * If A or B are symmetric, an internal unsymmetric copy is made first, however. * C is computed as if A and B are unsymmetric, and then if the stype input * parameter requests a symmetric form (upper or lower) the matrix is converted * into that form. * * C is returned as packed, and either unsorted or sorted, depending on the * "sorted" input parameter. If C is returned sorted, then either C = (B'*A')' * or C = (A*B)'' is computed, depending on the number of nonzeros in A, B, and * C. * * workspace: * if C unsorted: Flag (A->nrow), W (A->nrow) if values * if C sorted: Flag (B->ncol), W (B->ncol) if values * Iwork (max (A->ncol, A->nrow, B->nrow, B->ncol)) * allocates temporary copies for A, B, and C, if required. * * Only pattern and real matrices are supported. Complex and zomplex matrices * are supported only when the numerical values are not computed ("values" * is FALSE). */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === cholmod_ssmult ======================================================= */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(ssmult) ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to multiply */ cholmod_sparse *B, /* right matrix to multiply */ int stype, /* requested stype of C */ int values, /* TRUE: do numerical values, FALSE: pattern only */ int sorted, /* if TRUE then return C with sorted columns */ /* --------------- */ cholmod_common *Common ) { double bjt ; double *Ax, *Bx, *Cx, *W ; Int *Ap, *Anz, *Ai, *Bp, *Bnz, *Bi, *Cp, *Ci, *Flag ; cholmod_sparse *C, *A2, *B2, *A3, *B3, *C2 ; Int apacked, bpacked, j, i, pa, paend, pb, pbend, ncol, mark, cnz, t, p, nrow, anz, bnz, do_swap_and_transpose, n1, n2 ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_NULL (B, NULL) ; values = values && (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->ncol != B->nrow) { /* inner dimensions must agree */ ERROR (CHOLMOD_INVALID, "A and B inner dimensions must match") ; return (NULL) ; } /* A and B must have the same numerical type if values is TRUE (both must * be CHOLMOD_REAL, this is implicitly checked above) */ Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ if (A->nrow <= 1) { /* C will be implicitly sorted, so no need to sort it here */ sorted = FALSE ; } if (sorted) { n1 = MAX (A->nrow, B->ncol) ; } else { n1 = A->nrow ; } n2 = MAX4 (A->ncol, A->nrow, B->nrow, B->ncol) ; CHOLMOD(allocate_work) (n1, n2, values ? n1 : 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1 : 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* convert A to unsymmetric, if necessary */ A2 = NULL ; B2 = NULL ; if (A->stype) { /* workspace: Iwork (max (A->nrow,A->ncol)) */ A2 = CHOLMOD(copy) (A, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; return (NULL) ; } A = A2 ; } /* convert B to unsymmetric, if necessary */ if (B->stype) { /* workspace: Iwork (max (B->nrow,B->ncol)) */ B2 = CHOLMOD(copy) (B, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; return (NULL) ; } B = B2 ; } ASSERT (CHOLMOD(dump_sparse) (A, "A", Common) >= 0) ; ASSERT (CHOLMOD(dump_sparse) (B, "B", Common) >= 0) ; /* get the A matrix */ Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; apacked = A->packed ; /* get the B matrix */ Bp = B->p ; Bnz = B->nz ; Bi = B->i ; Bx = B->x ; bpacked = B->packed ; /* get the size of C */ nrow = A->nrow ; ncol = B->ncol ; /* get workspace */ W = Common->Xwork ; /* size nrow, unused if values is FALSE */ Flag = Common->Flag ; /* size nrow, Flag [0..nrow-1] < mark on input*/ /* ---------------------------------------------------------------------- */ /* count the number of entries in the result C */ /* ---------------------------------------------------------------------- */ cnz = 0 ; for (j = 0 ; j < ncol ; j++) { /* clear the Flag array */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* for each nonzero B(t,j) in column j, do: */ pb = Bp [j] ; pbend = (bpacked) ? (Bp [j+1]) : (pb + Bnz [j]) ; for ( ; pb < pbend ; pb++) { /* B(t,j) is nonzero */ t = Bi [pb] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) */ pa = Ap [t] ; paend = (apacked) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; cnz++ ; } } } if (cnz < 0) { break ; /* integer overflow case */ } } /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* ---------------------------------------------------------------------- */ /* check for integer overflow */ /* ---------------------------------------------------------------------- */ if (cnz < 0) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* Determine how to return C sorted (if requested) */ /* ---------------------------------------------------------------------- */ do_swap_and_transpose = FALSE ; if (sorted) { /* Determine the best way to return C with sorted columns. Computing * C = (B'*A')' takes cnz + anz + bnz time (ignoring O(n) terms). * Sorting C when done, C = (A*B)'', takes 2*cnz time. Pick the one * with the least amount of work. */ anz = CHOLMOD(nnz) (A, Common) ; bnz = CHOLMOD(nnz) (B, Common) ; do_swap_and_transpose = (anz + bnz < cnz) ; if (do_swap_and_transpose) { /* -------------------------------------------------------------- */ /* C = (B'*A')' */ /* -------------------------------------------------------------- */ /* workspace: Iwork (A->nrow) */ A3 = CHOLMOD(ptranspose) (A, values, NULL, NULL, 0, Common) ; CHOLMOD(free_sparse) (&A2, Common) ; A2 = A3 ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)); return (NULL) ; } /* workspace: Iwork (B->nrow) */ B3 = CHOLMOD(ptranspose) (B, values, NULL, NULL, 0, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; B2 = B3 ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)); return (NULL) ; } A = B2 ; B = A2 ; /* get the new A matrix */ Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; apacked = A->packed ; /* get the new B matrix */ Bp = B->p ; Bnz = B->nz ; Bi = B->i ; Bx = B->x ; bpacked = B->packed ; /* get the size of C' */ nrow = A->nrow ; ncol = B->ncol ; } } /* ---------------------------------------------------------------------- */ /* allocate C */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_sparse) (nrow, ncol, cnz, FALSE, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; return (NULL) ; } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* C = A*B */ /* ---------------------------------------------------------------------- */ cnz = 0 ; if (values) { /* pattern and values */ for (j = 0 ; j < ncol ; j++) { /* clear the Flag array */ /* mark = CHOLMOD(clear_flag (Common)) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* start column j of C */ Cp [j] = cnz ; /* for each nonzero B(t,j) in column j, do: */ pb = Bp [j] ; pbend = (bpacked) ? (Bp [j+1]) : (pb + Bnz [j]) ; for ( ; pb < pbend ; pb++) { /* B(t,j) is nonzero */ t = Bi [pb] ; bjt = Bx [pb] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) * and scatter the values into W */ pa = Ap [t] ; paend = (apacked) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; Ci [cnz++] = i ; } W [i] += Ax [pa] * bjt ; } } /* gather the values into C(:,j) */ for (p = Cp [j] ; p < cnz ; p++) { i = Ci [p] ; Cx [p] = W [i] ; W [i] = 0 ; } } } else { /* pattern only */ for (j = 0 ; j < ncol ; j++) { /* clear the Flag array */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; /* start column j of C */ Cp [j] = cnz ; /* for each nonzero B(t,j) in column j, do: */ pb = Bp [j] ; pbend = (bpacked) ? (Bp [j+1]) : (pb + Bnz [j]) ; for ( ; pb < pbend ; pb++) { /* B(t,j) is nonzero */ t = Bi [pb] ; /* add the nonzero pattern of A(:,t) to the pattern of C(:,j) */ pa = Ap [t] ; paend = (apacked) ? (Ap [t+1]) : (pa + Anz [t]) ; for ( ; pa < paend ; pa++) { i = Ai [pa] ; if (Flag [i] != mark) { Flag [i] = mark ; Ci [cnz++] = i ; } } } } } Cp [ncol] = cnz ; ASSERT (MAX (1,cnz) == C->nzmax) ; /* ---------------------------------------------------------------------- */ /* clear workspace and free temporary matrices */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; /* CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; /* ---------------------------------------------------------------------- */ /* convert C to a symmetric upper/lower matrix if requested */ /* ---------------------------------------------------------------------- */ /* convert C in place, which cannot fail since no memory is allocated */ if (stype > 0) { /* C = triu (C), in place */ (void) CHOLMOD(band_inplace) (0, ncol, values, C, Common) ; C->stype = 1 ; } else if (stype < 0) { /* C = tril (C), in place */ (void) CHOLMOD(band_inplace) (-nrow, 0, values, C, Common) ; C->stype = -1 ; } ASSERT (Common->status >= CHOLMOD_OK) ; /* ---------------------------------------------------------------------- */ /* sort C, if requested */ /* ---------------------------------------------------------------------- */ if (sorted) { if (do_swap_and_transpose) { /* workspace: Iwork (C->ncol), which is A->nrow since C=(B'*A') */ C2 = CHOLMOD(ptranspose) (C, values, NULL, NULL, 0, Common) ; CHOLMOD(free_sparse) (&C, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)); return (NULL) ; } C = C2 ; } else { /* workspace: Iwork (max (C->nrow,C->ncol)) */ if (!CHOLMOD(sort) (C, Common)) { /* out of memory */ CHOLMOD(free_sparse) (&C, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)); return (NULL) ; } } } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ DEBUG (CHOLMOD(dump_sparse) (C, "ssmult", Common) >= 0) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, values ? n1:0, Common)) ; return (C) ; } #endif igraph/src/CHOLMOD/MatrixOps/cholmod_scale.c0000644000175100001440000001437513431000472020310 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_scale ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* scale a matrix: A = diag(s)*A, A*diag(s), s*A, or diag(s)*A*diag(s) * * A can be of any type (packed/unpacked, upper/lower/unsymmetric). * The symmetry of A is ignored; all entries in the matrix are modified. * * If A is m-by-n unsymmetric but scaled symmtrically, the result is * A = diag (s (1:m)) * A * diag (s (1:n)). * * Note: diag(s) should be interpretted as spdiags(s,0,n,n) where n=length(s). * * Row or column scaling of a symmetric matrix still results in a symmetric * matrix, since entries are still ignored by other routines. * For example, when row-scaling a symmetric matrix where just the upper * triangular part is stored (and lower triangular entries ignored) * A = diag(s)*triu(A) is performed, where the result A is also * symmetric-upper. This has the effect of modifying the implicit lower * triangular part. In MATLAB notation: * * U = diag(s)*triu(A) ; * L = tril (U',-1) * A = L + U ; * * The scale parameter determines the kind of scaling to perform: * * CHOLMOD_SCALAR: s[0]*A * CHOLMOD_ROW: diag(s)*A * CHOLMOD_COL: A*diag(s) * CHOLMOD_SYM: diag(s)*A*diag(s) * * The size of S depends on the scale parameter: * * CHOLMOD_SCALAR: size 1 * CHOLMOD_ROW: size nrow-by-1 or 1-by-nrow * CHOLMOD_COL: size ncol-by-1 or 1-by-ncol * CHOLMOD_SYM: size max(nrow,ncol)-by-1, or 1-by-max(nrow,ncol) * * workspace: none * * Only real matrices are supported. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === cholmod_scale ======================================================== */ /* ========================================================================== */ int CHOLMOD(scale) ( /* ---- input ---- */ cholmod_dense *S, /* scale factors (scalar or vector) */ int scale, /* type of scaling to compute */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to scale */ /* --------------- */ cholmod_common *Common ) { double t ; double *Ax, *s ; Int *Ap, *Anz, *Ai ; Int packed, j, ncol, nrow, p, pend, sncol, snrow, nn, ok ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (S, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (S, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; ncol = A->ncol ; nrow = A->nrow ; sncol = S->ncol ; snrow = S->nrow ; if (scale == CHOLMOD_SCALAR) { ok = (snrow == 1 && sncol == 1) ; } else if (scale == CHOLMOD_ROW) { ok = (snrow == nrow && sncol == 1) || (snrow == 1 && sncol == nrow) ; } else if (scale == CHOLMOD_COL) { ok = (snrow == ncol && sncol == 1) || (snrow == 1 && sncol == ncol) ; } else if (scale == CHOLMOD_SYM) { nn = MAX (nrow, ncol) ; ok = (snrow == nn && sncol == 1) || (snrow == 1 && sncol == nn) ; } else { /* scale invalid */ ERROR (CHOLMOD_INVALID, "invalid scaling option") ; return (FALSE) ; } if (!ok) { /* S is wrong size */ ERROR (CHOLMOD_INVALID, "invalid scale factors") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; packed = A->packed ; s = S->x ; /* ---------------------------------------------------------------------- */ /* scale the matrix */ /* ---------------------------------------------------------------------- */ if (scale == CHOLMOD_ROW) { /* ------------------------------------------------------------------ */ /* A = diag(s)*A, row scaling */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Ax [p] *= s [Ai [p]] ; } } } else if (scale == CHOLMOD_COL) { /* ------------------------------------------------------------------ */ /* A = A*diag(s), column scaling */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { t = s [j] ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Ax [p] *= t ; } } } else if (scale == CHOLMOD_SYM) { /* ------------------------------------------------------------------ */ /* A = diag(s)*A*diag(s), symmetric scaling */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < ncol ; j++) { t = s [j] ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Ax [p] *= t * s [Ai [p]] ; } } } else if (scale == CHOLMOD_SCALAR) { /* ------------------------------------------------------------------ */ /* A = s[0] * A, scalar scaling */ /* ------------------------------------------------------------------ */ t = s [0] ; for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Ax [p] *= t ; } } } ASSERT (CHOLMOD(dump_sparse) (A, "A scaled", Common) >= 0) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/MatrixOps/License.txt0000644000175100001440000000203013430770173017467 0ustar hornikusersCHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/MatrixOps module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. igraph/src/CHOLMOD/MatrixOps/cholmod_vertcat.c0000644000175100001440000001402313431000472020657 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_vertcat ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Vertical concatenation, C = [A ; B] in MATLAB notation. * * A and B can be up/lo/unsym; C is unsymmetric and packed. * A and B must have the same number of columns. * C is sorted if both A and B are sorted. * * workspace: Iwork (max (A->nrow, A->ncol, B->nrow, B->ncol)). * allocates temporary copies of A and B if they are symmetric. * * Only pattern and real matrices are supported. Complex and zomplex matrices * are supported only if "values" is FALSE. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === cholmod_vertcat ====================================================== */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(vertcat) ( /* ---- input ---- */ cholmod_sparse *A, /* left matrix to concatenate */ cholmod_sparse *B, /* right matrix to concatenate */ int values, /* if TRUE compute the numerical values of C */ /* --------------- */ cholmod_common *Common ) { double *Ax, *Bx, *Cx ; Int *Ap, *Ai, *Anz, *Bp, *Bi, *Bnz, *Cp, *Ci ; cholmod_sparse *C, *A2, *B2 ; Int apacked, bpacked, anrow, bnrow, ncol, nrow, anz, bnz, nz, j, p, pend, pdest ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; RETURN_IF_NULL (B, NULL) ; values = values && (A->xtype != CHOLMOD_PATTERN) && (B->xtype != CHOLMOD_PATTERN) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; RETURN_IF_XTYPE_INVALID (B, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->ncol != B->ncol) { /* A and B must have the same number of columns */ ERROR (CHOLMOD_INVALID, "A and B must have same # of columns") ; return (NULL) ; } /* A and B must have the same numerical type if values is TRUE (both must * be CHOLMOD_REAL, this is implicitly checked above) */ Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ anrow = A->nrow ; bnrow = B->nrow ; ncol = A->ncol ; CHOLMOD(allocate_work) (0, MAX3 (anrow, bnrow, ncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* convert A to unsymmetric, if necessary */ A2 = NULL ; if (A->stype != 0) { /* workspace: Iwork (max (A->nrow,A->ncol)) */ A2 = CHOLMOD(copy) (A, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } A = A2 ; } /* convert B to unsymmetric, if necessary */ B2 = NULL ; if (B->stype != 0) { /* workspace: Iwork (max (B->nrow,B->ncol)) */ B2 = CHOLMOD(copy) (B, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; return (NULL) ; } B = B2 ; } Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; apacked = A->packed ; Bp = B->p ; Bnz = B->nz ; Bi = B->i ; Bx = B->x ; bpacked = B->packed ; /* ---------------------------------------------------------------------- */ /* allocate C */ /* ---------------------------------------------------------------------- */ anz = CHOLMOD(nnz) (A, Common) ; bnz = CHOLMOD(nnz) (B, Common) ; nrow = anrow + bnrow ; nz = anz + bnz ; C = CHOLMOD(allocate_sparse) (nrow, ncol, nz, A->sorted && B->sorted, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; return (NULL) ; } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* C = [A ; B] */ /* ---------------------------------------------------------------------- */ pdest = 0 ; for (j = 0 ; j < ncol ; j++) { /* attach A(:,j) as the first part of C(:,j) */ p = Ap [j] ; pend = (apacked) ? (Ap [j+1]) : (p + Anz [j]) ; Cp [j] = pdest ; for ( ; p < pend ; p++) { Ci [pdest] = Ai [p] ; if (values) { Cx [pdest] = Ax [p] ; } pdest++ ; } /* attach B(:,j) as the second part of C(:,j) */ p = Bp [j] ; pend = (bpacked) ? (Bp [j+1]) : (p + Bnz [j]) ; for ( ; p < pend ; p++) { Ci [pdest] = Bi [p] + anrow ; if (values) { Cx [pdest] = Bx [p] ; } pdest++ ; } } Cp [ncol] = pdest ; ASSERT (pdest == nz) ; /* ---------------------------------------------------------------------- */ /* free the unsymmetric copies of A and B, and return C */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&A2, Common) ; CHOLMOD(free_sparse) (&B2, Common) ; return (C) ; } #endif igraph/src/CHOLMOD/MatrixOps/cholmod_sdmult.c0000644000175100001440000001240213431000472020516 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_sdmult ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Sparse matrix times dense matrix: * Y = alpha*(A*X) + beta*Y or Y = alpha*(A'*X) + beta*Y, * where A is sparse and X and Y are dense. * * when using A, X has A->ncol columns and Y has A->nrow rows * when using A', X has A->nrow columns and Y has A->ncol rows * * workspace: none in Common. Temporary workspace of size 4*(X->nrow) is used * if A is stored in symmetric form and X has four columns or more. If the * workspace is not available, a slower method is used instead that requires * no workspace. * * transpose = 0: use A * otherwise, use A' (complex conjugate transpose) * * transpose is ignored if the matrix is symmetric or Hermitian. * (the array transpose A.' is not supported). * * Supports real, complex, and zomplex matrices, but the xtypes of A, X, and Y * must all match. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define REAL #include "t_cholmod_sdmult.c" #define COMPLEX #include "t_cholmod_sdmult.c" #define ZOMPLEX #include "t_cholmod_sdmult.c" /* ========================================================================== */ /* === cholmod_sdmult ======================================================= */ /* ========================================================================== */ int CHOLMOD(sdmult) ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to multiply */ int transpose, /* use A if 0, otherwise use A' */ double alpha [2], /* scale factor for A */ double beta [2], /* scale factor for Y */ cholmod_dense *X, /* dense matrix to multiply */ /* ---- in/out --- */ cholmod_dense *Y, /* resulting dense matrix */ /* --------------- */ cholmod_common *Common ) { double *w ; size_t nx, ny ; Int e ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (X, FALSE) ; RETURN_IF_NULL (Y, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (Y, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; ny = transpose ? A->ncol : A->nrow ; /* required length of Y */ nx = transpose ? A->nrow : A->ncol ; /* required length of X */ if (X->nrow != nx || X->ncol != Y->ncol || Y->nrow != ny) { /* X and/or Y have the wrong dimension */ ERROR (CHOLMOD_INVALID, "X and/or Y have wrong dimensions") ; return (FALSE) ; } if (A->xtype != X->xtype || A->xtype != Y->xtype) { ERROR (CHOLMOD_INVALID, "A, X, and Y must have same xtype") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace, if required */ /* ---------------------------------------------------------------------- */ w = NULL ; e = (A->xtype == CHOLMOD_REAL ? 1:2) ; if (A->stype && X->ncol >= 4) { w = CHOLMOD(malloc) (nx, 4*e*sizeof (double), Common) ; } if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } /* ---------------------------------------------------------------------- */ /* Y = alpha*op(A)*X + beta*Y via template routine */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (A, "A", Common) >= 0) ; DEBUG (CHOLMOD(dump_dense) (X, "X", Common)) ; DEBUG (if (IS_NONZERO (beta [0]) || (IS_NONZERO (beta [1]) && A->xtype != CHOLMOD_REAL)) CHOLMOD(dump_dense) (Y, "Y", Common)) ; switch (A->xtype) { case CHOLMOD_REAL: r_cholmod_sdmult (A, transpose, alpha, beta, X, Y, w) ; break ; case CHOLMOD_COMPLEX: c_cholmod_sdmult (A, transpose, alpha, beta, X, Y, w) ; break ; case CHOLMOD_ZOMPLEX: z_cholmod_sdmult (A, transpose, alpha, beta, X, Y, w) ; break ; } /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(free) (4*nx, e*sizeof (double), w, Common) ; DEBUG (CHOLMOD(dump_dense) (Y, "Y", Common)) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/MatrixOps/gpl.txt0000644000175100001440000004313313430770174016701 0ustar hornikusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. igraph/src/CHOLMOD/MatrixOps/cholmod_drop.c0000644000175100001440000001205513431000472020156 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_drop =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Drop small entries from A, and entries in the ignored part of A if A * is symmetric. None of the matrix operations drop small numerical entries * from a matrix, except for this one. NaN's and Inf's are kept. * * workspace: none * * Supports pattern and real matrices, complex and zomplex not supported. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === cholmod_drop ========================================================= */ /* ========================================================================== */ int CHOLMOD(drop) ( /* ---- input ---- */ double tol, /* keep entries with absolute value > tol */ /* ---- in/out --- */ cholmod_sparse *A, /* matrix to drop entries from */ /* --------------- */ cholmod_common *Common ) { double aij ; double *Ax ; Int *Ap, *Ai, *Anz ; Int packed, i, j, nrow, ncol, p, pend, nz, values ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_REAL, FALSE) ; Common->status = CHOLMOD_OK ; ASSERT (CHOLMOD(dump_sparse) (A, "A predrop", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Anz = A->nz ; packed = A->packed ; ncol = A->ncol ; nrow = A->nrow ; values = (A->xtype != CHOLMOD_PATTERN) ; nz = 0 ; if (values) { /* ------------------------------------------------------------------ */ /* drop small numerical entries from A, and entries in ignored part */ /* ------------------------------------------------------------------ */ if (A->stype > 0) { /* -------------------------------------------------------------- */ /* A is symmetric, with just upper triangular part stored */ /* -------------------------------------------------------------- */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Ap [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; aij = Ax [p] ; if (i <= j && (fabs (aij) > tol || IS_NAN (aij))) { Ai [nz] = i ; Ax [nz] = aij ; nz++ ; } } } } else if (A->stype < 0) { /* -------------------------------------------------------------- */ /* A is symmetric, with just lower triangular part stored */ /* -------------------------------------------------------------- */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Ap [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; aij = Ax [p] ; if (i >= j && (fabs (aij) > tol || IS_NAN (aij))) { Ai [nz] = i ; Ax [nz] = aij ; nz++ ; } } } } else { /* -------------------------------------------------------------- */ /* both parts of A present, just drop small entries */ /* -------------------------------------------------------------- */ for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; Ap [j] = nz ; for ( ; p < pend ; p++) { i = Ai [p] ; aij = Ax [p] ; if (fabs (aij) > tol || IS_NAN (aij)) { Ai [nz] = i ; Ax [nz] = aij ; nz++ ; } } } } Ap [ncol] = nz ; /* reduce A->i and A->x in size */ ASSERT (MAX (1,nz) <= A->nzmax) ; CHOLMOD(reallocate_sparse) (nz, A, Common) ; ASSERT (Common->status >= CHOLMOD_OK) ; } else { /* ------------------------------------------------------------------ */ /* consider only the pattern of A */ /* ------------------------------------------------------------------ */ /* Note that cholmod_band_inplace calls cholmod_reallocate_sparse */ if (A->stype > 0) { CHOLMOD(band_inplace) (0, ncol, 0, A, Common) ; } else if (A->stype < 0) { CHOLMOD(band_inplace) (-nrow, 0, 0, A, Common) ; } } ASSERT (CHOLMOD(dump_sparse) (A, "A dropped", Common) >= 0) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/MatrixOps/t_cholmod_sdmult.c0000644000175100001440000004456313431000472021056 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/t_cholmod_sdmult =========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Template routine for cholmod_sdmult */ #include "cholmod_template.h" #undef ADVANCE #ifdef REAL #define ADVANCE(x,z,d) x += d #elif defined (COMPLEX) #define ADVANCE(x,z,d) x += 2*d #else #define ADVANCE(x,z,d) x += d ; z += d #endif /* ========================================================================== */ /* === t_cholmod_sdmult ===================================================== */ /* ========================================================================== */ static void TEMPLATE (cholmod_sdmult) ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to multiply */ int transpose, /* use A if 0, or A' otherwise */ double alpha [2], /* scale factor for A */ double beta [2], /* scale factor for Y */ cholmod_dense *X, /* dense matrix to multiply */ /* ---- in/out --- */ cholmod_dense *Y, /* resulting dense matrix */ /* -- workspace -- */ double *W /* size 4*nx if needed, twice that for c/zomplex case */ ) { double yx [8], xx [8], ax [2] ; #ifdef ZOMPLEX double yz [4], xz [4], az [1] ; double betaz [1], alphaz [1] ; #endif double *Ax, *Az, *Xx, *Xz, *Yx, *Yz, *w, *Wz ; Int *Ap, *Ai, *Anz ; size_t nx, ny, dx, dy ; Int packed, nrow, ncol, j, k, p, pend, kcol, i ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ #ifdef ZOMPLEX betaz [0] = beta [1] ; alphaz [0] = alpha [1] ; #endif ny = transpose ? A->ncol : A->nrow ; /* required length of Y */ nx = transpose ? A->nrow : A->ncol ; /* required length of X */ nrow = A->nrow ; ncol = A->ncol ; Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; Az = A->z ; packed = A->packed ; Xx = X->x ; Xz = X->z ; Yx = Y->x ; Yz = Y->z ; kcol = X->ncol ; dy = Y->d ; dx = X->d ; w = W ; Wz = W + 4*nx ; /* ---------------------------------------------------------------------- */ /* Y = beta * Y */ /* ---------------------------------------------------------------------- */ if (ENTRY_IS_ZERO (beta, betaz, 0)) { for (k = 0 ; k < kcol ; k++) { for (i = 0 ; i < ((Int) ny) ; i++) { /* y [i] = 0. ; */ CLEAR (Yx, Yz, i) ; } /* y += dy ; */ ADVANCE (Yx,Yz,dy) ; } } else if (!ENTRY_IS_ONE (beta, betaz, 0)) { for (k = 0 ; k < kcol ; k++) { for (i = 0 ; i < ((Int) ny) ; i++) { /* y [i] *= beta [0] ; */ MULT (Yx,Yz,i, Yx,Yz,i, beta,betaz, 0) ; } /* y += dy ; */ ADVANCE (Yx,Yz,dy) ; } } if (ENTRY_IS_ZERO (alpha, alphaz, 0)) { /* nothing else to do */ return ; } /* ---------------------------------------------------------------------- */ /* Y += alpha * op(A) * X, where op(A)=A or A' */ /* ---------------------------------------------------------------------- */ Yx = Y->x ; Yz = Y->z ; k = 0 ; if (A->stype == 0) { if (transpose) { /* -------------------------------------------------------------- */ /* Y += alpha * A' * x, unsymmetric case */ /* -------------------------------------------------------------- */ if (kcol % 4 == 1) { for (j = 0 ; j < ncol ; j++) { /* yj = 0. ; */ CLEAR (yx, yz, 0) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* yj += conj(Ax [p]) * x [Ai [p]] ; */ i = Ai [p] ; ASSIGN_CONJ (ax,az,0, Ax,Az,p) ; MULTADD (yx,yz,0, ax,az,0, Xx,Xz,i) ; } /* y [j] += alpha [0] * yj ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; } /* y += dy ; */ /* x += dx ; */ ADVANCE (Yx,Yz,dy) ; ADVANCE (Xx,Xz,dx) ; k++ ; } else if (kcol % 4 == 2) { for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = conj (Ax [p]) ; */ ASSIGN_CONJ (ax,az,0, Ax,Az,p) ; /* yj0 += aij * x [i ] ; */ /* yj1 += aij * x [i+dx] ; */ MULTADD (yx,yz,0, ax,az,0, Xx,Xz,i) ; MULTADD (yx,yz,1, ax,az,0, Xx,Xz,i+dx) ; } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+dy] += alpha [0] * yj1 ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy, alpha,alphaz,0, yx,yz,1) ; } /* y += 2*dy ; */ /* x += 2*dx ; */ ADVANCE (Yx,Yz,2*dy) ; ADVANCE (Xx,Xz,2*dx) ; k += 2 ; } else if (kcol % 4 == 3) { for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ /* yj2 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; CLEAR (yx,yz,2) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = conj (Ax [p]) ; */ ASSIGN_CONJ (ax,az,0, Ax,Az,p) ; /* yj0 += aij * x [i ] ; */ /* yj1 += aij * x [i+ dx] ; */ /* yj2 += aij * x [i+2*dx] ; */ MULTADD (yx,yz,0, ax,az,0, Xx,Xz,i) ; MULTADD (yx,yz,1, ax,az,0, Xx,Xz,i+dx) ; MULTADD (yx,yz,2, ax,az,0, Xx,Xz,i+2*dx) ; } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+ dy] += alpha [0] * yj1 ; */ /* y [j+2*dy] += alpha [0] * yj2 ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy, alpha,alphaz,0, yx,yz,1) ; MULTADD (Yx,Yz,j+2*dy, alpha,alphaz,0, yx,yz,2) ; } /* y += 3*dy ; */ /* x += 3*dx ; */ ADVANCE (Yx,Yz,3*dy) ; ADVANCE (Xx,Xz,3*dx) ; k += 3 ; } for ( ; k < kcol ; k += 4) { for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ /* yj2 = 0. ; */ /* yj3 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; CLEAR (yx,yz,2) ; CLEAR (yx,yz,3) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = conj(Ax [p]) ; */ ASSIGN_CONJ (ax,az,0, Ax,Az,p) ; /* yj0 += aij * x [i ] ; */ /* yj1 += aij * x [i+ dx] ; */ /* yj2 += aij * x [i+2*dx] ; */ /* yj3 += aij * x [i+3*dx] ; */ MULTADD (yx,yz,0, ax,az,0, Xx,Xz,i) ; MULTADD (yx,yz,1, ax,az,0, Xx,Xz,i+dx) ; MULTADD (yx,yz,2, ax,az,0, Xx,Xz,i+2*dx) ; MULTADD (yx,yz,3, ax,az,0, Xx,Xz,i+3*dx) ; } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+ dy] += alpha [0] * yj1 ; */ /* y [j+2*dy] += alpha [0] * yj2 ; */ /* y [j+3*dy] += alpha [0] * yj3 ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy, alpha,alphaz,0, yx,yz,1) ; MULTADD (Yx,Yz,j+2*dy, alpha,alphaz,0, yx,yz,2) ; MULTADD (Yx,Yz,j+3*dy, alpha,alphaz,0, yx,yz,3) ; } /* y += 4*dy ; */ /* x += 4*dx ; */ ADVANCE (Yx,Yz,4*dy) ; ADVANCE (Xx,Xz,4*dx) ; } } else { /* -------------------------------------------------------------- */ /* Y += alpha * A * x, unsymmetric case */ /* -------------------------------------------------------------- */ if (kcol % 4 == 1) { for (j = 0 ; j < ncol ; j++) { /* xj = alpha [0] * x [j] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* y [Ai [p]] += Ax [p] * xj ; */ i = Ai [p] ; MULTADD (Yx,Yz,i, Ax,Az,p, xx,xz,0) ; } } /* y += dy ; */ /* x += dx ; */ ADVANCE (Yx,Yz,dy) ; ADVANCE (Xx,Xz,dx) ; k++ ; } else if (kcol % 4 == 2) { for (j = 0 ; j < ncol ; j++) { /* xj0 = alpha [0] * x [j ] ; */ /* xj1 = alpha [0] * x [j+dx] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; MULT (xx,xz,1, alpha,alphaz,0, Xx,Xz,j+dx) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+dy] += aij * xj1 ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; } } /* y += 2*dy ; */ /* x += 2*dx ; */ ADVANCE (Yx,Yz,2*dy) ; ADVANCE (Xx,Xz,2*dx) ; k += 2 ; } else if (kcol % 4 == 3) { for (j = 0 ; j < ncol ; j++) { /* xj0 = alpha [0] * x [j ] ; */ /* xj1 = alpha [0] * x [j+ dx] ; */ /* xj2 = alpha [0] * x [j+2*dx] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; MULT (xx,xz,1, alpha,alphaz,0, Xx,Xz,j+dx) ; MULT (xx,xz,2, alpha,alphaz,0, Xx,Xz,j+2*dx) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; } } /* y += 3*dy ; */ /* x += 3*dx ; */ ADVANCE (Yx,Yz,3*dy) ; ADVANCE (Xx,Xz,3*dx) ; k += 3 ; } for ( ; k < kcol ; k += 4) { for (j = 0 ; j < ncol ; j++) { /* xj0 = alpha [0] * x [j ] ; */ /* xj1 = alpha [0] * x [j+ dx] ; */ /* xj2 = alpha [0] * x [j+2*dx] ; */ /* xj3 = alpha [0] * x [j+3*dx] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; MULT (xx,xz,1, alpha,alphaz,0, Xx,Xz,j+dx) ; MULT (xx,xz,2, alpha,alphaz,0, Xx,Xz,j+2*dx) ; MULT (xx,xz,3, alpha,alphaz,0, Xx,Xz,j+3*dx) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ /* y [i+3*dy] += aij * xj3 ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; MULTADD (Yx,Yz,i+3*dy, ax,az,0, xx,xz,3) ; } } /* y += 4*dy ; */ /* x += 4*dx ; */ ADVANCE (Yx,Yz,4*dy) ; ADVANCE (Xx,Xz,4*dx) ; } } } else { /* ------------------------------------------------------------------ */ /* Y += alpha * (A or A') * x, symmetric case (upper/lower) */ /* ------------------------------------------------------------------ */ /* Only the upper/lower triangular part and the diagonal of A is used. * Since both x and y are written to in the innermost loop, this * code can experience cache bank conflicts if x is used directly. * Thus, a copy is made of x, four columns at a time, if x has * four or more columns. */ if (kcol % 4 == 1) { for (j = 0 ; j < ncol ; j++) { /* yj = 0. ; */ CLEAR (yx,yz,0) ; /* xj = alpha [0] * x [j] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* y [i] += Ax [p] * xj ; */ MULTADD (Yx,Yz,i, Ax,Az,p, xx,xz,0) ; } else if ((A->stype > 0 && i < j) || (A->stype < 0 && i > j)) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i] += aij * xj ; */ /* yj += aij * x [i] ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADDCONJ (yx,yz,0, ax,az,0, Xx,Xz,i) ; } } /* y [j] += alpha [0] * yj ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; } /* y += dy ; */ /* x += dx ; */ ADVANCE (Yx,Yz,dy) ; ADVANCE (Xx,Xz,dx) ; k++ ; } else if (kcol % 4 == 2) { for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; /* xj0 = alpha [0] * x [j ] ; */ /* xj1 = alpha [0] * x [j+dx] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; MULT (xx,xz,1, alpha,alphaz,0, Xx,Xz,j+dx) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+dy] += aij * xj1 ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; } else if ((A->stype > 0 && i < j) || (A->stype < 0 && i > j)) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+dy] += aij * xj1 ; */ /* yj0 += aij * x [i ] ; */ /* yj1 += aij * x [i+dx] ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADDCONJ (yx,yz,0, ax,az,0, Xx,Xz,i) ; MULTADDCONJ (yx,yz,1, ax,az,0, Xx,Xz,i+dx) ; } } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+dy] += alpha [0] * yj1 ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy, alpha,alphaz,0, yx,yz,1) ; } /* y += 2*dy ; */ /* x += 2*dx ; */ ADVANCE (Yx,Yz,2*dy) ; ADVANCE (Xx,Xz,2*dx) ; k += 2 ; } else if (kcol % 4 == 3) { for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ /* yj2 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; CLEAR (yx,yz,2) ; /* xj0 = alpha [0] * x [j ] ; */ /* xj1 = alpha [0] * x [j+ dx] ; */ /* xj2 = alpha [0] * x [j+2*dx] ; */ MULT (xx,xz,0, alpha,alphaz,0, Xx,Xz,j) ; MULT (xx,xz,1, alpha,alphaz,0, Xx,Xz,j+dx) ; MULT (xx,xz,2, alpha,alphaz,0, Xx,Xz,j+2*dx) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; } else if ((A->stype > 0 && i < j) || (A->stype < 0 && i > j)) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ /* yj0 += aij * x [i ] ; */ /* yj1 += aij * x [i+ dx] ; */ /* yj2 += aij * x [i+2*dx] ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; MULTADDCONJ (yx,yz,0, ax,az,0, Xx,Xz,i) ; MULTADDCONJ (yx,yz,1, ax,az,0, Xx,Xz,i+dx) ; MULTADDCONJ (yx,yz,2, ax,az,0, Xx,Xz,i+2*dx) ; } } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+ dy] += alpha [0] * yj1 ; */ /* y [j+2*dy] += alpha [0] * yj2 ; */ MULTADD (Yx,Yz,j, alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy, alpha,alphaz,0, yx,yz,1) ; MULTADD (Yx,Yz,j+2*dy, alpha,alphaz,0, yx,yz,2) ; } /* y += 3*dy ; */ /* x += 3*dx ; */ ADVANCE (Yx,Yz,3*dy) ; ADVANCE (Xx,Xz,3*dx) ; k += 3 ; } /* copy four columns of X into W, and put in row form */ for ( ; k < kcol ; k += 4) { for (j = 0 ; j < ncol ; j++) { /* w [4*j ] = x [j ] ; */ /* w [4*j+1] = x [j+ dx] ; */ /* w [4*j+2] = x [j+2*dx] ; */ /* w [4*j+3] = x [j+3*dx] ; */ ASSIGN (w,Wz,4*j , Xx,Xz,j ) ; ASSIGN (w,Wz,4*j+1, Xx,Xz,j+dx ) ; ASSIGN (w,Wz,4*j+2, Xx,Xz,j+2*dx) ; ASSIGN (w,Wz,4*j+3, Xx,Xz,j+3*dx) ; } for (j = 0 ; j < ncol ; j++) { /* yj0 = 0. ; */ /* yj1 = 0. ; */ /* yj2 = 0. ; */ /* yj3 = 0. ; */ CLEAR (yx,yz,0) ; CLEAR (yx,yz,1) ; CLEAR (yx,yz,2) ; CLEAR (yx,yz,3) ; /* xj0 = alpha [0] * w [4*j ] ; */ /* xj1 = alpha [0] * w [4*j+1] ; */ /* xj2 = alpha [0] * w [4*j+2] ; */ /* xj3 = alpha [0] * w [4*j+3] ; */ MULT (xx,xz,0, alpha,alphaz,0, w,Wz,4*j) ; MULT (xx,xz,1, alpha,alphaz,0, w,Wz,4*j+1) ; MULT (xx,xz,2, alpha,alphaz,0, w,Wz,4*j+2) ; MULT (xx,xz,3, alpha,alphaz,0, w,Wz,4*j+3) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i == j) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ /* y [i+3*dy] += aij * xj3 ; */ MULTADD (Yx,Yz,i , ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy , ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; MULTADD (Yx,Yz,i+3*dy, ax,az,0, xx,xz,3) ; } else if ((A->stype > 0 && i < j) || (A->stype < 0 && i > j)) { /* aij = Ax [p] ; */ ASSIGN (ax,az,0, Ax,Az,p) ; /* y [i ] += aij * xj0 ; */ /* y [i+ dy] += aij * xj1 ; */ /* y [i+2*dy] += aij * xj2 ; */ /* y [i+3*dy] += aij * xj3 ; */ /* yj0 += aij * w [4*i ] ; */ /* yj1 += aij * w [4*i+1] ; */ /* yj2 += aij * w [4*i+2] ; */ /* yj3 += aij * w [4*i+3] ; */ MULTADD (Yx,Yz,i, ax,az,0, xx,xz,0) ; MULTADD (Yx,Yz,i+dy, ax,az,0, xx,xz,1) ; MULTADD (Yx,Yz,i+2*dy, ax,az,0, xx,xz,2) ; MULTADD (Yx,Yz,i+3*dy, ax,az,0, xx,xz,3) ; MULTADDCONJ (yx,yz,0, ax,az,0, w,Wz,4*i) ; MULTADDCONJ (yx,yz,1, ax,az,0, w,Wz,4*i+1) ; MULTADDCONJ (yx,yz,2, ax,az,0, w,Wz,4*i+2) ; MULTADDCONJ (yx,yz,3, ax,az,0, w,Wz,4*i+3) ; } } /* y [j ] += alpha [0] * yj0 ; */ /* y [j+ dy] += alpha [0] * yj1 ; */ /* y [j+2*dy] += alpha [0] * yj2 ; */ /* y [j+3*dy] += alpha [0] * yj3 ; */ MULTADD (Yx,Yz,j , alpha,alphaz,0, yx,yz,0) ; MULTADD (Yx,Yz,j+dy , alpha,alphaz,0, yx,yz,1) ; MULTADD (Yx,Yz,j+2*dy, alpha,alphaz,0, yx,yz,2) ; MULTADD (Yx,Yz,j+3*dy, alpha,alphaz,0, yx,yz,3) ; } /* y += 4*dy ; */ /* x += 4*dx ; */ ADVANCE (Yx,Yz,4*dy) ; ADVANCE (Xx,Xz,4*dx) ; } } } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/MatrixOps/cholmod_submatrix.c0000644000175100001440000003164413431000472021235 0ustar hornikusers/* ========================================================================== */ /* === MatrixOps/cholmod_submatrix ========================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/MatrixOps Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/MatrixOps Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* C = A (rset,cset), where C becomes length(rset)-by-length(cset) in dimension. * rset and cset can have duplicate entries. A and C must be unsymmetric. C * is packed. If the sorted flag is TRUE on input, or rset is sorted and A is * sorted, then C is sorted; otherwise C is unsorted. * * A NULL rset or cset means "[ ]" in MATLAB notation. * If the length of rset or cset is negative, it denotes ":" in MATLAB notation. * * For permuting a matrix, this routine is an alternative to cholmod_ptranspose * (which permutes and transposes a matrix and can work on symmetric matrices). * * The time taken by this routine is O(A->nrow) if the Common workspace needs * to be initialized, plus O(C->nrow + C->ncol + nnz (A (:,cset))). Thus, if C * is small and the workspace is not initialized, the time can be dominated by * the call to cholmod_allocate_work. However, once the workspace is * allocated, subsequent calls take less time. * * workspace: Iwork (max (A->nrow + length (rset), length (cset))). * allocates temporary copy of C if it is to be returned sorted. * * Future work: A common case occurs where A has sorted columns, and rset is in * the form lo:hi in MATLAB notation. This routine could exploit that case * to run even faster when the matrix is sorted, particularly when lo is small. * * Only pattern and real matrices are supported. Complex and zomplex matrices * are supported only when "values" is FALSE. */ #ifndef NMATRIXOPS #include "cholmod_internal.h" #include "cholmod_matrixops.h" /* ========================================================================== */ /* === check_subset ========================================================= */ /* ========================================================================== */ /* Check the rset or cset, and return TRUE if valid, FALSE if invalid */ static int check_subset (Int *set, Int len, Int n) { Int k ; if (set == NULL) { return (TRUE) ; } for (k = 0 ; k < len ; k++) { if (set [k] < 0 || set [k] >= n) { return (FALSE) ; } } return (TRUE) ; } /* ========================================================================== */ /* === cholmod_submatrix ==================================================== */ /* ========================================================================== */ cholmod_sparse *CHOLMOD(submatrix) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to subreference */ Int *rset, /* set of row indices, duplicates OK */ SuiteSparse_long rsize, /* size of rset, or -1 for ":" */ Int *cset, /* set of column indices, duplicates OK */ SuiteSparse_long csize, /* size of cset, or -1 for ":" */ int values, /* if TRUE compute the numerical values of C */ int sorted, /* if TRUE then return C with sorted columns */ /* --------------- */ cholmod_common *Common ) { double aij = 0 ; double *Ax, *Cx ; Int *Ap, *Ai, *Anz, *Ci, *Cp, *Head, *Rlen, *Rnext, *Iwork ; cholmod_sparse *C ; Int packed, ancol, anrow, cnrow, cncol, nnz, i, j, csorted, ilast, p, pend, pdest, ci, cj, head, nr, nc ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (A, NULL) ; values = (values && (A->xtype != CHOLMOD_PATTERN)) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, values ? CHOLMOD_REAL : CHOLMOD_ZOMPLEX, NULL) ; if (A->stype != 0) { /* A must be unsymmetric */ ERROR (CHOLMOD_INVALID, "symmetric upper or lower case not supported") ; return (NULL) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ ancol = A->ncol ; anrow = A->nrow ; nr = rsize ; nc = csize ; if (rset == NULL) { /* nr = 0 denotes rset = [ ], nr < 0 denotes rset = 0:anrow-1 */ nr = (nr < 0) ? (-1) : 0 ; } if (cset == NULL) { /* nr = 0 denotes cset = [ ], nr < 0 denotes cset = 0:ancol-1 */ nc = (nc < 0) ? (-1) : 0 ; } cnrow = (nr < 0) ? anrow : nr ; /* negative rset means rset = 0:anrow-1 */ cncol = (nc < 0) ? ancol : nc ; /* negative cset means cset = 0:ancol-1 */ if (nr < 0 && nc < 0) { /* ------------------------------------------------------------------ */ /* C = A (:,:), use cholmod_copy instead */ /* ------------------------------------------------------------------ */ /* workspace: Iwork (max (C->nrow,C->ncol)) */ PRINT1 (("submatrix C = A (:,:)\n")) ; C = CHOLMOD(copy) (A, 0, values, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } return (C) ; } PRINT1 (("submatrix nr "ID" nc "ID" Cnrow "ID" Cncol "ID"" " Anrow "ID" Ancol "ID"\n", nr, nc, cnrow, cncol, anrow, ancol)) ; /* s = MAX3 (anrow+MAX(0,nr), cncol, cnrow) ; */ s = CHOLMOD(add_size_t) (anrow, MAX (0,nr), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } s = MAX3 (s, ((size_t) cncol), ((size_t) cnrow)) ; CHOLMOD(allocate_work) (anrow, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Anz = A->nz ; Ai = A->i ; Ax = A->x ; packed = A->packed ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Head = Common->Head ; /* size anrow */ Iwork = Common->Iwork ; Rlen = Iwork ; /* size anrow (i/i/l) */ Rnext = Iwork + anrow ; /* size nr (i/i/l), not used if nr < 0 */ /* ---------------------------------------------------------------------- */ /* construct inverse of rset and compute nnz (C) */ /* ---------------------------------------------------------------------- */ PRINT1 (("nr "ID" nc "ID"\n", nr, nc)) ; PRINT1 (("anrow "ID" ancol "ID"\n", anrow, ancol)) ; PRINT1 (("cnrow "ID" cncol "ID"\n", cnrow, cncol)) ; DEBUG (for (i = 0 ; i < nr ; i++) PRINT2 (("rset ["ID"] = "ID"\n", i, rset [i]))); DEBUG (for (i = 0 ; i < nc ; i++) PRINT2 (("cset ["ID"] = "ID"\n", i, cset [i]))); /* C is sorted if A and rset are sorted, or if C has one row or less */ csorted = A->sorted || (cnrow <= 1) ; if (!check_subset (rset, nr, anrow)) { ERROR (CHOLMOD_INVALID, "invalid rset") ; return (NULL) ; } if (!check_subset (cset, nc, ancol)) { ERROR (CHOLMOD_INVALID, "invalid cset") ; return (NULL) ; } nnz = 0 ; if (nr < 0) { /* C = A (:,cset) where cset = [ ] or cset is not empty */ ASSERT (IMPLIES (cncol > 0, cset != NULL)) ; for (cj = 0 ; cj < cncol ; cj++) { /* construct column cj of C, which is column j of A */ j = cset [cj] ; nnz += (packed) ? (Ap [j+1] - Ap [j]) : MAX (0, Anz [j]) ; } } else { /* C = A (rset,cset), where rset is not empty but cset might be empty */ /* create link lists in reverse order to preserve natural order */ ilast = anrow ; for (ci = nr-1 ; ci >= 0 ; ci--) { /* row i of A becomes row ci of C; add ci to ith link list */ i = rset [ci] ; head = Head [i] ; Rlen [i] = (head == EMPTY) ? 1 : (Rlen [i] + 1) ; Rnext [ci] = head ; Head [i] = ci ; if (i > ilast) { /* row indices in columns of C will not be sorted */ csorted = FALSE ; } ilast = i ; } #ifndef NDEBUG for (i = 0 ; i < anrow ; i++) { Int k = 0 ; Int rlen = (Head [i] != EMPTY) ? Rlen [i] : -1 ; PRINT1 (("Row "ID" Rlen "ID": ", i, rlen)) ; for (ci = Head [i] ; ci != EMPTY ; ci = Rnext [ci]) { k++ ; PRINT2 ((""ID" ", ci)) ; } PRINT1 (("\n")) ; ASSERT (IMPLIES (Head [i] != EMPTY, k == Rlen [i])) ; } #endif /* count nonzeros in C */ for (cj = 0 ; cj < cncol ; cj++) { /* count rows in column cj of C, which is column j of A */ j = (nc < 0) ? cj : (cset [cj]) ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* row i of A becomes multiple rows (ci) of C */ i = Ai [p] ; ASSERT (i >= 0 && i < anrow) ; if (Head [i] != EMPTY) { nnz += Rlen [i] ; } } } } PRINT1 (("nnz (C) "ID"\n", nnz)) ; /* rset and cset are now valid */ DEBUG (CHOLMOD(dump_subset) (rset, rsize, anrow, "rset", Common)) ; DEBUG (CHOLMOD(dump_subset) (cset, csize, ancol, "cset", Common)) ; /* ---------------------------------------------------------------------- */ /* allocate C */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_sparse) (cnrow, cncol, nnz, csorted, TRUE, 0, values ? A->xtype : CHOLMOD_PATTERN, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ for (i = 0 ; i < anrow ; i++) { Head [i] = EMPTY ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (NULL) ; } Cp = C->p ; Ci = C->i ; Cx = C->x ; /* ---------------------------------------------------------------------- */ /* C = A (rset,cset) */ /* ---------------------------------------------------------------------- */ pdest = 0 ; if (nnz == 0) { /* C has no nonzeros */ for (cj = 0 ; cj <= cncol ; cj++) { Cp [cj] = 0 ; } } else if (nr < 0) { /* C = A (:,cset), where cset is not empty */ for (cj = 0 ; cj < cncol ; cj++) { /* construct column cj of C, which is column j of A */ PRINT1 (("construct cj = j = "ID"\n", cj)) ; j = cset [cj] ; Cp [cj] = pdest ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { Ci [pdest] = Ai [p] ; if (values) { Cx [pdest] = Ax [p] ; } pdest++ ; ASSERT (pdest <= nnz) ; } } } else { /* C = A (rset,cset), where rset is not empty but cset might be empty */ for (cj = 0 ; cj < cncol ; cj++) { /* construct column cj of C, which is column j of A */ PRINT1 (("construct cj = "ID"\n", cj)) ; j = (nc < 0) ? cj : (cset [cj]) ; PRINT1 (("cj = "ID"\n", j)) ; Cp [cj] = pdest ; p = Ap [j] ; pend = (packed) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { /* row (Ai [p]) of A becomes multiple rows (ci) of C */ PRINT2 (("i: "ID" becomes: ", Ai [p])) ; if (values) { aij = Ax [p] ; } for (ci = Head [Ai [p]] ; ci != EMPTY ; ci = Rnext [ci]) { PRINT3 ((""ID" ", ci)) ; Ci [pdest] = ci ; if (values) { Cx [pdest] = aij ; } pdest++ ; ASSERT (pdest <= nnz) ; } PRINT2 (("\n")) ; } } } Cp [cncol] = pdest ; ASSERT (nnz == pdest) ; /* ---------------------------------------------------------------------- */ /* clear workspace */ /* ---------------------------------------------------------------------- */ for (ci = 0 ; ci < nr ; ci++) { Head [rset [ci]] = EMPTY ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* sort C, if requested */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (C , "C before sort", Common) >= 0) ; if (sorted && !csorted) { /* workspace: Iwork (max (C->nrow,C->ncol)) */ if (!CHOLMOD(sort) (C, Common)) { /* out of memory */ CHOLMOD(free_sparse) (&C, Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (NULL) ; } } /* ---------------------------------------------------------------------- */ /* return result */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_sparse) (C , "Final C", Common) >= 0) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (C) ; } #endif igraph/src/CHOLMOD/Makefile0000644000175100001440000000372513562737552015104 0ustar hornikusers#------------------------------------------------------------------------------- # CHOLMOD Makefile #------------------------------------------------------------------------------- VERSION = 2.1.2 # Note: If you do not have METIS, or do not wish to use it in CHOLMOD, you must # compile CHOLMOD with the -DNPARTITION flag. # See ../SuiteSparse_config/SuiteSparse_config.mk . default: all include ../SuiteSparse_config/SuiteSparse_config.mk # Compile the C-callable libraries and the Demo programs. all: ( cd Demo ; $(MAKE) ) # Compile the C-callable libraries only. library: ( cd Lib ; $(MAKE) ) # Remove all files not in the original distribution purge: ( cd Tcov ; $(MAKE) purge ) ( cd Lib ; $(MAKE) purge ) ( cd Valgrind ; $(MAKE) dopurge ) ( cd Demo ; $(MAKE) purge ) ( cd Doc ; $(MAKE) purge ) ( cd MATLAB ; $(RM) $(CLEAN) rename.h *.mex* ) # Remove all files not in the original distribution, except keep the # compiled libraries. clean: ( cd Tcov ; $(MAKE) clean ) ( cd Lib ; $(MAKE) clean ) ( cd Valgrind ; $(MAKE) clean ) ( cd Demo ; $(MAKE) clean ) ( cd MATLAB ; $(RM) $(CLEAN) ) distclean: purge ccode: all # Run the test coverage suite. Takes about 40 minutes on a 3.2GHz Pentium. # Requires Linux (gcc, gcov). cov: ( cd Tcov ; $(MAKE) ) # Run the test coverage suite using Valgrind. This takes a *** long *** time. valgrind: ( cd Valgrind ; $(MAKE) ) # Compile the C-callable libraries and the Demo programs. demos: ( cd Demo ; $(MAKE) ) # create PDF documents for the original distribution docs: ( cd Doc ; $(MAKE) ) # install CHOLMOD install: $(CP) Lib/libcholmod.a $(INSTALL_LIB)/libcholmod.$(VERSION).a ( cd $(INSTALL_LIB) ; ln -sf libcholmod.$(VERSION).a libcholmod.a ) $(CP) Include/cholmod*.h $(INSTALL_INCLUDE) $(RM) $(INSTALL_INCLUDE)/cholmod_internal.h chmod 644 $(INSTALL_LIB)/libcholmod*.a chmod 644 $(INSTALL_INCLUDE)/cholmod*.h # uninstall CHOLMOD uninstall: $(RM) $(INSTALL_LIB)/libcholmod*.a $(RM) $(INSTALL_INCLUDE)/cholmod*.h igraph/src/CHOLMOD/Partition/0000755000175100001440000000000013561251652015375 5ustar hornikusersigraph/src/CHOLMOD/Partition/cholmod_nesdis.c0000644000175100001440000020723513431000472020530 0ustar hornikusers/* ========================================================================== */ /* === Partition/cholmod_nesdis ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Partition Module. * Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Partition Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD nested dissection and graph partitioning. * * cholmod_bisect: * * Finds a set of nodes that partitions the graph into two parts. * Compresses the graph first. Requires METIS. * * cholmod_nested_dissection: * * Nested dissection, using its own compression and connected-commponents * algorithms, an external graph partitioner (METIS), and a constrained * minimum degree ordering algorithm (CCOLAMD or CSYMAMD). Typically * gives better orderings than METIS_NodeND (about 5% to 10% fewer * nonzeros in L). * * cholmod_collapse_septree: * * Prune the separator tree returned by cholmod_nested_dissection. * * This file contains several routines private to this file: * * partition compress and partition a graph * clear_flag clear Common->Flag, but do not modify negative entries * find_components find the connected components of a graph * * Supports any xtype (pattern, real, complex, or zomplex). */ static int igraph_stfu2(); static int igraph_stfu1() { return igraph_stfu2(); } static int igraph_stfu2() { return igraph_stfu1(); } #ifndef NPARTITION #include "cholmod_internal.h" #include "cholmod_partition.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === partition ============================================================ */ /* ========================================================================== */ /* Find a set of nodes that partition a graph. The graph must be symmetric * with no diagonal entries. To compress the graph first, compress is TRUE * and on input Hash [j] holds the hash key for node j, which must be in the * range 0 to csize-1. The input graph (Cp, Ci) is destroyed. Cew is all 1's * on input and output. Cnw [j] > 0 is the initial weight of node j. On * output, Cnw [i] = 0 if node i is absorbed into j and the original weight * Cnw [i] is added to Cnw [j]. If compress is FALSE, the graph is not * compressed and Cnw and Hash are unmodified. The partition itself is held in * the output array Part of size n. Part [j] is 0, 1, or 2, depending on * whether node j is in the left part of the graph, the right part, or the * separator, respectively. Note that the input graph need not be connected, * and the output subgraphs (the three parts) may also be unconnected. * * Returns the size of the separator, in terms of the sum of the weights of * the nodes. It is guaranteed to be between 1 and the total weight of all * the nodes. If it is of size less than the total weight, then both the left * and right parts are guaranteed to be non-empty (this guarantee depends on * cholmod_metis_bisector). */ static SuiteSparse_long partition /* size of separator or -1 if failure */ ( /* inputs, not modified on output */ #ifndef NDEBUG Int csize, /* upper bound on # of edges in the graph; * csize >= MAX (n, nnz(C)) must hold. */ #endif int compress, /* if TRUE the compress the graph first */ /* input/output */ Int Hash [ ], /* Hash [i] = hash >= 0 is the hash function for node * i on input. On output, Hash [i] = FLIP (j) if node * i is absorbed into j. Hash [i] >= 0 if i has not * been absorbed. */ /* input graph, compressed graph of cn nodes on output */ cholmod_sparse *C, /* input/output */ Int Cnw [ ], /* size n. Cnw [j] > 0 is the weight of node j on * input. On output, if node i is absorbed into * node j, then Cnw [i] = 0 and the original weight of * node i is added to Cnw [j]. The sum of Cnw [0..n-1] * is not modified. */ /* workspace */ Int Cew [ ], /* size csize, all 1's on input and output */ /* more workspace, undefined on input and output */ Int Cmap [ ], /* size n (i/i/l) */ /* output */ Int Part [ ], /* size n, Part [j] = 0, 1, or 2. */ cholmod_common *Common ) { Int n, hash, head, i, j, k, p, pend, ilen, ilast, pi, piend, jlen, ok, cn, csep, pdest, nodes_pruned, nz, total_weight, jscattered ; Int *Cp, *Ci, *Next, *Hhead ; #ifndef NDEBUG Int cnt, pruned ; double work = 0, goodwork = 0 ; #endif /* ---------------------------------------------------------------------- */ /* quick return for small or empty graphs */ /* ---------------------------------------------------------------------- */ n = C->nrow ; Cp = C->p ; Ci = C->i ; nz = Cp [n] ; PRINT2 (("Partition start, n "ID" nz "ID"\n", n, nz)) ; total_weight = 0 ; for (j = 0 ; j < n ; j++) { ASSERT (Cnw [j] > 0) ; total_weight += Cnw [j] ; } if (n <= 2) { /* very small graph */ for (j = 0 ; j < n ; j++) { Part [j] = 2 ; } return (total_weight) ; } else if (nz <= 0) { /* no edges, this is easy */ PRINT2 (("diagonal matrix\n")) ; k = n/2 ; for (j = 0 ; j < k ; j++) { Part [j] = 0 ; } for ( ; j < n ; j++) { Part [j] = 1 ; } /* ensure the separator is not empty (required by nested dissection) */ Part [n-1] = 2 ; return (Cnw [n-1]) ; } #ifndef NDEBUG ASSERT (n > 1 && nz > 0) ; PRINT2 (("original graph:\n")) ; for (j = 0 ; j < n ; j++) { PRINT2 ((""ID": ", j)) ; for (p = Cp [j] ; p < Cp [j+1] ; p++) { i = Ci [p] ; PRINT3 ((""ID" ", i)) ; ASSERT (i >= 0 && i < n && i != j) ; } PRINT2 (("hash: "ID"\n", Hash [j])) ; } DEBUG (for (p = 0 ; p < csize ; p++) ASSERT (Cew [p] == 1)) ; #endif nodes_pruned = 0 ; if (compress) { /* ------------------------------------------------------------------ */ /* get workspace */ /* ------------------------------------------------------------------ */ Next = Part ; /* use Part as workspace for Next [ */ Hhead = Cew ; /* use Cew as workspace for Hhead [ */ /* ------------------------------------------------------------------ */ /* create the hash buckets */ /* ------------------------------------------------------------------ */ for (j = 0 ; j < n ; j++) { /* get the hash key for node j */ hash = Hash [j] ; ASSERT (hash >= 0 && hash < csize) ; head = Hhead [hash] ; if (head > EMPTY) { /* hash bucket for this hash key is empty. */ head = EMPTY ; } else { /* hash bucket for this hash key is not empty. get old head */ head = FLIP (head) ; ASSERT (head >= 0 && head < n) ; } /* node j becomes the new head of the hash bucket. FLIP it so that * we can tell the difference between an empty or non-empty hash * bucket. */ Hhead [hash] = FLIP (j) ; Next [j] = head ; ASSERT (head >= EMPTY && head < n) ; } #ifndef NDEBUG for (cnt = 0, k = 0 ; k < n ; k++) { ASSERT (Hash [k] >= 0 && Hash [k] < csize) ; /* k is alive */ hash = Hash [k] ; ASSERT (hash >= 0 && hash < csize) ; head = Hhead [hash] ; ASSERT (head < EMPTY) ; /* hash bucket not empty */ j = FLIP (head) ; ASSERT (j >= 0 && j < n) ; if (j == k) { PRINT2 (("hash "ID": ", hash)) ; for ( ; j != EMPTY ; j = Next [j]) { PRINT3 ((" "ID"", j)) ; ASSERT (j >= 0 && j < n) ; ASSERT (Hash [j] == hash) ; cnt++ ; ASSERT (cnt <= n) ; } PRINT2 (("\n")) ; } } ASSERT (cnt == n) ; #endif /* ------------------------------------------------------------------ */ /* scan the non-empty hash buckets for indistinguishable nodes */ /* ------------------------------------------------------------------ */ /* If there are no hash collisions and no compression occurs, this takes * O(n) time. If no hash collisions, but some nodes are removed, this * takes time O(n+e) where e is the sum of the degress of the nodes * that are removed. Even with many hash collisions (a rare case), * this algorithm has never been observed to perform more than nnz(A) * useless work. * * Cmap is used as workspace to mark nodes of the graph, [ * for comparing the nonzero patterns of two nodes i and j. */ #define Cmap_MARK(i) Cmap [i] = j #define Cmap_MARKED(i) (Cmap [i] == j) for (i = 0 ; i < n ; i++) { Cmap [i] = EMPTY ; } for (k = 0 ; k < n ; k++) { hash = Hash [k] ; ASSERT (hash >= FLIP (n-1) && hash < csize) ; if (hash < 0) { /* node k has already been absorbed into some other node */ ASSERT (FLIP (Hash [k]) >= 0 && FLIP (Hash [k] < n)) ; continue ; } head = Hhead [hash] ; ASSERT (head < EMPTY || head == 1) ; if (head == 1) { /* hash bucket is already empty */ continue ; } PRINT2 (("\n--------------------hash "ID":\n", hash)) ; for (j = FLIP (head) ; j != EMPTY && Next[j] > EMPTY ; j = Next [j]) { /* compare j with all nodes i following it in hash bucket */ ASSERT (j >= 0 && j < n && Hash [j] == hash) ; p = Cp [j] ; pend = Cp [j+1] ; jlen = pend - p ; jscattered = FALSE ; DEBUG (for (i = 0 ; i < n ; i++) ASSERT (!Cmap_MARKED (i))) ; DEBUG (pruned = FALSE) ; ilast = j ; for (i = Next [j] ; i != EMPTY ; i = Next [i]) { ASSERT (i >= 0 && i < n && Hash [i] == hash && i != j) ; pi = Cp [i] ; piend = Cp [i+1] ; ilen = piend - pi ; DEBUG (work++) ; if (ilen != jlen) { /* i and j have different degrees */ ilast = i ; continue ; } /* scatter the pattern of node j, if not already */ if (!jscattered) { Cmap_MARK (j) ; for ( ; p < pend ; p++) { Cmap_MARK (Ci [p]) ; } jscattered = TRUE ; DEBUG (work += jlen) ; } for (ok = Cmap_MARKED (i) ; ok && pi < piend ; pi++) { ok = Cmap_MARKED (Ci [pi]) ; DEBUG (work++) ; } if (ok) { /* found it. kill node i and merge it into j */ PRINT2 (("found "ID" absorbed into "ID"\n", i, j)) ; Hash [i] = FLIP (j) ; Cnw [j] += Cnw [i] ; Cnw [i] = 0 ; ASSERT (ilast != i && ilast >= 0 && ilast < n) ; Next [ilast] = Next [i] ; /* delete i from bucket */ nodes_pruned++ ; DEBUG (goodwork += (ilen+1)) ; DEBUG (pruned = TRUE) ; } else { /* i and j are different */ ilast = i ; } } DEBUG (if (pruned) goodwork += jlen) ; } /* empty the hash bucket, restoring Cew */ Hhead [hash] = 1 ; } DEBUG (if (((work - goodwork) / (double) nz) > 0.20) PRINT0 (( "work %12g good %12g nz %12g (wasted work/nz: %6.2f )\n", work, goodwork, (double) nz, (work - goodwork) / ((double) nz)))) ; /* All hash buckets now empty. Cmap no longer needed as workspace. ] * Cew no longer needed as Hhead; Cew is now restored to all ones. ] * Part no longer needed as workspace for Next. ] */ } /* Edge weights are all one, node weights reflect node absorption */ DEBUG (for (p = 0 ; p < csize ; p++) ASSERT (Cew [p] == 1)) ; DEBUG (for (cnt = 0, j = 0 ; j < n ; j++) cnt += Cnw [j]) ; ASSERT (cnt == total_weight) ; /* ---------------------------------------------------------------------- */ /* compress and partition the graph */ /* ---------------------------------------------------------------------- */ if (nodes_pruned == 0) { /* ------------------------------------------------------------------ */ /* no pruning done at all. Do not create the compressed graph */ /* ------------------------------------------------------------------ */ /* FUTURE WORK: could call CHACO, SCOTCH, ... here too */ csep = CHOLMOD(metis_bisector) (C, Cnw, Cew, Part, Common) ; } else if (nodes_pruned == n-1) { /* ------------------------------------------------------------------ */ /* only one node left. This is a dense graph */ /* ------------------------------------------------------------------ */ PRINT2 (("completely dense graph\n")) ; csep = total_weight ; for (j = 0 ; j < n ; j++) { Part [j] = 2 ; } } else { /* ------------------------------------------------------------------ */ /* compress the graph and partition the compressed graph */ /* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */ /* create the map from the uncompressed graph to the compressed graph */ /* ------------------------------------------------------------------ */ /* Cmap [j] = k if node j is alive and the kth node of compressed graph. * The mapping is done monotonically (that is, k <= j) to simplify the * uncompression later on. Cmap [j] = EMPTY if node j is dead. */ for (j = 0 ; j < n ; j++) { Cmap [j] = EMPTY ; } k = 0 ; for (j = 0 ; j < n ; j++) { if (Cnw [j] > 0) { ASSERT (k <= j) ; Cmap [j] = k++ ; } } cn = k ; /* # of nodes in compressed graph */ PRINT2 (("compressed graph from "ID" to "ID" nodes\n", n, cn)) ; ASSERT (cn > 1 && cn == n - nodes_pruned) ; /* ------------------------------------------------------------------ */ /* create the compressed graph */ /* ------------------------------------------------------------------ */ k = 0 ; pdest = 0 ; for (j = 0 ; j < n ; j++) { if (Cnw [j] > 0) { /* node j in the full graph is node k in the compressed graph */ ASSERT (k <= j && Cmap [j] == k) ; p = Cp [j] ; pend = Cp [j+1] ; Cp [k] = pdest ; Cnw [k] = Cnw [j] ; for ( ; p < pend ; p++) { /* prune dead nodes, and remap to new node numbering */ i = Ci [p] ; ASSERT (i >= 0 && i < n && i != j) ; i = Cmap [i] ; ASSERT (i >= EMPTY && i < cn && i != k) ; if (i > EMPTY) { ASSERT (pdest <= p) ; Ci [pdest++] = i ; } } k++ ; } } Cp [cn] = pdest ; C->nrow = cn ; C->ncol = cn ; /* affects mem stats unless restored when C free'd */ #ifndef NDEBUG PRINT2 (("pruned graph ("ID"/"ID") nodes, ("ID"/"ID") edges\n", cn, n, pdest, nz)) ; PRINT2 (("compressed graph:\n")) ; for (cnt = 0, j = 0 ; j < cn ; j++) { PRINT2 ((""ID": ", j)) ; for (p = Cp [j] ; p < Cp [j+1] ; p++) { i = Ci [p] ; PRINT3 ((""ID" ", i)) ; ASSERT (i >= 0 && i < cn && i != j) ; } PRINT2 (("weight: "ID"\n", Cnw [j])) ; ASSERT (Cnw [j] > 0) ; cnt += Cnw [j] ; } ASSERT (cnt == total_weight) ; for (j = 0 ; j < n ; j++) PRINT2 (("Cmap ["ID"] = "ID"\n", j, Cmap[j])); ASSERT (k == cn) ; #endif /* ------------------------------------------------------------------ */ /* find the separator of the compressed graph */ /* ------------------------------------------------------------------ */ /* FUTURE WORK: could call CHACO, SCOTCH, ... here too */ csep = CHOLMOD(metis_bisector) (C, Cnw, Cew, Part, Common) ; if (csep < 0) { /* failed */ return (-1) ; } PRINT2 (("Part: ")) ; DEBUG (for (j = 0 ; j < cn ; j++) PRINT2 ((""ID" ", Part [j]))) ; PRINT2 (("\n")) ; /* Cp and Ci no longer needed */ /* ------------------------------------------------------------------ */ /* find the separator of the uncompressed graph */ /* ------------------------------------------------------------------ */ /* expand the separator to live nodes in the uncompressed graph */ for (j = n-1 ; j >= 0 ; j--) { /* do this in reverse order so that Cnw can be expanded in place */ k = Cmap [j] ; ASSERT (k >= EMPTY && k < n) ; if (k > EMPTY) { /* node k in compressed graph and is node j in full graph */ ASSERT (k <= j) ; ASSERT (Hash [j] >= EMPTY) ; Part [j] = Part [k] ; Cnw [j] = Cnw [k] ; } else { /* node j is a dead node */ Cnw [j] = 0 ; DEBUG (Part [j] = EMPTY) ; ASSERT (Hash [j] < EMPTY) ; } } /* find the components for the dead nodes */ for (i = 0 ; i < n ; i++) { if (Hash [i] < EMPTY) { /* node i has been absorbed into node j */ j = FLIP (Hash [i]) ; ASSERT (Part [i] == EMPTY && j >= 0 && j < n && Cnw [i] == 0) ; Part [i] = Part [j] ; } ASSERT (Part [i] >= 0 && Part [i] <= 2) ; } #ifndef NDEBUG PRINT2 (("Part: ")) ; for (cnt = 0, j = 0 ; j < n ; j++) { ASSERT (Part [j] != EMPTY) ; PRINT2 ((""ID" ", Part [j])) ; if (Part [j] == 2) cnt += Cnw [j] ; } PRINT2 (("\n")) ; PRINT2 (("csep "ID" "ID"\n", cnt, csep)) ; ASSERT (cnt == csep) ; for (cnt = 0, j = 0 ; j < n ; j++) cnt += Cnw [j] ; ASSERT (cnt == total_weight) ; #endif } /* ---------------------------------------------------------------------- */ /* return the separator (or -1 if error) */ /* ---------------------------------------------------------------------- */ PRINT2 (("Partition done, n "ID" csep "ID"\n", n, csep)) ; return (csep) ; } /* ========================================================================== */ /* === clear_flag =========================================================== */ /* ========================================================================== */ /* A node j has been removed from the graph if Flag [j] < EMPTY. * If Flag [j] >= EMPTY && Flag [j] < mark, then node j is alive but unmarked. * Flag [j] == mark means that node j is alive and marked. Incrementing mark * means that all nodes are either (still) dead, or live but unmarked. * * If Map is NULL, then on output, Common->mark < Common->Flag [i] for all i * from 0 to Common->nrow. This is the same output condition as * cholmod_clear_flag, except that this routine maintains the Flag [i] < EMPTY * condition as well, if that condition was true on input. * * If Map is non-NULL, then on output, Common->mark < Common->Flag [i] for all * i in the set Map [0..cn-1]. * * workspace: Flag (nrow) */ static SuiteSparse_long clear_flag (Int *Map, Int cn, cholmod_common *Common) { Int nrow, i ; Int *Flag ; PRINT2 (("old mark %ld\n", Common->mark)) ; Common->mark++ ; PRINT2 (("new mark %ld\n", Common->mark)) ; if (Common->mark <= 0) { nrow = Common->nrow ; Flag = Common->Flag ; if (Map != NULL) { for (i = 0 ; i < cn ; i++) { /* if Flag [Map [i]] < EMPTY, leave it alone */ if (Flag [Map [i]] >= EMPTY) { Flag [Map [i]] = EMPTY ; } } /* now Flag [Map [i]] <= EMPTY for all i */ } else { for (i = 0 ; i < nrow ; i++) { /* if Flag [i] < EMPTY, leave it alone */ if (Flag [i] >= EMPTY) { Flag [i] = EMPTY ; } } /* now Flag [i] <= EMPTY for all i */ } Common->mark = 0 ; } return (Common->mark) ; } /* ========================================================================== */ /* === find_components ====================================================== */ /* ========================================================================== */ /* Find all connected components of the current subgraph C. The subgraph C * consists of the nodes of B that appear in the set Map [0..cn-1]. If Map * is NULL, then it is assumed to be the identity mapping * (Map [0..cn-1] = 0..cn-1). * * A node j does not appear in B if it has been ordered (Flag [j] < EMPTY, * which means that j has been ordered and is "deleted" from B). * * If the size of a component is large, it is placed on the component stack, * Cstack. Otherwise, its nodes are ordered and it is not placed on the Cstack. * * A component S is defined by a "representative node" (repnode for short) * called the snode, which is one of the nodes in the subgraph. Likewise, the * subgraph C is defined by its repnode, called cnode. * * If Part is not NULL on input, then Part [i] determines how the components * are placed on the stack. Components containing nodes i with Part [i] == 0 * are placed first, followed by components with Part [i] == 1. * * The first node placed in each of the two parts is flipped when placed in * the Cstack. This allows the components of the two parts to be found simply * by traversing the Cstack. * * workspace: Flag (nrow) */ static void find_components ( /* inputs, not modified on output */ cholmod_sparse *B, Int Map [ ], /* size n, only Map [0..cn-1] used */ Int cn, /* # of nodes in C */ Int cnode, /* root node of component C, or EMPTY if C is the * entire graph B */ Int Part [ ], /* size cn, optional */ /* input/output */ Int Bnz [ ], /* size n. Bnz [j] = # nonzeros in column j of B. * Reduce since B is pruned of dead nodes. */ Int CParent [ ], /* CParent [i] = j if component with repnode j is * the parent of the component with repnode i. * CParent [i] = EMPTY if the component with * repnode i is a root of the separator tree. * CParent [i] is -2 if i is not a repnode. */ Int Cstack [ ], /* component stack for nested dissection */ Int *top, /* Cstack [0..top] contains root nodes of the * the components currently in the stack */ /* workspace, undefined on input and output: */ Int Queue [ ], /* size n, for breadth-first search */ cholmod_common *Common ) { Int n, mark, cj, j, sj, sn, p, i, snode, pstart, pdest, pend, nd_components, part, first, save_mark ; Int *Bp, *Bi, *Flag ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ PRINT2 (("find components: cn %d\n", cn)) ; Flag = Common->Flag ; /* size n */ /* force initialization of Flag [Map [0..cn-1]] */ save_mark = Common->mark ; /* save the current mark */ Common->mark = EMPTY ; /* clear Flag; preserve Flag [Map [i]] if Flag [Map [i]] already < EMPTY */ /* this takes O(cn) time */ mark = clear_flag (Map, cn, Common) ; Bp = B->p ; Bi = B->i ; n = B->nrow ; ASSERT (cnode >= EMPTY && cnode < n) ; ASSERT (IMPLIES (cnode >= 0, Flag [cnode] < EMPTY)) ; /* get ordering parameters */ nd_components = Common->method [Common->current].nd_components ; /* ---------------------------------------------------------------------- */ /* find the connected components of C via a breadth-first search */ /* ---------------------------------------------------------------------- */ part = (Part == NULL) ? 0 : 1 ; /* examine each part (part 1 and then part 0) */ for (part = (Part == NULL) ? 0 : 1 ; part >= 0 ; part--) { /* first is TRUE for the first connected component in each part */ first = TRUE ; /* find all connected components in the current part */ for (cj = 0 ; cj < cn ; cj++) { /* get node snode, which is node cj of C. It might already be in * the separator of C (and thus ordered, with Flag [snode] < EMPTY) */ snode = (Map == NULL) ? (cj) : (Map [cj]) ; ASSERT (snode >= 0 && snode < n) ; if (Flag [snode] >= EMPTY && Flag [snode] < mark && ((Part == NULL) || Part [cj] == part)) { /* ---------------------------------------------------------- */ /* find new connected component S */ /* ---------------------------------------------------------- */ /* node snode is the repnode of a connected component S, the * parent of which is cnode, the repnode of C. If cnode is * EMPTY then C is the original graph B. */ PRINT2 (("----------:::snode "ID" cnode "ID"\n", snode, cnode)); ASSERT (CParent [snode] == -2) ; if (first || nd_components) { /* If this is the first node in this part, then it becomes * the repnode of all components in this part, and all * components in this part form a single node in the * separator tree. If nd_components is TRUE, then all * connected components form their own node in the * separator tree. */ CParent [snode] = cnode ; } /* place j in the queue and mark it */ Queue [0] = snode ; Flag [snode] = mark ; sn = 1 ; /* breadth-first traversal, starting at node j */ for (sj = 0 ; sj < sn ; sj++) { /* get node j from head of Queue and traverse its edges */ j = Queue [sj] ; PRINT2 ((" j: "ID"\n", j)) ; ASSERT (j >= 0 && j < n) ; ASSERT (Flag [j] == mark) ; pstart = Bp [j] ; pdest = pstart ; pend = pstart + Bnz [j] ; for (p = pstart ; p < pend ; p++) { i = Bi [p] ; if (i != j && Flag [i] >= EMPTY) { /* node is still in the graph */ Bi [pdest++] = i ; if (Flag [i] < mark) { /* node i is in this component S, and unflagged * (first time node i has been seen in this BFS) * place node i in the queue and mark it */ Queue [sn++] = i ; Flag [i] = mark ; } } } /* edges to dead nodes have been removed */ Bnz [j] = pdest - pstart ; } /* ---------------------------------------------------------- */ /* order S if it is small; place it on Cstack otherwise */ /* ---------------------------------------------------------- */ PRINT2 (("sn "ID"\n", sn)) ; /* place the new component on the Cstack. Flip the node if * is the first connected component of the current part, * or if all components are treated as their own node in * the separator tree. */ Cstack [++(*top)] = (first || nd_components) ? FLIP (snode) : snode ; first = FALSE ; } } } /* restore the flag (normally taking O(1) time except for Int overflow) */ Common->mark = save_mark++ ; clear_flag (NULL, 0, Common) ; DEBUG (for (i = 0 ; i < n ; i++) ASSERT (Flag [i] < Common->mark)) ; } /* ========================================================================== */ /* === cholmod_bisect ======================================================= */ /* ========================================================================== */ /* Finds a node bisector of A, A*A', A(:,f)*A(:,f)'. * * workspace: Flag (nrow), * Iwork (nrow if symmetric, max (nrow,ncol) if unsymmetric). * Allocates a temporary matrix B=A*A' or B=A, * and O(nnz(A)) temporary memory space. */ SuiteSparse_long CHOLMOD(bisect) /* returns # of nodes in separator */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to bisect */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int compress, /* if TRUE, compress the graph first */ /* ---- output --- */ Int *Partition, /* size A->nrow. Node i is in the left graph if * Partition [i] = 0, the right graph if 1, and in the * separator if 2. */ /* --------------- */ cholmod_common *Common ) { Int *Bp, *Bi, *Hash, *Cmap, *Bnw, *Bew, *Iwork ; cholmod_sparse *B ; unsigned Int hash ; Int j, n, bnz, sepsize, p, pend ; size_t csize, s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_NULL (Partition, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* quick return */ /* ---------------------------------------------------------------------- */ n = A->nrow ; if (n == 0) { return (0) ; } /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = n + MAX (n, A->ncol) */ s = CHOLMOD(add_size_t) (A->nrow, MAX (A->nrow, A->ncol), &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (EMPTY) ; } CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; Iwork = Common->Iwork ; Hash = Iwork ; /* size n, (i/l/l) */ Cmap = Iwork + n ; /* size n, (i/i/l) */ /* ---------------------------------------------------------------------- */ /* convert the matrix to adjacency list form */ /* ---------------------------------------------------------------------- */ /* The input graph to must be symmetric, with no diagonal entries * present. The columns need not be sorted. */ /* B = A, A*A', or A(:,f)*A(:,f)', upper and lower parts present */ if (A->stype) { /* Add the upper/lower part to a symmetric lower/upper matrix by * converting to unsymmetric mode */ /* workspace: Iwork (nrow) */ B = CHOLMOD(copy) (A, 0, -1, Common) ; } else { /* B = A*A' or A(:,f)*A(:,f)', no diagonal */ /* workspace: Flag (nrow), Iwork (max (nrow,ncol)) */ B = CHOLMOD(aat) (A, fset, fsize, -1, Common) ; } if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } Bp = B->p ; Bi = B->i ; bnz = Bp [n] ; ASSERT ((Int) (B->nrow) == n && (Int) (B->ncol) == n) ; /* B does not include the diagonal, and both upper and lower parts. * Common->anz includes the diagonal, and just the lower part of B */ Common->anz = bnz / 2 + ((double) n) ; /* Bew should be at least size n for the hash function to work well */ /* this cannot cause overflow, because the matrix is already created */ csize = MAX (((size_t) n) + 1, (size_t) bnz) ; /* create the graph using Flag as workspace for node weights [ */ Bnw = Common->Flag ; /* size n workspace */ /* compute hash for each node if compression requested */ if (compress) { for (j = 0 ; j < n ; j++) { hash = j ; pend = Bp [j+1] ; for (p = Bp [j] ; p < pend ; p++) { hash += Bi [p] ; ASSERT (Bi [p] != j) ; } /* finalize the hash key for node j */ hash %= csize ; Hash [j] = (Int) hash ; ASSERT (Hash [j] >= 0 && Hash [j] < csize) ; } } /* allocate edge weights */ Bew = CHOLMOD(malloc) (csize, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (csize, sizeof (Int), Bew, Common) ; return (EMPTY) ; } /* graph has unit node and edge weights */ for (j = 0 ; j < n ; j++) { Bnw [j] = 1 ; } for (s = 0 ; s < csize ; s++) { Bew [s] = 1 ; } /* ---------------------------------------------------------------------- */ /* compress and partition the graph */ /* ---------------------------------------------------------------------- */ sepsize = partition ( #ifndef NDEBUG csize, #endif compress, Hash, B, Bnw, Bew, Cmap, Partition, Common) ; /* contents of Bp, Bi, Bnw, and Bew no longer needed ] */ /* If partition fails, free the workspace below and return sepsize < 0 */ /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ B->ncol = n ; /* restore size for memory usage statistics */ CHOLMOD(free_sparse) (&B, Common) ; Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; CHOLMOD(free) (csize, sizeof (Int), Bew, Common) ; return (sepsize) ; } /* ========================================================================== */ /* === cholmod_nested_dissection ============================================ */ /* ========================================================================== */ /* This method uses a node bisector, applied recursively (but using a * non-recursive algorithm). Once the graph is partitioned, it calls a * constrained min degree code (CAMD or CSYMAMD for A+A', and CCOLAMD for A*A') * to order all the nodes in the graph - but obeying the constraints determined * by the separators. This routine is similar to METIS_NodeND, except for how * it treats the leaf nodes. METIS_NodeND orders the leaves of the separator * tree with MMD, ignoring the rest of the matrix when ordering a single leaf. * This routine orders the whole matrix with CSYMAMD or CCOLAMD, all at once, * when the graph partitioning is done. * * This function also returns a postorderd separator tree (CParent), and a * mapping of nodes in the graph to nodes in the separator tree (Cmember). * * workspace: Flag (nrow), Head (nrow+1), Iwork (4*nrow + (ncol if unsymmetric)) * Allocates a temporary matrix B=A*A' or B=A, * and O(nnz(A)) temporary memory space. * Allocates an additional 3*n*sizeof(Int) temporary workspace */ SuiteSparse_long CHOLMOD(nested_dissection) /* returns # of components, or -1 if error */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ /* ---- output --- */ Int *Perm, /* size A->nrow, output permutation */ Int *CParent, /* size A->nrow. On output, CParent [c] is the parent * of component c, or EMPTY if c is a root, and where * c is in the range 0 to # of components minus 1 */ Int *Cmember, /* size A->nrow. Cmember [j] = c if node j of A is * in component c */ /* --------------- */ cholmod_common *Common ) { double prune_dense, nd_oksep ; Int *Bp, *Bi, *Bnz, *Cstack, *Imap, *Map, *Flag, *Head, *Next, *Bnw, *Iwork, *Ipost, *NewParent, *Hash, *Cmap, *Cp, *Ci, *Cew, *Cnw, *Part, *Post, *Work3n ; unsigned Int hash ; Int n, bnz, top, i, j, k, cnode, cdense, p, cj, cn, ci, cnz, mark, c, uncol, sepsize, parent, ncomponents, threshold, ndense, pstart, pdest, pend, nd_compress, nd_camd, csize, jnext, nd_small, total_weight, nchild, child = EMPTY ; cholmod_sparse *B, *C ; size_t s ; int ok = TRUE ; DEBUG (Int cnt) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_NULL (Perm, EMPTY) ; RETURN_IF_NULL (CParent, EMPTY) ; RETURN_IF_NULL (Cmember, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* quick return */ /* ---------------------------------------------------------------------- */ n = A->nrow ; if (n == 0) { return (1) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* get ordering parameters */ prune_dense = Common->method [Common->current].prune_dense ; nd_compress = Common->method [Common->current].nd_compress ; nd_oksep = Common->method [Common->current].nd_oksep ; nd_oksep = MAX (0, nd_oksep) ; nd_oksep = MIN (1, nd_oksep) ; nd_camd = Common->method [Common->current].nd_camd ; nd_small = Common->method [Common->current].nd_small ; nd_small = MAX (4, nd_small) ; PRINT0 (("nd_components %d nd_small %d nd_oksep %g\n", Common->method [Common->current].nd_components, nd_small, nd_oksep)) ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 4*n + uncol */ uncol = (A->stype == 0) ? A->ncol : 0 ; s = CHOLMOD(mult_size_t) (n, 4, &ok) ; s = CHOLMOD(add_size_t) (s, uncol, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (EMPTY) ; } CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size n */ Head = Common->Head ; /* size n+1, all equal to -1 */ Iwork = Common->Iwork ; Imap = Iwork ; /* size n, same as Queue in find_components */ Map = Iwork + n ; /* size n */ Bnz = Iwork + 2*((size_t) n) ; /* size n */ Hash = Iwork + 3*((size_t) n) ; /* size n */ Work3n = CHOLMOD(malloc) (n, 3*sizeof (Int), Common) ; Part = Work3n ; /* size n */ Bnw = Part + n ; /* size n */ Cnw = Bnw + n ; /* size n */ Cstack = Perm ; /* size n, use Perm as workspace for Cstack [ */ Cmap = Cmember ; /* size n, use Cmember as workspace [ */ if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } /* ---------------------------------------------------------------------- */ /* convert B to symmetric form with both upper/lower parts present */ /* ---------------------------------------------------------------------- */ /* B = A+A', A*A', or A(:,f)*A(:,f)', upper and lower parts present */ if (A->stype) { /* Add the upper/lower part to a symmetric lower/upper matrix by * converting to unsymmetric mode */ /* workspace: Iwork (nrow) */ B = CHOLMOD(copy) (A, 0, -1, Common) ; } else { /* B = A*A' or A(:,f)*A(:,f)', no diagonal */ /* workspace: Flag (nrow), Iwork (max (nrow,ncol)) */ B = CHOLMOD(aat) (A, fset, fsize, -1, Common) ; } if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (3*n, sizeof (Int), Work3n, Common) ; return (EMPTY) ; } Bp = B->p ; Bi = B->i ; bnz = CHOLMOD(nnz) (B, Common) ; ASSERT ((Int) (B->nrow) == n && (Int) (B->ncol) == n) ; csize = MAX (n, bnz) ; ASSERT (CHOLMOD(dump_sparse) (B, "B for nd:", Common) >= 0) ; /* ---------------------------------------------------------------------- */ /* initializations */ /* ---------------------------------------------------------------------- */ /* all nodes start out unmarked and unordered (Type 4, see below) */ Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; ASSERT (Flag == Common->Flag) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; for (j = 0 ; j < n ; j++) { CParent [j] = -2 ; } /* prune dense nodes from B */ if (IS_NAN (prune_dense) || prune_dense < 0) { /* only remove completely dense nodes */ threshold = n-2 ; } else { /* remove nodes with degree more than threshold */ threshold = (Int) (MAX (16, prune_dense * sqrt ((double) (n)))) ; threshold = MIN (n, threshold) ; } ndense = 0 ; cnode = EMPTY ; cdense = EMPTY ; for (j = 0 ; j < n ; j++) { Bnz [j] = Bp [j+1] - Bp [j] ; if (Bnz [j] > threshold) { /* node j is dense, prune it from B */ PRINT2 (("j is dense %d\n", j)) ; ndense++ ; if (cnode == EMPTY) { /* first dense node found becomes root of this component, * which contains all of the dense nodes found here */ cdense = j ; cnode = j ; CParent [cnode] = EMPTY ; } Flag [j] = FLIP (cnode) ; } } B->packed = FALSE ; ASSERT (B->nz == NULL) ; if (ndense == n) { /* all nodes removed: Perm is identity, all nodes in component zero, * and the separator tree has just one node. */ PRINT2 (("all nodes are dense\n")) ; for (k = 0 ; k < n ; k++) { Perm [k] = k ; Cmember [k] = 0 ; } CParent [0] = EMPTY ; CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (3*n, sizeof (Int), Work3n, Common) ; Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; return (1) ; } /* Cp and Ci are workspace to construct the subgraphs to partition */ C = CHOLMOD(allocate_sparse) (n, n, csize, FALSE, TRUE, 0, CHOLMOD_PATTERN, Common) ; Cew = CHOLMOD(malloc) (csize, sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&C, Common) ; CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (csize, sizeof (Int), Cew, Common) ; CHOLMOD(free) (3*n, sizeof (Int), Work3n, Common) ; Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; PRINT2 (("out of memory for C, etc\n")) ; return (EMPTY) ; } Cp = C->p ; Ci = C->i ; /* create initial unit node and edge weights */ for (j = 0 ; j < n ; j++) { Bnw [j] = 1 ; } for (p = 0 ; p < csize ; p++) { Cew [p] = 1 ; } /* push the initial connnected components of B onto the Cstack */ top = EMPTY ; /* Cstack is empty */ /* workspace: Flag (nrow), Iwork (nrow); use Imap as workspace for Queue [*/ find_components (B, NULL, n, cnode, NULL, Bnz, CParent, Cstack, &top, Imap, Common) ; /* done using Imap as workspace for Queue ] */ /* Nodes can now be of Type 0, 1, 2, or 4 (see definition below) */ /* ---------------------------------------------------------------------- */ /* while Cstack is not empty, do: */ /* ---------------------------------------------------------------------- */ while (top >= 0) { /* clear the Flag array, but do not modify negative entries in Flag */ mark = clear_flag (NULL, 0, Common) ; DEBUG (for (i = 0 ; i < n ; i++) Imap [i] = EMPTY) ; /* ------------------------------------------------------------------ */ /* get node(s) from the top of the Cstack */ /* ------------------------------------------------------------------ */ /* i is the repnode of its (unordered) connected component. Get * all repnodes for all connected components of a single part. If * each connected component is to be ordered separately (nd_components * is TRUE), then this while loop iterates just once. */ cnode = EMPTY ; cn = 0 ; while (cnode == EMPTY) { i = Cstack [top--] ; if (i < 0) { /* this is the last node in this component */ i = FLIP (i) ; cnode = i ; } ASSERT (i >= 0 && i < n && Flag [i] >= EMPTY) ; /* place i in the queue and mark it */ Map [cn] = i ; Flag [i] = mark ; Imap [i] = cn ; cn++ ; } ASSERT (cnode != EMPTY) ; /* During ordering, there are five kinds of nodes in the graph of B, * based on Flag [j] and CParent [j] for nodes j = 0 to n-1: * * Type 0: If cnode is a repnode of an unordered component, then * CParent [cnode] is in the range EMPTY to n-1 and * Flag [cnode] >= EMPTY. This is a "live" node. * * Type 1: If cnode is a repnode of an ordered separator component, * then Flag [cnode] < EMPTY and FLAG [cnode] = FLIP (cnode). * CParent [cnode] is in the range EMPTY to n-1. cnode is a root of * the separator tree if CParent [cnode] == EMPTY. This node is dead. * * Type 2: If node j isn't a repnode, has not been absorbed via * graph compression into another node, but is in an ordered separator * component, then cnode = FLIP (Flag [j]) gives the repnode of the * component that contains j and CParent [j] is -2. This node is dead. * Note that Flag [j] < EMPTY. * * Type 3: If node i has been absorbed via graph compression into some * other node j = FLIP (Flag [i]) where j is not a repnode. * CParent [j] is -2. Node i may or may not be in an ordered * component. This node is dead. Note that Flag [j] < EMPTY. * * Type 4: If node j is "live" (not in an ordered component, and not * absorbed into any other node), then Flag [j] >= EMPTY. * * Only "live" nodes (of type 0 or 4) are placed in a subgraph to be * partitioned. Node j is alive if Flag [j] >= EMPTY, and dead if * Flag [j] < EMPTY. */ /* ------------------------------------------------------------------ */ /* create the subgraph for this connected component C */ /* ------------------------------------------------------------------ */ /* Do a breadth-first search of the graph starting at cnode. * use Map [0..cn-1] for nodes in the component C [ * use Cnw and Cew for node and edge weights of the resulting subgraph [ * use Cp and Ci for the resulting subgraph [ * use Imap [i] for all nodes i in B that are in the component C [ */ cnz = 0 ; total_weight = 0 ; for (cj = 0 ; cj < cn ; cj++) { /* get node j from the head of the queue; it is node cj of C */ j = Map [cj] ; ASSERT (Flag [j] == mark) ; Cp [cj] = cnz ; Cnw [cj] = Bnw [j] ; ASSERT (Cnw [cj] >= 0) ; total_weight += Cnw [cj] ; pstart = Bp [j] ; pdest = pstart ; pend = pstart + Bnz [j] ; hash = cj ; for (p = pstart ; p < pend ; p++) { i = Bi [p] ; /* prune diagonal entries and dead edges from B */ if (i != j && Flag [i] >= EMPTY) { /* live node i is in the current component */ Bi [pdest++] = i ; if (Flag [i] != mark) { /* First time node i has been seen, it is a new node * of C. place node i in the queue and mark it */ Map [cn] = i ; Flag [i] = mark ; Imap [i] = cn ; cn++ ; } /* place the edge (cj,ci) in the adjacency list of cj */ ci = Imap [i] ; ASSERT (ci >= 0 && ci < cn && ci != cj && cnz < csize) ; Ci [cnz++] = ci ; hash += ci ; } } /* edges to dead nodes have been removed */ Bnz [j] = pdest - pstart ; /* finalize the hash key for column j */ hash %= csize ; Hash [cj] = (Int) hash ; ASSERT (Hash [cj] >= 0 && Hash [cj] < csize) ; } Cp [cn] = cnz ; C->nrow = cn ; C->ncol = cn ; /* affects mem stats unless restored when C free'd */ /* contents of Imap no longer needed ] */ #ifndef NDEBUG for (cj = 0 ; cj < cn ; cj++) { j = Map [cj] ; PRINT2 (("----------------------------C column cj: "ID" j: "ID"\n", cj, j)) ; ASSERT (j >= 0 && j < n) ; ASSERT (Flag [j] >= EMPTY) ; for (p = Cp [cj] ; p < Cp [cj+1] ; p++) { ci = Ci [p] ; i = Map [ci] ; PRINT3 (("ci: "ID" i: "ID"\n", ci, i)) ; ASSERT (ci != cj && ci >= 0 && ci < cn) ; ASSERT (i != j && i >= 0 && i < n) ; ASSERT (Flag [i] >= EMPTY) ; } } #endif PRINT0 (("consider cn %d nd_small %d ", cn, nd_small)) ; if (cn < nd_small) /* could be 'total_weight < nd_small' instead */ { /* place all nodes in the separator */ PRINT0 ((" too small\n")) ; sepsize = total_weight ; } else { /* Cp and Ci now contain the component, with cn nodes and cnz * nonzeros. The mapping of a node cj into node j the main graph * B is given by Map [cj] = j */ PRINT0 ((" cut\n")) ; /* -------------------------------------------------------------- */ /* compress and partition the graph C */ /* -------------------------------------------------------------- */ /* The edge weights Cew [0..csize-1] are all 1's on input to and * output from the partition routine. */ sepsize = partition ( #ifndef NDEBUG csize, #endif nd_compress, Hash, C, Cnw, Cew, Cmap, Part, Common) ; /* contents of Cp and Ci no longer needed ] */ if (sepsize < 0) { /* failed */ C->ncol = n ; /* restore size for memory usage statistics */ CHOLMOD(free_sparse) (&C, Common) ; CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (csize, sizeof (Int), Cew, Common) ; CHOLMOD(free) (3*n, sizeof (Int), Work3n, Common) ; Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; return (EMPTY) ; } /* -------------------------------------------------------------- */ /* compress B based on how C was compressed */ /* -------------------------------------------------------------- */ for (ci = 0 ; ci < cn ; ci++) { if (Hash [ci] < EMPTY) { /* ci is dead in C, having been absorbed into cj */ cj = FLIP (Hash [ci]) ; PRINT2 (("In C, "ID" absorbed into "ID" (wgt now "ID")\n", ci, cj, Cnw [cj])) ; /* i is dead in B, having been absorbed into j */ i = Map [ci] ; j = Map [cj] ; PRINT2 (("In B, "ID" (wgt "ID") => "ID" (wgt "ID")\n", i, Bnw [i], j, Bnw [j], Cnw [cj])) ; /* more than one node may be absorbed into j. This is * accounted for in Cnw [cj]. Assign it here rather * than += Bnw [i] */ Bnw [i] = 0 ; Bnw [j] = Cnw [cj] ; Flag [i] = FLIP (j) ; } } DEBUG (for (cnt = 0, j = 0 ; j < n ; j++) cnt += Bnw [j]) ; ASSERT (cnt == n) ; } /* contents of Cnw [0..cn-1] no longer needed ] */ /* ------------------------------------------------------------------ */ /* order the separator, and stack the components when C is split */ /* ------------------------------------------------------------------ */ /* one more component has been found: either the separator of C, * or all of C */ ASSERT (sepsize >= 0 && sepsize <= total_weight) ; PRINT0 (("sepsize %d tot %d : %8.4f ", sepsize, total_weight, ((double) sepsize) / ((double) total_weight))) ; if (sepsize == total_weight || sepsize == 0 || sepsize > nd_oksep * total_weight) { /* Order the nodes in the component. The separator is too large, * or empty. Note that the partition routine cannot return a * sepsize of zero, but it can return a separator consisting of the * whole graph. The "sepsize == 0" test is kept, above, in case the * partition routine changes. In either case, this component * remains unsplit, and becomes a leaf of the separator tree. */ PRINT2 (("cnode %d sepsize zero or all of graph: "ID"\n", cnode, sepsize)) ; for (cj = 0 ; cj < cn ; cj++) { j = Map [cj] ; Flag [j] = FLIP (cnode) ; PRINT2 ((" node cj: "ID" j: "ID" ordered\n", cj, j)) ; } ASSERT (Flag [cnode] == FLIP (cnode)) ; ASSERT (cnode != EMPTY && Flag [cnode] < EMPTY) ; PRINT0 (("discarded\n")) ; } else { /* Order the nodes in the separator of C and find a new repnode * cnode that is in the separator of C. This requires the separator * to be non-empty. */ PRINT0 (("sepsize not tiny: "ID"\n", sepsize)) ; parent = CParent [cnode] ; ASSERT (parent >= EMPTY && parent < n) ; CParent [cnode] = -2 ; cnode = EMPTY ; for (cj = 0 ; cj < cn ; cj++) { j = Map [cj] ; if (Part [cj] == 2) { /* All nodes in the separator become part of a component * whose repnode is cnode */ PRINT2 (("node cj: "ID" j: "ID" ordered\n", cj, j)) ; if (cnode == EMPTY) { PRINT2(("------------new cnode: cj "ID" j "ID"\n", cj, j)) ; cnode = j ; } Flag [j] = FLIP (cnode) ; } else { PRINT2 ((" node cj: "ID" j: "ID" not ordered\n", cj, j)) ; } } ASSERT (cnode != EMPTY && Flag [cnode] < EMPTY) ; ASSERT (CParent [cnode] == -2) ; CParent [cnode] = parent ; /* find the connected components when C is split, and push * them on the Cstack. Use Imap as workspace for Queue. [ */ /* workspace: Flag (nrow) */ find_components (B, Map, cn, cnode, Part, Bnz, CParent, Cstack, &top, Imap, Common) ; /* done using Imap as workspace for Queue ] */ } /* contents of Map [0..cn-1] no longer needed ] */ } /* done using Cmember as workspace for Cmap ] */ /* done using Perm as workspace for Cstack ] */ /* ---------------------------------------------------------------------- */ /* place nodes removed via compression into their proper component */ /* ---------------------------------------------------------------------- */ /* At this point, all nodes are of Type 1, 2, or 3, as defined above. */ for (i = 0 ; i < n ; i++) { /* find the repnode cnode that contains node i */ j = FLIP (Flag [i]) ; PRINT2 (("\nfind component for "ID", in: "ID"\n", i, j)) ; ASSERT (j >= 0 && j < n) ; DEBUG (cnt = 0) ; while (CParent [j] == -2) { j = FLIP (Flag [j]) ; PRINT2 ((" walk up to "ID" ", j)) ; ASSERT (j >= 0 && j < n) ; PRINT2 ((" CParent "ID"\n", CParent [j])) ; ASSERT (cnt < n) ; DEBUG (cnt++) ; } cnode = j ; ASSERT (cnode >= 0 && cnode < n) ; ASSERT (CParent [cnode] >= EMPTY && CParent [cnode] < n) ; PRINT2 (("i "ID" is in component with cnode "ID"\n", i, cnode)) ; ASSERT (Flag [cnode] == FLIP (cnode)) ; /* Mark all nodes along the path from i to cnode as being in the * component whos repnode is cnode. Perform path compression. */ j = FLIP (Flag [i]) ; Flag [i] = FLIP (cnode) ; DEBUG (cnt = 0) ; while (CParent [j] == -2) { ASSERT (j >= 0 && j < n) ; jnext = FLIP (Flag [j]) ; PRINT2 ((" "ID" walk "ID" set cnode to "ID"\n", i, j, cnode)) ; ASSERT (cnt < n) ; DEBUG (cnt++) ; Flag [j] = FLIP (cnode) ; j = jnext ; } } /* At this point, all nodes fall into Types 1 or 2, as defined above. */ #ifndef NDEBUG for (j = 0 ; j < n ; j++) { PRINT2 (("j %d CParent %d ", j, CParent [j])) ; if (CParent [j] >= EMPTY && CParent [j] < n) { /* case 1: j is a repnode of a component */ cnode = j ; PRINT2 ((" a repnode\n")) ; } else { /* case 2: j is not a repnode of a component */ cnode = FLIP (Flag [j]) ; PRINT2 ((" repnode is %d\n", cnode)) ; ASSERT (cnode >= 0 && cnode < n) ; ASSERT (CParent [cnode] >= EMPTY && CParent [cnode] < n) ; } ASSERT (Flag [cnode] == FLIP (cnode)) ; /* case 3 no longer holds */ } #endif /* ---------------------------------------------------------------------- */ /* free workspace */ /* ---------------------------------------------------------------------- */ C->ncol = n ; /* restore size for memory usage statistics */ CHOLMOD(free_sparse) (&C, Common) ; CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (csize, sizeof (Int), Cew, Common) ; CHOLMOD(free) (3*n, sizeof (Int), Work3n, Common) ; /* ---------------------------------------------------------------------- */ /* handle dense nodes */ /* ---------------------------------------------------------------------- */ /* The separator tree has nodes with either no children or two or more * children - with one exception. There may exist a single root node with * exactly one child, which holds the dense rows/columns of the matrix. * Delete this node if it exists. */ if (ndense > 0) { ASSERT (CParent [cdense] == EMPTY) ; /* cdense has no parent */ /* find the children of cdense */ nchild = 0 ; for (j = 0 ; j < n ; j++) { if (CParent [j] == cdense) { nchild++ ; child = j ; } } if (nchild == 1) { /* the cdense node has just one child; merge the two nodes */ PRINT1 (("root has one child\n")) ; CParent [cdense] = -2 ; /* cdense is deleted */ CParent [child] = EMPTY ; /* child becomes a root */ for (j = 0 ; j < n ; j++) { if (Flag [j] == FLIP (cdense)) { /* j is a dense node */ PRINT1 (("dense %d\n", j)) ; Flag [j] = FLIP (child) ; } } } } /* ---------------------------------------------------------------------- */ /* postorder the components */ /* ---------------------------------------------------------------------- */ DEBUG (for (cnt = 0, j = 0 ; j < n ; j++) if (CParent [j] != -2) cnt++) ; /* use Cmember as workspace for Post [ */ Post = Cmember ; /* cholmod_postorder uses Head and Iwork [0..2n]. It does not use Flag, * which here holds the mapping of nodes to repnodes. It ignores all nodes * for which CParent [j] < -1, so it operates just on the repnodes. */ /* workspace: Head (n), Iwork (2*n) */ ncomponents = CHOLMOD(postorder) (CParent, n, NULL, Post, Common) ; ASSERT (cnt == ncomponents) ; /* use Iwork [0..n-1] as workspace for Ipost ( */ Ipost = Iwork ; DEBUG (for (j = 0 ; j < n ; j++) Ipost [j] = EMPTY) ; /* compute inverse postorder */ for (c = 0 ; c < ncomponents ; c++) { cnode = Post [c] ; ASSERT (cnode >= 0 && cnode < n) ; Ipost [cnode] = c ; ASSERT (Head [c] == EMPTY) ; } /* adjust the parent array */ /* Iwork [n..2n-1] used for NewParent [ */ NewParent = Iwork + n ; for (c = 0 ; c < ncomponents ; c++) { parent = CParent [Post [c]] ; NewParent [c] = (parent == EMPTY) ? EMPTY : (Ipost [parent]) ; } for (c = 0 ; c < ncomponents ; c++) { CParent [c] = NewParent [c] ; } ASSERT (CHOLMOD(dump_parent) (CParent, ncomponents, "CParent", Common)) ; /* Iwork [n..2n-1] no longer needed for NewParent ] */ /* Cmember no longer needed for Post ] */ #ifndef NDEBUG /* count the number of children of each node */ for (c = 0 ; c < ncomponents ; c++) { Cmember [c] = 0 ; } for (c = 0 ; c < ncomponents ; c++) { if (CParent [c] != EMPTY) Cmember [CParent [c]]++ ; } for (c = 0 ; c < ncomponents ; c++) { /* a node is either a leaf, or has 2 or more children */ ASSERT (Cmember [c] == 0 || Cmember [c] >= 2) ; } #endif /* ---------------------------------------------------------------------- */ /* place each node in its component */ /* ---------------------------------------------------------------------- */ for (j = 0 ; j < n ; j++) { /* node j is in the cth component, whose repnode is cnode */ cnode = FLIP (Flag [j]) ; PRINT2 (("j "ID" flag "ID" cnode "ID"\n", j, Flag [j], FLIP (Flag [j]))) ; ASSERT (cnode >= 0 && cnode < n) ; c = Ipost [cnode] ; ASSERT (c >= 0 && c < ncomponents) ; Cmember [j] = c ; } /* Flag no longer needed for the node-to-component mapping */ /* done using Iwork [0..n-1] as workspace for Ipost ) */ /* ---------------------------------------------------------------------- */ /* clear the Flag array */ /* ---------------------------------------------------------------------- */ Common->mark = EMPTY ; CHOLMOD_CLEAR_FLAG (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* find the permutation */ /* ---------------------------------------------------------------------- */ PRINT1 (("nd_camd: %d A->stype %d\n", nd_camd, A->stype)) ; if (nd_camd) { /* ------------------------------------------------------------------ */ /* apply camd, csymamd, or ccolamd using the Cmember constraints */ /* ------------------------------------------------------------------ */ if (A->stype != 0) { /* ordering A+A', so fset and fsize are ignored. * Add the upper/lower part to a symmetric lower/upper matrix by * converting to unsymmetric mode * workspace: Iwork (nrow) */ B = CHOLMOD(copy) (A, 0, -1, Common) ; if (Common->status < CHOLMOD_OK) { PRINT0 (("make symmetric failed\n")) ; return (EMPTY) ; } ASSERT ((Int) (B->nrow) == n && (Int) (B->ncol) == n) ; PRINT2 (("nested dissection (2)\n")) ; B->stype = -1 ; if (nd_camd == 2) { /* workspace: Head (nrow+1), Iwork (nrow) if symmetric-upper */ ok = CHOLMOD(csymamd) (B, Cmember, Perm, Common) ; } else { /* workspace: Head (nrow), Iwork (4*nrow) */ ok = CHOLMOD(camd) (B, NULL, 0, Cmember, Perm, Common) ; } CHOLMOD(free_sparse) (&B, Common) ; if (!ok) { /* failed */ PRINT0 (("camd/csymamd failed\n")) ; return (EMPTY) ; } } else { /* ordering A*A' or A(:,f)*A(:,f)' */ /* workspace: Iwork (nrow if no fset; MAX(nrow,ncol) if fset) */ if (!CHOLMOD(ccolamd) (A, fset, fsize, Cmember, Perm, Common)) { /* ccolamd failed */ PRINT2 (("ccolamd failed\n")) ; return (EMPTY) ; } } } else { /* ------------------------------------------------------------------ */ /* natural ordering of each component */ /* ------------------------------------------------------------------ */ /* use Iwork [0..n-1] for Next [ */ Next = Iwork ; /* ------------------------------------------------------------------ */ /* place the nodes in link lists, one list per component */ /* ------------------------------------------------------------------ */ /* do so in reverse order, to preserve original ordering */ for (j = n-1 ; j >= 0 ; j--) { /* node j is in the cth component */ c = Cmember [j] ; ASSERT (c >= 0 && c < ncomponents) ; /* place node j in link list for component c */ Next [j] = Head [c] ; Head [c] = j ; } /* ------------------------------------------------------------------ */ /* order each node in each component */ /* ------------------------------------------------------------------ */ k = 0 ; for (c = 0 ; c < ncomponents ; c++) { for (j = Head [c] ; j != EMPTY ; j = Next [j]) { Perm [k++] = j ; } Head [c] = EMPTY ; } ASSERT (k == n) ; /* done using Iwork [0..n-1] for Next ] */ } /* ---------------------------------------------------------------------- */ /* clear workspace and return number of components */ /* ---------------------------------------------------------------------- */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; return (ncomponents) ; } /* ========================================================================== */ /* === cholmod_collapse_septree ============================================= */ /* ========================================================================== */ /* cholmod_nested_dissection returns the separator tree that was used in the * constrained minimum degree algorithm. Parameter settings (nd_small, * nd_oksep, etc) that give a good fill-reducing ordering may give too fine of * a separator tree for other uses (parallelism, multi-level LPDASA, etc). This * function takes as input the separator tree computed by * cholmod_nested_dissection, and collapses selected subtrees into single * nodes. A subtree is collapsed if its root node (the separator) is large * compared to the total number of nodes in the subtree, or if the subtree is * small. Note that the separator tree may actually be a forest. * * nd_oksep and nd_small act just like the ordering parameters in Common. * Returns the new number of nodes in the separator tree. */ SuiteSparse_long CHOLMOD(collapse_septree) ( /* ---- input ---- */ size_t n, /* # of nodes in the graph */ size_t ncomponents, /* # of nodes in the separator tree (must be <= n) */ double nd_oksep, /* collapse if #sep >= nd_oksep * #nodes in subtree */ size_t nd_small, /* collapse if #nodes in subtree < nd_small */ /* ---- in/out --- */ Int *CParent, /* size ncomponents; from cholmod_nested_dissection */ Int *Cmember, /* size n; from cholmod_nested_dissection */ /* --------------- */ cholmod_common *Common ) { Int *First, *Count, *Csubtree, *W, *Map ; Int c, j, k, nc, sepsize, total_weight, parent, nc_new, first ; int collapse = FALSE, ok = TRUE ; size_t s ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (CParent, EMPTY) ; RETURN_IF_NULL (Cmember, EMPTY) ; if (n < ncomponents) { ERROR (CHOLMOD_INVALID, "invalid separator tree") ; return (EMPTY) ; } Common->status = CHOLMOD_OK ; nc = ncomponents ; if (n <= 1 || ncomponents <= 1) { /* no change; tree is one node already */ return (nc) ; } nd_oksep = MAX (0, nd_oksep) ; nd_oksep = MIN (1, nd_oksep) ; nd_small = MAX (4, nd_small) ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 3*ncomponents */ s = CHOLMOD(mult_size_t) (ncomponents, 3, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (EMPTY) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (EMPTY) ; } W = Common->Iwork ; Count = W ; W += ncomponents ; /* size ncomponents */ Csubtree = W ; W += ncomponents ; /* size ncomponents */ First = W ; W += ncomponents ; /* size ncomponents */ /* ---------------------------------------------------------------------- */ /* find the first descendant of each node of the separator tree */ /* ---------------------------------------------------------------------- */ for (c = 0 ; c < nc ; c++) { First [c] = EMPTY ; } for (k = 0 ; k < nc ; k++) { for (c = k ; c != EMPTY && First [c] == -1 ; c = CParent [c]) { ASSERT (c >= 0 && c < nc) ; First [c] = k ; } } /* ---------------------------------------------------------------------- */ /* find the number of nodes of the graph in each node of the tree */ /* ---------------------------------------------------------------------- */ for (c = 0 ; c < nc ; c++) { Count [c] = 0 ; } for (j = 0 ; j < (Int) n ; j++) { ASSERT (Cmember [j] >= 0 && Cmember [j] < nc) ; Count [Cmember [j]]++ ; } /* ---------------------------------------------------------------------- */ /* find the number of nodes in each subtree */ /* ---------------------------------------------------------------------- */ for (c = 0 ; c < nc ; c++) { /* each subtree includes its root */ Csubtree [c] = Count [c] ; PRINT1 ((ID" size "ID" parent "ID" first "ID"\n", c, Count [c], CParent [c], First [c])) ; } for (c = 0 ; c < nc ; c++) { /* add the subtree of the child, c, into the count of its parent */ parent = CParent [c] ; ASSERT (parent >= EMPTY && parent < nc) ; if (parent != EMPTY) { Csubtree [parent] += Csubtree [c] ; } } #ifndef NDEBUG /* the sum of the roots should be n */ j = 0 ; for (c = 0 ; c < nc ; c++) if (CParent [c] == EMPTY) j += Csubtree [c] ; ASSERT (j == (Int) n) ; #endif /* ---------------------------------------------------------------------- */ /* find subtrees to collapse */ /* ---------------------------------------------------------------------- */ /* consider all nodes in reverse post-order */ for (c = nc-1 ; c >= 0 ; c--) { /* consider the subtree rooted at node c */ sepsize = Count [c] ; total_weight = Csubtree [c] ; PRINT1 (("Node "ID" sepsize "ID" subtree "ID" ratio %g\n", c, sepsize, total_weight, ((double) sepsize)/((double) total_weight))) ; first = First [c] ; if (first < c && /* c must not be a leaf */ (sepsize > nd_oksep * total_weight || total_weight < (int) nd_small)) { /* this separator is too large, or the subtree is too small. * collapse the tree, by converting the entire subtree rooted at * c into a single node. The subtree consists of all nodes from * First[c] to the root c. Flag all nodes from First[c] to c-1 * as dead. */ collapse = TRUE ; for (k = first ; k < c ; k++) { CParent [k] = -2 ; PRINT1 ((" collapse node "ID"\n", k)) ; } /* continue at the next node, first-1 */ c = first ; } } PRINT1 (("collapse: %d\n", collapse)) ; /* ---------------------------------------------------------------------- */ /* compress the tree */ /* ---------------------------------------------------------------------- */ Map = Count ; /* Count no longer needed */ nc_new = nc ; if (collapse) { nc_new = 0 ; for (c = 0 ; c < nc ; c++) { Map [c] = nc_new ; if (CParent [c] >= EMPTY) { /* node c is alive, and becomes node Map[c] in the new tree. * Increment nc_new for the next node c. */ nc_new++ ; } } PRINT1 (("Collapse the tree from "ID" to "ID" nodes\n", nc, nc_new)) ; ASSERT (nc_new > 0) ; for (c = 0 ; c < nc ; c++) { parent = CParent [c] ; if (parent >= EMPTY) { /* node c is alive */ CParent [Map [c]] = (parent == EMPTY) ? EMPTY : Map [parent] ; } } for (j = 0 ; j < (Int) n ; j++) { PRINT1 (("j "ID" Cmember[j] "ID" Map[Cmember[j]] "ID"\n", j, Cmember [j], Map [Cmember [j]])) ; Cmember [j] = Map [Cmember [j]] ; } } /* ---------------------------------------------------------------------- */ /* return new size of separator tree */ /* ---------------------------------------------------------------------- */ return (nc_new) ; } #endif igraph/src/CHOLMOD/Partition/cholmod_ccolamd.c0000644000175100001440000001524613431000472020644 0ustar hornikusers/* ========================================================================== */ /* === Partition/cholmod_ccolamd ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Partition Module. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Partition Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the CCOLAMD ordering routine. Finds a permutation * p such that the Cholesky factorization of PAA'P' is sparser than AA'. * The column etree is found and postordered, and the ccolamd ordering is then * combined with its postordering. A must be unsymmetric. * * workspace: Iwork (MAX (nrow,ncol)) * Allocates a copy of its input matrix, which is * then used as CCOLAMD's workspace. * * Supports any xtype (pattern, real, complex, or zomplex). */ static int igraph_stfu2(); static int igraph_stfu1() { return igraph_stfu2(); } static int igraph_stfu2() { return igraph_stfu1(); } #ifndef NCAMD #include "cholmod_internal.h" #include "ccolamd.h" #include "cholmod_camd.h" #if (CCOLAMD_VERSION < CCOLAMD_VERSION_CODE (2,5)) #error "CCOLAMD v2.0 or later is required" #endif /* ========================================================================== */ /* === ccolamd_interface ==================================================== */ /* ========================================================================== */ /* Order with ccolamd */ static int ccolamd_interface ( cholmod_sparse *A, size_t alen, Int *Perm, Int *Cmember, Int *fset, Int fsize, cholmod_sparse *C, cholmod_common *Common ) { double knobs [CCOLAMD_KNOBS] ; Int *Cp = NULL ; Int ok, k, nrow, ncol, stats [CCOLAMD_STATS] ; nrow = A->nrow ; ncol = A->ncol ; /* ---------------------------------------------------------------------- */ /* copy (and transpose) the input matrix A into the ccolamd workspace */ /* ---------------------------------------------------------------------- */ /* C = A (:,f)', which also packs A if needed. */ /* workspace: Iwork (nrow if no fset; MAX (nrow,ncol) if fset non-NULL) */ ok = CHOLMOD(transpose_unsym) (A, 0, NULL, fset, fsize, C, Common) ; /* ---------------------------------------------------------------------- */ /* order the matrix (destroys the contents of C->i and C->p) */ /* ---------------------------------------------------------------------- */ /* get parameters */ #ifdef LONG ccolamd_l_set_defaults (knobs) ; #else ccolamd_set_defaults (knobs) ; #endif if (Common->current < 0 || Common->current >= CHOLMOD_MAXMETHODS) { /* this is the CHOLMOD default, not the CCOLAMD default */ knobs [CCOLAMD_DENSE_ROW] = -1 ; } else { /* get the knobs from the Common parameters */ knobs [CCOLAMD_DENSE_COL] =Common->method[Common->current].prune_dense ; knobs [CCOLAMD_DENSE_ROW] =Common->method[Common->current].prune_dense2; knobs [CCOLAMD_AGGRESSIVE]=Common->method[Common->current].aggressive ; knobs [CCOLAMD_LU] =Common->method[Common->current].order_for_lu; } if (ok) { #ifdef LONG ccolamd_l (ncol, nrow, alen, C->i, C->p, knobs, stats, Cmember) ; #else ccolamd (ncol, nrow, alen, C->i, C->p, knobs, stats, Cmember) ; #endif ok = stats [CCOLAMD_STATUS] ; ok = (ok == CCOLAMD_OK || ok == CCOLAMD_OK_BUT_JUMBLED) ; /* permutation returned in C->p, if the ordering succeeded */ Cp = C->p ; for (k = 0 ; k < nrow ; k++) { Perm [k] = Cp [k] ; } } return (ok) ; } /* ========================================================================== */ /* === cholmod_ccolamd ====================================================== */ /* ========================================================================== */ /* Order AA' or A(:,f)*A(:,f)' using CCOLAMD. */ int CHOLMOD(ccolamd) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ Int *Cmember, /* size A->nrow. Cmember [i] = c if row i is in the * constraint set c. c must be >= 0. The # of * constraint sets is max (Cmember) + 1. If Cmember is * NULL, then it is interpretted as Cmember [i] = 0 for * all i */ /* ---- output --- */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *C ; Int ok, nrow, ncol ; size_t alen ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (A->stype != 0) { ERROR (CHOLMOD_INVALID, "matrix must be unsymmetric") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; ncol = A->ncol ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ #ifdef LONG alen = ccolamd_l_recommended (A->nzmax, ncol, nrow) ; #else alen = ccolamd_recommended (A->nzmax, ncol, nrow) ; #endif if (alen == 0) { ERROR (CHOLMOD_TOO_LARGE, "matrix invalid or too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (0, MAX (nrow,ncol), 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } C = CHOLMOD(allocate_sparse) (ncol, nrow, alen, TRUE, TRUE, 0, CHOLMOD_PATTERN, Common) ; /* ---------------------------------------------------------------------- */ /* order with ccolamd */ /* ---------------------------------------------------------------------- */ ok = ccolamd_interface (A, alen, Perm, Cmember, fset, fsize, C, Common) ; /* ---------------------------------------------------------------------- */ /* free the workspace and return result */ /* ---------------------------------------------------------------------- */ CHOLMOD(free_sparse) (&C, Common) ; return (ok) ; } #endif igraph/src/CHOLMOD/Partition/lesser.txt0000644000175100001440000006350013430770174017437 0ustar hornikusers GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! igraph/src/CHOLMOD/Partition/cholmod_metis.c0000644000175100001440000006417513431000472020370 0ustar hornikusers/* ========================================================================== */ /* === Partition/cholmod_metis ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Partition Module. * Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Partition Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the METIS package (Version 4.0.1): * * cholmod_metis_bisector: * * Wrapper for METIS_NodeComputeSeparator. Finds a set of nodes that * partitions the graph into two parts. * * cholmod_metis: * * Wrapper for METIS_NodeND, METIS's own nested dissection algorithm. * Typically faster than cholmod_nested_dissection, mostly because it * uses minimum degree on just the leaves of the separator tree, rather * than the whole matrix. * * Note that METIS does not return an error if it runs out of memory. Instead, * it terminates the program. This interface attempts to avoid that problem * by preallocating space that should be large enough for any memory allocations * within METIS, and then freeing that space, just before the call to METIS. * While this is not guaranteed to work, it is very unlikely to fail. If you * encounter this problem, increase Common->metis_memory. If you don't mind * having your program terminated, set Common->metis_memory to zero (a value of * 2.0 is usually safe). Several other METIS workarounds are made in the * routines in this file. See the description of metis_memory_ok, just below, * for more details. * * FUTURE WORK: interfaces to other partitioners (CHACO, SCOTCH, JOSTLE, ... ) * * workspace: several size-nz and size-n temporary arrays. Uses no workspace * in Common. * * Supports any xtype (pattern, real, complex, or zomplex). */ static int igraph_stfu2(); static int igraph_stfu1() { return igraph_stfu2(); } static int igraph_stfu2() { return igraph_stfu1(); } #ifndef NPARTITION #include "cholmod_internal.h" #undef ASSERT #include "metis.h" /* METIS has its own ASSERT that it reveals to the user, so remove it here: */ #undef ASSERT /* and redefine it back again */ #ifndef NDEBUG #define ASSERT(expression) (assert (expression)) #else #define ASSERT(expression) #endif #include "cholmod_partition.h" #include "cholmod_cholesky.h" /* ========================================================================== */ /* === dumpgraph ============================================================ */ /* ========================================================================== */ /* For dumping the input graph to METIS_NodeND, to check with METIS's onmetis * and graphchk programs. For debugging only. To use, uncomment this #define: #define DUMP_GRAPH */ #ifdef DUMP_GRAPH #include /* After dumping the graph with this routine, run "onmetis metisgraph" */ static void dumpgraph (idxtype *Mp, idxtype *Mi, SuiteSparse_long n, cholmod_common *Common) { SuiteSparse_long i, j, p, nz ; FILE *f ; nz = Mp [n] ; printf ("Dumping METIS graph n %ld nz %ld\n", n, nz) ; /* DUMP_GRAPH */ f = fopen ("metisgraph", "w") ; if (f == NULL) { ERROR (-99, "cannot open metisgraph") ; return ; } fprintf (f, "%ld %ld\n", n, nz/2) ; /* DUMP_GRAPH */ for (j = 0 ; j < n ; j++) { for (p = Mp [j] ; p < Mp [j+1] ; p++) { i = Mi [p] ; fprintf (f, " %ld", i+1) ; /* DUMP_GRAPH */ } fprintf (f, "\n") ; /* DUMP_GRAPH */ } fclose (f) ; } #endif /* ========================================================================== */ /* === metis_memory_ok ====================================================== */ /* ========================================================================== */ /* METIS_NodeND and METIS_NodeComputeSeparator will terminate your program it * they run out of memory. In an attempt to workaround METIS' behavior, this * routine allocates a single block of memory of size equal to an observed * upper bound on METIS' memory usage. It then immediately deallocates the * block. If the allocation fails, METIS is not called. * * Median memory usage for a graph with n nodes and nz edges (counting each * edge twice, or both upper and lower triangular parts of a matrix) is * 4*nz + 40*n + 4096 integers. A "typical" upper bound is 10*nz + 50*n + 4096 * integers. Nearly all matrices tested fit within that upper bound, with the * exception two in the UF sparse matrix collection: Schenk_IBMNA/c-64 and * Gupta/gupta2. The latter exceeds the "upper bound" by a factor of just less * than 2. * * If you do not mind having your program terminated if it runs out of memory, * set Common->metis_memory to zero. Its default value is 2, which allows for * some memory fragmentation, and also accounts for the Gupta/gupta2 matrix. * * An alternative, if CHOLMOD is used in MATLAB, is to use a version of METIS * (4.0.2, perhaps) proposed to George Karypis. This version uses function * pointer for malloc and free. They can be set to mxMalloc and mxFree * (see sputil_config in MATLAB/sputil.c). On Linux, with gcc, you must also * compile CHOLMOD, METIS, AMD, COLAMD, and CCOLAMD with the -fexceptions * compiler flag. With this configuration, mxMalloc safely aborts the * mexFunction, frees all memory allocted by METIS, and safely returns to * MATLAB. You may then set Common->metis_memory = 0. */ #define GUESS(nz,n) (10 * (nz) + 50 * (n) + 4096) static int metis_memory_ok ( Int n, Int nz, cholmod_common *Common ) { double s ; void *p ; size_t metis_guard ; if (Common->metis_memory <= 0) { /* do not prevent METIS from running out of memory */ return (TRUE) ; } n = MAX (1, n) ; nz = MAX (0, nz) ; /* compute in double, to avoid integer overflow */ s = GUESS ((double) nz, (double) n) ; s *= Common->metis_memory ; if (s * sizeof (idxtype) >= ((double) Size_max)) { /* don't even attempt to malloc such a large block */ return (FALSE) ; } /* recompute in size_t */ metis_guard = GUESS ((size_t) nz, (size_t) n) ; metis_guard *= Common->metis_memory ; /* attempt to malloc the block */ p = CHOLMOD(malloc) (metis_guard, sizeof (idxtype), Common) ; if (p == NULL) { /* failure - return out-of-memory condition */ return (FALSE) ; } /* success - free the block */ CHOLMOD(free) (metis_guard, sizeof (idxtype), p, Common) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_metis_bisector =============================================== */ /* ========================================================================== */ /* Finds a set of nodes that bisects the graph of A or AA' (direct interface * to METIS_NodeComputeSeparator). * * The input matrix A must be square, symmetric (with both upper and lower * parts present) and with no diagonal entries. These conditions are NOT * checked. */ SuiteSparse_long CHOLMOD(metis_bisector) /* returns separator size */ ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to bisect */ Int *Anw, /* size A->nrow, node weights */ Int *Aew, /* size nz, edge weights */ /* ---- output --- */ Int *Partition, /* size A->nrow */ /* --------------- */ cholmod_common *Common ) { Int *Ap, *Ai ; idxtype *Mp, *Mi, *Mnw, *Mew, *Mpart ; Int n, nleft, nright, j, p, csep, total_weight, lightest, nz ; int Opt [8], nn, csp ; size_t n1 ; DEBUG (Int nsep) ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_NULL (Anw, EMPTY) ; RETURN_IF_NULL (Aew, EMPTY) ; RETURN_IF_NULL (Partition, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; if (A->stype || A->nrow != A->ncol) { /* A must be square, with both upper and lower parts present */ ERROR (CHOLMOD_INVALID, "matrix must be square, symmetric," " and with both upper/lower parts present") ; return (EMPTY) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* quick return */ /* ---------------------------------------------------------------------- */ n = A->nrow ; if (n == 0) { return (0) ; } n1 = ((size_t) n) + 1 ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; nz = Ap [n] ; /* ---------------------------------------------------------------------- */ /* METIS does not have a 64-bit integer version */ /* ---------------------------------------------------------------------- */ #ifdef LONG if (sizeof (Int) > sizeof (idxtype) && MAX (n,nz) > INT_MAX / sizeof (int)) { /* CHOLMOD's matrix is too large for METIS */ return (EMPTY) ; } #endif /* ---------------------------------------------------------------------- */ /* set default options */ /* ---------------------------------------------------------------------- */ Opt [0] = 0 ; /* use defaults */ Opt [1] = 3 ; /* matching type */ Opt [2] = 1 ; /* init. partitioning algo*/ Opt [3] = 2 ; /* refinement algorithm */ Opt [4] = 0 ; /* no debug */ Opt [5] = 0 ; /* unused */ Opt [6] = 0 ; /* unused */ Opt [7] = -1 ; /* random seed */ DEBUG (for (j = 0 ; j < n ; j++) ASSERT (Anw [j] > 0)) ; /* ---------------------------------------------------------------------- */ /* copy Int to METIS idxtype, if necessary */ /* ---------------------------------------------------------------------- */ DEBUG (for (j = 0 ; j < nz ; j++) ASSERT (Aew [j] > 0)) ; if (sizeof (Int) == sizeof (idxtype)) { /* this is the typical case */ Mi = (idxtype *) Ai ; Mew = (idxtype *) Aew ; Mp = (idxtype *) Ap ; Mnw = (idxtype *) Anw ; Mpart = (idxtype *) Partition ; } else { /* idxtype and Int differ; copy the graph into the METIS idxtype */ Mi = CHOLMOD(malloc) (nz, sizeof (idxtype), Common) ; Mew = CHOLMOD(malloc) (nz, sizeof (idxtype), Common) ; Mp = CHOLMOD(malloc) (n1, sizeof (idxtype), Common) ; Mnw = CHOLMOD(malloc) (n, sizeof (idxtype), Common) ; Mpart = CHOLMOD(malloc) (n, sizeof (idxtype), Common) ; if (Common->status < CHOLMOD_OK) { CHOLMOD(free) (nz, sizeof (idxtype), Mi, Common) ; CHOLMOD(free) (nz, sizeof (idxtype), Mew, Common) ; CHOLMOD(free) (n1, sizeof (idxtype), Mp, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mnw, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mpart, Common) ; return (EMPTY) ; } for (p = 0 ; p < nz ; p++) { Mi [p] = Ai [p] ; } for (p = 0 ; p < nz ; p++) { Mew [p] = Aew [p] ; } for (j = 0 ; j <= n ; j++) { Mp [j] = Ap [j] ; } for (j = 0 ; j < n ; j++) { Mnw [j] = Anw [j] ; } } /* ---------------------------------------------------------------------- */ /* METIS workaround: try to ensure METIS doesn't run out of memory */ /* ---------------------------------------------------------------------- */ if (!metis_memory_ok (n, nz, Common)) { /* METIS might ask for too much memory and thus terminate the program */ if (sizeof (Int) != sizeof (idxtype)) { CHOLMOD(free) (nz, sizeof (idxtype), Mi, Common) ; CHOLMOD(free) (nz, sizeof (idxtype), Mew, Common) ; CHOLMOD(free) (n1, sizeof (idxtype), Mp, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mnw, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mpart, Common) ; } return (EMPTY) ; } /* ---------------------------------------------------------------------- */ /* partition the graph */ /* ---------------------------------------------------------------------- */ #ifndef NDEBUG PRINT1 (("Metis graph, n = "ID"\n", n)) ; for (j = 0 ; j < n ; j++) { Int ppp ; PRINT2 (("M(:,"ID") node weight "ID"\n", j, (Int) Mnw [j])) ; ASSERT (Mnw [j] > 0) ; for (ppp = Mp [j] ; ppp < Mp [j+1] ; ppp++) { PRINT3 ((" "ID" : "ID"\n", (Int) Mi [ppp], (Int) Mew [ppp])) ; ASSERT (Mi [ppp] != j) ; ASSERT (Mew [ppp] > 0) ; } } #endif nn = n ; METIS_NodeComputeSeparator (&nn, Mp, Mi, Mnw, Mew, Opt, &csp, Mpart) ; n = nn ; csep = csp ; PRINT1 (("METIS csep "ID"\n", csep)) ; /* ---------------------------------------------------------------------- */ /* copy the results back from idxtype, if required */ /* ---------------------------------------------------------------------- */ if (sizeof (Int) != sizeof (idxtype)) { for (j = 0 ; j < n ; j++) { Partition [j] = Mpart [j] ; } CHOLMOD(free) (nz, sizeof (idxtype), Mi, Common) ; CHOLMOD(free) (nz, sizeof (idxtype), Mew, Common) ; CHOLMOD(free) (n1, sizeof (idxtype), Mp, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mnw, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mpart, Common) ; } /* ---------------------------------------------------------------------- */ /* ensure a reasonable separator */ /* ---------------------------------------------------------------------- */ /* METIS can return a valid separator with no nodes in (for example) the * left part. In this case, there really is no separator. CHOLMOD * prefers, in this case, for all nodes to be in the separator (and both * left and right parts to be empty). Also, if the graph is unconnected, * METIS can return a valid empty separator. CHOLMOD prefers at least one * node in the separator. Note that cholmod_nested_dissection only calls * this routine on connected components, but cholmod_bisect can call this * routine for any graph. */ if (csep == 0) { /* The separator is empty, select lightest node as separator. If * ties, select the highest numbered node. */ lightest = 0 ; for (j = 0 ; j < n ; j++) { if (Anw [j] <= Anw [lightest]) { lightest = j ; } } PRINT1 (("Force "ID" as sep\n", lightest)) ; Partition [lightest] = 2 ; csep = Anw [lightest] ; } /* determine the node weights in the left and right part of the graph */ nleft = 0 ; nright = 0 ; DEBUG (nsep = 0) ; for (j = 0 ; j < n ; j++) { PRINT1 (("Partition ["ID"] = "ID"\n", j, Partition [j])) ; if (Partition [j] == 0) { nleft += Anw [j] ; } else if (Partition [j] == 1) { nright += Anw [j] ; } #ifndef NDEBUG else { ASSERT (Partition [j] == 2) ; nsep += Anw [j] ; } #endif } ASSERT (csep == nsep) ; total_weight = nleft + nright + csep ; if (csep < total_weight) { /* The separator is less than the whole graph. Make sure the left and * right parts are either both empty or both non-empty. */ PRINT1 (("nleft "ID" nright "ID" csep "ID" tot "ID"\n", nleft, nright, csep, total_weight)) ; ASSERT (nleft + nright + csep == total_weight) ; ASSERT (nleft > 0 || nright > 0) ; if ((nleft == 0 && nright > 0) || (nleft > 0 && nright == 0)) { /* left or right is empty; put all nodes in the separator */ PRINT1 (("Force all in sep\n")) ; csep = total_weight ; for (j = 0 ; j < n ; j++) { Partition [j] = 2 ; } } } ASSERT (CHOLMOD(dump_partition) (n, Ap, Ai, Anw, Partition, csep, Common)) ; /* ---------------------------------------------------------------------- */ /* return the sum of the weights of nodes in the separator */ /* ---------------------------------------------------------------------- */ return (csep) ; } /* ========================================================================== */ /* === cholmod_metis ======================================================== */ /* ========================================================================== */ /* CHOLMOD wrapper for the METIS_NodeND ordering routine. Creates A+A', * A*A' or A(:,f)*A(:,f)' and then calls METIS_NodeND on the resulting graph. * This routine is comparable to cholmod_nested_dissection, except that it * calls METIS_NodeND directly, and it does not return the separator tree. * * workspace: Flag (nrow), Iwork (4*n+uncol) * Allocates a temporary matrix B=A*A' or B=A. */ int CHOLMOD(metis) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ int postorder, /* if TRUE, follow with etree or coletree postorder */ /* ---- output --- */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { double d ; Int *Iperm, *Iwork, *Bp, *Bi ; idxtype *Mp, *Mi, *Mperm, *Miperm ; cholmod_sparse *B ; Int i, j, n, nz, p, identity, uncol ; int Opt [8], nn, zero = 0 ; size_t n1, s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* quick return */ /* ---------------------------------------------------------------------- */ n = A->nrow ; if (n == 0) { return (TRUE) ; } n1 = ((size_t) n) + 1 ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 4*n + uncol */ uncol = (A->stype == 0) ? A->ncol : 0 ; s = CHOLMOD(mult_size_t) (n, 4, &ok) ; s = CHOLMOD(add_size_t) (s, uncol, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* convert the matrix to adjacency list form */ /* ---------------------------------------------------------------------- */ /* The input graph for METIS must be symmetric, with both upper and lower * parts present, and with no diagonal entries. The columns need not be * sorted. * B = A+A', A*A', or A(:,f)*A(:,f)', upper and lower parts present */ if (A->stype) { /* Add the upper/lower part to a symmetric lower/upper matrix by * converting to unsymmetric mode */ /* workspace: Iwork (nrow) */ B = CHOLMOD(copy) (A, 0, -1, Common) ; } else { /* B = A*A' or A(:,f)*A(:,f)', no diagonal */ /* workspace: Flag (nrow), Iwork (max (nrow,ncol)) */ B = CHOLMOD(aat) (A, fset, fsize, -1, Common) ; } ASSERT (CHOLMOD(dump_sparse) (B, "B for NodeND", Common) >= 0) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (B->nrow == A->nrow) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Iwork = Common->Iwork ; Iperm = Iwork ; /* size n (i/i/l) */ Bp = B->p ; Bi = B->i ; nz = Bp [n] ; /* ---------------------------------------------------------------------- */ /* METIS does not have a SuiteSparse_long integer version */ /* ---------------------------------------------------------------------- */ #ifdef LONG if (sizeof (Int) > sizeof (idxtype) && MAX (n,nz) > INT_MAX / sizeof (int)) { /* CHOLMOD's matrix is too large for METIS */ CHOLMOD(free_sparse) (&B, Common) ; return (FALSE) ; } #endif /* B does not include the diagonal, and both upper and lower parts. * Common->anz includes the diagonal, and just the lower part of B */ Common->anz = nz / 2 + n ; /* ---------------------------------------------------------------------- */ /* set control parameters for METIS_NodeND */ /* ---------------------------------------------------------------------- */ Opt [0] = 0 ; /* use defaults */ Opt [1] = 3 ; /* matching type */ Opt [2] = 1 ; /* init. partitioning algo*/ Opt [3] = 2 ; /* refinement algorithm */ Opt [4] = 0 ; /* no debug */ Opt [5] = 1 ; /* initial compression */ Opt [6] = 0 ; /* no dense node removal */ Opt [7] = 1 ; /* number of separators @ each step */ /* ---------------------------------------------------------------------- */ /* allocate the METIS input arrays, if needed */ /* ---------------------------------------------------------------------- */ if (sizeof (Int) == sizeof (idxtype)) { /* This is the typical case. */ Miperm = (idxtype *) Iperm ; Mperm = (idxtype *) Perm ; Mp = (idxtype *) Bp ; Mi = (idxtype *) Bi ; } else { /* allocate graph for METIS only if Int and idxtype differ */ Miperm = CHOLMOD(malloc) (n, sizeof (idxtype), Common) ; Mperm = CHOLMOD(malloc) (n, sizeof (idxtype), Common) ; Mp = CHOLMOD(malloc) (n1, sizeof (idxtype), Common) ; Mi = CHOLMOD(malloc) (nz, sizeof (idxtype), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ CHOLMOD(free_sparse) (&B, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Miperm, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mperm, Common) ; CHOLMOD(free) (n1, sizeof (idxtype), Mp, Common) ; CHOLMOD(free) (nz, sizeof (idxtype), Mi, Common) ; return (FALSE) ; } for (j = 0 ; j <= n ; j++) { Mp [j] = Bp [j] ; } for (p = 0 ; p < nz ; p++) { Mi [p] = Bi [p] ; } } /* ---------------------------------------------------------------------- */ /* METIS workarounds */ /* ---------------------------------------------------------------------- */ identity = FALSE ; if (nz == 0) { /* The matrix has no off-diagonal entries. METIS_NodeND fails in this * case, so avoid using it. The best permutation is identity anyway, * so this is an easy fix. */ identity = TRUE ; PRINT1 (("METIS:: no nz\n")) ; } else if (Common->metis_nswitch > 0) { /* METIS_NodeND in METIS 4.0.1 gives a seg fault with one matrix of * order n = 3005 and nz = 6,036,025, including the diagonal entries. * The workaround is to return the identity permutation instead of using * METIS for matrices of dimension 3000 or more and with density of 66% * or more - admittedly an uncertain fix, but such matrices are so dense * that any reasonable ordering will do, even identity (n^2 is only 50% * higher than nz in this case). CHOLMOD's nested dissection method * (cholmod_nested_dissection) has no problems with the same matrix, * even though it too uses METIS_NodeComputeSeparator. The matrix is * derived from LPnetlib/lpi_cplex1 in the UF sparse matrix collection. * If C is the lpi_cplex matrix (of order 3005-by-5224), A = (C*C')^2 * results in the seg fault. The seg fault also occurs in the stand- * alone onmetis program that comes with METIS. If a future version of * METIS fixes this problem, then set Common->metis_nswitch to zero. */ d = ((double) nz) / (((double) n) * ((double) n)) ; if (n > (Int) (Common->metis_nswitch) && d > Common->metis_dswitch) { identity = TRUE ; PRINT1 (("METIS:: nswitch/dswitch activated\n")) ; } } if (!identity && !metis_memory_ok (n, nz, Common)) { /* METIS might ask for too much memory and thus terminate the program */ identity = TRUE ; } /* ---------------------------------------------------------------------- */ /* find the permutation */ /* ---------------------------------------------------------------------- */ if (identity) { /* no need to do the postorder */ postorder = FALSE ; for (i = 0 ; i < n ; i++) { Mperm [i] = i ; } } else { #ifdef DUMP_GRAPH /* DUMP_GRAPH */ printf ("Calling METIS_NodeND n "ID" nz "ID"" "density %g\n", n, nz, ((double) nz) / (((double) n) * ((double) n))); dumpgraph (Mp, Mi, n, Common) ; #endif nn = n ; METIS_NodeND (&nn, Mp, Mi, &zero, Opt, Mperm, Miperm) ; n = nn ; PRINT0 (("METIS_NodeND done\n")) ; } /* ---------------------------------------------------------------------- */ /* free the METIS input arrays */ /* ---------------------------------------------------------------------- */ if (sizeof (Int) != sizeof (idxtype)) { for (i = 0 ; i < n ; i++) { Perm [i] = (Int) (Mperm [i]) ; } CHOLMOD(free) (n, sizeof (idxtype), Miperm, Common) ; CHOLMOD(free) (n, sizeof (idxtype), Mperm, Common) ; CHOLMOD(free) (n+1, sizeof (idxtype), Mp, Common) ; CHOLMOD(free) (nz, sizeof (idxtype), Mi, Common) ; } CHOLMOD(free_sparse) (&B, Common) ; /* ---------------------------------------------------------------------- */ /* etree or column-etree postordering, using the Cholesky Module */ /* ---------------------------------------------------------------------- */ if (postorder) { Int *Parent, *Post, *NewPerm ; Int k ; Parent = Iwork + 2*((size_t) n) + uncol ; /* size n = nrow */ Post = Parent + n ; /* size n */ /* workspace: Iwork (2*nrow+uncol), Flag (nrow), Head (nrow+1) */ CHOLMOD(analyze_ordering) (A, CHOLMOD_METIS, Perm, fset, fsize, Parent, Post, NULL, NULL, NULL, Common) ; if (Common->status == CHOLMOD_OK) { /* combine the METIS permutation with its postordering */ NewPerm = Parent ; /* use Parent as workspace */ for (k = 0 ; k < n ; k++) { NewPerm [k] = Perm [Post [k]] ; } for (k = 0 ; k < n ; k++) { Perm [k] = NewPerm [k] ; } } } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; PRINT1 (("cholmod_metis done\n")) ; return (Common->status == CHOLMOD_OK) ; } #endif igraph/src/CHOLMOD/Partition/cholmod_csymamd.c0000644000175100001440000001135313431000472020672 0ustar hornikusers/* ========================================================================== */ /* === Partition/cholmod_csymamd ============================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Partition Module. * Copyright (C) 2005-2013, Univ. of Florida. Author: Timothy A. Davis * The CHOLMOD/Partition Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the CSYMAMD ordering routine. Finds a permutation * p such that the Cholesky factorization of PAP' is sparser than A. * The column etree is found and postordered, and the CSYMAMD * ordering is then combined with its postordering. If A is unsymmetric, * A+A' is ordered (A must be square). * * workspace: Head (nrow+1) * * Supports any xtype (pattern, real, complex, or zomplex). */ static int igraph_stfu2(); static int igraph_stfu1() { return igraph_stfu2(); } static int igraph_stfu2() { return igraph_stfu1(); } #ifndef NCAMD #include "cholmod_internal.h" #include "ccolamd.h" #include "cholmod_camd.h" #if (CCOLAMD_VERSION < CCOLAMD_VERSION_CODE (2,5)) #error "CCOLAMD v2.0 or later is required" #endif /* ========================================================================== */ /* === cholmod_csymamd ====================================================== */ /* ========================================================================== */ int CHOLMOD(csymamd) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ /* ---- output --- */ Int *Cmember, /* size nrow. see cholmod_ccolamd.c for description */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { double knobs [CCOLAMD_KNOBS] ; Int *perm, *Head ; Int ok, i, nrow, stats [CCOLAMD_STATS] ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; if (A->nrow != A->ncol || !(A->packed)) { ERROR (CHOLMOD_INVALID, "matrix must be square and packed") ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrow = A->nrow ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ CHOLMOD(allocate_work) (nrow, 0, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* order the matrix (does not affect A->p or A->i) */ /* ---------------------------------------------------------------------- */ perm = Common->Head ; /* size nrow+1 (i/l/l) */ /* get parameters */ #ifdef LONG ccolamd_l_set_defaults (knobs) ; #else ccolamd_set_defaults (knobs) ; #endif if (Common->current >= 0 && Common->current < CHOLMOD_MAXMETHODS) { /* get the knobs from the Common parameters */ knobs [CCOLAMD_DENSE_ROW] =Common->method[Common->current].prune_dense ; knobs [CCOLAMD_AGGRESSIVE]=Common->method[Common->current].aggressive ; } { #ifdef LONG csymamd_l (nrow, A->i, A->p, perm, knobs, stats, Common->calloc_memory, Common->free_memory, Cmember, A->stype) ; #else csymamd (nrow, A->i, A->p, perm, knobs, stats, Common->calloc_memory, Common->free_memory, Cmember, A->stype) ; #endif ok = stats [CCOLAMD_STATUS] ; } if (ok == CCOLAMD_ERROR_out_of_memory) { ERROR (CHOLMOD_OUT_OF_MEMORY, "out of memory") ; } ok = (ok == CCOLAMD_OK || ok == CCOLAMD_OK_BUT_JUMBLED) ; /* ---------------------------------------------------------------------- */ /* free the workspace and return result */ /* ---------------------------------------------------------------------- */ /* permutation returned in perm [0..n-1] */ for (i = 0 ; i < nrow ; i++) { Perm [i] = perm [i] ; } /* clear Head workspace (used for perm, in csymamd): */ Head = Common->Head ; for (i = 0 ; i <= nrow ; i++) { Head [i] = EMPTY ; } return (ok) ; } #endif igraph/src/CHOLMOD/Partition/License.txt0000644000175100001440000000210413430770174017515 0ustar hornikusersCHOLMOD/Partition Module. Copyright (C) 2005-2006, Univ. of Florida. Author: Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Partition module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA igraph/src/CHOLMOD/Partition/cholmod_camd.c0000644000175100001440000001745413431000472020151 0ustar hornikusers/* ========================================================================== */ /* === Partition/cholmod_camd =============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Partition Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Partition Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* CHOLMOD interface to the CAMD ordering routine. Orders A if the matrix is * symmetric. On output, Perm [k] = i if row/column i of A is the kth * row/column of P*A*P'. This corresponds to A(p,p) in MATLAB notation. * * If A is unsymmetric, cholmod_camd orders A*A'. On output, Perm [k] = i if * row/column i of A*A' is the kth row/column of P*A*A'*P'. This corresponds to * A(p,:)*A(p,:)' in MATLAB notation. If f is present, A(p,f)*A(p,f)' is * ordered. * * Computes the flop count for a subsequent LL' factorization, the number * of nonzeros in L, and the number of nonzeros in the matrix ordered (A, * A*A' or A(:,f)*A(:,f)'). * * workspace: Iwork (4*nrow). Head (nrow). * * Allocates a temporary copy of A+A' or A*A' (with * both upper and lower triangular parts) as input to CAMD. * Also allocates 3*(n+1) additional integer workspace (not in Common). * * Supports any xtype (pattern, real, complex, or zomplex) */ static int igraph_stfu2(); static int igraph_stfu1() { return igraph_stfu2(); } static int igraph_stfu2() { return igraph_stfu1(); } #ifndef NCAMD #include "cholmod_internal.h" #include "camd.h" #include "cholmod_camd.h" #if (CAMD_VERSION < CAMD_VERSION_CODE (2,0)) #error "CAMD v2.0 or later is required" #endif /* ========================================================================== */ /* === cholmod_camd ========================================================= */ /* ========================================================================== */ int CHOLMOD(camd) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to order */ Int *fset, /* subset of 0:(A->ncol)-1 */ size_t fsize, /* size of fset */ Int *Cmember, /* size nrow. see cholmod_ccolamd.c for description.*/ /* ---- output ---- */ Int *Perm, /* size A->nrow, output permutation */ /* --------------- */ cholmod_common *Common ) { double Info [CAMD_INFO], Control2 [CAMD_CONTROL], *Control ; Int *Cp, *Len, *Nv, *Head, *Elen, *Degree, *Wi, *Next, *BucketSet, *Work3n, *p ; cholmod_sparse *C ; Int j, n, cnz ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; n = A->nrow ; /* s = 4*n */ s = CHOLMOD(mult_size_t) (n, 4, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } RETURN_IF_NULL (Perm, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; Common->status = CHOLMOD_OK ; if (n == 0) { /* nothing to do */ Common->fl = 0 ; Common->lnz = 0 ; Common->anz = 0 ; return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ /* cholmod_analyze has allocated Cmember at Common->Iwork + 5*n+uncol, and * CParent at Common->Iwork + 4*n+uncol, where uncol is 0 if A is symmetric * or A->ncol otherwise. Thus, only the first 4n integers in Common->Iwork * can be used here. */ CHOLMOD(allocate_work) (n, s, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } p = Common->Iwork ; Degree = p ; p += n ; /* size n */ Elen = p ; p += n ; /* size n */ Len = p ; p += n ; /* size n */ Nv = p ; p += n ; /* size n */ Work3n = CHOLMOD(malloc) (n+1, 3*sizeof (Int), Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } p = Work3n ; Next = p ; p += n ; /* size n */ Wi = p ; p += (n+1) ; /* size n+1 */ BucketSet = p ; /* size n */ Head = Common->Head ; /* size n+1 */ /* ---------------------------------------------------------------------- */ /* construct the input matrix for CAMD */ /* ---------------------------------------------------------------------- */ if (A->stype == 0) { /* C = A*A' or A(:,f)*A(:,f)', add extra space of nnz(C)/2+n to C */ C = CHOLMOD(aat) (A, fset, fsize, -2, Common) ; } else { /* C = A+A', but use only the upper triangular part of A if A->stype = 1 * and only the lower part of A if A->stype = -1. Add extra space of * nnz(C)/2+n to C. */ C = CHOLMOD(copy) (A, 0, -2, Common) ; } if (Common->status < CHOLMOD_OK) { /* out of memory, fset invalid, or other error */ CHOLMOD(free) (n+1, 3*sizeof (Int), Work3n, Common) ; return (FALSE) ; } Cp = C->p ; for (j = 0 ; j < n ; j++) { Len [j] = Cp [j+1] - Cp [j] ; } /* C does not include the diagonal, and both upper and lower parts. * Common->anz includes the diagonal, and just the lower part of C */ cnz = Cp [n] ; Common->anz = cnz / 2 + n ; /* ---------------------------------------------------------------------- */ /* order C using CAMD */ /* ---------------------------------------------------------------------- */ /* get parameters */ if (Common->current < 0 || Common->current >= CHOLMOD_MAXMETHODS) { /* use CAMD defaults */ Control = NULL ; } else { Control = Control2 ; Control [CAMD_DENSE] = Common->method [Common->current].prune_dense ; Control [CAMD_AGGRESSIVE] = Common->method [Common->current].aggressive; } /* CAMD_2 does not use camd_malloc and camd_free, but set these pointers * just be safe. */ camd_malloc = Common->malloc_memory ; camd_free = Common->free_memory ; camd_calloc = Common->calloc_memory ; camd_realloc = Common->realloc_memory ; /* CAMD_2 doesn't print anything either, but future versions might, * so set the camd_printf pointer too. */ camd_printf = Common->print_function ; #ifdef LONG /* DEBUG (camd_l_debug_init ("cholmod_l_camd")) ; */ camd_l2 (n, C->p, C->i, Len, C->nzmax, cnz, Nv, Next, Perm, Head, Elen, Degree, Wi, Control, Info, Cmember, BucketSet) ; #else /* DEBUG (camd_debug_init ("cholmod_camd")) ; */ camd_2 (n, C->p, C->i, Len, C->nzmax, cnz, Nv, Next, Perm, Head, Elen, Degree, Wi, Control, Info, Cmember, BucketSet) ; #endif /* LL' flop count. Need to subtract n for LL' flop count. Note that this * is a slight upper bound which is often exact (see CAMD/Source/camd_2.c * for details). cholmod_analyze computes an exact flop count and * fill-in. */ Common->fl = Info [CAMD_NDIV] + 2 * Info [CAMD_NMULTSUBS_LDL] + n ; /* Info [CAMD_LNZ] excludes the diagonal */ Common->lnz = n + Info [CAMD_LNZ] ; /* ---------------------------------------------------------------------- */ /* free the CAMD workspace and clear the persistent workspace in Common */ /* ---------------------------------------------------------------------- */ ASSERT (IMPLIES (Common->status == CHOLMOD_OK, CHOLMOD(dump_perm) (Perm, n, n, "CAMD2 perm", Common))) ; CHOLMOD(free_sparse) (&C, Common) ; for (j = 0 ; j <= n ; j++) { Head [j] = EMPTY ; } CHOLMOD(free) (n+1, 3*sizeof (Int), Work3n, Common) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/Modify/0000755000175100001440000000000013561251652014653 5ustar hornikusersigraph/src/CHOLMOD/Modify/cholmod_rowadd.c0000644000175100001440000004643013431000472017777 0ustar hornikusers/* ========================================================================== */ /* === Modify/cholmod_rowadd ================================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Modify Module. * Copyright (C) 2005-2006, Timothy A. Davis and William W. Hager. * The CHOLMOD/Modify Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Adds a row and column to an LDL' factorization, and optionally updates the * solution to Lx=b. * * workspace: Flag (nrow), Head (nrow+1), W (2*nrow), Iwork (2*nrow) * * Only real matrices are supported. A symbolic L is converted into a * numeric identity matrix before the row is added. */ #ifndef NMODIFY #include "cholmod_internal.h" #include "cholmod_modify.h" /* ========================================================================== */ /* === cholmod_rowadd ======================================================= */ /* ========================================================================== */ /* cholmod_rowadd adds a row to the LDL' factorization. It computes the kth * row and kth column of L, and then updates the submatrix L (k+1:n,k+1:n) * accordingly. The kth row and column of L should originally be equal to the * kth row and column of the identity matrix (they are treated as such, if they * are not). The kth row/column of L is computed as the factorization of the * kth row/column of the matrix to factorize, which is provided as a single * n-by-1 sparse matrix R. The sparse vector R need not be sorted. */ int CHOLMOD(rowadd) ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { double bk [2] ; bk [0] = 0. ; bk [1] = 0. ; return (CHOLMOD(rowadd_mark) (k, R, bk, NULL, L, NULL, NULL, Common)) ; } /* ========================================================================== */ /* === cholmod_rowadd_solve ================================================= */ /* ========================================================================== */ /* Does the same as cholmod_rowadd, and also updates the solution to Lx=b * See cholmod_updown for a description of how Lx=b is updated. There is on * additional parameter: bk specifies the new kth entry of b. */ int CHOLMOD(rowadd_solve) ( /* ---- input ---- */ size_t k, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right-hand-side b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(rowadd_mark) (k, R, bk, NULL, L, X, DeltaB, Common)) ; } /* ========================================================================== */ /* === icomp ================================================================ */ /* ========================================================================== */ /* for sorting by qsort */ static int icomp (Int *i, Int *j) { if (*i < *j) { return (-1) ; } else { return (1) ; } } /* ========================================================================== */ /* === cholmod_rowadd_mark ================================================== */ /* ========================================================================== */ /* Does the same as cholmod_rowadd_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. */ int CHOLMOD(rowadd_mark) ( /* ---- input ---- */ size_t kadd, /* row/column index to add */ cholmod_sparse *R, /* row/column of matrix to factorize (n-by-1) */ double bk [2], /* kth entry of the right hand side, b */ Int *colmark, /* Int array of size 1. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { double dk, yj, l_kj, lx, l_ij, sqrt_dk, dj, xk, rnz, fl ; double *Lx, *W, *Cx, *Rx, *Xx, *Nx ; Int *Li, *Lp, *Lnz, *Flag, *Stack, *Ci, *Rj, *Rp, *Lnext, *Iwork, *Rnz ; cholmod_sparse *C, Cmatrix ; Int i, j, p, pend, top, len, kk, li, lnz, mark, k, n, parent, Cp [2], do_solve, do_update ; size_t s ; int ok = TRUE ; DEBUG (Int lastrow) ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (R, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (R, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; n = L->n ; k = kadd ; if (kadd >= L->n || k < 0) { ERROR (CHOLMOD_INVALID, "k invalid") ; return (FALSE) ; } if (R->ncol != 1 || R->nrow != L->n) { ERROR (CHOLMOD_INVALID, "R invalid") ; return (FALSE) ; } Rj = R->i ; Rx = R->x ; Rp = R->p ; Rnz = R->nz ; rnz = (R->packed) ? (Rp [1]) : (Rnz [0]) ; do_solve = (X != NULL) && (DeltaB != NULL) ; if (do_solve) { RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (DeltaB, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; Xx = X->x ; Nx = DeltaB->x ; if (X->nrow != L->n || X->ncol != 1 || DeltaB->nrow != L->n || DeltaB->ncol != 1 || Xx == NULL || Nx == NULL) { ERROR (CHOLMOD_INVALID, "X and/or DeltaB invalid") ; return (FALSE) ; } } else { Xx = NULL ; Nx = NULL ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 2*n */ s = CHOLMOD(mult_size_t) (n, 2, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, s, s, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, s, Common)) ; /* ---------------------------------------------------------------------- */ /* convert to simplicial numeric LDL' factor, if not already */ /* ---------------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN || L->is_super || L->is_ll) { /* can only update/downdate a simplicial LDL' factorization */ CHOLMOD(change_factor) (CHOLMOD_REAL, FALSE, FALSE, FALSE, FALSE, L, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory, L is returned unchanged */ return (FALSE) ; } } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* inputs, not modified on output: */ Lp = L->p ; /* size n+1. input, not modified on output */ /* outputs, contents defined on input for incremental case only: */ Lnz = L->nz ; /* size n */ Li = L->i ; /* size L->nzmax. Can change in size. */ Lx = L->x ; /* size L->nzmax. Can change in size. */ Lnext = L->next ; /* size n+2 */ ASSERT (L->nz != NULL) ; PRINT1 (("rowadd:\n")) ; fl = 0 ; #if 0 #ifndef NDEBUG /* column k of L should be zero, except for the diagonal. This test is * overly cautious. */ for (p = Lp [k] + 1 ; p < Lp [k] + Lnz [k] ; p++) ASSERT (Lx [p] == 0) ; #endif #endif /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size n */ W = Common->Xwork ; /* size n */ Cx = W + n ; /* size n (use 2nd column of Xwork for C) */ Iwork = Common->Iwork ; Stack = Iwork ; /* size n (i/i/l), also in cholmod_updown */ Ci = Iwork + n ; /* size n (i/i/l) */ /* NOTE: cholmod_updown uses Iwork [0..n-1] (i/i/l) as Stack as well */ mark = Common->mark ; /* copy Rj/Rx into W/Ci */ for (p = 0 ; p < rnz ; p++) { i = Rj [p] ; ASSERT (i >= 0 && i < n) ; W [i] = Rx [p] ; Ci [p] = i ; } /* At this point, W [Ci [0..rnz-1]] holds the sparse vector to add */ /* The nonzero pattern of column W is held in Ci (it may be unsorted). */ /* ---------------------------------------------------------------------- */ /* symbolic factorization to get pattern of kth row of L */ /* ---------------------------------------------------------------------- */ DEBUG (for (p = 0 ; p < rnz ; p++) PRINT1 (("C ("ID",%g)\n", Ci [p], W [Ci [p]]))) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* flag the diagonal */ Flag [k] = mark ; /* find the union of all the paths */ top = n ; lnz = 0 ; /* # of nonzeros in column k of L, excluding diagonal */ for (p = 0 ; p < rnz ; p++) { i = Ci [p] ; if (i < k) { /* walk from i = entry in Ci to root (and stop if i marked)*/ PRINT2 (("\nwalk from i = "ID" towards k = "ID"\n", i, k)) ; len = 0 ; /* walk up tree, but stop if we go below the diagonal */ while (i < k && i != EMPTY && Flag [i] < mark) { PRINT2 ((" Add "ID" to path\n", i)) ; ASSERT (i >= 0 && i < k) ; Stack [len++] = i ; /* place i on the stack */ Flag [i] = mark ; /* mark i as visited */ /* parent is the first entry in the column after the diagonal */ ASSERT (Lnz [i] > 0) ; parent = (Lnz [i] > 1) ? (Li [Lp [i] + 1]) : EMPTY ; PRINT2 ((" parent: "ID"\n", parent)) ; i = parent ; /* go up the tree */ } ASSERT (len <= top) ; /* move the path down to the bottom of the stack */ /* this shifts Stack [0..len-1] down to [ ... oldtop-1] */ while (len > 0) { Stack [--top] = Stack [--len] ; } } else if (i > k) { /* prune the diagonal and upper triangular entries from Ci */ Ci [lnz++] = i ; Flag [i] = mark ; } } #ifndef NDEBUG PRINT1 (("length of S after prune: "ID"\n", lnz)) ; for (p = 0 ; p < lnz ; p++) { PRINT1 (("After prune Ci ["ID"] = "ID"\n", p, Ci [p])) ; ASSERT (Ci [p] > k) ; } #endif /* ---------------------------------------------------------------------- */ /* ensure each column of L has enough space to grow */ /* ---------------------------------------------------------------------- */ for (kk = top ; kk < n ; kk++) { /* could skip this if we knew column j already included row k */ j = Stack [kk] ; if (Lp [j] + Lnz [j] >= Lp [Lnext [j]]) { PRINT1 (("Col "ID" realloc, old Lnz "ID"\n", j, Lnz [j])) ; if (!CHOLMOD(reallocate_column) (j, Lnz [j] + 1, L, Common)) { /* out of memory, L is now simplicial symbolic */ /* CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; for (i = 0 ; i < n ; i++) { W [i] = 0 ; } return (FALSE) ; } /* L->i and L->x may have moved */ Li = L->i ; Lx = L->x ; } ASSERT (Lp [j] + Lnz [j] < Lp [Lnext [j]] || (Lp [Lnext [j]] - Lp [j] == n-j)) ; } /* ---------------------------------------------------------------------- */ /* compute kth row of L and store in column form */ /* ---------------------------------------------------------------------- */ /* solve L (1:k-1, 1:k-1) * y (1:k-1) = b (1:k-1) */ /* where b (1:k) is in W and Ci */ /* L (k, 1:k-1) = y (1:k-1) ./ D (1:k-1) */ /* D (k) = B (k,k) - L (k, 1:k-1) * y (1:k-1) */ PRINT2 (("\nForward solve: "ID" to "ID"\n", top, n)) ; ASSERT (Lnz [k] >= 1 && Li [Lp [k]] == k) ; DEBUG (for (i = top ; i < n ; i++) PRINT2 ((" Path: "ID"\n", Stack [i]))) ; dk = W [k] ; W [k] = 0.0 ; /* if do_solve: compute x (k) = b (k) - L (k, 1:k-1) * x (1:k-1) */ xk = bk [0] ; PRINT2 (("B [k] = %g\n", xk)) ; for (kk = top ; kk < n ; kk++) { j = Stack [kk] ; i = j ; PRINT2 (("Forward solve col j = "ID":\n", j)) ; ASSERT (j >= 0 && j < k) ; /* forward solve using L (j+1:k-1,j) */ yj = W [j] ; W [j] = 0.0 ; p = Lp [j] ; pend = p + Lnz [j] ; ASSERT (Lnz [j] > 0) ; dj = Lx [p++] ; for ( ; p < pend ; p++) { i = Li [p] ; PRINT2 ((" row "ID"\n", i)) ; ASSERT (i > j) ; ASSERT (i < n) ; /* stop at row k */ if (i >= k) { break ; } W [i] -= Lx [p] * yj ; } /* each iteration of the above for loop did 2 flops, and 3 flops * are done below. so: fl += 2 * (Lp [j] - p - 1) + 3 becomes: */ fl += 2 * (Lp [j] - p) + 1 ; /* scale L (k,1:k-1) and compute dot product for D (k,k) */ l_kj = yj / dj ; dk -= l_kj * yj ; /* compute dot product for X(k) */ if (do_solve) { xk -= l_kj * Xx [j] ; } /* store l_kj in the jth column of L */ /* and shift the rest of the column down */ li = k ; lx = l_kj ; if (i == k) { /* no need to modify the nonzero pattern of L, since it already * contains row index k. */ ASSERT (Li [p] == k) ; Lx [p] = l_kj ; for (p++ ; p < pend ; p++) { i = Li [p] ; l_ij = Lx [p] ; ASSERT (i > k && i < n) ; PRINT2 ((" apply to row "ID" of column k of L\n", i)) ; /* add to the pattern of the kth column of L */ if (Flag [i] < mark) { PRINT2 ((" add Ci["ID"] = "ID"\n", lnz, i)) ; ASSERT (i > k) ; Ci [lnz++] = i ; Flag [i] = mark ; } /* apply the update to the kth column of L */ /* yj is equal to l_kj * d_j */ W [i] -= l_ij * yj ; } } else { PRINT2 (("Shift col j = "ID", apply saxpy to col k of L\n", j)) ; for ( ; p < pend ; p++) { /* swap (Li [p],Lx [p]) with (li,lx) */ i = Li [p] ; l_ij = Lx [p] ; Li [p] = li ; Lx [p] = lx ; li = i ; lx = l_ij ; ASSERT (i > k && i < n) ; PRINT2 ((" apply to row "ID" of column k of L\n", i)) ; /* add to the pattern of the kth column of L */ if (Flag [i] < mark) { PRINT2 ((" add Ci["ID"] = "ID"\n", lnz, i)) ; ASSERT (i > k) ; Ci [lnz++] = i ; Flag [i] = mark ; } /* apply the update to the kth column of L */ /* yj is equal to l_kj * d_j */ W [i] -= l_ij * yj ; } /* store the last value in the jth column of L */ Li [p] = li ; Lx [p] = lx ; Lnz [j]++ ; } } /* ---------------------------------------------------------------------- */ /* merge C with the pattern of the existing column of L */ /* ---------------------------------------------------------------------- */ /* This column should be zero, but it may contain explicit zero entries. * These entries should be kept, not dropped. */ p = Lp [k] ; pend = p + Lnz [k] ; for (p++ ; p < pend ; p++) { i = Li [p] ; /* add to the pattern of the kth column of L */ if (Flag [i] < mark) { PRINT2 ((" add Ci["ID"] = "ID" from existing col k\n", lnz, i)) ; ASSERT (i > k) ; Ci [lnz++] = i ; Flag [i] = mark ; } } /* ---------------------------------------------------------------------- */ if (do_solve) { Xx [k] = xk ; PRINT2 (("Xx [k] = %g\n", Xx [k])) ; } /* ---------------------------------------------------------------------- */ /* ensure abs (dk) >= dbound, if dbound is given */ /* ---------------------------------------------------------------------- */ dk = (IS_GT_ZERO (Common->dbound)) ? (CHOLMOD(dbound) (dk, Common)) : dk ; PRINT2 (("D [k = "ID"] = %g\n", k, dk)) ; /* ---------------------------------------------------------------------- */ /* store the kth column of L */ /* ---------------------------------------------------------------------- */ /* ensure the new column of L has enough space */ if (Lp [k] + lnz + 1 > Lp [Lnext [k]]) { PRINT1 (("New Col "ID" realloc, old Lnz "ID"\n", k, Lnz [k])) ; if (!CHOLMOD(reallocate_column) (k, lnz + 1, L, Common)) { /* out of memory, L is now simplicial symbolic */ CHOLMOD(clear_flag) (Common) ; for (i = 0 ; i < n ; i++) { W [i] = 0 ; } return (FALSE) ; } /* L->i and L->x may have moved */ Li = L->i ; Lx = L->x ; } ASSERT (Lp [k] + lnz + 1 <= Lp [Lnext [k]]) ; #ifndef NDEBUG PRINT2 (("\nPrior to sort: lnz "ID" (excluding diagonal)\n", lnz)) ; for (kk = 0 ; kk < lnz ; kk++) { i = Ci [kk] ; PRINT2 (("L ["ID"] kept: "ID" %e\n", kk, i, W [i] / dk)) ; } #endif /* sort Ci */ qsort (Ci, lnz, sizeof (Int), (int (*) (const void *, const void *)) icomp); /* store the kth column of L */ DEBUG (lastrow = k) ; p = Lp [k] ; Lx [p++] = dk ; Lnz [k] = lnz + 1 ; fl += lnz ; for (kk = 0 ; kk < lnz ; kk++, p++) { i = Ci [kk] ; PRINT2 (("L ["ID"] after sort: "ID", %e\n", kk, i, W [i] / dk)) ; ASSERT (i > lastrow) ; Li [p] = i ; Lx [p] = W [i] / dk ; W [i] = 0.0 ; DEBUG (lastrow = i) ; } /* compute DeltaB for updown (in DeltaB) */ if (do_solve) { p = Lp [k] ; pend = p + Lnz [k] ; for (p++ ; p < pend ; p++) { ASSERT (Li [p] > k) ; Nx [Li [p]] -= Lx [p] * xk ; } } /* clear the flag for the update */ mark = CHOLMOD(clear_flag) (Common) ; /* workspaces are now cleared */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 2*n, Common)) ; /* ---------------------------------------------------------------------- */ /* update/downdate */ /* ---------------------------------------------------------------------- */ /* update or downdate L (k+1:n, k+1:n) with the vector * C = L (:,k) * sqrt (abs (D [k])). * Do a numeric update if D[k] < 0, numeric downdate otherwise. */ ok = TRUE ; Common->modfl = 0 ; PRINT1 (("rowadd update lnz = "ID"\n", lnz)) ; if (lnz > 0) { do_update = IS_LT_ZERO (dk) ; if (do_update) { dk = -dk ; } sqrt_dk = sqrt (dk) ; p = Lp [k] + 1 ; for (kk = 0 ; kk < lnz ; kk++, p++) { Cx [kk] = Lx [p] * sqrt_dk ; } fl += lnz + 1 ; /* create a n-by-1 sparse matrix to hold the single column */ C = &Cmatrix ; C->nrow = n ; C->ncol = 1 ; C->nzmax = lnz ; C->sorted = TRUE ; C->packed = TRUE ; C->p = Cp ; C->i = Ci ; C->x = Cx ; C->nz = NULL ; C->itype = L->itype ; C->xtype = L->xtype ; C->dtype = L->dtype ; C->z = NULL ; C->stype = 0 ; Cp [0] = 0 ; Cp [1] = lnz ; /* numeric downdate if dk > 0, and optional Lx=b change */ /* workspace: Flag (nrow), Head (nrow+1), W (nrow), Iwork (2*nrow) */ ok = CHOLMOD(updown_mark) (do_update ? (1) : (0), C, colmark, L, X, DeltaB, Common) ; /* clear workspace */ for (kk = 0 ; kk < lnz ; kk++) { Cx [kk] = 0 ; } } Common->modfl += fl ; DEBUG (CHOLMOD(dump_factor) (L, "LDL factorization, L:", Common)) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 2*n, Common)) ; return (ok) ; } #endif igraph/src/CHOLMOD/Modify/t_cholmod_updown_numkr.c0000644000175100001440000005165213431000472021574 0ustar hornikusers/* ========================================================================== */ /* === Modify/t_cholmod_updown_numkr ======================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Modify Module. Copyright (C) 2005-2006, * Timothy A. Davis and William W. Hager. * The CHOLMOD/Modify Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Supernodal numerical update/downdate of rank K = RANK, along a single path. * This routine operates on a simplicial factor, but operates on adjacent * columns of L that would fit within a single supernode. "Adjacent" means * along a single path in the elimination tree; they may or may not be * adjacent in the matrix L. * * external defines: NUMERIC, WDIM, RANK. * * WDIM is 1, 2, 4, or 8. RANK can be 1 to WDIM. * * A simple method is included (#define SIMPLE). The code works, but is slow. * It is meant only to illustrate what this routine is doing. * * A rank-K update proceeds along a single path, using single-column, dual- * column, or quad-column updates of L. If a column j and the next column * in the path (its parent) do not have the same nonzero pattern, a single- * column update is used. If they do, but the 3rd and 4th column from j do * not have the same pattern, a dual-column update is used, in which the two * columns are treated as if they were a single supernode of two columns. If * there are 4 columns in the path that all have the same nonzero pattern, then * a quad-column update is used. All three kinds of updates can be used along * a single path, in a single call to this function. * * Single-column update: * * When updating a single column of L, each iteration of the for loop, * below, processes four rows of W (all columns involved) and one column * of L. Suppose we have a rank-5 update, and columns 2 through 6 of W * are involved. In this case, W in this routine is a pointer to column * 2 of the matrix W in the caller. W (in the caller, shown as 'W') is * held in row-major order, and is 8-by-n (a dense matrix storage format), * but shown below in column form to match the column of L. Suppose there * are 13 nonzero entries in column 27 of L, with row indices 27 (the * diagonal, D), 28, 30, 31, 42, 43, 44, 50, 51, 67, 81, 83, and 84. This * pattern is held in Li [Lp [27] ... Lp [27 + Lnz [27] - 1], where * Lnz [27] = 13. The modification of the current column j of L is done * in the following order. A dot (.) means the entry of W is not accessed. * * W0 points to row 27 of W, and G is a 1-by-8 temporary vector. * * G[0] G[4] * G x x x x x . . . * * W0 * | * v * 27 . . x x x x x . W0 points to W (27,2) * * * row 'W' W column j = 27 * | | | of L * v v v | * first iteration of for loop: v * * 28 . . 1 5 9 13 17 . x * 30 . . 2 6 10 14 18 . x * 31 . . 3 7 11 15 19 . x * 42 . . 4 8 12 16 20 . x * * second iteration of for loop: * * 43 . . 1 5 9 13 17 . x * 44 . . 2 6 10 14 18 . x * 50 . . 3 7 11 15 19 . x * 51 . . 4 8 12 16 20 . x * * third iteration of for loop: * * 67 . . 1 5 9 13 17 . x * 81 . . 2 6 10 14 18 . x * 83 . . 3 7 11 15 19 . x * 84 . . 4 8 12 16 20 . x * * If the number of offdiagonal nonzeros in column j of L is not divisible * by 4, then the switch-statement does the work for the first nz % 4 rows. * * Dual-column update: * * In this case, two columns of L that are adjacent in the path are being * updated, by 1 to 8 columns of W. Suppose columns j=27 and j=28 are * adjacent columns in the path (they need not be j and j+1). Two rows * of G and W are used as coefficients during the update: (G0, G1) and * (W0, W1). * * G0 x x x x x . . . * G1 x x x x x . . . * * 27 . . x x x x x . W0 points to W (27,2) * 28 . . x x x x x . W1 points to W (28,2) * * * row 'W' W0,W1 column j = 27 * | | | of L * v v v | * | |-- column j = 28 of L * v v * update L (j1,j): * * 28 . . 1 2 3 4 5 . x - ("-" is not stored in L) * * cleanup iteration since length is odd: * * 30 . . 1 2 3 4 5 . x x * * then each iteration does two rows of both columns of L: * * 31 . . 1 3 5 7 9 . x x * 42 . . 2 4 6 8 10 . x x * * 43 . . 1 3 5 7 9 . x x * 44 . . 2 4 6 8 10 . x x * * 50 . . 1 3 5 7 9 . x x * 51 . . 2 4 6 8 10 . x x * * 67 . . 1 3 5 7 9 . x x * 81 . . 2 4 6 8 10 . x x * * 83 . . 1 3 5 7 9 . x x * 84 . . 2 4 6 8 10 . x x * * If the number of offdiagonal nonzeros in column j of L is not even, * then the cleanup iteration does the work for the first row. * * Quad-column update: * * In this case, four columns of L that are adjacent in the path are being * updated, by 1 to 8 columns of W. Suppose columns j=27, 28, 30, and 31 * are adjacent columns in the path (they need not be j, j+1, ...). Four * rows of G and W are used as coefficients during the update: (G0 through * G3) and (W0 through W3). j=27, j1=28, j2=30, and j3=31. * * G0 x x x x x . . . * G1 x x x x x . . . * G3 x x x x x . . . * G4 x x x x x . . . * * 27 . . x x x x x . W0 points to W (27,2) * 28 . . x x x x x . W1 points to W (28,2) * 30 . . x x x x x . W2 points to W (30,2) * 31 . . x x x x x . W3 points to W (31,2) * * * row 'W' W0,W1,.. column j = 27 * | | | of L * v v v | * | |-- column j = 28 of L * | | |-- column j = 30 of L * | | | |-- column j = 31 of L * v v v v * update L (j1,j): * 28 . . 1 2 3 4 5 . x - - - * * update L (j2,j): * 30 . . 1 2 3 4 5 . # x - - (# denotes modified) * * update L (j2,j1) * 30 . . 1 2 3 4 5 . x # - - * * update L (j3,j) * 31 . . 1 2 3 4 5 . # x x - * * update L (j3,j1) * 31 . . 1 2 3 4 5 . x # x - * * update L (j3,j2) * 31 . . 1 2 3 4 5 . x x # - * * cleanup iteration since length is odd: * 42 . . 1 2 3 4 5 . x x x x * * * ----- CHOLMOD v1.1.1 did the following -------------------------------------- * then each iteration does two rows of all four colummns of L: * * 43 . . 1 3 5 7 9 . x x x x * 44 . . 2 4 6 8 10 . x x x x * * 50 . . 1 3 5 7 9 . x x x x * 51 . . 2 4 6 8 10 . x x x x * * 67 . . 1 3 5 7 9 . x x x x * 81 . . 2 4 6 8 10 . x x x x * * 83 . . 1 3 5 7 9 . x x x x * 84 . . 2 4 6 8 10 . x x x x * * ----- CHOLMOD v1.2.0 does the following ------------------------------------- * then each iteration does one rows of all four colummns of L: * * 43 . . 1 2 3 4 5 . x x x x * 44 . . 1 2 3 4 5 . x x x x * 50 . . 1 3 5 4 5 . x x x x * 51 . . 1 2 3 4 5 . x x x x * 67 . . 1 3 5 4 5 . x x x x * 81 . . 1 2 3 4 5 . x x x x * 83 . . 1 3 5 4 5 . x x x x * 84 . . 1 2 3 4 5 . x x x x * * This file is included in t_cholmod_updown.c, only. * It is not compiled separately. It contains no user-callable routines. * * workspace: Xwork (WDIM*nrow) */ /* ========================================================================== */ /* === loop unrolling macros ================================================ */ /* ========================================================================== */ #undef RANK1 #undef RANK2 #undef RANK3 #undef RANK4 #undef RANK5 #undef RANK6 #undef RANK7 #undef RANK8 #define RANK1(statement) statement #if RANK < 2 #define RANK2(statement) #else #define RANK2(statement) statement #endif #if RANK < 3 #define RANK3(statement) #else #define RANK3(statement) statement #endif #if RANK < 4 #define RANK4(statement) #else #define RANK4(statement) statement #endif #if RANK < 5 #define RANK5(statement) #else #define RANK5(statement) statement #endif #if RANK < 6 #define RANK6(statement) #else #define RANK6(statement) statement #endif #if RANK < 7 #define RANK7(statement) #else #define RANK7(statement) statement #endif #if RANK < 8 #define RANK8(statement) #else #define RANK8(statement) statement #endif #define FOR_ALL_K \ RANK1 (DO (0)) \ RANK2 (DO (1)) \ RANK3 (DO (2)) \ RANK4 (DO (3)) \ RANK5 (DO (4)) \ RANK6 (DO (5)) \ RANK7 (DO (6)) \ RANK8 (DO (7)) /* ========================================================================== */ /* === alpha/gamma ========================================================== */ /* ========================================================================== */ #undef ALPHA_GAMMA #define ALPHA_GAMMA(Dj,Alpha,Gamma,W) \ { \ double dj = Dj ; \ if (update) \ { \ for (k = 0 ; k < RANK ; k++) \ { \ double w = W [k] ; \ double alpha = Alpha [k] ; \ double a = alpha + (w * w) / dj ; \ dj *= a ; \ Alpha [k] = a ; \ Gamma [k] = (- w / dj) ; \ dj /= alpha ; \ } \ } \ else \ { \ for (k = 0 ; k < RANK ; k++) \ { \ double w = W [k] ; \ double alpha = Alpha [k] ; \ double a = alpha - (w * w) / dj ; \ dj *= a ; \ Alpha [k] = a ; \ Gamma [k] = w / dj ; \ dj /= alpha ; \ } \ } \ Dj = ((use_dbound) ? (CHOLMOD(dbound) (dj, Common)) : (dj)) ; \ } /* ========================================================================== */ /* === numeric update/downdate along one path =============================== */ /* ========================================================================== */ static void NUMERIC (WDIM, RANK) ( int update, /* TRUE for update, FALSE for downdate */ Int j, /* first column in the path */ Int e, /* last column in the path */ double Alpha [ ], /* alpha, for each column of W */ double W [ ], /* W is an n-by-WDIM array, stored in row-major order */ cholmod_factor *L, /* with unit diagonal (diagonal not stored) */ cholmod_common *Common ) { #ifdef SIMPLE #define w(row,col) W [WDIM*(row) + (col)] /* ---------------------------------------------------------------------- */ /* concise but slow version for illustration only */ /* ---------------------------------------------------------------------- */ double Gamma [WDIM] ; double *Lx ; Int *Li, *Lp, *Lnz ; Int p, k ; Int use_dbound = IS_GT_ZERO (Common->dbound) ; Li = L->i ; Lx = L->x ; Lp = L->p ; Lnz = L->nz ; /* walk up the etree from node j to its ancestor e */ for ( ; j <= e ; j = (Lnz [j] > 1) ? (Li [Lp [j] + 1]) : Int_max) { /* update the diagonal entry D (j,j) with each column of W */ ALPHA_GAMMA (Lx [Lp [j]], Alpha, Gamma, (&(w (j,0)))) ; /* update column j of L */ for (p = Lp [j] + 1 ; p < Lp [j] + Lnz [j] ; p++) { /* update row Li [p] of column j of L with each column of W */ Int i = Li [p] ; for (k = 0 ; k < RANK ; k++) { w (i,k) -= w (j,k) * Lx [p] ; Lx [p] -= Gamma [k] * w (i,k) ; } } /* clear workspace W */ for (k = 0 ; k < RANK ; k++) { w (j,k) = 0 ; } } #else /* ---------------------------------------------------------------------- */ /* dynamic supernodal version: supernodes detected dynamically */ /* ---------------------------------------------------------------------- */ double G0 [RANK], G1 [RANK], G2 [RANK], G3 [RANK] ; double Z0 [RANK], Z1 [RANK], Z2 [RANK], Z3 [RANK] ; double *W0, *W1, *W2, *W3, *Lx ; Int *Li, *Lp, *Lnz ; Int j1, j2, j3, p0, p1, p2, p3, parent, lnz, pend, k ; Int use_dbound = IS_GT_ZERO (Common->dbound) ; Li = L->i ; Lx = L->x ; Lp = L->p ; Lnz = L->nz ; /* walk up the etree from node j to its ancestor e */ for ( ; j <= e ; j = parent) { p0 = Lp [j] ; /* col j is Li,Lx [p0 ... p0+lnz-1] */ lnz = Lnz [j] ; W0 = W + WDIM * j ; /* pointer to row j of W */ pend = p0 + lnz ; /* for k = 0 to RANK-1 do: */ #define DO(k) Z0 [k] = W0 [k] ; FOR_ALL_K #undef DO /* for k = 0 to RANK-1 do: */ #define DO(k) W0 [k] = 0 ; FOR_ALL_K #undef DO /* update D (j,j) */ ALPHA_GAMMA (Lx [p0], Alpha, G0, Z0) ; p0++ ; /* determine how many columns of L to update at the same time */ parent = (lnz > 1) ? (Li [p0]) : Int_max ; if (parent <= e && lnz == Lnz [parent] + 1) { /* -------------------------------------------------------------- */ /* node j and its parent j1 can be updated at the same time */ /* -------------------------------------------------------------- */ j1 = parent ; j2 = (lnz > 2) ? (Li [p0+1]) : Int_max ; j3 = (lnz > 3) ? (Li [p0+2]) : Int_max ; W1 = W + WDIM * j1 ; /* pointer to row j1 of W */ p1 = Lp [j1] ; /* for k = 0 to RANK-1 do: */ #define DO(k) Z1 [k] = W1 [k] ; FOR_ALL_K #undef DO /* for k = 0 to RANK-1 do: */ #define DO(k) W1 [k] = 0 ; FOR_ALL_K #undef DO /* update L (j1,j) */ { double lx = Lx [p0] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ Z1 [k] -= Z0 [k] * lx ; \ lx -= G0 [k] * Z1 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx ; } /* update D (j1,j1) */ ALPHA_GAMMA (Lx [p1], Alpha, G1, Z1) ; p1++ ; /* -------------------------------------------------------------- */ /* update 2 or 4 columns of L */ /* -------------------------------------------------------------- */ if ((j2 <= e) && /* j2 in the current path */ (j3 <= e) && /* j3 in the current path */ (lnz == Lnz [j2] + 2) && /* column j2 matches */ (lnz == Lnz [j3] + 3)) /* column j3 matches */ { /* ---------------------------------------------------------- */ /* update 4 columns of L */ /* ---------------------------------------------------------- */ /* p0 and p1 currently point to row j2 in cols j and j1 of L */ parent = (lnz > 4) ? (Li [p0+2]) : Int_max ; W2 = W + WDIM * j2 ; /* pointer to row j2 of W */ W3 = W + WDIM * j3 ; /* pointer to row j3 of W */ p2 = Lp [j2] ; p3 = Lp [j3] ; /* for k = 0 to RANK-1 do: */ #define DO(k) Z2 [k] = W2 [k] ; FOR_ALL_K #undef DO /* for k = 0 to RANK-1 do: */ #define DO(k) Z3 [k] = W3 [k] ; FOR_ALL_K #undef DO /* for k = 0 to RANK-1 do: */ #define DO(k) W2 [k] = 0 ; FOR_ALL_K #undef DO /* for k = 0 to RANK-1 do: */ #define DO(k) W3 [k] = 0 ; FOR_ALL_K #undef DO /* update L (j2,j) and update L (j2,j1) */ { double lx [2] ; lx [0] = Lx [p0] ; lx [1] = Lx [p1] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ Z2 [k] -= Z0 [k] * lx [0] ; lx [0] -= G0 [k] * Z2 [k] ; \ Z2 [k] -= Z1 [k] * lx [1] ; lx [1] -= G1 [k] * Z2 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx [0] ; Lx [p1++] = lx [1] ; } /* update D (j2,j2) */ ALPHA_GAMMA (Lx [p2], Alpha, G2, Z2) ; p2++ ; /* update L (j3,j), L (j3,j1), and L (j3,j2) */ { double lx [3] ; lx [0] = Lx [p0] ; lx [1] = Lx [p1] ; lx [2] = Lx [p2] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ Z3 [k] -= Z0 [k] * lx [0] ; lx [0] -= G0 [k] * Z3 [k] ; \ Z3 [k] -= Z1 [k] * lx [1] ; lx [1] -= G1 [k] * Z3 [k] ; \ Z3 [k] -= Z2 [k] * lx [2] ; lx [2] -= G2 [k] * Z3 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx [0] ; Lx [p1++] = lx [1] ; Lx [p2++] = lx [2] ; } /* update D (j3,j3) */ ALPHA_GAMMA (Lx [p3], Alpha, G3, Z3) ; p3++ ; /* each iteration updates L (i, [j j1 j2 j3]) */ for ( ; p0 < pend ; p0++, p1++, p2++, p3++) { double lx [4], *w0 ; lx [0] = Lx [p0] ; lx [1] = Lx [p1] ; lx [2] = Lx [p2] ; lx [3] = Lx [p3] ; w0 = W + WDIM * Li [p0] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx [0] ; lx [0] -= G0 [k] * w0 [k] ; \ w0 [k] -= Z1 [k] * lx [1] ; lx [1] -= G1 [k] * w0 [k] ; \ w0 [k] -= Z2 [k] * lx [2] ; lx [2] -= G2 [k] * w0 [k] ; \ w0 [k] -= Z3 [k] * lx [3] ; lx [3] -= G3 [k] * w0 [k] ; FOR_ALL_K #undef DO Lx [p0] = lx [0] ; Lx [p1] = lx [1] ; Lx [p2] = lx [2] ; Lx [p3] = lx [3] ; } } else { /* ---------------------------------------------------------- */ /* update 2 columns of L */ /* ---------------------------------------------------------- */ parent = j2 ; /* cleanup iteration if length is odd */ if ((lnz - 2) % 2) { double lx [2] , *w0 ; lx [0] = Lx [p0] ; lx [1] = Lx [p1] ; w0 = W + WDIM * Li [p0] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx [0] ; lx [0] -= G0 [k] * w0 [k] ; \ w0 [k] -= Z1 [k] * lx [1] ; lx [1] -= G1 [k] * w0 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx [0] ; Lx [p1++] = lx [1] ; } for ( ; p0 < pend ; p0 += 2, p1 += 2) { double lx [2][2], w [2], *w0, *w1 ; lx [0][0] = Lx [p0 ] ; lx [1][0] = Lx [p0+1] ; lx [0][1] = Lx [p1 ] ; lx [1][1] = Lx [p1+1] ; w0 = W + WDIM * Li [p0 ] ; w1 = W + WDIM * Li [p0+1] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w [0] = w0 [k] - Z0 [k] * lx [0][0] ; \ w [1] = w1 [k] - Z0 [k] * lx [1][0] ; \ lx [0][0] -= G0 [k] * w [0] ; \ lx [1][0] -= G0 [k] * w [1] ; \ w0 [k] = w [0] -= Z1 [k] * lx [0][1] ; \ w1 [k] = w [1] -= Z1 [k] * lx [1][1] ; \ lx [0][1] -= G1 [k] * w [0] ; \ lx [1][1] -= G1 [k] * w [1] ; FOR_ALL_K #undef DO Lx [p0 ] = lx [0][0] ; Lx [p0+1] = lx [1][0] ; Lx [p1 ] = lx [0][1] ; Lx [p1+1] = lx [1][1] ; } } } else { /* -------------------------------------------------------------- */ /* update one column of L */ /* -------------------------------------------------------------- */ /* cleanup iteration if length is not a multiple of 4 */ switch ((lnz - 1) % 4) { case 1: { double lx , *w0 ; lx = Lx [p0] ; w0 = W + WDIM * Li [p0] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx ; lx -= G0 [k] * w0 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx ; } break ; case 2: { double lx [2], *w0, *w1 ; lx [0] = Lx [p0 ] ; lx [1] = Lx [p0+1] ; w0 = W + WDIM * Li [p0 ] ; w1 = W + WDIM * Li [p0+1] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx [0] ; \ w1 [k] -= Z0 [k] * lx [1] ; \ lx [0] -= G0 [k] * w0 [k] ; \ lx [1] -= G0 [k] * w1 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx [0] ; Lx [p0++] = lx [1] ; } break ; case 3: { double lx [3], *w0, *w1, *w2 ; lx [0] = Lx [p0 ] ; lx [1] = Lx [p0+1] ; lx [2] = Lx [p0+2] ; w0 = W + WDIM * Li [p0 ] ; w1 = W + WDIM * Li [p0+1] ; w2 = W + WDIM * Li [p0+2] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx [0] ; \ w1 [k] -= Z0 [k] * lx [1] ; \ w2 [k] -= Z0 [k] * lx [2] ; \ lx [0] -= G0 [k] * w0 [k] ; \ lx [1] -= G0 [k] * w1 [k] ; \ lx [2] -= G0 [k] * w2 [k] ; FOR_ALL_K #undef DO Lx [p0++] = lx [0] ; Lx [p0++] = lx [1] ; Lx [p0++] = lx [2] ; } } for ( ; p0 < pend ; p0 += 4) { double lx [4], *w0, *w1, *w2, *w3 ; lx [0] = Lx [p0 ] ; lx [1] = Lx [p0+1] ; lx [2] = Lx [p0+2] ; lx [3] = Lx [p0+3] ; w0 = W + WDIM * Li [p0 ] ; w1 = W + WDIM * Li [p0+1] ; w2 = W + WDIM * Li [p0+2] ; w3 = W + WDIM * Li [p0+3] ; /* for k = 0 to RANK-1 do: */ #define DO(k) \ w0 [k] -= Z0 [k] * lx [0] ; \ w1 [k] -= Z0 [k] * lx [1] ; \ w2 [k] -= Z0 [k] * lx [2] ; \ w3 [k] -= Z0 [k] * lx [3] ; \ lx [0] -= G0 [k] * w0 [k] ; \ lx [1] -= G0 [k] * w1 [k] ; \ lx [2] -= G0 [k] * w2 [k] ; \ lx [3] -= G0 [k] * w3 [k] ; FOR_ALL_K #undef DO Lx [p0 ] = lx [0] ; Lx [p0+1] = lx [1] ; Lx [p0+2] = lx [2] ; Lx [p0+3] = lx [3] ; } } } #endif } /* prepare this file for another inclusion in t_cholmod_updown.c: */ #undef RANK igraph/src/CHOLMOD/Modify/cholmod_updown.c0000644000175100001440000014336113431000472020034 0ustar hornikusers/* ========================================================================== */ /* === Modify/cholmod_updown ================================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Modify Module. * Copyright (C) 2005-2006, Timothy A. Davis and William W. Hager. * The CHOLMOD/Modify Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Updates/downdates the LDL' factorization (symbolic, then numeric), by * computing a new factorization of * * Lnew * Dnew * Lnew' = Lold * Dold * Lold' +/- C*C' * * C must be sorted. It can be either packed or unpacked. As in all CHOLMOD * routines, the columns of L are sorted on input, and also on output. * * If the factor is not an unpacked LDL' or dynamic LDL', it is converted * to an LDL' dynamic factor. An unpacked LDL' factor may be updated, but if * any one column runs out of space, the factor is converted to an LDL' * dynamic one. If the initial conversion fails, the factor is returned * unchanged. * * If memory runs out during the update, the factor is returned as a simplicial * symbolic factor. That is, everything is freed except for the fill-reducing * ordering and its corresponding column counts (typically computed by * cholmod_analyze). * * Note that the fill-reducing permutation L->Perm is NOT used. The row * indices of C refer to the rows of L, not A. If your original system is * LDL' = PAP' (where P = L->Perm), and you want to compute the LDL' * factorization of A+CC', then you must permute C first. That is: * * PAP' = LDL' * P(A+CC')P' = PAP'+PCC'P' = LDL' + (PC)(PC)' = LDL' + Cnew*Cnew' * where Cnew = P*C. * * You can use the cholmod_submatrix routine in the MatrixOps module * to permute C, with: * * Cnew = cholmod_submatrix (C, L->Perm, L->n, NULL, -1, TRUE, TRUE, Common) ; * * Note that the sorted input parameter to cholmod_submatrix must be TRUE, * because cholmod_updown requires C with sorted columns. * * The system Lx=b can also be updated/downdated. The old system was Lold*x=b. * The new system is Lnew*xnew = b + deltab. The old solution x is overwritten * with xnew. Note that as in the update/downdate of L itself, the fill- * reducing permutation L->Perm is not used. x and b are in the permuted * ordering, not your original ordering. x and b are n-by-1; this routine * does not handle multiple right-hand-sides. * * workspace: Flag (nrow), Head (nrow+1), W (maxrank*nrow), Iwork (nrow), * where maxrank is 2, 4, or 8. * * Only real matrices are supported. A symbolic L is converted into a * numeric identity matrix. */ #ifndef NMODIFY #include "cholmod_internal.h" #include "cholmod_modify.h" /* ========================================================================== */ /* === cholmod_updown ======================================================= */ /* ========================================================================== */ /* Compute the new LDL' factorization of LDL'+CC' (an update) or LDL'-CC' * (a downdate). The factor object L need not be an LDL' factorization; it * is converted to one if it isn't. */ int CHOLMOD(updown) ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(updown_mask) (update, C, NULL, NULL, L, NULL, NULL, Common)) ; } /* ========================================================================== */ /* === cholmod_updown_solve ================================================= */ /* ========================================================================== */ /* Does the same as cholmod_updown, except that it also updates/downdates the * solution to Lx=b+DeltaB. x and b must be n-by-1 dense matrices. b is not * need as input to this routine, but a sparse change to b is (DeltaB). Only * entries in DeltaB corresponding to columns modified in L are accessed; the * rest are ignored. */ int CHOLMOD(updown_solve) ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(updown_mask) (update, C, NULL, NULL, L, X, DeltaB, Common)) ; } /* ========================================================================== */ /* === Power2 =============================================================== */ /* ========================================================================== */ /* Power2 [i] is smallest power of 2 that is >= i (for i in range 0 to 8) */ static Int Power2 [ ] = { /* 0 1 2 3 4 5 6 7 8 */ 0, 1, 2, 4, 4, 8, 8, 8, 8 } ; /* ========================================================================== */ /* === debug routines ======================================================= */ /* ========================================================================== */ #ifndef NDEBUG static void dump_set (Int s, Int **Set_ps1, Int **Set_ps2, Int j, Int n, cholmod_common *Common) { Int *p, len, i, ilast ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return ; } len = Set_ps2 [s] - Set_ps1 [s] ; PRINT2 (("Set s: "ID" len: "ID":", s, len)) ; ASSERT (len > 0) ; ilast = j ; for (p = Set_ps1 [s] ; p < Set_ps2 [s] ; p++) { i = *p ; PRINT3 ((" "ID"", i)) ; ASSERT (i > ilast && i < n) ; ilast = i ; } PRINT3 (("\n")) ; } static void dump_col ( char *w, Int j, Int p1, Int p2, Int *Li, double *Lx, Int n, cholmod_common *Common ) { Int p, row, lastrow ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return ; } PRINT3 (("\n\nDUMP COL==== j = "ID" %s: p1="ID" p2="ID" \n", j, w, p1,p2)); lastrow = -1 ; for (p = p1 ; p < p2 ; p++) { PRINT3 ((" "ID": ", p)) ; row = Li [p] ; PRINT3 ((""ID" ", Li [p])) ; PRINT3 (("%g ", Lx [p])) ; PRINT3 (("\n")) ; ASSERT (row > lastrow && row < n) ; lastrow = row ; } ASSERT (p1 < p2) ; ASSERT (Li [p1] == j) ; PRINT3 (("\n")) ; } #endif /* ========================================================================== */ /* === a path =============================================================== */ /* ========================================================================== */ /* A path is a set of nodes of the etree which are all affected by the same * columns of C. */ typedef struct Path_struct { Int start ; /* column at which to start, or EMPTY if initial */ Int end ; /* column at which to end, or EMPTY if initial */ Int ccol ; /* column of C to which path refers */ Int parent ; /* parent path */ Int c ; /* child of j along this path */ Int next ; /* next path in link list */ Int rank ; /* number of rank-1 paths merged onto this path */ Int order ; /* dfs order of this path */ Int wfirst ; /* first column of W to affect this path */ Int pending ; /* column at which the path is pending */ Int botrow ; /* for partial update/downdate of solution to Lx=b */ } Path_type ; /* ========================================================================== */ /* === dfs ================================================================== */ /* ========================================================================== */ /* Compute the DFS order of the set of paths. This can be recursive because * there are at most 23 paths to sort: one for each column of C (8 at most), * and one for each node in a balanced binary tree with 8 leaves (15). * Stack overflow is thus not a problem. */ static void dfs ( Path_type *Path, /* the set of Paths */ Int k, /* the rank of the update/downdate */ Int path, /* which path to work on */ Int *path_order, /* the current path order */ Int *w_order, /* the current order of the columns of W */ Int depth, Int npaths /* total number of paths */ ) { Int c ; /* child path */ ASSERT (path >= 0 && path < npaths) ; if (path < k) { /* this is a leaf node, corresponding to column W (:,path) */ /* and column C (:, Path [path].ccol) */ ASSERT (Path [path].ccol >= 0) ; Path [path].wfirst = *w_order ; Path [path].order = *w_order ; (*w_order)++ ; } else { /* this is a non-leaf path, within the tree */ ASSERT (Path [path].c != EMPTY) ; ASSERT (Path [path].ccol == EMPTY) ; /* order each child path */ for (c = Path [path].c ; c != EMPTY ; c = Path [c].next) { dfs (Path, k, c, path_order, w_order, depth+1, npaths) ; if (Path [path].wfirst == EMPTY) { Path [path].wfirst = Path [c].wfirst ; } } /* order this path next */ Path [path].order = (*path_order)++ ; } } /* ========================================================================== */ /* === numeric update/downdate routines ===================================== */ /* ========================================================================== */ #define WDIM 1 #include "t_cholmod_updown.c" #define WDIM 2 #include "t_cholmod_updown.c" #define WDIM 4 #include "t_cholmod_updown.c" #define WDIM 8 #include "t_cholmod_updown.c" /* ========================================================================== */ /* === cholmod_updown_mark ================================================== */ /* ========================================================================== */ /* Update/downdate LDL' +/- C*C', and update/downdate selected portions of the * solution to Lx=b. * * The original system is L*x = b. The new system is Lnew*xnew = b + deltab. * deltab(i) can be nonzero only if column i of L is modified by the update/ * downdate. If column i is not modified, the deltab(i) is not accessed. * * The solution to Lx=b is not modified if either X or DeltaB are NULL. * * Rowmark and colmark: * -------------------- * * rowmark and colmark affect which portions of L take part in the update/ * downdate of the solution to Lx=b. They do not affect how L itself is * updated/downdated. They are both ignored if X or DeltaB are NULL. * * If not NULL, rowmark is an integer array of size n where L is n-by-n. * rowmark [j] defines the part of column j of L that takes part in the update/ * downdate of the forward solve, Lx=b. Specifically, if i = rowmark [j], * then L(j:i-1,j) is used, and L(i:end,j) is ignored. * * If not NULL, colmark is an integer array of size C->ncol. colmark [ccol] * for a column C(:,ccol) redefines those parts of L that take part in the * update/downdate of Lx=b. Each column of C affects a set of columns of L. * If column ccol of C affects column j of L, then the new rowmark [j] of * column j of L is defined as colmark [ccol]. In a multiple-rank update/ * downdate, if two or more columns of C affect column j, its new rowmark [j] * is the colmark of the least-numbered column of C. colmark is ignored if * it is NULL, in which case rowmark is not modified. If colmark [ccol] is * EMPTY (-1), then rowmark is not modified for that particular column of C. * colmark is ignored if it is NULL, or rowmark, X, or DeltaB are NULL. * * The algorithm for modifying the solution to Lx=b when rowmark and colmark * are NULL is as follows: * * for each column j of L that is modified: * deltab (j:end) += L (j:end,j) * x(j) * modify L * for each column j of L that is modified: * x (j) = deltab (j) * deltab (j) = 0 * deltab (j+1:end) -= L (j+1:end,j) * x(j) * * If rowmark is non-NULL but colmark is NULL: * * for each column j of L that is modified: * deltab (j:rowmark(j)-1) += L (j:rowmark(j)-1,j) * x(j) * modify L * for each column j of L that is modified: * x (j) = deltab (j) * deltab (j) = 0 * deltab (j+1:rowmark(j)-1) -= L (j+1:rowmark(j)-1,j) * x(j) * * If both rowmark and colmark are non-NULL: * * for each column j of L that is modified: * deltab (j:rowmark(j)-1) += L (j:rowmark(j)-1,j) * x(j) * modify L * for each column j of L that is modified: * modify rowmark (j) according to colmark * for each column j of L that is modified: * x (j) = deltab (j) * deltab (j) = 0 * deltab (j+1:rowmark(j)-1) -= L (j+1:rowmark(j)-1,j) * x(j) * * Note that if the rank of C exceeds k = Common->maxrank (which is 2, 4, or 8), * then the update/downdate is done as a series of rank-k updates. In this * case, the above algorithm is repeated for each block of k columns of C. * * Unless it leads to no changes in rowmark, colmark should be used only if * C->ncol <= Common->maxrank, because the update/downdate is done with maxrank * columns at a time. Otherwise, the results are undefined. * * This routine is an "expert" routine. It is meant for use in LPDASA only. */ int CHOLMOD(updown_mark) ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ Int *colmark, /* Int array of size n. */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(updown_mask) (update, C, colmark, NULL, L, X, DeltaB, Common)) ; } /* ========================================================================== */ /* === cholmod_updown_mask ================================================== */ /* ========================================================================== */ int CHOLMOD(updown_mask) ( /* ---- input ---- */ int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* the incoming sparse update */ Int *colmark, /* Int array of size n. See cholmod_updown.c */ Int *mask, /* size n */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { double xj, fl ; double *Lx, *W, *Xx, *Nx ; Int *Li, *Lp, *Lnz, *Cp, *Ci, *Cnz, *Head, *Flag, *Stack, *Lnext, *Iwork, *Set_ps1 [32], *Set_ps2 [32], *ps1, *ps2 ; size_t maxrank ; Path_type OrderedPath [32], Path [32] ; Int n, wdim, k1, k2, npaths, i, j, row, packed, ccol, p, cncol, do_solve, mark, jj, j2, kk, nextj, p1, p2, c, use_colmark, newlnz, k, newpath, path_order, w_order, scattered, path, newparent, pp1, pp2, smax, maxrow, row1, nsets, s, p3, newlnz1, Set [32], top, len, lnz, m, botrow ; size_t w ; int ok = TRUE ; DEBUG (Int oldparent) ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (C, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (C, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; n = L->n ; cncol = C->ncol ; if (!(C->sorted)) { ERROR (CHOLMOD_INVALID, "C must have sorted columns") ; return (FALSE) ; } if (n != (Int) (C->nrow)) { ERROR (CHOLMOD_INVALID, "C and L dimensions do not match") ; return (FALSE) ; } do_solve = (X != NULL) && (DeltaB != NULL) ; if (do_solve) { RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (DeltaB, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; Xx = X->x ; Nx = DeltaB->x ; if (X->nrow != L->n || X->ncol != 1 || DeltaB->nrow != L->n || DeltaB->ncol != 1 || Xx == NULL || Nx == NULL) { ERROR (CHOLMOD_INVALID, "X and/or DeltaB invalid") ; return (FALSE) ; } } else { Xx = NULL ; Nx = NULL ; } Common->status = CHOLMOD_OK ; Common->modfl = 0 ; fl = 0 ; use_colmark = (colmark != NULL) ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* Note: cholmod_rowadd and cholmod_rowdel use the second n doubles in * Common->Xwork for Cx, and then perform a rank-1 update here, which uses * the first n doubles in Common->Xwork. Both the rowadd and rowdel * routines allocate enough workspace so that Common->Xwork isn't destroyed * below. Also, both cholmod_rowadd and cholmod_rowdel use the second n * ints in Common->Iwork for Ci. */ /* make sure maxrank is in the proper range */ maxrank = CHOLMOD(maxrank) (n, Common) ; k = MIN (cncol, (Int) maxrank) ; /* maximum k is wdim */ wdim = Power2 [k] ; /* number of columns needed in W */ ASSERT (wdim <= (Int) maxrank) ; PRINT1 (("updown wdim final "ID" k "ID"\n", wdim, k)) ; /* w = wdim * n */ w = CHOLMOD(mult_size_t) (n, wdim, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, n, w, Common) ; if (Common->status < CHOLMOD_OK || maxrank == 0) { /* out of memory, L is returned unchanged */ return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* convert to simplicial numeric LDL' factor, if not already */ /* ---------------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN || L->is_super || L->is_ll) { /* can only update/downdate a simplicial LDL' factorization */ CHOLMOD(change_factor) (CHOLMOD_REAL, FALSE, FALSE, FALSE, FALSE, L, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory, L is returned unchanged */ return (FALSE) ; } } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; PRINT1 (("updown, rank %g update %d\n", (double) C->ncol, update)) ; DEBUG (CHOLMOD(dump_factor) (L, "input L for updown", Common)) ; ASSERT (CHOLMOD(dump_sparse) (C, "input C for updown", Common) >= 0) ; Ci = C->i ; Cp = C->p ; Cnz = C->nz ; packed = C->packed ; ASSERT (IMPLIES (!packed, Cnz != NULL)) ; /* ---------------------------------------------------------------------- */ /* quick return */ /* ---------------------------------------------------------------------- */ if (cncol <= 0 || n == 0) { /* nothing to do */ return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* get L */ /* ---------------------------------------------------------------------- */ Li = L->i ; Lx = L->x ; Lp = L->p ; Lnz = L->nz ; Lnext = L->next ; ASSERT (Lnz != NULL) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ Flag = Common->Flag ; /* size n, Flag [i] <= mark must hold */ Head = Common->Head ; /* size n, Head [i] == EMPTY must hold */ W = Common->Xwork ; /* size n-by-wdim, zero on input and output*/ /* note that Iwork [n .. 2*n-1] (i/i/l) may be in use in rowadd/rowdel: */ Iwork = Common->Iwork ; Stack = Iwork ; /* size n, uninitialized (i/i/l) */ /* ---------------------------------------------------------------------- */ /* entire rank-cncol update, done as a sequence of rank-k updates */ /* ---------------------------------------------------------------------- */ ps1 = NULL ; ps2 = NULL ; for (k1 = 0 ; k1 < cncol ; k1 += k) { /* ------------------------------------------------------------------ */ /* get the next k columns of C for the update/downdate */ /* ------------------------------------------------------------------ */ /* the last update/downdate might be less than rank-k */ if (k > cncol - k1) { k = cncol - k1 ; wdim = Power2 [k] ; } k2 = k1 + k - 1 ; /* workspaces are in the following state, on input and output */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, wdim, Common)) ; /* ------------------------------------------------------------------ */ /* create a zero-length path for each column of W */ /* ------------------------------------------------------------------ */ nextj = n ; path = 0 ; for (ccol = k1 ; ccol <= k2 ; ccol++) { PRINT1 (("Column ["ID"]: "ID"\n", path, ccol)) ; ASSERT (ccol >= 0 && ccol <= cncol) ; pp1 = Cp [ccol] ; pp2 = (packed) ? (Cp [ccol+1]) : (pp1 + Cnz [ccol]) ; /* get the row index j of the first entry in C (:,ccol) */ if (pp2 > pp1) { /* Column ccol of C has at least one entry. */ j = Ci [pp1] ; } else { /* Column ccol of C is empty. Pretend it has one entry in * the last column with numerical value of zero. */ j = n-1 ; } ASSERT (j >= 0 && j < n) ; /* find first column to work on */ nextj = MIN (nextj, j) ; Path [path].ccol = ccol ; /* which column of C this path is for */ Path [path].start = EMPTY ; /* paths for C have zero length */ Path [path].end = EMPTY ; Path [path].parent = EMPTY ; /* no parent yet */ Path [path].rank = 1 ; /* one column of W */ Path [path].c = EMPTY ; /* no child of this path (case A) */ Path [path].next = Head [j] ; /* this path is pending at col j */ Path [path].pending = j ; /* this path is pending at col j */ Head [j] = path ; /* this path is pending at col j */ PRINT1(("Path "ID" starts: start "ID" end "ID" parent "ID" c "ID"" "j "ID" ccol "ID"\n", path, Path [path].start, Path [path].end, Path [path].parent, Path [path].c, j, ccol)) ; /* initialize botrow for this path */ Path [path].botrow = (use_colmark) ? colmark [ccol] : n ; path++ ; } /* we start with paths 0 to k-1. Next one (now unused) is npaths */ npaths = k ; j = nextj ; ASSERT (j < n) ; scattered = FALSE ; /* ------------------------------------------------------------------ */ /* symbolic update of columns of L */ /* ------------------------------------------------------------------ */ while (j < n) { ASSERT (j >= 0 && j < n && Lnz [j] > 0) ; /* the old column, Li [p1..p2-1]. D (j,j) is stored in Lx [p1] */ p1 = Lp [j] ; newlnz = Lnz [j] ; p2 = p1 + newlnz ; #ifndef NDEBUG PRINT1 (("\n=========Column j="ID" p1 "ID" p2 "ID" lnz "ID" \n", j, p1, p2, newlnz)) ; dump_col ("Old", j, p1, p2, Li, Lx, n, Common) ; oldparent = (Lnz [j] > 1) ? (Li [p1 + 1]) : EMPTY ; ASSERT (CHOLMOD(dump_work) (TRUE, FALSE, 0, Common)) ; ASSERT (!scattered) ; PRINT1 (("Col "ID": Checking paths, npaths: "ID"\n", j, npaths)) ; for (kk = 0 ; kk < npaths ; kk++) { Int kk2, found, j3 = Path [kk].pending ; PRINT2 (("Path "ID" pending at "ID".\n", kk, j3)) ; if (j3 != EMPTY) { /* Path kk must be somewhere in link list for column j3 */ ASSERT (Head [j3] != EMPTY) ; PRINT3 ((" List at "ID": ", j3)) ; found = FALSE ; for (kk2 = Head [j3] ; kk2 != EMPTY ; kk2 = Path [kk2].next) { PRINT3 ((""ID" ", kk2)) ; ASSERT (Path [kk2].pending == j3) ; found = found || (kk2 == kk) ; } PRINT3 (("\n")) ; ASSERT (found) ; } } PRINT1 (("\nCol "ID": Paths at this column, head "ID"\n", j, Head [j])); ASSERT (Head [j] != EMPTY) ; for (kk = Head [j] ; kk != EMPTY ; kk = Path [kk].next) { PRINT1 (("path "ID": (c="ID" j="ID") npaths "ID"\n", kk, Path[kk].c, j, npaths)) ; ASSERT (kk >= 0 && kk < npaths) ; ASSERT (Path [kk].pending == j) ; } #endif /* -------------------------------------------------------------- */ /* determine the path we're on */ /* -------------------------------------------------------------- */ /* get the first old path at column j */ path = Head [j] ; /* -------------------------------------------------------------- */ /* update/downdate of forward solve, Lx=b */ /* -------------------------------------------------------------- */ if (do_solve) { xj = Xx [j] ; if (IS_NONZERO (xj)) { xj = Xx [j] ; /* This is first time column j has been seen for entire */ /* rank-k update/downdate. */ /* DeltaB += Lold (j:botrow-1,j) * X (j) */ Nx [j] += xj ; /* diagonal of L */ /* find the botrow for this column */ botrow = (use_colmark) ? Path [path].botrow : n ; for (p = p1 + 1 ; p < p2 ; p++) { i = Li [p] ; if (i >= botrow) { break ; } Nx [i] += Lx [p] * xj ; } /* clear X[j] to flag col j of Lold as having been seen. If * X (j) was initially zero, then the above code is never * executed for column j. This is safe, since if xj=0 the * code above does not do anything anyway. */ Xx [j] = 0.0 ; } } /* -------------------------------------------------------------- */ /* start a new path at this column if two or more paths merge */ /* -------------------------------------------------------------- */ newpath = /* start a new path if paths have merged */ (Path [path].next != EMPTY) /* or if j is the first node on a path (case A). */ || (Path [path].c == EMPTY) ; if (newpath) { /* get the botrow of the first path at column j */ botrow = (use_colmark) ? Path [path].botrow : n ; path = npaths++ ; ASSERT (npaths <= 3*k) ; Path [path].ccol = EMPTY ; /* no single col of C for this path*/ Path [path].start = j ; /* path starts at this column j */ Path [path].end = EMPTY ; /* don't know yet where it ends */ Path [path].parent = EMPTY ;/* don't know parent path yet */ Path [path].rank = 0 ; /* rank is sum of child path ranks */ PRINT1 (("Path "ID" starts: start "ID" end "ID" parent "ID"\n", path, Path [path].start, Path [path].end, Path [path].parent)) ; /* set the botrow of the new path */ Path [path].botrow = (use_colmark) ? botrow : n ; } /* -------------------------------------------------------------- */ /* for each path kk pending at column j */ /* -------------------------------------------------------------- */ /* make a list of the sets that need to be merged into column j */ nsets = 0 ; for (kk = Head [j] ; kk != EMPTY ; kk = Path [kk].next) { /* ---------------------------------------------------------- */ /* path kk is at (c,j) */ /* ---------------------------------------------------------- */ c = Path [kk].c ; ASSERT (c < j) ; PRINT1 (("TUPLE on path "ID" (c="ID" j="ID")\n", kk, c, j)) ; ASSERT (Path [kk].pending == j) ; if (newpath) { /* finalize path kk and find rank of this path */ Path [kk].end = c ; /* end of old path is previous node c */ Path [kk].parent = path ; /* parent is this path */ Path [path].rank += Path [kk].rank ; /* sum up ranks */ Path [kk].pending = EMPTY ; PRINT1 (("Path "ID" done:start "ID" end "ID" parent "ID"\n", kk, Path [kk].start, Path [kk].end, Path [kk].parent)) ; } if (c == EMPTY) { /* ------------------------------------------------------ */ /* CASE A: first node in path */ /* ------------------------------------------------------ */ /* update: add pattern of incoming column */ /* Column ccol of C is in Ci [pp1 ... pp2-1] */ ccol = Path [kk].ccol ; pp1 = Cp [ccol] ; pp2 = (packed) ? (Cp [ccol+1]) : (pp1 + Cnz [ccol]) ; PRINT1 (("Case A, ccol = "ID" len "ID"\n", ccol, pp2-pp1)) ; ASSERT (IMPLIES (pp2 > pp1, Ci [pp1] == j)) ; if (!scattered) { /* scatter the original pattern of column j of L */ for (p = p1 ; p < p2 ; p++) { Flag [Li [p]] = mark ; } scattered = TRUE ; } /* scatter column ccol of C (skip first entry, j) */ newlnz1 = newlnz ; for (p = pp1 + 1 ; p < pp2 ; p++) { row = Ci [p] ; if (Flag [row] < mark) { /* this is a new entry in Lj' */ Flag [row] = mark ; newlnz++ ; } } if (newlnz1 != newlnz) { /* column ccol of C adds something to column j of L */ Set [nsets++] = FLIP (ccol) ; } } else if (Head [c] == 1) { /* ------------------------------------------------------ */ /* CASE B: c is old, but changed, child of j */ /* CASE C: new child of j */ /* ------------------------------------------------------ */ /* Head [c] is 1 if col c of L has new entries, * EMPTY otherwise */ Flag [c] = 0 ; Head [c] = EMPTY ; /* update: add Lc' */ /* column c of L is in Li [pp1 .. pp2-1] */ pp1 = Lp [c] ; pp2 = pp1 + Lnz [c] ; PRINT1 (("Case B/C: c = "ID"\n", c)) ; DEBUG (dump_col ("Child", c, pp1, pp2, Li, Lx, n, Common)) ; ASSERT (j == Li [pp1 + 1]) ; /* j is new parent of c */ if (!scattered) { /* scatter the original pattern of column j of L */ for (p = p1 ; p < p2 ; p++) { Flag [Li [p]] = mark ; } scattered = TRUE ; } /* scatter column c of L (skip first two entries, c and j)*/ newlnz1 = newlnz ; for (p = pp1 + 2 ; p < pp2 ; p++) { row = Li [p] ; if (Flag [row] < mark) { /* this is a new entry in Lj' */ Flag [row] = mark ; newlnz++ ; } } PRINT2 (("\n")) ; if (newlnz1 != newlnz) { /* column c of L adds something to column j of L */ Set [nsets++] = c ; } } } /* -------------------------------------------------------------- */ /* update the pattern of column j of L */ /* -------------------------------------------------------------- */ /* Column j of L will be in Li/Lx [p1 .. p3-1] */ p3 = p1 + newlnz ; ASSERT (IMPLIES (nsets == 0, newlnz == Lnz [j])) ; PRINT1 (("p1 "ID" p2 "ID" p3 "ID" nsets "ID"\n", p1, p2, p3,nsets)); /* -------------------------------------------------------------- */ /* ensure we have enough space for the longer column */ /* -------------------------------------------------------------- */ if (nsets > 0 && p3 > Lp [Lnext [j]]) { PRINT1 (("Col realloc: j "ID" newlnz "ID"\n", j, newlnz)) ; if (!CHOLMOD(reallocate_column) (j, newlnz, L, Common)) { /* out of memory, L is now simplicial symbolic */ CHOLMOD(clear_flag) (Common) ; for (j = 0 ; j <= n ; j++) { Head [j] = EMPTY ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, wdim, Common)) ; return (FALSE) ; } /* L->i and L->x may have moved. Column j has moved too */ Li = L->i ; Lx = L->x ; p1 = Lp [j] ; p2 = p1 + Lnz [j] ; p3 = p1 + newlnz ; } /* -------------------------------------------------------------- */ /* create set pointers */ /* -------------------------------------------------------------- */ for (s = 0 ; s < nsets ; s++) { /* Pattern of Set s is *(Set_ps1 [s] ... Set_ps2 [s]-1) */ c = Set [s] ; if (c < EMPTY) { /* column ccol of C, skip first entry (j) */ ccol = FLIP (c) ; pp1 = Cp [ccol] ; pp2 = (packed) ? (Cp [ccol+1]) : (pp1 + Cnz [ccol]) ; ASSERT (pp2 - pp1 > 1) ; Set_ps1 [s] = &(Ci [pp1 + 1]) ; Set_ps2 [s] = &(Ci [pp2]) ; PRINT1 (("set "ID" is ccol "ID"\n", s, ccol)) ; } else { /* column c of L, skip first two entries (c and j) */ pp1 = Lp [c] ; pp2 = pp1 + Lnz [c] ; ASSERT (Lnz [c] > 2) ; Set_ps1 [s] = &(Li [pp1 + 2]) ; Set_ps2 [s] = &(Li [pp2]) ; PRINT1 (("set "ID" is L "ID"\n", s, c)) ; } DEBUG (dump_set (s, Set_ps1, Set_ps2, j, n, Common)) ; } /* -------------------------------------------------------------- */ /* multiset merge */ /* -------------------------------------------------------------- */ /* Merge the sets into a single sorted set, Lj'. Before the merge * starts, column j is located in Li/Lx [p1 ... p2-1] and the * space Li/Lx [p2 ... p3-1] is empty. p1 is Lp [j], p2 is * Lp [j] + Lnz [j] (the old length of the column), and p3 is * Lp [j] + newlnz (the new and longer length of the column). * * The sets 0 to nsets-1 are defined by the Set_ps1 and Set_ps2 * pointers. Set s is located in *(Set_ps1 [s] ... Set_ps2 [s]-1). * It may be a column of C, or a column of L. All row indices i in * the sets are in the range i > j and i < n. All sets are sorted. * * The merge into column j of L is done in place. * * During the merge, p2 and p3 are updated. Li/Lx [p1..p2-1] * reflects the indices of the old column j of L that are yet to * be merged into the new column. Entries in their proper place in * the new column j of L are located in Li/Lx [p3 ... p1+newlnz-1]. * The merge finishes when p2 == p3. * * During the merge, set s consumed as it is merged into column j of * L. Its unconsumed contents are *(Set_ps1 [s] ... Set_ps2 [s]-1). * When a set is completely consumed, it is removed from the set of * sets, and nsets is decremented. * * The multiset merge and 2-set merge finishes when p2 == p3. */ PRINT1 (("Multiset merge p3 "ID" p2 "ID" nsets "ID"\n", p3, p2, nsets)) ; while (p3 > p2 && nsets > 1) { #ifndef NDEBUG PRINT2 (("\nMultiset merge. nsets = "ID"\n", nsets)) ; PRINT2 (("Source col p1 = "ID", p2 = "ID", p3= "ID"\n", p1, p2, p3)) ; for (p = p1 + 1 ; p < p2 ; p++) { PRINT2 ((" p: "ID" source row "ID" %g\n", p, Li[p], Lx[p])) ; ASSERT (Li [p] > j && Li [p] < n) ; } PRINT2 (("---\n")) ; for (p = p3 ; p < p1 + newlnz ; p++) { PRINT2 ((" p: "ID" target row "ID" %g\n", p, Li[p], Lx[p])) ; ASSERT (Li [p] > j && Li [p] < n) ; } for (s = 0 ; s < nsets ; s++) { dump_set (s, Set_ps1, Set_ps2, j, n, Common) ; } #endif /* get the entry at the tail end of source column Lj */ row1 = Li [p2 - 1] ; ASSERT (row1 >= j && p2 >= p1) ; /* find the largest row in all the sets */ maxrow = row1 ; smax = EMPTY ; for (s = nsets-1 ; s >= 0 ; s--) { ASSERT (Set_ps1 [s] < Set_ps2 [s]) ; row = *(Set_ps2 [s] - 1) ; if (row == maxrow) { /* skip past this entry in set s (it is a duplicate) */ Set_ps2 [s]-- ; if (Set_ps1 [s] == Set_ps2 [s]) { /* nothing more in this set */ nsets-- ; Set_ps1 [s] = Set_ps1 [nsets] ; Set_ps2 [s] = Set_ps2 [nsets] ; if (smax == nsets) { /* Set smax redefined; it is now this set */ smax = s ; } } } else if (row > maxrow) { maxrow = row ; smax = s ; } } ASSERT (maxrow > j) ; /* move the row onto the stack of the target column */ if (maxrow == row1) { /* next entry is in Lj, move to the bottom of Lj' */ ASSERT (smax == EMPTY) ; p2-- ; p3-- ; Li [p3] = maxrow ; Lx [p3] = Lx [p2] ; } else { /* new entry in Lj' */ ASSERT (smax >= 0 && smax < nsets) ; Set_ps2 [smax]-- ; p3-- ; Li [p3] = maxrow ; Lx [p3] = 0.0 ; if (Set_ps1 [smax] == Set_ps2 [smax]) { /* nothing more in this set */ nsets-- ; Set_ps1 [smax] = Set_ps1 [nsets] ; Set_ps2 [smax] = Set_ps2 [nsets] ; PRINT1 (("Set "ID" now empty\n", smax)) ; } } } /* -------------------------------------------------------------- */ /* 2-set merge: */ /* -------------------------------------------------------------- */ /* This the same as the multi-set merge, except there is only one * set s = 0 left. The source column j and the set 0 are being * merged into the target column j. */ if (nsets > 0) { ps1 = Set_ps1 [0] ; ps2 = Set_ps2 [0] ; } while (p3 > p2) { #ifndef NDEBUG PRINT2 (("\n2-set merge.\n")) ; ASSERT (nsets == 1) ; PRINT2 (("Source col p1 = "ID", p2 = "ID", p3= "ID"\n", p1, p2, p3)) ; for (p = p1 + 1 ; p < p2 ; p++) { PRINT2 ((" p: "ID" source row "ID" %g\n", p, Li[p], Lx[p])) ; ASSERT (Li [p] > j && Li [p] < n) ; } PRINT2 (("---\n")) ; for (p = p3 ; p < p1 + newlnz ; p++) { PRINT2 ((" p: "ID" target row "ID" %g\n", p, Li[p], Lx[p])) ; ASSERT (Li [p] > j && Li [p] < n) ; } dump_set (0, Set_ps1, Set_ps2, j, n, Common) ; #endif if (p2 == p1 + 1) { /* the top of Lj is empty; copy the set and quit */ while (p3 > p2) { /* new entry in Lj' */ row = *(--ps2) ; p3-- ; Li [p3] = row ; Lx [p3] = 0.0 ; } } else { /* get the entry at the tail end of Lj */ row1 = Li [p2 - 1] ; ASSERT (row1 > j && row1 < n) ; /* get the entry at the tail end of the incoming set */ ASSERT (ps1 < ps2) ; row = *(ps2-1) ; ASSERT (row > j && row1 < n) ; /* move the larger of the two entries to the target set */ if (row1 >= row) { /* next entry is in Lj, move to the bottom */ if (row1 == row) { /* skip past this entry in the set */ ps2-- ; } p2-- ; p3-- ; Li [p3] = row1 ; Lx [p3] = Lx [p2] ; } else { /* new entry in Lj' */ ps2-- ; p3-- ; Li [p3] = row ; Lx [p3] = 0.0 ; } } } /* -------------------------------------------------------------- */ /* The new column j of L is now in Li/Lx [p1 ... p2-1] */ /* -------------------------------------------------------------- */ p2 = p1 + newlnz ; DEBUG (dump_col ("After merge: ", j, p1, p2, Li, Lx, n, Common)) ; fl += Path [path].rank * (6 + 4 * (double) newlnz) ; /* -------------------------------------------------------------- */ /* clear Flag; original pattern of column j L no longer marked */ /* -------------------------------------------------------------- */ mark = CHOLMOD(clear_flag) (Common) ; scattered = FALSE ; /* -------------------------------------------------------------- */ /* find the new parent */ /* -------------------------------------------------------------- */ newparent = (newlnz > 1) ? (Li [p1 + 1]) : EMPTY ; PRINT1 (("\nNew parent, Lnz: "ID": "ID" "ID"\n", j, newparent,newlnz)); ASSERT (oldparent == EMPTY || newparent <= oldparent) ; /* -------------------------------------------------------------- */ /* go to the next node in the path */ /* -------------------------------------------------------------- */ /* path moves to (j,nextj) unless j is a root */ nextj = (newparent == EMPTY) ? n : newparent ; /* place path at head of list for nextj, or terminate the path */ PRINT1 (("\n j = "ID" nextj = "ID"\n\n", j, nextj)) ; Path [path].c = j ; if (nextj < n) { /* put path on link list of pending paths at column nextj */ Path [path].next = Head [nextj] ; Path [path].pending = nextj ; Head [nextj] = path ; PRINT1 (("Path "ID" continues to ("ID","ID"). Rank "ID"\n", path, Path [path].c, nextj, Path [path].rank)) ; } else { /* path has ended here, at a root */ Path [path].next = EMPTY ; Path [path].pending = EMPTY ; Path [path].end = j ; PRINT1 (("Path "ID" ends at root ("ID"). Rank "ID"\n", path, Path [path].end, Path [path].rank)) ; } /* The link list Head [j] can now be emptied. Set Head [j] to 1 * if column j has changed (it is no longer used as a link list). */ PRINT1 (("column "ID", oldlnz = "ID"\n", j, Lnz [j])) ; Head [j] = (Lnz [j] != newlnz) ? 1 : EMPTY ; Lnz [j] = newlnz ; PRINT1 (("column "ID", newlnz = "ID"\n", j, newlnz)) ; DEBUG (dump_col ("New", j, p1, p2, Li, Lx, n, Common)) ; /* move to the next column */ if (k == Path [path].rank) { /* only one path left */ j = nextj ; } else { /* The current path is moving from column j to column nextj * (nextj is n if the path has ended). However, there may be * other paths pending in columns j+1 to nextj-1. There are * two methods for looking for the next column with a pending * update. The first one looks at all columns j+1 to nextj-1 * for a non-empty link list. This can be costly if j and * nextj differ by a large amount (it can be O(n), but this * entire routine may take Omega(1) time). The second method * looks at all paths and finds the smallest column at which any * path is pending. It takes O(# of paths), which is bounded * by 23: one for each column of C (up to 8), and then 15 for a * balanced binary tree with 8 leaves. However, if j and * nextj differ by a tiny amount (nextj is often j+1 near * the end of the matrix), looking at columns j+1 to nextj * would be faster. Both methods give the same answer. */ if (nextj - j < npaths) { /* there are fewer columns to search than paths */ PRINT1 (("check j="ID" to nextj="ID"\n", j, nextj)) ; for (j2 = j + 1 ; j2 < nextj ; j2++) { PRINT1 (("check j="ID" "ID"\n", j2, Head [j2])) ; if (Head [j2] != EMPTY) { PRINT1 (("found, j="ID"\n", j2)) ; ASSERT (Path [Head [j2]].pending == j2) ; break ; } } } else { /* there are fewer paths than columns to search */ j2 = nextj ; for (kk = 0 ; kk < npaths ; kk++) { jj = Path [kk].pending ; PRINT2 (("Path "ID" pending at "ID"\n", kk, jj)) ; if (jj != EMPTY) j2 = MIN (j2, jj) ; } } j = j2 ; } } /* ensure workspaces are back to the values required on input */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, TRUE, Common)) ; /* ------------------------------------------------------------------ */ /* depth-first-search of tree to order the paths */ /* ------------------------------------------------------------------ */ /* create lists of child paths */ PRINT1 (("\n\nDFS search:\n\n")) ; for (path = 0 ; path < npaths ; path++) { Path [path].c = EMPTY ; /* first child of path */ Path [path].next = EMPTY ; /* next sibling of path */ Path [path].order = EMPTY ; /* path is not ordered yet */ Path [path].wfirst = EMPTY ; /* 1st column of W not found yet */ #ifndef NDEBUG j = Path [path].start ; PRINT1 (("Path "ID" : start "ID" end "ID" parent "ID" ccol "ID"\n", path, j, Path [path].end, Path [path].parent, Path [path].ccol)) ; for ( ; ; ) { PRINT1 ((" column "ID"\n", j)) ; ASSERT (j == EMPTY || (j >= 0 && j < n)) ; if (j == Path [path].end) { break ; } ASSERT (j >= 0 && j < n) ; j = (Lnz [j] > 1) ? (Li [Lp [j] + 1]) : EMPTY ; } #endif } for (path = 0 ; path < npaths ; path++) { p = Path [path].parent ; /* add path to child list of parent */ if (p != EMPTY) { ASSERT (p < npaths) ; Path [path].next = Path [p].c ; Path [p].c = path ; } } path_order = k ; w_order = 0 ; for (path = npaths-1 ; path >= 0 ; path--) { if (Path [path].order == EMPTY) { /* this path is the root of a subtree of Tbar */ PRINT1 (("Root path "ID"\n", path)) ; ASSERT (path >= k) ; dfs (Path, k, path, &path_order, &w_order, 0, npaths) ; } } ASSERT (path_order == npaths) ; ASSERT (w_order == k) ; /* reorder the paths */ for (path = 0 ; path < npaths ; path++) { /* old order is path, new order is Path [path].order */ OrderedPath [Path [path].order] = Path [path] ; } #ifndef NDEBUG for (path = 0 ; path < npaths ; path++) { PRINT1 (("Ordered Path "ID": start "ID" end "ID" wfirst "ID" rank " ""ID" ccol "ID"\n", path, OrderedPath [path].start, OrderedPath [path].end, OrderedPath [path].wfirst, OrderedPath [path].rank, OrderedPath [path].ccol)) ; if (path < k) { ASSERT (OrderedPath [path].ccol >= 0) ; } else { ASSERT (OrderedPath [path].ccol == EMPTY) ; } } #endif /* ------------------------------------------------------------------ */ /* numeric update/downdate for all paths */ /* ------------------------------------------------------------------ */ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, wdim, Common)) ; switch (wdim) { case 1: updown_1_r (update, C, k, L, W, OrderedPath, npaths, mask, Common) ; break ; case 2: updown_2_r (update, C, k, L, W, OrderedPath, npaths, mask, Common) ; break ; case 4: updown_4_r (update, C, k, L, W, OrderedPath, npaths, mask, Common) ; break ; case 8: updown_8_r (update, C, k, L, W, OrderedPath, npaths, mask, Common) ; break ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, wdim, Common)) ; } /* ---------------------------------------------------------------------- */ /* update/downdate the forward solve */ /* ---------------------------------------------------------------------- */ if (do_solve) { /* We now have DeltaB += Lold (:,j) * X (j) for all columns j in union * of all paths seen during the entire rank-cncol update/downdate. For * each j in path, do DeltaB -= Lnew (:,j)*DeltaB(j) * in topological order. */ #ifndef NDEBUG PRINT1 (("\ndo_solve, DeltaB + Lold(:,Path)*X(Path):\n")) ; for (i = 0 ; i < n ; i++) { PRINT1 (("do_solve: "ID" %30.20e\n", i, Nx [i])) ; } #endif /* Note that the downdate, if it deleted entries, would need to compute * the Stack prior to doing any downdates. */ /* find the union of all the paths in the new L */ top = n ; /* "top" is stack pointer, not a row or column index */ for (ccol = 0 ; ccol < cncol ; ccol++) { /* -------------------------------------------------------------- */ /* j = first row index of C (:,ccol) */ /* -------------------------------------------------------------- */ pp1 = Cp [ccol] ; pp2 = (packed) ? (Cp [ccol+1]) : (pp1 + Cnz [ccol]) ; if (pp2 > pp1) { /* Column ccol of C has at least one entry. */ j = Ci [pp1] ; } else { /* Column ccol of C is empty */ j = n-1 ; } PRINT1 (("\ndo_solve: ccol= "ID"\n", ccol)) ; ASSERT (j >= 0 && j < n) ; len = 0 ; /* -------------------------------------------------------------- */ /* find the new rowmark */ /* -------------------------------------------------------------- */ /* Each column of C can redefine the region of L that takes part in * the update/downdate of the triangular solve Lx=b. If * i = colmark [ccol] for column C(:,ccol), then i = rowmark [j] is * redefined for all columns along the path modified by C(:,ccol). * If more than one column modifies any given column j of L, then * the rowmark of j is determined by the colmark of the least- * numbered column that affects column j. That is, if both * C(:,ccol1) and C(:,ccol2) affect column j of L, then * rowmark [j] = colmark [MIN (ccol1, ccol2)]. * * rowmark [j] is not modified if rowmark or colmark are NULL, * or if colmark [ccol] is EMPTY. */ botrow = (use_colmark) ? (colmark [ccol]) : EMPTY ; /* -------------------------------------------------------------- */ /* traverse from j towards root, stopping if node already visited */ /* -------------------------------------------------------------- */ while (j != EMPTY && Flag [j] < mark) { PRINT1 (("do_solve: subpath j= "ID"\n", j)) ; ASSERT (j >= 0 && j < n) ; Stack [len++] = j ; /* place j on the stack */ Flag [j] = mark ; /* flag j as visited */ /* if using colmark, mark column j with botrow */ ASSERT (Li [Lp [j]] == j) ; /* diagonal is always present */ if (use_colmark) { Li [Lp [j]] = botrow ; /* use the space for botrow */ } /* go up the tree, to the parent of j */ j = (Lnz [j] > 1) ? (Li [Lp [j] + 1]) : EMPTY ; } /* -------------------------------------------------------------- */ /* move the path down to the bottom of the stack */ /* -------------------------------------------------------------- */ ASSERT (len <= top) ; while (len > 0) { Stack [--top] = Stack [--len] ; } } #ifndef NDEBUG /* Union of paths now in Stack [top..n-1] in topological order */ PRINT1 (("\nTopological order:\n")) ; for (i = top ; i < n ; i++) { PRINT1 (("column "ID" in full path\n", Stack [i])) ; } #endif /* Do the forward solve for the full path part of L */ for (m = top ; m < n ; m++) { j = Stack [m] ; ASSERT (j >= 0 && j < n) ; PRINT1 (("do_solve: path j= "ID"\n", j)) ; p1 = Lp [j] ; lnz = Lnz [j] ; p2 = p1 + lnz ; xj = Nx [j] ; /* copy new solution onto old one, for all cols in full path */ Xx [j] = xj ; Nx [j] = 0. ; /* DeltaB -= Lnew (j+1:botrow-1,j) * deltab(j) */ if (use_colmark) { botrow = Li [p1] ; /* get botrow */ Li [p1] = j ; /* restore diagonal entry */ for (p = p1 + 1 ; p < p2 ; p++) { i = Li [p] ; if (i >= botrow) break ; Nx [i] -= Lx [p] * xj ; } } else { for (p = p1 + 1 ; p < p2 ; p++) { Nx [Li [p]] -= Lx [p] * xj ; } } } /* clear the Flag */ mark = CHOLMOD(clear_flag) (Common) ; } /* ---------------------------------------------------------------------- */ /* successful update/downdate */ /* ---------------------------------------------------------------------- */ Common->modfl = fl ; DEBUG (for (j = 0 ; j < n ; j++) ASSERT (IMPLIES (do_solve, Nx[j] == 0.))) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, TRUE, Common)) ; DEBUG (CHOLMOD(dump_factor) (L, "output L for updown", Common)) ; return (TRUE) ; } #endif igraph/src/CHOLMOD/Modify/License.txt0000644000175100001440000000204613430770174017000 0ustar hornikusersCHOLMOD/Modify Module. Copyright (C) 2005-2006, Timothy A. Davis and William W. Hager CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Modify module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. igraph/src/CHOLMOD/Modify/gpl.txt0000644000175100001440000004313313430770174016202 0ustar hornikusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. igraph/src/CHOLMOD/Modify/t_cholmod_updown.c0000644000175100001440000001504513431000472020354 0ustar hornikusers/* ========================================================================== */ /* === Modify/t_cholmod_updown ============================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Modify Module. Copyright (C) 2005-2006, * Timothy A. Davis and William W. Hager. * The CHOLMOD/Modify Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Updates/downdates the LDL' factorization, by computing a new factorization of * * Lnew * Dnew * Lnew' = Lold * Dold * Lold' +/- C*C' * * This file is not compiled separately. It is included into * cholmod_updown.c. There are no user-callable routines in this file. * * The next include statements, below, create the numerical update/downdate * kernels from t_cholmod_updown_numkr.c. There are 4 compiled versions of this * file, one for each value of WDIM in the set 1, 2, 4, and 8. Each calls * multiple versions of t_cholmod_updown_numkr; the number of versions of each * is equal to WDIM. Each t_cholmod_updown_numkr version is included as a * static function within its t_cholmod_updown.c caller routine. Thus: * * t*_updown.c creates these versions of t_cholmod_updown_numkr.c: * --------- --------------------------------------------------- * * updown_1_r updown_1_1 * * updown_2_r updown_2_1 updown_2_2 * * updown_4_r updown_4_1 updown_4_2 updown_4_3 updown_4_4 * * updown_8_r updown_8_1 updown_8_2 updown_8_3 updown_8_4 * updown_8_5 updown_8_6 updown_8_7 updown_8_8 * * workspace: Xwork (nrow*wdim) */ /* ========================================================================== */ /* === routines for numeric update/downdate along one path ================== */ /* ========================================================================== */ #undef FORM_NAME #undef NUMERIC #define FORM_NAME(k,rank) updown_ ## k ## _ ## rank #define NUMERIC(k,rank) FORM_NAME(k,rank) #define RANK 1 #include "t_cholmod_updown_numkr.c" #if WDIM >= 2 #define RANK 2 #include "t_cholmod_updown_numkr.c" #endif #if WDIM >= 4 #define RANK 3 #include "t_cholmod_updown_numkr.c" #define RANK 4 #include "t_cholmod_updown_numkr.c" #endif #if WDIM == 8 #define RANK 5 #include "t_cholmod_updown_numkr.c" #define RANK 6 #include "t_cholmod_updown_numkr.c" #define RANK 7 #include "t_cholmod_updown_numkr.c" #define RANK 8 #include "t_cholmod_updown_numkr.c" #endif /* ========================================================================== */ /* === numeric update/downdate for all paths ================================ */ /* ========================================================================== */ static void NUMERIC (WDIM, r) ( int update, /* TRUE for update, FALSE for downdate */ cholmod_sparse *C, /* in packed or unpacked, and sorted form */ /* no empty columns */ Int rank, /* rank of the update/downdate */ cholmod_factor *L, /* with unit diagonal (diagonal not stored) */ /* temporary workspaces: */ double W [ ], /* n-by-WDIM dense matrix, initially zero */ Path_type Path [ ], Int npaths, Int mask [ ], /* size n */ cholmod_common *Common ) { double Alpha [8] ; double *Cx, *Wpath, *W1, *a ; Int i, j, p, ccol, pend, wfirst, e, path, packed ; Int *Ci, *Cp, *Cnz ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ Ci = C->i ; Cx = C->x ; Cp = C->p ; Cnz = C->nz ; packed = C->packed ; ASSERT (IMPLIES (!packed, Cnz != NULL)) ; ASSERT (L->n == C->nrow) ; DEBUG (CHOLMOD(dump_real) ("num_d: in W:", W, WDIM, L->n, FALSE, 1,Common)); /* ---------------------------------------------------------------------- */ /* scatter C into W */ /* ---------------------------------------------------------------------- */ for (path = 0 ; path < rank ; path++) { /* W (:, path) = C (:, Path [path].col) */ ccol = Path [path].ccol ; Wpath = W + path ; PRINT1 (("Ordered Columns [path = "ID"] = "ID"\n", path, ccol)) ; p = Cp [ccol] ; pend = (packed) ? (Cp [ccol+1]) : (p + Cnz [ccol]) ; /* column C can be empty */ for ( ; p < pend ; p++) { i = Ci [p] ; ASSERT (i >= 0 && i < (Int) (C->nrow)) ; if (mask == NULL || mask [i] < 0) { Wpath [WDIM * i] = Cx [p] ; } PRINT1 ((" row "ID" : %g mask "ID"\n", i, Cx [p], (mask) ? mask [i] : 0)) ; } Alpha [path] = 1.0 ; } DEBUG (CHOLMOD(dump_real) ("num_d: W:", W, WDIM, L->n, FALSE, 1,Common)) ; /* ---------------------------------------------------------------------- */ /* numeric update/downdate of the paths */ /* ---------------------------------------------------------------------- */ /* for each disjoint subpath in Tbar in DFS order do */ for (path = rank ; path < npaths ; path++) { /* determine which columns of W to use */ wfirst = Path [path].wfirst ; e = Path [path].end ; j = Path [path].start ; ASSERT (e >= 0 && e < (Int) (L->n)) ; ASSERT (j >= 0 && j < (Int) (L->n)) ; W1 = W + wfirst ; /* pointer to row 0, column wfirst of W */ a = Alpha + wfirst ; /* pointer to Alpha [wfirst] */ PRINT1 (("Numerical update/downdate of path "ID"\n", path)) ; PRINT1 (("start "ID" end "ID" wfirst "ID" rank "ID" ccol "ID"\n", j, e, wfirst, Path [path].rank, Path [path].ccol)) ; #if WDIM == 1 NUMERIC (WDIM,1) (update, j, e, a, W1, L, Common) ; #else switch (Path [path].rank) { case 1: NUMERIC (WDIM,1) (update, j, e, a, W1, L, Common) ; break ; #if WDIM >= 2 case 2: NUMERIC (WDIM,2) (update, j, e, a, W1, L, Common) ; break ; #endif #if WDIM >= 4 case 3: NUMERIC (WDIM,3) (update, j, e, a, W1, L, Common) ; break ; case 4: NUMERIC (WDIM,4) (update, j, e, a, W1, L, Common) ; break ; #endif #if WDIM == 8 case 5: NUMERIC (WDIM,5) (update, j, e, a, W1, L, Common) ; break ; case 6: NUMERIC (WDIM,6) (update, j, e, a, W1, L, Common) ; break ; case 7: NUMERIC (WDIM,7) (update, j, e, a, W1, L, Common) ; break ; case 8: NUMERIC (WDIM,8) (update, j, e, a, W1, L, Common) ; break ; #endif } #endif } } /* prepare for the next inclusion of this file in cholmod_updown.c */ #undef WDIM igraph/src/CHOLMOD/Modify/cholmod_rowdel.c0000644000175100001440000003173013431000472020010 0ustar hornikusers/* ========================================================================== */ /* === Modify/cholmod_rowdel ================================================ */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Modify Module. * Copyright (C) 2005-2006, Timothy A. Davis and William W. Hager. * The CHOLMOD/Modify Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Deletes a row and column from an LDL' factorization. The row and column k * is set to the kth row and column of the identity matrix. Optionally * downdates the solution to Lx=b. * * workspace: Flag (nrow), Head (nrow+1), W (nrow*2), Iwork (2*nrow) * * Only real matrices are supported (exception: since only the pattern of R * is used, it can have any valid xtype). */ #ifndef NMODIFY #include "cholmod_internal.h" #include "cholmod_modify.h" /* ========================================================================== */ /* === cholmod_rowdel ======================================================= */ /* ========================================================================== */ /* Sets the kth row and column of L to be the kth row and column of the identity * matrix, and updates L(k+1:n,k+1:n) accordingly. To reduce the running time, * the caller can optionally provide the nonzero pattern (or an upper bound) of * kth row of L, as the sparse n-by-1 vector R. Provide R as NULL if you want * CHOLMOD to determine this itself, which is easier for the caller, but takes * a little more time. */ int CHOLMOD(rowdel) ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ /* --------------- */ cholmod_common *Common ) { double yk [2] ; yk [0] = 0. ; yk [1] = 0. ; return (CHOLMOD(rowdel_mark) (k, R, yk, NULL, L, NULL, NULL, Common)) ; } /* ========================================================================== */ /* === cholmod_rowdel_solve ================================================= */ /* ========================================================================== */ /* Does the same as cholmod_rowdel, but also downdates the solution to Lx=b. * When row/column k of A is "deleted" from the system A*y=b, this can induce * a change to x, in addition to changes arising when L and b are modified. * If this is the case, the kth entry of y is required as input (yk) */ int CHOLMOD(rowdel_solve) ( /* ---- input ---- */ size_t k, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(rowdel_mark) (k, R, yk, NULL, L, X, DeltaB, Common)) ; } /* ========================================================================== */ /* === cholmod_rowdel_mark ================================================== */ /* ========================================================================== */ /* Does the same as cholmod_rowdel_solve, except only part of L is used in * the update/downdate of the solution to Lx=b. This routine is an "expert" * routine. It is meant for use in LPDASA only. * * if R == NULL then columns 0:k-1 of L are searched for row k. Otherwise, it * searches columns in the set defined by the pattern of the first column of R. * This is meant to be the pattern of row k of L (a superset of that pattern is * OK too). R must be a permutation of a subset of 0:k-1. */ int CHOLMOD(rowdel_mark) ( /* ---- input ---- */ size_t kdel, /* row/column index to delete */ cholmod_sparse *R, /* NULL, or the nonzero pattern of kth row of L */ double yk [2], /* kth entry in the solution to A*y=b */ Int *colmark, /* Int array of size 1. See cholmod_updown.c */ /* ---- in/out --- */ cholmod_factor *L, /* factor to modify */ cholmod_dense *X, /* solution to Lx=b (size n-by-1) */ cholmod_dense *DeltaB, /* change in b, zero on output */ /* --------------- */ cholmod_common *Common ) { double dk, sqrt_dk, xk, dj, fl ; double *Lx, *Cx, *W, *Xx, *Nx ; Int *Li, *Lp, *Lnz, *Ci, *Rj, *Rp, *Iwork ; cholmod_sparse *C, Cmatrix ; Int j, p, pend, kk, lnz, n, Cp [2], do_solve, do_update, left, k, right, middle, i, klast, given_row, rnz ; size_t s ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_REAL, FALSE) ; n = L->n ; k = kdel ; if (kdel >= L->n || k < 0) { ERROR (CHOLMOD_INVALID, "k invalid") ; return (FALSE) ; } if (R == NULL) { Rj = NULL ; rnz = EMPTY ; } else { RETURN_IF_XTYPE_INVALID (R, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; if (R->ncol != 1 || R->nrow != L->n) { ERROR (CHOLMOD_INVALID, "R invalid") ; return (FALSE) ; } Rj = R->i ; Rp = R->p ; rnz = Rp [1] ; } do_solve = (X != NULL) && (DeltaB != NULL) ; if (do_solve) { RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; RETURN_IF_XTYPE_INVALID (DeltaB, CHOLMOD_REAL, CHOLMOD_REAL, FALSE) ; Xx = X->x ; Nx = DeltaB->x ; if (X->nrow != L->n || X->ncol != 1 || DeltaB->nrow != L->n || DeltaB->ncol != 1 || Xx == NULL || Nx == NULL) { ERROR (CHOLMOD_INVALID, "X and/or DeltaB invalid") ; return (FALSE) ; } } else { Xx = NULL ; Nx = NULL ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = 2*n */ s = CHOLMOD(mult_size_t) (n, 2, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, s, s, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 2*n, Common)) ; /* ---------------------------------------------------------------------- */ /* convert to simplicial numeric LDL' factor, if not already */ /* ---------------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN || L->is_super || L->is_ll) { /* can only update/downdate a simplicial LDL' factorization */ CHOLMOD(change_factor) (CHOLMOD_REAL, FALSE, FALSE, FALSE, FALSE, L, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory, L is returned unchanged */ return (FALSE) ; } } /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* inputs, not modified on output: */ Lp = L->p ; /* size n+1 */ /* outputs, contents defined on input for incremental case only: */ Lnz = L->nz ; /* size n */ Li = L->i ; /* size L->nzmax. Can change in size. */ Lx = L->x ; /* size L->nzmax. Can change in size. */ ASSERT (L->nz != NULL) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ W = Common->Xwork ; /* size n, used only in cholmod_updown */ Cx = W + n ; /* use 2nd column of Xwork for C (size n) */ Iwork = Common->Iwork ; Ci = Iwork + n ; /* size n (i/i/l) */ /* NOTE: cholmod_updown uses Iwork [0..n-1] (i/i/l) as Stack */ /* ---------------------------------------------------------------------- */ /* prune row k from all columns of L */ /* ---------------------------------------------------------------------- */ given_row = (rnz >= 0) ; klast = given_row ? rnz : k ; PRINT2 (("given_row "ID"\n", given_row)) ; for (kk = 0 ; kk < klast ; kk++) { /* either search j = 0:k-1 or j = Rj [0:rnz-1] */ j = given_row ? (Rj [kk]) : (kk) ; if (j < 0 || j >= k) { ERROR (CHOLMOD_INVALID, "R invalid") ; return (FALSE) ; } PRINT2 (("Prune col j = "ID":\n", j)) ; lnz = Lnz [j] ; dj = Lx [Lp [j]] ; ASSERT (Lnz [j] > 0 && Li [Lp [j]] == j) ; if (lnz > 1) { left = Lp [j] ; pend = left + lnz ; right = pend - 1 ; i = Li [right] ; if (i < k) { /* row k is not in column j */ continue ; } else if (i == k) { /* k is the last row index in this column (quick delete) */ if (do_solve) { Xx [j] -= yk [0] * dj * Lx [right] ; } Lx [right] = 0 ; } else { /* binary search for row k in column j */ PRINT2 (("\nBinary search: lnz "ID" k = "ID"\n", lnz, k)) ; while (left < right) { middle = (left + right) / 2 ; PRINT2 (("left "ID" right "ID" middle "ID": ["ID" "ID"" ""ID"]\n", left, right, middle, Li [left], Li [middle], Li [right])) ; if (k > Li [middle]) { left = middle + 1 ; } else { right = middle ; } } ASSERT (left >= Lp [j] && left < pend) ; #ifndef NDEBUG /* brute force, linear-time search */ { Int p3 = Lp [j] ; i = EMPTY ; PRINT2 (("Brute force:\n")) ; for ( ; p3 < pend ; p3++) { i = Li [p3] ; PRINT2 (("p "ID" ["ID"]\n", p3, i)) ; if (i >= k) { break ; } } if (i == k) { ASSERT (k == Li [p3]) ; ASSERT (p3 == left) ; } } #endif if (k == Li [left]) { if (do_solve) { Xx [j] -= yk [0] * dj * Lx [left] ; } /* found row k in column j. Prune it from the column.*/ Lx [left] = 0 ; } } } } #ifndef NDEBUG /* ensure that row k has been deleted from the matrix L */ for (j = 0 ; j < k ; j++) { Int lasti ; lasti = EMPTY ; p = Lp [j] ; pend = p + Lnz [j] ; /* look for row k in column j */ PRINT1 (("Pruned column "ID"\n", j)) ; for ( ; p < pend ; p++) { i = Li [p] ; PRINT2 ((" "ID"", i)) ; PRINT2 ((" %g\n", Lx [p])) ; ASSERT (IMPLIES (i == k, Lx [p] == 0)) ; ASSERT (i > lasti) ; lasti = i ; } PRINT1 (("\n")) ; } #endif /* ---------------------------------------------------------------------- */ /* set diagonal and clear column k of L */ /* ---------------------------------------------------------------------- */ lnz = Lnz [k] - 1 ; ASSERT (Lnz [k] > 0) ; /* ---------------------------------------------------------------------- */ /* update/downdate */ /* ---------------------------------------------------------------------- */ /* update or downdate L (k+1:n, k+1:n) with the vector * C = L (:,k) * sqrt (abs (D [k])) * Do a numeric update if D[k] > 0, numeric downdate otherwise. */ PRINT1 (("rowdel downdate lnz = "ID"\n", lnz)) ; /* store the new unit diagonal */ p = Lp [k] ; pend = p + lnz + 1 ; dk = Lx [p] ; Lx [p++] = 1 ; PRINT2 (("D [k = "ID"] = %g\n", k, dk)) ; ok = TRUE ; fl = 0 ; if (lnz > 0) { /* compute DeltaB for updown (in DeltaB) */ if (do_solve) { xk = Xx [k] - yk [0] * dk ; for ( ; p < pend ; p++) { Nx [Li [p]] += Lx [p] * xk ; } } do_update = IS_GT_ZERO (dk) ; if (!do_update) { dk = -dk ; } sqrt_dk = sqrt (dk) ; p = Lp [k] + 1 ; for (kk = 0 ; kk < lnz ; kk++, p++) { Ci [kk] = Li [p] ; Cx [kk] = Lx [p] * sqrt_dk ; Lx [p] = 0 ; /* clear column k */ } fl = lnz + 1 ; /* create a n-by-1 sparse matrix to hold the single column */ C = &Cmatrix ; C->nrow = n ; C->ncol = 1 ; C->nzmax = lnz ; C->sorted = TRUE ; C->packed = TRUE ; C->p = Cp ; C->i = Ci ; C->x = Cx ; C->nz = NULL ; C->itype = L->itype ; C->xtype = L->xtype ; C->dtype = L->dtype ; C->z = NULL ; C->stype = 0 ; Cp [0] = 0 ; Cp [1] = lnz ; /* numeric update if dk > 0, and with Lx=b change */ /* workspace: Flag (nrow), Head (nrow+1), W (nrow), Iwork (2*nrow) */ ok = CHOLMOD(updown_mark) (do_update ? (1) : (0), C, colmark, L, X, DeltaB, Common) ; /* clear workspace */ for (kk = 0 ; kk < lnz ; kk++) { Cx [kk] = 0 ; } } Common->modfl += fl ; if (do_solve) { /* kth equation becomes identity, so X(k) is now Y(k) */ Xx [k] = yk [0] ; } DEBUG (CHOLMOD(dump_factor) (L, "LDL factorization, L:", Common)) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 2*n, Common)) ; return (ok) ; } #endif igraph/src/CHOLMOD/Check/0000755000175100001440000000000013561251652014441 5ustar hornikusersigraph/src/CHOLMOD/Check/cholmod_read.c0000644000175100001440000011740113431000472017215 0ustar hornikusers/* ========================================================================== */ /* === Check/cholmod_read =================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Check Module. Copyright (C) 2005-2006, Timothy A. Davis. * The CHOLMOD/Check Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Read a sparse matrix in triplet or dense form. A triplet matrix can be * returned as compressed-column sparse matrix. The file format is compatible * with all variations of the Matrix Market "coordinate" and "array" format * (http://www.nist.gov/MatrixMarket). The format supported by these routines * also allow other formats, where the Matrix Market header is optional. * * Although the Matrix Market header is optional, I recommend that users stick * with the strict Matrix Market format. The optional format appears here to * support the reading of symmetric matrices stored with just their upper * triangular parts present, for testing and development of the A->stype > 0 * format in CHOLMOD. That format is not included in the Matrix Market format. * * If the first line of the file starts with %%MatrixMarket, then it is * interpretted as a file in Matrix Market format. This line must have * the following format: * * %%MatrixMarket matrix * * is one of: coordinate or array. The former is a sparse matrix in * triplet form. The latter is a dense matrix in column-major form. * * is one of: real, complex, pattern, or integer. * The functions here convert the "integer" and "pattern" types to real. * * is one of: general, hermitian, symmetric, or skew-symmetric * * The strings are case-insensitive. Only the first character is * significant (or the first two for skew-symmetric). * * is ignored for all matrices; the actual type (real, complex, * or pattern) is inferred from the number of tokens in each line of the * file. For a "coordinate" matrix: 2: pattern, 3: real, 4: complex; for * a dense "array" matrix: 1: real, 2: complex. This is compatible with * the Matrix Market format, since pattern matrices must have two tokens * per line, real matrices must have 3, and complex matrices must have 4. * A storage of "general" implies an stype of zero (see below). * "symmetric" and "hermitian" imply an stype of -1. Skew-symmetric and * complex symmetric matrices are always returned with both upper and lower * triangular parts present, with an stype of zero, since CHOLMOD does not * have a method for representing skew-symmetric and complex symmetric * matrices. Real symmetric and complex Hermitian matrices may optionally * be returned with both parts present. * * Any other lines starting with "%" are treated as comments, and are ignored. * Blank lines are ignored. The Matrix Market header is optional in this * routine (it is not optional in the Matrix Market format). * * Note that complex matrices are always returned in CHOLMOD_COMPLEX format, * not CHOLMOD_ZOMPLEX. * * ----------------------------------------------------------------------------- * Triplet matrices: * ----------------------------------------------------------------------------- * * The first data line of a triplet matrix contains 3 or 4 integers: * * nrow ncol nnz stype * * where stype is optional (stype does not appear in the Matrix Market format). * The matrix is nrow-by-ncol. The following nnz lines (excluding comments * and blank lines) each contain a single entry. Duplicates are permitted, * and are summed in the output matrix. * * The stype is first derived from the Matrix Market header. If the stype * appears as the fourth integer in the first data line, it is determined from * that line. * * If stype is present, it denotes the storage format for the matrix. * stype = 0 denotes an unsymmetric matrix (same as Matrix Market "general"). * stype = -1 denotes a real symmetric or complex Hermitian matrix whose lower * triangular entries are stored. Entries may be present in the upper * triangular part, but these are ignored (same as Matrix Market * "real symmetric" and "complex Hermitian"). * stype = 1 denotes a real symmetric or complex Hermitian matrix whose upper * triangular entries are stored. Entries may be present in the lower * triangular part, but these are ignored. This option is not present * in the Matrix Market format. * * If stype is not present (no Matrix Market header and not in the first data * line) it is inferred from the rest of the data. If the matrix is * rectangular, or has entries in both the upper and lower triangular parts, * then it is assumed to be unsymmetric (stype=0). If only entries in the * lower triangular part are present, the matrix is assumed to have stype = -1. * If only entries in the upper triangular part are present, the matrix is * assumed to have stype = 1. * * After the first data line (with nrow, ncol, nnz, and optionally stype), * each nonzero consists of one line with 2, 3, or 4 entries. All lines must * have the same number of entries. The first two entries are the row and * column indices of the nonzero. If 3 entries are present, the 3rd entry is * the numerical value, and the matrix is real. If 4 entries are present, * the 3rd and 4th entries in the line are the real and imaginary parts of * a complex value. * * The matrix can be either 0-based or 1-based. It is first assumed to be * one-based (all matrices in the Matrix Market are one-based), with row indices * in the range 1 to ncol and column indices in the range 1 to nrow. If a row * or column index of zero is found, the matrix is assumed to be zero-based * (with row indices in the range 0 to ncol-1 and column indices in the range 0 * to nrow-1). * * If Common->prefer_binary is set to its default value of FALSE, then * for symmetric pattern-only matrices, the kth diagonal (if present) is set to * one plus the degree of the row/column k, and the off-diagonal entries are set * to -1. A symmetric pattern-only matrix with a zero-free diagonal is thus * converted into a symmetric positive definite matrix. All entries are set to * one for an unsymmetric pattern-only matrix. This differs from the * Matrix Market format (A = mmread ('file') returns a binary pattern for A for * symmetric pattern-only matrices). If Common->prefer_binary is TRUE, then * this function returns a binary matrix (just like mmread('file')). * * ----------------------------------------------------------------------------- * Dense matrices: * ----------------------------------------------------------------------------- * * A dense matrix is specified by the Matrix Market "array" format. The * Matrix Market header is optional; if not present, the matrix is assumed to * be in the Matrix Market "general" format. The first data line contains just * two integers: * * nrow ncol * * The can be real, integer, or complex (not pattern). These functions * convert an integer type to real. The entries in the matrix are stored in * column-major format, with one line per entry. Two entries are present in * each line for complex matrices, one for real and integer matrices. In * rectangular and unsymmetric matrices, all entries are present. For real * symmetric or complex Hermitian matrices, only entries in the lower triangular * part appear. For skew-symmetric matrices, only entries in the strictly * lower triangular part appear. * * Since CHOLMOD does not have a data structure for presenting dense symmetric/ * Hermitian matrices, these functions always return a dense matrix in its * general form, with both upper and lower parts present. */ #ifndef NCHECK #include "cholmod_internal.h" #include "cholmod_check.h" #include #include /* The MatrixMarket format specificies a maximum line length of 1024 */ #define MAXLINE 1030 /* ========================================================================== */ /* === get_line ============================================================= */ /* ========================================================================== */ /* Read one line of the file, return TRUE if successful, FALSE if EOF. */ static int get_line (FILE *f, char *buf) { buf [0] = '\0' ; buf [1] = '\0' ; buf [MAXLINE] = '\0' ; return (fgets (buf, MAXLINE, f) != NULL) ; } /* ========================================================================== */ /* === fix_inf ============================================================== */ /* ========================================================================== */ /* Replace huge values with +/- Inf's, since scanf and printf don't deal * with Inf's properly. */ static double fix_inf (double x) { if ((x >= HUGE_DOUBLE) || (x <= -HUGE_DOUBLE)) { /* treat this as +/- Inf (assume 2*x leads to overflow) */ x = 2*x ; } return (x) ; } /* ========================================================================== */ /* === is_blank_line ======================================================== */ /* ========================================================================== */ /* TRUE if s is a blank line or comment, FALSE otherwise */ static int is_blank_line ( char *s ) { int c, k ; if (s [0] == '%') { /* a comment line */ return (TRUE) ; } for (k = 0 ; k <= MAXLINE ; k++) { c = s [k] ; if (c == '\0') { /* end of line */ break ; } if (!isspace (c)) { /* non-space character */ return (FALSE) ; } } return (TRUE) ; } /* ========================================================================== */ /* === read_header ========================================================== */ /* ========================================================================== */ /* Read the header. This consists of zero or more comment lines (blank, or * starting with a "%" in the first column), followed by a single data line * containing up to four numerical values. * * The first line may optionally be a Matrix Market header line, of the form * * %%MatrixMarket matrix * * The first data line of a sparse matrix in triplet form consists of 3 or 4 * numerical values: * * nrow ncol nnz stype * * where stype is optional (it does not appear in the Matrix Market file * format). The first line of a dense matrix in column-major form consists of * two numerical values: * * nrow ncol * * The stype of the matrix is determine either from the Matrix Market header, * or (optionally) from the first data line. stypes of 0 to -3 directly * correlate with the Matrix Market format; stype = 1 is an extension to that * format. * * 999: unknown (will be inferred from the data) * 1: real symmetric or complex Hermitian with upper part stored * (not in the Matrix Market format) * 0: unsymmetric (same as Matrix Market "general") * -1: real symmetric or complex Hermitian, with lower part stored * (Matrix Market "real symmetric" or "complex hermitian") * -2: real or complex skew symmetric (lower part stored, can only be * specified by Matrix Market header) * -3: complex symmetric (lower part stored) * specified by Matrix Market header) * * The Matrix Market header is optional. If stype appears in the first data * line, it is determine by that data line. Otherwise, if the Matrix Market * header appears, stype is determined from that header. If stype does not * appear, it is set to "unknown" (999). */ #define STYPE_UNKNOWN 999 #define STYPE_SYMMETRIC_UPPER 1 #define STYPE_UNSYMMETRIC 0 #define STYPE_SYMMETRIC_LOWER -1 #define STYPE_SKEW_SYMMETRIC -2 #define STYPE_COMPLEX_SYMMETRIC_LOWER -3 static int read_header /* returns TRUE if successful, FALSE on error */ ( /* ---- input ---- */ FILE *f, /* file to read from */ /* ---- output --- */ char *buf, /* a character array of size MAXLINE+1 */ int *mtype, /* CHOLMOD_TRIPLET or CHOLMOD_DENSE */ size_t *nrow, /* number of rows in the matrix */ size_t *ncol, /* number of columns in the matrix */ size_t *nnz, /* number of entries in a triplet matrix (0 for dense)*/ int *stype /* stype (see above) */ ) { char *p ; int first = TRUE, got_mm_header = FALSE, c, c2, is_complex, nitems ; double l1, l2, l3, l4 ; *mtype = CHOLMOD_TRIPLET ; *nrow = 0 ; *ncol = 0 ; *nnz = 0 ; *stype = STYPE_UNKNOWN ; for ( ; ; ) { /* ------------------------------------------------------------------ */ /* get the next line */ /* ------------------------------------------------------------------ */ if (!get_line (f, buf)) { /* premature end of file */ return (FALSE) ; } if (first && (strncmp (buf, "%%MatrixMarket", 14) == 0)) { /* -------------------------------------------------------------- */ /* read a Matrix Market header */ /* -------------------------------------------------------------- */ got_mm_header = TRUE ; p = buf ; /* -------------------------------------------------------------- */ /* get "matrix" token */ /* -------------------------------------------------------------- */ while (*p && !isspace (*p)) p++ ; while (*p && isspace (*p)) p++ ; c = tolower (*p) ; if (c != 'm') { /* bad format */ return (FALSE) ; } /* -------------------------------------------------------------- */ /* get the fmt token ("coord" or "array") */ /* -------------------------------------------------------------- */ while (*p && !isspace (*p)) p++ ; while (*p && isspace (*p)) p++ ; c = tolower (*p) ; if (c == 'c') { *mtype = CHOLMOD_TRIPLET ; } else if (c == 'a') { *mtype = CHOLMOD_DENSE ; } else { /* bad format, neither "coordinate" nor "array" */ return (FALSE) ; } /* -------------------------------------------------------------- */ /* get type token (real, pattern, complex, integer) */ /* -------------------------------------------------------------- */ while (*p && !isspace (*p)) p++ ; while (*p && isspace (*p)) p++ ; c = tolower (*p) ; if (!(c == 'r' || c == 'p' || c == 'c' || c == 'i')) { /* bad format */ return (FALSE) ; } is_complex = (c == 'c') ; /* -------------------------------------------------------------- */ /* get storage token (general, hermitian, symmetric, skew) */ /* -------------------------------------------------------------- */ while (*p && !isspace (*p)) p++ ; while (*p && isspace (*p)) p++ ; c = tolower (*p) ; c2 = tolower (*(p+1)) ; if (c == 'g') { /* "general" storage (unsymmetric matrix), both parts present */ *stype = STYPE_UNSYMMETRIC ; } else if (c == 's' && c2 == 'y') { /* "symmetric" */ if (is_complex) { /* complex symmetric, lower triangular part present */ *stype = STYPE_COMPLEX_SYMMETRIC_LOWER ; } else { /* real symmetric, lower triangular part present */ *stype = STYPE_SYMMETRIC_LOWER ; } } else if (c == 'h') { /* "hermitian" matrix, lower triangular part present */ *stype = STYPE_SYMMETRIC_LOWER ; } else if (c == 's' && c2 == 'k') { /* "skew-symmetric" (real or complex), lower part present */ *stype = STYPE_SKEW_SYMMETRIC ; } else { /* bad format */ return (FALSE) ; } } else if (is_blank_line (buf)) { /* -------------------------------------------------------------- */ /* blank line or comment line */ /* -------------------------------------------------------------- */ continue ; } else { /* -------------------------------------------------------------- */ /* read the first data line and return */ /* -------------------------------------------------------------- */ /* format: nrow ncol nnz stype */ l1 = EMPTY ; l2 = EMPTY ; l3 = 0 ; l4 = 0 ; nitems = sscanf (buf, "%lg %lg %lg %lg\n", &l1, &l2, &l3, &l4) ; if (nitems < 2 || nitems > 4 || l1 > Int_max || l2 > Int_max) { /* invalid matrix */ return (FALSE) ; } *nrow = l1 ; *ncol = l2 ; if (nitems == 2) { /* a dense matrix */ if (!got_mm_header) { *mtype = CHOLMOD_DENSE ; *stype = STYPE_UNSYMMETRIC ; } } if (nitems == 3 || nitems == 4) { /* a sparse triplet matrix */ *nnz = l3 ; if (!got_mm_header) { *mtype = CHOLMOD_TRIPLET ; } } if (nitems == 4) { /* an stype specified here can only be 1, 0, or -1 */ if (l4 < 0) { *stype = STYPE_SYMMETRIC_LOWER ; } else if (l4 > 0) { *stype = STYPE_SYMMETRIC_UPPER ; } else { *stype = STYPE_UNSYMMETRIC ; } } if (*nrow != *ncol) { /* a rectangular matrix must be unsymmetric */ *stype = STYPE_UNSYMMETRIC ; } return (TRUE) ; } first = FALSE ; } } /* ========================================================================== */ /* === read_triplet ========================================================= */ /* ========================================================================== */ /* Header has already been read in, including first line (nrow ncol nnz stype). * Read the triplets. */ static cholmod_triplet *read_triplet ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ size_t nrow, /* number of rows */ size_t ncol, /* number of columns */ size_t nnz, /* number of triplets in file to read */ int stype, /* stype from header, or "unknown" */ int prefer_unsym, /* if TRUE, always return T->stype of zero */ /* ---- workspace */ char *buf, /* of size MAXLINE+1 */ /* --------------- */ cholmod_common *Common ) { double x, z ; double *Tx ; Int *Ti, *Tj, *Rdeg, *Cdeg ; cholmod_triplet *T ; double l1, l2 ; Int nitems, xtype, unknown, k, nshould, is_lower, is_upper, one_based, i, j, imax, jmax, skew_symmetric, p, complex_symmetric ; size_t s, nnz2, extra ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* quick return for empty matrix */ /* ---------------------------------------------------------------------- */ if (nrow == 0 || ncol == 0 || nnz == 0) { /* return an empty matrix */ return (CHOLMOD(allocate_triplet) (nrow, ncol, 0, 0, CHOLMOD_REAL, Common)) ; } /* ---------------------------------------------------------------------- */ /* special stype cases: unknown, skew symmetric, and complex symmetric */ /* ---------------------------------------------------------------------- */ unknown = (stype == STYPE_UNKNOWN) ; skew_symmetric = (stype == STYPE_SKEW_SYMMETRIC) ; complex_symmetric = (stype == STYPE_COMPLEX_SYMMETRIC_LOWER) ; extra = 0 ; if (stype < STYPE_SYMMETRIC_LOWER || (prefer_unsym && stype != STYPE_UNSYMMETRIC)) { /* 999: unknown might be converted to unsymmetric */ /* 1: symmetric upper converted to unsym. if prefer_unsym is TRUE */ /* -1: symmetric lower converted to unsym. if prefer_unsym is TRUE */ /* -2: real or complex skew symmetric converted to unsymmetric */ /* -3: complex symmetric converted to unsymmetric */ stype = STYPE_UNSYMMETRIC ; extra = nnz ; } nnz2 = CHOLMOD(add_size_t) (nnz, extra, &ok) ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ /* s = nrow + ncol */ s = CHOLMOD(add_size_t) (nrow, ncol, &ok) ; if (!ok || nrow > Int_max || ncol > Int_max || nnz > Int_max) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (NULL) ; } CHOLMOD(allocate_work) (0, s, 0, Common) ; Rdeg = Common->Iwork ; /* size nrow */ Cdeg = Rdeg + nrow ; /* size ncol */ /* ---------------------------------------------------------------------- */ /* read the triplets */ /* ---------------------------------------------------------------------- */ is_lower = TRUE ; is_upper = TRUE ; one_based = TRUE ; imax = 0 ; jmax = 0 ; Tx = NULL ; Ti = NULL ; Tj = NULL ; xtype = 999 ; nshould = 0 ; for (k = 0 ; k < (Int) nnz ; k++) { /* ------------------------------------------------------------------ */ /* get the next triplet, skipping blank lines and comment lines */ /* ------------------------------------------------------------------ */ l1 = EMPTY ; l2 = EMPTY ; x = 0 ; z = 0 ; for ( ; ; ) { if (!get_line (f, buf)) { /* premature end of file - not enough triplets read in */ ERROR (CHOLMOD_INVALID, "premature EOF") ; return (NULL) ; } if (is_blank_line (buf)) { /* blank line or comment */ continue ; } nitems = sscanf (buf, "%lg %lg %lg %lg\n", &l1, &l2, &x, &z) ; x = fix_inf (x) ; z = fix_inf (z) ; break ; } nitems = (nitems == EOF) ? 0 : nitems ; i = l1 ; j = l2 ; /* ------------------------------------------------------------------ */ /* for first triplet: determine type and allocate triplet matrix */ /* ------------------------------------------------------------------ */ if (k == 0) { if (nitems < 2 || nitems > 4) { /* invalid matrix */ ERROR (CHOLMOD_INVALID, "invalid format") ; return (NULL) ; } else if (nitems == 2) { /* this will be converted into a real matrix later */ xtype = CHOLMOD_PATTERN ; } else if (nitems == 3) { xtype = CHOLMOD_REAL ; } else if (nitems == 4) { xtype = CHOLMOD_COMPLEX ; } /* the rest of the lines should have the same number of entries */ nshould = nitems ; /* allocate triplet matrix */ T = CHOLMOD(allocate_triplet) (nrow, ncol, nnz2, stype, (xtype == CHOLMOD_PATTERN ? CHOLMOD_REAL : xtype), Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } Ti = T->i ; Tj = T->j ; Tx = T->x ; T->nnz = nnz ; } /* ------------------------------------------------------------------ */ /* save the entry in the triplet matrix */ /* ------------------------------------------------------------------ */ if (nitems != nshould || i < 0 || j < 0) { /* wrong format, premature end-of-file, or negative indices */ CHOLMOD(free_triplet) (&T, Common) ; ERROR (CHOLMOD_INVALID, "invalid matrix file") ; return (NULL) ; } Ti [k] = i ; Tj [k] = j ; if (i < j) { /* this entry is in the upper triangular part */ is_lower = FALSE ; } if (i > j) { /* this entry is in the lower triangular part */ is_upper = FALSE ; } if (xtype == CHOLMOD_REAL) { Tx [k] = x ; } else if (xtype == CHOLMOD_COMPLEX) { Tx [2*k ] = x ; /* real part */ Tx [2*k+1] = z ; /* imaginary part */ } if (i == 0 || j == 0) { one_based = FALSE ; } imax = MAX (i, imax) ; jmax = MAX (j, jmax) ; } /* ---------------------------------------------------------------------- */ /* convert to zero-based */ /* ---------------------------------------------------------------------- */ if (one_based) { /* input matrix is one-based; convert matrix to zero-based */ for (k = 0 ; k < (Int) nnz ; k++) { Ti [k]-- ; Tj [k]-- ; } } if (one_based ? (imax > (Int) nrow || jmax > (Int) ncol) : (imax >= (Int) nrow || jmax >= (Int) ncol)) { /* indices out of range */ CHOLMOD(free_triplet) (&T, Common) ; ERROR (CHOLMOD_INVALID, "indices out of range") ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* determine the stype, if not yet known */ /* ---------------------------------------------------------------------- */ if (unknown) { if (is_lower && is_upper) { /* diagonal matrix, symmetric with upper part present */ stype = STYPE_SYMMETRIC_UPPER ; } else if (is_lower && !is_upper) { /* symmetric, lower triangular part present */ stype = STYPE_SYMMETRIC_LOWER ; } else if (!is_lower && is_upper) { /* symmetric, upper triangular part present */ stype = STYPE_SYMMETRIC_UPPER ; } else { /* unsymmetric */ stype = STYPE_UNSYMMETRIC ; extra = 0 ; } } /* ---------------------------------------------------------------------- */ /* add the remainder of symmetric, skew-symmetric or Hermitian matrices */ /* ---------------------------------------------------------------------- */ /* note that this step is not done for real symmetric or complex Hermitian * matrices, unless prefer_unsym is TRUE */ if (extra > 0) { p = nnz ; for (k = 0 ; k < (Int) nnz ; k++) { i = Ti [k] ; j = Tj [k] ; if (i != j) { Ti [p] = j ; Tj [p] = i ; if (xtype == CHOLMOD_REAL) { if (skew_symmetric) { Tx [p] = -Tx [k] ; } else { Tx [p] = Tx [k] ; } } else if (xtype == CHOLMOD_COMPLEX) { if (skew_symmetric) { Tx [2*p ] = -Tx [2*k ] ; Tx [2*p+1] = -Tx [2*k+1] ; } else if (complex_symmetric) { Tx [2*p ] = Tx [2*k ] ; Tx [2*p+1] = Tx [2*k+1] ; } else /* Hermitian */ { Tx [2*p ] = Tx [2*k ] ; Tx [2*p+1] = -Tx [2*k+1] ; } } p++ ; } } T->nnz = p ; nnz = p ; } T->stype = stype ; /* ---------------------------------------------------------------------- */ /* create values for a pattern-only matrix */ /* ---------------------------------------------------------------------- */ if (xtype == CHOLMOD_PATTERN) { if (stype == STYPE_UNSYMMETRIC || Common->prefer_binary) { /* unsymmetric case, or binary case */ for (k = 0 ; k < (Int) nnz ; k++) { Tx [k] = 1 ; } } else { /* compute the row and columm degrees (excluding the diagonal) */ for (i = 0 ; i < (Int) nrow ; i++) { Rdeg [i] = 0 ; } for (j = 0 ; j < (Int) ncol ; j++) { Cdeg [j] = 0 ; } for (k = 0 ; k < (Int) nnz ; k++) { i = Ti [k] ; j = Tj [k] ; if ((stype < 0 && i > j) || (stype > 0 && i < j)) { /* both a(i,j) and a(j,i) appear in the matrix */ Rdeg [i]++ ; Cdeg [j]++ ; Rdeg [j]++ ; Cdeg [i]++ ; } } /* assign the numerical values */ for (k = 0 ; k < (Int) nnz ; k++) { i = Ti [k] ; j = Tj [k] ; Tx [k] = (i == j) ? (1 + MAX (Rdeg [i], Cdeg [j])) : (-1) ; } } } /* ---------------------------------------------------------------------- */ /* return the new triplet matrix */ /* ---------------------------------------------------------------------- */ return (T) ; } /* ========================================================================== */ /* === read_dense =========================================================== */ /* ========================================================================== */ /* Header has already been read in, including first line (nrow ncol). * Read a dense matrix. */ static cholmod_dense *read_dense ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ size_t nrow, /* number of rows */ size_t ncol, /* number of columns */ int stype, /* stype from header */ /* ---- workspace */ char *buf, /* of size MAXLINE+1 */ /* --------------- */ cholmod_common *Common ) { double x, z ; double *Xx = NULL ; cholmod_dense *X ; Int nitems, xtype = -1, nshould = 0, i, j, k, kup, first ; /* ---------------------------------------------------------------------- */ /* quick return for empty matrix */ /* ---------------------------------------------------------------------- */ if (nrow == 0 || ncol == 0) { /* return an empty dense matrix */ return (CHOLMOD(zeros) (nrow, ncol, CHOLMOD_REAL, Common)) ; } /* ---------------------------------------------------------------------- */ /* read the entries */ /* ---------------------------------------------------------------------- */ first = TRUE ; for (j = 0 ; j < (Int) ncol ; j++) { /* ------------------------------------------------------------------ */ /* get the row index of the first entry in the file for column j */ /* ------------------------------------------------------------------ */ if (stype == STYPE_UNSYMMETRIC) { i = 0 ; } else if (stype == STYPE_SKEW_SYMMETRIC) { i = j+1 ; } else /* real symmetric or complex Hermitian lower */ { i = j ; } /* ------------------------------------------------------------------ */ /* get column j */ /* ------------------------------------------------------------------ */ for ( ; i < (Int) nrow ; i++) { /* -------------------------------------------------------------- */ /* get the next entry, skipping blank lines and comment lines */ /* -------------------------------------------------------------- */ x = 0 ; z = 0 ; for ( ; ; ) { if (!get_line (f, buf)) { /* premature end of file - not enough entries read in */ ERROR (CHOLMOD_INVALID, "premature EOF") ; return (NULL) ; } if (is_blank_line (buf)) { /* blank line or comment */ continue ; } nitems = sscanf (buf, "%lg %lg\n", &x, &z) ; x = fix_inf (x) ; z = fix_inf (z) ; break ; } nitems = (nitems == EOF) ? 0 : nitems ; /* -------------------------------------------------------------- */ /* for first entry: determine type and allocate dense matrix */ /* -------------------------------------------------------------- */ if (first) { first = FALSE ; if (nitems < 1 || nitems > 2) { /* invalid matrix */ ERROR (CHOLMOD_INVALID, "invalid format") ; return (NULL) ; } else if (nitems == 1) { /* a real matrix */ xtype = CHOLMOD_REAL ; } else if (nitems == 2) { /* a complex matrix */ xtype = CHOLMOD_COMPLEX ; } /* the rest of the lines should have same number of entries */ nshould = nitems ; /* allocate the result */ X = CHOLMOD(zeros) (nrow, ncol, xtype, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (NULL) ; } Xx = X->x ; } /* -------------------------------------------------------------- */ /* save the entry in the dense matrix */ /* -------------------------------------------------------------- */ if (nitems != nshould) { /* wrong format or premature end-of-file */ CHOLMOD(free_dense) (&X, Common) ; ERROR (CHOLMOD_INVALID, "invalid matrix file") ; return (NULL) ; } k = i + j*nrow ; kup = j + i*nrow ; if (xtype == CHOLMOD_REAL) { /* real matrix */ Xx [k] = x ; if (k != kup) { if (stype == STYPE_SYMMETRIC_LOWER) { /* real symmetric matrix */ Xx [kup] = x ; } else if (stype == STYPE_SKEW_SYMMETRIC) { /* real skew symmetric matrix */ Xx [kup] = -x ; } } } else if (xtype == CHOLMOD_COMPLEX) { Xx [2*k ] = x ; /* real part */ Xx [2*k+1] = z ; /* imaginary part */ if (k != kup) { if (stype == STYPE_SYMMETRIC_LOWER) { /* complex Hermitian */ Xx [2*kup ] = x ; /* real part */ Xx [2*kup+1] = -z ; /* imaginary part */ } else if (stype == STYPE_SKEW_SYMMETRIC) { /* complex skew symmetric */ Xx [2*kup ] = -x ; /* real part */ Xx [2*kup+1] = -z ; /* imaginary part */ } if (stype == STYPE_COMPLEX_SYMMETRIC_LOWER) { /* complex symmetric */ Xx [2*kup ] = x ; /* real part */ Xx [2*kup+1] = z ; /* imaginary part */ } } } } } /* ---------------------------------------------------------------------- */ /* return the new dense matrix */ /* ---------------------------------------------------------------------- */ return (X) ; } /* ========================================================================== */ /* === cholmod_read_triplet ================================================= */ /* ========================================================================== */ /* Read in a triplet matrix from a file. */ cholmod_triplet *CHOLMOD(read_triplet) ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) { char buf [MAXLINE+1] ; size_t nrow, ncol, nnz ; int stype, mtype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (f, NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* read the header and first data line */ /* ---------------------------------------------------------------------- */ if (!read_header (f, buf, &mtype, &nrow, &ncol, &nnz, &stype) || mtype != CHOLMOD_TRIPLET) { /* invalid matrix - this function can only read in a triplet matrix */ ERROR (CHOLMOD_INVALID, "invalid format") ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* read the triplet matrix */ /* ---------------------------------------------------------------------- */ return (read_triplet (f, nrow, ncol, nnz, stype, FALSE, buf, Common)) ; } /* ========================================================================== */ /* === cholmod_read_sparse ================================================== */ /* ========================================================================== */ /* Read a sparse matrix from a file. See cholmod_read_triplet for a discussion * of the file format. * * If Common->prefer_upper is TRUE (the default case), a symmetric matrix is * returned stored in upper-triangular form (A->stype == 1). */ cholmod_sparse *CHOLMOD(read_sparse) ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) { cholmod_sparse *A, *A2 ; cholmod_triplet *T ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (f, NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* convert to a sparse matrix in compressed-column form */ /* ---------------------------------------------------------------------- */ T = CHOLMOD(read_triplet) (f, Common) ; A = CHOLMOD(triplet_to_sparse) (T, 0, Common) ; CHOLMOD(free_triplet) (&T, Common) ; if (Common->prefer_upper && A != NULL && A->stype == -1) { /* A=A' */ A2 = CHOLMOD(transpose) (A, 2, Common) ; CHOLMOD(free_sparse) (&A, Common) ; A = A2 ; } return (A) ; } /* ========================================================================== */ /* === cholmod_read_dense =================================================== */ /* ========================================================================== */ /* Read a dense matrix from a file. */ cholmod_dense *CHOLMOD(read_dense) ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ /* --------------- */ cholmod_common *Common ) { char buf [MAXLINE+1] ; size_t nrow, ncol, nnz ; int stype, mtype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (f, NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* read the header and first data line */ /* ---------------------------------------------------------------------- */ if (!read_header (f, buf, &mtype, &nrow, &ncol, &nnz, &stype) || mtype != CHOLMOD_DENSE) { /* invalid matrix - this function can only read in a dense matrix */ ERROR (CHOLMOD_INVALID, "invalid format") ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* read the dense matrix */ /* ---------------------------------------------------------------------- */ return (read_dense (f, nrow, ncol, stype, buf, Common)) ; } /* ========================================================================== */ /* === cholmod_read_matrix ================================================== */ /* ========================================================================== */ /* Read a triplet matrix, sparse matrix or a dense matrix from a file. Returns * a void pointer to either a cholmod_triplet, cholmod_sparse, or cholmod_dense * object. The type of object is passed back to the caller as the mtype * argument. */ void *CHOLMOD(read_matrix) ( /* ---- input ---- */ FILE *f, /* file to read from, must already be open */ int prefer, /* If 0, a sparse matrix is always return as a * cholmod_triplet form. It can have any stype * (symmetric-lower, unsymmetric, or * symmetric-upper). * If 1, a sparse matrix is returned as an unsymmetric * cholmod_sparse form (A->stype == 0), with both * upper and lower triangular parts present. * This is what the MATLAB mread mexFunction does, * since MATLAB does not have an stype. * If 2, a sparse matrix is returned with an stype of 0 * or 1 (unsymmetric, or symmetric with upper part * stored). * This argument has no effect for dense matrices. */ /* ---- output---- */ int *mtype, /* CHOLMOD_TRIPLET, CHOLMOD_SPARSE or CHOLMOD_DENSE */ /* --------------- */ cholmod_common *Common ) { void *G = NULL ; cholmod_sparse *A, *A2 ; cholmod_triplet *T ; char buf [MAXLINE+1] ; size_t nrow, ncol, nnz ; int stype ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (NULL) ; RETURN_IF_NULL (f, NULL) ; RETURN_IF_NULL (mtype, NULL) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* read the header to determine the mtype */ /* ---------------------------------------------------------------------- */ if (!read_header (f, buf, mtype, &nrow, &ncol, &nnz, &stype)) { /* invalid matrix */ ERROR (CHOLMOD_INVALID, "invalid format") ; return (NULL) ; } /* ---------------------------------------------------------------------- */ /* read a matrix */ /* ---------------------------------------------------------------------- */ if (*mtype == CHOLMOD_TRIPLET) { /* read in the triplet matrix, converting to unsymmetric format if * prefer == 1 */ T = read_triplet (f, nrow, ncol, nnz, stype, prefer == 1, buf, Common) ; if (prefer == 0) { /* return matrix in its original triplet form */ G = T ; } else { /* return matrix in a compressed-column form */ A = CHOLMOD(triplet_to_sparse) (T, 0, Common) ; CHOLMOD(free_triplet) (&T, Common) ; if (A != NULL && prefer == 2 && A->stype == -1) { /* convert A from symmetric-lower to symmetric-upper */ A2 = CHOLMOD(transpose) (A, 2, Common) ; CHOLMOD(free_sparse) (&A, Common) ; A = A2 ; } *mtype = CHOLMOD_SPARSE ; G = A ; } } else if (*mtype == CHOLMOD_DENSE) { /* return a dense matrix */ G = read_dense (f, nrow, ncol, stype, buf, Common) ; } return (G) ; } #endif igraph/src/CHOLMOD/Check/lesser.txt0000644000175100001440000006350013430770172016501 0ustar hornikusers GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! igraph/src/CHOLMOD/Check/cholmod_write.c0000644000175100001440000005124213431000472017434 0ustar hornikusers/* ========================================================================== */ /* === Check/cholmod_write ================================================== */ /* ========================================================================== */ /* Write a matrix to a file in Matrix Market form. * * A can be sparse or full. * * If present and non-empty, A and Z must have the same dimension. Z contains * the explicit zero entries in the matrix (which MATLAB drops). The entries * of Z appear as explicit zeros in the output file. Z is optional. If it is * an empty matrix it is ignored. Z must be sparse or empty, if present. * It is ignored if A is full. * * filename is the name of the output file. comments is file whose * contents are include after the Matrix Market header and before the first * data line. Ignored if an empty string or not present. * * Except for the workspace used by cholmod_symmetry (ncol integers) for * the sparse case, these routines use no workspace at all. */ #ifndef NCHECK #include "cholmod_internal.h" #include "cholmod_check.h" #include "cholmod_matrixops.h" #include #include #define MMLEN 1024 #define MAXLINE MMLEN+6 /* ========================================================================== */ /* === include_comments ===================================================== */ /* ========================================================================== */ /* Read in the comments file, if it exists, and copy it to the Matrix Market * file. A "%" is prepended to each line. Returns TRUE if successful, FALSE * otherwise. */ static int include_comments (FILE *f, const char *comments) { FILE *cf = NULL ; char buffer [MAXLINE] ; int ok = TRUE ; if (comments != NULL && comments [0] != '\0') { cf = fopen (comments, "r") ; if (cf == NULL) { return (FALSE) ; } while (ok && fgets (buffer, MAXLINE, cf) != NULL) { /* ensure the line is not too long */ buffer [MMLEN-1] = '\0' ; buffer [MMLEN-2] = '\n' ; ok = ok && (fprintf (f, "%%%s", buffer) > 0) ; } fclose (cf) ; } return (ok) ; } /* ========================================================================== */ /* === get_value ============================================================ */ /* ========================================================================== */ /* Get the pth value in the matrix. */ static void get_value ( double *Ax, /* real values, or real/imag. for CHOLMOD_COMPLEX type */ double *Az, /* imaginary values for CHOLMOD_ZOMPLEX type */ Int p, /* get the pth entry */ Int xtype, /* A->xtype: pattern, real, complex, or zomplex */ double *x, /* the real part */ double *z /* the imaginary part */ ) { switch (xtype) { case CHOLMOD_PATTERN: *x = 1 ; *z = 0 ; break ; case CHOLMOD_REAL: *x = Ax [p] ; *z = 0 ; break ; case CHOLMOD_COMPLEX: *x = Ax [2*p] ; *z = Ax [2*p+1] ; break ; case CHOLMOD_ZOMPLEX: *x = Ax [p] ; *z = Az [p] ; break ; } } /* ========================================================================== */ /* === print_value ========================================================== */ /* ========================================================================== */ /* Print a numeric value to the file, using the shortest format that ensures * the value is written precisely. Returns TRUE if successful, FALSE otherwise. */ static int print_value ( FILE *f, /* file to print to */ double x, /* value to print */ Int is_integer /* TRUE if printing as an integer */ ) { double y ; char s [MAXLINE], *p ; Int i, dest = 0, src = 0 ; int width, ok ; if (is_integer) { i = (Int) x ; ok = (fprintf (f, ID, i) > 0) ; return (ok) ; } /* ---------------------------------------------------------------------- */ /* handle Inf and NaN */ /* ---------------------------------------------------------------------- */ /* change -inf to -HUGE_DOUBLE, and change +inf and nan to +HUGE_DOUBLE */ if (CHOLMOD_IS_NAN (x) || x >= HUGE_DOUBLE) { x = HUGE_DOUBLE ; } else if (x <= -HUGE_DOUBLE) { x = -HUGE_DOUBLE ; } /* ---------------------------------------------------------------------- */ /* find the smallest acceptable precision */ /* ---------------------------------------------------------------------- */ for (width = 6 ; width < 20 ; width++) { sprintf (s, "%.*g", width, x) ; sscanf (s, "%lg", &y) ; if (x == y) break ; } /* ---------------------------------------------------------------------- */ /* shorten the string */ /* ---------------------------------------------------------------------- */ /* change "e+0" to "e", change "e+" to "e", and change "e-0" to "e-" */ for (i = 0 ; i < MAXLINE && s [i] != '\0' ; i++) { if (s [i] == 'e') { if (s [i+1] == '+') { dest = i+1 ; if (s [i+2] == '0') { /* delete characters s[i+1] and s[i+2] */ src = i+3 ; } else { /* delete characters s[i+1] */ src = i+2 ; } } else if (s [i+1] == '-') { dest = i+2 ; if (s [i+2] == '0') { /* delete character s[i+2] */ src = i+3 ; } else { /* no change */ break ; } } while (s [src] != '\0') { s [dest++] = s [src++] ; } s [dest] = '\0' ; break ; } } /* delete the leading "0" if present and not necessary */ p = s ; s [MAXLINE-1] = '\0' ; i = strlen (s) ; if (i > 2 && s [0] == '0' && s [1] == '.') { /* change "0.x" to ".x" */ p = s + 1 ; } else if (i > 3 && s [0] == '-' && s [1] == '0' && s [2] == '.') { /* change "-0.x" to "-.x" */ s [1] = '-' ; p = s + 1 ; } #if 0 /* double-check */ i = sscanf (p, "%lg", &z) ; if (i != 1 || y != z) { /* oops! something went wrong in the "e+0" edit, above. */ /* this "cannot" happen */ sprintf (s, "%.*g", width, x) ; p = s ; } #endif /* ---------------------------------------------------------------------- */ /* print the value to the file */ /* ---------------------------------------------------------------------- */ ok = (fprintf (f, "%s", p) > 0) ; return (ok) ; } /* ========================================================================== */ /* === print_triplet ======================================================== */ /* ========================================================================== */ /* Print a triplet, converting it to one-based. Returns TRUE if successful, * FALSE otherwise. */ static int print_triplet ( FILE *f, /* file to print to */ Int is_binary, /* TRUE if file is "pattern" */ Int is_complex, /* TRUE if file is "complex" */ Int is_integer, /* TRUE if file is "integer" */ Int i, /* row index (zero-based) */ Int j, /* column index (zero-based) */ double x, /* real part */ double z /* imaginary part */ ) { int ok ; ok = (fprintf (f, ID " " ID, 1+i, 1+j) > 0) ; if (!is_binary) { fprintf (f, " ") ; ok = ok && print_value (f, x, is_integer) ; if (is_complex) { fprintf (f, " ") ; ok = ok && print_value (f, z, is_integer) ; } } ok = ok && (fprintf (f, "\n") > 0) ; return (ok) ; } /* ========================================================================== */ /* === ntriplets ============================================================ */ /* ========================================================================== */ /* Compute the number of triplets that will be printed to the file * from the matrix A. */ static Int ntriplets ( cholmod_sparse *A, /* matrix that will be printed */ Int is_sym /* TRUE if the file is symmetric (lower part only)*/ ) { Int *Ap, *Ai, *Anz, packed, i, j, p, pend, ncol, stype, nz = 0 ; if (A == NULL) { /* the Z matrix is NULL */ return (0) ; } stype = A->stype ; Ap = A->p ; Ai = A->i ; Anz = A->nz ; packed = A->packed ; ncol = A->ncol ; for (j = 0 ; j < ncol ; j++) { p = Ap [j] ; pend = (packed) ? Ap [j+1] : p + Anz [j] ; for ( ; p < pend ; p++) { i = Ai [p] ; if ((stype < 0 && i >= j) || (stype == 0 && (i >= j || !is_sym))) { /* CHOLMOD matrix is symmetric-lower (and so is the file); * or CHOLMOD matrix is unsymmetric and either A(i,j) is in * the lower part or the file is unsymmetric. */ nz++ ; } else if (stype > 0 && i <= j) { /* CHOLMOD matrix is symmetric-upper, but the file is * symmetric-lower. Need to transpose the entry. */ nz++ ; } } } return (nz) ; } /* ========================================================================== */ /* === cholmod_write_sparse ================================================= */ /* ========================================================================== */ /* Write a sparse matrix to a file in Matrix Market format. Optionally include * comments, and print explicit zero entries given by the pattern of the Z * matrix. If not NULL, the Z matrix must have the same dimensions and stype * as A. * * Returns the symmetry in which the matrix was printed (1 to 7, see the * CHOLMOD_MM_* codes in CHOLMOD/Include/cholmod_core.h), or -1 on failure. * * If A and Z are sorted on input, and either unsymmetric (stype = 0) or * symmetric-lower (stype < 0), and if A and Z do not overlap, then the triplets * are sorted, first by column and then by row index within each column, with * no duplicate entries. If all the above holds except stype > 0, then the * triplets are sorted by row first and then column. */ int CHOLMOD(write_sparse) ( /* ---- input ---- */ FILE *f, /* file to write to, must already be open */ cholmod_sparse *A, /* matrix to print */ cholmod_sparse *Z, /* optional matrix with pattern of explicit zeros */ const char *comments, /* optional filename of comments to include */ /* --------------- */ cholmod_common *Common ) { double x = 0, z = 0 ; double *Ax, *Az ; Int *Ap, *Ai, *Anz, *Zp, *Zi, *Znz ; Int nrow, ncol, is_complex, symmetry, i, j, q, iz, p, nz, is_binary, stype, is_integer, asym, is_sym, xtype, apacked, zpacked, pend, qend, zsym ; int ok ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (f, EMPTY) ; RETURN_IF_NULL (A, EMPTY) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; if (Z != NULL && (Z->nrow == 0 || Z->ncol == 0)) { /* Z is non-NULL but empty, so treat it as a NULL matrix */ Z = NULL ; } if (Z != NULL) { RETURN_IF_XTYPE_INVALID (Z, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, EMPTY) ; if (Z->nrow != A->nrow || Z->ncol != A->ncol || Z->stype != A->stype) { ERROR (CHOLMOD_INVALID, "dimension or type of A and Z mismatch") ; return (EMPTY) ; } } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get the A matrix */ /* ---------------------------------------------------------------------- */ Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; nrow = A->nrow ; ncol = A->ncol ; xtype = A->xtype ; apacked = A->packed ; if (xtype == CHOLMOD_PATTERN) { /* a CHOLMOD pattern matrix is printed as "pattern" in the file */ is_binary = TRUE ; is_integer = FALSE ; is_complex = FALSE ; } else if (xtype == CHOLMOD_REAL) { /* determine if a real matrix is in fact binary or integer */ is_binary = TRUE ; is_integer = TRUE ; is_complex = FALSE ; for (j = 0 ; (is_binary || is_integer) && j < ncol ; j++) { p = Ap [j] ; pend = (apacked) ? Ap [j+1] : p + Anz [j] ; for ( ; (is_binary || is_integer) && p < pend ; p++) { x = Ax [p] ; if (x != 1) { is_binary = FALSE ; } /* convert to Int and then back to double */ i = (Int) x ; z = (double) i ; if (z != x) { is_integer = FALSE ; } } } } else { /* a CHOLMOD complex matrix is printed as "complex" in the file */ is_binary = FALSE ; is_integer = FALSE ; is_complex = TRUE ; } /* ---------------------------------------------------------------------- */ /* get the Z matrix (only consider the pattern) */ /* ---------------------------------------------------------------------- */ Zp = NULL ; Zi = NULL ; Znz = NULL ; zpacked = TRUE ; if (Z != NULL) { Zp = Z->p ; Zi = Z->i ; Znz = Z->nz ; zpacked = Z->packed ; } /* ---------------------------------------------------------------------- */ /* determine the symmetry of A and Z */ /* ---------------------------------------------------------------------- */ stype = A->stype ; if (A->nrow != A->ncol) { asym = CHOLMOD_MM_RECTANGULAR ; } else if (stype != 0) { /* CHOLMOD's A and Z matrices have a symmetric (and matching) stype. * Note that the diagonal is not checked. */ asym = is_complex ? CHOLMOD_MM_HERMITIAN : CHOLMOD_MM_SYMMETRIC ; } else if (!A->sorted) { /* A is in unsymmetric storage, but unsorted */ asym = CHOLMOD_MM_UNSYMMETRIC ; } else { /* CHOLMOD's stype is zero (stored in unsymmetric form) */ asym = EMPTY ; zsym = EMPTY ; #ifndef NMATRIXOPS /* determine if the matrices are in fact symmetric or Hermitian */ asym = CHOLMOD(symmetry) (A, 1, NULL, NULL, NULL, NULL, Common) ; zsym = (Z == NULL) ? 999 : CHOLMOD(symmetry) (Z, 1, NULL, NULL, NULL, NULL, Common) ; #endif if (asym == EMPTY || zsym <= CHOLMOD_MM_UNSYMMETRIC) { /* not computed, out of memory, or Z is unsymmetric */ asym = CHOLMOD_MM_UNSYMMETRIC ; } } /* ---------------------------------------------------------------------- */ /* write the Matrix Market header */ /* ---------------------------------------------------------------------- */ ok = fprintf (f, "%%%%MatrixMarket matrix coordinate") > 0 ; if (is_complex) { ok = ok && (fprintf (f, " complex") > 0) ; } else if (is_binary) { ok = ok && (fprintf (f, " pattern") > 0) ; } else if (is_integer) { ok = ok && (fprintf (f, " integer") > 0) ; } else { ok = ok && (fprintf (f, " real") > 0) ; } is_sym = FALSE ; switch (asym) { case CHOLMOD_MM_RECTANGULAR: case CHOLMOD_MM_UNSYMMETRIC: /* A is rectangular or unsymmetric */ ok = ok && (fprintf (f, " general\n") > 0) ; is_sym = FALSE ; symmetry = CHOLMOD_MM_UNSYMMETRIC ; break ; case CHOLMOD_MM_SYMMETRIC: case CHOLMOD_MM_SYMMETRIC_POSDIAG: /* A is symmetric */ ok = ok && (fprintf (f, " symmetric\n") > 0) ; is_sym = TRUE ; symmetry = CHOLMOD_MM_SYMMETRIC ; break ; case CHOLMOD_MM_HERMITIAN: case CHOLMOD_MM_HERMITIAN_POSDIAG: /* A is Hermitian */ ok = ok && (fprintf (f, " Hermitian\n") > 0) ; is_sym = TRUE ; symmetry = CHOLMOD_MM_HERMITIAN ; break ; case CHOLMOD_MM_SKEW_SYMMETRIC: /* A is skew symmetric */ ok = ok && (fprintf (f, " skew-symmetric\n") > 0) ; is_sym = TRUE ; symmetry = CHOLMOD_MM_SKEW_SYMMETRIC ; break ; } /* ---------------------------------------------------------------------- */ /* include the comments if present */ /* ---------------------------------------------------------------------- */ ok = ok && include_comments (f, comments) ; /* ---------------------------------------------------------------------- */ /* write a sparse matrix (A and Z) */ /* ---------------------------------------------------------------------- */ nz = ntriplets (A, is_sym) + ntriplets (Z, is_sym) ; /* write the first data line, with nrow, ncol, and # of triplets */ ok = ok && (fprintf (f, ID " " ID " " ID "\n", nrow, ncol, nz) > 0) ; for (j = 0 ; ok && j < ncol ; j++) { /* merge column of A and Z */ p = Ap [j] ; pend = (apacked) ? Ap [j+1] : p + Anz [j] ; q = (Z == NULL) ? 0 : Zp [j] ; qend = (Z == NULL) ? 0 : ((zpacked) ? Zp [j+1] : q + Znz [j]) ; while (ok) { /* get the next row index from A and Z */ i = (p < pend) ? Ai [p] : (nrow+1) ; iz = (q < qend) ? Zi [q] : (nrow+2) ; if (i <= iz) { /* get A(i,j), or quit if both A and Z are exhausted */ if (i == nrow+1) break ; get_value (Ax, Az, p, xtype, &x, &z) ; p++ ; } else { /* get Z(i,j) */ i = iz ; x = 0 ; z = 0 ; q++ ; } if ((stype < 0 && i >= j) || (stype == 0 && (i >= j || !is_sym))) { /* CHOLMOD matrix is symmetric-lower (and so is the file); * or CHOLMOD matrix is unsymmetric and either A(i,j) is in * the lower part or the file is unsymmetric. */ ok = ok && print_triplet (f, is_binary, is_complex, is_integer, i,j, x,z) ; } else if (stype > 0 && i <= j) { /* CHOLMOD matrix is symmetric-upper, but the file is * symmetric-lower. Need to transpose the entry. If the * matrix is real, the complex part is ignored. If the matrix * is complex, it Hermitian. */ ASSERT (IMPLIES (is_complex, asym == CHOLMOD_MM_HERMITIAN)) ; if (z != 0) { z = -z ; } ok = ok && print_triplet (f, is_binary, is_complex, is_integer, j,i, x,z) ; } } } if (!ok) { ERROR (CHOLMOD_INVALID, "error reading/writing file") ; return (EMPTY) ; } return (asym) ; } /* ========================================================================== */ /* === cholmod_write_dense ================================================== */ /* ========================================================================== */ /* Write a dense matrix to a file in Matrix Market format. Optionally include * comments. Returns > 0 if successful, -1 otherwise (1 if rectangular, 2 if * square). Future versions may return 1 to 7 on success (a CHOLMOD_MM_* code, * just as cholmod_write_sparse does). * * A dense matrix is written in "general" format; symmetric formats in the * Matrix Market standard are not exploited. */ int CHOLMOD(write_dense) ( /* ---- input ---- */ FILE *f, /* file to write to, must already be open */ cholmod_dense *X, /* matrix to print */ const char *comments, /* optional filename of comments to include */ /* --------------- */ cholmod_common *Common ) { double x = 0, z = 0 ; double *Xx, *Xz ; Int nrow, ncol, is_complex, i, j, xtype, p ; int ok ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (EMPTY) ; RETURN_IF_NULL (f, EMPTY) ; RETURN_IF_NULL (X, EMPTY) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, EMPTY) ; Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* get the X matrix */ /* ---------------------------------------------------------------------- */ Xx = X->x ; Xz = X->z ; nrow = X->nrow ; ncol = X->ncol ; xtype = X->xtype ; is_complex = (xtype == CHOLMOD_COMPLEX) || (xtype == CHOLMOD_ZOMPLEX) ; /* ---------------------------------------------------------------------- */ /* write the Matrix Market header */ /* ---------------------------------------------------------------------- */ ok = (fprintf (f, "%%%%MatrixMarket matrix array") > 0) ; if (is_complex) { ok = ok && (fprintf (f, " complex general\n") > 0) ; } else { ok = ok && (fprintf (f, " real general\n") > 0) ; } /* ---------------------------------------------------------------------- */ /* include the comments if present */ /* ---------------------------------------------------------------------- */ ok = ok && include_comments (f, comments) ; /* ---------------------------------------------------------------------- */ /* write a dense matrix */ /* ---------------------------------------------------------------------- */ /* write the first data line, with nrow and ncol */ ok = ok && (fprintf (f, ID " " ID "\n", nrow, ncol) > 0) ; Xx = X->x ; Xz = X->z ; for (j = 0 ; ok && j < ncol ; j++) { for (i = 0 ; ok && i < nrow ; i++) { p = i + j*nrow ; get_value (Xx, Xz, p, xtype, &x, &z) ; ok = ok && print_value (f, x, FALSE) ; if (is_complex) { ok = ok && (fprintf (f, " ") > 0) ; ok = ok && print_value (f, z, FALSE) ; } ok = ok && (fprintf (f, "\n") > 0) ; } } if (!ok) { ERROR (CHOLMOD_INVALID, "error reading/writing file") ; return (EMPTY) ; } return ((nrow == ncol) ? CHOLMOD_MM_UNSYMMETRIC : CHOLMOD_MM_RECTANGULAR) ; } #endif igraph/src/CHOLMOD/Check/License.txt0000644000175100001440000000204213430770172016560 0ustar hornikusersCHOLMOD/Check Module. Copyright (C) 2005-2006, Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Check module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA igraph/src/CHOLMOD/Check/cholmod_check.c0000644000175100001440000020250413431000472017356 0ustar hornikusers/* ========================================================================== */ /* === Check/cholmod_check ================================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Check Module. Copyright (C) 2005-2013, Timothy A. Davis * The CHOLMOD/Check Module is licensed under Version 2.1 of the GNU * Lesser General Public License. See lesser.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ /* Routines to check and print the contents of the 5 CHOLMOD objects: * * No CHOLMOD routine calls the check or print routines. If a user wants to * check CHOLMOD's input parameters, a separate call to the appropriate check * routine should be used before calling other CHOLMOD routines. * * cholmod_check_common check statistics and workspace in Common * cholmod_check_sparse check sparse matrix in compressed column form * cholmod_check_dense check dense matrix * cholmod_check_factor check factorization * cholmod_check_triplet check sparse matrix in triplet form * * cholmod_print_common print statistics in Common * cholmod_print_sparse print sparse matrix in compressed column form * cholmod_print_dense print dense matrix * cholmod_print_factor print factorization * cholmod_print_triplet print sparse matrix in triplet form * * In addition, this file contains routines to check and print three types of * integer vectors: * * cholmod_check_perm check a permutation of 0:n-1 (no duplicates) * cholmod_check_subset check a subset of 0:n-1 (duplicates OK) * cholmod_check_parent check an elimination tree * * cholmod_print_perm print a permutation * cholmod_print_subset print a subset * cholmod_print_parent print an elimination tree * * Each Common->print level prints the items at or below the given level: * * 0: print nothing; just check the data structures and return TRUE/FALSE * 1: error messages * 2: warning messages * 3: one-line summary of each object printed * 4: short summary of each object (first and last few entries) * 5: entire contents of the object * * No CHOLMOD routine calls these routines, so no printing occurs unless * the user specifically calls a cholmod_print_* routine. Thus, the default * print level is 3. * * Common->precise controls the # of digits printed for numerical entries * (5 if FALSE, 15 if TRUE). * * If Common->print_function is NULL, then no printing occurs. The * cholmod_check_* and cholmod_print_* routines still check their inputs and * return TRUE/FALSE if the object is valid or not. * * This file also includes debugging routines that are enabled only when * NDEBUG is defined in cholmod_internal.h (cholmod_dump_*). */ #ifndef NCHECK #include "cholmod_internal.h" #include "cholmod_check.h" /* ========================================================================== */ /* === printing definitions ================================================= */ /* ========================================================================== */ #ifdef LONG #define I8 "%8ld" #define I_8 "%-8ld" #else #define I8 "%8d" #define I_8 "%-8d" #endif #define PR(i,format,arg) \ { \ if (print >= i && Common->print_function != NULL) \ { \ (Common->print_function) (format, arg) ; \ } \ } #define P1(format,arg) PR(1,format,arg) #define P2(format,arg) PR(2,format,arg) #define P3(format,arg) PR(3,format,arg) #define P4(format,arg) PR(4,format,arg) #define ERR(msg) \ { \ P1 ("\nCHOLMOD ERROR: %s: ", type) ; \ if (name != NULL) \ { \ P1 ("%s", name) ; \ } \ P1 (": %s\n", msg) ; \ ERROR (CHOLMOD_INVALID, "invalid") ; \ return (FALSE) ; \ } /* print a numerical value */ #define PRINTVALUE(value) \ { \ if (Common->precise) \ { \ P4 (" %23.15e", value) ; \ } \ else \ { \ P4 (" %.5g", value) ; \ } \ } /* start printing */ #define ETC_START(count,limit) \ { \ count = (init_print == 4) ? (limit) : (-1) ; \ } /* re-enable printing if condition is met */ #define ETC_ENABLE(condition,count,limit) \ { \ if ((condition) && init_print == 4) \ { \ count = limit ; \ print = 4 ; \ } \ } /* turn off printing if limit is reached */ #define ETC_DISABLE(count) \ { \ if ((count >= 0) && (count-- == 0) && print == 4) \ { \ P4 ("%s", " ...\n") ; \ print = 3 ; \ } \ } /* re-enable printing, or turn if off after limit is reached */ #define ETC(condition,count,limit) \ { \ ETC_ENABLE (condition, count, limit) ; \ ETC_DISABLE (count) ; \ } #define BOOLSTR(x) ((x) ? "true " : "false") /* ========================================================================== */ /* === print_value ========================================================== */ /* ========================================================================== */ static void print_value ( Int print, Int xtype, double *Xx, double *Xz, Int p, cholmod_common *Common) { if (xtype == CHOLMOD_REAL) { PRINTVALUE (Xx [p]) ; } else if (xtype == CHOLMOD_COMPLEX) { P4 ("%s", "(") ; PRINTVALUE (Xx [2*p ]) ; P4 ("%s", " , ") ; PRINTVALUE (Xx [2*p+1]) ; P4 ("%s", ")") ; } else if (xtype == CHOLMOD_ZOMPLEX) { P4 ("%s", "(") ; PRINTVALUE (Xx [p]) ; P4 ("%s", " , ") ; PRINTVALUE (Xz [p]) ; P4 ("%s", ")") ; } } /* ========================================================================== */ /* === cholmod_check_common ================================================= */ /* ========================================================================== */ /* Print and verify the contents of Common */ static int check_common ( Int print, const char *name, cholmod_common *Common ) { double fl, lnz ; double *Xwork ; Int *Flag, *Head ; SuiteSparse_long mark ; Int i, nrow, nmethods, ordering, xworksize, amd_backup, init_print ; const char *type = "common" ; /* ---------------------------------------------------------------------- */ /* print control parameters and statistics */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; init_print = print ; P2 ("%s", "\n") ; P1 ("CHOLMOD version %d", CHOLMOD_MAIN_VERSION) ; P1 (".%d", CHOLMOD_SUB_VERSION) ; P1 (".%d", CHOLMOD_SUBSUB_VERSION) ; P1 (", %s: ", CHOLMOD_DATE) ; if (name != NULL) { P1 ("%s: ", name) ; } switch (Common->status) { case CHOLMOD_OK: P1 ("%s", "status: OK\n") ; break ; case CHOLMOD_OUT_OF_MEMORY: P1 ("%s", "status: ERROR, out of memory\n") ; break ; case CHOLMOD_INVALID: P1 ("%s", "status: ERROR, invalid parameter\n") ; break ; case CHOLMOD_TOO_LARGE: P1 ("%s", "status: ERROR, problem too large\n") ; break ; case CHOLMOD_NOT_INSTALLED: P1 ("%s", "status: ERROR, method not installed\n") ; break ; #if GPU_BLAS case CHOLMOD_GPU_PROBLEM: P1 ("%s", "status: ERROR, GPU had a fatal error\n") ; break ; #endif case CHOLMOD_NOT_POSDEF: P1 ("%s", "status: warning, matrix not positive definite\n") ; break ; case CHOLMOD_DSMALL: P1 ("%s", "status: warning, diagonal entry has tiny abs. value\n") ; break ; default: ERR ("unknown status") ; } P2 (" Architecture: %s\n", CHOLMOD_ARCHITECTURE) ; P3 (" sizeof(int): %d\n", (int) sizeof (int)) ; P3 (" sizeof(SuiteSparse_long): %d\n", (int) sizeof (SuiteSparse_long)); P3 (" sizeof(void *): %d\n", (int) sizeof (void *)) ; P3 (" sizeof(double): %d\n", (int) sizeof (double)) ; P3 (" sizeof(Int): %d (CHOLMOD's basic integer)\n", (int) sizeof (Int)) ; P3 (" sizeof(BLAS_INT): %d (integer used in the BLAS)\n", (int) sizeof (BLAS_INT)) ; if (Common->fl != EMPTY) { P2 ("%s", " Results from most recent analysis:\n") ; P2 (" Cholesky flop count: %.5g\n", Common->fl) ; P2 (" Nonzeros in L: %.5g\n", Common->lnz) ; } if (Common->modfl != EMPTY) { P2 (" Update/downdate flop count: %.5g\n", Common->modfl) ; } P2 (" memory blocks in use: %8.0f\n", (double) (Common->malloc_count)) ; P2 (" memory in use (MB): %8.1f\n", (double) (Common->memory_inuse) / 1048576.) ; P2 (" peak memory usage (MB): %8.1f\n", (double) (Common->memory_usage) / 1048576.) ; /* ---------------------------------------------------------------------- */ /* primary control parameters and related ordering statistics */ /* ---------------------------------------------------------------------- */ P3 (" maxrank: update/downdate rank: "ID"\n", (Int) CHOLMOD(maxrank) (0, Common)) ; P3 (" supernodal control: %d", Common->supernodal) ; P3 (" %g ", Common->supernodal_switch) ; if (Common->supernodal <= CHOLMOD_SIMPLICIAL) { P3 ("%s", "(always do simplicial)\n") ; } else if (Common->supernodal == CHOLMOD_AUTO) { P3 ("(supernodal if flops/lnz >= %g)\n", Common->supernodal_switch) ; } else { P3 ("%s", "(always do supernodal)\n") ; } nmethods = MIN (Common->nmethods, CHOLMOD_MAXMETHODS) ; nmethods = MAX (0, nmethods) ; if (nmethods > 0) { P3 ("%s", " nmethods: number of ordering methods to try: ") ; P3 (""ID"\n", nmethods) ; amd_backup = (nmethods > 1) || (nmethods == 1 && (Common->method [0].ordering == CHOLMOD_METIS || Common->method [0].ordering == CHOLMOD_NESDIS)) ; } else { P3 ("%s", " nmethods=0: default strategy: Try user permutation if " "given. Try AMD.\n") ; #ifndef NPARTITION if (Common->default_nesdis) { P3 ("%s", " Try NESDIS if AMD reports flops/nnz(L) >= 500 and " "nnz(L)/nnz(A) >= 5.\n") ; } else { P3 ("%s", " Try METIS if AMD reports flops/nnz(L) >= 500 and " "nnz(L)/nnz(A) >= 5.\n") ; } #endif P3 ("%s", " Select best ordering tried.\n") ; Common->method [0].ordering = CHOLMOD_GIVEN ; Common->method [1].ordering = CHOLMOD_AMD ; Common->method [2].ordering = (Common->default_nesdis ? CHOLMOD_NESDIS : CHOLMOD_METIS) ; amd_backup = FALSE ; #ifndef NPARTITION nmethods = 3 ; #else nmethods = 2 ; #endif } for (i = 0 ; i < nmethods ; i++) { P3 (" method "ID": ", i) ; ordering = Common->method [i].ordering ; fl = Common->method [i].fl ; lnz = Common->method [i].lnz ; switch (ordering) { case CHOLMOD_NATURAL: P3 ("%s", "natural\n") ; break ; case CHOLMOD_GIVEN: P3 ("%s", "user permutation (if given)\n") ; break ; case CHOLMOD_AMD: P3 ("%s", "AMD (or COLAMD if factorizing AA')\n") ; amd_backup = FALSE ; break ; case CHOLMOD_COLAMD: P3 ("%s", "AMD if factorizing A, COLAMD if factorizing AA')\n"); amd_backup = FALSE ; break ; case CHOLMOD_METIS: P3 ("%s", "METIS_NodeND nested dissection\n") ; break ; case CHOLMOD_NESDIS: P3 ("%s", "CHOLMOD nested dissection\n") ; P3 (" nd_small: # nodes in uncut subgraph: "ID"\n", (Int) (Common->method [i].nd_small)) ; P3 (" nd_compress: compress the graph: %s\n", BOOLSTR (Common->method [i].nd_compress)) ; P3 (" nd_camd: use constrained min degree: %s\n", BOOLSTR (Common->method [i].nd_camd)) ; break ; default: P3 (ID, ordering) ; ERR ("unknown ordering method") ; break ; } if (!(ordering == CHOLMOD_NATURAL || ordering == CHOLMOD_GIVEN)) { if (Common->method [i].prune_dense < 0) { P3 (" prune_dense: for pruning dense nodes: %s\n", " none pruned") ; } else { P3 (" prune_dense: for pruning dense nodes: " "%.5g\n", Common->method [i].prune_dense) ; P3 (" a dense node has degree " ">= max(16,(%.5g)*sqrt(n))\n", Common->method [i].prune_dense) ; } } if (ordering == CHOLMOD_COLAMD || ordering == CHOLMOD_NESDIS) { if (Common->method [i].prune_dense2 < 0) { P3 (" prune_dense2: for pruning dense rows for AA':" " %s\n", " none pruned") ; } else { P3 (" prune_dense2: for pruning dense rows for AA':" " %.5g\n", Common->method [i].prune_dense2) ; P3 (" a dense row has degree " ">= max(16,(%.5g)*sqrt(ncol))\n", Common->method [i].prune_dense2) ; } } if (fl != EMPTY) P3 (" flop count: %.5g\n", fl) ; if (lnz != EMPTY) P3 (" nnz(L): %.5g\n", lnz) ; } /* backup AMD results, if any */ if (amd_backup) { P3 ("%s", " backup method: ") ; P3 ("%s", "AMD (or COLAMD if factorizing AA')\n") ; fl = Common->method [nmethods].fl ; lnz = Common->method [nmethods].lnz ; if (fl != EMPTY) P3 (" AMD flop count: %.5g\n", fl) ; if (lnz != EMPTY) P3 (" AMD nnz(L): %.5g\n", lnz) ; } /* ---------------------------------------------------------------------- */ /* arcane control parameters */ /* ---------------------------------------------------------------------- */ if (Common->final_asis) { P4 ("%s", " final_asis: TRUE, leave as is\n") ; } else { P4 ("%s", " final_asis: FALSE, convert when done\n") ; if (Common->final_super) { P4 ("%s", " final_super: TRUE, leave in supernodal form\n") ; } else { P4 ("%s", " final_super: FALSE, convert to simplicial form\n") ; } if (Common->final_ll) { P4 ("%s", " final_ll: TRUE, convert to LL' form\n") ; } else { P4 ("%s", " final_ll: FALSE, convert to LDL' form\n") ; } if (Common->final_pack) { P4 ("%s", " final_pack: TRUE, pack when done\n") ; } else { P4 ("%s", " final_pack: FALSE, do not pack when done\n") ; } if (Common->final_monotonic) { P4 ("%s", " final_monotonic: TRUE, ensure L is monotonic\n") ; } else { P4 ("%s", " final_monotonic: FALSE, do not ensure L is monotonic\n") ; } P4 (" final_resymbol: remove zeros from amalgamation: %s\n", BOOLSTR (Common->final_resymbol)) ; } P4 (" dbound: LDL' diagonal threshold: % .5g\n Entries with abs. value" " less than dbound are replaced with +/- dbound.\n", Common->dbound) ; P4 (" grow0: memory reallocation: % .5g\n", Common->grow0) ; P4 (" grow1: memory reallocation: % .5g\n", Common->grow1) ; P4 (" grow2: memory reallocation: %g\n", (double) (Common->grow2)) ; P4 ("%s", " nrelax, zrelax: supernodal amalgamation rule:\n") ; P4 ("%s", " s = # columns in two adjacent supernodes\n") ; P4 ("%s", " z = % of zeros in new supernode if they are merged.\n") ; P4 ("%s", " Two supernodes are merged if") ; P4 (" (s <= %g) or (no new zero entries) or\n", (double) (Common->nrelax [0])) ; P4 (" (s <= %g and ", (double) (Common->nrelax [1])) ; P4 ("z < %.5g%%) or", Common->zrelax [0] * 100) ; P4 (" (s <= %g and ", (double) (Common->nrelax [2])) ; P4 ("z < %.5g%%) or", Common->zrelax [1] * 100) ; P4 (" (z < %.5g%%)\n", Common->zrelax [2] * 100) ; /* ---------------------------------------------------------------------- */ /* check workspace */ /* ---------------------------------------------------------------------- */ mark = Common->mark ; nrow = Common->nrow ; Flag = Common->Flag ; Head = Common->Head ; if (nrow > 0) { if (mark < 0 || Flag == NULL || Head == NULL) { ERR ("workspace corrupted (Flag and/or Head missing)") ; } for (i = 0 ; i < nrow ; i++) { if (Flag [i] >= mark) { PRINT0 (("Flag ["ID"]="ID", mark = %ld\n", i, Flag [i], mark)) ; ERR ("workspace corrupted (Flag)") ; } } for (i = 0 ; i <= nrow ; i++) { if (Head [i] != EMPTY) { PRINT0 (("Head ["ID"] = "ID",\n", i, Head [i])) ; ERR ("workspace corrupted (Head)") ; } } } xworksize = Common->xworksize ; Xwork = Common->Xwork ; if (xworksize > 0) { if (Xwork == NULL) { ERR ("workspace corrupted (Xwork missing)") ; } for (i = 0 ; i < xworksize ; i++) { if (Xwork [i] != 0.) { PRINT0 (("Xwork ["ID"] = %g\n", i, Xwork [i])) ; ERR ("workspace corrupted (Xwork)") ; } } } /* workspace and parameters are valid */ P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_common) ( cholmod_common *Common ) { return (check_common (0, NULL, Common)) ; } int CHOLMOD(print_common) ( /* ---- input ---- */ const char *name, /* printed name of Common object */ /* --------------- */ cholmod_common *Common ) { Int print = (Common == NULL) ? 3 : (Common->print) ; return (check_common (print, name, Common)) ; } /* ========================================================================== */ /* === cholmod_gpu_stats ==================================================== */ /* ========================================================================== */ /* Print CPU / GPU statistics. If the timer is not installed, the times are reported as zero, but this function still works. Likewise, the function still works if the GPU BLAS is not installed. */ int CHOLMOD(gpu_stats) ( cholmod_common *Common /* input */ ) { double cpu_time, gpu_time ; int print ; RETURN_IF_NULL_COMMON (FALSE) ; print = Common->print ; P2 ("%s", "\nCHOLMOD GPU/CPU statistics:\n") ; P2 ("SYRK CPU calls %12.0f", (double) Common->CHOLMOD_CPU_SYRK_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_CPU_SYRK_TIME) ; P2 (" GPU calls %12.0f", (double) Common->CHOLMOD_GPU_SYRK_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_GPU_SYRK_TIME) ; P2 ("GEMM CPU calls %12.0f", (double) Common->CHOLMOD_CPU_GEMM_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_CPU_GEMM_TIME) ; P2 (" GPU calls %12.0f", (double) Common->CHOLMOD_GPU_GEMM_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_GPU_GEMM_TIME) ; P2 ("POTRF CPU calls %12.0f", (double) Common->CHOLMOD_CPU_POTRF_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_CPU_POTRF_TIME) ; P2 (" GPU calls %12.0f", (double) Common->CHOLMOD_GPU_POTRF_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_GPU_POTRF_TIME) ; P2 ("TRSM CPU calls %12.0f", (double) Common->CHOLMOD_CPU_TRSM_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_CPU_TRSM_TIME) ; P2 (" GPU calls %12.0f", (double) Common->CHOLMOD_GPU_TRSM_CALLS) ; P2 (" time %12.4e\n", Common->CHOLMOD_GPU_TRSM_TIME) ; cpu_time = Common->CHOLMOD_CPU_SYRK_TIME + Common->CHOLMOD_CPU_TRSM_TIME + Common->CHOLMOD_CPU_GEMM_TIME + Common->CHOLMOD_CPU_POTRF_TIME ; gpu_time = Common->CHOLMOD_GPU_SYRK_TIME + Common->CHOLMOD_GPU_TRSM_TIME + Common->CHOLMOD_GPU_GEMM_TIME + Common->CHOLMOD_GPU_POTRF_TIME ; P2 ("time in the BLAS: CPU %12.4e", cpu_time) ; P2 (" GPU %12.4e", gpu_time) ; P2 (" total: %12.4e\n", cpu_time + gpu_time) ; P2 ("assembly time %12.4e", Common->CHOLMOD_ASSEMBLE_TIME) ; P2 (" %12.4e\n", Common->CHOLMOD_ASSEMBLE_TIME2) ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_check_sparse ================================================= */ /* ========================================================================== */ /* Ensure that a sparse matrix in column-oriented form is valid, and optionally * print it. Returns the number of entries on the diagonal or -1 if error. * * workspace: Iwork (nrow) */ static SuiteSparse_long check_sparse ( Int *Wi, Int print, const char *name, cholmod_sparse *A, SuiteSparse_long *nnzdiag, cholmod_common *Common ) { double *Ax, *Az ; Int *Ap, *Ai, *Anz ; Int nrow, ncol, nzmax, sorted, packed, j, p, pend, i, nz, ilast, space, init_print, dnz, count, xtype ; const char *type = "sparse" ; /* ---------------------------------------------------------------------- */ /* print header information */ /* ---------------------------------------------------------------------- */ P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD sparse: ") ; if (name != NULL) { P3 ("%s: ", name) ; } if (A == NULL) { ERR ("null") ; } nrow = A->nrow ; ncol = A->ncol ; nzmax = A->nzmax ; sorted = A->sorted ; packed = A->packed ; xtype = A->xtype ; Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; nz = CHOLMOD(nnz) (A, Common) ; P3 (" "ID"", nrow) ; P3 ("-by-"ID", ", ncol) ; P3 ("nz "ID",", nz) ; if (A->stype > 0) { P3 ("%s", " upper.") ; } else if (A->stype < 0) { P3 ("%s", " lower.") ; } else { P3 ("%s", " up/lo.") ; } P4 ("\n nzmax "ID", ", nzmax) ; if (nz > nzmax) { ERR ("nzmax too small") ; } if (!sorted) { P4 ("%s", "un") ; } P4 ("%s", "sorted, ") ; if (!packed) { P4 ("%s", "un") ; } P4 ("%s", "packed, ") ; switch (A->itype) { case CHOLMOD_INT: P4 ("%s", "\n scalar types: int, ") ; break ; case CHOLMOD_INTLONG: ERR ("mixed int/long type unsupported") ; case CHOLMOD_LONG: P4 ("%s", "\n scalar types: SuiteSparse_long, "); break ; default: ERR ("unknown itype") ; } switch (A->xtype) { case CHOLMOD_PATTERN: P4 ("%s", "pattern") ; break ; case CHOLMOD_REAL: P4 ("%s", "real") ; break ; case CHOLMOD_COMPLEX: P4 ("%s", "complex") ; break ; case CHOLMOD_ZOMPLEX: P4 ("%s", "zomplex") ; break ; default: ERR ("unknown xtype") ; } switch (A->dtype) { case CHOLMOD_DOUBLE: P4 ("%s", ", double\n") ; break ; case CHOLMOD_SINGLE: ERR ("float unsupported") ; default: ERR ("unknown dtype") ; } if (A->itype != ITYPE || A->dtype != DTYPE) { ERR ("integer and real type must match routine") ; } if (A->stype && nrow != ncol) { ERR ("symmetric but not square") ; } /* check for existence of Ap, Ai, Anz, Ax, and Az arrays */ if (Ap == NULL) { ERR ("p array not present") ; } if (Ai == NULL) { ERR ("i array not present") ; } if (!packed && Anz == NULL) { ERR ("nz array not present") ; } if (xtype != CHOLMOD_PATTERN && Ax == NULL) { ERR ("x array not present") ; } if (xtype == CHOLMOD_ZOMPLEX && Az == NULL) { ERR ("z array not present") ; } /* packed matrices must start at Ap [0] = 0 */ if (packed && Ap [0] != 0) { ERR ("p [0] must be zero") ; } if (packed && (Ap [ncol] < Ap [0] || Ap [ncol] > nzmax)) { ERR ("p [ncol] invalid") ; } /* ---------------------------------------------------------------------- */ /* allocate workspace if needed */ /* ---------------------------------------------------------------------- */ if (!sorted) { if (Wi == NULL) { CHOLMOD(allocate_work) (0, nrow, 0, Common) ; Wi = Common->Iwork ; /* size nrow, (i/i/l) */ } if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } for (i = 0 ; i < nrow ; i++) { Wi [i] = EMPTY ; } } /* ---------------------------------------------------------------------- */ /* check and print each column */ /* ---------------------------------------------------------------------- */ init_print = print ; dnz = 0 ; ETC_START (count, 8) ; for (j = 0 ; j < ncol ; j++) { ETC (j == ncol-1, count, 4) ; p = Ap [j] ; if (packed) { pend = Ap [j+1] ; nz = pend - p ; } else { /* Note that Anz [j] < 0 is treated as zero */ nz = MAX (0, Anz [j]) ; pend = p + nz ; } /* Note that space can be negative if the matrix is non-monotonic */ space = Ap [j+1] - p ; P4 (" col "ID":", j) ; P4 (" nz "ID"", nz) ; P4 (" start "ID"", p) ; P4 (" end "ID"", pend) ; if (!packed) { P4 (" space "ID"", space) ; } P4 ("%s", ":\n") ; if (p < 0 || pend > nzmax) { ERR ("pointer invalid") ; } if (nz < 0 || nz > nrow) { ERR ("nz invalid") ; } ilast = EMPTY ; for ( ; p < pend ; p++) { ETC (j == ncol-1 && p >= pend-4, count, -1) ; i = Ai [p] ; P4 (" "I8":", i) ; print_value (print, xtype, Ax, Az, p, Common) ; if (i == j) { dnz++ ; } if (i < 0 || i >= nrow) { ERR ("row index out of range") ; } if (sorted && i <= ilast) { ERR ("row indices out of order") ; } if (!sorted && Wi [i] == j) { ERR ("duplicate row index") ; } P4 ("%s", "\n") ; ilast = i ; if (!sorted) { Wi [i] = j ; } } } /* matrix is valid */ P4 (" nnz on diagonal: "ID"\n", dnz) ; P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; *nnzdiag = dnz ; return (TRUE) ; } int CHOLMOD(check_sparse) ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to check */ /* --------------- */ cholmod_common *Common ) { SuiteSparse_long nnzdiag ; RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_sparse (NULL, 0, NULL, A, &nnzdiag, Common)) ; } int CHOLMOD(print_sparse) ( /* ---- input ---- */ cholmod_sparse *A, /* sparse matrix to print */ const char *name, /* printed name of sparse matrix */ /* --------------- */ cholmod_common *Common ) { SuiteSparse_long nnzdiag ; RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_sparse (NULL, Common->print, name, A, &nnzdiag, Common)) ; } /* ========================================================================== */ /* === cholmod_check_dense ================================================== */ /* ========================================================================== */ /* Ensure a dense matrix is valid, and optionally print it. */ static int check_dense ( Int print, const char *name, cholmod_dense *X, cholmod_common *Common ) { double *Xx, *Xz ; Int i, j, d, nrow, ncol, nzmax, nz, init_print, count, xtype ; const char *type = "dense" ; /* ---------------------------------------------------------------------- */ /* print header information */ /* ---------------------------------------------------------------------- */ P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD dense: ") ; if (name != NULL) { P3 ("%s: ", name) ; } if (X == NULL) { ERR ("null") ; } nrow = X->nrow ; ncol = X->ncol ; nzmax = X->nzmax ; d = X->d ; Xx = X->x ; Xz = X->z ; xtype = X->xtype ; P3 (" "ID"", nrow) ; P3 ("-by-"ID", ", ncol) ; P4 ("\n leading dimension "ID", ", d) ; P4 ("nzmax "ID", ", nzmax) ; if (d * ncol > nzmax) { ERR ("nzmax too small") ; } if (d < nrow) { ERR ("leading dimension must be >= # of rows") ; } if (Xx == NULL) { ERR ("null") ; } switch (X->xtype) { case CHOLMOD_PATTERN: ERR ("pattern unsupported") ; break ; case CHOLMOD_REAL: P4 ("%s", "real") ; break ; case CHOLMOD_COMPLEX: P4 ("%s", "complex") ; break ; case CHOLMOD_ZOMPLEX: P4 ("%s", "zomplex") ; break ; default: ERR ("unknown xtype") ; } switch (X->dtype) { case CHOLMOD_DOUBLE: P4 ("%s", ", double\n") ; break ; case CHOLMOD_SINGLE: ERR ("single unsupported") ; default: ERR ("unknown dtype") ; } /* ---------------------------------------------------------------------- */ /* check and print each entry */ /* ---------------------------------------------------------------------- */ if (print >= 4) { init_print = print ; ETC_START (count, 9) ; nz = nrow * ncol ; for (j = 0 ; j < ncol ; j++) { ETC (j == ncol-1, count, 5) ; P4 (" col "ID":\n", j) ; for (i = 0 ; i < nrow ; i++) { ETC (j == ncol-1 && i >= nrow-4, count, -1) ; P4 (" "I8":", i) ; print_value (print, xtype, Xx, Xz, i+j*d, Common) ; P4 ("%s", "\n") ; } } } /* dense is valid */ P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_dense) ( /* ---- input ---- */ cholmod_dense *X, /* dense matrix to check */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_dense (0, NULL, X, Common)) ; } int CHOLMOD(print_dense) ( /* ---- input ---- */ cholmod_dense *X, /* dense matrix to print */ const char *name, /* printed name of dense matrix */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_dense (Common->print, name, X, Common)) ; } /* ========================================================================== */ /* === cholmod_check_subset ================================================= */ /* ========================================================================== */ /* Ensure S (0:len-1) is a subset of 0:n-1. Duplicates are allowed. S may be * NULL. A negative len denotes the set 0:n-1. * * To check the rset and cset for A(rset,cset), where nc and nr are the length * of cset and rset respectively: * * cholmod_check_subset (cset, nc, A->ncol, Common) ; * cholmod_check_subset (rset, nr, A->nrow, Common) ; * * workspace: none */ static int check_subset ( Int *S, SuiteSparse_long len, size_t n, Int print, const char *name, cholmod_common *Common ) { Int i, k, init_print, count ; const char *type = "subset" ; init_print = print ; if (S == NULL) { /* zero len denotes S = [ ], negative len denotes S = 0:n-1 */ len = (len < 0) ? (-1) : 0 ; } P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD subset: ") ; if (name != NULL) { P3 ("%s: ", name) ; } P3 (" len: %ld ", len) ; if (len < 0) { P3 ("%s", "(denotes 0:n-1) ") ; } P3 ("n: "ID"", (Int) n) ; P4 ("%s", "\n") ; if (len <= 0 || S == NULL) { P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } if (print >= 4) { ETC_START (count, 8) ; for (k = 0 ; k < ((Int) len) ; k++) { ETC (k == ((Int) len) - 4, count, -1) ; i = S [k] ; P4 (" "I8":", k) ; P4 (" "ID"\n", i) ; if (i < 0 || i >= ((Int) n)) { ERR ("entry out range") ; } } } else { for (k = 0 ; k < ((Int) len) ; k++) { i = S [k] ; if (i < 0 || i >= ((Int) n)) { ERR ("entry out range") ; } } } P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_subset) ( /* ---- input ---- */ Int *Set, /* Set [0:len-1] is a subset of 0:n-1. Duplicates OK */ SuiteSparse_long len, /* size of Set (an integer array), or < 0 if 0:n-1 */ size_t n, /* 0:n-1 is valid range */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_subset (Set, len, n, 0, NULL, Common)) ; } int CHOLMOD(print_subset) ( /* ---- input ---- */ Int *Set, /* Set [0:len-1] is a subset of 0:n-1. Duplicates OK */ SuiteSparse_long len, /* size of Set (an integer array), or < 0 if 0:n-1 */ size_t n, /* 0:n-1 is valid range */ const char *name, /* printed name of Set */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_subset (Set, len, n, Common->print, name, Common)) ; } /* ========================================================================== */ /* === cholmod_check_perm =================================================== */ /* ========================================================================== */ /* Ensure that Perm [0..len-1] is a permutation of a subset of 0:n-1. Perm * may be NULL, which is interpreted as the identity permutation. There can * be no duplicate entries (len must be <= n). * * If n <= Common->nrow, then this routine takes O(len) time and does not * allocate any memory, by using Common->Flag. Otherwise, it takes O(n) time * and ensures that Common->Iwork is at least n*sizeof(Int) in size. * * To check the fset: cholmod_check_perm (fset, fsize, ncol, Common) ; * To check a permutation: cholmod_check_perm (Perm, n, n, Common) ; * * workspace: Flag (n) if n <= Common->nrow, Iwork (n) otherwise. */ static int check_perm ( Int *Wi, Int print, const char *name, Int *Perm, size_t len, size_t n, cholmod_common *Common ) { Int *Flag ; Int i, k, mark, init_print, count ; const char *type = "perm" ; /* ---------------------------------------------------------------------- */ /* checks that take O(1) time */ /* ---------------------------------------------------------------------- */ if (Perm == NULL || n == 0) { /* Perm is valid implicit identity, or empty */ return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* checks that take O(n) time or require memory allocation */ /* ---------------------------------------------------------------------- */ init_print = print ; ETC_START (count, 8) ; if (Wi == NULL && n <= Common->nrow) { /* use the Common->Flag array if it's big enough */ mark = CHOLMOD(clear_flag) (Common) ; Flag = Common->Flag ; ASSERT (CHOLMOD(dump_work) (TRUE, FALSE, 0, Common)) ; if (print >= 4) { for (k = 0 ; k < ((Int) len) ; k++) { ETC (k >= ((Int) len) - 4, count, -1) ; i = Perm [k] ; P4 (" "I8":", k) ; P4 (""ID"\n", i) ; if (i < 0 || i >= ((Int) n) || Flag [i] == mark) { CHOLMOD(clear_flag) (Common) ; ERR ("invalid permutation") ; } Flag [i] = mark ; } } else { for (k = 0 ; k < ((Int) len) ; k++) { i = Perm [k] ; if (i < 0 || i >= ((Int) n) || Flag [i] == mark) { CHOLMOD(clear_flag) (Common) ; ERR ("invalid permutation") ; } Flag [i] = mark ; } } CHOLMOD(clear_flag) (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, FALSE, 0, Common)) ; } else { if (Wi == NULL) { /* use Common->Iwork instead, but initialize it first */ CHOLMOD(allocate_work) (0, n, 0, Common) ; Wi = Common->Iwork ; /* size n, (i/i/i) is OK */ } if (Common->status < CHOLMOD_OK) { return (FALSE) ; /* out of memory */ } for (i = 0 ; i < ((Int) n) ; i++) { Wi [i] = FALSE ; } if (print >= 4) { for (k = 0 ; k < ((Int) len) ; k++) { ETC (k >= ((Int) len) - 4, count, -1) ; i = Perm [k] ; P4 (" "I8":", k) ; P4 (""ID"\n", i) ; if (i < 0 || i >= ((Int) n) || Wi [i]) { ERR ("invalid permutation") ; } Wi [i] = TRUE ; } } else { for (k = 0 ; k < ((Int) len) ; k++) { i = Perm [k] ; if (i < 0 || i >= ((Int) n) || Wi [i]) { ERR ("invalid permutation") ; } Wi [i] = TRUE ; } } } /* perm is valid */ return (TRUE) ; } int CHOLMOD(check_perm) ( /* ---- input ---- */ Int *Perm, /* Perm [0:len-1] is a permutation of subset of 0:n-1 */ size_t len, /* size of Perm (an integer array) */ size_t n, /* 0:n-1 is valid range */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_perm (NULL, 0, NULL, Perm, len, n, Common)) ; } int CHOLMOD(print_perm) ( /* ---- input ---- */ Int *Perm, /* Perm [0:len-1] is a permutation of subset of 0:n-1 */ size_t len, /* size of Perm (an integer array) */ size_t n, /* 0:n-1 is valid range */ const char *name, /* printed name of Perm */ /* --------------- */ cholmod_common *Common ) { Int ok, print ; RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; print = Common->print ; P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD perm: ") ; if (name != NULL) { P3 ("%s: ", name) ; } P3 (" len: "ID"", (Int) len) ; P3 (" n: "ID"", (Int) n) ; P4 ("%s", "\n") ; ok = check_perm (NULL, print, name, Perm, len, n, Common) ; if (ok) { P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_check_parent ================================================= */ /* ========================================================================== */ /* Ensure that Parent is a valid elimination tree of nodes 0 to n-1. * If j is a root of the tree then Parent [j] is EMPTY (-1). * * NOTE: this check will fail if applied to the component tree (CParent) in * cholmod_nested_dissection, unless it has been postordered and renumbered. * * workspace: none */ static int check_parent ( Int *Parent, size_t n, Int print, const char *name, cholmod_common *Common ) { Int j, p, init_print, count ; const char *type = "parent" ; init_print = print ; P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD parent: ") ; if (name != NULL) { P3 ("%s: ", name) ; } P3 (" n: "ID"", (Int) n) ; P4 ("%s", "\n") ; if (Parent == NULL) { ERR ("null") ; } /* ---------------------------------------------------------------------- */ /* checks that take O(n) time */ /* ---------------------------------------------------------------------- */ ETC_START (count, 8) ; for (j = 0 ; j < ((Int) n) ; j++) { ETC (j == ((Int) n) - 4, count, -1) ; p = Parent [j] ; P4 (" "I8":", j) ; P4 (" "ID"\n", p) ; if (!(p == EMPTY || p > j)) { ERR ("invalid") ; } } P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_parent) ( /* ---- input ---- */ Int *Parent, /* Parent [0:n-1] is an elimination tree */ size_t n, /* size of Parent */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_parent (Parent, n, 0, NULL, Common)) ; } int CHOLMOD(print_parent) ( /* ---- input ---- */ Int *Parent, /* Parent [0:n-1] is an elimination tree */ size_t n, /* size of Parent */ const char *name, /* printed name of Parent */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_parent (Parent, n, Common->print, name, Common)) ; } /* ========================================================================== */ /* === cholmod_check_factor ================================================= */ /* ========================================================================== */ static int check_factor ( Int *Wi, Int print, const char *name, cholmod_factor *L, cholmod_common *Common ) { double *Lx, *Lz ; Int *Lp, *Li, *Lnz, *Lnext, *Lprev, *Perm, *ColCount, *Lpi, *Lpx, *Super, *Ls ; Int n, nzmax, j, p, pend, i, nz, ordering, space, is_monotonic, minor, count, precise, init_print, ilast, lnz, head, tail, jprev, plast, jnext, examine_super, nsuper, s, k1, k2, psi, psend, psx, nsrow, nscol, ps2, psxend, ssize, xsize, maxcsize, maxesize, nsrow2, jj, ii, xtype ; Int for_cholesky ; const char *type = "factor" ; /* ---------------------------------------------------------------------- */ /* print header information */ /* ---------------------------------------------------------------------- */ P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD factor: ") ; if (name != NULL) { P3 ("%s: ", name) ; } if (L == NULL) { ERR ("null") ; } n = L->n ; minor = L->minor ; ordering = L->ordering ; xtype = L->xtype ; Perm = L->Perm ; ColCount = L->ColCount ; lnz = 0 ; precise = Common->precise ; P3 (" "ID"", n) ; P3 ("-by-"ID"", n) ; if (minor < n) { P3 (" not positive definite (column "ID")", minor) ; } switch (L->itype) { case CHOLMOD_INT: P4 ("%s", "\n scalar types: int, ") ; break ; case CHOLMOD_INTLONG: ERR ("mixed int/long type unsupported") ; case CHOLMOD_LONG: P4 ("%s", "\n scalar types: SuiteSparse_long, "); break ; default: ERR ("unknown itype") ; } switch (L->xtype) { case CHOLMOD_PATTERN: P4 ("%s", "pattern") ; break ; case CHOLMOD_REAL: P4 ("%s", "real") ; break ; case CHOLMOD_COMPLEX: P4 ("%s", "complex") ; break ; case CHOLMOD_ZOMPLEX: P4 ("%s", "zomplex") ; break ; default: ERR ("unknown xtype") ; } switch (L->dtype) { case CHOLMOD_DOUBLE: P4 ("%s", ", double\n") ; break ; case CHOLMOD_SINGLE: ERR ("single unsupported") ; default: ERR ("unknown dtype") ; } if (L->itype != ITYPE || L->dtype != DTYPE) { ERR ("integer and real type must match routine") ; } if (L->is_super) { P3 ("%s", " supernodal") ; } else { P3 ("%s", " simplicial") ; } if (L->is_ll) { P3 ("%s", ", LL'.") ; } else { P3 ("%s", ", LDL'.") ; } P4 ("%s", "\n ordering method used: ") ; switch (L->ordering) { case CHOLMOD_POSTORDERED:P4 ("%s", "natural (postordered)") ; break ; case CHOLMOD_NATURAL: P4 ("%s", "natural") ; break ; case CHOLMOD_GIVEN: P4 ("%s", "user-provided") ; break ; case CHOLMOD_AMD: P4 ("%s", "AMD") ; break ; case CHOLMOD_COLAMD: P4 ("%s", "AMD for A, COLAMD for A*A'") ;break ; #ifndef NPARTITION case CHOLMOD_METIS: P4 ("%s", "METIS NodeND") ; break ; case CHOLMOD_NESDIS: P4 ("%s", "CHOLMOD nested dissection") ; break ; #endif default: ERR ("unknown ordering") ; } P4 ("%s", "\n") ; init_print = print ; if (L->is_super && L->xtype == CHOLMOD_ZOMPLEX) { ERR ("Supernodal zomplex L not supported") ; } /* ---------------------------------------------------------------------- */ /* check L->Perm */ /* ---------------------------------------------------------------------- */ if (!check_perm (Wi, print, name, Perm, n, n, Common)) { return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* check L->ColCount */ /* ---------------------------------------------------------------------- */ if (ColCount == NULL) { ERR ("ColCount vector invalid") ; } ETC_START (count, 8) ; for (j = 0 ; j < n ; j++) { ETC (j >= n-4, count, -1) ; P4 (" col: "ID" ", j) ; nz = ColCount [j] ; P4 ("colcount: "ID"\n", nz) ; if (nz < 0 || nz > n-j) { ERR ("ColCount out of range") ; } } /* ---------------------------------------------------------------------- */ /* check factor */ /* ---------------------------------------------------------------------- */ if (L->xtype == CHOLMOD_PATTERN && !(L->is_super)) { /* ------------------------------------------------------------------ */ /* check simplicial symbolic factor */ /* ------------------------------------------------------------------ */ /* nothing else to do */ ; } else if (L->xtype != CHOLMOD_PATTERN && !(L->is_super)) { /* ------------------------------------------------------------------ */ /* check simplicial numerical factor */ /* ------------------------------------------------------------------ */ P4 ("monotonic: %d\n", L->is_monotonic) ; nzmax = L->nzmax ; P3 (" nzmax "ID".", nzmax) ; P4 ("%s", "\n") ; Lp = L->p ; Li = L->i ; Lx = L->x ; Lz = L->z ; Lnz = L->nz ; Lnext = L->next ; Lprev = L->prev ; /* check for existence of Lp, Li, Lnz, Lnext, Lprev, and Lx arrays */ if (Lp == NULL) { ERR ("p array not present") ; } if (Li == NULL) { ERR ("i array not present") ; } if (Lnz == NULL) { ERR ("nz array not present") ; } if (Lx == NULL) { ERR ("x array not present") ; } if (xtype == CHOLMOD_ZOMPLEX && Lz == NULL) { ERR ("z array not present") ; } if (Lnext == NULL) { ERR ("next array not present") ; } if (Lprev == NULL) { ERR ("prev array not present") ; } ETC_START (count, 8) ; /* check each column of L */ plast = 0 ; is_monotonic = TRUE ; for (j = 0 ; j < n ; j++) { ETC (j >= n-3, count, -1) ; p = Lp [j] ; nz = Lnz [j] ; pend = p + nz ; lnz += nz ; P4 (" col "ID":", j) ; P4 (" nz "ID"", nz) ; P4 (" start "ID"", p) ; P4 (" end "ID"", pend) ; if (Lnext [j] < 0 || Lnext [j] > n) { ERR ("invalid link list") ; } space = Lp [Lnext [j]] - p ; P4 (" space "ID"", space) ; P4 (" free "ID":\n", space - nz) ; if (p < 0 || pend > nzmax || space < 1) { ERR ("pointer invalid") ; } if (nz < 1 || nz > (n-j) || nz > space) { ERR ("nz invalid") ; } ilast = j-1 ; if (p < plast) { is_monotonic = FALSE ; } plast = p ; i = Li [p] ; P4 (" "I8":", i) ; if (i != j) { ERR ("diagonal missing") ; } print_value (print, xtype, Lx, Lz, p, Common) ; P4 ("%s", "\n") ; ilast = j ; for (p++ ; p < pend ; p++) { ETC_DISABLE (count) ; i = Li [p] ; P4 (" "I8":", i) ; if (i < j || i >= n) { ERR ("row index out of range") ; } if (i <= ilast) { ERR ("row indices out of order") ; } print_value (print, xtype, Lx, Lz, p, Common) ; P4 ("%s", "\n") ; ilast = i ; } } if (L->is_monotonic && !is_monotonic) { ERR ("columns not monotonic") ; } /* check the link list */ head = n+1 ; tail = n ; j = head ; jprev = EMPTY ; count = 0 ; for ( ; ; ) { if (j < 0 || j > n+1 || count > n+2) { ERR ("invalid link list") ; } jnext = Lnext [j] ; if (j >= 0 && j < n) { if (jprev != Lprev [j]) { ERR ("invalid link list") ; } } count++ ; if (j == tail) { break ; } jprev = j ; j = jnext ; } if (Lnext [tail] != EMPTY || count != n+2) { ERR ("invalid link list") ; } } else { /* ------------------------------------------------------------------ */ /* check supernodal numeric or symbolic factor */ /* ------------------------------------------------------------------ */ nsuper = L->nsuper ; ssize = L->ssize ; xsize = L->xsize ; maxcsize = L->maxcsize ; maxesize = L->maxesize ; Ls = L->s ; Lpi = L->pi ; Lpx = L->px ; Super = L->super ; Lx = L->x ; ETC_START (count, 8) ; P4 (" ssize "ID" ", ssize) ; P4 ("xsize "ID" ", xsize) ; P4 ("maxcsize "ID" ", maxcsize) ; P4 ("maxesize "ID"\n", maxesize) ; if (Ls == NULL) { ERR ("invalid: L->s missing") ; } if (Lpi == NULL) { ERR ("invalid: L->pi missing") ; } if (Lpx == NULL) { ERR ("invalid: L->px missing") ; } if (Super == NULL) { ERR ("invalid: L->super missing") ; } if (L->xtype != CHOLMOD_PATTERN) { /* numerical supernodal factor */ if (Lx == NULL) { ERR ("invalid: L->x missing") ; } if (Ls [0] == EMPTY) { ERR ("invalid: L->s not defined") ; } examine_super = TRUE ; } else { /* symbolic supernodal factor, but only if it has been computed */ examine_super = (Ls [0] != EMPTY) ; } if (examine_super) { if (Lpi [0] != 0 || MAX (1, Lpi [nsuper]) != ssize) { PRINT0 (("Lpi [0] "ID", Lpi [nsuper = "ID"] = "ID"\n", Lpi [0], nsuper, Lpi [nsuper])) ; ERR ("invalid: L->pi invalid") ; } for_cholesky = (Lpx [0] != 123456) ; if (for_cholesky && (Lpx [0] != 0 || MAX (1, Lpx[nsuper]) != xsize)) { ERR ("invalid: L->px invalid") ; } /* check and print each supernode */ for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; nsrow = psend - psi ; nscol = k2 - k1 ; nsrow2 = nsrow - nscol ; ps2 = psi + nscol ; if (for_cholesky) { psx = Lpx [s] ; psxend = Lpx [s+1] ; } ETC (s == nsuper-1, count, 4) ; P4 (" supernode "ID", ", s) ; P4 ("col "ID" ", k1) ; P4 ("to "ID". ", k2-1) ; P4 ("nz in first col: "ID".\n", nsrow) ; if (for_cholesky) { P4 (" values start "ID", ", psx) ; P4 ("end "ID"\n", psxend) ; } if (k1 > k2 || k1 < 0 || k2 > n || nsrow < nscol || nsrow2 < 0 || (for_cholesky && psxend - psx != nsrow * nscol)) { ERR ("invalid supernode") ; } lnz += nscol * nsrow - (nscol*nscol - nscol)/2 ; if (L->xtype != CHOLMOD_PATTERN) { /* print each column of the supernode */ for (jj = 0 ; jj < nscol ; jj++) { ETC_ENABLE (s == nsuper-1 && jj >= nscol-3, count, -1) ; j = k1 + jj ; P4 (" col "ID"\n", j) ; ilast = j ; i = Ls [psi + jj] ; P4 (" "I8":", i) ; if (i != j) { ERR ("row index invalid") ; } /* PRINTVALUE (Lx [psx + jj + jj*nsrow]) ; */ print_value (print, xtype, Lx, NULL, psx + jj + jj*nsrow, Common) ; P4 ("%s", "\n") ; for (ii = jj + 1 ; ii < nsrow ; ii++) { ETC_DISABLE (count) ; i = Ls [psi + ii] ; P4 (" "I8":", i) ; if (i <= ilast || i > n) { ERR ("row index out of range") ; } /* PRINTVALUE (Lx [psx + ii + jj*nsrow]) ; */ print_value (print, xtype, Lx, NULL, psx + ii + jj*nsrow, Common) ; P4 ("%s", "\n") ; ilast = i ; } } } else { /* just print the leading column of the supernode */ P4 (" col "ID"\n", k1) ; for (jj = 0 ; jj < nscol ; jj++) { ETC (s == nsuper-1 && jj >= nscol-3, count, -1) ; j = k1 + jj ; i = Ls [psi + jj] ; P4 (" "I8"", i) ; if (i != j) { ERR ("row index invalid") ; } P4 ("%s", "\n") ; } ilast = j ; for (ii = nscol ; ii < nsrow ; ii++) { ETC_DISABLE (count) ; i = Ls [psi + ii] ; P4 (" "I8"", i) ; if (i <= ilast || i > n) { ERR ("row index out of range") ; } P4 ("%s", "\n") ; ilast = i ; } } } } } /* factor is valid */ P3 (" nz "ID"", lnz) ; P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_factor) ( /* ---- input ---- */ cholmod_factor *L, /* factor to check */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_factor (NULL, 0, NULL, L, Common)) ; } int CHOLMOD(print_factor) ( /* ---- input ---- */ cholmod_factor *L, /* factor to print */ const char *name, /* printed name of factor */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_factor (NULL, Common->print, name, L, Common)) ; } /* ========================================================================== */ /* === cholmod_check_triplet ================================================ */ /* ========================================================================== */ /* Ensure a triplet matrix is valid, and optionally print it. */ static int check_triplet ( Int print, const char *name, cholmod_triplet *T, cholmod_common *Common ) { double *Tx, *Tz ; Int *Ti, *Tj ; Int i, j, p, nrow, ncol, nzmax, nz, xtype, init_print, count ; const char *type = "triplet" ; /* ---------------------------------------------------------------------- */ /* print header information */ /* ---------------------------------------------------------------------- */ P4 ("%s", "\n") ; P3 ("%s", "CHOLMOD triplet: ") ; if (name != NULL) { P3 ("%s: ", name) ; } if (T == NULL) { ERR ("null") ; } nrow = T->nrow ; ncol = T->ncol ; nzmax = T->nzmax ; nz = T->nnz ; Ti = T->i ; Tj = T->j ; Tx = T->x ; Tz = T->z ; xtype = T->xtype ; P3 (" "ID"", nrow) ; P3 ("-by-"ID", ", ncol) ; P3 ("nz "ID",", nz) ; if (T->stype > 0) { P3 ("%s", " upper.") ; } else if (T->stype < 0) { P3 ("%s", " lower.") ; } else { P3 ("%s", " up/lo.") ; } P4 ("\n nzmax "ID", ", nzmax) ; if (nz > nzmax) { ERR ("nzmax too small") ; } switch (T->itype) { case CHOLMOD_INT: P4 ("%s", "\n scalar types: int, ") ; break ; case CHOLMOD_INTLONG: ERR ("mixed int/long type unsupported") ; case CHOLMOD_LONG: P4 ("%s", "\n scalar types: SuiteSparse_long, "); break ; default: ERR ("unknown itype") ; } switch (T->xtype) { case CHOLMOD_PATTERN: P4 ("%s", "pattern") ; break ; case CHOLMOD_REAL: P4 ("%s", "real") ; break ; case CHOLMOD_COMPLEX: P4 ("%s", "complex") ; break ; case CHOLMOD_ZOMPLEX: P4 ("%s", "zomplex") ; break ; default: ERR ("unknown xtype") ; } switch (T->dtype) { case CHOLMOD_DOUBLE: P4 ("%s", ", double\n") ; break ; case CHOLMOD_SINGLE: ERR ("single unsupported") ; default: ERR ("unknown dtype") ; } if (T->itype != ITYPE || T->dtype != DTYPE) { ERR ("integer and real type must match routine") ; } if (T->stype && nrow != ncol) { ERR ("symmetric but not square") ; } /* check for existence of Ti, Tj, Tx arrays */ if (Tj == NULL) { ERR ("j array not present") ; } if (Ti == NULL) { ERR ("i array not present") ; } if (xtype != CHOLMOD_PATTERN && Tx == NULL) { ERR ("x array not present") ; } if (xtype == CHOLMOD_ZOMPLEX && Tz == NULL) { ERR ("z array not present") ; } /* ---------------------------------------------------------------------- */ /* check and print each entry */ /* ---------------------------------------------------------------------- */ init_print = print ; ETC_START (count, 8) ; for (p = 0 ; p < nz ; p++) { ETC (p >= nz-4, count, -1) ; i = Ti [p] ; P4 (" "I8":", p) ; P4 (" "I_8"", i) ; if (i < 0 || i >= nrow) { ERR ("row index out of range") ; } j = Tj [p] ; P4 (" "I_8"", j) ; if (j < 0 || j >= ncol) { ERR ("column index out of range") ; } print_value (print, xtype, Tx, Tz, p, Common) ; P4 ("%s", "\n") ; } /* triplet matrix is valid */ P3 ("%s", " OK\n") ; P4 ("%s", "\n") ; return (TRUE) ; } int CHOLMOD(check_triplet) ( /* ---- input ---- */ cholmod_triplet *T, /* triplet matrix to check */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_triplet (0, NULL, T, Common)) ; } int CHOLMOD(print_triplet) ( /* ---- input ---- */ cholmod_triplet *T, /* triplet matrix to print */ const char *name, /* printed name of triplet matrix */ /* --------------- */ cholmod_common *Common ) { RETURN_IF_NULL_COMMON (FALSE) ; Common->status = CHOLMOD_OK ; return (check_triplet (Common->print, name, T, Common)) ; } /* ========================================================================== */ /* === CHOLMOD debugging routines =========================================== */ /* ========================================================================== */ #ifndef NDEBUG /* The global variables present only when debugging enabled. */ int CHOLMOD(dump) = 0 ; int CHOLMOD(dump_malloc) = -1 ; /* workspace: no debug routines use workspace in Common */ /* ========================================================================== */ /* === cholmod_dump_init ==================================================== */ /* ========================================================================== */ void CHOLMOD(dump_init) (const char *s, cholmod_common *Common) { int i = 0 ; FILE *f ; f = fopen ("debug", "r") ; CHOLMOD(dump) = 0 ; if (f != NULL) { i = fscanf (f, "%d", &CHOLMOD(dump)) ; fclose (f) ; } PRINT1 (("%s: cholmod_dump_init, D = %d\n", s, CHOLMOD(dump))) ; } /* ========================================================================== */ /* === cholmod_dump_sparse ================================================== */ /* ========================================================================== */ /* returns nnz (diag (A)) or EMPTY if error */ SuiteSparse_long CHOLMOD(dump_sparse) ( cholmod_sparse *A, const char *name, cholmod_common *Common ) { Int *Wi ; SuiteSparse_long nnzdiag ; Int ok ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (0) ; } RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; Wi = malloc (MAX (1, A->nrow) * sizeof (Int)) ; ok = check_sparse (Wi, CHOLMOD(dump), name, A, &nnzdiag, Common) ; if (Wi != NULL) free (Wi) ; return (ok ? nnzdiag : EMPTY) ; } /* ========================================================================== */ /* === cholmod_dump_factor ================================================== */ /* ========================================================================== */ int CHOLMOD(dump_factor) ( cholmod_factor *L, const char *name, cholmod_common *Common ) { Int *Wi ; int ok ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; Wi = malloc (MAX (1, L->n) * sizeof (Int)) ; ok = check_factor (Wi, CHOLMOD(dump), name, L, Common) ; if (Wi != NULL) free (Wi) ; return (ok) ; } /* ========================================================================== */ /* === cholmod_dump_perm ==================================================== */ /* ========================================================================== */ int CHOLMOD(dump_perm) ( Int *Perm, size_t len, size_t n, const char *name, cholmod_common *Common ) { Int *Wi ; int ok ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; Wi = malloc (MAX (1, n) * sizeof (Int)) ; ok = check_perm (Wi, CHOLMOD(dump), name, Perm, len, n,Common) ; if (Wi != NULL) free (Wi) ; return (ok) ; } /* ========================================================================== */ /* === cholmod_dump_dense =================================================== */ /* ========================================================================== */ int CHOLMOD(dump_dense) ( cholmod_dense *X, const char *name, cholmod_common *Common ) { if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; return (check_dense (CHOLMOD(dump), name, X, Common)) ; } /* ========================================================================== */ /* === cholmod_dump_triplet ================================================= */ /* ========================================================================== */ int CHOLMOD(dump_triplet) ( cholmod_triplet *T, const char *name, cholmod_common *Common ) { if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; return (check_triplet (CHOLMOD(dump), name, T, Common)) ; } /* ========================================================================== */ /* === cholmod_dump_subset ================================================== */ /* ========================================================================== */ int CHOLMOD(dump_subset) ( Int *S, size_t len, size_t n, const char *name, cholmod_common *Common ) { if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; return (check_subset (S, len, n, CHOLMOD(dump), name, Common)) ; } /* ========================================================================== */ /* === cholmod_dump_parent ================================================== */ /* ========================================================================== */ int CHOLMOD(dump_parent) ( Int *Parent, size_t n, const char *name, cholmod_common *Common ) { if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; return (check_parent (Parent, n, CHOLMOD(dump), name, Common)) ; } /* ========================================================================== */ /* === cholmod_dump_real ==================================================== */ /* ========================================================================== */ void CHOLMOD(dump_real) ( const char *name, Real *X, SuiteSparse_long nrow, SuiteSparse_long ncol, int lower, int xentry, cholmod_common *Common ) { /* dump an nrow-by-ncol real dense matrix */ SuiteSparse_long i, j ; double x, z ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return ; } PRINT1 (("%s: dump_real, nrow: %ld ncol: %ld lower: %d\n", name, nrow, ncol, lower)) ; for (j = 0 ; j < ncol ; j++) { PRINT2 ((" col %ld\n", j)) ; for (i = 0 ; i < nrow ; i++) { /* X is stored in column-major form */ if (lower && i < j) { PRINT2 ((" %5ld: -", i)) ; } else { x = *X ; PRINT2 ((" %5ld: %e", i, x)) ; if (xentry == 2) { z = *(X+1) ; PRINT2 ((", %e", z)) ; } } PRINT2 (("\n")) ; X += xentry ; } } } /* ========================================================================== */ /* === cholmod_dump_super =================================================== */ /* ========================================================================== */ void CHOLMOD(dump_super) ( SuiteSparse_long s, Int *Super, Int *Lpi, Int *Ls, Int *Lpx, double *Lx, int xentry, cholmod_common *Common ) { Int k1, k2, do_values, psi, psx, nsrow, nscol, psend, ilast, p, i ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return ; } k1 = Super [s] ; k2 = Super [s+1] ; nscol = k2 - k1 ; do_values = (Lpx != NULL) && (Lx != NULL) ; psi = Lpi [s] ; psend = Lpi [s+1] ; nsrow = psend - psi ; PRINT1 (("\nSuper %ld, columns "ID" to "ID", "ID" rows "ID" cols\n", s, k1, k2-1, nsrow, nscol)) ; ilast = -1 ; for (p = psi ; p < psend ; p++) { i = Ls [p] ; PRINT2 ((" "ID" : p-psi "ID"\n", i, p-psi)) ; ASSERT (IMPLIES (p-psi < nscol, i == k1 + (p-psi))) ; if (p-psi == nscol-1) PRINT2 (("------\n")) ; ASSERT (i > ilast) ; ilast = i ; } if (do_values) { psx = Lpx [s] ; CHOLMOD(dump_real) ("Supernode", Lx + xentry*psx, nsrow, nscol, TRUE, xentry, Common) ; } } /* ========================================================================== */ /* === cholmod_dump_mem ===================================================== */ /* ========================================================================== */ int CHOLMOD(dump_mem) ( const char *where, SuiteSparse_long should, cholmod_common *Common ) { SuiteSparse_long diff = should - Common->memory_inuse ; if (diff != 0) { PRINT0 (("mem: %-15s peak %10g inuse %10g should %10g\n", where, (double) Common->memory_usage, (double) Common->memory_inuse, (double) should)) ; PRINT0 (("mem: %s diff %ld !\n", where, diff)) ; } return (diff == 0) ; } /* ========================================================================== */ /* === cholmod_dump_partition =============================================== */ /* ========================================================================== */ /* make sure we have a proper separator (for debugging only) * * workspace: none */ int CHOLMOD(dump_partition) ( SuiteSparse_long n, Int *Cp, Int *Ci, Int *Cnw, Int *Part, SuiteSparse_long sepsize, cholmod_common *Common ) { Int chek [3], which, ok, i, j, p ; PRINT1 (("bisect sepsize %ld\n", sepsize)) ; ok = TRUE ; chek [0] = 0 ; chek [1] = 0 ; chek [2] = 0 ; for (j = 0 ; j < n ; j++) { PRINT2 (("--------j "ID" in part "ID" nw "ID"\n", j, Part [j], Cnw[j])); which = Part [j] ; for (p = Cp [j] ; p < Cp [j+1] ; p++) { i = Ci [p] ; PRINT3 (("i "ID", part "ID"\n", i, Part [i])) ; if (which == 0) { if (Part [i] == 1) { PRINT0 (("Error! "ID" "ID"\n", i, j)) ; ok = FALSE ; } } else if (which == 1) { if (Part [i] == 0) { PRINT0 (("Error! "ID" "ID"\n", i, j)) ; ok = FALSE ; } } } if (which < 0 || which > 2) { PRINT0 (("Part out of range\n")) ; ok = FALSE ; } chek [which] += Cnw [j] ; } PRINT1 (("sepsize %ld check "ID" "ID" "ID"\n", sepsize, chek[0], chek[1],chek[2])); if (sepsize != chek[2]) { PRINT0 (("mismatch!\n")) ; ok = FALSE ; } return (ok) ; } /* ========================================================================== */ /* === cholmod_dump_work ==================================================== */ /* ========================================================================== */ int CHOLMOD(dump_work) (int flag, int head, SuiteSparse_long wsize, cholmod_common *Common) { double *W ; Int *Flag, *Head ; Int k, nrow, mark ; if (CHOLMOD(dump) < -1) { /* no checks if debug level is -2 or less */ return (TRUE) ; } RETURN_IF_NULL_COMMON (FALSE) ; nrow = Common->nrow ; Flag = Common->Flag ; Head = Common->Head ; W = Common->Xwork ; mark = Common->mark ; if (wsize < 0) { /* check all of Xwork */ wsize = Common->xworksize ; } else { /* check on the first wsize doubles in Xwork */ wsize = MIN (wsize, (Int) (Common->xworksize)) ; } if (flag) { for (k = 0 ; k < nrow ; k++) { if (Flag [k] >= mark) { PRINT0 (("Flag invalid, Flag ["ID"] = "ID", mark = "ID"\n", k, Flag [k], mark)) ; ASSERT (0) ; return (FALSE) ; } } } if (head) { for (k = 0 ; k < nrow ; k++) { if (Head [k] != EMPTY) { PRINT0 (("Head invalid, Head ["ID"] = "ID"\n", k, Head [k])) ; ASSERT (0) ; return (FALSE) ; } } } for (k = 0 ; k < wsize ; k++) { if (W [k] != 0.) { PRINT0 (("W invalid, W ["ID"] = %g\n", k, W [k])) ; ASSERT (0) ; return (FALSE) ; } } return (TRUE) ; } #endif #endif igraph/src/CHOLMOD/Supernodal/0000755000175100001440000000000013561251652015540 5ustar hornikusersigraph/src/CHOLMOD/Supernodal/cholmod_super_symbolic.c0000644000175100001440000007176113431000472022450 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/cholmod_super_symbolic ==================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Supernodal symbolic analysis of the LL' factorization of A, A*A', * A(:,f)*A(:,f)'. * * This routine must be preceded by a simplicial symbolic analysis * (cholmod_rowcolcounts). See cholmod_analyze.c for an example of how to use * this routine. * * The user need not call this directly; cholmod_analyze is a "simple" wrapper * for this routine. * * Symmetric case: * * A is stored in column form, with entries stored in the upper triangular * part. Entries in the lower triangular part are ignored. * * Unsymmetric case: * * A is stored in column form. If F is equal to the transpose of A, then * A*A' is analyzed. F can include a subset of the columns of A * (F=A(:,f)'), in which case F*F' is analyzed. * * Requires Parent and L->ColCount to be defined on input; these are the * simplicial Parent and ColCount arrays as computed by cholmod_rowcolcounts. * Does not use L->Perm; the input matrices A and F must already be properly * permuted. Allocates and computes the supernodal pattern of L (L->super, * L->pi, L->px, and L->s). Does not allocate the real part (L->x). * * Supports any xtype (pattern, real, complex, or zomplex). */ #ifndef NSUPERNODAL #include "cholmod_internal.h" #include "cholmod_supernodal.h" /* ========================================================================== */ /* === subtree ============================================================== */ /* ========================================================================== */ /* In the symmetric case, traverse the kth row subtree from the nonzeros in * A (0:k1-1,k) and add the new entries found to the pattern of the kth row * of L. The current supernode s contains the diagonal block k1:k2-1, so it * can be skipped. * * In the unsymmetric case, the nonzero pattern of A*F is computed one column * at a time (thus, the total time spent in this function is bounded below by * the time taken to multiply A*F, which can be high if A is tall and thin). * The kth column is A*F(:,k), or the set union of all columns A(:,j) for which * F(j,k) is nonzero. This routine is called once for each entry j. Only the * upper triangular part is needed, so only A (0:k1-1,j) is accessed, where * k1:k2-1 are the columns of the current supernode s (k is in the range k1 to * k2-1). * * If A is sorted, then the total time taken by this function is proportional * to the number of nonzeros in the strictly block upper triangular part of A, * plus the number of entries in the strictly block lower triangular part of * the supernodal part of L. This excludes entries in the diagonal blocks * corresponding to the columns in each supernode. That is, if k1:k2-1 are * in a single supernode, then only A (0:k1-1,k1:k2-1) are accessed. * * For the unsymmetric case, only the strictly block upper triangular part * of A*F is constructed. * * Only adds column indices corresponding to the leading columns of each * relaxed supernode. */ static void subtree ( /* inputs, not modified: */ Int j, /* j = k for symmetric case */ Int k, Int Ap [ ], Int Ai [ ], Int Anz [ ], Int SuperMap [ ], Int Sparent [ ], Int mark, Int sorted, /* true if the columns of A are sorted */ Int k1, /* only consider A (0:k1-1,k) */ /* input/output: */ Int Flag [ ], Int Ls [ ], Int Lpi2 [ ] ) { Int p, pend, i, si ; p = Ap [j] ; pend = (Anz == NULL) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i < k1) { /* (i,k) is an entry in the upper triangular part of A or A*F'. * symmetric case: A(i,k) is nonzero (j=k). * unsymmetric case: A(i,j) and F(j,k) are both nonzero. * * Column i is in supernode si = SuperMap [i]. Follow path from si * to root of supernodal etree, stopping at the first flagged * supernode. The root of the row subtree is supernode SuperMap[k], * which is flagged already. This traversal will stop there, or it * might stop earlier if supernodes have been flagged by previous * calls to this routine for the same k. */ for (si = SuperMap [i] ; Flag [si] < mark ; si = Sparent [si]) { ASSERT (si <= SuperMap [k]) ; Ls [Lpi2 [si]++] = k ; Flag [si] = mark ; } } else if (sorted) { break ; } } } /* clear workspace used by cholmod_super_symbolic */ #define FREE_WORKSPACE \ { \ /* CHOLMOD(clear_flag) (Common) ; */ \ CHOLMOD_CLEAR_FLAG (Common) ; \ for (k = 0 ; k <= nfsuper ; k++) \ { \ Head [k] = EMPTY ; \ } \ ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; \ } \ /* ========================================================================== */ /* === cholmod_super_symbolic2 ============================================== */ /* ========================================================================== */ /* Analyze for supernodal Cholesky or multifrontal QR. CHOLMOD itself always * analyzes for supernodal Cholesky, of course. The "for_cholesky = TRUE" * option is used by SuiteSparseQR only. */ int CHOLMOD(super_symbolic2) ( /* ---- input ---- */ int for_cholesky, /* Cholesky if TRUE, QR if FALSE */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* F = A' or A(:,f)' */ Int *Parent, /* elimination tree */ /* ---- in/out --- */ cholmod_factor *L, /* simplicial symbolic on input, * supernodal symbolic on output */ /* --------------- */ cholmod_common *Common ) { double zrelax0, zrelax1, zrelax2, xxsize ; Int *Wi, *Wj, *Super, *Snz, *Ap, *Ai, *Flag, *Head, *Ls, *Lpi, *Lpx, *Fnz, *Sparent, *Anz, *SuperMap, *Merged, *Nscol, *Zeros, *Fp, *Fj, *ColCount, *Lpi2, *Lsuper, *Iwork ; Int nsuper, d, n, j, k, s, mark, parent, p, pend, k1, k2, packed, nscol, nsrow, ndrow1, ndrow2, stype, ssize, xsize, sparent, plast, slast, csize, maxcsize, ss, nscol0, nscol1, ns, nfsuper, newzeros, totzeros, merge, snext, esize, maxesize, nrelax0, nrelax1, nrelax2, Asorted ; size_t w ; int ok = TRUE ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (Parent, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_PATTERN, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_PATTERN, FALSE) ; stype = A->stype ; if (stype < 0) { /* invalid symmetry; symmetric lower form not supported */ ERROR (CHOLMOD_INVALID, "symmetric lower not supported") ; return (FALSE) ; } if (stype == 0) { /* F must be present in the unsymmetric case */ RETURN_IF_NULL (F, FALSE) ; } if (L->is_super) { /* L must be a simplicial symbolic factor */ ERROR (CHOLMOD_INVALID, "L must be symbolic on input") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace */ /* ---------------------------------------------------------------------- */ n = A->nrow ; /* w = 5*n */ w = CHOLMOD(mult_size_t) (n, 5, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, w, 0, Common) ; if (Common->status < CHOLMOD_OK) { /* out of memory */ return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ /* A is now either A or triu(A(p,p)) for the symmetric case. It is either * A or A(p,f) for the unsymmetric case (both in column form). It can be * either packed or unpacked, and either sorted or unsorted. Entries in * the lower triangular part may be present if A is symmetric, but these * are ignored. */ Ap = A->p ; Ai = A->i ; Anz = A->nz ; if (stype != 0) { /* F not accessed */ Fp = NULL ; Fj = NULL ; Fnz = NULL ; packed = TRUE ; } else { /* F = A(:,f) or A(p,f) in packed row form, either sorted or unsorted */ Fp = F->p ; Fj = F->i ; Fnz = F->nz ; packed = F->packed ; } ColCount = L->ColCount ; nrelax0 = Common->nrelax [0] ; nrelax1 = Common->nrelax [1] ; nrelax2 = Common->nrelax [2] ; zrelax0 = Common->zrelax [0] ; zrelax1 = Common->zrelax [1] ; zrelax2 = Common->zrelax [2] ; zrelax0 = IS_NAN (zrelax0) ? 0 : zrelax0 ; zrelax1 = IS_NAN (zrelax1) ? 0 : zrelax1 ; zrelax2 = IS_NAN (zrelax2) ? 0 : zrelax2 ; ASSERT (CHOLMOD(dump_parent) (Parent, n, "Parent", Common)) ; /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ /* Sparent, Snz, and Merged could be allocated later, of size nfsuper */ Iwork = Common->Iwork ; Wi = Iwork ; /* size n (i/l/l). Lpi2 is i/l/l */ Wj = Iwork + n ; /* size n (i/l/l). Zeros is i/l/l */ Sparent = Iwork + 2*((size_t) n) ; /* size nfsuper <= n [ */ Snz = Iwork + 3*((size_t) n) ; /* size nfsuper <= n [ */ Merged = Iwork + 4*((size_t) n) ; /* size nfsuper <= n [ */ Flag = Common->Flag ; /* size n */ Head = Common->Head ; /* size n+1 */ /* ---------------------------------------------------------------------- */ /* find the fundamental supernodes */ /* ---------------------------------------------------------------------- */ /* count the number of children of each node, using Wi [ */ for (j = 0 ; j < n ; j++) { Wi [j] = 0 ; } for (j = 0 ; j < n ; j++) { parent = Parent [j] ; if (parent != EMPTY) { Wi [parent]++ ; } } Super = Head ; /* use Head [0..nfsuper] as workspace for Super list ( */ /* column 0 always starts a new supernode */ nfsuper = (n == 0) ? 0 : 1 ; /* number of fundamental supernodes */ Super [0] = 0 ; for (j = 1 ; j < n ; j++) { /* check if j starts new supernode, or in the same supernode as j-1 */ if (Parent [j-1] != j /* parent of j-1 is not j */ || (ColCount [j-1] != ColCount [j] + 1) /* j-1 not subset of j*/ || Wi [j] > 1) /* j has more than one child */ { /* j is the leading node of a supernode */ Super [nfsuper++] = j ; } } Super [nfsuper] = n ; /* contents of Wi no longer needed for child count ] */ Nscol = Wi ; /* use Wi as size-nfsuper workspace for Nscol [ */ /* ---------------------------------------------------------------------- */ /* find the mapping of fundamental nodes to supernodes */ /* ---------------------------------------------------------------------- */ SuperMap = Wj ; /* use Wj as workspace for SuperMap [ */ /* SuperMap [k] = s if column k is contained in supernode s */ for (s = 0 ; s < nfsuper ; s++) { for (k = Super [s] ; k < Super [s+1] ; k++) { SuperMap [k] = s ; } } /* ---------------------------------------------------------------------- */ /* construct the fundamental supernodal etree */ /* ---------------------------------------------------------------------- */ for (s = 0 ; s < nfsuper ; s++) { j = Super [s+1] - 1 ; /* last node in supernode s */ parent = Parent [j] ; /* parent of last node */ Sparent [s] = (parent == EMPTY) ? EMPTY : SuperMap [parent] ; PRINT1 (("Sparent ["ID"] = "ID"\n", s, Sparent [s])) ; } /* contents of Wj no longer needed as workspace for SuperMap ] * SuperMap will be recomputed below, for the relaxed supernodes. */ Zeros = Wj ; /* use Wj for Zeros, workspace of size nfsuper [ */ /* ---------------------------------------------------------------------- */ /* relaxed amalgamation */ /* ---------------------------------------------------------------------- */ for (s = 0 ; s < nfsuper ; s++) { Merged [s] = EMPTY ; /* s not merged into another */ Nscol [s] = Super [s+1] - Super [s] ; /* # of columns in s */ Zeros [s] = 0 ; /* # of zero entries in s */ ASSERT (s <= Super [s]) ; Snz [s] = ColCount [Super [s]] ; /* # of entries in leading col of s */ PRINT2 (("lnz ["ID"] "ID"\n", s, Snz [s])) ; } for (s = nfsuper-2 ; s >= 0 ; s--) { /* should supernodes s and s+1 merge into a new node s? */ PRINT1 (("\n========= Check relax of s "ID" and s+1 "ID"\n", s, s+1)) ; ss = Sparent [s] ; if (ss == EMPTY) { PRINT1 (("s "ID" is a root, no merge with s+1 = "ID"\n", s, s+1)) ; continue ; } /* find the current parent of s (perform path compression as needed) */ for (ss = Sparent [s] ; Merged [ss] != EMPTY ; ss = Merged [ss]) ; sparent = ss ; PRINT2 (("Current sparent of s "ID" is "ID"\n", s, sparent)) ; /* ss is the current parent of s */ for (ss = Sparent [s] ; Merged [ss] != EMPTY ; ss = snext) { snext = Merged [ss] ; PRINT2 (("ss "ID" is dead, merged into snext "ID"\n", ss, snext)) ; Merged [ss] = sparent ; } /* if s+1 is not the current parent of s, do not merge */ if (sparent != s+1) { continue ; } nscol0 = Nscol [s] ; /* # of columns in s */ nscol1 = Nscol [s+1] ; /* # of columns in s+1 */ ns = nscol0 + nscol1 ; PRINT2 (("ns "ID" nscol0 "ID" nscol1 "ID"\n", ns, nscol0, nscol1)) ; totzeros = Zeros [s+1] ; /* current # of zeros in s+1 */ /* determine if supernodes s and s+1 should merge */ if (ns <= nrelax0) { PRINT2 (("ns is tiny ("ID"), so go ahead and merge\n", ns)) ; merge = TRUE ; } else { /* use double to avoid integer overflow */ double lnz0 = Snz [s] ; /* # entries in leading column of s */ double lnz1 = Snz [s+1] ; /* # entries in leading column of s+1 */ double xnewzeros = nscol0 * (lnz1 + nscol0 - lnz0) ; /* use Int for the final update of Zeros [s] below */ newzeros = nscol0 * (Snz [s+1] + nscol0 - Snz [s]) ; ASSERT (newzeros == xnewzeros) ; PRINT2 (("lnz0 %g lnz1 %g xnewzeros %g\n", lnz0, lnz1, xnewzeros)) ; if (xnewzeros == 0) { /* no new zeros, so go ahead and merge */ PRINT2 (("no new fillin, so go ahead and merge\n")) ; merge = TRUE ; } else { /* # of zeros if merged */ double xtotzeros = ((double) totzeros) + xnewzeros ; /* xtotsize: total size of merged supernode, if merged: */ double xns = (double) ns ; double xtotsize = (xns * (xns+1) / 2) + xns * (lnz1 - nscol1) ; double z = xtotzeros / xtotsize ; Int totsize ; totsize = (ns * (ns+1) / 2) + ns * (Snz [s+1] - nscol1) ; PRINT2 (("oldzeros "ID" newzeros "ID" xtotsize %g z %g\n", Zeros [s+1], newzeros, xtotsize, z)) ; /* use Int for the final update of Zeros [s] below */ totzeros += newzeros ; /* do not merge if supernode would become too big * (Int overflow). Continue computing; not (yet) an error. */ /* fl.pt. compare, but no NaN's can occur here */ merge = ((ns <= nrelax1 && z < zrelax0) || (ns <= nrelax2 && z < zrelax1) || (z < zrelax2)) && (xtotsize < Int_max / sizeof (double)) ; } } if (merge) { PRINT1 (("Merge node s ("ID") and s+1 ("ID")\n", s, s+1)) ; Zeros [s] = totzeros ; Merged [s+1] = s ; Snz [s] = nscol0 + Snz [s+1] ; Nscol [s] += Nscol [s+1] ; } } /* contents of Wj no longer needed for Zeros ] */ /* contents of Wi no longer needed for Nscol ] */ /* contents of Sparent no longer needed (recomputed below) */ /* ---------------------------------------------------------------------- */ /* construct the relaxed supernode list */ /* ---------------------------------------------------------------------- */ nsuper = 0 ; for (s = 0 ; s < nfsuper ; s++) { if (Merged [s] == EMPTY) { PRINT1 (("live supernode: "ID" snz "ID"\n", s, Snz [s])) ; Super [nsuper] = Super [s] ; Snz [nsuper] = Snz [s] ; nsuper++ ; } } Super [nsuper] = n ; PRINT1 (("Fundamental supernodes: "ID" relaxed "ID"\n", nfsuper, nsuper)) ; /* Merged no longer needed ] */ /* ---------------------------------------------------------------------- */ /* find the mapping of relaxed nodes to supernodes */ /* ---------------------------------------------------------------------- */ /* use Wj as workspace for SuperMap { */ /* SuperMap [k] = s if column k is contained in supernode s */ for (s = 0 ; s < nsuper ; s++) { for (k = Super [s] ; k < Super [s+1] ; k++) { SuperMap [k] = s ; } } /* ---------------------------------------------------------------------- */ /* construct the relaxed supernodal etree */ /* ---------------------------------------------------------------------- */ for (s = 0 ; s < nsuper ; s++) { j = Super [s+1] - 1 ; /* last node in supernode s */ parent = Parent [j] ; /* parent of last node */ Sparent [s] = (parent == EMPTY) ? EMPTY : SuperMap [parent] ; PRINT1 (("new Sparent ["ID"] = "ID"\n", s, Sparent [s])) ; } /* ---------------------------------------------------------------------- */ /* determine the size of L->s and L->x */ /* ---------------------------------------------------------------------- */ ssize = 0 ; xsize = 0 ; xxsize = 0 ; for (s = 0 ; s < nsuper ; s++) { nscol = Super [s+1] - Super [s] ; nsrow = Snz [s] ; ASSERT (nscol > 0) ; ssize += nsrow ; if (for_cholesky) { xsize += nscol * nsrow ; /* also compute xsize in double to guard against Int overflow */ xxsize += ((double) nscol) * ((double) nsrow) ; } if (ssize < 0 || (for_cholesky && xxsize > Int_max)) { /* Int overflow, clear workspace and return. QR factorization will not use xxsize, so that error is ignored. For Cholesky factorization, however, memory of space xxsize will be allocated, so this is a failure. Both QR and Cholesky fail if ssize overflows. */ ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; FREE_WORKSPACE ; return (FALSE) ; } ASSERT (ssize > 0) ; ASSERT (IMPLIES (for_cholesky, xsize > 0)) ; } xsize = MAX (1, xsize) ; ssize = MAX (1, ssize) ; PRINT1 (("ix sizes: "ID" "ID" nsuper "ID"\n", ssize, xsize, nsuper)) ; /* ---------------------------------------------------------------------- */ /* allocate L (all except real part L->x) */ /* ---------------------------------------------------------------------- */ L->ssize = ssize ; L->xsize = xsize ; L->nsuper = nsuper ; CHOLMOD(change_factor) (CHOLMOD_PATTERN, TRUE, TRUE, TRUE, TRUE, L, Common); if (Common->status < CHOLMOD_OK) { /* out of memory; L is still a valid simplicial symbolic factor */ FREE_WORKSPACE ; return (FALSE) ; } DEBUG (CHOLMOD(dump_factor) (L, "L to symbolic super", Common)) ; ASSERT (L->is_ll && L->xtype == CHOLMOD_PATTERN && L->is_super) ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Ls [0] = 0 ; /* flag for cholmod_check_factor; supernodes are defined */ Lpx [0] = for_cholesky ? 0 : 123456 ; /* magic number for sparse QR */ Lsuper = L->super ; /* copy the list of relaxed supernodes into the final list in L */ for (s = 0 ; s <= nsuper ; s++) { Lsuper [s] = Super [s] ; } /* Head no longer needed as workspace for fundamental Super list ) */ Super = Lsuper ; /* Super is now the list of relaxed supernodes */ /* ---------------------------------------------------------------------- */ /* construct column pointers of relaxed supernodal pattern (L->pi) */ /* ---------------------------------------------------------------------- */ p = 0 ; for (s = 0 ; s < nsuper ; s++) { Lpi [s] = p ; p += Snz [s] ; PRINT1 (("Snz ["ID"] = "ID", Super ["ID"] = "ID"\n", s, Snz [s], s, Super[s])) ; } Lpi [nsuper] = p ; ASSERT ((Int) (L->ssize) == MAX (1,p)) ; /* ---------------------------------------------------------------------- */ /* construct pointers for supernodal values (L->px) */ /* ---------------------------------------------------------------------- */ if (for_cholesky) { /* L->px is not needed for QR factorization (it may lead to Int overflow, anyway, if xsize caused Int overflow above) */ p = 0 ; for (s = 0 ; s < nsuper ; s++) { nscol = Super [s+1] - Super [s] ; /* number of columns in s */ nsrow = Snz [s] ; /* # of rows, incl triangular part*/ Lpx [s] = p ; /* pointer to numerical part of s */ p += nscol * nsrow ; } Lpx [s] = p ; ASSERT ((Int) (L->xsize) == MAX (1,p)) ; } /* Snz no longer needed ] */ /* ---------------------------------------------------------------------- */ /* symbolic analysis to construct the relaxed supernodal pattern (L->s) */ /* ---------------------------------------------------------------------- */ Lpi2 = Wi ; /* copy Lpi into Lpi2, using Wi as workspace for Lpi2 [ */ for (s = 0 ; s < nsuper ; s++) { Lpi2 [s] = Lpi [s] ; } Asorted = A->sorted ; for (s = 0 ; s < nsuper ; s++) { /* sth supernode is in columns k1 to k2-1. * compute nonzero pattern of L (k1:k2-1,:). */ /* place rows k1 to k2-1 in leading column of supernode s */ k1 = Super [s] ; k2 = Super [s+1] ; PRINT1 (("=========>>> Supernode "ID" k1 "ID" k2-1 "ID"\n", s, k1, k2-1)) ; for (k = k1 ; k < k2 ; k++) { Ls [Lpi2 [s]++] = k ; } /* compute nonzero pattern each row k1 to k2-1 */ for (k = k1 ; k < k2 ; k++) { /* compute row k of L. In the symmetric case, the pattern of L(k,:) * is the set of nodes reachable in the supernodal etree from any * row i in the nonzero pattern of A(0:k,k). In the unsymmetric * case, the pattern of the kth column of A*A' is the set union * of all columns A(0:k,j) for each nonzero F(j,k). */ /* clear the Flag array and mark the current supernode */ /* mark = CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; mark = Common->mark ; Flag [s] = mark ; ASSERT (s == SuperMap [k]) ; /* traverse the row subtree for each nonzero in A or AA' */ if (stype != 0) { subtree (k, k, Ap, Ai, Anz, SuperMap, Sparent, mark, Asorted, k1, Flag, Ls, Lpi2) ; } else { /* for each j nonzero in F (:,k) do */ p = Fp [k] ; pend = (packed) ? (Fp [k+1]) : (p + Fnz [k]) ; for ( ; p < pend ; p++) { subtree (Fj [p], k, Ap, Ai, Anz, SuperMap, Sparent, mark, Asorted, k1, Flag, Ls, Lpi2) ; } } } } #ifndef NDEBUG for (s = 0 ; s < nsuper ; s++) { PRINT1 (("Lpi2[s] "ID" Lpi[s+1] "ID"\n", Lpi2 [s], Lpi [s+1])) ; ASSERT (Lpi2 [s] == Lpi [s+1]) ; CHOLMOD(dump_super) (s, Super, Lpi, Ls, NULL, NULL, 0, Common) ; } #endif /* contents of Wi no longer needed for Lpi2 ] */ /* Sparent no longer needed ] */ /* ---------------------------------------------------------------------- */ /* determine the largest update matrix (L->maxcsize) */ /* ---------------------------------------------------------------------- */ /* maxcsize could be determined before L->s is allocated and defined, which * would mean that all memory requirements for both the symbolic and numeric * factorizations could be computed using O(nnz(A)+O(n)) space. However, it * would require a lot of extra work. The analysis phase, above, would need * to be duplicated, but with Ls not kept; instead, the algorithm would keep * track of the current s and slast for each supernode d, and update them * when a new row index appears in supernode d. An alternative would be to * do this computation only if the allocation of L->s failed, in which case * the following code would be skipped. * * The csize for a supernode is the size of its largest contribution to * a subsequent ancestor supernode. For example, suppose the rows of #'s * in the figure below correspond to the columns of a subsequent supernode, * and the dots are the entries in that ancestore. * * c * c c * c c c * x x x * x x x * # # # . * # # # . . * * * * . . * * * * . . * * * * . . * . . * * Then for this update, the csize is 3-by-2, or 6, because there are 3 * rows of *'s which is the number of rows in the update, and there are * 2 rows of #'s, which is the number columns in the update. The csize * of a supernode is the largest such contribution for any ancestor * supernode. maxcsize, for the whole matrix, has a rough upper bound of * the maximum size of any supernode. This bound is loose, because the * the contribution must be less than the size of the ancestor supernodal * that it's updating. maxcsize of a completely dense matrix, with one * supernode, is zero. * * maxesize is the column dimension for the workspace E needed for the * solve. E is of size nrhs-by-maxesize, where the nrhs is the number of * columns in the right-hand-side. The maxesize is the largest esize of * any supernode. The esize of a supernode is the number of row indices * it contains, excluding the column indices of the supernode itself. * For the following example, esize is 4: * * c * c c * c c c * x x x * x x x * x x x * x x x * * maxesize can be no bigger than n. */ maxcsize = 1 ; maxesize = 1 ; /* Do not need to guard csize against Int overflow since xsize is OK. */ if (for_cholesky) { /* this is not needed for QR factorization */ for (d = 0 ; d < nsuper ; d++) { nscol = Super [d+1] - Super [d] ; p = Lpi [d] + nscol ; plast = p ; pend = Lpi [d+1] ; esize = pend - p ; maxesize = MAX (maxesize, esize) ; slast = (p == pend) ? (EMPTY) : (SuperMap [Ls [p]]) ; for ( ; p <= pend ; p++) { s = (p == pend) ? (EMPTY) : (SuperMap [Ls [p]]) ; if (s != slast) { /* row i is the start of a new supernode */ ndrow1 = p - plast ; ndrow2 = pend - plast ; csize = ndrow2 * ndrow1 ; PRINT1 (("Supernode "ID" ancestor "ID" C: "ID"-by-"ID " csize "ID"\n", d, slast, ndrow1, ndrow2, csize)) ; maxcsize = MAX (maxcsize, csize) ; plast = p ; slast = s ; } } } PRINT1 (("max csize "ID"\n", maxcsize)) ; } /* Wj no longer needed for SuperMap } */ L->maxcsize = maxcsize ; L->maxesize = maxesize ; L->is_super = TRUE ; ASSERT (L->xtype == CHOLMOD_PATTERN && L->is_ll) ; /* ---------------------------------------------------------------------- */ /* supernodal symbolic factorization is complete */ /* ---------------------------------------------------------------------- */ FREE_WORKSPACE ; return (TRUE) ; } /* ========================================================================== */ /* === cholmod_super_symbolic =============================================== */ /* ========================================================================== */ /* Analyzes A, AA', or A(:,f)*A(:,f)' in preparation for a supernodal numeric * factorization. The user need not call this directly; cholmod_analyze is * a "simple" wrapper for this routine. * * This function does all the analysis for a supernodal Cholesky factorization. * * workspace: Flag (nrow), Head (nrow), Iwork (2*nrow), * and temporary space of size 3*nfsuper*sizeof(Int), where nfsuper <= n * is the number of fundamental supernodes. */ int CHOLMOD(super_symbolic) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to analyze */ cholmod_sparse *F, /* F = A' or A(:,f)' */ Int *Parent, /* elimination tree */ /* ---- in/out --- */ cholmod_factor *L, /* simplicial symbolic on input, * supernodal symbolic on output */ /* --------------- */ cholmod_common *Common ) { return (CHOLMOD(super_symbolic2) (TRUE, A, F, Parent, L, Common)) ; } #endif igraph/src/CHOLMOD/Supernodal/t_cholmod_super_numeric.c0000644000175100001440000007774113431000472022620 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/t_cholmod_super_numeric =================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2012, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Template routine for cholmod_super_numeric. All xtypes supported, except * that a zomplex A and F result in a complex L (there is no supernodal * zomplex L). */ /* ========================================================================== */ /* === complex arithmetic =================================================== */ /* ========================================================================== */ #include "cholmod_template.h" #ifdef USING_R #include #ifdef HAVE_F77_UNDERSCORE # define F77_CALL(x) x ## _ #else # define F77_CALL(x) x #endif #define F77_NAME(x) F77_CALL(x) #define F77_SUB(x) F77_CALL(x) #define F77_COM(x) F77_CALL(x) #define F77_COMDECL(x) F77_CALL(x) void F77_NAME(dsyrk)(const char *uplo, const char *trans, const int *n, const int *k, const double *alpha, const double *a, const int *lda, const double *beta, double *c, const int *ldc); void F77_NAME(dpotrf)(const char* uplo, const int* n, double* a, const int* lda, int* info); void F77_NAME(dtrsm)(const char *side, const char *uplo, const char *transa, const char *diag, const int *m, const int *n, const double *alpha, const double *a, const int *lda, double *b, const int *ldb); void F77_NAME(dtrsv)(const char *uplo, const char *trans, const char *diag, const int *n, const double *a, const int *lda, double *x, const int *incx); #endif #undef L_ENTRY #undef L_CLEAR #undef L_ASSIGN #undef L_MULTADD #undef L_ASSEMBLE #undef L_ASSEMBLESUB #ifdef REAL /* -------------------------------------------------------------------------- */ /* A, F, and L are all real */ /* -------------------------------------------------------------------------- */ #define L_ENTRY 1 #define L_CLEAR(Lx,p) Lx [p] = 0 #define L_ASSIGN(Lx,q, Ax,Az,p) Lx [q] = Ax [p] #define L_MULTADD(Lx,q, Ax,Az,p, f) Lx [q] += Ax [p] * f [0] #define L_ASSEMBLE(Lx,q,b) Lx [q] += b [0] #define L_ASSEMBLESUB(Lx,q,C,p) Lx [q] -= C [p] #else /* -------------------------------------------------------------------------- */ /* A and F are complex or zomplex, L and C are complex */ /* -------------------------------------------------------------------------- */ #define L_ENTRY 2 #define L_CLEAR(Lx,p) Lx [2*(p)] = 0 ; Lx [2*(p)+1] = 0 #define L_ASSEMBLE(Lx,q,b) Lx [2*(q)] += b [0] ; #define L_ASSEMBLESUB(Lx,q,C,p) \ Lx [2*(q) ] -= C [2*(p) ] ; \ Lx [2*(q)+1] -= C [2*(p)+1] ; #ifdef COMPLEX /* -------------------------------------------------------------------------- */ /* A, F, L, and C are all complex */ /* -------------------------------------------------------------------------- */ #define L_ASSIGN(Lx,q, Ax,Az,p) \ Lx [2*(q) ] = Ax [2*(p) ] ; \ Lx [2*(q)+1] = Ax [2*(p)+1] #define L_MULTADD(Lx,q, Ax,Az,p, f) \ Lx [2*(q) ] += Ax [2*(p) ] * f [0] - Ax [2*(p)+1] * f [1] ; \ Lx [2*(q)+1] += Ax [2*(p)+1] * f [0] + Ax [2*(p) ] * f [1] #else /* -------------------------------------------------------------------------- */ /* A and F are zomplex, L and C is complex */ /* -------------------------------------------------------------------------- */ #define L_ASSIGN(Lx,q, Ax,Az,p) \ Lx [2*(q) ] = Ax [p] ; \ Lx [2*(q)+1] = Az [p] ; #define L_MULTADD(Lx,q, Ax,Az,p, f) \ Lx [2*(q) ] += Ax [p] * f [0] - Az [p] * f [1] ; \ Lx [2*(q)+1] += Az [p] * f [0] + Ax [p] * f [1] #endif #endif /* ========================================================================== */ /* === t_cholmod_super_numeric ============================================== */ /* ========================================================================== */ /* This function returns FALSE only if integer overflow occurs in the BLAS. * It returns TRUE otherwise whether or not the matrix is positive definite. */ static int TEMPLATE (cholmod_super_numeric) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* F = A' or A(:,f)' */ double beta [2], /* beta*I is added to diagonal of matrix to factorize */ /* ---- in/out --- */ cholmod_factor *L, /* factorization */ /* -- workspace -- */ cholmod_dense *Cwork, /* size (L->maxcsize)-by-1 */ /* --------------- */ cholmod_common *Common ) { double one [2], zero [2], fjk [2], tstart ; double *Lx, *Ax, *Fx, *Az, *Fz, *C ; Int *Super, *Head, *Ls, *Lpi, *Lpx, *Map, *SuperMap, *RelativeMap, *Next, *Lpos, *Fp, *Fi, *Fnz, *Ap, *Ai, *Anz, *Iwork, *Next_save, *Lpos_save ; Int nsuper, n, j, i, k, s, p, pend, k1, k2, nscol, psi, psx, psend, nsrow, pj, d, kd1, kd2, info, ndcol, ndrow, pdi, pdx, pdend, pdi1, pdi2, pdx1, ndrow1, ndrow2, px, dancestor, sparent, dnext, nsrow2, ndrow3, pk, pf, pfend, stype, Apacked, Fpacked, q, imap, repeat_supernode, nscol2, ss, nscol_new = 0 ; /* If integer overflow occurs in the BLAS, Common->status is set to * CHOLMOD_TOO_LARGE, and the contents of Lx are undefined. */ Common->blas_ok = TRUE ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nsuper = L->nsuper ; n = L->n ; C = Cwork->x ; /* workspace of size L->maxcsize */ one [0] = 1.0 ; /* ALPHA for *syrk, *herk, *gemm, and *trsm */ one [1] = 0. ; zero [0] = 0. ; /* BETA for *syrk, *herk, and *gemm */ zero [1] = 0. ; Iwork = Common->Iwork ; SuperMap = Iwork ; /* size n (i/i/l) */ RelativeMap = Iwork + n ; /* size n (i/i/l) */ Next = Iwork + 2*((size_t) n) ; /* size nsuper*/ Lpos = Iwork + 2*((size_t) n) + nsuper ; /* size nsuper*/ Next_save = Iwork + 2*((size_t) n) + 2*((size_t) nsuper) ;/* size nsuper*/ Lpos_save = Iwork + 2*((size_t) n) + 3*((size_t) nsuper) ;/* size nsuper*/ Map = Common->Flag ; /* size n, use Flag as workspace for Map array */ Head = Common->Head ; /* size n+1, only Head [0..nsuper-1] used */ Ls = L->s ; Lpi = L->pi ; Lpx = L->px ; Super = L->super ; Lx = L->x ; #ifdef GPU_BLAS TEMPLATE (CHOLMOD (gpu_init)) (C, L->maxcsize, Common) ; #endif #ifndef NTIMER /* clear GPU / CPU statistics */ Common->CHOLMOD_CPU_GEMM_CALLS = 0 ; Common->CHOLMOD_CPU_SYRK_CALLS = 0 ; Common->CHOLMOD_CPU_TRSM_CALLS = 0 ; Common->CHOLMOD_CPU_POTRF_CALLS = 0 ; Common->CHOLMOD_GPU_GEMM_CALLS = 0 ; Common->CHOLMOD_GPU_SYRK_CALLS = 0 ; Common->CHOLMOD_GPU_TRSM_CALLS = 0 ; Common->CHOLMOD_GPU_POTRF_CALLS = 0 ; Common->CHOLMOD_CPU_GEMM_TIME = 0 ; Common->CHOLMOD_CPU_SYRK_TIME = 0 ; Common->CHOLMOD_CPU_TRSM_TIME = 0 ; Common->CHOLMOD_CPU_POTRF_TIME = 0 ; Common->CHOLMOD_GPU_GEMM_TIME = 0 ; Common->CHOLMOD_GPU_SYRK_TIME = 0 ; Common->CHOLMOD_GPU_TRSM_TIME = 0 ; Common->CHOLMOD_GPU_POTRF_TIME = 0 ; Common->CHOLMOD_ASSEMBLE_TIME = 0 ; Common->CHOLMOD_ASSEMBLE_TIME2 = 0 ; #endif stype = A->stype ; if (stype != 0) { /* F not accessed */ Fp = NULL ; Fi = NULL ; Fx = NULL ; Fz = NULL ; Fnz = NULL ; Fpacked = TRUE ; } else { Fp = F->p ; Fi = F->i ; Fx = F->x ; Fz = F->z ; Fnz = F->nz ; Fpacked = F->packed ; } Ap = A->p ; Ai = A->i ; Ax = A->x ; Az = A->z ; Anz = A->nz ; Apacked = A->packed ; /* clear the Map so that changes in the pattern of A can be detected */ for (i = 0 ; i < n ; i++) { Map [i] = EMPTY ; } /* If the matrix is not positive definite, the supernode s containing the * first zero or negative diagonal entry of L is repeated (but factorized * only up to just before the problematic diagonal entry). The purpose is * to provide MATLAB with [R,p]=chol(A); columns 1 to p-1 of L=R' are * required, where L(p,p) is the problematic diagonal entry. The * repeat_supernode flag tells us whether this is the repeated supernode. * Once supernode s is repeated, the factorization is terminated. */ repeat_supernode = FALSE ; /* ---------------------------------------------------------------------- */ /* supernodal numerical factorization */ /* ---------------------------------------------------------------------- */ for (s = 0 ; s < nsuper ; s++) { /* ------------------------------------------------------------------ */ /* get the size of supernode s */ /* ------------------------------------------------------------------ */ k1 = Super [s] ; /* s contains columns k1 to k2-1 of L */ k2 = Super [s+1] ; nscol = k2 - k1 ; /* # of columns in all of s */ psi = Lpi [s] ; /* pointer to first row of s in Ls */ psx = Lpx [s] ; /* pointer to first row of s in Lx */ psend = Lpi [s+1] ; /* pointer just past last row of s in Ls */ nsrow = psend - psi ; /* # of rows in all of s */ PRINT1 (("====================================================\n" "S "ID" k1 "ID" k2 "ID" nsrow "ID" nscol "ID" psi "ID" psend " ""ID" psx "ID"\n", s, k1, k2, nsrow, nscol, psi, psend, psx)) ; /* ------------------------------------------------------------------ */ /* zero the supernode s */ /* ------------------------------------------------------------------ */ ASSERT ((size_t) (psx + nsrow*nscol) <= L->xsize) ; pend = psx + nsrow * nscol ; /* s is nsrow-by-nscol */ for (p = psx ; p < pend ; p++) { /* Lx [p] = 0 ; */ L_CLEAR (Lx,p) ; } /* ------------------------------------------------------------------ */ /* construct the scattered Map for supernode s */ /* ------------------------------------------------------------------ */ /* If row i is the kth row in s, then Map [i] = k. Similarly, if * column j is the kth column in s, then Map [j] = k. */ for (k = 0 ; k < nsrow ; k++) { PRINT1 ((" "ID" map "ID"\n", Ls [psi+k], k)) ; Map [Ls [psi + k]] = k ; } /* ------------------------------------------------------------------ */ /* copy matrix into supernode s (lower triangular part only) */ /* ------------------------------------------------------------------ */ pk = psx ; for (k = k1 ; k < k2 ; k++) { if (stype != 0) { /* copy the kth column of A into the supernode */ p = Ap [k] ; pend = (Apacked) ? (Ap [k+1]) : (p + Anz [k]) ; for ( ; p < pend ; p++) { /* row i of L is located in row Map [i] of s */ i = Ai [p] ; if (i >= k) { /* This test is here simply to avoid a segfault. If * the test is false, the numeric factorization of A * is undefined. It does not detect all invalid * entries, only some of them (when debugging is * enabled, and Map is cleared after each step, then * all entries not in the pattern of L are detected). */ imap = Map [i] ; if (imap >= 0 && imap < nsrow) { /* Lx [Map [i] + pk] = Ax [p] ; */ L_ASSIGN (Lx,(imap+pk), Ax,Az,p) ; } } } } else { /* copy the kth column of A*F into the supernode */ pf = Fp [k] ; pfend = (Fpacked) ? (Fp [k+1]) : (p + Fnz [k]) ; for ( ; pf < pfend ; pf++) { j = Fi [pf] ; /* fjk = Fx [pf] ; */ L_ASSIGN (fjk,0, Fx,Fz,pf) ; p = Ap [j] ; pend = (Apacked) ? (Ap [j+1]) : (p + Anz [j]) ; for ( ; p < pend ; p++) { i = Ai [p] ; if (i >= k) { /* See the discussion of imap above. */ imap = Map [i] ; if (imap >= 0 && imap < nsrow) { /* Lx [Map [i] + pk] += Ax [p] * fjk ; */ L_MULTADD (Lx,(imap+pk), Ax,Az,p, fjk) ; } } } } } pk += nsrow ; /* advance to the next column of the supernode */ } /* add beta to the diagonal of the supernode, if nonzero */ if (beta [0] != 0.0) { /* note that only the real part of beta is used */ pk = psx ; for (k = k1 ; k < k2 ; k++) { /* Lx [pk] += beta [0] ; */ L_ASSEMBLE (Lx,pk, beta) ; pk += nsrow + 1 ; /* advance to the next diagonal entry */ } } PRINT1 (("Supernode with just A: repeat: "ID"\n", repeat_supernode)) ; DEBUG (CHOLMOD(dump_super) (s, Super, Lpi, Ls, Lpx, Lx, L_ENTRY, Common)) ; PRINT1 (("\n\n")) ; /* ------------------------------------------------------------------ */ /* save/restore the list of supernodes */ /* ------------------------------------------------------------------ */ if (!repeat_supernode) { /* Save the list of pending descendants in case s is not positive * definite. Also save Lpos for each descendant d, so that we can * find which part of d is used to update s. */ for (d = Head [s] ; d != EMPTY ; d = Next [d]) { Lpos_save [d] = Lpos [d] ; Next_save [d] = Next [d] ; } } else { /* s is not positive definite, and is being repeated. Restore * the list of supernodes. This can be done with pointer assignment * because all 4 arrays are held within Common->Iwork. */ Lpos = Lpos_save ; Next = Next_save ; } /* ------------------------------------------------------------------ */ /* update supernode s with each pending descendant d */ /* ------------------------------------------------------------------ */ #ifndef NDEBUG for (d = Head [s] ; d != EMPTY ; d = Next [d]) { PRINT1 (("\nWill update "ID" with Child: "ID"\n", s, d)) ; DEBUG (CHOLMOD(dump_super) (d, Super, Lpi, Ls, Lpx, Lx, L_ENTRY, Common)) ; } PRINT1 (("\nNow factorizing supernode "ID":\n", s)) ; #endif for (d = Head [s] ; d != EMPTY ; d = dnext) { /* -------------------------------------------------------------- */ /* get the size of supernode d */ /* -------------------------------------------------------------- */ kd1 = Super [d] ; /* d contains cols kd1 to kd2-1 of L */ kd2 = Super [d+1] ; ndcol = kd2 - kd1 ; /* # of columns in all of d */ pdi = Lpi [d] ; /* pointer to first row of d in Ls */ pdx = Lpx [d] ; /* pointer to first row of d in Lx */ pdend = Lpi [d+1] ; /* pointer just past last row of d in Ls */ ndrow = pdend - pdi ; /* # rows in all of d */ PRINT1 (("Child: ")) ; DEBUG (CHOLMOD(dump_super) (d, Super, Lpi, Ls, Lpx, Lx, L_ENTRY, Common)) ; /* -------------------------------------------------------------- */ /* find the range of rows of d that affect rows k1 to k2-1 of s */ /* -------------------------------------------------------------- */ p = Lpos [d] ; /* offset of 1st row of d affecting s */ pdi1 = pdi + p ; /* ptr to 1st row of d affecting s in Ls */ pdx1 = pdx + p ; /* ptr to 1st row of d affecting s in Lx */ /* there must be at least one row remaining in d to update s */ ASSERT (pdi1 < pdend) ; PRINT1 (("Lpos[d] "ID" pdi1 "ID" Ls[pdi1] "ID"\n", Lpos[d], pdi1, Ls [pdi1])) ; ASSERT (Ls [pdi1] >= k1 && Ls [pdi1] < k2) ; for (pdi2 = pdi1 ; pdi2 < pdend && Ls [pdi2] < k2 ; pdi2++) ; ndrow1 = pdi2 - pdi1 ; /* # rows in first part of d */ ndrow2 = pdend - pdi1 ; /* # rows in remaining d */ /* rows Ls [pdi1 ... pdi2-1] are in the range k1 to k2-1. Since d * affects s, this set cannot be empty. */ ASSERT (pdi1 < pdi2 && pdi2 <= pdend) ; PRINT1 (("ndrow1 "ID" ndrow2 "ID"\n", ndrow1, ndrow2)) ; DEBUG (for (p = pdi1 ; p < pdi2 ; p++) PRINT1 (("Ls["ID"] "ID"\n", p, Ls[p]))) ; /* -------------------------------------------------------------- */ /* construct the update matrix C for this supernode d */ /* -------------------------------------------------------------- */ /* C = L (k1:n-1, kd1:kd2-1) * L (k1:k2-1, kd1:kd2-1)', except * that k1:n-1 refers to all of the rows in L, but many of the * rows are all zero. Supernode d holds columns kd1 to kd2-1 of L. * Nonzero rows in the range k1:k2-1 are in the list * Ls [pdi1 ... pdi2-1], of size ndrow1. Nonzero rows in the range * k2:n-1 are in the list Ls [pdi2 ... pdend], of size ndrow2. Let * L1 = L (Ls [pdi1 ... pdi2-1], kd1:kd2-1), and let * L2 = L (Ls [pdi2 ... pdend], kd1:kd2-1). C is ndrow2-by-ndrow1. * Let C1 be the first ndrow1 rows of C and let C2 be the last * ndrow2-ndrow1 rows of C. Only the lower triangular part of C1 * needs to be computed since C1 is symmetric. */ /* maxcsize is the largest size of C for all pairs (d,s) */ ASSERT (ndrow2 * ndrow1 <= ((Int) L->maxcsize)) ; /* compute leading ndrow1-by-ndrow1 lower triangular block of C, * C1 = L1*L1' */ ndrow3 = ndrow2 - ndrow1 ; /* number of rows of C2 */ ASSERT (ndrow3 >= 0) ; #ifdef GPU_BLAS if (!TEMPLATE (CHOLMOD (gpu_updateC)) (ndrow1, ndrow2, ndrow, ndcol, pdx1, Lx, C, Common)) #endif { #ifndef NTIMER Common->CHOLMOD_CPU_SYRK_CALLS++ ; tstart = SuiteSparse_time () ; #endif #ifdef REAL BLAS_dsyrk ("L", "N", ndrow1, ndcol, /* N, K: L1 is ndrow1-by-ndcol*/ one, /* ALPHA: 1 */ Lx + L_ENTRY*pdx1, ndrow, /* A, LDA: L1, ndrow */ zero, /* BETA: 0 */ C, ndrow2) ; /* C, LDC: C1 */ #else BLAS_zherk ("L", "N", ndrow1, ndcol, /* N, K: L1 is ndrow1-by-ndcol*/ one, /* ALPHA: 1 */ Lx + L_ENTRY*pdx1, ndrow, /* A, LDA: L1, ndrow */ zero, /* BETA: 0 */ C, ndrow2) ; /* C, LDC: C1 */ #endif #ifndef NTIMER Common->CHOLMOD_CPU_SYRK_TIME += SuiteSparse_time () - tstart ; #endif /* compute remaining (ndrow2-ndrow1)-by-ndrow1 block of C, * C2 = L2*L1' */ if (ndrow3 > 0) { #ifndef NTIMER Common->CHOLMOD_CPU_GEMM_CALLS++ ; tstart = SuiteSparse_time () ; #endif #ifdef REAL BLAS_dgemm ("N", "C", ndrow3, ndrow1, ndcol, /* M, N, K */ one, /* ALPHA: 1 */ Lx + L_ENTRY*(pdx1 + ndrow1), /* A, LDA: L2, ndrow */ ndrow, Lx + L_ENTRY*pdx1, /* B, LDB: L1, ndrow */ ndrow, zero, /* BETA: 0 */ C + L_ENTRY*ndrow1, /* C, LDC: C2 */ ndrow2) ; #else BLAS_zgemm ("N", "C", ndrow3, ndrow1, ndcol, /* M, N, K */ one, /* ALPHA: 1 */ Lx + L_ENTRY*(pdx1 + ndrow1),/* A, LDA: L2, ndrow */ ndrow, Lx + L_ENTRY*pdx1, /* B, LDB: L1, ndrow */ ndrow, zero, /* BETA: 0 */ C + L_ENTRY*ndrow1, /* C, LDC: C2 */ ndrow2) ; #endif #ifndef NTIMER Common->CHOLMOD_CPU_GEMM_TIME += SuiteSparse_time () - tstart ; #endif } } DEBUG (CHOLMOD(dump_real) ("C", C, ndrow2, ndrow1, TRUE, L_ENTRY, Common)) ; /* -------------------------------------------------------------- */ /* construct relative map to assemble d into s */ /* -------------------------------------------------------------- */ for (i = 0 ; i < ndrow2 ; i++) { RelativeMap [i] = Map [Ls [pdi1 + i]] ; ASSERT (RelativeMap [i] >= 0 && RelativeMap [i] < nsrow) ; } /* -------------------------------------------------------------- */ /* assemble C into supernode s using the relative map */ /* -------------------------------------------------------------- */ #ifdef GPU_BLAS TEMPLATE (CHOLMOD (gpu_syncSyrk)) (Common) ; if (ndrow3 <= 0) { #endif /* non-GPU version, or GPU version when ndrow3 is zero */ pj = 0 ; for (j = 0 ; j < ndrow1 ; j++) /* cols k1:k2-1 */ { ASSERT (RelativeMap [j] == Map [Ls [pdi1 + j]]) ; ASSERT (RelativeMap [j] >= 0 && RelativeMap [j] < nscol) ; px = psx + RelativeMap [j] * nsrow ; for (i = j ; i < ndrow2 ; i++) /* rows k1:n-1 */ { ASSERT (RelativeMap [i] == Map [Ls [pdi1 + i]]) ; ASSERT (RelativeMap [i] >= j && RelativeMap[i] < nsrow); /* Lx [px + RelativeMap [i]] -= C [i + pj] ; */ q = px + RelativeMap [i] ; L_ASSEMBLESUB (Lx,q, C, i+pj) ; } pj += ndrow2 ; } #ifdef GPU_BLAS } else { /* GPU version when ndrow3 > zero, splits into two parts */ #ifndef NTIMER tstart = SuiteSparse_time () ; #endif pj = 0 ; for (j = 0 ; j < ndrow1 ; j++) /* cols k1:k2-1 */ { ASSERT (RelativeMap [j] == Map [Ls [pdi1 + j]]) ; ASSERT (RelativeMap [j] >= 0 && RelativeMap [j] < nscol) ; px = psx + RelativeMap [j] * nsrow ; for (i = j ; i < ndrow1 ; i++) /* rows k1:k2-1 */ { ASSERT (RelativeMap [i] == Map [Ls [pdi1 + i]]) ; ASSERT (RelativeMap [i] >= j && RelativeMap[i] < nsrow); /* Lx [px + RelativeMap [i]] -= C [i + pj] ; */ q = px + RelativeMap [i] ; L_ASSEMBLESUB (Lx,q, C, i+pj) ; } pj += ndrow2 ; } #ifndef NTIMER Common->CHOLMOD_ASSEMBLE_TIME2 += SuiteSparse_time () - tstart ; #endif /* wait for dgemm to finish */ TEMPLATE (CHOLMOD (gpu_syncGemm)) (Common) ; pj = 0 ; for (j = 0 ; j < ndrow1 ; j++) /* cols k1:k2-1 */ { ASSERT (RelativeMap [j] == Map [Ls [pdi1 + j]]) ; ASSERT (RelativeMap [j] >= 0 && RelativeMap [j] < nscol) ; px = psx + RelativeMap [j] * nsrow ; for (i = ndrow1 ; i < ndrow2 ; i++) /* rows k2:n-1 */ { ASSERT (RelativeMap [i] == Map [Ls [pdi1 + i]]) ; ASSERT (RelativeMap [i] >= j && RelativeMap[i] < nsrow); /* Lx [px + RelativeMap [i]] -= C [i + pj] ; */ q = px + RelativeMap [i] ; L_ASSEMBLESUB (Lx,q, C, i+pj) ; } pj += ndrow2 ; } #ifndef NTIMER Common->CHOLMOD_ASSEMBLE_TIME += SuiteSparse_time () - tstart ; #endif } #endif /* -------------------------------------------------------------- */ /* prepare this supernode d for its next ancestor */ /* -------------------------------------------------------------- */ dnext = Next [d] ; if (!repeat_supernode) { /* If node s is being repeated, Head [dancestor] has already * been cleared (set to EMPTY). It must remain EMPTY. The * dancestor will not be factorized since the factorization * terminates at node s. */ Lpos [d] = pdi2 - pdi ; if (Lpos [d] < ndrow) { dancestor = SuperMap [Ls [pdi2]] ; ASSERT (dancestor > s && dancestor < nsuper) ; /* place d in the link list of its next ancestor */ Next [d] = Head [dancestor] ; Head [dancestor] = d ; } } } PRINT1 (("\nSupernode with contributions A: repeat: "ID"\n", repeat_supernode)) ; DEBUG (CHOLMOD(dump_super) (s, Super, Lpi, Ls, Lpx, Lx, L_ENTRY, Common)) ; PRINT1 (("\n\n")) ; /* ------------------------------------------------------------------ */ /* factorize diagonal block of supernode s in LL' */ /* ------------------------------------------------------------------ */ /* The current supernode s is ready to factorize. It has been updated * by all descendant supernodes. Let S = the current supernode, which * holds rows k1:n-1 and columns k1:k2-1 of the updated matrix. It * splits into two parts: the square diagonal block S1, and the * rectangular part S2. Here, S1 is factorized into L1*L1' and * overwritten by L1. * * If supernode s is being repeated, only factorize it up to but not * including the column containing the problematic entry. */ nscol2 = (repeat_supernode) ? (nscol_new) : (nscol) ; #ifdef GPU_BLAS if (!TEMPLATE (CHOLMOD (gpu_lower_potrf)) (nscol2, nsrow, psx, Lx, &info, Common)) #endif { #ifndef NTIMER Common->CHOLMOD_CPU_POTRF_CALLS++ ; tstart = SuiteSparse_time () ; #endif #ifdef REAL LAPACK_dpotrf ("L", nscol2, /* N: nscol2 */ Lx + L_ENTRY*psx, nsrow, /* A, LDA: S1, nsrow */ info) ; /* INFO */ #else LAPACK_zpotrf ("L", nscol2, /* N: nscol2 */ Lx + L_ENTRY*psx, nsrow, /* A, LDA: S1, nsrow */ info) ; /* INFO */ #endif #ifndef NTIMER Common->CHOLMOD_CPU_POTRF_TIME += SuiteSparse_time ()- tstart ; #endif } /* ------------------------------------------------------------------ */ /* check if the matrix is not positive definite */ /* ------------------------------------------------------------------ */ if (repeat_supernode) { /* the leading part has been refactorized; it must have succeeded */ info = 0 ; /* zero out the rest of this supernode */ p = psx + nsrow * nscol_new ; pend = psx + nsrow * nscol ; /* s is nsrow-by-nscol */ for ( ; p < pend ; p++) { /* Lx [p] = 0 ; */ L_CLEAR (Lx,p) ; } } /* info is set to one in LAPACK_*potrf if blas_ok is FALSE. It is * set to zero in dpotrf/zpotrf if the factorization was successful. */ if (CHECK_BLAS_INT && !Common->blas_ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large for the BLAS") ; } if (info != 0) { /* Matrix is not positive definite. dpotrf/zpotrf do NOT report an * error if the diagonal of L has NaN's, only if it has a zero. */ if (Common->status == CHOLMOD_OK) { ERROR (CHOLMOD_NOT_POSDEF, "matrix not positive definite") ; } /* L->minor is the column of L that contains a zero or negative * diagonal term. */ L->minor = k1 + info - 1 ; /* clear the link lists of all subsequent supernodes */ for (ss = s+1 ; ss < nsuper ; ss++) { Head [ss] = EMPTY ; } /* zero this supernode, and all remaining supernodes */ pend = L->xsize ; for (p = psx ; p < pend ; p++) { /* Lx [p] = 0. ; */ L_CLEAR (Lx,p) ; } /* If L is indefinite, it still contains useful information. * Supernodes 0 to s-1 are valid, similar to MATLAB [R,p]=chol(A), * where the 1-based p is identical to the 0-based L->minor. Since * L->minor is in the current supernode s, it and any columns to the * left of it in supernode s are also all zero. This differs from * [R,p]=chol(A), which contains nonzero rows 1 to p-1. Fix this * by setting repeat_supernode to TRUE, and repeating supernode s. * * If Common->quick_return_if_not_posdef is true, then the entire * supernode s is not factorized; it is left as all zero. */ if (info == 1 || Common->quick_return_if_not_posdef) { /* If the first column of supernode s contains a zero or * negative diagonal entry, then it is already properly set to * zero. Also, info will be 1 if integer overflow occured in * the BLAS. */ Head [s] = EMPTY ; #ifdef GPU_BLAS TEMPLATE (CHOLMOD (gpu_end)) (Common) ; #endif return (Common->status >= CHOLMOD_OK) ; } else { /* Repeat supernode s, but only factorize it up to but not * including the column containing the problematic diagonal * entry. */ repeat_supernode = TRUE ; s-- ; nscol_new = info - 1 ; continue ; } } /* ------------------------------------------------------------------ */ /* compute the subdiagonal block and prepare supernode for its parent */ /* ------------------------------------------------------------------ */ nsrow2 = nsrow - nscol2 ; if (nsrow2 > 0) { /* The current supernode is columns k1 to k2-1 of L. Let L1 be the * diagonal block (factorized by dpotrf/zpotrf above; rows/cols * k1:k2-1), and L2 be rows k2:n-1 and columns k1:k2-1 of L. The * triangular system to solve is L2*L1' = S2, where S2 is * overwritten with L2. More precisely, L2 = S2 / L1' in MATLAB * notation. */ #ifdef GPU_BLAS if (!TEMPLATE (CHOLMOD (gpu_triangular_solve)) (nsrow2, nscol2, nsrow, psx, Lx, Common)) #endif { #ifndef NTIMER Common->CHOLMOD_CPU_TRSM_CALLS++ ; tstart = SuiteSparse_time () ; #endif #ifdef REAL BLAS_dtrsm ("R", "L", "C", "N", nsrow2, nscol2, /* M, N */ one, /* ALPHA: 1 */ Lx + L_ENTRY*psx, nsrow, /* A, LDA: L1, nsrow */ Lx + L_ENTRY*(psx + nscol2), /* B, LDB, L2, nsrow */ nsrow) ; #else BLAS_ztrsm ("R", "L", "C", "N", nsrow2, nscol2, /* M, N */ one, /* ALPHA: 1 */ Lx + L_ENTRY*psx, nsrow, /* A, LDA: L1, nsrow */ Lx + L_ENTRY*(psx + nscol2), /* B, LDB, L2, nsrow */ nsrow) ; #endif #ifndef NTIMER Common->CHOLMOD_CPU_TRSM_TIME += SuiteSparse_time () - tstart ; #endif } if (CHECK_BLAS_INT && !Common->blas_ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large for the BLAS") ; } if (!repeat_supernode) { /* Lpos [s] is offset of first row of s affecting its parent */ Lpos [s] = nscol ; sparent = SuperMap [Ls [psi + nscol]] ; ASSERT (sparent != EMPTY) ; ASSERT (Ls [psi + nscol] >= Super [sparent]) ; ASSERT (Ls [psi + nscol] < Super [sparent+1]) ; ASSERT (SuperMap [Ls [psi + nscol]] == sparent) ; ASSERT (sparent > s && sparent < nsuper) ; /* place s in link list of its parent */ Next [s] = Head [sparent] ; Head [sparent] = s ; } } Head [s] = EMPTY ; /* link list for supernode s no longer needed */ /* clear the Map (debugging only, to detect changes in pattern of A) */ DEBUG (for (k = 0 ; k < nsrow ; k++) Map [Ls [psi + k]] = EMPTY) ; DEBUG (CHOLMOD(dump_super) (s, Super, Lpi, Ls, Lpx, Lx, L_ENTRY, Common)) ; if (repeat_supernode) { /* matrix is not positive definite; finished clean-up for supernode * containing negative diagonal */ #ifdef GPU_BLAS TEMPLATE (CHOLMOD (gpu_end)) (Common) ; #endif return (Common->status >= CHOLMOD_OK) ; } } /* success; matrix is positive definite */ L->minor = n ; #ifdef GPU_BLAS TEMPLATE (CHOLMOD (gpu_end)) (Common) ; #endif return (Common->status >= CHOLMOD_OK) ; } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Supernodal/License.txt0000644000175100001440000000203113430770174017657 0ustar hornikusersCHOLMOD/Supernodal Module. Copyright (C) 2005-2006, Timothy A. Davis CHOLMOD is also available under other licenses; contact authors for details. http://www.suitesparse.com Note that this license is for the CHOLMOD/Supernodal module only. All CHOLMOD modules are licensed separately. -------------------------------------------------------------------------------- This Module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This Module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this Module; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. igraph/src/CHOLMOD/Supernodal/cholmod_super_solve.c0000644000175100001440000001602413431000472021746 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/cholmod_super_solve ======================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Solve Lx=b or L'x=b for a supernodal factorization. These routines do not * apply the permutation L->Perm. See cholmod_solve for a more general * interface that performs that operation. */ #ifndef NSUPERNODAL #include "cholmod_internal.h" #include "cholmod_supernodal.h" #include "igraph_blas_internal.h" /* ========================================================================== */ /* === TEMPLATE ============================================================= */ /* ========================================================================== */ #define REAL #include "t_cholmod_super_solve.c" /* #define COMPLEX */ /* #include "t_cholmod_super_solve.c" */ /* ========================================================================== */ /* === cholmod_super_lsolve ================================================= */ /* ========================================================================== */ /* Solve Lx=b where x and b are of size n-by-nrhs. b is overwritten by the * solution x. On input, b is stored in col-major order with leading dimension * of d, and on output x is stored in the same manner. * * The contents of the workspace E are undefined on both input and output. * * workspace: none */ int CHOLMOD(super_lsolve) /* TRUE if OK, FALSE if BLAS overflow occured */ ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the forward solve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to Lx=b on output */ /* ---- workspace ---- */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (X, FALSE) ; RETURN_IF_NULL (E, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (E, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; if (L->xtype != X->xtype) { ERROR (CHOLMOD_INVALID, "L and X must have the same xtype") ; return (FALSE) ; } if (L->xtype != E->xtype) { ERROR (CHOLMOD_INVALID, "L and E must have the same xtype") ; return (FALSE) ; } if (X->d < X->nrow || L->n != X->nrow) { ERROR (CHOLMOD_INVALID, "X and L dimensions must match") ; return (FALSE) ; } if (E->nzmax < X->ncol * (L->maxesize)) { ERROR (CHOLMOD_INVALID, "workspace E not large enough") ; return (FALSE) ; } if (!(L->is_ll) || !(L->is_super)) { ERROR (CHOLMOD_INVALID, "L not supernodal") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; ASSERT (IMPLIES (L->n == 0, L->nsuper == 0)) ; if (L->n == 0 || X->ncol == 0) { /* nothing to do */ return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* solve Lx=b using template routine */ /* ---------------------------------------------------------------------- */ switch (L->xtype) { case CHOLMOD_REAL: r_cholmod_super_lsolve (L, X, E, Common) ; break ; /* case CHOLMOD_COMPLEX: */ /* c_cholmod_super_lsolve (L, X, E, Common) ; */ /* break ; */ } if (CHECK_BLAS_INT && !Common->blas_ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large for the BLAS") ; } return (Common->blas_ok) ; } /* ========================================================================== */ /* === cholmod_super_ltsolve ================================================ */ /* ========================================================================== */ /* Solve L'x=b where x and b are of size n-by-nrhs. b is overwritten by the * solution x. On input, b is stored in col-major order with leading dimension * of d, and on output x is stored in the same manner. * * The contents of the workspace E are undefined on both input and output. * * workspace: none */ int CHOLMOD(super_ltsolve) /* TRUE if OK, FALSE if BLAS overflow occured */ ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the backsolve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to L'x=b on output */ /* ---- workspace ---- */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) { /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (X, FALSE) ; RETURN_IF_NULL (E, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (X, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (E, CHOLMOD_REAL, CHOLMOD_COMPLEX, FALSE) ; if (L->xtype != X->xtype) { ERROR (CHOLMOD_INVALID, "L and X must have the same xtype") ; return (FALSE) ; } if (L->xtype != E->xtype) { ERROR (CHOLMOD_INVALID, "L and E must have the same xtype") ; return (FALSE) ; } if (X->d < X->nrow || L->n != X->nrow) { ERROR (CHOLMOD_INVALID, "X and L dimensions must match") ; return (FALSE) ; } if (E->nzmax < X->ncol * (L->maxesize)) { ERROR (CHOLMOD_INVALID, "workspace E not large enough") ; return (FALSE) ; } if (!(L->is_ll) || !(L->is_super)) { ERROR (CHOLMOD_INVALID, "L not supernodal") ; return (FALSE) ; } Common->status = CHOLMOD_OK ; ASSERT (IMPLIES (L->n == 0, L->nsuper == 0)) ; if (L->n == 0 || X->ncol == 0) { /* nothing to do */ return (TRUE) ; } /* ---------------------------------------------------------------------- */ /* solve Lx=b using template routine */ /* ---------------------------------------------------------------------- */ switch (L->xtype) { case CHOLMOD_REAL: r_cholmod_super_ltsolve (L, X, E, Common) ; break ; /* case CHOLMOD_COMPLEX: */ /* c_cholmod_super_ltsolve (L, X, E, Common) ; */ /* break ; */ } if (CHECK_BLAS_INT && !Common->blas_ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large for the BLAS") ; } return (Common->blas_ok) ; } #endif igraph/src/CHOLMOD/Supernodal/gpl.txt0000644000175100001440000004313313430770174017067 0ustar hornikusers GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. igraph/src/CHOLMOD/Supernodal/t_cholmod_gpu.c0000644000175100001440000010374613431000472020526 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/t_cholmod_gpu ============================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2012, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* GPU BLAS template routine for cholmod_super_numeric. */ /* ========================================================================== */ /* === include files and definitions ======================================== */ /* ========================================================================== */ #include "cholmod_template.h" #undef L_ENTRY #ifdef REAL #define L_ENTRY 1 #else #define L_ENTRY 2 #endif /* #define GPU_Printf printf */ #define GPU_Printf #define PAGE_SIZE (4*1024) #define OK(cuda_operation) ((cuda_operation) == cudaSuccess) /* ========================================================================== */ /* === gpu_init ============================================================= */ /* ========================================================================== */ void TEMPLATE (CHOLMOD (gpu_init)) ( void *Cwork, Int maxSize, cholmod_common *Common ) { Int i ; cublasStatus_t cublasError ; cudaError_t cudaErr ; size_t maxBytesSize, HostPinnedSize ; Common->GemmUsed = 0 ; GPU_Printf ("gpu_init : %p\n", (void *) ((size_t) Cwork & ~(PAGE_SIZE-1))) ; if (!(Common->cublasHandle)) { /* ------------------------------------------------------------------ */ /* create the CUDA BLAS handle */ /* ------------------------------------------------------------------ */ cublasError = cublasCreate (&(Common->cublasHandle)) ; if (cublasError != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "CUBLAS initialization") ; return ; } /* ------------------------------------------------------------------ */ /* create each CUDA stream */ /* ------------------------------------------------------------------ */ cudaErr = cudaStreamCreate (&(Common->cudaStreamSyrk)) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA stream initialization") ; return ; } cudaErr = cudaStreamCreate (&(Common->cudaStreamGemm)) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA stream initialization") ; return ; } cudaErr = cudaStreamCreate (&(Common->cudaStreamTrsm)) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA stream initialization") ; return ; } for (i = 0 ; i < 3 ; i++) { cudaErr = cudaStreamCreate (&(Common->cudaStreamPotrf [i])) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA stream initialization") ; return ; } } /* ------------------------------------------------------------------ */ /* create each CUDA event */ /* ------------------------------------------------------------------ */ for (i = 0 ; i < 2 ; i++) { cudaErr = cudaEventCreateWithFlags (&(Common->cublasEventPotrf [i]), cudaEventDisableTiming) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA event") ; return ; } } } /* ---------------------------------------------------------------------- */ /* pin the Host memory */ /* ---------------------------------------------------------------------- */ Common->HostPinnedMemory = (void *) ((size_t) Cwork & ~(PAGE_SIZE-1)) ; maxBytesSize = sizeof (double)*L_ENTRY*maxSize ; /* Align on a 4K page boundary (it is no more necessary in 4.1 */ HostPinnedSize = (((size_t) Cwork + maxBytesSize + PAGE_SIZE-1) & ~(PAGE_SIZE-1)) - (size_t) (Common->HostPinnedMemory) ; GPU_Printf ("gpu HostPinnedSize: %g %p\n", (double) HostPinnedSize, Common->HostPinnedMemory) ; cudaErr = cudaHostRegister (Common->HostPinnedMemory, HostPinnedSize, 0) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA Pinning Memory") ; Common->HostPinnedMemory = NULL ; } } /* ========================================================================== */ /* === gpu_end ============================================================== */ /* ========================================================================== */ void TEMPLATE (CHOLMOD (gpu_end)) ( cholmod_common *Common ) { int i; /* unpin the Host memory */ GPU_Printf ("gpu_end %p\n", Common->HostPinnedMemory) ; cudaError_t cudaErr = cudaHostUnregister (Common->HostPinnedMemory) ; if (cudaErr != cudaSuccess) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA Unpinning Memory") ; Common->HostPinnedMemory = NULL ; } /* ------------------------------------------------------------------ */ /* destroy Cublas Handle */ /* ------------------------------------------------------------------ */ if (Common->cublasHandle) { cublasDestroy(Common->cublasHandle); Common->cublasHandle = NULL ; } /* ------------------------------------------------------------------ */ /* destroy each CUDA stream */ /* ------------------------------------------------------------------ */ if (Common->cudaStreamSyrk) { cudaStreamDestroy (Common->cudaStreamSyrk) ; Common->cudaStreamSyrk = NULL ; } if (Common->cudaStreamGemm) { cudaStreamDestroy (Common->cudaStreamGemm) ; } if (Common->cudaStreamTrsm) { cudaStreamDestroy (Common->cudaStreamTrsm) ; Common->cudaStreamTrsm = NULL ; } for (i = 0 ; i < 3 ; i++) { if (Common->cudaStreamPotrf [i]) { cudaStreamDestroy(Common->cudaStreamPotrf [i]) ; Common->cudaStreamPotrf [i] = NULL ; } } /* ------------------------------------------------------------------ */ /* destroy each CUDA event */ /* ------------------------------------------------------------------ */ for (i = 0 ; i < 2 ; i++) { if (Common->cublasEventPotrf [i]) { cudaEventDestroy( Common->cublasEventPotrf [i] ) ; Common->cublasEventPotrf [i] = NULL ; } } } /* ========================================================================== */ /* === gpu_updateC ========================================================== */ /* ========================================================================== */ /* C = L (k1:n-1, kd1:kd2-1) * L (k1:k2-1, kd1:kd2-1)', except that k1:n-1 * refers to all of the rows in L, but many of the rows are all zero. * Supernode d holds columns kd1 to kd2-1 of L. Nonzero rows in the range * k1:k2-1 are in the list Ls [pdi1 ... pdi2-1], of size ndrow1. Nonzero rows * in the range k2:n-1 are in the list Ls [pdi2 ... pdend], of size ndrow2. * Let L1 = L (Ls [pdi1 ... pdi2-1], kd1:kd2-1), and let L2 = L (Ls [pdi2 ... * pdend], kd1:kd2-1). C is ndrow2-by-ndrow1. Let C1 be the first ndrow1 * rows of C and let C2 be the last ndrow2-ndrow1 rows of C. Only the lower * triangular part of C1 needs to be computed since C1 is symmetric. */ int TEMPLATE (CHOLMOD (gpu_updateC)) ( Int ndrow1, /* C is ndrow2-by-ndrow2 */ Int ndrow2, Int ndrow, /* leading dimension of Lx */ Int ndcol, /* L1 is ndrow1-by-ndcol */ Int pdx1, /* L1 starts at Lx + L_ENTRY*pdx1 */ /* L2 starts at Lx + L_ENTRY*(pdx1 + ndrow1) */ double *Lx, double *C, cholmod_common *Common ) { double *devPtrLx, *devPtrC ; double alpha, beta ; cublasStatus_t cublasStatus ; cudaError_t cudaStat [2] ; Int ndrow3 ; Common->SyrkUsed = 0 ; Common->GemmUsed = 0 ; if ((ndrow2 < 512) || (ndcol < 128)) { /* too small for the CUDA BLAS; use the CPU instead */ return (0) ; } ndrow3 = ndrow2 - ndrow1 ; #ifndef NTIMER Common->syrkStart = SuiteSparse_time ( ) ; #endif /* ---------------------------------------------------------------------- */ /* allocate workspace on the GPU */ /* ---------------------------------------------------------------------- */ cudaStat [0] = cudaMalloc ((void **) &devPtrLx, ndrow2 * ndcol * L_ENTRY * sizeof (devPtrLx [0])) ; cudaStat [1] = cudaMalloc ((void **) &devPtrC, ndrow2 * ndrow1 * L_ENTRY * sizeof (devPtrC [0])) ; Common->devSyrkGemmPtrLx = devPtrLx ; Common->devSyrkGemmPtrC = devPtrC ; if (cudaStat [0] || cudaStat [1]) { /* one or both cudaMalloc's failed */ if (devPtrLx) cudaFree (devPtrLx) ; if (devPtrC) cudaFree (devPtrC) ; GPU_Printf ("gpu malloc failed =%d,%d ndrow1=%d ndrow2=%d ndcol=%d\n", cudaStat [0], cudaStat [1], (int) ndrow1, (int) ndrow2, (int) ndcol) ; /* cudaMalloc failure is not an error, just bypass the GPU */ return (0) ; } Common->SyrkUsed = 1 ; #ifndef NTIMER Common->CHOLMOD_GPU_SYRK_CALLS++ ; #endif /* ---------------------------------------------------------------------- */ /* copy Lx to the GPU */ /* ---------------------------------------------------------------------- */ /* copy Lx in two steps on different streams. * (ldLx is shortened from ndrow to ndrow2) */ cudaStat [0] = cudaMemcpy2DAsync (devPtrLx, ndrow2 * L_ENTRY * sizeof (devPtrLx [0]), Lx + L_ENTRY * pdx1, ndrow * L_ENTRY * sizeof (Lx [0]), ndrow1 * L_ENTRY * sizeof (devPtrLx [0]), ndcol, cudaMemcpyHostToDevice, Common->cudaStreamSyrk) ; if (cudaStat [0]) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } if (ndrow3 > 0) { Common->GemmUsed = 1 ; cudaStat [1] = cudaMemcpy2DAsync (devPtrLx + L_ENTRY*ndrow1, ndrow2 * L_ENTRY * sizeof (devPtrLx [0]), Lx + L_ENTRY * (pdx1 + ndrow1), ndrow * L_ENTRY * sizeof (Lx [0]), ndrow3 * L_ENTRY * sizeof (devPtrLx [0]), ndcol, cudaMemcpyHostToDevice, Common->cudaStreamGemm) ; if (cudaStat [1]) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } } /* ---------------------------------------------------------------------- */ /* do the CUDA SYRK */ /* ---------------------------------------------------------------------- */ cublasStatus = cublasSetStream (Common->cublasHandle, Common->cudaStreamSyrk) ; if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS stream") ; } alpha = 1.0 ; beta = 0.0 ; #ifdef REAL cublasStatus = cublasDsyrk (Common->cublasHandle, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_N, (int) ndrow1, (int) ndcol, /* N, K: L1 is ndrow1-by-ndcol */ &alpha, /* ALPHA: 1 */ devPtrLx, ndrow2, /* A, LDA: L1, ndrow2 */ &beta, /* BETA: 0 */ devPtrC, ndrow2) ; /* C, LDC: C1 */ #else cublasStatus = cublasZherk (Common->cublasHandle, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_N, (int) ndrow1, (int) ndcol, /* N, K: L1 is ndrow1-by-ndcol*/ &alpha, /* ALPHA: 1 */ (const cuDoubleComplex *) devPtrLx, ndrow2, /* A, LDA: L1, ndrow2 */ &beta, /* BETA: 0 */ (cuDoubleComplex *) devPtrC, ndrow2) ; /* C, LDC: C1 */ #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } /* ---------------------------------------------------------------------- */ /* partial copy of C to the GPU */ /* ---------------------------------------------------------------------- */ cudaStat [0] = cudaMemcpy2DAsync (C, ndrow2 * L_ENTRY * sizeof (C [0]), devPtrC, ndrow2 * L_ENTRY * sizeof (devPtrC [0]), ndrow1 * L_ENTRY * sizeof (devPtrC [0]), ndrow1, cudaMemcpyDeviceToHost, Common->cudaStreamSyrk) ; if (cudaStat [0]) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy from device") ; } /* ---------------------------------------------------------------------- */ /* compute remaining (ndrow2-ndrow1)-by-ndrow1 block of C, C2 = L2*L1' */ /* ---------------------------------------------------------------------- */ if (ndrow3 > 0) { #ifndef REAL cuDoubleComplex calpha = {1.0,0.0} ; cuDoubleComplex cbeta = {0.0,0.0} ; #endif #ifndef NTIMER Common->CHOLMOD_GPU_GEMM_CALLS++ ; #endif cublasStatus = cublasSetStream (Common->cublasHandle, Common->cudaStreamGemm) ; if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS stream") ; } /* ------------------------------------------------------------------ */ /* do the CUDA BLAS dgemm */ /* ------------------------------------------------------------------ */ #ifdef REAL alpha = 1.0 ; beta = 0.0 ; cublasStatus = cublasDgemm (Common->cublasHandle, CUBLAS_OP_N, CUBLAS_OP_T, ndrow3, ndrow1, ndcol, /* M, N, K */ &alpha, /* ALPHA: 1 */ devPtrLx + L_ENTRY*(ndrow1), /* A, LDA: L2, ndrow */ ndrow2, devPtrLx, /* B, LDB: L1, ndrow */ ndrow2, &beta, /* BETA: 0 */ devPtrC + L_ENTRY*ndrow1, /* C, LDC: C2 */ ndrow2) ; #else cublasStatus = cublasZgemm (Common->cublasHandle, CUBLAS_OP_N, CUBLAS_OP_C, ndrow3, ndrow1, ndcol, /* M, N, K */ &calpha, /* ALPHA: 1 */ (const cuDoubleComplex *) devPtrLx + ndrow1, /* A, LDA: L2, ndrow */ ndrow2, (const cuDoubleComplex *) devPtrLx, /* B, LDB: L1, ndrow */ ndrow2, &cbeta, /* BETA: 0 */ (cuDoubleComplex *)devPtrC + ndrow1, /* C, LDC: C2 */ ndrow2) ; #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } /* ------------------------------------------------------------------ */ /* finish copy of C */ /* ------------------------------------------------------------------ */ cudaStat [0] = cudaMemcpy2DAsync (C + L_ENTRY*ndrow1, ndrow2 * L_ENTRY * sizeof (C [0]), devPtrC+ L_ENTRY*ndrow1, ndrow2 * L_ENTRY * sizeof (devPtrC [0]), ndrow3 * L_ENTRY * sizeof (devPtrC [0]), ndrow1, cudaMemcpyDeviceToHost, Common->cudaStreamGemm) ; if (cudaStat [0]) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy from device") ; } } return (1) ; } /* ========================================================================== */ /* === gpu_syncSyrk ========================================================= */ /* ========================================================================== */ /* synchronize with the CUDA BLAS dsyrk stream */ void TEMPLATE (CHOLMOD (gpu_syncSyrk)) ( cholmod_common *Common ) { if (Common->SyrkUsed) { cudaStreamSynchronize (Common->cudaStreamSyrk) ; if (!Common->GemmUsed) { cudaFree (Common->devSyrkGemmPtrLx) ; cudaFree (Common->devSyrkGemmPtrC) ; Common->devSyrkGemmPtrLx = NULL ; Common->devSyrkGemmPtrC = NULL ; #ifndef NTIMER /* this actually sums time spend on Syrk and Gemm */ Common->CHOLMOD_GPU_SYRK_TIME += SuiteSparse_time ( ) - Common->syrkStart ; #endif } } } /* ========================================================================== */ /* === gpu_syncGemm ========================================================= */ /* ========================================================================== */ /* synchronize with the CUDA BLAS dgemm stream */ void TEMPLATE (CHOLMOD (gpu_syncGemm)) ( cholmod_common *Common ) { if (Common->GemmUsed) { cudaStreamSynchronize (Common->cudaStreamGemm) ; cudaFree (Common->devSyrkGemmPtrLx) ; cudaFree (Common->devSyrkGemmPtrC) ; Common->devSyrkGemmPtrLx = NULL ; Common->devSyrkGemmPtrC = NULL ; #ifndef NTIMER /* this actually sums time spend on Syrk and Gemm */ Common->CHOLMOD_GPU_SYRK_TIME += SuiteSparse_time ( ) - Common->syrkStart ; #endif } } /* ========================================================================== */ /* === gpu_lower_potrf ====================================================== */ /* ========================================================================== */ /* Cholesky factorzation (dpotrf) of a matrix S, operating on the lower * triangular part only. S is nscol2-by-nscol2 with leading dimension nsrow. * * S is the top part of the supernode (the lower triangular matrx). * This function also copies the bottom rectangular part of the supernode (B) * onto the GPU, in preparation for gpu_triangular_solve. */ int TEMPLATE (CHOLMOD (gpu_lower_potrf)) ( Int nscol2, /* S is nscol2-by-nscol2 */ Int nsrow, /* leading dimension of S */ Int psx, /* S is located at Lx + L_Entry*psx */ double *Lx, /* contains S; overwritten with Cholesky factor */ Int *info, /* BLAS info return value */ cholmod_common *Common ) { double *devPtrA, *devPtrB, *A ; double alpha, beta ; cudaError_t cudaStat ; cublasStatus_t cublasStatus ; Int j, nsrow2, nb, n, gpu_lda, lda, gpu_ldb ; int ilda, ijb, iinfo ; #ifndef NTIMER double tstart = SuiteSparse_time ( ) ; #endif if (nscol2 < 256) { /* too small for the CUDA BLAS; use the CPU instead */ return (0) ; } nsrow2 = nsrow - nscol2 ; /* ---------------------------------------------------------------------- */ /* heuristic to get the block size depending of the problem size */ /* ---------------------------------------------------------------------- */ nb = 128 ; if (nscol2 > 4096) nb = 256 ; if (nscol2 > 8192) nb = 384 ; n = nscol2 ; gpu_lda = ((nscol2+31)/32)*32 ; lda = nsrow ; A = Lx + L_ENTRY*psx ; /* ---------------------------------------------------------------------- */ /* free the dpotrf workspace, if allocated */ /* ---------------------------------------------------------------------- */ if (Common->devPotrfWork) { cudaFree (Common->devPotrfWork) ; Common->devPotrfWork = NULL ; } /* ---------------------------------------------------------------------- */ /* determine the GPU leading dimension of B */ /* ---------------------------------------------------------------------- */ gpu_ldb = 0 ; if (nsrow2 > 0) { gpu_ldb = ((nsrow2+31)/32)*32 ; } /* ---------------------------------------------------------------------- */ /* allocate device memory for the factorization and for potential solve */ /* ---------------------------------------------------------------------- */ cudaStat = cudaMalloc ((void **) &devPtrA, gpu_lda * (gpu_lda + gpu_ldb) * L_ENTRY * sizeof (devPtrA [0])) ; if (cudaStat) { GPU_Printf ("@@gpu_lower_potrf cudaMalloc failed =%d gpu_lda=%d\n", cudaStat, (int) (gpu_lda)) ; /* cudaMalloc failure not fatal, GPU bypassed */ return (0) ; } #ifndef NTIMER Common->CHOLMOD_GPU_POTRF_CALLS++ ; #endif /* ---------------------------------------------------------------------- */ /* remember where device memory is, to be used by triangular solve later */ /* ---------------------------------------------------------------------- */ Common->devPotrfWork = devPtrA ; devPtrB = devPtrA + gpu_lda * gpu_lda * L_ENTRY ; /* ---------------------------------------------------------------------- */ /* copy B in advance, for gpu_triangular_solve */ /* ---------------------------------------------------------------------- */ if (nsrow2 > 0) { cudaStat = cudaMemcpy2DAsync (devPtrB, gpu_ldb * L_ENTRY * sizeof (devPtrB [0]), Lx + L_ENTRY * (psx + nscol2), nsrow * L_ENTRY * sizeof (Lx [0]), nsrow2 * L_ENTRY * sizeof (devPtrB [0]), nscol2, cudaMemcpyHostToDevice, Common->cudaStreamTrsm) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } } /* ---------------------------------------------------------------------- */ /* block Cholesky factorization of S */ /* ---------------------------------------------------------------------- */ for (j = 0 ; j < n ; j += nb) { Int jb = nb < (n-j) ? nb : (n-j) ; /* ------------------------------------------------------------------ */ /* copy jb columns starting at the diagonal to the GPU */ /* ------------------------------------------------------------------ */ cudaStat = cudaMemcpy2DAsync (devPtrA + (j + j*gpu_lda)*L_ENTRY, gpu_lda * L_ENTRY * sizeof (devPtrA [0]), A + L_ENTRY*(j + j*lda), lda * L_ENTRY * sizeof (A [0]), (n-j) * L_ENTRY * sizeof (devPtrA [0]), jb, cudaMemcpyHostToDevice, Common->cudaStreamPotrf [0]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } /* ------------------------------------------------------------------ */ /* define the dpotrf stream */ /* ------------------------------------------------------------------ */ cublasStatus = cublasSetStream (Common->cublasHandle, Common->cudaStreamPotrf [0]) ; if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS stream") ; } /* ------------------------------------------------------------------ */ /* record the end of the copy of block L22 | L32 */ /* ------------------------------------------------------------------ */ cudaStat = cudaEventRecord (Common->cublasEventPotrf [0], Common->cudaStreamPotrf [0]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA event failure") ; } /* ------------------------------------------------------------------ */ /* do the CUDA BLAS dsyrk */ /* ------------------------------------------------------------------ */ alpha = -1.0 ; beta = 1.0 ; #ifdef REAL cublasStatus = cublasDsyrk (Common->cublasHandle, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_N, jb, j, &alpha, devPtrA + j, gpu_lda, &beta, devPtrA + j + j*gpu_lda, gpu_lda) ; #else cublasStatus = cublasZherk (Common->cublasHandle, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_N, jb, j, &alpha, (cuDoubleComplex*)devPtrA + j, gpu_lda, &beta, (cuDoubleComplex*)devPtrA + j + j*gpu_lda, gpu_lda) ; #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } /* ------------------------------------------------------------------ */ cudaStat = cudaEventRecord (Common->cublasEventPotrf [1], Common->cudaStreamPotrf [0]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA event failure") ; } cudaStat = cudaStreamWaitEvent (Common->cudaStreamPotrf [1], Common->cublasEventPotrf [1], 0) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "CUDA event failure") ; } /* ------------------------------------------------------------------ */ /* copy back the jb columns on two different streams */ /* ------------------------------------------------------------------ */ cudaStat = cudaMemcpy2DAsync (A + L_ENTRY*(j + j*lda), lda * L_ENTRY * sizeof (double), devPtrA + L_ENTRY*(j + j*gpu_lda), gpu_lda * L_ENTRY * sizeof (double), L_ENTRY * sizeof (double)*jb, jb, cudaMemcpyDeviceToHost, Common->cudaStreamPotrf [1]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy from device") ; } cudaStat = cudaMemcpy2DAsync (A + L_ENTRY*j, lda * L_ENTRY * sizeof (double), devPtrA + L_ENTRY*j, gpu_lda * L_ENTRY * sizeof (double), L_ENTRY * sizeof (double)*jb, j, cudaMemcpyDeviceToHost, Common->cudaStreamPotrf [0]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } /* ------------------------------------------------------------------ */ /* do the CUDA BLAS dgemm */ /* ------------------------------------------------------------------ */ if ((j+jb) < n) { #ifdef REAL alpha = -1.0 ; beta = 1.0 ; cublasStatus = cublasDgemm (Common->cublasHandle, CUBLAS_OP_N, CUBLAS_OP_T, (n-j-jb), jb, j, &alpha, devPtrA + (j+jb), gpu_lda, devPtrA + (j) , gpu_lda, &beta, devPtrA + (j+jb + j*gpu_lda), gpu_lda) ; #else cuDoubleComplex calpha = {-1.0,0.0} ; cuDoubleComplex cbeta = { 1.0,0.0} ; cublasStatus = cublasZgemm (Common->cublasHandle, CUBLAS_OP_N, CUBLAS_OP_C, (n-j-jb), jb, j, &calpha, (cuDoubleComplex*)devPtrA + (j+jb), gpu_lda, (cuDoubleComplex*)devPtrA + (j) , gpu_lda, &cbeta, (cuDoubleComplex*)devPtrA + (j+jb + j*gpu_lda), gpu_lda) ; #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } } cudaStat = cudaStreamSynchronize (Common->cudaStreamPotrf [1]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } /* ------------------------------------------------------------------ */ /* compute the Cholesky factorization of the jbxjb block on the CPU */ /* ------------------------------------------------------------------ */ ilda = (int) lda ; ijb = jb ; #ifdef REAL LAPACK_DPOTRF ("L", &ijb, A + L_ENTRY * (j + j*lda), &ilda, &iinfo) ; #else LAPACK_ZPOTRF ("L", &ijb, A + L_ENTRY * (j + j*lda), &ilda, &iinfo) ; #endif *info = iinfo ; if (*info != 0) { *info = *info + j ; break ; } /* ------------------------------------------------------------------ */ /* copy the result back to the GPU */ /* ------------------------------------------------------------------ */ cudaStat = cudaMemcpy2DAsync (devPtrA + L_ENTRY*(j + j*gpu_lda), gpu_lda * L_ENTRY * sizeof (double), A + L_ENTRY * (j + j*lda), lda * L_ENTRY * sizeof (double), L_ENTRY * sizeof (double) * jb, jb, cudaMemcpyHostToDevice, Common->cudaStreamPotrf [0]) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy to device") ; } /* ------------------------------------------------------------------ */ /* do the CUDA BLAS dtrsm */ /* ------------------------------------------------------------------ */ if ((j+jb) < n) { #ifdef REAL alpha = 1.0 ; cublasStatus = cublasDtrsm (Common->cublasHandle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_T, CUBLAS_DIAG_NON_UNIT, (n-j-jb), jb, &alpha, devPtrA + (j + j*gpu_lda), gpu_lda, devPtrA + (j+jb + j*gpu_lda), gpu_lda) ; #else cuDoubleComplex calpha = {1.0,0.0}; cublasStatus = cublasZtrsm (Common->cublasHandle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_C, CUBLAS_DIAG_NON_UNIT, (n-j-jb), jb, &calpha, (cuDoubleComplex *)devPtrA + (j + j*gpu_lda), gpu_lda, (cuDoubleComplex *)devPtrA + (j+jb + j*gpu_lda), gpu_lda) ; #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } } } if (nsrow2 <= 0) { /* No TRSM necessary */ cudaFree (Common->devPotrfWork) ; Common->devPotrfWork = NULL ; } #ifndef NTIMER Common->CHOLMOD_GPU_POTRF_TIME += SuiteSparse_time ( ) - tstart ; #endif return (1) ; } /* ========================================================================== */ /* === gpu_triangular_solve ================================================= */ /* ========================================================================== */ /* The current supernode is columns k1 to k2-1 of L. Let L1 be the diagonal * block (factorized by dpotrf/zpotrf above; rows/cols k1:k2-1), and L2 be rows * k2:n-1 and columns k1:k2-1 of L. The triangular system to solve is L2*L1' = * S2, where S2 is overwritten with L2. More precisely, L2 = S2 / L1' in * MATLAB notation. */ /* Version with pre-allocation in POTRF */ int TEMPLATE (CHOLMOD (gpu_triangular_solve)) ( Int nsrow2, /* L1 and S2 are nsrow2-by-nscol2 */ Int nscol2, /* L1 is nscol2-by-nscol2 */ Int nsrow, /* leading dimension of L1, L2, and S2 */ Int psx, /* L1 is at Lx+L_ENTRY*psx; L2 at Lx+L_ENTRY*(psx+nscol2)*/ double *Lx, /* holds L1, L2, and S2 */ cholmod_common *Common ) { double *devPtrA, *devPtrB ; cudaError_t cudaStat ; cublasStatus_t cublasStatus ; Int gpu_lda, gpu_ldb ; #ifdef REAL double alpha = 1.0 ; #else cuDoubleComplex calpha = {1.0,0.0} ; #endif if (!Common->devPotrfWork) { /* no workspace for triangular solve */ return (0) ; } #ifndef NTIMER double tstart = SuiteSparse_time ( ) ; Common->CHOLMOD_GPU_TRSM_CALLS++ ; #endif gpu_lda = ((nscol2+31)/32)*32 ; gpu_ldb = ((nsrow2+31)/32)*32 ; devPtrA = Common->devPotrfWork ; devPtrB = devPtrA + gpu_lda * gpu_lda * L_ENTRY ; /* ---------------------------------------------------------------------- */ /* start the trsm stream */ /* ---------------------------------------------------------------------- */ cublasStatus = cublasSetStream (Common->cublasHandle, Common->cudaStreamTrsm) ; if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS stream") ; } /* ---------------------------------------------------------------------- */ /* do the CUDA BLAS dtrsm */ /* ---------------------------------------------------------------------- */ #ifdef REAL cublasStatus = cublasDtrsm (Common->cublasHandle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_T, CUBLAS_DIAG_NON_UNIT, nsrow2, nscol2, /* M, N */ &alpha, /* ALPHA: 1 */ devPtrA, gpu_lda, /* A, LDA */ devPtrB, gpu_ldb) ; /* B, LDB */ #else cublasStatus = cublasZtrsm (Common->cublasHandle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_LOWER, CUBLAS_OP_C, CUBLAS_DIAG_NON_UNIT, nsrow2, nscol2, /* M, N */ &calpha, /* ALPHA: 1 */ (const cuDoubleComplex *) devPtrA, gpu_lda, /* A, LDA */ (cuDoubleComplex *) devPtrB, gpu_ldb) ; /* B, LDB: nsrow2 */ #endif if (cublasStatus != CUBLAS_STATUS_SUCCESS) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU CUBLAS routine failure") ; } /* ---------------------------------------------------------------------- */ /* copy result back to the CPU */ /* ---------------------------------------------------------------------- */ cudaStat = cudaMemcpy2DAsync (Lx + L_ENTRY*(psx + nscol2), nsrow * L_ENTRY * sizeof (Lx [0]), devPtrB, gpu_ldb * L_ENTRY * sizeof (devPtrB [0]), nsrow2 * L_ENTRY * sizeof (devPtrB [0]), nscol2, cudaMemcpyDeviceToHost, Common->cudaStreamTrsm) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU memcopy from device") ; } /* ---------------------------------------------------------------------- */ /* synchronize with the GPU */ /* ---------------------------------------------------------------------- */ cudaStat = cudaThreadSynchronize ( ) ; if (cudaStat) { ERROR (CHOLMOD_GPU_PROBLEM, "GPU synchronization failure") ; } /* ---------------------------------------------------------------------- */ /* free workspace and return */ /* ---------------------------------------------------------------------- */ cudaFree (Common->devPotrfWork) ; Common->devPotrfWork = NULL ; #ifndef NTIMER Common->CHOLMOD_GPU_TRSM_TIME += SuiteSparse_time ( ) - tstart ; #endif return (1) ; } #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/CHOLMOD/Supernodal/cholmod_super_numeric.c0000644000175100001440000002561113431000472022262 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/cholmod_super_numeric ===================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Computes the Cholesky factorization of A+beta*I or A*F+beta*I. Only the * the lower triangular part of A+beta*I or A*F+beta*I is accessed. The * matrices A and F must already be permuted according to the fill-reduction * permutation L->Perm. cholmod_factorize is an "easy" wrapper for this code * which applies that permutation. beta is real. * * Symmetric case: A is a symmetric (lower) matrix. F is not accessed. * With a fill-reducing permutation, A(p,p) should be passed instead, where is * p is L->Perm. * * Unsymmetric case: A is unsymmetric, and F must be present. Normally, F=A'. * With a fill-reducing permutation, A(p,f) and A(p,f)' should be passed as A * and F, respectively, where f is a list of the subset of the columns of A. * * The input factorization L must be supernodal (L->is_super is TRUE). It can * either be symbolic or numeric. In the first case, L has been analyzed by * cholmod_analyze or cholmod_super_symbolic, but the matrix has not yet been * numerically factorized. The numerical values are allocated here and the * factorization is computed. In the second case, a prior matrix has been * analyzed and numerically factorized, and a new matrix is being factorized. * The numerical values of L are replaced with the new numerical factorization. * * L->is_ll is ignored, and set to TRUE. This routine always computes an LL' * factorization. Supernodal LDL' factorization is not (yet) supported. * FUTURE WORK: perform a supernodal LDL' factorization if L->is_ll is FALSE. * * Uses BLAS routines dsyrk, dgemm, dtrsm, and the LAPACK routine dpotrf. * The supernodal solver uses BLAS routines dtrsv, dgemv, dtrsm, and dgemm. * * If the matrix is not positive definite the routine returns TRUE, but sets * Common->status to CHOLMOD_NOT_POSDEF and L->minor is set to the column at * which the failure occurred. The supernode containing the non-positive * diagonal entry is set to zero (this includes columns to the left of L->minor * in the same supernode), as are all subsequent supernodes. * * workspace: Flag (nrow), Head (nrow+1), Iwork (2*nrow + 4*nsuper). * Allocates temporary space of size L->maxcsize * sizeof(double) * (twice that for the complex/zomplex case). * * If L is supernodal symbolic on input, it is converted to a supernodal numeric * factor on output, with an xtype of real if A is real, or complex if A is * complex or zomplex. If L is supernodal numeric on input, its xtype must * match A (except that L can be complex and A zomplex). The xtype of A and F * must match. */ #ifndef NSUPERNODAL #include "cholmod_internal.h" #include "cholmod_supernodal.h" #include "igraph_blas_internal.h" #include "igraph_lapack_internal.h" /* ========================================================================== */ /* === TEMPLATE codes for GPU and regular numeric factorization ============= */ /* ========================================================================== */ #ifdef GPU_BLAS #define REAL #include "t_cholmod_gpu.c" #define COMPLEX #include "t_cholmod_gpu.c" #define ZOMPLEX #include "t_cholmod_gpu.c" #endif #define REAL #include "t_cholmod_super_numeric.c" /* #define COMPLEX */ /* #include "t_cholmod_super_numeric.c" */ /* #define ZOMPLEX */ /* #include "t_cholmod_super_numeric.c" */ /* ========================================================================== */ /* === cholmod_super_numeric ================================================ */ /* ========================================================================== */ /* Returns TRUE if successful, or if the matrix is not positive definite. * Returns FALSE if out of memory, inputs are invalid, or other fatal error * occurs. */ int CHOLMOD(super_numeric) ( /* ---- input ---- */ cholmod_sparse *A, /* matrix to factorize */ cholmod_sparse *F, /* F = A' or A(:,f)' */ double beta [2], /* beta*I is added to diagonal of matrix to factorize */ /* ---- in/out --- */ cholmod_factor *L, /* factorization */ /* --------------- */ cholmod_common *Common ) { cholmod_dense *C ; Int *Super, *Map, *SuperMap ; size_t maxcsize ; Int nsuper, n, i, k, s, stype, nrow ; int ok = TRUE, symbolic ; size_t t, w ; /* ---------------------------------------------------------------------- */ /* check inputs */ /* ---------------------------------------------------------------------- */ RETURN_IF_NULL_COMMON (FALSE) ; RETURN_IF_NULL (L, FALSE) ; RETURN_IF_NULL (A, FALSE) ; RETURN_IF_XTYPE_INVALID (A, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; RETURN_IF_XTYPE_INVALID (L, CHOLMOD_PATTERN, CHOLMOD_COMPLEX, FALSE) ; stype = A->stype ; if (stype < 0) { if (A->nrow != A->ncol || A->nrow != L->n) { ERROR (CHOLMOD_INVALID, "invalid dimensions") ; return (FALSE) ; } } else if (stype == 0) { if (A->nrow != L->n) { ERROR (CHOLMOD_INVALID, "invalid dimensions") ; return (FALSE) ; } RETURN_IF_NULL (F, FALSE) ; RETURN_IF_XTYPE_INVALID (F, CHOLMOD_REAL, CHOLMOD_ZOMPLEX, FALSE) ; if (A->nrow != F->ncol || A->ncol != F->nrow || F->stype != 0) { ERROR (CHOLMOD_INVALID, "F invalid") ; return (FALSE) ; } if (A->xtype != F->xtype) { ERROR (CHOLMOD_INVALID, "A and F must have same xtype") ; return (FALSE) ; } } else { /* symmetric upper case not suppored */ ERROR (CHOLMOD_INVALID, "symmetric upper case not supported") ; return (FALSE) ; } if (!(L->is_super)) { ERROR (CHOLMOD_INVALID, "L not supernodal") ; return (FALSE) ; } if (L->xtype != CHOLMOD_PATTERN) { if (! ((A->xtype == CHOLMOD_REAL && L->xtype == CHOLMOD_REAL) || (A->xtype == CHOLMOD_COMPLEX && L->xtype == CHOLMOD_COMPLEX) || (A->xtype == CHOLMOD_ZOMPLEX && L->xtype == CHOLMOD_COMPLEX))) { ERROR (CHOLMOD_INVALID, "complex type mismatch") ; return (FALSE) ; } } Common->status = CHOLMOD_OK ; /* ---------------------------------------------------------------------- */ /* allocate workspace in Common */ /* ---------------------------------------------------------------------- */ nsuper = L->nsuper ; maxcsize = L->maxcsize ; nrow = A->nrow ; n = nrow ; PRINT1 (("nsuper "ID" maxcsize %g\n", nsuper, (double) maxcsize)) ; ASSERT (nsuper >= 0 && maxcsize > 0) ; /* w = 2*n + 4*nsuper */ w = CHOLMOD(mult_size_t) (n, 2, &ok) ; t = CHOLMOD(mult_size_t) (nsuper, 4, &ok) ; w = CHOLMOD(add_size_t) (w, t, &ok) ; if (!ok) { ERROR (CHOLMOD_TOO_LARGE, "problem too large") ; return (FALSE) ; } CHOLMOD(allocate_work) (n, w, 0, Common) ; if (Common->status < CHOLMOD_OK) { return (FALSE) ; } ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; /* ---------------------------------------------------------------------- */ /* get the current factor L and allocate numerical part, if needed */ /* ---------------------------------------------------------------------- */ Super = L->super ; symbolic = (L->xtype == CHOLMOD_PATTERN) ; if (symbolic) { /* convert to supernodal numeric by allocating L->x */ CHOLMOD(change_factor) ( (A->xtype == CHOLMOD_REAL) ? CHOLMOD_REAL : CHOLMOD_COMPLEX, TRUE, TRUE, TRUE, TRUE, L, Common) ; if (Common->status < CHOLMOD_OK) { /* the factor L remains in symbolic supernodal form */ return (FALSE) ; } } ASSERT (L->dtype == DTYPE) ; ASSERT (L->xtype == CHOLMOD_REAL || L->xtype == CHOLMOD_COMPLEX) ; /* supernodal LDL' is not supported */ L->is_ll = TRUE ; /* ---------------------------------------------------------------------- */ /* get more workspace */ /* ---------------------------------------------------------------------- */ C = CHOLMOD(allocate_dense) (maxcsize, 1, maxcsize, L->xtype, Common) ; if (Common->status < CHOLMOD_OK) { int status = Common->status ; if (symbolic) { /* Change L back to symbolic, since the numeric values are not * initialized. This cannot fail. */ CHOLMOD(change_factor) (CHOLMOD_PATTERN, TRUE, TRUE, TRUE, TRUE, L, Common) ; } /* the factor L is now back to the form it had on input */ Common->status = status ; return (FALSE) ; } /* ---------------------------------------------------------------------- */ /* get workspace */ /* ---------------------------------------------------------------------- */ SuperMap = Common->Iwork ; /* size n (i/i/l) */ Map = Common->Flag ; /* size n, use Flag as workspace for Map array */ for (i = 0 ; i < n ; i++) { Map [i] = EMPTY ; } /* ---------------------------------------------------------------------- */ /* find the mapping of nodes to relaxed supernodes */ /* ---------------------------------------------------------------------- */ /* SuperMap [k] = s if column k is contained in supernode s */ for (s = 0 ; s < nsuper ; s++) { PRINT1 (("Super ["ID"] "ID" ncols "ID"\n", s, Super[s], Super[s+1]-Super[s])); for (k = Super [s] ; k < Super [s+1] ; k++) { SuperMap [k] = s ; PRINT2 (("relaxed SuperMap ["ID"] = "ID"\n", k, SuperMap [k])) ; } } /* ---------------------------------------------------------------------- */ /* supernodal numerical factorization, using template routine */ /* ---------------------------------------------------------------------- */ switch (A->xtype) { case CHOLMOD_REAL: ok = r_cholmod_super_numeric (A, F, beta, L, C, Common) ; break ; /* case CHOLMOD_COMPLEX: */ /* ok = c_cholmod_super_numeric (A, F, beta, L, C, Common) ; */ /* break ; */ /* case CHOLMOD_ZOMPLEX: */ /* /\* This operates on complex L, not zomplex *\/ */ /* ok = z_cholmod_super_numeric (A, F, beta, L, C, Common) ; */ /* break ; */ } /* ---------------------------------------------------------------------- */ /* clear Common workspace, free temp workspace C, and return */ /* ---------------------------------------------------------------------- */ /* Flag array was used as workspace, clear it */ Common->mark = EMPTY ; /* CHOLMOD(clear_flag) (Common) ; */ CHOLMOD_CLEAR_FLAG (Common) ; ASSERT (CHOLMOD(dump_work) (TRUE, TRUE, 0, Common)) ; CHOLMOD(free_dense) (&C, Common) ; return (ok) ; } #endif igraph/src/CHOLMOD/Supernodal/t_cholmod_super_solve.c0000644000175100001440000002753513431000472022302 0ustar hornikusers/* ========================================================================== */ /* === Supernodal/t_cholmod_super_solve ===================================== */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * CHOLMOD/Supernodal Module. Copyright (C) 2005-2006, Timothy A. Davis * The CHOLMOD/Supernodal Module is licensed under Version 2.0 of the GNU * General Public License. See gpl.txt for a text of the license. * CHOLMOD is also available under other licenses; contact authors for details. * http://www.suitesparse.com * -------------------------------------------------------------------------- */ /* Template routine for cholmod_super_solve. Supports real or complex L. */ #include "cholmod_template.h" #ifdef USING_R #include #ifdef HAVE_F77_UNDERSCORE # define F77_CALL(x) x ## _ #else # define F77_CALL(x) x #endif #define F77_NAME(x) F77_CALL(x) #define F77_SUB(x) F77_CALL(x) #define F77_COM(x) F77_CALL(x) #define F77_COMDECL(x) F77_CALL(x) void F77_NAME(dsyrk)(const char *uplo, const char *trans, const int *n, const int *k, const double *alpha, const double *a, const int *lda, const double *beta, double *c, const int *ldc); void F77_NAME(dpotrf)(const char* uplo, const int* n, double* a, const int* lda, int* info); void F77_NAME(dtrsm)(const char *side, const char *uplo, const char *transa, const char *diag, const int *m, const int *n, const double *alpha, const double *a, const int *lda, double *b, const int *ldb); void F77_NAME(dtrsv)(const char *uplo, const char *trans, const char *diag, const int *n, const double *a, const int *lda, double *x, const int *incx); #endif static void TEMPLATE (cholmod_super_lsolve) ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the forward solve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to Lx=b on output */ /* ---- workspace ---- */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) { double *Lx, *Xx, *Ex ; double minus_one [2], one [2] ; Int *Lpi, *Lpx, *Ls, *Super ; Int nsuper, k1, k2, psi, psend, psx, nsrow, nscol, ii, s, nsrow2, n, ps2, j, i, d, nrhs ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrhs = X->ncol ; Ex = E->x ; Xx = X->x ; n = L->n ; d = X->d ; nsuper = L->nsuper ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Super = L->super ; Lx = L->x ; minus_one [0] = -1.0 ; minus_one [1] = 0 ; one [0] = 1.0 ; one [1] = 0 ; /* ---------------------------------------------------------------------- */ /* solve Lx=b */ /* ---------------------------------------------------------------------- */ if (nrhs == 1) { for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; psx = Lpx [s] ; nsrow = psend - psi ; nscol = k2 - k1 ; nsrow2 = nsrow - nscol ; ps2 = psi + nscol ; ASSERT ((size_t) nsrow2 <= L->maxesize) ; /* L1 is nscol-by-nscol, lower triangular with non-unit diagonal. * L2 is nsrow2-by-nscol. L1 and L2 have leading dimension of * nsrow. x1 is nscol-by-nsrow, with leading dimension n. * E is nsrow2-by-1, with leading dimension nsrow2. */ /* gather X into E */ for (ii = 0 ; ii < nsrow2 ; ii++) { /* Ex [ii] = Xx [Ls [ps2 + ii]] ; */ ASSIGN (Ex,-,ii, Xx,-,Ls [ps2 + ii]) ; } #ifdef REAL /* solve L1*x1 (that is, x1 = L1\x1) */ BLAS_dtrsv ("L", "N", "N", nscol, /* N: L1 is nscol-by-nscol */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, 1) ; /* X, INCX: x1 */ /* E = E - L2*x1 */ BLAS_dgemv ("N", nsrow2, nscol, /* M, N: L2 is nsrow2-by-nscol */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Xx + ENTRY_SIZE*k1, 1, /* X, INCX: x1 */ one, /* BETA: 1 */ Ex, 1) ; /* Y, INCY: E */ #else /* solve L1*x1 (that is, x1 = L1\x1) */ BLAS_ztrsv ("L", "N", "N", nscol, /* N: L1 is nscol-by-nscol */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, 1) ; /* X, INCX: x1 */ /* E = E - L2*x1 */ BLAS_zgemv ("N", nsrow2, nscol, /* M, N: L2 is nsrow2-by-nscol */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Xx + ENTRY_SIZE*k1, 1, /* X, INCX: x1 */ one, /* BETA: 1 */ Ex, 1) ; /* Y, INCY: E */ #endif /* scatter E back into X */ for (ii = 0 ; ii < nsrow2 ; ii++) { /* Xx [Ls [ps2 + ii]] = Ex [ii] ; */ ASSIGN (Xx,-,Ls [ps2 + ii], Ex,-,ii) ; } } } else { for (s = 0 ; s < nsuper ; s++) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; psx = Lpx [s] ; nsrow = psend - psi ; nscol = k2 - k1 ; nsrow2 = nsrow - nscol ; ps2 = psi + nscol ; ASSERT ((size_t) nsrow2 <= L->maxesize) ; /* E is nsrow2-by-nrhs, with leading dimension nsrow2. */ /* gather X into E */ for (ii = 0 ; ii < nsrow2 ; ii++) { i = Ls [ps2 + ii] ; for (j = 0 ; j < nrhs ; j++) { /* Ex [ii + j*nsrow2] = Xx [i + j*d] ; */ ASSIGN (Ex,-,ii+j*nsrow2, Xx,-,i+j*d) ; } } #ifdef REAL /* solve L1*x1 */ BLAS_dtrsm ("L", "L", "N", "N", nscol, nrhs, /* M, N: x1 is nscol-by-nrhs */ one, /* ALPHA: 1 */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, d) ; /* B, LDB: x1 */ /* E = E - L2*x1 */ if (nsrow2 > 0) { BLAS_dgemm ("N", "N", nsrow2, nrhs, nscol, /* M, N, K */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Xx + ENTRY_SIZE*k1, d, /* B, LDB: X1 */ one, /* BETA: 1 */ Ex, nsrow2) ; /* C, LDC: E */ } #else /* solve L1*x1 */ BLAS_ztrsm ("L", "L", "N", "N", nscol, nrhs, /* M, N: x1 is nscol-by-nrhs */ one, /* ALPHA: 1 */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, d) ; /* B, LDB: x1 */ /* E = E - L2*x1 */ if (nsrow2 > 0) { BLAS_zgemm ("N", "N", nsrow2, nrhs, nscol, /* M, N, K */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Xx + ENTRY_SIZE*k1, d, /* B, LDB: X1 */ one, /* BETA: 1 */ Ex, nsrow2) ; /* C, LDC: E */ } #endif /* scatter E back into X */ for (ii = 0 ; ii < nsrow2 ; ii++) { i = Ls [ps2 + ii] ; for (j = 0 ; j < nrhs ; j++) { /* Xx [i + j*d] = Ex [ii + j*nsrow2] ; */ ASSIGN (Xx,-,i+j*d, Ex,-,ii+j*nsrow2) ; } } } } } static void TEMPLATE (cholmod_super_ltsolve) ( /* ---- input ---- */ cholmod_factor *L, /* factor to use for the forward solve */ /* ---- output ---- */ cholmod_dense *X, /* b on input, solution to Lx=b on output */ /* ---- workspace ---- */ cholmod_dense *E, /* workspace of size nrhs*(L->maxesize) */ /* --------------- */ cholmod_common *Common ) { double *Lx, *Xx, *Ex ; double minus_one [2], one [2] ; Int *Lpi, *Lpx, *Ls, *Super ; Int nsuper, k1, k2, psi, psend, psx, nsrow, nscol, ii, s, nsrow2, n, ps2, j, i, d, nrhs ; /* ---------------------------------------------------------------------- */ /* get inputs */ /* ---------------------------------------------------------------------- */ nrhs = X->ncol ; Ex = E->x ; Xx = X->x ; n = L->n ; d = X->d ; nsuper = L->nsuper ; Lpi = L->pi ; Lpx = L->px ; Ls = L->s ; Super = L->super ; Lx = L->x ; minus_one [0] = -1.0 ; minus_one [1] = 0 ; one [0] = 1.0 ; one [1] = 0 ; /* ---------------------------------------------------------------------- */ /* solve L'x=b */ /* ---------------------------------------------------------------------- */ if (nrhs == 1) { for (s = nsuper-1 ; s >= 0 ; s--) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; psx = Lpx [s] ; nsrow = psend - psi ; nscol = k2 - k1 ; nsrow2 = nsrow - nscol ; ps2 = psi + nscol ; ASSERT ((size_t) nsrow2 <= L->maxesize) ; /* L1 is nscol-by-nscol, lower triangular with non-unit diagonal. * L2 is nsrow2-by-nscol. L1 and L2 have leading dimension of * nsrow. x1 is nscol-by-nsrow, with leading dimension n. * E is nsrow2-by-1, with leading dimension nsrow2. */ /* gather X into E */ for (ii = 0 ; ii < nsrow2 ; ii++) { /* Ex [ii] = Xx [Ls [ps2 + ii]] ; */ ASSIGN (Ex,-,ii, Xx,-,Ls [ps2 + ii]) ; } #ifdef REAL /* x1 = x1 - L2'*E */ BLAS_dgemv ("C", nsrow2, nscol, /* M, N: L2 is nsrow2-by-nscol */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Ex, 1, /* X, INCX: Ex */ one, /* BETA: 1 */ Xx + ENTRY_SIZE*k1, 1) ; /* Y, INCY: x1 */ /* solve L1'*x1 */ BLAS_dtrsv ("L", "C", "N", nscol, /* N: L1 is nscol-by-nscol */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, 1) ; /* X, INCX: x1 */ #else /* x1 = x1 - L2'*E */ BLAS_zgemv ("C", nsrow2, nscol, /* M, N: L2 is nsrow2-by-nscol */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Ex, 1, /* X, INCX: Ex */ one, /* BETA: 1 */ Xx + ENTRY_SIZE*k1, 1) ; /* Y, INCY: x1 */ /* solve L1'*x1 */ BLAS_ztrsv ("L", "C", "N", nscol, /* N: L1 is nscol-by-nscol */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, 1) ; /* X, INCX: x1 */ #endif } } else { for (s = nsuper-1 ; s >= 0 ; s--) { k1 = Super [s] ; k2 = Super [s+1] ; psi = Lpi [s] ; psend = Lpi [s+1] ; psx = Lpx [s] ; nsrow = psend - psi ; nscol = k2 - k1 ; nsrow2 = nsrow - nscol ; ps2 = psi + nscol ; ASSERT ((size_t) nsrow2 <= L->maxesize) ; /* E is nsrow2-by-nrhs, with leading dimension nsrow2. */ /* gather X into E */ for (ii = 0 ; ii < nsrow2 ; ii++) { i = Ls [ps2 + ii] ; for (j = 0 ; j < nrhs ; j++) { /* Ex [ii + j*nsrow2] = Xx [i + j*d] ; */ ASSIGN (Ex,-,ii+j*nsrow2, Xx,-,i+j*d) ; } } #ifdef REAL /* x1 = x1 - L2'*E */ if (nsrow2 > 0) { BLAS_dgemm ("C", "N", nscol, nrhs, nsrow2, /* M, N, K */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Ex, nsrow2, /* B, LDB: E */ one, /* BETA: 1 */ Xx + ENTRY_SIZE*k1, d) ; /* C, LDC: x1 */ } /* solve L1'*x1 */ BLAS_dtrsm ("L", "L", "C", "N", nscol, nrhs, /* M, N: x1 is nscol-by-nrhs */ one, /* ALPHA: 1 */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, d) ; /* B, LDB: x1 */ #else /* x1 = x1 - L2'*E */ if (nsrow2 > 0) { BLAS_zgemm ("C", "N", nscol, nrhs, nsrow2, /* M, N, K */ minus_one, /* ALPHA: -1 */ Lx + ENTRY_SIZE*(psx + nscol), /* A, LDA: L2 */ nsrow, Ex, nsrow2, /* B, LDB: E */ one, /* BETA: 1 */ Xx + ENTRY_SIZE*k1, d) ; /* C, LDC: x1 */ } /* solve L1'*x1 */ BLAS_ztrsm ("L", "L", "C", "N", nscol, nrhs, /* M, N: x1 is nscol-by-nrhs */ one, /* ALPHA: 1 */ Lx + ENTRY_SIZE*psx, nsrow, /* A, LDA: L1 */ Xx + ENTRY_SIZE*k1, d) ; /* B, LDB: x1 */ #endif } } } #undef PATTERN #undef REAL #undef COMPLEX #undef ZOMPLEX igraph/src/igraph_flow_internal.h0000644000175100001440000000240713431000472016674 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IGRAPH_FLOW_INTERNAL_H #define IGRAPH_FLOW_INTERNAL_H #include "igraph_types.h" #include "igraph_marked_queue.h" #include "igraph_estack.h" typedef int igraph_provan_shier_pivot_t(const igraph_t *graph, const igraph_marked_queue_t *S, const igraph_estack_t *T, long int source, long int target, long int *v, igraph_vector_t *Isv, void *arg); #endif igraph/src/components.c0000644000175100001440000006774613431000472014700 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_components.h" #include "igraph_memory.h" #include "igraph_interface.h" #include "igraph_adjlist.h" #include "igraph_interrupt_internal.h" #include "igraph_progress.h" #include "igraph_structural.h" #include "igraph_dqueue.h" #include "igraph_stack.h" #include "igraph_vector.h" #include "config.h" #include #include int igraph_clusters_weak(const igraph_t *graph, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t *no); int igraph_clusters_strong(const igraph_t *graph, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t *no); /** * \ingroup structural * \function igraph_clusters * \brief Calculates the (weakly or strongly) connected components in a graph. * * \param graph The graph object to analyze. * \param membership First half of the result will be stored here. For * every vertex the id of its component is given. The vector * has to be preinitialized and will be resized. Alternatively * this argument can be \c NULL, in which case it is ignored. * \param csize The second half of the result. For every component it * gives its size, the order is defined by the component ids. * The vector has to be preinitialized and will be resized. * Alternatively this argument can be \c NULL, in which * case it is ignored. * \param no Pointer to an integer, if not \c NULL then the number of * clusters will be stored here. * \param mode For directed graph this specifies whether to calculate * weakly or strongly connected components. Possible values: * \c IGRAPH_WEAK, * \c IGRAPH_STRONG. This argument is * ignored for undirected graphs. * \return Error code: * \c IGRAPH_EINVAL: invalid mode argument. * * Time complexity: O(|V|+|E|), * |V| and * |E| are the number of vertices and * edges in the graph. */ int igraph_clusters(const igraph_t *graph, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t *no, igraph_connectedness_t mode) { if (mode==IGRAPH_WEAK || !igraph_is_directed(graph)) { return igraph_clusters_weak(graph, membership, csize, no); } else if (mode==IGRAPH_STRONG) { return igraph_clusters_strong(graph, membership, csize, no); } else { IGRAPH_ERROR("Cannot calculate clusters", IGRAPH_EINVAL); } return 1; } int igraph_clusters_weak(const igraph_t *graph, igraph_vector_t *membership, igraph_vector_t *csize, igraph_integer_t *no) { long int no_of_nodes=igraph_vcount(graph); char *already_added; long int first_node, act_cluster_size=0, no_of_clusters=1; igraph_dqueue_t q=IGRAPH_DQUEUE_NULL; long int i; igraph_vector_t neis=IGRAPH_VECTOR_NULL; already_added=igraph_Calloc(no_of_nodes,char); if (already_added==0) { IGRAPH_ERROR("Cannot calculate clusters", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, already_added); IGRAPH_DQUEUE_INIT_FINALLY(&q, no_of_nodes > 100000 ? 10000 : no_of_nodes/10); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); /* Memory for result, csize is dynamically allocated */ if (membership) { IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes)); } if (csize) { igraph_vector_clear(csize); } /* The algorithm */ for (first_node=0; first_node < no_of_nodes; ++first_node) { if (already_added[first_node]==1) continue; IGRAPH_ALLOW_INTERRUPTION(); already_added[first_node]=1; act_cluster_size=1; if (membership) { VECTOR(*membership)[first_node]=no_of_clusters-1; } IGRAPH_CHECK(igraph_dqueue_push(&q, first_node)); while ( !igraph_dqueue_empty(&q) ) { long int act_node=(long int) igraph_dqueue_pop(&q); IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) act_node, IGRAPH_ALL)); for (i=0; i igraph_vector_int_size(tmp)) { continue; } IGRAPH_CHECK(igraph_dqueue_push(&q, i)); while (!igraph_dqueue_empty(&q)) { long int act_node=(long int) igraph_dqueue_back(&q); tmp = igraph_adjlist_get(&adjlist, act_node); if (VECTOR(next_nei)[act_node]==0) { /* this is the first time we've met this vertex */ VECTOR(next_nei)[act_node]++; } else if (VECTOR(next_nei)[act_node] <= igraph_vector_int_size(tmp)) { /* we've already met this vertex but it has more children */ long int neighbor=(long int) VECTOR(*tmp)[(long int) VECTOR(next_nei)[act_node]-1]; if (VECTOR(next_nei)[neighbor] == 0) { IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor)); } VECTOR(next_nei)[act_node]++; } else { /* we've met this vertex and it has no more children */ IGRAPH_CHECK(igraph_vector_push_back(&out, act_node)); igraph_dqueue_pop_back(&q); num_seen++; if (num_seen % 10000 == 0) { /* time to report progress and allow the user to interrupt */ IGRAPH_PROGRESS("Strongly connected components: ", num_seen * 50.0 / no_of_nodes, NULL); IGRAPH_ALLOW_INTERRUPTION(); } } } /* while q */ } /* for */ IGRAPH_PROGRESS("Strongly connected components: ", 50.0, NULL); igraph_adjlist_destroy(&adjlist); IGRAPH_FINALLY_CLEAN(1); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_IN)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); /* OK, we've the 'out' values for the nodes, let's use them in decreasing order with the help of a heap */ igraph_vector_null(&next_nei); /* mark already added vertices */ num_seen = 0; while (!igraph_vector_empty(&out)) { long int grandfather=(long int) igraph_vector_pop_back(&out); if (VECTOR(next_nei)[grandfather] != 0) { continue; } VECTOR(next_nei)[grandfather]=1; act_cluster_size=1; if (membership) { VECTOR(*membership)[grandfather]=no_of_clusters-1; } IGRAPH_CHECK(igraph_dqueue_push(&q, grandfather)); num_seen++; if (num_seen % 10000 == 0) { /* time to report progress and allow the user to interrupt */ IGRAPH_PROGRESS("Strongly connected components: ", 50.0 + num_seen * 50.0 / no_of_nodes, NULL); IGRAPH_ALLOW_INTERRUPTION(); } while (!igraph_dqueue_empty(&q)) { long int act_node=(long int) igraph_dqueue_pop_back(&q); tmp = igraph_adjlist_get(&adjlist, act_node); n = igraph_vector_int_size(tmp); for (i=0; i * * Time complexity: O(|V|+|E|), the number of vertices plus the number * of edges. * * \example examples/simple/igraph_decompose.c */ int igraph_decompose(const igraph_t *graph, igraph_vector_ptr_t *components, igraph_connectedness_t mode, long int maxcompno, long int minelements) { long int actstart; long int no_of_nodes=igraph_vcount(graph); long int resco=0; /* number of graphs created so far */ char *already_added; igraph_dqueue_t q; igraph_vector_t verts; igraph_vector_t neis; long int i; igraph_t *newg; if (!igraph_is_directed(graph)) { mode=IGRAPH_WEAK; } if (mode != IGRAPH_WEAK) { IGRAPH_ERROR("only 'IGRAPH_WEAK' is implemented", IGRAPH_EINVAL); } if (maxcompno<0) { maxcompno=LONG_MAX; } igraph_vector_ptr_clear(components); IGRAPH_FINALLY(igraph_decompose_destroy, components); already_added=igraph_Calloc(no_of_nodes, char); if (already_added==0) { IGRAPH_ERROR("Cannot decompose graph", IGRAPH_ENOMEM); } IGRAPH_FINALLY(igraph_free, already_added); IGRAPH_CHECK(igraph_dqueue_init(&q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &q); IGRAPH_VECTOR_INIT_FINALLY(&verts, 0); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); for(actstart=0; resco * A biconnected component of a graph is a maximal biconnected * subgraph of it. The biconnected components of a graph can be given * by the partition of its edges: every edge is a member of exactly * one biconnected component. Note that this is not true for * vertices: the same vertex can be part of many biconnected * components. * \param graph The input graph. * \param no The number of biconnected components will be stored here. * \param tree_edges If not a NULL pointer, then the found components * are stored here, in a list of vectors. Every vector in the list * is a biconnected component, represented by its edges. More precisely, * a spanning tree of the biconnected component is returned. * Note you'll have to * destroy each vector first by calling \ref igraph_vector_destroy() * and then free() on it, plus you need to call * \ref igraph_vector_ptr_destroy() on the list to regain all * allocated memory. * \param component_edges If not a NULL pointer, then the edges of the * biconnected components are stored here, in the same form as for * \c tree_edges. * \param components If not a NULL pointer, then the vertices of the * biconnected components are stored here, in the same format as * for the previous two arguments. * \param articulation_points If not a NULL pointer, then the * articulation points of the graph are stored in this vector. * A vertex is an articulation point if its removal increases the * number of (weakly) connected components in the graph. * \return Error code. * * Time complexity: O(|V|+|E|), linear in the number of vertices and * edges, but only if you do not calculate \c components and * \c component_edges. If you calculate \c components, then it is * quadratic in the number of vertices. If you calculate \c * component_edges as well, then it is cubic in the number of * vertices. * * \sa \ref igraph_articulation_points(), \ref igraph_clusters(). * * \example examples/simple/igraph_biconnected_components.c */ int igraph_biconnected_components(const igraph_t *graph, igraph_integer_t *no, igraph_vector_ptr_t *tree_edges, igraph_vector_ptr_t *component_edges, igraph_vector_ptr_t *components, igraph_vector_t *articulation_points) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_long_t nextptr; igraph_vector_long_t num, low; igraph_vector_bool_t found; igraph_vector_int_t *adjedges; igraph_stack_t path; igraph_vector_t edgestack; igraph_inclist_t inclist; long int i, counter, rootdfs=0; igraph_vector_long_t vertex_added; long int comps=0; igraph_vector_ptr_t *mycomponents=components, vcomponents; IGRAPH_CHECK(igraph_vector_long_init(&nextptr, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &nextptr); IGRAPH_CHECK(igraph_vector_long_init(&num, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &num); IGRAPH_CHECK(igraph_vector_long_init(&low, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &low); IGRAPH_CHECK(igraph_vector_bool_init(&found, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &found); IGRAPH_CHECK(igraph_stack_init(&path, 100)); IGRAPH_FINALLY(igraph_stack_destroy, &path); IGRAPH_VECTOR_INIT_FINALLY(&edgestack, 0); IGRAPH_CHECK(igraph_vector_reserve(&edgestack, 100)); IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_inclist_destroy, &inclist); IGRAPH_CHECK(igraph_vector_long_init(&vertex_added, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_long_destroy, &vertex_added); if (no) { *no=0; } if (tree_edges) { igraph_vector_ptr_clear(tree_edges); } if (components) { igraph_vector_ptr_clear(components); } if (component_edges) { igraph_vector_ptr_clear(component_edges); } if (articulation_points) { igraph_vector_clear(articulation_points); } if (component_edges && !components) { mycomponents=&vcomponents; IGRAPH_CHECK(igraph_vector_ptr_init(mycomponents, 0)); IGRAPH_FINALLY(igraph_i_free_vectorlist, mycomponents); } for (i=0; i= VECTOR(num)[prev]) { if (articulation_points && !VECTOR(found)[prev] && prev != i /* the root */) { IGRAPH_CHECK(igraph_vector_push_back(articulation_points, prev)); VECTOR(found)[prev] = 1; } if (no) { *no += 1; } /*------------------------------------*/ /* Record the biconnected component just found */ if (tree_edges || mycomponents) { igraph_vector_t *v = 0, *v2 = 0; comps++; if (tree_edges) { v=igraph_Calloc(1, igraph_vector_t); if (!v) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_init(v, 0)); IGRAPH_FINALLY(igraph_vector_destroy, v); } if (mycomponents) { v2=igraph_Calloc(1, igraph_vector_t); if (!v2) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_init(v2, 0)); IGRAPH_FINALLY(igraph_vector_destroy, v2); } while (!igraph_vector_empty(&edgestack)) { long int e=(long int) igraph_vector_pop_back(&edgestack); long int from=IGRAPH_FROM(graph,e); long int to=IGRAPH_TO(graph,e); if (tree_edges) { IGRAPH_CHECK(igraph_vector_push_back(v, e)); } if (mycomponents) { if (VECTOR(vertex_added)[from] != comps) { VECTOR(vertex_added)[from] = comps; IGRAPH_CHECK(igraph_vector_push_back(v2, from)); } if (VECTOR(vertex_added)[to] != comps) { VECTOR(vertex_added)[to] = comps; IGRAPH_CHECK(igraph_vector_push_back(v2, to)); } } if (from==prev || to==prev) { break; } } if (mycomponents) { IGRAPH_CHECK(igraph_vector_ptr_push_back(mycomponents, v2)); IGRAPH_FINALLY_CLEAN(1); } if (tree_edges) { IGRAPH_CHECK(igraph_vector_ptr_push_back(tree_edges, v)); IGRAPH_FINALLY_CLEAN(1); } if (component_edges) { igraph_vector_t *nodes=VECTOR(*mycomponents)[comps-1]; igraph_vector_t *vv=igraph_Calloc(1, igraph_vector_t); long int ii, no_vert=igraph_vector_size(nodes); if (!vv) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); } IGRAPH_CHECK(igraph_vector_init(vv, 0)); IGRAPH_FINALLY(igraph_vector_destroy, vv); for (ii=0; ii= 2) { IGRAPH_CHECK(igraph_vector_push_back(articulation_points, i)); } } /* i < no_of_nodes */ if (mycomponents != components) { igraph_i_free_vectorlist(mycomponents); IGRAPH_FINALLY_CLEAN(1); } igraph_vector_long_destroy(&vertex_added); igraph_inclist_destroy(&inclist); igraph_vector_destroy(&edgestack); igraph_stack_destroy(&path); igraph_vector_bool_destroy(&found); igraph_vector_long_destroy(&low); igraph_vector_long_destroy(&num); igraph_vector_long_destroy(&nextptr); IGRAPH_FINALLY_CLEAN(8); return 0; } igraph/src/separators.c0000644000175100001440000006366113431000472014666 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2010-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_separators.h" #include "igraph_memory.h" #include "igraph_adjlist.h" #include "igraph_dqueue.h" #include "igraph_vector.h" #include "igraph_interface.h" #include "igraph_flow.h" #include "igraph_flow_internal.h" #include "igraph_components.h" #include "igraph_structural.h" #include "igraph_constructors.h" #include "igraph_stack.h" #include "igraph_interrupt_internal.h" int igraph_i_is_separator(const igraph_t *graph, igraph_vit_t *vit, long int except, igraph_bool_t *res, igraph_vector_bool_t *removed, igraph_dqueue_t *Q, igraph_vector_t *neis, long int no_of_nodes) { long int start=0; if (IGRAPH_VIT_SIZE(*vit) >= no_of_nodes-1) { /* Just need to check that we really have at least n-1 vertices in it */ igraph_vector_bool_t hit; long int nohit=0; IGRAPH_CHECK(igraph_vector_bool_init(&hit, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &hit); for (IGRAPH_VIT_RESET(*vit); !IGRAPH_VIT_END(*vit); IGRAPH_VIT_NEXT(*vit)) { long int v=IGRAPH_VIT_GET(*vit); if (!VECTOR(hit)[v]) { nohit++; VECTOR(hit)[v] = 1; } } igraph_vector_bool_destroy(&hit); IGRAPH_FINALLY_CLEAN(1); if (nohit >= no_of_nodes-1) { *res = 0; return 0; } } /* Remove the given vertices from the graph, do a breadth-first search and check the number of components */ if (except < 0) { for (IGRAPH_VIT_RESET(*vit); !IGRAPH_VIT_END(*vit); IGRAPH_VIT_NEXT(*vit)) { VECTOR(*removed)[ (long int) IGRAPH_VIT_GET(*vit) ] = 1; } } else { /* There is an exception */ long int i; for (i=0, IGRAPH_VIT_RESET(*vit); iThis implementation first checks that the given * candidate is a separator, by calling \ref * igraph_is_separator(). If it is a separator, then it checks that * each subset of size n-1, where n is the size of the candidate, is * not a separator. * \param graph The input graph. It may be directed, but edge * directions are ignored. * \param candidate Pointer to a vector of long integers, the * candidate minimal separator. * \param res Pointer to a boolean variable, the result is stored * here. * \return Error code. * * Time complexity: O(n(|V|+|E|)), |V| is the number of vertices, |E| * is the number of edges, n is the number vertices in the candidate * separator. * * \example examples/simple/igraph_is_minimal_separator.c */ int igraph_is_minimal_separator(const igraph_t *graph, const igraph_vs_t candidate, igraph_bool_t *res) { long int no_of_nodes=igraph_vcount(graph); igraph_vector_bool_t removed; igraph_dqueue_t Q; igraph_vector_t neis; long int candsize; igraph_vit_t vit; IGRAPH_CHECK(igraph_vit_create(graph, candidate, &vit)); IGRAPH_FINALLY(igraph_vit_destroy, &vit); candsize=IGRAPH_VIT_SIZE(vit); IGRAPH_CHECK(igraph_vector_bool_init(&removed, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &removed); IGRAPH_CHECK(igraph_dqueue_init(&Q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &Q); IGRAPH_VECTOR_INIT_FINALLY(&neis, 0); /* Is it a separator at all? */ IGRAPH_CHECK(igraph_i_is_separator(graph, &vit, -1, res, &removed, &Q, &neis, no_of_nodes)); if (!(*res)) { /* Not a separator at all, nothing to do, *res is already set */ } else if (candsize == 0) { /* Nothing to do, minimal, *res is already set */ } else { /* General case, we need to remove each vertex from 'candidate' * and check whether the remainder is a separator. If this is * false for all vertices, then 'candidate' is a minimal * separator. */ long int i; for (i=0, *res=0; iSee more about the implemented algorithm in * Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating All the * Minimal Separators of a Graph, In: Peter Widmayer, Gabriele Neyer * and Stephan Eidenbenz (editors): Graph-theoretic concepts in * computer science, 1665, 167--172, 1999. Springer. * * \param graph The input graph. It may be directed, but edge * directions are ignored. * \param separators An initialized pointer vector, the separators * are stored here. It is a list of pointers to igraph_vector_t * objects. Each vector will contain the ids of the vertices in * the separator. * To free all memory allocated for \c separators, you need call * \ref igraph_vector_destroy() and then \ref igraph_free() on * each element, before destroying the pointer vector itself. * \return Error code. * * Time complexity: O(n|V|^3), |V| is the number of vertices, n is the * number of separators. * * \example examples/simple/igraph_minimal_separators.c */ int igraph_all_minimal_st_separators(const igraph_t *graph, igraph_vector_ptr_t *separators) { /* * Some notes about the tricks used here. For finding the components * of the graph after removing some vertices, we do the * following. First we mark the vertices with the actual mark stamp * (mark), then run breadth-first search on the graph, but not * considering the marked vertices. Then we increase the mark. If * there is integer overflow here, then we zero out the mark and set * it to one. (We might as well just always zero it out.) * * For each separator the vertices are stored in vertex id order. * This facilitates the comparison of the separators when we find a * potential new candidate. * * To keep track of which separator we already used as a basis, we * keep a boolean vector (already_tried). The try_next pointer show * the next separator to try as a basis. */ long int no_of_nodes=igraph_vcount(graph); igraph_vector_t leaveout; igraph_vector_bool_t already_tried; long int try_next=0; unsigned long int mark=1; long int v; igraph_adjlist_t adjlist; igraph_vector_t components; igraph_dqueue_t Q; igraph_vector_t sorter; igraph_vector_ptr_clear(separators); IGRAPH_FINALLY(igraph_i_separators_free, separators); IGRAPH_CHECK(igraph_vector_init(&leaveout, no_of_nodes)); IGRAPH_FINALLY(igraph_vector_destroy, &leaveout); IGRAPH_CHECK(igraph_vector_bool_init(&already_tried, 0)); IGRAPH_FINALLY(igraph_vector_bool_destroy, &already_tried); IGRAPH_CHECK(igraph_vector_init(&components, 0)); IGRAPH_FINALLY(igraph_vector_destroy, &components); IGRAPH_CHECK(igraph_vector_reserve(&components, no_of_nodes*2)); IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_ALL)); IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist); IGRAPH_CHECK(igraph_dqueue_init(&Q, 100)); IGRAPH_FINALLY(igraph_dqueue_destroy, &Q); IGRAPH_CHECK(igraph_vector_init(&sorter, 0)); IGRAPH_FINALLY(igraph_vector_destroy, &sorter); IGRAPH_CHECK(igraph_vector_reserve(&sorter, no_of_nodes)); /* --------------------------------------------------------------- * INITIALIZATION, we check whether the neighborhoods of the * vertices separate the graph. The ones that do will form the * initial basis. */ for (v=0; vThe implementation is based on the following paper: * Arkady Kanevsky: Finding all minimum-size separating vertex sets in * a graph, Networks 23, 533--541, 1993. * * \param graph The input graph, it may be directed, but edge * directions will be ignored. * \param separators An initialized pointer vector, the separators * are stored here. It is a list of pointers to igraph_vector_t * objects. Each vector will contain the ids of the vertices in * the separator. * To free all memory allocated for \c separators, you need call * \ref igraph_vector_destroy() and then \ref igraph_free() on * each element, before destroying the pointer vector itself. * \return Error code. * * Time complexity: TODO. * * \example examples/simple/igraph_minimum_size_separators.c */ int igraph_minimum_size_separators(const igraph_t *graph, igraph_vector_ptr_t *separators) { long int no_of_nodes=igraph_vcount(graph); long int no_of_edges=igraph_ecount(graph); igraph_integer_t conn; long int k; igraph_vector_t X; long int i, j; igraph_bool_t issepX; igraph_t Gbar; igraph_vector_t phi; igraph_t graph_copy; igraph_vector_t capacity; igraph_maxflow_stats_t stats; igraph_vector_ptr_clear(separators); IGRAPH_FINALLY(igraph_i_separators_free, separators); /* ---------------------------------------------------------------- */ /* 1 Find the vertex connectivity of 'graph' */ IGRAPH_CHECK(igraph_vertex_connectivity(graph, &conn, /* checks= */ 1)); k=conn; /* Special cases for low connectivity, two exits here! */ if (conn==0) { /* Nothing to do */ IGRAPH_FINALLY_CLEAN(1); /* separators */ return 0; } else if (conn==1) { igraph_vector_t ap; long int i, n; IGRAPH_VECTOR_INIT_FINALLY(&ap, 0); IGRAPH_CHECK(igraph_articulation_points(graph, &ap)); n=igraph_vector_size(&ap); IGRAPH_CHECK(igraph_vector_ptr_resize(separators, n)); igraph_vector_ptr_null(separators); for (i=0; i 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_vector.h" #include "igraph_types_internal.h" typedef struct { void *scanner; int eof; char errmsg[300]; int has_weights; igraph_vector_t *vector; igraph_vector_t *weights; igraph_trie_t *trie; int actvertex; } igraph_i_lgl_parsedata_t; igraph/src/SuiteSparse_config/0000755000175100001440000000000013561251636016135 5ustar hornikusersigraph/src/SuiteSparse_config/SuiteSparse_config_Mac.mk0000644000175100001440000003511513430770175023046 0ustar hornikusers#=============================================================================== # SuiteSparse_config_Mac.mk: Mac configuration file for the SuiteSparse # To use this configuration, delete the SuiteSparse_config.mk file that # comes with SuiteSparse and rename this file as SuiteSparse_config.mk . #=============================================================================== # This file contains all configuration settings for all packages authored or # co-authored by Tim Davis: # # Package Version Description # ------- ------- ----------- # AMD 1.2 or later approximate minimum degree ordering # COLAMD 2.4 or later column approximate minimum degree ordering # CCOLAMD 1.0 or later constrained column approximate minimum degree ordering # CAMD any constrained approximate minimum degree ordering # UMFPACK 4.5 or later sparse LU factorization, with the BLAS # CHOLMOD any sparse Cholesky factorization, update/downdate # KLU 0.8 or later sparse LU factorization, BLAS-free # BTF 0.8 or later permutation to block triangular form # LDL 1.2 or later concise sparse LDL' # CXSparse any extended version of CSparse (int/long, real/complex) # SuiteSparseQR any sparse QR factorization # RBio 2.0 or later read/write sparse matrices in Rutherford-Boeing format # # By design, this file is NOT included in the CSparse makefile. # That package is fully stand-alone. CSparse is primarily for teaching; # production code should use CXSparse. # # The SuiteSparse_config directory and the above packages should all appear in # a single directory, in order for the Makefile's within each package to find # this file. # # To enable an option of the form "# OPTION = ...", edit this file and # delete the "#" in the first column of the option you wish to use. # # The use of METIS 4.0.1 is optional. To exclude METIS, you must compile with # CHOLMOD_CONFIG set to -DNPARTITION. See below for details. However, if you # do not have a metis-4.0 directory inside the SuiteSparse directory, the # */Makefile's that optionally rely on METIS will automatically detect this # and compile without METIS. #------------------------------------------------------------------------------ # Generic configuration #------------------------------------------------------------------------------ # Using standard definitions from the make environment, typically: # # CC cc C compiler # CXX g++ C++ compiler # CFLAGS [ ] flags for C and C++ compiler # CPPFLAGS [ ] flags for C and C++ compiler # TARGET_ARCH [ ] target architecture # FFLAGS [ ] flags for Fortran compiler # RM rm -f delete a file # AR ar create a static *.a library archive # ARFLAGS rv flags for ar # MAKE make make itself (sometimes called gmake) # # You can redefine them here, but by default they are used from the # default make environment. # C and C++ compiler flags. The first three are standard for *.c and *.cpp # Add -DNTIMER if you do use any timing routines (otherwise -lrt is required). # CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC -DNTIMER CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC # ranlib, and ar, for generating libraries. If you don't need ranlib, # just change it to RANLAB = echo RANLIB = ranlib ARCHIVE = $(AR) $(ARFLAGS) # copy and delete a file CP = cp -f MV = mv -f # Fortran compiler (not required for 'make' or 'make library') F77 = gfortran F77FLAGS = $(FFLAGS) -O F77LIB = # C and Fortran libraries. Remove -lrt if you don't have it. LIB = -lm -lrt # Using the following requires CF = ... -DNTIMER on POSIX C systems. # LIB = -lm # For "make install" INSTALL_LIB = /usr/local/lib INSTALL_INCLUDE = /usr/local/include # Which version of MAKE you are using (default is "make") # MAKE = make # MAKE = gmake #------------------------------------------------------------------------------ # BLAS and LAPACK configuration: #------------------------------------------------------------------------------ # UMFPACK and CHOLMOD both require the BLAS. CHOLMOD also requires LAPACK. # See Kazushige Goto's BLAS at http://www.cs.utexas.edu/users/flame/goto/ or # http://www.tacc.utexas.edu/~kgoto/ for the best BLAS to use with CHOLMOD. # LAPACK is at http://www.netlib.org/lapack/ . You can use the standard # Fortran LAPACK along with Goto's BLAS to obtain very good performance. # CHOLMOD gets a peak numeric factorization rate of 3.6 Gflops on a 3.2 GHz # Pentium 4 (512K cache, 4GB main memory) with the Goto BLAS, and 6 Gflops # on a 2.5Ghz dual-core AMD Opteron. # These settings will probably not work, since there is no fixed convention for # naming the BLAS and LAPACK library (*.a or *.so) files. # This is probably slow ... it might connect to the Standard Reference BLAS: BLAS = -lblas -lgfortran LAPACK = -llapack # NOTE: this next option for the "Goto BLAS" has nothing to do with a "goto" # statement. Rather, the Goto BLAS is written by Dr. Kazushige Goto. # Using the Goto BLAS: # BLAS = -lgoto -lgfortran -lgfortranbegin # BLAS = -lgoto2 -lgfortran -lgfortranbegin -lpthread # Using non-optimized versions: # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack_plain # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack # The BLAS might not contain xerbla, an error-handling routine for LAPACK and # the BLAS. Also, the standard xerbla requires the Fortran I/O library, and # stops the application program if an error occurs. A C version of xerbla # distributed with this software (SuiteSparse_config/xerbla/libcerbla.a) # includes a Fortran-callable xerbla routine that prints nothing and does not # stop the application program. This is optional. # XERBLA = ../../SuiteSparse_config/xerbla/libcerbla.a # If you wish to use the XERBLA in LAPACK and/or the BLAS instead, # use this option: XERBLA = # If you wish to use the Fortran SuiteSparse_config/xerbla/xerbla.f instead, # use this: # XERBLA = ../../SuiteSparse_config/xerbla/libxerbla.a #------------------------------------------------------------------------------ # GPU configuration for CHOLMOD, using the CUDA BLAS #------------------------------------------------------------------------------ # no cuda GPU_BLAS_PATH = GPU_CONFIG = # with cuda BLAS acceleration for CHOLMOD # GPU_BLAS_PATH=/usr/local/cuda # GPU_CONFIG=-DGPU_BLAS -I$(GPU_BLAS_PATH)/include #------------------------------------------------------------------------------ # METIS, optionally used by CHOLMOD #------------------------------------------------------------------------------ # If you do not have METIS, or do not wish to use it in CHOLMOD, you must # compile CHOLMOD with the -DNPARTITION flag. # The path is relative to where it is used, in CHOLMOD/Lib, CHOLMOD/MATLAB, etc. # You may wish to use an absolute path. METIS is optional. Compile # CHOLMOD with -DNPARTITION if you do not wish to use METIS. METIS_PATH = ../../metis-4.0 METIS = ../../metis-4.0/libmetis.a #------------------------------------------------------------------------------ # UMFPACK configuration: #------------------------------------------------------------------------------ # Configuration flags for UMFPACK. See UMFPACK/Source/umf_config.h for details. # # -DNBLAS do not use the BLAS. UMFPACK will be very slow. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF do not use the Sun Perf. Library (default is use it on Solaris) # -DNRECIPROCAL do not multiply by the reciprocal # -DNO_DIVIDE_BY_ZERO do not divide by zero # -DNCHOLMOD do not use CHOLMOD as a ordering method. If -DNCHOLMOD is # included in UMFPACK_CONFIG, then UMFPACK does not rely on # CHOLMOD, CAMD, CCOLAMD, COLAMD, and METIS. UMFPACK_CONFIG = # uncomment this line to compile UMFPACK without CHOLMOD: # UMFPACK_CONFIG = -DNCHOLMOD #------------------------------------------------------------------------------ # CHOLMOD configuration #------------------------------------------------------------------------------ # CHOLMOD Library Modules, which appear in libcholmod.a: # Core requires: none # Check requires: Core # Cholesky requires: Core, AMD, COLAMD. optional: Partition, Supernodal # MatrixOps requires: Core # Modify requires: Core # Partition requires: Core, CCOLAMD, METIS. optional: Cholesky # Supernodal requires: Core, BLAS, LAPACK # # CHOLMOD test/demo Modules (all are GNU GPL, do not appear in libcholmod.a): # Tcov requires: Core, Check, Cholesky, MatrixOps, Modify, Supernodal # optional: Partition # Valgrind same as Tcov # Demo requires: Core, Check, Cholesky, MatrixOps, Supernodal # optional: Partition # # Configuration flags: # -DNCHECK do not include the Check module. License GNU LGPL # -DNCHOLESKY do not include the Cholesky module. License GNU LGPL # -DNPARTITION do not include the Partition module. License GNU LGPL # also do not include METIS. # -DNCAMD do not use CAMD, etc from Partition module. GNU LGPL # -DNGPL do not include any GNU GPL Modules in the CHOLMOD library: # -DNMATRIXOPS do not include the MatrixOps module. License GNU GPL # -DNMODIFY do not include the Modify module. License GNU GPL # -DNSUPERNODAL do not include the Supernodal module. License GNU GPL # # -DNPRINT do not print anything. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF for Solaris only. If defined, do not use the Sun # Performance Library CHOLMOD_CONFIG = $(GPU_CONFIG) # uncomment this line to compile CHOLMOD without METIS: # CHOLMOD_CONFIG = -DNPARTITION #------------------------------------------------------------------------------ # SuiteSparseQR configuration: #------------------------------------------------------------------------------ # The SuiteSparseQR library can be compiled with the following options: # # -DNPARTITION do not include the CHOLMOD partition module # -DNEXPERT do not include the functions in SuiteSparseQR_expert.cpp # -DHAVE_TBB enable the use of Intel's Threading Building Blocks (TBB) # default, without timing, without TBB: SPQR_CONFIG = # with TBB: # SPQR_CONFIG = -DHAVE_TBB # This is needed for IBM AIX: (but not for and C codes, just C++) # SPQR_CONFIG = -DBLAS_NO_UNDERSCORE # with TBB, you must select this: # TBB = -ltbb # without TBB: TBB = #------------------------------------------------------------------------------ # Linux #------------------------------------------------------------------------------ # Using default compilers: # CC = gcc # CF = $(CFLAGS) -O3 -fexceptions # alternatives: # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi \ -funit-at-a-time # CF = $(CFLAGS) -O3 -fexceptions \ -Wall -W -Werror -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi # CF = $(CFLAGS) -O3 -fexceptions -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # CF = $(CFLAGS) -O3 # CF = $(CFLAGS) -O3 -g -fexceptions # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow \ -Wredundant-decls -Wdisabled-optimization -ansi # consider: # -fforce-addr -fmove-all-movables -freduce-all-givs -ftsp-ordering # -frename-registers -ffast-math -funroll-loops # Using the Goto BLAS: # BLAS = -lgoto -lfrtbegin -lg2c $(XERBLA) -lpthread # Using Intel's icc and ifort compilers: # (does not work for mexFunctions unless you add a mexopts.sh file) # F77 = ifort # CC = icc # CF = $(CFLAGS) -O3 -xN -vec_report=0 # CF = $(CFLAGS) -g # 64bit: # F77FLAGS = -O -m64 # CF = $(CFLAGS) -O3 -fexceptions -m64 # BLAS = -lgoto64 -lfrtbegin -lg2c -lpthread $(XERBLA) # LAPACK = -llapack64 # SUSE Linux 10.1, AMD Opteron, with GOTO Blas # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # SUSE Linux 10.1, Intel Pentium, with GOTO Blas # F77 = gfortran # BLAS = -lgoto -lgfortran #------------------------------------------------------------------------------ # Mac #------------------------------------------------------------------------------ # As recommended by macports, http://suitesparse.darwinports.com/ # I've tested them myself on Mac OSX 10.6.1 and 10.6.8 (Snow Leopard), # on my MacBook Air, and they work fine. F77 = gfortran CF = $(CFLAGS) -O3 -fno-common -fexceptions -DNTIMER BLAS = -framework Accelerate LAPACK = -framework Accelerate LIB = -lm #------------------------------------------------------------------------------ # Solaris #------------------------------------------------------------------------------ # 32-bit # CF = $(CFLAGS) -KPIC -dalign -xc99=%none -Xc -xlibmieee -xO5 -xlibmil -m32 # 64-bit # CF = $(CFLAGS) -fast -KPIC -xc99=%none -xlibmieee -xlibmil -m64 -Xc # FFLAGS = -fast -KPIC -dalign -xlibmil -m64 # The Sun Performance Library includes both LAPACK and the BLAS: # BLAS = -xlic_lib=sunperf # LAPACK = #------------------------------------------------------------------------------ # Compaq Alpha #------------------------------------------------------------------------------ # 64-bit mode only # CF = $(CFLAGS) -O2 -std1 # BLAS = -ldxml # LAPACK = #------------------------------------------------------------------------------ # IBM RS 6000 #------------------------------------------------------------------------------ # BLAS = -lessl # LAPACK = # 32-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 # 64-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -q64 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 -q64 #------------------------------------------------------------------------------ # SGI IRIX #------------------------------------------------------------------------------ # BLAS = -lscsl # LAPACK = # 32-bit mode # CF = $(CFLAGS) -O # 64-bit mode (32 bit int's and 64-bit long's): # CF = $(CFLAGS) -64 # F77FLAGS = -64 # SGI doesn't have ranlib # RANLIB = echo #------------------------------------------------------------------------------ # AMD Opteron (64 bit) #------------------------------------------------------------------------------ # BLAS = -lgoto_opteron64 -lg2c # LAPACK = -llapack_opteron64 # SUSE Linux 10.1, AMD Opteron # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # LAPACK = -llapack_opteron64 #------------------------------------------------------------------------------ # remove object files and profile output #------------------------------------------------------------------------------ CLEAN = *.o *.obj *.ln *.bb *.bbg *.da *.tcov *.gcov gmon.out *.bak *.d *.gcda *.gcno igraph/src/SuiteSparse_config/README.txt0000644000175100001440000000451313430770175017635 0ustar hornikusersSuiteSparse_config, 2013, Timothy A. Davis, http://www.suitesparse.com (formerly the UFconfig package) SuiteSparse_config contains configuration settings for all many of the software packages that I develop or co-author. Note that older versions of some of these packages do not require SuiteSparse_config. Package Description ------- ----------- AMD approximate minimum degree ordering CAMD constrained AMD COLAMD column approximate minimum degree ordering CCOLAMD constrained approximate minimum degree ordering UMFPACK sparse LU factorization, with the BLAS CXSparse int/long/real/complex version of CSparse CHOLMOD sparse Cholesky factorization, update/downdate KLU sparse LU factorization, BLAS-free BTF permutation to block triangular form LDL concise sparse LDL' LPDASA LP Dual Active Set Algorithm RBio read/write files in Rutherford/Boeing format SPQR sparse QR factorization (full name: SuiteSparseQR) SuiteSparse_config is not required by these packages: CSparse a Concise Sparse matrix package MATLAB_Tools toolboxes for use in MATLAB In addition, the xerbla/ directory contains Fortan and C versions of the BLAS/LAPACK xerbla routine, which is called when an invalid input is passed to the BLAS or LAPACK. The xerbla provided here does not print any message, so the entire Fortran I/O library does not need to be linked into a C application. Most versions of the BLAS contain xerbla, but those from K. Goto do not. Use this if you need too. If you edit this directory (SuiteSparse_config.mk in particular) then you must do "make purge ; make" in the parent directory to recompile all of SuiteSparse. Otherwise, the changes will not necessarily be applied. -------------------------------------------------------------------------------- A note on the update to SuiteSparse Version 4.0.0: The SuiteSparse_long macro defines an integer that is 64-bits in size on 64-bit platforms, and 32-bits on 32-bit platforms. It was formerly called UF_long, but UF_long has been removed because of potential name conflicts. UF_long is still available to user codes, but it can now be safely #undef'd in case of name conflicts in user code. Future codes should use SuiteSparse_long in place of UF_long. -------------------------------------------------------------------------------- igraph/src/SuiteSparse_config/SuiteSparse_config_GPU.mk0000644000175100001440000003467713430770175023015 0ustar hornikusers#=============================================================================== # SuiteSparse_config.mk: common configuration file for the SuiteSparse #=============================================================================== # This file contains all configuration settings for all packages authored or # co-authored by Tim Davis: # # Package Version Description # ------- ------- ----------- # AMD 1.2 or later approximate minimum degree ordering # COLAMD 2.4 or later column approximate minimum degree ordering # CCOLAMD 1.0 or later constrained column approximate minimum degree ordering # CAMD any constrained approximate minimum degree ordering # UMFPACK 4.5 or later sparse LU factorization, with the BLAS # CHOLMOD any sparse Cholesky factorization, update/downdate # KLU 0.8 or later sparse LU factorization, BLAS-free # BTF 0.8 or later permutation to block triangular form # LDL 1.2 or later concise sparse LDL' # CXSparse any extended version of CSparse (int/long, real/complex) # SuiteSparseQR any sparse QR factorization # RBio 2.0 or later read/write sparse matrices in Rutherford-Boeing format # # By design, this file is NOT included in the CSparse makefile. # That package is fully stand-alone. CSparse is primarily for teaching; # production code should use CXSparse. # # The SuiteSparse_config directory and the above packages should all appear in # a single directory, in order for the Makefile's within each package to find # this file. # # To enable an option of the form "# OPTION = ...", edit this file and # delete the "#" in the first column of the option you wish to use. # # The use of METIS 4.0.1 is optional. To exclude METIS, you must compile with # CHOLMOD_CONFIG set to -DNPARTITION. See below for details. However, if you # do not have a metis-4.0 directory inside the SuiteSparse directory, the # */Makefile's that optionally rely on METIS will automatically detect this # and compile without METIS. #------------------------------------------------------------------------------ # Generic configuration #------------------------------------------------------------------------------ # Using standard definitions from the make environment, typically: # # CC cc C compiler # CXX g++ C++ compiler # CFLAGS [ ] flags for C and C++ compiler # CPPFLAGS [ ] flags for C and C++ compiler # TARGET_ARCH [ ] target architecture # FFLAGS [ ] flags for Fortran compiler # RM rm -f delete a file # AR ar create a static *.a library archive # ARFLAGS rv flags for ar # MAKE make make itself (sometimes called gmake) # # You can redefine them here, but by default they are used from the # default make environment. # C and C++ compiler flags. The first three are standard for *.c and *.cpp # Add -DNTIMER if you do use any timing routines (otherwise -lrt is required). # CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC -DNTIMER CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC # ranlib, and ar, for generating libraries. If you don't need ranlib, # just change it to RANLAB = echo RANLIB = ranlib ARCHIVE = $(AR) $(ARFLAGS) # copy and delete a file CP = cp -f MV = mv -f # Fortran compiler (not required for 'make' or 'make library') F77 = gfortran F77FLAGS = $(FFLAGS) -O F77LIB = # C and Fortran libraries. Remove -lrt if you don't have it. LIB = -lm -lrt # Using the following requires CF = ... -DNTIMER on POSIX C systems. # LIB = -lm # For "make install" INSTALL_LIB = /usr/local/lib INSTALL_INCLUDE = /usr/local/include # Which version of MAKE you are using (default is "make") # MAKE = make # MAKE = gmake #------------------------------------------------------------------------------ # BLAS and LAPACK configuration: #------------------------------------------------------------------------------ # UMFPACK and CHOLMOD both require the BLAS. CHOLMOD also requires LAPACK. # See Kazushige Goto's BLAS at http://www.cs.utexas.edu/users/flame/goto/ or # http://www.tacc.utexas.edu/~kgoto/ for the best BLAS to use with CHOLMOD. # LAPACK is at http://www.netlib.org/lapack/ . You can use the standard # Fortran LAPACK along with Goto's BLAS to obtain very good performance. # CHOLMOD gets a peak numeric factorization rate of 3.6 Gflops on a 3.2 GHz # Pentium 4 (512K cache, 4GB main memory) with the Goto BLAS, and 6 Gflops # on a 2.5Ghz dual-core AMD Opteron. # These settings will probably not work, since there is no fixed convention for # naming the BLAS and LAPACK library (*.a or *.so) files. # This is probably slow ... it might connect to the Standard Reference BLAS: BLAS = -lblas -lgfortran LAPACK = -llapack # NOTE: this next option for the "Goto BLAS" has nothing to do with a "goto" # statement. Rather, the Goto BLAS is written by Dr. Kazushige Goto. # Using the Goto BLAS: # BLAS = -lgoto -lgfortran -lgfortranbegin # BLAS = -lgoto2 -lgfortran -lgfortranbegin -lpthread # Using non-optimized versions: # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack_plain # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack # The BLAS might not contain xerbla, an error-handling routine for LAPACK and # the BLAS. Also, the standard xerbla requires the Fortran I/O library, and # stops the application program if an error occurs. A C version of xerbla # distributed with this software (SuiteSparse_config/xerbla/libcerbla.a) # includes a Fortran-callable xerbla routine that prints nothing and does not # stop the application program. This is optional. # XERBLA = ../../SuiteSparse_config/xerbla/libcerbla.a # If you wish to use the XERBLA in LAPACK and/or the BLAS instead, # use this option: XERBLA = # If you wish to use the Fortran SuiteSparse_config/xerbla/xerbla.f instead, # use this: # XERBLA = ../../SuiteSparse_config/xerbla/libxerbla.a #------------------------------------------------------------------------------ # GPU configuration for CHOLMOD, using the CUDA BLAS #------------------------------------------------------------------------------ # no cuda # GPU_BLAS_PATH = # GPU_CONFIG = # with cuda BLAS acceleration for CHOLMOD GPU_BLAS_PATH=/usr/local/cuda GPU_CONFIG=-DGPU_BLAS -I$(GPU_BLAS_PATH)/include #------------------------------------------------------------------------------ # METIS, optionally used by CHOLMOD #------------------------------------------------------------------------------ # If you do not have METIS, or do not wish to use it in CHOLMOD, you must # compile CHOLMOD with the -DNPARTITION flag. # The path is relative to where it is used, in CHOLMOD/Lib, CHOLMOD/MATLAB, etc. # You may wish to use an absolute path. METIS is optional. Compile # CHOLMOD with -DNPARTITION if you do not wish to use METIS. METIS_PATH = ../../metis-4.0 METIS = ../../metis-4.0/libmetis.a #------------------------------------------------------------------------------ # UMFPACK configuration: #------------------------------------------------------------------------------ # Configuration flags for UMFPACK. See UMFPACK/Source/umf_config.h for details. # # -DNBLAS do not use the BLAS. UMFPACK will be very slow. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF do not use the Sun Perf. Library (default is use it on Solaris) # -DNRECIPROCAL do not multiply by the reciprocal # -DNO_DIVIDE_BY_ZERO do not divide by zero # -DNCHOLMOD do not use CHOLMOD as a ordering method. If -DNCHOLMOD is # included in UMFPACK_CONFIG, then UMFPACK does not rely on # CHOLMOD, CAMD, CCOLAMD, COLAMD, and METIS. UMFPACK_CONFIG = # uncomment this line to compile UMFPACK without CHOLMOD: # UMFPACK_CONFIG = -DNCHOLMOD #------------------------------------------------------------------------------ # CHOLMOD configuration #------------------------------------------------------------------------------ # CHOLMOD Library Modules, which appear in libcholmod.a: # Core requires: none # Check requires: Core # Cholesky requires: Core, AMD, COLAMD. optional: Partition, Supernodal # MatrixOps requires: Core # Modify requires: Core # Partition requires: Core, CCOLAMD, METIS. optional: Cholesky # Supernodal requires: Core, BLAS, LAPACK # # CHOLMOD test/demo Modules (all are GNU GPL, do not appear in libcholmod.a): # Tcov requires: Core, Check, Cholesky, MatrixOps, Modify, Supernodal # optional: Partition # Valgrind same as Tcov # Demo requires: Core, Check, Cholesky, MatrixOps, Supernodal # optional: Partition # # Configuration flags: # -DNCHECK do not include the Check module. License GNU LGPL # -DNCHOLESKY do not include the Cholesky module. License GNU LGPL # -DNPARTITION do not include the Partition module. License GNU LGPL # also do not include METIS. # -DNCAMD do not use CAMD, etc from Partition module. GNU LGPL # -DNGPL do not include any GNU GPL Modules in the CHOLMOD library: # -DNMATRIXOPS do not include the MatrixOps module. License GNU GPL # -DNMODIFY do not include the Modify module. License GNU GPL # -DNSUPERNODAL do not include the Supernodal module. License GNU GPL # # -DNPRINT do not print anything. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF for Solaris only. If defined, do not use the Sun # Performance Library CHOLMOD_CONFIG = $(GPU_CONFIG) # uncomment this line to compile CHOLMOD without METIS: # CHOLMOD_CONFIG = -DNPARTITION #------------------------------------------------------------------------------ # SuiteSparseQR configuration: #------------------------------------------------------------------------------ # The SuiteSparseQR library can be compiled with the following options: # # -DNPARTITION do not include the CHOLMOD partition module # -DNEXPERT do not include the functions in SuiteSparseQR_expert.cpp # -DHAVE_TBB enable the use of Intel's Threading Building Blocks (TBB) # default, without timing, without TBB: SPQR_CONFIG = # with TBB: # SPQR_CONFIG = -DHAVE_TBB # This is needed for IBM AIX: (but not for and C codes, just C++) # SPQR_CONFIG = -DBLAS_NO_UNDERSCORE # with TBB, you must select this: # TBB = -ltbb # without TBB: TBB = #------------------------------------------------------------------------------ # Linux #------------------------------------------------------------------------------ # Using default compilers: # CC = gcc # CF = $(CFLAGS) -O3 -fexceptions # alternatives: # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi \ -funit-at-a-time # CF = $(CFLAGS) -O3 -fexceptions \ -Wall -W -Werror -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi # CF = $(CFLAGS) -O3 -fexceptions -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # CF = $(CFLAGS) -O3 # CF = $(CFLAGS) -O3 -g -fexceptions # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow \ -Wredundant-decls -Wdisabled-optimization -ansi # consider: # -fforce-addr -fmove-all-movables -freduce-all-givs -ftsp-ordering # -frename-registers -ffast-math -funroll-loops # Using the Goto BLAS: # BLAS = -lgoto -lfrtbegin -lg2c $(XERBLA) -lpthread # Using Intel's icc and ifort compilers: # (does not work for mexFunctions unless you add a mexopts.sh file) # F77 = ifort # CC = icc # CF = $(CFLAGS) -O3 -xN -vec_report=0 # CF = $(CFLAGS) -g # 64bit: # F77FLAGS = -O -m64 # CF = $(CFLAGS) -O3 -fexceptions -m64 # BLAS = -lgoto64 -lfrtbegin -lg2c -lpthread $(XERBLA) # LAPACK = -llapack64 # SUSE Linux 10.1, AMD Opteron, with GOTO Blas # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # SUSE Linux 10.1, Intel Pentium, with GOTO Blas # F77 = gfortran # BLAS = -lgoto -lgfortran #------------------------------------------------------------------------------ # Mac #------------------------------------------------------------------------------ # As recommended by macports, http://suitesparse.darwinports.com/ # I've tested them myself on Mac OSX 10.6.1 and 10.6.8 (Snow Leopard), # on my MacBook Air, and they work fine. # F77 = gfortran # CF = $(CFLAGS) -O3 -fno-common -fexceptions -DNTIMER # BLAS = -framework Accelerate # LAPACK = -framework Accelerate # LIB = -lm #------------------------------------------------------------------------------ # Solaris #------------------------------------------------------------------------------ # 32-bit # CF = $(CFLAGS) -KPIC -dalign -xc99=%none -Xc -xlibmieee -xO5 -xlibmil -m32 # 64-bit # CF = $(CFLAGS) -fast -KPIC -xc99=%none -xlibmieee -xlibmil -m64 -Xc # FFLAGS = -fast -KPIC -dalign -xlibmil -m64 # The Sun Performance Library includes both LAPACK and the BLAS: # BLAS = -xlic_lib=sunperf # LAPACK = #------------------------------------------------------------------------------ # Compaq Alpha #------------------------------------------------------------------------------ # 64-bit mode only # CF = $(CFLAGS) -O2 -std1 # BLAS = -ldxml # LAPACK = #------------------------------------------------------------------------------ # IBM RS 6000 #------------------------------------------------------------------------------ # BLAS = -lessl # LAPACK = # 32-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 # 64-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -q64 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 -q64 #------------------------------------------------------------------------------ # SGI IRIX #------------------------------------------------------------------------------ # BLAS = -lscsl # LAPACK = # 32-bit mode # CF = $(CFLAGS) -O # 64-bit mode (32 bit int's and 64-bit long's): # CF = $(CFLAGS) -64 # F77FLAGS = -64 # SGI doesn't have ranlib # RANLIB = echo #------------------------------------------------------------------------------ # AMD Opteron (64 bit) #------------------------------------------------------------------------------ # BLAS = -lgoto_opteron64 -lg2c # LAPACK = -llapack_opteron64 # SUSE Linux 10.1, AMD Opteron # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # LAPACK = -llapack_opteron64 #------------------------------------------------------------------------------ # remove object files and profile output #------------------------------------------------------------------------------ CLEAN = *.o *.obj *.ln *.bb *.bbg *.da *.tcov *.gcov gmon.out *.bak *.d *.gcda *.gcno igraph/src/SuiteSparse_config/SuiteSparse_config.h0000644000175100001440000001576313431000472022100 0ustar hornikusers/* ========================================================================== */ /* === SuiteSparse_config =================================================== */ /* ========================================================================== */ /* Configuration file for SuiteSparse: a Suite of Sparse matrix packages * (AMD, COLAMD, CCOLAMD, CAMD, CHOLMOD, UMFPACK, CXSparse, and others). * * SuiteSparse_config.h provides the definition of the long integer. On most * systems, a C program can be compiled in LP64 mode, in which long's and * pointers are both 64-bits, and int's are 32-bits. Windows 64, however, uses * the LLP64 model, in which int's and long's are 32-bits, and long long's and * pointers are 64-bits. * * SuiteSparse packages that include long integer versions are * intended for the LP64 mode. However, as a workaround for Windows 64 * (and perhaps other systems), the long integer can be redefined. * * If _WIN64 is defined, then the __int64 type is used instead of long. * * The long integer can also be defined at compile time. For example, this * could be added to SuiteSparse_config.mk: * * CFLAGS = -O -D'SuiteSparse_long=long long' \ * -D'SuiteSparse_long_max=9223372036854775801' -D'SuiteSparse_long_idd="lld"' * * This file defines SuiteSparse_long as either long (on all but _WIN64) or * __int64 on Windows 64. The intent is that a SuiteSparse_long is always a * 64-bit integer in a 64-bit code. ptrdiff_t might be a better choice than * long; it is always the same size as a pointer. * * This file also defines the SUITESPARSE_VERSION and related definitions. * * Copyright (c) 2012, Timothy A. Davis. No licensing restrictions apply * to this file or to the SuiteSparse_config directory. * Author: Timothy A. Davis. */ #ifndef _SUITESPARSECONFIG_H #define _SUITESPARSECONFIG_H #ifdef __cplusplus extern "C" { #endif #include #include /* ========================================================================== */ /* === SuiteSparse_long ===================================================== */ /* ========================================================================== */ #ifndef SuiteSparse_long #ifdef _WIN64 #define SuiteSparse_long __int64 #define SuiteSparse_long_max _I64_MAX #define SuiteSparse_long_idd "I64d" #else #define SuiteSparse_long long #define SuiteSparse_long_max LONG_MAX #define SuiteSparse_long_idd "ld" #endif #define SuiteSparse_long_id "%" SuiteSparse_long_idd #endif /* For backward compatibility with prior versions of SuiteSparse. The UF_* * macros are deprecated and will be removed in a future version. */ #ifndef UF_long #define UF_long SuiteSparse_long #define UF_long_max SuiteSparse_long_max #define UF_long_idd SuiteSparse_long_idd #define UF_long_id SuiteSparse_long_id #endif /* ========================================================================== */ /* === SuiteSparse_config parameters and functions ========================== */ /* ========================================================================== */ /* SuiteSparse-wide parameters will be placed in this struct. */ typedef struct SuiteSparse_config_struct { void *(*malloc_memory) (size_t) ; /* pointer to malloc */ void *(*realloc_memory) (void *, size_t) ; /* pointer to realloc */ void (*free_memory) (void *) ; /* pointer to free */ void *(*calloc_memory) (size_t, size_t) ; /* pointer to calloc */ } SuiteSparse_config ; void *SuiteSparse_malloc /* pointer to allocated block of memory */ ( size_t nitems, /* number of items to malloc (>=1 is enforced) */ size_t size_of_item, /* sizeof each item */ int *ok, /* TRUE if successful, FALSE otherwise */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) ; void *SuiteSparse_free /* always returns NULL */ ( void *p, /* block to free */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) ; void SuiteSparse_tic /* start the timer */ ( double tic [2] /* output, contents undefined on input */ ) ; double SuiteSparse_toc /* return time in seconds since last tic */ ( double tic [2] /* input: from last call to SuiteSparse_tic */ ) ; double SuiteSparse_time /* returns current wall clock time in seconds */ ( void ) ; /* determine which timer to use, if any */ #ifndef NTIMER #ifdef _POSIX_C_SOURCE #if _POSIX_C_SOURCE >= 199309L #define SUITESPARSE_TIMER_ENABLED #endif #endif #endif /* ========================================================================== */ /* === SuiteSparse version ================================================== */ /* ========================================================================== */ /* SuiteSparse is not a package itself, but a collection of packages, some of * which must be used together (UMFPACK requires AMD, CHOLMOD requires AMD, * COLAMD, CAMD, and CCOLAMD, etc). A version number is provided here for the * collection itself. The versions of packages within each version of * SuiteSparse are meant to work together. Combining one packge from one * version of SuiteSparse, with another package from another version of * SuiteSparse, may or may not work. * * SuiteSparse contains the following packages: * * SuiteSparse_config version 4.2.1 (version always the same as SuiteSparse) * AMD version 2.3.1 * BTF version 1.2.0 * CAMD version 2.3.1 * CCOLAMD version 2.8.0 * CHOLMOD version 2.1.2 * COLAMD version 2.8.0 * CSparse version 3.1.2 * CXSparse version 3.1.2 * KLU version 1.2.1 * LDL version 2.1.0 * RBio version 2.1.1 * SPQR version 1.3.1 (full name is SuiteSparseQR) * UMFPACK version 5.6.2 * MATLAB_Tools various packages & M-files * * Other package dependencies: * BLAS required by CHOLMOD and UMFPACK * LAPACK required by CHOLMOD * METIS 4.0.1 required by CHOLMOD (optional) and KLU (optional) */ int SuiteSparse_version /* returns SUITESPARSE_VERSION */ ( /* output, not defined on input. Not used if NULL. Returns the three version codes in version [0..2]: version [0] is SUITESPARSE_MAIN_VERSION version [1] is SUITESPARSE_SUB_VERSION version [2] is SUITESPARSE_SUBSUB_VERSION */ int version [3] ) ; /* Versions prior to 4.2.0 do not have the above function. The following code fragment will work with any version of SuiteSparse: #ifdef SUITESPARSE_HAS_VERSION_FUNCTION v = SuiteSparse_version (NULL) ; #else v = SUITESPARSE_VERSION ; #endif */ #define SUITESPARSE_HAS_VERSION_FUNCTION #define SUITESPARSE_DATE "April 25, 2013" #define SUITESPARSE_VER_CODE(main,sub) ((main) * 1000 + (sub)) #define SUITESPARSE_MAIN_VERSION 4 #define SUITESPARSE_SUB_VERSION 2 #define SUITESPARSE_SUBSUB_VERSION 1 #define SUITESPARSE_VERSION \ SUITESPARSE_VER_CODE(SUITESPARSE_MAIN_VERSION,SUITESPARSE_SUB_VERSION) #ifdef __cplusplus } #endif #endif igraph/src/SuiteSparse_config/Makefile0000644000175100001440000000216713562737552017612 0ustar hornikusers#------------------------------------------------------------------------------- # SuiteSparse_config Makefile #------------------------------------------------------------------------------- VERSION = 4.2.1 default: ccode include SuiteSparse_config.mk ccode: libsuitesparseconfig.a all: libsuitesparseconfig.a library: libsuitesparseconfig.a libsuitesparseconfig.a: SuiteSparse_config.c SuiteSparse_config.h $(CC) $(CF) -c SuiteSparse_config.c $(ARCHIVE) libsuitesparseconfig.a SuiteSparse_config.o $(RANLIB) libsuitesparseconfig.a - $(RM) SuiteSparse_config.o distclean: purge purge: clean - $(RM) *.o *.a clean: - $(RM) -r $(CLEAN) # install SuiteSparse_config install: $(CP) libsuitesparseconfig.a $(INSTALL_LIB)/libsuitesparseconfig.$(VERSION).a ( cd $(INSTALL_LIB) ; ln -sf libsuitesparseconfig.$(VERSION).a libsuitesparseconfig.a ) $(CP) SuiteSparse_config.h $(INSTALL_INCLUDE) chmod 644 $(INSTALL_LIB)/libsuitesparseconfig*.a chmod 644 $(INSTALL_INCLUDE)/SuiteSparse_config.h # uninstall SuiteSparse_config uninstall: $(RM) $(INSTALL_LIB)/libsuitesparseconfig*.a $(RM) $(INSTALL_INCLUDE)/SuiteSparse_config.h igraph/src/SuiteSparse_config/SuiteSparse_config.mk0000644000175100001440000003467313430770175022276 0ustar hornikusers#=============================================================================== # SuiteSparse_config.mk: common configuration file for the SuiteSparse #=============================================================================== # This file contains all configuration settings for all packages authored or # co-authored by Tim Davis: # # Package Version Description # ------- ------- ----------- # AMD 1.2 or later approximate minimum degree ordering # COLAMD 2.4 or later column approximate minimum degree ordering # CCOLAMD 1.0 or later constrained column approximate minimum degree ordering # CAMD any constrained approximate minimum degree ordering # UMFPACK 4.5 or later sparse LU factorization, with the BLAS # CHOLMOD any sparse Cholesky factorization, update/downdate # KLU 0.8 or later sparse LU factorization, BLAS-free # BTF 0.8 or later permutation to block triangular form # LDL 1.2 or later concise sparse LDL' # CXSparse any extended version of CSparse (int/long, real/complex) # SuiteSparseQR any sparse QR factorization # RBio 2.0 or later read/write sparse matrices in Rutherford-Boeing format # # By design, this file is NOT included in the CSparse makefile. # That package is fully stand-alone. CSparse is primarily for teaching; # production code should use CXSparse. # # The SuiteSparse_config directory and the above packages should all appear in # a single directory, in order for the Makefile's within each package to find # this file. # # To enable an option of the form "# OPTION = ...", edit this file and # delete the "#" in the first column of the option you wish to use. # # The use of METIS 4.0.1 is optional. To exclude METIS, you must compile with # CHOLMOD_CONFIG set to -DNPARTITION. See below for details. However, if you # do not have a metis-4.0 directory inside the SuiteSparse directory, the # */Makefile's that optionally rely on METIS will automatically detect this # and compile without METIS. #------------------------------------------------------------------------------ # Generic configuration #------------------------------------------------------------------------------ # Using standard definitions from the make environment, typically: # # CC cc C compiler # CXX g++ C++ compiler # CFLAGS [ ] flags for C and C++ compiler # CPPFLAGS [ ] flags for C and C++ compiler # TARGET_ARCH [ ] target architecture # FFLAGS [ ] flags for Fortran compiler # RM rm -f delete a file # AR ar create a static *.a library archive # ARFLAGS rv flags for ar # MAKE make make itself (sometimes called gmake) # # You can redefine them here, but by default they are used from the # default make environment. # C and C++ compiler flags. The first three are standard for *.c and *.cpp # Add -DNTIMER if you do use any timing routines (otherwise -lrt is required). # CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC -DNTIMER CF = $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -O3 -fexceptions -fPIC # ranlib, and ar, for generating libraries. If you don't need ranlib, # just change it to RANLAB = echo RANLIB = ranlib ARCHIVE = $(AR) $(ARFLAGS) # copy and delete a file CP = cp -f MV = mv -f # Fortran compiler (not required for 'make' or 'make library') F77 = gfortran F77FLAGS = $(FFLAGS) -O F77LIB = # C and Fortran libraries. Remove -lrt if you don't have it. LIB = -lm -lrt # Using the following requires CF = ... -DNTIMER on POSIX C systems. # LIB = -lm # For "make install" INSTALL_LIB = /usr/local/lib INSTALL_INCLUDE = /usr/local/include # Which version of MAKE you are using (default is "make") # MAKE = make # MAKE = gmake #------------------------------------------------------------------------------ # BLAS and LAPACK configuration: #------------------------------------------------------------------------------ # UMFPACK and CHOLMOD both require the BLAS. CHOLMOD also requires LAPACK. # See Kazushige Goto's BLAS at http://www.cs.utexas.edu/users/flame/goto/ or # http://www.tacc.utexas.edu/~kgoto/ for the best BLAS to use with CHOLMOD. # LAPACK is at http://www.netlib.org/lapack/ . You can use the standard # Fortran LAPACK along with Goto's BLAS to obtain very good performance. # CHOLMOD gets a peak numeric factorization rate of 3.6 Gflops on a 3.2 GHz # Pentium 4 (512K cache, 4GB main memory) with the Goto BLAS, and 6 Gflops # on a 2.5Ghz dual-core AMD Opteron. # These settings will probably not work, since there is no fixed convention for # naming the BLAS and LAPACK library (*.a or *.so) files. # This is probably slow ... it might connect to the Standard Reference BLAS: BLAS = -lblas -lgfortran LAPACK = -llapack # NOTE: this next option for the "Goto BLAS" has nothing to do with a "goto" # statement. Rather, the Goto BLAS is written by Dr. Kazushige Goto. # Using the Goto BLAS: # BLAS = -lgoto -lgfortran -lgfortranbegin # BLAS = -lgoto2 -lgfortran -lgfortranbegin -lpthread # Using non-optimized versions: # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack_plain # BLAS = -lblas_plain -lgfortran -lgfortranbegin # LAPACK = -llapack # The BLAS might not contain xerbla, an error-handling routine for LAPACK and # the BLAS. Also, the standard xerbla requires the Fortran I/O library, and # stops the application program if an error occurs. A C version of xerbla # distributed with this software (SuiteSparse_config/xerbla/libcerbla.a) # includes a Fortran-callable xerbla routine that prints nothing and does not # stop the application program. This is optional. # XERBLA = ../../SuiteSparse_config/xerbla/libcerbla.a # If you wish to use the XERBLA in LAPACK and/or the BLAS instead, # use this option: XERBLA = # If you wish to use the Fortran SuiteSparse_config/xerbla/xerbla.f instead, # use this: # XERBLA = ../../SuiteSparse_config/xerbla/libxerbla.a #------------------------------------------------------------------------------ # GPU configuration for CHOLMOD, using the CUDA BLAS #------------------------------------------------------------------------------ # no cuda GPU_BLAS_PATH = GPU_CONFIG = # with cuda BLAS acceleration for CHOLMOD # GPU_BLAS_PATH=/usr/local/cuda # GPU_CONFIG=-DGPU_BLAS -I$(GPU_BLAS_PATH)/include #------------------------------------------------------------------------------ # METIS, optionally used by CHOLMOD #------------------------------------------------------------------------------ # If you do not have METIS, or do not wish to use it in CHOLMOD, you must # compile CHOLMOD with the -DNPARTITION flag. # The path is relative to where it is used, in CHOLMOD/Lib, CHOLMOD/MATLAB, etc. # You may wish to use an absolute path. METIS is optional. Compile # CHOLMOD with -DNPARTITION if you do not wish to use METIS. METIS_PATH = ../../metis-4.0 METIS = ../../metis-4.0/libmetis.a #------------------------------------------------------------------------------ # UMFPACK configuration: #------------------------------------------------------------------------------ # Configuration flags for UMFPACK. See UMFPACK/Source/umf_config.h for details. # # -DNBLAS do not use the BLAS. UMFPACK will be very slow. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF do not use the Sun Perf. Library (default is use it on Solaris) # -DNRECIPROCAL do not multiply by the reciprocal # -DNO_DIVIDE_BY_ZERO do not divide by zero # -DNCHOLMOD do not use CHOLMOD as a ordering method. If -DNCHOLMOD is # included in UMFPACK_CONFIG, then UMFPACK does not rely on # CHOLMOD, CAMD, CCOLAMD, COLAMD, and METIS. UMFPACK_CONFIG = # uncomment this line to compile UMFPACK without CHOLMOD: # UMFPACK_CONFIG = -DNCHOLMOD #------------------------------------------------------------------------------ # CHOLMOD configuration #------------------------------------------------------------------------------ # CHOLMOD Library Modules, which appear in libcholmod.a: # Core requires: none # Check requires: Core # Cholesky requires: Core, AMD, COLAMD. optional: Partition, Supernodal # MatrixOps requires: Core # Modify requires: Core # Partition requires: Core, CCOLAMD, METIS. optional: Cholesky # Supernodal requires: Core, BLAS, LAPACK # # CHOLMOD test/demo Modules (all are GNU GPL, do not appear in libcholmod.a): # Tcov requires: Core, Check, Cholesky, MatrixOps, Modify, Supernodal # optional: Partition # Valgrind same as Tcov # Demo requires: Core, Check, Cholesky, MatrixOps, Supernodal # optional: Partition # # Configuration flags: # -DNCHECK do not include the Check module. License GNU LGPL # -DNCHOLESKY do not include the Cholesky module. License GNU LGPL # -DNPARTITION do not include the Partition module. License GNU LGPL # also do not include METIS. # -DNCAMD do not use CAMD, etc from Partition module. GNU LGPL # -DNGPL do not include any GNU GPL Modules in the CHOLMOD library: # -DNMATRIXOPS do not include the MatrixOps module. License GNU GPL # -DNMODIFY do not include the Modify module. License GNU GPL # -DNSUPERNODAL do not include the Supernodal module. License GNU GPL # # -DNPRINT do not print anything. # -D'LONGBLAS=long' or -DLONGBLAS='long long' defines the integers used by # LAPACK and the BLAS (defaults to 'int') # -DNSUNPERF for Solaris only. If defined, do not use the Sun # Performance Library CHOLMOD_CONFIG = $(GPU_CONFIG) # uncomment this line to compile CHOLMOD without METIS: # CHOLMOD_CONFIG = -DNPARTITION #------------------------------------------------------------------------------ # SuiteSparseQR configuration: #------------------------------------------------------------------------------ # The SuiteSparseQR library can be compiled with the following options: # # -DNPARTITION do not include the CHOLMOD partition module # -DNEXPERT do not include the functions in SuiteSparseQR_expert.cpp # -DHAVE_TBB enable the use of Intel's Threading Building Blocks (TBB) # default, without timing, without TBB: SPQR_CONFIG = # with TBB: # SPQR_CONFIG = -DHAVE_TBB # This is needed for IBM AIX: (but not for and C codes, just C++) # SPQR_CONFIG = -DBLAS_NO_UNDERSCORE # with TBB, you must select this: # TBB = -ltbb # without TBB: TBB = #------------------------------------------------------------------------------ # Linux #------------------------------------------------------------------------------ # Using default compilers: # CC = gcc # CF = $(CFLAGS) -O3 -fexceptions # alternatives: # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi \ -funit-at-a-time # CF = $(CFLAGS) -O3 -fexceptions \ -Wall -W -Werror -Wshadow -Wmissing-prototypes -Wstrict-prototypes \ -Wredundant-decls -Wnested-externs -Wdisabled-optimization -ansi # CF = $(CFLAGS) -O3 -fexceptions -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE # CF = $(CFLAGS) -O3 # CF = $(CFLAGS) -O3 -g -fexceptions # CF = $(CFLAGS) -g -fexceptions \ -Wall -W -Wshadow \ -Wredundant-decls -Wdisabled-optimization -ansi # consider: # -fforce-addr -fmove-all-movables -freduce-all-givs -ftsp-ordering # -frename-registers -ffast-math -funroll-loops # Using the Goto BLAS: # BLAS = -lgoto -lfrtbegin -lg2c $(XERBLA) -lpthread # Using Intel's icc and ifort compilers: # (does not work for mexFunctions unless you add a mexopts.sh file) # F77 = ifort # CC = icc # CF = $(CFLAGS) -O3 -xN -vec_report=0 # CF = $(CFLAGS) -g # 64bit: # F77FLAGS = -O -m64 # CF = $(CFLAGS) -O3 -fexceptions -m64 # BLAS = -lgoto64 -lfrtbegin -lg2c -lpthread $(XERBLA) # LAPACK = -llapack64 # SUSE Linux 10.1, AMD Opteron, with GOTO Blas # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # SUSE Linux 10.1, Intel Pentium, with GOTO Blas # F77 = gfortran # BLAS = -lgoto -lgfortran #------------------------------------------------------------------------------ # Mac #------------------------------------------------------------------------------ # As recommended by macports, http://suitesparse.darwinports.com/ # I've tested them myself on Mac OSX 10.6.1 and 10.6.8 (Snow Leopard), # on my MacBook Air, and they work fine. # F77 = gfortran # CF = $(CFLAGS) -O3 -fno-common -fexceptions -DNTIMER # BLAS = -framework Accelerate # LAPACK = -framework Accelerate # LIB = -lm #------------------------------------------------------------------------------ # Solaris #------------------------------------------------------------------------------ # 32-bit # CF = $(CFLAGS) -KPIC -dalign -xc99=%none -Xc -xlibmieee -xO5 -xlibmil -m32 # 64-bit # CF = $(CFLAGS) -fast -KPIC -xc99=%none -xlibmieee -xlibmil -m64 -Xc # FFLAGS = -fast -KPIC -dalign -xlibmil -m64 # The Sun Performance Library includes both LAPACK and the BLAS: # BLAS = -xlic_lib=sunperf # LAPACK = #------------------------------------------------------------------------------ # Compaq Alpha #------------------------------------------------------------------------------ # 64-bit mode only # CF = $(CFLAGS) -O2 -std1 # BLAS = -ldxml # LAPACK = #------------------------------------------------------------------------------ # IBM RS 6000 #------------------------------------------------------------------------------ # BLAS = -lessl # LAPACK = # 32-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 # 64-bit mode: # CF = $(CFLAGS) -O4 -qipa -qmaxmem=16384 -q64 -qproto # F77FLAGS = -O4 -qipa -qmaxmem=16384 -q64 #------------------------------------------------------------------------------ # SGI IRIX #------------------------------------------------------------------------------ # BLAS = -lscsl # LAPACK = # 32-bit mode # CF = $(CFLAGS) -O # 64-bit mode (32 bit int's and 64-bit long's): # CF = $(CFLAGS) -64 # F77FLAGS = -64 # SGI doesn't have ranlib # RANLIB = echo #------------------------------------------------------------------------------ # AMD Opteron (64 bit) #------------------------------------------------------------------------------ # BLAS = -lgoto_opteron64 -lg2c # LAPACK = -llapack_opteron64 # SUSE Linux 10.1, AMD Opteron # F77 = gfortran # BLAS = -lgoto_opteron64 -lgfortran # LAPACK = -llapack_opteron64 #------------------------------------------------------------------------------ # remove object files and profile output #------------------------------------------------------------------------------ CLEAN = *.o *.obj *.ln *.bb *.bbg *.da *.tcov *.gcov gmon.out *.bak *.d *.gcda *.gcno igraph/src/SuiteSparse_config/SuiteSparse_config.c0000644000175100001440000001354513431000472022067 0ustar hornikusers/* ========================================================================== */ /* === SuiteSparse_config =================================================== */ /* ========================================================================== */ /* Copyright (c) 2012, Timothy A. Davis. No licensing restrictions * apply to this file or to the SuiteSparse_config directory. * Author: Timothy A. Davis. */ #include "SuiteSparse_config.h" /* -------------------------------------------------------------------------- */ /* SuiteSparse_malloc: malloc wrapper */ /* -------------------------------------------------------------------------- */ void *SuiteSparse_malloc /* pointer to allocated block of memory */ ( size_t nitems, /* number of items to malloc (>=1 is enforced) */ size_t size_of_item, /* sizeof each item */ int *ok, /* TRUE if successful, FALSE otherwise */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) { void *p ; if (nitems < 1) nitems = 1 ; if (nitems * size_of_item != ((double) nitems) * size_of_item) { /* Int overflow */ *ok = 0 ; return (NULL) ; } if (!config || config->malloc_memory == NULL) { /* use malloc by default */ p = (void *) malloc (nitems * size_of_item) ; } else { /* use the pointer to malloc in the config */ p = (void *) (config->malloc_memory) (nitems * size_of_item) ; } *ok = (p != NULL) ; return (p) ; } /* -------------------------------------------------------------------------- */ /* SuiteSparse_free: free wrapper */ /* -------------------------------------------------------------------------- */ void *SuiteSparse_free /* always returns NULL */ ( void *p, /* block to free */ SuiteSparse_config *config /* SuiteSparse-wide configuration */ ) { if (p) { if (!config || config->free_memory == NULL) { /* use free by default */ free (p) ; } else { /* use the pointer to free in the config */ (config->free_memory) (p) ; } } return (NULL) ; } /* -------------------------------------------------------------------------- */ /* SuiteSparse_tic: return current wall clock time */ /* -------------------------------------------------------------------------- */ /* Returns the number of seconds (tic [0]) and nanoseconds (tic [1]) since some * unspecified but fixed time in the past. If no timer is installed, zero is * returned. A scalar double precision value for 'tic' could be used, but this * might cause loss of precision because clock_getttime returns the time from * some distant time in the past. Thus, an array of size 2 is used. * * The timer is enabled by default. To disable the timer, compile with * -DNTIMER. If enabled on a POSIX C 1993 system, the timer requires linking * with the -lrt library. * * example: * * double tic [2], r, s, t ; * SuiteSparse_tic (tic) ; // start the timer * // do some work A * t = SuiteSparse_toc (tic) ; // t is time for work A, in seconds * // do some work B * s = SuiteSparse_toc (tic) ; // s is time for work A and B, in seconds * SuiteSparse_tic (tic) ; // restart the timer * // do some work C * r = SuiteSparse_toc (tic) ; // s is time for work C, in seconds * * A double array of size 2 is used so that this routine can be more easily * ported to non-POSIX systems. The caller does not rely on the POSIX * include file. */ #ifdef SUITESPARSE_TIMER_ENABLED #include void SuiteSparse_tic ( double tic [2] /* output, contents undefined on input */ ) { /* POSIX C 1993 timer, requires -librt */ struct timespec t ; clock_gettime (CLOCK_MONOTONIC, &t) ; tic [0] = (double) (t.tv_sec) ; tic [1] = (double) (t.tv_nsec) ; } #else void SuiteSparse_tic ( double tic [2] /* output, contents undefined on input */ ) { /* no timer installed */ tic [0] = 0 ; tic [1] = 0 ; } #endif /* -------------------------------------------------------------------------- */ /* SuiteSparse_toc: return time since last tic */ /* -------------------------------------------------------------------------- */ /* Assuming SuiteSparse_tic is accurate to the nanosecond, this function is * accurate down to the nanosecond for 2^53 nanoseconds since the last call to * SuiteSparse_tic, which is sufficient for SuiteSparse (about 104 days). If * additional accuracy is required, the caller can use two calls to * SuiteSparse_tic and do the calculations differently. */ double SuiteSparse_toc /* returns time in seconds since last tic */ ( double tic [2] /* input, not modified from last call to SuiteSparse_tic */ ) { double toc [2] ; SuiteSparse_tic (toc) ; return ((toc [0] - tic [0]) + 1e-9 * (toc [1] - tic [1])) ; } /* -------------------------------------------------------------------------- */ /* SuiteSparse_time: return current wallclock time in seconds */ /* -------------------------------------------------------------------------- */ /* This function might not be accurate down to the nanosecond. */ double SuiteSparse_time /* returns current wall clock time in seconds */ ( void ) { double toc [2] ; SuiteSparse_tic (toc) ; return (toc [0] + 1e-9 * toc [1]) ; } /* -------------------------------------------------------------------------- */ /* SuiteSparse_version: return the current version of SuiteSparse */ /* -------------------------------------------------------------------------- */ int SuiteSparse_version ( int version [3] ) { if (version != NULL) { version [0] = SUITESPARSE_MAIN_VERSION ; version [1] = SUITESPARSE_SUB_VERSION ; version [2] = SUITESPARSE_SUBSUB_VERSION ; } return (SUITESPARSE_VERSION) ; } igraph/src/igraph_stack.c0000644000175100001440000000416013431000472015127 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_stack.h" #define BASE_IGRAPH_REAL #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_IGRAPH_REAL #define BASE_LONG #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_LONG #define BASE_INT #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_INT #define BASE_CHAR #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_CHAR #define BASE_BOOL #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_BOOL #define BASE_PTR #include "igraph_pmt.h" #include "stack.pmt" #include "igraph_pmt_off.h" #undef BASE_PTR /** * \ingroup stack * \brief Calls free() on all elements of a pointer stack. */ void igraph_stack_ptr_free_all (igraph_stack_ptr_t* v) { void **ptr; assert(v != 0); assert(v->stor_begin != 0); for (ptr=v->stor_begin; ptrend; ptr++) { igraph_Free(*ptr); } } /** * \ingroup stack * \brief Calls free() on all elements and destroys the stack. */ void igraph_stack_ptr_destroy_all (igraph_stack_ptr_t* v) { assert(v != 0); assert(v->stor_begin != 0); igraph_stack_ptr_free_all(v); igraph_stack_ptr_destroy(v); } igraph/src/igraph_strvector.c0000644000175100001440000003611713431000472016064 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2003-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "igraph_types.h" #include "igraph_strvector.h" #include "igraph_memory.h" #include "igraph_random.h" #include "igraph_error.h" #include "config.h" #include #include /* memcpy & co. */ #include /** * \section igraph_strvector_t * The igraph_strvector_t type is a vector of strings. * The current implementation is very simple and not too efficient. It * works fine for not too many strings, e.g. the list of attribute * names is returned in a string vector by \ref * igraph_cattribute_list(). Do not expect great performance from this * type. * * * \example examples/simple/igraph_strvector.c * */ /** * \ingroup strvector * \function igraph_strvector_init * \brief Initialize * * Reserves memory for the string vector, a string vector must be * first initialized before calling other functions on it. * All elements of the string vector are set to the empty string. * \param sv Pointer to an initialized string vector. * \param len The (initial) length of the string vector. * \return Error code. * * Time complexity: O(\p len). */ int igraph_strvector_init(igraph_strvector_t *sv, long int len) { long int i; sv->data=igraph_Calloc(len, char*); if (sv->data==0) { IGRAPH_ERROR("strvector init failed", IGRAPH_ENOMEM); } for (i=0; idata[i]=igraph_Calloc(1, char); if (sv->data[i]==0) { igraph_strvector_destroy(sv); IGRAPH_ERROR("strvector init failed", IGRAPH_ENOMEM); } sv->data[i][0]='\0'; } sv->len=len; return 0; } /** * \ingroup strvector * \function igraph_strvector_destroy * \brief Free allocated memory * * Destroy a string vector. It may be reinitialized with \ref * igraph_strvector_init() later. * \param sv The string vector. * * Time complexity: O(l), the total length of the strings, maybe less * depending on the memory manager. */ void igraph_strvector_destroy(igraph_strvector_t *sv) { long int i; assert(sv != 0); if (sv->data != 0) { for (i=0; ilen; i++) { if (sv->data[i] != 0) { igraph_Free(sv->data[i]); } } igraph_Free(sv->data); } } /** * \ingroup strvector * \function igraph_strvector_get * \brief Indexing * * Query an element of a string vector. See also the \ref STR macro * for an easier way. * \param sv The input string vector. * \param idx The index of the element to query. * \param Pointer to a char*, the address of the string * is stored here. * * Time complexity: O(1). */ void igraph_strvector_get(const igraph_strvector_t *sv, long int idx, char **value) { assert(sv != 0); assert(sv->data != 0); assert(sv->data[idx] != 0); *value = sv->data[idx]; } /** * \ingroup strvector * \function igraph_strvector_set * \brief Set an element * * The provided \p value is copied into the \p idx position in the * string vector. * \param sv The string vector. * \param idx The position to set. * \param value The new value. * \return Error code. * * Time complexity: O(l), the length of the new string. Maybe more, * depending on the memory management, if reallocation is needed. */ int igraph_strvector_set(igraph_strvector_t *sv, long int idx, const char *value) { assert(sv != 0); assert(sv->data != 0); if (sv->data[idx] == 0) { sv->data[idx] = igraph_Calloc(strlen(value)+1, char); if (sv->data[idx]==0) { IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM); } } else { char *tmp=igraph_Realloc(sv->data[idx], strlen(value)+1, char); if (tmp==0) { IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM); } sv->data[idx]=tmp; } strcpy(sv->data[idx], value); return 0; } /** * \ingroup strvector * \function igraph_strvector_set2 * \brief Sets an element * * This is almost the same as \ref igraph_strvector_set, but the new * value is not a zero terminated string, but its length is given. * \param sv The string vector. * \param idx The position to set. * \param value The new value. * \param len The length of the new value. * \return Error code. * * Time complexity: O(l), the length of the new string. Maybe more, * depending on the memory management, if reallocation is needed. */ int igraph_strvector_set2(igraph_strvector_t *sv, long int idx, const char *value, int len) { assert(sv != 0); assert(sv->data != 0); if (sv->data[idx] == 0) { sv->data[idx] = igraph_Calloc(len+1, char); if (sv->data[idx]==0) { IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM); } } else { char *tmp=igraph_Realloc(sv->data[idx], (size_t) len+1, char); if (tmp==0) { IGRAPH_ERROR("strvector set failed", IGRAPH_ENOMEM); } sv->data[idx]=tmp; } memcpy(sv->data[idx], value, (size_t) len*sizeof(char)); sv->data[idx][len]='\0'; return 0; } /** * \ingroup strvector * \function igraph_strvector_remove_section * \brief Removes a section from a string vector. * \todo repair realloc */ void igraph_strvector_remove_section(igraph_strvector_t *v, long int from, long int to) { long int i; /* char **tmp; */ assert(v != 0); assert(v->data != 0); for (i=from; idata[i] != 0) { igraph_Free(v->data[i]); } } for (i=0; ilen-to; i++) { v->data[from+i]=v->data[to+i]; } v->len -= (to-from); /* try to make it smaller */ /* tmp=igraph_Realloc(v->data, v->len, char*); */ /* if (tmp!=0) { */ /* v->data=tmp; */ /* } */ } /** * \ingroup strvector * \function igraph_strvector_remove * \brief Removes a single element from a string vector. * * The string will be one shorter. * \param The string vector. * \param elem The index of the element to remove. * * Time complexity: O(n), the length of the string. */ void igraph_strvector_remove(igraph_strvector_t *v, long int elem) { assert(v != 0); assert(v->data != 0); igraph_strvector_remove_section(v, elem, elem+1); } /** * \ingroup strvector * \function igraph_strvector_move_interval * \brief Copies an interval of a string vector. */ void igraph_strvector_move_interval(igraph_strvector_t *v, long int begin, long int end, long int to) { long int i; assert(v != 0); assert(v->data != 0); for (i=to; idata[i] != 0) { igraph_Free(v->data[i]); } } for (i=0; idata[begin+i] != 0) { size_t len=strlen(v->data[begin+i])+1; v->data[to+i]=igraph_Calloc(len, char); memcpy(v->data[to+i], v->data[begin+i], sizeof(char)*len); } } } /** * \ingroup strvector * \function igraph_strvector_copy * \brief Initialization by copying. * * Initializes a string vector by copying another string vector. * \param to Pointer to an uninitialized string vector. * \param from The other string vector, to be copied. * \return Error code. * * Time complexity: O(l), the total length of the strings in \p from. */ int igraph_strvector_copy(igraph_strvector_t *to, const igraph_strvector_t *from) { long int i; char *str; assert(from != 0); /* assert(from->data != 0); */ to->data=igraph_Calloc(from->len, char*); if (to->data==0) { IGRAPH_ERROR("Cannot copy string vector", IGRAPH_ENOMEM); } to->len=from->len; for (i=0; ilen; i++) { int ret; igraph_strvector_get(from, i, &str); ret=igraph_strvector_set(to, i, str); if (ret != 0) { igraph_strvector_destroy(to); IGRAPH_ERROR("cannot copy string vector", ret); } } return 0; } /** * \function igraph_strvector_append * Concatenate two string vectors. * * \param to The first string vector, the result is stored here. * \param from The second string vector, it is kept unchanged. * \return Error code. * * Time complexity: O(n+l2), n is the number of strings in the new * string vector, l2 is the total length of strings in the \p from * string vector. */ int igraph_strvector_append(igraph_strvector_t *to, const igraph_strvector_t *from) { long int len1=igraph_strvector_size(to), len2=igraph_strvector_size(from); long int i; igraph_bool_t error=0; IGRAPH_CHECK(igraph_strvector_resize(to, len1+len2)); for (i=0; idata[i][0] != '\0') { igraph_Free(to->data[len1+i]); to->data[len1+i] = strdup(from->data[i]); if (!to->data[len1+i]) { error=1; break; } } } if (error) { igraph_strvector_resize(to, len1); IGRAPH_ERROR("Cannot append string vector", IGRAPH_ENOMEM); } return 0; } /** * \function igraph_strvector_clear * Remove all elements * * After this operation the string vector will be empty. * \param sv The string vector. * * Time complexity: O(l), the total length of strings, maybe less, * depending on the memory manager. */ void igraph_strvector_clear(igraph_strvector_t *sv) { long int i, n=igraph_strvector_size(sv); char **tmp; for (i=0; idata[i]); } sv->len=0; /* try to give back some memory */ tmp=igraph_Realloc(sv->data, 1, char*); if (tmp != 0) { sv->data=tmp; } } /** * \ingroup strvector * \function igraph_strvector_resize * \brief Resize * * If the new size is bigger then empty strings are added, if it is * smaller then the unneeded elements are removed. * \param v The string vector. * \param newsize The new size. * \return Error code. * * Time complexity: O(n), the number of strings if the vector is made * bigger, O(l), the total length of the deleted strings if it is made * smaller, maybe less, depending on memory management. */ int igraph_strvector_resize(igraph_strvector_t* v, long int newsize) { long int toadd=newsize-v->len, i, j; char **tmp; long int reallocsize=newsize; if (reallocsize==0) { reallocsize=1; } assert(v != 0); assert(v->data != 0); /* printf("resize %li to %li\n", v->len, newsize); */ if (newsize < v->len) { for (i=newsize; ilen; i++) { igraph_Free(v->data[i]); } /* try to give back some space */ tmp=igraph_Realloc(v->data, (size_t) reallocsize, char*); /* printf("resize %li to %li, %p\n", v->len, newsize, tmp); */ if (tmp != 0) { v->data=tmp; } } else if (newsize > v->len) { igraph_bool_t error=0; tmp=igraph_Realloc(v->data, (size_t) reallocsize, char*); if (tmp==0) { IGRAPH_ERROR("cannot resize string vector", IGRAPH_ENOMEM); } v->data = tmp; for (i=0; idata[v->len+i] = igraph_Calloc(1, char); if (v->data[v->len+i] == 0) { error=1; break; } v->data[v->len+i][0]='\0'; } if (error) { /* There was an error, free everything we've allocated so far */ for (j=0; jdata[v->len+i] != 0) { igraph_Free(v->data[v->len+i]); } } /* Try to give back space */ tmp=igraph_Realloc(v->data, (size_t) (v->len), char*); if (tmp != 0) { v->data=tmp; } IGRAPH_ERROR("Cannot resize string vector", IGRAPH_ENOMEM); } } v->len = newsize; return 0; } /** * \ingroup strvector * \function igraph_strvector_size * \brief Gives the size of a string vector. * * \param sv The string vector. * \return The length of the string vector. * * Time complexity: O(1). */ long int igraph_strvector_size(const igraph_strvector_t *sv) { assert(sv != 0); assert(sv->data != 0); return sv->len; } /** * \ingroup strvector * \function igraph_strvector_add * \brief Adds an element to the back of a string vector. * * \param v The string vector. * \param value The string to add, it will be copied. * \return Error code. * * Time complexity: O(n+l), n is the total number of strings, l is the * length of the new string. */ int igraph_strvector_add(igraph_strvector_t *v, const char *value) { long int s=igraph_strvector_size(v); char **tmp; assert(v != 0); assert(v->data != 0); tmp=igraph_Realloc(v->data, (size_t) s+1, char*); if (tmp == 0) { IGRAPH_ERROR("cannot add string to string vector", IGRAPH_ENOMEM); } v->data=tmp; v->data[s]=igraph_Calloc(strlen(value)+1, char); if (v->data[s]==0) { IGRAPH_ERROR("cannot add string to string vector", IGRAPH_ENOMEM); } strcpy(v->data[s], value); v->len += 1; return 0; } /** * \ingroup strvector * \function igraph_strvector_permdelete * \brief Removes elements from a string vector (for internal use) */ void igraph_strvector_permdelete(igraph_strvector_t *v, const igraph_vector_t *index, long int nremove) { long int i; char **tmp; assert(v != 0); assert(v->data != 0); for (i=0; idata[ (long int) VECTOR(*index)[i]-1 ] = v->data[i]; } else { igraph_Free(v->data[i]); } } /* Try to make it shorter */ tmp=igraph_Realloc(v->data, v->len-nremove ? (size_t) (v->len-nremove) : 1, char*); if (tmp != 0) { v->data=tmp; } v->len -= nremove; } /** * \ingroup strvector * \function igraph_strvector_remove_negidx * \brief Removes elements from a string vector (for internal use) */ void igraph_strvector_remove_negidx(igraph_strvector_t *v, const igraph_vector_t *neg, long int nremove) { long int i, idx=0; char **tmp; assert(v != 0); assert(v->data != 0); for (i=0; i= 0) { v->data[idx++] = v->data[i]; } else { igraph_Free(v->data[i]); } } /* Try to give back some memory */ tmp=igraph_Realloc(v->data, v->len-nremove ? (size_t) (v->len-nremove) : 1, char*); if (tmp != 0) { v->data=tmp; } v->len -= nremove; } int igraph_strvector_print(const igraph_strvector_t *v, FILE *file, const char *sep) { long int i, n=igraph_strvector_size(v); if (n!=0) { fprintf(file, "%s", STR(*v, 0)); } for (i=1; i 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include #include #include #include /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; typedef uint64_t flex_uint64_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; #endif /* ! C99 */ /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE igraph_dl_yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #define YY_BUF_SIZE 16384 #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ yy_size_t yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via igraph_dl_yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] void igraph_dl_yyrestart (FILE *input_file ,yyscan_t yyscanner ); void igraph_dl_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_dl_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void igraph_dl_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_dl_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void igraph_dl_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void igraph_dl_yypop_buffer_state (yyscan_t yyscanner ); static void igraph_dl_yyensure_buffer_stack (yyscan_t yyscanner ); static void igraph_dl_yy_load_buffer_state (yyscan_t yyscanner ); static void igraph_dl_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER igraph_dl_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE igraph_dl_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_dl_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE igraph_dl_yy_scan_bytes (yyconst char *bytes,yy_size_t len ,yyscan_t yyscanner ); void *igraph_dl_yyalloc (yy_size_t ,yyscan_t yyscanner ); void *igraph_dl_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void igraph_dl_yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer igraph_dl_yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ igraph_dl_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_dl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ igraph_dl_yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ igraph_dl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) #define igraph_dl_yywrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ yyleng = (yy_size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ yyg->yy_c_buf_p = yy_cp; #define YY_NUM_RULES 25 #define YY_END_OF_BUFFER 26 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[131] = { 0, 0, 0, 0, 0, 0, 0, 18, 18, 21, 21, 26, 23, 22, 1, 1, 4, 23, 23, 23, 23, 12, 23, 1, 11, 12, 12, 14, 15, 13, 17, 18, 17, 16, 20, 21, 19, 22, 1, 4, 0, 0, 0, 0, 0, 3, 12, 12, 12, 12, 14, 13, 17, 18, 16, 17, 17, 20, 21, 19, 0, 2, 0, 0, 3, 12, 12, 16, 17, 16, 0, 0, 0, 12, 12, 5, 0, 0, 5, 12, 0, 0, 12, 0, 0, 0, 6, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 0, 10, 7, 7, 9, 8, 10, 8, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 7, 8, 9, 1, 10, 11, 10, 10, 10, 10, 10, 10, 10, 10, 12, 1, 1, 13, 1, 1, 1, 14, 15, 1, 16, 17, 18, 19, 1, 20, 1, 1, 21, 22, 23, 24, 1, 1, 25, 26, 27, 28, 1, 1, 29, 1, 1, 1, 1, 1, 1, 1, 1, 14, 15, 1, 16, 17, 18, 19, 1, 20, 1, 1, 21, 22, 23, 24, 1, 1, 25, 26, 27, 28, 1, 1, 29, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[30] = { 0, 1, 2, 3, 3, 2, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int16_t yy_base[140] = { 0, 0, 22, 44, 64, 84, 94, 104, 114, 124, 134, 288, 289, 4, 283, 283, 2, 1, 261, 270, 15, 29, 289, 280, 289, 39, 50, 0, 289, 34, 0, 52, 19, 64, 0, 54, 51, 74, 289, 67, 255, 88, 256, 265, 138, 98, 108, 118, 128, 144, 0, 145, 0, 151, 151, 72, 159, 0, 152, 153, 265, 169, 256, 260, 170, 171, 175, 171, 168, 173, 264, 261, 253, 184, 185, 289, 246, 246, 189, 193, 195, 197, 199, 205, 218, 209, 289, 210, 0, 255, 242, 245, 246, 248, 245, 249, 231, 228, 217, 211, 200, 184, 181, 172, 150, 138, 138, 128, 126, 106, 75, 66, 67, 45, 45, 36, 42, 39, 22, 26, 219, 211, 6, 220, 227, 228, 232, 237, 238, 242, 289, 247, 250, 253, 256, 259, 262, 7, 6, 0 } ; static yyconst flex_int16_t yy_def[140] = { 0, 131, 131, 132, 132, 133, 133, 134, 134, 135, 135, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 136, 130, 130, 130, 136, 136, 137, 130, 137, 138, 130, 138, 138, 139, 130, 139, 130, 130, 130, 130, 130, 130, 130, 130, 130, 136, 130, 136, 136, 137, 130, 138, 130, 138, 138, 138, 139, 130, 139, 130, 130, 130, 130, 130, 136, 136, 138, 138, 138, 130, 130, 130, 136, 136, 130, 130, 130, 136, 136, 130, 130, 136, 130, 130, 130, 130, 130, 84, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 0, 130, 130, 130, 130, 130, 130, 130, 130, 130 } ; static yyconst flex_int16_t yy_nxt[319] = { 0, 57, 13, 14, 15, 13, 37, 52, 50, 37, 16, 16, 39, 39, 130, 40, 17, 44, 18, 130, 44, 19, 41, 20, 13, 14, 15, 13, 45, 54, 54, 47, 16, 16, 47, 127, 51, 123, 17, 51, 18, 47, 122, 19, 47, 20, 22, 14, 23, 24, 121, 24, 47, 48, 53, 47, 58, 53, 120, 58, 25, 59, 59, 119, 49, 26, 22, 14, 23, 24, 118, 24, 117, 55, 54, 54, 37, 39, 39, 37, 25, 56, 67, 67, 116, 26, 28, 14, 23, 28, 61, 22, 115, 61, 29, 29, 28, 14, 23, 28, 64, 22, 114, 64, 29, 29, 31, 14, 23, 31, 47, 22, 32, 47, 33, 33, 31, 14, 23, 31, 47, 22, 32, 47, 33, 33, 35, 14, 23, 35, 47, 22, 113, 47, 36, 36, 35, 14, 23, 35, 44, 22, 112, 44, 36, 36, 47, 51, 111, 47, 51, 45, 110, 53, 58, 65, 53, 58, 109, 66, 55, 54, 54, 59, 59, 68, 108, 68, 56, 69, 69, 61, 64, 47, 61, 64, 47, 47, 69, 69, 47, 67, 67, 69, 69, 73, 47, 47, 56, 47, 47, 47, 74, 107, 47, 47, 78, 83, 47, 85, 83, 87, 85, 106, 87, 105, 79, 83, 84, 86, 83, 85, 87, 126, 85, 87, 126, 104, 84, 82, 88, 124, 128, 88, 124, 128, 92, 92, 103, 124, 124, 125, 124, 124, 126, 89, 90, 126, 102, 129, 128, 91, 129, 128, 129, 101, 100, 129, 12, 12, 12, 21, 21, 21, 27, 27, 27, 30, 30, 30, 34, 34, 34, 46, 46, 99, 98, 97, 96, 95, 94, 93, 81, 80, 77, 76, 75, 72, 71, 70, 63, 62, 60, 38, 43, 42, 38, 38, 130, 11, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130 } ; static yyconst flex_int16_t yy_chk[319] = { 0, 139, 1, 1, 1, 1, 13, 138, 137, 13, 1, 1, 16, 16, 0, 17, 1, 20, 1, 0, 20, 1, 17, 1, 2, 2, 2, 2, 20, 32, 32, 21, 2, 2, 21, 122, 29, 119, 2, 29, 2, 25, 118, 2, 25, 2, 3, 3, 3, 3, 117, 3, 26, 25, 31, 26, 35, 31, 116, 35, 3, 36, 36, 115, 26, 3, 4, 4, 4, 4, 114, 4, 113, 33, 33, 33, 37, 39, 39, 37, 4, 33, 55, 55, 112, 4, 5, 5, 5, 5, 41, 5, 111, 41, 5, 5, 6, 6, 6, 6, 45, 6, 110, 45, 6, 6, 7, 7, 7, 7, 46, 7, 7, 46, 7, 7, 8, 8, 8, 8, 47, 8, 8, 47, 8, 8, 9, 9, 9, 9, 48, 9, 109, 48, 9, 9, 10, 10, 10, 10, 44, 10, 108, 44, 10, 10, 49, 51, 107, 49, 51, 44, 106, 53, 58, 48, 53, 58, 105, 49, 54, 54, 54, 59, 59, 56, 104, 56, 54, 56, 56, 61, 64, 65, 61, 64, 65, 66, 68, 68, 66, 67, 67, 69, 69, 65, 73, 74, 67, 73, 74, 78, 66, 103, 78, 79, 73, 80, 79, 81, 80, 82, 81, 102, 82, 101, 74, 83, 80, 81, 83, 85, 87, 121, 85, 87, 121, 100, 83, 79, 84, 120, 123, 84, 120, 123, 85, 87, 99, 124, 125, 120, 124, 125, 126, 84, 84, 126, 98, 127, 128, 84, 127, 128, 129, 97, 96, 129, 131, 131, 131, 132, 132, 132, 133, 133, 133, 134, 134, 134, 135, 135, 135, 136, 136, 95, 94, 93, 92, 91, 90, 89, 77, 76, 72, 71, 70, 63, 62, 60, 43, 42, 40, 23, 19, 18, 15, 14, 11, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "src/foreign-dl-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #line 24 "src/foreign-dl-lexer.l" /* IGraph library. Copyright (C) 2007-2012 Gabor Csardi 334 Harvard st, Cambridge, MA, 02138 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include #include #include "foreign-dl-header.h" #include "foreign-dl-parser.h" #define YY_EXTRA_TYPE igraph_i_dl_parsedata_t* #define YY_USER_ACTION yylloc->first_line = yylineno; /* We assume that 'file' is 'stderr' here. */ #ifdef USING_R #define fprintf(file, msg, ...) (1) #endif #ifdef stdout # undef stdout #endif #define stdout 0 #define exit(code) igraph_error("Fatal error in DL parser", __FILE__, \ __LINE__, IGRAPH_PARSEERROR); #define YY_NO_INPUT 1 #line 606 "lex.yy.c" #define INITIAL 0 #define LABELM 1 #define FULLMATRIX 2 #define EDGELIST 3 #define NODELIST 4 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; yy_size_t yy_n_chars; yy_size_t yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; YYLTYPE * yylloc_r; }; /* end struct yyguts_t */ static int yy_init_globals (yyscan_t yyscanner ); /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r # define yylloc yyg->yylloc_r int igraph_dl_yylex_init (yyscan_t* scanner); int igraph_dl_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int igraph_dl_yylex_destroy (yyscan_t yyscanner ); int igraph_dl_yyget_debug (yyscan_t yyscanner ); void igraph_dl_yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE igraph_dl_yyget_extra (yyscan_t yyscanner ); void igraph_dl_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *igraph_dl_yyget_in (yyscan_t yyscanner ); void igraph_dl_yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *igraph_dl_yyget_out (yyscan_t yyscanner ); void igraph_dl_yyset_out (FILE * out_str ,yyscan_t yyscanner ); yy_size_t igraph_dl_yyget_leng (yyscan_t yyscanner ); char *igraph_dl_yyget_text (yyscan_t yyscanner ); int igraph_dl_yyget_lineno (yyscan_t yyscanner ); void igraph_dl_yyset_lineno (int line_number ,yyscan_t yyscanner ); YYSTYPE * igraph_dl_yyget_lval (yyscan_t yyscanner ); void igraph_dl_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); YYLTYPE *igraph_dl_yyget_lloc (yyscan_t yyscanner ); void igraph_dl_yyset_lloc (YYLTYPE * yylloc_param ,yyscan_t yyscanner ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int igraph_dl_yywrap (yyscan_t yyscanner ); #else extern int igraph_dl_yywrap (yyscan_t yyscanner ); #endif #endif #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #define YY_READ_BUF_SIZE 8192 #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO fwrite( yytext, yyleng, 1, yyout ) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ yy_size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int igraph_dl_yylex \ (YYSTYPE * yylval_param,YYLTYPE * yylloc_param ,yyscan_t yyscanner); #define YY_DECL int igraph_dl_yylex \ (YYSTYPE * yylval_param, YYLTYPE * yylloc_param , yyscan_t yyscanner) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; #line 81 "src/foreign-dl-lexer.l" #line 852 "lex.yy.c" yylval = yylval_param; yylloc = yylloc_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) yyin = stdin; if ( ! yyout ) yyout = stdout; if ( ! YY_CURRENT_BUFFER ) { igraph_dl_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_dl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_dl_yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 289 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 83 "src/foreign-dl-lexer.l" { return NEWLINE; } YY_BREAK case 2: YY_RULE_SETUP #line 85 "src/foreign-dl-lexer.l" { return DL; } YY_BREAK case 3: YY_RULE_SETUP #line 86 "src/foreign-dl-lexer.l" { return NEQ; } YY_BREAK case 4: YY_RULE_SETUP #line 88 "src/foreign-dl-lexer.l" { return NUM; } YY_BREAK case 5: YY_RULE_SETUP #line 90 "src/foreign-dl-lexer.l" { switch (yyextra->mode) { case 0: BEGIN(FULLMATRIX); break; case 1: BEGIN(EDGELIST); break; case 2: BEGIN(NODELIST); break; } return DATA; } YY_BREAK case 6: YY_RULE_SETUP #line 101 "src/foreign-dl-lexer.l" { BEGIN(LABELM); return LABELS; } YY_BREAK case 7: YY_RULE_SETUP #line 102 "src/foreign-dl-lexer.l" { return LABELSEMBEDDED; } YY_BREAK case 8: YY_RULE_SETUP #line 104 "src/foreign-dl-lexer.l" { yyextra->mode=0; return FORMATFULLMATRIX; } YY_BREAK case 9: YY_RULE_SETUP #line 106 "src/foreign-dl-lexer.l" { yyextra->mode=1; return FORMATEDGELIST1; } YY_BREAK case 10: YY_RULE_SETUP #line 108 "src/foreign-dl-lexer.l" { yyextra->mode=2; return FORMATNODELIST1; } YY_BREAK case 11: YY_RULE_SETUP #line 111 "src/foreign-dl-lexer.l" { /* eaten up */ } YY_BREAK case 12: YY_RULE_SETUP #line 112 "src/foreign-dl-lexer.l" { return LABEL; } YY_BREAK case 13: YY_RULE_SETUP #line 114 "src/foreign-dl-lexer.l" { return DIGIT; } YY_BREAK case 14: YY_RULE_SETUP #line 115 "src/foreign-dl-lexer.l" { return LABEL; } YY_BREAK case 15: YY_RULE_SETUP #line 116 "src/foreign-dl-lexer.l" { } YY_BREAK case 16: YY_RULE_SETUP #line 118 "src/foreign-dl-lexer.l" { return NUM; } YY_BREAK case 17: YY_RULE_SETUP #line 119 "src/foreign-dl-lexer.l" { return LABEL; } YY_BREAK case 18: YY_RULE_SETUP #line 120 "src/foreign-dl-lexer.l" { } YY_BREAK case 19: YY_RULE_SETUP #line 122 "src/foreign-dl-lexer.l" { return NUM; } YY_BREAK case 20: YY_RULE_SETUP #line 123 "src/foreign-dl-lexer.l" { return LABEL; } YY_BREAK case 21: YY_RULE_SETUP #line 124 "src/foreign-dl-lexer.l" { } YY_BREAK case 22: YY_RULE_SETUP #line 126 "src/foreign-dl-lexer.l" { /* eaten up */ } YY_BREAK case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(LABELM): case YY_STATE_EOF(FULLMATRIX): case YY_STATE_EOF(EDGELIST): case YY_STATE_EOF(NODELIST): #line 128 "src/foreign-dl-lexer.l" { if (yyextra->eof) { yyterminate(); } else { yyextra->eof=1; BEGIN(INITIAL); return EOFF; } } YY_BREAK case 23: YY_RULE_SETUP #line 138 "src/foreign-dl-lexer.l" { return 0; } YY_BREAK case 24: YY_RULE_SETUP #line 140 "src/foreign-dl-lexer.l" { return ERROR; } YY_BREAK case 25: YY_RULE_SETUP #line 141 "src/foreign-dl-lexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 1095 "lex.yy.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * igraph_dl_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( igraph_dl_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of igraph_dl_yylex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { yy_size_t num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { yy_size_t new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ igraph_dl_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; igraph_dl_yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) igraph_dl_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 131 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 130); return yy_is_jam ? 0 : yy_current_state; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ igraph_dl_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( igraph_dl_yywrap(yyscanner ) ) return 0; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ void igraph_dl_yyrestart (FILE * input_file , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ igraph_dl_yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = igraph_dl_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } igraph_dl_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); igraph_dl_yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ void igraph_dl_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * igraph_dl_yypop_buffer_state(); * igraph_dl_yypush_buffer_state(new_buffer); */ igraph_dl_yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; igraph_dl_yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (igraph_dl_yywrap()) processing, but the only time this flag * is looked at is after igraph_dl_yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } static void igraph_dl_yy_load_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ YY_BUFFER_STATE igraph_dl_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) igraph_dl_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) igraph_dl_yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yy_create_buffer()" ); b->yy_is_our_buffer = 1; igraph_dl_yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with igraph_dl_yy_create_buffer() * @param yyscanner The scanner object. */ void igraph_dl_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) igraph_dl_yyfree((void *) b->yy_ch_buf ,yyscanner ); igraph_dl_yyfree((void *) b ,yyscanner ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a igraph_dl_yyrestart() or at EOF. */ static void igraph_dl_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; igraph_dl_yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then igraph_dl_yy_init_buffer was _probably_ * called from igraph_dl_yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ void igraph_dl_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) igraph_dl_yy_load_buffer_state(yyscanner ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ void igraph_dl_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; igraph_dl_yyensure_buffer_stack(yyscanner); /* This block is copied from igraph_dl_yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from igraph_dl_yy_switch_to_buffer. */ igraph_dl_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ void igraph_dl_yypop_buffer_state (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; igraph_dl_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { igraph_dl_yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void igraph_dl_yyensure_buffer_stack (yyscan_t yyscanner) { yy_size_t num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_dl_yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)igraph_dl_yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_dl_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) igraph_dl_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; igraph_dl_yy_switch_to_buffer(b ,yyscanner ); return b; } /** Setup the input buffer state to scan a string. The next call to igraph_dl_yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * igraph_dl_yy_scan_bytes() instead. */ YY_BUFFER_STATE igraph_dl_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return igraph_dl_yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /** Setup the input buffer state to scan the given bytes. The next call to igraph_dl_yylex() will * scan from a @e copy of @a bytes. * @param bytes the byte buffer to scan * @param len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE igraph_dl_yy_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n, i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) igraph_dl_yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in igraph_dl_yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = igraph_dl_yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in igraph_dl_yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE igraph_dl_yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /** Get the current line number. * @param yyscanner The scanner object. */ int igraph_dl_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int igraph_dl_yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *igraph_dl_yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *igraph_dl_yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ yy_size_t igraph_dl_yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *igraph_dl_yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void igraph_dl_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void igraph_dl_yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_dl_yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void igraph_dl_yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "igraph_dl_yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see igraph_dl_yy_switch_to_buffer */ void igraph_dl_yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void igraph_dl_yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int igraph_dl_yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void igraph_dl_yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* Accessor methods for yylval and yylloc */ YYSTYPE * igraph_dl_yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void igraph_dl_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } YYLTYPE *igraph_dl_yyget_lloc (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylloc; } void igraph_dl_yyset_lloc (YYLTYPE * yylloc_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylloc = yylloc_param; } /* User-visible API */ /* igraph_dl_yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int igraph_dl_yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_dl_yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* igraph_dl_yylex_init_extra has the same functionality as igraph_dl_yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to igraph_dl_yyalloc in * the yyextra field. */ int igraph_dl_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; igraph_dl_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) igraph_dl_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); igraph_dl_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from igraph_dl_yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * igraph_dl_yylex_init() */ return 0; } /* igraph_dl_yylex_destroy is for both reentrant and non-reentrant scanners. */ int igraph_dl_yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ igraph_dl_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; igraph_dl_yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ igraph_dl_yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ igraph_dl_yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * igraph_dl_yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* Destroy the main struct (reentrant only). */ igraph_dl_yyfree ( yyscanner , yyscanner ); yyscanner = NULL; return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *igraph_dl_yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *igraph_dl_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void igraph_dl_yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see igraph_dl_yyrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 141 "src/foreign-dl-lexer.l" igraph/src/infomap_FlowGraph.cc0000644000175100001440000002615213431000472016242 0ustar hornikusers/* -*- mode: C -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* IGraph library. Copyright (C) 2011-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "infomap_FlowGraph.h" #define plogp( x ) ( (x) > 0.0 ? (x)*log(x) : 0.0 ) void FlowGraph::init(int n, const igraph_vector_t *v_weights) { alpha = 0.15; beta = 1.0 - alpha; Nnode = n; node = new Node*[Nnode]; if (v_weights) { for (int i=0;i 0.0) { if (from != to) { node[(int) from]->outLinks.push_back(make_pair((int)to, linkWeight)); node[(int) to]->inLinks.push_back(make_pair((int) from, linkWeight)); } } } } FlowGraph::FlowGraph(FlowGraph * fgraph) { int n = fgraph->Nnode; init(n, NULL); for (int i=0; inode[i]); } //XXX: quid de danglings et Ndanglings? alpha = fgraph->alpha ; beta = fgraph->beta ; exit = fgraph->exit; exitFlow = fgraph->exitFlow; exit_log_exit = fgraph->exit_log_exit; size_log_size = fgraph->size_log_size ; nodeSize_log_nodeSize = fgraph->nodeSize_log_nodeSize; codeLength = fgraph->codeLength; } /** construct a graph by extracting a subgraph from the given graph */ FlowGraph::FlowGraph(FlowGraph * fgraph, int sub_Nnode, int * sub_members) { init(sub_Nnode, NULL); //XXX: use set of integer to ensure that elements are sorted set sub_mem; for (int j=0 ; j::iterator it_mem = sub_mem.begin(); vector sub_renumber = vector(fgraph->Nnode); // id --> sub_id for (int j=0; jNnode; j++) { sub_renumber[j] = -1; } for (int j=0; jteleportWeight = fgraph->node[orig_nr]->teleportWeight; node[j]->selfLink = fgraph->node[orig_nr]->selfLink; // Take care of self-link int orig_NoutLinks = fgraph->node[orig_nr]->outLinks.size(); int orig_NinLinks = fgraph->node[orig_nr]->inLinks.size(); sub_renumber[orig_nr] = j; for (int k=0; knode[orig_nr]->outLinks[k].first; int to_newnr = sub_renumber[to]; double link_weight = fgraph->node[orig_nr]->outLinks[k].second; if (to < orig_nr) { // we add links if the destination (to) has already be seen // (ie. smaller than current id) => orig if (sub_mem.find(to) != sub_mem.end()) { // printf("%2d | %4d to %4d\n", j, orig_nr, to); // printf("from %4d (%4d:%1.5f) to %4d (%4d)\n", j, orig_nr, // node[j]->selfLink, to_newnr, to); node[j]->outLinks.push_back(make_pair(to_newnr, link_weight)); node[to_newnr]->inLinks.push_back(make_pair(j, link_weight)); } } } for (int k=0; knode[orig_nr]->inLinks[k].first; int to_newnr = sub_renumber[to]; double link_weight = fgraph->node[orig_nr]->inLinks[k].second; if (to < orig_nr) { if (sub_mem.find(to) != sub_mem.end()) { node[j]->inLinks.push_back(make_pair(to_newnr,link_weight)); node[to_newnr]->outLinks.push_back(make_pair(j,link_weight)); } } } it_mem++; } } FlowGraph::~FlowGraph() { //printf("delete FlowGraph !\n"); for (int i=0;inode; int Nnode_tmp = fgraph->Nnode; fgraph->node = node; fgraph->Nnode = Nnode; node = node_tmp; Nnode = Nnode_tmp; calibrate(); } /** Initialisation of the graph, compute the flow inside the graph * - count danglings nodes * - normalized edge weights * - Call eigenvector() to compute steady state distribution * - call calibrate to compute codelenght */ void FlowGraph::initiate() { // Take care of dangling nodes, normalize outLinks, and calculate // total teleport weight Ndanglings = 0; double totTeleportWeight = 0.0; for (int i=0;iteleportWeight; for (int i=0;iteleportWeight /= totTeleportWeight; // normalize teleportation weight if (node[i]->outLinks.empty() && (node[i]->selfLink <= 0.0)) { danglings.push_back(i); Ndanglings++; } else { // Normalize the weights int NoutLinks = node[i]->outLinks.size(); double sum = node[i]->selfLink; // Take care of self-links for (int j=0;j < NoutLinks; j++) sum += node[i]->outLinks[j].second; node[i]->selfLink /= sum; for (int j=0;j < NoutLinks; j++) node[i]->outLinks[j].second /= sum; } } // Calculate steady state matrix eigenvector(); // Update links to represent flow for (int i=0; iselfLink = beta * node[i]->size * node[i]->selfLink; // (1 - \tau) * \pi_i * P_{ii} if (!node[i]->outLinks.empty()) { int NoutLinks = node[i]->outLinks.size(); for (int j=0;j < NoutLinks; j++) { node[i]->outLinks[j].second = beta * node[i]->size * node[i]->outLinks[j].second; // (1 - \tau) * \pi_i * P_{ij} } // Update values for corresponding inlink for (int j=0; j < NoutLinks; j++) { int NinLinks = node[node[i]->outLinks[j].first]->inLinks.size(); for (int k=0; k < NinLinks; k++) { if (node[node[i]->outLinks[j].first]->inLinks[k].first == i) { node[node[i]->outLinks[j].first]->inLinks[k].second = node[i]->outLinks[j].second; k = NinLinks; } } } } } // To be able to handle dangling nodes efficiently for (int i=0;ioutLinks.empty() && (node[i]->selfLink <= 0.0)) { node[i]->danglingSize = node[i]->size; } else { node[i]->danglingSize = 0.0; } nodeSize_log_nodeSize = 0.0 ; // The exit flow from each node at initiation for (int i=0;iexit = node[i]->size // Proba to be on i - (alpha * node[i]->size + beta * node[i]->danglingSize) * node[i]->teleportWeight // Proba teleport back to i - node[i]->selfLink; // Proba stay on i // node[i]->exit == q_{i\exit} nodeSize_log_nodeSize += plogp(node[i]->size); } calibrate(); } /* Compute steady state distribution (ie. PageRank) over the network * (for all i update node[i]->size) */ void FlowGraph::eigenvector() { vector size_tmp = vector(Nnode,1.0/Nnode); int Niterations = 0; double danglingSize; double sqdiff = 1.0; double sqdiff_old; double sum; do { // Calculate dangling size danglingSize = 0.0; for (int i=0;isize = (alpha + beta*danglingSize) * node[i]->teleportWeight; // Flow from network steps for (int i=0;isize += beta * node[i]->selfLink * size_tmp[i]; int Nlinks = node[i]->outLinks.size(); for (int j=0; j < Nlinks; j++) node[node[i]->outLinks[j].first]->size += beta * node[i]->outLinks[j].second * size_tmp[i]; } // Normalize sum = 0.0; for (int i=0;isize; } sqdiff_old = sqdiff; sqdiff = 0.0; for (int i=0;isize /= sum; sqdiff += fabs(node[i]->size - size_tmp[i]); size_tmp[i] = node[i]->size; } Niterations++; if (sqdiff == sqdiff_old) { alpha += 1.0e-10; beta = 1.0-alpha; } } while ((Niterations < 200) && (sqdiff > 1.0e-15 || Niterations < 50)); danglingSize = 0.0; for (int i=0;iexit + node[i]->size); // use of index codebook exitFlow += node[i]->exit; exit_log_exit += plogp(node[i]->exit); } exit = plogp(exitFlow); codeLength = exit - 2.0*exit_log_exit + size_log_size - nodeSize_log_nodeSize; } /* Restore the data from the given FlowGraph object */ void FlowGraph::back_to(FlowGraph * fgraph) { // delete current nodes for (int i=0 ; iNnode; // copy original ones node = new Node*[Nnode]; for (int i=0;inode[i]); } // restore atributs alpha = fgraph->alpha ; beta = fgraph->beta ; exit = fgraph->exit; exitFlow = fgraph->exitFlow; exit_log_exit = fgraph->exit_log_exit; size_log_size = fgraph->size_log_size ; nodeSize_log_nodeSize = fgraph->nodeSize_log_nodeSize; codeLength = fgraph->codeLength; } igraph/src/atlas-edges.h0000644000175100001440000020247613431000472014700 0ustar hornikusers/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2006-2012 Gabor Csardi 334 Harvard street, Cambridge, MA 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS #include "igraph_types.h" const igraph_real_t igraph_i_atlas_edges[]={ 0,0, 1,0, 2,0, 2,1,0,1, 3,0, 3,1,1,2, 3,2,0,1,0,2, 3,3,0,1,0,2,1,2, 4,0, 4,1,3,2, 4,2,3,2,3,1, 4,2,0,1,3,2, 4,3,3,2,1,2,3,1, 4,3,3,0,3,1,3,2, 4,3,0,1,1,2,0,3, 4,4,3,2,1,2,3,1,3,0, 4,4,0,1,1,2,2,3,0,3, 4,5,0,1,0,2,0,3,1,2,2,3, 4,6,0,1,1,2,0,2,3,0,3,1,3,2, 5,0, 5,1,4,3, 5,2,1,2,0,1, 5,2,0,2,4,3, 5,3,1,2,0,1,2,0, 5,3,4,3,3,2,3,1, 5,3,3,2,4,3,0,4, 5,3,1,2,0,1,4,3, 5,4,4,3,1,2,3,1,3,2, 5,4,0,3,1,0,2,1,3,2, 5,4,4,3,4,0,4,1,4,2, 5,4,4,0,3,1,4,3,3,2, 5,4,2,3,1,2,0,1,4,0, 5,4,1,2,0,1,2,0,4,3, 5,5,0,3,2,0,3,2,1,0,2,1, 5,5,4,2,4,3,2,3,4,1,4,0, 5,5,0,1,1,2,2,3,0,4,0,2, 5,5,4,0,1,2,4,3,3,2,3,1, 5,5,1,0,4,1,2,4,3,2,1,3, 5,5,0,1,1,2,2,3,3,4,0,4, 5,6,1,0,4,1,4,0,0,3,1,3,3,4, 5,6,1,0,4,1,2,4,3,2,1,3,2,1, 5,6,1,0,4,1,2,4,3,2,1,3,3,4, 5,6,0,1,4,3,2,3,4,2,4,0,4,1, 5,6,0,4,3,0,4,3,2,3,1,2,0,1, 5,6,2,1,0,2,3,0,1,3,4,1,0,4, 5,7,4,0,1,2,4,3,3,2,3,1,4,1,2,4, 5,7,4,1,2,4,3,2,1,3,3,4,0,3,4,0, 5,7,0,1,1,2,2,3,3,4,0,4,1,3,4,1, 5,7,2,1,0,2,3,0,1,3,4,1,0,4,2,4, 5,8,1,0,4,1,2,4,3,2,1,3,4,0,3,4,0,3, 5,8,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3, 5,9,0,1,3,4,0,3,0,4,1,2,1,3,1,4,2,3,2,4, 5,10,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4, 6,0, 6,1,5,4, 6,2,0,3,5,4, 6,2,1,3,1,2, 6,3,1,3,2,1,3,2, 6,3,0,3,5,0,4,0, 6,3,4,3,5,4,0,5, 6,3,4,3,5,1,5,2, 6,3,1,2,3,0,5,4, 6,4,0,3,4,0,5,4,0,5, 6,4,3,0,5,3,4,5,0,4, 6,4,5,1,5,3,5,2,0,5, 6,4,4,3,3,1,4,0,3,2, 6,4,0,2,1,3,2,1,5,3, 6,4,1,3,2,1,3,2,0,5, 6,4,1,2,0,3,5,0,4,0, 6,4,4,5,1,2,0,5,3,4, 6,4,0,2,4,0,3,1,5,3, 6,5,3,0,5,3,4,5,0,4,5,0, 6,5,5,3,3,1,3,2,4,3,4,5, 6,5,5,3,5,4,2,3,3,4,0,4, 6,5,4,3,1,2,4,0,3,2,3,1, 6,5,1,4,3,4,4,0,2,1,3,2, 6,5,0,1,1,2,2,3,3,4,0,4, 6,5,5,3,5,4,5,0,5,1,5,2, 6,5,1,4,5,1,1,0,2,1,2,3, 6,5,0,1,3,4,0,2,3,0,5,3, 6,5,1,0,2,1,2,4,1,3,5,3, 6,5,4,3,0,5,4,0,3,2,3,1, 6,5,1,2,0,1,4,5,1,3,2,3, 6,5,0,1,0,5,2,3,3,4,4,5, 6,5,4,3,5,1,5,2,0,3,4,0, 6,5,1,2,3,0,5,3,4,5,0,4, 6,6,0,3,5,0,4,5,3,4,5,3,4,0, 6,6,1,4,2,4,4,0,2,3,3,1,3,4, 6,6,1,4,2,4,4,0,2,1,3,1,2,3, 6,6,2,0,5,4,4,3,5,3,4,0,2,4, 6,6,3,2,4,3,0,4,1,0,2,1,0,3, 6,6,4,1,3,1,4,2,3,2,2,0,1,0, 6,6,5,2,5,3,5,4,3,4,5,1,5,0, 6,6,4,3,4,2,4,0,1,4,3,0,5,3, 6,6,4,3,3,5,5,4,5,1,3,2,4,0, 6,6,4,2,1,2,4,3,4,1,4,0,0,5, 6,6,1,2,3,1,0,3,2,0,4,0,5,0, 6,6,2,0,4,2,1,4,2,1,3,1,5,3, 6,6,1,2,3,1,0,3,2,0,4,0,5,3, 6,6,5,3,2,5,2,0,4,2,4,3,3,1, 6,6,0,2,3,4,1,0,5,3,4,5,3,0, 6,6,1,2,3,0,5,3,4,5,0,4,5,0, 6,6,4,3,1,2,4,0,3,2,3,1,5,0, 6,6,1,4,2,4,4,0,0,5,3,1,2,3, 6,6,0,1,1,2,2,3,3,4,0,4,1,5, 6,6,0,1,1,2,2,3,3,4,4,5,0,5, 6,6,1,3,2,1,3,2,0,4,5,0,4,5, 6,7,0,1,1,2,0,2,3,0,3,1,3,2,0,5, 6,7,1,4,2,4,2,1,3,1,2,3,2,0,0,1, 6,7,0,1,1,2,2,3,3,4,0,4,1,3,4,1, 6,7,0,1,3,2,0,2,3,0,3,1,5,1,5,2, 6,7,1,4,2,4,2,3,0,4,3,1,4,5,3,4, 6,7,1,0,4,1,2,4,3,2,5,1,2,5,1,2, 6,7,0,4,2,0,1,2,3,1,5,3,3,0,2,3, 6,7,1,4,2,4,2,3,2,1,3,1,4,5,0,4, 6,7,1,0,4,1,2,4,3,2,5,1,2,5,4,5, 6,7,0,1,1,2,0,2,3,0,3,1,3,2,5,4, 6,7,0,5,4,0,5,4,0,2,3,0,3,2,0,1, 6,7,0,1,1,2,2,3,3,4,0,4,1,5,4,1, 6,7,0,1,4,0,1,4,0,2,3,0,3,2,3,5, 6,7,1,4,2,4,4,0,0,5,3,1,2,3,3,4, 6,7,2,0,3,2,4,3,5,4,2,5,1,2,4,1, 6,7,1,5,0,1,4,0,3,4,2,3,1,2,0,3, 6,7,1,4,2,4,4,0,0,5,3,1,2,3,2,1, 6,7,0,1,1,2,2,3,3,4,0,4,0,2,5,1, 6,7,2,0,4,1,1,2,5,4,2,5,3,1,5,3, 6,7,5,0,3,5,2,3,0,2,1,3,4,1,3,4, 6,7,1,3,2,1,0,2,5,0,4,5,3,4,2,3, 6,7,0,1,1,2,2,3,3,4,4,5,0,5,0,3, 6,7,4,3,0,4,1,0,2,1,3,2,0,5,5,3, 6,7,1,2,0,1,2,0,3,0,4,3,5,4,3,5, 6,8,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1, 6,8,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3, 6,8,0,1,1,2,0,2,3,0,3,1,3,2,5,0,0,4, 6,8,1,2,3,1,0,3,1,0,2,0,3,2,5,3,4,0, 6,8,0,1,2,4,0,2,5,2,3,1,3,2,2,1,4,1, 6,8,0,1,1,2,2,3,3,4,0,4,1,3,4,1,1,5, 6,8,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4, 6,8,0,1,2,5,0,2,4,0,3,1,3,2,2,1,5,1, 6,8,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0, 6,8,0,1,2,5,0,2,4,0,3,1,3,2,3,0,5,1, 6,8,2,0,3,2,4,3,5,4,2,5,1,2,4,1,5,3, 6,8,0,1,1,2,0,2,3,0,3,1,3,2,0,5,5,4, 6,8,0,1,2,5,0,2,4,0,3,1,3,2,5,1,5,3, 6,8,1,4,2,4,2,3,0,4,3,1,4,5,0,5,3,4, 6,8,0,1,1,2,2,3,3,4,0,4,5,0,5,2,0,2, 6,8,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3, 6,8,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2, 6,8,1,3,2,1,0,2,5,0,4,5,3,4,1,4,0,1, 6,8,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0, 6,8,1,4,2,4,2,3,0,4,3,1,4,5,0,5,2,1, 6,8,0,1,1,2,2,3,3,4,0,4,4,5,5,3,1,5, 6,8,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,1, 6,8,0,1,1,2,2,3,3,4,0,4,1,5,5,2,5,0, 6,8,0,1,1,2,2,3,3,4,4,5,0,5,4,1,5,2, 6,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3, 6,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,2, 6,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4, 6,9,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,4,5, 6,9,2,0,4,1,1,2,5,4,2,5,3,1,5,3,3,2,4,3, 6,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,5, 6,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5, 6,9,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0, 6,9,1,3,2,1,0,2,5,0,4,5,3,4,0,4,1,0,4,1, 6,9,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1, 6,9,0,1,1,2,0,2,3,0,3,1,3,2,5,4,4,0,5,0, 6,9,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5, 6,9,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0, 6,9,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4, 6,9,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1, 6,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,2,0, 6,9,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3, 6,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1, 6,9,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2, 6,9,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2, 6,9,0,1,1,2,2,3,3,4,4,5,0,5,0,3,5,2,4,1, 6,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2, 6,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,4,5, 6,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,5, 6,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,1,0, 6,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5, 6,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,2,4, 6,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2, 6,10,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2, 6,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2, 6,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1, 6,10,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3, 6,10,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4, 6,10,0,1,1,2,2,3,3,4,4,5,0,5,2,4,0,2,1,3,5,1, 6,10,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,3,2,0,3, 6,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0, 6,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2,1,5, 6,11,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3, 6,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5, 6,11,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,0,2, 6,11,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0,5,1, 6,11,1,3,4,1,3,4,2,3,0,2,4,0,5,4,2,5,4,2,0,5,1,5, 6,11,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1, 6,11,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2, 6,11,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,0,3, 6,12,0,1,1,2,0,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,4,3, 6,12,3,2,1,3,2,1,0,2,5,0,2,5,2,4,5,1,0,3,1,4,0,1,0,4, 6,12,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,4,5, 6,12,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,2,3, 6,12,0,1,1,2,0,2,3,2,3,1,4,0,2,4,5,1,0,5,4,5,3,4,5,3, 6,13,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,2,3,0,4, 6,13,0,1,1,2,0,2,3,2,3,1,4,0,2,4,5,1,0,5,4,5,3,4,5,3,3,0, 6,14,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,1,3,2,0,4,0,5,3, 6,15,0,1,0,2,0,3,0,4,0,5,1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5, 7,0, 7,1,6,5, 7,2,2,3,1,2, 7,2,5,4,6,0, 7,3,0,4,4,2,2,0, 7,3,0,1,0,6,0,5, 7,3,5,4,6,0,5,6, 7,3,3,2,1,2,5,6, 7,3,3,1,5,6,0,4, 7,4,2,5,6,2,5,6,1,2, 7,4,1,2,4,1,5,4,2,5, 7,4,1,0,5,1,1,2,4,1, 7,4,1,0,2,1,5,2,6,2, 7,4,3,4,2,3,1,2,0,1, 7,4,4,2,0,4,2,0,5,6, 7,4,0,1,6,0,0,5,4,2, 7,4,3,1,5,4,6,5,0,6, 7,4,0,4,3,0,2,5,6,2, 7,4,2,3,1,2,6,0,5,4, 7,5,0,4,3,0,1,3,4,1,1,0, 7,5,2,5,6,2,5,6,4,2,3,2, 7,5,4,2,4,0,2,0,5,4,6,0, 7,5,2,5,6,2,5,6,1,2,0,1, 7,5,4,1,0,4,3,0,1,3,2,1, 7,5,1,2,0,1,4,0,3,4,2,3, 7,5,5,1,5,0,2,5,3,5,4,5, 7,5,1,5,6,1,1,0,2,1,3,2, 7,5,1,5,4,1,2,3,6,2,2,1, 7,5,1,5,6,1,1,2,2,3,4,3, 7,5,2,1,3,2,4,3,5,4,3,6, 7,5,6,5,2,6,1,2,5,2,3,4, 7,5,4,3,5,4,6,5,0,6,1,0, 7,5,0,4,3,0,2,5,6,2,5,6, 7,5,4,1,5,2,6,5,3,6,2,3, 7,5,1,4,3,1,1,0,2,1,6,5, 7,5,0,4,3,0,1,0,2,1,6,5, 7,5,0,4,3,0,2,1,5,2,6,2, 7,5,6,5,3,4,2,3,1,2,0,1, 7,5,2,3,1,2,6,0,5,6,5,4, 7,5,0,1,4,6,5,4,3,2,6,5, 7,6,1,5,6,1,5,6,2,5,1,2,6,2, 7,6,1,4,3,1,2,3,4,2,1,0,2,1, 7,6,0,4,3,0,1,3,2,1,1,4,3,4, 7,6,5,2,4,5,2,4,3,2,6,3,2,6, 7,6,1,2,4,1,5,4,2,5,0,1,4,0, 7,6,1,2,5,1,4,5,2,4,0,2,5,0, 7,6,2,5,6,2,5,6,2,4,1,2,3,2, 7,6,1,4,3,1,2,3,1,2,2,5,6,2, 7,6,5,4,6,5,1,6,5,1,3,6,0,1, 7,6,6,5,1,6,5,1,3,1,0,3,1,4, 7,6,0,4,3,0,2,3,4,2,2,5,6,2, 7,6,1,4,3,1,2,3,1,2,2,5,6,5, 7,6,2,3,1,2,3,6,5,4,6,5,5,2, 7,6,2,5,6,2,5,6,1,4,3,1,2,1, 7,6,4,5,0,4,3,0,2,3,4,2,6,3, 7,6,0,4,3,0,1,3,6,5,1,4,1,0, 7,6,1,4,3,1,2,3,5,2,6,5,2,6, 7,6,6,3,5,6,4,5,1,4,2,1,5,2, 7,6,1,0,3,1,6,3,5,6,4,5,1,4, 7,6,0,1,1,2,2,3,3,4,4,5,0,5, 7,6,0,4,3,0,4,3,2,5,6,2,5,6, 7,6,6,3,0,6,6,2,5,6,6,1,4,6, 7,6,2,4,5,2,2,3,6,2,1,2,1,0, 7,6,1,0,2,1,5,2,1,4,3,1,6,2, 7,6,1,0,2,1,3,6,1,3,4,1,5,4, 7,6,1,0,2,1,5,2,6,5,1,4,3,1, 7,6,1,0,2,4,5,2,6,5,2,6,3,2, 7,6,4,0,1,4,3,1,2,1,5,2,6,2, 7,6,6,5,1,2,0,1,2,0,3,2,0,4, 7,6,0,4,3,0,1,0,2,1,5,2,6,2, 7,6,1,0,3,1,6,3,2,6,4,1,5,4, 7,6,2,5,6,2,4,2,1,4,3,1,0,3, 7,6,0,4,3,0,2,3,4,2,1,2,6,5, 7,6,0,4,3,0,2,1,5,2,6,5,2,6, 7,6,3,4,1,0,2,1,5,2,6,5,2,6, 7,6,4,5,0,4,3,0,6,3,1,0,2,1, 7,6,2,5,6,2,5,6,1,4,3,1,1,0, 7,6,4,5,3,4,2,3,1,2,0,1,6,0, 7,6,6,4,5,6,4,5,2,3,1,2,0,1, 7,6,0,1,4,0,2,3,5,2,6,5,3,6, 7,6,1,2,0,1,4,0,3,4,2,3,6,5, 7,7,1,4,3,1,2,3,4,2,1,0,2,1,3,4, 7,7,1,2,5,1,4,5,2,4,0,2,5,0,5,2, 7,7,0,1,1,2,2,3,3,4,0,4,1,3,4,1, 7,7,1,2,5,1,4,5,2,4,0,2,5,0,1,0, 7,7,0,4,3,0,2,3,4,2,2,5,6,2,2,0, 7,7,1,4,3,1,2,3,4,2,1,0,2,1,2,6, 7,7,1,4,3,1,2,3,4,2,1,0,3,4,6,3, 7,7,0,4,3,0,2,3,4,2,2,5,6,2,3,4, 7,7,0,4,3,0,1,3,3,6,1,4,1,0,5,4, 7,7,0,4,3,0,1,3,6,5,1,4,1,0,3,4, 7,7,5,2,4,5,2,4,3,2,6,3,2,6,2,1, 7,7,0,1,1,2,2,3,3,4,0,4,0,2,2,5, 7,7,5,2,4,5,2,4,3,2,6,3,2,6,3,1, 7,7,1,4,3,1,2,3,4,2,2,0,2,1,6,0, 7,7,1,2,5,1,4,5,2,4,0,2,5,0,3,5, 7,7,0,1,1,2,2,3,3,4,0,4,0,2,3,5, 7,7,0,1,1,2,2,3,3,4,0,4,0,2,1,5, 7,7,3,2,4,3,3,5,2,4,5,2,6,1,6,4, 7,7,1,2,5,1,4,5,2,4,0,2,5,0,0,3, 7,7,3,4,1,3,2,1,6,2,5,6,1,5,4,1, 7,7,0,1,4,0,1,4,2,1,3,2,5,3,4,5, 7,7,6,3,5,6,1,5,2,1,3,2,4,2,5,4, 7,7,1,2,4,1,5,4,6,5,3,6,2,3,5,2, 7,7,4,1,3,4,1,3,2,1,6,2,5,6,2,5, 7,7,3,0,6,3,0,6,1,0,0,2,5,0,0,4, 7,7,1,5,6,1,1,2,3,1,4,3,1,4,4,0, 7,7,5,0,6,5,0,6,5,2,1,5,6,3,4,6, 7,7,4,1,0,4,1,0,2,1,0,3,6,0,4,5, 7,7,5,2,6,5,2,6,2,4,3,2,1,0,2,1, 7,7,4,1,0,4,3,0,1,3,2,1,1,5,6,1, 7,7,1,0,4,1,0,4,5,4,2,1,3,2,6,1, 7,7,0,1,4,0,1,4,2,1,3,2,5,4,6,4, 7,7,2,3,5,2,6,5,3,6,1,2,4,5,0,5, 7,7,0,4,3,0,1,3,4,1,1,0,2,1,6,5, 7,7,2,5,6,2,5,6,4,2,1,2,0,1,3,1, 7,7,2,5,6,2,4,2,1,4,3,1,2,3,0,1, 7,7,6,2,5,6,2,5,1,2,0,1,4,1,3,1, 7,7,0,4,3,0,1,3,4,1,5,4,2,1,6,3, 7,7,2,5,6,2,5,6,4,5,3,6,1,2,0,1, 7,7,2,5,6,2,1,4,1,2,0,1,4,0,0,3, 7,7,6,5,1,2,4,1,0,4,3,0,1,3,3,4, 7,7,4,1,0,4,1,0,3,6,2,3,0,2,5,0, 7,7,4,1,0,4,3,0,1,3,2,1,5,2,6,1, 7,7,4,1,0,4,1,0,2,3,0,2,5,0,6,5, 7,7,0,1,5,0,6,5,3,6,2,3,0,2,4,0, 7,7,1,0,4,1,2,4,3,2,4,3,0,4,6,5, 7,7,3,6,2,3,1,2,0,1,4,0,1,4,5,4, 7,7,1,0,5,1,6,5,2,6,1,2,3,2,4,3, 7,7,2,3,1,2,0,1,4,0,5,4,6,5,4,1, 7,7,5,2,6,5,2,6,1,2,4,1,0,4,3,1, 7,7,2,3,1,2,0,1,4,0,5,4,6,5,5,2, 7,7,1,4,0,1,2,0,3,2,5,3,0,5,6,3, 7,7,2,1,3,2,6,3,5,6,0,5,2,0,5,4, 7,7,5,2,6,5,2,6,1,2,0,1,4,0,3,0, 7,7,4,1,0,4,3,0,1,3,2,1,5,2,6,2, 7,7,1,0,2,1,5,2,4,5,0,4,4,1,6,3, 7,7,2,5,6,2,0,4,3,0,1,3,4,1,1,0, 7,7,6,5,0,4,3,0,1,3,4,1,2,4,3,2, 7,7,2,1,5,2,4,5,0,4,3,0,6,3,2,6, 7,7,4,0,3,4,1,3,2,1,5,2,6,5,2,6, 7,7,6,5,2,6,1,2,4,1,0,4,3,0,1,3, 7,7,4,1,0,4,2,0,3,2,6,3,5,6,0,5, 7,7,0,4,3,0,4,3,2,1,5,2,6,5,2,6, 7,7,0,1,1,2,2,3,3,4,4,5,5,6,0,6, 7,7,1,0,4,1,0,4,5,2,6,5,3,6,2,3, 7,8,0,1,4,0,5,4,2,5,1,2,5,1,4,1,2,4, 7,8,4,1,5,4,2,5,1,2,0,1,5,0,0,4,2,0, 7,8,0,4,3,0,1,3,4,1,1,0,3,4,5,1,6,1, 7,8,4,1,5,4,2,5,1,2,5,1,6,5,2,4,3,2, 7,8,1,3,0,1,4,0,2,4,1,2,4,1,5,4,1,5, 7,8,2,0,3,2,6,3,5,6,0,5,3,0,0,6,4,0, 7,8,1,0,2,1,5,2,4,5,0,4,2,0,5,0,6,5, 7,8,1,0,2,1,3,2,1,3,4,3,2,4,5,2,3,5, 7,8,2,0,3,2,6,3,5,6,0,5,3,0,6,0,4,5, 7,8,1,0,2,1,4,3,1,5,4,1,2,4,5,2,3,5, 7,8,3,5,2,1,4,3,1,5,4,1,2,4,5,2,4,6, 7,8,0,4,3,0,1,3,4,1,1,0,3,4,2,1,5,2, 7,8,3,5,2,1,4,3,1,5,4,1,2,4,5,2,0,3, 7,8,4,0,2,4,0,2,3,0,2,3,5,2,6,5,2,6, 7,8,3,2,6,3,5,6,2,5,0,2,5,0,4,5,2,4, 7,8,0,5,4,0,2,4,5,2,1,5,4,1,3,4,5,3, 7,8,2,3,1,2,4,1,5,4,1,5,5,2,6,5,3,6, 7,8,5,2,4,5,0,4,3,0,6,3,2,6,4,2,3,2, 7,8,0,4,3,0,1,3,4,1,2,4,3,2,5,4,2,5, 7,8,5,6,2,5,6,2,3,2,4,3,0,4,3,0,2,4, 7,8,1,0,5,0,3,2,1,3,5,2,6,1,6,2,6,5, 7,8,5,4,6,5,3,6,0,3,4,0,2,4,3,2,0,2, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,4,2,1,5, 7,8,5,0,6,2,0,6,1,0,2,1,5,2,4,5,4,6, 7,8,0,4,3,0,1,3,4,1,1,0,2,1,1,5,6,1, 7,8,0,2,4,0,1,4,0,1,3,0,1,3,5,1,6,1, 7,8,4,2,0,4,3,0,1,3,4,1,1,0,1,5,6,1, 7,8,0,4,3,0,4,3,1,4,3,1,1,5,2,1,6,1, 7,8,2,1,0,2,3,0,5,3,2,5,3,2,4,3,6,5, 7,8,4,2,0,4,3,0,1,3,4,1,3,4,1,5,6,1, 7,8,2,1,0,2,3,0,5,3,2,5,6,5,4,3,5,0, 7,8,1,0,2,1,3,2,1,3,4,2,3,4,4,5,6,4, 7,8,6,5,1,2,4,1,0,4,3,0,1,3,0,1,3,4, 7,8,0,1,6,5,2,3,6,4,6,3,6,2,6,0,6,1, 7,8,6,4,1,2,2,3,6,5,4,5,6,2,6,0,6,1, 7,8,0,1,1,2,2,3,6,5,6,4,6,3,6,0,6,2, 7,8,0,4,3,0,1,3,4,1,1,0,6,1,5,1,2,5, 7,8,3,0,2,3,4,2,0,4,1,0,2,1,5,2,6,2, 7,8,2,1,3,2,6,3,5,6,0,5,2,0,5,2,4,5, 7,8,1,0,2,1,3,2,4,3,5,2,1,5,6,1,2,6, 7,8,2,5,4,2,1,4,3,1,0,3,1,0,2,1,6,2, 7,8,4,5,0,4,3,0,2,3,4,2,1,4,3,1,6,3, 7,8,0,1,4,0,1,4,2,1,4,2,5,4,1,5,6,3, 7,8,0,1,2,0,3,2,4,3,1,4,2,1,1,6,5,0, 7,8,4,5,0,4,1,0,4,1,3,0,1,3,6,1,2,6, 7,8,2,5,4,2,0,4,1,0,4,1,3,0,1,3,6,1, 7,8,1,6,2,1,0,2,1,0,4,1,3,4,2,3,4,5, 7,8,0,1,2,0,3,2,4,3,1,4,2,1,1,6,5,3, 7,8,0,4,3,0,4,3,1,4,3,1,5,1,6,2,1,6, 7,8,2,3,1,2,0,1,5,0,4,5,0,4,2,0,6,5, 7,8,4,5,0,4,3,0,1,3,4,1,2,4,3,2,6,2, 7,8,2,3,1,2,0,1,4,0,5,4,4,1,2,6,5,2, 7,8,0,1,1,2,2,3,6,3,4,5,6,2,6,0,6,1, 7,8,4,1,0,4,3,0,1,3,0,1,2,1,5,2,6,2, 7,8,0,1,1,2,2,3,6,5,4,5,6,2,6,4,6,1, 7,8,0,1,4,0,0,2,5,0,6,5,3,6,2,3,5,2, 7,8,0,4,3,0,2,3,4,2,1,4,3,1,2,5,6,2, 7,8,4,5,3,4,1,3,2,1,6,2,4,6,3,2,0,1, 7,8,1,0,2,6,3,2,4,3,5,2,1,5,6,1,6,5, 7,8,2,3,1,2,0,1,4,0,5,4,6,5,5,2,4,1, 7,8,4,1,0,4,3,0,1,3,3,4,2,1,2,5,6,2, 7,8,0,6,4,0,1,4,3,1,0,3,2,4,3,2,5,2, 7,8,0,4,3,0,1,3,4,1,2,4,3,2,1,0,6,5, 7,8,0,1,4,0,3,2,6,3,5,6,2,5,6,2,3,5, 7,8,5,2,6,5,2,6,4,2,0,4,3,0,2,3,1,2, 7,8,2,0,1,2,0,1,5,0,4,5,0,4,6,0,3,6, 7,8,0,1,2,0,3,2,2,1,1,4,5,4,5,3,1,6, 7,8,1,6,2,1,0,2,1,0,4,1,3,4,2,3,5,6, 7,8,6,1,0,6,1,0,5,1,0,5,2,1,3,2,4,3, 7,8,6,5,2,6,1,2,4,1,3,4,0,3,4,0,2,4, 7,8,1,6,0,1,5,0,1,5,3,0,4,3,2,4,0,2, 7,8,2,6,4,2,0,4,1,0,4,1,3,4,5,3,2,5, 7,8,1,0,2,1,6,2,5,6,1,5,4,1,3,4,2,3, 7,8,6,1,4,3,1,0,5,1,3,2,2,1,4,6,5,4, 7,8,4,2,0,4,1,0,4,1,3,4,6,3,5,6,3,5, 7,8,4,1,2,4,0,2,6,0,3,6,0,3,5,0,4,5, 7,8,5,6,4,5,0,4,3,0,2,3,4,2,1,4,3,1, 7,8,6,3,5,6,4,5,0,4,1,0,2,1,5,2,4,1, 7,8,0,1,2,0,3,2,2,1,1,4,5,4,5,3,4,6, 7,8,4,0,3,4,2,3,6,2,5,6,1,5,4,1,2,1, 7,8,6,1,0,6,4,3,5,1,0,5,2,1,3,2,5,6, 7,8,6,2,5,6,3,5,6,3,4,3,0,4,1,0,4,1, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,0,6,5,1, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,0,6,4,2, 7,8,0,1,2,0,3,2,4,3,1,4,2,1,5,6,0,5, 7,8,4,0,2,4,3,2,6,3,5,6,4,5,1,2,5,1, 7,8,5,1,2,4,3,2,0,3,5,0,4,5,1,2,0,6, 7,8,5,6,2,5,4,2,0,4,3,0,2,3,1,4,3,1, 7,8,0,4,1,0,4,1,3,4,5,3,6,5,2,6,4,2, 7,8,0,1,6,5,2,3,3,4,6,4,0,5,6,2,6,1, 7,8,1,2,0,1,4,0,5,4,2,5,3,2,6,3,5,6, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,2,6,1,6, 7,8,6,2,5,6,2,5,1,2,4,1,0,4,3,0,1,3, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,6,5,6,1, 7,8,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,3, 7,8,0,4,1,0,3,2,1,4,2,5,5,3,6,4,6,3, 7,8,0,4,3,0,1,3,4,1,1,0,6,2,5,6,2,5, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3, 7,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,2, 7,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4, 7,9,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,4,5, 7,9,2,0,4,1,1,2,5,4,2,5,3,1,5,3,3,2,4,3, 7,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,5, 7,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5, 7,9,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0, 7,9,1,3,2,1,0,2,5,0,4,5,3,4,0,4,1,0,4,1, 7,9,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,5,4,4,0,5,0, 7,9,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5, 7,9,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0, 7,9,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4, 7,9,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1, 7,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,2,0, 7,9,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2, 7,9,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,0,3,5,2,4,1, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,5,0,0,4,0,6, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,5,0,0,4,2,6, 7,9,1,2,3,1,0,3,1,0,2,0,3,2,5,3,4,0,1,6, 7,9,0,1,2,4,0,2,3,1,3,2,2,1,4,1,5,2,2,6, 7,9,0,1,2,4,0,2,5,2,3,1,3,2,2,1,4,1,1,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,1,5,1,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,1,5,4,6, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,2,1,5,1,1,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,6, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,2,1,5,1,0,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0,1,6, 7,9,2,0,3,2,4,3,5,4,2,5,1,2,4,1,5,3,2,6, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,3,0,5,1,0,6, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,5,0,0,4,5,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,2,6, 7,9,2,0,3,2,4,3,5,4,2,5,1,2,4,1,5,3,5,6, 7,9,1,2,3,1,0,3,1,0,2,0,3,2,4,0,6,5,6,3, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0,0,6, 7,9,0,1,1,2,2,3,3,4,0,4,3,6,5,4,0,3,2,4, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,2,1,5,1,5,6, 7,9,2,0,3,2,4,3,5,4,2,5,1,2,4,1,5,3,4,6, 7,9,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0,2,6, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,3,0,5,1,5,6, 7,9,0,1,2,5,0,2,5,4,3,1,3,2,3,0,5,1,2,6, 7,9,0,1,2,5,0,2,4,0,3,1,3,2,5,1,5,3,0,6, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,0,5,5,4,5,6, 7,9,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,3,4,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,5,0,5,2,0,2,0,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,3,4,3,6, 7,9,0,1,2,4,0,2,5,2,3,1,3,2,2,1,4,1,5,6, 7,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,2,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,6,5,6,1, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,3,4,2,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,3,4,0,6, 7,9,1,3,2,1,0,2,5,0,6,5,3,6,1,6,0,1,1,4, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,0,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,2,1,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,5,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,4,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,5,6, 7,9,1,3,2,1,0,2,5,0,6,5,3,6,1,6,0,1,0,4, 7,9,0,1,1,2,2,3,3,4,0,4,5,0,5,2,0,2,1,6, 7,9,0,1,1,2,2,3,3,4,0,4,5,0,5,2,0,2,4,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,2,1,2,6, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,3,6, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,2,6, 7,9,0,1,2,5,0,2,5,1,3,1,3,2,2,1,6,0,6,4, 7,9,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,1,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,0,5,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,0,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,3,6, 7,9,1,3,2,1,0,2,5,0,6,5,3,6,1,6,0,1,2,4, 7,9,0,1,1,2,2,3,3,4,0,4,4,5,5,3,1,5,3,6, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,1,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,1,4,6, 7,9,0,1,2,5,0,2,5,1,3,1,3,2,3,0,6,4,6,0, 7,9,0,1,1,2,2,3,3,4,0,4,1,5,5,2,5,0,1,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,2,1,6,0, 7,9,5,3,3,2,4,3,5,4,2,5,1,2,4,1,6,0,6,2, 7,9,0,1,1,2,2,3,3,4,0,4,1,5,5,2,5,0,0,6, 7,9,0,1,1,2,2,3,3,4,0,4,4,5,5,3,1,5,5,6, 7,9,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,4,6, 7,9,1,3,2,1,0,2,5,0,6,5,3,6,1,6,0,1,5,4, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,4,1,5,2,5,6, 7,9,0,1,1,2,2,3,3,4,0,4,4,5,5,3,1,5,1,6, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,2,1,3,6, 7,9,0,1,1,2,0,2,3,0,3,1,3,2,0,5,5,4,4,6, 7,9,0,1,1,2,2,3,3,4,0,4,4,5,5,3,1,5,0,6, 7,9,0,1,1,2,2,3,3,4,0,4,1,5,5,2,5,0,4,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,1,0,6, 7,9,0,1,2,5,0,2,5,3,3,1,3,2,5,1,6,4,6,0, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,4,1,5,2,0,6, 7,9,6,3,1,2,6,5,3,4,6,4,0,5,6,0,6,1,6,2, 7,9,0,1,2,0,3,2,4,3,1,4,2,1,6,2,5,6,2,5, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,3,4,6,5,6,0, 7,9,1,4,2,4,2,3,0,4,3,1,4,5,0,5,6,4,6,3, 7,9,4,1,5,4,6,5,3,6,2,3,1,2,5,2,0,5,2,0, 7,9,4,1,3,1,2,3,4,0,5,0,5,2,5,4,6,4,5,6, 7,9,1,0,2,1,6,2,3,6,5,3,4,5,3,4,2,3,0,2, 7,9,0,2,5,0,1,5,2,1,4,2,5,4,6,5,3,6,2,3, 7,9,0,1,1,2,2,3,3,4,4,5,5,6,0,6,1,3,4,1, 7,9,0,1,1,2,2,3,3,4,0,4,5,4,5,1,6,1,0,6, 7,9,0,4,1,0,4,1,3,4,2,3,6,2,5,6,1,5,2,1, 7,9,0,1,2,0,3,2,4,3,1,4,2,1,5,3,6,5,3,6, 7,9,6,5,3,6,2,3,0,4,0,5,1,0,2,0,1,2,5,4, 7,9,0,1,1,2,2,3,3,4,0,4,5,3,5,1,6,1,0,6, 7,9,5,2,6,5,3,6,2,3,0,2,4,0,5,4,1,5,0,1, 7,9,2,4,1,2,4,1,5,4,0,5,1,0,6,4,3,6,2,3, 7,9,6,2,5,6,2,5,1,2,0,1,4,0,1,4,3,1,0,3, 7,9,0,5,6,0,1,6,4,1,2,4,3,2,1,3,5,1,6,5, 7,9,6,5,3,6,2,3,5,2,0,5,1,0,4,1,0,4,2,0, 7,9,0,4,3,0,1,3,4,1,2,4,6,2,5,6,2,5,3,2, 7,9,1,0,4,1,5,4,0,5,6,0,3,6,2,3,0,2,3,4, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,1,6,3, 7,9,0,1,1,2,2,3,0,3,4,1,5,4,5,3,6,0,6,4, 7,9,0,1,4,0,1,4,2,1,5,2,4,5,6,5,3,6,2,3, 7,9,1,0,6,3,0,4,5,0,3,5,5,6,1,2,1,4,6,2, 7,9,6,2,5,6,2,5,1,2,0,3,4,0,1,4,3,1,3,4, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,6,1,5,6,6,0, 7,9,0,4,1,0,2,1,3,2,0,3,2,4,5,4,6,5,3,6, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,4,2,6,1,5,6, 7,9,0,1,1,2,2,3,3,4,0,4,5,3,5,4,6,1,6,5, 7,9,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,4,6,2, 7,9,0,4,3,0,4,3,6,1,5,6,1,5,2,1,5,2,6,2, 7,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2, 7,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,4, 7,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,1,0, 7,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,2,4, 7,10,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1, 7,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2, 7,10,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,2,4,0,2,1,3,5,1, 7,10,0,1,1,2,3,4,0,2,3,0,2,4,5,2,1,5,4,1,3,5, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,2,2,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,2,1,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4,1,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4,0,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4,3,6, 7,10,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,4,5,4,6, 7,10,2,0,4,1,1,2,5,4,2,5,3,1,5,3,3,2,4,3,3,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,5,2,6, 7,10,2,0,4,1,1,2,5,4,2,5,3,1,5,3,3,2,4,3,2,6, 7,10,2,3,1,2,4,1,5,4,2,5,0,2,4,0,0,1,5,0,6,5, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,0,4,5,6, 7,10,2,0,4,1,1,2,5,4,2,5,3,1,5,3,3,2,4,3,4,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,4,5,6,5, 7,10,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,6,5, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0,0,6, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0,2,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,1,6, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0,3,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,0,4,1,0,4,1,0,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1,1,6, 7,10,0,1,1,2,0,2,3,0,3,1,3,2,5,4,4,0,5,0,0,6, 7,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,3,6, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0,5,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,3,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1,0,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,2,0,5,3,2,3,6,2, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,6,4,6,2, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,2,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1,5,6, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,3,0,4,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,3,6, 7,10,0,1,1,2,0,2,3,0,3,1,3,2,5,4,4,0,5,0,2,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,2,0,5,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,2,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,2,0,5,3,2,3,0,6, 7,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,1,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,4,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,6,4,6,0, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,5,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,0,4,1,0,4,1,5,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,2,0,0,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,4,1,1,0,5,1,2,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2,2,6, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,5,6, 7,10,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1,0,6, 7,10,0,1,1,2,0,2,3,0,3,1,3,2,5,4,4,0,5,0,5,6, 7,10,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,6,5,6,4, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,1,6, 7,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,4,6, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,4,6, 7,10,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,2,6, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,0,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2,5,6, 7,10,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1,1,6, 7,10,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,3,6, 7,10,4,3,4,1,1,2,5,4,2,5,3,1,5,3,3,2,6,0,6,2, 7,10,1,0,2,1,3,2,4,3,5,4,1,5,6,1,4,6,2,6,5,2, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2,0,6, 7,10,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1,3,6, 7,10,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1,2,6, 7,10,0,1,2,5,0,2,3,0,3,1,3,2,2,1,5,1,6,5,6,4, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,1,6, 7,10,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,6, 7,10,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,2,0,1,6, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,1,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,0,3,4,2,5,2,1,6, 7,10,0,1,1,2,2,3,3,4,0,4,3,0,5,2,5,0,5,1,4,6, 7,10,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2,4,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,0,3,5,2,4,1,0,6, 7,10,4,0,1,4,3,1,2,3,1,2,6,1,0,6,5,0,1,5,0,1, 7,10,3,2,6,3,5,6,0,5,2,0,5,2,1,5,2,1,4,2,5,4, 7,10,2,0,1,2,3,1,0,3,6,0,1,6,5,1,0,5,4,0,1,4, 7,10,6,4,1,2,6,5,3,4,4,5,0,5,6,0,6,1,6,2,6,3, 7,10,0,1,6,5,2,3,3,4,6,4,0,5,6,0,6,1,6,2,6,3, 7,10,0,1,2,0,3,2,4,3,1,4,2,1,0,5,5,2,6,1,2,6, 7,10,0,1,2,0,3,2,4,3,1,4,2,1,5,0,5,2,6,2,0,6, 7,10,6,4,1,2,6,5,3,4,4,5,0,5,6,3,6,1,6,2,0,4, 7,10,1,0,2,1,0,2,3,2,4,3,2,4,5,2,4,5,6,4,1,6, 7,10,0,1,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,5,2,6, 7,10,0,2,5,0,4,5,2,4,1,2,5,1,6,5,3,6,2,3,2,6, 7,10,0,1,2,0,3,2,4,3,1,4,2,1,5,1,0,5,6,0,2,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,2,6,4,0,2,4,0, 7,10,0,4,3,0,2,3,5,2,6,5,2,6,4,2,1,4,3,1,4,3, 7,10,1,6,2,1,0,2,1,0,4,1,3,4,2,3,5,6,4,5,3,1, 7,10,6,5,1,2,2,3,3,4,4,5,0,5,6,0,6,1,6,2,6,4, 7,10,0,1,6,5,2,3,3,4,6,4,0,5,6,0,6,1,6,2,5,3, 7,10,0,1,1,2,2,3,5,4,0,4,5,0,5,3,5,2,6,5,6,1, 7,10,0,3,2,0,1,2,3,1,4,3,2,4,0,4,6,0,5,6,0,5, 7,10,0,3,2,0,1,2,3,1,4,3,0,5,0,4,6,0,5,6,1,4, 7,10,0,1,6,5,2,3,3,4,6,4,0,5,6,0,6,1,6,2,4,2, 7,10,1,2,5,1,6,5,2,6,1,6,5,2,4,1,0,4,3,0,1,3, 7,10,4,2,6,2,5,3,4,1,2,0,6,3,5,2,0,1,0,4,6,0, 7,10,4,2,3,6,5,3,5,1,2,0,6,0,5,2,1,4,0,4,5,4, 7,10,4,0,5,4,4,1,2,1,3,2,0,3,3,4,5,3,6,1,6,5, 7,10,0,4,1,0,2,1,4,2,3,4,5,3,4,5,5,2,6,3,2,6, 7,10,1,6,2,1,0,2,1,0,4,1,3,4,2,3,5,6,4,5,4,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,3,6,1,6,5,5,1, 7,10,1,0,4,1,0,4,2,0,3,2,6,3,5,6,0,5,5,2,6,2, 7,10,0,1,1,2,2,3,3,4,0,4,5,3,5,1,5,4,6,1,5,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,2,4,4,1,6,1,6,5, 7,10,0,1,2,0,3,2,4,3,1,4,2,1,5,3,2,5,6,1,4,6, 7,10,0,1,1,2,2,3,3,4,0,4,5,2,5,4,6,5,6,0,0,2, 7,10,2,0,5,2,1,5,0,1,3,0,5,3,6,5,4,6,0,4,4,3, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,4,2,1,5,6,2,6,5, 7,10,5,0,6,5,2,6,3,2,0,3,4,0,2,4,4,3,1,4,3,1, 7,10,0,1,1,2,2,3,3,4,0,4,6,3,5,6,3,5,4,5,4,6, 7,10,5,2,2,1,3,2,4,3,1,4,5,0,6,1,6,0,1,5,2,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,2,6,4,4,2,5,1, 7,10,4,2,2,3,4,1,0,1,3,0,6,4,0,6,5,0,4,5,1,5, 7,10,2,1,5,2,3,5,0,3,4,0,6,4,3,6,1,3,4,1,5,4, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,6,5,6,3, 7,10,0,1,4,0,1,4,2,1,5,2,4,5,6,5,3,6,2,3,5,3, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,5,6,1,6,2,4,2, 7,10,0,1,1,2,2,3,3,4,0,4,5,0,5,3,5,2,6,5,6,4, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,3,6,2,4,0, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,4,6,5,6,3, 7,10,0,5,6,0,1,6,0,1,1,5,2,1,3,2,4,3,6,4,4,5, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,5,6,4,2,0, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,1,6,5,6,3, 7,10,2,1,2,0,3,2,4,3,1,4,5,1,5,0,6,0,1,6,6,5, 7,10,0,1,1,2,2,3,3,4,0,4,5,3,5,1,6,1,6,4,6,5, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,5,2,4,1,6,0,5,6, 7,10,3,1,0,3,5,0,1,5,2,1,6,2,0,6,0,4,4,2,4,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,4,6,1,6,2,6,5, 7,10,0,3,2,0,1,2,3,1,4,3,2,4,5,4,5,0,6,4,6,1, 7,10,0,1,6,5,2,3,3,4,6,4,0,5,6,2,6,1,4,2,5,1, 7,10,5,2,6,5,2,6,4,2,0,4,3,0,2,3,1,0,1,3,4,1, 7,10,3,4,1,3,4,1,0,4,3,0,1,0,2,1,5,2,6,5,2,6, 7,10,5,6,2,5,6,2,3,6,0,3,4,0,5,4,1,4,3,1,2,1, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,1,6,5,4,2, 7,10,1,0,2,1,3,2,0,3,5,0,1,5,4,5,6,4,3,6,2,6, 7,10,0,1,1,2,2,3,3,4,4,5,0,5,4,1,2,5,6,0,3,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2,1,5, 7,11,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5, 7,11,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,0,2, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,5,1, 7,11,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,4,6,5,6, 7,11,3,6,1,3,2,1,0,2,5,0,6,5,2,6,5,1,0,3,1,6,0,1, 7,11,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,0,3, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,4,6,4, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,3,6,4, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,2,4,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,2,5,6,2, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,2,0,6, 7,11,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,6,5, 7,11,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,1,0,4,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5,1,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5,6,4, 7,11,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,4,5,1,0,1,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,2,4,2,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5,5,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2,2,6, 7,11,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2,6,1, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2,3,6, 7,11,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2,6,4, 7,11,0,4,1,5,1,6,2,3,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,11,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2,0,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2,0,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1,1,6, 7,11,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2,5,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,5,4,3,5,1,5,0,6, 7,11,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3,2,6, 7,11,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2,3,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1,2,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2,5,6, 7,11,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2,5,6, 7,11,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3,5,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,4,5,6, 7,11,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2,1,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1,4,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1,5,6, 7,11,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3,4,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,4,0,2,4,1,6, 7,11,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,6,5,6,2, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4,5,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,2,4,0,2,1,3,5,1,1,6, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4,1,6, 7,11,1,0,4,1,0,4,5,0,4,5,3,4,1,3,5,1,2,3,1,2,2,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,3,2,0,3,2,4,5,2,1,6, 7,11,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,5,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0,1,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,2,4,0,2,1,3,5,1,5,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,2,4,0,2,1,3,5,1,6,3, 7,11,4,3,0,4,1,0,2,1,3,2,0,5,5,3,0,3,1,5,5,2,4,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,5,0,5,2,0,5,1,4,1,6,3, 7,11,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,3,2,0,3,1,6, 7,11,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0,6,2, 7,11,0,1,2,4,0,2,4,5,3,1,3,2,4,1,5,1,5,2,5,3,0,6, 7,11,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5, 7,11,6,5,0,6,5,0,1,5,6,1,2,6,5,2,3,5,6,3,4,6,5,4, 7,11,0,1,2,0,3,2,4,3,1,4,2,1,5,1,2,5,6,2,1,6,3,1, 7,11,0,1,1,2,2,3,3,4,0,4,5,1,3,5,6,1,4,6,1,4,3,1, 7,11,1,4,2,3,4,2,0,6,4,5,6,5,3,1,6,4,3,0,3,6,4,3, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,4,2,6,4,2,6,5,2,0,2, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,4,0,3,0,2,0,6,0,3,6, 7,11,0,1,2,0,5,2,6,5,2,6,1,2,4,1,2,4,3,2,4,3,3,1, 7,11,4,5,1,4,2,1,3,2,6,3,5,6,2,5,4,2,3,5,0,5,2,0, 7,11,0,1,1,2,2,3,3,4,0,4,4,2,5,2,5,0,6,2,4,6,5,4, 7,11,0,1,1,2,2,3,3,4,0,4,6,1,2,6,0,2,6,0,5,2,0,5, 7,11,0,5,6,0,1,6,5,1,2,5,6,2,4,3,3,2,4,5,6,4,6,5, 7,11,0,5,6,0,1,6,5,1,2,5,6,2,3,6,5,3,4,5,6,4,4,3, 7,11,0,5,0,6,1,2,1,6,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,11,0,1,1,2,2,3,3,4,0,4,0,2,2,4,5,2,4,5,6,5,6,0, 7,11,0,1,1,2,2,3,3,4,4,5,5,6,0,6,4,2,0,4,2,0,6,4, 7,11,0,1,2,0,3,2,4,3,1,4,5,1,5,2,6,1,2,6,4,2,5,4, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,2,5,4,2,6,2,4,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,4,6,2,0,2,4,0, 7,11,0,1,1,2,2,3,3,4,0,4,3,1,5,3,4,5,1,4,6,5,6,1, 7,11,0,4,3,0,4,3,2,4,3,2,1,3,2,1,4,1,5,2,6,5,2,6, 7,11,0,5,0,6,1,4,1,6,2,3,2,5,3,4,3,5,3,6,4,5,4,6, 7,11,0,1,4,0,5,4,6,5,3,6,2,3,1,2,4,1,2,4,5,2,1,5, 7,11,0,4,3,0,4,3,2,4,6,2,1,6,5,1,2,5,3,2,1,3,4,1, 7,11,0,1,6,5,2,3,3,4,4,5,0,5,6,0,6,1,6,2,6,3,6,4, 7,11,4,1,0,4,1,0,3,1,0,3,5,1,6,5,1,6,2,1,5,2,6,2, 7,11,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,4,6,5,4,6, 7,11,1,0,2,1,3,2,4,3,0,4,2,0,5,2,6,5,3,6,6,0,0,5, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,0,2,4,0,6,4,0,6,3,6, 7,11,0,1,1,2,2,3,3,4,0,4,2,0,5,2,6,5,4,6,0,5,6,0, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,6,0,2,6,3,6,0,3,4,0, 7,11,4,6,5,4,6,5,3,6,5,3,2,5,3,2,5,0,6,0,1,0,2,1, 7,11,2,0,4,2,5,4,3,5,1,3,0,1,2,1,3,2,6,3,5,6,4,3, 7,11,4,3,4,2,1,4,3,1,0,3,1,0,3,2,3,5,2,5,6,0,4,6, 7,11,0,1,0,2,2,3,5,1,1,3,5,2,6,3,6,0,5,3,4,5,3,4, 7,11,4,0,1,4,6,1,0,6,3,0,1,3,5,1,0,5,6,5,2,3,0,2, 7,11,0,1,5,0,4,5,1,4,2,1,3,2,4,3,4,2,6,4,2,6,3,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,3,5,6,3,4,6,5,6, 7,11,6,3,5,6,2,5,3,2,5,3,4,5,2,4,1,2,5,1,0,1,4,0, 7,11,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,1,6,5,4,6, 7,11,0,4,3,0,2,3,5,2,6,5,2,6,4,2,1,4,3,1,1,0,2,1, 7,11,5,0,0,1,3,0,5,3,2,5,6,2,4,6,5,4,1,5,6,1,3,6, 7,11,0,1,2,0,3,2,4,3,1,4,2,1,5,1,2,5,6,4,6,2,3,6, 7,11,3,2,6,3,5,6,0,5,2,0,1,2,0,1,5,1,2,5,4,2,6,4, 7,11,0,1,1,2,2,3,3,4,0,4,4,1,5,3,5,1,6,4,6,5,3,6, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,3,6,0,6,2,6,3,5,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,6,5,4,6,3,6,1,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,6,5,1,6,2,6,4,2, 7,11,0,1,1,2,2,3,0,3,4,0,4,3,4,2,6,1,6,4,5,2,3,5, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,6,1,4,6,6,5,2,6, 7,11,0,3,0,6,1,2,1,5,2,4,2,6,3,4,3,5,4,5,4,6,5,6, 7,11,5,1,6,5,4,6,3,4,2,3,0,2,1,0,5,0,6,0,2,6,4,2, 7,11,1,0,2,1,3,2,4,3,0,4,5,2,3,5,6,0,6,5,6,2,3,6, 7,11,0,3,4,0,2,4,3,2,1,3,4,1,5,1,6,0,6,1,5,3,4,5, 7,11,0,5,0,6,1,3,1,4,2,3,2,5,2,6,3,4,4,5,4,6,5,6, 7,11,0,2,1,0,2,1,0,3,3,1,5,4,5,3,6,4,6,2,6,0,1,6, 7,11,4,1,5,4,2,5,1,2,0,1,5,0,6,5,3,6,2,3,0,2,4,0, 7,11,0,1,2,0,3,2,4,3,1,4,6,1,6,2,5,1,3,5,5,2,4,5, 7,11,0,5,0,6,1,4,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,6,3,6,4,6,2,2,0,4,0, 7,11,0,2,1,0,2,1,0,3,3,1,5,4,5,3,6,4,6,2,4,0,1,4, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,6,2,0,6,1,6, 7,11,0,3,4,0,1,4,3,1,4,3,0,1,2,4,6,2,5,6,2,5,1,2, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,6,1,6,5, 7,11,4,1,5,4,2,5,1,2,0,1,4,0,5,0,6,5,3,6,2,3,5,3, 7,11,0,1,1,2,2,3,0,3,4,0,4,3,4,2,5,1,5,4,6,5,4,6, 7,11,0,1,1,2,2,3,5,4,0,4,5,0,5,1,5,2,5,3,6,3,6,4, 7,11,0,4,3,0,1,3,4,1,3,4,5,1,6,5,1,6,2,1,5,2,6,2, 7,11,4,1,0,4,3,0,2,5,5,4,6,5,2,6,1,2,3,1,6,3,2,3, 7,11,0,1,1,2,2,3,0,3,4,0,4,2,5,4,5,3,6,0,6,5,3,6, 7,11,5,2,2,4,5,3,4,1,5,4,0,1,3,0,0,2,6,2,6,3,0,6, 7,11,0,1,1,2,2,3,3,4,0,4,5,0,5,4,5,2,5,3,6,1,0,6, 7,11,0,3,0,4,1,2,1,5,1,6,2,4,2,6,3,5,3,6,4,5,5,6, 7,11,4,0,3,4,5,3,0,5,1,0,2,1,3,2,4,1,5,2,6,4,5,6, 7,11,2,3,4,2,0,4,5,0,1,5,4,1,3,4,5,3,1,0,6,5,6,2, 7,11,4,1,0,4,3,0,4,3,5,4,6,5,2,6,1,2,3,1,6,3,2,5, 7,11,0,3,4,0,2,4,3,2,1,3,0,1,6,0,5,6,2,5,1,5,4,1, 7,11,0,3,0,4,1,4,1,5,1,6,2,3,2,5,2,6,3,6,4,5,5,6, 7,11,0,1,1,2,2,3,0,3,4,0,4,3,4,2,5,1,5,4,6,1,5,6, 7,11,4,1,5,4,6,5,3,6,2,3,1,2,0,1,5,0,4,0,5,2,6,2, 7,11,0,1,1,2,2,3,3,4,0,4,4,2,3,5,4,5,3,0,6,5,6,1, 7,11,0,4,1,0,4,1,3,4,2,3,1,2,6,1,5,6,3,5,5,4,2,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,5,1,4,2,6,2,3,6,4,6, 7,11,0,1,1,2,2,3,3,4,4,5,0,5,6,2,1,6,5,2,4,1,0,3, 7,11,0,3,0,4,1,2,1,5,1,6,2,5,2,6,3,5,3,6,4,5,4,6, 7,11,0,1,1,2,2,3,5,4,0,4,5,3,5,1,6,3,6,4,4,2,0,3, 7,11,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,4,2,6,3,6,4,5, 7,11,4,3,2,4,3,2,0,3,2,1,5,4,5,0,6,4,6,1,1,5,0,6, 7,11,6,4,3,6,1,3,4,1,0,4,2,0,3,2,0,1,5,0,6,5,5,2, 7,11,6,1,2,6,1,2,0,1,3,0,4,3,5,4,3,5,2,0,4,0,5,6, 7,12,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,4,3,0,2, 7,12,3,6,1,3,2,1,0,2,5,0,6,5,2,6,5,1,0,3,1,6,0,1,0,6, 7,12,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,5,1,2,4, 7,12,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,2,3, 7,12,0,1,1,2,0,2,3,2,3,1,4,0,2,4,5,1,0,5,4,5,3,4,5,3, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2,1,5,6,1, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2,4,6,5,3, 7,12,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3,1,6, 7,12,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3,3,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5,4,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5,6,1, 7,12,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3,0,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5,0,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5,2,6, 7,12,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,0,2,1,6, 7,12,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,0,2,4,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,0,2,6,1,6,5, 7,12,1,3,2,1,0,2,5,0,4,5,3,4,5,1,5,3,2,5,1,0,4,1,1,6, 7,12,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,3,5,0,3,5,6, 7,12,3,6,1,3,2,1,0,2,5,0,6,5,2,6,5,1,0,3,1,6,0,1,1,4, 7,12,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,3,5,0,3,3,6, 7,12,0,1,2,4,0,2,2,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3,4,6, 7,12,1,3,2,1,0,2,5,0,4,5,3,4,5,1,5,3,2,5,1,0,4,1,2,6, 7,12,3,6,1,3,2,1,0,2,5,0,6,5,2,6,5,1,0,3,1,6,0,1,0,4, 7,12,1,3,4,1,3,4,2,3,0,2,4,0,5,4,2,5,4,2,0,5,1,5,3,6, 7,12,1,3,4,1,3,4,2,3,0,2,4,0,5,4,2,5,4,2,0,5,1,5,0,6, 7,12,0,1,1,2,2,3,3,4,0,4,1,3,4,1,2,4,0,3,5,0,4,5,5,6, 7,12,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,0,3,5,6, 7,12,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,4,6, 7,12,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,0,6, 7,12,3,6,1,3,2,1,0,2,5,0,6,5,2,6,5,1,0,3,1,6,0,1,4,5, 7,12,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,3,6, 7,12,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,0,3,0,6, 7,12,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,0,2,5,6, 7,12,0,3,6,0,5,6,3,5,1,3,6,1,4,6,3,4,2,3,6,2,3,6,5,4, 7,12,0,1,4,0,5,4,1,5,4,1,2,4,1,2,6,1,4,6,2,6,3,2,4,3, 7,12,4,1,3,2,3,0,4,2,5,1,5,0,3,5,4,3,5,4,6,5,3,6,4,6, 7,12,0,1,1,2,0,2,3,0,3,1,3,2,4,2,3,4,5,3,0,5,6,3,1,6, 7,12,0,1,1,2,0,2,3,0,3,1,3,2,6,3,0,6,5,0,1,5,4,1,2,4, 7,12,6,2,5,6,3,5,2,3,1,2,4,1,5,4,2,5,4,2,0,4,1,0,5,1, 7,12,5,4,6,5,3,6,4,3,0,4,3,0,1,3,0,1,4,1,3,5,2,3,4,2, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,5,0,1,5,6,1,0,6, 7,12,1,2,0,1,2,0,3,2,0,3,1,3,4,2,0,4,5,4,2,5,6,2,1,6, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,2,4,5,6,4,3,6, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,5,0,1,5,6,1,2,6, 7,12,1,2,0,1,2,0,3,2,0,3,1,3,4,2,0,4,6,4,2,6,5,2,4,5, 7,12,1,0,2,1,0,2,3,0,4,3,0,4,5,0,3,5,4,5,6,4,3,6,6,0, 7,12,0,1,1,2,0,2,3,0,3,1,3,2,4,1,0,4,5,0,2,5,6,5,2,6, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,6,4,0,6,5,0,3,5, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,1,5,6,1,0,6,5,0,4,5, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,6,1,0,6,5,0,2,5, 7,12,5,4,3,5,4,3,6,4,3,6,2,3,4,2,0,4,3,0,1,0,2,1,6,2, 7,12,4,1,3,2,3,0,4,2,5,1,5,0,3,5,4,3,5,4,6,5,0,6,3,6, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,6,1,0,6,5,0,1,5, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,3,1,5,1,6,5,4,6, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,5,4,3,5,6,3,4,6, 7,12,1,0,2,1,3,2,0,3,4,3,1,4,4,0,5,4,0,5,3,5,6,0,1,6, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,6,2,4,6,5,0,1,5, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,5,4,2,5,1,5,6,1,5,6, 7,12,0,2,1,0,2,1,0,3,3,1,4,2,5,3,6,1,6,4,4,0,3,4,1,5, 7,12,0,1,1,2,0,2,3,0,3,2,4,3,4,1,0,4,5,2,5,4,6,0,3,6, 7,12,5,0,2,5,6,2,3,6,2,3,1,2,0,1,4,0,1,4,5,1,6,5,0,2, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,6,4,2,6,5,2,3,5, 7,12,0,2,1,0,5,1,3,5,6,3,2,6,4,2,3,4,5,4,2,5,1,2,4,1, 7,12,0,2,1,0,2,1,0,3,3,1,4,0,1,4,4,2,3,4,5,4,6,5,3,6, 7,12,0,1,1,2,0,2,3,0,3,1,3,2,6,1,2,6,4,6,3,4,5,3,6,5, 7,12,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,5,0,6,5,0,6,3,4, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,1,2,5,6,0,3,6, 7,12,0,1,1,2,2,3,3,4,0,4,5,3,5,1,5,4,6,3,4,6,1,6,6,5, 7,12,0,5,0,6,1,3,1,4,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,12,0,1,1,2,2,3,3,4,0,4,5,2,6,5,0,6,6,2,0,5,1,5,6,1, 7,12,0,1,6,5,2,3,3,4,4,5,0,5,6,0,6,1,6,2,6,3,6,4,5,1, 7,12,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4,6,1,5,6, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,1,4,5,6,4,5,6, 7,12,2,1,0,2,5,0,4,5,3,4,5,1,5,3,2,5,1,0,4,1,6,3,6,1, 7,12,0,4,0,6,1,3,1,5,1,6,2,3,2,5,2,6,3,5,4,5,4,6,5,6, 7,12,0,5,0,6,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,5,6, 7,12,0,1,2,4,0,2,2,1,4,6,4,1,5,1,5,2,5,3,0,3,6,1,2,6, 7,12,0,1,1,2,2,3,5,4,0,4,5,3,5,1,6,3,6,4,4,2,0,3,4,3, 7,12,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,6,1,6,5, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,1,6,5,0,6,1,6, 7,12,0,3,4,0,2,4,3,2,1,3,4,1,1,0,5,1,5,2,6,1,2,6,4,6, 7,12,0,1,1,2,2,3,0,3,4,2,5,0,5,4,4,1,1,6,5,3,1,5,6,2, 7,12,0,1,1,2,2,3,0,3,4,2,5,0,5,4,4,1,1,5,5,3,6,1,4,6, 7,12,0,1,1,2,2,3,0,3,4,2,5,0,5,4,4,1,1,5,5,3,6,1,0,6, 7,12,4,3,1,2,0,1,0,3,4,0,6,4,4,2,5,4,6,2,6,3,3,2,5,1, 7,12,2,3,4,2,0,4,6,0,6,5,4,5,1,3,5,1,0,5,6,1,3,6,5,3, 7,12,0,3,0,5,1,2,1,5,1,6,2,4,2,6,3,4,3,6,4,5,4,6,5,6, 7,12,0,3,0,6,1,4,1,5,1,6,2,3,2,4,2,5,3,6,4,5,4,6,5,6, 7,12,0,1,1,2,2,3,4,5,0,4,4,3,5,3,6,1,3,6,6,2,0,6,4,6, 7,12,0,1,2,4,0,2,6,1,3,1,3,2,4,1,5,1,5,2,5,3,0,3,4,6, 7,12,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,6,3,1,6, 7,12,4,3,1,2,5,0,0,3,4,0,4,1,4,2,5,1,6,2,6,3,3,2,6,4, 7,12,2,3,4,2,5,4,0,5,6,0,1,6,3,1,6,3,5,3,1,5,4,0,3,0, 7,12,0,3,0,5,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,6,4,6,5,6, 7,12,3,2,1,2,5,0,0,3,4,0,4,1,6,4,5,1,6,2,6,3,6,1,0,6, 7,12,0,5,0,6,1,3,1,4,1,6,2,3,2,4,2,6,3,5,4,5,4,6,5,6, 7,12,0,3,0,5,1,2,1,4,1,6,2,4,2,6,3,5,3,6,4,5,4,6,5,6, 7,12,0,3,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,4,6,5,6, 7,12,0,5,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,6, 7,12,0,1,1,2,2,3,0,3,4,2,5,0,5,4,4,1,3,4,5,3,2,6,6,1, 7,12,0,1,1,2,2,3,0,3,4,2,5,0,5,4,4,1,3,4,5,3,6,1,6,5, 7,12,0,2,0,6,1,4,1,5,1,6,2,3,2,5,3,4,3,5,3,6,4,5,4,6, 7,12,0,5,0,6,1,3,1,4,1,6,2,3,2,4,2,5,3,4,3,6,4,5,5,6, 7,12,0,1,1,2,2,3,0,3,4,1,2,4,5,2,0,5,4,3,6,5,6,4,3,5, 7,12,0,2,0,6,1,2,1,4,1,5,2,3,3,4,3,5,3,6,4,5,4,6,5,6, 7,12,0,2,0,6,1,3,1,4,1,5,2,4,2,5,3,4,3,5,3,6,4,6,5,6, 7,12,0,2,0,6,1,3,1,4,1,5,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,12,0,5,0,6,1,3,1,4,1,6,2,3,2,4,2,6,3,4,3,5,4,5,5,6, 7,12,0,5,0,6,1,2,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6, 7,12,3,0,2,3,4,2,0,4,5,1,5,2,6,1,6,0,3,6,5,3,4,5,6,4, 7,12,0,5,0,6,1,2,1,3,1,4,2,3,2,4,3,5,3,6,4,5,4,6,5,6, 7,12,0,1,0,2,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,12,3,0,2,3,4,2,0,4,5,1,5,2,6,1,6,0,3,6,5,3,6,4,1,3, 7,12,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,4,2,5,3,6,4,6,5,6, 7,12,2,3,4,2,5,2,4,1,6,0,3,0,3,1,6,3,5,6,1,5,4,0,3,4, 7,12,2,3,4,2,4,1,2,5,6,0,6,4,3,1,6,3,0,3,1,5,4,0,5,3, 7,12,0,4,0,5,0,6,1,2,1,3,1,6,2,3,2,6,3,5,4,5,4,6,5,6, 7,12,3,0,2,3,4,2,0,4,5,1,5,2,6,1,6,0,3,6,1,3,6,4,5,4, 7,12,6,3,1,2,2,3,0,3,4,2,5,0,0,6,4,1,3,4,6,5,5,1,0,4, 7,12,0,3,0,5,0,6,1,2,1,5,1,6,2,4,2,6,3,4,3,5,4,5,4,6, 7,12,0,3,0,5,0,6,1,2,1,4,1,6,2,3,2,5,3,4,4,5,4,6,5,6, 7,12,0,3,0,5,0,6,1,2,1,5,1,6,2,3,2,4,3,4,4,5,4,6,5,6, 7,12,0,4,3,0,1,3,4,1,1,0,4,5,2,4,6,2,5,6,2,5,3,2,6,3, 7,12,0,1,1,2,2,3,0,3,4,0,4,1,5,2,5,4,6,4,6,3,6,2,5,3, 7,12,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,5,2,6,3,4,4,5,4,6, 7,12,3,0,4,2,3,1,4,0,5,2,5,1,4,3,5,4,3,5,6,1,0,6,2,6, 7,12,1,0,4,1,0,4,5,0,6,5,1,6,3,4,5,3,2,3,5,2,6,3,2,6, 7,12,0,1,2,0,2,3,3,4,0,4,0,5,6,1,4,6,6,5,2,6,3,1,5,3, 7,12,0,1,1,2,2,3,3,4,4,5,0,5,6,0,6,1,6,2,6,3,6,4,6,5, 7,12,3,6,1,2,0,6,0,3,4,0,4,1,4,2,4,3,5,1,2,5,4,5,6,4, 7,13,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,13,0,6,1,4,1,5,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,4,3,0,2,6,4, 7,13,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,0,4,1,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,2,3,2,4,2,5,2,6,3,6,4,5,5,6, 7,13,0,6,1,4,1,5,1,6,2,3,2,4,2,5,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,0,3,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,13,0,6,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,5,6, 7,13,0,6,1,3,1,4,1,5,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,13,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,4,5,1,6, 7,13,0,1,1,2,2,3,4,5,0,4,1,3,4,1,2,4,0,3,5,3,4,3,0,2,5,6, 7,13,0,5,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,6,4,6,5,6, 7,13,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,13,5,6,0,5,6,0,4,6,5,4,1,5,6,1,3,6,5,3,2,5,6,2,1,0,2,1, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,2,3,2,4,2,6, 7,13,3,4,0,3,4,0,1,4,3,1,2,3,4,2,1,0,2,1,6,0,3,6,5,3,4,5, 7,13,3,4,0,3,4,0,1,4,3,1,2,3,4,2,1,0,2,1,6,0,3,6,5,3,0,5, 7,13,3,4,0,3,4,0,1,4,3,1,2,3,4,2,1,0,2,1,6,4,0,6,5,0,3,5, 7,13,0,5,0,6,1,3,1,4,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,3,2,4,3,5,4,6, 7,13,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,5,1,6,5,1,6, 7,13,0,4,0,6,1,3,1,5,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,13,0,5,0,6,1,4,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,5,6, 7,13,0,5,0,6,1,3,1,4,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,13,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,5,3,6,5,4,6, 7,13,0,5,0,6,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,13,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,6,1,6,5,5,1, 7,13,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,4,0,5,6,0,3,6,6,4, 7,13,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,6,1,5,1,2,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,2,3,2,4,5,6, 7,13,1,0,2,1,4,2,1,4,3,1,0,3,2,3,5,2,1,5,0,5,6,0,1,6,2,6, 7,13,2,5,6,2,5,6,4,5,3,4,0,3,4,0,1,4,3,1,6,3,2,1,4,2,3,2, 7,13,0,3,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,13,2,4,3,2,1,3,4,1,0,4,3,0,6,3,1,6,5,1,4,5,6,4,3,5,1,2, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,4,2,5,3,5,3,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,3,2,4,3,5,5,6, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,3,2,5,3,6,4,5, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,6,2,4,2,5,3,4,3,5, 7,13,0,2,0,6,1,4,1,5,1,6,2,3,2,5,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,2,5,1,2,5,1,4,5,3,4,0,3,4,0,3,2,4,2,1,3,6,3,2,6,1,6, 7,13,0,4,0,6,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,5,3,6,4,5,5,6, 7,13,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,0,4,6,1,4,6, 7,13,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2,5,0,6,5,1,6,4,0, 7,13,0,1,1,2,0,2,3,0,1,3,3,2,4,0,2,5,3,4,5,3,0,5,6,4,6,1, 7,13,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2,6,2,5,6,0,5,1,2, 7,13,5,4,6,2,6,4,4,3,5,0,3,1,3,2,6,3,5,6,4,0,1,4,5,1,0,3, 7,13,0,2,0,6,1,3,1,4,1,5,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,1,5,4,1,0,4,5,0,2,5,4,2,3,4,5,3,0,1,2,0,3,2,6,5,6,4, 7,13,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,0,4,0,6,4,6, 7,13,0,4,3,0,2,3,4,2,1,4,3,1,1,0,5,0,4,5,1,5,6,1,0,6,3,6, 7,13,0,5,0,6,1,2,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,1,3,2,1,0,2,5,0,4,5,3,4,4,1,5,3,2,5,1,0,6,3,4,6,5,1, 7,13,5,2,0,2,3,0,4,3,1,4,5,1,4,5,1,0,6,2,6,3,1,2,3,1,4,0, 7,13,1,0,2,1,0,2,0,3,3,2,6,2,1,6,5,1,6,5,4,6,5,4,0,5,4,0, 7,13,0,5,0,6,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,6, 7,13,0,5,0,6,1,3,1,4,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,13,0,1,1,2,4,1,3,1,0,4,2,3,0,3,2,0,5,0,6,5,4,6,3,5,4,2, 7,13,0,5,0,6,1,2,1,3,1,4,2,4,2,5,2,6,3,4,3,5,3,6,4,6,5,6, 7,13,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,0,4,2,3,6,5,0,6, 7,13,5,2,0,2,3,0,4,3,1,4,5,1,4,5,1,0,6,2,6,3,2,3,5,0,4,0, 7,13,0,1,1,2,2,3,5,4,0,4,5,0,5,1,5,2,5,3,6,3,6,4,4,2,0,3, 7,13,0,1,0,6,1,4,1,5,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,6,5,6, 7,13,0,1,0,6,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,13,0,1,1,2,2,3,3,4,0,4,6,2,0,6,5,0,2,5,5,3,4,5,6,4,3,6, 7,13,0,1,1,2,2,3,3,4,0,4,6,5,0,6,0,2,2,5,5,3,4,5,6,4,3,6, 7,13,3,4,0,3,4,0,3,6,3,1,2,3,4,2,1,0,2,1,5,2,3,5,6,2,5,6, 7,13,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4,6,5,3,6,4,6, 7,13,1,0,2,1,6,0,1,4,3,1,0,3,2,3,1,6,1,5,2,6,4,3,5,4,6,5, 7,13,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,2,5,2,6,3,5,4,6, 7,13,0,6,1,2,2,3,0,3,4,2,5,0,6,3,4,1,3,4,6,5,1,5,3,5,1,3, 7,13,0,1,1,2,2,3,0,3,4,0,4,1,6,4,4,3,5,4,5,2,6,0,3,6,3,5, 7,13,0,1,1,2,2,3,3,6,0,4,6,5,0,6,6,4,2,5,5,3,4,5,1,5,6,1, 7,13,0,4,0,5,0,6,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,5,6, 7,13,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,5,2,6,3,4,4,5,4,6,5,6, 7,13,2,3,5,2,6,5,3,6,4,3,5,4,0,5,2,0,1,2,0,1,5,1,4,2,6,4, 7,13,2,1,0,5,6,0,4,6,5,4,1,5,6,1,3,6,5,3,2,5,6,2,1,0,3,4, 7,13,0,1,2,0,2,3,3,4,0,4,0,5,6,1,4,6,6,5,2,6,3,1,5,3,6,0, 7,13,0,4,0,5,0,6,1,2,1,5,1,6,2,3,2,6,3,4,3,5,3,6,4,5,4,6, 7,13,2,3,0,2,3,0,4,3,4,6,5,1,4,5,3,1,5,2,6,0,6,1,2,1,4,1, 7,13,0,1,1,2,2,3,0,3,4,0,4,1,4,3,5,4,5,2,5,1,6,5,1,6,2,6, 7,13,0,4,0,5,0,6,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,5,3,6,4,6, 7,13,3,0,2,3,4,2,0,4,5,1,5,2,6,1,6,0,3,6,1,3,6,4,5,4,5,3, 7,13,0,4,0,5,0,6,1,2,1,4,1,5,2,3,2,6,3,4,3,5,3,6,4,6,5,6, 7,13,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,4,2,5,3,4,3,6,4,6,5,6, 7,13,0,2,0,5,0,6,1,2,1,4,1,6,2,3,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,3,4,5,0,3,5,0,6,6,4,2,3,4,2,1,0,2,1,1,6,5,1,2,5,6,2, 7,13,0,2,0,5,0,6,1,2,1,3,1,4,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,13,3,0,2,3,4,2,0,4,5,3,5,2,5,4,1,3,1,0,4,1,6,0,3,6,1,6, 7,13,2,3,0,2,3,0,4,3,1,4,5,1,4,5,6,0,1,6,6,3,4,6,1,2,5,0, 7,13,0,4,0,5,0,6,1,2,1,3,1,6,2,3,2,5,2,6,3,4,3,5,4,5,4,6, 7,13,0,4,0,5,0,6,1,2,1,3,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5, 7,13,0,1,1,2,2,3,0,3,4,0,4,1,5,3,5,4,6,4,6,2,6,5,5,2,3,6, 7,13,0,1,0,5,0,6,1,3,1,4,2,3,2,4,2,5,2,6,3,4,3,6,4,5,5,6, 7,13,0,1,0,5,0,6,1,3,1,4,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,13,0,1,2,0,2,3,3,4,0,4,0,5,6,1,4,6,6,5,2,6,3,1,5,3,2,1, 7,14,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,1,3,2,0,4,0,5,3, 7,14,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,2,3,0,4,1,6, 7,14,0,6,1,3,1,4,1,5,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,2,4,2,5,2,6,3,4,3,5,3,6,4,6,5,6, 7,14,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,14,0,3,1,2,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,3,6,5,3,4,5,6,4, 7,14,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,6,2,1,6,5,1,0,5, 7,14,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,5,2,3,5,6,4,0,6, 7,14,3,4,1,3,2,1,0,2,5,0,4,5,2,4,5,1,0,3,1,4,0,1,0,4,6,4,0,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,3,4,3,5,4,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,6,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,14,3,4,1,3,2,1,0,2,5,0,4,5,0,1,5,1,0,4,1,4,5,3,2,5,6,4,0,6, 7,14,1,3,2,1,0,2,5,0,4,5,3,4,5,3,2,5,1,0,4,1,6,1,5,1,2,6,0,4, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,6,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,14,2,3,4,2,6,3,4,0,6,0,3,4,3,1,5,4,5,0,0,3,1,5,5,3,6,4,6,1, 7,14,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,5,3,6,5,4,6,5,4, 7,14,3,1,1,4,2,3,3,4,0,4,1,5,0,1,0,2,2,5,5,3,4,5,1,2,6,2,5,6, 7,14,0,3,0,6,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,14,0,3,0,6,1,2,1,4,1,5,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,0,5,0,6,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,14,0,1,0,6,1,4,1,5,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,0,5,0,6,1,2,1,3,1,4,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,4,6,5,2,1,5,0,5,6,3, 7,14,0,1,1,2,2,3,3,4,0,4,5,0,5,1,5,2,5,3,5,4,4,2,3,0,6,1,5,6, 7,14,0,4,0,6,1,2,1,3,1,5,1,6,2,3,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,14,0,4,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,5,6, 7,14,0,5,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,6,4,5,5,6, 7,14,2,3,0,2,3,0,4,3,1,4,5,1,1,2,5,2,4,0,3,1,5,0,6,5,6,4,0,1, 7,14,2,3,0,2,3,0,4,3,1,4,5,1,4,5,5,2,6,0,6,1,5,0,1,2,3,1,4,0, 7,14,5,6,0,5,6,0,4,6,5,4,1,5,6,1,3,6,5,3,2,5,6,2,1,0,2,1,3,4, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,5,1,6,2,5,2,6,3,4,3,6,4,5,5,6, 7,14,0,1,2,0,2,3,3,4,0,4,0,5,6,1,4,6,6,5,2,6,3,1,5,3,6,0,3,6, 7,14,3,1,4,2,4,5,4,0,1,4,0,3,5,0,5,2,6,1,3,6,6,0,5,6,6,2,4,6, 7,14,0,4,3,0,2,3,4,2,1,4,3,1,1,0,2,1,5,4,1,5,6,1,3,6,0,5,6,0, 7,14,3,4,4,2,1,5,4,0,1,4,5,3,3,0,5,2,6,4,0,6,3,6,2,6,5,6,1,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,4,1,5,2,3,2,6,3,6,4,5,4,6,5,6, 7,14,2,3,4,2,6,3,4,0,4,5,3,4,3,1,5,2,1,6,5,6,6,0,5,3,6,4,0,1, 7,14,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,4,2,6,3,4,3,5,4,5,4,6,5,6, 7,14,0,4,0,5,0,6,1,2,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,14,2,3,4,2,6,3,4,0,1,4,6,0,3,1,5,2,4,5,5,6,1,5,5,3,6,4,3,0, 7,14,3,1,4,2,0,3,4,0,1,4,5,3,5,0,5,2,6,4,1,6,6,3,0,6,6,5,2,6, 7,14,0,1,4,2,3,0,4,0,4,5,5,3,1,3,5,2,6,4,2,6,6,5,3,6,6,1,0,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,6,2,5,3,4,3,5,3,6,4,5,4,6, 7,14,0,1,0,2,0,3,0,4,0,5,0,6,1,5,1,6,2,3,2,4,3,5,3,6,4,5,4,6, 7,14,2,3,4,2,6,3,4,0,1,4,6,1,3,1,5,2,5,0,5,6,4,5,5,3,6,0,3,0, 7,14,2,3,4,2,3,0,4,0,4,5,3,4,3,1,5,2,0,1,5,6,6,0,5,3,6,4,1,6, 7,14,0,4,0,5,0,6,1,3,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,6,4,5,5,6, 7,14,0,3,0,4,0,6,1,2,1,4,1,5,2,3,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,14,0,4,0,5,0,6,1,2,1,3,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5,5,6, 7,14,0,1,0,5,0,6,1,4,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,5,6, 7,14,0,1,0,4,0,6,1,3,1,5,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,14,2,3,4,2,6,3,4,0,1,4,4,5,3,1,5,2,5,0,6,1,0,6,5,3,6,4,3,0, 7,14,0,1,0,5,0,6,1,3,1,4,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,14,0,4,0,5,0,6,1,2,1,3,1,4,2,3,2,5,2,6,3,5,3,6,4,5,4,6,5,6, 7,14,0,4,0,5,0,6,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,5,6, 7,14,2,3,4,2,6,3,4,0,4,5,3,5,3,1,5,2,3,0,1,4,6,0,1,6,6,4,0,1, 7,14,0,4,0,5,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,6, 7,14,0,4,0,5,0,6,1,2,1,3,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,4,6, 7,14,0,4,0,5,0,6,1,2,1,3,1,5,1,6,2,3,2,4,2,6,3,4,3,5,4,6,5,6, 7,14,0,3,0,4,0,5,1,2,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,6,5,6, 7,14,0,3,0,4,0,5,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,6,4,6,5,6, 7,14,0,1,1,2,2,3,3,4,4,5,5,6,0,6,0,2,5,0,3,5,1,3,6,1,4,6,2,4, 7,14,0,3,0,4,0,5,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,6,4,5, 7,15,0,1,0,2,0,3,0,4,0,5,1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5, 7,15,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,1,3,2,0,4,0,5,3,1,6, 7,15,0,1,1,2,2,3,3,4,4,5,0,5,2,4,5,2,1,5,1,4,1,3,2,0,4,0,5,3,0,6, 7,15,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,3,4,3,5,3,6,5,6, 7,15,0,1,0,2,0,3,0,4,0,5,0,6,1,5,1,6,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,15,3,4,4,5,0,3,0,4,0,5,0,6,3,6,4,6,5,6,1,5,3,5,2,3,2,4,1,6,0,1, 7,15,3,4,4,5,0,3,0,4,0,5,0,6,3,6,1,3,1,4,1,5,3,5,2,3,2,4,6,1,4,6, 7,15,0,1,1,2,2,3,0,3,4,0,4,1,4,2,4,3,5,1,0,5,5,2,3,5,4,5,6,1,5,6, 7,15,4,3,4,5,5,3,0,1,0,5,0,3,2,4,1,5,1,3,6,5,3,6,6,0,1,6,6,2,4,6, 7,15,3,4,4,5,5,6,0,4,0,5,0,6,3,6,1,3,4,6,1,5,3,5,2,3,2,4,1,6,0,1, 7,15,0,2,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,3,4,3,5,3,6,4,5,4,6,5,6, 7,15,6,1,4,5,0,3,0,4,0,5,0,6,3,6,1,3,1,4,1,5,3,5,2,3,2,4,5,6,4,6, 7,15,3,4,4,5,0,3,0,4,0,5,4,6,3,6,1,3,1,4,1,5,3,5,2,3,2,4,5,6,5,2, 7,15,3,4,4,5,0,3,0,4,6,0,4,6,3,6,1,3,1,4,1,5,3,5,2,3,2,4,5,6,5,2, 7,15,0,1,1,2,0,2,3,0,1,3,2,3,5,1,3,5,4,3,2,4,6,2,3,6,6,1,0,5,4,0, 7,15,0,1,2,0,3,2,4,3,1,4,3,1,4,2,0,4,3,0,6,3,4,6,5,4,3,5,6,2,5,1, 7,15,0,1,0,2,0,3,0,4,1,2,1,3,1,4,2,3,2,4,3,4,5,3,4,5,6,4,5,6,6,3, 7,15,0,1,1,2,2,3,0,3,4,0,4,3,4,2,6,1,2,6,5,2,4,5,6,4,0,6,6,5,3,6, 7,15,0,1,5,3,1,3,0,4,3,0,4,3,2,4,5,2,4,5,6,4,2,6,6,5,3,6,6,1,0,6, 7,15,5,2,4,5,3,1,0,4,0,5,0,3,2,4,1,5,1,4,6,3,1,6,6,0,5,6,6,2,4,6, 7,15,0,1,1,2,2,3,3,4,4,5,0,5,0,3,2,0,3,1,6,4,5,6,6,3,0,6,6,2,1,6, 7,15,5,2,3,0,5,3,0,4,0,5,4,3,2,4,1,5,1,4,6,4,2,6,6,0,5,6,6,3,1,6, 7,15,0,4,0,5,0,6,1,2,1,3,1,6,2,3,2,4,2,5,3,4,3,5,3,6,4,5,4,6,5,6, 7,15,6,1,4,5,0,3,0,4,0,5,4,6,3,6,1,3,1,4,0,6,3,5,2,3,2,4,5,6,5,2, 7,15,3,4,0,1,0,3,0,4,0,5,4,6,3,6,1,3,1,4,6,0,1,6,2,3,2,4,5,6,5,2, 7,15,0,1,0,2,0,3,0,4,0,5,0,6,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,6, 7,15,5,2,4,5,5,3,0,4,0,1,1,3,2,4,3,0,1,4,6,4,1,6,6,0,3,6,6,2,5,6, 7,15,5,0,4,3,5,3,5,2,0,1,1,3,2,4,3,0,1,4,6,2,5,6,6,4,3,6,6,0,1,6, 7,15,3,4,4,5,0,3,4,6,0,1,1,6,3,6,1,3,1,4,6,0,0,5,2,3,2,4,5,6,5,2, 7,15,0,2,0,3,0,6,1,3,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,15,0,4,0,5,0,6,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,15,3,4,5,0,0,3,0,4,4,6,1,6,3,6,1,3,1,4,6,0,1,5,2,3,2,4,5,6,5,2, 7,15,6,4,5,2,0,3,0,4,2,4,1,6,3,6,1,3,1,4,6,0,3,5,2,3,0,1,5,6,4,5, 7,15,0,4,0,5,0,6,1,2,1,3,1,5,1,6,2,3,2,4,2,6,3,4,3,5,4,5,4,6,5,6, 7,15,0,1,0,2,0,3,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,15,2,3,0,2,3,0,4,3,1,4,5,1,4,5,1,0,5,2,6,2,5,6,6,1,0,6,6,4,3,6, 7,15,3,0,3,5,3,4,2,0,2,5,2,4,1,4,1,5,1,0,6,0,1,6,6,5,3,6,6,4,2,6, 7,15,0,3,0,4,0,5,0,6,1,2,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,5,6, 7,15,3,4,6,2,0,3,0,4,5,0,1,6,3,6,1,3,1,4,6,0,4,5,2,3,2,4,5,1,5,2, 7,15,3,4,6,2,0,3,0,4,5,0,5,6,3,6,1,3,1,4,0,1,4,6,2,3,2,4,5,1,5,2, 7,15,0,1,1,2,2,3,3,4,0,4,6,2,1,6,6,0,4,6,5,4,0,5,3,5,6,3,5,2,1,5, 7,16,0,1,0,2,0,3,0,4,0,5,1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5,2,6, 7,16,3,0,4,1,4,3,1,3,4,0,2,5,6,2,5,6,1,5,4,5,3,5,0,5,0,6,3,6,4,6,6,1, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,6,2,3,2,4,2,5,3,4,3,5,3,6,4,5,4,6,5,6, 7,16,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6, 7,16,3,4,5,1,0,3,0,4,5,0,4,6,3,6,1,3,1,4,6,0,3,5,2,3,2,4,5,6,4,5,2,5, 7,16,2,4,3,1,3,0,4,3,4,0,5,2,4,5,5,0,3,5,5,1,6,5,1,6,3,6,6,0,4,6,6,2, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,16,2,4,4,1,3,0,3,1,4,0,5,2,4,5,5,0,3,5,6,5,1,5,6,1,3,6,4,6,6,2,6,0, 7,16,0,1,0,3,0,5,0,6,1,3,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,16,2,5,0,1,4,5,1,3,5,0,4,3,5,3,2,4,1,4,3,0,6,3,2,6,6,4,5,6,6,1,0,6, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,3,1,6,2,4,2,5,2,6,3,4,3,5,4,5,4,6,5,6, 7,16,2,5,5,1,3,1,0,4,5,0,4,3,5,3,2,4,1,4,3,0,6,2,4,6,5,6,6,1,0,6,3,6, 7,16,1,6,0,1,0,3,0,4,5,0,4,6,3,6,1,3,1,4,6,0,3,5,2,3,2,4,5,6,4,5,2,5, 7,16,3,4,5,1,0,3,0,4,5,0,4,6,3,6,1,3,1,4,6,0,1,6,2,3,2,4,5,6,0,1,2,5, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,5,2,6,3,4,3,6,4,5, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,4,1,5,1,6,2,3,2,5,2,6,3,4,3,6,4,5,5,6, 7,16,0,1,0,2,0,3,0,4,0,5,0,6,1,4,1,5,1,6,2,4,2,5,2,6,3,4,3,5,3,6,5,6, 7,16,2,5,5,1,3,5,0,4,0,1,4,3,3,2,2,4,1,4,0,5,6,4,2,6,6,3,5,6,6,1,0,6, 7,16,5,6,5,1,0,3,0,4,0,1,4,6,3,6,1,3,1,4,6,0,3,5,2,3,2,4,6,2,4,5,2,5, 7,16,3,4,5,1,0,3,0,4,0,1,4,6,3,6,1,3,1,4,6,0,5,0,2,3,2,4,6,2,6,5,2,5, 7,16,5,0,5,1,0,3,0,4,6,1,4,6,3,6,1,3,1,4,6,0,3,5,2,3,2,4,6,2,4,5,2,5, 7,17,0,1,0,2,0,3,0,4,0,5,1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5,6,2,1,6, 7,17,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,4,5,4,6, 7,17,4,0,4,3,0,1,3,0,2,4,3,1,5,3,4,5,5,2,6,5,5,0,1,5,6,1,0,6,6,4,2,6,3,6, 7,17,0,1,5,1,5,3,0,4,5,0,4,3,3,1,2,5,1,4,3,0,2,4,6,2,5,6,6,3,1,6,6,0,4,6, 7,17,3,4,5,1,0,3,0,4,4,5,4,6,3,6,1,3,1,4,0,1,3,5,2,3,2,4,2,5,5,0,5,6,6,2, 7,17,3,2,4,1,0,1,3,0,2,4,4,3,5,1,4,5,5,2,0,5,5,3,6,5,2,6,6,3,0,6,1,6,4,6, 7,17,3,2,4,1,4,0,3,0,2,4,3,1,5,2,4,5,5,0,3,5,5,1,6,5,2,6,6,0,3,6,6,4,1,6, 7,17,3,2,5,1,5,0,0,4,0,1,4,3,5,3,2,5,1,4,3,0,2,4,6,4,5,6,6,2,3,6,6,0,1,6, 7,17,3,2,5,1,5,0,0,4,4,5,0,1,3,1,2,5,1,4,3,0,2,4,6,0,3,6,6,1,5,6,6,2,4,6, 7,17,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,5,3,6,4,5,4,6, 7,18,0,1,0,2,0,3,0,4,0,5,1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5,6,1,0,6,5,6, 7,18,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6, 7,18,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,4,1,5,2,3,2,4,2,5,2,6,3,4,3,6,4,5,4,6,5,6, 7,18,0,1,0,2,0,3,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,18,4,0,4,5,3,0,3,5,2,0,2,5,1,3,1,4,1,5,1,0,2,3,2,4,6,0,5,6,6,1,2,6,6,4,3,6, 7,19,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,3,4,3,5,3,6,4,5,4,6,5,6, 7,19,0,1,0,2,0,3,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,6,4,5,4,6,5,6, 7,20,0,1,0,2,0,3,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, 7,21,0,1,0,2,0,3,0,4,0,5,0,6,1,2,1,3,1,4,1,5,1,6,2,3,2,4,2,5,2,6,3,4,3,5,3,6,4,5,4,6,5,6, }; const long int igraph_i_atlas_edges_pos[]={0, 2, 4, 6, 10, 12, 16, 22, 30, 32, 36, 42, 48, 56, 64, 72, 82, 92, 104, 118, 120, 124, 130, 136, 144, 152, 160, 168, 178, 188, 198, 208, 218, 228, 240, 252, 264, 276, 288, 300, 314, 328, 342, 356, 370, 384, 400, 416, 432, 448, 466, 484, 504, 526, 528, 532, 538, 544, 552, 560, 568, 576, 584, 594, 604, 614, 624, 634, 644, 654, 664, 674, 686, 698, 710, 722, 734, 746, 758, 770, 782, 794, 806, 818, 830, 842, 854, 868, 882, 896, 910, 924, 938, 952, 966, 980, 994, 1008, 1022, 1036, 1050, 1064, 1078, 1092, 1106, 1120, 1134, 1148, 1164, 1180, 1196, 1212, 1228, 1244, 1260, 1276, 1292, 1308, 1324, 1340, 1356, 1372, 1388, 1404, 1420, 1436, 1452, 1468, 1484, 1500, 1516, 1532, 1550, 1568, 1586, 1604, 1622, 1640, 1658, 1676, 1694, 1712, 1730, 1748, 1766, 1784, 1802, 1820, 1838, 1856, 1874, 1892, 1910, 1928, 1946, 1964, 1984, 2004, 2024, 2044, 2064, 2084, 2104, 2124, 2144, 2164, 2184, 2204, 2224, 2244, 2264, 2284, 2304, 2324, 2344, 2364, 2384, 2406, 2428, 2450, 2472, 2494, 2516, 2538, 2560, 2582, 2604, 2626, 2648, 2670, 2692, 2714, 2738, 2762, 2786, 2810, 2834, 2858, 2882, 2906, 2930, 2956, 2982, 3008, 3034, 3060, 3088, 3116, 3146, 3178, 3180, 3184, 3190, 3196, 3204, 3212, 3220, 3228, 3236, 3246, 3256, 3266, 3276, 3286, 3296, 3306, 3316, 3326, 3336, 3348, 3360, 3372, 3384, 3396, 3408, 3420, 3432, 3444, 3456, 3468, 3480, 3492, 3504, 3516, 3528, 3540, 3552, 3564, 3576, 3588, 3602, 3616, 3630, 3644, 3658, 3672, 3686, 3700, 3714, 3728, 3742, 3756, 3770, 3784, 3798, 3812, 3826, 3840, 3854, 3868, 3882, 3896, 3910, 3924, 3938, 3952, 3966, 3980, 3994, 4008, 4022, 4036, 4050, 4064, 4078, 4092, 4106, 4120, 4134, 4148, 4162, 4178, 4194, 4210, 4226, 4242, 4258, 4274, 4290, 4306, 4322, 4338, 4354, 4370, 4386, 4402, 4418, 4434, 4450, 4466, 4482, 4498, 4514, 4530, 4546, 4562, 4578, 4594, 4610, 4626, 4642, 4658, 4674, 4690, 4706, 4722, 4738, 4754, 4770, 4786, 4802, 4818, 4834, 4850, 4866, 4882, 4898, 4914, 4930, 4946, 4962, 4978, 4994, 5010, 5026, 5042, 5058, 5074, 5090, 5106, 5122, 5138, 5154, 5170, 5186, 5202, 5220, 5238, 5256, 5274, 5292, 5310, 5328, 5346, 5364, 5382, 5400, 5418, 5436, 5454, 5472, 5490, 5508, 5526, 5544, 5562, 5580, 5598, 5616, 5634, 5652, 5670, 5688, 5706, 5724, 5742, 5760, 5778, 5796, 5814, 5832, 5850, 5868, 5886, 5904, 5922, 5940, 5958, 5976, 5994, 6012, 6030, 6048, 6066, 6084, 6102, 6120, 6138, 6156, 6174, 6192, 6210, 6228, 6246, 6264, 6282, 6300, 6318, 6336, 6354, 6372, 6390, 6408, 6426, 6444, 6462, 6480, 6498, 6516, 6534, 6552, 6570, 6588, 6606, 6624, 6642, 6660, 6678, 6696, 6714, 6732, 6750, 6768, 6786, 6804, 6822, 6840, 6858, 6876, 6894, 6912, 6930, 6948, 6968, 6988, 7008, 7028, 7048, 7068, 7088, 7108, 7128, 7148, 7168, 7188, 7208, 7228, 7248, 7268, 7288, 7308, 7328, 7348, 7368, 7388, 7408, 7428, 7448, 7468, 7488, 7508, 7528, 7548, 7568, 7588, 7608, 7628, 7648, 7668, 7688, 7708, 7728, 7748, 7768, 7788, 7808, 7828, 7848, 7868, 7888, 7908, 7928, 7948, 7968, 7988, 8008, 8028, 8048, 8068, 8088, 8108, 8128, 8148, 8168, 8188, 8208, 8228, 8248, 8268, 8288, 8308, 8328, 8348, 8368, 8388, 8408, 8428, 8448, 8468, 8488, 8508, 8528, 8548, 8568, 8588, 8608, 8628, 8648, 8668, 8688, 8708, 8728, 8748, 8768, 8788, 8808, 8828, 8848, 8868, 8888, 8908, 8928, 8948, 8968, 8988, 9008, 9028, 9048, 9068, 9088, 9108, 9128, 9148, 9168, 9188, 9208, 9228, 9248, 9268, 9288, 9308, 9328, 9348, 9368, 9388, 9408, 9428, 9448, 9468, 9488, 9508, 9528, 9548, 9568, 9590, 9612, 9634, 9656, 9678, 9700, 9722, 9744, 9766, 9788, 9810, 9832, 9854, 9876, 9898, 9920, 9942, 9964, 9986, 10008, 10030, 10052, 10074, 10096, 10118, 10140, 10162, 10184, 10206, 10228, 10250, 10272, 10294, 10316, 10338, 10360, 10382, 10404, 10426, 10448, 10470, 10492, 10514, 10536, 10558, 10580, 10602, 10624, 10646, 10668, 10690, 10712, 10734, 10756, 10778, 10800, 10822, 10844, 10866, 10888, 10910, 10932, 10954, 10976, 10998, 11020, 11042, 11064, 11086, 11108, 11130, 11152, 11174, 11196, 11218, 11240, 11262, 11284, 11306, 11328, 11350, 11372, 11394, 11416, 11438, 11460, 11482, 11504, 11526, 11548, 11570, 11592, 11614, 11636, 11658, 11680, 11702, 11724, 11746, 11768, 11790, 11812, 11834, 11856, 11878, 11900, 11922, 11944, 11966, 11988, 12010, 12032, 12054, 12076, 12098, 12120, 12142, 12164, 12186, 12208, 12230, 12252, 12274, 12296, 12318, 12340, 12362, 12384, 12406, 12428, 12450, 12472, 12494, 12516, 12538, 12560, 12582, 12604, 12626, 12648, 12670, 12692, 12714, 12736, 12758, 12780, 12802, 12824, 12848, 12872, 12896, 12920, 12944, 12968, 12992, 13016, 13040, 13064, 13088, 13112, 13136, 13160, 13184, 13208, 13232, 13256, 13280, 13304, 13328, 13352, 13376, 13400, 13424, 13448, 13472, 13496, 13520, 13544, 13568, 13592, 13616, 13640, 13664, 13688, 13712, 13736, 13760, 13784, 13808, 13832, 13856, 13880, 13904, 13928, 13952, 13976, 14000, 14024, 14048, 14072, 14096, 14120, 14144, 14168, 14192, 14216, 14240, 14264, 14288, 14312, 14336, 14360, 14384, 14408, 14432, 14456, 14480, 14504, 14528, 14552, 14576, 14600, 14624, 14648, 14672, 14696, 14720, 14744, 14768, 14792, 14816, 14840, 14864, 14888, 14912, 14936, 14960, 14984, 15008, 15032, 15056, 15080, 15104, 15128, 15152, 15176, 15200, 15224, 15248, 15272, 15296, 15320, 15344, 15368, 15392, 15416, 15440, 15464, 15488, 15512, 15536, 15560, 15584, 15608, 15632, 15656, 15680, 15704, 15728, 15752, 15776, 15800, 15824, 15848, 15872, 15896, 15920, 15944, 15968, 15992, 16016, 16040, 16064, 16088, 16112, 16136, 16160, 16184, 16208, 16232, 16256, 16280, 16304, 16328, 16352, 16376, 16402, 16428, 16454, 16480, 16506, 16532, 16558, 16584, 16610, 16636, 16662, 16688, 16714, 16740, 16766, 16792, 16818, 16844, 16870, 16896, 16922, 16948, 16974, 17000, 17026, 17052, 17078, 17104, 17130, 17156, 17182, 17208, 17234, 17260, 17286, 17312, 17338, 17364, 17390, 17416, 17442, 17468, 17494, 17520, 17546, 17572, 17598, 17624, 17650, 17676, 17702, 17728, 17754, 17780, 17806, 17832, 17858, 17884, 17910, 17936, 17962, 17988, 18014, 18040, 18066, 18092, 18118, 18144, 18170, 18196, 18222, 18248, 18274, 18300, 18326, 18352, 18378, 18404, 18430, 18456, 18482, 18508, 18534, 18560, 18586, 18612, 18638, 18664, 18690, 18716, 18742, 18768, 18794, 18820, 18846, 18872, 18898, 18924, 18950, 18976, 19002, 19028, 19054, 19080, 19106, 19132, 19158, 19184, 19210, 19236, 19262, 19288, 19314, 19340, 19366, 19392, 19418, 19444, 19470, 19496, 19522, 19548, 19574, 19600, 19626, 19652, 19678, 19704, 19730, 19756, 19782, 19810, 19838, 19866, 19894, 19922, 19950, 19978, 20006, 20034, 20062, 20090, 20118, 20146, 20174, 20202, 20230, 20258, 20286, 20314, 20342, 20370, 20398, 20426, 20454, 20482, 20510, 20538, 20566, 20594, 20622, 20650, 20678, 20706, 20734, 20762, 20790, 20818, 20846, 20874, 20902, 20930, 20958, 20986, 21014, 21042, 21070, 21098, 21126, 21154, 21182, 21210, 21238, 21266, 21294, 21322, 21350, 21378, 21406, 21434, 21462, 21490, 21518, 21546, 21574, 21602, 21630, 21658, 21686, 21714, 21742, 21770, 21798, 21826, 21854, 21882, 21910, 21938, 21966, 21994, 22022, 22050, 22078, 22106, 22134, 22162, 22190, 22218, 22246, 22274, 22302, 22330, 22358, 22386, 22414, 22442, 22470, 22498, 22528, 22558, 22588, 22618, 22648, 22678, 22708, 22738, 22768, 22798, 22828, 22858, 22888, 22918, 22948, 22978, 23008, 23038, 23068, 23098, 23128, 23158, 23188, 23218, 23248, 23278, 23308, 23338, 23368, 23398, 23428, 23458, 23488, 23518, 23548, 23578, 23608, 23638, 23668, 23698, 23728, 23758, 23788, 23818, 23848, 23878, 23908, 23938, 23968, 23998, 24028, 24058, 24088, 24118, 24148, 24178, 24208, 24238, 24268, 24298, 24328, 24358, 24388, 24418, 24448, 24480, 24512, 24544, 24576, 24608, 24640, 24672, 24704, 24736, 24768, 24800, 24832, 24864, 24896, 24928, 24960, 24992, 25024, 25056, 25088, 25120, 25152, 25184, 25216, 25248, 25280, 25312, 25344, 25376, 25408, 25440, 25472, 25504, 25536, 25568, 25600, 25632, 25664, 25696, 25728, 25760, 25794, 25828, 25862, 25896, 25930, 25964, 25998, 26032, 26066, 26100, 26134, 26168, 26202, 26236, 26270, 26304, 26338, 26372, 26406, 26440, 26474, 26510, 26546, 26582, 26618, 26654, 26690, 26726, 26762, 26798, 26834, 26872, 26910, 26948, 26986, 27024, 27064, 27104, 27146}; __END_DECLS igraph/src/dsapps.f0000644000175100001440000004431213431000472013770 0ustar hornikusersc----------------------------------------------------------------------- c\BeginDoc c c\Name: igraphdsapps c c\Description: c Given the Arnoldi factorization c c A*V_{k} - V_{k}*H_{k} = r_{k+p}*e_{k+p}^T, c c apply NP shifts implicitly resulting in c c A*(V_{k}*Q) - (V_{k}*Q)*(Q^T* H_{k}*Q) = r_{k+p}*e_{k+p}^T * Q c c where Q is an orthogonal matrix of order KEV+NP. Q is the product of c rotations resulting from the NP bulge chasing sweeps. The updated Arnoldi c factorization becomes: c c A*VNEW_{k} - VNEW_{k}*HNEW_{k} = rnew_{k}*e_{k}^T. c c\Usage: c call igraphdsapps c ( N, KEV, NP, SHIFT, V, LDV, H, LDH, RESID, Q, LDQ, WORKD ) c c\Arguments c N Integer. (INPUT) c Problem size, i.e. dimension of matrix A. c c KEV Integer. (INPUT) c INPUT: KEV+NP is the size of the input matrix H. c OUTPUT: KEV is the size of the updated matrix HNEW. c c NP Integer. (INPUT) c Number of implicit shifts to be applied. c c SHIFT Double precision array of length NP. (INPUT) c The shifts to be applied. c c V Double precision N by (KEV+NP) array. (INPUT/OUTPUT) c INPUT: V contains the current KEV+NP Arnoldi vectors. c OUTPUT: VNEW = V(1:n,1:KEV); the updated Arnoldi vectors c are in the first KEV columns of V. c c LDV Integer. (INPUT) c Leading dimension of V exactly as declared in the calling c program. c c H Double precision (KEV+NP) by 2 array. (INPUT/OUTPUT) c INPUT: H contains the symmetric tridiagonal matrix of the c Arnoldi factorization with the subdiagonal in the 1st column c starting at H(2,1) and the main diagonal in the 2nd column. c OUTPUT: H contains the updated tridiagonal matrix in the c KEV leading submatrix. c c LDH Integer. (INPUT) c Leading dimension of H exactly as declared in the calling c program. c c RESID Double precision array of length (N). (INPUT/OUTPUT) c INPUT: RESID contains the the residual vector r_{k+p}. c OUTPUT: RESID is the updated residual vector rnew_{k}. c c Q Double precision KEV+NP by KEV+NP work array. (WORKSPACE) c Work array used to accumulate the rotations during the bulge c chase sweep. c c LDQ Integer. (INPUT) c Leading dimension of Q exactly as declared in the calling c program. c c WORKD Double precision work array of length 2*N. (WORKSPACE) c Distributed array used in the application of the accumulated c orthogonal matrix Q. c c\EndDoc c c----------------------------------------------------------------------- c c\BeginLib c c\Local variables: c xxxxxx real c c\References: c 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in c a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), c pp 357-385. c 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly c Restarted Arnoldi Iteration", Rice University Technical Report c TR95-13, Department of Computational and Applied Mathematics. c c\Routines called: c igraphivout ARPACK utility routine that prints integers. c igraphsecond ARPACK utility routine for timing. c igraphdvout ARPACK utility routine that prints vectors. c dlamch LAPACK routine that determines machine constants. c dlartg LAPACK Givens rotation construction routine. c dlacpy LAPACK matrix copy routine. c dlaset LAPACK matrix initialization routine. c dgemv Level 2 BLAS routine for matrix vector multiplication. c daxpy Level 1 BLAS that computes a vector triad. c dcopy Level 1 BLAS that copies one vector to another. c dscal Level 1 BLAS that scales a vector. c c\Author c Danny Sorensen Phuong Vu c Richard Lehoucq CRPC / Rice University c Dept. of Computational & Houston, Texas c Applied Mathematics c Rice University c Houston, Texas c c\Revision history: c 12/16/93: Version ' 2.1' c c\SCCS Information: @(#) c FILE: sapps.F SID: 2.5 DATE OF SID: 4/19/96 RELEASE: 2 c c\Remarks c 1. In this version, each shift is applied to all the subblocks of c the tridiagonal matrix H and not just to the submatrix that it c comes from. This routine assumes that the subdiagonal elements c of H that are stored in h(1:kev+np,1) are nonegative upon input c and enforce this condition upon output. This version incorporates c deflation. See code for documentation. c c\EndLib c c----------------------------------------------------------------------- c subroutine igraphdsapps & ( n, kev, np, shift, v, ldv, h, ldh, resid, q, ldq, workd ) c c %----------------------------------------------------% c | Include files for debugging and timing information | c %----------------------------------------------------% c include 'debug.h' include 'stat.h' c c %------------------% c | Scalar Arguments | c %------------------% c integer kev, ldh, ldq, ldv, n, np c c %-----------------% c | Array Arguments | c %-----------------% c Double precision & h(ldh,2), q(ldq,kev+np), resid(n), shift(np), & v(ldv,kev+np), workd(2*n) c c %------------% c | Parameters | c %------------% c Double precision & one, zero parameter (one = 1.0D+0, zero = 0.0D+0) c c %---------------% c | Local Scalars | c %---------------% c integer i, iend, istart, itop, j, jj, kplusp, msglvl logical first Double precision & a1, a2, a3, a4, big, c, epsmch, f, g, r, s save epsmch, first c c c %----------------------% c | External Subroutines | c %----------------------% c external daxpy, dcopy, dscal, dlacpy, dlartg, dlaset, & igraphdvout, igraphivout, igraphsecond, dgemv c c %--------------------% c | External Functions | c %--------------------% c Double precision & dlamch external dlamch c c %----------------------% c | Intrinsics Functions | c %----------------------% c intrinsic abs c c %----------------% c | Data statments | c %----------------% c data first / .true. / c c %-----------------------% c | Executable Statements | c %-----------------------% c if (first) then epsmch = dlamch('Epsilon-Machine') first = .false. end if itop = 1 c c %-------------------------------% c | Initialize timing statistics | c | & message level for debugging | c %-------------------------------% c call igraphsecond (t0) msglvl = msapps c kplusp = kev + np c c %----------------------------------------------% c | Initialize Q to the identity matrix of order | c | kplusp used to accumulate the rotations. | c %----------------------------------------------% c call dlaset ('All', kplusp, kplusp, zero, one, q, ldq) c c %----------------------------------------------% c | Quick return if there are no shifts to apply | c %----------------------------------------------% c if (np .eq. 0) go to 9000 c c %----------------------------------------------------------% c | Apply the np shifts implicitly. Apply each shift to the | c | whole matrix and not just to the submatrix from which it | c | comes. | c %----------------------------------------------------------% c do 90 jj = 1, np c istart = itop c c %----------------------------------------------------------% c | Check for splitting and deflation. Currently we consider | c | an off-diagonal element h(i+1,1) negligible if | c | h(i+1,1) .le. epsmch*( |h(i,2)| + |h(i+1,2)| ) | c | for i=1:KEV+NP-1. | c | If above condition tests true then we set h(i+1,1) = 0. | c | Note that h(1:KEV+NP,1) are assumed to be non negative. | c %----------------------------------------------------------% c 20 continue c c %------------------------------------------------% c | The following loop exits early if we encounter | c | a negligible off diagonal element. | c %------------------------------------------------% c do 30 i = istart, kplusp-1 big = abs(h(i,2)) + abs(h(i+1,2)) if (h(i+1,1) .le. epsmch*big) then if (msglvl .gt. 0) then call igraphivout (logfil, 1, i, ndigit, & '_sapps: deflation at row/column no.') call igraphivout (logfil, 1, jj, ndigit, & '_sapps: occured before shift number.') call igraphdvout (logfil, 1, h(i+1,1), ndigit, & '_sapps: the corresponding off diagonal element') end if h(i+1,1) = zero iend = i go to 40 end if 30 continue iend = kplusp 40 continue c if (istart .lt. iend) then c c %--------------------------------------------------------% c | Construct the plane rotation G'(istart,istart+1,theta) | c | that attempts to drive h(istart+1,1) to zero. | c %--------------------------------------------------------% c f = h(istart,2) - shift(jj) g = h(istart+1,1) call dlartg (f, g, c, s, r) c c %-------------------------------------------------------% c | Apply rotation to the left and right of H; | c | H <- G' * H * G, where G = G(istart,istart+1,theta). | c | This will create a "bulge". | c %-------------------------------------------------------% c a1 = c*h(istart,2) + s*h(istart+1,1) a2 = c*h(istart+1,1) + s*h(istart+1,2) a4 = c*h(istart+1,2) - s*h(istart+1,1) a3 = c*h(istart+1,1) - s*h(istart,2) h(istart,2) = c*a1 + s*a2 h(istart+1,2) = c*a4 - s*a3 h(istart+1,1) = c*a3 + s*a4 c c %----------------------------------------------------% c | Accumulate the rotation in the matrix Q; Q <- Q*G | c %----------------------------------------------------% c do 60 j = 1, min(istart+jj,kplusp) a1 = c*q(j,istart) + s*q(j,istart+1) q(j,istart+1) = - s*q(j,istart) + c*q(j,istart+1) q(j,istart) = a1 60 continue c c c %----------------------------------------------% c | The following loop chases the bulge created. | c | Note that the previous rotation may also be | c | done within the following loop. But it is | c | kept separate to make the distinction among | c | the bulge chasing sweeps and the first plane | c | rotation designed to drive h(istart+1,1) to | c | zero. | c %----------------------------------------------% c do 70 i = istart+1, iend-1 c c %----------------------------------------------% c | Construct the plane rotation G'(i,i+1,theta) | c | that zeros the i-th bulge that was created | c | by G(i-1,i,theta). g represents the bulge. | c %----------------------------------------------% c f = h(i,1) g = s*h(i+1,1) c c %----------------------------------% c | Final update with G(i-1,i,theta) | c %----------------------------------% c h(i+1,1) = c*h(i+1,1) call dlartg (f, g, c, s, r) c c %-------------------------------------------% c | The following ensures that h(1:iend-1,1), | c | the first iend-2 off diagonal of elements | c | H, remain non negative. | c %-------------------------------------------% c if (r .lt. zero) then r = -r c = -c s = -s end if c c %--------------------------------------------% c | Apply rotation to the left and right of H; | c | H <- G * H * G', where G = G(i,i+1,theta) | c %--------------------------------------------% c h(i,1) = r c a1 = c*h(i,2) + s*h(i+1,1) a2 = c*h(i+1,1) + s*h(i+1,2) a3 = c*h(i+1,1) - s*h(i,2) a4 = c*h(i+1,2) - s*h(i+1,1) c h(i,2) = c*a1 + s*a2 h(i+1,2) = c*a4 - s*a3 h(i+1,1) = c*a3 + s*a4 c c %----------------------------------------------------% c | Accumulate the rotation in the matrix Q; Q <- Q*G | c %----------------------------------------------------% c do 50 j = 1, min( j+jj, kplusp ) a1 = c*q(j,i) + s*q(j,i+1) q(j,i+1) = - s*q(j,i) + c*q(j,i+1) q(j,i) = a1 50 continue c 70 continue c end if c c %--------------------------% c | Update the block pointer | c %--------------------------% c istart = iend + 1 c c %------------------------------------------% c | Make sure that h(iend,1) is non-negative | c | If not then set h(iend,1) <-- -h(iend,1) | c | and negate the last column of Q. | c | We have effectively carried out a | c | similarity on transformation H | c %------------------------------------------% c if (h(iend,1) .lt. zero) then h(iend,1) = -h(iend,1) call dscal(kplusp, -one, q(1,iend), 1) end if c c %--------------------------------------------------------% c | Apply the same shift to the next block if there is any | c %--------------------------------------------------------% c if (iend .lt. kplusp) go to 20 c c %-----------------------------------------------------% c | Check if we can increase the the start of the block | c %-----------------------------------------------------% c do 80 i = itop, kplusp-1 if (h(i+1,1) .gt. zero) go to 90 itop = itop + 1 80 continue c c %-----------------------------------% c | Finished applying the jj-th shift | c %-----------------------------------% c 90 continue c c %------------------------------------------% c | All shifts have been applied. Check for | c | more possible deflation that might occur | c | after the last shift is applied. | c %------------------------------------------% c do 100 i = itop, kplusp-1 big = abs(h(i,2)) + abs(h(i+1,2)) if (h(i+1,1) .le. epsmch*big) then if (msglvl .gt. 0) then call igraphivout (logfil, 1, i, ndigit, & '_sapps: deflation at row/column no.') call igraphdvout (logfil, 1, h(i+1,1), ndigit, & '_sapps: the corresponding off diagonal element') end if h(i+1,1) = zero end if 100 continue c c %-------------------------------------------------% c | Compute the (kev+1)-st column of (V*Q) and | c | temporarily store the result in WORKD(N+1:2*N). | c | This is not necessary if h(kev+1,1) = 0. | c %-------------------------------------------------% c if ( h(kev+1,1) .gt. zero ) & call dgemv ('N', n, kplusp, one, v, ldv, & q(1,kev+1), 1, zero, workd(n+1), 1) c c %-------------------------------------------------------% c | Compute column 1 to kev of (V*Q) in backward order | c | taking advantage that Q is an upper triangular matrix | c | with lower bandwidth np. | c | Place results in v(:,kplusp-kev:kplusp) temporarily. | c %-------------------------------------------------------% c do 130 i = 1, kev call dgemv ('N', n, kplusp-i+1, one, v, ldv, & q(1,kev-i+1), 1, zero, workd, 1) call dcopy (n, workd, 1, v(1,kplusp-i+1), 1) 130 continue c c %-------------------------------------------------% c | Move v(:,kplusp-kev+1:kplusp) into v(:,1:kev). | c %-------------------------------------------------% c call dlacpy ('All', n, kev, v(1,np+1), ldv, v, ldv) c c %--------------------------------------------% c | Copy the (kev+1)-st column of (V*Q) in the | c | appropriate place if h(kev+1,1) .ne. zero. | c %--------------------------------------------% c if ( h(kev+1,1) .gt. zero ) & call dcopy (n, workd(n+1), 1, v(1,kev+1), 1) c c %-------------------------------------% c | Update the residual vector: | c | r <- sigmak*r + betak*v(:,kev+1) | c | where | c | sigmak = (e_{kev+p}'*Q)*e_{kev} | c | betak = e_{kev+1}'*H*e_{kev} | c %-------------------------------------% c call dscal (n, q(kplusp,kev), resid, 1) if (h(kev+1,1) .gt. zero) & call daxpy (n, h(kev+1,1), v(1,kev+1), 1, resid, 1) c if (msglvl .gt. 1) then call igraphdvout (logfil, 1, q(kplusp,kev), ndigit, & '_sapps: sigmak of the updated residual vector') call igraphdvout (logfil, 1, h(kev+1,1), ndigit, & '_sapps: betak of the updated residual vector') call igraphdvout (logfil, kev, h(1,2), ndigit, & '_sapps: updated main diagonal of H for next iteration') if (kev .gt. 1) then call igraphdvout (logfil, kev-1, h(2,1), ndigit, & '_sapps: updated sub diagonal of H for next iteration') end if end if c call igraphsecond (t1) tsapps = tsapps + (t1 - t0) c 9000 continue return c c %---------------% c | End of igraphdsapps | c %---------------% c end igraph/configure.win0000644000175100001440000000000013177712334014240 0ustar hornikusersigraph/R/0000755000175100001440000000000013562737551011761 5ustar hornikusersigraph/R/pp.R0000644000175100001440000000201513177712334012513 0ustar hornikusers # IGraph R package # Copyright (C) 2014 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### get.all.simple.paths.pp <- function(vect) { .Call(C_R_igraph_get_all_simple_paths_pp, vect) } igraph/R/print.R0000644000175100001440000006225613177712334013245 0ustar hornikusers ## ---------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ---------------------------------------------------------------------- ################################################################### # Convert graphs to human readable forms ################################################################### .get.attr.codes <- function(object) { ga <- va <- ea <- "" gal <- graph_attr_names(object) if (length(gal) != 0) { ga <- paste(sep="", gal, " (g/", .Call(C_R_igraph_get_attr_mode, object, 2L), ")") } val <- vertex_attr_names(object) if (length(val) != 0) { va <- paste(sep="", val, " (v/", .Call(C_R_igraph_get_attr_mode, object, 3L), ")") } eal <- edge_attr_names(object) if (length(eal) != 0) { ea <- paste(sep="", edge_attr_names(object), " (e/", .Call(C_R_igraph_get_attr_mode, object, 4L), ")") } c(ga, va, ea) } .print.header <- function(object) { if (!is_igraph(object)) { stop("Not a graph object") } title <- paste(sep="", "IGRAPH ", substr(graph_id(object), 1, 7), " ", c("U","D")[is_directed(object)+1], c("-","N")[is_named(object)+1], c("-","W")[is_weighted(object)+1], c("-","B")[is_bipartite(object)+1], " ", vcount(object), " ", ecount(object), " -- ") w <- getOption("width") if (nchar(title) < w && "name" %in% graph_attr_names(object)) { title <- substring(paste(sep="", title, as.character(object$name)[1]), 1, w-1) } cat(title, "\n", sep="") atxt <- .get.attr.codes(object) atxt <- paste(atxt[atxt!=""], collapse=", ") if (atxt != "") { atxt <- strwrap(paste(sep="", "+ attr: ", atxt), prefix = "| ", initial = "") cat(atxt, sep="\n") } 1 + if (length(atxt) == 1 && atxt == "") 0 else length(atxt) } #' @importFrom utils capture.output .print.graph.attributes <- function(x, full, max.lines) { list <- graph_attr_names(x) if (length(list)!=0) { cat("+ graph attributes:\n") out <- capture.output({ lapply(list, function(n) { cat(sep="", "+ ", n, ":\n") indent_print(graph_attr(x, n), .indent = " ") }) invisible(NULL) }) indent_print(out, sep = "\n", .indent = "| ", .printer = cat) length(out) + 1 } else { 0 } } ## IGRAPH U--- 10 10 -- Ring graph ## + attr: name (g/c), mutual (g/l), circular (g/l) ## + graph attributes: ## | + name: ## | [1] "Ring graph" ## | + mutual: ## | [1] FALSE ## | + circular= ## | [1] TRUE ## | + layout = ## | [,1] [,2] ## | [1,] 0.000000 0.000000e+00 ## | [2,] 1.000000 0.000000e+00 ## | [3,] 0.809017 5.877853e-01 ## | [4,] 0.309017 9.510565e-01 ## | [5,] -0.309017 9.510565e-01 ## | [6,] -0.809017 5.877853e-01 ## | [7,] -1.000000 1.224647e-16 ## | [8,] -0.809017 -5.877853e-01 ## | [9,] -0.309017 -9.510565e-01 ## | [10,] 0.309017 -9.510565e-01 ## | [11,] 0.809017 -5.877853e-01 ## + edges: ## [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10 .print.vertex.attributes <- function(x, full, max.lines) { pf <- function(x) .print.vertex.attributes.old(x, full, max.lines) if (length(vertex_attr_names(x))) cat("+ vertex attributes:\n") indent_print(x, .indent = "| ", .printer = pf) } .print.vertex.attributes.old <- function(x, full, max.lines) { vc <- vcount(x) list <- vertex_attr_names(x) if (length(list) != 0) { mp <- getOption("max.print") options(max.print=1000000000) if (vc <= mp) { omitted.vertices <- 0 ind <- as.numeric(V(x)) } else { omitted.vertices <- vc-mp ind <- seq(length=mp) } if (vc==0 || all(sapply(list, function(v) is.numeric(vertex_attr(x, v)) || is.character(vertex_attr(x, v)) || is.logical(vertex_attr(x, v))))) { ## create a table tab <- data.frame(v=paste(sep="", "[", ind, "]"), row.names="v") for (i in list) { tab[i] <- vertex_attr(x, i, ind) } print(tab) } else { for (i in ind) { cat(sep="", "[[", i, "]]\n") lapply(list, function(n) { cat(sep="", "[[", i, "]][[", n, "]]\n") print(vertex_attr(x, n, i))}) } } options(max.print=mp) if (omitted.vertices != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.vertices, "vertices ]\n\n")) } } } .print.edges.edgelist <- function(x, edges = E(x), names) { ec <- length(edges) list <- edge_attr_names(x) list <- list[list!="name"] arrow <- ifelse(is_directed(x), "->", "--") if (is_named(x)) { cat("+ edges (vertex names) and their attributes:\n") } else { cat("+ edges and their attributes:\n") } if (names && ! "name" %in% vertex_attr_names(x)) { names <- FALSE } if (names && "name" %in% vertex_attr_names(x) && !is.numeric(vertex_attr(x, "name")) && !is.character(vertex_attr(x, "name")) && !is.logical(vertex_attr(x, "name"))) { warning("Can't print vertex names, complex `name' vertex attribute") names <- FALSE } mp <- getOption("max.print") if (mp >= ec) { omitted.edges <- 0 el <- ends(x, edges, names=names) } else { omitted.edges <- ec-mp el <- ends(x, ends[seq_len(mp)]) if (names) { el[] <- V(x)$name[el] } } ename <- if ("name" %in% edge_attr_names(x)) { paste(sep="", "'", E(x)$name, "'") } else { seq(length=nrow(el)) } if (ec==0 || all(sapply(list, function(v) is.numeric(edge_attr(x, v)) | is.character(edge_attr(x,v)) | is.logical(edge_attr(x, v))))) { ## create a table tab <- data.frame(row.names=paste(sep="", "[", ename, "]")) if (is.numeric(el)) { w <- nchar(max(el)) } else { w <- max(nchar(el)) } tab["edge"] <- paste(sep="", format(el[,1], width=w), arrow, format(el[,2], width=w)) for (i in list) { tab[i] <- edge_attr(x, i) } print(tab) } else { i <- 1 apply(el, 1, function(v) { cat(sep="", "[", ename[i], "] ", v[1], " ", arrow, " ", v[2]); lapply(list, function(n) { cat(sep="", "\n[[", i, "]][[", n, "]]\n") print(edge_attr(x, n, i))}) cat("\n") i <<- i+1 }) } if (omitted.edges != 0) { cat(paste('[ reached getOption("max.print") -- omitted', omitted.edges, 'edges ]\n\n')) } } .print.edges.compressed <- function(x, edges = E(x), names, num = FALSE, max.lines = igraph_opt("auto.print.lines")) { len <- length(edges) id <- graph_id(edges) title <- "+" %+% (if (num) " " %+% chr(len) %+% "/" %+% (if (is.null(x)) "?" else chr(gsize(x))) else "") %+% (if (len == 1) " edge" else " edges") %+% (if (!is.na(id)) paste(" from", substr(id, 1, 7)) else " unknown") %+% (if (is.null(x)) " (deleted)" else "") %+% (if (is.null(attr(edges, "vnames"))) "" else " (vertex names)") %+% ":\n" cat(title) if (!is.null(attr(edges, "single")) && attr(edges, "single") && !is.null(x)) { ## Double bracket ea <- edge_attr(x) if (all(sapply(ea, is.atomic))) { etail <- tail_of(x, edges) ehead <- head_of(x, edges) df <- data.frame( stringsAsFactors = FALSE, tail = as_ids(etail), head = as_ids(ehead), tid = as.vector(etail), hid = as.vector(ehead) ) if (length(ea)) { ea <- do_call(data.frame, .args = ea, stringsAsFactors = FALSE) df <- cbind(df, ea[as.vector(edges), , drop = FALSE]) } print(df) } else { print(lapply(ea, "[", as.vector(edges))) } } else if (is.null(max.lines)) { .print.edges.compressed.all(x, edges, names) } else { .print.edges.compressed.limit(x, edges, names, max.lines) } } .print.edges.compressed.all <- function(x, edges, names) { arrow <- c("--", "->")[is_directed(x)+1] if (!is.null(x)) { el <- ends(x, edges, names=names) pr <- paste(sep="", format(el[,1]), arrow, format(el[,2])) print(pr, quote=FALSE) } else { if (!is.null(attr(edges, "vnames"))) { print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { print(names(edges), quote = FALSE) } else { print(as.vector(edges)) } } } #' @importFrom utils capture.output .print.edges.compressed.limit <- function(x, edges, names, max.lines) { if (!is.null(x)) { arrow <- c("--", "->")[is_directed(x)+1] can_max <- NA el <- NA fun <- function(q, no) { if (q == "length") { length(edges) } else if (q == "min_width") { 5 } else if (q == "width") { el <<- ends(x, edges[seq_len(no)], names = names) cummax(nchar(el[,1])) + nchar(arrow) + cummax(nchar(el[,2])) + 1 } else if (q == "print") { el <<- el[seq_len(no), , drop = FALSE] out <- paste(sep="", format(el[,1]), arrow, format(el[,2])) capture.output(print(out, quote = FALSE)) } else if (q == "max") { can_max <<- no } else if (q == "done") { if (no["tried_items"] < length(edges) || no["printed_lines"] < no["tried_lines"]) { cat("+ ... omitted several edges\n") } } } fun <- printer_callback(fun) head_print(fun, max_lines = max.lines) } else { if (!is.null(attr(edges, "vnames"))) { head_print(as.vector(attr(edges, "vnames")), quote = FALSE) } else if (!is.null(names(edges))) { head_print(names(edges), quote = FALSE) } else { head_print(as.vector(edges)) } } } .print.edges.adjlist <- function(x) { ## TODO: getOption("max.print") cat("+ edges:\n") vc <- vcount(x) arrow <- c(" -- ", " -> ")[is_directed(x)+1] al <- as_adj_list(x, mode="out") w <- nchar(max(which(degree(x, mode="in") != 0))) mpl <- trunc((getOption("width")-nchar(arrow)-nchar(vc)) / (w+1)) if (any(sapply(al, length) > mpl)) { ## Wrapping needed mw <- nchar(vcount(x)) sm <- paste(collapse="", rep(" ", mw+4)) alstr <- lapply(seq_along(al), function(x) { len <- length(al[[x]]) fac <- rep(1:(len/mpl+1), each=mpl, length=len) nei <- tapply(format(al[[x]], width=mw), fac, paste, collapse=" ") mark <- paste(sep="", format(x, width=mw), arrow) mark <- c(mark, rep(sm, max(0, length(nei)-1))) paste(sep="", mark, nei) }) cat(unlist(alstr), sep="\n") } else { alstr <- sapply(al, function(x) { paste(format(x, width=w), collapse=" ") }) mark <- paste(sep="", format(seq_len(vc)), arrow) alstr <- paste(sep="", mark, alstr) maxw <- max(nchar(alstr)) sep <- " " ncol <- trunc((getOption("width")-1+nchar(sep)) / (maxw+nchar(sep))) if (ncol > 1) { alstr <- format(alstr, width=maxw, justify="left") fac <- rep(1:(vc/ncol+1), each=ncol, length=vc) alstr <- tapply(alstr, fac, paste, collapse=sep) } cat(alstr, sep="\n") } } .print.edges.adjlist.named <- function(x, edges = E(x)) { ## TODO getOption("max.print") cat("+ edges (vertex names):\n") arrow <- c(" -- ", " -> ")[is_directed(x)+1] vn <- V(x)$name al <- as_adj_list(x, mode="out") alstr <- sapply(al, function(x) { paste(collapse=", ", vn[x]) }) alstr <- paste(sep="", format(vn), arrow, alstr) alstr <- strwrap(alstr, exdent=max(nchar(vn))+nchar(arrow)) cat(alstr, sep="\n") } #' @export print_all <- function(object, ...) { print.igraph(object, full=TRUE, ...) } #' Print graphs to the terminal #' #' These functions attempt to print a graph to the terminal in a human readable #' form. #' #' \code{summary.igraph} prints the number of vertices, edges and whether the #' graph is directed. #' #' \code{print_all} prints the same information, and also lists the edges, and #' optionally graph, vertex and/or edge attributes. #' #' \code{print.igraph} behaves either as \code{summary.igraph} or #' \code{print_all} depending on the \code{full} argument. See also the #' \sQuote{print.full} igraph option and \code{\link{igraph_opt}}. #' #' The graph summary printed by \code{summary.igraph} (and \code{print.igraph} #' and \code{print_all}) consists one or more lines. The first line contains #' the basic properties of the graph, and the rest contains its attributes. #' Here is an example, a small star graph with weighted directed edges and named #' vertices: \preformatted{ IGRAPH badcafe DNW- 10 9 -- In-star #' + attr: name (g/c), mode (g/c), center (g/n), name (v/c), #' weight (e/n) } #' The first line always #' starts with \code{IGRAPH}, showing you that the object is an igraph graph. #' Then a seven character code is printed, this the first seven characters #' of the unique id of the graph. See \code{\link{graph_id}} for more. #' Then a four letter long code string is printed. The first letter #' distinguishes between directed (\sQuote{\code{D}}) and undirected #' (\sQuote{\code{U}}) graphs. The second letter is \sQuote{\code{N}} for named #' graphs, i.e. graphs with the \code{name} vertex attribute set. The third #' letter is \sQuote{\code{W}} for weighted graphs, i.e. graphs with the #' \code{weight} edge attribute set. The fourth letter is \sQuote{\code{B}} for #' bipartite graphs, i.e. for graphs with the \code{type} vertex attribute set. #' #' Then, after two dashes, the name of the graph is printed, if it has one, #' i.e. if the \code{name} graph attribute is set. #' #' From the second line, the attributes of the graph are listed, separated by a #' comma. After the attribute names, the kind of the attribute -- graph #' (\sQuote{\code{g}}), vertex (\sQuote{\code{v}}) or edge (\sQuote{\code{e}}) #' -- is denoted, and the type of the attribute as well, character #' (\sQuote{\code{c}}), numeric (\sQuote{\code{n}}), logical #' (\sQuote{\code{l}}), or other (\sQuote{\code{x}}). #' #' As of igraph 0.4 \code{print_all} and \code{print.igraph} use the #' \code{max.print} option, see \code{\link[base]{options}} for details. #' #' As of igraph 1.1.1, the \code{str.igraph} function is defunct, use #' \code{print_all()}. #' #' @aliases print.igraph print_all summary.igraph str.igraph #' @param x The graph to print. #' @param full Logical scalar, whether to print the graph structure itself as #' well. #' @param graph.attributes Logical constant, whether to print graph attributes. #' @param vertex.attributes Logical constant, whether to print vertex #' attributes. #' @param edge.attributes Logical constant, whether to print edge attributes. #' @param names Logical constant, whether to print symbolic vertex names (ie. #' the \code{name} vertex attribute) or vertex ids. #' @param max.lines The maximum number of lines to use. The rest of the #' output will be truncated. #' @param object The graph of which the summary will be printed. #' @param \dots Additional agruments. #' @return All these functions return the graph invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method print igraph #' @export #' @export print.igraph #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g #' summary(g) #' print.igraph <- function(x, full=igraph_opt("print.full"), graph.attributes=igraph_opt("print.graph.attributes"), vertex.attributes=igraph_opt("print.vertex.attributes"), edge.attributes=igraph_opt("print.edge.attributes"), names=TRUE, max.lines = igraph_opt("auto.print.lines"), ...) { if (!is_igraph(x)) { stop("Not a graph object") } head_lines <- .print.header(x) if (is.logical(full) && full) { if (graph.attributes) { head_lines <- head_lines + .print.graph.attributes(x, full, max.lines) } if (vertex.attributes) { head_lines <- head_lines + .print.vertex.attributes(x, full, max.lines) } if (ecount(x)==0) { ## Do nothing } else if (edge.attributes && length(edge_attr_names(x)) != 0 ) { .print.edges.edgelist(x, names = names) } else if (median(degree(x, mode="out")) < 3) { .print.edges.compressed(x, names = names, max.lines = NULL) } else if (is_named(x)) { .print.edges.adjlist.named(x) } else { .print.edges.adjlist(x) } } else if (full == "auto") { .print.edges.compressed(x, names = names, max.lines = max.lines - head_lines) } invisible(x) } #' @rdname print.igraph #' @method summary igraph #' @export summary.igraph <- function(object, ...) { .print.header(object) invisible(object) } " #################################################################### ## Various designs for printing graphs ## Summary IGRAPH UNW- 5 5 -- A ring Attr: name (g/c), name (v/c), weight (e/n) IGRAPH D-W- 100 200 -- Gnm random graph ## Printing, edge list IGRAPH-UNW--V5-E5----------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + edges: edge weight [1]' a--b 1 [2]' b--c 2 [3]' c--d -1 [4]' d--e 0.5 [5]' a--e 1 ## Compressed edge list IGRAPH UNW- 5 10 -- A ring + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1--2 2--3 3--4 4--5 1--5 2--5 5--1 [8]' 1--4 4--2 1--3 ## This is good if vertices are named IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- [1] Beverly, Carol, Diane, Fernando Beverly -- [1] Andre, Diane, Ed, Garth Carol -- [1] Andre, Diane, Fernando Diane -- [1] Andre, Beverly, Carol, Diane, Ed -- [6] Garth Ed -- [1] Beverly, Diane, Garth Fernando -- [1] Andre, Carol, Diane, Garth Garth -- [1] Beverly, Diane, Ed, Fernando Heather -- [1] Fernando, Garth Ike -- [1] Heather, Jane Jane -- [1] Ike IGRAPH UNW- 10 18 -- Krackhardt kite + attributes: name (g/c), name (v/c), weight (e/n) + edges: Andre -- Beverly, Carol, Diane, Fernando Beverly -- Andre, Diane, Ed, Garth Carol -- Andre, Diane, Fernando Diane -- Andre, Beverly, Carol, Diane, Ed, Garth Ed -- Beverly, Diane, Garth Fernando -- Andre, Carol, Diane, Garth Garth -- Beverly, Diane, Ed, Fernando Heather -- Fernando, Garth Ike -- Heather, Jane Jane -- Ike ## This is the good one if vertices are not named IGRAPH U--- 100 200 -- Gnm random graph + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... ## Alternative designs, summary IGRAPH-UNW--V5-E5,---------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) IGRAPH. |V|=5, |E|=5, undirected, named, weighted. Attributes: name (g/c), name (v/c), weight (e/n) IGRAPH: 'A ring' Graph attributes: |V|=5, |E|=5, undirected, name. Vertex attributes: name. Edge attributes: weight. ## Alternative designs, printing IGRAPH-UNW--V5-E5----------------------------------------- A ring - '- attributes: name (g), name (v), weight (e). ' edge weight [1] 'a' -- 'b' 1 [2] 'b' -- 'c' 2 [3] 'c' -- 'd' -1 [4] 'd' -- 'e' 0.5 [5] 'a' -- 'e' 1 IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - |- attributes: name (g), name (v), weight (e). |- edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g), name (v), weight (e). + vertices: | name | [1] a | [2] b | [3] c | [4] d | [5] e + edges: [1] 'a'--'b' 'b'--'c' 'c'--'d' 'd'--'e' 'a'--'e' 'b'-'e' [7] 'e'--'a' 'a'--'d' 'd'--'b' 'a'--'c' IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name + vertex attributes: name + edge attributes: weight + vertices: | name |1] a |2] b |3] c |4] d |5] e + edges: |1] a--b b--c c--d d--e a--e b-e |7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + graph attributes: name (c) + vertex attributes: name (c) + edge attributes: weight (n) + edges: [1] a--b b--c c--d d--e a--e b-e [7] e--a a--d d--b a--c IGRAPH-UNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a--b b--c c--d d--e a--e b--e e--a a--d d--b [10] a--c IGRAPH-DNW--V-5-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/n), weight (e/n) + edges: [1]' 1->2 2->3 3->4 4->5 1->5 2->5 5->1 [8]' 1->4 4->2 1->3 IGRAPH-UNW--V-5-E-20-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ 1] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c [11] a-b b-c c-d d-e a-e b-e e-a a-d d-b a-c IGRAPH-UNW--V-8-E-10-------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] b c e f h [b] a c e [c] a b d [d] a b c h [e] a b d [f] a [g] [h] a d IGRAPH-UNW--V-10-E-18------------------------------------- A ring - + attributes: name (g/c), name (v/c), weight (e/n) + edges: [a] a--{b,c,e,f,h} b--{a,c,e} c--{a,b,d} d--{a,b,c,h} [e] e--{a,b,d} f--{a} g--{} h--{a,d} IGRAPH-UNW--V10-E18------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly Carol Diane Fernando [ Beverly][1] Andre Diane Ed Garth [ Carol][1] Andre Diane Fernando [ Diane][1] Andre Beverly Carol Diane Ed [ Diane][6] Garth [ Ed][1] Beverly Diane Garth [Fernando][1] Andre Carol Diane Garth [ Garth][1] Beverly Diane Ed Fernando [ Heather][1] Fernando Garth [ Ike][1] Heather Jane [ Jane][1] Ike IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly/1 Carol/3 Diane/3 Fernando/1 [ Beverly][1] Andre/1 Diane/1 Ed/2 Garth/2 [ Carol][1] Andre/2 Diane/2 Fernando/1 [ Diane][1] Andre/5 Beverly/1 Carol/0.4 Diane/2 [ Diane][5] Ed/1.5 Garth/2.5 [ Ed][1] Beverly/-1 Diane/1.5 Garth/2 [Fernando][1] Andre/1 Carol/2 Diane/1 Garth/1 [ Garth][1] Beverly/2 Diane/3 Ed/1 Fernando/-1 [ Heather][1] Fernando/3 Garth/1 [ Ike][1] Heather/1 Jane/-1 [ Jane][1] Ike/-2 IGRAPH-UNW--V10-E18-------------------------------Krackhardt kite-- + attributes: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH UNW- V10 E18 -- Krackhardt kite + attr: name (g/c), name (v/c), weight (e/n) + edges: [ Andre][1] Beverly (1) Carol (3) Diane (3) Fernando (1) [ Beverly][1] Andre (1) Diane (1) Ed (2) Garth (2) [ Carol][1] Andre (2) Diane (2) Fernando (1) [ Diane][1] Andre (5) Beverly (1) Carol (0.5) Diane (2) [ Diane][5] Ed (1.5) Garth (2.5) [ Ed][1] Beverly (-1) Diane (1.5) Garth (2) [Fernando][1] Andre (1) Carol (2) Diane (1) Garth (1) [ Garth][1] Beverly (2) Diane (3) Ed (1) Fernando (-1) [ Heather][1] Fernando (3) Garth (1) [ Ike][1] Heather (1) Jane (-1) [ Jane][1] Ike (-2) IGRAPH-U----V100-E200----------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... IGRAPH-U----100-200------------------------------Gnm random graph-- + edges: [ 1] 28 46 89 90 [ 2] 47 69 72 89 [ 3] 29 [ 4] 17 20 [ 5] 11 40 42 51 78 89 [ 6] 27 32 70 87 93 [ 7] 18 27 87 [ 8] 18 24 82 [ 9] 18 20 85 94 [ 10] 24 70 77 91 [ 11] 5 12 34 61 62 [ 12] 11 41 44 61 65 80 ... " igraph/R/sir.R0000644000175100001440000001145513177712334012701 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' SIR model on graphs #' #' Run simulations for an SIR (susceptible-infected-recovered) model, on a #' graph #' #' The SIR model is a simple model from epidemiology. The individuals of the #' population might be in three states: susceptible, infected and recovered. #' Recovered people are assumed to be immune to the disease. Susceptibles #' become infected with a rate that depends on their number of infected #' neigbors. Infected people become recovered with a constant rate. #' #' The function \code{sir} simulates the model. #' #' Function \code{time_bins} bins the simulation steps, using the #' Freedman-Diaconis heuristics to determine the bin width. #' #' Function \code{median} and \code{quantile} calculate the median and #' quantiles of the results, respectively, in bins calculated with #' \code{time_bins}. #' #' @aliases median.sir quantile.sir time_bins time_bins.sir sir #' @param graph The graph to run the model on. If directed, then edge #' directions are ignored and a warning is given. #' @param beta Non-negative scalar. The rate of infection of an individual that #' is susceptible and has a single infected neighbor. The infection rate of a #' susceptible individual with n infected neighbors is n times beta. Formally #' this is the rate parameter of an exponential distribution. #' @param gamma Positive scalar. The rate of recovery of an infected #' individual. Formally, this is the rate parameter of an exponential #' distribution. #' @param no.sim Integer scalar, the number simulation runs to perform. #' @param x A \code{sir} object, returned by the \code{sir} function. #' @param middle Logical scalar, whether to return the middle of the time bins, #' or the boundaries. #' @param na.rm Logical scalar, whether to ignore \code{NA} values. \code{sir} #' objects do not contain any \code{NA} values currently, so this argument is #' effectively ignored. #' @param comp Character scalar. The component to calculate the quantile of. #' \code{NI} is infected agents, \code{NS} is susceptibles, \code{NR} stands #' for recovered. #' @param prob Numeric vector of probabilities, in [0,1], they specify the #' quantiles to calculate. #' @param \dots Additional arguments, ignored currently. #' @return For \code{sir} the results are returned in an object of class #' \sQuote{\code{sir}}, which is a list, with one element for each simulation. #' Each simulation is itself a list with the following elements. They are all #' numeric vectors, with equal length: \describe{ #' \item{times}{The times of the events.} #' \item{NS}{The number of susceptibles in the population, over time.} #' \item{NI}{The number of infected individuals in the population, over #' time.} #' \item{NR}{The number of recovered individuals in the population, over #' time.} #' } #' #' Function \code{time_bins} returns a numeric vector, the middle or the #' boundaries of the time bins, depending on the \code{middle} argument. #' #' \code{median} returns a list of three named numeric vectors, \code{NS}, #' \code{NI} and \code{NR}. The names within the vectors are created from the #' time bins. #' #' \code{quantile} returns the same vector as \code{median} (but only one, the #' one requested) if only one quantile is requested. If multiple quantiles are #' requested, then a list of these vectors is returned, one for each quantile. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com}. Eric Kolaczyk #' (\url{http://math.bu.edu/people/kolaczyk/}) wrote the initial version in R. #' @seealso \code{\link{plot.sir}} to conveniently plot the results #' @references Bailey, Norman T. J. (1975). The mathematical theory of #' infectious diseases and its applications (2nd ed.). London: Griffin. #' @keywords graphs #' @examples #' #' g <- sample_gnm(100, 100) #' sm <- sir(g, beta=5, gamma=1) #' plot(sm) #' @export sir <- sir igraph/R/structure.info.R0000644000175100001440000000350613177712334015074 0ustar hornikusers # IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Are two vertices adjacent? #' #' The order of the vertices only matters in directed graphs, #' where the existence of a directed \code{(v1, v2)} edge is queried. #' #' @aliases are.connected #' @param graph The graph. #' @param v1 The first vertex, tail in directed graphs. #' @param v2 The second vertex, head in directed graphs. #' @return A logical scalar, \code{TRUE} is a \code{(v1, v2)} exists in the #' graph. #' #' @family structural queries #' #' @export #' @examples #' ug <- make_ring(10) #' ug #' are_adjacent(ug, 1, 2) #' are_adjacent(ug, 2, 1) #' #' dg <- make_ring(10, directed = TRUE) #' dg #' are_adjacent(ug, 1, 2) #' are_adjacent(ug, 2, 1) are_adjacent <- function(graph, v1, v2) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_are_connected, graph, as.igraph.vs(graph, v1)-1, as.igraph.vs(graph, v2)-1) } igraph/R/make.R0000644000175100001440000014300413562503110013001 0ustar hornikusers ## ---------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------- #' Make a new graph #' #' This is is generic function for creating graphs. #' #' @details #' \code{make_} is a generic function for creating graphs. #' For every graph constructor in igraph that has a \code{make_} prefix, #' there is a corresponding function without the prefix: e.g. #' for \code{\link{make_ring}} there is also \code{\link{ring}}, etc. #' #' The same is true for the random graph samplers, i.e. for each #' constructor with a \code{sample_} prefix, there is a corresponding #' function without that prefix. #' #' These shorter forms can be used together with \code{make_}. #' The advantage of this form is that the user can specify constructor #' modifiers which work with all constructors. E.g. the #' \code{link{with_vertex_}} modifier adds vertex attributes #' to the newly created graphs. #' #' See the examples and the various constructor modifiers below. #' #' @param ... Parameters, see details below. #' #' @seealso simplified with_edge_ with_graph_ with_vertex_ #' without_loops without_multiples #' @export #' @examples #' r <- make_(ring(10)) #' l <- make_(lattice(c(3, 3, 3))) #' #' r2 <- make_(ring(10), with_vertex_(color = "red", name = LETTERS[1:10])) #' l2 <- make_(lattice(c(3, 3, 3)), with_edge_(weight = 2)) #' #' ran <- sample_(degseq(c(3,3,3,3,3,3), method = "simple"), simplified()) #' degree(ran) #' is_simple(ran) make_ <- function(...) { me <- attr(sys.function(), "name") %||% "construct" args <- list(...) cidx <- vapply(args, inherits, TRUE, what = "igraph_constructor_spec") if (sum(cidx) == 0) { stop("Don't know how to ", me, ", nothing given") } if (sum(cidx) > 1) { stop("Don't know how to ", me, ", multiple constructors given") } cons <- args[ cidx][[1]] args <- args[!cidx] ## Modifiers ## WRONG! wmods <- vapply(args, class, "") == "igraph_constructor_modifier" ## Correct: wmods <- vapply(args, inherits, TRUE, what = "igraph_constructor_modifier") mods <- args[wmods] args <- args[!wmods] args2 <- if (cons$lazy) lapply(cons$args, "[[", "expr") else lazy_eval(cons$args) res <- do_call(cons$fun, args2, args) for (m in mods) { if (m$id == "without_attr") { ## TODO: speed this up ga <- graph_attr_names(res) va <- vertex_attr_names(res) ea <- edge_attr_names(res) for (g in ga) res <- delete_graph_attr(res, g) for (v in va) res <- delete_vertex_attr(res, v) for (e in ea) res <- delete_edge_attr(res, e) } else if (m$id == "without_loops") { res <- simplify(res, remove.loops = TRUE, remove.multiple = FALSE) } else if (m$id == "without_multiples") { res <- simplify(res, remove.loops = FALSE, remove.multiple = TRUE) } else if (m$id == "simplified") { res <- simplify(res) } else if (m$id == "with_vertex_") { m$args <- lapply(m$args, eval) ## TODO speed this up for (a in seq_along(m$args)) { n <- names(m$args)[a] v <- m$args[[a]] stopifnot(! is.null(n)) res <- set_vertex_attr(res, n, value = v) } } else if (m$id == "with_edge_") { m$args <- lapply(m$args, eval) ## TODO speed this up for (a in seq_along(m$args)) { n <- names(m$args)[a] v <- m$args[[a]] stopifnot(! is.null(n)) res <- set_edge_attr(res, n, value = v) } } else if (m$id == "with_graph_") { m$args <- lapply(m$args, eval) ## TODO speed this up for (a in seq_along(m$args)) { n <- names(m$args)[a] v <- m$args[[a]] stopifnot(! is.null(n)) res <- set_graph_attr(res, n, value = v) } } } res } #' Sample from a random graph model #' #' Generic function for sampling from network models. #' #' @details #' TODO #' #' @param ... Parameters, see details below. #' #' @export #' @examples #' pref_matrix <- cbind(c(0.8, 0.1), c(0.1, 0.7)) #' blocky <- sample_(sbm(n = 20, pref.matrix = pref_matrix, #' block.sizes = c(10, 10))) #' #' blocky2 <- pref_matrix %>% #' sample_sbm(n = 20, block.sizes = c(10, 10)) #' #' ## Arguments are passed on from sample_ to sample_sbm #' blocky3 <- pref_matrix %>% #' sample_(sbm(), n = 20, block.sizes = c(10, 10)) sample_ <- make_ #' Convert object to a graph #' #' This is a generic function to convert R objects to igraph graphs. #' #' @details #' TODO #' #' @param ... Parameters, see details below. #' #' @export #' @examples #' ## These are equivalent #' graph_(cbind(1:5,2:6), from_edgelist(directed = FALSE)) #' graph_(cbind(1:5,2:6), from_edgelist(), directed = FALSE) graph_ <- make_ attr(make_, "name") <- "make_" attr(sample_, "name") <- "sample_" attr(graph_, "name") <- "graph_" constructor_spec <- function(fun, ..., .lazy = FALSE) { structure( list( fun = fun, args = lazy_dots(...), lazy = .lazy ), class = "igraph_constructor_spec" ) } ## ----------------------------------------------------------------- ## Constructor modifiers constructor_modifier <- function(...) { structure( list(...), class = "igraph_constructor_modifier" ) } #' Construtor modifier to remove all attributes from a graph #' #' @family constructor modifiers #' #' @export #' @examples #' g1 <- make_ring(10) #' g1 #' #' g2 <- make_(ring(10), without_attr()) #' g2 without_attr <- function() { constructor_modifier( id = "without_attr" ) } #' Constructor modifier to drop loop edges #' #' @family constructor modifiers #' #' @export #' @examples #' # An artificial example #' make_(full_graph(5, loops = TRUE)) #' make_(full_graph(5, loops = TRUE), without_loops()) without_loops <- function() { constructor_modifier( id = "without_loops" ) } #' Constructor modifier to drop multiple edges #' #' @family constructor modifiers #' #' @export #' @examples #' sample_(pa(10, m = 3, algorithm = "bag")) #' sample_(pa(10, m = 3, algorithm = "bag"), without_multiples()) without_multiples <- function() { constructor_modifier( id = "without_multiples" ) } #' Constructor modifier to drop multiple and loop edges #' #' @family constructor modifiers #' #' @export #' @examples #' sample_(pa(10, m = 3, algorithm = "bag")) #' sample_(pa(10, m = 3, algorithm = "bag"), simplified()) simplified <- function() { constructor_modifier( id = "simplified" ) } #' Constructor modifier to add vertex attributes #' #' @param ... The attributes to add. They must be named. #' #' @family constructor modifiers #' #' @export #' @examples #' make_(ring(10), #' with_vertex_( #' color = "#7fcdbb", #' frame.color = "#7fcdbb", #' name = LETTERS[1:10])) %>% #' plot() with_vertex_ <- function(...) { args <- grab_args() constructor_modifier( id = "with_vertex_", args = args ) } #' Constructor modifier to add edge attributes #' #' @param ... The attributes to add. They must be named. #' #' @family constructor modifiers #' #' @export #' @examples #' make_(ring(10), #' with_edge_( #' color = "red", #' weight = rep(1:2, 5))) %>% #' plot() with_edge_ <- function(...) { args <- grab_args() constructor_modifier( id = "with_edge_", args = args ) } #' Constructor modifier to add graph attributes #' #' @param ... The attributes to add. They must be named. #' #' @family constructor modifiers #' #' @export #' @examples #' make_(ring(10), with_graph_(name = "10-ring")) with_graph_ <- function(...) { args <- grab_args() constructor_modifier( id = "with_graph_", args = args ) } ## ----------------------------------------------------------------- #' Create an igraph graph from a list of edges, or a notable graph #' #' @section Notable graphs: #' #' \code{make_graph} can create some notable graphs. The name of the #' graph (case insensitive), a character scalar must be suppliced as #' the \code{edges} argument, and other arguments are ignored. (A warning #' is given is they are specified.) #' #' \code{make_graph} knows the following graphs: \describe{ #' \item{Bull}{The bull graph, 5 vertices, 5 edges, resembles to the head #' of a bull if drawn properly.} #' \item{Chvatal}{This is the smallest triangle-free graph that is #' both 4-chromatic and 4-regular. According to the Grunbaum conjecture there #' exists an m-regular, m-chromatic graph with n vertices for every m>1 and #' n>2. The Chvatal graph is an example for m=4 and n=12. It has 24 edges.} #' \item{Coxeter}{A non-Hamiltonian cubic symmetric graph with 28 vertices and #' 42 edges.} #' \item{Cubical}{The Platonic graph of the cube. A convex regular #' polyhedron with 8 vertices and 12 edges.} #' \item{Diamond}{A graph with 4 vertices and 5 edges, resembles to a #' schematic diamond if drawn properly.} #' \item{Dodecahedral, Dodecahedron}{Another Platonic solid with 20 vertices #' and 30 edges.} #' \item{Folkman}{The semisymmetric graph with minimum number of #' vertices, 20 and 40 edges. A semisymmetric graph is regular, edge transitive #' and not vertex transitive.} #' \item{Franklin}{This is a graph whose embedding #' to the Klein bottle can be colored with six colors, it is a counterexample #' to the neccessity of the Heawood conjecture on a Klein bottle. It has 12 #' vertices and 18 edges.} #' \item{Frucht}{The Frucht Graph is the smallest #' cubical graph whose automorphism group consists only of the identity #' element. It has 12 vertices and 18 edges.} #' \item{Grotzsch}{The Groetzsch #' graph is a triangle-free graph with 11 vertices, 20 edges, and chromatic #' number 4. It is named after German mathematician Herbert Groetzsch, and its #' existence demonstrates that the assumption of planarity is necessary in #' Groetzsch's theorem that every triangle-free planar graph is 3-colorable.} #' \item{Heawood}{The Heawood graph is an undirected graph with 14 vertices and #' 21 edges. The graph is cubic, and all cycles in the graph have six or more #' edges. Every smaller cubic graph has shorter cycles, so this graph is the #' 6-cage, the smallest cubic graph of girth 6.} #' \item{Herschel}{The Herschel #' graph is the smallest nonhamiltonian polyhedral graph. It is the unique such #' graph on 11 nodes, and has 18 edges.} #' \item{House}{The house graph is a #' 5-vertex, 6-edge graph, the schematic draw of a house if drawn properly, #' basicly a triangle of the top of a square.} #' \item{HouseX}{The same as the #' house graph with an X in the square. 5 vertices and 8 edges.} #' \item{Icosahedral, Icosahedron}{A Platonic solid with 12 vertices and 30 #' edges.} #' \item{Krackhardt kite}{A social network with 10 vertices and 18 #' edges. Krackhardt, D. Assessing the Political Landscape: Structure, #' Cognition, and Power in Organizations. Admin. Sci. Quart. 35, 342-369, #' 1990.} #' \item{Levi}{The graph is a 4-arc transitive cubic graph, it has 30 #' vertices and 45 edges.} #' \item{McGee}{The McGee graph is the unique 3-regular #' 7-cage graph, it has 24 vertices and 36 edges.} #' \item{Meredith}{The Meredith #' graph is a quartic graph on 70 nodes and 140 edges that is a counterexample #' to the conjecture that every 4-regular 4-connected graph is Hamiltonian.} #' \item{Noperfectmatching}{A connected graph with 16 vertices and 27 edges #' containing no perfect matching. A matching in a graph is a set of pairwise #' non-adjacent edges; that is, no two edges share a common vertex. A perfect #' matching is a matching which covers all vertices of the graph.} #' \item{Nonline}{A graph whose connected components are the 9 graphs whose #' presence as a vertex-induced subgraph in a graph makes a nonline graph. It #' has 50 vertices and 72 edges.} #' \item{Octahedral, Octahedron}{Platonic solid #' with 6 vertices and 12 edges.} #' \item{Petersen}{A 3-regular graph with 10 #' vertices and 15 edges. It is the smallest hypohamiltonian graph, ie. it is #' non-hamiltonian but removing any single vertex from it makes it #' Hamiltonian.} #' \item{Robertson}{The unique (4,5)-cage graph, ie. a 4-regular #' graph of girth 5. It has 19 vertices and 38 edges.} #' \item{Smallestcyclicgroup}{A smallest nontrivial graph whose automorphism #' group is cyclic. It has 9 vertices and 15 edges.} #' \item{Tetrahedral, #' Tetrahedron}{Platonic solid with 4 vertices and 6 edges.} #' \item{Thomassen}{The smallest hypotraceable graph, on 34 vertices and 52 #' edges. A hypotracable graph does not contain a Hamiltonian path but after #' removing any single vertex from it the remainder always contains a #' Hamiltonian path. A graph containing a Hamiltonian path is called tracable.} #' \item{Tutte}{Tait's Hamiltonian graph conjecture states that every #' 3-connected 3-regular planar graph is Hamiltonian. This graph is a #' counterexample. It has 46 vertices and 69 edges.} #' \item{Uniquely3colorable}{Returns a 12-vertex, triangle-free graph with #' chromatic number 3 that is uniquely 3-colorable.} #' \item{Walther}{An identity #' graph with 25 vertices and 31 edges. An identity graph has a single graph #' automorphism, the trivial one.} #' \item{Zachary}{Social network of friendships #' between 34 members of a karate club at a US university in the 1970s. See W. #' W. Zachary, An information flow model for conflict and fission in small #' groups, Journal of Anthropological Research 33, 452-473 (1977). } } #' #' @encoding UTF-8 #' @aliases graph.famous graph #' @param edges A vector defining the edges, the first edge points #' from the first element to the second, the second edge from the third #' to the fourth, etc. For a numeric vector, these are interpreted #' as internal vertex ids. For character vectors, they are interpreted #' as vertex names. #' #' Alternatively, this can be a character scalar, the name of a #' notable graph. See Notable graphs below. The name is case #' insensitive. #' #' Starting from igraph 0.8.0, you can also include literals here, #' via igraph's formula notation (see \code{\link{graph_from_literal}}). #' In this case, the first term of the formula has to start with #' a \sQuote{\code{~}} character, just like regular formulae in R. #' See examples below. #' @param ... For \code{make_graph}: extra arguments for the case when the #' graph is given via a literal, see \code{\link{graph_from_literal}}. #' For \code{directed_graph} and \code{undirected_graph}: #' Passed to \code{make_directed_graph} or \code{make_undirected_graph}. #' @param n The number of vertices in the graph. This argument is #' ignored (with a warning) if \code{edges} are symbolic vertex names. It #' is also ignored if there is a bigger vertex id in \code{edges}. This #' means that for this function it is safe to supply zero here if the #' vertex with the largest id is not an isolate. #' @param isolates Character vector, names of isolate vertices, #' for symbolic edge lists. It is ignored for numeric edge lists. #' @param directed Whether to create a directed graph. #' @param dir It is the same as \code{directed}, for compatibility. #' Do not give both of them. #' @param simplify For graph literals, whether to simplify the graph. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' make_graph(c(1, 2, 2, 3, 3, 4, 5, 6), directed = FALSE) #' make_graph(c("A", "B", "B", "C", "C", "D"), directed = FALSE) #' #' solids <- list(make_graph("Tetrahedron"), #' make_graph("Cubical"), #' make_graph("Octahedron"), #' make_graph("Dodecahedron"), #' make_graph("Icosahedron")) #' #' graph <- make_graph( ~ A-B-C-D-A, E-A:B:C:D, #' F-G-H-I-F, J-F:G:H:I, #' K-L-M-N-K, O-K:L:M:N, #' P-Q-R-S-P, T-P:Q:R:S, #' B-F, E-J, C-I, L-T, O-T, M-S, #' C-P, C-L, I-L, I-P) make_graph <- function(edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE) { if (inherits(edges, "formula")) { if (!missing(n)) stop("'n' should not be given for graph literals") if (!missing(isolates)) { stop("'isolates' should not be given for graph literals") } if (!missing(directed)) { stop("'directed' should not be given for graph literals") } mf <- as.list(match.call())[-1] mf[[1]] <- mf[[1]][[2]] graph_from_literal_i(mf) } else { if (!missing(simplify)) { stop("'simplify' should not be given for graph literals") } if (!missing(dir) && !missing(directed)) { stop("Only give one of 'dir' and 'directed'") } if (!missing(dir) && missing(directed)) directed <- dir if (is.character(edges) && length(edges) == 1) { if (!missing(n)) warning("'n' is ignored for the '", edges, "' graph") if (!missing(isolates)) { warning("'isolates' is ignored for the '", edges, "' graph") } if (!missing(directed)) { warning("'directed' is ignored for the '", edges, "' graph") } if (!missing(dir)) { warning("'dir' is ignored for the '", edges, "' graph") } if (length(list(...))) stop("Extra arguments in make_graph") make_famous_graph(edges) ## NULL and empty logical vector is allowed for compatibility } else if (is.numeric(edges) || is.null(edges) || (is.logical(edges) && length(edges) == 0)) { if (is.null(edges) || is.logical(edges)) edges <- as.numeric(edges) if (!is.null(isolates)) { warning("'isolates' ignored for numeric edge list") } old_graph <- function(edges, n = max(edges), directed = TRUE) { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_create, as.numeric(edges)-1, as.numeric(n), as.logical(directed)) } args <- list(edges, ...) if (!missing(n)) args <- c(args, list(n = n)) if (!missing(directed)) args <- c(args, list(directed = directed)) do.call(old_graph, args) } else if (is.character(edges)) { if (!missing(n)) { warning("'n' is ignored for edge list with vertex names") } if (length(list(...))) stop("Extra arguments in make_graph") el <- matrix(edges, ncol = 2, byrow = TRUE) res <- graph_from_edgelist(el, directed = directed) if (!is.null(isolates)) { isolates <- as.character(isolates) res <- res + vertices(isolates) } res } else { stop("'edges' must be numeric or character") } } } make_famous_graph <- function(name) { name <- gsub("\\s", "_", name) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_famous, as.character(name)) if (igraph_opt("add.params")) { res$name <- capitalize(name) } res } #' @rdname make_graph #' @export make_directed_graph <- function(edges, n = max(edges)) { if (missing(n)) { make_graph(edges, directed = TRUE) } else { make_graph(edges, n = n, directed = TRUE) } } #' @rdname make_graph #' @export make_undirected_graph <- function(edges, n = max(edges)) { if (missing(n)) { make_graph(edges, directed = FALSE) } else { make_graph(edges, n = n, directed = FALSE) } } #' @rdname make_graph #' @export directed_graph <- function(...) constructor_spec(make_directed_graph, ...) #' @rdname make_graph #' @export undirected_graph <- function(...) constructor_spec(make_undirected_graph, ...) ## ----------------------------------------------------------------- #' A graph with no edges #' #' @aliases graph.empty #' @concept Empty graph. #' @param n Number of vertices. #' @param directed Whether to create a directed graph. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' make_empty_graph(n = 10) #' make_empty_graph(n = 5, directed = FALSE) make_empty_graph <- function(n=0, directed=TRUE) { # Argument checks n <- as.integer(n) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_empty, n, directed) res } #' @rdname make_empty_graph #' @param ... Passed to \code{make_graph_empty}. #' @export empty_graph <- function(...) constructor_spec(make_empty_graph, ...) ## ----------------------------------------------------------------- #' Creating (small) graphs via a simple interface #' #' This function is useful if you want to create a small (named) graph #' quickly, it works for both directed and undirected graphs. #' #' @details #' \code{graph_from_literal} is very handy for creating small graphs quickly. #' You need to supply one or more R expressions giving the structure of #' the graph. The expressions consist of vertex names and edge #' operators. An edge operator is a sequence of \sQuote{\code{-}} and #' \sQuote{\code{+}} characters, the former is for the edges and the #' latter is used for arrow heads. The edges can be arbitrarily long, #' ie. you may use as many \sQuote{\code{-}} characters to \dQuote{draw} #' them as you like. #' #' If all edge operators consist of only \sQuote{\code{-}} characters #' then the graph will be undirected, whereas a single \sQuote{\code{+}} #' character implies a directed graph. #' #' Let us see some simple examples. Without arguments the function #' creates an empty graph: #' \preformatted{ graph_from_literal() #' } #' #' A simple undirected graph with two vertices called \sQuote{A} and #' \sQuote{B} and one edge only: #' \preformatted{ graph_from_literal(A-B) #' } #' #' Remember that the length of the edges does not matter, so we could #' have written the following, this creates the same graph: #' \preformatted{ graph_from_literal( A-----B ) #' } #' #' If you have many disconnected components in the graph, separate them #' with commas. You can also give isolate vertices. #' \preformatted{ graph_from_literal( A--B, C--D, E--F, G--H, I, J, K ) #' } #' #' The \sQuote{\code{:}} operator can be used to define vertex sets. If #' an edge operator connects two vertex sets then every vertex from the #' first set will be connected to every vertex in the second set. The #' following form creates a full graph, including loop edges: #' \preformatted{ graph_from_literal( A:B:C:D -- A:B:C:D ) #' } #' #' In directed graphs, edges will be created only if the edge operator #' includes a arrow head (\sQuote{+}) \emph{at the end} of the edge: #' \preformatted{ graph_from_literal( A -+ B -+ C ) #' graph_from_literal( A +- B -+ C ) #' graph_from_literal( A +- B -- C ) #' } #' Thus in the third example no edge is created between vertices \code{B} #' and \code{C}. #' #' Mutual edges can be also created with a simple edge operator: #' \preformatted{ graph_from_literal( A +-+ B +---+ C ++ D + E) #' } #' Note again that the length of the edge operators is arbitrary, #' \sQuote{\code{+}}, \sQuote{\code{++}} and \sQuote{\code{+-----+}} have #' exactly the same meaning. #' #' If the vertex names include spaces or other special characters then #' you need to quote them: #' \preformatted{ graph_from_literal( "this is" +- "a silly" -+ "graph here" ) #' } #' You can include any character in the vertex names this way, even #' \sQuote{+} and \sQuote{-} characters. #' #' See more examples below. #' #' @aliases graph.formula #' @param ... For \code{graph_from_literal} the formulae giving the #' structure of the graph, see details below. For \code{from_literal} #' all arguments are passed to \code{graph_from_literal}. #' @param simplify Logical scalar, whether to call \code{\link{simplify}} #' on the created graph. By default the graph is simplified, loop and #' multiple edges are removed. #' @return An igraph graph #' #' @family determimistic constructors #' @export #' @examples #' # A simple undirected graph #' g <- graph_from_literal( Alice-Bob-Cecil-Alice, Daniel-Cecil-Eugene, #' Cecil-Gordon ) #' g #' #' # Another undirected graph, ":" notation #' g2 <- graph_from_literal( Alice-Bob:Cecil:Daniel, Cecil:Daniel-Eugene:Gordon ) #' g2 #' #' # A directed graph #' g3 <- graph_from_literal( Alice +-+ Bob --+ Cecil +-- Daniel, #' Eugene --+ Gordon:Helen ) #' g3 #' #' # A graph with isolate vertices #' g4 <- graph_from_literal( Alice -- Bob -- Daniel, Cecil:Gordon, Helen ) #' g4 #' V(g4)$name #' #' # "Arrows" can be arbitrarily long #' g5 <- graph_from_literal( Alice +---------+ Bob ) #' g5 #' #' # Special vertex names #' g6 <- graph_from_literal( "+" -- "-", "*" -- "/", "%%" -- "%/%" ) #' g6 #' graph_from_literal <- function(..., simplify=TRUE) { mf <- as.list(match.call())[-1] graph_from_literal_i(mf) } graph_from_literal_i <- function(mf) { ## In case 'simplify' is given simplify <- TRUE if ('simplify' %in% names(mf)) { w <- which(names(mf)=='simplify') if (length(w) > 1) { stop("'simplify' specified multiple times") } simplify <- eval(mf[[w]]) mf <- mf[-w] } ## Operators first f <- function(x) { if (is.call(x)) { return (list(as.character(x[[1]]), lapply(x[-1], f))) } else { return (NULL) } } ops <- unlist(lapply(mf, f)) if (all(ops %in% c("-", ":"))) { directed <- FALSE } else if (all(ops %in% c("-", "+", ":"))) { directed <- TRUE } else { stop("Invalid operator in formula") } f <- function(x) { if (is.call(x)) { if (length(x)==3) { return( list(f(x[[2]]), op=as.character(x[[1]]), f(x[[3]])) ) } else { return( list(op=as.character(x[[1]]), f(x[[2]])) ) } } else { return( c(sym=as.character(x)) ) } } ret <- lapply(mf, function(x) unlist(f(x))) v <- unique(unlist(lapply(ret, function(x) { x[ names(x)=="sym" ] }))) ## Merge symbols for ":" ret <- lapply(ret, function(x) { res <- list() for (i in seq(along=x)) { if (x[i]==":" && names(x)[i]=="op") { ## SKIP } else if (i>1 && x[i-1]==":" && names(x)[i-1]=="op") { res[[length(res)]] <- c(res[[length(res)]], unname(x[i])) } else { res <- c(res, x[i]) } } res }) ## Ok, create the edges edges <- numeric() for (i in seq(along=ret)) { prev.sym <- character() lhead <- rhead <- character() for (j in seq(along=ret[[i]])) { act <- ret[[i]][[j]] if (names(ret[[i]])[j]=="op") { if (length(lhead)==0) { lhead <- rhead <- act } else { rhead <- act } } else if (names(ret[[i]])[j]=="sym") { for (ps in prev.sym) { for (ps2 in act) { if (lhead=="+") { edges <- c(edges, unname(c(ps2, ps))) } if (!directed || rhead=="+") { edges <- c(edges, unname(c(ps, ps2))) } } } lhead <- rhead <- character() prev.sym <- act } } } ids <- seq(along=v) names(ids) <- v res <- graph( unname(ids[edges]), n=length(v), directed=directed) if (simplify) res <- simplify(res) res <- set_vertex_attr(res, "name", value=v) res } #' @rdname graph_from_literal #' @export from_literal <- function(...) constructor_spec(graph_from_literal, ..., .lazy = TRUE) ## ----------------------------------------------------------------- #' Create a star graph, a tree with n vertices and n - 1 leaves #' #' \code{star} creates a star graph, in this every single vertex is #' connected to the center vertex and nobody else. #' #' @aliases graph.star #' @concept Star graph #' @param n Number of vertices. #' @param mode It defines the direction of the #' edges, \code{in}: the edges point \emph{to} the center, \code{out}: #' the edges point \emph{from} the center, \code{mutual}: a directed #' star is created with mutual edges, \code{undirected}: the edges #' are undirected. #' @param center ID of the center vertex. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' make_star(10, mode = "out") #' make_star(5, mode = "undirected") make_star <- function(n, mode=c("in", "out", "mutual", "undirected"), center=1 ) { mode <- igraph.match.arg(mode) mode1 <- switch(mode, "out"=0, "in"=1, "undirected"=2, "mutual"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_star, as.numeric(n), as.numeric(mode1), as.numeric(center)-1) if (igraph_opt("add.params")) { res$name <- switch(mode, "in"="In-star", "out"="Out-star", "Star") res$mode <- mode res$center <- center } res } #' @rdname make_star #' @param ... Passed to \code{make_star}. #' @export star <- function(...) constructor_spec(make_star, ...) ## ----------------------------------------------------------------- #' Create a full graph #' #' @aliases graph.full #' @concept Full graph #' @param n Number of vertices. #' @param directed Whether to create a directed graph. #' @param loops Whether to add self-loops to the graph. #' @return An igraph graph #' #' @family determimistic constructors #' @export #' @examples #' make_full_graph(5) #' print_all(make_full_graph(4, directed = TRUE)) make_full_graph <- function(n, directed=FALSE, loops=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_full, as.numeric(n), as.logical(directed), as.logical(loops)) if (igraph_opt("add.params")) { res$name <- "Full graph" res$loops <- loops } res } #' @rdname make_full_graph #' @param ... Passed to \code{make_full_graph}. #' @export full_graph <- function(...) constructor_spec(make_full_graph, ...) ## ----------------------------------------------------------------- #' Create a lattice graph #' #' \code{make_lattice} is a flexible function, it can create lattices of #' arbitrary dimensions, periodic or unperiodic ones. It has two #' forms. In the first form you only supply \code{dimvector}, but not #' \code{length} and \code{dim}. In the second form you omit #' \code{dimvector} and supply \code{length} and \code{dim}. #' #' @aliases graph.lattice #' @concept Lattice #' @param dimvector A vector giving the size of the lattice in each #' dimension. #' @param length Integer constant, for regular lattices, the size of the #' lattice in each dimension. #' @param dim Integer constant, the dimension of the lattice. #' @param nei The distance within which (inclusive) the neighbors on the #' lattice will be connected. This parameter is not used right now. #' @param directed Whether to create a directed lattice. #' @param mutual Logical, if \code{TRUE} directed lattices will be #' mutually connected. #' @param circular Logical, if \code{TRUE} the lattice or ring will be #' circular. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' make_lattice(c(5, 5, 5)) #' make_lattice(length = 5, dim = 3) make_lattice <- function(dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, circular=FALSE) { if (is.null(dimvector)) { dimvector <- rep(length, dim) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_lattice, as.numeric(dimvector), as.numeric(nei), as.logical(directed), as.logical(mutual), as.logical(circular)) if (igraph_opt("add.params")) { res$name <- "Lattice graph" res$dimvector <- dimvector res$nei <- nei res$mutual <- mutual res$circular <- circular } res } #' @rdname make_lattice #' @param ... Passed to \code{make_lattice}. #' @export lattice <- function(...) constructor_spec(make_lattice, ...) ## ----------------------------------------------------------------- #' Create a ring graph #' #' A ring is a one-dimensional lattice and this function is a special case #' of \code{\link{make_lattice}}. #' #' @aliases make_ring graph.ring #' @param n Number of vertices. #' @param directed Whether the graph is directed. #' @param mutual Whether directed edges are mutual. It is ignored in #' undirected graphs. #' @param circular Whether to create a circular ring. A non-circular #' ring is essentially a \dQuote{line}: a tree where every non-leaf #' vertex has one child. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' print_all(make_ring(10)) #' print_all(make_ring(10, directed = TRUE, mutual = TRUE)) make_ring <- function(n, directed=FALSE, mutual=FALSE, circular=TRUE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_ring, as.numeric(n), as.logical(directed), as.logical(mutual), as.logical(circular)) if (igraph_opt("add.params")) { res$name <- "Ring graph" res$mutual <- mutual res$circular <- circular } res } #' @rdname make_ring #' @param ... Passed to \code{make_ring}. #' @export ring <- function(...) constructor_spec(make_ring, ...) ## ----------------------------------------------------------------- #' Create tree graphs #' #' Create a regular tree graph. #' #' @aliases graph.tree #' @concept Trees. #' @param n Number of vertices. #' @param children Integer scalar, the number of children of a vertex #' (except for leafs) #' @param mode Defines the direction of the #' edges. \code{out} indicates that the edges point from the parent to #' the children, \code{in} indicates that they point from the children #' to their parents, while \code{undirected} creates an undirected #' graph. #' @return An igraph graph #' #' @family determimistic constructors #' @export #' @examples #' make_tree(10, 2) #' make_tree(10, 3, mode = "undirected") make_tree <- function(n, children=2, mode=c("out", "in", "undirected")) { mode <- igraph.match.arg(mode) mode1 <- switch(mode, "out"=0, "in"=1, "undirected"=2); on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_tree, as.numeric(n), as.numeric(children), as.numeric(mode1)) if (igraph_opt("add.params")) { res$name <- "Tree" res$children <- children res$mode <- mode } res } #' @rdname make_tree #' @param ... Passed to \code{make_tree}. #' @export tree <- function(...) constructor_spec(make_tree, ...) ## ----------------------------------------------------------------- #' Create a graph from the Graph Atlas #' #' \code{graph_from_atlas} creates graphs from the book #' \sQuote{An Atlas of Graphs} by #' Roland C. Read and Robin J. Wilson. The atlas contains all undirected #' graphs with up to seven vertices, numbered from 0 up to 1252. The #' graphs are listed: #' \enumerate{ #' \item in increasing order of number of nodes; #' \item for a fixed number of nodes, in increasing order of the number #' of edges; #' \item for fixed numbers of nodes and edges, in increasing order of #' the degree sequence, for example 111223 < 112222; #' \item for fixed degree sequence, in increasing number of #' automorphisms. #' } #' #' @aliases graph.atlas #' @concept Graph Atlas. #' @param n The id of the graph to create. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' ## Some randomly picked graphs from the atlas #' graph_from_atlas(sample(0:1252, 1)) #' graph_from_atlas(sample(0:1252, 1)) graph_from_atlas <- function(n) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_atlas, as.numeric(n)) if (igraph_opt("add.params")) { res$name <- sprintf("Graph from the Atlas #%i", n) res$n <- n } res } #' @rdname graph_from_atlas #' @param ... Passed to \code{graph_from_atlas}. #' @export atlas <- function(...) constructor_spec(graph_from_atlas, ...) ## ----------------------------------------------------------------- #' Create an extended chordal ring graph #' #' \code{make_chordal_ring} creates an extended chordal ring. #' An extended chordal ring is regular graph, each node has the same #' degree. It can be obtained from a simple ring by adding some extra #' edges specified by a matrix. Let p denote the number of columns in #' the \sQuote{\code{W}} matrix. The extra edges of vertex \code{i} #' are added according to column \code{i mod p} in #' \sQuote{\code{W}}. The number of extra edges is the number #' of rows in \sQuote{\code{W}}: for each row \code{j} an edge #' \code{i->i+w[ij]} is added if \code{i+w[ij]} is less than the number #' of total nodes. See also Kotsis, G: Interconnection Topologies for #' Parallel Processing Systems, PARS Mitteilungen 11, 1-6, 1993. #' #' @aliases graph.extended.chordal.ring #' @param n The number of vertices. #' @param w A matrix which specifies the extended chordal ring. See #' details below. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' chord <- make_chordal_ring(15, #' matrix(c(3, 12, 4, 7, 8, 11), nr = 2)) make_chordal_ring <- function(n, w) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_extended_chordal_ring, as.numeric(n), as.matrix(w)) if (igraph_opt("add.params")) { res$name <- "Extended chordal ring" res$w <- w } res } #' @rdname make_chordal_ring #' @param ... Passed to \code{make_chordal_ring}. #' @export chordal_ring <- function(...) constructor_spec(make_chordal_ring, ...) ## ----------------------------------------------------------------- #' Line graph of a graph #' #' This function calculates the line graph of another graph. #' #' The line graph \code{L(G)} of a \code{G} undirected graph is defined as #' follows. \code{L(G)} has one vertex for each edge in \code{G} and two #' vertices in \code{L(G)} are connected by an edge if their corresponding #' edges share an end point. #' #' The line graph \code{L(G)} of a \code{G} directed graph is slightly #' different, \code{L(G)} has one vertex for each edge in \code{G} and two #' vertices in \code{L(G)} are connected by a directed edge if the target of #' the first vertex's corresponding edge is the same as the source of the #' second vertex's corresponding edge. #' #' @aliases line.graph #' @param graph The input graph, it can be directed or undirected. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com}, the first version of #' the C code was written by Vincent Matossian. #' @keywords graphs #' @examples #' #' # generate the first De-Bruijn graphs #' g <- make_full_graph(2, directed=TRUE, loops=TRUE) #' make_line_graph(g) #' make_line_graph(make_line_graph(g)) #' make_line_graph(make_line_graph(make_line_graph(g))) #' make_line_graph <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_line_graph, graph) if (igraph_opt("add.params")) { res$name <- "Line graph" } res } #' @rdname make_line_graph #' @param ... Passed to \code{make_line_graph}. #' @export line_graph <- function(...) constructor_spec(make_line_graph, ...) ## ----------------------------------------------------------------- #' De Bruijn graphs #' #' De Bruijn graphs are labeled graphs representing the overlap of strings. #' #' A de Bruijn graph represents relationships between strings. An alphabet of #' \code{m} letters are used and strings of length \code{n} are considered. A #' vertex corresponds to every possible string and there is a directed edge #' from vertex \code{v} to vertex \code{w} if the string of \code{v} can be #' transformed into the string of \code{w} by removing its first letter and #' appending a letter to it. #' #' Please note that the graph will have \code{m} to the power \code{n} vertices #' and even more edges, so probably you don't want to supply too big numbers #' for \code{m} and \code{n}. #' #' De Bruijn graphs have some interesting properties, please see another #' source, eg. Wikipedia for details. #' #' @aliases graph.de.bruijn #' @param m Integer scalar, the size of the alphabet. See details below. #' @param n Integer scalar, the length of the labels. See details below. #' @return A graph object. #' @author Gabor Csardi #' @seealso \code{\link{make_kautz_graph}}, \code{\link{make_line_graph}} #' @keywords graphs #' @export #' @examples #' #' # de Bruijn graphs can be created recursively by line graphs as well #' g <- make_de_bruijn_graph(2,1) #' make_de_bruijn_graph(2,2) #' make_line_graph(g) make_de_bruijn_graph <- function(m, n) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_de_bruijn, as.numeric(m), as.numeric(n)) if (igraph_opt("add.params")) { res$name <- sprintf("De-Bruijn graph %i-%i", m, n) res$m <- m res$n <- n } res } #' @rdname make_de_bruijn_graph #' @param ... Passed to \code{make_de_bruijn_graph}. #' @export de_bruijn_graph <- function(...) constructor_spec(make_de_bruijn_graph, ...) ## ----------------------------------------------------------------- #' Kautz graphs #' #' Kautz graphs are labeled graphs representing the overlap of strings. #' #' A Kautz graph is a labeled graph, vertices are labeled by strings of length #' \code{n+1} above an alphabet with \code{m+1} letters, with the restriction #' that every two consecutive letters in the string must be different. There is #' a directed edge from a vertex \code{v} to another vertex \code{w} if it is #' possible to transform the string of \code{v} into the string of \code{w} by #' removing the first letter and appending a letter to it. #' #' Kautz graphs have some interesting properties, see eg. Wikipedia for #' details. #' #' @aliases graph.kautz #' @param m Integer scalar, the size of the alphabet. See details below. #' @param n Integer scalar, the length of the labels. See details below. #' @return A graph object. #' @author Gabor Csardi , the first version in R was #' written by Vincent Matossian. #' @seealso \code{\link{make_de_bruijn_graph}}, \code{\link{make_line_graph}} #' @keywords graphs #' @export #' @examples #' #' make_line_graph(make_kautz_graph(2,1)) #' make_kautz_graph(2,2) #' make_kautz_graph <- function(m, n) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_kautz, as.numeric(m), as.numeric(n)) if (igraph_opt("add.params")) { res$name <- sprintf("Kautz graph %i-%i", m, n) res$m <- m res$n <- n } res } #' @rdname make_kautz_graph #' @param ... Passed to \code{make_kautz_graph}. #' @export kautz_graph <- function(...) constructor_spec(make_kautz_graph, ...) ## ----------------------------------------------------------------- #' Create a full bipartite graph #' #' Bipartite graphs are also called two-mode by some. This function creates a #' bipartite graph in which every possible edge is present. #' #' Bipartite graphs have a \sQuote{\code{type}} vertex attribute in igraph, #' this is boolean and \code{FALSE} for the vertices of the first kind and #' \code{TRUE} for vertices of the second kind. #' #' @aliases graph.full.bipartite #' @param n1 The number of vertices of the first kind. #' @param n2 The number of vertices of the second kind. #' @param directed Logical scalar, whether the graphs is directed. #' @param mode Scalar giving the kind of edges to create for directed graphs. #' If this is \sQuote{\code{out}} then all vertices of the first kind are #' connected to the others; \sQuote{\code{in}} specifies the opposite #' direction; \sQuote{\code{all}} creates mutual edges. This argument is #' ignored for undirected graphs.x #' @return An igraph graph, with the \sQuote{\code{type}} vertex attribute set. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{make_full_graph}} for creating one-mode full graphs #' @keywords graphs #' @examples #' #' g <- make_full_bipartite_graph(2, 3) #' g2 <- make_full_bipartite_graph(2, 3, dir=TRUE) #' g3 <- make_full_bipartite_graph(2, 3, dir=TRUE, mode="in") #' g4 <- make_full_bipartite_graph(2, 3, dir=TRUE, mode="all") #' make_full_bipartite_graph <- function(n1, n2, directed=FALSE, mode=c("all", "out", "in")) { n1 <- as.integer(n1) n2 <- as.integer(n2) directed <- as.logical(directed) mode1 <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_full_bipartite, n1, n2, as.logical(directed), mode1) if (igraph_opt("add.params")) { res$graph$name <- "Full bipartite graph" res$n1 <- n1 res$n2 <- n2 res$mode <- mode } set_vertex_attr(res$graph, "type", value=res$types) } #' @rdname make_full_bipartite_graph #' @param ... Passed to \code{make_full_bipartite_graph}. #' @export full_bipartite_graph <- function(...) constructor_spec(make_full_bipartite_graph, ...) ## ----------------------------------------------------------------- #' Create a bipartite graph #' #' A bipartite graph has two kinds of vertices and connections are only allowed #' between different kinds. #' #' Bipartite graphs have a \code{type} vertex attribute in igraph, this is #' boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} #' for vertices of the second kind. #' #' \code{make_bipartite_graph} basically does three things. First it checks tha #' \code{edges} vector against the vertex \code{types}. Then it creates a graph #' using the \code{edges} vector and finally it adds the \code{types} vector as #' a vertex attribute called \code{type}. #' #' \code{is_bipartite} checks whether the graph is bipartite or not. It just #' checks whether the graph has a vertex attribute called \code{type}. #' #' @aliases make_bipartite_graph graph.bipartite is.bipartite is_bipartite #' @param types A vector giving the vertex types. It will be coerced into #' boolean. The length of the vector gives the number of vertices in the graph. #' @param edges A vector giving the edges of the graph, the same way as for the #' regular \code{\link{graph}} function. It is checked that the edges indeed #' connect vertices of different kind, accoding to the supplied \code{types} #' vector. #' @param directed Whether to create a directed graph, boolean constant. Note #' that by default undirected graphs are created, as this is more common for #' bipartite graphs. #' @param graph The input graph. #' @return \code{make_bipartite_graph} returns a bipartite igraph graph. In other #' words, an igraph graph that has a vertex attribute named \code{type}. #' #' \code{is_bipartite} returns a logical scalar. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{graph}} to create one-mode networks #' @keywords graphs #' @examples #' #' g <- make_bipartite_graph( rep(0:1,length=10), c(1:10)) #' print(g, v=TRUE) #' make_bipartite_graph <- function(types, edges, directed=FALSE) { types <- as.logical(types) edges <- as.numeric(edges)-1 directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_create_bipartite, types, edges, directed) set_vertex_attr(res, "type", value=types) } #' @rdname make_bipartite_graph #' @param ... Passed to \code{make_bipartite_graph}. #' @export bipartite_graph <- function(...) constructor_spec(make_bipartite_graph, ...) ## ----------------------------------------------------------------- #' Create a complete (full) citation graph #' #' \code{make_full_citation_graph} creates a full citation graph. This is a #' directed graph, where every \code{i->j} edge is present if and only if #' \eqn{j # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Is this object an igraph graph? #' #' @aliases is.igraph #' @param graph An R object. #' @return A logical constant, \code{TRUE} if argument \code{graph} is a graph #' object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' is_igraph(g) #' is_igraph(numeric(10)) is_igraph <- function(graph){ "igraph" %in% class(graph) } #' @export get.edge <- function(graph, id) { .Deprecated("ends", msg = paste("'get.edge' is deperecated, please use", "'ends' instead.")) if (!is_igraph(graph)) { stop("Not a graph object") } id <- as.numeric(id) ec <- ecount(graph) if (id < 1 || id > ec) { stop("No such edge") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_edge, graph, as.numeric(id)-1) res+1 } #' Head of the edge(s) in a graph #' #' For undirected graphs, head and tail is not defined. In this case #' \code{head_of} returns vertices incident to the supplied edges, and #' \code{tail_of} returns the other end(s) of the edge(s). #' #' @param graph The input graph. #' @param es The edges to query. #' @return A vertex sequence with the head(s) of the edge(s). #' #' @family structural queries #' #' @export head_of <- function(graph, es) { create_vs(graph, ends(graph, es, names = FALSE)[,2]) } #' Tails of the edge(s) in a graph #' #' For undirected graphs, head and tail is not defined. In this case #' \code{tail_of} returns vertices incident to the supplied edges, and #' \code{head_of} returns the other end(s) of the edge(s). #' #' @param graph The input graph. #' @param es The edges to query. #' @return A vertex sequence with the tail(s) of the edge(s). #' #' @family structural queries #' #' @export tail_of <- function(graph, es) { create_vs(graph, ends(graph, es, names = FALSE)[,1]) } igraph/R/console.R0000644000175100001440000002111213177712334013535 0ustar hornikusers # IGraph R package # Copyright (C) 2010-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### .igraph.pb <- NULL #' @export .igraph.progress <- function(percent, message, clean=FALSE) { if (clean) { if (!is.null(.igraph.pb)) { close(.igraph.pb) } return(invisible()) } type <- igraph_opt("verbose") if (is.logical(type) && type) { .igraph.progress.txt(percent, message) } else { switch (type, "tk"=.igraph.progress.tk(percent, message), "tkconsole"=.igraph.progress.tkconsole(percent, message), stop("Cannot interpret 'verbose' option, this should not happen")) } } #' @export .igraph.status <- function(message) { type <- igraph_opt("verbose") if (is.logical(type) && type) { message(message, appendLF=FALSE) } else { switch(type, "tk"=message(message, appendLF=FALSE), "tkconsole"=.igraph.progress.tkconsole.message(message, start=TRUE), stop("Cannot interpret 'verbose' option, this should not happen")) } 0L } #' @importFrom utils txtProgressBar setTxtProgressBar .igraph.progress.txt <- function(percent, message) { pb <- get(".igraph.pb", asNamespace("igraph")) if (percent==0) { if (!is.null(pb)) { close(pb) } cat(sep="", " ", message, "\n") pb <- txtProgressBar(min=0, max=100, style=3) } setTxtProgressBar(pb, percent) if (percent==100) { close(pb); pb <- NULL } assign(".igraph.pb", pb, envir=asNamespace("igraph")) 0L } .igraph.progress.tk <- function(percent, message) { pb <- get(".igraph.pb", asNamespace("igraph")) if (percent==0) { if (!is.null(pb)) { close(pb) } pb <- tcltk::tkProgressBar(min=0, max=100, title=message, label="0 %") } tcltk::setTkProgressBar(pb, percent, label=paste(percent, "%")) if (percent==100) { close(pb); pb <- NULL } assign(".igraph.pb", pb, envir=asNamespace("igraph")) 0L } .igraph.progress.tkconsole <- function(percent, message) { pb <- get(".igraph.pb", asNamespace("igraph")) startmess <- FALSE ## Open the console, if it is not open if (is.null(pb)) { startmess <- TRUE pb <- .igraph.progress.tkconsole.create(NA) } ## Update progress bar pb$pb$set(pb$pb$widget, percent) tcltk::tkconfigure(pb$pb$label, text=substr(message, 1, 20)) tcltk::tcl("update", "idletasks") ## Done assign(".igraph.pb", pb, envir=asNamespace("igraph")) if (startmess) .igraph.progress.tkconsole.message("Console started.\n") 0L } .igraph.progress.tkconsole.create <- function(oldverb) { console <- tcltk::tktoplevel() tcltk::tktitle(console) <- "igraph console" fn <- tcltk::tkfont.create(family="courier", size=8) lfr <- tcltk::tkframe(console) image <- tcltk::tkimage.create("photo", "img", format="gif", file=system.file("igraph2.gif", package="igraph")) logo <- tcltk::tklabel(lfr, relief="flat", padx=10, pady=10, image=image) scr <- tcltk::tkscrollbar(console, repeatinterval=5, command=function(...) tcltk::tkyview(txt, ...)) txt <- tcltk::tktext(console, yscrollcommand=function(...) tcltk::tkset(scr, ...), width=60, height=7, font=fn) tcltk::tkconfigure(txt, state="disabled") pbar <- .igraph.progress.tkconsole.pbar(console) bclear <- tcltk::tkbutton(lfr, text="Clear", command=function() { tcltk::tkconfigure(txt, state="normal") tcltk::tkdelete(txt, "0.0", "end") tcltk::tkconfigure(txt, state="disabled") }) bstop <- tcltk::tkbutton(lfr, text="Stop", command=function() {}) bclose <- tcltk::tkbutton(lfr, text="Close", command=function() { if (!is.na(oldverb) && igraph_opt("verbose") == "tkconsole") { igraph_options(verbose=oldverb) } tcltk::tkdestroy(console) }) tcltk::tkpack(logo, side="top", fill="none", expand=0, anchor="n", ipadx=10, ipady=10) tcltk::tkpack(bclear, side="top", fill="x", expand=0, padx=10) ## tcltk::tkpack(bstop, side="top", fill="x", expand=0, padx=10) tcltk::tkpack(bclose, side="top", fill="x", expand=0, padx=10) tcltk::tkpack(lfr, side="left", fill="none", expand=0, anchor="n") tcltk::tkpack(pbar$frame, side="bottom", fill="x", expand=0) tcltk::tkpack(scr, side="right", fill="y", expand=0) tcltk::tkpack(txt, side="left", fill="both", expand=1) tcltk::tkbind(console, "", function() { if (!is.na(oldverb) && igraph_opt("verbose") == "tkconsole") { igraph_options(verbose=oldverb) } assign(".igraph.pb", NULL, envir=asNamespace("igraph")) }) res <- list(top=console, txt=txt, pb=pbar$pb, oldverb=oldverb) class(res) <- "igraphconsole" res } .igraph.progress.tkconsole.message <- function(message, start=FALSE) { txt <- get(".igraph.pb", asNamespace("igraph"))$txt if (is.null(txt)) { if (start) { pb <- .igraph.progress.tkconsole.create(NA) assign(".igraph.pb", pb, envir=asNamespace("igraph")) txt <- pb$txt } else { return() } } tcltk::tkconfigure(txt, state="normal") now <- paste(sep="", substr(date(), 5, 19), ": ") s1 <- grepl("^ ", message) if (!s1) { tcltk::tkinsert(txt, "insert", now) } tcltk::tkinsert(txt, "insert", message) tcltk::tksee(txt, "end") tcltk::tkconfigure(txt, state="disabled") tcltk::tcl("update", "idletasks") } close.igraphconsole <- function(con, ...) { invisible() } ## Much of this is from tkProgressbar .igraph.progress.tkconsole.pbar <- function(top) { useText <- FALSE have_ttk <- as.character(tcltk::tcl("info", "tclversion")) >= "8.5" if (!have_ttk && as.character(tcltk::tclRequire("PBar")) == "FALSE") useText <- TRUE fn <- tcltk::tkfont.create(family = "helvetica", size = 10) frame <- tcltk::tkframe(top) if (useText) { .lab <- tcltk::tklabel(frame, text = " ", font = fn, anchor="w", padx = 20) tcltk::tkpack(.lab, side = "left", anchor="w", padx=5) fn2 <- tcltk::tkfont.create(family = "helvetica", size = 12) .vlab <- tcltk::tklabel(frame, text = "0%", font = fn2, padx = 20) tcltk::tkpack(.vlab, side = "right") } else { .lab <- tcltk::tklabel(frame, text = " ", font = fn, anchor="w", pady = 5) tcltk::tkpack(.lab, side = "top", anchor="w", padx=5) tcltk::tkpack(tcltk::tklabel(frame, text = "", font = fn), side = "bottom") .val <- tcltk::tclVar() pBar <- if (have_ttk) { tcltk::ttkprogressbar(frame, length = 300, variable=.val) } else { tcltk::tkwidget(frame, "ProgressBar", width = 300, variable=.val) } tcltk::tkpack(pBar, side = "bottom", anchor="w", padx=5) } get <- function(w) { return(tcltk::tclvalue(.val)); } set <- function(w, val) { tcltk::tclvalue(.val) <<- val } pb <- list(widget=pBar, get=get, set=set, label=.lab) list(frame=frame, pb=pb) } #' The igraph console #' #' The igraph console is a GUI windows that shows what the currently running #' igraph function is doing. #' #' The console can be started by calling the \code{console} function. #' Then it stays open, until the user closes it. #' #' Another way to start it to set the \code{verbose} igraph option to #' \dQuote{tkconsole} via \code{igraph_options}. Then the console (re)opens #' each time an igraph function supporting it starts; to close it, set the #' \code{verbose} option to another value. #' #' The console is written in Tcl/Tk and required the \code{tcltk} package. #' #' @aliases igraph.console #' @return \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{igraph_options}} and the \code{verbose} option. #' @keywords graphs #' @export console <- function() { oldverb <- igraph_opt("verbose") igraph_options(verbose="tkconsole") pb <- .igraph.progress.tkconsole.create(oldverb) assign(".igraph.pb", pb, envir=asNamespace("igraph")) .igraph.progress.tkconsole.message("Console started.\n") invisible() } igraph/R/printr.R0000644000175100001440000001200613177712334013413 0ustar hornikusers #' Create a printer callback function #' #' A printer callback fucntion is a function can performs the actual #' printing. It has a number of subcommands, that are called by #' the \code{printer} package, in a form \preformatted{ #' printer_callback("subcommand", argument1, argument2, ...) #' } See the examples below. #' #' The subcommands: #' #' \describe{ #' \item{\code{length}}{The length of the data to print, the number of #' items, in natural units. E.g. for a list of objects, it is the #' number of objects.} #' \item{\code{min_width}}{TODO} #' \item{\code{width}}{Width of one item, if \code{no} items will be #' printed. TODO} #' \item{\code{print}}{Argument: \code{no}. Do the actual printing, #' print \code{no} items.} #' \item{\code{done}}{TODO} #' } #' #' @param fun The function to use as a printer callback function. #' @family printer callbacks #' @export printer_callback <- function(fun) { if (!is.function(fun)) warning("'fun' is not a function") add_class(fun, "printer_callback") } #' Is this a printer callback? #' #' @param x An R object. #' @family printer callbacks #' @export is_printer_callback <- function(x) { inherits(x, "printer_callback") } print_header <- function(header) { print_head_foot(header) } print_footer <- function(footer) { print_head_foot(footer) } print_head_foot <- function(head_foot) { if (is.function(head_foot)) head_foot() else cat(head_foot) } #' Print the only the head of an R object #' #' @param x The object to print, or a callback function. See #' \code{\link{printer_callback}} for details. #' @param max_lines Maximum number of lines to print, \emph{not} #' including the header and the footer. #' @param header The header, if a function, then it will be called, #' otherwise printed using \code{cat}. #' @param footer The footer, if a function, then it will be called, #' otherwise printed using \code{cat}. #' @param omitted_footer Footer that is only printed if anything #' is omitted from the printout. If a function, then it will be called, #' otherwise printed using \code{cat}. #' @param ... Extra arguments to pass to \code{print()}. #' @return \code{x}, invisibly. #' #' @export head_print <- function(x, max_lines = 20, header = "", footer = "", omitted_footer = "", ...) { if (is_printer_callback(x)) { head_print_callback(x, max_lines, header, footer, omitted_footer, ...) } else { head_print_object(x, max_lines, header, footer, omitted_footer, ...) } invisible(x) } head_print_object <- function(x, max_lines, header, footer, omitted_footer, print_fun = print, ...) { print_header(header) cout <- capture.output(print_fun(x, ...)) cout_no <- min(length(cout), max_lines) cat(cout[seq_len(cout_no)], sep = "\n") print_footer(footer) if (cout_no < length(cout)) print_footer(omitted_footer) invisible(c(lines = length(cout), printed = cout_no)) } #' @importFrom utils tail head_print_callback <- function(x, max_lines, header, footer, omitted_footer, ...) { ## Header print_header(header) len <- x("length") minw <- x("min_width") ow <- getOption("width", 80) ## Max number of items we can print. This is an upper bound. can_max <- min(floor(ow / minw) * max_lines, len) if (can_max == 0) { return() } ## Width of item if we print up to this cm <- x("width", no = can_max) ## How many rows we need if we print up to a certain point no_rows <- ceiling(cm * seq_along(cm) /(ow - 4) ) ## So how many items should be print? no <- tail(which(no_rows <= max_lines), 1) if (is.na(no)) no <- len cat_pern <- function(..., sep = "\n") cat(..., sep = sep) ## Format them, and print out_lines <- head_print_object( x("print", no = no, ...), print_fun = cat_pern, max_lines = max_lines, header = "", footer = "", omitted_footer = "" ) done_stat <- c(tried_items = no, tried_lines = out_lines[["lines"]], printed_lines = out_lines[["printed"]]) if (done_stat["tried_items"] < len || done_stat["printed_lines"] < done_stat["tried_lines"]) { print_footer(omitted_footer) } x("done", done_stat) ## Footer print_footer(footer) } #' Indent a printout #' #' @param ... Passed to the printing function. #' @param .indent Character scalar, indent the printout with this. #' @param .printer The printing function, defaults to \code{print}. #' @return The first element in \code{...}, invisibly. #' #' @export indent_print <- function(..., .indent = " ", .printer = print) { if (length(.indent) != 1) stop(".indent must be a scalar") opt <- options(width = getOption("width") - nchar(.indent)) on.exit(options(opt), add = TRUE) cout <- capture.output(.printer(...)) if (length(cout)) { cout <- paste0(.indent, cout) cat(cout, sep = "\n") } invisible(list(...)[[1]]) } #' Better printing of R packages #' #' @docType package #' @name printr NULL add_class <- function(x, class) { if (!inherits(x, class)) { class(x) <- c(class(x), class) } x } igraph/R/triangles.R0000644000175100001440000000524113240142531014053 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Find triangles in graphs #' #' Count how many triangles a vertex is part of, in a graph, or just list the #' triangles of a graph. #' #' \code{triangles} lists all triangles of a graph. For efficiency, all #' triangles are returned in a single vector. The first three vertices belong #' to the first triangle, etc. #' #' \code{count_triangles} counts how many triangles a vertex is part of. #' #' @aliases count_triangles adjacent.triangles triangles #' @param graph The input graph. It might be directed, but edge directions are #' ignored. #' @param vids The vertices to query, all of them by default. This might be a #' vector of numeric ids, or a character vector of symbolic vertex names for #' named graphs. #' @return For \code{triangles} a numeric vector of vertex ids, the first three #' vertices belong to the first triangle found, etc. #' #' For \code{count_triangles} a numeric vector, the number of triangles for all #' vertices queried. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{transitivity}} #' @keywords graphs #' @examples #' #' ## A small graph #' kite <- make_graph("Krackhardt_Kite") #' plot(kite) #' matrix(triangles(kite), nrow=3) #' #' ## Adjacenct triangles #' atri <- count_triangles(kite) #' plot(kite, vertex.label=atri) #' #' ## Always true #' sum(count_triangles(kite)) == length(triangles(kite)) #' #' ## Should match, local transitivity is the #' ## number of adjacent triangles divided by the number #' ## of adjacency triples #' transitivity(kite, type="local") #' count_triangles(kite) / (degree(kite) * (degree(kite)-1)/2) #' @export #' @include auto.R count_triangles <- count_triangles igraph/R/utils.R0000644000175100001440000000470013177712334013237 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- make_call <- function(f, ..., .args = list()) { if (is.character(f)) f <- as.name(f) as.call(c(f, ..., .args)) } do_call <- function(f, ..., .args = list(), .env = parent.frame()) { f <- substitute(f) call <- make_call(f, ..., .args) eval(call, .env) } add_class <- function(x, class) { if (!is(x, class)) { class(x) <- c(class, class(x)) } x } `%||%` <- function (lhs, rhs) { lres <- withVisible(eval(lhs, envir = parent.frame())) if (is.null(lres$value)) { eval(rhs, envir = parent.frame()) } else { if (lres$visible) { lres$value } else { invisible(lres$value) } } } `%&&%` <- function(lhs, rhs) { lres <- withVisible(eval(lhs, envir = parent.frame())) if (!is.null(lres$value)) { eval(rhs, envir = parent.frame()) } else { if (lres$visible) { lres$value } else { invisible(lres$value) } } } ## Grab all arguments of the parent call, in a list grab_args <- function() { envir <- parent.frame() func <- sys.function(-1) call <- sys.call(-1) dots <- match.call(func, call, expand.dots=FALSE)$... c(as.list(envir), dots) } capitalize <- function(x) { x <- tolower(x) substr(x, 1, 1) <- toupper(substr(x, 1, 1)) x } address <- function(x) { .Call(C_R_igraph_address, x) } `%+%` <- function(x, y) { stopifnot(is.character(x), is.character(y)) paste0(x, y) } chr <- as.character drop_null <- function(x) { x [!sapply(x, is.null)] } igraph/R/cliques.R0000644000175100001440000002536013240142531013534 0ustar hornikusers# IGraph R package # Copyright (C) 2006-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' The functions find cliques, ie. complete subgraphs in a graph #' #' These functions find all, the largest or all the maximal cliques in an #' undirected graph. The size of the largest clique can also be calculated. #' #' \code{cliques} find all complete subgraphs in the input graph, obeying the #' size limitations given in the \code{min} and \code{max} arguments. #' #' \code{largest_cliques} finds all largest cliques in the input graph. A #' clique is largest if there is no other clique including more vertices. #' #' \code{max_cliques} finds all maximal cliques in the input graph. A #' clique in maximal if it cannot be extended to a larger clique. The largest #' cliques are always maximal, but a maximal clique is not neccessarily the #' largest. #' #' \code{count_max_cliques} counts the maximal cliques. #' #' \code{clique_num} calculates the size of the largest clique(s). #' #' The current implementation of these functions searches for maximal #' independent vertex sets (see \code{\link{ivs}}) in the #' complementer graph. #' #' @aliases cliques largest_cliques maximal.cliques maximal.cliques.count #' clique.number clique_num largest.cliques count_max_cliques max_cliques #' @param graph The input graph, directed graphs will be considered as #' undirected ones, multiple edges and loops are ignored. #' @param min Numeric constant, lower limit on the size of the cliques to find. #' \code{NULL} means no limit, ie. it is the same as 0. #' @param max Numeric constant, upper limit on the size of the cliques to find. #' \code{NULL} means no limit. #' @return \code{cliques}, \code{largest_cliques} and \code{clique_num} #' return a list containing numeric vectors of vertex ids. Each list element is #' a clique. #' #' \code{max_cliques} returns \code{NULL}, invisibly, if its \code{file} #' argument is not \code{NULL}. The output is written to the specified file in #' this case. #' #' \code{clique_num} and \code{count_max_cliques} return an integer #' scalar. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{ivs}} #' @references For maximal cliques the following algorithm is implemented: #' David Eppstein, Maarten Loffler, Darren Strash: Listing All Maximal Cliques #' in Sparse Graphs in Near-optimal Time. \url{http://arxiv.org/abs/1006.5440} #' @export #' @keywords graphs #' @examples #' #' # this usually contains cliques of size six #' g <- sample_gnp(100, 0.3) #' clique_num(g) #' cliques(g, min=6) #' largest_cliques(g) #' #' # To have a bit less maximal cliques, about 100-200 usually #' g <- sample_gnp(100, 0.03) #' max_cliques(g) #' #' cliques <- function(graph, min=NULL, max=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(min)) { min <- 0 } if (is.null(max)) { max <- 0 } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_cliques, graph, as.numeric(min), as.numeric(max)) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @export largest_cliques <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_largest_cliques, graph) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @rdname cliques #' @param subset If not \code{NULL}, then it must be a vector of vertex ids, #' numeric or symbolic if the graph is named. The algorithm is run from these #' vertices only, so only a subset of all maximal cliques is returned. See the #' Eppstein paper for details. This argument makes it possible to easily #' parallelize the finding of maximal cliques. #' @param file If not \code{NULL}, then it must be a file name, i.e. a #' character scalar. The output of the algorithm is written to this file. (If #' it exists, then it will be overwritten.) Each clique will be a separate line #' in the file, given with the numeric ids of its vertices, separated by #' whitespace. #' @export max_cliques <- function(graph, min=NULL, max=NULL, subset=NULL, file=NULL) { if (!is_igraph(graph)) { stop("Not a graph object"); } if (is.null(min)) { min <- 0 } if (is.null(max)) { max <- 0 } if (!is.null(subset)) { subset <- as.integer(as.igraph.vs(graph, subset)-1) } if (!is.null(file)) { if (!is.character(file) || length(grep("://", file, fixed=TRUE)) > 0 || length(grep("~", file, fixed=TRUE)) > 0) { tmpfile <- TRUE origfile <- file file <- tempfile() } else { tmpfile <- FALSE } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_maximal_cliques_file, graph, subset, file, as.numeric(min), as.numeric(max)) if (tmpfile) { buffer <- read.graph.toraw(file) write.graph.fromraw(buffer, origfile) } invisible(NULL) } else { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_maximal_cliques, graph, subset, as.numeric(min), as.numeric(max)) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } } #' @export count_max_cliques <- function(graph, min=NULL, max=NULL, subset=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(min)) { min <- 0 } if (is.null(max)) { max <- 0 } min <- as.integer(min) max <- as.integer(max) if (!is.null(subset)) { subset <- as.integer(as.igraph.vs(graph, subset)-1) } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_maximal_cliques_count, graph, subset, min, max) res } #' @export clique_num <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_clique_number, graph) } #' Independent vertex sets #' #' A vertex set is called independent if there no edges between any two #' vertices in it. These functions find independent vertex sets in undirected #' graphs #' #' \code{ivs} finds all independent vertex sets in the #' network, obeying the size limitations given in the \code{min} and \code{max} #' arguments. #' #' \code{largest_ivs} finds the largest independent vertex #' sets in the graph. An independent vertex set is largest if there is no #' independent vertex set with more vertices. #' #' \code{maximal_ivs} finds the maximal independent vertex #' sets in the graph. An independent vertex set is maximal if it cannot be #' extended to a larger independent vertex set. The largest independent vertex #' sets are maximal, but the opposite is not always true. #' #' \code{independece.number} calculate the size of the largest independent #' vertex set(s). #' #' These functions use the algorithm described by Tsukiyama et al., see #' reference below. #' #' @aliases independent.vertex.sets largest.independent.vertex.sets #' maximal.independent.vertex.sets independence.number ivs_size ivs #' largest_ivs maximal_ivs #' @param graph The input graph, directed graphs are considered as undirected, #' loop edges and multiple edges are ignored. #' @param min Numeric constant, limit for the minimum size of the independent #' vertex sets to find. \code{NULL} means no limit. #' @param max Numeric constant, limit for the maximum size of the independent #' vertex sets to find. \code{NULL} means no limit. #' @return \code{ivs}, #' \code{largest_ivs} and #' \code{maximal_ivs} return a list containing numeric #' vertex ids, each list element is an independent vertex set. #' #' \code{ivs_size} returns an integer constant. #' @author Tamas Nepusz \email{ntamas@@gmail.com} ported it from the Very Nauty #' Graph Library by Keith Briggs (\url{http://keithbriggs.info/}) and Gabor #' Csardi \email{csardi.gabor@@gmail.com} wrote the R interface and this manual #' page. #' @seealso \code{\link{cliques}} #' @references S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new #' algorithm for generating all the maximal independent sets. \emph{SIAM J #' Computing}, 6:505--517, 1977. #' @export #' @keywords graphs #' @examples #' #' # Do not run, takes a couple of seconds #' \dontrun{ #' #' # A quite dense graph #' set.seed(42) #' g <- sample_gnp(100, 0.9) #' ivs_size(g) #' ivs(g, min=ivs_size(g)) #' largest_ivs(g) #' # Empty graph #' induced_subgraph(g, largest_ivs(g)[[1]]) #' #' length(maximal_ivs(g)) #' } ivs <- function(graph, min=NULL, max=NULL) { if (!is_igraph(graph)) { stop("Not a graph object"); } if (is.null(min)) { min <- 0 } if (is.null(max)) { max <- 0 } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_independent_vertex_sets, graph, as.numeric(min), as.numeric(max)) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @export largest_ivs <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_largest_independent_vertex_sets, graph) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @export maximal_ivs <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_maximal_independent_vertex_sets, graph) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @export ivs_size <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_independence_number, graph) } igraph/R/minimum.spanning.tree.R0000644000175100001440000000705313177712334016330 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Minimum spanning tree #' #' A subgraph of a connected graph is a \emph{minimum spanning tree} if it is #' tree, and the sum of its edge weights are the minimal among all tree #' subgraphs of the graph. A minimum spanning forest of a graph is the graph #' consisting of the minimum spanning trees of its components. #' #' If the graph is unconnected a minimum spanning forest is returned. #' #' @aliases minimum.spanning.tree #' @param graph The graph object to analyze. #' @param weights Numeric algorithm giving the weights of the edges in the #' graph. The order is determined by the edge ids. This is ignored if the #' \code{unweighted} algorithm is chosen. Edge weights are interpreted as #' distances. #' @param algorithm The algorithm to use for calculation. \code{unweighted} can #' be used for unwieghted graphs, and \code{prim} runs Prim's algorithm for #' weighted graphs. If this is \code{NULL} then igraph tries to select the #' algorithm automatically: if the graph has an edge attribute called #' \code{weight} of the \code{weights} argument is not \code{NULL} then Prim's #' algorithm is chosen, otherwise the unwweighted algorithm is performed. #' @param \dots Additional arguments, unused. #' @return A graph object with the minimum spanning forest. (To check that it #' is a tree check that the number of its edges is \code{vcount(graph)-1}.) #' The edge and vertex attributes of the original graph are preserved in the #' result. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{components}} #' @references Prim, R.C. 1957. Shortest connection networks and some #' generalizations \emph{Bell System Technical Journal}, 37 1389--1401. #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(100, 3/100) #' g_mst <- mst(g) #' mst <- function(graph, weights=NULL, algorithm=NULL, ...) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(algorithm)) { if (!is.null(weights) || "weight" %in% edge_attr_names(graph)) { algorithm <- "prim" } else { algorithm <- "unweighted" } } if (algorithm=="unweighted") { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_minimum_spanning_tree_unweighted, graph) } else if (algorithm=="prim") { if (is.null(weights) && ! "weight" %in% edge_attr_names(graph)) { stop("edges weights must be supplied for Prim's algorithm") } else if (is.null(weights)) { weights <- E(graph)$weight } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_minimum_spanning_tree_prim, graph, as.numeric(weights)) } else { stop("Invalid algorithm") } } igraph/R/components.R0000644000175100001440000001615113240142531014252 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Connected components, subgraphs, kinda ################################################################### #' @export count_components <- function(graph, mode=c("weak", "strong")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "weak"=1, "strong"=2) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_no_clusters, graph, as.numeric(mode)) } #' @rdname components #' @param cumulative Logical, if TRUE the cumulative distirubution (relative #' frequency) is calculated. #' @param mul.size Logical. If TRUE the relative frequencies will be multiplied #' by the cluster sizes. #' @export #' @importFrom graphics hist component_distribution <- function(graph, cumulative=FALSE, mul.size=FALSE, ...) { if (!is_igraph(graph)) { stop("Not a graph object") } cs <- components(graph, ...)$csize; hi <- hist(cs, -1:max(cs), plot=FALSE)$density if (mul.size) { hi <- hi*1:max(cs) hi <- hi/sum(hi) } if (!cumulative) { res <- hi } else { res <- rev(cumsum(rev(hi))); } res } #' @export is_connected <- function(graph, mode=c("weak", "strong")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "weak"=1, "strong"=2) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_is_connected, graph, as.numeric(mode)) } #' Decompose a graph into components #' #' Creates a separate graph for each component of a graph. #' #' @aliases decompose.graph #' @param graph The original graph. #' @param mode Character constant giving the type of the components, wither #' \code{weak} for weakly connected components or \code{strong} for strongly #' connected components. #' @param max.comps The maximum number of components to return. The first #' \code{max.comps} components will be returned (which hold at least #' \code{min.vertices} vertices, see the next parameter), the others will be #' ignored. Supply \code{NA} here if you don't want to limit the number of #' components. #' @param min.vertices The minimum number of vertices a component should #' contain in order to place it in the result list. Eg. supply 2 here to ignore #' isolate vertices. #' @return A list of graph objects. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{is_connected}} to decide whether a graph is connected, #' \code{\link{components}} to calculate the connected components of a graph. #' @export #' @keywords graphs #' @examples #' #' # the diameter of each component in a random graph #' g <- sample_gnp(1000, 1/1000) #' components <- decompose(g, min.vertices=2) #' sapply(components, diameter) #' decompose <- function(graph, mode=c("weak", "strong"), max.comps=NA, min.vertices=0) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "weak"=1, "strong"=2) if (is.na(max.comps)) { max.comps=-1 } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_decompose, graph, as.numeric(mode), as.numeric(max.comps), as.numeric(min.vertices)) } #' Articulation points of a graph #' #' Articuation points or cut vertices are vertices whose removal increases the #' number of connected components in a graph. #' #' Articuation points or cut vertices are vertices whose removal increases the #' number of connected components in a graph. If the original graph was #' connected, then the removal of a single articulation point makes it #' undirected. If a graph contains no articulation points, then its vertex #' connectivity is at least two. #' #' @aliases articulation.points articulation_points #' @param graph The input graph. It is treated as an undirected graph, even if #' it is directed. #' @return A numeric vector giving the vertex ids of the articulation points of #' the input graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{biconnected_components}}, \code{\link{components}}, #' \code{\link{is_connected}}, \code{\link{vertex_connectivity}} #' @keywords graphs #' @examples #' #' g <- disjoint_union( make_full_graph(5), make_full_graph(5) ) #' clu <- components(g)$membership #' g <- add_edges(g, c(match(1, clu), match(2, clu)) ) #' articulation_points(g) #' @export #' @include auto.R articulation_points <- articulation_points #' Biconnected components #' #' Finding the biconnected components of a graph #' #' A graph is biconnected if the removal of any single vertex (and its adjacent #' edges) does not disconnect it. #' #' A biconnected component of a graph is a maximal biconnected subgraph of it. #' The biconnected components of a graph can be given by the partition of its #' edges: every edge is a member of exactly one biconnected component. Note #' that this is not true for vertices: the same vertex can be part of many #' biconnected components. #' #' @aliases biconnected.components biconnected_components #' @param graph The input graph. It is treated as an undirected graph, even if #' it is directed. #' @return A named list with three components: \item{no}{Numeric scalar, an #' integer giving the number of biconnected components in the graph.} #' \item{tree_edges}{The components themselves, a list of numeric vectors. Each #' vector is a set of edge ids giving the edges in a biconnected component. #' These edges define a spanning tree of the component.} #' \item{component_edges}{A list of numeric vectors. It gives all edges in the #' components.} \item{components}{A list of numeric vectors, the vertices of #' the components.} \item{articulation_points}{The articulation points of the #' graph. See \code{\link{articulation_points}}.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{articulation_points}}, \code{\link{components}}, #' \code{\link{is_connected}}, \code{\link{vertex_connectivity}} #' @keywords graphs #' @examples #' #' g <- disjoint_union( make_full_graph(5), make_full_graph(5) ) #' clu <- components(g)$membership #' g <- add_edges(g, c(which(clu==1), which(clu==2))) #' bc <- biconnected_components(g) #' @export biconnected_components <- biconnected_components igraph/R/decomposition.R0000644000175100001440000001035513177712334014756 0ustar hornikusers# IGraph R package # Copyright (C) 2008-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Graph decomposition ################################################################### #' Chordality of a graph #' #' A graph is chordal (or triangulated) if each of its cycles of four or more #' nodes has a chord, which is an edge joining two nodes that are not adjacent #' in the cycle. An equivalent definition is that any chordless cycles have at #' most three nodes. #' #' The chordality of the graph is decided by first performing maximum #' cardinality search on it (if the \code{alpha} and \code{alpham1} arguments #' are \code{NULL}), and then calculating the set of fill-in edges. #' #' The set of fill-in edges is empty if and only if the graph is chordal. #' #' It is also true that adding the fill-in edges to the graph makes it chordal. #' #' @aliases is.chordal #' @param graph The input graph. It may be directed, but edge directions are #' ignored, as the algorithm is defined for undirected graphs. #' @param alpha Numeric vector, the maximal chardinality ordering of the #' vertices. If it is \code{NULL}, then it is automatically calculated by #' calling \code{\link{max_cardinality}}, or from \code{alpham1} if #' that is given.. #' @param alpham1 Numeric vector, the inverse of \code{alpha}. If it is #' \code{NULL}, then it is automatically calculated by calling #' \code{\link{max_cardinality}}, or from \code{alpha}. #' @param fillin Logical scalar, whether to calculate the fill-in edges. #' @param newgraph Logical scalar, whether to calculate the triangulated graph. #' @return A list with three members: \item{chordal}{Logical scalar, it is #' \code{TRUE} iff the input graph is chordal.} \item{fillin}{If requested, #' then a numeric vector giving the fill-in edges. \code{NULL} otherwise.} #' \item{newgraph}{If requested, then the triangulated graph, an \code{igraph} #' object. \code{NULL} otherwise.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{max_cardinality}} #' @references Robert E Tarjan and Mihalis Yannakakis. (1984). Simple #' linear-time algorithms to test chordality of graphs, test acyclicity of #' hypergraphs, and selectively reduce acyclic hypergraphs. \emph{SIAM Journal #' of Computation} 13, 566--579. #' @export #' @keywords graphs #' @examples #' #' ## The examples from the Tarjan-Yannakakis paper #' g1 <- graph_from_literal(A-B:C:I, B-A:C:D, C-A:B:E:H, D-B:E:F, #' E-C:D:F:H, F-D:E:G, G-F:H, H-C:E:G:I, #' I-A:H) #' max_cardinality(g1) #' is_chordal(g1, fillin=TRUE) #' #' g2 <- graph_from_literal(A-B:E, B-A:E:F:D, C-E:D:G, D-B:F:E:C:G, #' E-A:B:C:D:F, F-B:D:E, G-C:D:H:I, H-G:I:J, #' I-G:H:J, J-H:I) #' max_cardinality(g2) #' is_chordal(g2, fillin=TRUE) #' is_chordal <- function(graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(alpha)) alpha <- as.numeric(alpha)-1 if (!is.null(alpham1)) alpham1 <- as.numeric(alpham1)-1 fillin <- as.logical(fillin) newgraph <- as.logical(newgraph) on.exit(.Call(C_R_igraph_finalizer)) res <- .Call(C_R_igraph_is_chordal, graph, alpha, alpham1, fillin, newgraph) if (fillin) { res$fillin <- res$fillin + 1 } res } igraph/R/simple.R0000644000175100001440000000533313177712334013373 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Simple graphs #' #' Simple graphs are graphs which do not contain loop and multiple edges. #' #' A loop edge is an edge for which the two endpoints are the same #' vertex. Two edges are multiple edges if they have exactly the same two #' endpoints (for directed graphs order does matter). A graph is simple is #' it does not contain loop edges and multiple edges. #' #' \code{is_simple} checks whether a graph is simple. #' #' \code{simplify} removes the loop and/or multiple edges from a graph. If #' both \code{remove.loops} and \code{remove.multiple} are \code{TRUE} the #' function returns a simple graph. #' #' @aliases simplify is.simple is_simple #' @param graph The graph to work on. #' @param remove.loops Logical, whether the loop edges are to be removed. #' @param remove.multiple Logical, whether the multiple edges are to be #' removed. #' @param edge.attr.comb Specifies what to do with edge attributes, if #' \code{remove.multiple=TRUE}. In this case many edges might be mapped to a #' single one in the new graph, and their attributes are combined. Please see #' \code{\link{attribute.combination}} for details on this. #' @return A new graph object with the edges deleted. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{which_loop}}, \code{\link{which_multiple}} and #' \code{\link{count_multiple}}, \code{\link{delete_edges}}, #' \code{\link{delete_vertices}} #' @keywords graphs #' @examples #' #' g <- graph( c(1,2,1,2,3,3) ) #' is_simple(g) #' is_simple(simplify(g, remove.loops=FALSE)) #' is_simple(simplify(g, remove.multiple=FALSE)) #' is_simple(simplify(g)) #' @export #' @include auto.R simplify <- simplify #' @export #' @rdname simplify is_simple <- is_simple igraph/R/par.R0000644000175100001440000002232313177712334012662 0ustar hornikusers # IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### .igraph.pars <- list("print.vertex.attributes"=FALSE, "print.edge.attributes"=FALSE, "print.graph.attributes"=FALSE, "verbose"=FALSE, "vertex.attr.comb"=list(name="concat", "ignore"), "edge.attr.comb"=list(weight="sum", name="concat", "ignore"), "sparsematrices"=TRUE, "nexus.url"="http://nexus.igraph.org", "add.params"=TRUE, "add.vertex.names"=TRUE, "dend.plot.type"="auto", "print.full"="auto", "annotate.plot"=FALSE, "auto.print.lines" = 10, "return.vs.es" = TRUE ) igraph.pars.set.verbose <- function(verbose) { if (is.logical(verbose)) { .Call(C_R_igraph_set_verbose, verbose) } else if (is.character(verbose)) { if (!verbose %in% c("tk", "tkconsole")) { stop("Unknown 'verbose' value") } if (verbose %in% c("tk", "tkconsole")) { if (!capabilities()[["X11"]]) { stop("X11 not available") } if (!requireNamespace("tcltk", quietly = TRUE)) { stop("tcltk package not available") } } .Call(C_R_igraph_set_verbose, verbose) } else { stop("'verbose' should be a logical or character scalar") } verbose } igraph.pars.callbacks <- list("verbose"=igraph.pars.set.verbose) ## This is based on 'sm.options' in the 'sm' package #' Parameters for the igraph package #' #' igraph has some parameters which (usually) affect the behavior of many #' functions. These can be set for the whole session via \code{igraph_options}. #' #' The parameter values set via a call to the \code{igraph_options} function #' will remain in effect for the rest of the session, affecting the subsequent #' behaviour of the other functions of the \code{igraph} package for which the #' given parameters are relevant. #' #' This offers the possibility of customizing the functioning of the #' \code{igraph} package, for instance by insertions of appropriate calls to #' \code{igraph_options} in a load hook for package \pkg{igraph}. #' #' The currently used parameters in alphabetical order: #' \describe{ #' \item{add.params}{Logical scalar, whether to add model #' parameter to the graphs that are created by the various #' graph constructors. By default it is \code{TRUE}.} #' \item{add.vertex.names}{Logical scalar, whether to add #' vertex names to node level indices, like degree, betweenness #' scores, etc. By default it is \code{TRUE}.} #' \item{annotate.plot}{Logical scalar, whether to annotate igraph #' plots with the graph's name (\code{name} graph attribute, if #' present) as \code{main}, and with the number of vertices and edges #' as \code{xlab}. Defaults to \code{FALSE}.} #' \item{dend.plot.type}{The plotting function to use when plotting #' community structure dendrograms via #' \code{\link{plot_dendrogram}}}. Possible values are \sQuote{auto} (the #' default), \sQuote{phylo}, \sQuote{hclust} and #' \sQuote{dendrogram}. See \code{\link{plot_dendrogram}} for details. #' \item{edge.attr.comb}{Specifies what to do with the edge #' attributes if the graph is modified. The default value is #' \code{list(weight="sum", name="concat", "ignore")}. See #' \code{\link{attribute.combination}} for details on this.} #' \item{nexus.url}{The base URL of the default Nexus server. See #' \code{\link{nexus}} for details.} #' \item{print.edge.attributes}{Logical constant, whether to print edge #' attributes when printing graphs. Defaults to \code{FALSE}.} #' \item{print.full}{Logical scalar, whether \code{\link{print.igraph}} #' should show the graph structure as well, or only a summary of the #' graph.} #' \item{print.graph.attributes}{Logical constant, whether to print #' graph attributes when printing graphs. Defaults to \code{FALSE}.} #' \item{print.vertex.attributes}{Logical constant, whether to print #' vertex attributes when printing graphs. Defaults to \code{FALSE}.} #' \item{return.vs.es}{Whether functions that return a set or sequence #' of vertices/edges should return formal vertex/edge sequence #' objects. This option was introduced in igraph version 1.0.0 and #' defaults to TRUE. If your package requires the old behavior, #' you can set it to FALSE in the \code{.onLoad} function of #' your package, without affecting other packages.} #' \item{sparsematrices}{Whether to use the \code{Matrix} package for #' (sparse) matrices. It is recommended, if the user works with #' larger graphs.} #' \item{verbose}{Logical constant, whether igraph functions should #' talk more than minimal. Eg. if \code{TRUE} thne some functions #' will use progress bars while computing. Defaults to \code{FALSE}.} #' \item{vertex.attr.comb}{Specifies what to do with the vertex #' attributes if the graph is modified. The default value is #' \code{list(name="concat", "ignore")} See #' \code{\link{attribute.combination}} for details on this.} #' } #' #' @aliases igraph.options igraph_options getIgraphOpt igraph_opt #' @param \dots A list may be given as the only argument, or any number of #' arguments may be in the \code{name=value} form, or no argument at all may be #' given. See the Value and Details sections for explanation. #' @param x A character string holding an option name. #' @param default If the specified option is not set in the options list, this #' value is returned. This facilitates retrieving an option and checking #' whether it is set and setting it separately if not. #' @return \code{igraph_options} returns a list with the old values of the #' updated parameters, invisibly. Without any arguments, it returns the #' values of all options. #' #' For \code{igraph_opt}, the current value set for option \code{x}, or #' \code{NULL} if the option is unset. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{igraph_options} is similar to \code{\link{options}} and #' \code{igraph_opt} is similar to \code{\link{getOption}}. #' @keywords graphs #' @examples #' #' oldval <- igraph_opt("verbose") #' igraph_options(verbose = TRUE) #' layout_with_kk(make_ring(10)) #' igraph_options(verbose = oldval) #' #' oldval <- igraph_options(verbose = TRUE, sparsematrices = FALSE) #' make_ring(10)[] #' igraph_options(oldval) #' igraph_opt("verbose") #' #' @export #' @family igraph options #' @importFrom pkgconfig set_config_in get_config igraph_options <- function(...) { if (nargs() == 0) return(get_all_options()) ## Short notation temp <- list(...) if (length(temp) == 1 && is.null(names(temp))) { arg <- temp[[1]] switch(mode(arg), list = temp <- arg, character = return(.igraph.pars[arg]), stop("invalid argument: ", sQuote(arg))) } if (length(temp) == 0) return(get_all_options()) ## Callbacks n <- names(temp) if (is.null(n)) stop("options must be given by name") cb <- intersect(names(igraph.pars.callbacks), n) for (cn in cb) { temp[[cn]] <- igraph.pars.callbacks[[cn]](temp[[cn]]) } ## Old values old <- lapply(names(temp), igraph_opt) names(old) <- names(temp) ## Set them names(temp) <- paste0("igraph::", names(temp)) do.call(set_config_in, c(temp, list(.in = parent.frame()))) invisible(old) } #' @importFrom pkgconfig set_config get_config get_all_options <- function() { res <- lapply(names(.igraph.pars), function(n) { nn <- paste0("igraph::", n) get_config(nn, fallback = .igraph.pars[[n]]) }) names(res) <- names(.igraph.pars) res } #' @rdname igraph_options #' @export igraph_opt <- function(x, default = NULL) { if (missing(default)) { get_config(paste0("igraph::", x), .igraph.pars[[x]]) } else { get_config(paste0("igraph::", x), default) } } #' Run code with a temporary igraph options setting #' #' @param options A named list of the options to change. #' @param code The code to run. #' @return The result of the \code{code}. #' #' @export #' @family igraph options #' @examples #' with_igraph_opt( #' list(sparsematrices = FALSE), #' make_ring(10)[] #' ) #' igraph_opt("sparsematrices") with_igraph_opt <- function(options, code) { on.exit(igraph_options(old)) old <- igraph_options(options) force(code) } igraph/R/zzz-deprecate.R0000644000175100001440000005261513177712334014676 0ustar hornikusers # IGraph R package # Copyright (C) 2014 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' @include attributes.R auto.R basic.R bipartite.R centrality.R #' @include cliques.R cocitation.R cohesive.blocks.R community.R #' @include components.R console.R conversion.R decomposition.R demo.R #' @include epi.R fit.R flow.R foreign.R games.R glet.R hrg.R indexing.R #' @include interface.R iterators.R layout.R minimum.spanning.tree.R #' @include motifs.R nexus.R operators.R other.R package.R par.R plot.R #' @include plot.common.R plot.shapes.R pp.R print.R scg.R socnet.R #' @include sparsedf.R structural.properties.R #' @include structure.info.R test.R tkplot.R topology.R layout_drl.R NULL ## For the future, right now, we do not warn or even message #' @importFrom utils packageName deprecated <- function(old, new) { assign(old, new, envir = asNamespace(packageName())) } #' @export add.edges deprecated("add.edges", add_edges) #' @export add.vertex.shape deprecated("add.vertex.shape", add_shape) #' @export add.vertices deprecated("add.vertices", add_vertices) #' @export adjacent.triangles deprecated("adjacent.triangles", count_triangles) #' @export articulation.points deprecated("articulation.points", articulation_points) #' @export aging.prefatt.game deprecated("aging.prefatt.game", sample_pa_age) #' @export aging.ba.game deprecated("aging.ba.game", sample_pa_age) #' @export aging.barabasi.game deprecated("aging.barabasi.game", sample_pa_age) #' @export alpha.centrality deprecated("alpha.centrality", alpha_centrality) #' @export are.connected deprecated("are.connected", are_adjacent) #' @export asPhylo deprecated("asPhylo", as_phylo) #' @method asPhylo communities deprecated("asPhylo.communities", as_phylo.communities) #' @method asPhylo igraphHRG deprecated("asPhylo.igraphHRG", as_phylo.igraphHRG) #' @export assortativity.degree deprecated("assortativity.degree", assortativity_degree) #' @export assortativity.nominal deprecated("assortativity.nominal", assortativity_nominal) #' @export asymmetric.preference.game deprecated("asymmetric.preference.game", sample_asym_pref) #' @export authority.score deprecated("authority.score", authority_score) #' @export autocurve.edges deprecated("autocurve.edges", curve_multiple) #' @export average.path.length deprecated("average.path.length", mean_distance) #' @export ba.game deprecated("ba.game", sample_pa) #' @export barabasi.game deprecated("barabasi.game", sample_pa) #' @export betweenness.estimate deprecated("betweenness.estimate", estimate_betweenness) #' @export biconnected.components deprecated("biconnected.components", biconnected_components) #' @export bipartite.mapping deprecated("bipartite.mapping", bipartite_mapping) #' @export bipartite.projection deprecated("bipartite.projection", bipartite_projection) #' @export bipartite.projection.size deprecated("bipartite.projection.size", bipartite_projection_size) #' @export bipartite.random.game deprecated("bipartite.random.game", sample_bipartite) #' @export blockGraphs deprecated("blockGraphs", graphs_from_cohesive_blocks) #' @export bonpow deprecated("bonpow", power_centrality) #' @export callaway.traits.game deprecated("callaway.traits.game", sample_traits_callaway) #' @export canonical.permutation deprecated("canonical.permutation", canonical_permutation) #' @export centralization.betweenness deprecated("centralization.betweenness", centr_betw) #' @export centralization.betweenness.tmax deprecated("centralization.betweenness.tmax", centr_betw_tmax) #' @export centralization.closeness deprecated("centralization.closeness", centr_clo) #' @export centralization.closeness.tmax deprecated("centralization.closeness.tmax", centr_clo_tmax) #' @export centralization.degree deprecated("centralization.degree", centr_degree) #' @export centralization.degree.tmax deprecated("centralization.degree.tmax", centr_degree_tmax) #' @export centralization.evcent deprecated("centralization.evcent", centr_eigen) #' @export centralization.evcent.tmax deprecated("centralization.evcent.tmax", centr_eigen_tmax) #' @export centralize.scores deprecated("centralize.scores", centralize) #' @export cited.type.game deprecated("cited.type.game", sample_cit_types) #' @export citing.cited.type.game deprecated("citing.cited.type.game", sample_cit_cit_types) #' @export clique.number deprecated("clique.number", clique_num) #' @export closeness.estimate deprecated("closeness.estimate", estimate_closeness) #' @export cluster.distribution deprecated("cluster.distribution", component_distribution) #' @export clusters deprecated("clusters", components) #' @export code.length deprecated("code.length", code_len) #' @export cohesive.blocks deprecated("cohesive.blocks", cohesive_blocks) #' @export connect.neighborhood deprecated("connect.neighborhood", connect) #' @export contract.vertices deprecated("contract.vertices", contract) #' @export convex.hull deprecated("convex.hull", convex_hull) #' @export count.multiple deprecated("count.multiple", count_multiple) #' @export cutat deprecated("cutat", cut_at) #' @export decompose.graph deprecated("decompose.graph", decompose) #' @export degree.distribution deprecated("degree.distribution", degree_distribution) #' @export degree.sequence.game deprecated("degree.sequence.game", sample_degseq) #' @export delete.edges deprecated("delete.edges", delete_edges) #' @export delete.vertices deprecated("delete.vertices", delete_vertices) #' @export dendPlot deprecated("dendPlot", plot_dendrogram) #' @method dendPlot communities deprecated("dendPlot.communities", plot_dendrogram.communities) #' @method dendPlot igraphHRG deprecated("dendPlot.igraphHRG", plot_dendrogram.igraphHRG) #' @export dominator.tree deprecated("dominator.tree", dominator_tree) #' @export dyad.census deprecated("dyad.census", dyad_census) #' @export ecount deprecated("ecount", gsize) #' @export edge.betweenness deprecated("edge.betweenness", edge_betweenness) #' @export edge.betweenness.community deprecated("edge.betweenness.community", cluster_edge_betweenness) #' @export edge.betweenness.estimate deprecated("edge.betweenness.estimate", estimate_edge_betweenness) #' @export edge.connectivity deprecated("edge.connectivity", edge_connectivity) #' @export edge.disjoint.paths deprecated("edge.disjoint.paths", edge_disjoint_paths) #' @export establishment.game deprecated("establishment.game", sample_traits) #' @export evcent deprecated("evcent", eigen_centrality) #' @export farthest.nodes deprecated("farthest.nodes", farthest_vertices) #' @export fastgreedy.community deprecated("fastgreedy.community", cluster_fast_greedy) #' @export forest.fire.game deprecated("forest.fire.game", sample_forestfire) #' @export get.adjedgelist deprecated("get.adjedgelist", as_adj_edge_list) #' @export get.adjlist deprecated("get.adjlist", as_adj_list) #' @export get.adjacency deprecated("get.adjacency", as_adjacency_matrix) #' @export get.data.frame deprecated("get.data.frame", as_data_frame) #' @export get.edge.attribute deprecated("get.edge.attribute", edge_attr) #' @export get.edgelist deprecated("get.edgelist", as_edgelist) #' @export get.graph.attribute deprecated("get.graph.attribute", graph_attr) #' @export get.incidence deprecated("get.incidence", as_incidence_matrix) #' @export get.stochastic deprecated("get.stochastic", stochastic_matrix) #' @export get.vertex.attribute deprecated("get.vertex.attribute", vertex_attr) #' @export graph.adhesion deprecated("graph.adhesion", adhesion) #' @export graph.adjacency deprecated("graph.adjacency", graph_from_adjacency_matrix) #' @export graph.adjlist deprecated("graph.adjlist", graph_from_adj_list) #' @export graph.atlas deprecated("graph.atlas", graph_from_atlas) #' @export graph.automorphisms deprecated("graph.automorphisms", automorphisms) #' @export graph.bfs deprecated("graph.bfs", bfs) #' @export graph.bipartite deprecated("graph.bipartite", make_bipartite_graph) #' @export graph.cohesion deprecated("graph.cohesion", cohesion) #' @export graph.complementer deprecated("graph.complementer", complementer) #' @export graph.compose deprecated("graph.compose", compose) #' @export graph.coreness deprecated("graph.coreness", coreness) #' @export graph.data.frame deprecated("graph.data.frame", graph_from_data_frame) #' @export graph.de.bruijn deprecated("graph.de.bruijn", make_de_bruijn_graph) #' @export graph.density deprecated("graph.density", edge_density) #' @export graph.disjoint.union deprecated("graph.disjoint.union", disjoint_union) #' @export graph.dfs deprecated("graph.dfs", dfs) #' @export graph.difference deprecated("graph.difference", difference) #' @export graph.diversity deprecated("graph.diversity", diversity) #' @export graph.edgelist deprecated("graph.edgelist", graph_from_edgelist) #' @export graph.eigen deprecated("graph.eigen", spectrum) #' @export graph.empty deprecated("graph.empty", make_empty_graph) #' @export graph.extended.chordal.ring deprecated("graph.extended.chordal.ring", make_chordal_ring) #' @export graph.formula deprecated("graph.formula", graph_from_literal) #' @export graph.full deprecated("graph.full", make_full_graph) #' @export graph.full.bipartite deprecated("graph.full.bipartite", make_full_bipartite_graph) #' @export graph.full.citation deprecated("graph.full.citation", make_full_citation_graph) #' @export graph.graphdb deprecated("graph.graphdb", graph_from_graphdb) #' @export graph.incidence deprecated("graph.incidence", graph_from_incidence_matrix) #' @export graph.isocreate deprecated("graph.isocreate", graph_from_isomorphism_class) #' @export graph.kautz deprecated("graph.kautz", make_kautz_graph) #' @export graph.knn deprecated("graph.knn", knn) #' @export graph.laplacian deprecated("graph.laplacian", laplacian_matrix) #' @export graph.lattice deprecated("graph.lattice", make_lattice) #' @export graph.lcf deprecated("graph.lcf", graph_from_lcf) #' @export graph.maxflow deprecated("graph.maxflow", max_flow) #' @export graph.mincut deprecated("graph.mincut", min_cut) #' @export graph.motifs deprecated("graph.motifs", motifs) #' @export graph.motifs.est deprecated("graph.motifs.est", sample_motifs) #' @export graph.motifs.no deprecated("graph.motifs.no", count_motifs) #' @export graph.neighborhood deprecated("graph.neighborhood", make_ego_graph) #' @export graph.star deprecated("graph.star", make_star) #' @export graph.strength deprecated("graph.strength", strength) #' @export graph.tree deprecated("graph.tree", make_tree) #' @export graph.union deprecated("graph.union", union.igraph) #' @export graph.ring deprecated("graph.ring", make_ring) #' @export graphlets.candidate.basis deprecated("graphlets.candidate.basis", graphlet_basis) #' @export graphlets.project deprecated("graphlets.project", graphlet_proj) #' @export growing.random.game deprecated("growing.random.game", sample_growing) #' @export grg.game deprecated("grg.game", sample_grg) #' @export has.multiple deprecated("has.multiple", any_multiple) #' @export hrg.consensus deprecated("hrg.consensus", consensus_tree) #' @export hrg.create deprecated("hrg.create", hrg) #' @export hrg.dendrogram deprecated("hrg.dendrogram", hrg_tree) #' @export hrg.game deprecated("hrg.game", sample_hrg) #' @export hrg.fit deprecated("hrg.fit", fit_hrg) #' @export hrg.predict deprecated("hrg.predict", predict_edges) #' @export hub.score deprecated("hub.score", hub_score) #' @export igraph.arpack.default deprecated("igraph.arpack.default", arpack_defaults) #' @export igraph.console deprecated("igraph.console", console) #' @export igraph.eigen.default deprecated("igraph.eigen.default", eigen_defaults) #' @export igraph.sample deprecated("igraph.sample", sample_seq) #' @export igraph.version deprecated("igraph.version", igraph_version) #' @export igraphdemo deprecated("igraphdemo", igraph_demo) #' @export igraphtest deprecated("igraphtest", igraph_test) #' @export independence.number deprecated("independence.number", ivs_size) #' @export independent.vertex.sets deprecated("independent.vertex.sets", ivs) #' @export infomap.community deprecated("infomap.community", cluster_infomap) #' @export induced.subgraph deprecated("induced.subgraph", induced_subgraph) #' @export interconnected.islands.game deprecated("interconnected.islands.game", sample_islands) #' @export is.bipartite deprecated("is.bipartite", is_bipartite) #' @export is.chordal deprecated("is.chordal", is_chordal) #' @export is.connected deprecated("is.connected", is_connected) #' @export is.dag deprecated("is.dag", is_dag) #' @export is.degree.sequence deprecated("is.degree.sequence", is_degseq) #' @export is.directed deprecated("is.directed", is_directed) #' @export is.graphical.degree.sequence deprecated("is.graphical.degree.sequence", is_graphical) #' @export is.hierarchical deprecated("is.hierarchical", is_hierarchical) #' @export is.igraph deprecated("is.igraph", is_igraph) #' @export is.loop deprecated("is.loop", which_loop) #' @export is.matching deprecated("is.matching", is_matching) #' @export is.maximal.matching deprecated("is.maximal.matching", is_max_matching) #' @export is.minimal.separator deprecated("is.minimal.separator", is_min_separator) #' @export is.multiple deprecated("is.multiple", which_multiple) #' @export is.mutual deprecated("is.mutual", which_mutual) #' @export is.named deprecated("is.named", is_named) #' @export is.separator deprecated("is.separator", is_separator) #' @export is.simple deprecated("is.simple", is_simple) #' @export is.weighted deprecated("is.weighted", is_weighted) #' @export k.regular.game deprecated("k.regular.game", sample_k_regular) #' @export label.propagation.community deprecated("label.propagation.community", cluster_label_prop) #' @export largest.cliques deprecated("largest.cliques", largest_cliques) #' @export largest.independent.vertex.sets deprecated("largest.independent.vertex.sets", largest_ivs) #' @export lastcit.game deprecated("lastcit.game", sample_last_cit) #' @export layout.auto deprecated("layout.auto", layout_nicely) #' @export layout.bipartite deprecated("layout.bipartite", layout_as_bipartite) #' @export layout.davidson.harel deprecated("layout.davidson.harel", layout_with_dh) #' @export layout.drl deprecated("layout.drl", layout_with_drl) #' @export layout.gem deprecated("layout.gem", layout_with_gem) #' @export layout.graphopt deprecated("layout.graphopt", layout_with_graphopt) #' @export layout.grid deprecated("layout.grid", layout_on_grid) #' @export layout.mds deprecated("layout.mds", layout_with_mds) #' @export layout.merge deprecated("layout.merge", merge_coords) #' @export layout.norm deprecated("layout.norm", norm_coords) #' @export layout.star deprecated("layout.star", layout_as_star) #' @export layout.sugiyama deprecated("layout.sugiyama", layout_with_sugiyama) #' @export leading.eigenvector.community deprecated("leading.eigenvector.community", cluster_leading_eigen) #' @export line.graph deprecated("line.graph", make_line_graph) #' @export list.edge.attributes deprecated("list.edge.attributes", edge_attr_names) #' @export list.graph.attributes deprecated("list.graph.attributes", graph_attr_names) #' @export list.vertex.attributes deprecated("list.vertex.attributes", vertex_attr_names) #' @export maxcohesion deprecated("maxcohesion", max_cohesion) #' @export maximal.cliques deprecated("maximal.cliques", max_cliques) #' @export maximal.cliques.count deprecated("maximal.cliques.count", count_max_cliques) #' @export maximal.independent.vertex.sets deprecated("maximal.independent.vertex.sets", maximal_ivs) #' @export minimal.st.separators deprecated("minimal.st.separators", min_st_separators) #' @export maximum.bipartite.matching deprecated("maximum.bipartite.matching", max_bipartite_match) #' @export maximum.cardinality.search deprecated("maximum.cardinality.search", max_cardinality) #' @export minimum.size.separators deprecated("minimum.size.separators", min_separators) #' @export minimum.spanning.tree deprecated("minimum.spanning.tree", mst) #' @export mod.matrix deprecated("mod.matrix", modularity_matrix) #' @export multilevel.community deprecated("multilevel.community", cluster_louvain) #' @export neighborhood deprecated("neighborhood", ego) #' @export neighborhood.size deprecated("neighborhood.size", ego_size) #' @export nexus.get deprecated("nexus.get", nexus_get) #' @export nexus.info deprecated("nexus.info", nexus_info) #' @export nexus.list deprecated("nexus.list", nexus_list) #' @export nexus.search deprecated("nexus.search", nexus_search) #' @export no.clusters deprecated("no.clusters", count_components) #' @export optimal.community deprecated("optimal.community", cluster_optimal) #' @export page.rank deprecated("page.rank", page_rank) #' @export page.rank.old deprecated("page.rank.old", page_rank_old) #' @export path.length.hist deprecated("path.length.hist", distance_table) #' @export permute.vertices deprecated("permute.vertices", permute) #' @export piecewise.layout deprecated("piecewise.layout", layout_components) #' @export plotHierarchy deprecated("plotHierarchy", plot_hierarchy) #' @export power.law.fit deprecated("power.law.fit", fit_power_law) #' @export preference.game deprecated("preference.game", sample_pref) #' @export read.graph deprecated("read.graph", read_graph) #' @export remove.edge.attribute deprecated("remove.edge.attribute", delete_edge_attr) #' @export remove.graph.attribute deprecated("remove.graph.attribute", delete_graph_attr) #' @export remove.vertex.attribute deprecated("remove.vertex.attribute", delete_vertex_attr) #' @export running.mean deprecated("running.mean", running_mean) #' @export sbm.game deprecated("sbm.game", sample_sbm) #' @export scgGrouping deprecated("scgGrouping", scg_group) #' @export scgNormEps deprecated("scgNormEps", scg_eps) #' @export scgSemiProjectors deprecated("scgSemiProjectors", scg_semi_proj) #' @export set.edge.attribute deprecated("set.edge.attribute", set_edge_attr) #' @export set.graph.attribute deprecated("set.graph.attribute", set_graph_attr) #' @export set.vertex.attribute deprecated("set.vertex.attribute", set_vertex_attr) #' @export shortest.paths deprecated("shortest.paths", distances) #' @export showtrace deprecated("showtrace", show_trace) #' @export spinglass.community deprecated("spinglass.community", cluster_spinglass) #' @export stCuts deprecated("stCuts", st_cuts) #' @export stMincuts deprecated("stMincuts", st_min_cuts) #' @export static.fitness.game deprecated("static.fitness.game", sample_fitness) #' @export static.power.law.game deprecated("static.power.law.game", sample_fitness_pl) #' @export subgraph.centrality deprecated("subgraph.centrality", subgraph_centrality) #' @export tkplot.canvas deprecated("tkplot.canvas", tk_canvas) #' @export tkplot.center deprecated("tkplot.center", tk_center) #' @export tkplot.close deprecated("tkplot.close", tk_close) #' @export tkplot.export.postscript deprecated("tkplot.export.postscript", tk_postscript) #' @export tkplot.fit.to.screen deprecated("tkplot.fit.to.screen", tk_fit) #' @export tkplot.getcoords deprecated("tkplot.getcoords", tk_coords) #' @export tkplot.off deprecated("tkplot.off", tk_off) #' @export tkplot.reshape deprecated("tkplot.reshape", tk_reshape) #' @export tkplot.rotate deprecated("tkplot.rotate", tk_rotate) #' @export tkplot.setcoords deprecated("tkplot.setcoords", tk_set_coords) #' @export topological.sort deprecated("topological.sort", topo_sort) #' @export triad.census deprecated("triad.census", triad_census) #' @export unfold.tree deprecated("unfold.tree", unfold_tree) #' @export vcount deprecated("vcount", gorder) #' @export vertex.connectivity deprecated("vertex.connectivity", vertex_connectivity) #' @export vertex.disjoint.paths deprecated("vertex.disjoint.paths", vertex_disjoint_paths) #' @export walktrap.community deprecated("walktrap.community", cluster_walktrap) #' @export watts.strogatz.game deprecated("watts.strogatz.game", sample_smallworld) #' @export write.graph deprecated("write.graph", write_graph) #' @export graph.famous deprecated("graph.famous", make_famous_graph) #' @export igraph.from.graphNEL deprecated("igraph.from.graphNEL", graph_from_graphnel) #' @export igraph.to.graphNEL deprecated("igraph.to.graphNEL", as_graphnel) #' @export getIgraphOpt deprecated("getIgraphOpt", igraph_opt) #' @export igraph.options deprecated("igraph.options", igraph_options) #' @export graph.intersection deprecated("graph.intersection", intersection) #' @export exportPajek deprecated("exportPajek", export_pajek) #' @export get.diameter deprecated("get.diameter", get_diameter) #' @export get.all.shortest.paths deprecated("get.all.shortest.paths", all_shortest_paths) #' @export get.shortest.paths deprecated("get.shortest.paths", shortest_paths) #' @export graph deprecated("graph", make_graph) #' @export vertex.shapes deprecated("vertex.shapes", shapes) #' @export igraph.shape.noclip deprecated("igraph.shape.noclip", shape_noclip) #' @export igraph.shape.noplot deprecated("igraph.shape.noplot", shape_noplot) #' @export create.communities deprecated("create.communities", make_clusters) igraph/R/games.R0000644000175100001440000021055613247053711013176 0ustar hornikusers ## ----------------------------------------------------------------- ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------- #' Generate scale-free graphs according to the Barabasi-Albert model #' #' The BA-model is a very simple stochastic algorithm for building a graph. #' #' This is a simple stochastic algorithm to generate a graph. It is a discrete #' time step model and in each time step a single vertex is added. #' #' We start with a single vertex and no edges in the first time step. Then we #' add one vertex in each time step and the new vertex initiates some edges to #' old vertices. The probability that an old vertex is chosen is given by #' \deqn{P[i] \sim k_i^\alpha+a}{P[i] ~ k[i]^alpha + a} where \eqn{k_i}{k[i]} #' is the in-degree of vertex \eqn{i} in the current time step (more precisely #' the number of adjacent edges of \eqn{i} which were not initiated by \eqn{i} #' itself) and \eqn{\alpha}{alpha} and \eqn{a} are parameters given by the #' \code{power} and \code{zero.appeal} arguments. #' #' The number of edges initiated in a time step is given by the \code{m}, #' \code{out.dist} and \code{out.seq} arguments. If \code{out.seq} is given and #' not NULL then it gives the number of edges to add in a vector, the first #' element is ignored, the second is the number of edges to add in the second #' time step and so on. If \code{out.seq} is not given or null and #' \code{out.dist} is given and not NULL then it is used as a discrete #' distribution to generate the number of edges in each time step. Its first #' element is the probability that no edges will be added, the second is the #' probability that one edge is added, etc. (\code{out.dist} does not need to #' sum up to one, it normalized automatically.) \code{out.dist} should contain #' non-negative numbers and at east one element should be positive. #' #' If both \code{out.seq} and \code{out.dist} are omitted or NULL then \code{m} #' will be used, it should be a positive integer constant and \code{m} edges #' will be added in each time step. #' #' \code{sample_pa} generates a directed graph by default, set #' \code{directed} to \code{FALSE} to generate an undirected graph. Note that #' even if an undirected graph is generated \eqn{k_i}{k[i]} denotes the number #' of adjacent edges not initiated by the vertex itself and not the total (in- #' + out-) degree of the vertex, unless the \code{out.pref} argument is set to #' \code{TRUE}. #' #' @aliases sample_pa barabasi.game ba.game #' @param n Number of vertices. #' @param power The power of the preferential attachment, the default is one, #' ie. linear preferential attachment. #' @param m Numeric constant, the number of edges to add in each time step This #' argument is only used if both \code{out.dist} and \code{out.seq} are omitted #' or NULL. #' @param out.dist Numeric vector, the distribution of the number of edges to #' add in each time step. This argument is only used if the \code{out.seq} #' argument is omitted or NULL. #' @param out.seq Numeric vector giving the number of edges to add in each time #' step. Its first element is ignored as no edges are added in the first time #' step. #' @param out.pref Logical, if true the total degree is used for calculating #' the citation probability, otherwise the in-degree is used. #' @param zero.appeal The \sQuote{attractiveness} of the vertices with no #' adjacent edges. See details below. #' @param directed Whether to create a directed graph. #' @param algorithm The algorithm to use for the graph generation. #' \code{psumtree} uses a partial prefix-sum tree to generate the graph, this #' algorithm can handle any \code{power} and \code{zero.appeal} values and #' never generates multiple edges. \code{psumtree-multiple} also uses a #' partial prefix-sum tree, but the generation of multiple edges is allowed. #' Before the 0.6 version igraph used this algorithm if \code{power} was not #' one, or \code{zero.appeal} was not one. \code{bag} is the algorithm that #' was previously (before version 0.6) used if \code{power} was one and #' \code{zero.appeal} was one as well. It works by putting the ids of the #' vertices into a bag (mutliset, really), exactly as many times as their #' (in-)degree, plus once more. Then the required number of cited vertices are #' drawn from the bag, with replacement. This method might generate multiple #' edges. It only works if \code{power} and \code{zero.appeal} are equal one. #' @param start.graph \code{NULL} or an igraph graph. If a graph, then the #' supplied graph is used as a starting graph for the preferential attachment #' algorithm. The graph should have at least one vertex. If a graph is supplied #' here and the \code{out.seq} argument is not \code{NULL}, then it should #' contain the out degrees of the new vertices only, not the ones in the #' \code{start.graph}. #' @return A graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnp}} #' @references Barabasi, A.-L. and Albert R. 1999. Emergence of scaling in #' random networks \emph{Science}, 286 509--512. #' @export #' @keywords graphs #' @examples #' #' g <- sample_pa(10000) #' degree_distribution(g) #' sample_pa <- function(n, power=1, m=NULL, out.dist=NULL, out.seq=NULL, out.pref=FALSE, zero.appeal=1, directed=TRUE, algorithm=c("psumtree", "psumtree-multiple", "bag"), start.graph=NULL) { if (!is.null(start.graph) && !is_igraph(start.graph)) { stop("`start.graph' not an `igraph' object") } # Checks if (! is.null(out.seq) && (!is.null(m) || !is.null(out.dist))) { warning("if `out.seq' is given `m' and `out.dist' should be NULL") m <- out.dist <- NULL } if (is.null(out.seq) && !is.null(out.dist) && !is.null(m)) { warning("if `out.dist' is given `m' will be ignored") m <- NULL } if (!is.null(m) && m==0) { warning("`m' is zero, graph will be empty") } if (power < 0) { warning("`power' is negative") } if (is.null(m) && is.null(out.dist) && is.null(out.seq)) { m <- 1 } n <- as.numeric(n) power <- as.numeric(power) if (!is.null(m)) { m <- as.numeric(m) } if (!is.null(out.dist)) { out.dist <- as.numeric(out.dist) } if (!is.null(out.seq)) { out.seq <- as.numeric(out.seq) } out.pref <- as.logical(out.pref) if (!is.null(out.dist)) { nn <- if (is.null(start.graph)) n else n-vcount(start.graph) out.seq <- as.numeric(sample(0:(length(out.dist)-1), nn, replace=TRUE, prob=out.dist)) } if (is.null(out.seq)) { out.seq <- numeric() } algorithm <- igraph.match.arg(algorithm) algorithm1 <- switch(algorithm, "psumtree"=1, "psumtree-multiple"=2, "bag"=0) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_barabasi_game, n, power, m, out.seq, out.pref, zero.appeal, directed, algorithm1, start.graph) if (igraph_opt("add.params")) { res$name <- "Barabasi graph" res$power <- power res$m <- m res$zero.appeal <- zero.appeal res$algorithm <- algorithm } res } #' @rdname sample_pa #' @param ... Passed to \code{sample_pa}. #' @export pa <- function(...) constructor_spec(sample_pa, ...) ## ----------------------------------------------------------------- #' Generate random graphs according to the G(n,p) Erdos-Renyi model #' #' This model is very simple, every possible edge is created with the same #' constant probability. #' #' #' The graph has \sQuote{n} vertices and for each edge the #' probability that it is present in the graph is \sQuote{p}. #' #' @param n The number of vertices in the graph. #' @param p The probability for drawing an edge between two #' arbitrary vertices (G(n,p) graph). #' @param directed Logical, whether the graph will be directed, defaults to #' FALSE. #' @param loops Logical, whether to add loop edges, defaults to FALSE. #' @return A graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnm}}, \code{\link{sample_pa}} #' @references Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes #' Mathematicae} 6, 290--297 (1959). #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(1000, 1/1000) #' degree_distribution(g) sample_gnp <- function(n, p, directed = FALSE, loops = FALSE) { type <- "gnp" type1 <- switch(type, "gnp"=0, "gnm"=1) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_erdos_renyi_game, as.numeric(n), as.numeric(type1), as.numeric(p), as.logical(directed), as.logical(loops)) if (igraph_opt("add.params")) { res$name <- sprintf("Erdos renyi (%s) graph", type) res$type <- type res$loops <- loops res$p <- p } res } #' @rdname sample_gnp #' @param ... Passed to \code{sample_app}. #' @export gnp <- function(...) constructor_spec(sample_gnp, ...) ## ----------------------------------------------------------------- #' Generate random graphs according to the G(n,m) Erdos-Renyi model #' #' This model is very simple, every possible edge is created with the same #' constant probability. #' #' The graph has \sQuote{n} vertices and \sQuote{m} edges, #' and the \sQuote{m} edges are chosen uniformly randomly from the set of all #' possible edges. This set includes loop edges as well if the \code{loops} #' parameter is TRUE. #' #' @param n The number of vertices in the graph. #' @param m The number of edges in the graph. #' @param directed Logical, whether the graph will be directed, defaults to #' FALSE. #' @param loops Logical, whether to add loop edges, defaults to FALSE. #' @return A graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnp}}, \code{\link{sample_pa}} #' @references Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes #' Mathematicae} 6, 290--297 (1959). #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnm(1000, 1000) #' degree_distribution(g) sample_gnm <- function(n, m, directed = FALSE, loops = FALSE) { type <- "gnm" type1 <- switch(type, "gnp"=0, "gnm"=1) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_erdos_renyi_game, as.numeric(n), as.numeric(type1), as.numeric(m), as.logical(directed), as.logical(loops)) if (igraph_opt("add.params")) { res$name <- sprintf("Erdos renyi (%s) graph", type) res$type <- type res$loops <- loops res$m <- m } res } #' @rdname sample_gnm #' @param ... Passed to \code{sample_app}. #' @export gnm <- function(...) constructor_spec(sample_gnm, ...) ## ----------------------------------------------------------------- #' Generate random graphs according to the Erdos-Renyi model #' #' This model is very simple, every possible edge is created with the same #' constant probability. #' #' In G(n,p) graphs, the graph has \sQuote{n} vertices and for each edge the #' probability that it is present in the graph is \sQuote{p}. #' #' In G(n,m) graphs, the graph has \sQuote{n} vertices and \sQuote{m} edges, #' and the \sQuote{m} edges are chosen uniformly randomly from the set of all #' possible edges. This set includes loop edges as well if the \code{loops} #' parameter is TRUE. #' #' \code{random.graph.game} is an alias to this function. #' #' @section Deprecated: #' #' Since igraph version 0.8.0, both \code{erdos.renyi.game} and #' \code{random.graph.game} are deprecated, and \code{\link{sample_gnp}} and #' \code{\link{sample_gnm}} should be used instead. #' #' @aliases erdos.renyi.game random.graph.game #' @param n The number of vertices in the graph. #' @param p.or.m Either the probability for drawing an edge between two #' arbitrary vertices (G(n,p) graph), or the number of edges in the graph (for #' G(n,m) graphs). #' @param type The type of the random graph to create, either \code{gnp} #' (G(n,p) graph) or \code{gnm} (G(n,m) graph). #' @param directed Logical, whether the graph will be directed, defaults to #' FALSE. #' @param loops Logical, whether to add loop edges, defaults to FALSE. #' @param \dots Additional arguments, ignored. #' @return A graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_pa}} #' @references Erdos, P. and Renyi, A., On random graphs, \emph{Publicationes #' Mathematicae} 6, 290--297 (1959). #' @export #' @keywords graphs #' @examples #' #' g <- erdos.renyi.game(1000, 1/1000) #' degree_distribution(g) #' erdos.renyi.game <- function(n, p.or.m, type=c("gnp", "gnm"), directed=FALSE, loops=FALSE, ...) { type <- igraph.match.arg(type) type1 <- switch(type, "gnp"=0, "gnm"=1) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_erdos_renyi_game, as.numeric(n), as.numeric(type1), as.numeric(p.or.m), as.logical(directed), as.logical(loops)) if (igraph_opt("add.params")) { res$name <- sprintf("Erdos renyi (%s) graph", type) res$type <- type res$loops <- loops if (type=="gnp") { res$p <- p.or.m } if (type=="gnm") { res$m <- p.or.m } } res } #' @export random.graph.game <- erdos.renyi.game ## ----------------------------------------------------------------- #' Generate random graphs with a given degree sequence #' #' It is often useful to create a graph with given vertex degrees. This is #' exactly what \code{sample_degseq} does. #' #' The \dQuote{simple} method connects the out-stubs of the edges (undirected #' graphs) or the out-stubs and in-stubs (directed graphs) together. This way #' loop edges and also multiple edges may be generated. This method is not #' adequate if one needs to generate simple graphs with a given degree #' sequence. The multiple and loop edges can be deleted, but then the degree #' sequence is distorted and there is nothing to ensure that the graphs are #' sampled uniformly. #' #' The \dQuote{simple.no.multiple} method is similar to \dQuote{simple}, but #' tries to avoid multiple and loop edges and restarts the generation from #' scratch if it gets stuck. It is not guaranteed to sample uniformly from the #' space of all possible graphs with the given sequence, but it is relatively #' fast and it will eventually succeed if the provided degree sequence is #' graphical, but there is no upper bound on the number of iterations. #' #' The \dQuote{vl} method is a more sophisticated generator. The algorithm and #' the implementation was done by Fabien Viger and Matthieu Latapy. This #' generator always generates undirected, connected simple graphs, it is an #' error to pass the \code{in.deg} argument to it. The algorithm relies on #' first creating an initial (possibly unconnected) simple undirected graph #' with the given degree sequence (if this is possible at all). Then some #' rewiring is done to make the graph connected. Finally a Monte-Carlo #' algorithm is used to randomize the graph. The \dQuote{vl} samples from the #' undirected, connected simple graphs unformly. #' #' @aliases degree.sequence.game #' @param out.deg Numeric vector, the sequence of degrees (for undirected #' graphs) or out-degrees (for directed graphs). For undirected graphs its sum #' should be even. For directed graphs its sum should be the same as the sum of #' \code{in.deg}. #' @param in.deg For directed graph, the in-degree sequence. By default this is #' \code{NULL} and an undirected graph is created. #' @param method Character, the method for generating the graph. Right now the #' \dQuote{simple}, \dQuote{simple.no.multiple} and \dQuote{vl} methods are #' implemented. #' @return The new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnp}}, \code{\link{sample_pa}}, #' \code{\link{simplify}} to get rid of the multiple and/or loops edges. #' @export #' @keywords graphs #' @examples #' #' ## The simple generator #' g <- sample_degseq(rep(2,100)) #' degree(g) #' is_simple(g) # sometimes TRUE, but can be FALSE #' g2 <- sample_degseq(1:10, 10:1) #' degree(g2, mode="out") #' degree(g2, mode="in") #' #' ## The vl generator #' g3 <- sample_degseq(rep(2,100), method="vl") #' degree(g3) #' is_simple(g3) # always TRUE #' #' ## Exponential degree distribution #' ## Note, that we correct the degree sequence if its sum is odd #' degs <- sample(1:100, 100, replace=TRUE, prob=exp(-0.5*(1:100))) #' if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } #' g4 <- sample_degseq(degs, method="vl") #' all(degree(g4) == degs) #' #' ## Power-law degree distribution #' ## Note, that we correct the degree sequence if its sum is odd #' degs <- sample(1:100, 100, replace=TRUE, prob=(1:100)^-2) #' if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } #' g5 <- sample_degseq(degs, method="vl") #' all(degree(g5) == degs) sample_degseq <- function(out.deg, in.deg=NULL, method=c("simple", "vl", "simple.no.multiple")) { method <- igraph.match.arg(method) method1 <- switch(method, "simple"=0, "vl"=1, "simple.no.multiple"=2) if (!is.null(in.deg)) { in.deg <- as.numeric(in.deg) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_degree_sequence_game, as.numeric(out.deg), in.deg, as.numeric(method1)) if (igraph_opt("add.params")) { res$name <- "Degree sequence random graph" res$method <- method } res } #' @rdname sample_degseq #' @param ... Passed to \code{sample_degree}. #' @export degseq <- function(...) constructor_spec(sample_degseq, ...) ## ----------------------------------------------------------------- #' Growing random graph generation #' #' This function creates a random graph by simulating its stochastic evolution. #' #' This is discrete time step model, in each time step a new vertex is added to #' the graph and \code{m} new edges are created. If \code{citation} is #' \code{FALSE} these edges are connecting two uniformly randomly chosen #' vertices, otherwise the edges are connecting new vertex to uniformly #' randomly chosen old vertices. #' #' @aliases growing.random.game #' @param n Numeric constant, number of vertices in the graph. #' @param m Numeric constant, number of edges added in each time step. #' @param directed Logical, whether to create a directed graph. #' @param citation Logical. If \code{TRUE} a citation graph is created, ie. in #' each time step the added edges are originating from the new vertex. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_pa}}, \code{\link{sample_gnp}} #' @export #' @keywords graphs #' @examples #' #' g <- sample_growing(500, citation=FALSE) #' g2 <- sample_growing(500, citation=TRUE) #' sample_growing <- function(n, m=1, directed=TRUE, citation=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_growing_random_game, as.numeric(n), as.numeric(m), as.logical(directed), as.logical(citation)) if (igraph_opt("add.params")) { res$name <- "Growing random graph" res$m <- m res$citation <- citation } res } #' @rdname sample_growing #' @param ... Passed to \code{sample_app}. #' @export growing <- function(...) constructor_spec(sample_growing, ...) ## ----------------------------------------------------------------- #' Generate an evolving random graph with preferential attachment and aging #' #' This function creates a random graph by simulating its evolution. Each time #' a new vertex is added it creates a number of links to old vertices and the #' probability that an old vertex is cited depends on its in-degree #' (preferential attachment) and age. #' #' This is a discrete time step model of a growing graph. We start with a #' network containing a single vertex (and no edges) in the first time step. #' Then in each time step (starting with the second) a new vertex is added and #' it initiates a number of edges to the old vertices in the network. The #' probability that an old vertex is connected to is proportional to \deqn{P[i] #' \sim (c\cdot k_i^\alpha+a)(d\cdot l_i^\beta+b)\cdot }{% P[i] ~ (c k[i]^alpha #' + a) (d l[i]^beta + a)} #' #' Here \eqn{k_i}{k[i]} is the in-degree of vertex \eqn{i} in the current time #' step and \eqn{l_i}{l[i]} is the age of vertex \eqn{i}. The age is simply #' defined as the number of time steps passed since the vertex is added, with #' the extension that vertex age is divided to be in \code{aging.bin} bins. #' #' \eqn{c}, \eqn{\alpha}{alpha}, \eqn{a}, \eqn{d}, \eqn{\beta}{beta} and #' \eqn{b} are parameters and they can be set via the following arguments: #' \code{pa.exp} (\eqn{\alpha}{alpha}, mandatory argument), \code{aging.exp} #' (\eqn{\beta}{beta}, mandatory argument), \code{zero.deg.appeal} (\eqn{a}, #' optional, the default value is 1), \code{zero.age.appeal} (\eqn{b}, #' optional, the default is 0), \code{deg.coef} (\eqn{c}, optional, the default #' is 1), and \code{age.coef} (\eqn{d}, optional, the default is 1). #' #' The number of edges initiated in each time step is governed by the \code{m}, #' \code{out.seq} and \code{out.pref} parameters. If \code{out.seq} is given #' then it is interpreted as a vector giving the number of edges to be added in #' each time step. It should be of length \code{n} (the number of vertices), #' and its first element will be ignored. If \code{out.seq} is not given (or #' NULL) and \code{out.dist} is given then it will be used as a discrete #' probability distribution to generate the number of edges. Its first element #' gives the probability that zero edges are added at a time step, the second #' element is the probability that one edge is added, etc. (\code{out.seq} #' should contain non-negative numbers, but if they don't sum up to 1, they #' will be normalized to sum up to 1. This behavior is similar to the #' \code{prob} argument of the \code{sample} command.) #' #' By default a directed graph is generated, but it \code{directed} is set to #' \code{FALSE} then an undirected is created. Even if an undirected graph is #' generaed \eqn{k_i}{k[i]} denotes only the adjacent edges not initiated by #' the vertex itself except if \code{out.pref} is set to \code{TRUE}. #' #' If the \code{time.window} argument is given (and not NULL) then #' \eqn{k_i}{k[i]} means only the adjacent edges added in the previous #' \code{time.window} time steps. #' #' This function might generate graphs with multiple edges. #' #' @aliases sample_pa_age aging.prefatt.game aging.barabasi.game aging.ba.game #' @param n The number of vertices in the graph. #' @param pa.exp The preferantial attachment exponent, see the details below. #' @param aging.exp The exponent of the aging, usually a non-positive number, #' see details below. #' @param m The number of edges each new vertex creates (except the very first #' vertex). This argument is used only if both the \code{out.dist} and #' \code{out.seq} arguments are NULL. #' @param aging.bin The number of bins to use for measuring the age of #' vertices, see details below. #' @param out.dist The discrete distribution to generate the number of edges to #' add in each time step if \code{out.seq} is NULL. See details below. #' @param out.seq The number of edges to add in each time step, a vector #' containing as many elements as the number of vertices. See details below. #' @param out.pref Logical constant, whether to include edges not initiated by #' the vertex as a basis of preferential attachment. See details below. #' @param directed Logical constant, whether to generate a directed graph. See #' details below. #' @param zero.deg.appeal The degree-dependent part of the #' \sQuote{attractiveness} of the vertices with no adjacent edges. See also #' details below. #' @param zero.age.appeal The age-dependent part of the \sQuote{attrativeness} #' of the vertices with age zero. It is usually zero, see details below. #' @param deg.coef The coefficient of the degree-dependent #' \sQuote{attractiveness}. See details below. #' @param age.coef The coefficient of the age-dependent part of the #' \sQuote{attractiveness}. See details below. #' @param time.window Integer constant, if NULL only adjacent added in the last #' \code{time.windows} time steps are counted as a basis of the preferential #' attachment. See also details below. #' @return A new graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_pa}}, \code{\link{sample_gnp}} #' @export #' @keywords graphs #' @examples #' #' # The maximum degree for graph with different aging exponents #' g1 <- sample_pa_age(10000, pa.exp=1, aging.exp=0, aging.bin=1000) #' g2 <- sample_pa_age(10000, pa.exp=1, aging.exp=-1, aging.bin=1000) #' g3 <- sample_pa_age(10000, pa.exp=1, aging.exp=-3, aging.bin=1000) #' max(degree(g1)) #' max(degree(g2)) #' max(degree(g3)) sample_pa_age <- function(n, pa.exp, aging.exp, m=NULL, aging.bin=300, out.dist=NULL, out.seq=NULL, out.pref=FALSE, directed=TRUE, zero.deg.appeal=1, zero.age.appeal=0, deg.coef=1, age.coef=1, time.window=NULL) { # Checks if (! is.null(out.seq) && (!is.null(m) || !is.null(out.dist))) { warning("if `out.seq' is given `m' and `out.dist' should be NULL") m <- out.dist <- NULL } if (is.null(out.seq) && !is.null(out.dist) && !is.null(m)) { warning("if `out.dist' is given `m' will be ignored") m <- NULL } if (!is.null(out.seq) && length(out.seq) != n) { stop("`out.seq' should be of length `n'") } if (!is.null(out.seq) && min(out.seq)<0) { stop("negative elements in `out.seq'"); } if (!is.null(m) && m<0) { stop("`m' is negative") } if (!is.null(time.window) && time.window <= 0) { stop("time window size should be positive") } if (!is.null(m) && m==0) { warning("`m' is zero, graph will be empty") } if (pa.exp < 0) { warning("preferential attachment is negative") } if (aging.exp > 0) { warning("aging exponent is positive") } if (zero.deg.appeal <=0 ) { warning("initial attractiveness is not positive") } if (is.null(m) && is.null(out.dist) && is.null(out.seq)) { m <- 1 } n <- as.numeric(n) if (!is.null(m)) { m <- as.numeric(m) } if (!is.null(out.dist)) { out.dist <- as.numeric(out.dist) } if (!is.null(out.seq)) { out.seq <- as.numeric(out.seq) } out.pref <- as.logical(out.pref) if (!is.null(out.dist)) { out.seq <- as.numeric(sample(0:(length(out.dist)-1), n, replace=TRUE, prob=out.dist)) } if (is.null(out.seq)) { out.seq <- numeric() } on.exit( .Call(C_R_igraph_finalizer) ) res <- if (is.null(time.window)) { .Call(C_R_igraph_barabasi_aging_game, as.numeric(n), as.numeric(pa.exp), as.numeric(aging.exp), as.numeric(aging.bin), m, out.seq, out.pref, as.numeric(zero.deg.appeal), as.numeric(zero.age.appeal), as.numeric(deg.coef), as.numeric(age.coef), directed) } else { .Call(C_R_igraph_recent_degree_aging_game, as.numeric(n), as.numeric(pa.exp), as.numeric(aging.exp), as.numeric(aging.bin), m, out.seq, out.pref, as.numeric(zero.deg.appeal), directed, time.window) } if (igraph_opt("add.params")) { res$name <- "Aging Barabasi graph" res$pa.exp <- pa.exp res$aging.exp <- aging.exp res$m <- m res$aging.bin <- aging.bin res$out.pref <- out.pref res$zero.deg.appeal <- zero.deg.appeal res$zero.age.appeal <- zero.age.appeal res$deg.coef <- deg.coef res$age.coef <- age.coef res$time.window <- if (is.null(time.window)) Inf else time.window } res } #' @rdname sample_pa_age #' @param ... Passed to \code{sample_pa_age}. #' @export pa_age <- function(...) constructor_spec(sample_pa_age, ...) ## ----------------------------------------------------------------- #' Graph generation based on different vertex types #' #' These functions implement evolving network models based on different vertex #' types. #' #' For \code{sample_traits_callaway} the simulation goes like this: in each #' discrete time step a new vertex is added to the graph. The type of this #' vertex is generated based on \code{type.dist}. Then two vertices are #' selected uniformly randomly from the graph. The probability that they will #' be connected depends on the types of these vertices and is taken from #' \code{pref.matrix}. Then another two vertices are selected and this is #' repeated \code{edges.per.step} times in each time step. #' #' For \code{sample_traits} the simulation goes like this: a single vertex is #' added at each time step. This new vertex tries to connect to \code{k} #' vertices in the graph. The probability that such a connection is realized #' depends on the types of the vertices involved and is taken from #' \code{pref.matrix}. #' #' @aliases sample_traits_callaway sample_traits callaway.traits.game #' establishment.game #' @param nodes The number of vertices in the graph. #' @param types The number of different vertex types. #' @param edge.per.step The number of edges to add to the graph per time step. #' @param type.dist The distribution of the vertex types. This is assumed to be #' stationary in time. #' @param pref.matrix A matrix giving the preferences of the given vertex #' types. These should be probabilities, ie. numbers between zero and one. #' @param directed Logical constant, whether to generate directed graphs. #' @param k The number of trials per time step, see details below. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' # two types of vertices, they like only themselves #' g1 <- sample_traits_callaway(1000, 2, pref.matrix=matrix( c(1,0,0,1), nc=2)) #' g2 <- sample_traits(1000, 2, k=2, pref.matrix=matrix( c(1,0,0,1), nc=2)) sample_traits_callaway <- function(nodes, types, edge.per.step=1, type.dist=rep(1, types), pref.matrix=matrix(1, types, types), directed=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_callaway_traits_game, as.double(nodes), as.double(types), as.double(edge.per.step), as.double(type.dist), matrix(as.double(pref.matrix), types, types), as.logical(directed)) if (igraph_opt("add.params")) { res$name <- "Trait-based Callaway graph" res$types <- types res$edge.per.step <- edge.per.step res$type.dist <- type.dist res$pref.matrix <- pref.matrix } res } #' @rdname sample_traits_callaway #' @param ... Passed to the constructor, \code{sample_traits} or #' \code{sample_traits_callaway}. #' @export traits_callaway <- function(...) constructor_spec(sample_traits_callaway, ...) #' @rdname sample_traits_callaway #' @export sample_traits <- function(nodes, types, k=1, type.dist=rep(1, types), pref.matrix=matrix(1, types, types), directed=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_establishment_game, as.double(nodes), as.double(types), as.double(k), as.double(type.dist), matrix(as.double(pref.matrix), types, types), as.logical(directed)) if (igraph_opt("add.params")) { res$name <- "Trait-based growing graph" res$types <- types res$k <- k res$type.dist <- type.dist res$pref.matrix <- pref.matrix } res } #' @rdname sample_traits_callaway #' @export traits <- function(...) constructor_spec(sample_traits, ...) ## ----------------------------------------------------------------- #' Geometric random graphs #' #' Generate a random graph based on the distance of random point on a unit #' square #' #' First a number of points are dropped on a unit square, these points #' correspond to the vertices of the graph to create. Two points will be #' connected with an undirected edge if they are closer to each other in #' Euclidean norm than a given radius. If the \code{torus} argument is #' \code{TRUE} then a unit area torus is used instead of a square. #' #' @aliases grg.game #' @param nodes The number of vertices in the graph. #' @param radius The radius within which the vertices will be connected by an #' edge. #' @param torus Logical constant, whether to use a torus instead of a square. #' @param coords Logical scalar, whether to add the positions of the vertices #' as vertex attributes called \sQuote{\code{x}} and \sQuote{\code{y}}. #' @return A graph object. If \code{coords} is \code{TRUE} then with vertex #' attributes \sQuote{\code{x}} and \sQuote{\code{y}}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com}, first version was #' written by Keith Briggs (\url{http://keithbriggs.info/}). #' @seealso \code{\link{sample_gnp}} #' @export #' @keywords graphs #' @examples #' #' g <- sample_grg(1000, 0.05, torus=FALSE) #' g2 <- sample_grg(1000, 0.05, torus=TRUE) #' sample_grg <- function(nodes, radius, torus=FALSE, coords=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_grg_game, as.double(nodes), as.double(radius), as.logical(torus), as.logical(coords)) if (coords) { V(res[[1]])$x <- res[[2]] V(res[[1]])$y <- res[[3]] } if (igraph_opt("add.params")) { res[[1]]$name <- "Geometric random graph" res[[1]]$radius <- radius res[[1]]$torus <- torus } res[[1]] } #' @rdname sample_grg #' @param ... Passed to \code{sample_grg}. #' @export grg <- function(...) constructor_spec(sample_grg, ...) ## ----------------------------------------------------------------- #' Trait-based random generation #' #' Generation of random graphs based on different vertex types. #' #' Both models generate random graphs with given vertex types. For #' \code{sample_pref} the probability that two vertices will be connected #' depends on their type and is given by the \sQuote{pref.matrix} argument. #' This matrix should be symmetric to make sense but this is not checked. The #' distribution of the different vertes types is given by the #' \sQuote{type.dist} vector. #' #' For \code{sample_asym_pref} each vertex has an in-type and an #' out-type and a directed graph is created. The probability that a directed #' edge is realized from a vertex with a given out-type to a vertex with a #' given in-type is given in the \sQuote{pref.matrix} argument, which can be #' asymmetric. The joint distribution for the in- and out-types is given in the #' \sQuote{type.dist.matrix} argument. #' #' @aliases sample_pref sample_asym_pref preference.game asymmetric.preference.game #' @param nodes The number of vertices in the graphs. #' @param types The number of different vertex types. #' @param type.dist The distribution of the vertex types, a numeric vector of #' length \sQuote{types} containing non-negative numbers. The vector will be #' normed to obtain probabilities. #' @param fixed.sizes Fix the number of vertices with a given vertex type #' label. The \code{type.dist} argument gives the group sizes (i.e. number of #' vertices with the different labels) in this case. #' @param type.dist.matrix The joint distribution of the in- and out-vertex #' types. #' @param pref.matrix A square matrix giving the preferences of the vertex #' types. The matrix has \sQuote{types} rows and columns. #' @param directed Logical constant, whether to create a directed graph. #' @param loops Logical constant, whether self-loops are allowed in the graph. #' @return An igraph graph. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} for the R interface #' @seealso \code{\link{sample_traits}}. #' \code{\link{sample_traits_callaway}} #' @export #' @keywords graphs #' @examples #' #' pf <- matrix( c(1, 0, 0, 1), nr=2) #' g <- sample_pref(20, 2, pref.matrix=pf) #' \dontrun{tkplot(g, layout=layout_with_fr)} #' #' pf <- matrix( c(0, 1, 0, 0), nr=2) #' g <- sample_asym_pref(20, 2, pref.matrix=pf) #' \dontrun{tkplot(g, layout=layout_in_circle)} #' sample_pref <- function(nodes, types, type.dist=rep(1, types), fixed.sizes=FALSE, pref.matrix=matrix(1, types, types), directed=FALSE, loops=FALSE) { if (nrow(pref.matrix) != types || ncol(pref.matrix) != types) { stop("Invalid size for preference matrix") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_preference_game, as.double(nodes), as.double(types), as.double(type.dist), as.logical(fixed.sizes), matrix(as.double(pref.matrix), types, types), as.logical(directed), as.logical(loops)) V(res[[1]])$type <- res[[2]]+1 if (igraph_opt("add.params")) { res[[1]]$name <- "Preference random graph" res[[1]]$types <- types res[[1]]$type.dist <- type.dist res[[1]]$fixed.sizes <- fixed.sizes res[[1]]$pref.matrix <- pref.matrix res[[1]]$loops <- loops } res[[1]] } #' @rdname sample_pref #' @param ... Passed to the constructor, \code{sample_pref} or #' \code{sample_asym_pref}. #' @export pref <- function(...) constructor_spec(sample_pref, ...) #' @rdname sample_pref #' @export sample_asym_pref <- function(nodes, types, type.dist.matrix=matrix(1, types,types), pref.matrix=matrix(1, types, types), loops=FALSE) { if (nrow(pref.matrix) != types || ncol(pref.matrix) != types) { stop("Invalid size for preference matrix") } if (nrow(type.dist.matrix) != types || ncol(type.dist.matrix) != types) { stop("Invalid size for type distribution matrix") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_asymmetric_preference_game, as.double(nodes), as.double(types), matrix(as.double(type.dist.matrix), types, types), matrix(as.double(pref.matrix), types, types), as.logical(loops)) if (igraph_opt("add.params")) { res$name <- "Asymmetric preference random graph" res$types <- types res$type.dist.matrix <- type.dist.matrix res$pref.matrix <- pref.matrix res$loops <- loops } res } #' @rdname sample_pref #' @export asym_pref <- function(...) constructor_spec(sample_asym_pref, ...) ## ----------------------------------------------------------------- connect <- function(graph, order, mode=c("all", "out", "in", "total")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_connect_neighborhood, graph, as.numeric(order), as.numeric(mode)) } #' The Watts-Strogatz small-world model #' #' Generate a graph according to the Watts-Strogatz network model. #' #' First a lattice is created with the given \code{dim}, \code{size} and #' \code{nei} arguments. Then the edges of the lattice are rewired uniformly #' randomly with probability \code{p}. #' #' Note that this function might create graphs with loops and/or multiple #' edges. You can use \code{\link{simplify}} to get rid of these. #' #' @aliases watts.strogatz.game #' @param dim Integer constant, the dimension of the starting lattice. #' @param size Integer constant, the size of the lattice along each dimension. #' @param nei Integer constant, the neighborhood within which the vertices of #' the lattice will be connected. #' @param p Real constant between zero and one, the rewiring probability. #' @param loops Logical scalar, whether loops edges are allowed in the #' generated graph. #' @param multiple Logical scalar, whether multiple edges are allowed int the #' generated graph. #' @return A graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{make_lattice}}, \code{\link{rewire}} #' @references Duncan J Watts and Steven H Strogatz: Collective dynamics of #' \sQuote{small world} networks, Nature 393, 440-442, 1998. #' @export #' @keywords graphs #' @examples #' #' g <- sample_smallworld(1, 100, 5, 0.05) #' mean_distance(g) #' transitivity(g, type="average") #' sample_smallworld <- function(dim, size, nei, p, loops=FALSE, multiple=FALSE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_watts_strogatz_game, as.numeric(dim), as.numeric(size), as.numeric(nei), as.numeric(p), as.logical(loops), as.logical(multiple)) if (igraph_opt("add.params")) { res$name <- "Watts-Strogatz random graph" res$dim <- dim res$size <- size res$nei <- nei res$p <- p res$loops <- loops res$multiple <- multiple } res } #' @rdname sample_smallworld #' @param ... Passed to \code{sample_smallworld}. #' @export smallworld <- function(...) constructor_spec(sample_smallworld, ...) ## ----------------------------------------------------------------- #' Random citation graphs #' #' \code{sample_last_cit} creates a graph, where vertices age, and #' gain new connections based on how long ago their last citation #' happened. #' #' \code{sample_cit_cit_types} is a stochastic block model where the #' graph is growing. #' #' \code{sample_cit_types} is similarly a growing stochastic block model, #' but the probability of an edge depends on the (potentiall) cited #' vertex only. #' #' @aliases cited.type.game sample_cit_types citing.cited.type.game #' sample_cit_cit_types sample_last_cit lastcit.game #' @param n Number of vertices. #' @param edges Number of edges per step. #' @param agebins Number of aging bins. #' @param pref Vector (\code{sample_last_cit} and \code{sample_cit_types} or #' matrix (\code{sample_cit_cit_types}) giving the (unnormalized) citation #' probabilities for the different vertex types. #' @param directed Logical scalar, whether to generate directed networks. #' @param types Vector of length \sQuote{\code{n}}, the types of the vertices. #' Types are numbered from zero. #' @param attr Logical scalar, whether to add the vertex types to the generated #' graph as a vertex attribute called \sQuote{\code{type}}. #' @return A new graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export sample_last_cit <- function(n, edges=1, agebins=n/7100, pref=(1:(agebins+1))^-3, directed=TRUE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_lastcit_game, as.numeric(n), as.numeric(edges), as.numeric(agebins), as.numeric(pref), as.logical(directed)) if (igraph_opt("add.params")) { res$name <- "Random citation graph based on last citation" res$edges <- edges res$agebins <- agebins } res } #' @rdname sample_last_cit #' @param ... Passed to the actual constructor. #' @export last_cit <- function(...) constructor_spec(sample_last_cit, ...) #' @rdname sample_last_cit #' @export sample_cit_types <- function(n, edges=1, types=rep(0, n), pref=rep(1, length(types)), directed=TRUE, attr=TRUE) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_cited_type_game, as.numeric(n), as.numeric(edges), as.numeric(types), as.numeric(pref), as.logical(directed)) if (attr) { V(res)$type <- types } if (igraph_opt("add.params")) { res$name <- "Random citation graph (cited type)" res$edges <- edges } res } #' @rdname sample_last_cit #' @export cit_types <- function(...) constructor_spec(sample_cit_types, ...) #' @rdname sample_last_cit #' @export sample_cit_cit_types <- function(n, edges=1, types=rep(0, n), pref=matrix(1, nrow=length(types), ncol=length(types)), directed=TRUE, attr=TRUE) { pref <- structure(as.numeric(pref), dim=dim(pref)) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_citing_cited_type_game, as.numeric(n), as.numeric(types), pref, as.numeric(edges), as.logical(directed)) if (attr) { V(res)$type <- types } if (igraph_opt("add.params")) { res$name <- "Random citation graph (citing & cited type)" res$edges <- edges } res } #' @rdname sample_last_cit #' @export cit_cit_types <- function(...) constructor_spec(sample_cit_cit_types, ...) ## ----------------------------------------------------------------- #' Bipartite random graphs #' #' Generate bipartite graphs using the Erdos-Renyi model #' #' Similarly to unipartite (one-mode) networks, we can define the $G(n,p)$, and #' $G(n,m)$ graph classes for bipartite graphs, via their generating process. #' In $G(n,p)$ every possible edge between top and bottom vertices is realized #' with probablity $p$, independently of the rest of the edges. In $G(n,m)$, we #' uniformly choose $m$ edges to realize. #' #' @aliases bipartite.random.game #' @param n1 Integer scalar, the number of bottom vertices. #' @param n2 Integer scalar, the number of top vertices. #' @param type Character scalar, the type of the graph, \sQuote{gnp} creates a #' $G(n,p)$ graph, \sQuote{gnm} creates a $G(n,m)$ graph. See details below. #' @param p Real scalar, connection probability for $G(n,p)$ graphs. Should not #' be given for $G(n,m)$ graphs. #' @param m Integer scalar, the number of edges for $G(n,p)$ graphs. Should not #' be given for $G(n,p)$ graphs. #' @param directed Logical scalar, whether to create a directed graph. See also #' the \code{mode} argument. #' @param mode Character scalar, specifies how to direct the edges in directed #' graphs. If it is \sQuote{out}, then directed edges point from bottom #' vertices to top vertices. If it is \sQuote{in}, edges point from top #' vertices to bottom vertices. \sQuote{out} and \sQuote{in} do not generate #' mutual edges. If this argument is \sQuote{all}, then each edge direction is #' considered independently and mutual edges might be generated. This argument #' is ignored for undirected graphs. #' @return A bipartite igraph graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnp}} for the unipartite version. #' @export #' @keywords graphs #' @examples #' #' ## empty graph #' sample_bipartite(10, 5, p=0) #' #' ## full graph #' sample_bipartite(10, 5, p=1) #' #' ## random bipartite graph #' sample_bipartite(10, 5, p=.1) #' #' ## directed bipartite graph, G(n,m) #' sample_bipartite(10, 5, type="Gnm", m=20, directed=TRUE, mode="all") #' sample_bipartite <- function(n1, n2, type=c("gnp", "gnm"), p, m, directed=FALSE, mode=c("out", "in", "all")) { n1 <- as.integer(n1) n2 <- as.integer(n2) type <- igraph.match.arg(type) if (!missing(p)) { p <- as.numeric(p) } if (!missing(m)) { m <- as.integer(m) } directed <- as.logical(directed) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3) if (type=="gnp" && missing(p)) { stop("Connection probability `p' is not given for Gnp graph") } if (type=="gnp" && !missing(m)) { warning("Number of edges `m' is ignored for Gnp graph") } if (type=="gnm" && missing(m)) { stop("Number of edges `m' is not given for Gnm graph") } if (type=="gnm" && !missing(p)) { warning("Connection probability `p' is ignored for Gnp graph") } on.exit( .Call(C_R_igraph_finalizer) ) if (type=="gnp") { res <- .Call(C_R_igraph_bipartite_game_gnp, n1, n2, p, directed, mode) res <- set_vertex_attr(res$graph, "type", value=res$types) res$name <- "Bipartite Gnp random graph" res$p <- p } else if (type=="gnm") { res <- .Call(C_R_igraph_bipartite_game_gnm, n1, n2, m, directed, mode) res <- set_vertex_attr(res$graph, "type", value=res$types) res$name <- "Bipartite Gnm random graph" res$m <- m } res } #' @rdname sample_bipartite #' @param ... Passed to \code{sample_bipartite}. #' @export bipartite <- function(...) constructor_spec(sample_bipartite, ...) #' Sample stochastic block model #' #' Sampling from the stochastic block model of networks #' #' This function samples graphs from a stochastic block model by (doing the #' equivalent of) Bernoulli trials for each potential edge with the #' probabilities given by the Bernoulli rate matrix, \code{pref.matrix}. #' #' @aliases sample_sbm sbm.game sbm #' @param n Number of vertices in the graph. #' @param pref.matrix The matrix giving the Bernoulli rates. This is a #' \eqn{K\times K}{KxK} matrix, where \eqn{K} is the number of groups. The #' probability of creating an edge between vertices from groups \eqn{i} and #' \eqn{j} is given by element \eqn{(i,j)}. For undirected graphs, this matrix #' must be symmetric. #' @param block.sizes Numeric vector giving the number of vertices in each #' group. The sum of the vector must match the number of vertices. #' @param directed Logical scalar, whether to generate a directed graph. #' @param loops Logical scalar, whether self-loops are allowed in the graph. #' @param \dots Passed to \code{sample_sbm}. #' @return An igraph graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_gnp}}, \code{\link{sample_gnm}} #' @references Faust, K., & Wasserman, S. (1992a). Blockmodels: Interpretation #' and evaluation. \emph{Social Networks}, 14, 5--61. #' @keywords graphs #' @examples #' #' ## Two groups with not only few connection between groups #' pm <- cbind( c(.1, .001), c(.001, .05) ) #' g <- sample_sbm(1000, pref.matrix=pm, block.sizes=c(300,700)) #' g #' @export sample_sbm <- sample_sbm #' @export sbm <- function(...) constructor_spec(sample_sbm, ...) ## ----------------------------------------------------------------- #' Sample the hierarchical stochastic block model #' #' Sampling from a hierarchical stochastic block model of networks. #' #' The function generates a random graph according to the hierarchical #' stochastic block model. #' #' @aliases sample_hierarchical_sbm hierarchical_sbm #' @param n Integer scalar, the number of vertices. #' @param m Integer scalar, the number of vertices per block. \code{n / m} must #' be integer. Alternatively, an integer vector of block sizes, if not all the #' blocks have equal sizes. #' @param rho Numeric vector, the fraction of vertices per cluster, within a #' block. Must sum up to 1, and \code{rho * m} must be integer for all elements #' of rho. Alternatively a list of rho vectors, one for each block, if they are #' not the same for all blocks. #' @param C A square, symmetric numeric matrix, the Bernoulli rates for the #' clusters within a block. Its size must mach the size of the \code{rho} #' vector. Alternatively, a list of square matrices, if the Bernoulli rates #' differ in different blocks. #' @param p Numeric scalar, the Bernoulli rate of connections between vertices #' in different blocks. #' @param \dots Passed to \code{sample_hierarchical_sbm}. #' @return An igraph graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sbm.game}} #' @keywords graphs, random graphs #' @examples #' #' ## Ten blocks with three clusters each #' C <- matrix(c(1 , 3/4, 0, #' 3/4, 0, 3/4, #' 0 , 3/4, 3/4), nrow=3) #' g <- sample_hierarchical_sbm(100, 10, rho=c(3, 3, 4)/10, C=C, p=1/20) #' g #' if (require(Matrix)) { image(g[]) } #' @export sample_hierarchical_sbm <- function(n, m, rho, C, p) { mlen <- length(m) rholen <- if (is.list(rho)) length(rho) else 1 Clen <- if (is.list(C)) length(C) else 1 commonlen <- unique(c(mlen, rholen, Clen)) if (length(commonlen) == 1 && commonlen == 1) { hsbm.1.game(n, m, rho, C, p) } else { commonlen <- setdiff(commonlen, 1) if (length(commonlen) != 1) { stop("Lengths of `m', `rho' and `C' must match") } m <- rep(m, length.out=commonlen) rho <- if (is.list(rho)) { rep(rho, length.out=commonlen) } else { rep(list(rho), length.out=commonlen) } C <- if (is.list(C)) { rep(C, length.out=commonlen) } else { rep(list(C), length.out=commonlen) } hsbm.list.game(n, m, rho, C, p) } } #' @export hierarchical_sbm <- function(...) constructor_spec(sample_hierarchical_sbm, ...) ## ----------------------------------------------------------------- #' Generate random graphs according to the random dot product graph model #' #' In this model, each vertex is represented by a latent position vector. #' Probability of an edge between two vertices are given by the dot product of #' their latent position vectors. #' #' The dot product of the latent position vectors should be in the [0,1] #' interval, otherwise a warning is given. For negative dot products, no edges #' are added; dot products that are larger than one always add an edge. #' #' @aliases sample_dot_product dot_product #' @param vecs A numeric matrix in which each latent position vector is a #' column. #' @param directed A logical scalar, TRUE if the generated graph should be #' directed. #' @param \dots Passed to \code{sample_dot_product}. #' @return An igraph graph object which is the generated random dot product #' graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{sample_dirichlet}}, \code{\link{sample_sphere_surface}} #' and \code{\link{sample_sphere_volume}} for sampling position vectors. #' @references Christine Leigh Myers Nickel: Random dot product graphs, a model #' for social networks. Dissertation, Johns Hopkins University, Maryland, USA, #' 2006. #' @keywords graphs #' @examples #' #' ## A randomly generated graph #' lpvs <- matrix(rnorm(200), 20, 10) #' lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) #' g <- sample_dot_product(lpvs) #' g #' #' ## Sample latent vectors from the surface of the unit sphere #' lpvs2 <- sample_sphere_surface(dim=5, n=20) #' g2 <- sample_dot_product(lpvs2) #' g2 #' @export sample_dot_product <- sample_dot_product #' @export dot_product <- function(...) constructor_spec(sample_dot_product, ...) #' A graph with subgraphs that are each a random graph. #' #' Create a number of Erdos-Renyi random graphs with identical parameters, and #' connect them with the specified number of edges. #' #' @section Examples: #' \preformatted{ #' g <- sample_islands(3, 10, 5/10, 1) #' oc <- cluster_optimal(g) #' oc #' } #' #' @aliases interconnected.islands.game sample_islands #' @param islands.n The number of islands in the graph. #' @param islands.size The size of islands in the graph. #' @param islands.pin The probability to create each possible edge into each #' island. #' @param n.inter The number of edges to create between two islands. #' @return An igraph graph. #' @author Samuel Thiriot #' @seealso \code{\link{sample_gnp}} #' @keywords graphs #' @export sample_islands <- sample_islands #' Create a random regular graph #' #' Generate a random graph where each vertex has the same degree. #' #' This game generates a directed or undirected random graph where the degrees #' of vertices are equal to a predefined constant k. For undirected graphs, at #' least one of k and the number of vertices must be even. #' #' The game simply uses \code{\link{sample_degseq}} with appropriately #' constructed degree sequences. #' #' @aliases sample_k_regular k.regular.game #' @param no.of.nodes Integer scalar, the number of vertices in the generated #' graph. #' @param k Integer scalar, the degree of each vertex in the graph, or the #' out-degree and in-degree in a directed graph. #' @param directed Logical scalar, whether to create a directed graph. #' @param multiple Logical scalar, whether multiple edges are allowed. #' @return An igraph graph. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @seealso \code{\link{sample_degseq}} for a generator with prescribed degree #' sequence. #' @keywords graphs #' @examples #' #' ## A simple ring #' ring <- sample_k_regular(10, 2) #' plot(ring) #' #' ## k-regular graphs on 10 vertices, with k=1:9 #' k10 <- lapply(1:9, sample_k_regular, no.of.nodes=10) #' #' layout(matrix(1:9, nrow=3, byrow=TRUE)) #' sapply(k10, plot, vertex.label=NA) #' @export sample_k_regular <- sample_k_regular #' Random graphs from vertex fitness scores #' #' This function generates a non-growing random graph with edge probabilities #' proportional to node fitness scores. #' #' This game generates a directed or undirected random graph where the #' probability of an edge between vertices \eqn{i} and \eqn{j} depends on the #' fitness scores of the two vertices involved. For undirected graphs, each #' vertex has a single fitness score. For directed graphs, each vertex has an #' out- and an in-fitness, and the probability of an edge from \eqn{i} to #' \eqn{j} depends on the out-fitness of vertex \eqn{i} and the in-fitness of #' vertex \eqn{j}. #' #' The generation process goes as follows. We start from \eqn{N} disconnected #' nodes (where \eqn{N} is given by the length of the fitness vector). Then we #' randomly select two vertices \eqn{i} and \eqn{j}, with probabilities #' proportional to their fitnesses. (When the generated graph is directed, #' \eqn{i} is selected according to the out-fitnesses and \eqn{j} is selected #' according to the in-fitnesses). If the vertices are not connected yet (or if #' multiple edges are allowed), we connect them; otherwise we select a new #' pair. This is repeated until the desired number of links are created. #' #' It can be shown that the \emph{expected} degree of each vertex will be #' proportional to its fitness, although the actual, observed degree will not #' be. If you need to generate a graph with an exact degree sequence, consider #' \code{\link{sample_degseq}} instead. #' #' This model is commonly used to generate static scale-free networks. To #' achieve this, you have to draw the fitness scores from the desired power-law #' distribution. Alternatively, you may use \code{\link{sample_fitness_pl}} #' which generates the fitnesses for you with a given exponent. #' #' @aliases sample_fitness static.fitness.game #' @param no.of.edges The number of edges in the generated graph. #' @param fitness.out A numeric vector containing the fitness of each vertex. #' For directed graphs, this specifies the out-fitness of each vertex. #' @param fitness.in If \code{NULL} (the default), the generated graph will be #' undirected. If not \code{NULL}, then it should be a numeric vector and it #' specifies the in-fitness of each vertex. #' #' If this argument is not \code{NULL}, then a directed graph is generated, #' otherwise an undirected one. #' @param loops Logical scalar, whether to allow loop edges in the graph. #' @param multiple Logical scalar, whether to allow multiple edges in the #' graph. #' @return An igraph graph, directed or undirected. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references Goh K-I, Kahng B, Kim D: Universal behaviour of load #' distribution in scale-free networks. \emph{Phys Rev Lett} 87(27):278701, #' 2001. #' @keywords graphs #' @examples #' #' N <- 10000 #' g <- sample_fitness(5*N, sample((1:50)^-2, N, replace=TRUE)) #' degree_distribution(g) #' \dontrun{plot(degree_distribution(g, cumulative=TRUE), log="xy")} sample_fitness <- sample_fitness #' Scale-free random graphs, from vertex fitness scores #' #' This function generates a non-growing random graph with expected power-law #' degree distributions. #' #' This game generates a directed or undirected random graph where the degrees #' of vertices follow power-law distributions with prescribed exponents. For #' directed graphs, the exponents of the in- and out-degree distributions may #' be specified separately. #' #' The game simply uses \code{\link{sample_fitness}} with appropriately #' constructed fitness vectors. In particular, the fitness of vertex \eqn{i} is #' \eqn{i^{-alpha}}{i^(-alpha)}, where \eqn{alpha = 1/(gamma-1)} and gamma is #' the exponent given in the arguments. #' #' To remove correlations between in- and out-degrees in case of directed #' graphs, the in-fitness vector will be shuffled after it has been set up and #' before \code{\link{sample_fitness}} is called. #' #' Note that significant finite size effects may be observed for exponents #' smaller than 3 in the original formulation of the game. This function #' provides an argument that lets you remove the finite size effects by #' assuming that the fitness of vertex \eqn{i} is #' \eqn{(i+i_0-1)^{-alpha}}{(i+i0-1)^(-alpha)} where \eqn{i_0}{i0} is a #' constant chosen appropriately to ensure that the maximum degree is less than #' the square root of the number of edges times the average degree; see the #' paper of Chung and Lu, and Cho et al for more details. #' #' @aliases sample_fitness_pl static.power.law.game #' @param no.of.nodes The number of vertices in the generated graph. #' @param no.of.edges The number of edges in the generated graph. #' @param exponent.out Numeric scalar, the power law exponent of the degree #' distribution. For directed graphs, this specifies the exponent of the #' out-degree distribution. It must be greater than or equal to 2. If you pass #' \code{Inf} here, you will get back an Erdos-Renyi random network. #' @param exponent.in Numeric scalar. If negative, the generated graph will be #' undirected. If greater than or equal to 2, this argument specifies the #' exponent of the in-degree distribution. If non-negative but less than 2, an #' error will be generated. #' @param loops Logical scalar, whether to allow loop edges in the generated #' graph. #' @param multiple Logical scalar, whether to allow multiple edges in the #' generated graph. #' @param finite.size.correction Logical scalar, whether to use the proposed #' finite size correction of Cho et al., see references below. #' @return An igraph graph, directed or undirected. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references Goh K-I, Kahng B, Kim D: Universal behaviour of load #' distribution in scale-free networks. \emph{Phys Rev Lett} 87(27):278701, #' 2001. #' #' Chung F and Lu L: Connected components in a random graph with given degree #' sequences. \emph{Annals of Combinatorics} 6, 125-145, 2002. #' #' Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions in #' scale-free networks under the Achlioptas process. \emph{Phys Rev Lett} #' 103:135702, 2009. #' @keywords graphs #' @examples #' #' g <- sample_fitness_pl(10000, 30000, 2.2, 2.3) #' \dontrun{plot(degree_distribution(g, cumulative=TRUE, mode="out"), log="xy")} sample_fitness_pl <- sample_fitness_pl #' Forest Fire Network Model #' #' This is a growing network model, which resembles of how the forest fire #' spreads by igniting trees close by. #' #' The forest fire model intends to reproduce the following network #' characteristics, observed in real networks: \itemize{ \item Heavy-tailed #' in-degree distribution. \item Heavy-tailed out-degree distribution. \item #' Communities. \item Densification power-law. The network is densifying in #' time, according to a power-law rule. \item Shrinking diameter. The diameter #' of the network decreases in time. } #' #' The network is generated in the following way. One vertex is added at a #' time. This vertex connects to (cites) \code{ambs} vertices already present #' in the network, chosen uniformly random. Now, for each cited vertex \eqn{v} #' we do the following procedure: \enumerate{ \item We generate two random #' number, \eqn{x} and \eqn{y}, that are geometrically distributed with means #' \eqn{p/(1-p)} and \eqn{rp(1-rp)}. (\eqn{p} is \code{fw.prob}, \eqn{r} is #' \code{bw.factor}.) The new vertex cites \eqn{x} outgoing neighbors and #' \eqn{y} incoming neighbors of \eqn{v}, from those which are not yet cited by #' the new vertex. If there are less than \eqn{x} or \eqn{y} such vertices #' available then we cite all of them. \item The same procedure is applied to #' all the newly cited vertices. } #' #' @aliases sample_forestfire forest.fire.game #' @param nodes The number of vertices in the graph. #' @param fw.prob The forward burning probability, see details below. #' @param bw.factor The backward burning ratio. The backward burning #' probability is calculated as \code{bw.factor*fw.prob}. #' @param ambs The number of ambassador vertices. #' @param directed Logical scalar, whether to create a directed graph. #' @return A simple graph, possibly directed if the \code{directed} argument is #' \code{TRUE}. #' @note The version of the model in the published paper is incorrect in the #' sense that it cannot generate the kind of graphs the authors claim. A #' corrected version is available from #' \url{http://www.cs.cmu.edu/~jure/pubs/powergrowth-tkdd.pdf}, our #' implementation is based on this. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{barabasi.game}} for the basic preferential attachment #' model. #' @references Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs over #' time: densification laws, shrinking diameters and possible explanations. #' \emph{KDD '05: Proceeding of the eleventh ACM SIGKDD international #' conference on Knowledge discovery in data mining}, 177--187, 2005. #' @keywords graphs #' @examples #' #' g <- sample_forestfire(10000, fw.prob=0.37, bw.factor=0.32/0.37) #' dd1 <- degree_distribution(g, mode="in") #' dd2 <- degree_distribution(g, mode="out") #' plot(seq(along=dd1)-1, dd1, log="xy") #' points(seq(along=dd2)-1, dd2, col=2, pch=2) sample_forestfire <- sample_forestfire #' Generate a new random graph from a given graph by randomly #' adding/removing edges #' #' Sample a new graph by perturbing the adjacency matrix of a given graph #' and shuffling its vertices. #' #' Please see the reference given below. #' #' @param old.graph The original graph. #' @param corr A scalar in the unit interval, the target Pearson #' correlation between the adjacency matrices of the original the generated #' graph (the adjacency matrix being used as a vector). #' @param p A numeric scalar, the probability of an edge between two #' vertices, it must in the open (0,1) interval. #' @param permutation A numeric vector, a permutation vector that is #' applied on the vertices of the first graph, to get the second graph. If #' \code{NULL}, the vertices are not permuted. #' @return An unweighted graph of the same size as \code{old.graph} such #' that the correlation coefficient between the entries of the two #' adjacency matrices is \code{corr}. Note each pair of corresponding #' matrix entries is a pair of correlated Bernoulli random variables. #' #' @seealso \code{\link{sample_correlated_gnp_pair}}, #' \code{\link{sample_gnp}} #' @references Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seeded #' graph matching for correlated Erdos-Renyi graphs. #' \url{http://arxiv.org/abs/1304.7844} #' @examples #' g <- sample_gnp(1000, .1) #' g2 <- sample_correlated_gnp(g, corr = 0.5) #' cor(as.vector(g[]), as.vector(g2[])) #' g #' g2 sample_correlated_gnp <- sample_correlated_gnp #' Sample a pair of correlated G(n,p) random graphs #' #' Sample a new graph by perturbing the adjacency matrix of a given graph and #' shuffling its vertices. #' #' Please see the reference given below. #' #' @param n Numeric scalar, the number of vertices for the sampled graphs. #' @param corr A scalar in the unit interval, the target Pearson correlation #' between the adjacency matrices of the original the generated graph (the #' adjacency matrix being used as a vector). #' @param p A numeric scalar, the probability of an edge between two vertices, #' it must in the open (0,1) interval. #' @param directed Logical scalar, whether to generate directed graphs. #' @param permutation A numeric vector, a permutation vector that is applied on #' the vertices of the first graph, to get the second graph. If \code{NULL}, #' the vertices are not permuted. #' @return A list of two igraph objects, named \code{graph1} and #' \code{graph2}, which are two graphs whose adjacency matrix entries are #' correlated with \code{corr}. #' #' @seealso \code{\link{sample_correlated_gnp}}, #' \code{\link{sample_gnp}}. #' @references Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seeded #' graph matching for correlated Erdos-Renyi graphs. #' \url{http://arxiv.org/abs/1304.7844} #' @keywords graphs,random graphs #' @examples #' gg <- sample_correlated_gnp_pair(n = 10, corr = .8, p = .5, #' directed = FALSE) #' gg #' cor(as.vector(gg[[1]][]), as.vector(gg[[2]][])) sample_correlated_gnp_pair <- sample_correlated_gnp_pair igraph/R/lazyeval.R0000644000175100001440000001444113177712334013731 0ustar hornikusersas.lazy <- function(x, env = baseenv()) UseMethod("as.lazy") as.lazy.lazy <- function(x, env = baseenv()) x as.lazy.formula <- function(x, env = baseenv()) lazy_(x[[2]], environment(x)) as.lazy.character <- function(x, env = baseenv()) lazy_(parse(text = x)[[1]], env) as.lazy.call <- function(x, env = baseenv()) lazy_(x, env) as.lazy.name <- function(x, env = baseenv()) lazy_(x, env) as.lazy.numeric <- function(x, env = baseenv()) { if (length(x) > 1) { warning("Truncating vector to length 1", call. = FALSE) x <- x[1] } lazy_(x, env) } as.lazy.logical <- as.lazy.numeric as.lazy_dots <- function(x, env) UseMethod("as.lazy_dots") as.lazy_dots.NULL <- function(x, env = baseenv()) { structure(list(), class = "lazy_dots") } as.lazy_dots.list <- function(x, env = baseenv()) { structure(lapply(x, as.lazy, env = env), class = "lazy_dots") } as.lazy_dots.name <- function(x, env = baseenv()) { structure(list(as.lazy(x, env)), class = "lazy_dots") } as.lazy_dots.formula <- as.lazy_dots.name as.lazy_dots.call <- as.lazy_dots.name as.lazy_dots.lazy <- function(x, env = baseenv()) { structure(list(x), class = "lazy_dots") } as.lazy_dots.character <- function(x, env = baseenv()) { structure(lapply(x, as.lazy, env = env), class = "lazy_dots") } as.lazy_dots.lazy_dots <- function(x, env = baseenv()) { x } all_dots <- function(.dots, ..., all_named = FALSE) { dots <- as.lazy_dots(list(...)) if (!missing(.dots)) { dots2 <- as.lazy_dots(.dots) dots <- c(dots, dots2) } if (all_named) { dots <- auto_name(dots) } dots } lazy_eval <- function(x, data = NULL) { if (is.lazy_dots(x)) { return(lapply(x, lazy_eval, data = data)) } x <- as.lazy(x) if (!is.null(data)) { eval(x$expr, data, x$env) } else { eval(x$expr, x$env, emptyenv()) } } interp <- function(`_obj`, ..., .values) { UseMethod("interp") } interp.call <- function(`_obj`, ..., .values) { values <- all_values(.values, ...) substitute_(`_obj`, values) } interp.name <- function(`_obj`, ..., .values) { values <- all_values(.values, ...) substitute_(`_obj`, values) } interp.formula <- function(`_obj`, ..., .values) { values <- all_values(.values, ...) `_obj`[[2]] <- substitute_(`_obj`[[2]], values) `_obj` } interp.lazy <- function(`_obj`, ..., .values) { values <- all_values(.values, ...) `_obj`$expr <- substitute_(`_obj`$expr, values) `_obj` } interp.character <- function(`_obj`, ..., .values) { values <- all_values(.values, ...) expr1 <- parse(text = `_obj`)[[1]] expr2 <- substitute_(expr1, values) deparse(expr2) } substitute_ <- function(x, env) { call <- substitute(substitute(x, env), list(x = x)) eval(call) } all_values <- function(.values, ...) { if (missing(.values)) { values <- list(...) } else if (identical(.values, globalenv())) { # substitute doesn't want to replace in globalenv values <- as.list(globalenv()) } else { values <- .values } # Replace lazy objects with their expressions is_lazy <- vapply(values, is.lazy, logical(1)) values[is_lazy] <- lapply(values[is_lazy], `[[`, "expr") values } missing_arg <- function() { quote(expr = ) } lazy_dots <- function(..., .follow_symbols = FALSE) { if (nargs() == 0 || (nargs() == 1 && ! missing(.follow_symbols))) { return(structure(list(), class = "lazy_dots")) } .Call(C_make_lazy_dots, environment(), .follow_symbols) } is.lazy_dots <- function(x) inherits(x, "lazy_dots") `[.lazy_dots` <- function(x, i) { structure(NextMethod(), class = "lazy_dots") } `$<-.lazy_dots` <- function(x, i, value) { value <- as.lazy(value, parent.frame()) x[[i]] <- value x } `[<-.lazy_dots` <- function(x, i, value) { value <- lapply(value, as.lazy, env = parent.frame()) NextMethod() } c.lazy_dots <- function(..., recursive = FALSE) { structure(NextMethod(), class = "lazy_dots") } lazy_ <- function(expr, env) { stopifnot(is.call(expr) || is.name(expr) || is.atomic(expr)) structure(list(expr = expr, env = env), class = "lazy") } lazy <- function(expr, env = parent.frame(), .follow_symbols = TRUE) { .Call(C_make_lazy, quote(expr), environment(), .follow_symbols) } is.lazy <- function(x) inherits(x, "lazy") print.lazy <- function(x, ...) { code <- deparse(x$expr) if (length(code) > 1) { code <- paste(code[[1]], "...") } cat("\n") cat(" expr: ", code, "\n", sep = "") cat(" env: ", format(x$env), "\n", sep = "") } make_call <- function(fun, args) { stopifnot(is.call(fun) || is.name(fun)) args <- as.lazy_dots(args) expr <- lapply(args, `[[`, "expr") lazy_( as.call(c(fun, expr)), common_env(args) ) } common_env <- function(dots) { if (!is.list(dots)) stop("dots must be a list", call. = FALSE) if (length(dots) == 0) return(baseenv()) dots <- as.lazy_dots(dots) env <- dots[[1]]$env if (length(dots) == 1) return(env) for (i in 2:length(dots)) { if (!identical(env, dots[[i]]$env)) { return(baseenv()) } } env } eval_call <- function(fun, dots, env = parent.frame()) { vars <- paste0("x", seq_along(dots)) names(vars) <- names(dots) # Create environment containing promises env <- new.env(parent = env) for(i in seq_along(dots)) { dot <- dots[[i]] assign_call <- substitute( delayedAssign(vars[i], expr, dot$env, assign.env = env), list(expr = dot$expr) ) eval(assign_call) } args <- lapply(vars, as.symbol) call <- as.call(c(fun, args)) eval(call, env) } auto_name <- function(x, max_width = 40) { names(x) <- auto_names(x, max_width = max_width) x } auto_names <- function(x, max_width = 40) { x <- as.lazy_dots(x) nms <- names(x) %||% rep("", length(x)) missing <- nms == "" expr <- lapply(x[missing], `[[`, "expr") nms[missing] <- vapply(expr, deparse_trunc, width = max_width, FUN.VALUE = character(1), USE.NAMES = FALSE) nms } deparse_trunc <- function(x, width = getOption("width")) { if (is.symbol(x)) { return(as.character(x)) } text <- deparse(x, width.cutoff = width) if (length(text) == 1 && nchar(text) < width) return(text) paste0(substr(text[1], 1, width - 3), "...") } promise_expr <- function(prom) { .Call(C_promise_expr_, prom) } promise_env <- function(prom) { .Call(C_promise_env_, prom) } as.lazy.promise <- function(x, ...) { lazy_(promise_expr(x), promise_env(x)) } "%||%" <- function(x, y) if(is.null(x)) y else x igraph/R/nexus.R0000644000175100001440000005151313247070263013241 0ustar hornikusers # IGraph R package # Copyright (C) 2011-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### makeNexusDatasetInfo <- function(entries) { dsi <- lapply(entries, "[", 2) nam <- sapply(entries, "[", 1) attr <- nam=="attribute" myattr <- unlist(dsi[attr]) dsi <- dsi[!attr] nam <- nam[!attr] names(dsi) <- nam class(dsi) <- "nexusDatasetInfo" if (length(myattr) != 0) { myattr <- strsplit(myattr, "\n", fixed=TRUE) attrdat <- lapply(myattr, function(x) strsplit(x[1], " ")[[1]]) myattr <- sapply(myattr, "[", 2) dsi$attributes <- mapply(attrdat, myattr, SIMPLIFY=FALSE, FUN=function(dat, desc) { list(type=dat[1], datatype=dat[2], name=dat[3], description=desc) }) } dsi$id <- as.numeric(dsi$id) dsi$tags <- strsplit(dsi$tags, ";", fixed=TRUE)[[1]] dsi } #' @method print nexusDatasetInfo #' @rdname nexus print.nexusDatasetInfo <- function(x, ...) { ve <- strsplit(parseVE(x$`vertices/edges`), "/")[[1]] nc <- c("U", "-", "-", "-") if ("directed" %in% x$tags && "undirected" %in% x$tags) { nc[1] <- "B" } else if ("directed" %in% x$tags) { nc[1] <- "D" } if (is.null(x$attributes)) { nc[2] <- "?" } else if (any(sapply(x$attributes, function(X) X$name=="name" && X$type=="vertex"))) { nc[2] <- "N" } if ("weighted" %in% x$tags) { nc[3] <- "W" } if ("bipartite" %in% x$tags) { nc[4] <- "B" } nc <- paste(nc, collapse="") head <- paste(sep="", "NEXUS ", nc, " ", ve[1], " ", ve[2], " #", x$id, " ", x$sid, " -- ", x$name) if (nchar(head) > getOption("width")) { head <- paste(sep="", substr(head, 1, getOption("width")-1), "+") } cat(head, sep="", "\n") if (length(x$tags) != 0) { tt <- strwrap(paste(sep="", "+ tags: ", paste(x$tags, collapse="; ")), initial="", prefix=" ") cat(tt, sep="\n") } if ("networks" %in% names(x)) { nets <- strsplit(x$networks, " ")[[1]] nn <- strwrap(paste(sep="", "+ nets: ", paste(nets, collapse="; ")), initial="", prefix=" ") cat(nn, sep="\n") } attr <- x[["attributes"]] printed <- c("id", "sid", "vertices/edges", "name", "tags", "networks", "attributes") x <- x[ setdiff(names(x), printed) ] if (length(attr)>0) { dcode <- function(d) { if (d=="numeric") return("n") if (d=="string") return("c") "x" } cat("+ attr: ") astr <- sapply(attr, function(a) { paste(sep="", a$name, " (", substr(a$type, 1, 1), "/", dcode(a$datatype), ")") }) cat(strwrap(paste(astr, collapse=", "), exdent=2), "\n") } for (i in names(x)) { xx <- strsplit(x[[i]], "\n")[[1]] ff <- strwrap(paste(sep="", "+ ", i, ": ", xx[1]), initial="", prefix=" ") xx <- unlist(sapply(xx[-1], strwrap, prefix=" ")) cat(ff, sep="\n") if (length(xx)>0) { cat(xx, sep="\n") } } invisible(x) } #' @method summary nexusDatasetInfoList #' @rdname nexus summary.nexusDatasetInfoList <- function(object, ...) { o <- as.numeric(attr(object, "offset")) s <- as.numeric(attr(object, "size")) t <- as.numeric(attr(object, "totalsize")) n <- attr(object, "name") cat(sep="", "NEXUS ", o+1, "-", o+s, "/", t, " -- ", n, "\n") invisible(object) } parseVE <- function(ve) { if (length(ve)==0) { return(character(0)) } ve <- strsplit(unname(ve), " ") ve <- lapply(ve, strsplit, "/") v <- lapply(ve, function(x) sapply(x, "[", 1)) e <- lapply(ve, function(x) sapply(x, "[", 2)) int <- function(x) { if (length(unique(x))==1) { as.character(x[1]) } else { paste(sep="", min(x), "-", max(x)) } } v <- sapply(v, int) e <- sapply(e, int) paste(v, sep="/", e) } #' @method print nexusDatasetInfoList #' @rdname nexus print.nexusDatasetInfoList <- function(x, ...) { summary(x) if (length(x)==0) { return(invisible(x)) } ve <- parseVE(unname(sapply(x, "[[", "vertices/edges"))) nets <- sapply(x, function(y) length(strsplit(y$networks, " ")[[1]])) sid <- sapply(x, "[[", "sid") if (any(nets>1)) { sid[nets > 1] <- paste(sep="", sid[nets>1], ".", nets[nets>1]) } df <- data.frame(no=paste(sep="", "[", format(seq_along(x)), "] "), sid=format(sid), size=paste(sep="", " ", format(ve)), id=paste(sep="", " #", format(sapply(x, "[[", "id")), " "), name=sapply(x, "[[", "name")) out <- do.call(paste, c(as.list(df), sep="")) long <- nchar(out) > getOption("width") out <- paste(sep="", substr(out, 1, getOption("width")-1), ifelse(long, "+", "")) cat(out, sep="\n") invisible(x) } nexus.format.result <- function(l, name="") { if (length(l)==0) { res <- list() class(res) <- "nexusDatasetInfoList" return(res) } l <- lapply(l, function(x) c(sub("[ ]*:[^:]*$", "", x), sub("^[^:]*:[ ]*", "", x))) spos <- which(sapply(l, function(x) x[1]=="id")) epos <- c((spos-1), length(l)) ehead <- epos[1] epos <- epos[-1] res <- mapply(spos, epos, SIMPLIFY=FALSE, FUN=function(s, e) makeNexusDatasetInfo(l[s:e])) class(res) <- "nexusDatasetInfoList" for (h in 1:ehead) { attr(res, l[[h]][1]) <- l[[h]][2] attr(res, "name") <- name } res } #' Query and download from the Nexus network repository #' #' The Nexus network repository is an online collection of network data sets. #' These functions can be used to query it and download data from it, directly #' as an igraph graph. #' #' Nexus is an online repository of networks, with an API that allow #' programatic queries against it, and programatic data download as well. #' #' The \code{nexus_list} and \code{nexus_info} functions query the online #' database. They both return \code{nexusDatasetInfo} objects. #' \code{nexus_info} returns more information than \code{nexus_list}. #' #' \code{nexus_search} searches Nexus, and returns a list of data sets, as #' \code{nexusDatasetInfo} objects. See below for some search examples. #' #' \code{nexus_get} downloads a data set from Nexus, based on its numeric id, #' or based on a Nexus search string. For search strings, only the first search #' hit is downloaded, but see also the \code{offset} argument. (If there are #' not data sets found, then the function returns an error.) #' #' The \code{nexusDatasetInfo} objects returned by \code{nexus_list} have the #' following fields: \describe{ #' \item{id}{The numeric id of the dataset.} #' \item{sid}{The character id of the dataset.} #' \item{name}{Character scalar, the name of the dataset.} #' \item{vertices/edges}{Character, the number of vertices and edges in #' the graph(s). Vertices and edges are separated by a slash, and if #' the data set consists of multiple networks, then they are separated #' by spaces.} #' \item{tags}{Character vector, the tags of the dataset. Directed graph #' have the tags \sQuote{directed}. Undirected graphs are tagged #' as \sQuote{undirected}. Other common tags are: \sQuote{weighted}, #' \sQuote{bipartite}, \sQuote{social network}, etc.} #' \item{networks}{The ids and names of the networks in the data set. The #' numeric and character id are separated by a slash, and multiple networks #' are separated by spaces.} #' } #' #' \code{nexusDatasetInfo} objects returned by \code{nexus_info} have the #' following additional fields: \describe{ #' \item{date}{Character scalar, e.g. \sQuote{2011-01-09}, the date when #' the dataset was added to the database.} #' \item{formats}{Character vector, the data formats in which the data set is #' available. The various formats are separated by semicolons.} #' \item{licence}{Character scalar, the licence of the dataset.} #' \item{licence url}{Character scalar, the URL of the licence of the #' dataset. Pleaase make sure you consult this before using a dataset.} #' \item{summary}{Character scalar, the short description of the dataset, #' this is usually a single sentence.} #' \item{description}{Character scalar, the full description of the #' dataset.} #' \item{citation}{Character scalar, the paper(s) describing the #' dataset. Please cite these papers if you are using the dataset in your #' research, the licence of most datasets requires this.} #' \item{attributes}{A list of lists, each list entry is a graph, vertex #' or edge attribute and has the following entries: \describe{ #' \item{type}{Type of the attribute, either \sQuote{graph}, #' \sQuote{vertex} or \sQuote{edge}.} #' \item{datatype}{Data type of the attribute, currently it can be #' \sQuote{numeric} and \sQuote{string}.} #' \item{name}{Character scalar, the name of the attribute.} #' \item{description}{Character scalar, the description of the #' attribute.} #' } #' } #' } #' #' The results of the Nexus queries are printed to the screen in a consise #' format, similar to the format of igraph graphs. A data set list (typically #' the result of \code{nexus_list} and \code{nexus_search}) looks like this: #' \preformatted{NEXUS 1-5/18 -- data set list #' [1] kaptail.4 39/109-223 #18 Kapferer tailor shop #' [2] condmatcollab2003 31163/120029 #17 Condensed matter collaborations+ #' [3] condmatcollab 16726/47594 #16 Condensed matter collaborations+ #' [4] powergrid 4941/6594 #15 Western US power grid #' [5] celegansneural 297/2359 #14 C. Elegans neural network } #' Each line here represents a data set, and the following information is #' given about them: the character id of the data set (e.g. \code{kaptail} #' or \code{powergrid}), the number of vertices and number of edges in the #' graph of the data sets. For data sets with multiple graphs, intervals #' are given here. Then the numeric id of the data set and the reamining #' space is filled with the name of the data set. #' #' Summary information about an individual Nexus data set is printed as #' \preformatted{NEXUS B--- 39 109-223 #18 kaptail -- Kapferer tailor shop #' + tags: directed; social network; undirected #' + nets: 1/KAPFTI2; 2/KAPFTS2; 3/KAPFTI1; 4/KAPFTS1} #' This is very similar to the header that is used for printing igraph #' graphs, but there are some differences as well. The four characters #' after the \code{NEXUS} word give the most important properties of the #' graph(s): the first is \sQuote{\code{U}} for undirected and #' \sQuote{\code{D}} for directed graphs, and \sQuote{\code{B}} if the data #' set contains both directed and undirected graphs. The second is #' \sQuote{\code{N}} named graphs. The third character is \sQuote{\code{W}} #' for weighted graphs, the fourth is \sQuote{\code{B}} if the data set #' contains bipartite graphs. Then the number of vertices and number of #' edges are printed, for data sets with multiple graphs, the smallest and #' the largest values are given. Then comes the numeric id, and the string #' id of the data set. The end of the first line contains the name of the #' data set. The second row lists the data set tags, and the third row the #' networks that are included in the data set. #' #' Detailed data set information is printed similarly, but it contains more #' fields. #' #' @rdname nexus #' @aliases nexus nexus.list nexus.info nexus.get nexus.search nexus_list #' nexus_info nexus_get nexus_search nexusDatasetInfo print.nexusDatasetInfo #' print.nexusDatasetInfoList summary.nexusDatasetInfoList #' @param tags A character vector, the tags that are searched. If not given (or #' \code{NULL}), then all datasets are listed. #' @param offset An offset to select part of the results. Results are listed #' from \code{offset}+1. #' @param limit The maximum number of results to return. #' @param operator A character scalar. If \sQuote{or} (the default), then all #' datasets that have at least one of the given tags, are returned. If it if #' \sQuote{and}, then only datasets that have all the given tags, are returned. #' @param order The ordering of the results, possible values are: #' \sQuote{date}, \sQuote{name}, \sQuote{popularity}. #' @param id The numeric or character id of the data set to query or download. #' Instead of the data set ids, it is possible to supply a #' \code{nexusDatasetInfo} or \code{nexusDatasetInfoList} object here directly #' and then the query is done on the corresponding data set(s). #' @param q Nexus search string. See examples below. #' @param nexus.url The URL of the Nexus server. Don't change this from the #' default, unless you set up your own Nexus server. #' @param x,object The \code{nexusDatasetInfo} object to print. #' @param \dots Currently ignored. #' @return \code{nexus_list} and \code{nexus_search} return a list of #' \code{nexusDatasetInfo} objects. The list also has these attributes: #' \describe{ \item{size}{The number of data sets returned by the query.} #' \item{totalsize}{The total number of data sets found for the query.} #' \item{offset}{The offset parameter of the query.} \item{limit}{The limit #' parameter of the query.} } #' #' \code{nexus_info} returns a single \code{nexusDatasetInfo} object. #' #' \code{nexus_get} returns an igraph graph object, or a list of graph objects, #' if the data set consists of multiple networks. #' @section Examples: #' \preformatted{ #' nexus_list(tag="weighted") #' nexus_list(limit=3, order="name") #' nexus_list(limit=3, order="name")[[1]] #' nexus_info(2) #' g <- nexus_get(2) #' summary(g) #' #' ## Data sets related to 'US': #' nexus_search("US") #' #' ## Search for data sets that have 'network' in their name: #' nexus_search("name:network") #' #' ## Any word can match #' nexus_search("blog or US or karate") #' } #' @export #' @importFrom utils URLencode nexus_list <- function(tags=NULL, offset=0, limit=10, operator=c("or", "and"), order=c("date", "name", "popularity"), nexus.url=igraph_opt("nexus.url")) { operator=igraph.match.arg(operator) order=igraph.match.arg(order) if (is.null(tags)) { u <- paste(sep="", nexus.url, "/api/dataset_info?format=text", "&offset=", offset, "&limit=", limit, "&order=", order) name <- "data set list" } else { tags <- paste(tags, collapse="|") u <- paste(sep="", nexus.url, "/api/dataset_info?tag=", tags, "&operator=", operator, "&format=text", "&offset=", offset, "&limit=", limit, "&order=", order) name <- paste("tags:", gsub("|", "; ", tags, fixed=TRUE)) } f <- url(URLencode(u)) l <- readLines(f) close(f) nexus.format.result(l, name) } #' @export #' @rdname nexus #' @importFrom utils URLencode nexus_info <- function(id, nexus.url=igraph_opt("nexus.url")) { if (inherits(id, "nexusDatasetInfo")) { id <- id$id } else if (inherits(id, "nexusDatasetInfoList")) { rid <- sapply(id, "[[", "id") res <- lapply(rid, nexus_info, nexus.url=nexus.url) class(res) <- class(id) attributes(res) <- attributes(id) return(res) } u <- paste(sep="", nexus.url, "/api/dataset_info?format=text&id=", id) f <- url(URLencode(u)) l <- readLines(f) close(f) l2 <- character() for (i in seq_along(l)) { if (!grepl("^ ", l[i])) { l2 <- c(l2, l[i]) } else { l2[length(l2)] <- paste(sep="\n", l2[length(l2)], sub(" ", "", l[i], fixed=TRUE)) } } l2 <- lapply(l2, function(x) c(sub("[ ]*:.*$", "", x), sub("^[^:]*:[ ]*", "", x))) res <- makeNexusDatasetInfo(l2) if (! "attributes" %in% names(res)) { res$attributes <- list() } return(res) } #' @export #' @rdname nexus #' @importFrom utils URLencode nexus_get <- function(id, offset=0, order=c("date", "name", "popularity"), nexus.url=igraph_opt("nexus.url")) { order=igraph.match.arg(order) if (inherits(id, "nexusDatasetInfo")) { id <- id$id } else if (inherits(id, "nexusDatasetInfoList")) { id <- sapply(id, "[[", "id") return(lapply(id, nexus_get, nexus.url=nexus.url)) } u <- paste(sep="", nexus.url, "/api/dataset?id=", id, "&format=R-igraph") env <- new.env() rdata <- url(URLencode(u)) load(rdata, envir=env) close(rdata) res <- get(ls(env)[1], env) upgrade_if_igraph <- function(x) if (is_igraph(x)) upgrade_graph(x) else x if (is_igraph(res)) { upgrade_if_igraph(res) } else if (is.list(res)) { res2 <- lapply(res, upgrade_if_igraph) attributes(res2) <- attributes(res) res2 } } #' @export #' @rdname nexus #' @importFrom utils URLencode nexus_search <- function(q, offset=0, limit=10, order=c("date", "name", "popularity"), nexus.url=igraph_opt("nexus.url")) { order=igraph.match.arg(order) u <- paste(sep="", nexus.url, "/api/search?q=", q, "&format=text","&offset=", offset, "&limit=", limit, "&order=", order) f <- url(URLencode(u)) l <- readLines(f) close(f) if (length(l)==0) { res <- list() class(res) <- "nexusDatasetInfoList" return(res) } nexus.format.result(l, name=paste("q:", q)) } #' @param i Index. #' @method [ nexusDatasetInfoList #' @rdname nexus `[.nexusDatasetInfoList` <- function(x, i) { res <- unclass(x)[i] class(res) <- class(x) attributes(res) <- attributes(x) res } ' DATA SET LIST: -------------- NEXUS 1-10/18 -- data set list [ 1] kaptail.4 #18 39/109-223 Kapferer tailor shop [ 2] condmatcollab2003 #17 31163/120029 Condensed matter collaborations, 2003 [ 3] condmatcollab #16 16726/47594 Condensed matter collaborations, 1999 [ 4] powergrid #15 4941/6594 Western US power grid [ 5] celegansneural #14 297/2359 C. Elegans neural network [ 6] polblogs #13 1490/19090 US political blog network [ 7] dolphins #12 62/159 Dolphin social network [ 8] football #11 115/616 Network of American college ... [ 9] adjnoun #10 112/425 Word adjacencies from David ... [10] huckleberry # 9 74/301 Coappearance network from ... TAG SEARCH: ----------- NEXUS 1-4/4 -- tags: directed [1] kaptail.4 #18 39/109-223 Kapferer tailor shop [2] polblogs #13 1490/19090 US political blog network [3] macaque # 4 45/463 Macaque visuotactile brain areas [4] UKfaculty # 2 81/817 UK faculty social network FULL TEXT SEARCH: ----------------- NEXUS 1-2/2 -- q: US [1] powergrid #15 4941/6594 Western US power grid [2] polblogs #13 1490/19090 US political blog network DATA SET SUMMARY: ----------------- NEXUS B--- 39 109-223 -- #18 Kapferer tailor shop + tags: directed; social network; undirected + networks: 1/KAPFTI2; 2/KAPFTS2; 3/KAPFTI1; 4/KAPFTS1 NEXUS U--- 4941 6594 -- #15 Western US power grid + tags: technology DATA SET INFO: -------------- NEXUS B--- 39 109-223 -- #18 Kapferer tailor shop + tags: directed; social network; undirected + attr: name (v/c) [Actor names] + networks: 1/KAPFTI2; 2/KAPFTS2; 3/KAPFTI1; 4/KAPFTS1 + nets: #1 KAPFTI2; #2 KAPFTS2; #3 KAPFTI1; #4 KAPFTS1 + date: 2011-01-23 + licence: Creative Commons by-sa 3.0 + licence url: http://creativecommons.org/licenses/by-sa/3.0/ + summary: Interactions in a tailor shop in Zambia (then Northern Rhodesia) over a period of ten months. + details: Bruce Kapferer (1972) observed interactions in a tailor shop in Zambia (then Northern Rhodesia) over a period of ten months. His focus was the changing patterns of alliance among workers during extended negotiations for higher wages. . The matrices represent two different types of interaction, recorded at two different times (seven months apart) over a period of one month. TI1 and TI2 record the "instrumental" (work- and assistance-related) interactions at the two times; TS1 and TS2 the "sociational" (friendship, socioemotional) interactions. . The data are particularly interesting since an abortive strike occurred after the first set of observations, and a successful strike took place after the second. + formats: Pajek; R-igraph + citation: Kapferer B. (1972). Strategy and transaction in an African factory. Manchester: Manchester University Press. ' igraph/R/flow.R0000644000175100001440000007457013177712334013062 0ustar hornikusers# IGraph R package # Copyright (C) 2006-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Minimum cut in a graph #' #' \code{min_cut} calculates the minimum st-cut between two vertices in a graph #' (if the \code{source} and \code{target} arguments are given) or the minimum #' cut of the graph (if both \code{source} and \code{target} are \code{NULL}). #' #' The minimum st-cut between \code{source} and \code{target} is the minimum #' total weight of edges needed to remove to eliminate all paths from #' \code{source} to \code{target}. #' #' The minimum cut of a graph is the minimum total weight of the edges needed #' to remove to separate the graph into (at least) two components. (Which is to #' make the graph \emph{not} strongly connected in the directed case.) #' #' The maximum flow between two vertices in a graph is the same as the minimum #' st-cut, so \code{max_flow} and \code{min_cut} essentially calculate the same #' quantity, the only difference is that \code{min_cut} can be invoked without #' giving the \code{source} and \code{target} arguments and then minimum of all #' possible minimum cuts is calculated. #' #' For undirected graphs the Stoer-Wagner algorithm (see reference below) is #' used to calculate the minimum cut. #' #' @aliases graph.mincut #' @param graph The input graph. #' @param source The id of the source vertex. #' @param target The id of the target vertex (sometimes also called sink). #' @param capacity Vector giving the capacity of the edges. If this is #' \code{NULL} (the default) then the \code{capacity} edge attribute is used. #' @param value.only Logical scalar, if \code{TRUE} only the minumum cut value #' is returned, if \code{FALSE} the edges in the cut and a the two (or more) #' partitions are also returned. #' @return For \code{min_cut} a numeric constant, the value of the minimum #' cut, except if \code{value.only = FALSE}. In this case a named list with #' components: #' \item{value}{Numeric scalar, the cut value.} #' \item{cut}{Numeric vector, the edges in the cut.} #' \item{partition1}{The vertices in the first partition after the cut #' edges are removed. Note that these vertices might be actually in #' different components (after the cut edges are removed), as the graph #' may fall apart into more than two components.} #' \item{partition2}{The vertices in the second partition #' after the cut edges are removed. Note that these vertices might be #' actually in different components (after the cut edges are removed), as #' the graph may fall apart into more than two components.} #' @seealso \code{\link{max_flow}} for the related maximum flow #' problem, \code{\link{distances}}, \code{\link{edge_connectivity}}, #' \code{\link{vertex_connectivity}} #' @references M. Stoer and F. Wagner: A simple min-cut algorithm, #' \emph{Journal of the ACM}, 44 585-591, 1997. #' @examples #' g <- make_ring(100) #' min_cut(g, capacity=rep(1,vcount(g))) #' min_cut(g, value.only=FALSE, capacity=rep(1,vcount(g))) #' #' g2 <- graph( c(1,2,2,3,3,4, 1,6,6,5,5,4, 4,1) ) #' E(g2)$capacity <- c(3,1,2, 10,1,3, 2) #' min_cut(g2, value.only=FALSE) #' @export #' @include auto.R min_cut <- function(graph, source=NULL, target=NULL, capacity=NULL, value.only=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(capacity)) { if ("capacity" %in% edge_attr_names(graph)) { capacity <- E(graph)$capacity } } if (is.null(source) && !is.null(target) || is.null(target) && !is.null(source)) { stop("Please give both source and target or neither") } if (!is.null(capacity)) { capacity <- as.numeric(capacity) } value.only <- as.logical(value.only) on.exit( .Call(C_R_igraph_finalizer) ) if (is.null(target) && is.null(source)) { if (value.only) { res <- .Call(C_R_igraph_mincut_value, graph, capacity) } else { res <- .Call(C_R_igraph_mincut, graph, capacity) res$cut <- res$cut + 1 res$partition1 <- res$partition1 + 1 res$partition2 <- res$partition2 + 1 if (igraph_opt("return.vs.es")) { res$cut <- create_es(graph, res$cut) res$partition1 <- create_vs(graph, res$partition1) res$partition2 <- create_vs(graph, res$partition2) } res } } else { if (value.only) { res <- .Call(C_R_igraph_st_mincut_value, graph, as.igraph.vs(graph, source)-1, as.igraph.vs(graph, target)-1, capacity) } else { stop("Calculating minimum s-t cuts is not implemented yet") } } res } #' Vertex connectivity. #' #' The vertex connectivity of a graph or two vertices, this is recently also #' called group cohesion. #' #' The vertex connectivity of two vertices (\code{source} and \code{target}) in #' a directed graph is the minimum number of vertices needed to remove from the #' graph to eliminate all (directed) paths from \code{source} to \code{target}. #' \code{vertex_connectivity} calculates this quantity if both the #' \code{source} and \code{target} arguments are given and they're not #' \code{NULL}. #' #' The vertex connectivity of a graph is the minimum vertex connectivity of all #' (ordered) pairs of vertices in the graph. In other words this is the minimum #' number of vertices needed to remove to make the graph not strongly #' connected. (If the graph is not strongly connected then this is zero.) #' \code{vertex_connectivity} calculates this quantitty if neither the #' \code{source} nor \code{target} arguments are given. (Ie. they are both #' \code{NULL}.) #' #' A set of vertex disjoint directed paths from \code{source} to \code{vertex} #' is a set of directed paths between them whose vertices do not contain common #' vertices (apart from \code{source} and \code{target}). The maximum number of #' vertex disjoint paths between two vertices is the same as their vertex #' connectivity in most cases (if the two vertices are not connected by an #' edge). #' #' The cohesion of a graph (as defined by White and Harary, see references), is #' the vertex connectivity of the graph. This is calculated by #' \code{cohesion}. #' #' These three functions essentially calculate the same measure(s), more #' precisely \code{vertex_connectivity} is the most general, the other two are #' included only for the ease of using more descriptive function names. #' #' @aliases vertex.connectivity vertex.disjoint.paths cohesion vertex_connectivity #' vertex_disjoint_paths graph.cohesion #' @param graph,x The input graph. #' @param source The id of the source vertex, for \code{vertex_connectivity} it #' can be \code{NULL}, see details below. #' @param target The id of the target vertex, for \code{vertex_connectivity} it #' can be \code{NULL}, see details below. #' @param checks Logical constant. Whether to check that the graph is connected #' and also the degree of the vertices. If the graph is not (strongly) #' connected then the connectivity is obviously zero. Otherwise if the minimum #' degree is one then the vertex connectivity is also one. It is a good idea to #' perform these checks, as they can be done quickly compared to the #' connectivity calculation itself. They were suggested by Peter McMahan, #' thanks Peter. #' @param ... Ignored. #' @return A scalar real value. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{max_flow}}, \code{\link{edge_connectivity}}, #' \code{\link{edge_disjoint_paths}}, \code{\link{adhesion}} #' @references White, Douglas R and Frank Harary 2001. The Cohesiveness of #' Blocks In Social Networks: Node Connectivity and Conditional Density. #' \emph{Sociological Methodology} 31 (1) : 305-359. #' @export #' @keywords graphs #' @examples #' #' g <- barabasi.game(100, m=1) #' g <- delete_edges(g, E(g)[ 100 %--% 1 ]) #' g2 <- barabasi.game(100, m=5) #' g2 <- delete_edges(g2, E(g2)[ 100 %--% 1]) #' vertex_connectivity(g, 100, 1) #' vertex_connectivity(g2, 100, 1) #' vertex_disjoint_paths(g2, 100, 1) #' #' g <- sample_gnp(50, 5/50) #' g <- as.directed(g) #' g <- induced_subgraph(g, subcomponent(g, 1)) #' cohesion(g) #' vertex_connectivity <- function(graph, source=NULL, target=NULL, checks=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(source) && is.null(target)) { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_vertex_connectivity, graph, as.logical(checks)) } else if (!is.null(source) && !is.null(target)) { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_st_vertex_connectivity, graph, as.igraph.vs(graph, source)-1, as.igraph.vs(graph, target)-1) } else { stop("either give both source and target or neither") } } #' Edge connectivity. #' #' The edge connectivity of a graph or two vertices, this is recently also #' called group adhesion. #' #' The edge connectivity of a pair of vertices (\code{source} and #' \code{target}) is the minimum number of edges needed to remove to eliminate #' all (directed) paths from \code{source} to \code{target}. #' \code{edge_connectivity} calculates this quantity if both the \code{source} #' and \code{target} arguments are given (and not \code{NULL}). #' #' The edge connectivity of a graph is the minimum of the edge connectivity of #' every (ordered) pair of vertices in the graph. \code{edge_connectivity} #' calculates this quantity if neither the \code{source} nor the \code{target} #' arguments are given (ie. they are both \code{NULL}). #' #' A set of edge disjoint paths between two vertices is a set of paths between #' them containing no common edges. The maximum number of edge disjoint paths #' between two vertices is the same as their edge connectivity. #' #' The adhesion of a graph is the minimum number of edges needed to remove to #' obtain a graph which is not strongly connected. This is the same as the edge #' connectivity of the graph. #' #' The three functions documented on this page calculate similar properties, #' more precisely the most general is \code{edge_connectivity}, the others are #' included only for having more descriptive function names. #' #' @aliases edge.connectivity edge_disjoint_paths graph.adhesion adhesion #' edge_connectivity edge.disjoint.paths #' @param graph The input graph. #' @param source The id of the source vertex, for \code{edge_connectivity} it #' can be \code{NULL}, see details below. #' @param target The id of the target vertex, for \code{edge_connectivity} it #' can be \code{NULL}, see details below. #' @param checks Logical constant. Whether to check that the graph is connected #' and also the degree of the vertices. If the graph is not (strongly) #' connected then the connectivity is obviously zero. Otherwise if the minimum #' degree is one then the edge connectivity is also one. It is a good idea to #' perform these checks, as they can be done quickly compared to the #' connectivity calculation itself. They were suggested by Peter McMahan, #' thanks Peter. #' @return A scalar real value. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{max_flow}}, \code{\link{vertex_connectivity}}, #' \code{\link{vertex_disjoint_paths}}, \code{\link{cohesion}} #' @references Douglas R. White and Frank Harary: The cohesiveness of blocks in #' social networks: node connectivity and conditional density, TODO: citation #' @export #' @keywords graphs #' @examples #' #' g <- barabasi.game(100, m=1) #' g2 <- barabasi.game(100, m=5) #' edge_connectivity(g, 100, 1) #' edge_connectivity(g2, 100, 1) #' edge_disjoint_paths(g2, 100, 1) #' #' g <- sample_gnp(50, 5/50) #' g <- as.directed(g) #' g <- induced_subgraph(g, subcomponent(g, 1)) #' adhesion(g) #' edge_connectivity <- function(graph, source=NULL, target=NULL, checks=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(source) && is.null(target)) { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_edge_connectivity, graph, as.logical(checks)) } else if (!is.null(source) && !is.null(target)) { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_st_edge_connectivity, graph, as.igraph.vs(graph, source)-1, as.igraph.vs(graph, target)-1) } else { stop("either give both source and target or neither") } } #' @export edge_disjoint_paths <- function(graph, source, target) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_edge_disjoint_paths, graph, as.igraph.vs(graph, source)-1, as.igraph.vs(graph, target)-1) } #' @export vertex_disjoint_paths <- function(graph, source=NULL, target=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_vertex_disjoint_paths, graph, as.igraph.vs(graph, source)-1, as.igraph.vs(graph, target)-1) } #' @export adhesion <- function(graph, checks=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_adhesion, graph, as.logical(checks)) } #' @rdname vertex_connectivity #' @method cohesion igraph #' @export cohesion.igraph <- function(x, checks=TRUE, ...) { if (!is_igraph(x)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_cohesion, x, as.logical(checks)) } #' List all (s,t)-cuts of a graph #' #' List all (s,t)-cuts in a directed graph. #' #' Given a \eqn{G} directed graph and two, different and non-ajacent vertices, #' \eqn{s} and \eqn{t}, an \eqn{(s,t)}-cut is a set of edges, such that after #' removing these edges from \eqn{G} there is no directed path from \eqn{s} to #' \eqn{t}. #' #' @aliases stCuts st_cuts #' @param graph The input graph. It must be directed. #' @param source The source vertex. #' @param target The target vertex. #' @return A list with entries: \item{cuts}{A list of numeric vectors #' containing edge ids. Each vector is an \eqn{(s,t)}-cut.} #' \item{partition1s}{A list of numeric vectors containing vertex ids, they #' correspond to the edge cuts. Each vertex set is a generator of the #' corresponding cut, i.e. in the graph \eqn{G=(V,E)}, the vertex set \eqn{X} #' and its complementer \eqn{V-X}, generates the cut that contains exactly the #' edges that go from \eqn{X} to \eqn{V-X}.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{st_min_cuts}} to list all minimum cuts. #' @references JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in #' graphs, \emph{Algorithmica} 15, 351--372, 1996. #' @keywords graphs #' @examples #' #' # A very simple graph #' g <- graph_from_literal(a -+ b -+ c -+ d -+ e) #' st_cuts(g, source="a", target="e") #' #' # A somewhat more difficult graph #' g2 <- graph_from_literal(s --+ a:b, a:b --+ t, #' a --+ 1:2:3, 1:2:3 --+ b) #' st_cuts(g2, source="s", target="t") #' @export #' @include auto.R st_cuts <- st_cuts #' List all minimum \eqn{(s,t)}-cuts of a graph #' #' Listing all minimum \eqn{(s,t)}-cuts of a directed graph, for given \eqn{s} #' and \eqn{t}. #' #' Given a \eqn{G} directed graph and two, different and non-ajacent vertices, #' \eqn{s} and \eqn{t}, an \eqn{(s,t)}-cut is a set of edges, such that after #' removing these edges from \eqn{G} there is no directed path from \eqn{s} to #' \eqn{t}. #' #' The size of an \eqn{(s,t)}-cut is defined as the sum of the capacities (or #' weights) in the cut. For unweighed (=equally weighted) graphs, this is #' simply the number of edges. #' #' An \eqn{(s,t)}-cut is minimum if it is of the smallest possible size. #' #' @aliases st_min_cuts stMincuts #' @param graph The input graph. It must be directed. #' @param source The id of the source vertex. #' @param target The id of the target vertex. #' @param capacity Numeric vector giving the edge capacities. If this is #' \code{NULL} and the graph has a \code{weight} edge attribute, then this #' attribute defines the edge capacities. For forcing unit edge capacities, #' even for graphs that have a \code{weight} edge attribute, supply \code{NA} #' here. #' @return A list with entries: \item{value}{Numeric scalar, the size of the #' minimum cut(s).} \item{cuts}{A list of numeric vectors containing edge ids. #' Each vector is a minimum \eqn{(s,t)}-cut.} \item{partition1s}{A list of #' numeric vectors containing vertex ids, they correspond to the edge cuts. #' Each vertex set is a generator of the corresponding cut, i.e. in the graph #' \eqn{G=(V,E)}, the vertex set \eqn{X} and its complementer \eqn{V-X}, #' generates the cut that contains exactly the edges that go from \eqn{X} to #' \eqn{V-X}.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{st_cuts}}, \code{\link{min_separators}} #' @references JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in #' graphs, \emph{Algorithmica} 15, 351--372, 1996. #' @keywords graphs #' @examples #' #' # A difficult graph, from the Provan-Shier paper #' g <- graph_from_literal(s --+ a:b, a:b --+ t, #' a --+ 1:2:3:4:5, 1:2:3:4:5 --+ b) #' st_min_cuts(g, source="s", target="t") #' @export #' @include auto.R st_min_cuts <- st_min_cuts #' Dominator tree #' #' Dominator tree of a directed graph. #' #' A flowgraph is a directed graph with a distinguished start (or root) vertex #' \eqn{r}, such that for any vertex \eqn{v}, there is a path from \eqn{r} to #' \eqn{v}. A vertex \eqn{v} dominates another vertex \eqn{w} (not equal to #' \eqn{v}), if every path from \eqn{r} to \eqn{w} contains \eqn{v}. Vertex #' \eqn{v} is the immediate dominator or \eqn{w}, #' \eqn{v=\textrm{idom}(w)}{v=idom(w)}, if \eqn{v} dominates \eqn{w} and every #' other dominator of \eqn{w} dominates \eqn{v}. The edges #' \eqn{{(\textrm{idom}(w), w)| w \ne r}}{{(idom(w),w)| w is not r}} form a #' directed tree, rooted at \eqn{r}, called the dominator tree of the graph. #' Vertex \eqn{v} dominates vertex \eqn{w} if and only if \eqn{v} is an #' ancestor of \eqn{w} in the dominator tree. #' #' This function implements the Lengauer-Tarjan algorithm to construct the #' dominator tree of a directed graph. For details see the reference below. #' #' @aliases dominator.tree dominator_tree #' @param graph A directed graph. If it is not a flowgraph, and it contains #' some vertices not reachable from the root vertex, then these vertices will #' be collected and returned as part of the result. #' @param root The id of the root (or source) vertex, this will be the root of #' the tree. #' @param mode Constant, must be \sQuote{\code{in}} or \sQuote{\code{out}}. If #' it is \sQuote{\code{in}}, then all directions are considered as opposite to #' the original one in the input graph. #' @return A list with components: \item{dom}{ A numeric vector giving the #' immediate dominators for each vertex. For vertices that are unreachable from #' the root, it contains \code{NaN}. For the root vertex itself it contains #' minus one. } \item{domtree}{ A graph object, the dominator tree. Its vertex #' ids are the as the vertex ids of the input graph. Isolate vertices are the #' ones that are unreachable from the root. } \item{leftout}{ A numeric vector #' containing the vertex ids that are unreachable from the root. } #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Thomas Lengauer, Robert Endre Tarjan: A fast algorithm for #' finding dominators in a flowgraph, \emph{ACM Transactions on Programming #' Languages and Systems (TOPLAS)} I/1, 121--141, 1979. #' @keywords graphs #' @examples #' #' ## The example from the paper #' g <- graph_from_literal(R-+A:B:C, A-+D, B-+A:D:E, C-+F:G, D-+L, #' E-+H, F-+I, G-+I:J, H-+E:K, I-+K, J-+I, #' K-+I:R, L-+H) #' dtree <- dominator_tree(g, root="R") #' layout <- layout_as_tree(dtree$domtree, root="R") #' layout[,2] <- -layout[,2] #' plot(dtree$domtree, layout=layout, vertex.label=V(dtree$domtree)$name) #' @export dominator_tree <- dominator_tree #' Minimum size vertex separators #' #' List all vertex sets that are minimal (s,t) separators for some s and t, in #' an undirected graph. #' #' A \eqn{(s,t)} vertex separator is a set of vertices, such that after their #' removal from the graph, there is no path between \eqn{s} and \eqn{t} in the #' graph. #' #' A \eqn{(s,t)} vertex separator is minimal if none of its subsets is an #' \eqn{(s,t)} vertex separator. #' #' @aliases minimal.st.separators min_st_separators #' @param graph The input graph. It may be directed, but edge directions are #' ignored. #' @return A list of numeric vectors. Each vector contains a vertex set #' (defined by vertex ids), each vector is an (s,t) separator of the input #' graph, for some \eqn{s} and \eqn{t}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating All #' the Minimal Separators of a Graph, In: Peter Widmayer, Gabriele Neyer and #' Stephan Eidenbenz (editors): \emph{Graph-theoretic concepts in computer #' science}, 1665, 167--172, 1999. Springer. #' @keywords graphs #' @examples #' #' ring <- make_ring(4) #' min_st_separators(ring) #' #' chvatal <- make_graph("chvatal") #' min_st_separators(chvatal) min_st_separators <- min_st_separators #' Maximum flow in a graph #' #' In a graph where each edge has a given flow capacity the maximal flow #' between two vertices is calculated. #' #' \code{max_flow} calculates the maximum flow between two vertices in a #' weighted (ie. valued) graph. A flow from \code{source} to \code{target} is #' an assignment of non-negative real numbers to the edges of the graph, #' satisfying two properties: (1) for each edge the flow (ie. the assigned #' number) is not more than the capacity of the edge (the \code{capacity} #' parameter or edge attribute), (2) for every vertex, except the source and #' the target the incoming flow is the same as the outgoing flow. The value of #' the flow is the incoming flow of the \code{target} vertex. The maximum flow #' is the flow of maximum value. #' #' @aliases graph.maxflow #' @param graph The input graph. #' @param source The id of the source vertex. #' @param target The id of the target vertex (sometimes also called sink). #' @param capacity Vector giving the capacity of the edges. If this is #' \code{NULL} (the default) then the \code{capacity} edge attribute is used. #' Note that the \code{weight} edge attribute is not used by this function. #' @return A named list with components: #' \item{value}{A numeric scalar, the value of the maximum flow.} #' \item{flow}{A numeric vector, the flow itself, one entry for each #' edge. For undirected graphs this entry is bit trickier, since for #' these the flow direction is not predetermined by the edge #' direction. For these graphs the elements of the this vector can be #' negative, this means that the flow goes from the bigger vertex id to #' the smaller one. Positive values mean that the flow goes from #' the smaller vertex id to the bigger one.} #' \item{cut}{A numeric vector of edge ids, the minimum cut corresponding #' to the maximum flow.} #' \item{partition1}{A numeric vector of vertex ids, the vertices in the #' first partition of the minimum cut corresponding to the maximum #' flow.} #' \item{partition2}{A numeric vector of vertex ids, the vertices in the #' second partition of the minimum cut corresponding to the maximum #' flow.} #' \item{stats}{A list with some statistics from the push-relabel #' algorithm. Five integer values currently: \code{nopush} is the #' number of push operations, \code{norelabel} the number of #' relabelings, \code{nogap} is the number of times the gap heuristics #' was used, \code{nogapnodes} is the total number of gap nodes omitted #' because of the gap heuristics and \code{nobfs} is the number of #' times a global breadth-first-search update was performed to assign #' better height (=distance) values to the vertices.} #' @seealso \code{\link{min_cut}} for minimum cut calculations, #' \code{\link{distances}}, \code{\link{edge_connectivity}}, #' \code{\link{vertex_connectivity}} #' @references A. V. Goldberg and R. E. Tarjan: A New Approach to the Maximum #' Flow Problem \emph{Journal of the ACM} 35:921-940, 1988. #' @examples #' #' E <- rbind( c(1,3,3), c(3,4,1), c(4,2,2), c(1,5,1), c(5,6,2), c(6,2,10)) #' colnames(E) <- c("from", "to", "capacity") #' g1 <- graph_from_data_frame(as.data.frame(E)) #' max_flow(g1, source=V(g1)["1"], target=V(g1)["2"]) #' @export #' @include auto.R max_flow <- max_flow #' Vertex separators #' #' Check whether a given set of vertices is a vertex separator. #' #' \code{is_separator} decides whether the supplied vertex set is a vertex #' separator. A vertex set is a vertex separator if its removal results a #' disconnected graph. #' #' In the special case of a fully connected graph with \eqn{n} vertices, each #' set of \eqn{n-1} vertices is considered to be a vertex separator. #' #' @aliases is.separator #' @param graph The input graph. It may be directed, but edge directions are #' ignored. #' @param candidate A numeric vector giving the vertex ids of the candidate #' separator. #' @return A logical scalar, whether the supplied vertex set is a (minimal) #' vertex separator or not. #' @seealso \code{\link{is_min_separator}}, \code{\link{min_separators}} #' lists all vertex separator of minimum size. #' @export is_separator <- is_separator #' Minumal vertex separators #' #' Check whether a given set of vertices is a minimal vertex separator. #' #' \code{is_min_separator} decides whether the supplied vertex set is a minimal #' vertex separator. A minimal vertex separator is a vertex separator, such #' that none of its subsets is a vertex separator. #' #' In the special case of a fully connected graph with \eqn{n} vertices, each #' set of \eqn{n-1} vertices is considered to be a vertex separator. #' #' @aliases is.minimal.separator #' @param graph The input graph. It may be directed, but edge directions are #' ignored. #' @param candidate A numeric vector giving the vertex ids of the candidate #' separator. #' @return A logical scalar, whether the supplied vertex set is a (minimal) #' vertex separator or not. #' @seealso \code{\link{min_separators}} lists all vertex separator of minimum #' size. #' @examples #' # The graph from the Moody-White paper #' mw <- graph_from_literal(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, #' 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, #' 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, #' 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, #' 21-22:23, 22-23) #' #' # Cohesive subgraphs #' mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) #' mw2 <- induced_subgraph(mw, as.character(7:16)) #' mw3 <- induced_subgraph(mw, as.character(17:23)) #' mw4 <- induced_subgraph(mw, as.character(c(7,8,11,14))) #' mw5 <- induced_subgraph(mw, as.character(1:7)) #' #' check.sep <- function(G) { #' sep <- min_separators(G) #' sapply(sep, is_min_separator, graph=G) #' } #' #' check.sep(mw) #' check.sep(mw1) #' check.sep(mw2) #' check.sep(mw3) #' check.sep(mw4) #' check.sep(mw5) #' #' @export is_min_separator <- is_min_separator #' Minimum size vertex separators #' #' Find all vertex sets of minimal size whose removal separates the graph into #' more components #' #' This function implements the Kanevsky algorithm for finding all minimal-size #' vertex separators in an undirected graph. See the reference below for the #' details. #' #' In the special case of a fully connected input graph with \eqn{n} vertices, #' all subsets of size \eqn{n-1} are listed as the result. #' #' @aliases minimum.size.separators #' @param graph The input graph. It may be directed, but edge directions are #' ignored. #' @return A list of numeric vectors. Each numeric vector is a vertex #' separator. #' @seealso \code{\link{is.separator}} #' @references Arkady Kanevsky: Finding all minimum-size separating vertex sets #' in a graph. \emph{Networks} 23 533--541, 1993. #' #' JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, #' \emph{Algorithmica} 15, 351--372, 1996. #' #' J. Moody and D. R. White. Structural cohesion and embeddedness: A #' hierarchical concept of social groups. \emph{American Sociological Review}, #' 68 103--127, Feb 2003. #' @export #' @examples #' # The graph from the Moody-White paper #' mw <- graph.formula(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, #' 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, #' 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, #' 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, #' 21-22:23, 22-23) #' #' # Cohesive subgraphs #' mw1 <- induced.subgraph(mw, as.character(c(1:7, 17:23))) #' mw2 <- induced.subgraph(mw, as.character(7:16)) #' mw3 <- induced.subgraph(mw, as.character(17:23)) #' mw4 <- induced.subgraph(mw, as.character(c(7,8,11,14))) #' mw5 <- induced.subgraph(mw, as.character(1:7)) #' #' min_separators(mw) #' min_separators(mw1) #' min_separators(mw2) #' min_separators(mw3) #' min_separators(mw4) #' min_separators(mw5) #' #' # Another example, the science camp network #' camp <- graph.formula(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, #' Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, #' Holly - Carol:Pat:Pam:Jennie:Bill, #' Bill - Pauline:Michael:Lee:Holly, #' Pauline - Bill:Jennie:Ann, #' Jennie - Holly:Michael:Lee:Ann:Pauline, #' Michael - Bill:Jennie:Ann:Lee:John, #' Ann - Michael:Jennie:Pauline, #' Lee - Michael:Bill:Jennie, #' Gery - Pat:Steve:Russ:John, #' Russ - Steve:Bert:Gery:John, #' John - Gery:Russ:Michael) #' min_separators(camp) min_separators <- min_separators igraph/R/weakref.R0000644000175100001440000000256713177712334013534 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- make_weak_ref <- function(key, value, finalizer = NULL) { .Call(C_R_igraph_make_weak_ref, key, value, finalizer) } weak_ref_key <- function(ref) { .Call(C_R_igraph_weak_ref_key, ref) } weak_ref_value <- function(ref) { .Call(C_R_igraph_weak_ref_value, ref) } weak_ref_run_finalizer <- function(ref) { .Call(C_R_igraph_weak_ref_run_finalizer, ref) } igraph/R/auto.R0000644000175100001440000013612713430770211013046 0ustar hornikusers#' @export gorder <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_vcount, graph) res } #' @export graph_from_lcf <- function(n, shifts, repeats=1) { # Argument checks n <- as.integer(n) shifts <- as.numeric(shifts) repeats <- as.integer(repeats) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_lcf_vector, n, shifts, repeats) res <- set.graph.attribute(res, 'name', 'LCF graph') res } #' @export graph_from_adj_list <- function(adjlist, mode=c("out", "in", "all", "total"), duplicate=TRUE) { # Argument checks adjlist <- lapply(adjlist, function(x) as.integer(x)-1L) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) duplicate <- as.logical(duplicate) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_adjlist, adjlist, mode, duplicate) res } #' @export sample_forestfire <- function(nodes, fw.prob, bw.factor=1, ambs=1, directed=TRUE) { # Argument checks nodes <- as.integer(nodes) fw.prob <- as.numeric(fw.prob) bw.factor <- as.numeric(bw.factor) ambs <- as.integer(ambs) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_forest_fire_game, nodes, fw.prob, bw.factor, ambs, directed) res <- set.graph.attribute(res, 'name', 'Forest fire model') res <- set.graph.attribute(res, 'fw.prob', fw.prob) res <- set.graph.attribute(res, 'bw.factor', bw.factor) res <- set.graph.attribute(res, 'ambs', ambs) res } #' @export sample_islands <- function(islands.n, islands.size, islands.pin, n.inter) { # Argument checks islands.n <- as.integer(islands.n) islands.size <- as.integer(islands.size) islands.pin <- as.numeric(islands.pin) n.inter <- as.integer(n.inter) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_simple_interconnected_islands_game, islands.n, islands.size, islands.pin, n.inter) res <- set.graph.attribute(res, 'name', 'Interconnected islands model') res <- set.graph.attribute(res, 'islands.n', islands.n) res <- set.graph.attribute(res, 'islands.size', islands.size) res <- set.graph.attribute(res, 'islands.pin', islands.pin) res <- set.graph.attribute(res, 'n.inter', n.inter) res } #' @export sample_fitness <- function(no.of.edges, fitness.out, fitness.in=NULL, loops=FALSE, multiple=FALSE) { # Argument checks no.of.edges <- as.integer(no.of.edges) fitness.out <- as.numeric(fitness.out) if (!is.null(fitness.in)) fitness.in <- as.numeric(fitness.in) loops <- as.logical(loops) multiple <- as.logical(multiple) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_static_fitness_game, no.of.edges, fitness.out, fitness.in, loops, multiple) res <- set.graph.attribute(res, 'name', 'Static fitness model') res <- set.graph.attribute(res, 'loops', loops) res <- set.graph.attribute(res, 'multiple', multiple) res } #' @export sample_fitness_pl <- function(no.of.nodes, no.of.edges, exponent.out, exponent.in=-1, loops=FALSE, multiple=FALSE, finite.size.correction=TRUE) { # Argument checks no.of.nodes <- as.integer(no.of.nodes) no.of.edges <- as.integer(no.of.edges) exponent.out <- as.numeric(exponent.out) exponent.in <- as.numeric(exponent.in) loops <- as.logical(loops) multiple <- as.logical(multiple) finite.size.correction <- as.logical(finite.size.correction) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_static_power_law_game, no.of.nodes, no.of.edges, exponent.out, exponent.in, loops, multiple, finite.size.correction) res <- set.graph.attribute(res, 'name', 'Static power law model') res <- set.graph.attribute(res, 'exponent.out', exponent.out) res <- set.graph.attribute(res, 'exponent.in', exponent.in) res <- set.graph.attribute(res, 'loops', loops) res <- set.graph.attribute(res, 'multiple', multiple) res <- set.graph.attribute(res, 'finite.size.correction', finite.size.correction) res } #' @export sample_k_regular <- function(no.of.nodes, k, directed=FALSE, multiple=FALSE) { # Argument checks no.of.nodes <- as.integer(no.of.nodes) k <- as.integer(k) directed <- as.logical(directed) multiple <- as.logical(multiple) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_k_regular_game, no.of.nodes, k, directed, multiple) res <- set.graph.attribute(res, 'name', 'k-regular graph') res <- set.graph.attribute(res, 'k', k) res } #' @export sample_sbm <- function(n, pref.matrix, block.sizes, directed=FALSE, loops=FALSE) { # Argument checks n <- as.integer(n) pref.matrix <- as.matrix(structure(as.double(pref.matrix), dim=dim(pref.matrix))) block.sizes <- as.integer(block.sizes) directed <- as.logical(directed) loops <- as.logical(loops) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sbm_game, n, pref.matrix, block.sizes, directed, loops) res <- set.graph.attribute(res, 'name', 'Stochastic block-model') res <- set.graph.attribute(res, 'loops', loops) res } hsbm.1.game <- function(n, m, rho, C, p) { # Argument checks n <- as.integer(n) m <- as.integer(m) rho <- as.numeric(rho) C <- as.matrix(structure(as.double(C), dim=dim(C))) p <- as.numeric(p) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hsbm_game, n, m, rho, C, p) res <- set.graph.attribute(res, 'name', 'Hierarchical stochastic block model') res <- set.graph.attribute(res, 'm', m) res <- set.graph.attribute(res, 'rho', rho) res <- set.graph.attribute(res, 'C', C) res <- set.graph.attribute(res, 'p', p) res } hsbm.list.game <- function(n, mlist, rholist, Clist, p) { # Argument checks n <- as.integer(n) mlist <- as.integer(mlist) if (!all(sapply(Clist, is.matrix))) { stop("%I is not a list of matrices") } p <- as.numeric(p) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hsbm_list_game, n, mlist, rholist, Clist, p) res <- set.graph.attribute(res, 'name', 'Hierarchical stochastic block model') res <- set.graph.attribute(res, 'p', p) res } #' @export sample_correlated_gnp <- function(old.graph, corr, p=old.graph$p, permutation=NULL) { # Argument checks if (!is_igraph(old.graph)) { stop("Not a graph object") } corr <- as.numeric(corr) p <- as.numeric(p) if (!is.null(permutation)) permutation <- as.numeric(permutation)-1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_correlated_game, old.graph, corr, p, permutation) res <- set.graph.attribute(res, 'name', 'Correlated random graph') res <- set.graph.attribute(res, 'corr', corr) res <- set.graph.attribute(res, 'p', p) res } #' @export sample_correlated_gnp_pair <- function(n, corr, p, directed=FALSE, permutation=NULL) { # Argument checks n <- as.integer(n) corr <- as.numeric(corr) p <- as.numeric(p) directed <- as.logical(directed) if (!is.null(permutation)) permutation <- as.numeric(permutation)-1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_correlated_pair_game, n, corr, p, directed, permutation) res } #' @export sample_dot_product <- function(vecs, directed=FALSE) { # Argument checks vecs <- as.matrix(structure(as.double(vecs), dim=dim(vecs))) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_dot_product_game, vecs, directed) res } #' @export sample_sphere_surface <- function(dim, n=1, radius=1, positive=TRUE) { # Argument checks dim <- as.integer(dim) n <- as.integer(n) radius <- as.numeric(radius) positive <- as.logical(positive) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_sphere_surface, dim, n, radius, positive) res } #' @export sample_sphere_volume <- function(dim, n=1, radius=1, positive=TRUE) { # Argument checks dim <- as.integer(dim) n <- as.integer(n) radius <- as.numeric(radius) positive <- as.logical(positive) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_sphere_volume, dim, n, radius, positive) res } #' @export sample_dirichlet <- function(n, alpha) { # Argument checks n <- as.integer(n) alpha <- as.numeric(alpha) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_dirichlet, n, alpha) res } #' @export page_rank_old <- function(graph, vids=V(graph), directed=TRUE, niter=1000, eps=0.001, damping=0.85, old=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) directed <- as.logical(directed) niter <- as.integer(niter) eps <- as.numeric(eps) damping <- as.numeric(damping) old <- as.logical(old) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_pagerank_old, graph, vids-1, directed, niter, eps, damping, old) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' @export page_rank <- function(graph, algo=c("prpack", "arpack", "power"), vids=V(graph), directed=TRUE, damping=0.85, personalized=NULL, weights=NULL, options=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } algo <- switch(igraph.match.arg(algo), "power"=0L, "arpack"=1L, "prpack"=2L) vids <- as.igraph.vs(graph, vids) directed <- as.logical(directed) damping <- as.numeric(damping) if (!is.null(personalized)) personalized <- as.numeric(personalized) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } if (is.null(options)) { if (algo == 0L) { options <- list(niter=1000, eps=0.001) } else if (algo == 1L) { options <- arpack_defaults } else { options <- NULL } } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_personalized_pagerank, graph, algo, vids-1, directed, damping, personalized, weights, options) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$vector) <- vertex_attr(graph, "name", vids) } res } #' @export distance_table <- function(graph, directed=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_path_length_hist, graph, directed) res } #' @export simplify <- function(graph, remove.multiple=TRUE, remove.loops=TRUE, edge.attr.comb=igraph_opt("edge.attr.comb")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } remove.multiple <- as.logical(remove.multiple) remove.loops <- as.logical(remove.loops) edge.attr.comb <- igraph.i.attribute.combination(edge.attr.comb) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_simplify, graph, remove.multiple, remove.loops, edge.attr.comb) res } #' @export is_dag <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_dag, graph) res } #' @export is_simple <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_simple, graph) res } #' @export any_multiple <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_has_multiple, graph) res } #' @export eigen_centrality <- function(graph, directed=FALSE, scale=TRUE, weights=NULL, options=arpack_defaults) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } directed <- as.logical(directed) scale <- as.logical(scale) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_eigenvector_centrality, graph, directed, scale, weights, options) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$vector) <- vertex_attr(graph, "name", ) } res } #' @export hub_score <- function(graph, scale=TRUE, weights=NULL, options=arpack_defaults) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } scale <- as.logical(scale) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hub_score, graph, scale, weights, options) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$vector) <- vertex_attr(graph, "name", ) } res } #' @export authority_score <- function(graph, scale=TRUE, weights=NULL, options=arpack_defaults) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } scale <- as.logical(scale) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_authority_score, graph, scale, weights, options) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$vector) <- vertex_attr(graph, "name", ) } res } #' @export which_mutual <- function(graph, es=E(graph)) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } es <- as.igraph.es(graph, es) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_mutual, graph, es-1) res } #' @export max_cardinality <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_maximum_cardinality_search, graph) if (igraph_opt("return.vs.es")) { res$alpha <- create_vs(graph, res$alpha) } res } #' @export knn <- function(graph, vids=V(graph), weights=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_avg_nearest_neighbor_degree, graph, vids-1, weights) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$knn) <- vertex_attr(graph, "name", vids) } res } #' @export strength <- function(graph, vids=V(graph), mode=c("all", "out", "in", "total"), loops=TRUE, weights=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) loops <- as.logical(loops) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_strength, graph, vids-1, mode, loops, weights) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' @export centralize <- function(scores, theoretical.max=0, normalized=TRUE) { # Argument checks scores <- as.numeric(scores) theoretical.max <- as.numeric(theoretical.max) normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization, scores, theoretical.max, normalized) res } #' @export centr_degree <- function(graph, mode=c("all", "out", "in", "total"), loops=TRUE, normalized=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) loops <- as.logical(loops) normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_degree, graph, mode, loops, normalized) res } #' @export centr_degree_tmax <- function(graph=NULL, nodes=0, mode=c("all", "out", "in", "total"), loops=FALSE) { # Argument checks if (!is.null(graph) && !is_igraph(graph)) { stop("Not a graph object") } nodes <- as.integer(nodes) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) loops <- as.logical(loops) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_degree_tmax, graph, nodes, mode, loops) res } #' @export centr_betw <- function(graph, directed=TRUE, nobigint=TRUE, normalized=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } directed <- as.logical(directed) nobigint <- as.logical(nobigint) normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_betweenness, graph, directed, nobigint, normalized) res } #' @export centr_betw_tmax <- function(graph=NULL, nodes=0, directed=TRUE) { # Argument checks if (!is.null(graph) && !is_igraph(graph)) { stop("Not a graph object") } nodes <- as.integer(nodes) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_betweenness_tmax, graph, nodes, directed) res } #' @export centr_clo <- function(graph, mode=c("out", "in", "all", "total"), normalized=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_closeness, graph, mode, normalized) res } #' @export centr_clo_tmax <- function(graph=NULL, nodes=0, mode=c("out", "in", "all", "total")) { # Argument checks if (!is.null(graph) && !is_igraph(graph)) { stop("Not a graph object") } nodes <- as.integer(nodes) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_closeness_tmax, graph, nodes, mode) res } #' @export centr_eigen <- function(graph, directed=FALSE, scale=TRUE, options=arpack_defaults, normalized=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } directed <- as.logical(directed) scale <- as.logical(scale) options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_eigenvector_centrality, graph, directed, scale, options, normalized) res } #' @export centr_eigen_tmax <- function(graph=NULL, nodes=0, directed=FALSE, scale=TRUE) { # Argument checks if (!is.null(graph) && !is_igraph(graph)) { stop("Not a graph object") } nodes <- as.integer(nodes) directed <- as.logical(directed) scale <- as.logical(scale) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_centralization_eigenvector_centrality_tmax, graph, nodes, directed, scale) res } #' @export assortativity_nominal <- function(graph, types, directed=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } types <- as.numeric(types)-1 directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_assortativity_nominal, graph, types, directed) res } #' @export assortativity <- function(graph, types1, types2=NULL, directed=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } types1 <- as.numeric(types1) if (!is.null(types2)) types2 <- as.numeric(types2) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_assortativity, graph, types1, types2, directed) res } #' @export assortativity_degree <- function(graph, directed=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_assortativity_degree, graph, directed) res } #' @export contract <- function(graph, mapping, vertex.attr.comb=igraph_opt("vertex.attr.comb")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mapping <- as.numeric(mapping)-1 vertex.attr.comb <- igraph.i.attribute.combination(vertex.attr.comb) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_contract_vertices, graph, mapping, vertex.attr.comb) res } #' @export eccentricity <- function(graph, vids=V(graph), mode=c("all", "out", "in", "total")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_eccentricity, graph, vids-1, mode) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' @export radius <- function(graph, mode=c("all", "out", "in", "total")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_radius, graph, mode) res } #' @export diversity <- function(graph, weights=NULL, vids=V(graph)) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } vids <- as.igraph.vs(graph, vids) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_diversity, graph, weights, vids-1) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' @export is_degseq <- function(out.deg, in.deg=NULL) { # Argument checks out.deg <- as.numeric(out.deg) if (!is.null(in.deg)) in.deg <- as.numeric(in.deg) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_degree_sequence, out.deg, in.deg) res } #' @export is_graphical <- function(out.deg, in.deg=NULL) { # Argument checks out.deg <- as.numeric(out.deg) if (!is.null(in.deg)) in.deg <- as.numeric(in.deg) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_graphical_degree_sequence, out.deg, in.deg) res } #' @export bipartite_projection_size <- function(graph, types=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { if (!is.logical(types)) { warning("vertex types converted to logical") } types <- as.logical(types) if (any(is.na(types))) { stop("`NA' is not allowed in vertex types") } } else { stop("Not a bipartite graph, supply `types' argument") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_bipartite_projection_size, graph, types) res } #' @export bipartite_mapping <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_bipartite, graph) res } #' @export articulation_points <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_articulation_points, graph) if (igraph_opt("return.vs.es")) { res <- create_vs(graph, res) } res } #' @export biconnected_components <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_biconnected_components, graph) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$tree_edges)) { res$tree_edges[[i_]] <- create_es(graph, res$tree_edges[[i_]]) } } if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$component_edges)) { res$component_edges[[i_]] <- create_es(graph, res$component_edges[[i_]]) } } if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$components)) { res$components[[i_]] <- create_vs(graph, res$components[[i_]]) } } if (igraph_opt("return.vs.es")) { res$articulation_points <- create_vs(graph, res$articulation_points) } res } #' @export similarity.jaccard <- function(graph, vids=V(graph), mode=c("all", "out", "in", "total"), loops=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) loops <- as.logical(loops) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_similarity_jaccard, graph, vids-1, mode, loops) res } #' @export similarity.dice <- function(graph, vids=V(graph), mode=c("all", "out", "in", "total"), loops=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) loops <- as.logical(loops) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_similarity_dice, graph, vids-1, mode, loops) res } #' @export similarity.invlogweighted <- function(graph, vids=V(graph), mode=c("all", "out", "in", "total")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_similarity_inverse_log_weighted, graph, vids-1, mode) res } #' @export sample_hrg <- function(hrg) { # Argument checks if (is.null(hrg)) { hrg <- list(left=c(), right=c(), prob=c(), edges=c(), vertices=c()) } hrg <- lapply(hrg[c("left","right","prob","edges","vertices")], as.numeric) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_game, hrg) res <- set.graph.attribute(res, 'name', 'Hierarchical random graph model') res } #' @export hrg_tree <- function(hrg) { # Argument checks if (is.null(hrg)) { hrg <- list(left=c(), right=c(), prob=c(), edges=c(), vertices=c()) } hrg <- lapply(hrg[c("left","right","prob","edges","vertices")], as.numeric) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_dendrogram, hrg) res } #' @export consensus_tree <- function(graph, hrg=NULL, start=FALSE, num.samples=10000) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(hrg)) { hrg <- list(left=c(), right=c(), prob=c(), edges=c(), vertices=c()) } hrg <- lapply(hrg[c("left","right","prob","edges","vertices")], as.numeric) start <- as.logical(start) num.samples <- as.integer(num.samples) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_consensus, graph, hrg, start, num.samples) res } #' @export hrg <- function(graph, prob) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } prob <- as.numeric(prob) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_create, graph, prob) class(res) <- "igraphHRG" res } #' @export graphlets <- function(graph, weights=NULL, niter=1000) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } niter <- as.integer(niter) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_graphlets, graph, weights, niter) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$cliques)) { res$cliques[[i_]] <- create_vs(graph, res$cliques[[i_]]) } } res } #' @export dyad_census <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_dyad_census, graph) res } #' @export triad_census <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_triad_census, graph) res } #' @export count_triangles <- function(graph, vids=V(graph)) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_adjacent_triangles, graph, vids-1) res } #' @export triangles <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_list_triangles, graph) if (igraph_opt("return.vs.es")) { res <- create_vs(graph, res) } res } #' @export max_flow <- function(graph, source, target, capacity=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } source <- as.igraph.vs(graph, source) target <- as.igraph.vs(graph, target) if (is.null(capacity) && "capacity" %in% edge_attr_names(graph)) { capacity <- E(graph)$capacity } if (!is.null(capacity) && any(!is.na(capacity))) { capacity <- as.numeric(capacity) } else { capacity <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_maxflow, graph, source-1, target-1, capacity) if (igraph_opt("return.vs.es")) { res$partition1 <- create_vs(graph, res$partition1) } if (igraph_opt("return.vs.es")) { res$partition2 <- create_vs(graph, res$partition2) } res } #' @export dominator_tree <- function(graph, root, mode=c("out", "in")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } root <- as.igraph.vs(graph, root) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_dominator_tree, graph, root-1, mode) if (igraph_opt("return.vs.es")) { res$dom <- create_vs(graph, res$dom) } if (igraph_opt("return.vs.es")) { res$leftout <- create_vs(graph, res$leftout) } res } #' @export st_cuts <- function(graph, source, target) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } source <- as.igraph.vs(graph, source) target <- as.igraph.vs(graph, target) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_all_st_cuts, graph, source-1, target-1) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$cuts)) { res$cuts[[i_]] <- create_es(graph, res$cuts[[i_]]) } } if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$partition1s)) { res$partition1s[[i_]] <- create_vs(graph, res$partition1s[[i_]]) } } res } #' @export st_min_cuts <- function(graph, source, target, capacity=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } source <- as.igraph.vs(graph, source) target <- as.igraph.vs(graph, target) if (is.null(capacity) && "weight" %in% edge_attr_names(graph)) { capacity <- E(graph)$weight } if (!is.null(capacity) && any(!is.na(capacity))) { capacity <- as.numeric(capacity) } else { capacity <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_all_st_mincuts, graph, source-1, target-1, capacity) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$cuts)) { res$cuts[[i_]] <- create_es(graph, res$cuts[[i_]]) } } if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res$partition1s)) { res$partition1s[[i_]] <- create_vs(graph, res$partition1s[[i_]]) } } res } #' @export is_separator <- function(graph, candidate) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } candidate <- as.igraph.vs(graph, candidate) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_separator, graph, candidate-1) res } #' @export is_min_separator <- function(graph, candidate) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } candidate <- as.igraph.vs(graph, candidate) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_minimal_separator, graph, candidate-1) res } #' @export min_st_separators <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_all_minimal_st_separators, graph) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res)) { res[[i_]] <- create_vs(graph, res[[i_]]) } } res } #' @export min_separators <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_minimum_size_separators, graph) if (igraph_opt("return.vs.es")) { for (i_ in seq_along(res)) { res[[i_]] <- create_vs(graph, res[[i_]]) } } res } #' @export graph.isoclass <- function(graph) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isoclass, graph) res } #' @export graph.isomorphic <- function(graph1, graph2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isomorphic, graph1, graph2) res } #' @export graph_from_isomorphism_class <- function(size, number, directed=TRUE) { # Argument checks size <- as.integer(size) number <- as.integer(number) directed <- as.logical(directed) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isoclass_create, size, number, directed) res } #' @export graph.isomorphic.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isomorphic_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) res } #' @export graph.count.isomorphisms.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_count_isomorphisms_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) res } #' @export graph.subisomorphic.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_subisomorphic_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) res } #' @export graph.count.subisomorphisms.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_count_subisomorphisms_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) res } #' @export graph.isomorphic.34 <- function(graph1, graph2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isomorphic_34, graph1, graph2) res } #' @export canonical_permutation <- function(graph, sh="fm") { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } sh <- switch(igraph.match.arg(sh), "f"=0, "fl"=1, "fs"=2, "fm"=3, "flm"=4, "fsm"=5) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_canonical_permutation, graph, sh) res } #' @export permute <- function(graph, permutation) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } permutation <- as.numeric(permutation)-1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_permute_vertices, graph, permutation) res } #' @export graph.isomorphic.bliss <- function(graph1, graph2, sh="fm") { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } sh <- switch(igraph.match.arg(sh), "f"=0, "fl"=1, "fs"=2, "fm"=3, "flm"=4, "fsm"=5) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isomorphic_bliss, graph1, graph2, sh) res } #' @export automorphisms <- function(graph, sh="fm") { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } sh <- switch(igraph.match.arg(sh), "f"=0, "fl"=1, "fs"=2, "fm"=3, "flm"=4, "fsm"=5) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_automorphisms, graph, sh) res } #' @export scg_eps <- function(V, groups, mtype=c("symmetric", "laplacian", "stochastic"), p=NULL, norm=c("row", "col")) { # Argument checks V <- as.matrix(structure(as.double(V), dim=dim(V))) groups <- as.numeric(groups)-1 mtype <- switch(igraph.match.arg(mtype), "symmetric"=1, "laplacian"=2, "stochastic"=3) if (!is.null(p)) p <- as.numeric(p) norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_scg_norm_eps, V, groups, mtype, p, norm) res } #' @export embed_adjacency_matrix <- function(graph, no, weights=NULL, which=c("lm", "la", "sa"), scaled=TRUE, cvec=graph.strength(graph, weights=weights)/(vcount(graph)-1), options=igraph.arpack.default) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } no <- as.integer(no) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } which <- switch(igraph.match.arg(which), "lm"=0L, "la"=2L, "sa"=3L) scaled <- as.logical(scaled) cvec <- as.numeric(cvec) options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_adjacency_spectral_embedding, graph, no, weights, which, scaled, cvec, options) res } #' @export embed_laplacian_matrix <- function(graph, no, weights=NULL, which=c("lm", "la", "sa"), degmode=c("out", "in", "all", "total"), type=c("default", "D-A", "DAD", "I-DAD", "OAP"), scaled=TRUE, options=igraph.arpack.default) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } no <- as.integer(no) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } which <- switch(igraph.match.arg(which), "lm"=0L, "la"=2L, "sa"=3L) degmode <- switch(igraph.match.arg(degmode), "out"=1, "in"=2, "all"=3, "total"=3) type <- switch(igraph.match.arg(type), "default"=if (is.directed(graph)) 3L else 0L, "da"=0L, "d-a"=0L, "idad"=1L, "i-dad"=1L, "dad"=2L, "oap"=3L) scaled <- as.logical(scaled) options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_laplacian_spectral_embedding, graph, no, weights, which, degmode, type, scaled, options) res } #' @export spectrum <- function(graph, algorithm=c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which=list(), options=arpack_defaults) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } algorithm <- switch(igraph.match.arg(algorithm), "auto"=0, "lapack"=1, "arpack"=2, "comp_auto"=3, "comp_lapack"=4, "comp_arpack"=5) which.tmp <- eigen_defaults; which.tmp[ names(which) ] <- which ; which <- which.tmp options.tmp <- arpack_defaults; options.tmp[ names(options) ] <- options ; options <- options.tmp on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_eigen_adjacency, graph, algorithm, which, options) res } #' @export sir <- function(graph, beta, gamma, no.sim=100) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } beta <- as.numeric(beta) gamma <- as.numeric(gamma) no.sim <- as.integer(no.sim) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sir, graph, beta, gamma, no.sim) class(res) <- "sir" res } #' @export convex_hull <- function(data) { # Argument checks data <- as.matrix(structure(as.double(data), dim=dim(data))) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_convex_hull, data) res } #' @export dim_select <- function(sv) { # Argument checks sv <- as.numeric(sv) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_dim_select, sv) res } igraph/R/tkplot.R0000644000175100001440000016521513247071256013424 0ustar hornikusers# IGraph R package # Copyright (C) 2003-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' @include layout.R ################################################################### # Internal variables ################################################################### # the environment containing all the plots .tkplot.env <- new.env() assign(".next", 1, .tkplot.env) ################################################################### # Main function ################################################################### #' Interactive plotting of graphs #' #' \code{tkplot} and its companion functions serve as an interactive graph #' drawing facility. Not all parameters of the plot can be changed #' interactively right now though, eg. the colors of vertices, edges, and also #' others have to be pre-defined. #' #' \code{tkplot} is an interactive graph drawing facility. It is not very well #' developed at this stage, but it should be still useful. #' #' It's handling should be quite straightforward most of the time, here are #' some remarks and hints. #' #' There are different popup menus, activated by the right mouse button, for #' vertices and edges. Both operate on the current selection if the vertex/edge #' under the cursor is part of the selection and operate on the vertex/edge #' under the cursor if it is not. #' #' One selection can be active at a time, either a vertex or an edge selection. #' A vertex/edge can be added to a selection by holding the \code{control} key #' while clicking on it with the left mouse button. Doing this again deselect #' the vertex/edge. #' #' Selections can be made also from the \code{Select} menu. The `Select some #' vertices' dialog allows to give an expression for the vertices to be #' selected: this can be a list of numeric R expessions separated by commas, #' like `\code{1,2:10,12,14,15}' for example. Similarly in the `Select some #' edges' dialog two such lists can be given and all edges connecting a vertex #' in the first list to one in the second list will be selected. #' #' In the color dialog a color name like 'orange' or RGB notation can also be #' used. #' #' The \code{tkplot} command creates a new Tk window with the graphical #' representation of \code{graph}. The command returns an integer number, the #' tkplot id. The other commands utilize this id to be able to query or #' manipulate the plot. #' #' \code{tk_close} closes the Tk plot with id \code{tkp.id}. #' #' \code{tk_off} closes all Tk plots. #' #' \code{tk_fit} fits the plot to the given rectange #' (\code{width} and \code{height}), if some of these are \code{NULL} the #' actual phisical width od height of the plot window is used. #' #' \code{tk_reshape} applies a new layout to the plot, its optional #' parameters will be collected to a list analogous to \code{layout.par}. #' #' \code{tk_postscript} creates a dialog window for saving the plot #' in postscript format. #' #' \code{tk_canvas} returns the Tk canvas object that belongs to a graph #' plot. The canvas can be directly manipulated then, eg. labels can be added, #' it could be saved to a file programatically, etc. See an example below. #' #' \code{tk_coords} returns the coordinates of the vertices in a matrix. #' Each row corresponds to one vertex. #' #' \code{tk_set_coords} sets the coordinates of the vertices. A two-column #' matrix specifies the new positions, with each row corresponding to a single #' vertex. #' #' \code{tk_center} shifts the figure to the center of its plot window. #' #' \code{tk_rotate} rotates the figure, its parameter can be given either #' in degrees or in radians. #' #' @aliases tkplot tkplot.close tkplot.off tkplot.fit.to.screen tkplot.reshape #' tkplot.export.postscript tkplot.canvas tkplot.getcoords tkplot.setcoords #' tkplot.center tkplot.rotate tk_canvas tk_center tk_close tk_postscript #' tk_fit tk_coords tk_off tk_reshape tk_rotate tk_set_coords #' @param graph The \code{graph} to plot. #' @param canvas.width,canvas.height The size of the tkplot drawing area. #' @param tkp.id The id of the tkplot window to close/reshape/etc. #' @param window.close Leave this on the default value. #' @param width The width of the rectangle for generating new coordinates. #' @param height The height of the rectangle for generating new coordinates. #' @param newlayout The new layout, see the \code{layout} parameter of tkplot. #' @param norm Logical, should we norm the coordinates. #' @param coords Two-column numeric matrix, the new coordinates of the #' vertices, in absolute coordinates. #' @param degree The degree to rotate the plot. #' @param rad The degree to rotate the plot, in radian. #' @param \dots Additional plotting parameters. See \link{igraph.plotting} for #' the complete list. #' @return \code{tkplot} returns an integer, the id of the plot, this can be #' used to manipulate it from the command line. #' #' \code{tk_canvas} retuns \code{tkwin} object, the Tk canvas. #' #' \code{tk_coords} returns a matrix with the coordinates. #' #' \code{tk_close}, \code{tk_off}, \code{tk_fit}, #' \code{tk_reshape}, \code{tk_postscript}, \code{tk_center} #' and \code{tk_rotate} return \code{NULL} invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{plot.igraph}}, \code{\link{layout}} #' @export #' @keywords graphs #' @section Examples: #' \preformatted{ #' g <- make_ring(10) #' tkplot(g) #' #' ## Saving a tkplot() to a file programatically #' g <- make_star(10, center=10) %u% make_ring(9, directed=TRUE) #' E(g)$width <- sample(1:10, ecount(g), replace=TRUE) #' lay <- layout_nicely(g) #' #' id <- tkplot(g, layout=lay) #' canvas <- tk_canvas(id) #' tcltk::tkpostscript(canvas, file="/tmp/output.eps") #' tk_close(id) #' #' ## Setting the coordinates and adding a title label #' g <- make_ring(10) #' id <- tkplot(make_ring(10), canvas.width=450, canvas.height=500) #' #' canvas <- tk_canvas(id) #' padding <- 20 #' coords <- norm_coords(layout_in_circle(g), 0+padding, 450-padding, #' 50+padding, 500-padding) #' tk_set_coords(id, coords) #' #' width <- as.numeric(tkcget(canvas, "-width")) #' height <- as.numeric(tkcget(canvas, "-height")) #' tkcreate(canvas, "text", width/2, 25, text="My title", #' justify="center", font=tcltk::tkfont.create(family="helvetica", #' size=20,weight="bold")) #' } #' tkplot <- function(graph, canvas.width=450, canvas.height=450, ...) { if (!is_igraph(graph)) { stop("Not a graph object") } # Libraries requireNamespace("tcltk", quietly = TRUE) || stop("tcl/tk library not available") # Visual parameters params <- i.parse.plot.params(graph, list(...)) labels <- params("vertex", "label") label.color <- .tkplot.convert.color(params("vertex", "label.color")) label.font <- .tkplot.convert.font(params("vertex", "label.font"), params("vertex", "label.family"), params("vertex", "label.cex")) label.degree <- params("vertex", "label.degree") label.dist <- params("vertex", "label.dist") vertex.color <- .tkplot.convert.color(params("vertex", "color")) vertex.size <- params("vertex", "size") vertex.frame.color <- .tkplot.convert.color(params("vertex", "frame.color")) edge.color <- .tkplot.convert.color(params("edge", "color")) edge.width <- params("edge", "width") edge.labels <- params("edge", "label") edge.lty <- params("edge", "lty") loop.angle <- params("edge", "loop.angle") arrow.mode <- params("edge", "arrow.mode") edge.label.font <- .tkplot.convert.font(params("edge", "label.font"), params("edge", "label.family"), params("edge", "label.cex")) edge.label.color <- params("edge", "label.color") arrow.size <- params("edge", "arrow.size")[1] curved <- params("edge", "curved") curved <- rep(curved, length=ecount(graph)) layout <- unname(params("plot", "layout")) layout[,2] <- -layout[,2] margin <- params("plot", "margin") margin <- rep(margin, length=4) # the new style parameters can't do this yet arrow.mode <- i.get.arrow.mode(graph, arrow.mode) # Edge line type edge.lty <- i.tkplot.get.edge.lty(edge.lty) # Create window & canvas top <- tcltk::tktoplevel(background="lightgrey") canvas <- tcltk::tkcanvas(top, relief="raised", width=canvas.width, height=canvas.height, borderwidth=2) tcltk::tkpack(canvas, fill="both", expand=1) # Create parameters vertex.params <- sdf(vertex.color=vertex.color, vertex.size=vertex.size, label.font=label.font, NROW=vcount(graph)) params <- list(vertex.params=vertex.params, edge.color=edge.color, label.color=label.color, labels.state=1, edge.width=edge.width, padding=margin*300+max(vertex.size)+5, grid=0, label.degree=label.degree, label.dist=label.dist, edge.labels=edge.labels, vertex.frame.color=vertex.frame.color, loop.angle=loop.angle, edge.lty=edge.lty, arrow.mode=arrow.mode, edge.label.font=edge.label.font, edge.label.color=edge.label.color, arrow.size=arrow.size, curved=curved) # The popup menu popup.menu <- tcltk::tkmenu(canvas) tcltk::tkadd(popup.menu, "command", label="Fit to screen", command=function() { tk_fit(tkp.id)}) # Different popup menu for vertices vertex.popup.menu <- tcltk::tkmenu(canvas) tcltk::tkadd(vertex.popup.menu, "command", label="Vertex color", command=function() { tkp <- .tkplot.get(tkp.id) vids <- .tkplot.get.selected.vertices(tkp.id) if (length(vids)==0) return(FALSE) initialcolor <- tkp$params$vertex.params[vids[1], "vertex.color"] color <- .tkplot.select.color(initialcolor) if (color=="") return(FALSE) # Cancel .tkplot.update.vertex.color(tkp.id, vids, color) }) tcltk::tkadd(vertex.popup.menu, "command", label="Vertex size", command=function() { tkp <- .tkplot.get(tkp.id) vids <- .tkplot.get.selected.vertices(tkp.id) if (length(vids)==0) return(FALSE) initialsize <- tkp$params$vertex.params[1, "vertex.size"] size <- .tkplot.select.number("Vertex size", initialsize, 1, 20) if (is.na(size)) return(FALSE) .tkplot.update.vertex.size(tkp.id, vids, size) }) # Different popup menu for edges edge.popup.menu <- tcltk::tkmenu(canvas) tcltk::tkadd(edge.popup.menu, "command", label="Edge color", command=function() { tkp <- .tkplot.get(tkp.id) eids <- .tkplot.get.selected.edges(tkp.id) if (length(eids)==0) return(FALSE) initialcolor <- ifelse(length(tkp$params$edge.color)>1, tkp$params$edge.color[eids[1]], tkp$params$edge.color) color <- .tkplot.select.color(initialcolor) if (color=="") return(FALSE) # Cancel .tkplot.update.edge.color(tkp.id, eids, color) }) tcltk::tkadd(edge.popup.menu, "command", label="Edge width", command=function() { tkp <- .tkplot.get(tkp.id) eids <- .tkplot.get.selected.edges(tkp.id) if (length(eids)==0) return(FALSE) initialwidth <- ifelse(length(tkp$params$edge.width)>1, tkp$params$edge.width[eids[1]], tkp$params$edge.width) width <- .tkplot.select.number("Edge width", initialwidth, 1, 10) if (is.na(width)) return(FALSE) # Cancel .tkplot.update.edge.width(tkp.id, eids, width) }) # Create plot object tkp <- list(top=top, canvas=canvas, graph=graph, coords=layout, labels=labels, params=params, popup.menu=popup.menu, vertex.popup.menu=vertex.popup.menu, edge.popup.menu=edge.popup.menu) tkp.id <- .tkplot.new(tkp) tcltk::tktitle(top) <- paste("Graph plot", as.character(tkp.id)) # The main pull-down menu main.menu <- tcltk::tkmenu(top) tcltk::tkadd(main.menu, "command", label="Close", command=function() { tk_close(tkp.id, TRUE)}) select.menu <- .tkplot.select.menu(tkp.id, main.menu) tcltk::tkadd(main.menu, "cascade", label="Select", menu=select.menu) layout.menu <- .tkplot.layout.menu(tkp.id, main.menu) tcltk::tkadd(main.menu, "cascade", label="Layout", menu=layout.menu) view.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(main.menu, "cascade", label="View", menu=view.menu) tcltk::tkadd(view.menu, "command", label="Fit to screen", command=function() { tk_fit(tkp.id)}) tcltk::tkadd(view.menu, "command", label="Center on screen", command=function() { tk_center(tkp.id)}) tcltk::tkadd(view.menu, "separator") view.menu.labels <- tcltk::tclVar(1) view.menu.grid <- tcltk::tclVar(0) tcltk::tkadd(view.menu, "checkbutton", label="Labels", variable=view.menu.labels, command=function() { .tkplot.toggle.labels(tkp.id)}) # grid canvas object not implemented in tcltk (?) :( # tcltk::tkadd(view.menu, "checkbutton", label="Grid", # variable=view.menu.grid, command=function() { # .tkplot.toggle.grid(tkp.id)}) tcltk::tkadd(view.menu, "separator") rotate.menu <- tcltk::tkmenu(view.menu) tcltk::tkadd(view.menu, "cascade", label="Rotate", menu=rotate.menu) sapply(c(-90,-45,-15,-5,-1,1,5,15,45,90), function(deg) { tcltk::tkadd(rotate.menu, "command", label=paste(deg, "degree"), command=function() { tk_rotate(tkp.id, degree=deg) }) }) export.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(main.menu, "cascade", label="Export", menu=export.menu) tcltk::tkadd(export.menu, "command", label="Postscript", command=function() { tk_postscript(tkp.id)}) tcltk::tkconfigure(top, "-menu", main.menu) # plot it .tkplot.create.edges(tkp.id) .tkplot.create.vertices(tkp.id) # we would need an update here tk_fit(tkp.id, canvas.width, canvas.height) # Kill myself if window was closed tcltk::tkbind(top, "", function() tk_close(tkp.id, FALSE)) ################################################################### # The callbacks for interactive editing ################################################################### tcltk::tkitembind(canvas, "vertex||label||edge", "<1>", function(x, y) { tkp <- .tkplot.get(tkp.id) canvas <- .tkplot.get(tkp.id, "canvas") .tkplot.deselect.all(tkp.id) .tkplot.select.current(tkp.id) # tcltk::tkitemraise(canvas, "current") }) tcltk::tkitembind(canvas, "vertex||label||edge", "", function(x,y) { canvas <- .tkplot.get(tkp.id, "canvas") curtags <- as.character(tcltk::tkgettags(canvas, "current")) seltags <- as.character(tcltk::tkgettags(canvas, "selected")) if ("vertex" %in% curtags && "vertex" %in% seltags) { if ("selected" %in% curtags) { .tkplot.deselect.current(tkp.id) } else { .tkplot.select.current(tkp.id) } } else if ("edge" %in% curtags && "edge" %in% seltags) { if ("selected" %in% curtags) { .tkplot.deselect.current(tkp.id) } else { .tkplot.select.current(tkp.id) } } else if ("label" %in% curtags && "vertex" %in% seltags) { vtag <- curtags[pmatch("v-", curtags)] tkid <- as.numeric(tcltk::tkfind(canvas, "withtag", paste(sep="", "vertex&&", vtag))) vtags <- as.character(tcltk::tkgettags(canvas, tkid)) if ("selected" %in% vtags) { .tkplot.deselect.vertex(tkp.id, tkid) } else { .tkplot.select.vertex(tkp.id, tkid) } } else { .tkplot.deselect.all(tkp.id) .tkplot.select.current(tkp.id) } }) tcltk::tkitembind(canvas, "vertex||edge||label", "", function(x, y) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkitemlower(canvas, "current") }) tcltk::tkitembind(canvas, "vertex||edge||label", "", function(x, y) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkitemraise(canvas, "current") }) tcltk::tkbind(canvas, "<3>", function(x, y) { canvas <- .tkplot.get(tkp.id, "canvas") tags <- as.character(tcltk::tkgettags(canvas, "current")) if ("label" %in% tags) { vtag <- tags[ pmatch("v-", tags) ] vid <- as.character(tcltk::tkfind(canvas, "withtag", paste(sep="", "vertex&&", vtag))) tags <- as.character(tcltk::tkgettags(canvas, vid)) } if ("selected" %in% tags) { # The selection is active } else { # Delete selection, single object .tkplot.deselect.all(tkp.id) .tkplot.select.current(tkp.id) } tags <- as.character(tcltk::tkgettags(canvas, "selected")) ## TODO: what if different types of objects are selected if ("vertex" %in% tags || "label" %in% tags) { menu <- .tkplot.get(tkp.id, "vertex.popup.menu") } else if ("edge" %in% tags) { menu <- .tkplot.get(tkp.id, "edge.popup.menu") } else { menu <- .tkplot.get(tkp.id, "popup.menu") } x <- as.integer(x) + as.integer(tcltk::tkwinfo("rootx", canvas)) y <- as.integer(y) + as.integer(tcltk::tkwinfo("rooty", canvas)) tcltk::.Tcl(paste("tk_popup", tcltk::.Tcl.args(menu, x, y))) }) if (tkp$params$label.dist==0) tobind <- "vertex||label" else tobind <- "vertex" tcltk::tkitembind(canvas, tobind, "", function(x, y) { tkp <- .tkplot.get(tkp.id) x <- as.numeric(x) y <- as.numeric(y) width <- as.numeric(tcltk::tkwinfo("width", tkp$canvas)) height <- as.numeric(tcltk::tkwinfo("height", tkp$canvas)) if (x < 10) { x <- 10 } if (x > width-10) { x <- width-10 } if (y < 10) { y <- 10 } if (y > height-10) { y <- height-10 } # get the id tags <- as.character(tcltk::tkgettags(tkp$canvas, "selected")) id <- as.numeric(strsplit(tags[pmatch("v-", tags)], "-", fixed=TRUE)[[1]][2]) if (is.na(id)) { return() } # move the vertex .tkplot.set.vertex.coords(tkp.id, id, x, y) .tkplot.update.vertex(tkp.id, id, x, y) }) if (tkp$params$label.dist!=0) { tcltk::tkitembind(canvas, "label", "", function(x,y) { tkp <- .tkplot.get(tkp.id) x <- as.numeric(x) y <- as.numeric(y) # get the id tags <- as.character(tcltk::tkgettags(tkp$canvas, "selected")) id <- as.numeric(strsplit(tags[pmatch("v-", tags)], "-", fixed=TRUE)[[1]][2]) if (is.na(id)) { return() } phi <- pi+atan2(tkp$coords[id,2]-y, tkp$coords[id,1]-x) .tkplot.set.label.degree(tkp.id, id, phi) .tkplot.update.label(tkp.id, id, tkp$coords[id,1], tkp$coords[id,2]) }) } # We don't need these any more, they are stored in the environment rm(tkp, params, layout, vertex.color, edge.color, top, canvas, main.menu, layout.menu, view.menu, export.menu, label.font, label.degree, vertex.frame.color, vertex.params) tkp.id } ################################################################### # Internal functions handling data about layouts for the GUI ################################################################### .tkplot.addlayout <- function(name, layout.data) { if (!exists(".layouts", envir=.tkplot.env)) { assign(".layouts", list(), .tkplot.env) } assign("tmp", layout.data, .tkplot.env) cmd <- paste(sep="", ".layouts[[\"", name, "\"]]", " <- tmp") eval(parse(text=cmd), .tkplot.env) rm("tmp", envir=.tkplot.env) } .tkplot.getlayout <- function(name) { cmd <- paste(sep="", ".layouts[[\"", name, "\"]]") eval(parse(text=cmd), .tkplot.env) } .tkplot.layouts.newdefaults <- function(name, defaults) { assign("tmp", defaults, .tkplot.env) for (i in seq(along=defaults)) { cmd <- paste(sep="", '.layouts[["', name, '"]]$params[[', i, ']]$default <- tmp[[', i, ']]') eval(parse(text=cmd), .tkplot.env) } } .tkplot.getlayoutlist <- function() { eval(parse(text="names(.layouts)"), .tkplot.env) } .tkplot.getlayoutname <- function(name) { cmd <- paste(sep="", '.layouts[["', name, '"]]$name') eval(parse(text=cmd), .tkplot.env) } .tkplot.addlayout("random", list(name="Random", f=layout_randomly, params=list())) .tkplot.addlayout("circle", list(name="Circle", f=layout_in_circle, params=list())) .tkplot.addlayout("fruchterman.reingold", list(name="Fruchterman-Reingold", f=layout_with_fr, params=list( niter=list(name="Number of iterations", type="numeric", default=500), start.temp=list(name="Start temperature", type="expression", default=expression(sqrt(vcount(.tkplot.g))))) ) ) .tkplot.addlayout("kamada.kawai", list(name="Kamada-Kawai", f=layout_with_kk, params=list( maxiter=list(name="Maximum number of iterations", type="expression", default=expression(50 * vcount(.tkplot.g))), kkconst=list(name="Vertex attraction constant", type="expression", default=expression(vcount(.tkplot.g)))) ) ) .tkplot.addlayout("reingold.tilford", list(names="Reingold-Tilford", f=layout_as_tree, params=list( root=list(name="Root vertex", type="numeric", default=1) ) ) ) ################################################################### # Other public functions, misc. ################################################################### #' @rdname tkplot #' @export tk_close <- function(tkp.id, window.close=TRUE) { if (window.close) { cmd <- paste(sep="", "tkp.", tkp.id, "$top") top <- eval(parse(text=cmd), .tkplot.env) tcltk::tkbind(top, "", "") tcltk::tkdestroy(top) } cmd <- paste(sep="", "tkp.", tkp.id) rm(list=cmd, envir=.tkplot.env) invisible(NULL) } #' @rdname tkplot #' @export tk_off <- function() { eapply(.tkplot.env, function(tkp) { tcltk::tkdestroy(tkp$top) }) rm(list=ls(.tkplot.env), envir=.tkplot.env) invisible(NULL) } #' @rdname tkplot #' @export tk_fit <- function(tkp.id, width=NULL, height=NULL) { tkp <- .tkplot.get(tkp.id) if (is.null(width)) { width <- as.numeric(tcltk::tkwinfo("width", tkp$canvas)) } if (is.null(height)) { height <- as.numeric(tcltk::tkwinfo("height", tkp$canvas)) } coords <- .tkplot.get(tkp.id, "coords") # Shift to zero coords[,1] <- coords[,1]-min(coords[,1]) coords[,2] <- coords[,2]-min(coords[,2]) # Scale coords[,1] <- coords[,1] / max(coords[,1]) * (width-(tkp$params$padding[2]+tkp$params$padding[4])) coords[,2] <- coords[,2] / max(coords[,2]) * (height-(tkp$params$padding[1]+tkp$params$padding[3])) # Padding coords[,1] <- coords[,1]+tkp$params$padding[2] coords[,2] <- coords[,2]+tkp$params$padding[3] # Store .tkplot.set(tkp.id, "coords", coords) # Update .tkplot.update.vertices(tkp.id) invisible(NULL) } #' @rdname tkplot #' @export tk_center <- function(tkp.id) { tkp <- .tkplot.get(tkp.id) width <- as.numeric(tcltk::tkwinfo("width", tkp$canvas)) height <- as.numeric(tcltk::tkwinfo("height", tkp$canvas)) coords <- .tkplot.get(tkp.id, "coords") canvas.center.x <- width/2 canvas.center.y <- height/2 coords <- .tkplot.get(tkp.id, "coords") r1 <- range(coords[,1]) r2 <- range(coords[,2]) coords.center.x <- (r1[1]+r1[2])/2 coords.center.y <- (r2[1]+r2[2])/2 # Shift to center coords[,1] <- coords[,1]+canvas.center.x-coords.center.x coords[,2] <- coords[,2]+canvas.center.y-coords.center.y # Store .tkplot.set(tkp.id, "coords", coords) # Update .tkplot.update.vertices(tkp.id) invisible(NULL) } #' @rdname tkplot #' @param params Extra parameters in a list, to pass to the layout function. #' @export tk_reshape <- function(tkp.id, newlayout, ..., params) { tkp <- .tkplot.get(tkp.id) new_coords <- do_call(newlayout, .args=c(list(tkp$graph), list(...), params)) .tkplot.set(tkp.id, "coords", new_coords) tk_fit(tkp.id) .tkplot.update.vertices(tkp.id) invisible(NULL) } #' @rdname tkplot #' @export tk_postscript <- function(tkp.id) { tkp <- .tkplot.get(tkp.id) filename <- tcltk::tkgetSaveFile(initialfile="Rplots.eps", defaultextension="eps", title="Export graph to PostScript file") tcltk::tkpostscript(tkp$canvas, file=filename) invisible(NULL) } #' @rdname tkplot #' @export tk_coords <- function(tkp.id, norm=FALSE) { coords <- .tkplot.get(tkp.id, "coords") coords[,2] <- max(coords[,2]) - coords[,2] if (norm) { # Shift coords[,1] <- coords[,1]-min(coords[,1]) coords[,2] <- coords[,2]-min(coords[,2]) # Scale coords[,1] <- coords[,1] / max(coords[,1])-0.5 coords[,2] <- coords[,2] / max(coords[,2])-0.5 } coords } #' @rdname tkplot #' @export tk_set_coords <- function(tkp.id, coords) { stopifnot(is.matrix(coords), ncol(coords)==2) .tkplot.set(tkp.id, "coords", coords) .tkplot.update.vertices(tkp.id) invisible(NULL) } #' @rdname tkplot #' @export tk_rotate <- function(tkp.id, degree=NULL, rad=NULL) { coords <- .tkplot.get(tkp.id, "coords") if (is.null(degree) && is.null(rad)) { rad <- pi/2 } else if (is.null(rad) && !is.null(degree)) { rad <- degree/180*pi } center <- c(mean(range(coords[,1])), mean(range(coords[,2]))) phi <- atan2(coords[,2]-center[2], coords[,1]-center[1]) r <- sqrt((coords[,1]-center[1])**2 + (coords[,2]-center[2])**2) phi <- phi + rad coords[,1] <- r * cos(phi) coords[,2] <- r * sin(phi) .tkplot.set(tkp.id, "coords", coords) tk_center(tkp.id) invisible(NULL) } #' @rdname tkplot #' @export tk_canvas <- function(tkp.id) { .tkplot.get(tkp.id)$canvas } ################################################################### # Internal functions, handling the internal environment ################################################################### .tkplot.new <- function(tkp) { id <- get(".next", .tkplot.env) assign(".next", id+1, .tkplot.env) assign("tmp", tkp, .tkplot.env) cmd <- paste("tkp.", id, "<- tmp", sep="") eval(parse(text=cmd), .tkplot.env) rm("tmp", envir=.tkplot.env) id } .tkplot.get <- function(tkp.id, what=NULL) { if (is.null(what)) { get(paste("tkp.", tkp.id, sep=""), .tkplot.env) } else { cmd <- paste("tkp.", tkp.id, "$", what, sep="") eval(parse(text=cmd), .tkplot.env) } } .tkplot.set <- function(tkp.id, what, value) { assign("tmp", value, .tkplot.env) cmd <- paste(sep="", "tkp.", tkp.id, "$", what, "<-tmp") eval(parse(text=cmd), .tkplot.env) rm("tmp", envir=.tkplot.env) TRUE } .tkplot.set.params <- function(tkp.id, what, value) { assign("tmp", value, .tkplot.env) cmd <- paste(sep="", "tkp.", tkp.id, "$params$", what, "<-tmp") eval(parse(text=cmd), .tkplot.env) rm("tmp", envir=.tkplot.env) TRUE } .tkplot.set.vertex.coords <- function(tkp.id, id, x, y) { cmd <- paste(sep="", "tkp.", tkp.id, "$coords[",id,",]<-c(",x,",",y,")") eval(parse(text=cmd), .tkplot.env) TRUE } .tkplot.set.label.degree <- function(tkp.id, id, phi) { tkp <- .tkplot.get(tkp.id) if (length(tkp$params$label.degree)==1) { label.degree <- rep(tkp$params$label.degree, times=vcount(tkp$graph)) label.degree[id] <- phi assign("tmp", label.degree, .tkplot.env) cmd <- paste(sep="", "tkp.", tkp.id, "$params$label.degree <- tmp") eval(parse(text=cmd), .tkplot.env) rm("tmp", envir=.tkplot.env) } else { cmd <- paste(sep="", "tkp.", tkp.id, "$params$label.degree[", id, "] <- ", phi) eval(parse(text=cmd), .tkplot.env) } TRUE } ################################################################### # Internal functions, creating and updating canvas objects ################################################################### # Creates a new vertex tk object .tkplot.create.vertex <- function(tkp.id, id, label, x=0, y=0) { tkp <- .tkplot.get(tkp.id) vertex.size <- tkp$params$vertex.params[id, "vertex.size"] vertex.color <- tkp$params$vertex.params[id, "vertex.color"] vertex.frame.color <- ifelse(length(tkp$params$vertex.frame.color)>1, tkp$params$vertex.frame.color[id], tkp$params$vertex.frame.color) item <- tcltk::tkcreate(tkp$canvas, "oval", x-vertex.size, y-vertex.size, x+vertex.size, y+vertex.size, width=1, outline=vertex.frame.color, fill=vertex.color) tcltk::tkaddtag(tkp$canvas, "vertex", "withtag", item) tcltk::tkaddtag(tkp$canvas, paste("v-", id, sep=""), "withtag", item) if (!is.na(label)) { label.degree <- ifelse(length(tkp$params$label.degree)>1, tkp$params$label.degree[id], tkp$params$label.degree) label.color <- if (length(tkp$params$label.color)>1) { tkp$params$label.color[id] } else { tkp$params$label.color } label.dist <- tkp$params$label.dist label.x <- x+label.dist*cos(label.degree)* (vertex.size+6+4*(ceiling(log10(id)))) label.y <- y+label.dist*sin(label.degree)* (vertex.size+6+4*(ceiling(log10(id)))) if (label.dist==0) { afill <- label.color } else { afill <- "red" } litem <- tcltk::tkcreate(tkp$canvas, "text", label.x, label.y, text=as.character(label), state="normal", fill=label.color, activefill=afill, font=tkp$params$vertex.params[id, "label.font"]) tcltk::tkaddtag(tkp$canvas, "label", "withtag", litem) tcltk::tkaddtag(tkp$canvas, paste("v-", id, sep=""), "withtag", litem) } item } # Create all vertex objects and move them into correct position .tkplot.create.vertices <- function(tkp.id) { tkp <- .tkplot.get(tkp.id) n <- vcount(tkp$graph) # Labels labels <- i.get.labels(tkp$graph, tkp$labels) mapply(function(v, l, x, y) .tkplot.create.vertex(tkp.id, v, l, x, y), 1:n, labels, tkp$coords[,1], tkp$coords[,2]) } .tkplot.update.label <- function(tkp.id, id, x, y) { tkp <- .tkplot.get(tkp.id) vertex.size <- tkp$params$vertex.params[id, "vertex.size"] label.degree <- ifelse(length(tkp$params$label.degree)>1, tkp$params$label.degree[id], tkp$params$label.degree) label.dist <- tkp$params$label.dist label.x <- x+label.dist*cos(label.degree)* (vertex.size+6+4*(ceiling(log10(id)))) label.y <- y+label.dist*sin(label.degree)* (vertex.size+6+4*(ceiling(log10(id)))) tcltk::tkcoords(tkp$canvas, paste("label&&v-", id, sep=""), label.x, label.y) } .tkplot.update.vertex <- function(tkp.id, id, x, y) { tkp <- .tkplot.get(tkp.id) vertex.size <- tkp$params$vertex.params[id, "vertex.size"] # Vertex tcltk::tkcoords(tkp$canvas, paste("vertex&&v-", id, sep=""), x-vertex.size, y-vertex.size, x+vertex.size, y+vertex.size) # Label .tkplot.update.label(tkp.id, id, x, y) # Edges edge.from.ids <- as.numeric(tcltk::tkfind(tkp$canvas, "withtag", paste("from-", id, sep=""))) edge.to.ids <- as.numeric(tcltk::tkfind(tkp$canvas, "withtag", paste("to-", id, sep=""))) for (i in seq(along=edge.from.ids)) { .tkplot.update.edge(tkp.id, edge.from.ids[i]) } for (i in seq(along=edge.to.ids)) { .tkplot.update.edge(tkp.id, edge.to.ids[i]) } } .tkplot.update.vertices <- function(tkp.id) { tkp <- .tkplot.get(tkp.id) n <- vcount(tkp$graph) mapply(function(v, x, y) .tkplot.update.vertex(tkp.id, v, x, y), 1:n, tkp$coords[,1], tkp$coords[,2]) } # Creates tk object for edge 'id' .tkplot.create.edge <- function(tkp.id, from, to, id) { tkp <- .tkplot.get(tkp.id) from.c <- tkp$coords[from,] to.c <- tkp$coords[to,] edge.color <- ifelse(length(tkp$params$edge.color)>1, tkp$params$edge.color[id], tkp$params$edge.color) edge.width <- ifelse(length(tkp$params$edge.width)>1, tkp$params$edge.width[id], tkp$params$edge.width) edge.lty <- ifelse(length(tkp$params$edge.lty)>1, tkp$params$edge.lty[[id]], tkp$params$edge.lty) arrow.mode <- ifelse(length(tkp$params$arrow.mode)>1, tkp$params$arrow.mode[[id]], tkp$params$arrow.mode) arrow.size <- tkp$params$arrow.size curved <- tkp$params$curved[[id]] arrow <- c("none", "first", "last", "both")[arrow.mode+1] if (from != to) { ## non-loop edge if (is.logical(curved)) curved <- curved * 0.5 if (curved != 0) { smooth <- TRUE midx <- (from.c[1]+to.c[1])/2 midy <- (from.c[2]+to.c[2])/2 spx <- midx - curved * 1/2 * (from.c[2]-to.c[2]) spy <- midy + curved * 1/2 * (from.c[1]-to.c[1]) coords <- c(from.c[1], from.c[2], spx, spy, to.c[1], to.c[2]) } else { smooth <- FALSE coords <- c(from.c[1], from.c[2], to.c[1], to.c[2]) } args <- c(list(tkp$canvas, "line"), coords, list(width=edge.width, activewidth=2*edge.width, arrow=arrow, arrowshape=arrow.size * c(10, 10, 5), fill=edge.color, activefill="red", dash=edge.lty, tags=c("edge", paste(sep="", "edge-", id), paste(sep="", "from-", from), paste(sep="", "to-", to))), smooth=smooth) do.call(tcltk::tkcreate, args) } else { ## loop edge ## the coordinates are not correct but we will call update anyway... tcltk::tkcreate(tkp$canvas, "line", from.c[1], from.c[2], from.c[1]+20, from.c[1]-10, from.c[2]+30, from.c[2], from.c[1]+20, from.c[1]+10, from.c[1], from.c[2], width=edge.width, activewidth=2*edge.width, arrow=arrow, arrowshape=arrow.size * c(10,10,5), dash=edge.lty, fill=edge.color, activefill="red", smooth=TRUE, tags=c("edge", "loop", paste(sep="", "edge-", id), paste(sep="", "from-", from), paste(sep="", "to-", to))) } edge.label <- ifelse(length(tkp$params$edge.labels)>1, tkp$params$edge.labels[id], tkp$params$edge.labels) if (!is.na(edge.label)) { label.color <- ifelse(length(tkp$params$edge.label.color)>1, tkp$params$edge.label.color[id], tkp$params$edge.label.color) ## not correct for loop edges but we will update anyway... label.x <- (to.c[1]+from.c[1])/2 label.y <- (to.c[2]+from.c[2])/2 litem <- tcltk::tkcreate(tkp$canvas, "text", label.x, label.y, text=as.character(edge.label), state="normal", fill=label.color, font=tkp$params$edge.label.font) tcltk::tkaddtag(tkp$canvas, "label", "withtag", litem) tcltk::tkaddtag(tkp$canvas, paste(sep="", "edge-", id), "withtag", litem) } } # Creates all edges .tkplot.create.edges <- function(tkp.id) { tkp <- .tkplot.get(tkp.id) n <- ecount(tkp$graph) edgematrix <- as_edgelist(tkp$graph, names=FALSE) mapply(function(from, to, id) .tkplot.create.edge(tkp.id, from, to, id), edgematrix[,1], edgematrix[,2], 1:nrow(edgematrix)) } # Update an edge with given itemid (not edge id!) .tkplot.update.edge <- function(tkp.id, itemid) { tkp <- .tkplot.get(tkp.id) tags <- as.character(tcltk::tkgettags(tkp$canvas, itemid)) from <- as.numeric(substring(grep("from-", tags, value=TRUE, fixed=TRUE),6)) to <- as.numeric(substring(grep("to-", tags, value=TRUE, fixed=TRUE),4)) from.c <- tkp$coords[from,] to.c <- tkp$coords[to,] edgeid <- as.numeric(substring(tags[ pmatch("edge-", tags) ], 6)) if (from != to) { phi <- atan2(to.c[2]-from.c[2], to.c[1]-from.c[1]) r <- sqrt( (to.c[1]-from.c[1])^2 + (to.c[2]-from.c[2])^2 ) vertex.size <- tkp$params$vertex.params[to, "vertex.size"] vertex.size2 <- tkp$params$vertex.params[from, "vertex.size"] curved <- tkp$params$curved[[edgeid]] to.c[1] <- from.c[1] + (r-vertex.size)*cos(phi) to.c[2] <- from.c[2] + (r-vertex.size)*sin(phi) from.c[1] <- from.c[1] + vertex.size2*cos(phi) from.c[2] <- from.c[2] + vertex.size2*sin(phi) if (is.logical(curved)) curved <- curved * 0.5 if (curved == 0) { tcltk::tkcoords(tkp$canvas, itemid, from.c[1], from.c[2], to.c[1], to.c[2]) } else { midx <- (from.c[1]+to.c[1])/2 midy <- (from.c[2]+to.c[2])/2 spx <- midx - curved * 1/2 * (from.c[2]-to.c[2]) spy <- midy + curved * 1/2 * (from.c[1]-to.c[1]) tcltk::tkcoords(tkp$canvas, itemid, from.c[1], from.c[2], spx, spy, to.c[1], to.c[2]) } } else { vertex.size <- tkp$params$vertex.params[to, "vertex.size"] loop.angle <- ifelse(length(tkp$param$loop.angle)>1, tkp$params$loop.angle[edgeid], tkp$params$loop.angle) xx <- from.c[1] + cos(loop.angle/180*pi)*vertex.size yy <- from.c[2] + sin(loop.angle/180*pi)*vertex.size cc <- matrix(c(xx,yy, xx+20,yy-10, xx+30,yy, xx+20,yy+10, xx,yy), ncol=2, byrow=TRUE) phi <- atan2(cc[,2]-yy, cc[,1]-xx) r <- sqrt((cc[,1]-xx)**2 + (cc[,2]-yy)**2) phi <- phi+loop.angle/180*pi cc[,1] <- xx+r*cos(phi) cc[,2] <- yy+r*sin(phi) tcltk::tkcoords(tkp$canvas, itemid, cc[1,1], cc[1,2], cc[2,1], cc[2,2], cc[3,1], cc[3,2], cc[4,1], cc[4,2], cc[5,1]+0.001, cc[5,2]+0.001) } edge.label <- ifelse(length(tkp$params$edge.labels)>1, tkp$params$edge.labels[edgeid], tkp$params$edge.labels) if (!is.na(edge.label)) { if (from != to) { label.x <- (to.c[1]+from.c[1])/2 label.y <- (to.c[2]+from.c[2])/2 } else { ## loops label.x <- xx+cos(loop.angle/180*pi)*30 label.y <- yy+sin(loop.angle/180*pi)*30 } litem <- as.numeric(tcltk::tkfind(tkp$canvas, "withtag", paste(sep="", "label&&edge-", edgeid))) tcltk::tkcoords(tkp$canvas, litem, label.x, label.y) } } .tkplot.toggle.labels <- function(tkp.id) { .tkplot.set.params(tkp.id, "labels.state", 1 - .tkplot.get(tkp.id, "params")$labels.state) tkp <- .tkplot.get(tkp.id) state <- ifelse(tkp$params$labels.state==1, "normal", "hidden") tcltk::tkitemconfigure(tkp$canvas, "label", "-state", state) } .tkplot.toggle.grid <- function(tkp.id) { .tkplot.set.params(tkp.id, "grid", 1 - .tkplot.get(tkp.id, "params")$grid) tkp <- .tkplot.get(tkp.id) state <- ifelse(tkp$params$grid==1, "normal", "hidden") if (state=="hidden") { tcltk::tkdelete(tkp$canvas, "grid") } else { tcltk::tkcreate(tkp$canvas, "grid", 0, 0, 10, 10, tags=c("grid")) } } .tkplot.update.vertex.color <- function(tkp.id, vids, newcolor) { tkp <- .tkplot.get(tkp.id) vparams <- tkp$params$vertex.params vparams[vids, "vertex.color"] <- newcolor .tkplot.set(tkp.id, "params$vertex.params", vparams) tcltk::tkitemconfigure(tkp$canvas, "selected&&vertex", "-fill", newcolor) } .tkplot.update.edge.color <- function(tkp.id, eids, newcolor) { tkp <- .tkplot.get(tkp.id) colors <- tkp$params$edge.color if (length(colors)==1 && length(eids)==ecount(tkp$graph)) { ## Uniform color -> uniform color .tkplot.set(tkp.id, "params$edge.color", newcolor) } else if (length(colors)==1) { ## Uniform color -> nonuniform color colors <- rep(colors, ecount(tkp$graph)) colors[eids] <- newcolor .tkplot.set(tkp.id, "params$edge.color", colors) } else if (length(eids)==ecount(tkp$graph)) { ## Non-uniform -> uniform .tkplot.set(tkp.id, "params$edge.color", newcolor) } else { ## Non-uniform -> non-uniform colors[eids] <- newcolor .tkplot.set(tkp.id, "params$edge.color", colors) } tcltk::tkitemconfigure(tkp$canvas, "selected&&edge", "-fill", newcolor) } .tkplot.update.edge.width <- function(tkp.id, eids, newwidth) { tkp <- .tkplot.get(tkp.id) widths <- tkp$params$edge.width if (length(widths)==1 && length(eids)==ecount(tkp$graph)) { ## Uniform width -> uniform width .tkplot.set(tkp.id, "params$edge.width", newwidth) } else if (length(widths)==1) { ## Uniform width -> nonuniform width widths <- rep(widths, ecount(tkp$graph)) widths[eids] <- newwidth .tkplot.set(tkp.id, "params$edge.width", widths) } else if (length(eids)==ecount(tkp$graph)) { ## Non-uniform -> uniform .tkplot.set(tkp.id, "params$edge.width", newwidth) } else { ## Non-uniform -> non-uniform widths[eids] <- newwidth .tkplot.set(tkp.id, "params$edge.width", widths) } tcltk::tkitemconfigure(tkp$canvas, "selected&&edge", "-width", newwidth) } .tkplot.update.vertex.size <- function(tkp.id, vids, newsize) { tkp <- .tkplot.get(tkp.id) vparams <- tkp$params$vertex.params vparams[vids, "vertex.size"] <- newsize .tkplot.set(tkp.id, "params$vertex.params", vparams) sapply(vids, function(id) { .tkplot.update.vertex(tkp.id, id, tkp$coords[id,1], tkp$coords[id,2]) }) } .tkplot.get.numeric.vector <- function(...) { labels <- list(...) if (length(labels)==0) return(FALSE) answers <- as.list(rep("", length(labels))) dialog <- tcltk::tktoplevel() vars <- lapply(answers, tcltk::tclVar) retval <- list() OnOK <- function() { retval <<- lapply(vars, tcltk::tclvalue) tcltk::tkdestroy(dialog) } OK.but <- tcltk::tkbutton(dialog, text=" OK ", command=OnOK) for (i in seq(along=labels)) { tcltk::tkgrid(tcltk::tklabel(dialog, text=labels[[i]])) tmp <- tcltk::tkentry(dialog, width="40",textvariable=vars[[i]]) tcltk::tkgrid(tmp) tcltk::tkbind(tmp, "", OnOK) } tcltk::tkgrid(OK.but) tcltk::tkwait.window(dialog) retval <- lapply(retval, function(v) { eval(parse(text=paste("c(", v, ")"))) }) return (retval) } .tkplot.select.number <- function(label, initial, low=1, high=100) { dialog <- tcltk::tktoplevel() SliderValue <- tcltk::tclVar(as.character(initial)) SliderValueLabel <- tcltk::tklabel(dialog,text=as.character(tcltk::tclvalue(SliderValue))) tcltk::tkgrid(tcltk::tklabel(dialog,text=label), SliderValueLabel) tcltk::tkconfigure(SliderValueLabel, textvariable=SliderValue) slider <- tcltk::tkscale(dialog, from=high, to=low, showvalue=F, variable=SliderValue, resolution=1, orient="horizontal") OnOK <- function() { SliderValue <<- as.numeric(tcltk::tclvalue(SliderValue)) tcltk::tkdestroy(dialog) } OnCancel <- function() { SliderValue <<- NA tcltk::tkdestroy(dialog) } OK.but <- tcltk::tkbutton(dialog, text=" OK ", command=OnOK) cancel.but <- tcltk::tkbutton(dialog, text=" Cancel ", command=OnCancel) tcltk::tkgrid(slider) tcltk::tkgrid(OK.but, cancel.but) tcltk::tkwait.window(dialog) return(SliderValue) } ################################################################### # Internal functions, vertex and edge selection ################################################################### .tkplot.deselect.all <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") ids <- as.numeric(tcltk::tkfind(canvas, "withtag", "selected")) for (i in ids) { .tkplot.deselect.this(tkp.id, i) } } .tkplot.select.all.vertices <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") vertices <- as.numeric(tcltk::tkfind(canvas, "withtag", "vertex")) for (i in vertices) { .tkplot.select.vertex(tkp.id, i) } } .tkplot.select.some.vertices <- function(tkp.id, vids) { canvas <- .tkplot.get(tkp.id, "canvas") vids <- unique(vids) for (i in vids) { tkid <- as.numeric(tcltk::tkfind(canvas, "withtag", paste(sep="", "vertex&&v-", i))) .tkplot.select.vertex(tkp.id, tkid) } } .tkplot.select.all.edges <- function(tkp.id, vids) { canvas <- .tkplot.get(tkp.id, "canvas") edges <- as.numeric(tcltk::tkfind(canvas, "withtag", "edge")) for (i in edges) { .tkplot.select.edge(tkp.id, i) } } .tkplot.select.some.edges <- function(tkp.id, from, to) { canvas <- .tkplot.get(tkp.id, "canvas") fromtags <- sapply(from, function(i) { paste(sep="", "from-", i) }) totags <- sapply(from, function(i) { paste(sep="", "to-", i) }) edges <- as.numeric(tcltk::tkfind(canvas, "withtag", "edge")) for (i in edges) { tags <- as.character(tcltk::tkgettags(canvas, i)) ftag <- tags[ pmatch("from-", tags) ] ttag <- tags[ pmatch("to-", tags) ] if (ftag %in% fromtags && ttag %in% totags) { .tkplot.select.edge(tkp.id, i) } } } .tkplot.select.vertex <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkaddtag(canvas, "selected", "withtag", tkid) tcltk::tkitemconfigure(canvas, tkid, "-outline", "red", "-width", 2) } .tkplot.select.edge <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkaddtag(canvas, "selected", "withtag", tkid) tcltk::tkitemconfigure(canvas, tkid, "-dash", "-") } .tkplot.select.label <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkaddtag(canvas, "selected", "withtag", tkid) } .tkplot.deselect.vertex <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkdtag(canvas, tkid, "selected") tkp <- .tkplot.get(tkp.id) tags <- as.character(tcltk::tkgettags(canvas, tkid)) id <- as.numeric(substring(tags[pmatch("v-", tags)], 3)) vertex.frame.color <- ifelse(length(tkp$params$vertex.frame.color)>1, tkp$params$vertex.frame.color[id], tkp$params$vertex.frame.color) tcltk::tkitemconfigure(canvas, tkid, "-outline", vertex.frame.color, "-width", 1) } .tkplot.deselect.edge <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkdtag(canvas, tkid, "selected") tkp <- .tkplot.get(tkp.id) tags <- as.character(tcltk::tkgettags(canvas, tkid)) id <- as.numeric(substring(tags[pmatch("edge-", tags)], 6)) edge.lty <- ifelse(length(tkp$params$edge.lty)>1, tkp$params$edge.lty[[id]], tkp$params$edge.lty) tcltk::tkitemconfigure(canvas, tkid, "-dash", edge.lty) } .tkplot.deselect.label <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tcltk::tkdtag(canvas, tkid, "selected") } .tkplot.select.current <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") tkid <- as.numeric(tcltk::tkfind(canvas, "withtag", "current")) .tkplot.select.this(tkp.id, tkid) } .tkplot.deselect.current <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") tkid <- as.numeric(tcltk::tkfind(canvas, "withtag", "current")) .tkplot.deselect.this(tkp.id, tkid) } .tkplot.select.this <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tags <- as.character(tcltk::tkgettags(canvas, tkid)) if ("vertex" %in% tags) { .tkplot.select.vertex(tkp.id, tkid) } else if ("edge" %in% tags) { .tkplot.select.edge(tkp.id, tkid) } else if ("label" %in% tags) { tkp <- .tkplot.get(tkp.id) if (tkp$params$label.dist == 0) { id <- tags[pmatch("v-", tags)] tkid <- as.character(tcltk::tkfind(canvas, "withtag", paste(sep="", "vertex&&", id))) .tkplot.select.vertex(tkp.id, tkid) } else { .tkplot.select.label(tkp.id, tkid) } } } .tkplot.deselect.this <- function(tkp.id, tkid) { canvas <- .tkplot.get(tkp.id, "canvas") tags <- as.character(tcltk::tkgettags(canvas, tkid)) if ("vertex" %in% tags) { .tkplot.deselect.vertex(tkp.id, tkid) } else if ("edge" %in% tags) { .tkplot.deselect.edge(tkp.id, tkid) } else if ("label" %in% tags) { tkp <- .tkplot.get(tkp.id) if (tkp$params$label.dist == 0) { id <- tags[pmatch("v-", tags)] tkid <- as.character(tcltk::tkfind(canvas, "withtag", paste(sep="", "vertex&&", id))) .tkplot.deselect.vertex(tkp.id, tkid) } else { .tkplot.deselect.label(tkp.id, tkid) } } } .tkplot.get.selected.vertices <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") tkids <- as.numeric(tcltk::tkfind(canvas, "withtag", "vertex&&selected")) ids <- sapply(tkids, function(tkid) { tags <- as.character(tcltk::tkgettags(canvas, tkid)) id <- as.numeric(substring(tags [pmatch("v-", tags)], 3)) id}) ids } .tkplot.get.selected.edges <- function(tkp.id) { canvas <- .tkplot.get(tkp.id, "canvas") tkids <- as.numeric(tcltk::tkfind(canvas, "withtag", "edge&&selected")) ids <- sapply(tkids, function(tkid) { tags <- as.character(tcltk::tkgettags(canvas, tkid)) id <- as.numeric(substring(tags [pmatch("edge-", tags)], 6)) id}) ids } ################################################################### # Internal functions: manipulating the UI ################################################################### .tkplot.select.menu <- function(tkp.id, main.menu) { select.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(select.menu, "command", label="Select all vertices", command=function() { .tkplot.deselect.all(tkp.id) .tkplot.select.all.vertices(tkp.id) }) tcltk::tkadd(select.menu, "command", label="Select all edges", command=function() { .tkplot.deselect.all(tkp.id) .tkplot.select.all.edges(tkp.id) }) tcltk::tkadd(select.menu, "command", label="Select some vertices...", command=function() { vids <- .tkplot.get.numeric.vector("Select vertices") .tkplot.select.some.vertices(tkp.id, vids[[1]]) }) tcltk::tkadd(select.menu, "command", label="Select some edges...", command=function() { fromto <- .tkplot.get.numeric.vector("Select edges from vertices", "to vertices") .tkplot.select.some.edges(tkp.id, fromto[[1]], fromto[[2]]) }) tcltk::tkadd(select.menu, "separator") tcltk::tkadd(select.menu, "command", label="Deselect everything", command=function() { .tkplot.deselect.all(tkp.id) }) select.menu } .tkplot.layout.menu <- function(tkp.id, main.menu) { layout.menu <- tcltk::tkmenu(main.menu) sapply(.tkplot.getlayoutlist(), function(n) { tcltk::tkadd(layout.menu, "command", label=.tkplot.getlayoutname(n), command=function() { .tkplot.layout.dialog(tkp.id, n) }) }) layout.menu } .tkplot.layout.dialog <- function(tkp.id, layout.name) { layout <- .tkplot.getlayout(layout.name) # No parameters if (length(layout$params)==0) { return(tk_reshape(tkp.id, layout$f, params=list())) } submit <- function() { realparams <- params <- vector(mode="list", length(layout$params)) names(realparams) <- names(params) <- names(layout$params) for (i in seq(along=layout$params)) { realparams[[i]] <- params[[i]] <- switch(layout$params[[i]]$type, "numeric"=as.numeric(tcltk::tkget(values[[i]])), "character"=as.character(tcltk::tkget(values[[i]])), "logical"=as.logical(tcltk::tclvalue(values[[i]])), "choice"=as.character(tcltk::tclvalue(values[[i]])), "initial"=as.logical(tcltk::tclvalue(values[[i]])), "expression"=as.numeric(tcltk::tkget(values[[i]])) ) if (layout$params[[i]]$type=="initial" && params[[i]]) { realparams[[i]] <- tk_coords(tkp.id, norm=TRUE) } } if (as.logical(tcltk::tclvalue(save.default))) { .tkplot.layouts.newdefaults(layout.name, params) } tcltk::tkdestroy(dialog) tk_reshape(tkp.id, layout$f, params=realparams) } dialog <- tcltk::tktoplevel(.tkplot.get(tkp.id, "top")) tcltk::tkwm.title(dialog, paste("Layout parameters for graph plot", tkp.id)) tcltk::tkwm.transient(dialog, .tkplot.get(tkp.id, "top")) tcltk::tkgrid(tcltk::tklabel(dialog, text=paste(layout$name, "layout"), font=tcltk::tkfont.create(family="helvetica",size=20,weight="bold")), row=0, column=0, columnspan=2, padx=10, pady=10) row <- 1 values <- list() for (i in seq(along=layout$params)) { tcltk::tkgrid(tcltk::tklabel(dialog, text=paste(sep="", layout$params[[i]]$name, ":")), row=row, column=0, sticky="ne", padx=5, pady=5) if (layout$params[[i]]$type %in% c("numeric", "character")) { values[[i]] <- tcltk::tkentry(dialog) tcltk::tkinsert(values[[i]], 0, as.character(layout$params[[i]]$default)) tcltk::tkgrid(values[[i]], row=row, column=1, sticky="nw", padx=5, pady=5) } else if (layout$params[[i]]$type=="logical") { values[[i]] <- tcltk::tclVar(as.character(layout$params[[i]]$default)) tmp <- tcltk::tkcheckbutton(dialog, onvalue="TRUE", offvalue="FALSE", variable=values[[i]]) tcltk::tkgrid(tmp, row=row, column=1, sticky="nw", padx=5, pady=5) } else if (layout$params[[i]]$type=="choice") { tmp.frame <- tcltk::tkframe(dialog) tcltk::tkgrid(tmp.frame, row=row, column=1, sticky="nw", padx=5, pady=5) values[[i]] <- tcltk::tclVar(layout$params[[i]]$default) for (j in 1:length(layout$params[[i]]$values)) { tmp <- tcltk::tkradiobutton(tmp.frame, variable=values[[i]], value=layout$params[[i]]$values[j], text=layout$params[[i]]$values[j]) tcltk::tkpack(tmp, anchor="nw") } } else if (layout$params[[i]]$type=="initial") { values[[i]] <- tcltk::tclVar(as.character(layout$params[[i]]$default)) tcltk::tkgrid(tcltk::tkcheckbutton(dialog, onvalue="TRUE", offvalue="FALSE", variable=values[[i]]), row=row, column=1, sticky="nw", padx=5, pady=5) } else if (layout$param[[i]]$type=="expression") { values[[i]] <- tcltk::tkentry(dialog) .tkplot.g <- .tkplot.get(tkp.id, "graph") tcltk::tkinsert(values[[i]], 0, as.character(eval(layout$params[[i]]$default))) tcltk::tkgrid(values[[i]], row=row, column=1, sticky="nw", padx=5, pady=5) } row <- row + 1 } # for along layout$params tcltk::tkgrid(tcltk::tklabel(dialog, text="Set these as defaults"), sticky="ne", row=row, column=0, padx=5, pady=5) save.default <- tcltk::tclVar("FALSE") tcltk::tkgrid(tcltk::tkcheckbutton(dialog, onvalue="TRUE", offvalue="FALSE", variable=save.default, text=""), row=row, column=1, sticky="nw", padx=5, pady=5) row <- row + 1 tcltk::tkgrid(tcltk::tkbutton(dialog, text="OK", command=submit), row=row, column=0) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Cancel", command=function() { tcltk::tkdestroy(dialog); invisible(TRUE) }), row=row, column=1) } .tkplot.select.color <- function(initialcolor) { color <- tcltk::tclvalue(tcltk::tcl("tk_chooseColor", initialcolor=initialcolor, title="Choose a color")) return(color); } ################################################################### # Internal functions: other ################################################################### #' @importFrom grDevices palette .tkplot.convert.color <- function(col) { if (is.numeric(col)) { ## convert numeric color based on current palette p <- palette() col <- col %% length(p) col[col==0] <- length(p) col <- palette()[col] } else if (is.character(col) && any(substr(col,1,1)=="#" & nchar(col)==9)) { ## drop alpha channel, tcltk doesn't support it idx <- substr(col,1,1)=="#" & nchar(col)==9 col[idx] <- substr(col[idx],1,7) } ## replace NA's with "" col[is.na(col)] <- "" col } .tkplot.convert.font <- function(font, family, cex) { tk.fonts <- as.character(tcltk::tkfont.names()) if (as.character(font) %in% tk.fonts) { ## already defined Tk font as.character(font) } else { ## we create a font from familiy, font & cex font <- as.numeric(font) family <- as.character(family) cex <- as.numeric(cex) ## multiple sizes if (length(cex) > 1) { return(sapply(cex, .tkplot.convert.font, font=font, family=family)) } ## set slant & weight if (font==2) { slant <- "roman" weight <- "bold" } else if (font==3) { slant <- "italic" weight <- "normal" } else if (font==4) { slant <- "italic" weight <- "bold" } else { slant <- "roman" weight <- "normal" } ## set tkfamily if (family=="symbol" || font==5) { tkfamily <- "symbol" } else if (family=="serif") { tkfamily <- "Times" } else if (family=="sans") { tkfamily <- "Helvetica" } else if (family=="mono") { tkfamily <- "Courier" } else { ## pass the family and see what happens tkfamily <- family } newfont <- tcltk::tkfont.create(family=tkfamily, slant=slant, weight=weight, size=as.integer(12*cex)) as.character(newfont) } } i.tkplot.get.edge.lty <- function(edge.lty) { if (is.numeric(edge.lty)) { lty <- c( " ", "", "-", ".", "-.", "--", "--.") edge.lty <- lty[edge.lty %% 7 + 1] } else if (is.character(edge.lty)) { wh <- edge.lty %in% c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash") lty <- c( " ", "", "-", ".", "-.", "--", "--.") names(lty) <- c("blank", "solid", "dashed", "dotted", "dotdash", "longdash", "twodash") edge.lty[wh] <- lty[ edge.lty[wh] ] } edge.lty } igraph/R/indexing.R0000644000175100001440000003772113177712334013715 0ustar hornikusers ## IGraph library. ## Copyright (C) 2010-2012 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA # Indexing of igraph graphs. # # Goals: # 1. flexible graph manipulation # 2. to be as close to the usual matrix and adjacency list semantics, # as possible # 3. simple # 4. fast # 5. orthogonal # # Rules: # - [ is about the existence of the edges. # - [ can be used for weights as well, if the graph is weighted. # - [[ is about adjacent vertices, and essentially works as an # adjacency list. # # Use cases: # - G[1,2] is there an edge from vertex 1 to vertex 2? # - G[1,1:3] are there edges from vertex 1 to vertices 1:3? # - G[1:2,1:3] are there adges from vertices 1:2 to vertices 1:3? # this returns a (possibly sparse) matrix. # - G[degree(G)==0,1:4] # logical vectors work # - G[1,-1] negative indices work # # - G[[1,]] adjacent vertices of 1 # - G[[,1]] adjacent predessors of 1 # - G[[degree(G),]] # logical vectors work # - G[[-1,]] negative indices work # # - G[1,2,attr="value"] # query an edge attribute # - G[1:3,2,eid=TRUE] # create an edge sequence #' Query and manipulate a graph as it were an adjacency matrix #' #' @details #' The single bracket indexes the (possibly weighted) adjacency matrix of #' the graph. Here is what you can do with it: #' #' \enumerate{ #' \item Check whether there is an edge between two vertices (\eqn{v} #' and \eqn{w}) in the graph: \preformatted{ graph[v, w]} #' A numeric scalar is returned, one if the edge exists, zero #' otherwise. #' \item Extract the (sparse) adjacency matrix of the graph, or part of #' it: \preformatted{ graph[] #' graph[1:3,5:6] #' graph[c(1,3,5),]} #' The first variants returns the full adjacency matrix, the other #' two return part of it. #' \item The \code{from} and \code{to} arguments can be used to check #' the existence of many edges. In this case, both \code{from} and #' \code{to} must be present and they must have the same length. They #' must contain vertex ids or names. A numeric vector is returned, of #' the same length as \code{from} and \code{to}, it contains ones #' for existing edges edges and zeros for non-existing ones. #' Example: \preformatted{ graph[from=1:3, to=c(2,3,5)]}. #' \item For weighted graphs, the \code{[} operator returns the edge #' weights. For non-esistent edges zero weights are returned. Other #' edge attributes can be queried as well, by giving the \code{attr} #' argument. #' \item Querying edge ids instead of the existance of edges or edge #' attributes. E.g. \preformatted{ graph[1, 2, edges=TRUE]} #' returns the id of the edge between vertices 1 and 2, or zero if #' there is no such edge. #' \item Adding one or more edges to a graph. For this the element(s) of #' the imaginary adjacency matrix must be set to a non-zero numeric #' value (or \code{TRUE}): \preformatted{ graph[1, 2] <- 1 #' graph[1:3,1] <- 1 #' graph[from=1:3, to=c(2,3,5)] <- TRUE} #' This does not affect edges that are already present in the graph, #' i.e. no multiple edges are created. #' \item Adding weighted edges to a graph. The \code{attr} argument #' contains the name of the edge attribute to set, so it does not #' have to be \sQuote{weight}: \preformatted{ graph[1, 2, attr="weight"]<- 5 #' graph[from=1:3, to=c(2,3,5)] <- c(1,-1,4)} #' If an edge is already present in the network, then only its #' weights or other attribute are updated. If the graph is already #' weighted, then the \code{attr="weight"} setting is implicit, and #' one does not need to give it explicitly. #' \item Deleting edges. The replacement syntax allow the deletion of #' edges, by specifying \code{FALSE} or \code{NULL} as the #' replacement value: \preformatted{ graph[v, w] <- FALSE} #' removes the edge from vertex \eqn{v} to vertex \eqn{w}. #' As this can be used to delete edges between two sets of vertices, #' either pairwise: \preformatted{ graph[from=v, to=w] <- FALSE} #' or not: \preformatted{ graph[v, w] <- FALSE } #' if \eqn{v} and \eqn{w} are vectors of edge ids or names. #' } #' #' \sQuote{\code{[}} allows logical indices and negative indices as well, #' with the usual R semantics. E.g. \preformatted{ graph[degree(graph)==0, 1] <- 1} #' adds an edge from every isolate vertex to vertex one, #' and \preformatted{ G <- make_empty_graph(10) #' G[-1,1] <- TRUE} #' creates a star graph. #' #' Of course, the indexing operators support vertex names, #' so instead of a numeric vertex id a vertex can also be given to #' \sQuote{\code{[}} and \sQuote{\code{[[}}. #' #' @param x The graph. #' @param i Index. Vertex ids or names or logical vectors. See details #' below. #' @param j Index. Vertex ids or names or logical vectors. See details #' below. #' @param ... Currently ignored. #' @param from A numeric or character vector giving vertex ids or #' names. Together with the \code{to} argument, it can be used to #' query/set a sequence of edges. See details below. This argument cannot #' be present together with any of the \code{i} and \code{j} arguments #' and if it is present, then the \code{to} argument must be present as #' well. #' @param to A numeric or character vector giving vertex ids or #' names. Together with the \code{from} argument, it can be used to #' query/set a sequence of edges. See details below. This argument cannot #' be present together with any of the \code{i} and \code{j} arguments #' and if it is present, then the \code{from} argument must be present as #' well. #' @param sparse Logical scalar, whether to return sparse matrices. #' @param edges Logical scalar, whether to return edge ids. #' @param drop Ignored. #' @param attr If not \code{NULL}, then it should be the name of an edge #' attribute. This attribute is queried and returned. #' @return A scalar or matrix. See details below. #' #' @family structural queries #' #' @method [ igraph #' @export `[.igraph` <- function(x, i, j, ..., from, to, sparse=igraph_opt("sparsematrices"), edges=FALSE, drop=TRUE, attr=if (is_weighted(x)) "weight" else NULL) { ## TODO: make it faster, don't need the whole matrix usually ################################################################ ## Argument checks if ((!missing(from) || !missing(to)) && (!missing(i) || !missing(j))) { stop("Cannot give 'from'/'to' together with regular indices") } if ((!missing(from) && missing(to)) || ( missing(from) && !missing(to))) { stop("Cannot give 'from'/'to' without the other") } if (!missing(from)) { if ((!is.numeric(from) && !is.character(from)) || any(is.na(from))) { stop("'from' must be a numeric or character vector without NAs") } if ((!is.numeric(to) && !is.character(to)) || any(is.na(to))) { stop("'to' must be a numeric or character vector without NAs") } if (length(from) != length(to)) { stop("'from' and 'to' must have the same length") } } ################################################################## if (!missing(from)) { res <- get.edge.ids(x, rbind(from, to), error=FALSE) if (edges) { ## nop } else if (!is.null(attr)) { if (any(res!=0)) { res[res!=0] <- edge_attr(x, attr, res[res!=0]) } } else { res <- as.logical(res)+0 } res } else if (missing(i) && missing(j)) { as_adj(x, sparse=sparse, attr=attr, edges=edges) } else if (missing(j)) { as_adj(x, sparse=sparse, attr=attr, edges=edges)[i,,drop=drop] } else if (missing(i)) { as_adj(x, sparse=sparse, attr=attr, edges=edges)[,j,drop=drop] } else { as_adj(x, sparse=sparse, attr=attr, edges=edges)[i,j,drop=drop] } } #' Query and manipulate a graph as it were an adjacency list #' #' @details #' The double bracket operator indexes the (imaginary) adjacency list #' of the graph. This can used for the following operations: #' \enumerate{ #' \item Querying the adjacent vertices for one or more #' vertices: \preformatted{ graph[[1:3,]] #' graph[[,1:3]]} #' The first form gives the successors, the second the predessors #' or the 1:3 vertices. (For undirected graphs they are equivalent.) #' \item Querying the incident edges for one or more vertices, #' if the \code{edges} argument is set to #' \code{TRUE}: \preformatted{ graph[[1:3, , edges=TRUE]] #' graph[[, 1:3, edges=TRUE]]} #' \item Querying the edge ids between two sets or vertices, #' if both indices are used. E.g. \preformatted{ graph[[v, w, edges=TRUE]]} #' gives the edge ids of all the edges that exist from vertices #' \eqn{v} to vertices \eqn{w}. #' } #' #' The alternative argument names \code{from} and \code{to} can be used #' instead of the usual \code{i} and \code{j}, to make the code more #' readable: \preformatted{ graph[[from = 1:3]] #' graph[[from = v, to = w, edges = TRUE]]} #' #' \sQuote{\code{[[}} operators allows logical indices and negative indices #' as well, with the usual R semantics. #' #' Vertex names are also supported, so instead of a numeric vertex id a #' vertex can also be given to \sQuote{\code{[}} and \sQuote{\code{[[}}. #' #' @param x The graph. #' @param i Index, integer, character or logical, see details below. #' @param j Index, integer, character or logical, see details below. #' @param from A numeric or character vector giving vertex ids or #' names. Together with the \code{to} argument, it can be used to #' query/set a sequence of edges. See details below. This argument cannot #' be present together with any of the \code{i} and \code{j} arguments #' and if it is present, then the \code{to} argument must be present as #' well. #' @param to A numeric or character vector giving vertex ids or #' names. Together with the \code{from} argument, it can be used to #' query/set a sequence of edges. See details below. This argument cannot #' be present together with any of the \code{i} and \code{j} arguments #' and if it is present, then the \code{from} argument must be present as #' well. #' @param ... Additional arguments are not used currently. #' @param directed Logical scalar, whether to consider edge directions #' in directed graphs. It is ignored for undirected graphs. #' @param edges Logical scalar, whether to return edge ids. #' @param exact Ignored. #' #' @family structural queries #' #' @method [[ igraph #' @export `[[.igraph` <- function(x, i, j, from, to, ..., directed=TRUE, edges=FALSE, exact=TRUE) { getfun <- if (edges) as_adj_edge_list else as_adj_list if (!missing(i) && !missing(from)) stop("Cannot give both 'i' and 'from'") if (!missing(j) && !missing(to)) stop("Cannot give both 'j' and 'to'") if (missing(i) && ! missing(from)) i <- from if (missing(j) && ! missing(to)) j <- to if (missing(i) && missing(j)) { mode <- if (directed) "out" else "all" getfun(x, mode=mode) } else if (missing(j)) { mode <- if (directed) "out" else "all" if (!edges) { adjacent_vertices(x, i, mode = if (directed) "out" else "all") } else { incident_edges(x, i, mode = if (directed) "out" else "all") } } else if (missing(i)) { if (!edges) { adjacent_vertices(x, j, mode = if (directed) "in" else "all") } else { incident_edges(x, j, mode = if (directed) "in" else "all") } } else { if (!edges) { mode <- if (directed) "out" else "all" lapply(adjacent_vertices(x, i, mode = mode), intersection, V(x)[j]) } else { i <- as.igraph.vs(x, i) j <- as.igraph.vs(x, j) mode <- if (directed) "out" else "all" ee <- incident_edges(x, i, mode = mode) lapply(seq_along(i), function(yy) { from <- i[yy] el <- ends(x, ee[[yy]], names = FALSE) other <- ifelse(el[,1]==from, el[,2], el[,1]) ee[[yy]][other %in% j] }) } } } #' @method [<- igraph #' @family functions for manipulating graph structure #' @export `[<-.igraph` <- function(x, i, j, ..., from, to, attr=if (is_weighted(x)) "weight" else NULL, value) { ## TODO: rewrite this in C to make it faster ################################################################ ## Argument checks if ((!missing(from) || !missing(to)) && (!missing(i) || !missing(j))) { stop("Cannot give 'from'/'to' together with regular indices") } if ((!missing(from) && missing(to)) || ( missing(from) && !missing(to))) { stop("Cannot give 'from'/'to' without the other") } if (is.null(attr) && (!is.null(value) && !is.numeric(value) && !is.logical(value))) { stop("New value should be NULL, numeric or logical") } if (is.null(attr) && !is.null(value) && length(value) != 1) { stop("Logical or numeric value must be of length 1") } if (!missing(from)) { if ((!is.numeric(from) && !is.character(from)) || any(is.na(from))) { stop("'from' must be a numeric or character vector without NAs") } if ((!is.numeric(to) && !is.character(to)) || any(is.na(to))) { stop("'to' must be a numeric or character vector without NAs") } if (length(from) != length(to)) { stop("'from' and 'to' must have the same length") } } ################################################################## if (!missing(from)) { if (is.null(value) || (is.logical(value) && !value) || (is.null(attr) && is.numeric(value) && value==0)) { ## Delete edges todel <- x[from=from, to=to, ..., edges=TRUE] x <- delete_edges(x, todel) } else { ## Addition or update of an attribute (or both) ids <- x[from=from, to=to, ..., edges=TRUE] if (any(ids==0)) { x <- add_edges(x, rbind(from[ids==0], to[ids==0])) } if (!is.null(attr)) { ids <- x[from=from, to=to, ..., edges=TRUE] x <- set_edge_attr(x, attr, ids, value=value) } } } else if (is.null(value) || (is.logical(value) && !value) || (is.null(attr) && is.numeric(value) && value==0)) { ## Delete edges if (missing(i) && missing(j)) { todel <- unlist(x[[ , , ..., edges=TRUE]]) } else if (missing(j)) { todel <- unlist(x[[i, , ..., edges=TRUE]]) } else if (missing(i)) { todel <- unlist(x[[ , j, ..., edges=TRUE]]) } else { todel <- unlist(x[[i, j, ..., edges=TRUE]]) } x <- delete_edges(x, todel) } else { ## Addition or update of an attribute (or both) i <- if (missing(i)) as.numeric(V(x)) else as.igraph.vs(x, i) j <- if (missing(j)) as.numeric(V(x)) else as.igraph.vs(x, j) if (length(i) != 0 && length(j) != 0) { ## Existing edges, and their endpoints exe <- lapply(x[[i, j, ..., edges=TRUE]], as.vector) exv <- lapply(x[[i, j, ...]], as.vector) toadd <- unlist(lapply(seq_along(exv), function(idx) { to <- setdiff(j, exv[[idx]]) if (length(to!=0)) { rbind(i[idx], setdiff(j, exv[[idx]])) } else { numeric() } })) ## Do the changes if (is.null(attr)) { x <- add_edges(x, toadd) } else { x <- add_edges(x, toadd, attr=structure(list(value), names=attr)) toupdate <- unlist(exe) x <- set_edge_attr(x, attr, toupdate, value) } } } x } igraph/R/auto.R.in0000644000175100001440000000000013177712334013441 0ustar hornikusersigraph/R/sparsedf.R0000644000175100001440000000613313177712334013710 0ustar hornikusers # IGraph R package # Copyright (C) 2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### # This is a sparse data frame. It is like a regular data frame, # but it allows for some columns to be constant, and then it # stores that column more economically. sdf <- function(..., row.names = NULL, NROW = NULL) { cols <- list(...) if (is.null(names(cols)) || any(names(cols) == "") || any(duplicated(names(cols)))) { stop("Columns must be have (unique) names") } lens <- sapply(cols, length) n1lens <- lens[ lens != 1 ] if (length(unique(n1lens)) > 1) { stop("Columns must be constants or have the same length") } if (length(n1lens) == 0) { if (is.null(NROW)) { stop("Cannot determine number of rows") } attr(cols, "NROW") <- NROW } else { if (!is.null(NROW) && n1lens[1] != NROW) { stop("NROW does not match column lengths") } attr(cols, "NROW") <- unname(n1lens[1]) } class(cols) <- "igraphSDF" attr(cols, "row.names") <- row.names cols } #' @method as.data.frame igraphSDF as.data.frame.igraphSDF <- function(x, row.names, optional, ...) { as.data.frame(lapply(x, rep, length.out=attr(x, "NROW"))) } #' @method "[" igraphSDF `[.igraphSDF` <- function(x, i, j, ..., drop=TRUE) { if (!is.character(j)) { stop("The column index must be character") } if (!missing(i) && !is.numeric(i)) { stop("The row index must be numeric") } if (missing(i)) { rep(x[[j]], length.out=attr(x, "NROW")) } else { if (length(x[[j]])==1) { rep(x[[j]], length(i)) } else { x[[j]][i] } } } #' @method "[<-" igraphSDF `[<-.igraphSDF` <- function(x, i, j, value) { if (!is.character(j)) { stop("The column index must be character") } if (!missing(i) && !is.numeric(i)) { stop("Row index must be numeric, if given") } if (missing(i)) { if (length(value) != attr(x, "NROW") && length(value) != 1) { stop("Replacement value has the wrong length") } x[[j]] <- value } else { if (length(value) != length(i) && length(value) != 1) { stop("Replacement value has the wrong length") } tmp <- rep(x[[j]], length=attr(x, "NROW")) tmp[i] <- value if (length(unique(tmp)) == 1) { tmp <- tmp[1] } x[[j]] <- tmp } x } igraph/R/cohesive.blocks.R0000644000175100001440000005262313240142531015152 0ustar hornikusers# IGraph R package # Copyright (C) 2010-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Calculate Cohesive Blocks #' #' Calculates cohesive blocks for objects of class \code{igraph}. #' #' Cohesive blocking is a method of determining hierarchical subsets of graph #' vertices based on their structural cohesion (or vertex connectivity). For a #' given graph \eqn{G}, a subset of its vertices \eqn{S\subset V(G)}{S} is said #' to be maximally \eqn{k}-cohesive if there is no superset of \eqn{S} with #' vertex connectivity greater than or equal to \eqn{k}. Cohesive blocking is a #' process through which, given a \eqn{k}-cohesive set of vertices, maximally #' \eqn{l}-cohesive subsets are recursively identified with \eqn{l>k}. Thus a #' hiearchy of vertex subsets is found, whith the entire graph \eqn{G} at its #' root. #' #' The function \code{cohesive_blocks} implements cohesive blocking. It #' returns a \code{cohesiveBlocks} object. \code{cohesiveBlocks} should be #' handled as an opaque class, i.e. its internal structure should not be #' accessed directly, but through the functions listed here. #' #' The function \code{length} can be used on \code{cohesiveBlocks} objects and #' it gives the number of blocks. #' #' The function \code{blocks} returns the actual blocks stored in the #' \code{cohesiveBlocks} object. They are returned in a list of numeric #' vectors, each containing vertex ids. #' #' The function \code{graphs_from_cohesive_blocks} is similar, but returns the blocks as #' (induced) subgraphs of the input graph. The various (graph, vertex and edge) #' attributes are kept in the subgraph. #' #' The function \code{cohesion} returns a numeric vector, the cohesion of the #' different blocks. The order of the blocks is the same as for the #' \code{blocks} and \code{graphs_from_cohesive_blocks} functions. #' #' The block hierarchy can be queried using the \code{hierarchy} function. It #' returns an igraph graph, its vertex ids are ordered according the order of #' the blocks in the \code{blocks} and \code{graphs_from_cohesive_blocks}, \code{cohesion}, #' etc. functions. #' #' \code{parent} gives the parent vertex of each block, in the block hierarchy, #' for the root vertex it gives 0. #' #' \code{plot_hierarchy} plots the hierarchy tree of the cohesive blocks on the #' active graphics device, by calling \code{igraph.plot}. #' #' The \code{export_pajek} function can be used to export the graph and its #' cohesive blocks in Pajek format. It can either export a single Pajek project #' file with all the information, or a set of files, depending on its #' \code{project.file} argument. If \code{project.file} is \code{TRUE}, then #' the following information is written to the file (or connection) given in #' the \code{file} argument: (1) the input graph, together with its attributes, #' see \code{\link{write_graph}} for details; (2) the hierarchy graph; and (3) #' one binary partition for each cohesive block. If \code{project.file} is #' \code{FALSE}, then the \code{file} argument must be a character scalar and #' it is used as the base name for the generated files. If \code{file} is #' \sQuote{basename}, then the following files are created: (1) #' \sQuote{basename.net} for the original graph; (2) #' \sQuote{basename_hierarchy.net} for the hierarchy graph; (3) #' \sQuote{basename_block_x.net} for each cohesive block, where \sQuote{x} is #' the number of the block, starting with one. #' #' \code{max_cohesion} returns the maximal cohesion of each vertex, i.e. the #' cohesion of the most cohesive block of the vertex. #' #' The generic function \code{summary} works on \code{cohesiveBlocks} objects #' and it prints a one line summary to the terminal. #' #' The generic function \code{print} is also defined on \code{cohesiveBlocks} #' objects and it is invoked automatically if the name of the #' \code{cohesiveBlocks} object is typed in. It produces an output like this: #' \preformatted{ Cohesive block structure: #' B-1 c 1, n 23 #' '- B-2 c 2, n 14 oooooooo.. .o......oo ooo #' '- B-4 c 5, n 7 ooooooo... .......... ... #' '- B-3 c 2, n 10 ......o.oo o.oooooo.. ... #' '- B-5 c 3, n 4 ......o.oo o......... ... } #' The left part shows the block structure, in this case for five #' blocks. The first block always corresponds to the whole graph, even if its #' cohesion is zero. Then cohesion of the block and the number of vertices in #' the block are shown. The last part is only printed if the display is wide #' enough and shows the vertices in the blocks, ordered by vertex ids. #' \sQuote{o} means that the vertex is included, a dot means that it is not, #' and the vertices are shown in groups of ten. #' #' The generic function \code{plot} plots the graph, showing one or more #' cohesive blocks in it. #' #' @aliases cohesive.blocks cohesiveBlocks blocks graphs_from_cohesive_blocks blockGraphs #' hierarchy parent plotHierarchy export_pajek maxcohesion plot.cohesiveBlocks #' summary.cohesiveBlocks length.cohesiveBlocks print.cohesiveBlocks #' plot_hierarchy max_cohesion exportPajek #' @param graph For \code{cohesive_blocks} a graph object of class #' \code{igraph}. It must be undirected and simple. (See #' \code{\link{is_simple}}.) #' #' For \code{graphs_from_cohesive_blocks} and \code{export_pajek} the same graph must be #' supplied whose cohesive block structure is given in the \code{blocks} #' argument. #' @param labels Logical scalar, whether to add the vertex labels to the result #' object. These labels can be then used when reporting and plotting the #' cohesive blocks. #' @param blocks,x,object A \code{cohesiveBlocks} object, created with the #' \code{cohesive_blocks} function. #' @param file Defines the file (or connection) the Pajek file is written to. #' #' If the \code{project.file} argument is \code{TRUE}, then it can be a #' filename (with extension), a file object, or in general any king of #' connection object. The file/connection will be opened if it wasn't already. #' #' If the \code{project.file} argument is \code{FALSE}, then several files are #' created and \code{file} must be a character scalar containing the base name #' of the files, without extension. (But it can contain the path to the files.) #' #' See also details below. #' @param project.file Logical scalar, whether to create a single Pajek project #' file containing all the data, or to create separated files for each item. #' See details below. #' @param y The graph whose cohesive blocks are supplied in the \code{x} #' argument. #' @param colbar Color bar for the vertex colors. Its length should be at least #' \eqn{m+1}, where \eqn{m} is the maximum cohesion in the graph. #' Alternatively, the vertex colors can also be directly specified via the #' \code{col} argument. #' @param col A vector of vertex colors, in any of the usual formats. (Symbolic #' color names (e.g. \sQuote{red}, \sQuote{blue}, etc.) , RGB colors (e.g. #' \sQuote{#FF9900FF}), integer numbers referring to the current palette. By #' default the given \code{colbar} is used and vertices with the same maximal #' cohesion will have the same color. #' @param mark.groups A list of vertex sets to mark on the plot by circling #' them. By default all cohesive blocks are marked, except the one #' corresponding to the all vertices. #' @param layout The layout of a plot, it is simply passed on to #' \code{plot.igraph}, see the possible formats there. By default the #' Reingold-Tilford layout generator is used. #' @param \dots Additional arguments. \code{plot_hierarchy} and \code{plot} pass #' them to \code{plot.igraph}. \code{print} and \code{summary} ignore them. #' @return \code{cohesive_blocks} returns a \code{cohesiveBlocks} object. #' #' \code{blocks} returns a list of numeric vectors, containing vertex ids. #' #' \code{graphs_from_cohesive_blocks} returns a list of igraph graphs, corresponding to the #' cohesive blocks. #' #' \code{cohesion} returns a numeric vector, the cohesion of each block. #' #' \code{hierarchy} returns an igraph graph, the representation of the cohesive #' block hierarchy. #' #' \code{parent} returns a numeric vector giving the parent block of each #' cohesive block, in the block hierarchy. The block at the root of the #' hierarchy has no parent and \code{0} is returned for it. #' #' \code{plot_hierarchy}, \code{plot} and \code{export_pajek} return \code{NULL}, #' invisibly. #' #' \code{max_cohesion} returns a numeric vector with one entry for each vertex, #' giving the cohesion of its most cohesive block. #' #' \code{print} and \code{summary} return the \code{cohesiveBlocks} object #' itself, invisibly. #' #' \code{length} returns a numeric scalar, the number of blocks. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} for the current #' implementation, Peter McMahan (\url{http://home.uchicago.edu/~mcmahan/}) #' wrote the first version in R. #' @seealso \code{\link{cohesion}} #' @references J. Moody and D. R. White. Structural cohesion and embeddedness: #' A hierarchical concept of social groups. \emph{American Sociological #' Review}, 68(1):103--127, Feb 2003. #' @export #' @keywords graphs #' @examples #' #' ## The graph from the Moody-White paper #' mw <- graph_from_literal(1-2:3:4:5:6, 2-3:4:5:7, 3-4:6:7, 4-5:6:7, #' 5-6:7:21, 6-7, 7-8:11:14:19, 8-9:11:14, 9-10, #' 10-12:13, 11-12:14, 12-16, 13-16, 14-15, 15-16, #' 17-18:19:20, 18-20:21, 19-20:22:23, 20-21, #' 21-22:23, 22-23) #' #' mwBlocks <- cohesive_blocks(mw) #' #' # Inspect block membership and cohesion #' mwBlocks #' blocks(mwBlocks) #' cohesion(mwBlocks) #' #' # Save results in a Pajek file #' \dontrun{ #' export_pajek(mwBlocks, mw, file="/tmp/mwBlocks.paj") #' } #' #' # Plot the results #' plot(mwBlocks, mw) #' #' ## The science camp network #' camp <- graph_from_literal(Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, #' Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, #' Holly - Carol:Pat:Pam:Jennie:Bill, #' Bill - Pauline:Michael:Lee:Holly, #' Pauline - Bill:Jennie:Ann, #' Jennie - Holly:Michael:Lee:Ann:Pauline, #' Michael - Bill:Jennie:Ann:Lee:John, #' Ann - Michael:Jennie:Pauline, #' Lee - Michael:Bill:Jennie, #' Gery - Pat:Steve:Russ:John, #' Russ - Steve:Bert:Gery:John, #' John - Gery:Russ:Michael) #' campBlocks <- cohesive_blocks(camp) #' campBlocks #' #' plot(campBlocks, camp, vertex.label=V(camp)$name, margin=-0.2, #' vertex.shape="rectangle", vertex.size=24, vertex.size2=8, #' mark.border=1, colbar=c(NA, NA,"cyan","orange") ) #' cohesive_blocks <- function(graph, labels=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_cohesive_blocks, graph) class(res) <- "cohesiveBlocks" if (labels && "name" %in% vertex_attr_names(graph)) { res$labels <- V(graph)$name } if (igraph_opt("return.vs.es")) { res$blocks <- lapply(res$blocks, create_vs, graph = graph) } res$vcount <- vcount(graph) res } #' @rdname cohesive_blocks #' @method length cohesiveBlocks #' @export length.cohesiveBlocks <- function(x) { length(x$blocks) } #' @rdname cohesive_blocks #' @export blocks <- function(blocks) { blocks$blocks } #' @rdname cohesive_blocks #' @export graphs_from_cohesive_blocks <- function(blocks, graph) { lapply(blocks(blocks), induced_subgraph, graph=graph) } #' @export cohesion <- function(x, ...) UseMethod("cohesion") #' @rdname cohesive_blocks #' @method cohesion cohesiveBlocks #' @export cohesion.cohesiveBlocks <- function(x, ...) { x$cohesion } #' @rdname cohesive_blocks #' @export hierarchy <- function(blocks) { blocks$blockTree } #' @rdname cohesive_blocks #' @export parent <- function(blocks) { blocks$parent } #' @rdname cohesive_blocks #' @method print cohesiveBlocks #' @export print.cohesiveBlocks <- function(x, ...) { cat("Cohesive block structure:\n") myb <- blocks(x) ch <- cohesion(x) pp <- parent(x) si <- sapply(myb, length) cs <- 3 + 2 + nchar(length(x)) + max(distances(hierarchy(x), mode="out", v=1)) * 3 .plot <- function(b, ind="") { if (b!=1) { he <- format(paste(sep="", ind, "'- B-", b), width=cs) ind <- paste(" ", ind) } else { he <- format(paste(sep="", "B-", b), width=cs) } cat(sep="", he, "c ", format(ch[b], width=nchar(max(ch)), justify="right"), ", n ", format(si[b], width=nchar(x$vcount), justify="right")) if (x$vcount <= options("width")$width-40 && b != 1) { o <- rep(".", x$vcount) o[ myb[[b]] ] <- "o" oo <- character() for (i in 1:floor(x$vcount/10)) { oo <- c(oo, o[((i-1)*10+1):(i*10)], " ") } if (x$vcount %% 10) { oo <- c(oo, o[(i*10+1):length(o)]) } cat(" ", paste(oo, collapse=""), "\n") } else { cat("\n") } wc <- which(pp==b) sapply(wc, .plot, ind=ind) } if (length(x) >0) .plot(1) else cat("No cohesive blocks found.") invisible(x) } #' @rdname cohesive_blocks #' @method summary cohesiveBlocks #' @export summary.cohesiveBlocks <- function(object, ...) { cat("Structurally cohesive block structure, with", length(blocks(object)), "blocks.\n") invisible(object) } #' @rdname cohesive_blocks #' @method plot cohesiveBlocks #' @export #' @importFrom grDevices rainbow #' @importFrom graphics plot plot.cohesiveBlocks <- function(x, y, colbar=rainbow(max(cohesion(x))+1), col=colbar[max_cohesion(x)+1], mark.groups=blocks(x)[-1], ...) { plot(y, mark.groups=mark.groups, vertex.color=col, ...) } #' @rdname cohesive_blocks #' @export #' @importFrom graphics plot plot_hierarchy <- function(blocks, layout=layout_as_tree(hierarchy(blocks), root=1), ...) { plot(hierarchy(blocks), layout=layout, ...) } exportPajek.cohesiveblocks.pf <- function(blocks, graph, file) { closeit <- FALSE if (is.character(file)) { file <- file(file, open = "w+b") closeit <- TRUE } if (!isOpen(file)) { file <- open(file) closeit <- TRUE } ## The original graph cat(file=file, sep="", "*Network cohesive_blocks_input.net\r\n") write_graph(graph, file=file, format="pajek") ## The hierarchy graph cat(file=file, sep="", "\r\n*Network hierarchy.net\r\n") write_graph(hierarchy(blocks), file=file, format="pajek") ## The blocks myb <- blocks(blocks) for (b in seq_along(myb)) { thisb <- rep(0, vcount(graph)) thisb[ myb[[b]] ] <- 1 cat(file=file, sep="", "\r\n*Partition block_", b, ".clu\r\n", "*Vertices ", vcount(graph), "\r\n ") cat(thisb, sep="\r\n ", file=file) } if (closeit) { close(file) } invisible(NULL) } exportPajek.cohesiveblocks.nopf <- function(blocks, graph, file) { ## The original graph write_graph(graph, file=paste(sep="", file, ".net"), format="pajek") ## The hierarchy graph write_graph(hierarchy(blocks), file=paste(sep="", file, "_hierarchy.net"), format="pajek") ## The blocks myb <- blocks(blocks) for (b in seq_along(myb)) { thisb <- rep(0, vcount(graph)) thisb[ myb[[b]] ] <- 1 cat(file=paste(sep="", file, "_block_", b, ".clu"), sep="\r\n", paste("*Vertices", vcount(graph)), thisb) } invisible(NULL) } #' @rdname cohesive_blocks #' @export export_pajek <- function(blocks, graph, file, project.file=TRUE) { if (!project.file && !is.character(file)) { stop(paste("`file' must be a filename (without extension) when writing", "to separate files")) } if (project.file) { return(exportPajek.cohesiveblocks.pf(blocks, graph, file)) } else { return(exportPajek.cohesiveblocks.nopf(blocks, graph, file)) } } #' @rdname cohesive_blocks #' @export max_cohesion <- function(blocks) { res <- numeric(blocks$vcount) myb <- blocks(blocks) coh <- cohesion(blocks) oo <- order(coh) myb <- myb[oo] coh <- coh[oo] for (b in seq_along(myb)) { res[ myb[[b]] ] <- coh[b] } res } ######################################################### ## Various designs to print the cohesive blocks ## Cohesive block structure: ## B-1 c. 1, n. 34 ## '- B-2 c. 2, n. 28 1,2,3,4,8,9,10,13,14,15,16,18,19,20,21,22, ## | 23,24,25,26,27,28,29,30,31,32,33,34 ## '- B-4 c. 4, n. 5 1,2,3,4,8 ## '- B-5 c. 3, n. 7 1,2,3,9,31,33,34 ## '- B-7 c. 4, n. 5 1,2,3,4,14 ## '- B-8 c. 3, n. 10 3,24,25,26,28,29,30,32,33,34 ## '- B-3 c. 2, n. 6 1,5,6,7,11,17 ## '- B-6 c. 3, n. 5 1,5,6,7,11 ## Cohesive block structure: ## B-1 c. 1, n. 23 ## '- B-2 c. 2, n. 14 1,2,3,4,5,6,7,8,12,19,20,21,22,23 ## '- B-4 c. 5, n. 7 1,2,3,4,5,6,7 ## '- B-3 c. 2, n. 10 7,9,10,11,13,14,15,16,17,18 ## '- B-5 c. 3, n. 4 7,9,10,11 ## ######################################################### ## Cohesive block structure: ## B-1 c 1, n 34 ## '- B-2 c 2, n 28 oooo...ooo ..oooo.ooo oooooooooo oooo ## '- B-4 c 4, n 5 oooo...o.. .......... .......... .... ## '- B-5 c 3, n 7 ooo.....o. .......... .......... o.oo ## '- B-7 c 4, n 5 oooo...... ...o...... .......... .... ## '- B-8 c 3, n 10 ..o....... .......... ...ooo.ooo .ooo ## '- B-3 c 2, n 6 o...ooo... o.....o... .......... .... ## '- B-6 c 3, n 5 o...ooo... o......... .......... .... ## Cohesive block structure: ## B-1 c 1, n 23 oooooooooo oooooooooo ooo ## '- B-2 c 2, n 14 oooooooo.. .o......oo ooo ## '- B-4 c 5, n 7 ooooooo... .......... ... ## '- B-3 c 2, n 10 ......o.oo o.oooooo.. ... ## '- B-5 c 3, n 4 ......o.oo o......... ... ## ######################################################### ## Cohesive block structure: ## B-1 c. 1, n. 34 ## '- B-2 c. 2, n. 28 1, 2, 3, 4, 8, 9,10,13,14,15,16,18,19,20,21, ## | 22,23,24,25,26,27,28,29,30,31,32,33,34 ## '- B-4 c. 4, n. 5 1, 2, 3, 4, 8 ## '- B-5 c. 3, n. 7 1, 2, 3, 9,31,33,34 ## '- B-7 c. 4, n. 5 1, 2, 3, 4,14 ## '- B-8 c. 3, n. 10 3,24,25,26,28,29,30,32,33,34 ## '- B-3 c. 2, n. 6 1, 5, 6, 7,11,17 ## '- B-6 c. 3, n. 5 1, 5, 6, 7,11 ## Cohesive block structure: ## B-1 c. 1, n. 23 ## '- B-2 c. 2, n. 14 1, 2, 3, 4, 5, 6, 7, 8,12,19,20,21,22,23 ## '- B-4 c. 5, n. 7 1, 2, 3, 4, 5, 6, 7 ## '- B-3 c. 2, n. 10 7, 9,10,11,13,14,15,16,17,18 ## '- B-5 c. 3, n. 4 7, 9,10,11 ## ######################################################### ## Cohesive block structure: ## B-1 c. 1, n. 34 ## '- B-2 c. 2, n. 28 1-4, 8-10, 13-16, 18-34 ## '- B-4 c. 4, n. 5 1-4, 8 ## '- B-5 c. 3, n. 7 1-3, 9, 31, 33-34 ## '- B-7 c. 4, n. 5 1-4, 14 ## '- B-8 c. 3, n. 10 3, 24-26, 28-30, 32-34 ## '- B-3 c. 2, n. 6 1, 5-7, 11, 17 ## '- B-6 c. 3, n. 5 1, 5-7, 11 ## Cohesive block structure: ## B-1 c. 1, n. 23 ## '- B-2 c. 2, n. 14 1-8, 12, 19-23 ## '- B-4 c. 5, n. 7 1-7 ## '- B-3 c. 2, n. 10 7, 9-11, 13-18 ## '- B-5 c. 3, n. 4 7, 9-11 ## ########################################################## ## Cohesive block structure: ## B-1 c. 1, n. 34 ## |- B-2 c. 2, n. 28 [ 1] oooo...ooo ..oooo.ooo ## | | [21] oooooooooo oooo ## | |- B-4 c. 4, n. 5 [ 1] oooo...o.. .......... ## | | [21] .......... .... ## | |- B-5 c. 3, n. 7 [ 1] ooo.....o. .......... ## | | [21] .......... o.oo ## | |- B-7 c. 4, n. 5 [ 1] oooo...... ...o...... ## | | [21] .......... .... ## | |- B-8 c. 3, n. 10 [ 1] ..o....... .......... ## | [21] ...ooo.ooo .ooo ## '- B-3 c. 2, n. 6 [ 1] o...ooo... o.....o... ## | [21] .......... .... ## '- B-6 c. 3, n. 5 [ 1] o...ooo... o......... ## [21] .......... .... ## Cohesive block structure: ## B-1 c. 1, n. 23 [ 1] oooooooooo oooooooooo ## | [21] ooo ## |- B-2 c. 2, n. 14 [ 1] oooooooo.. .o......oo ## | | [21] ooo ## | '- B-4 c. 5, n. 7 [ 1] ooooooo... .......... ## | [21] ... ## '- B-3 c. 2, n. 10 [ 1] ......o.oo o.oooooo.. ## | [21] ... ## '- B-5 c. 3, n. 4 [ 1] ......o.oo o......... ## [21] ... igraph/R/topology.R0000644000175100001440000007720013177712334013760 0ustar hornikusers # IGraph R package # Copyright (C) 2006-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' @export graph.get.isomorphisms.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_get_isomorphisms_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) lapply(res, function(x) V(graph2)[x + 1]) } #' @export graph.get.subisomorphisms.vf2 <- function(graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) { # Argument checks if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } if (missing(vertex.color1)) { if ("color" %in% vertex_attr_names(graph1)) { vertex.color1 <- V(graph1)$color } else { vertex.color1 <- NULL } } if (!is.null(vertex.color1)) { vertex.color1 <- as.integer(vertex.color1)-1L } if (missing(vertex.color2)) { if ("color" %in% vertex_attr_names(graph2)) { vertex.color2 <- V(graph2)$color } else { vertex.color2 <- NULL } } if (!is.null(vertex.color2)) { vertex.color2 <- as.integer(vertex.color2)-1L } if (missing(edge.color1)) { if ("color" %in% edge_attr_names(graph1)) { edge.color1 <- E(graph1)$color } else { edge.color1 <- NULL } } if (!is.null(edge.color1)) { edge.color1 <- as.integer(edge.color1)-1L } if (missing(edge.color2)) { if ("color" %in% edge_attr_names(graph2)) { edge.color2 <- E(graph2)$color } else { edge.color2 <- NULL } } if (!is.null(edge.color2)) { edge.color2 <- as.integer(edge.color2)-1L } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_get_subisomorphisms_vf2, graph1, graph2, vertex.color1, vertex.color2, edge.color1, edge.color2) lapply(res, function(x) V(graph1)[x + 1]) } #' @export graph.isoclass.subgraph <- function(graph, vids) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids)-1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_isoclass_subgraph, graph, vids) res } #' @export graph.subisomorphic.lad <- function(pattern, target, domains=NULL, induced=FALSE, map=TRUE, all.maps=FALSE, time.limit=Inf) { # Argument checks if (!is_igraph(pattern)) { stop("Not a graph object") } if (!is_igraph(target)) { stop("Not a graph object") } induced <- as.logical(induced) if (time.limit==Inf) { time.limit <- 0L } else { time.limit <- as.integer(time.limit) } map <- as.logical(map) all.maps <- as.logical(all.maps) if (!is.null(domains)) { if (!is.list(domains)) { stop("`domains' must be a list of vertex vectors from `target'") } if (length(domains) != vcount(pattern)) { stop("`domains' length and `pattern' number of vertices must match") } domains <- lapply(domains, function(x) as.igraph.vs(target, x)-1) } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_subisomorphic_lad, pattern, target, domains, induced, time.limit, map, all.maps) if (map) { res$map <- res$map + 1 if (igraph_opt("add.vertex.names") && is_named(target)) { names(res$map) <- V(target)$name[res$map] } } if (all.maps) res$maps <- lapply(res$maps, function(x) V(target)[x+1]) res } ## ---------------------------------------------------------------------- ## NEW API #' Decide if two graphs are isomorphic #' #' @section \sQuote{auto} method: #' It tries to select the appropriate method based on the two graphs. #' This is the algorithm it uses: #' \enumerate{ #' \item If the two graphs do not agree on their order and size #' (i.e. number of vertices and edges), then return \code{FALSE}. #' \item If the graphs have three or four vertices, then the #' \sQuote{direct} method is used. #' \item If the graphs are directed, then the \sQuote{vf2} method is #' used. #' \item Otherwise the \sQuote{bliss} method is used. #' } #' #' @section \sQuote{direct} method: #' This method only works on graphs with three or four vertices, #' and it is based on a pre-calculated and stored table. It does not #' have any extra arguments. #' #' @section \sQuote{vf2} method: #' This method uses the VF2 algorithm by Cordella, Foggia et al., see #' references below. It supports vertex and edge colors and have the #' following extra arguments: #' \describe{ #' \item{vertex.color1, vertex.color2}{Optional integer vectors giving the #' colors of the vertices for colored graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} vertex attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments. See also examples #' below.} #' \item{edge.color1, edge.color2}{Optional integer vectors giving the #' colors of the edges for edge-colored (sub)graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} edge attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments.} #' } #' #' @section \sQuote{bliss} method: #' Uses the BLISS algorithm by Junttila and Kaski, and it works for #' undirected graphs. For both graphs the #' \code{\link{canonical_permutation}} and then the \code{\link{permute}} #' function is called to transfer them into canonical form; finally the #' canonical forms are compared. #' Extra arguments: #' \describe{ #' \item{sh1}{Character constant, the heuristics to use in the BLISS #' algorithm, for \code{graph1}. See the \code{sh} argument of #' \code{\link{canonical_permutation}} for possible values.} #' \item{sh2}{Character constant, the heuristics to use in the BLISS #' algorithm, for \code{graph2}. See the \code{sh} argument of #' \code{\link{canonical_permutation}} for possible values.} #' } #' \code{sh1} and \code{sh2} default to \sQuote{fm}. #' #' @param graph1 The first graph. #' @param graph2 The second graph. #' @param method The method to use. Possible values: \sQuote{auto}, #' \sQuote{direct}, \sQuote{vf2}, \sQuote{bliss}. See their details #' below. #' @param ... Additional arguments, passed to the various methods. #' @return Logical scalar, \code{TRUE} if the graphs are isomorphic. #' #' @aliases graph.isomorphic graph.isomorphic.34 graph.isomorphic.vf2 #' graph.isomorphic.bliss #' #' @references #' Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical #' Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of the #' Ninth Workshop on Algorithm Engineering and Experiments and the Fourth #' Workshop on Analytic Algorithms and Combinatorics.} 2007. #' #' LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm #' for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop #' on Graphbased Representations in Pattern Recognition}, 149--159, 2001. #' #' @export #' @family graph isomorphism #' @examples #' # create some non-isomorphic graphs #' g1 <- graph_from_isomorphism_class(3, 10) #' g2 <- graph_from_isomorphism_class(3, 11) #' isomorphic(g1, g2) #' #' # create two isomorphic graphs, by permuting the vertices of the first #' g1 <- barabasi.game(30, m=2, directed=FALSE) #' g2 <- permute(g1, sample(vcount(g1))) #' # should be TRUE #' isomorphic(g1, g2) #' isomorphic(g1, g2, method = "bliss") #' isomorphic(g1, g2, method = "vf2") #' #' # colored graph isomorphism #' g1 <- make_ring(10) #' g2 <- make_ring(10) #' isomorphic(g1, g2) #' #' V(g1)$color <- rep(1:2, length = vcount(g1)) #' V(g2)$color <- rep(2:1, length = vcount(g2)) #' # consider colors by default #' count_isomorphisms(g1, g2) #' # ignore colors #' count_isomorphisms(g1, g2, vertex.color1 = NULL, #' vertex.color2 = NULL) isomorphic <- function(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...) { if (!is_igraph(graph1)) { stop("Not a graph object") } if (!is_igraph(graph2)) { stop("Not a graph object") } method <- igraph.match.arg(method) if (method == "auto") { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_isomorphic, graph1, graph2) } else if (method == "direct") { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_isomorphic_34, graph1, graph2) } else if (method == "vf2") { graph.isomorphic.vf2(graph1, graph2, ...)$iso } else if (method == "bliss") { graph.isomorphic.bliss(graph1, graph2, ...)$iso } } #' @export #' @rdname isomorphic #' @inheritParams isomorphic is_isomorphic_to <- isomorphic #' Decide if a graph is subgraph isomorphic to another one #' #' @section \sQuote{auto} method: #' This method currently selects \sQuote{lad}, always, as it seems #' to be superior on most graphs. #' #' @section \sQuote{lad} method: #' This is the LAD algorithm by Solnon, see the reference below. It has #' the following extra arguments: #' \describe{ #' \item{domains}{If not \code{NULL}, then it specifies matching #' restrictions. It must be a list of \code{target} vertex sets, given #' as numeric vertex ids or symbolic vertex names. The length of the #' list must be \code{vcount(pattern)} and for each vertex in #' \code{pattern} it gives the allowed matching vertices in #' \code{target}. Defaults to \code{NULL}.} #' \item{induced}{Logical scalar, whether to search for an induced #' subgraph. It is \code{FALSE} by default.} #' \item{time.limit}{The processor time limit for the computation, in #' seconds. It defaults to \code{Inf}, which means no limit.} #' } #' #' @section \sQuote{vf2} method: #' This method uses the VF2 algorithm by Cordella, Foggia et al., see #' references below. It supports vertex and edge colors and have the #' following extra arguments: #' \describe{ #' \item{vertex.color1, vertex.color2}{Optional integer vectors giving the #' colors of the vertices for colored graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} vertex attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments. See also examples #' below.} #' \item{edge.color1, edge.color2}{Optional integer vectors giving the #' colors of the edges for edge-colored (sub)graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} edge attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments.} #' } #' #' @param pattern The smaller graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param target The bigger graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param method The method to use. Possible values: \sQuote{auto}, #' \sQuote{lad}, \sQuote{vf2}. See their details below. #' @param ... Additional arguments, passed to the various methods. #' @return Logical scalar, \code{TRUE} if the \code{pattern} is #' isomorphic to a (possibly induced) subgraph of \code{target}. #' #' @aliases graph.subisomorphic.vf2 graph.subisomorphic.lad #' #' @references #' LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm #' for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop #' on Graphbased Representations in Pattern Recognition}, 149--159, 2001. #' #' C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, #' \emph{Artificial Intelligence} 174(12-13):850--864, 2010. #' #' @export #' @family graph isomorphism #' @examples #' # A LAD example #' pattern <- make_graph(~ 1:2:3:4:5, #' 1 - 2:5, 2 - 1:5:3, 3 - 2:4, 4 - 3:5, 5 - 4:2:1) #' target <- make_graph(~ 1:2:3:4:5:6:7:8:9, #' 1 - 2:5:7, 2 - 1:5:3, 3 - 2:4, 4 - 3:5:6:8:9, #' 5 - 1:2:4:6:7, 6 - 7:5:4:9, 7 - 1:5:6, #' 8 - 4:9, 9 - 6:4:8) #' domains <- list(`1` = c(1,3,9), `2` = c(5,6,7,8), `3` = c(2,4,6,7,8,9), #' `4` = c(1,3,9), `5` = c(2,4,8,9)) #' subgraph_isomorphisms(pattern, target) #' subgraph_isomorphisms(pattern, target, induced = TRUE) #' subgraph_isomorphisms(pattern, target, domains = domains) #' #' # Directed LAD example #' pattern <- make_graph(~ 1:2:3, 1 -+ 2:3) #' dring <- make_ring(10, directed = TRUE) #' subgraph_isomorphic(pattern, dring) subgraph_isomorphic <- function(pattern, target, method = c("auto", "lad", "vf2"), ...) { method <- igraph.match.arg(method) if (method == "auto") method <- "lad" if (method == "lad") { graph.subisomorphic.lad(pattern, target, map = FALSE, all.maps = FALSE, ...)$iso } else if (method == "vf2") { graph.subisomorphic.vf2(target, pattern, ...)$iso } } #' @export #' @rdname subgraph_isomorphic #' @inheritParams subgraph_isomorphic is_subgraph_isomorphic_to <- subgraph_isomorphic #' Count the number of isomorphic mappings between two graphs #' #' @param graph1 The first graph. #' @param graph2 The second graph. #' @param method Currently only \sQuote{vf2} is supported, see #' \code{\link{isomorphic}} for details about it and extra arguments. #' @param ... Passed to the individual methods. #' @return Number of isomirphic mappings between the two graphs. #' #' @include auto.R #' @aliases graph.count.isomorphisms.vf2 #' #' @references #' LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm #' for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop #' on Graphbased Representations in Pattern Recognition}, 149--159, 2001. #' #' @export #' @family graph isomorphism #' @examples #' # colored graph isomorphism #' g1 <- make_ring(10) #' g2 <- make_ring(10) #' isomorphic(g1, g2) #' #' V(g1)$color <- rep(1:2, length = vcount(g1)) #' V(g2)$color <- rep(2:1, length = vcount(g2)) #' # consider colors by default #' count_isomorphisms(g1, g2) #' # ignore colors #' count_isomorphisms(g1, g2, vertex.color1 = NULL, #' vertex.color2 = NULL) count_isomorphisms <- function(graph1, graph2, method = "vf2", ...) { method <- igraph.match.arg(method) if (method == "vf2") { graph.count.isomorphisms.vf2(graph1, graph2, ...) } } #' Count the isomorphic mappings between a graph and the subgraphs of #' another graph #' #' @section \sQuote{lad} method: #' This is the LAD algorithm by Solnon, see the reference below. It has #' the following extra arguments: #' \describe{ #' \item{domains}{If not \code{NULL}, then it specifies matching #' restrictions. It must be a list of \code{target} vertex sets, given #' as numeric vertex ids or symbolic vertex names. The length of the #' list must be \code{vcount(pattern)} and for each vertex in #' \code{pattern} it gives the allowed matching vertices in #' \code{target}. Defaults to \code{NULL}.} #' \item{induced}{Logical scalar, whether to search for an induced #' subgraph. It is \code{FALSE} by default.} #' \item{time.limit}{The processor time limit for the computation, in #' seconds. It defaults to \code{Inf}, which means no limit.} #' } #' #' @section \sQuote{vf2} method: #' This method uses the VF2 algorithm by Cordella, Foggia et al., see #' references below. It supports vertex and edge colors and have the #' following extra arguments: #' \describe{ #' \item{vertex.color1, vertex.color2}{Optional integer vectors giving the #' colors of the vertices for colored graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} vertex attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments. See also examples #' below.} #' \item{edge.color1, edge.color2}{Optional integer vectors giving the #' colors of the edges for edge-colored (sub)graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} edge attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments.} #' } #' #' @param pattern The smaller graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param target The bigger graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param method The method to use. Possible values: #' \sQuote{lad}, \sQuote{vf2}. See their details below. #' @param ... Additional arguments, passed to the various methods. #' @return Logical scalar, \code{TRUE} if the \code{pattern} is #' isomorphic to a (possibly induced) subgraph of \code{target}. #' #' @aliases graph.count.subisomorphisms.vf2 #' #' @references #' LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm #' for matching large graphs, \emph{Proc. of the 3rd IAPR TC-15 Workshop #' on Graphbased Representations in Pattern Recognition}, 149--159, 2001. #' #' C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, #' \emph{Artificial Intelligence} 174(12-13):850--864, 2010. #' #' @export #' @family graph isomorphism count_subgraph_isomorphisms <- function(pattern, target, method = c("lad", "vf2"), ...) { method <- igraph.match.arg(method) if (method == "lad") { length(graph.subisomorphic.lad(pattern, target, all.maps = TRUE, ...)$maps) } else if (method == "vf2") { graph.count.subisomorphisms.vf2(target, pattern, ...) } } #' Calculate all isomorphic mappings between the vertices of two graphs #' #' @param graph1 The first graph. #' @param graph2 The second graph. #' @param method Currently only \sQuote{vf2} is supported, see #' \code{\link{isomorphic}} for details about it and extra arguments. #' @param ... Extra arguments, passed to the various methods. #' @return A list of vertex sequences, corresponding to all #' mappings from the first graph to the second. #' #' @aliases graph.get.isomorphisms.vf2 #' #' @export #' @family graph isomorphism isomorphisms <- function(graph1, graph2, method = "vf2", ...) { method <- igraph.match.arg(method) if (method == "vf2") { graph.get.isomorphisms.vf2(graph1, graph2, ...) } } #' All isomorphic mappings between a graph and subgraphs of another graph #' #' @section \sQuote{lad} method: #' This is the LAD algorithm by Solnon, see the reference below. It has #' the following extra arguments: #' \describe{ #' \item{domains}{If not \code{NULL}, then it specifies matching #' restrictions. It must be a list of \code{target} vertex sets, given #' as numeric vertex ids or symbolic vertex names. The length of the #' list must be \code{vcount(pattern)} and for each vertex in #' \code{pattern} it gives the allowed matching vertices in #' \code{target}. Defaults to \code{NULL}.} #' \item{induced}{Logical scalar, whether to search for an induced #' subgraph. It is \code{FALSE} by default.} #' \item{time.limit}{The processor time limit for the computation, in #' seconds. It defaults to \code{Inf}, which means no limit.} #' } #' #' @section \sQuote{vf2} method: #' This method uses the VF2 algorithm by Cordella, Foggia et al., see #' references below. It supports vertex and edge colors and have the #' following extra arguments: #' \describe{ #' \item{vertex.color1, vertex.color2}{Optional integer vectors giving the #' colors of the vertices for colored graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} vertex attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments. See also examples #' below.} #' \item{edge.color1, edge.color2}{Optional integer vectors giving the #' colors of the edges for edge-colored (sub)graph isomorphism. If they #' are not given, but the graph has a \dQuote{color} edge attribute, #' then it will be used. If you want to ignore these attributes, then #' supply \code{NULL} for both of these arguments.} #' } #' #' @param pattern The smaller graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param target The bigger graph, it might be directed or #' undirected. Undirected graphs are treated as directed graphs with #' mutual edges. #' @param method The method to use. Possible values: \sQuote{auto}, #' \sQuote{lad}, \sQuote{vf2}. See their details below. #' @param ... Additional arguments, passed to the various methods. #' @return A list of vertex sequences, corresponding to all #' mappings from the first graph to the second. #' #' @aliases graph.get.subisomorphisms.vf2 #' #' @export #' @family graph isomorphism subgraph_isomorphisms <- function(pattern, target, method = c("lad", "vf2"), ...) { method <- igraph.match.arg(method) if (method == "lad") { graph.subisomorphic.lad(pattern, target, all.maps = TRUE, ...)$maps } else if (method == "vf2") { graph.get.subisomorphisms.vf2(target, pattern, ...) } } #' Isomorphism class of a graph #' #' The isomorphism class is a non-negative integer number. #' Graphs (with the same number of vertices) having the same isomorphism #' class are isomorphic and isomorphic graphs always have the same #' isomorphism class. Currently it can handle only graphs with 3 or 4 #' vertices. #' #' @param graph The input graph. #' @param v Optionally a vertex sequence. If not missing, then an induced #' subgraph of the input graph, consisting of this vertices, is used. #' @return An integer number. #' #' @aliases graph.isoclass graph.isoclass.subgraph #' #' @export #' @family graph isomorphism #' @examples #' # create some non-isomorphic graphs #' g1 <- graph_from_isomorphism_class(3, 10) #' g2 <- graph_from_isomorphism_class(3, 11) #' isomorphism_class(g1) #' isomorphism_class(g2) #' isomorphic(g1, g2) isomorphism_class <- function(graph, v) { if (missing(v)) { graph.isoclass(graph) } else { graph.isoclass.subgraph(graph, v) } } #' Create a graph from an isomorphism class #' #' The isomorphism class is a non-negative integer number. #' Graphs (with the same number of vertices) having the same isomorphism #' class are isomorphic and isomorphic graphs always have the same #' isomorphism class. Currently it can handle only graphs with 3 or 4 #' vertices. #' #' @param size The number of vertices in the graph. #' @param number The isomorphism class. #' @param directed Whether to create a directed graph (the default). #' @return An igraph object, the graph of the given size, directedness #' and isomorphism class. #' #' @aliases graph.isocreate #' @include auto.R #' #' @family graph isomorphism graph_from_isomorphism_class <- graph_from_isomorphism_class #' Canonical permutation of a graph #' #' The canonical permutation brings every isomorphic graphs into the same #' (labeled) graph. #' #' \code{canonical_permutation} computes a permutation which brings the graph #' into canonical form, as defined by the BLISS algorithm. All isomorphic #' graphs have the same canonical form. #' #' See the paper below for the details about BLISS. This and more information #' is available at \url{http://www.tcs.hut.fi/Software/bliss/index.html}. #' #' The possible values for the \code{sh} argument are: \describe{ #' \item{"f"}{First non-singleton cell.} \item{"fl"}{First largest #' non-singleton cell.} \item{"fs"}{First smallest non-singleton cell.} #' \item{"fm"}{First maximally non-trivially connectec non-singleton #' cell.} \item{"flm"}{Largest maximally non-trivially connected #' non-singleton cell.} \item{"fsm"}{Smallest maximally non-trivially #' connected non-singleton cell.} } See the paper in references for details #' about these. #' #' @aliases canonical.permutation canonical_permutation #' @param graph The input graph, treated as undirected. #' @param sh Type of the heuristics to use for the BLISS algorithm. See details #' for possible values. #' @return A list with the following members: \item{labeling}{The canonical #' parmutation which takes the input graph into canonical form. A numeric #' vector, the first element is the new label of vertex 0, the second element #' for vertex 1, etc. } \item{info}{Some information about the BLISS #' computation. A named list with the following members: \describe{ #' \item{"nof_nodes"}{The number of nodes in the search tree.} #' \item{"nof_leaf_nodes"}{The number of leaf nodes in the search tree.} #' \item{"nof_bad_nodes"}{Number of bad nodes.} #' \item{"nof_canupdates"}{Number of canrep updates.} #' \item{"max_level"}{Maximum level.} \item{"group_size"}{The size #' of the automorphism group of the input graph, as a string. This number is #' exact if igraph was compiled with the GMP library, and approximate #' otherwise.} } } #' @author Tommi Junttila for BLISS, Gabor Csardi #' \email{csardi.gabor@@gmail.com} for the igraph and R interfaces. #' @seealso \code{\link{permute}} to apply a permutation to a graph, #' \code{\link{graph.isomorphic}} for deciding graph isomorphism, possibly #' based on canonical labels. #' @references Tommi Junttila and Petteri Kaski: Engineering an Efficient #' Canonical Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of #' the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth #' Workshop on Analytic Algorithms and Combinatorics.} 2007. #' @keywords graphs #' @examples #' #' ## Calculate the canonical form of a random graph #' g1 <- sample_gnm(10, 20) #' cp1 <- canonical_permutation(g1) #' cf1 <- permute(g1, cp1$labeling) #' #' ## Do the same with a random permutation of it #' g2 <- permute(g1, sample(vcount(g1))) #' cp2 <- canonical_permutation(g2) #' cf2 <- permute(g2, cp2$labeling) #' #' ## Check that they are the same #' el1 <- as_edgelist(cf1) #' el2 <- as_edgelist(cf2) #' el1 <- el1[ order(el1[,1], el1[,2]), ] #' el2 <- el2[ order(el2[,1], el2[,2]), ] #' all(el1 == el2) #' @export canonical_permutation <- canonical_permutation #' Permute the vertices of a graph #' #' Create a new graph, by permuting vertex ids. #' #' This function creates a new graph from the input graph by permuting its #' vertices according to the specified mapping. Call this function with the #' output of \code{\link{canonical_permutation}} to create the canonical form #' of a graph. #' #' \code{permute} keeps all graph, vertex and edge attributes of the graph. #' #' @aliases permute.vertices permute #' @param graph The input graph, it can directed or undirected. #' @param permutation A numeric vector giving the permutation to apply. The #' first element is the new id of vertex 1, etc. Every number between one and #' \code{vcount(graph)} must appear exactly once. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{canonical_permutation}} #' @keywords graphs #' @examples #' #' # Random permutation of a random graph #' g <- sample_gnm(20, 50) #' g2 <- permute(g, sample(vcount(g))) #' graph.isomorphic(g, g2) #' #' # Permutation keeps all attributes #' g$name <- "Random graph, Gnm, 20, 50" #' V(g)$name <- letters[1:vcount(g)] #' E(g)$weight <- sample(1:5, ecount(g), replace=TRUE) #' g2 <- permute(g, sample(vcount(g))) #' graph.isomorphic(g, g2) #' g2$name #' V(g2)$name #' E(g2)$weight #' all(sort(E(g2)$weight) == sort(E(g)$weight)) #' @export permute <- permute #' Number of automorphisms #' #' Calculate the number of automorphisms of a graph, i.e. the number of #' isomorphisms to itself. #' #' An automorphism of a graph is a permutation of its vertices which brings the #' graph into itself. #' #' This function calculates the number of automorphism of a graph using the #' BLISS algorithm. See also the BLISS homepage at #' \url{http://www.tcs.hut.fi/Software/bliss/index.html}. #' #' @aliases graph.automorphisms automorphisms #' @param graph The input graph, it is treated as undirected. #' @param sh The splitting heuristics for the BLISS algorithm. Possible values #' are: \sQuote{\code{f}}: first non-singleton cell, \sQuote{\code{fl}}: first #' largest non-singleton cell, \sQuote{\code{fs}}: first smallest non-singleton #' cell, \sQuote{\code{fm}}: first maximally non-trivially connected #' non-singleton cell, \sQuote{\code{flm}}: first largest maximally #' non-trivially connected non-singleton cell, \sQuote{\code{fsm}}: first #' smallest maximally non-trivially connected non-singleton cell. #' @return A named list with the following members: \item{group_size}{The size #' of the automorphism group of the input graph, as a string. This number is #' exact if igraph was compiled with the GMP library, and approximate #' otherwise.} \item{nof_nodes}{The number of nodes in the search tree.} #' \item{nof_leaf_nodes}{The number of leaf nodes in the search tree.} #' \item{nof_bad_nodes}{Number of bad nodes.} \item{nof_canupdates}{Number of #' canrep updates.} \item{max_level}{Maximum level.} #' @author Tommi Junttila (\url{http://users.ics.aalto.fi/tjunttil/}) for BLISS #' and Gabor Csardi \email{csardi.gabor@@gmail.com} for the igraph glue code #' and this manual page. #' @seealso \code{\link{canonical_permutation}}, \code{\link{permute}} #' @references Tommi Junttila and Petteri Kaski: Engineering an Efficient #' Canonical Labeling Tool for Large and Sparse Graphs, \emph{Proceedings of #' the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth #' Workshop on Analytic Algorithms and Combinatorics.} 2007. #' @keywords graphs #' @examples #' #' ## A ring has n*2 automorphisms, you can "turn" it by 0-9 vertices #' ## and each of these graphs can be "flipped" #' g <- make_ring(10) #' automorphisms(g) #' @export automorphisms <- automorphisms igraph/R/plot.common.R0000644000175100001440000015423013177712334014350 0ustar hornikusers# IGraph R package # Copyright (C) 2003-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Common functions for plot and tkplot ################################################################### i.parse.plot.params <- function(graph, params) { ## store the arguments p <- list(vertex=list(), edge=list(), plot=list()) for (n in names(params)) { if (substr(n, 1, 7)=="vertex.") { nn <- substring(n, 8) p[["vertex"]][[nn]] <- params[[n]] } else if (substr(n, 1, 5)=="edge.") { nn <- substring(n, 6) p[["edge"]][[nn]] <- params[[n]] } else { p[["plot"]][[n]] <- params[[n]] } } func <- function(type, name, range=NULL, dontcall=FALSE) { if (! type %in% names(p)) { stop("Invalid plot option type") } ret <- function() { v <- p[[type]][[name]] if (is.function(v) && !dontcall) { v <- v(graph) } if (is.null(range)) { return (v) } else { if (length(v)==1) { return(rep(v, length(range))) } else { return (rep(v, length=max(range)+1)[[range+1]]) } } } if (name %in% names(p[[type]])) { ## we already have the parameter return(ret()) } else { ## we don't have the parameter, check attributes first if (type=="vertex" && name %in% vertex_attr_names(graph)) { p[[type]][[name]] <- vertex_attr(graph, name) return(ret()) } else if (type=="edge" && name %in% edge_attr_names(graph)) { p[[type]][[name]] <- edge_attr(graph, name) return(ret()) } else if (type=="plot" && name %in% graph_attr_names(graph)) { p[[type]][[name]] <- graph_attr(graph, name) return(ret()) } else { ## no attributes either, check igraph parameters n <- paste(sep="", type, ".", name) v <- igraph_opt(n) if (!is.null(v)) { p[[type]][[name]] <- v return(ret()) } ## no igraph parameter either, use default value p[[type]][[name]] <- i.default.values[[type]][[name]] return(ret()) } } } return (func) } i.get.edge.labels <- function(graph, edge.labels=NULL) { if (is.null(edge.labels)) { edge.labels <- rep(NA, ecount(graph)) } edge.labels } i.get.labels <- function(graph, labels=NULL) { if (is.null(labels)) { if ("name" %in% vertex_attr_names(graph)) { labels <- vertex_attr(graph, "name") } else { labels <- seq_len(vcount(graph)) } } labels } i.get.arrow.mode <- function(graph, arrow.mode=NULL) { if (is.character(arrow.mode) && length(arrow.mode)==1 && substr(arrow.mode, 1, 2)=="a:") { arrow.mode <- vertex_attr(graph, substring(arrow.mode,3)) } if (is.character(arrow.mode)) { tmp <- numeric(length(arrow.mode)) tmp[ arrow.mode %in% c("<", "<-") ] <- 1 tmp[ arrow.mode %in% c(">", "->") ] <- 2 tmp[ arrow.mode %in% c("<>", "<->") ] <- 3 arrow.mode <- tmp } if (is.null(arrow.mode)) { if (is_directed(graph)) { arrow.mode <- 2 } else { arrow.mode <- 0 } } arrow.mode } i.get.main <- function(graph) { if (igraph_opt("annotate.plot")) { n <- graph$name[1] n } else { "" } } i.get.xlab <- function(graph) { if (igraph_opt("annotate.plot")) { paste(vcount(graph), "vertices,", ecount(graph), "edges") } else { "" } } igraph.check.shapes <- function(x) { xx <- unique(x) bad.shapes <- ! xx %in% ls(.igraph.shapes) if (any(bad.shapes)) { bs <- paste(xx[bad.shapes], collapse=", ") stop("Bad vertex shape(s): ", bs, ".") } x } #' Optimal edge curvature when plotting graphs #' #' If graphs have multiple edges, then drawing them as straight lines does not #' show them when plotting the graphs; they will be on top of each other. One #' solution is to bend the edges, with diffenent curvature, so that all of them #' are visible. #' #' \code{curve_multiple} calculates the optimal \code{edge.curved} vector for #' plotting a graph with multiple edges, so that all edges are visible. #' #' @aliases autocurve.edges #' @param graph The input graph. #' @param start The curvature at the two extreme edges. All edges will have a #' curvature between \code{-start} and \code{start}, spaced equally. #' @return A numeric vector, its length is the number of edges in the graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{igraph.plotting}} for all plotting parameters, #' \code{\link{plot.igraph}}, \code{\link{tkplot}} and \code{\link{rglplot}} #' for plotting functions. #' @export #' @importFrom stats ave #' @keywords graphs #' @examples #' #' g <- graph( c(0,1,1,0,1,2,1,3,1,3,1,3, #' 2,3,2,3,2,3,2,3,0,1)+1 ) #' #' curve_multiple(g) #' #' \dontrun{ #' set.seed(42) #' plot(g) #' } #' curve_multiple <- function(graph, start=0.5) { el <- apply(as_edgelist(graph, names=FALSE), 1, paste, collapse=":") ave(rep(NA, length(el)), el, FUN=function(x) { if (length(x) == 1) { return(0) } else { return(seq(-start, start, length=length(x))) } }) } .igraph.logo.raster <- structure(c(16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 311332508L, 1217499541L, 1804702102L, 1066570390L, 211129749L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 379033495L, 1334940052L, -2104389227L, -1450012011L, -2087546218L, 1368494484L, 412456341L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 41975936L, 1905496981L, -141388906L, -7171435L, -7171435L, -7171435L, -325938283L, 1452380564L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 41975936L, 1905496981L, -158166379L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -141389163L, 1972540052L, 41975936L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -2037148780L, -7171435L, -24798561L, -12009013L, -13250855L, -11616826L, -24340838L, -7171435L, 1586664085L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 311332508L, -963472747L, -7171435L, -7171435L, -7171435L, -7171435L, -7236971L, -7171435L, -7171435L, -7171435L, -7171435L, -946695531L, 361927314L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 798134930L, -40791403L, -25321308L, -16061704L, -16715521L, -16715521L, -16715521L, -15408144L, -24471653L, -258829418L, 344755353L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1483500650L, -7171435L, -7171435L, -7824996L, -12858668L, -15212050L, -16519427L, -15212050L, -12858668L, -7890531L, -7171435L, -7171435L, -1382903147L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 2056426132L, -7171435L, -13643043L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -12139572L, -7171435L, 1385337493L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1452380564L, -7171435L, -7171435L, -8936279L, -15800587L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -15865867L, -9132373L, -7171435L, -7171435L, 1485934996L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1433234795L, -7171435L, -15603981L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -14100510L, -7171435L, -2104389227L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -812412011L, -7171435L, -7432808L, -15080979L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -15277585L, -7498344L, -7171435L, -694971499L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1919774060L, -7171435L, -14623768L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -13120041L, -7171435L, 1704104597L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 177838489L, -74280299L, -7171435L, -10439750L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -10701380L, -7171435L, -40725867L, 211129749L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1368494484L, -7171435L, -10374471L, -16715521L, -16715521L, -16715521L, -16715521L, -16584963L, -9067350L, -7171435L, 714248856L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 999527315L, -7171435L, -7171435L, -12270386L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -12531503L, -7171435L, -7171435L, 1033015958L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, -1080913258L, -7171435L, -10701636L, -15277329L, -16519427L, -14885141L, -9720911L, -7171435L, -1718381676L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1217499541L, -7171435L, -7171435L, -12793389L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -13054505L, -7171435L, -7171435L, 1251053972L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 479367826L, -929918315L, -7171435L, -7171435L, -7236971L, -7171435L, -7171435L, -1366060139L, 227117469L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 361927314L, -7171435L, -7171435L, -10962753L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -11289661L, -7171435L, -7171435L, 412456341L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1536398230L, -7171435L, -778857580L, -1013804395L, -1752067691L, 1334940052L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -544042347L, -7171435L, -8086625L, -16061704L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16126983L, -8217439L, -7171435L, -426601835L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1097690475L, -23948651L, 579833750L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 76714645L, 1452446357L, -1986882923L, -1785556331L, 1720881813L, 361927317L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -2070703211L, -7171435L, -7171435L, -10570822L, -16649985L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16649985L, -10636101L, -7171435L, -7171435L, -2020503147L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 596808338L, -23948651L, -1114467692L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 747803285L, -829255019L, -7171435L, -7171435L, -7171435L, -7171435L, -326004074L, 1418891925L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 127046290L, -728591723L, -7171435L, -7171435L, -9786446L, -15603981L, -16715521L, -16715521L, -16715521L, -15538958L, -9655375L, -7171435L, -7171435L, -661482859L, 144678815L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -2053991786L, -7171435L, 1502778005L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 278041237L, -443444587L, -7171435L, -10963009L, -14492954L, -15015956L, -12335666L, -24340839L, -40725867L, 999461525L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 848598164L, -225275243L, -7171435L, -7171435L, -7171435L, -8347998L, -9720911L, -8348254L, -7171435L, -7171435L, -7171435L, -225275243L, 949129878L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 61516458L, -443379051L, -292384107L, 127046290L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1835887979L, -7171435L, -12008757L, -16715521L, -16715521L, -16715521L, -16715521L, -14492954L, -24013930L, -745368939L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 546279319L, -1114467692L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -1064136043L, 546279319L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1301451413L, -7171435L, -1835822188L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -795700587L, -24340838L, -16519427L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -9917004L, -7171435L, 361927317L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, 1469289365L, -1752067691L, -896363883L, -242052459L, -141389163L, -7171435L, -309095531L, 429496729L, 1301451413L, -2104389227L, -1215130987L, -879586667L, -1701670251L, 1704104597L, 798134930L, 75530368L, 16777215L, -1332571499L, -7171435L, 798134930L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -174943595L, -9067350L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -11420476L, -7171435L, 999461525L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1986948715L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -158166379L, -1517120875L, -74280299L, -879586667L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -812477803L, -24340839L, -16519427L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -9851469L, -7171435L, 328372885L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 261724569L, -1248685419L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7566182L, -8355679L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -1869376618L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1902996843L, -7171435L, -11681849L, -16715521L, -16715521L, -16715521L, -16715521L, -14166045L, -7236714L, -208498027L, 882086803L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1150456470L, -493710699L, -7171435L, -7171435L, -7303018L, -10789959L, -13026608L, -14934812L, -16513548L, -16645131L, -15921426L, -14013478L, -11973946L, -8618845L, -7171435L, -7171435L, -23948651L, -1768779114L, 144678815L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 227709589L, -544107883L, -7171435L, -10570822L, -13969951L, -14492954L, -11943478L, -24210280L, -23948651L, -7171435L, -23948651L, -1517186668L, 529831060L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 596808338L, -174943595L, -7171435L, -7171435L, -8684636L, -14605855L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16316174L, -11382080L, -7237226L, -7171435L, -7171435L, -1852665195L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 663917205L, -929918315L, -7171435L, -7171435L, -7171435L, -7171435L, -393112938L, 1284674197L, 1049661588L, -879586667L, -7171435L, -141389163L, -1986948715L, 261724569L, 16777215L, 16777215L, 16777215L, 41975936L, -1013804395L, -7171435L, -7171435L, -11184706L, -16316174L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -14342690L, -8158305L, -7171435L, -23948651L, 1066570390L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 59937429L, 1234342549L, 2140312213L, -1936551275L, 1486000789L, 294818453L, 16777215L, 16777215L, 33554431L, 1519621014L, -527265131L, -7171435L, -342715755L, 1821545109L, 93952409L, 16777215L, 1922142614L, -7171435L, -7171435L, -9868880L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -14210851L, -7237227L, -7171435L, -560819563L, 211129749L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 144678815L, 1989383061L, -258829675L, -7171435L, -644705643L, 1804767894L, -141389163L, -7171435L, -7829349L, -15658261L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -11184706L, -7171435L, -7171435L, -1785622123L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 344755353L, -1835822188L, -91057515L, -7171435L, -7171435L, -7171435L, -13289772L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16250383L, -8421470L, -7171435L, -292384107L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 647271572L, -409824619L, -7171435L, -7566183L, -16513548L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -11447872L, -7171435L, -7171435L, 613782933L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -460090475L, -7171435L, -9342293L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -13421357L, -7171435L, -7171435L, 1502778005L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 965907093L, -1785556331L, -879586667L, -158166379L, -695037291L, -1584229739L, 1435669141L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 412456341L, -7171435L, -7171435L, -11184706L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -15263513L, -7171435L, -7171435L, -1903062635L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 143823509L, -1936551275L, -40725867L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -1299017067L, 412258965L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1200853907L, -7171435L, -7171435L, -12895025L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16579339L, -7566183L, -7171435L, -1114467692L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1231908203L, -7171435L, -7171435L, -7171435L, -8282719L, -9655375L, -8544092L, -7236714L, -7171435L, -7171435L, -577596779L, 194155157L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 747737495L, -7171435L, -7171435L, -11908411L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -15987217L, -7171435L, -7171435L, -1483566443L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1720881813L, -7171435L, -7171435L, -8348254L, -14231324L, -16715521L, -16715521L, -16715521L, -15212050L, -9263188L, -7171435L, -7171435L, -1768779115L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 61516458L, -158166379L, -7171435L, -10000462L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -14145060L, -7171435L, -7171435L, -91057515L, -1315794284L, 1603375510L, 295081622L, 16777215L, 16777215L, 16777215L, 16777215L, 127046293L, -242052459L, -7171435L, -7629158L, -15538958L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16519427L, -8740442L, -7171435L, -23948651L, 747803285L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -963472747L, -7171435L, -8158305L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -12237111L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -74280299L, -1164865131L, 1754502038L, 412456341L, 16777215L, 915575445L, -7171435L, -7171435L, -12008757L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -13773857L, -7171435L, -7171435L, 1720881813L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1819110763L, -7171435L, -7171435L, -15263513L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -9868879L, -7171435L, -74280299L, 1368560277L, -1651338603L, -325938539L, -7171435L, -7171435L, -7171435L, -40725867L, -1013804395L, -1382903147L, -7171435L, -7171435L, -14100510L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16061960L, -7171435L, -7171435L, -1668115819L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1402180499L, -7171435L, -7171435L, -9539923L, -16579339L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -13816104L, -7171435L, -7171435L, -946695531L, 16777215L, 16777215L, 61516458L, 1116967831L, -1802333548L, -460090475L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -14558233L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16388613L, -7302250L, -7171435L, -1433234795L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1198353770L, -7171435L, -7171435L, -12500278L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -15987217L, -8092514L, -7171435L, -74280299L, 898666645L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, 949129878L, -1970105706L, -443379050L, -7171435L, -7171435L, -12793389L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -14558233L, -7171435L, -7171435L, 1972540053L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 479367826L, -258829675L, -7171435L, -7500391L, -14737438L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16447757L, -10263627L, -7171435L, -7171435L, -2070703211L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 294818453L, -23948651L, -7171435L, -8478812L, -16323334L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -9917005L, -7171435L, -7171435L, 1083347605L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1603375510L, -7171435L, -7171435L, -7434600L, -12237111L, -16513548L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -15000603L, -9013337L, -7171435L, -7171435L, -778923371L, 109084842L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1768779115L, -7171435L, -7171435L, -10178634L, -16061960L, -16715521L, -16715521L, -16715521L, -16388612L, -11224382L, -7171435L, -7171435L, -997027179L, 43160213L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, -728591723L, -7171435L, -7171435L, -7171435L, -9276502L, -14605855L, -16513549L, -16645131L, -16645131L, -16645131L, -16645131L, -16645131L, -15789843L, -12171320L, -7368809L, -7171435L, -7171435L, -376270187L, 781226134L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 194155157L, -577596779L, -7171435L, -7171435L, -7890531L, -10636100L, -12335666L, -11028288L, -8413533L, -7171435L, -7171435L, -174943595L, 613585557L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, 579833750L, 261724569L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 160337550L, -1416457579L, -7171435L, -7171435L, -124611948L, -7171435L, -7171435L, -7171435L, -7500391L, -9342293L, -11316288L, -12171320L, -10263627L, -8355679L, -7171435L, -7171435L, -7171435L, -7171435L, -1416457579L, 344755353L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 647139989L, -913141099L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -476933483L, 1150456469L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1184010901L, -1131244907L, -275606891L, -7171435L, -23948651L, -644705643L, -1768779114L, 311332508L, 16777215L, 16777215L, 16777215L, 16777215L, 379033495L, -929852523L, -7171435L, -23948651L, 2056426132L, 428838809L, -1282305642L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -325938539L, 1485934996L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 59937429L, 2039648917L, -711814507L, -40725867L, -7171435L, -7171435L, -510487915L, -1752001899L, 261264021L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 211129749L, -1701670251L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -426601835L, 1234408342L, 16777215L, 16777215L, 697274261L, -544042347L, -7171435L, -124611947L, 1485934996L, 16777215L, 16777215L, 16777215L, 1167365268L, -2137943659L, -1248619627L, -376270187L, -7171435L, -7171435L, -91057515L, -846032235L, -1752067691L, 1653772948L, 395350160L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 227709589L, 949129877L, 378704533L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1550741099L, -7171435L, -7171435L, -8021089L, -11616570L, -13446949L, -12662830L, -10178634L, -7171435L, -7171435L, -91057515L, 831689367L, 1133613460L, -275606891L, -7171435L, -342715755L, 999527315L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 529831060L, 865178006L, 144678815L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1368494484L, -7171435L, -7171435L, -9851725L, -15996425L, -16715521L, -16715521L, -16715521L, -16715521L, -13904672L, -7563622L, -7171435L, -476933483L, -91057514L, -7171435L, -644705643L, 613782933L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -846032235L, -7171435L, -8217439L, -16061704L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -12727853L, -7171435L, -7171435L, -7171435L, -1030581611L, 311332508L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 109084842L, -91057515L, -7171435L, -12139828L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16649985L, -7890531L, -7171435L, -695037291L, 109084842L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 831689367L, -7171435L, -7171435L, -13970208L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -9720911L, -7171435L, -1080913258L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 596808338L, -7171435L, -7171435L, -13512485L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -9197652L, -7171435L, -1299017067L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 33554431L, -258829675L, -7171435L, -11355453L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16192519L, -7498343L, -7171435L, 2089980564L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, -1265462635L, -7171435L, -7367273L, -14950677L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -16715521L, -10897730L, -7171435L, -7171435L, 1049661588L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 630296984L, -174943595L, -7171435L, -8086625L, -14100766L, -16715521L, -16715521L, -16715521L, -16323077L, -11028288L, -7171435L, -7171435L, -1550741099L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1821545109L, -7171435L, -7171435L, -7236971L, -8740186L, -10439750L, -9655375L, -7825252L, -7171435L, -7171435L, -476933483L, 277843855L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 1385337493L, -376270187L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -7171435L, -1332571499L, 395350160L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 344755353L, 1922142614L, -1533898091L, -728591723L, -1080913258L, -1903062635L, 1284805780L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L, 16777215L), .Dim = c(64L, 64L), class = "nativeRaster", channels = 4L) #' @include palette.R i.vertex.default <- list(color=1, size=15, size2=15, label=i.get.labels, label.degree=-pi/4, label.color="darkblue", label.dist=0, label.family="serif", label.font=1, label.cex=1, frame.color="black", shape="circle", pie=1, pie.color=list(c("white", "lightblue", "mistyrose", "lightcyan", "lavender", "cornsilk")), pie.border=list(c("white", "lightblue","mistyrose", "lightcyan", "lavender", "cornsilk")), pie.angle=45, pie.density=-1, pie.lty=1, raster=.igraph.logo.raster) i.edge.default <- list(color="darkgrey", label=i.get.edge.labels, lty=1, width=1, loop.angle=0, loop.angle2=0, label.family="serif", label.font=1, label.cex=1, label.color="darkblue", label.x=NULL, label.y=NULL, arrow.size=1, arrow.mode=i.get.arrow.mode, curved=curve_multiple, arrow.width=1) i.plot.default <- list(palette=categorical_pal(8), layout=layout_nicely, margin=c(0,0,0,0), rescale=TRUE, asp=1, frame=FALSE, main=i.get.main, sub="", xlab=i.get.xlab, ylab="") i.default.values <- new.env() i.default.values[["vertex"]] <- i.vertex.default i.default.values[["edge"]] <- i.edge.default i.default.values[["plot"]] <- i.plot.default igraph/R/layout.R0000644000175100001440000021533313247212322013410 0ustar hornikusers ## ---------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2003-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ---------------------------------------------------------------- ## ---------------------------------------------------------------- ## This is the new layout API ## ---------------------------------------------------------------- #' Graph layouts #' #' This is a generic function to apply a layout function to #' a graph. #' #' There are two ways to calculate graph layouts in igraph. #' The first way is to call a layout function (they all have #' prefix \code{layout_} on a graph, to get the vertex coordinates. #' #' The second way (new in igraph 0.8.0), has two steps, and it #' is more flexible. First you call a layout specification #' function (the one without the \code{layout_} prefix, and #' then \code{layout_} (or \code{\link{add_layout_}}) to #' perform the layouting. #' #' The second way is preferred, as it is more flexible. It allows #' operations before and after the layouting. E.g. using the #' \code{component_wise} argument, the layout can be calculated #' separately for each component, and then merged to get the #' final results. #' #' @aliases layout #' @section Modifiers: #' Modifiers modify how a layout calculation is performed. #' Currently implemented modifyers: \itemize{ #' \item \code{component_wise} calculates the layout separately #' for each component of the graph, and then merges #' them. #' \item \code{normalize} scales the layout to a square. #' } #' #' @param graph The input graph. #' @param layout The layout specification. It must be a call #' to a layout specification function. #' @param ... Further modifiers, see a complete list below. #' For the \code{print} methods, it is ignored. #' @return The return value of the layout function, usually a #' two column matrix. For 3D layouts a three column matrix. #' #' @seealso \code{\link{add_layout_}} to add the layout to the #' graph as an attribute. #' @export #' @family graph layouts #' @examples #' g <- make_ring(10) + make_full_graph(5) #' coords <- layout_(g, as_star()) #' plot(g, layout = coords) layout_ <- function(graph, layout, ...) { modifiers <- list(...) stopifnot(all(sapply(modifiers, inherits, what = "igraph_layout_modifier"))) ids <- sapply(modifiers, "[[", "id") stopifnot(all(ids %in% c("component_wise", "normalize"))) if (anyDuplicated(ids)) stop("Duplicate modifiers") names(modifiers) <- ids ## TODO: better, generic mechanism for modifiers if ("component_wise" %in% ids) { graph$id <- seq(vcount(graph)) comps <- decompose(graph) coords <- lapply(comps, function(comp) { do_call(layout$fun, list(graph = comp), layout$args) }) all_coords <- merge_coords( comps, coords, method = modifiers[["component_wise"]]$args$merge_method ) all_coords[ unlist(sapply(comps, vertex_attr, "id")), ] <- all_coords[] result <- all_coords } else { result <- do_call(layout$fun, list(graph = graph), layout$args) } if ("normalize" %in% ids) { result <- do_call(norm_coords, list(result), modifiers[["normalize"]]$args) } result } #' Add layout to graph #' #' @param graph The input graph. #' @param ... Additional arguments are passed to \code{\link{layout_}}. #' @param overwrite Whether to overwrite the layout of the graph, #' if it already has one. #' @return The input graph, with the layout added. #' #' @seealso \code{\link{layout_}} for a description of the layout API. #' @export #' @family graph layouts #' @examples #' (make_star(11) + make_star(11)) %>% #' add_layout_(as_star(), component_wise()) %>% #' plot() add_layout_ <- function(graph, ..., overwrite = TRUE) { if (overwrite && 'layout' %in% graph_attr_names(graph)) { graph <- delete_graph_attr(graph, 'layout') } graph$layout <- layout_(graph, ...) graph } layout_spec <- function(fun, ...) { my_call <- match.call(sys.function(1), sys.call(1)) my_call[[1]] <- substitute(fun) structure( list( fun = fun, call_str = sub("(", "(, ", deparse(my_call), fixed = TRUE), args = list(...) ), class = "igraph_layout_spec" ) } #' @rdname layout_ #' @param x The layout specification #' @method print igraph_layout_spec #' @export print.igraph_layout_spec <- function(x, ...) { cat(paste( sep = "", "igraph layout specification, see ?layout_:\n", x$call_str, "\n" )) } layout_modifier <- function(...) { structure( list(...), class = "igraph_layout_modifier" ) } #' @rdname layout_ #' @method print igraph_layout_modifier #' @export print.igraph_layout_modifier <- function(x, ...) { cat(sep = "", "igraph layout modifier: ", x$id, ".\n") } #' Component-wise layout #' #' This is a layout modifier function, and it can be used #' to calculate the layout separately for each component #' of the graph. #' #' @param merge_method Merging algorithm, the \code{method} #' argument of \code{\link{merge_coords}}. #' #' @family layout modifiers #' @family graph layouts #' @seealso \code{\link{merge_coords}}, \code{\link{layout_}}. #' @export #' @examples #' g <- make_ring(10) + make_ring(10) #' g %>% #' add_layout_(in_circle(), component_wise()) %>% #' plot() component_wise <- function(merge_method = "dla") { args <- grab_args() layout_modifier( id = "component_wise", args = args ) } #' Normalize layout #' #' Scale coordinates of a layout. #' #' @param xmin,xmax Minimum and maximum for x coordinates. #' @param ymin,ymax Minimum and maximum for y coordinates. #' @param zmin,zmax Minimum and maximum for z coordinates. #' #' @family layout modifiers #' @family graph layouts #' @seealso \code{\link{merge_coords}}, \code{\link{layout_}}. #' @export #' @examples #' layout_(make_ring(10), with_fr(), normalize()) normalize <- function(xmin = -1, xmax = 1, ymin = xmin, ymax = xmax, zmin = xmin, zmax = xmax) { args <- grab_args() layout_modifier( id = "normalize", args = args ) } ## ---------------------------------------------------------------- ## Layout definitions for the new API ## ---------------------------------------------------------------- #' Simple two-row layout for bipartite graphs #' #' Minimize edge-crossings in a simple two-row (or column) layout for bipartite #' graphs. #' #' The layout is created by first placing the vertices in two rows, according #' to their types. Then the positions within the rows are optimized to minimize #' edge crossings, using the Sugiyama algorithm (see #' \code{\link{layout_with_sugiyama}}). #' #' @aliases layout_as_bipartite layout.bipartite #' @param graph The bipartite input graph. It should have a logical #' \sQuote{\code{type}} vertex attribute, or the \code{types} argument must be #' given. #' @param types A logical vector, the vertex types. If this argument is #' \code{NULL} (the default), then the \sQuote{\code{type}} vertex attribute is #' used. #' @param hgap Real scalar, the minimum horizontal gap between vertices in the #' same layer. #' @param vgap Real scalar, the distance between the two layers. #' @param maxiter Integer scalar, the maximum number of iterations in the #' crossing minimization stage. 100 is a reasonable default; if you feel that #' you have too many edge crossings, increase this. #' @return A matrix with two columns and as many rows as the number of vertices #' in the input graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout_with_sugiyama}} #' @keywords graphs #' @export #' @family graph layouts #' @examples #' # Random bipartite graph #' inc <- matrix(sample(0:1, 50, replace = TRUE, prob=c(2,1)), 10, 5) #' g <- graph_from_incidence_matrix(inc) #' plot(g, layout = layout_as_bipartite, #' vertex.color=c("green","cyan")[V(g)$type+1]) #' #' # Two columns #' g %>% #' add_layout_(as_bipartite()) %>% #' plot() layout_as_bipartite <- function(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100) { ## Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { if (!is.logical(types)) { warning("vertex types converted to logical") } types <- as.logical(types) if (any(is.na(types))) { stop("`NA' is not allowed in vertex types") } } else { stop("Not a bipartite graph, supply `types' argument") } hgap <- as.numeric(hgap) vgap <- as.numeric(vgap) maxiter <- as.integer(maxiter) on.exit(.Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_layout_bipartite, graph, types, hgap, vgap, maxiter) res } #' @rdname layout_as_bipartite #' @param ... Arguments to pass to \code{layout_as_bipartite}. #' @export as_bipartite <- function(...) layout_spec(layout_as_bipartite, ...) ## ---------------------------------------------------------------- #' Generate coordinates to place the vertices of a graph in a star-shape #' #' A simple layout generator, that places one vertex in the center of a circle #' and the rest of the vertices equidistantly on the perimeter. #' #' It is possible to choose the vertex that will be in the center, and the #' order of the vertices can be also given. #' #' @aliases layout_as_star layout.star #' @param graph The graph to layout. #' @param center The id of the vertex to put in the center. By default it is #' the first vertex. #' @param order Numeric vector, the order of the vertices along the perimeter. #' The default ordering is given by the vertex ids. #' @return A matrix with two columns and as many rows as the number of vertices #' in the input graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout}} and \code{\link{layout.drl}} for other layout #' algorithms, \code{\link{plot.igraph}} and \code{\link{tkplot}} on how to #' plot graphs and \code{\link{star}} on how to create ring graphs. #' @keywords graphs #' @export #' @family graph layouts #' @examples #' #' g <- make_star(10) #' layout_as_star(g) #' #' ## Alternative form #' layout_(g, as_star()) layout_as_star <- function(graph, center=V(graph)[1], order=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } center <- as.igraph.vs(graph, center) if (!is.null(order)) order <- as.numeric(order)-1 on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_star, graph, center-1, order) res } #' @rdname layout_as_star #' @param ... Arguments to pass to \code{layout_as_star}. #' @export as_star <- function(...) layout_spec(layout_as_star, ...) ## ---------------------------------------------------------------- #' The Reingold-Tilford graph layout algorithm #' #' A tree-like layout, it is perfect for trees, acceptable for graphs with not #' too many cycles. #' #' Arranges the nodes in a tree where the given node is used as the root. The #' tree is directed downwards and the parents are centered above its children. #' For the exact algorithm, the refernce below. #' #' If the given graph is not a tree, a breadth-first search is executed first #' to obtain a possible spanning tree. #' #' @param graph The input graph. #' @param root The index of the root vertex or root vertices. If this is a #' non-empty vector then the supplied vertex ids are used as the roots of the #' trees (or a single tree if the graph is connected). If it is an empty #' vector, then the root vertices are automatically calculated based on #' topological sorting, performed with the opposite mode than the \code{mode} #' argument. After the vertices have been sorted, one is selected from each #' component. #' @param circular Logical scalar, whether to plot the tree in a circular #' fashion. Defaults to \code{FALSE}, so the tree branches are going bottom-up #' (or top-down, see the \code{flip.y} argument. #' @param rootlevel This argument can be useful when drawing forests which are #' not trees (i.e. they are unconnected and have tree components). It specifies #' the level of the root vertices for every tree in the forest. It is only #' considered if the \code{roots} argument is not an empty vector. #' @param mode Specifies which edges to consider when building the tree. If it #' is \sQuote{out}, then only the outgoing, if it is \sQuote{in}, then only the #' incoming edges of a parent are considered. If it is \sQuote{all} then all #' edges are used (this was the behavior in igraph 0.5 and before). This #' parameter also influences how the root vertices are calculated, if they are #' not given. See the \code{roots} parameter. #' @param flip.y Logical scalar, whether to flip the \sQuote{y} coordinates. #' The default is flipping because that puts the root vertex on the top. #' @return A numeric matrix with two columns, and one row for each vertex. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @references Reingold, E and Tilford, J (1981). Tidier drawing of trees. #' \emph{IEEE Trans. on Softw. Eng.}, SE-7(2):223--228. #' @keywords graphs #' @export #' @family graph layouts #' @examples #' #' tree <- make_tree(20, 3) #' plot(tree, layout=layout_as_tree) #' plot(tree, layout=layout_as_tree(tree, flip.y=FALSE)) #' plot(tree, layout=layout_as_tree(tree, circular=TRUE)) #' #' tree2 <- make_tree(10, 3) + make_tree(10, 2) #' plot(tree2, layout=layout_as_tree) #' plot(tree2, layout=layout_as_tree(tree2, root=c(1,11), #' rootlevel=c(2,1))) layout_as_tree <- function(graph, root=numeric(), circular=FALSE, rootlevel=numeric(), mode=c("out", "in", "all"), flip.y=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } root <- as.igraph.vs(graph, root)-1 circular <- as.logical(circular) rootlevel <- as.double(rootlevel) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) flip.y <- as.logical(flip.y) on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_layout_reingold_tilford, graph, root, mode, rootlevel, circular) if (flip.y) { res[,2] <- max(res[,2])-res[,2] } res } #' @rdname layout_as_tree #' @param ... Passed to \code{layout_as_tree}. #' @export as_tree <- function(...) layout_spec(layout_as_tree, ...) #' @export #' @rdname layout.deprecated layout.reingold.tilford <- function(..., params = list()) { do_call(layout_as_tree, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' Graph layout with vertices on a circle. #' #' Place vertices on a circle, in the order of their vertex ids. #' #' If you want to order the vertices differently, then permute them using the #' \code{\link{permute}} function. #' #' @param graph The input graph. #' @param order The vertices to place on the circle, in the order of their #' desired placement. Vertices that are not included here will be placed at #' (0,0). #' @return A numeric matrix with two columns, and one row for each vertex. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @family graph layouts #' @examples #' #' ## Place vertices on a circle, order them according to their #' ## community #' \dontrun{ #' library(igraphdata) #' data(karate) #' karate_groups <- cluster_optimal(karate) #' coords <- layout_in_circle(karate, order = #' order(membership(karate_groups))) #' V(karate)$label <- sub("Actor ", "", V(karate)$name) #' V(karate)$label.color <- membership(karate_groups) #' V(karate)$shape <- "none" #' plot(karate, layout = coords) #' } layout_in_circle <- function(graph, order=V(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } order <- as.igraph.vs(graph, order) - 1L on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_circle, graph, order) } #' @rdname layout_in_circle #' @param ... Passed to \code{layout_in_circle}. #' @export in_circle <- function(...) layout_spec(layout_in_circle, ...) #' @export #' @rdname layout.deprecated layout.circle <- function(..., params = list()) { do_call(layout_in_circle, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' Choose an appropriate graph layout algorithm automatically #' #' This function tries to choose an appropriate graph layout algorithm for the #' graph, automatically, based on a simple algorithm. See details below. #' #' \code{layout_nicely} tries to choose an appropriate layout function for the #' supplied graph, and uses that to generate the layout. The current #' implementation works like this: \enumerate{ \item If the graph has a graph #' attribute called \sQuote{layout}, then this is used. If this attribute is an #' R function, then it is called, with the graph and any other extra arguments. #' \item Otherwise, if the graph has vertex attributes called \sQuote{x} and #' \sQuote{y}, then these are used as coordinates. If the graph has an #' additional \sQuote{z} vertex attribute, that is also used. \item Otherwise, #' if the graph is connected and has less than 1000 vertices, the #' Fruchterman-Reingold layout is used, by calling \code{layout_with_fr}. #' \item Otherwise the DrL layout is used, \code{layout_with_drl} is called. } #' #' @aliases layout.auto #' @param graph The input graph #' @param dim Dimensions, should be 2 or 3. #' @param \dots For \code{layout_nicely} the extra arguments are passed to #' the real layout function. For \code{nicely} all argument are passed to #' \code{layout_nicely}. #' @return A numeric matrix with two or three columns. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{plot.igraph}} #' @keywords graphs #' @export #' @family graph layouts layout_nicely <- function(graph, dim=2, ...) { ## 1. If there is a 'layout' graph attribute, we just use that. ## 2. Otherwise, if there are vertex attributes called 'x' and 'y', ## we use those (and the 'z' vertex attribute as well, if present). ## 3. Otherwise, if the graph is small (<1000) we use ## the Fruchterman-Reingold layout. ## 5. Otherwise we use the DrL layout generator. if ("layout" %in% graph_attr_names(graph)) { lay <- graph_attr(graph, "layout") if (is.function(lay)) { lay(graph, ...) } else { lay } } else if ( all(c("x", "y") %in% vertex_attr_names(graph)) ) { if ("z" %in% vertex_attr_names(graph)) { cbind(V(graph)$x, V(graph)$y, V(graph)$z) } else { cbind(V(graph)$x, V(graph)$y) } } else if (vcount(graph) < 1000) { layout_with_fr(graph, dim=dim, ...) } else { layout_with_drl(graph, dim=dim, ...) } } #' @rdname layout_nicely #' @export nicely <- function(...) layout_spec(layout_nicely, ...) ## ---------------------------------------------------------------- #' Simple grid layout #' #' This layout places vertices on a rectangulat grid, in two or three #' dimensions. #' #' The function places the vertices on a simple rectangular grid, one after the #' other. If you want to change the order of the vertices, then see the #' \code{\link{permute}} function. #' #' @aliases layout_on_grid layout.grid layout.grid.3d #' @param graph The input graph. #' @param width The number of vertices in a single row of the grid. If this is #' zero or negative, then for 2d layouts the width of the grid will be the #' square root of the number of vertices in the graph, rounded up to the next #' integer. Similarly, it will be the cube root for 3d layouts. #' @param height The number of vertices in a single column of the grid, for #' three dimensional layouts. If this is zero or negative, then it is #' determinted automatically. #' @param dim Two or three. Whether to make 2d or a 3d layout. #' @return A two-column or three-column matrix. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @seealso \code{\link{layout}} for other layout generators #' @keywords graphs #' @export #' @family graph layouts #' @examples #' #' g <- make_lattice( c(3,3) ) #' layout_on_grid(g) #' #' g2 <- make_lattice( c(3,3,3) ) #' layout_on_grid(g2, dim = 3) #' #' \dontrun{ #' plot(g, layout=layout_on_grid) #' rglplot(g, layout=layout_on_grid(g, dim = 3)) #' } layout_on_grid <- function(graph, width = 0, height = 0, dim = 2) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } width <- as.integer(width) dim <- as.integer(dim) stopifnot(dim == 2 || dim == 3) if (dim == 3) { height <- as.integer(height) } on.exit(.Call(C_R_igraph_finalizer) ) # Function call if (dim == 2) { res <- .Call(C_R_igraph_layout_grid, graph, width) } else { res <- .Call(C_R_igraph_layout_grid_3d, graph, width, height) } res } #' @rdname layout_on_grid #' @param ... Passed to \code{layout_on_grid}. #' @export on_grid <- function(...) layout_spec(layout_on_grid, ...) #' @rdname layout_on_grid #' @export layout.grid.3d <- function(graph, width=0, height=0) { .Deprecated("layout_on_grid", msg = paste0("layout.grid.3d is deprecated from\n", "igraph 0.8.0, please use layout_on_grid instead")) # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } width <- as.integer(width) height <- as.integer(height) on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_grid_3d, graph, width, height) res } ## ---------------------------------------------------------------- #' Graph layout with vertices on the surface of a sphere #' #' Place vertices on a sphere, approximately uniformly, in the order of their #' vertex ids. #' #' \code{layout_on_sphere} places the vertices (approximately) uniformly on the #' surface of a sphere, this is thus a 3d layout. It is not clear however what #' \dQuote{uniformly on a sphere} means. #' #' If you want to order the vertices differently, then permute them using the #' \code{\link{permute}} function. #' #' @param graph The input graph. #' @return A numeric matrix with three columns, and one row for each vertex. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @family graph layouts layout_on_sphere <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_sphere, graph) } #' @rdname layout_on_sphere #' @param ... Passed to \code{layout_on_sphere}. #' @export on_sphere <- function(...) layout_spec(layout_on_sphere, ...) #' @export #' @rdname layout.deprecated layout.sphere <- function(..., params = list()) { do_call(layout_on_sphere, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' Randomly place vertices on a plane or in 3d space #' #' This function uniformly randomly places the vertices of the graph in two or #' three dimensions. #' #' Randomly places vertices on a [-1,1] square (in 2d) or in a cube (in 3d). It #' is probably a useless layout, but it can use as a starting point for other #' layout generators. #' #' @param graph The input graph. #' @param dim Integer scalar, the dimension of the space to use. It must be 2 #' or 3. #' @return A numeric matrix with two or three columns. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @family graph layouts layout_randomly <- function(graph, dim=2) { if (!is_igraph(graph)) { stop("Not a graph object") } if (dim==2) { on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_random, graph) } else if (dim==3) { on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_random_3d, graph) } else { stop("Invalid `dim' value"); } } #' @rdname layout_randomly #' @param ... Parameters to pass to \code{layout_randomly}. #' @export randomly <- function(...) layout_spec(layout_randomly, ...) #' Deprecated layout functions #' #' Please use the new names, see \code{\link{layout_}}. #' #' @param ... Passed to the new layout functions. #' @param params Passed to the new layout functions as arguments. #' @export #' @rdname layout.deprecated layout.random <- function(..., params = list()) { do_call(layout_randomly, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' The Davidson-Harel layout algorithm #' #' Place vertices of a graph on the plane, according to the simulated annealing #' algorithm by Davidson and Harel. #' #' This function implements the algorithm by Davidson and Harel, see Ron #' Davidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. ACM #' Transactions on Graphics 15(4), pp. 301-331, 1996. #' #' The algorithm uses simulated annealing and a sophisticated energy function, #' which is unfortunately hard to parameterize for different graphs. The #' original publication did not disclose any parameter values, and the ones #' below were determined by experimentation. #' #' The algorithm consists of two phases, an annealing phase, and a fine-tuning #' phase. There is no simulated annealing in the second phase. #' #' Our implementation tries to follow the original publication, as much as #' possible. The only major difference is that coordinates are explicitly kept #' within the bounds of the rectangle of the layout. #' #' @aliases layout.davidson.harel #' @param graph The graph to lay out. Edge directions are ignored. #' @param coords Optional starting positions for the vertices. If this argument #' is not \code{NULL} then it should be an appropriate matrix of starting #' coordinates. #' @param maxiter Number of iterations to perform in the first phase. #' @param fineiter Number of iterations in the fine tuning phase. #' @param cool.fact Cooling factor. #' @param weight.node.dist Weight for the node-node distances component of the #' energy function. #' @param weight.border Weight for the distance from the border component of #' the energy function. It can be set to zero, if vertices are allowed to sit #' on the border. #' @param weight.edge.lengths Weight for the edge length component of the #' energy function. #' @param weight.edge.crossings Weight for the edge crossing component of the #' energy function. #' @param weight.node.edge.dist Weight for the node-edge distance component of #' the energy function. #' @return A two- or three-column matrix, each row giving the coordinates of a #' vertex, according to the ids of the vertex ids. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout_with_fr}}, #' \code{\link{layout_with_kk}} for other layout algorithms. #' @references Ron Davidson, David Harel: Drawing Graphs Nicely Using Simulated #' Annealing. \emph{ACM Transactions on Graphics} 15(4), pp. 301-331, 1996. #' @export #' @family graph layouts #' @examples #' #' set.seed(42) #' ## Figures from the paper #' g_1b <- make_star(19, mode="undirected") + path(c(2:19, 2)) + #' path(c(seq(2, 18, by=2), 2)) #' plot(g_1b, layout=layout_with_dh) #' #' g_2 <- make_lattice(c(8, 3)) + edges(1,8, 9,16, 17,24) #' plot(g_2, layout=layout_with_dh) #' #' g_3 <- make_empty_graph(n=70) #' plot(g_3, layout=layout_with_dh) #' #' g_4 <- make_empty_graph(n=70, directed=FALSE) + edges(1:70) #' plot(g_4, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_5a <- make_ring(24) #' plot(g_5a, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_5b <- make_ring(40) #' plot(g_5b, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_6 <- make_lattice(c(2,2,2)) #' plot(g_6, layout=layout_with_dh) #' #' g_7 <- graph_from_literal(1:3:5 -- 2:4:6) #' plot(g_7, layout=layout_with_dh, vertex.label=V(g_7)$name) #' #' g_8 <- make_ring(5) + make_ring(10) + make_ring(5) + #' edges(1,6, 2,8, 3, 10, 4,12, 5,14, #' 7,16, 9,17, 11,18, 13,19, 15,20) #' plot(g_8, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_9 <- make_lattice(c(3,2,2)) #' plot(g_9, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_10 <- make_lattice(c(6,6)) #' plot(g_10, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_11a <- make_tree(31, 2, mode="undirected") #' plot(g_11a, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_11b <- make_tree(21, 4, mode="undirected") #' plot(g_11b, layout=layout_with_dh, vertex.size=5, vertex.label=NA) #' #' g_12 <- make_empty_graph(n=37, directed=FALSE) + #' path(1:5,10,22,31,37:33,27,16,6,1) + path(6,7,11,9,10) + path(16:22) + #' path(27:31) + path(2,7,18,28,34) + path(3,8,11,19,29,32,35) + #' path(4,9,20,30,36) + path(1,7,12,14,19,24,26,30,37) + #' path(5,9,13,15,19,23,25,28,33) + path(3,12,16,25,35,26,22,13,3) #' plot(g_12, layout=layout_with_dh, vertex.size=5, vertex.label=NA) layout_with_dh <- function(graph, coords=NULL, maxiter=10, fineiter=max(10, log2(vcount(graph))), cool.fact=0.75, weight.node.dist=1.0, weight.border=0.0, weight.edge.lengths=edge_density(graph) / 10, weight.edge.crossings=1.0 - sqrt(edge_density(graph)), weight.node.edge.dist=0.2 * (1-edge_density(graph))) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(coords)) { coords <- as.matrix(structure(as.double(coords), dim=dim(coords))) use.seed <- TRUE } else { coords <- matrix(NA_real_, ncol=2, nrow=0) use.seed <- FALSE } maxiter <- as.integer(maxiter) fineiter <- as.integer(fineiter) cool.fact <- as.numeric(cool.fact) weight.node.dist <- as.numeric(weight.node.dist) weight.border <- as.numeric(weight.border) weight.edge.lengths <- as.numeric(weight.edge.lengths) weight.edge.crossings <- as.numeric(weight.edge.crossings) weight.node.edge.dist <- as.numeric(weight.node.edge.dist) on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_davidson_harel, graph, coords, use.seed, maxiter, fineiter, cool.fact, weight.node.dist, weight.border, weight.edge.lengths, weight.edge.crossings, weight.node.edge.dist) res } #' @rdname layout_with_dh #' @param ... Passed to \code{layout_with_dh}. #' @export with_dh <- function(...) layout_spec(layout_with_dh, ...) ## ---------------------------------------------------------------- #' The Fruchterman-Reingold layout algorithm #' #' Place vertices on the plane using the force-directed layout algorithm by #' Fruchterman and Reingold. #' #' See the referenced paper below for the details of the algorithm. #' #' This function was rewritten from scratch in igraph version 0.8.0. #' #' @param graph The graph to lay out. Edge directions are ignored. #' @param coords Optional starting positions for the vertices. If this argument #' is not \code{NULL} then it should be an appropriate matrix of starting #' coordinates. #' @param dim Integer scalar, 2 or 3, the dimension of the layout. Two #' dimensional layouts are places on a plane, three dimensional ones in the 3d #' space. #' @param niter Integer scalar, the number of iterations to perform. #' @param start.temp Real scalar, the start temperature. This is the maximum #' amount of movement alloved along one axis, within one step, for a vertex. #' Currently it is decreased linearly to zero during the iteration. #' @param grid Character scalar, whether to use the faster, but less accurate #' grid based implementation of the algorithm. By default (\dQuote{auto}), the #' grid-based implementation is used if the graph has more than one thousand #' vertices. #' @param weights A vector giving edge weights. The \code{weight} edge #' attribute is used by default, if present. If weights are given, then the #' attraction along the edges will be multiplied by the given edge weights. #' This places vertices connected with a highly weighted edge closer to #' each other. #' @param minx If not \code{NULL}, then it must be a numeric vector that gives #' lower boundaries for the \sQuote{x} coordinates of the vertices. The length #' of the vector must match the number of vertices in the graph. #' @param maxx Similar to \code{minx}, but gives the upper boundaries. #' @param miny Similar to \code{minx}, but gives the lower boundaries of the #' \sQuote{y} coordinates. #' @param maxy Similar to \code{minx}, but gives the upper boundaries of the #' \sQuote{y} coordinates. #' @param minz Similar to \code{minx}, but gives the lower boundaries of the #' \sQuote{z} coordinates. #' @param maxz Similar to \code{minx}, but gives the upper boundaries of the #' \sQuote{z} coordinates. #' @param coolexp,maxdelta,area,repulserad These arguments are not supported #' from igraph version 0.8.0 and are ignored (with a warning). #' @param maxiter A deprecated synonym of \code{niter}, for compatibility. #' @return A two- or three-column matrix, each row giving the coordinates of a #' vertex, according to the ids of the vertex ids. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout_with_drl}}, \code{\link{layout_with_kk}} for #' other layout algorithms. #' @references Fruchterman, T.M.J. and Reingold, E.M. (1991). Graph Drawing by #' Force-directed Placement. \emph{Software - Practice and Experience}, #' 21(11):1129-1164. #' @export #' @family graph layouts #' @keywords graphs #' @examples #' #' # Fixing ego #' g <- sample_pa(20, m=2) #' minC <- rep(-Inf, vcount(g)) #' maxC <- rep(Inf, vcount(g)) #' minC[1] <- maxC[1] <- 0 #' co <- layout_with_fr(g, minx=minC, maxx=maxC, #' miny=minC, maxy=maxC) #' co[1,] #' plot(g, layout=co, vertex.size=30, edge.arrow.size=0.2, #' vertex.label=c("ego", rep("", vcount(g)-1)), rescale=FALSE, #' xlim=range(co[,1]), ylim=range(co[,2]), vertex.label.dist=0, #' vertex.label.color="red") #' axis(1) #' axis(2) #' layout_with_fr <- function(graph, coords=NULL, dim=2, niter=500, start.temp=sqrt(vcount(graph)), grid=c("auto", "grid", "nogrid"), weights=NULL, minx=NULL, maxx=NULL, miny=NULL, maxy=NULL, minz=NULL, maxz=NULL, coolexp, maxdelta, area, repulserad, maxiter) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(coords)) { coords <- as.matrix(structure(as.double(coords), dim=dim(coords))) } dim <- as.integer(dim) if (dim != 2L && dim != 3L) { stop("Dimension must be two or three") } if (!missing(niter) && !missing(maxiter)) { stop("Both `niter' and `maxiter' are given, give only one of them") } if (!missing(maxiter)) niter <- maxiter niter <- as.integer(niter) start.temp <- as.numeric(start.temp) grid <- igraph.match.arg(grid) grid <- switch(grid, "grid"=0L, "nogrid"=1L, "auto"=2L) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } if (!is.null(minx)) minx <- as.numeric(minx) if (!is.null(maxx)) maxx <- as.numeric(maxx) if (!is.null(miny)) miny <- as.numeric(miny) if (!is.null(maxy)) maxy <- as.numeric(maxy) if (!is.null(minz)) minz <- as.numeric(minz) if (!is.null(maxz)) maxz <- as.numeric(maxz) if (!missing(coolexp)) { warning("Argument `coolexp' is deprecated and has no effect") } if (!missing(maxdelta)) { warning("Argument `maxdelta' is deprecated and has no effect") } if (!missing(area)) { warning("Argument `area' is deprecated and has no effect") } if (!missing(repulserad)) { warning("Argument `repulserad' is deprecated and has no effect") } on.exit(.Call(C_R_igraph_finalizer) ) if (dim==2) { res <- .Call(C_R_igraph_layout_fruchterman_reingold, graph, coords, niter, start.temp, weights, minx, maxx, miny, maxy, grid) } else { res <- .Call(C_R_igraph_layout_fruchterman_reingold_3d, graph, coords, niter, start.temp, weights, minx, maxx, miny, maxy, minz, maxz) } res } #' @rdname layout_with_fr #' @param ... Passed to \code{layout_with_fr}. #' @export with_fr <- function(...) layout_spec(layout_with_fr, ...) #' @export #' @rdname layout.deprecated layout.fruchterman.reingold <- function(..., params = list()) { do_call(layout_with_fr, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' The GEM layout algorithm #' #' Place vertices on the plane using the GEM force-directed layout algorithm. #' #' See the referenced paper below for the details of the algorithm. #' #' @aliases layout.gem #' @param graph The input graph. Edge directions are ignored. #' @param coords If not \code{NULL}, then the starting coordinates should be #' given here, in a two or three column matrix, depending on the \code{dim} #' argument. #' @param maxiter The maximum number of iterations to perform. Updating a #' single vertex counts as an iteration. A reasonable default is 40 * n * n, #' where n is the number of vertices. The original paper suggests 4 * n * n, #' but this usually only works if the other parameters are set up carefully. #' @param temp.max The maximum allowed local temperature. A reasonable default #' is the number of vertices. #' @param temp.min The global temperature at which the algorithm terminates #' (even before reaching \code{maxiter} iterations). A reasonable default is #' 1/10. #' @param temp.init Initial local temperature of all vertices. A reasonable #' default is the square root of the number of vertices. #' @return A numeric matrix with two columns, and as many rows as the number of #' vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout_with_fr}}, #' \code{\link{plot.igraph}}, \code{\link{tkplot}} #' @references Arne Frick, Andreas Ludwig, Heiko Mehldau: A Fast Adaptive #' Layout Algorithm for Undirected Graphs, \emph{Proc. Graph Drawing 1994}, #' LNCS 894, pp. 388-403, 1995. #' @export #' @family graph layouts #' @keywords graphs #' @examples #' #' set.seed(42) #' g <- make_ring(10) #' plot(g, layout=layout_with_gem) #' layout_with_gem <- function(graph, coords=NULL, maxiter=40*vcount(graph)^2, temp.max=vcount(graph), temp.min=1/10, temp.init=sqrt(vcount(graph))) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(coords)) { coords <- as.matrix(structure(as.double(coords), dim=dim(coords))) use.seed <- TRUE } else { coords <- matrix(NA_real_, ncol=2, nrow=0) use.seed <- FALSE } maxiter <- as.integer(maxiter) temp.max <- as.numeric(temp.max) temp.min <- as.numeric(temp.min) temp.init <- as.numeric(temp.init) on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_gem, graph, coords, use.seed, maxiter, temp.max, temp.min, temp.init) res } #' @rdname layout_with_gem #' @param ... Passed to \code{layout_with_gem}. #' @export with_gem <- function(...) layout_spec(layout_with_gem, ...) ## ---------------------------------------------------------------- #' The graphopt layout algorithm #' #' A force-directed layout algorithm, that scales relatively well to large #' graphs. #' #' \code{layout_with_graphopt} is a port of the graphopt layout algorithm by Michael #' Schmuhl. graphopt version 0.4.1 was rewritten in C and the support for #' layers was removed (might be added later) and a code was a bit reorganized #' to avoid some unneccessary steps is the node charge (see below) is zero. #' #' graphopt uses physical analogies for defining attracting and repelling #' forces among the vertices and then the physical system is simulated until it #' reaches an equilibrium. (There is no simulated annealing or anything like #' that, so a stable fixed point is not guaranteed.) #' #' See also \url{http://www.schmuhl.org/graphopt/} for the original graphopt. #' #' @aliases layout.graphopt #' @param graph The input graph. #' @param start If given, then it should be a matrix with two columns and one #' line for each vertex. This matrix will be used as starting positions for the #' algorithm. If not given, then a random starting matrix is used. #' @param niter Integer scalar, the number of iterations to perform. Should be #' a couple of hundred in general. If you have a large graph then you might #' want to only do a few iterations and then check the result. If it is not #' good enough you can feed it in again in the \code{start} argument. The #' default value is 500. #' @param charge The charge of the vertices, used to calculate electric #' repulsion. The default is 0.001. #' @param mass The mass of the vertices, used for the spring forces. The #' default is 30. #' @param spring.length The length of the springs, an integer number. The #' default value is zero. #' @param spring.constant The spring constant, the default value is one. #' @param max.sa.movement Real constant, it gives the maximum amount of #' movement allowed in a single step along a single axis. The default value is #' 5. #' @return A numeric matrix with two columns, and a row for each vertex. #' @author Michael Schmuhl for the original graphopt code, rewritten and #' wrapped by Gabor Csardi \email{csardi.gabor@@gmail.com}. #' @keywords graphs #' @export #' @family graph layouts layout_with_graphopt <- function(graph, start=NULL, niter=500, charge=0.001, mass=30, spring.length=0, spring.constant=1, max.sa.movement=5) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(start)) { start <- structure(as.numeric(start), dim=dim(start)) } niter <- as.double(niter) charge <- as.double(charge) mass <- as.double(mass) spring.length <- as.double(spring.length) spring.constant <- as.double(spring.constant) max.sa.movement <- as.double(max.sa.movement) on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_graphopt, graph, niter, charge, mass, spring.length, spring.constant, max.sa.movement, start) } #' @rdname layout_with_graphopt #' @param ... Passed to \code{layout_with_graphopt}. #' @export with_graphopt <- function(...) layout_spec(layout_with_graphopt, ...) ## ---------------------------------------------------------------- #' The Kamada-Kawai layout algorithm #' #' Place the vertices on the plane, or in the 3d space, based on a phyisical #' model of springs. #' #' See the referenced paper below for the details of the algorithm. #' #' This function was rewritten from scratch in igraph version 0.8.0 and it #' follows truthfully the original publication by Kamada and Kawai now. #' #' @param graph The input graph. Edge directions are ignored. #' @param coords If not \code{NULL}, then the starting coordinates should be #' given here, in a two or three column matrix, depending on the \code{dim} #' argument. #' @param dim Integer scalar, 2 or 3, the dimension of the layout. Two #' dimensional layouts are places on a plane, three dimensional ones in the 3d #' space. #' @param maxiter The maximum number of iterations to perform. The algorithm #' might terminate earlier, see the \code{epsilon} argument. #' @param epsilon Numeric scalar, the algorithm terminates, if the maximal #' delta is less than this. (See the reference below for what delta means.) If #' you set this to zero, then the function always performs \code{maxiter} #' iterations. #' @param kkconst Numeric scalar, the Kamada-Kawai vertex attraction constant. #' Typical (and default) value is the number of vertices. #' @param weights Edge weights, larger values will result longer edges. #' Note that this is opposite to \code{\link{layout_with_fr}}. #' @param minx If not \code{NULL}, then it must be a numeric vector that gives #' lower boundaries for the \sQuote{x} coordinates of the vertices. The length #' of the vector must match the number of vertices in the graph. #' @param maxx Similar to \code{minx}, but gives the upper boundaries. #' @param miny Similar to \code{minx}, but gives the lower boundaries of the #' \sQuote{y} coordinates. #' @param maxy Similar to \code{minx}, but gives the upper boundaries of the #' \sQuote{y} coordinates. #' @param minz Similar to \code{minx}, but gives the lower boundaries of the #' \sQuote{z} coordinates. #' @param maxz Similar to \code{minx}, but gives the upper boundaries of the #' \sQuote{z} coordinates. #' @param niter,sigma,initemp,coolexp These arguments are not supported from #' igraph version 0.8.0 and are ignored (with a warning). #' @param start Deprecated synonym for \code{coords}, for compatibility. #' @return A numeric matrix with two (dim=2) or three (dim=3) columns, and as #' many rows as the number of vertices, the x, y and potentially z coordinates #' of the vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout_with_drl}}, \code{\link{plot.igraph}}, #' \code{\link{tkplot}} #' @references Kamada, T. and Kawai, S.: An Algorithm for Drawing General #' Undirected Graphs. \emph{Information Processing Letters}, 31/1, 7--15, 1989. #' @export #' @family graph layouts #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' E(g)$weight <- rep(1:2, length.out=ecount(g)) #' plot(g, layout=layout_with_kk, edge.label=E(g)$weight) #' layout_with_kk <- function(graph, coords=NULL, dim=2, maxiter=50*vcount(graph), epsilon=0.0, kkconst=vcount(graph), weights=NULL, minx=NULL, maxx=NULL, miny=NULL, maxy=NULL, minz=NULL, maxz=NULL, niter, sigma, initemp, coolexp, start) { # Argument checks if (!missing(coords) && !missing(start)) { stop("Both `coords' and `start' are given, give only one of them.") } if (!missing(start)) coords <- start if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(coords)) { coords <- as.matrix(structure(as.double(coords), dim=dim(coords))) } dim <- as.integer(dim) if (dim != 2L && dim != 3L) { stop("Dimension must be two or three") } maxiter <- as.integer(maxiter) epsilon <- as.numeric(epsilon) kkconst <- as.numeric(kkconst) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } if (!is.null(minx)) minx <- as.numeric(minx) if (!is.null(maxx)) maxx <- as.numeric(maxx) if (!is.null(miny)) miny <- as.numeric(miny) if (!is.null(maxy)) maxy <- as.numeric(maxy) if (!is.null(minz)) minz <- as.numeric(minz) if (!is.null(maxz)) maxz <- as.numeric(maxz) if (!missing(niter)) { warning("Argument `niter' is deprecated and has no effect") } if (!missing(sigma)) { warning("Argument `sigma' is deprecated and has no effect") } if (!missing(initemp)) { warning("Argument `initemp' is deprecated and has no effect") } if (!missing(coolexp)) { warning("Argument `coolexp' is deprecated and has no effect") } on.exit(.Call(C_R_igraph_finalizer) ) # Function call if (dim == 2) { res <- .Call(C_R_igraph_layout_kamada_kawai, graph, coords, maxiter, epsilon, kkconst, weights, minx, maxx, miny, maxy) } else { res <- .Call(C_R_igraph_layout_kamada_kawai_3d, graph, coords, maxiter, epsilon, kkconst, weights, minx, maxx, miny, maxy, minz, maxz) } res } #' @rdname layout_with_kk #' @param ... Passed to \code{layout_with_kk}. #' @export #' with_kk <- function(...) layout_spec(layout_with_kk, ...) #' @export #' @rdname layout.deprecated layout.kamada.kawai <- function(..., params = list()) { do_call(layout_with_kk, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' Large Graph Layout #' #' A layout generator for larger graphs. #' #' \code{layout_with_lgl} is for large connected graphs, it is similar to the layout #' generator of the Large Graph Layout software #' (\url{http://lgl.sourceforge.net/}). #' #' @param graph The input graph #' @param maxiter The maximum number of iterations to perform (150). #' @param maxdelta The maximum change for a vertex during an iteration (the #' number of vertices). #' @param area The area of the surface on which the vertices are placed (square #' of the number of vertices). #' @param coolexp The cooling exponent of the simulated annealing (1.5). #' @param repulserad Cancellation radius for the repulsion (the \code{area} #' times the number of vertices). #' @param cellsize The size of the cells for the grid. When calculating the #' repulsion forces between vertices only vertices in the same or neighboring #' grid cells are taken into account (the fourth root of the number of #' \code{area}. #' @param root The id of the vertex to place at the middle of the layout. The #' default value is -1 which means that a random vertex is selected. #' @return A numeric matrix with two columns and as many rows as vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @family graph layouts layout_with_lgl <- function(graph, maxiter=150, maxdelta=vcount(graph), area=vcount(graph)^2, coolexp=1.5, repulserad=area * vcount(graph), cellsize=sqrt(sqrt(area)), root=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(root)) { root <- -1 } else { root <- as.igraph.vs(graph, root)-1 } on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_layout_lgl, graph, as.double(maxiter), as.double(maxdelta), as.double(area), as.double(coolexp), as.double(repulserad), as.double(cellsize), root) } #' @rdname layout_with_lgl #' @param ... Passed to \code{layout_with_lgl}. #' @export with_lgl <- function(...) layout_spec(layout_with_lgl, ...) #' @export #' @rdname layout.deprecated layout.lgl <- function(..., params = list()) { do_call(layout_with_lgl, .args = c(list(...), params)) } ## ---------------------------------------------------------------- #' Graph layout by multidimensional scaling #' #' Multidimensional scaling of some distance matrix defined on the vertices of #' a graph. #' #' \code{layout_with_mds} uses metric multidimensional scaling for generating the #' coordinates. Multidimensional scaling aims to place points from a higher #' dimensional space in a (typically) 2 dimensional plane, so that the distance #' between the points are kept as much as this is possible. #' #' By default igraph uses the shortest path matrix as the distances between the #' nodes, but the user can override this via the \code{dist} argument. #' #' This function generates the layout separately for each graph component and #' then merges them via \code{\link{merge_coords}}. #' #' @aliases layout.mds #' @param graph The input graph. #' @param dist The distance matrix for the multidimensional scaling. If #' \code{NULL} (the default), then the unweighted shortest path matrix is used. #' @param dim \code{layout_with_mds} supports dimensions up to the number of nodes #' minus one, but only if the graph is connected; for unconnected graphs, the #' only possible values is 2. This is because \code{merge_coords} only works in #' 2D. #' @param options This is currently ignored, as ARPACK is not used any more for #' solving the eigenproblem #' @return A numeric matrix with \code{dim} columns. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout}}, \code{\link{plot.igraph}} #' @references Cox, T. F. and Cox, M. A. A. (2001) \emph{Multidimensional #' Scaling}. Second edition. Chapman and Hall. #' @export #' @family graph layouts #' @keywords graphs #' @examples #' #' g <- sample_gnp(100, 2/100) #' l <- layout_with_mds(g) #' plot(g, layout=l, vertex.label=NA, vertex.size=3) layout_with_mds <- function(graph, dist=NULL, dim=2, options=arpack_defaults) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(dist)) dist <- structure(as.double(dist), dim=dim(dist)) dim <- as.integer(dim) on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_mds, graph, dist, dim) res } #' @rdname layout_with_mds #' @param ... Passed to \code{layout_with_mds}. #' @export with_mds <- function(...) layout_spec(layout_with_mds, ...) ## ---------------------------------------------------------------- #' The Sugiyama graph layout generator #' #' Sugiyama layout algorithm for layered directed acyclic graphs. The algorithm #' minimized edge crossings. #' #' This layout algorithm is designed for directed acyclic graphs where each #' vertex is assigned to a layer. Layers are indexed from zero, and vertices of #' the same layer will be placed on the same horizontal line. The X coordinates #' of vertices within each layer are decided by the heuristic proposed by #' Sugiyama et al. to minimize edge crossings. #' #' You can also try to lay out undirected graphs, graphs containing cycles, or #' graphs without an a priori layered assignment with this algorithm. igraph #' will try to eliminate cycles and assign vertices to layers, but there is no #' guarantee on the quality of the layout in such cases. #' #' The Sugiyama layout may introduce \dQuote{bends} on the edges in order to #' obtain a visually more pleasing layout. This is achieved by adding dummy #' nodes to edges spanning more than one layer. The resulting layout assigns #' coordinates not only to the nodes of the original graph but also to the #' dummy nodes. The layout algorithm will also return the extended graph with #' the dummy nodes. #' #' For more details, see the reference below. #' #' @aliases layout.sugiyama #' @param graph The input graph. #' @param layers A numeric vector or \code{NULL}. If not \code{NULL}, then it #' should specify the layer index of the vertices. Layers are numbered from #' one. If \code{NULL}, then igraph calculates the layers automatically. #' @param hgap Real scalar, the minimum horizontal gap between vertices in the #' same layer. #' @param vgap Real scalar, the distance between layers. #' @param maxiter Integer scalar, the maximum number of iterations in the #' crossing minimization stage. 100 is a reasonable default; if you feel that #' you have too many edge crossings, increase this. #' @param weights Optional edge weight vector. If \code{NULL}, then the #' 'weight' edge attribute is used, if there is one. Supply \code{NA} here and #' igraph ignores the edge weights. These are used only if the graph #' contains cycles; igraph will tend to reverse edges with smaller weights #' when breaking the cycles. #' @param attributes Which graph/vertex/edge attributes to keep in the extended #' graph. \sQuote{default} keeps the \sQuote{size}, \sQuote{size2}, #' \sQuote{shape}, \sQuote{label} and \sQuote{color} vertex attributes and the #' \sQuote{arrow.mode} and \sQuote{arrow.size} edge attributes. \sQuote{all} #' keep all graph, vertex and edge attributes, \sQuote{none} keeps none of #' them. #' @return A list with the components: \item{layout}{The layout, a two-column #' matrix, for the original graph vertices.} \item{layout.dummy}{The layout for #' the dummy vertices, a two column matrix.} \item{extd_graph}{The original #' graph, extended with dummy vertices. The \sQuote{dummy} vertex attribute is #' set on this graph, it is a logical attributes, and it tells you whether the #' vertex is a dummy vertex. The \sQuote{layout} graph attribute is also set, #' and it is the layout matrix for all (original and dummy) vertices.} #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references K. Sugiyama, S. Tagawa and M. Toda, "Methods for Visual #' Understanding of Hierarchical Systems". IEEE Transactions on Systems, Man #' and Cybernetics 11(2):109-125, 1981. #' @export #' @importFrom utils head #' @family graph layouts #' @keywords graphs #' @examples #' #' ## Data taken from http://tehnick-8.narod.ru/dc_clients/ #' DC <- graph_from_literal("DC++" -+ #' "LinuxDC++":"BCDC++":"EiskaltDC++":"StrongDC++":"DiCe!++", #' "LinuxDC++" -+ "FreeDC++", "BCDC++" -+ "StrongDC++", #' "FreeDC++" -+ "BMDC++":"EiskaltDC++", #' "StrongDC++" -+ "AirDC++":"zK++":"ApexDC++":"TkDC++", #' "StrongDC++" -+ "StrongDC++ SQLite":"RSX++", #' "ApexDC++" -+ "FlylinkDC++ ver <= 4xx", #' "ApexDC++" -+ "ApexDC++ Speed-Mod":"DiCe!++", #' "StrongDC++ SQLite" -+ "FlylinkDC++ ver >= 5xx", #' "ApexDC++ Speed-Mod" -+ "FlylinkDC++ ver <= 4xx", #' "ApexDC++ Speed-Mod" -+ "GreylinkDC++", #' "FlylinkDC++ ver <= 4xx" -+ "FlylinkDC++ ver >= 5xx", #' "FlylinkDC++ ver <= 4xx" -+ AvaLink, #' "GreylinkDC++" -+ AvaLink:"RayLinkDC++":"SparkDC++":PeLink) #' #' ## Use edge types #' E(DC)$lty <- 1 #' E(DC)["BCDC++" %->% "StrongDC++"]$lty <- 2 #' E(DC)["FreeDC++" %->% "EiskaltDC++"]$lty <- 2 #' E(DC)["ApexDC++" %->% "FlylinkDC++ ver <= 4xx"]$lty <- 2 #' E(DC)["ApexDC++" %->% "DiCe!++"]$lty <- 2 #' E(DC)["StrongDC++ SQLite" %->% "FlylinkDC++ ver >= 5xx"]$lty <- 2 #' E(DC)["GreylinkDC++" %->% "AvaLink"]$lty <- 2 #' #' ## Layers, as on the plot #' layers <- list(c("DC++"), #' c("LinuxDC++", "BCDC++"), #' c("FreeDC++", "StrongDC++"), #' c("BMDC++", "EiskaltDC++", "AirDC++", "zK++", "ApexDC++", #' "TkDC++", "RSX++"), #' c("StrongDC++ SQLite", "ApexDC++ Speed-Mod", "DiCe!++"), #' c("FlylinkDC++ ver <= 4xx", "GreylinkDC++"), #' c("FlylinkDC++ ver >= 5xx", "AvaLink", "RayLinkDC++", #' "SparkDC++", "PeLink")) #' #' ## Check that we have all nodes #' all(sort(unlist(layers)) == sort(V(DC)$name)) #' #' ## Add some graphical parameters #' V(DC)$color <- "white" #' V(DC)$shape <- "rectangle" #' V(DC)$size <- 20 #' V(DC)$size2 <- 10 #' V(DC)$label <- lapply(V(DC)$name, function(x) #' paste(strwrap(x, 12), collapse="\n")) #' E(DC)$arrow.size <- 0.5 #' #' ## Create a similar layout using the predefined layers #' lay1 <- layout_with_sugiyama(DC, layers=apply(sapply(layers, #' function(x) V(DC)$name %in% x), 1, which)) #' #' ## Simple plot, not very nice #' par(mar=rep(.1, 4)) #' plot(DC, layout=lay1$layout, vertex.label.cex=0.5) #' #' ## Sugiyama plot #' plot(lay1$extd_graph, vertex.label.cex=0.5) #' #' ## The same with automatic layer calculation #' ## Keep vertex/edge attributes in the extended graph #' lay2 <- layout_with_sugiyama(DC, attributes="all") #' plot(lay2$extd_graph, vertex.label.cex=0.5) #' #' ## Another example, from the following paper: #' ## Markus Eiglsperger, Martin Siebenhaller, Michael Kaufmann: #' ## An Efficient Implementation of Sugiyama's Algorithm for #' ## Layered Graph Drawing, Journal of Graph Algorithms and #' ## Applications 9, 305--325 (2005). #' #' ex <- graph_from_literal( 0 -+ 29: 6: 5:20: 4, #' 1 -+ 12, #' 2 -+ 23: 8, #' 3 -+ 4, #' 4, #' 5 -+ 2:10:14:26: 4: 3, #' 6 -+ 9:29:25:21:13, #' 7, #' 8 -+ 20:16, #' 9 -+ 28: 4, #' 10 -+ 27, #' 11 -+ 9:16, #' 12 -+ 9:19, #' 13 -+ 20, #' 14 -+ 10, #' 15 -+ 16:27, #' 16 -+ 27, #' 17 -+ 3, #' 18 -+ 13, #' 19 -+ 9, #' 20 -+ 4, #' 21 -+ 22, #' 22 -+ 8: 9, #' 23 -+ 9:24, #' 24 -+ 12:15:28, #' 25 -+ 11, #' 26 -+ 18, #' 27 -+ 13:19, #' 28 -+ 7, #' 29 -+ 25 ) #' #' layers <- list( 0, c(5, 17), c(2, 14, 26, 3), c(23, 10, 18), c(1, 24), #' 12, 6, c(29,21), c(25,22), c(11,8,15), 16, 27, c(13,19), #' c(9, 20), c(4, 28), 7 ) #' #' layex <- layout_with_sugiyama(ex, layers=apply(sapply(layers, #' function(x) V(ex)$name %in% as.character(x)), #' 1, which)) #' #' origvert <- c(rep(TRUE, vcount(ex)), rep(FALSE, nrow(layex$layout.dummy))) #' realedge <- as_edgelist(layex$extd_graph)[,2] <= vcount(ex) #' plot(layex$extd_graph, vertex.label.cex=0.5, #' edge.arrow.size=.5, #' vertex.size=ifelse(origvert, 5, 0), #' vertex.shape=ifelse(origvert, "square", "none"), #' vertex.label=ifelse(origvert, V(ex)$name, ""), #' edge.arrow.mode=ifelse(realedge, 2, 0)) #' layout_with_sugiyama <- function(graph, layers=NULL, hgap=1, vgap=1, maxiter=100, weights=NULL, attributes=c("default", "all", "none")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.null(layers)) layers <- as.numeric(layers)-1 hgap <- as.numeric(hgap) vgap <- as.numeric(vgap) maxiter <- as.integer(maxiter) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } attributes <- igraph.match.arg(attributes) on.exit(.Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_layout_sugiyama, graph, layers, hgap, vgap, maxiter, weights) # Flip the y coordinates, more natural this way res$res[,2] <- max(res$res[,2]) - res$res[,2] + 1 # Separate real and dummy vertices vc <- vcount(graph) res$layout <- res$res[seq_len(vc),] if (nrow(res$res)==vc) { res$layout.dummy <- matrix(NA_real_, nrow=0, ncol=2) } else { res$layout.dummy <- res$res[(vc+1):nrow(res$res),] } # Add some attributes to the extended graph E(res$extd_graph)$orig <- res$extd_to_orig_eids res$extd_to_orig_eids <- NULL res$extd_graph <- set_vertex_attr(res$extd_graph, "dummy", value=c(rep(FALSE, vc), rep(TRUE, nrow(res$res)-vc))) res$extd_graph$layout <- rbind(res$layout, res$layout.dummy) if (attributes=="default" || attributes=="all") { if ("size" %in% vertex_attr_names(graph)) { V(res$extd_graph)$size <- 0 V(res$extd_graph)$size[ !V(res$extd_graph)$dummy ] <- V(graph)$size } if ("size2" %in% vertex_attr_names(graph)) { V(res$extd_graph)$size2 <- 0 V(res$extd_graph)$size2[ !V(res$extd_graph)$dummy ] <- V(graph)$size2 } if ("shape" %in% vertex_attr_names(graph)) { V(res$extd_graph)$shape <- "none" V(res$extd_graph)$shape[ !V(res$extd_graph)$dummy ] <- V(graph)$shape } if ("label" %in% vertex_attr_names(graph)) { V(res$extd_graph)$label <- "" V(res$extd_graph)$label[ !V(res$extd_graph)$dummy ] <- V(graph)$label } if ("color" %in% vertex_attr_names(graph)) { V(res$extd_graph)$color <- head(V(graph)$color, 1) V(res$extd_graph)$color[ !V(res$extd_graph)$dummy ] <- V(graph)$color } eetar <- as_edgelist(res$extd_graph, names=FALSE)[,2] E(res$extd_graph)$arrow.mode <- 0 if ("arrow.mode" %in% edge_attr_names(graph)) { E(res$extd_graph)$arrow.mode[ eetar <= vc ] <- E(graph)$arrow.mode } else { E(res$extd_graph)$arrow.mode[ eetar <= vc ] <- is_directed(graph) * 2 } if ("arrow.size" %in% edge_attr_names(graph)) { E(res$extd_graph)$arrow.size <- 0 E(res$extd_graph)$arrow.size[ eetar <= vc ] <- E(graph)$arrow.size } } if (attributes=="all") { gatt <- setdiff(graph_attr_names(graph), "layout") vatt <- setdiff(vertex_attr_names(graph), c("size", "size2", "shape", "label", "color")) eatt <- setdiff(edge_attr_names(graph), c("arrow.mode", "arrow.size")) for (ga in gatt) { res$extd_graph <- set_graph_attr(res$extd_graph, ga, graph_attr(graph, ga)) } for (va in vatt) { notdummy <- which(!V(res$extd_graph)$dummy) res$extd_graph <- set_vertex_attr(res$extd_graph, va, notdummy, vertex_attr(graph, va)) } for (ea in eatt) { eanew <- edge_attr(graph, ea)[E(res$extd_graph)$orig] res$extd_graph <- set_edge_attr(res$extd_graph, ea, value=eanew) } } res$res <- NULL res } #' @rdname layout_with_sugiyama #' @param ... Passed to \code{layout_with_sugiyama}. #' @export with_sugiyama <- function(...) layout_spec(layout_with_sugiyama, ...) ## ---------------------------------------------------------------- #' Merging graph layouts #' #' Place several graphs on the same layout #' #' \code{merge_coords} takes a list of graphs and a list of coordinates and #' places the graphs in a common layout. The method to use is chosen via the #' \code{method} parameter, although right now only the \code{dla} method is #' implemented. #' #' The \code{dla} method covers the graph with circles. Then it sorts the #' graphs based on the number of vertices first and places the largest graph at #' the center of the layout. Then the other graphs are placed in decreasing #' order via a DLA (diffision limited aggregation) algorithm: the graph is #' placed randomly on a circle far away from the center and a random walk is #' conducted until the graph walks into the larger graphs already placed or #' walks too far from the center of the layout. #' #' The \code{layout_components} function disassembles the graph first into #' maximal connected components and calls the supplied \code{layout} function #' for each component separately. Finally it merges the layouts via calling #' \code{merge_coords}. #' #' @aliases layout.merge piecewise.layout #' @param graphs A list of graph objects. #' @param layouts A list of two-column matrices. #' @param method Character constant giving the method to use. Right now only #' \code{dla} is implemented. #' @param layout A function object, the layout function to use. #' @param \dots Additional arguments to pass to the \code{layout} layout #' function. #' @return A matrix with two columns and as many lines as the total number of #' vertices in the graphs. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{plot.igraph}}, \code{\link{tkplot}}, #' \code{\link{layout}}, \code{\link{disjoint_union}} #' @export #' @family graph layouts #' @keywords graphs #' @examples #' #' # create 20 scale-free graphs and place them in a common layout #' graphs <- lapply(sample(5:20, 20, replace=TRUE), #' barabasi.game, directed=FALSE) #' layouts <- lapply(graphs, layout_with_kk) #' lay <- merge_coords(graphs, layouts) #' g <- disjoint_union(graphs) #' \dontrun{plot(g, layout=lay, vertex.size=3, labels=NA, edge.color="black")} merge_coords <- function(graphs, layouts, method="dla") { if (!all(sapply(graphs, is_igraph))) { stop("Not a graph object") } if (method == "dla") { on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_layout_merge_dla, graphs, layouts) } else { stop("Invalid `method'.") } res } #' Normalize coordinates for plotting graphs #' #' Rescale coordinates linearly to be within given bounds. #' #' \code{norm_coords} normalizes a layout, it linearly transforms each #' coordinate separately to fit into the given limits. #' #' @aliases layout.norm #' @param layout A matrix with two or three columns, the layout to normalize. #' @param xmin,xmax The limits for the first coordinate, if one of them or both #' are \code{NULL} then no normalization is performed along this direction. #' @param ymin,ymax The limits for the second coordinate, if one of them or #' both are \code{NULL} then no normalization is performed along this #' direction. #' @param zmin,zmax The limits for the third coordinate, if one of them or both #' are \code{NULL} then no normalization is performed along this direction. #' @return A numeric matrix with at the same dimension as \code{layout}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @family graph layouts #' @keywords graphs norm_coords <- function(layout, xmin=-1, xmax=1, ymin=-1, ymax=1, zmin=-1, zmax=1) { if (!is.matrix(layout)) { stop("`layout' not a matrix") } if (ncol(layout) != 2 && ncol(layout) != 3) { stop("`layout' should have 2 or three columns") } if (!is.null(xmin) && !is.null(xmax)) { layout[,1] <- .layout.norm.col(layout[,1], xmin, xmax) } if (!is.null(ymin) && !is.null(ymax)) { layout[,2] <- .layout.norm.col(layout[,2], ymin, ymax) } if (ncol(layout)==3 && !is.null(zmin) && !is.null(zmax)) { layout[,3] <- .layout.norm.col(layout[,3], zmin, zmax) } layout } .layout.norm.col <- function(v, min, max) { vr <- range(v) if (vr[1]==vr[2]) { fac <- 1 } else { fac <- (max-min)/(vr[2]-vr[1]) } (v-vr[1]) * fac + min } #' @rdname merge_coords #' @aliases piecewise.layout #' @param graph The input graph. #' @export layout_components <- function(graph, layout=layout_with_kk, ...) { if (!is_igraph(graph)) { stop("Not a graph object") } V(graph)$id <- seq(vcount(graph)) gl <- decompose(graph) ll <- lapply(gl, layout, ...) l <- merge_coords(gl, ll) l[ unlist(sapply(gl, vertex_attr, "id")), ] <- l[] l } #' Spring layout, this was removed from igraph #' #' Now it calls the Fruchterman-Reingold layout, with a warning. #' #' @param graph Input graph. #' @param ... Extra arguments are ignored. #' @return Layout coordinates, a two column matrix. #' #' @export layout.spring <- function(graph, ...) { warning("Spring layout was removed, we use Fruchterman-Reingold instead.") layout_with_fr(graph) } #' SVD layout, this was removed from igraph #' #' Now it calls the Fruchterman-Reingold layout, with a warning. #' #' @param graph Input graph. #' @param ... Extra arguments are ignored. #' @return Layout coordinates, a two column matrix. #' #' @export layout.svd <- function(graph, ...) { warning("SVD layout was removed, we use Fruchterman-Reingold instead.") layout_with_fr(graph) } #' Grid Fruchterman-Reingold layout, this was removed from igraph #' #' Now it calls the Fruchterman-Reingold layout, with a warning. #' #' @param graph Input graph. #' @param ... Extra arguments are ignored. #' @return Layout coordinates, a two column matrix. #' #' @export layout.fruchterman.reingold.grid <- function(graph, ...) { warning("Grid Fruchterman-Reingold layout was removed,\n", "we use Fruchterman-Reingold instead.") layout_with_fr(graph) } igraph/R/fit.R0000644000175100001440000001774713177712334012700 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Pit a power-law (khmm a Yule really) distribution, # this is a common degree distribution in networks ################################################################### #' Fitting a power-law distribution function to discrete data #' #' \code{fit_power_law} fits a power-law distribution to a data set. #' #' This function fits a power-law distribution to a vector containing samples #' from a distribution (that is assumed to follow a power-law of course). In a #' power-law distribution, it is generally assumed that \eqn{P(X=x)} is #' proportional to \eqn{x^{-alpha}}{x^-alpha}, where \eqn{x} is a positive #' number and \eqn{\alpha}{alpha} is greater than 1. In many real-world cases, #' the power-law behaviour kicks in only above a threshold value #' \eqn{x_{min}}{xmin}. The goal of this function is to determine #' \eqn{\alpha}{alpha} if \eqn{x_{min}}{xmin} is given, or to determine #' \eqn{x_{min}}{xmin} and the corresponding value of \eqn{\alpha}{alpha}. #' #' \code{fit_power_law} provides two maximum likelihood implementations. If #' the \code{implementation} argument is \sQuote{\code{R.mle}}, then the BFGS #' optimization (see \link[stats4]{mle}) algorithm is applied. The additional #' arguments are passed to the mle function, so it is possible to change the #' optimization method and/or its parameters. This implementation can #' \emph{not} to fit the \eqn{x_{min}}{xmin} argument, so use the #' \sQuote{\code{plfit}} implementation if you want to do that. #' #' The \sQuote{\code{plfit}} implementation also uses the maximum likelihood #' principle to determine \eqn{\alpha}{alpha} for a given \eqn{x_{min}}{xmin}; #' When \eqn{x_{min}}{xmin} is not given in advance, the algorithm will attempt #' to find itsoptimal value for which the \eqn{p}-value of a Kolmogorov-Smirnov #' test between the fitted distribution and the original sample is the largest. #' The function uses the method of Clauset, Shalizi and Newman to calculate the #' parameters of the fitted distribution. See references below for the details. #' #' @aliases power.law.fit #' @param x The data to fit, a numeric vector. For implementation #' \sQuote{\code{R.mle}} the data must be integer values. For the #' \sQuote{\code{plfit}} implementation non-integer values might be present and #' then a continuous power-law distribution is fitted. #' @param xmin Numeric scalar, or \code{NULL}. The lower bound for fitting the #' power-law. If \code{NULL}, the smallest value in \code{x} will be used for #' the \sQuote{\code{R.mle}} implementation, and its value will be #' automatically determined for the \sQuote{\code{plfit}} implementation. This #' argument makes it possible to fit only the tail of the distribution. #' @param start Numeric scalar. The initial value of the exponent for the #' minimizing function, for the \sQuote{\code{R.mle}} implementation. Ususally #' it is safe to leave this untouched. #' @param force.continuous Logical scalar. Whether to force a continuous #' distribution for the \sQuote{\code{plfit}} implementation, even if the #' sample vector contains integer values only (by chance). If this argument is #' false, igraph will assume a continuous distribution if at least one sample #' is non-integer and assume a discrete distribution otherwise. #' @param implementation Character scalar. Which implementation to use. See #' details below. #' @param \dots Additional arguments, passed to the maximum likelihood #' optimizing function, \code{\link[stats4]{mle}}, if the \sQuote{\code{R.mle}} #' implementation is chosen. It is ignored by the \sQuote{\code{plfit}} #' implementation. #' @return Depends on the \code{implementation} argument. If it is #' \sQuote{\code{R.mle}}, then an object with class \sQuote{\code{mle}}. It can #' be used to calculate confidence intervals and log-likelihood. See #' \code{\link[stats4]{mle-class}} for details. #' #' If \code{implementation} is \sQuote{\code{plfit}}, then the result is a #' named list with entries: \item{continuous}{Logical scalar, whether the #' fitted power-law distribution was continuous or discrete.} #' \item{alpha}{Numeric scalar, the exponent of the fitted power-law #' distribution.} \item{xmin}{Numeric scalar, the minimum value from which the #' power-law distribution was fitted. In other words, only the values larger #' than \code{xmin} were used from the input vector.} \item{logLik}{Numeric #' scalar, the log-likelihood of the fitted parameters.} \item{KS.stat}{Numeric #' scalar, the test statistic of a Kolmogorov-Smirnov test that compares the #' fitted distribution with the input vector. Smaller scores denote better #' fit.} \item{KS.p}{Numeric scalar, the p-value of the Kolmogorov-Smirnov #' test. Small p-values (less than 0.05) indicate that the test rejected the #' hypothesis that the original data could have been drawn from the fitted #' power-law distribution.} #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @seealso \code{\link[stats4]{mle}} #' @references Power laws, Pareto distributions and Zipf's law, M. E. J. #' Newman, \emph{Contemporary Physics}, 46, 323-351, 2005. #' #' Aaron Clauset, Cosma R .Shalizi and Mark E.J. Newman: Power-law #' distributions in empirical data. SIAM Review 51(4):661-703, 2009. #' @export #' @keywords graphs #' @examples #' #' # This should approximately yield the correct exponent 3 #' g <- barabasi.game(1000) # increase this number to have a better estimate #' d <- degree(g, mode="in") #' fit1 <- fit_power_law(d+1, 10) #' fit2 <- fit_power_law(d+1, 10, implementation="R.mle") #' #' fit1$alpha #' stats4::coef(fit2) #' fit1$logLik #' stats4::logLik(fit2) #' fit_power_law <- function(x, xmin=NULL, start=2, force.continuous=FALSE, implementation=c("plfit", "R.mle"), ...) { implementation <- igraph.match.arg(implementation) if (implementation == "r.mle") { power.law.fit.old(x, xmin, start, ...) } else if (implementation == "plfit") { if (is.null(xmin)) xmin <- -1 power.law.fit.new(x, xmin=xmin, force.continuous=force.continuous) } } power.law.fit.old <- function(x, xmin=NULL, start=2, ...) { if (length(x) == 0) { stop("zero length vector") } if (length(x) == 1) { stop("vector should be at least of length two") } if (is.null(xmin)) { xmin <- min(x) } n <- length(x) x <- x[ x >= xmin] if (length(x) != n) { n <- length(x) } # mlogl <- function(alpha) { # if (xmin > 1) { # C <- 1/(1/(alpha-1)-sum(beta(1:(xmin-1), alpha))) # } else { # C <- alpha-1 # } # -n*log(C)-sum(lbeta(x, alpha)) # } mlogl <- function(alpha) { C <- 1/sum( (xmin:10000)^-alpha ) -n*log(C)+alpha*sum(log(x)) } alpha <- stats4::mle(mlogl, start=list(alpha=start), ...) alpha } power.law.fit.new <- function(data, xmin=-1, force.continuous=FALSE) { # Argument checks data <- as.numeric(data) xmin <- as.numeric(xmin) force.continuous <- as.logical(force.continuous) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_power_law_fit, data, xmin, force.continuous) res } igraph/R/rewire.R0000644000175100001440000001105113177712334013371 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Rewiring edges of a graph #' #' See the links below for the implemented rewiring methods. #' #' @param graph The graph to rewire #' @param with A function call to one of the rewiring methods, #' see details below. #' @return The rewired graph. #' #' @family rewiring functions #' @export rewire #' @examples #' g <- make_ring(10) #' g %>% #' rewire(each_edge(p = .1, loops = FALSE)) %>% #' plot(layout=layout_in_circle) #' print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10))) rewire <- function(graph, with) { if (! is(with, "igraph_rewiring_method")) { stop("'with' is not an igraph rewiring method") } do_call(with$fun, list(graph), .args = with$args) } #' Graph rewiring while preserving the degree distribution #' #' This function can be used together with \code{\link{rewire}} to #' randomly rewire the edges while preserving the original graph's degree #' distribution. #' #' The rewiring algorithm chooses two arbitrary edges in each step ((a,b) #' and (c,d)) and substitutes them with (a,d) and (c,b), if they not #' already exists in the graph. The algorithm does not create multiple #' edges. #' #' @param loops Whether to allow destroying and creating loop edges. #' @param niter Number of rewiring trials to perform. #' #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @family rewiring functions #' @seealso \code{\link{sample_degseq}} #' @export #' @keywords graphs #' @examples #' g <- make_ring(10) #' g %>% #' rewire(keeping_degseq(niter = 20)) %>% #' degree() #' print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10))) keeping_degseq <- function(loops = FALSE, niter = 100) { method <- list( fun = rewire_keeping_degseq, args = list(loops = loops, niter = niter) ) add_class(method, "igraph_rewiring_method") } rewire_keeping_degseq <- function(graph, loops, niter) { if (!is_igraph(graph)) { stop("Not a graph object") } loops <- as.logical(loops) mode <- if (loops) 1 else 0 on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_rewire, graph, as.numeric(niter), as.numeric(mode)) } #' Rewires the endpoints of the edges of a graph to a random vertex #' #' This function can be used together with \code{\link{rewire}}. #' This method rewires the endpoints of the edges with a constant probability #' uniformly randomly to a new vertex in a graph. #' #' Note that this method might create graphs with multiple and/or loop edges. #' #' @param prob The rewiring probability, a real number between zero and one. #' @param loops Logical scalar, whether loop edges are allowed in the rewired #' graph. #' @param multiple Logical scalar, whether multiple edges are allowed int the #' generated graph. #' #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @family rewiring functions #' @export #' @keywords graphs #' @examples #' #' # Some random shortcuts shorten the distances on a lattice #' g <- make_lattice(length = 100, dim = 1, nei = 5) #' mean_distance(g) #' g <- rewire(g, each_edge(prob = 0.05)) #' mean_distance(g) each_edge <- function(prob, loops = FALSE, multiple = FALSE) { method <- list( fun = rewire_each_edge, args = list(prob = prob, loops = loops, multiple = multiple) ) add_class(method, "igraph_rewiring_method") } rewire_each_edge <- function(graph, prob, loops=FALSE, multiple=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_rewire_edges, graph, as.numeric(prob), as.logical(loops), as.logical(multiple)) } igraph/R/paths.R0000644000175100001440000002150513177712334013220 0ustar hornikusers## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' List all simple paths from one source #' #' This function lists are simple paths from one source vertex to another #' vertex or vertices. A path is simple if the vertices it visits are not #' visited more than once. #' #' Note that potentially there are exponentially many paths between two #' vertices of a graph, and you may run out of memory when using this #' function, if your graph is lattice-like. #' #' This function currently ignored multiple and loop edges. #' #' @param graph The input graph. #' @param from The source vertex. #' @param to The target vertex of vertices. Defaults to all vertices. #' @param mode Character constant, gives whether the shortest paths to or #' from the given vertices should be calculated for directed graphs. If #' \code{out} then the shortest paths \emph{from} the vertex, if \code{in} #' then \emph{to} it will be considered. If \code{all}, the default, then #' the corresponding undirected graph will be used, ie. not directed paths #' are searched. This argument is ignored for undirected graphs. #' @return A list of integer vectors, each integer vector is a path from #' the source vertex to one of the target vertices. A path is given by its #' vertex ids. #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' all_simple_paths(g, 1, 5) #' all_simple_paths(g, 1, c(3,5)) #' #' @export all_simple_paths <- function(graph, from, to = V(graph), mode = c("out", "in", "all", "total")) { ## Argument checks if (!is_igraph(graph)) stop("Not a graph object") from <- as.igraph.vs(graph, from) to <- as.igraph.vs(graph, to) mode <- switch(igraph.match.arg(mode), "out" = 1, "in" = 2, "all" = 3, "total" = 3) on.exit( .Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_get_all_simple_paths, graph, from - 1, to - 1, mode) res <- get.all.simple.paths.pp(res) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' Directed acyclic graphs #' #' This function tests whether the given graph is a DAG, a directed acyclic #' graph. #' #' \code{is_dag} checks whether there is a directed cycle in the graph. If not, #' the graph is a DAG. #' #' @aliases is.dag is_dag #' @param graph The input graph. It may be undirected, in which case #' \code{FALSE} is reported. #' @return A logical vector of length one. #' @author Tamas Nepusz \email{ntamas@@gmail.com} for the C code, Gabor Csardi #' \email{csardi.gabor@@gmail.com} for the R interface. #' @keywords graphs #' @examples #' #' g <- make_tree(10) #' is_dag(g) #' g2 <- g + edge(5,1) #' is_dag(g2) #' @export #' @include auto.R is_dag <- is_dag #' Maximum cardinality search #' #' Maximum cardinality search is a simple ordering a vertices that is useful in #' determining the chordality of a graph. #' #' Maximum cardinality search visits the vertices in such an order that every #' time the vertex with the most already visited neighbors is visited. Ties are #' broken randomly. #' #' The algorithm provides a simple basis for deciding whether a graph is #' chordal, see References below, and also \code{\link{is_chordal}}. #' #' @aliases maximum.cardinality.search max_cardinality #' @param graph The input graph. It may be directed, but edge directions are #' ignored, as the algorithm is defined for undirected graphs. #' @return A list with two components: \item{alpha}{Numeric vector. The #' vertices ordered according to the maximum cardinality search.} #' \item{alpham1}{Numeric vector. The inverse of \code{alpha}.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{is_chordal}} #' @references Robert E Tarjan and Mihalis Yannakakis. (1984). Simple #' linear-time algorithms to test chordality of graphs, test acyclicity of #' hypergraphs, and selectively reduce acyclic hypergraphs. \emph{SIAM Journal #' of Computation} 13, 566--579. #' @keywords graphs #' @examples #' #' ## The examples from the Tarjan-Yannakakis paper #' g1 <- graph_from_literal(A-B:C:I, B-A:C:D, C-A:B:E:H, D-B:E:F, #' E-C:D:F:H, F-D:E:G, G-F:H, H-C:E:G:I, #' I-A:H) #' max_cardinality(g1) #' is_chordal(g1, fillin=TRUE) #' #' g2 <- graph_from_literal(A-B:E, B-A:E:F:D, C-E:D:G, D-B:F:E:C:G, #' E-A:B:C:D:F, F-B:D:E, G-C:D:H:I, H-G:I:J, #' I-G:H:J, J-H:I) #' max_cardinality(g2) #' is_chordal(g2, fillin=TRUE) max_cardinality <- max_cardinality #' Eccentricity of the vertices in a graph #' #' The eccentricity of a vertex is its shortest path distance from the farthest #' other node in the graph. #' #' The eccentricity of a vertex is calculated by measuring the shortest #' distance from (or to) the vertex, to (or from) all vertices in the graph, #' and taking the maximum. #' #' This implementation ignores vertex pairs that are in different components. #' Isolate vertices have eccentricity zero. #' #' @param graph The input graph, it can be directed or undirected. #' @param vids The vertices for which the eccentricity is calculated. #' @param mode Character constant, gives whether the shortest paths to or from #' the given vertices should be calculated for directed graphs. If \code{out} #' then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} #' it will be considered. If \code{all}, the default, then the corresponding #' undirected graph will be used, edge directions will be ignored. This #' argument is ignored for undirected graphs. #' @return \code{eccentricity} returns a numeric vector, containing the #' eccentricity score of each given vertex. #' @seealso \code{\link{radius}} for a related concept, #' \code{\link{distances}} for general shortest path calculations. #' @references Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, #' 1994. #' @examples #' g <- make_star(10, mode="undirected") #' eccentricity(g) #' @export #' @include auto.R eccentricity <- eccentricity #' Radius of a graph #' #' The eccentricity of a vertex is its shortest path distance from the #' farthest other node in the graph. The smallest eccentricity in a graph #' is called its radius #' #' The eccentricity of a vertex is calculated by measuring the shortest #' distance from (or to) the vertex, to (or from) all vertices in the #' graph, and taking the maximum. #' #' This implementation ignores vertex pairs that are in different #' components. Isolate vertices have eccentricity zero. #' #' @param graph The input graph, it can be directed or undirected. #' @param mode Character constant, gives whether the shortest paths to or from #' the given vertices should be calculated for directed graphs. If \code{out} #' then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} #' it will be considered. If \code{all}, the default, then the corresponding #' undirected graph will be used, edge directions will be ignored. This #' argument is ignored for undirected graphs. #' @return A numeric scalar, the radius of the graph. #' @seealso \code{\link{eccentricity}} for the underlying #' calculations, code{\link{distances}} for general shortest path #' calculations. #' @references Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, #' 1994. #' @examples #' g <- make_star(10, mode="undirected") #' eccentricity(g) #' radius(g) #' @export #' @include auto.R radius <- radius #' @rdname distances #' @param directed Whether to consider directed paths in directed graphs, #' this argument is ignored for undirected graphs. #' @param unconnected What to do if the graph is unconnected (not #' strongly connected if directed paths are considered). If TRUE only #' the lengths of the existing paths are considered and averaged; if #' FALSE the length of the missing paths are counted having length #' \code{vcount(graph)}, one longer than the longest possible geodesic #' in the network. #' @export distance_table <- distance_table igraph/R/embedding.R0000644000175100001440000003621113177712334014017 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Spectral Embedding of Adjacency Matrices #' #' Spectral decomposition of the adjacency matrices of graphs. #' #' This function computes a \code{no}-dimensional Euclidean representation of #' the graph based on its adjacency matrix, \eqn{A}. This representation is #' computed via the singular value decomposition of the adjacency matrix, #' \eqn{A=UDV^T}.In the case, where the graph is a random dot product graph #' generated using latent position vectors in \eqn{R^{no}} for each vertex, the #' embedding will provide an estimate of these latent vectors. #' #' For undirected graphs the latent positions are calculated as #' \eqn{X=U^{no}D^{1/2}}{U[no] sqrt(D[no])}, where \eqn{U^{no}}{U[no]} equals #' to the first \code{no} columns of \eqn{U}, and \eqn{D^{1/2}}{sqrt(D[no])} is #' a diagonal matrix containing the top \code{no} singular values on the #' diagonal. #' #' For directed graphs the embedding is defined as the pair #' \eqn{X=U^{no}D^{1/2}}{U[no] sqrt(D[no])} and \eqn{Y=V^{no}D^{1/2}}{V[no] #' sqrt(D[no])}. (For undirected graphs \eqn{U=V}, so it is enough to keep one #' of them.) #' #' @param graph The input graph, directed or undirected. #' @param no An integer scalar. This value is the embedding dimension of the #' spectral embedding. Should be smaller than the number of vertices. The #' largest \code{no}-dimensional non-zero singular values are used for the #' spectral embedding. #' @param weights Optional positive weight vector for calculating a weighted #' embedding. If the graph has a \code{weight} edge attribute, then this is #' used by default. In a weighted embedding, the edge weights are used instead #' of the binary adjacencny matrix. #' @param which Which eigenvalues (or singular values, for directed graphs) to #' use. \sQuote{lm} means the ones with the largest magnitude, \sQuote{la} is #' the ones (algebraic) largest, and \sQuote{sa} is the (algebraic) smallest #' eigenvalues. The default is \sQuote{lm}. Note that for directed graphs #' \sQuote{la} and \sQuote{lm} are the equivalent, because the singular values #' are used for the ordering. #' @param scaled Logical scalar, if \code{FALSE}, then \eqn{U} and \eqn{V} are #' returned instead of \eqn{X} and \eqn{Y}. #' @param cvec A numeric vector, its length is the number vertices in the #' graph. This vector is added to the diagonal of the adjacency matrix. #' @param options A named list containing the parameters for the SVD #' computation algorithm in ARPACK. By default, the list of values is assigned #' the values given by \code{\link{igraph.arpack.default}}. #' @return A list containing with entries: \item{X}{Estimated latent positions, #' an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} #' \item{Y}{\code{NULL} for undirected graphs, the second half of the latent #' positions for directed graphs, an \code{n} times \code{no} matrix, \code{n} #' is the number of vertices.} \item{D}{The eigenvalues (for undirected graphs) #' or the singular values (for directed graphs) calculated by the algorithm.} #' \item{options}{A named list, information about the underlying ARPACK #' computation. See \code{\link{arpack}} for the details.} #' @seealso \code{\link{sample_dot_product}} #' @references Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A #' Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, #' \emph{Journal of the American Statistical Association}, Vol. 107(499), 2012 #' @keywords graphs #' @examples #' #' ## A small graph #' lpvs <- matrix(rnorm(200), 20, 10) #' lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) #' RDP <- sample_dot_product(lpvs) #' embed <- embed_adjacency_matrix(RDP, 5) #' @export #' @include auto.R embed_adjacency_matrix <- embed_adjacency_matrix #' Dimensionality selection for singular values using profile likelihood. #' #' Select the number of significant singular values, by finding the #' \sQuote{elbow} of the scree plot, in a principled way. #' #' The input of the function is a numeric vector which contains the measure of #' \sQuote{importance} for each dimension. #' #' For spectral embedding, these are the singular values of the adjacency #' matrix. The singular values are assumed to be generated from a Gaussian #' mixture distribution with two components that have different means and same #' variance. The dimensionality \eqn{d} is chosen to maximize the likelihood #' when the \eqn{d} largest singular values are assigned to one component of #' the mixture and the rest of the singular values assigned to the other #' component. #' #' This function can also be used for the general separation problem, where we #' assume that the left and the right of the vector are coming from two Normal #' distributions, with different means, and we want to know their border. See #' examples below. #' #' @param sv A numeric vector, the ordered singular values. #' @return A numeric scalar, the estimate of \eqn{d}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{embed_adjacency_matrix}} #' @references M. Zhu, and A. Ghodsi (2006). Automatic dimensionality selection #' from the scree plot via the use of profile likelihood. \emph{Computational #' Statistics and Data Analysis}, Vol. 51, 918--930. #' @keywords graphs #' @examples #' #' # Generate the two groups of singular values with #' # Gaussian mixture of two components that have different means #' sing.vals <- c( rnorm (10, mean=1, sd=1), rnorm(10, mean=3, sd=1) ) #' dim.chosen <- dim_select(sing.vals) #' dim.chosen #' #' # Sample random vectors with multivariate normal distribution #' # and normalize to unit length #' lpvs <- matrix(rnorm(200), 10, 20) #' lpvs <- apply(lpvs, 2, function(x) { (abs(x) / sqrt(sum(x^2))) }) #' RDP.graph <- sample_dot_product(lpvs) #' dim_select( embed_adjacency_matrix(RDP.graph, 10)$D ) #' #' # Sample random vectors with the Dirichlet distribution #' lpvs.dir <- sample_dirichlet(n=20, rep(1, 10)) #' RDP.graph.2 <- sample_dot_product(lpvs.dir) #' dim_select( embed_adjacency_matrix(RDP.graph.2, 10)$D ) #' #' # Sample random vectors from hypersphere with radius 1. #' lpvs.sph <- sample_sphere_surface(dim=10, n=20, radius=1) #' RDP.graph.3 <- sample_dot_product(lpvs.sph) #' dim_select( embed_adjacency_matrix(RDP.graph.3, 10)$D ) #' #' @export dim_select <- dim_select #' Spectral Embedding of the Laplacian of a Graph #' #' Spectral decomposition of Laplacian matrices of graphs. #' #' This function computes a \code{no}-dimensional Euclidean representation of #' the graph based on its Laplacian matrix, \eqn{L}. This representation is #' computed via the singular value decomposition of the Laplacian matrix. #' #' They are essentially doing the same as \code{\link{embed_adjacency_matrix}}, #' but work on the Laplacian matrix, instead of the adjacency matrix. #' #' @param graph The input graph, directed or undirected. #' @param no An integer scalar. This value is the embedding dimension of the #' spectral embedding. Should be smaller than the number of vertices. The #' largest \code{no}-dimensional non-zero singular values are used for the #' spectral embedding. #' @param weights Optional positive weight vector for calculating a weighted #' embedding. If the graph has a \code{weight} edge attribute, then this is #' used by default. For weighted embedding, edge weights are used instead #' of the binary adjacency matrix, and vertex stregth (see #' \code{\link{strength}}) is used instead of the degrees. #' @param which Which eigenvalues (or singular values, for directed graphs) to #' use. \sQuote{lm} means the ones with the largest magnitude, \sQuote{la} is #' the ones (algebraic) largest, and \sQuote{sa} is the (algebraic) smallest #' eigenvalues. The default is \sQuote{lm}. Note that for directed graphs #' \sQuote{la} and \sQuote{lm} are the equivalent, because the singular values #' are used for the ordering. #' @param degmode TODO #' @param type The type of the Laplacian to use. Various definitions exist for #' the Laplacian of a graph, and one can choose between them with this #' argument. #' #' Possible values: \code{D-A} means \eqn{D-A} where \eqn{D} is the degree #' matrix and \eqn{A} is the adjacency matrix; \code{DAD} means #' \eqn{D^{1/2}}{D^1/2} times \eqn{A} times \eqn{D^{1/2}{D^1/2}}, #' \eqn{D^{1/2}}{D^1/2} is the inverse of the square root of the degree matrix; #' \code{I-DAD} means \eqn{I-D^{1/2}}{I-D^1/2}, where \eqn{I} is the identity #' matrix. \code{OAP} is \eqn{O^{1/2}AP^{1/2}}{O^1/2 A P^1/2}, where #' \eqn{O^{1/2}}{O^1/2} is the inverse of the square root of the out-degree #' matrix and \eqn{P^{1/2}}{P^1/2} is the same for the in-degree matrix. #' #' \code{OAP} is not defined for undireted graphs, and is the only defined type #' for directed graphs. #' #' The default (i.e. type \code{default}) is to use \code{D-A} for undirected #' graphs and \code{OAP} for directed graphs. #' @param scaled Logical scalar, if \code{FALSE}, then \eqn{U} and \eqn{V} are #' returned instead of \eqn{X} and \eqn{Y}. #' @param options A named list containing the parameters for the SVD #' computation algorithm in ARPACK. By default, the list of values is assigned #' the values given by \code{\link{igraph.arpack.default}}. #' @return A list containing with entries: \item{X}{Estimated latent positions, #' an \code{n} times \code{no} matrix, \code{n} is the number of vertices.} #' \item{Y}{\code{NULL} for undirected graphs, the second half of the latent #' positions for directed graphs, an \code{n} times \code{no} matrix, \code{n} #' is the number of vertices.} \item{D}{The eigenvalues (for undirected graphs) #' or the singular values (for directed graphs) calculated by the algorithm.} #' \item{options}{A named list, information about the underlying ARPACK #' computation. See \code{\link{arpack}} for the details.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{embed_adjacency_matrix}}, #' \code{\link{sample_dot_product}} #' @references Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A #' Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, #' \emph{Journal of the American Statistical Association}, Vol. 107(499), 2012 #' @keywords graphs #' @examples #' #' ## A small graph #' lpvs <- matrix(rnorm(200), 20, 10) #' lpvs <- apply(lpvs, 2, function(x) { return (abs(x)/sqrt(sum(x^2))) }) #' RDP <- sample_dot_product(lpvs) #' embed <- embed_laplacian_matrix(RDP, 5) embed_laplacian_matrix <- embed_laplacian_matrix #' Sample vectors uniformly from the surface of a sphere #' #' Sample finite-dimensional vectors to use as latent position vectors in #' random dot product graphs #' #' \code{sample_sphere_surface} generates uniform samples from \eqn{S^{dim-1}} #' (the \code{(dim-1)}-sphere) with radius \code{radius}, i.e. the Euclidean #' norm of the samples equal \code{radius}. #' #' @param dim Integer scalar, the dimension of the random vectors. #' @param n Integer scalar, the sample size. #' @param radius Numeric scalar, the radius of the sphere to sample. #' @param positive Logical scalar, whether to sample from the positive orthant #' of the sphere. #' @return A \code{dim} (length of the \code{alpha} vector for #' \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample #' vectors. #' #' @family latent position vector samplers #' #' @export #' @examples #' lpvs.sph <- sample_sphere_surface(dim=10, n=20, radius=1) #' RDP.graph.3 <- sample_dot_product(lpvs.sph) #' vec.norm <- apply(lpvs.sph, 2, function(x) { sum(x^2) }) #' vec.norm sample_sphere_surface <- function(dim, n=1, radius=1, positive=TRUE) { # Argument checks dim <- as.integer(dim) n <- as.integer(n) radius <- as.numeric(radius) positive <- as.logical(positive) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_sphere_surface, dim, n, radius, positive) res } #' Sample vectors uniformly from the volume of a sphere #' #' Sample finite-dimensional vectors to use as latent position vectors in #' random dot product graphs #' #' \code{sample_sphere_volume} generates uniform samples from \eqn{S^{dim-1}} #' (the \code{(dim-1)}-sphere) i.e. the Euclidean norm of the samples is #' smaller or equal to \code{radius}. #' #' @param dim Integer scalar, the dimension of the random vectors. #' @param n Integer scalar, the sample size. #' @param radius Numeric scalar, the radius of the sphere to sample. #' @param positive Logical scalar, whether to sample from the positive orthant #' of the sphere. #' @return A \code{dim} (length of the \code{alpha} vector for #' \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample #' vectors. #' #' @family latent position vector samplers #' #' @export #' @examples #' lpvs.sph.vol <- sample_sphere_volume(dim=10, n=20, radius=1) #' RDP.graph.4 <- sample_dot_product(lpvs.sph.vol) #' vec.norm <- apply(lpvs.sph.vol, 2, function(x) { sum(x^2) }) #' vec.norm sample_sphere_volume <- function(dim, n=1, radius=1, positive=TRUE) { # Argument checks dim <- as.integer(dim) n <- as.integer(n) radius <- as.numeric(radius) positive <- as.logical(positive) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_sphere_volume, dim, n, radius, positive) res } #' Sample from a Dirichlet distribution #' #' Sample finite-dimensional vectors to use as latent position vectors in #' random dot product graphs #' #' \code{sample_dirichlet} generates samples from the Dirichlet distribution #' with given \eqn{\alpha}{alpha} parameter. The sample is drawn from #' \code{length(alpha)-1}-simplex. #' #' @param n Integer scalar, the sample size. #' @param alpha Numeric vector, the vector of \eqn{\alpha}{alpha} parameter for #' the Dirichlet distribution. #' @return A \code{dim} (length of the \code{alpha} vector for #' \code{sample_dirichlet}) times \code{n} matrix, whose columns are the sample #' vectors. #' #' @family latent position vector samplers #' #' @export #' @examples #' lpvs.dir <- sample_dirichlet(n=20, alpha=rep(1, 10)) #' RDP.graph.2 <- sample_dot_product(lpvs.dir) #' colSums(lpvs.dir) sample_dirichlet <- function(n, alpha) { # Argument checks n <- as.integer(n) alpha <- as.numeric(alpha) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_sample_dirichlet, n, alpha) res } igraph/R/cocitation.R0000644000175100001440000000607513177712334014242 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Cocitation coupling #' #' Two vertices are cocited if there is another vertex citing both of them. #' \code{cocitation} siply counts how many types two vertices are cocited. The #' bibliographic coupling of two vertices is the number of other vertices they #' both cite, \code{bibcoupling} calculates this. #' #' \code{cocitation} calculates the cocitation counts for the vertices in the #' \code{v} argument and all vertices in the graph. #' #' \code{bibcoupling} calculates the bibliographic coupling for vertices in #' \code{v} and all vertices in the graph. #' #' Calculating the cocitation or bibliographic coupling for only one vertex #' costs the same amount of computation as for all vertices. This might change #' in the future. #' #' @aliases cocitation bibcoupling #' @param graph The graph object to analyze #' @param v Vertex sequence or numeric vector, the vertex ids for which the #' cocitation or bibliographic coupling values we want to calculate. The #' default is all vertices. #' @return A numeric matrix with \code{length(v)} lines and #' \code{vcount(graph)} columns. Element \code{(i,j)} contains the cocitation #' or bibliographic coupling for vertices \code{v[i]} and \code{j}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' cocitation(g) #' bibcoupling(g) #' cocitation <- function(graph, v=V(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } v <- as.igraph.vs(graph, v) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_cocitation, graph, v-1) if (igraph_opt("add.vertex.names") && is_named(graph)) { rownames(res) <- vertex_attr(graph, "name", v) colnames(res) <- vertex_attr(graph, "name") } res } #' @export bibcoupling <- function(graph, v=V(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } v <- as.igraph.vs(graph, v) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_bibcoupling, graph, v-1) if (igraph_opt("add.vertex.names") && is_named(graph)) { rownames(res) <- vertex_attr(graph, "name", v) colnames(res) <- vertex_attr(graph, "name") } res } igraph/R/interface.R0000644000175100001440000003571413240142531014033 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Structure building ################################################################### #' Add edges to a graph #' #' The new edges are given as a vertex sequence, e.g. internal #' numeric vertex ids, or vertex names. The first edge points from #' \code{edges[1]} to \code{edges[2]}, the second from \code{edges[3]} #' to \code{edges[4]}, etc. #' #' If attributes are supplied, and they are not present in the graph, #' their values for the original edges of the graph are set to \code{NA}. #' #' @param graph The input graph #' @param edges The edges to add, a vertex sequence with even number #' of vertices. #' @param ... Additional arguments, they must be named, #' and they will be added as edge attributes, for the newly added #' edges. See also details below. #' @param attr A named list, its elements will be added #' as edge attributes, for the newly added edges. See also details #' below. #' @return The graph, with the edges (and attributes) added. #' #' @export #' #' @aliases add.edges #' @family functions for manipulating graph structure #' #' @examples #' g <- make_empty_graph(n = 5) %>% #' add_edges(c(1,2, 2,3, 3,4, 4,5)) %>% #' set_edge_attr("color", value = "red") %>% #' add_edges(c(5,1), color = "green") #' E(g)[[]] #' plot(g) add_edges <- function(graph, edges, ..., attr = list()) { if (!is_igraph(graph)) { stop("Not a graph object") } attrs <- list(...) attrs <- append(attrs, attr) nam <- names(attrs) if (length(attrs) != 0 && (is.null(nam) || any(nam==""))) { stop("please supply names for attributes") } edges.orig <- ecount(graph) on.exit( .Call(C_R_igraph_finalizer) ) graph <- .Call(C_R_igraph_add_edges, graph, as.igraph.vs(graph, edges)-1) edges.new <- ecount(graph) if (edges.new-edges.orig != 0) { idx <- seq(edges.orig+1, edges.new) } else { idx <- numeric() } eattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L) for (i in seq(attrs)) { eattrs[[nam[i]]][idx] <- attrs[[nam[i]]] } .Call(C_R_igraph_mybracket2_set, graph, 9L, 4L, eattrs) } #' Add vertices to a graph #' #' If attributes are supplied, and they are not present in the graph, #' their values for the original vertices of the graph are set to #' \code{NA}. #' #' @param graph The input graph. #' @param nv The number of vertices to add. #' @param ... Additional arguments, they must be named, #' and they will be added as vertex attributes, for the newly added #' vertices. See also details below. #' @param attr A named list, its elements will be added #' as vertex attributes, for the newly added vertices. See also details #' below. #' @return The graph, with the vertices (and attributes) added. #' #' @aliases add.vertices #' @family functions for manipulating graph structure #' #' @export #' @examples #' g <- make_empty_graph() %>% #' add_vertices(3, color = "red") %>% #' add_vertices(2, color = "green") %>% #' add_edges(c(1,2, 2,3, 3,4, 4,5)) #' g #' V(g)[[]] #' plot(g) add_vertices <- function(graph, nv, ..., attr=list()) { if (!is_igraph(graph)) { stop("Not a graph object") } attrs <- list(...) attrs <- append(attrs, attr) nam <- names(attrs) if (length(attrs) != 0 && (is.null(nam) || any(nam==""))) { stop("please supply names for attributes") } vertices.orig <- vcount(graph) on.exit( .Call(C_R_igraph_finalizer) ) graph <- .Call(C_R_igraph_add_vertices, graph, as.numeric(nv)) vertices.new <- vcount(graph) if (vertices.new-vertices.orig != 0) { idx <- seq(vertices.orig+1, vertices.new) } else { idx <- numeric() } vattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) for (i in seq(attrs)) { vattrs[[nam[i]]][idx] <- attrs[[nam[i]]] } .Call(C_R_igraph_mybracket2_set, graph, 9L, 3L, vattrs) } #' Delete edges from a graph #' #' @param graph The input graph. #' @param edges The edges to remove, specified as an edge sequence. #' @return The graph, with the edges removed. #' #' @aliases delete.edges #' @family functions for manipulating graph structure #' #' @export #' @examples #' g <- make_ring(10) %>% #' delete_edges(seq(1, 9, by = 2)) #' g #' #' g <- make_ring(10) %>% #' delete_edges("10|1") #' g delete_edges <- function(graph, edges) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_delete_edges, graph, as.igraph.es(graph, edges)-1) } #' Delete vertices from a graph #' #' @param graph The input graph. #' @param v The vertices to remove, a vertex sequence. #' @return The graph, with the vertices removed. #' #' @aliases delete.vertices #' @family functions for manipulating graph structure #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) #' g #' V(g) #' #' g2 <- delete_vertices(g, c(1,5)) %>% #' delete_vertices("B") #' g2 #' V(g2) delete_vertices <- function(graph, v) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_delete_vertices, graph, as.igraph.vs(graph, v)-1) } ################################################################### # Structure query ################################################################### #' The size of the graph (number of edges) #' #' \code{ecount} of an alias of this function. #' #' @param graph The graph. #' @return Numeric scalar, the number of edges. #' #' @aliases ecount #' @family structural queries #' #' @export #' @examples #' g <- sample_gnp(100, 2/100) #' gsize(g) #' #' # Number of edges in a G(n,p) graph #' replicate(100, sample_gnp(10, 1/2), simplify = FALSE) %>% #' vapply(gsize, 0) %>% #' hist() gsize <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_ecount, graph) } #' Neighboring (adjacent) vertices in a graph #' #' A vertex is a neighbor of another one (in other words, the two #' vertices are adjacent), if they are incident to the same edge. #' #' @param graph The input graph. #' @param v The vertex of which the adjacent vertices are queried. #' @param mode Whether to query outgoing (\sQuote{out}), incoming #' (\sQuote{in}) edges, or both types (\sQuote{all}). This is #' ignored for undirected graphs. #' @return A vertex sequence containing the neighbors of the input vertex. #' #' @family structural queries #' #' @export #' @examples #' g <- make_graph("Zachary") #' n1 <- neighbors(g, 1) #' n34 <- neighbors(g, 34) #' intersection(n1, n34) neighbors <- function(graph, v, mode = c("out", "in", "all", "total")) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.character(mode)) { mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3, "total"=3) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_neighbors, graph, as.igraph.vs(graph, v)-1, as.numeric(mode)) V(graph)[res + 1] } #' Incident edges of a vertex in a graph #' #' @param graph The input graph. #' @param v The vertex of which the indicent edges are queried. #' @param mode Whether to query outgoing (\sQuote{out}), incoming #' (\sQuote{in}) edges, or both types (\sQuote{all}). This is #' ignored for undirected graphs. #' @return An edge sequence containing the incident edges of #' the input vertex. #' #' @family structural queries #' #' @export #' @examples #' g <- make_graph("Zachary") #' incident(g, 1) #' incident(g, 34) incident <- function(graph, v, mode=c("all", "out", "in", "total")) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is_directed(graph)) { mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3, "total"=3) } else { mode=1 } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_incident, graph, as.igraph.vs(graph, v)-1, as.numeric(mode)) + 1L if (igraph_opt("return.vs.es")) res <- create_es(graph, res) res } #' Check whether a graph is directed #' #' @param graph The input graph #' @return Logical scalar, whether the graph is directed. #' #' @aliases is.directed #' @family structural queries #' #' @export #' @examples #' g <- make_ring(10) #' is_directed(g) #' #' g2 <- make_ring(10, directed = TRUE) #' is_directed(g2) is_directed <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_is_directed, graph) } #' Incident vertices of some graph edges #' #' @param graph The input graph #' @param es The sequence of edges to query #' @param names Whether to return vertex names or #' numeric vertex ids. By default vertex names are used. #' @return A two column matrix of vertex names or vertex ids. #' #' @aliases get.edges get.edge #' @family structural queries #' #' @export #' @importFrom stats na.omit #' @examples #' g <- make_ring(5) #' ends(g, E(g)) ends <- function(graph, es, names = TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } es2 <- as.igraph.es(graph, na.omit(es)) - 1 res <- matrix(NA_integer_, ncol = length(es), nrow = 2) on.exit( .Call(C_R_igraph_finalizer) ) if (length(es) == 1) { res[, !is.na(es)] <- .Call(C_R_igraph_get_edge, graph, es2) + 1 } else { res[, !is.na(es)] <- .Call(C_R_igraph_edges, graph, es2) + 1 } if (names && is_named(graph)) { res <- vertex_attr(graph, "name")[res] } matrix(res, ncol = 2, byrow = TRUE) } #' @export get.edges <- function(graph, es) { ends(graph, es, names = FALSE) } #' Find the edge ids based on the incident vertices of the edges #' #' Find the edges in an igraph graph that have the specified end points. This #' function handles multi-graph (graphs with multiple edges) and can consider #' or ignore the edge directions in directed graphs. #' #' igraph vertex ids are natural numbers, starting from one, up to the number #' of vertices in the graph. Similarly, edges are also numbered from one, up to #' the number of edges. #' #' This function allows finding the edges of the graph, via their incident #' vertices. #' #' @param graph The input graph. #' @param vp The indicent vertices, given as vertex ids or symbolic vertex #' names. They are interpreted pairwise, i.e. the first and second are used for #' the first edge, the third and fourth for the second, etc. #' @param directed Logical scalar, whether to consider edge directions in #' directed graphs. This argument is ignored for undirected graphs. #' @param error Logical scalar, whether to report an error if an edge is not #' found in the graph. If \code{FALSE}, then no error is reported, and zero is #' returned for the non-existant edge(s). #' @param multi Logical scalar, whether to handle multiple edges properly. If #' \code{FALSE}, and a pair of vertices are given twice (or more), then always #' the same edge id is reported back for them. If \code{TRUE}, then the edge #' ids of multiple edges are correctly reported. #' @return A numeric vector of edge ids, one for each pair of input vertices. #' If there is no edge in the input graph for a given pair of vertices, then #' zero is reported. (If the \code{error} argument is \code{FALSE}.) #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @family structural queries #' #' @examples #' #' g <- make_ring(10) #' ei <- get.edge.ids(g, c(1,2, 4,5)) #' E(g)[ei] #' #' ## non-existant edge #' get.edge.ids(g, c(2,1, 1,4, 5,4)) #' get.edge.ids <- function(graph, vp, directed=TRUE, error=FALSE, multi=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_get_eids, graph, as.igraph.vs(graph, vp)-1, as.logical(directed), as.logical(error), as.logical(multi)) + 1 } #' Order (number of vertices) of a graph #' #' @param graph The graph #' @return Number of vertices, numeric scalar. #' #' @aliases vcount #' @family structural queries #' #' @export #' @examples #' g <- make_ring(10) #' gorder(g) gorder <- gorder #' Adjacent vertices of multiple vertices in a graph #' #' This function is similar to \code{\link{neighbors}}, but it queries #' the adjacent vertices for multiple vertices at once. #' #' @param graph Input graph. #' @param v The vertices to query. #' @param mode Whether to query outgoing (\sQuote{out}), incoming #' (\sQuote{in}) edges, or both types (\sQuote{all}). This is #' ignored for undirected graphs. #' @return A list of vertex sequences. #' #' @family structural queries #' @export #' @examples #' g <- make_graph("Zachary") #' adjacent_vertices(g, c(1, 34)) adjacent_vertices <- function(graph, v, mode = c("out", "in", "all", "total")) { if (!is_igraph(graph)) stop("Not a graph object") vv <- as.igraph.vs(graph, v) - 1 mode <- switch(match.arg(mode), "out" = 1, "in" = 2, "all" = 3, "total" = 3) on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_adjacent_vertices, graph, vv, mode) if (igraph_opt("return.vs.es")) { res <- lapply(res, function(x) create_vs(graph, x + 1)) } if (is_named(graph)) names(res) <- V(graph)$name[vv + 1] res } #' Incident edges of multiple vertices in a graph #' #' This function is similar to \code{\link{incident}}, but it #' queries multiple vertices at once. #' #' @param graph Input graph. #' @param v The vertices to query #' @param mode Whether to query outgoing (\sQuote{out}), incoming #' (\sQuote{in}) edges, or both types (\sQuote{all}). This is #' ignored for undirected graphs. #' @return A list of edge sequences. #' #' @family structural queries #' @export #' @examples #' g <- make_graph("Zachary") #' incident_edges(g, c(1, 34)) incident_edges <- function(graph, v, mode = c("out", "in", "all", "total")) { if (!is_igraph(graph)) stop("Not a graph object") vv <- as.igraph.vs(graph, v) - 1 mode <- switch(match.arg(mode), "out" = 1, "in" = 2, "all" = 3, "total" = 3) on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_incident_edges, graph, vv, mode) if (igraph_opt("return.vs.es")) { res <- lapply(res, function(x) create_es(graph, x + 1)) } if (is_named(graph)) names(res) <- V(graph)$name[vv + 1] res } igraph/R/assortativity.R0000644000175100001440000001175413240142531015016 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Assortativity coefficient #' #' The assortativity coefficient is positive is similar vertices (based on some #' external property) tend to connect to each, and negative otherwise. #' #' The assortativity coefficient measures the level of homophyly of the graph, #' based on some vertex labeling or values assigned to vertices. If the #' coefficient is high, that means that connected vertices tend to have the #' same labels or similar assigned values. #' #' M.E.J. Newman defined two kinds of assortativity coefficients, the first one #' is for categorical labels of vertices. \code{assortativity_nominal} #' calculates this measure. It is defines as #' #' \deqn{r=\frac{\sum_i e_{ii}-\sum_i a_i b_i}{1-\sum_i a_i b_i}}{ #' r=(sum(e(i,i), i) - sum(a(i)b(i), i)) / (1 - sum(a(i)b(i), i))} #' #' where \eqn{e_{ij}}{e(i,j)} is the fraction of edges connecting vertices of #' type \eqn{i} and \eqn{j}, \eqn{a_i=\sum_j e_{ij}}{a(i)=sum(e(i,j), j)} and #' \eqn{b_j=\sum_i e_{ij}}{b(j)=sum(e(i,j), i)}. #' #' The second assortativity variant is based on values assigned to the #' vertices. \code{assortativity} calculates this measure. It is defined as #' #' \deqn{r=\frac1{\sigma_q^2}\sum_{jk} jk(e_{jk}-q_j q_k)}{ #' sum(jk(e(j,k)-q(j)q(k)), j, k) / sigma(q)^2} #' #' for undirected graphs (\eqn{q_i=\sum_j e_{ij}}{q(i)=sum(e(i,j), j)}) and as #' #' \deqn{r=\frac1{\sigma_o\sigma_i}\sum_{jk}jk(e_{jk}-q_j^o q_k^i)}{ #' sum(jk(e(j,k)-qout(j)qin(k)), j, k) / sigma(qin) / sigma(qout) } #' #' for directed ones. Here \eqn{q_i^o=\sum_j e_{ij}}{qout(i)=sum(e(i,j), j)}, #' \eqn{q_i^i=\sum_j e_{ji}}{qin(i)=sum(e(j,i), j)}, moreover, #' \eqn{\sigma_q}{sigma(q)}, \eqn{sigma_o}{sigma(qout)} and #' \eqn{sigma_i}{sigma(qin)} are the standard deviations of \eqn{q}, #' \eqn{q^o}{qout} and \eqn{q^i}{qin}, respectively. #' #' The reason of the difference is that in directed networks the relationship #' is not symmetric, so it is possible to assign different values to the #' outgoing and the incoming end of the edges. #' #' \code{assortativity_degree} uses vertex degree (minus one) as vertex values #' and calls \code{assortativity}. #' #' @aliases assortativity assortativity.degree assortativity_degree #' assortativity.nominal assortativity_nominal #' @param graph The input graph, it can be directed or undirected. #' @param types Vector giving the vertex types. They as assumed to be integer #' numbers, starting with one. Non-integer values are converted to integers #' with \code{\link{as.integer}}. #' @param types1 The vertex values, these can be arbitrary numeric values. #' @param types2 A second value vector to be using for the incoming edges when #' calculating assortativity for a directed graph. Supply \code{NULL} here if #' you want to use the same values for outgoing and incoming edges. This #' argument is ignored (with a warning) if it is not \code{NULL} and undirected #' assortativity coefficient is being calculated. #' @param directed Logical scalar, whether to consider edge directions for #' directed graphs. This argument is ignored for undirected graphs. Supply #' \code{TRUE} here to do the natural thing, i.e. use directed version of the #' measure for directed graphs and the undirected version for undirected #' graphs. #' @return A single real number. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references M. E. J. Newman: Mixing patterns in networks, \emph{Phys. Rev. #' E} 67, 026126 (2003) \url{http://arxiv.org/abs/cond-mat/0209450} #' #' M. E. J. Newman: Assortative mixing in networks, \emph{Phys. Rev. Lett.} 89, #' 208701 (2002) \url{http://arxiv.org/abs/cond-mat/0205405/} #' @keywords graphs #' @examples #' #' # random network, close to zero #' assortativity_degree(sample_gnp(10000, 3/10000)) #' #' # BA model, tends to be dissortative #' assortativity_degree(sample_pa(10000, m=4)) #' @include auto.R assortativity <- assortativity #' @rdname assortativity assortativity_nominal <- assortativity_nominal #' @rdname assortativity assortativity_degree <- assortativity_degree igraph/R/glet.R0000644000175100001440000001304713177712334013036 0ustar hornikusers #' Graphlet decomposition of a graph #' #' Graphlet decomposition models a weighted undirected graph via the union of #' potentially overlapping dense social groups. This is done by a two-step #' algorithm. In the first step a candidate set of groups (a candidate basis) #' is created by finding cliques if the thresholded input graph. In the second #' step these the graph is projected on the candidate basis, resulting a weight #' coefficient for each clique in the candidate basis. #' #' igraph contains three functions for performing the graph decomponsition of a #' graph. The first is \code{graphlets}, which performed both steps on the #' method and returns a list of subgraphs, with their corresponding weights. #' The second and third functions correspond to the first and second steps of #' the algorithm, and they are useful if the user wishes to perform them #' individually: \code{graphlet_basis} and \code{graphlet_proj}. #' #' @aliases graphlets graphlets.project graphlet_proj graphlet_basis #' graphlets.candidate.basis #' @param graph The input graph, edge directions are ignored. Only simple graph #' (i.e. graphs without self-loops and multiple edges) are supported. #' @param weights Edge weights. If the graph has a \code{weight} edge attribute #' and this argument is \code{NULL} (the default), then the \code{weight} edge #' attribute is used. #' @param niter Integer scalar, the number of iterations to perform. #' @param cliques A list of vertex ids, the graphlet basis to use for the #' projection. #' @param Mu Starting weights for the projection. #' @return \code{graphlets} returns a list with two members: \item{cliques}{A #' list of subgraphs, the candidate graphlet basis. Each subgraph is give by a #' vector of vertex ids.} \item{Mu}{The weights of the subgraphs in graphlet #' basis.} #' #' \code{graphlet_basis} returns a list of two elements: \item{cliques}{A list #' of subgraphs, the candidate graphlet basis. Each subgraph is give by a #' vector of vertex ids.} \item{thresholds}{The weight thresholds used for #' finding the subgraphs.} #' #' \code{graphlet_proj} return a numeric vector, the weights of the graphlet #' basis subgraphs. #' @examples #' #' ## Create an example graph first #' D1 <- matrix(0, 5, 5) #' D2 <- matrix(0, 5, 5) #' D3 <- matrix(0, 5, 5) #' D1[1:3, 1:3] <- 2 #' D2[3:5, 3:5] <- 3 #' D3[2:5, 2:5] <- 1 #' #' g <- simplify(graph_from_adjacency_matrix(D1 + D2 + D3, #' mode="undirected", weighted=TRUE)) #' V(g)$color <- "white" #' E(g)$label <- E(g)$weight #' E(g)$label.cex <- 2 #' E(g)$color <- "black" #' layout(matrix(1:6, nrow=2, byrow=TRUE)) #' co <- layout_with_kk(g) #' par(mar=c(1,1,1,1)) #' plot(g, layout=co) #' #' ## Calculate graphlets #' gl <- graphlets(g, niter=1000) #' #' ## Plot graphlets #' for (i in 1:length(gl$cliques)) { #' sel <- gl$cliques[[i]] #' V(g)$color <- "white" #' V(g)[sel]$color <- "#E495A5" #' E(g)$width <- 1 #' E(g)[ V(g)[sel] %--% V(g)[sel] ]$width <- 2 #' E(g)$label <- "" #' E(g)[ width == 2 ]$label <- round(gl$Mu[i], 2) #' E(g)$color <- "black" #' E(g)[ width == 2 ]$color <- "#E495A5" #' plot(g, layout=co) #' } #' @export graphlet_basis <- function(graph, weights=NULL) { ## Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } ## Drop all attributes, we don't want to deal with them, TODO graph2 <- graph graph2[[9]] <- list(c(1,0,1), list(), list(), list()) on.exit( .Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_graphlets_candidate_basis, graph2, weights) res } #' @rdname graphlet_basis #' @export graphlet_proj <- function(graph, weights=NULL, cliques, niter=1000, Mu=rep(1, length(cliques))) { # Argument checks if (!is.igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } Mu <- as.numeric(Mu) niter <- as.integer(niter) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_graphlets_project, graph, weights, cliques, Mu, niter) res } ################# ## Example code function() { library(igraph) fitandplot <- function(g, gl) { g <- simplify(g) V(g)$color <- "white" E(g)$label <- E(g)$weight E(g)$label.cex <- 2 E(g)$color <- "black" plot.new() layout(matrix(1:6, nrow=2, byrow=TRUE)) co <- layout_with_kk(g) par(mar=c(1,1,1,1)) plot(g, layout=co) for (i in 1:length(gl$Bc)) { sel <- gl$Bc[[i]] V(g)$color <- "white" V(g)[sel]$color <- "#E495A5" E(g)$width <- 1 E(g)[ V(g)[sel] %--% V(g)[sel] ]$width <- 2 E(g)$label <- "" E(g)[ width == 2 ]$label <- round(gl$Muc[i], 2) E(g)$color <- "black" E(g)[ width == 2 ]$color <- "#E495A5" plot(g, layout=co) } } D1 <- matrix(0, 5, 5) D2 <- matrix(0, 5, 5) D3 <- matrix(0, 5, 5) D1[1:3, 1:3] <- 2 D2[3:5, 3:5] <- 3 D3[2:5, 2:5] <- 1 g <- graph_from_adjacency_matrix(D1 + D2 + D3, mode="undirected", weighted=TRUE) gl <- graphlets(g, iter=1000) fitandplot(g, gl) ## Project another graph on the graphlets set.seed(42) g2 <- set_edge_attr(g, "weight", value=sample(E(g)$weight)) gl2 <- graphlet_proj(g2, gl$Bc, 1000) fitandplot(g2, gl2) } igraph/R/versions.R0000644000175100001440000000723413177712334013754 0ustar hornikusers ## ---------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ---------------------------------------------------------------------- #' Igraph data structure versions #' #' Igraph's internal data representation changes sometimes between #' versions. This means that it is not possible to use igraph objects #' that were created (and possibly saved to a file) with an older #' igraph version. #' #' \code{graph_version} queries the current data format, #' or the data format of a possibly older igraph graph. #' #' \code{\link{upgrade_graph}} can convert an older data format #' to the current one. #' #' @param graph The input graph. If it is missing, then #' the version number of the current data format is returned. #' @return A character scalar. #' #' @seealso upgrade_graph to convert the data format of a graph. #' @export graph_version <- function(graph) { if (missing(graph)) { "0.8.0" } else { stopifnot(is_igraph(graph)) .Call(C_R_igraph_graph_version, graph) } } #' Igraph data structure versions #' #' Igraph's internal data representation changes sometimes between #' versions. This means that it is not possible to use igraph objects #' that were created (and possibly saved to a file) with an older #' igraph version. #' #' \code{\link{graph_version}} queries the current data format, #' or the data format of a possibly older igraph graph. #' #' \code{upgrade_graph} can convert an older data format #' to the current one. #' #' @param graph The input graph. #' @return The graph in the current format. #' #' @seealso graph_version to check the current data format version #' or the version of a graph. #' @export upgrade_graph <- function(graph) { stopifnot(is_igraph(graph)) g_ver <- graph_version(graph) p_ver <- graph_version() if (g_ver < p_ver) { if ((g_ver == "0.4.0" && p_ver == "0.8.0")) { .Call(C_R_igraph_add_env, graph) } else if (g_ver == "0.7.999" && p_ver == "0.8.0") { .Call(C_R_igraph_add_version_to_env, graph) } else { stop("Don't know how to upgrade graph from ", g_ver, " to ", p_ver) } } else if (g_ver > p_ver) { stop("Don't know how to downgrade graph from ", g_ver, " to ", p_ver) } else { graph } } ## Check that the version is the latest check_version <- function(graph) { if (graph_version() != graph_version(graph)) { stop("This graph was created by an old(er) igraph version.\n", " Call upgrade_graph() on it to use with the current igraph version") } } warn_version <- function(graph) { if (graph_version() != graph_version(graph)) { message("This graph was created by an old(er) igraph version.\n", " Call upgrade_graph() on it to use with the current igraph version\n", " For now we convert it on the fly...") TRUE } else { FALSE } } igraph/R/layout_drl.R0000644000175100001440000002766713177712334014276 0ustar hornikusers #' The DrL graph layout generator #' #' DrL is a force-directed graph layout toolbox focused on real-world #' large-scale graphs, developed by Shawn Martin and colleagues at Sandia #' National Laboratories. #' #' This function implements the force-directed DrL layout generator. #' #' The generator has the following parameters: \describe{ \item{edge.cut}{Edge #' cutting is done in the late stages of the algorithm in order to achieve less #' dense layouts. Edges are cut if there is a lot of stress on them (a large #' value in the objective function sum). The edge cutting parameter is a value #' between 0 and 1 with 0 representing no edge cutting and 1 representing #' maximal edge cutting. } \item{init.iterations}{Number of iterations in the #' first phase.} \item{init.temperature}{Start temperature, first phase.} #' \item{init.attraction}{Attraction, first phase.} #' \item{init.damping.mult}{Damping, first phase.} #' \item{liquid.iterations}{Number of iterations, liquid phase.} #' \item{liquid.temperature}{Start temperature, liquid phase.} #' \item{liquid.attraction}{Attraction, liquid phase.} #' \item{liquid.damping.mult}{Damping, liquid phase.} #' \item{expansion.iterations}{Number of iterations, expansion phase.} #' \item{expansion.temperature}{Start temperature, expansion phase.} #' \item{expansion.attraction}{Attraction, expansion phase.} #' \item{expansion.damping.mult}{Damping, expansion phase.} #' \item{cooldown.iterations}{Number of iterations, cooldown phase.} #' \item{cooldown.temperature}{Start temperature, cooldown phase.} #' \item{cooldown.attraction}{Attraction, cooldown phase.} #' \item{cooldown.damping.mult}{Damping, cooldown phase.} #' \item{crunch.iterations}{Number of iterations, crunch phase.} #' \item{crunch.temperature}{Start temperature, crunch phase.} #' \item{crunch.attraction}{Attraction, crunch phase.} #' \item{crunch.damping.mult}{Damping, crunch phase.} #' \item{simmer.iterations}{Number of iterations, simmer phase.} #' \item{simmer.temperature}{Start temperature, simmer phase.} #' \item{simmer.attraction}{Attraction, simmer phase.} #' \item{simmer.damping.mult}{Damping, simmer phase.} #' #' There are five pre-defined parameter settings as well, these are called #' \code{drl_defaults$default}, \code{drl_defaults$coarsen}, #' \code{drl_defaults$coarsest}, \code{drl_defaults$refine} and #' \code{drl_defaults$final}. } #' #' @aliases layout.drl drl_defaults igraph.drl.coarsen #' igraph.drl.coarsest igraph.drl.default igraph.drl.final #' igraph.drl.refine #' @param graph The input graph, in can be directed or undirected. #' @param use.seed Logical scalar, whether to use the coordinates given in the #' \code{seed} argument as a starting point. #' @param seed A matrix with two columns, the starting coordinates for the #' vertices is \code{use.seed} is \code{TRUE}. It is ignored otherwise. #' @param options Options for the layout generator, a named list. See details #' below. #' @param weights Optional edge weights. Supply \code{NULL} here if you want to #' weight edges equally. By default the \code{weight} edge attribute is used if #' the graph has one. Larger weights correspond to stronger connections, #' and the vertices will be placed closer to each other. #' @param fixed Logical vector, it can be used to fix some vertices. All #' vertices for which it is \code{TRUE} are kept at the coordinates supplied in #' the \code{seed} matrix. It is ignored it \code{NULL} or if \code{use.seed} #' is \code{FALSE}. #' @param dim Either \sQuote{2} or \sQuote{3}, it specifies whether we want a #' two dimensional or a three dimensional layout. Note that because of the #' nature of the DrL algorithm, the three dimensional layout takes #' significantly longer to compute. #' @return A numeric matrix with two columns. #' @author Shawn Martin (\url{http://www.cs.otago.ac.nz/homepages/smartin/}) #' and Gabor Csardi \email{csardi.gabor@@gmail.com} for the R/igraph interface #' and the three dimensional version. #' @seealso \code{\link{layout}} for other layout generators. #' @references See the following technical report: Martin, S., Brown, W.M., #' Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) Layout. SAND #' Reports, 2008. 2936: p. 1-10. #' @export #' @importFrom stats runif #' @keywords graphs #' @examples #' #' g <- as.undirected(sample_pa(100, m=1)) #' l <- layout_with_drl(g, options=list(simmer.attraction=0)) #' \dontrun{ #' plot(g, layout=l, vertex.size=3, vertex.label=NA) #' } #' layout_with_drl <- function(graph, use.seed = FALSE, seed=matrix(runif(vcount(graph)*2), ncol=2), options=drl_defaults$default, weights=E(graph)$weight, fixed=NULL, dim=2) { if (!is_igraph(graph)) { stop("Not a graph object") } if (dim != 2 && dim != 3) { stop("`dim' must be 2 or 3") } use.seed <- as.logical(use.seed) seed <- as.matrix(seed) options.tmp <- drl_defaults$default options.tmp[names(options)] <- options options <- options.tmp if (!is.null(weights)) { weights <- as.numeric(weights) } if (!is.null(fixed)) { fixed <- as.logical(fixed) } on.exit(.Call(C_R_igraph_finalizer)) if (dim==2) { res <- .Call(C_R_igraph_layout_drl, graph, seed, use.seed, options, weights, fixed) } else { res <- .Call(C_R_igraph_layout_drl_3d, graph, seed, use.seed, options, weights, fixed) } res } #' @rdname layout_with_drl #' @param ... Passed to \code{layout_with_drl}. #' @export with_drl <- function(...) layout_spec(layout_with_drl, ...) #' @export igraph.drl.default <- list(edge.cut=32/40, init.iterations=0, init.temperature=2000, init.attraction=10, init.damping.mult=1.0, liquid.iterations=200, liquid.temperature=2000, liquid.attraction=10, liquid.damping.mult=1.0, expansion.iterations=200, expansion.temperature=2000, expansion.attraction=2, expansion.damping.mult=1.0, cooldown.iterations=200, cooldown.temperature=2000, cooldown.attraction=1, cooldown.damping.mult=.1, crunch.iterations=50, crunch.temperature=250, crunch.attraction=1, crunch.damping.mult=0.25, simmer.iterations=100, simmer.temperature=250, simmer.attraction=.5, simmer.damping.mult=0) #' @export igraph.drl.coarsen <- list(edge.cut=32/40, init.iterations=0, init.temperature=2000, init.attraction=10, init.damping.mult=1.0, liquid.iterations=200, liquid.temperature=2000, liquid.attraction=2, liquid.damping.mult=1.0, expansion.iterations=200, expansion.temperature=2000, expansion.attraction=10, expansion.damping.mult=1.0, cooldown.iterations=200, cooldown.temperature=2000, cooldown.attraction=1, cooldown.damping.mult=.1, crunch.iterations=50, crunch.temperature=250, crunch.attraction=1, crunch.damping.mult=0.25, simmer.iterations=100, simmer.temperature=250, simmer.attraction=.5, simmer.damping.mult=0) #' @export igraph.drl.coarsest <- list(edge.cut=32/40, init.iterations=0, init.temperature=2000, init.attraction=10, init.damping.mult=1.0, liquid.iterations=200, liquid.temperature=2000, liquid.attraction=2, liquid.damping.mult=1.0, expansion.iterations=200, expansion.temperature=2000, expansion.attraction=10, expansion.damping.mult=1.0, cooldown.iterations=200, cooldown.temperature=2000, cooldown.attraction=1, cooldown.damping.mult=.1, crunch.iterations=200, crunch.temperature=250, crunch.attraction=1, crunch.damping.mult=0.25, simmer.iterations=100, simmer.temperature=250, simmer.attraction=.5, simmer.damping.mult=0) #' @export igraph.drl.refine <- list(edge.cut=32/40, init.iterations=0, init.temperature=50, init.attraction=.5, init.damping.mult=1.0, liquid.iterations=0, liquid.temperature=2000, liquid.attraction=2, liquid.damping.mult=1.0, expansion.iterations=50, expansion.temperature=500, expansion.attraction=.1, expansion.damping.mult=.25, cooldown.iterations=50, cooldown.temperature=250, cooldown.attraction=1, cooldown.damping.mult=.1, crunch.iterations=50, crunch.temperature=250, crunch.attraction=1, crunch.damping.mult=0.25, simmer.iterations=0, simmer.temperature=250, simmer.attraction=.5, simmer.damping.mult=0) #' @export igraph.drl.final <- list(edge.cut=32/40, init.iterations=0, init.temperature=50, init.attraction=.5, init.damping.mult=0, liquid.iterations=0, liquid.temperature=2000, liquid.attraction=2, liquid.damping.mult=1.0, expansion.iterations=50, expansion.temperature=2000, expansion.attraction=2, expansion.damping.mult=1.0, cooldown.iterations=50, cooldown.temperature=200, cooldown.attraction=1, cooldown.damping.mult=.1, crunch.iterations=50, crunch.temperature=250, crunch.attraction=1, crunch.damping.mult=0.25, simmer.iterations=25, simmer.temperature=250, simmer.attraction=.5, simmer.damping.mult=0) #' @export drl_defaults <- list( coarsen = igraph.drl.coarsen, coarsest = igraph.drl.coarsest, default = igraph.drl.default, final = igraph.drl.final, refine = igraph.drl.refine ) igraph/R/incidence.R0000644000175100001440000002135713562472260014026 0ustar hornikusers ## ---------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------- graph.incidence.sparse <- function(incidence, directed, mode, multiple, weighted) { n1 <- nrow(incidence) n2 <- ncol(incidence) el <- mat_summary(incidence) # was summary(..) el[,2] <- el[,2] + n1 if (!is.null(weighted)) { if (is.logical(weighted) && weighted) { weighted <- "weight" } if (!is.character(weighted)) { stop("invalid value supplied for `weighted' argument, please see docs.") } if (!directed || mode==1) { ## nothing do to } else if (mode==2) { el[,1:2] <- el[,c(2,1)] } else if (mode==3) { el <- rbind(el, el[,c(2,1,3)]) } res <- make_empty_graph(n=n1+n2, directed=directed) weight <- list(el[,3]) names(weight) <- weighted res <- add_edges(res, edges=t(as.matrix(el[,1:2])), attr=weight) } else { if (multiple) { el[,3] <- ceiling(el[,3]) el[,3][ el[,3] < 0 ] <- 0 } else { el[,3] <- el[,3] != 0 } if (!directed || mode==1) { ## nothing do to } else if (mode==2) { el[,1:2] <- el[,c(2,1)] } else if (mode==3) { el <- rbind(el, el[,c(2,1,3)]) } edges <- unlist(apply(el, 1, function(x) rep(unname(x[1:2]), x[3]))) res <- graph(n=n1+n2, edges, directed=directed) } set_vertex_attr(res, "type", value=c(rep(FALSE, n1), rep(TRUE, n2))) } graph.incidence.dense <- function(incidence, directed, mode, multiple, weighted) { if (!is.null(weighted)) { if (is.logical(weighted) && weighted) { weighted <- "weight" } if (!is.character(weighted)) { stop("invalid value supplied for `weighted' argument, please see docs.") } n1 <- nrow(incidence) n2 <- ncol(incidence) no.edges <- sum(incidence != 0) if (directed && mode==3) { no.edges <- no.edges * 2 } edges <- numeric(2*no.edges) weight <- numeric(no.edges) ptr <- 1 for (i in seq_len(nrow(incidence))) { for (j in seq_len(ncol(incidence))) { if (incidence[i,j] != 0) { if (!directed || mode==1) { edges[2*ptr-1] <- i edges[2*ptr] <- n1+j weight[ptr] <- incidence[i,j] ptr <- ptr + 1 } else if (mode==2) { edges[2*ptr-1] <- n1+j edges[2*ptr] <- i weight[ptr] <- incidence[i,j] ptr <- ptr + 1 } else if (mode==3) { edges[2*ptr-1] <- i edges[2*ptr] <- n1+j weight[ptr] <- incidence[i,j] ptr <- ptr + 1 edges[2*ptr-1] <- n1+j edges[2*ptr] <- i } } } } res <- make_empty_graph(n=n1+n2, directed=directed) weight <- list(weight) names(weight) <- weighted res <- add_edges(res, edges, attr=weight) res <- set_vertex_attr(res, "type", value=c(rep(FALSE, n1), rep(TRUE, n2))) } else { mode(incidence) <- "double" on.exit( .Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_incidence, incidence, directed, mode, multiple) res <- set_vertex_attr(res$graph, "type", value=res$types) } res } #' Create graphs from an incidence matrix #' #' \code{graph_from_incidence_matrix} creates a bipartite igraph graph from an incidence #' matrix. #' #' Bipartite graphs have a \sQuote{\code{type}} vertex attribute in igraph, #' this is boolean and \code{FALSE} for the vertices of the first kind and #' \code{TRUE} for vertices of the second kind. #' #' \code{graph_from_incidence_matrix} can operate in two modes, depending on the #' \code{multiple} argument. If it is \code{FALSE} then a single edge is #' created for every non-zero element in the incidence matrix. If #' \code{multiple} is \code{TRUE}, then the matrix elements are rounded up to #' the closest non-negative integer to get the number of edges to create #' between a pair of vertices. #' #' @aliases graph.incidence #' @param incidence The input incidence matrix. It can also be a sparse matrix #' from the \code{Matrix} package. #' @param directed Logical scalar, whether to create a directed graph. #' @param mode A character constant, defines the direction of the edges in #' directed graphs, ignored for undirected graphs. If \sQuote{\code{out}}, then #' edges go from vertices of the first kind (corresponding to rows in the #' incidence matrix) to vertices of the second kind (columns in the incidence #' matrix). If \sQuote{\code{in}}, then the opposite direction is used. If #' \sQuote{\code{all}} or \sQuote{\code{total}}, then mutual edges are created. #' @param multiple Logical scalar, specifies how to interpret the matrix #' elements. See details below. #' @param weighted This argument specifies whether to create a weighted graph #' from the incidence matrix. If it is \code{NULL} then an unweighted graph is #' created and the \code{multiple} argument is used to determine the edges of #' the graph. If it is a character constant then for every non-zero matrix #' entry an edge is created and the value of the entry is added as an edge #' attribute named by the \code{weighted} argument. If it is \code{TRUE} then a #' weighted graph is created and the name of the edge attribute will be #' \sQuote{\code{weight}}. #' @param add.names A character constant, \code{NA} or \code{NULL}. #' \code{graph_from_incidence_matrix} can add the row and column names of the incidence #' matrix as vertex attributes. If this argument is \code{NULL} (the default) #' and the incidence matrix has both row and column names, then these are added #' as the \sQuote{\code{name}} vertex attribute. If you want a different vertex #' attribute for this, then give the name of the attributes as a character #' string. If this argument is \code{NA}, then no vertex attributes (other than #' type) will be added. #' @return A bipartite igraph graph. In other words, an igraph graph that has a #' vertex attribute \code{type}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{make_bipartite_graph}} for another way to create bipartite #' graphs #' @keywords graphs #' @examples #' #' inc <- matrix(sample(0:1, 15, repl=TRUE), 3, 5) #' colnames(inc) <- letters[1:5] #' rownames(inc) <- LETTERS[1:3] #' graph_from_incidence_matrix(inc) #' graph_from_incidence_matrix <- function(incidence, directed=FALSE, mode=c("all", "out", "in", "total"), multiple=FALSE, weighted=NULL, add.names=NULL) { # Argument checks directed <- as.logical(directed) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) multiple <- as.logical(multiple) if (inherits(incidence, "Matrix")) { res <- graph.incidence.sparse(incidence, directed=directed, mode=mode, multiple=multiple, weighted=weighted) } else { incidence <- as.matrix(incidence) res <- graph.incidence.dense(incidence, directed=directed, mode=mode, multiple=multiple, weighted=weighted) } ## Add names if (is.null(add.names)) { if (!is.null(rownames(incidence)) && !is.null(colnames(incidence))) { add.names <- "name" } else { add.names <- NA } } else if (!is.na(add.names)) { if (is.null(rownames(incidence)) || is.null(colnames(incidence))) { warning("Cannot add row- and column names, at least one of them is missing") add.names <- NA } } if (!is.na(add.names)) { res <- set_vertex_attr(res, add.names, value=c(rownames(incidence), colnames(incidence))) } res } #' @rdname graph_from_incidence_matrix #' @param ... Passed to \code{graph_from_incidence_matrix}. #' @export from_incidence_matrix <- function(...) constructor_spec(graph_from_incidence_matrix, ...) igraph/R/data_frame.R0000644000175100001440000002307513177712334014170 0ustar hornikusers ## ---------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------- #' Creating igraph graphs from data frames or vice-versa #' #' This function creates an igraph graph from one or two data frames containing #' the (symbolic) edge list and edge/vertex attributes. #' #' \code{graph_from_data_frame} creates igraph graphs from one or two data frames. #' It has two modes of operatation, depending whether the \code{vertices} #' argument is \code{NULL} or not. #' #' If \code{vertices} is \code{NULL}, then the first two columns of \code{d} #' are used as a symbolic edge list and additional columns as edge attributes. #' The names of the attributes are taken from the names of the columns. #' #' If \code{vertices} is not \code{NULL}, then it must be a data frame giving #' vertex metadata. The first column of \code{vertices} is assumed to contain #' symbolic vertex names, this will be added to the graphs as the #' \sQuote{\code{name}} vertex attribute. Other columns will be added as #' additional vertex attributes. If \code{vertices} is not \code{NULL} then the #' symbolic edge list given in \code{d} is checked to contain only vertex names #' listed in \code{vertices}. #' #' Typically, the data frames are exported from some speadsheat software like #' Excel and are imported into R via \code{\link{read.table}}, #' \code{\link{read.delim}} or \code{\link{read.csv}}. #' #' \code{as_data_frame} converts the igraph graph into one or more data #' frames, depending on the \code{what} argument. #' #' If the \code{what} argument is \code{edges} (the default), then the edges of #' the graph and also the edge attributes are returned. The edges will be in #' the first two columns, named \code{from} and \code{to}. (This also denotes #' edge direction for directed graphs.) For named graphs, the vertex names #' will be included in these columns, for other graphs, the numeric vertex ids. #' The edge attributes will be in the other columns. It is not a good idea to #' have an edge attribute named \code{from} or \code{to}, because then the #' column named in the data frame will not be unique. The edges are listed in #' the order of their numeric ids. #' #' If the \code{what} argument is \code{vertices}, then vertex attributes are #' returned. Vertices are listed in the order of their numeric vertex ids. #' #' If the \code{what} argument is \code{both}, then both vertex and edge data #' is returned, in a list with named entries \code{vertices} and \code{edges}. #' #' @aliases graph_from_data_frame graph.data.frame as_data_frame get.data.frame #' @param d A data frame containing a symbolic edge list in the first two #' columns. Additional columns are considered as edge attributes. Since #' version 0.7 this argument is coerced to a data frame with #' \code{as.data.frame}. #' @param directed Logical scalar, whether or not to create a directed graph. #' @param vertices A data frame with vertex metadata, or \code{NULL}. See #' details below. Since version 0.7 this argument is coerced to a data frame #' with \code{as.data.frame}, if not \code{NULL}. #' @return An igraph graph object for \code{graph_from_data_frame}, and either a #' data frame or a list of two data frames named \code{edges} and #' \code{vertices} for \code{as.data.frame}. #' @note For \code{graph_from_data_frame} \code{NA} elements in the first two #' columns \sQuote{d} are replaced by the string \dQuote{NA} before creating #' the graph. This means that all \code{NA}s will correspond to a single #' vertex. #' #' \code{NA} elements in the first column of \sQuote{vertices} are also #' replaced by the string \dQuote{NA}, but the rest of \sQuote{vertices} is not #' touched. In other words, vertex names (=the first column) cannot be #' \code{NA}, but other vertex attributes can. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{graph_from_literal}} #' for another way to create graphs, \code{\link{read.table}} to read in tables #' from files. #' @keywords graphs #' @examples #' #' ## A simple example with a couple of actors #' ## The typical case is that these tables are read in from files.... #' actors <- data.frame(name=c("Alice", "Bob", "Cecil", "David", #' "Esmeralda"), #' age=c(48,33,45,34,21), #' gender=c("F","M","F","M","F")) #' relations <- data.frame(from=c("Bob", "Cecil", "Cecil", "David", #' "David", "Esmeralda"), #' to=c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), #' same.dept=c(FALSE,FALSE,TRUE,FALSE,FALSE,TRUE), #' friendship=c(4,5,5,2,1,1), advice=c(4,5,5,4,2,3)) #' g <- graph_from_data_frame(relations, directed=TRUE, vertices=actors) #' print(g, e=TRUE, v=TRUE) #' #' ## The opposite operation #' as_data_frame(g, what="vertices") #' as_data_frame(g, what="edges") #' graph_from_data_frame <- function(d, directed=TRUE, vertices=NULL) { d <- as.data.frame(d) if (!is.null(vertices)) { vertices <- as.data.frame(vertices) } if (ncol(d) < 2) { stop("the data frame should contain at least two columns") } ## Handle if some elements are 'NA' if (any(is.na(d[,1:2]))) { warning("In `d' `NA' elements were replaced with string \"NA\"") d[,1:2][ is.na(d[,1:2]) ] <- 'NA' } if (!is.null(vertices) && any(is.na(vertices[,1]))) { warning("In `vertices[,1]' `NA' elements were replaced with string \"NA\"") vertices[,1][is.na(vertices[,1])] <- 'NA' } names <- unique( c(as.character(d[,1]), as.character(d[,2])) ) if (!is.null(vertices)) { names2 <- names vertices <- as.data.frame(vertices) if (ncol(vertices) < 1) { stop("Vertex data frame contains no rows") } names <- as.character(vertices[,1]) if (any(duplicated(names))) { stop("Duplicate vertex names") } if (any(! names2 %in% names)) { stop("Some vertex names in edge list are not listed in vertex data frame") } } # create graph g <- make_empty_graph(n=0, directed=directed) # vertex attributes attrs <- list(name=names) if (!is.null(vertices)) { if (ncol(vertices) > 1) { for (i in 2:ncol(vertices)) { newval <- vertices[,i] if (class(newval) == "factor") { newval <- as.character(newval) } attrs[[ names(vertices)[i] ]] <- newval } } } # add vertices g <- add_vertices(g, length(names), attr=attrs) # create edge list from <- as.character(d[,1]) to <- as.character(d[,2]) edges <- rbind(match(from, names), match(to,names)) # edge attributes attrs <- list() if (ncol(d) > 2) { for (i in 3:ncol(d)) { newval <- d[,i] if (class(newval) == "factor") { newval <- as.character(newval) } attrs[[ names(d)[i] ]] <- newval } } # add the edges g <- add_edges(g, edges, attr=attrs) g } #' @rdname graph_from_data_frame #' @param ... Passed to \code{graph_from_data_frame}. #' @export from_data_frame <- function(...) constructor_spec(graph_from_data_frame, ...) ## ----------------------------------------------------------------- #' Create a graph from an edge list matrix #' #' \code{graph_from_edgelist} creates a graph from an edge list. Its argument #' is a two-column matrix, each row defines one edge. If it is #' a numeric matrix then its elements are interpreted as vertex ids. If #' it is a character matrix then it is interpreted as symbolic vertex #' names and a vertex id will be assigned to each name, and also a #' \code{name} vertex attribute will be added. #' #' @aliases graph.edgelist #' @concept Edge list #' @param el The edge list, a two column matrix, character or numeric. #' @param directed Whether to create a directed graph. #' @return An igraph graph. #' #' @family determimistic constructors #' @export #' @examples #' el <- matrix( c("foo", "bar", "bar", "foobar"), nc = 2, byrow = TRUE) #' graph_from_edgelist(el) #' #' # Create a ring by hand #' graph_from_edgelist(cbind(1:10, c(2:10, 1))) graph_from_edgelist <- function(el, directed=TRUE) { if (!is.matrix(el) || ncol(el) != 2) { stop("graph_from_edgelist expects a matrix with two columns") } if (nrow(el) == 0) { res <- make_empty_graph(directed=directed) } else { if (is.character(el)) { ## symbolic edge list names <- unique(as.character(t(el))) ids <- seq(names) names(ids) <- names res <- graph( unname(ids[t(el)]), directed=directed) rm(ids) V(res)$name <- names } else { ## normal edge list res <- graph( t(el), directed=directed ) } } res } #' @rdname graph_from_edgelist #' @param ... Passed to \code{graph_from_edgelist}. #' @export from_edgelist <- function(...) constructor_spec(graph_from_edgelist, ...) igraph/R/structural.properties.R0000644000175100001440000032311113247212322016470 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Structural properties ################################################################### #' Diameter of a graph #' #' The diameter of a graph is the length of the longest geodesic. #' #' The diameter is calculated by using a breadth-first search like method. #' #' \code{get_diameter} returns a path with the actual diameter. If there are #' many shortest paths of the length of the diameter, then it returns the first #' one found. #' #' \code{farthest_vertices} returns two vertex ids, the vertices which are #' connected by the diameter path. #' #' @aliases diameter get.diameter farthest.nodes farthest_vertices get_diameter #' @param graph The graph to analyze. #' @param directed Logical, whether directed or undirected paths are to be #' considered. This is ignored for undirected graphs. #' @param unconnected Logical, what to do if the graph is unconnected. If #' FALSE, the function will return a number that is one larger the largest #' possible diameter, which is always the number of vertices. If TRUE, the #' diameters of the connected components will be calculated and the largest one #' will be returned. #' @param weights Optional positive weight vector for calculating weighted #' distances. If the graph has a \code{weight} edge attribute, then this is #' used by default. #' @return A numeric constant for \code{diameter}, a numeric vector for #' \code{get_diameter}. \code{farthest_vertices} returns a list with two #' entries: \itemize{ #' \item \code{vertices} The two vertices that are the farthest. #' \item \code{distance} Their distance. #' } #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{distances}} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g2 <- delete_edges(g, c(1,2,1,10)) #' diameter(g2, unconnected=TRUE) #' diameter(g2, unconnected=FALSE) #' #' ## Weighted diameter #' set.seed(1) #' g <- make_ring(10) #' E(g)$weight <- sample(seq_len(ecount(g))) #' diameter(g) #' get_diameter(g) #' diameter(g, weights=NA) #' get_diameter(g, weights=NA) #' diameter <- function(graph, directed=TRUE, unconnected=TRUE, weights=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_diameter, graph, as.logical(directed), as.logical(unconnected), weights) } #' @export get_diameter <- function(graph, directed=TRUE, unconnected=TRUE, weights=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_diameter, graph, as.logical(directed), as.logical(unconnected), weights) + 1L if (igraph_opt("return.vs.es")) { res <- create_vs(graph, res) } res } #' @export farthest_vertices <- function(graph, directed=TRUE, unconnected=TRUE, weights=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_farthest_points, graph, as.logical(directed), as.logical(unconnected), weights) res <- list(vertices = res[1:2] + 1L, distance = res[3]) if (igraph_opt("return.vs.es")) { res$vertices <- create_vs(graph, res$vertices) } res } #' @export #' @rdname distances mean_distance <- function(graph, directed=TRUE, unconnected=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_average_path_length, graph, as.logical(directed), as.logical(unconnected)) } #' Degree and degree distribution of the vertices #' #' The degree of a vertex is its most basic structural property, the number of #' its adjacent edges. #' #' #' @aliases degree degree.distribution degree_distribution #' @param graph The graph to analyze. #' @param v The ids of vertices of which the degree will be calculated. #' @param mode Character string, \dQuote{out} for out-degree, \dQuote{in} for #' in-degree or \dQuote{total} for the sum of the two. For undirected graphs #' this argument is ignored. \dQuote{all} is a synonym of \dQuote{total}. #' @param loops Logical; whether the loop edges are also counted. #' @param normalized Logical scalar, whether to normalize the degree. If #' \code{TRUE} then the result is divided by \eqn{n-1}, where \eqn{n} is the #' number of vertices in the graph. #' @param \dots Additional arguments to pass to \code{degree}, eg. \code{mode} #' is useful but also \code{v} and \code{loops} make sense. #' @return For \code{degree} a numeric vector of the same length as argument #' \code{v}. #' #' For \code{degree_distribution} a numeric vector of the same length as the #' maximum degree plus one. The first element is the relative frequency zero #' degree vertices, the second vertices with degree one, etc. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @examples #' #' g <- make_ring(10) #' degree(g) #' g2 <- sample_gnp(1000, 10/1000) #' degree_distribution(g2) #' degree <- function(graph, v=V(graph), mode=c("all", "out", "in", "total"), loops=TRUE, normalized=FALSE){ if (!is_igraph(graph)) { stop("Not a graph object") } v <- as.igraph.vs(graph, v) mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3, "total"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_degree, graph, v-1, as.numeric(mode), as.logical(loops)) if (normalized) { res <- res / (vcount(graph)-1) } if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- V(graph)$name[v] } res } #' @rdname degree #' @param cumulative Logical; whether the cumulative degree distribution is to #' be calculated. #' @export #' @importFrom graphics hist degree_distribution <- function(graph, cumulative=FALSE, ...) { if (!is_igraph(graph)) { stop("Not a graph object") } cs <- degree(graph, ...) hi <- hist(cs, -1:max(cs), plot=FALSE)$density if (!cumulative) { res <- hi } else { res <- rev(cumsum(rev(hi))) } res } #' Shortest (directed or undirected) paths between vertices #' #' \code{distances} calculates the length of all the shortest paths from #' or to the vertices in the network. \code{shortest_paths} calculates one #' shortest path (the path itself, and not just its length) from or to the #' given vertex. #' #' The shortest path, or geodesic between two pair of vertices is a path with #' the minimal number of vertices. The functions documented in this manual page #' all calculate shortest paths between vertex pairs. #' #' \code{distances} calculates the lengths of pairwise shortest paths from #' a set of vertices (\code{from}) to another set of vertices (\code{to}). It #' uses different algorithms, depending on the \code{algorithm} argument and #' the \code{weight} edge attribute of the graph. The implemented algorithms #' are breadth-first search (\sQuote{\code{unweighted}}), this only works for #' unweighted graphs; the Dijkstra algorithm (\sQuote{\code{dijkstra}}), this #' works for graphs with non-negative edge weights; the Bellman-Ford algorithm #' (\sQuote{\code{bellman-ford}}), and Johnson's algorithm #' (\sQuote{\code{"johnson"}}). The latter two algorithms work with arbitrary #' edge weights, but (naturally) only for graphs that don't have a negative #' cycle. #' #' igraph can choose automatically between algorithms, and chooses the most #' efficient one that is appropriate for the supplied weights (if any). For #' automatic algorithm selection, supply \sQuote{\code{automatic}} as the #' \code{algorithm} argument. (This is also the default.) #' #' \code{shortest_paths} calculates a single shortest path (i.e. the path #' itself, not just its length) between the source vertex given in \code{from}, #' to the target vertices given in \code{to}. \code{shortest_paths} uses #' breadth-first search for unweighted graphs and Dijkstra's algorithm for #' weighted graphs. The latter only works if the edge weights are non-negative. #' #' \code{all_shortest_paths} calculates \emph{all} shortest paths between #' pairs of vertices. More precisely, between the \code{from} vertex to the #' vertices given in \code{to}. It uses a breadth-first search for unweighted #' graphs and Dijkstra's algorithm for weighted ones. The latter only supports #' non-negative edge weights. #' #' \code{mean_distance} calculates the average path length in a graph, by #' calculating the shortest paths between all pairs of vertices (both ways for #' directed graphs). This function does not consider edge weights currently and #' uses a breadth-first search. #' #' \code{distance_table} calculates a histogram, by calculating the shortest #' path length between each pair of vertices. For directed graphs both #' directions are considered, so every pair of vertices appears twice in the #' histogram. #' #' @aliases shortest.paths get.shortest.paths get.all.shortest.paths distances #' mean_distance distance_table average.path.length path.length.hist #' all_shortest_paths shortest_paths #' @param graph The graph to work on. #' @param v Numeric vector, the vertices from which the shortest paths will be #' calculated. #' @param to Numeric vector, the vertices to which the shortest paths will be #' calculated. By default it includes all vertices. Note that for #' \code{distances} every vertex must be included here at most once. (This #' is not required for \code{shortest_paths}. #' @param mode Character constant, gives whether the shortest paths to or from #' the given vertices should be calculated for directed graphs. If \code{out} #' then the shortest paths \emph{from} the vertex, if \code{in} then \emph{to} #' it will be considered. If \code{all}, the default, then the corresponding #' undirected graph will be used, ie. not directed paths are searched. This #' argument is ignored for undirected graphs. #' @param weights Possibly a numeric vector giving edge weights. If this is #' \code{NULL} and the graph has a \code{weight} edge attribute, then the #' attribute is used. If this is \code{NA} then no weights are used (even if #' the graph has a \code{weight} attribute). #' @param algorithm Which algorithm to use for the calculation. By default #' igraph tries to select the fastest suitable algorithm. If there are no #' weights, then an unweighted breadth-first search is used, otherwise if all #' weights are positive, then Dijkstra's algorithm is used. If there are #' negative weights and we do the calculation for more than 100 sources, then #' Johnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used. #' You can override igraph's choice by explicitly giving this parameter. Note #' that the igraph C core might still override your choice in obvious cases, #' i.e. if there are no edge weights, then the unweighted algorithm will be #' used, regardless of this argument. #' @return For \code{distances} a numeric matrix with \code{length(to)} #' columns and \code{length(v)} rows. The shortest path length from a vertex to #' itself is always zero. For unreachable vertices \code{Inf} is included. #' #' For \code{shortest_paths} a named list with four entries is returned: #' \item{vpath}{This itself is a list, of length \code{length(to)}; list #' element \code{i} contains the vertex ids on the path from vertex \code{from} #' to vertex \code{to[i]} (or the other way for directed graphs depending on #' the \code{mode} argument). The vector also contains \code{from} and \code{i} #' as the first and last elements. If \code{from} is the same as \code{i} then #' it is only included once. If there is no path between two vertices then a #' numeric vector of length zero is returned as the list element. If this #' output is not requested in the \code{output} argument, then it will be #' \code{NULL}.} \item{epath}{This is a list similar to \code{vpath}, but the #' vectors of the list contain the edge ids along the shortest paths, instead #' of the vertex ids. This entry is set to \code{NULL} if it is not requested #' in the \code{output} argument.} \item{predecessors}{Numeric vector, the #' predecessor of each vertex in the \code{to} argument, or \code{NULL} if it #' was not requested.} \item{inbound_edges}{Numeric vector, the inbound edge #' for each vertex, or \code{NULL}, if it was not requested.} #' #' For \code{all_shortest_paths} a list is returned, each list element #' contains a shortest path from \code{from} to a vertex in \code{to}. The #' shortest paths to the same vertex are collected into consecutive elements of #' the list. #' #' For \code{mean_distance} a single number is returned. #' #' \code{distance_table} returns a named list with two entries: \code{res} is #' a numeric vector, the histogram of distances, \code{unconnected} is a #' numeric scalar, the number of pairs for which the first vertex is not #' reachable from the second. The sum of the two entries is always \eqn{n(n-1)} #' for directed graphs and \eqn{n(n-1)/2} for undirected graphs. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references West, D.B. (1996). \emph{Introduction to Graph Theory.} Upper #' Saddle River, N.J.: Prentice Hall. #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' distances(g) #' shortest_paths(g, 5) #' all_shortest_paths(g, 1, 6:8) #' mean_distance(g) #' ## Weighted shortest paths #' el <- matrix(nc=3, byrow=TRUE, #' c(1,2,0, 1,3,2, 1,4,1, 2,3,0, 2,5,5, 2,6,2, 3,2,1, 3,4,1, #' 3,7,1, 4,3,0, 4,7,2, 5,6,2, 5,8,8, 6,3,2, 6,7,1, 6,9,1, #' 6,10,3, 8,6,1, 8,9,1, 9,10,4) ) #' g2 <- add_edges(make_empty_graph(10), t(el[,1:2]), weight=el[,3]) #' distances(g2, mode="out") #' distances <- function(graph, v=V(graph), to=V(graph), mode=c("all", "out", "in"), weights=NULL, algorithm=c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson")) { if (!is_igraph(graph)) { stop("Not a graph object") } v <- as.igraph.vs(graph, v) to <- as.igraph.vs(graph, to) mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) algorithm <- igraph.match.arg(algorithm) algorithm <- switch(algorithm, "automatic"=0, "unweighted"=1, "dijkstra"=2, "bellman-ford"=3, "johnson"=4) if (is.null(weights)) { if ("weight" %in% edge_attr_names(graph)) { weights <- as.numeric(E(graph)$weight) } } else { if (length(weights)==1 && is.na(weights)) { weights <- NULL } else { weights <- as.numeric(weights) } } if (! is.null(weights) && algorithm==1) { weights <- NULL warning("Unweighted algorithm chosen, weights ignored") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_shortest_paths, graph, v-1, to-1, as.numeric(mode), weights, as.numeric(algorithm)) if (igraph_opt("add.vertex.names") && is_named(graph)) { rownames(res) <- V(graph)$name[v] colnames(res) <- V(graph)$name[to] } res } #' @rdname distances #' @param from Numeric constant, the vertex from or to the shortest paths will #' be calculated. Note that right now this is not a vector of vertex ids, but #' only a single vertex. #' @param output Character scalar, defines how to report the shortest paths. #' \dQuote{vpath} means that the vertices along the paths are reported, this #' form was used prior to igraph version 0.6. \dQuote{epath} means that the #' edges along the paths are reported. \dQuote{both} means that both forms are #' returned, in a named list with components \dQuote{vpath} and \dQuote{epath}. #' @param predecessors Logical scalar, whether to return the predecessor vertex #' for each vertex. The predecessor of vertex \code{i} in the tree is the #' vertex from which vertex \code{i} was reached. The predecessor of the start #' vertex (in the \code{from} argument) is itself by definition. If the #' predecessor is zero, it means that the given vertex was not reached from the #' source during the search. Note that the search terminates if all the #' vertices in \code{to} are reached. #' @param inbound.edges Logical scalar, whether to return the inbound edge for #' each vertex. The inbound edge of vertex \code{i} in the tree is the edge via #' which vertex \code{i} was reached. The start vertex and vertices that were #' not reached during the search will have zero in the corresponding entry of #' the vector. Note that the search terminates if all the vertices in \code{to} #' are reached. #' @export shortest_paths <- function(graph, from, to=V(graph), mode=c("out", "all", "in"), weights=NULL, output=c("vpath", "epath", "both"), predecessors=FALSE, inbound.edges=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) output <- igraph.match.arg(output) output <- switch(output, "vpath"=0, "epath"=1, "both"=2) if (is.null(weights)) { if ("weight" %in% edge_attr_names(graph)) { weights <- as.numeric(E(graph)$weight) } } else { if (length(weights)==1 && is.na(weights)) { weights <- NULL } else { weights <- as.numeric(weights) } } to <- as.igraph.vs(graph, to)-1 on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_shortest_paths, graph, as.igraph.vs(graph, from)-1, to, as.numeric(mode), as.numeric(length(to)), weights, as.numeric(output), as.logical(predecessors), as.logical(inbound.edges)) if (!is.null(res$vpath)) { res$vpath <- lapply(res$vpath, function(x) x+1) } if (!is.null(res$epath)) { res$epath <- lapply(res$epath, function(x) x+1) } if (!is.null(res$predecessors)) { res$predecessors <- res$predecessors + 1 } if (!is.null(res$inbound_edges)) { res$inbound_edges <- res$inbound_edges + 1 } if (igraph_opt("return.vs.es")) { if (!is.null(res$vpath)) { res$vpath <- lapply(res$vpath, create_vs, graph = graph) } if (!is.null(res$epath)) { res$epath <- lapply(res$epath, create_es, graph = graph) } if (!is.null(res$predecessors)) { res$predecessors <- create_vs(res$predecessors, graph = graph, na_ok = TRUE) } if (!is.null(res$inbound_edges)) { res$inbound_edges <- create_es(res$inbound_edges, graph = graph, na_ok = TRUE) } } res } #' @export #' @rdname distances all_shortest_paths <- function(graph, from, to=V(graph), mode=c("out", "all", "in"), weights=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) if (is.null(weights)) { if ("weight" %in% edge_attr_names(graph)) { weights <- as.numeric(E(graph)$weight) } } else { if (length(weights)==1 && is.na(weights)) { weights <- NULL } else { weights <- as.numeric(weights) } } on.exit( .Call(C_R_igraph_finalizer) ) if (is.null(weights)) { res <- .Call(C_R_igraph_get_all_shortest_paths, graph, as.igraph.vs(graph, from)-1, as.igraph.vs(graph, to)-1, as.numeric(mode)) } else { res <- .Call(C_R_igraph_get_all_shortest_paths_dijkstra, graph, as.igraph.vs(graph, from)-1, as.igraph.vs(graph, to)-1, weights, as.numeric(mode)) } if (igraph_opt("return.vs.es")) { res$res <- lapply(res$res, create_vs, graph = graph) } res } #' In- or out- component of a vertex #' #' Finds all vertices reachable from a given vertex, or the opposite: all #' vertices from which a given vertex is reachable via a directed path. #' #' A breadh-first search is conducted starting from vertex \code{v}. #' #' @aliases subcomponent #' @param graph The graph to analyze. #' @param v The vertex to start the search from. #' @param mode Character string, either \dQuote{in}, \dQuote{out} or #' \dQuote{all}. If \dQuote{in} all vertices from which \code{v} is reachable #' are listed. If \dQuote{out} all vertices reachable from \code{v} are #' returned. If \dQuote{all} returns the union of these. It is ignored for #' undirected graphs. #' @return Numeric vector, the ids of the vertices in the same component as #' \code{v}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{components}} #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(100, 1/200) #' subcomponent(g, 1, "in") #' subcomponent(g, 1, "out") #' subcomponent(g, 1, "all") subcomponent <- function(graph, v, mode=c("all", "out", "in")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_subcomponent, graph, as.igraph.vs(graph, v)-1, as.numeric(mode)) + 1L if (igraph_opt("return.vs.es")) res <- create_vs(graph, res) res } #' Subgraph of a graph #' #' \code{subgraph} creates a subgraph of a graph, containing only the specified #' vertices and all the edges among them. #' #' \code{induced_subgraph} calculates the induced subgraph of a set of vertices #' in a graph. This means that exactly the specified vertices and all the edges #' between them will be kept in the result graph. #' #' \code{subgraph.edges} calculates the subgraph of a graph. For this function #' one can specify the vertices and edges to keep. This function will be #' renamed to \code{subgraph} in the next major version of igraph. #' #' The \code{subgraph} function does the same as \code{induced.graph} currently #' (assuming \sQuote{\code{auto}} as the \code{impl} argument), but it is #' deprecated and will be removed in the next major version of igraph. #' #' @aliases subgraph induced.subgraph subgraph.edges induced_subgraph #' @param graph The original graph. #' @param v Numeric vector, the vertices of the original graph which will #' form the subgraph. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g2 <- induced_subgraph(g, 1:7) #' g3 <- subgraph.edges(g, 1:5, 1:5) #' subgraph <- function(graph, v) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_subgraph, graph, as.igraph.vs(graph, v)-1) } #' @rdname subgraph #' @param vids Numeric vector, the vertices of the original graph which will #' form the subgraph. #' @param impl Character scalar, to choose between two implementation of the #' subgraph calculation. \sQuote{\code{copy_and_delete}} copies the graph #' first, and then deletes the vertices and edges that are not included in the #' result graph. \sQuote{\code{create_from_scratch}} searches for all vertices #' and edges that must be kept and then uses them to create the graph from #' scratch. \sQuote{\code{auto}} chooses between the two implementations #' automatically, using heuristics based on the size of the original and the #' result graph. #' @export induced_subgraph <- function(graph, vids, impl=c("auto", "copy_and_delete", "create_from_scratch")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) impl <- switch(igraph.match.arg(impl), "auto"=0, "copy_and_delete"=1, "create_from_scratch"=2) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_induced_subgraph, graph, vids-1, impl) res } #' @rdname subgraph #' @param eids The edge ids of the edges that will be kept in the result graph. #' @param delete.vertices Logical scalar, whether to remove vertices that do #' not have any adjacent edges in \code{eids}. #' @export subgraph.edges <- function(graph, eids, delete.vertices=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } eids <- as.igraph.es(graph, eids) delete.vertices <- as.logical(delete.vertices) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_subgraph_edges, graph, eids-1, delete.vertices) res } #' @rdname betweenness #' @param vids The vertices for which the vertex betweenness estimation will be #' calculated. #' @param cutoff The maximum path length to consider when calculating the #' betweenness. If zero or negative then there is no such limit. #' @export estimate_betweenness <- function(graph, vids=V(graph), directed=TRUE, cutoff, weights=NULL, nobigint=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) directed <- as.logical(directed) cutoff <- as.numeric(cutoff) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } nobigint <- as.logical(nobigint) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_betweenness_estimate, graph, vids-1, directed, cutoff, weights, nobigint) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' Vertex and edge betweenness centrality #' #' The vertex and edge betweenness are (roughly) defined by the number of #' geodesics (shortest paths) going through a vertex or an edge. #' #' The vertex betweenness of vertex \eqn{v}{\code{v}} is defined by #' #' \deqn{\sum_{i\ne j, i\ne v, j\ne v} g_{ivj}/g_{ij}}{sum( g_ivj / g_ij, #' i!=j,i!=v,j!=v)} #' #' The edge betweenness of edge \eqn{e}{\code{e}} is defined by #' #' \deqn{\sum_{i\ne j} g{iej}/g_{ij}.}{sum( g_iej / g_ij, i!=j).} #' #' \code{betweenness} calculates vertex betweenness, \code{edge_betweenness} #' calculates edge betweenness. #' #' \code{estimate_betweenness} only considers paths of length \code{cutoff} or #' smaller, this can be run for larger graphs, as the running time is not #' quadratic (if \code{cutoff} is small). If \code{cutoff} is zero or negative #' then the function calculates the exact betweenness scores. #' #' \code{estimate_edge_betweenness} is similar, but for edges. #' #' For calculating the betweenness a similar algorithm to the one proposed by #' Brandes (see References) is used. #' #' @aliases betweenness edge.betweenness betweenness.estimate #' edge.betweenness.estimate edge_betweenness estimate_betweenness #' estimate_edge_betweenness #' @param graph The graph to analyze. #' @param v The vertices for which the vertex betweenness will be calculated. #' @param directed Logical, whether directed paths should be considered while #' determining the shortest paths. #' @param weights Optional positive weight vector for calculating weighted #' betweenness. If the graph has a \code{weight} edge attribute, then this is #' used by default. Weights are used to calculate weighted shortest paths, #' so they are interpreted as distances. #' @param nobigint Logical scalar, whether to use big integers during the #' calculation. This is only required for lattice-like graphs that have very #' many shortest paths between a pair of vertices. If \code{TRUE} (the #' default), then big integers are not used. #' @param normalized Logical scalar, whether to normalize the betweenness #' scores. If \code{TRUE}, then the results are normalized according to #' \deqn{B^n=\frac{2B}{n^2-3n+2}}{Bnorm=2*B/(n*n-3*n+2)}, where #' \eqn{B^n}{Bnorm} is the normalized, \eqn{B} the raw betweenness, and \eqn{n} #' is the number of vertices in the graph. #' @return A numeric vector with the betweenness score for each vertex in #' \code{v} for \code{betweenness}. #' #' A numeric vector with the edge betweenness score for each edge in \code{e} #' for \code{edge_betweenness}. #' #' \code{estimate_betweenness} returns the estimated betweenness scores for #' vertices in \code{vids}, \code{estimate_edge_betweenness} the estimated edge #' betweenness score for \emph{all} edges; both in a numeric vector. #' @note \code{edge_betweenness} might give false values for graphs with #' multiple edges. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{closeness}}, \code{\link{degree}} #' @references Freeman, L.C. (1979). Centrality in Social Networks I: #' Conceptual Clarification. \emph{Social Networks}, 1, 215-239. #' #' Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. \emph{Journal #' of Mathematical Sociology} 25(2):163-177, 2001. #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(10, 3/10) #' betweenness(g) #' edge_betweenness(g) #' betweenness <- function(graph, v=V(graph), directed=TRUE, weights=NULL, nobigint=TRUE, normalized=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } v <- as.igraph.vs(graph, v) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_betweenness, graph, v-1, as.logical(directed), weights, as.logical(nobigint)) if (normalized) { vc <- vcount(graph) if (is_directed(graph) && directed) { res <- res / ( vc*vc-3*vc+2) } else { res <- 2*res / ( vc*vc-3*vc+2) } } if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- V(graph)$name[v] } res } #' Transitivity of a graph #' #' Transitivity measures the probability that the adjacent vertices of a vertex #' are connected. This is sometimes also called the clustering coefficient. #' #' Note that there are essentially two classes of transitivity measures, one is #' a vertex-level, the other a graph level property. #' #' There are several generalizations of transitivity to weighted graphs, here #' we use the definition by A. Barrat, this is a local vertex-level quantity, #' its formula is #' #' \deqn{C_i^w=\frac{1}{s_i(k_i-1)}\sum_{j,h}\frac{w_{ij}+w_{ih}}{2}a_{ij}a_{ih}a_{jh}}{ #' weighted C_i = 1/s_i 1/(k_i-1) sum( (w_ij+w_ih)/2 a_ij a_ih a_jh, j, h)} #' #' \eqn{s_i}{s_i} is the strength of vertex \eqn{i}{i}, see #' \code{\link{strength}}, \eqn{a_{ij}}{a_ij} are elements of the #' adjacency matrix, \eqn{k_i}{k_i} is the vertex degree, \eqn{w_{ij}}{w_ij} #' are the weights. #' #' This formula gives back the normal not-weighted local transitivity if all #' the edge weights are the same. #' #' The \code{barrat} type of transitivity does not work for graphs with #' multiple and/or loop edges. If you want to calculate it for a directed #' graph, call \code{\link{as.undirected}} with the \code{collapse} mode first. #' #' @param graph The graph to analyze. #' @param type The type of the transitivity to calculate. Possible values: #' \describe{ \item{"global"}{The global transitivity of an undirected #' graph (directed graphs are considered as undirected ones as well). This is #' simply the ratio of the triangles and the connected triples in the graph. #' For directed graph the direction of the edges is ignored. } #' \item{"local"}{The local transitivity of an undirected graph, this is #' calculated for each vertex given in the \code{vids} argument. The local #' transitivity of a vertex is the ratio of the triangles connected to the #' vertex and the triples centered on the vertex. For directed graph the #' direction of the edges is ignored. } \item{"undirected"}{This is the #' same as \code{global}.} \item{"globalundirected"}{This is the same as #' \code{global}.} \item{"localundirected"}{This is the same as #' \code{local}.} \item{"barrat"}{The weighted transitivity as defined A. #' Barrat. See details below.} \item{"weighted"}{The same as #' \code{barrat}.} } #' @param vids The vertex ids for the local transitivity will be calculated. #' This will be ignored for global transitivity types. The default value is #' \code{NULL}, in this case all vertices are considered. It is slightly faster #' to supply \code{NULL} here than \code{V(graph)}. #' @param weights Optional weights for weighted transitivity. It is ignored for #' other transitivity measures. If it is \code{NULL} (the default) and the #' graph has a \code{weight} edge attribute, then it is used automatically. #' @param isolates Character scalar, defines how to treat vertices with degree #' zero and one. If it is \sQuote{\code{NaN}} then they local transitivity is #' reported as \code{NaN} and they are not included in the averaging, for the #' transitivity types that calculate an average. If there are no vertices with #' degree two or higher, then the averaging will still result \code{NaN}. If it #' is \sQuote{\code{zero}}, then we report 0 transitivity for them, and they #' are included in the averaging, if an average is calculated. #' @return For \sQuote{\code{global}} a single number, or \code{NaN} if there #' are no connected triples in the graph. #' #' For \sQuote{\code{local}} a vector of transitivity scores, one for each #' vertex in \sQuote{\code{vids}}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Wasserman, S., and Faust, K. (1994). \emph{Social Network #' Analysis: Methods and Applications.} Cambridge: Cambridge University Press. #' #' Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro #' Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. #' Sci. USA 101, 3747 (2004) #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' transitivity(g) #' g2 <- sample_gnp(1000, 10/1000) #' transitivity(g2) # this is about 10/1000 #' #' # Weighted version, the figure from the Barrat paper #' gw <- graph_from_literal(A-B:C:D:E, B-C:D, C-D) #' E(gw)$weight <- 1 #' E(gw)[ V(gw)[name == "A"] %--% V(gw)[name == "E" ] ]$weight <- 5 #' transitivity(gw, vids="A", type="local") #' transitivity(gw, vids="A", type="weighted") #' #' # Weighted reduces to "local" if weights are the same #' gw2 <- sample_gnp(1000, 10/1000) #' E(gw2)$weight <- 1 #' t1 <- transitivity(gw2, type="local") #' t2 <- transitivity(gw2, type="weighted") #' all(is.na(t1) == is.na(t2)) #' all(na.omit(t1 == t2)) #' transitivity <- function(graph, type=c("undirected", "global", "globalundirected", "localundirected", "local", "average", "localaverage", "localaverageundirected", "barrat", "weighted"), vids=NULL, weights=NULL, isolates=c("NaN", "zero")) { if (!is_igraph(graph)) { stop("Not a graph object") } type <- igraph.match.arg(type) type <- switch(type, "undirected"=0, "global"=0, "globalundirected"=0, "localundirected"=1, "local"=1, "average"=2, "localaverage"=2, "localaverageundirected"=2, "barrat"=3, "weighted"=3) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } isolates <- igraph.match.arg(isolates) isolates <- as.double(switch(isolates, "nan"=0, "zero"=1)) on.exit( .Call(C_R_igraph_finalizer) ) if (type==0) { .Call(C_R_igraph_transitivity_undirected, graph, isolates) } else if (type==1) { if (is.null(vids)) { .Call(C_R_igraph_transitivity_local_undirected_all, graph, isolates) } else { vids <- as.igraph.vs(graph, vids)-1 .Call(C_R_igraph_transitivity_local_undirected, graph, vids, isolates) } } else if (type==2) { .Call(C_R_igraph_transitivity_avglocal_undirected, graph, isolates) } else if (type==3) { if (is.null(vids)) { vids <- V(graph) } vids <- as.igraph.vs(graph, vids)-1 if (is.null(weights)) { .Call(C_R_igraph_transitivity_local_undirected, graph, vids, isolates) } else { .Call(C_R_igraph_transitivity_barrat, graph, vids, weights, isolates) } } } ## Generated by stimulus now ## laplacian_matrix <- function(graph, normalized=FALSE) { ## if (!is_igraph(graph)) { ## stop("Not a graph object") ## } ## on.exit( .Call(C_R_igraph_finalizer) ) ## .Call(C_R_igraph_laplacian, graph, as.logical(normalized)) ## } ## OLD implementation ## laplacian_matrix <- function(graph, normalized=FALSE) { ## if (!is_igraph(graph)) { ## stop("Not a graph object") ## } ## if (is_directed(graph)) { ## warning("Laplacian of a directed graph???") ## } ## M <- as_adj(graph) ## if (!normalized) { ## M <- structure(ifelse(M>0, -1, 0), dim=dim(M)) ## diag(M) <- degree(graph) ## } else { ## deg <- degree(graph) ## deg <- outer(deg, deg, "*") ## M <- structure(ifelse(M>0, -1/deg, 0)) ## diag(M) <- 1 ## } ## M ## } ## Structural holes a'la Burt, code contributed by ## Jeroen Bruggeman ## constraint.orig <- function(graph, nodes=V(graph), attr=NULL) { ## if (!is_igraph(graph)) { ## stop("Not a graph object") ## } ## idx <- degree(graph) != 0 ## A <- as_adj(graph, attr=attr) ## A <- A[idx, idx] ## n <- sum(idx) ## one <- c(rep(1,n)) ## CZ <- A + t(A) ## cs <- CZ %*% one # degree of vertices ## ics <- 1/cs ## CS <- ics %*% t(one) # 1/degree of vertices ## P <- CZ * CS #intermediate result: proportionate tie strengths ## PSQ <- P%*%P #sum paths of length two ## P.bi <- as.numeric(P>0) #exclude paths to non-contacts (& reflexive): ## PC <- (P + (PSQ*P.bi))^2 #dyadic constraint ## ci <- PC %*% one #overall constraint ## dim(ci) <- NULL ## ci2 <- numeric(vcount(graph)) ## ci2[idx] <- ci ## ci2[!idx] <- NaN ## ci2[nodes+1] ## } ## Newest implementation, hopefully correct, there is a C implementation ## now so we don't need this ## constraint.old <- function(graph, nodes=V(graph)) { ## if (!is_igraph(graph)) { ## stop("Not a graph object") ## } ## nodes <- as.numeric(nodes) ## res <- numeric(length(nodes)) ## deg <- degree(graph, mode="all", loops=FALSE) ## not <- function(i, v) v[ v!=i ] ## for (a in seq(along=nodes)) { ## i <- nodes[a] ## first <- not(i, neighbors(graph, i, mode="all")) ## first <- unique(first) ## for (b in seq(along=first)) { ## j <- first[b] ## ## cj is the contribution of j ## cj <- are_adjacent(graph, i, j) / deg[i+1] ## cj <- cj + are_adjacent(graph, j, i) / deg[i+1] ## second <- not(i, not(j, neighbors(graph, j, mode="all"))) ## for (c in seq(along=second)) { ## q <- second[c] ## cj <- cj + are_adjacent(graph, i, q) / deg[q+1] / deg[i+1] ## cj <- cj + are_adjacent(graph, q, i) / deg[q+1] / deg[i+1] ## } ## ## Ok, we have the total contribution of j ## res[a] <- res[a] + cj*cj ## } ## } ## if (!is_directed(graph)) { ## res <- res/4 ## } ## res ## } #' Burt's constraint #' #' Given a graph, \code{constraint} calculates Burt's constraint for each #' vertex. #' #' Burt's constraint is higher if ego has less, or mutually #' stronger related (i.e. more redundant) contacts. Burt's measure of #' constraint, \eqn{C_i}{C[i]}, of vertex \eqn{i}'s ego network #' \eqn{V_i}{V[i]}, is defined for directed and valued graphs, #' \deqn{C_i=\sum_{j \in V_i \setminus \{i\}} (p_{ij}+\sum_{q \in V_i #' \setminus \{i,j\}} p_{iq} p_{qj})^2}{ #' C[i] = sum( [sum( p[i,j] + p[i,q] p[q,j], q in V[i], q != i,j )]^2, j in #' V[i], j != i). #' } #' for a graph of order (ie. number of vertices) \eqn{N}, where #' proportional tie strengths are defined as #' \deqn{p_{ij} = \frac{a_{ij}+a_{ji}}{\sum_{k \in V_i \setminus \{i\}}(a_{ik}+a_{ki})},}{ #' p[i,j]=(a[i,j]+a[j,i]) / sum(a[i,k]+a[k,i], k in V[i], k != i), #' } #' \eqn{a_{ij}}{a[i,j]} are elements of \eqn{A} and the latter being the #' graph adjacency matrix. For isolated vertices, constraint is undefined. #' #' @param graph A graph object, the input graph. #' @param nodes The vertices for which the constraint will be calculated. #' Defaults to all vertices. #' @param weights The weights of the edges. If this is \code{NULL} and there is #' a \code{weight} edge attribute this is used. If there is no such edge #' attribute all edges will have the same weight. #' @return A numeric vector of constraint scores #' @author Jeroen Bruggeman #' (\url{https://sites.google.com/site/jebrug/jeroen-bruggeman-social-science}) #' and Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Burt, R.S. (2004). Structural holes and good ideas. #' \emph{American Journal of Sociology} 110, 349-399. #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(20, 5/20) #' constraint(g) #' constraint <- function(graph, nodes=V(graph), weights=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } nodes <- as.igraph.vs(graph, nodes) if (is.null(weights)) { if ("weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_constraint, graph, nodes-1, as.numeric(weights)) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- V(graph)$name[nodes] } res } #' Reciprocity of graphs #' #' Calculates the reciprocity of a directed graph. #' #' The measure of reciprocity defines the proportion of mutual connections, in #' a directed graph. It is most commonly defined as the probability that the #' opposite counterpart of a directed edge is also included in the graph. Or in #' adjacency matrix notation: \eqn{\sum_{ij} (A\cdot A')_{ij}}{sum(i, j, #' (A.*A')ij) / sum(i, j, Aij)}, where \eqn{A\cdot A'}{A.*A'} is the #' element-wise product of matrix \eqn{A} and its transpose. This measure is #' calculated if the \code{mode} argument is \code{default}. #' #' Prior to igraph version 0.6, another measure was implemented, defined as the #' probability of mutual connection between a vertex pair, if we know that #' there is a (possibly non-mutual) connection between them. In other words, #' (unordered) vertex pairs are classified into three groups: (1) #' not-connected, (2) non-reciprocaly connected, (3) reciprocally connected. #' The result is the size of group (3), divided by the sum of group sizes #' (2)+(3). This measure is calculated if \code{mode} is \code{ratio}. #' #' @param graph The graph object. #' @param ignore.loops Logical constant, whether to ignore loop edges. #' @param mode See below. #' @return A numeric scalar between zero and one. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(20, 5/20, directed=TRUE) #' reciprocity(g) #' reciprocity <- function(graph, ignore.loops=TRUE, mode=c("default", "ratio")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), 'default'=0, 'ratio'=1) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_reciprocity, graph, as.logical(ignore.loops), as.numeric(mode)) } bonpow.dense <- function(graph, nodes=V(graph), loops=FALSE, exponent=1, rescale=FALSE, tol=1e-7){ if (!is_igraph(graph)) { stop("Not a graph object") } d <- as_adj(graph) if (!loops) { diag(d) <- 0 } n <- vcount(graph) id <- matrix(0,nrow=n,ncol=n) diag(id) <- 1 # ev <- apply(solve(id-exponent*d,tol=tol)%*%d,1,sum) ev <- solve(id-exponent*d, tol=tol) %*% apply(d,1,sum) if(rescale) { ev <- ev/sum(ev) } else { ev <- ev*sqrt(n/sum((ev)^2)) } ev[as.numeric(nodes)] } bonpow.sparse <- function(graph, nodes=V(graph), loops=FALSE, exponent=1, rescale=FALSE, tol=1e-07) { ## remove loops if requested if (!loops) { graph <- simplify(graph, remove.multiple=FALSE, remove.loops=TRUE) } vg <- vcount(graph) ## sparse adjacency matrix d <- as_adj(graph, sparse=TRUE) ## sparse identity matrix id <- Matrix::Diagonal(vg) ## solve it ev <- Matrix::solve(id - exponent * d, degree(graph, mode="out"), tol=tol) if (rescale) { ev <- ev/sum(ev) } else { ev <- ev * sqrt(vcount(graph)/sum((ev)^2)) } ev[as.numeric(nodes)] } #' Find Bonacich Power Centrality Scores of Network Positions #' #' \code{power_centrality} takes a graph (\code{dat}) and returns the Boncich power #' centralities of positions (selected by \code{nodes}). The decay rate for #' power contributions is specified by \code{exponent} (1 by default). #' #' Bonacich's power centrality measure is defined by #' \eqn{C_{BP}\left(\alpha,\beta\right)=\alpha\left(\mathbf{I}-\beta\mathbf{A}\right)^{-1}\mathbf{A}\mathbf{1}}{C_BP(alpha,beta)=alpha #' (I-beta A)^-1 A 1}, where \eqn{\beta}{beta} is an attenuation parameter (set #' here by \code{exponent}) and \eqn{\mathbf{A}}{A} is the graph adjacency #' matrix. (The coefficient \eqn{\alpha}{alpha} acts as a scaling parameter, #' and is set here (following Bonacich (1987)) such that the sum of squared #' scores is equal to the number of vertices. This allows 1 to be used as a #' reference value for the ``middle'' of the centrality range.) When #' \eqn{\beta \rightarrow }{beta->1/lambda_A1}\eqn{ #' 1/\lambda_{\mathbf{A}1}}{beta->1/lambda_A1} (the reciprocal of the largest #' eigenvalue of \eqn{\mathbf{A}}{A}), this is to within a constant multiple of #' the familiar eigenvector centrality score; for other values of \eqn{\beta}, #' the behavior of the measure is quite different. In particular, \eqn{\beta} #' gives positive and negative weight to even and odd walks, respectively, as #' can be seen from the series expansion #' \eqn{C_{BP}\left(\alpha,\beta\right)=\alpha \sum_{k=0}^\infty \beta^k #' }{C_BP(alpha,beta) = alpha sum( beta^k A^(k+1) 1, k in 0..infinity )}\eqn{ #' \mathbf{A}^{k+1} \mathbf{1}}{C_BP(alpha,beta) = alpha sum( beta^k A^(k+1) 1, #' k in 0..infinity )} which converges so long as \eqn{|\beta| #' }{|beta|<1/lambda_A1}\eqn{ < 1/\lambda_{\mathbf{A}1}}{|beta|<1/lambda_A1}. #' The magnitude of \eqn{\beta}{beta} controls the influence of distant actors #' on ego's centrality score, with larger magnitudes indicating slower rates of #' decay. (High rates, hence, imply a greater sensitivity to edge effects.) #' #' Interpretively, the Bonacich power measure corresponds to the notion that #' the power of a vertex is recursively defined by the sum of the power of its #' alters. The nature of the recursion involved is then controlled by the #' power exponent: positive values imply that vertices become more powerful as #' their alters become more powerful (as occurs in cooperative relations), #' while negative values imply that vertices become more powerful only as their #' alters become \emph{weaker} (as occurs in competitive or antagonistic #' relations). The magnitude of the exponent indicates the tendency of the #' effect to decay across long walks; higher magnitudes imply slower decay. #' One interesting feature of this measure is its relative instability to #' changes in exponent magnitude (particularly in the negative case). If your #' theory motivates use of this measure, you should be very careful to choose a #' decay parameter on a non-ad hoc basis. #' #' @aliases bonpow #' @param graph the input graph. #' @param nodes vertex sequence indicating which vertices are to be included in #' the calculation. By default, all vertices are included. #' @param loops boolean indicating whether or not the diagonal should be #' treated as valid data. Set this true if and only if the data can contain #' loops. \code{loops} is \code{FALSE} by default. #' @param exponent exponent (decay rate) for the Bonacich power centrality #' score; can be negative #' @param rescale if true, centrality scores are rescaled such that they sum to #' 1. #' @param tol tolerance for near-singularities during matrix inversion (see #' \code{\link{solve}}) #' @param sparse Logical scalar, whether to use sparse matrices for the #' calculation. The \sQuote{Matrix} package is required for sparse matrix #' support #' @return A vector, containing the centrality scores. #' @note This function was ported (ie. copied) from the SNA package. #' @section Warning : Singular adjacency matrices cause no end of headaches for #' this algorithm; thus, the routine may fail in certain cases. This will be #' fixed when I get a better algorithm. \code{power_centrality} will not symmetrize your #' data before extracting eigenvectors; don't send this routine asymmetric #' matrices unless you really mean to do so. #' @author Carter T. Butts #' (\url{http://www.faculty.uci.edu/profile.cfm?faculty_id=5057}), ported to #' igraph by Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{eigen_centrality}} and \code{\link{alpha_centrality}} #' @references Bonacich, P. (1972). ``Factoring and Weighting Approaches to #' Status Scores and Clique Identification.'' \emph{Journal of Mathematical #' Sociology}, 2, 113-120. #' #' Bonacich, P. (1987). ``Power and Centrality: A Family of Measures.'' #' \emph{American Journal of Sociology}, 92, 1170-1182. #' @keywords graphs #' @export #' @examples #' #' # Generate some test data from Bonacich, 1987: #' g.c <- graph( c(1,2,1,3,2,4,3,5), dir=FALSE) #' g.d <- graph( c(1,2,1,3,1,4,2,5,3,6,4,7), dir=FALSE) #' g.e <- graph( c(1,2,1,3,1,4,2,5,2,6,3,7,3,8,4,9,4,10), dir=FALSE) #' g.f <- graph( c(1,2,1,3,1,4,2,5,2,6,2,7,3,8,3,9,3,10,4,11,4,12,4,13), dir=FALSE) #' # Compute power centrality scores #' for (e in seq(-0.5,.5, by=0.1)) { #' print(round(power_centrality(g.c, exp=e)[c(1,2,4)], 2)) #' } #' #' for (e in seq(-0.4,.4, by=0.1)) { #' print(round(power_centrality(g.d, exp=e)[c(1,2,5)], 2)) #' } #' #' for (e in seq(-0.4,.4, by=0.1)) { #' print(round(power_centrality(g.e, exp=e)[c(1,2,5)], 2)) #' } #' #' for (e in seq(-0.4,.4, by=0.1)) { #' print(round(power_centrality(g.f, exp=e)[c(1,2,5)], 2)) #' } #' power_centrality <- function(graph, nodes=V(graph), loops=FALSE, exponent=1, rescale=FALSE, tol=1e-7, sparse=TRUE){ nodes <- as.igraph.vs(graph, nodes) if (sparse) { res <- bonpow.sparse(graph, nodes, loops, exponent, rescale, tol) } else { res <- bonpow.dense(graph, nodes, loops, exponent, rescale, tol) } if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", nodes) } res } alpha.centrality.dense <- function(graph, nodes=V(graph), alpha=1, loops=FALSE, exo=1, weights=NULL, tol=1e-7) { if (!is_igraph(graph)) { stop("Not a graph object") } exo <- rep(exo, length=vcount(graph)) exo <- matrix(exo, ncol=1) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { ## weights == NULL and there is a "weight" edge attribute attr <- "weight" } else if (is.null(weights)) { ## weights == NULL, but there is no "weight" edge attribute attr <- NULL } else if (is.character(weights) && length(weights)==1) { ## name of an edge attribute, nothing to do attr <- "weight" } else if (any(!is.na(weights))) { ## weights != NULL and weights != rep(NA, x) graph <- set_edge_attr(graph, "weight", value=as.numeric(weights)) attr <- "weight" } else { ## weights != NULL, but weights == rep(NA, x) attr <- NULL } d <- t(as_adj(graph, attr=attr, sparse=FALSE)) if (!loops) { diag(d) <- 0 } n <- vcount(graph) id <- matrix(0, nrow=n, ncol=n) diag(id) <- 1 ev <- solve(id-alpha*d, tol=tol) %*% exo ev[as.numeric(nodes)] } alpha.centrality.sparse <- function(graph, nodes=V(graph), alpha=1, loops=FALSE, exo=1, weights=NULL, tol=1e-7) { if (!is_igraph(graph)) { stop("Not a graph object") } vc <- vcount(graph) if (!loops) { graph <- simplify(graph, remove.multiple=FALSE, remove.loops=TRUE) } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { ## weights == NULL and there is a "weight" edge attribute attr <- "weight" } else if (is.null(weights)) { ## weights == NULL, but there is no "weight" edge attribute attr <- NULL } else if (is.character(weights) && length(weights)==1) { ## name of an edge attribute, nothing to do attr <- "weight" } else if (any(!is.na(weights))) { ## weights != NULL and weights != rep(NA, x) graph <- set_edge_attr(graph, "weight", value=as.numeric(weights)) attr <- "weight" } else { ## weights != NULL, but weights == rep(NA, x) attr <- NULL } M <- Matrix::t(as_adj(graph, attr = attr, sparse = TRUE)) M <- as(M, "dgCMatrix") ## Create an identity matrix M2 <- Matrix::sparseMatrix(dims=c(vc, vc), i=1:vc, j=1:vc, x=rep(1, vc)) M2 <- as(M2, "dgCMatrix") ## exo exo <- cbind(rep(exo, length=vc)) ## Solve the equation M3 <- M2-alpha*M r <- Matrix::solve(M3, tol=tol, exo) r[ as.numeric(nodes)] } #' Find Bonacich alpha centrality scores of network positions #' #' \code{alpha_centrality} calculates the alpha centrality of some (or all) #' vertices in a graph. #' #' The alpha centrality measure can be considered as a generalization of #' eigenvector centerality to directed graphs. It was proposed by Bonacich in #' 2001 (see reference below). #' #' The alpha centrality of the vertices in a graph is defined as the solution #' of the following matrix equation: \deqn{x=\alpha A^T x+e,}{x=alpha t(A)x+e,} #' where \eqn{A}{A} is the (not neccessarily symmetric) adjacency matrix of the #' graph, \eqn{e}{e} is the vector of exogenous sources of status of the #' vertices and \eqn{\alpha}{alpha} is the relative importance of the #' endogenous versus exogenous factors. #' #' @aliases alpha.centrality #' @param graph The input graph, can be directed or undirected #' @param nodes Vertex sequence, the vertices for which the alpha centrality #' values are returned. (For technical reasons they will be calculated for all #' vertices, anyway.) #' @param alpha Parameter specifying the relative importance of endogenous #' versus exogenous factors in the determination of centrality. See details #' below. #' @param loops Whether to eliminate loop edges from the graph before the #' calculation. #' @param exo The exogenous factors, in most cases this is either a constant -- #' the same factor for every node, or a vector giving the factor for every #' vertex. Note that too long vectors will be truncated and too short vectors #' will be replicated to match the number of vertices. #' @param weights A character scalar that gives the name of the edge attribute #' to use in the adjacency matrix. If it is \code{NULL}, then the #' \sQuote{weight} edge attribute of the graph is used, if there is one. #' Otherwise, or if it is \code{NA}, then the calculation uses the standard #' adjacency matrix. #' @param tol Tolerance for near-singularities during matrix inversion, see #' \code{\link{solve}}. #' @param sparse Logical scalar, whether to use sparse matrices for the #' calculation. The \sQuote{Matrix} package is required for sparse matrix #' support #' @return A numeric vector contaning the centrality scores for the selected #' vertices. #' @section Warning: Singular adjacency matrices cause problems for this #' algorithm, the routine may fail is certain cases. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{eigen_centrality}} and \code{\link{power_centrality}} #' @references Bonacich, P. and Lloyd, P. (2001). ``Eigenvector-like #' measures of centrality for asymmetric relations'' \emph{Social Networks}, #' 23, 191-201. #' @export #' @keywords graphs #' @examples #' #' # The examples from Bonacich's paper #' g.1 <- graph( c(1,3,2,3,3,4,4,5) ) #' g.2 <- graph( c(2,1,3,1,4,1,5,1) ) #' g.3 <- graph( c(1,2,2,3,3,4,4,1,5,1) ) #' alpha_centrality(g.1) #' alpha_centrality(g.2) #' alpha_centrality(g.3,alpha=0.5) #' alpha_centrality <- function(graph, nodes=V(graph), alpha=1, loops=FALSE, exo=1, weights=NULL, tol=1e-7, sparse=TRUE) { nodes <- as.igraph.vs(graph, nodes) if (sparse) { res <- alpha.centrality.sparse(graph, nodes, alpha, loops, exo, weights, tol) } else { res <- alpha.centrality.dense(graph, nodes, alpha, loops, exo, weights, tol) } if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", nodes) } res } #' Graph density #' #' The density of a graph is the ratio of the number of edges and the number of #' possible edges. #' #' Note that this function may return strange results for graph with multiple #' edges, density is ill-defined for graphs with multiple edges. #' #' @aliases graph.density #' @param graph The input graph. #' @param loops Logical constant, whether to allow loop edges in the graph. If #' this is TRUE then self loops are considered to be possible. If this is FALSE #' then we assume that the graph does not contain any loop edges and that loop #' edges are not meaningful. #' @return A real constant. This function returns \code{NaN} (=0.0/0.0) for an #' empty graph with zero vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{vcount}}, \code{\link{ecount}}, \code{\link{simplify}} #' to get rid of the multiple and/or loop edges. #' @references Wasserman, S., and Faust, K. (1994). Social Network Analysis: #' Methods and Applications. Cambridge: Cambridge University Press. #' @export #' @keywords graphs #' @examples #' #' g1 <- make_empty_graph(n=10) #' g2 <- make_full_graph(n=10) #' g3 <- sample_gnp(n=10, 0.4) #' #' # loop edges #' g <- graph( c(1,2, 2,2, 2,3) ) #' edge_density(g, loops=FALSE) # this is wrong!!! #' edge_density(g, loops=TRUE) # this is right!!! #' edge_density(simplify(g), loops=FALSE) # this is also right, but different #' edge_density <- function(graph, loops=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_density, graph, as.logical(loops)) } #' @rdname ego #' @export ego_size <- function(graph, order = 1, nodes=V(graph), mode=c("all", "out", "in"), mindist=0) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) mindist <- as.integer(mindist) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_neighborhood_size, graph, as.igraph.vs(graph, nodes)-1, as.numeric(order), as.numeric(mode), mindist) } #' Neighborhood of graph vertices #' #' These functions find the vertices not farther than a given limit from #' another fixed vertex, these are called the neighborhood of the vertex. #' #' The neighborhood of a given order \code{o} of a vertex \code{v} includes all #' vertices which are closer to \code{v} than the order. Ie. order 0 is always #' \code{v} itself, order 1 is \code{v} plus its immediate neighbors, order 2 #' is order 1 plus the immediate neighbors of the vertices in order 1, etc. #' #' \code{ego_size} calculates the size of the neighborhoods for the #' given vertices with the given order. #' #' \code{ego} calculates the neighborhoods of the given vertices with #' the given order parameter. #' #' \code{make_ego_graph} is creates (sub)graphs from all neighborhoods of #' the given vertices with the given order parameter. This function preserves #' the vertex, edge and graph attributes. #' #' \code{connect} creates a new graph by connecting each vertex to #' all other vertices in its neighborhood. #' #' @aliases neighborhood neighborhood.size graph.neighborhood ego_graph #' connect.neighborhood connect ego_size ego #' @param graph The input graph. #' @param order Integer giving the order of the neighborhood. #' @param nodes The vertices for which the calculation is performed. #' @param mode Character constant, it specifies how to use the direction of #' the edges if a directed graph is analyzed. For \sQuote{out} only the #' outgoing edges are followed, so all vertices reachable from the source #' vertex in at most \code{order} steps are counted. For \sQuote{"in"} all #' vertices from which the source vertex is reachable in at most \code{order} #' steps are counted. \sQuote{"all"} ignores the direction of the edges. This #' argument is ignored for undirected graphs. #' @param mindist The minimum distance to include the vertex in the result. #' @return \code{ego_size} returns with an integer vector. #' #' \code{ego} returns with a list of integer vectors. #' #' \code{make_ego_graph} returns with a list of graphs. #' #' \code{connect} returns with a new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com}, the first version was #' done by Vincent Matossian #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' ego_size(g, order = 0, 1:3) #' ego_size(g, order = 1, 1:3) #' ego_size(g, order = 2, 1:3) #' ego(g, order = 0, 1:3) #' ego(g, order = 1, 1:3) #' ego(g, order = 2, 1:3) #' #' # attributes are preserved #' V(g)$name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") #' make_ego_graph(g, order = 2, 1:3) #' #' # connecting to the neighborhood #' g <- make_ring(10) #' g <- connect(g, 2) #' ego <- function(graph, order = 1, nodes=V(graph), mode=c("all", "out", "in"), mindist=0) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) mindist <- as.integer(mindist) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_neighborhood, graph, as.igraph.vs(graph, nodes)-1, as.numeric(order), as.numeric(mode), mindist) res <- lapply(res, function(x) x+1) if (igraph_opt("return.vs.es")) { res <- lapply(res, create_vs, graph = graph) } res } #' @rdname ego #' @export make_ego_graph <- function(graph, order = 1, nodes=V(graph), mode=c("all", "out", "in"), mindist=0) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) mindist <- as.integer(mindist) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_neighborhood_graphs, graph, as.igraph.vs(graph, nodes)-1, as.numeric(order), as.numeric(mode), mindist) res } #' K-core decomposition of graphs #' #' The k-core of graph is a maximal subgraph in which each vertex has at least #' degree k. The coreness of a vertex is k if it belongs to the k-core but not #' to the (k+1)-core. #' #' The k-core of a graph is the maximal subgraph in which every vertex has at #' least degree k. The cores of a graph form layers: the (k+1)-core is always a #' subgraph of the k-core. #' #' This function calculates the coreness for each vertex. #' #' @aliases graph.coreness #' @param graph The input graph, it can be directed or undirected #' @param mode The type of the core in directed graphs. Character constant, #' possible values: \code{in}: in-cores are computed, \code{out}: out-cores are #' computed, \code{all}: the corresponding undirected graph is considered. This #' argument is ignored for undirected graphs. #' @return Numeric vector of integer numbers giving the coreness of each #' vertex. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{degree}} #' @references Vladimir Batagelj, Matjaz Zaversnik: An O(m) Algorithm for Cores #' Decomposition of Networks, 2002 #' #' Seidman S. B. (1983) Network structure and minimum degree, \emph{Social #' Networks}, 5, 269--287. #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g <- add_edges(g, c(1,2, 2,3, 1,3)) #' coreness(g) # small core triangle in a ring #' coreness <- function(graph, mode=c("all", "out", "in")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_coreness, graph, as.numeric(mode)) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name") } res } #' Topological sorting of vertices in a graph #' #' A topological sorting of a directed acyclic graph is a linear ordering of #' its nodes where each node comes before all nodes to which it has edges. #' #' Every DAG has at least one topological sort, and may have many. This #' function returns a possible topological sort among them. If the graph is not #' acyclic (it has at least one cycle), a partial topological sort is returned #' and a warning is issued. #' #' @aliases topological.sort #' @param graph The input graph, should be directed #' @param mode Specifies how to use the direction of the edges. For #' \dQuote{\code{out}}, the sorting order ensures that each node comes before #' all nodes to which it has edges, so nodes with no incoming edges go first. #' For \dQuote{\code{in}}, it is quite the opposite: each node comes before all #' nodes from which it receives edges. Nodes with no outgoing edges go first. #' @return A vertex sequence (by default, but see the \code{return.vs.es} #' option of \code{\link{igraph_options}}) containing vertices in #' topologically sorted order. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} for the R interface #' @keywords graphs #' @export #' @examples #' #' g <- barabasi.game(100) #' topo_sort(g) #' topo_sort <- function(graph, mode=c("out", "all", "in")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_topological_sorting, graph, as.numeric(mode)) + 1L if (igraph_opt("return.vs.es")) res <- create_vs(graph, res) res } #' Girth of a graph #' #' The girth of a graph is the length of the shortest circle in it. #' #' The current implementation works for undirected graphs only, directed graphs #' are treated as undirected graphs. Loop edges and multiple edges are ignored. #' If the graph is a forest (ie. acyclic), then zero is returned. #' #' This implementation is based on Alon Itai and Michael Rodeh: Finding a #' minimum circuit in a graph \emph{Proceedings of the ninth annual ACM #' symposium on Theory of computing}, 1-10, 1977. The first implementation of #' this function was done by Keith Briggs, thanks Keith. #' #' @param graph The input graph. It may be directed, but the algorithm searches #' for undirected circles anyway. #' @param circle Logical scalar, whether to return the shortest circle itself. #' @return A named list with two components: \item{girth}{Integer constant, the #' girth of the graph, or 0 if the graph is acyclic.} \item{circle}{Numeric #' vector with the vertex ids in the shortest circle.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Alon Itai and Michael Rodeh: Finding a minimum circuit in a #' graph \emph{Proceedings of the ninth annual ACM symposium on Theory of #' computing}, 1-10, 1977 #' @export #' @keywords graphs #' @examples #' #' # No circle in a tree #' g <- make_tree(1000, 3) #' girth(g) #' #' # The worst case running time is for a ring #' g <- make_ring(100) #' girth(g) #' #' # What about a random graph? #' g <- sample_gnp(1000, 1/1000) #' girth(g) #' girth <- function(graph, circle=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_girth, graph, as.logical(circle)) if (igraph_opt("return.vs.es") && circle) { res$circle <- create_vs(graph, res$circle) } res } #' @export which_loop <- function(graph, eids=E(graph)) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_is_loop, graph, as.igraph.es(graph, eids)-1) } #' Find the multiple or loop edges in a graph #' #' A loop edge is an edge from a vertex to itself. An edge is a multiple edge #' if it has exactly the same head and tail vertices as another edge. A graph #' without multiple and loop edges is called a simple graph. #' #' \code{which_loop} decides whether the edges of the graph are loop edges. #' #' \code{any_multiple} decides whether the graph has any multiple edges. #' #' \code{which_multiple} decides whether the edges of the graph are multiple #' edges. #' #' \code{count_multiple} counts the multiplicity of each edge of a graph. #' #' Note that the semantics for \code{which_multiple} and \code{count_multiple} is #' different. \code{which_multiple} gives \code{TRUE} for all occurences of a #' multiple edge except for one. Ie. if there are three \code{i-j} edges in the #' graph then \code{which_multiple} returns \code{TRUE} for only two of them while #' \code{count_multiple} returns \sQuote{3} for all three. #' #' See the examples for getting rid of multiple edges while keeping their #' original multiplicity as an edge attribute. #' #' @aliases has.multiple is.loop is.multiple count.multiple count_multiple #' any_multiple which_loop #' @param graph The input graph. #' @param eids The edges to which the query is restricted. By default this is #' all edges in the graph. #' @return \code{any_multiple} returns a logical scalar. \code{which_loop} and #' \code{which_multiple} return a logical vector. \code{count_multiple} returns a #' numeric vector. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{simplify}} to eliminate loop and multiple edges. #' @export #' @keywords graphs #' @examples #' #' # Loops #' g <- graph( c(1,1,2,2,3,3,4,5) ) #' which_loop(g) #' #' # Multiple edges #' g <- barabasi.game(10, m=3, algorithm="bag") #' any_multiple(g) #' which_multiple(g) #' count_multiple(g) #' which_multiple(simplify(g)) #' all(count_multiple(simplify(g)) == 1) #' #' # Direction of the edge is important #' which_multiple(graph( c(1,2, 2,1) )) #' which_multiple(graph( c(1,2, 2,1), dir=FALSE )) #' #' # Remove multiple edges but keep multiplicity #' g <- barabasi.game(10, m=3, algorithm="bag") #' E(g)$weight <- count_multiple(g) #' g <- simplify(g) #' any(which_multiple(g)) #' E(g)$weight #' which_multiple <- function(graph, eids=E(graph)) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_is_multiple, graph, as.igraph.es(graph, eids)-1) } #' @export count_multiple <- function(graph, eids=E(graph)) { if (!is_igraph(graph)) { stop("Not a graph object"); } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_count_multiple, graph, as.igraph.es(graph, eids)-1) } #' Breadth-first search #' #' Breadth-first search is an algorithm to traverse a graph. We start from a #' root vertex and spread along every edge \dQuote{simultaneously}. #' #' #' The callback function must have the following arguments: \describe{ #' \item{graph}{The input graph is passed to the callback function here.} #' \item{data}{A named numeric vector, with the following entries: #' \sQuote{vid}, the vertex that was just visited, \sQuote{pred}, its #' predecessor, \sQuote{succ}, its successor, \sQuote{rank}, the rank of the #' current vertex, \sQuote{dist}, its distance from the root of the search #' tree.} \item{extra}{The extra argument.} } See examples below on how to use #' the callback function. #' #' @aliases graph.bfs #' @param graph The input graph. #' @param root Numeric vector, usually of length one. The root vertex, or root #' vertices to start the search from. #' @param neimode For directed graphs specifies the type of edges to follow. #' \sQuote{out} follows outgoing, \sQuote{in} incoming edges. \sQuote{all} #' ignores edge directions completely. \sQuote{total} is a synonym for #' \sQuote{all}. This argument is ignored for undirected graphs. #' @param unreachable Logical scalar, whether the search should visit the #' vertices that are unreachable from the given root vertex (or vertices). If #' \code{TRUE}, then additional searches are performed until all vertices are #' visited. #' @param restricted \code{NULL} (=no restriction), or a vector of vertices #' (ids or symbolic names). In the latter case, the search is restricted to the #' given vertices. #' @param order Logical scalar, whether to return the ordering of the vertices. #' @param rank Logical scalar, whether to return the rank of the vertices. #' @param father Logical scalar, whether to return the father of the vertices. #' @param pred Logical scalar, whether to return the predecessors of the #' vertices. #' @param succ Logical scalar, whether to return the successors of the #' vertices. #' @param dist Logical scalar, whether to return the distance from the root of #' the search tree. #' @param callback If not \code{NULL}, then it must be callback function. This #' is called whenever a vertex is visited. See details below. #' @param extra Additional argument to supply to the callback function. #' @param rho The environment in which the callback function is evaluated. #' @return A named list with the following entries: \item{root}{Numeric scalar. #' The root vertex that was used as the starting point of the search.} #' \item{neimode}{Character scalar. The \code{neimode} argument of the function #' call. Note that for undirected graphs this is always \sQuote{all}, #' irrespectively of the supplied value.} \item{order}{Numeric vector. The #' vertex ids, in the order in which they were visited by the search.} #' \item{rank}{Numeric vector. The rank for each vertex.} \item{father}{Numeric #' vector. The father of each vertex, i.e. the vertex it was discovered from.} #' \item{pred}{Numeric vector. The previously visited vertex for each vertex, #' or 0 if there was no such vertex.} \item{succ}{Numeric vector. The next #' vertex that was visited after the current one, or 0 if there was no such #' vertex.} \item{dist}{Numeric vector, for each vertex its distance from the #' root of the search tree.} #' #' Note that \code{order}, \code{rank}, \code{father}, \code{pred}, \code{succ} #' and \code{dist} might be \code{NULL} if their corresponding argument is #' \code{FALSE}, i.e. if their calculation is not requested. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{dfs}} for depth-first search. #' @export #' @keywords graphs #' @examples #' #' ## Two rings #' bfs(make_ring(10) %du% make_ring(10), root=1, "out", #' order=TRUE, rank=TRUE, father=TRUE, pred=TRUE, #' succ=TRUE, dist=TRUE) #' #' ## How to use a callback #' f <- function(graph, data, extra) { #' print(data) #' FALSE #' } #' tmp <- bfs(make_ring(10) %du% make_ring(10), root=1, "out", #' callback=f) #' #' ## How to use a callback to stop the search #' ## We stop after visiting all vertices in the initial component #' f <- function(graph, data, extra) { #' data['succ'] == -1 #' } #' bfs(make_ring(10) %du% make_ring(10), root=1, callback=f) #' #' bfs <- function(graph, root, neimode=c("out", "in", "all", "total"), unreachable=TRUE, restricted=NULL, order=TRUE, rank=FALSE, father=FALSE, pred=FALSE, succ=FALSE, dist=FALSE, callback=NULL, extra=NULL, rho=parent.frame()) { if (!is_igraph(graph)) { stop("Not a graph object"); } if (length(root)==1) { root <- as.igraph.vs(graph, root)-1 roots <- NULL } else { roots <- as.igraph.vs(graph, root)-1 root <- 0 # ignored anyway } neimode <- switch(igraph.match.arg(neimode), "out"=1, "in"=2, "all"=3, "total"=3) unreachable <- as.logical(unreachable) if (!is.null(restricted)) { restricted <- as.igraph.vs(graph, restricted) - 1 } if (!is.null(callback)) { callback <- as.function(callback) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_bfs, graph, root, roots, neimode, unreachable, restricted, as.logical(order), as.logical(rank), as.logical(father), as.logical(pred), as.logical(succ), as.logical(dist), callback, extra, rho) if (order) res$order <- res$order+1 if (rank) res$rank <- res$rank+1 if (father) res$father <- res$father+1 if (pred) res$pred <- res$pred+1 if (succ) res$succ <- res$succ+1 if (igraph_opt("return.vs.es")) { if (order) res$order <- create_vs(graph, res$order, na_ok = TRUE) if (father) res$father <- create_vs(graph, res$father, na_ok = TRUE) if (pred) res$pred <- create_vs(graph, res$pred, na_ok = TRUE) if (succ) res$succ <- create_vs(graph, res$succ, na_ok = TRUE) } if (igraph_opt("add.vertex.names") && is_named(graph)) { if (rank) names(res$rank) <- V(graph)$name if (father) names(res$father) <- V(graph)$name if (pred) names(res$pred) <- V(graph)$name if (succ) names(res$succ) <- V(graph)$name if (dist) names(res$dist) <- V(graph)$name } res } #' Depth-first search #' #' Depth-first search is an algorithm to traverse a graph. It starts from a #' root vertex and tries to go quickly as far from as possible. #' #' The callback functions must have the following arguments: \describe{ #' \item{graph}{The input graph is passed to the callback function here.} #' \item{data}{A named numeric vector, with the following entries: #' \sQuote{vid}, the vertex that was just visited and \sQuote{dist}, its #' distance from the root of the search tree.} \item{extra}{The extra #' argument.} } See examples below on how to use the callback functions. #' #' @aliases graph.dfs #' @param graph The input graph. #' @param root The single root vertex to start the search from. #' @param neimode For directed graphs specifies the type of edges to follow. #' \sQuote{out} follows outgoing, \sQuote{in} incoming edges. \sQuote{all} #' ignores edge directions completely. \sQuote{total} is a synonym for #' \sQuote{all}. This argument is ignored for undirected graphs. #' @param unreachable Logical scalar, whether the search should visit the #' vertices that are unreachable from the given root vertex (or vertices). If #' \code{TRUE}, then additional searches are performed until all vertices are #' visited. #' @param order Logical scalar, whether to return the DFS ordering of the #' vertices. #' @param order.out Logical scalar, whether to return the ordering based on #' leaving the subtree of the vertex. #' @param father Logical scalar, whether to return the father of the vertices. #' @param dist Logical scalar, whether to return the distance from the root of #' the search tree. #' @param in.callback If not \code{NULL}, then it must be callback function. #' This is called whenever a vertex is visited. See details below. #' @param out.callback If not \code{NULL}, then it must be callback function. #' This is called whenever the subtree of a vertex is completed by the #' algorithm. See details below. #' @param extra Additional argument to supply to the callback function. #' @param rho The environment in which the callback function is evaluated. #' @return A named list with the following entries: \item{root}{Numeric scalar. #' The root vertex that was used as the starting point of the search.} #' \item{neimode}{Character scalar. The \code{neimode} argument of the function #' call. Note that for undirected graphs this is always \sQuote{all}, #' irrespectively of the supplied value.} \item{order}{Numeric vector. The #' vertex ids, in the order in which they were visited by the search.} #' \item{order.out}{Numeric vector, the vertex ids, in the order of the #' completion of their subtree.} \item{father}{Numeric vector. The father of #' each vertex, i.e. the vertex it was discovered from.} \item{dist}{Numeric #' vector, for each vertex its distance from the root of the search tree.} #' #' Note that \code{order}, \code{order.out}, \code{father}, and \code{dist} #' might be \code{NULL} if their corresponding argument is \code{FALSE}, i.e. #' if their calculation is not requested. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{bfs}} for breadth-first search. #' @export #' @keywords graphs #' @examples #' #' ## A graph with two separate trees #' dfs(make_tree(10) %du% make_tree(10), root=1, "out", #' TRUE, TRUE, TRUE, TRUE) #' #' ## How to use a callback #' f.in <- function(graph, data, extra) { #' cat("in:", paste(collapse=", ", data), "\n") #' FALSE #' } #' f.out <- function(graph, data, extra) { #' cat("out:", paste(collapse=", ", data), "\n") #' FALSE #' } #' tmp <- dfs(make_tree(10), root=1, "out", #' in.callback=f.in, out.callback=f.out) #' #' ## Terminate after the first component, using a callback #' f.out <- function(graph, data, extra) { #' data['vid'] == 1 #' } #' tmp <- dfs(make_tree(10) %du% make_tree(10), root=1, #' out.callback=f.out) #' #' dfs <- function(graph, root, neimode=c("out", "in", "all", "total"), unreachable=TRUE, order=TRUE, order.out=FALSE, father=FALSE, dist=FALSE, in.callback=NULL, out.callback=NULL, extra=NULL, rho=parent.frame()) { if (!is_igraph(graph)) { stop("Not a graph object"); } root <- as.igraph.vs(graph, root)-1 neimode <- switch(igraph.match.arg(neimode), "out"=1, "in"=2, "all"=3, "total"=3) unreachable <- as.logical(unreachable) if (!is.null(in.callback)) { in.callback <- as.function(in.callback) } if (!is.null(out.callback)) { out.callback <- as.function(out.callback) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_dfs, graph, root, neimode, unreachable, as.logical(order), as.logical(order.out), as.logical(father), as.logical(dist), in.callback, out.callback, extra, rho) if (order) res$order <- res$order+1 if (order.out) res$order.out <- res$order.out+1 if (father) res$father <- res$father+1 if (igraph_opt("return.vs.es")) { if (order) res$order <- V(graph)[res$order, na_ok = TRUE] if (order.out) res$order.out <- V(graph)[res$order.out, na_ok = TRUE] if (father) res$father <- create_vs(graph, res$father, na_ok = TRUE) } if (igraph_opt("add.vertex.names") && is_named(graph)) { if (father) names(res$father) <- V(graph)$name if (dist) names(res$dist) <- V(graph)$name } res } #' @rdname betweenness #' @param e The edges for which the edge betweenness will be calculated. #' @export edge_betweenness <- function(graph, e=E(graph), directed=TRUE, weights=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } e <- as.igraph.es(graph, e) directed <- as.logical(directed) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_edge_betweenness, graph, directed, weights) res[as.numeric(e)] } #' @export estimate_edge_betweenness <- function(graph, e=E(graph), directed=TRUE, cutoff, weights=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } e <- as.igraph.es(graph, e) directed <- as.logical(directed) cutoff <- as.numeric(cutoff) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_edge_betweenness_estimate, graph, directed, cutoff, weights) res[as.numeric(e)] } #' Connected components of a graph #' #' Calculate the maximal (weakly or strongly) connected components of a graph #' #' \code{is_connected} decides whether the graph is weakly or strongly #' connected. #' #' \code{components} finds the maximal (weakly or strongly) connected components #' of a graph. #' #' \code{count_components} does almost the same as \code{components} but returns only #' the number of clusters found instead of returning the actual clusters. #' #' \code{component_distribution} creates a histogram for the maximal connected #' component sizes. #' #' The weakly connected components are found by a simple breadth-first search. #' The strongly connected components are implemented by two consecutive #' depth-first searches. #' #' @aliases no.clusters clusters is.connected cluster.distribution components #' count_components is_connected #' @param graph The graph to analyze. #' @param mode Character string, either \dQuote{weak} or \dQuote{strong}. For #' directed graphs \dQuote{weak} implies weakly, \dQuote{strong} strongly #' connected components to search. It is ignored for undirected graphs. #' @param \dots Additional attributes to pass to \code{cluster}, right now only #' \code{mode} makes sense. #' @return For \code{is_connected} a logical constant. #' #' For \code{components} a named list with three components: #' \item{membership}{numeric vector giving the cluster id to which each vertex #' belongs.} \item{csize}{numeric vector giving the sizes of the clusters.} #' \item{no}{numeric constant, the number of clusters.} #' #' For \code{count_components} an integer constant is returned. #' #' For \code{component_distribution} a numeric vector with the relative #' frequencies. The length of the vector is the size of the largest component #' plus one. Note that (for currently unknown reasons) the first element of the #' vector is the number of clusters of size zero, so this is always zero. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{subcomponent}}, \code{\link{groups}} #' @export #' @keywords graphs #' @examples #' #' g <- sample_gnp(20, 1/20) #' clu <- components(g) #' groups(clu) #' components <- function(graph, mode=c("weak", "strong")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "weak"=1, "strong"=2) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_clusters, graph, mode) res$membership <- res$membership + 1 if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res$membership) <- V(graph)$name } res } #' Convert a general graph into a forest #' #' Perform a breadth-first search on a graph and convert it into a tree or #' forest by replicating vertices that were found more than once. #' #' A forest is a graph, whose components are trees. #' #' The \code{roots} vector can be calculated by simply doing a topological sort #' in all components of the graph, see the examples below. #' #' @aliases unfold.tree #' @param graph The input graph, it can be either directed or undirected. #' @param mode Character string, defined the types of the paths used for the #' breadth-first search. \dQuote{out} follows the outgoing, \dQuote{in} the #' incoming edges, \dQuote{all} and \dQuote{total} both of them. This argument #' is ignored for undirected graphs. #' @param roots A vector giving the vertices from which the breadth-first #' search is performed. Typically it contains one vertex per component. #' @return A list with two components: \item{tree}{The result, an \code{igraph} #' object, a tree or a forest.} \item{vertex_index}{A numeric vector, it gives #' a mapping from the vertices of the new graph to the vertices of the old #' graph.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_tree(10) %du% make_tree(10) #' V(g)$id <- seq_len(vcount(g))-1 #' roots <- sapply(decompose(g), function(x) { #' V(x)$id[ topo_sort(x)[1]+1 ] }) #' tree <- unfold_tree(g, roots=roots) #' unfold_tree <- function(graph, mode=c("all", "out", "in", "total"), roots) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) roots <- as.igraph.vs(graph, roots)-1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_unfold_tree, graph, mode, roots) res } #' Closeness centrality of vertices #' #' Cloness centrality measures how many steps is required to access every other #' vertex from a given vertex. #' #' The closeness centrality of a vertex is defined by the inverse of the #' average length of the shortest paths to/from all the other vertices in the #' graph: #' #' \deqn{\frac{1}{\sum_{i\ne v} d_vi}}{1/sum( d(v,i), i != v)} #' #' If there is no (directed) path between vertex \eqn{v}{\code{v}} and #' \eqn{i}{\code{i}} then the total number of vertices is used in the formula #' instead of the path length. #' #' \code{estimate_closeness} only considers paths of length \code{cutoff} or #' smaller, this can be run for larger graphs, as the running time is not #' quadratic (if \code{cutoff} is small). If \code{cutoff} is zero or negative #' then the function calculates the exact closeness scores. #' #' @aliases closeness closeness.estimate estimate_closeness #' @param graph The graph to analyze. #' @param vids The vertices for which closeness will be calculated. #' @param mode Character string, defined the types of the paths used for #' measuring the distance in directed graphs. \dQuote{in} measures the paths #' \emph{to} a vertex, \dQuote{out} measures paths \emph{from} a vertex, #' \emph{all} uses undirected paths. This argument is ignored for undirected #' graphs. #' @param normalized Logical scalar, whether to calculate the normalized #' closeness. Normalization is performed by multiplying the raw closeness by #' \eqn{n-1}, where \eqn{n} is the number of vertices in the graph. #' @param weights Optional positive weight vector for calculating weighted #' closeness. If the graph has a \code{weight} edge attribute, then this is #' used by default. Weights are used for calculating weighted shortest #' paths, so they are interpreted as distances. #' @return Numeric vector with the closeness values of all the vertices in #' \code{v}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{betweenness}}, \code{\link{degree}} #' @references Freeman, L.C. (1979). Centrality in Social Networks I: #' Conceptual Clarification. \emph{Social Networks}, 1, 215-239. #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g2 <- make_star(10) #' closeness(g) #' closeness(g2, mode="in") #' closeness(g2, mode="out") #' closeness(g2, mode="all") #' closeness <- function(graph, vids=V(graph), mode=c("out", "in", "all", "total"), weights=NULL, normalized=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_closeness, graph, vids-1, mode, weights, normalized) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- V(graph)$name[vids] } res } #' @rdname closeness #' @param cutoff The maximum path length to consider when calculating the #' betweenness. If zero or negative then there is no such limit. #' @export estimate_closeness <- function(graph, vids=V(graph), mode=c("out", "in", "all", "total"), cutoff, weights=NULL, normalized=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } vids <- as.igraph.vs(graph, vids) mode <- switch(igraph.match.arg(mode), "out"=1, "in"=2, "all"=3, "total"=3) cutoff <- as.numeric(cutoff) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } normalized <- as.logical(normalized) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_closeness_estimate, graph, vids-1, mode, cutoff, weights, normalized) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name", vids) } res } #' Graph Laplacian #' #' The Laplacian of a graph. #' #' The Laplacian Matrix of a graph is a symmetric matrix having the same number #' of rows and columns as the number of vertices in the graph and element (i,j) #' is d[i], the degree of vertex i if if i==j, -1 if i!=j and there is an edge #' between vertices i and j and 0 otherwise. #' #' A normalized version of the Laplacian Matrix is similar: element (i,j) is 1 #' if i==j, -1/sqrt(d[i] d[j]) if i!=j and there is an edge between vertices i #' and j and 0 otherwise. #' #' The weighted version of the Laplacian simply works with the weighted degree #' instead of the plain degree. I.e. (i,j) is d[i], the weighted degree of #' vertex i if if i==j, -w if i!=j and there is an edge between vertices i and #' j with weight w, and 0 otherwise. The weighted degree of a vertex is the sum #' of the weights of its adjacent edges. #' #' @aliases graph.laplacian #' @param graph The input graph. #' @param normalized Whether to calculate the normalized Laplacian. See #' definitions below. #' @param weights An optional vector giving edge weights for weighted Laplacian #' matrix. If this is \code{NULL} and the graph has an edge attribute called #' \code{weight}, then it will be used automatically. Set this to \code{NA} if #' you want the unweighted Laplacian on a graph that has a \code{weight} edge #' attribute. #' @param sparse Logical scalar, whether to return the result as a sparse #' matrix. The \code{Matrix} package is required for sparse matrices. #' @return A numeric matrix. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' laplacian_matrix(g) #' laplacian_matrix(g, norm=TRUE) #' laplacian_matrix(g, norm=TRUE, sparse=FALSE) #' laplacian_matrix <- function(graph, normalized=FALSE, weights=NULL, sparse=igraph_opt("sparsematrices")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } normalized <- as.logical(normalized) if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } sparse <- as.logical(sparse) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_laplacian, graph, normalized, weights, sparse) if (sparse) { res <- igraph.i.spMatrix(res) } if (igraph_opt("add.vertex.names") && is_named(graph)) { rownames(res) <- colnames(res) <- V(graph)$name } res } #' Graph matching #' #' A matching in a graph means the selection of a set of edges that are #' pairwise non-adjacenct, i.e. they have no common incident vertices. A #' matching is maximal if it is not a proper subset of any other matching. #' #' \code{is_matching} checks a matching vector and verifies whether its #' length matches the number of vertices in the given graph, its values are #' between zero (inclusive) and the number of vertices (inclusive), and #' whether there exists a corresponding edge in the graph for every matched #' vertex pair. For bipartite graphs, it also verifies whether the matched #' vertices are in different parts of the graph. #' #' \code{is_max_matching} checks whether a matching is maximal. A matching #' is maximal if and only if there exists no unmatched vertex in a graph #' such that one of its neighbors is also unmatched. #' #' \code{max_bipartite_match} calculates a maximum matching in a bipartite #' graph. A matching in a bipartite graph is a partial assignment of #' vertices of the first kind to vertices of the second kind such that each #' vertex of the first kind is matched to at most one vertex of the second #' kind and vice versa, and matched vertices must be connected by an edge #' in the graph. The size (or cardinality) of a matching is the number of #' edges. A matching is a maximum matching if there exists no other #' matching with larger cardinality. For weighted graphs, a maximum #' matching is a matching whose edges have the largest possible total #' weight among all possible matchings. #' #' Maximum matchings in bipartite graphs are found by the push-relabel #' algorithm with greedy initialization and a global relabeling after every #' \eqn{n/2} steps where \eqn{n} is the number of vertices in the graph. #' #' @rdname matching #' @aliases is.matching is_matching is.maximal.matching is_max_matching #' maximum.bipartite.matching max_bipartite_match #' @param graph The input graph. It might be directed, but edge directions will #' be ignored. #' @param types Vertex types, if the graph is bipartite. By default they #' are taken from the \sQuote{\code{type}} vertex attribute, if present. #' @param matching A potential matching. An integer vector that gives the #' pair in the matching for each vertex. For vertices without a pair, #' supply \code{NA} here. #' @param weights Potential edge weights. If the graph has an edge #' attribute called \sQuote{\code{weight}}, and this argument is #' \code{NULL}, then the edge attribute is used automatically. #' In weighed matching, the weights of the edges must match as #' much as possible. #' @param eps A small real number used in equality tests in the weighted #' bipartite matching algorithm. Two real numbers are considered equal in #' the algorithm if their difference is smaller than \code{eps}. This is #' required to avoid the accumulation of numerical errors. By default it is #' set to the smallest \eqn{x}, such that \eqn{1+x \ne 1}{1+x != 1} #' holds. If you are running the algorithm with no weights, this argument #' is ignored. #' @return \code{is_matching} and \code{is_max_matching} return a logical #' scalar. #' #' \code{max_bipartite_match} returns a list with components: #' \item{matching_size}{The size of the matching, i.e. the number of edges #' connecting the matched vertices.} #' \item{matching_weight}{The weights of the matching, if the graph was #' weighted. For unweighted graphs this is the same as the size of the #' matching.} #' \item{matching}{The matching itself. Numeric vertex id, or vertex #' names if the graph was named. Non-matched vertices are denoted by #' \code{NA}.} #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @examples #' g <- graph_from_literal( a-b-c-d-e-f ) #' m1 <- c("b", "a", "d", "c", "f", "e") # maximal matching #' m2 <- c("b", "a", "d", "c", NA, NA) # non-maximal matching #' m3 <- c("b", "c", "d", "c", NA, NA) # not a matching #' is_matching(g, m1) #' is_matching(g, m2) #' is_matching(g, m3) #' is_max_matching(g, m1) #' is_max_matching(g, m2) #' is_max_matching(g, m3) #' #' V(g)$type <- c(FALSE,TRUE) #' print_all(g, v=TRUE) #' max_bipartite_match(g) #' #' g2 <- graph_from_literal( a-b-c-d-e-f-g ) #' V(g2)$type <- rep(c(FALSE,TRUE), length=vcount(g2)) #' print_all(g2, v=TRUE) #' max_bipartite_match(g2) #' #' @keywords graphs #' @export is_matching <- function(graph, matching, types=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { types <- as.logical(types) } matching <- as.igraph.vs(graph, matching, na.ok=TRUE)-1 matching[ is.na(matching) ] <- -1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_matching, graph, types, matching) res } #' @export #' @rdname matching is_max_matching <- function(graph, matching, types=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { types <- as.logical(types) } matching <- as.igraph.vs(graph, matching, na.ok=TRUE)-1 matching[ is.na(matching) ] <- -1 on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_is_maximal_matching, graph, types, matching) res } #' @export #' @rdname matching max_bipartite_match <- function(graph, types=NULL, weights=NULL, eps=.Machine$double.eps) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { types <- as.logical(types) } if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } eps <- as.numeric(eps) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_maximum_bipartite_matching, graph, types, weights, eps) res$matching[ res$matching==0 ] <- NA if (igraph_opt("add.vertex.names") && is_named(graph)) { res$matching <- V(graph)$name[res$matching] names(res$matching) <- V(graph)$name } res } #' Find mutual edges in a directed graph #' #' This function checks the reciproc pair of the supplied edges. #' #' In a directed graph an (A,B) edge is mutual if the graph also includes a #' (B,A) directed edge. #' #' Note that multi-graphs are not handled properly, i.e. if the graph contains #' two copies of (A,B) and one copy of (B,A), then these three edges are #' considered to be mutual. #' #' Undirected graphs contain only mutual edges by definition. #' #' @aliases is.mutual which_mutual #' @param graph The input graph. #' @param es Edge sequence, the edges that will be probed. By default is #' includes all edges in the order of their ids. #' @return A logical vector of the same length as the number of edges supplied. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{reciprocity}}, \code{\link{dyad_census}} if you just #' want some statistics about mutual edges. #' @keywords graphs #' @examples #' #' g <- sample_gnm(10, 50, directed=TRUE) #' reciprocity(g) #' dyad_census(g) #' which_mutual(g) #' sum(which_mutual(g))/2 == dyad_census(g)$mut #' @export which_mutual <- which_mutual #' Average nearest neighbor degree #' #' Calculate the average nearest neighbor degree of the given vertices and the #' same quantity in the function of vertex degree #' #' Note that for zero degree vertices the answer in \sQuote{\code{knn}} is #' \code{NaN} (zero divided by zero), the same is true for \sQuote{\code{knnk}} #' if a given degree never appears in the network. #' #' @aliases knn graph.knn #' @param graph The input graph. It can be directed, but it will be treated as #' undirected, i.e. the direction of the edges is ignored. #' @param vids The vertices for which the calculation is performed. Normally it #' includes all vertices. Note, that if not all vertices are given here, then #' both \sQuote{\code{knn}} and \sQuote{\code{knnk}} will be calculated based #' on the given vertices only. #' @param weights Weight vector. If the graph has a \code{weight} edge #' attribute, then this is used by default. If this argument is given, then #' vertex strength (see \code{\link{strength}}) is used instead of vertex #' degree. But note that \code{knnk} is still given in the function of the #' normal vertex degree. #' Weights are are used to calculate a weighted degree (also called #' \code{\link{strength}}) instead of the degree. #' @return A list with two members: \item{knn}{A numeric vector giving the #' average nearest neighbor degree for all vertices in \code{vids}.} #' \item{knnk}{A numeric vector, its length is the maximum (total) vertex #' degree in the graph. The first element is the average nearest neighbor #' degree of vertices with degree one, etc. } #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, #' Alessandro Vespignani: The architecture of complex weighted networks, Proc. #' Natl. Acad. Sci. USA 101, 3747 (2004) #' @keywords graphs #' @examples #' #' # Some trivial ones #' g <- make_ring(10) #' knn(g) #' g2 <- make_star(10) #' knn(g2) #' #' # A scale-free one, try to plot 'knnk' #' g3 <- sample_pa(1000, m=5) #' knn(g3) #' #' # A random graph #' g4 <- sample_gnp(1000, p=5/1000) #' knn(g4) #' #' # A weighted graph #' g5 <- make_star(10) #' E(g5)$weight <- seq(ecount(g5)) #' knn(g5) #' @export #' @include auto.R knn <- knn igraph/R/centrality.R0000644000175100001440000010526213247212322014250 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' @rdname arpack #' @export arpack_defaults <- list(bmat="I", n=0, which="XX", nev=1, tol=0.0, ncv=3, ldv=0, ishift=1, maxiter=1000, nb=1, mode=1, start=0, sigma=0.0, sigmai=0.0) #' ARPACK eigenvector calculation #' #' Interface to the ARPACK library for calculating eigenvectors of sparse #' matrices #' #' ARPACK is a library for solving large scale eigenvalue problems. The #' package is designed to compute a few eigenvalues and corresponding #' eigenvectors of a general \eqn{n} by \eqn{n} matrix \eqn{A}. It is most #' appropriate for large sparse or structured matrices \eqn{A} where structured #' means that a matrix-vector product \code{w <- Av} requires order \eqn{n} #' rather than the usual order \eqn{n^2} floating point operations. Please see #' \url{http://www.caam.rice.edu/software/ARPACK/} for details. #' #' This function is an interface to ARPACK. igraph does not contain all ARPACK #' routines, only the ones dealing with symmetric and non-symmetric eigenvalue #' problems using double precision real numbers. #' #' The eigenvalue calculation in ARPACK (in the simplest case) involves the #' calculation of the \eqn{Av} product where \eqn{A} is the matrix we work with #' and \eqn{v} is an arbitrary vector. The function supplied in the \code{fun} #' argument is expected to perform this product. If the product can be done #' efficiently, e.g. if the matrix is sparse, then \code{arpack} is usually #' able to calculate the eigenvalues very quickly. #' #' The \code{options} argument specifies what kind of calculation to perform. #' It is a list with the following members, they correspond directly to ARPACK #' parameters. On input it has the following fields: \describe{ #' \item{bmat}{Character constant, possible values: \sQuote{\code{I}}, stadard #' eigenvalue problem, \eqn{Ax=\lambda x}{A*x=lambda*x}; and \sQuote{\code{G}}, #' generalized eigenvalue problem, \eqn{Ax=\lambda B x}{A*x=lambda B*x}. #' Currently only \sQuote{\code{I}} is supported.} \item{n}{Numeric scalar. The #' dimension of the eigenproblem. You only need to set this if you call #' \code{\link{arpack}} directly. (I.e. not needed for #' \code{\link{eigen_centrality}}, \code{\link{page_rank}}, etc.)} #' \item{which}{Specify which eigenvalues/vectors to compute, character #' constant with exactly two characters. #' #' Possible values for symmetric input matrices: \describe{ #' \item{"LA"}{Compute \code{nev} largest (algebraic) eigenvalues.} #' \item{"SA"}{Compute \code{nev} smallest (algebraic) #' eigenvalues.} \item{"LM"}{Compute \code{nev} largest (in #' magnitude) eigenvalues.} \item{"SM"}{Compute \code{nev} smallest #' (in magnitude) eigenvalues.} \item{"BE"}{Compute \code{nev} #' eigenvalues, half from each end of the spectrum. When \code{nev} is odd, #' compute one more from the high end than from the low end.} } #' #' Possible values for non-symmetric input matrices: \describe{ #' \item{"LM"}{Compute \code{nev} eigenvalues of largest #' magnitude.} \item{"SM"}{Compute \code{nev} eigenvalues of #' smallest magnitude.} \item{"LR"}{Compute \code{nev} eigenvalues #' of largest real part.} \item{"SR"}{Compute \code{nev} #' eigenvalues of smallest real part.} \item{"LI"}{Compute #' \code{nev} eigenvalues of largest imaginary part.} #' \item{"SI"}{Compute \code{nev} eigenvalues of smallest imaginary #' part.} } #' #' This parameter is sometimes overwritten by the various functions, e.g. #' \code{\link{page_rank}} always sets \sQuote{\code{LM}}. } #' \item{nev}{Numeric scalar. The number of eigenvalues to be computed.} #' \item{tol}{Numeric scalar. Stopping criterion: the relative accuracy of the #' Ritz value is considered acceptable if its error is less than \code{tol} #' times its estimated value. If this is set to zero then machine precision is #' used.} \item{ncv}{Number of Lanczos vectors to be generated.} #' \item{ldv}{Numberic scalar. It should be set to zero in the current #' implementation.} \item{ishift}{Either zero or one. If zero then the shifts #' are provided by the user via reverse communication. If one then exact shifts #' with respect to the reduced tridiagonal matrix \eqn{T}. Please always set #' this to one.} \item{maxiter}{Maximum number of Arnoldi update iterations #' allowed. } \item{nb}{Blocksize to be used in the recurrence. Please always #' leave this on the default value, one.} \item{mode}{The type of the #' eigenproblem to be solved. Possible values if the input matrix is #' symmetric: \describe{ \item{1}{\eqn{Ax=\lambda x}{A*x=lambda*x}, \eqn{A} is #' symmetric.} \item{2}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is #' symmetric, \eqn{M} is symmetric positive definite.} \item{3}{\eqn{Kx=\lambda #' Mx}{K*x=lambda*M*x}, \eqn{K} is symmetric, \eqn{M} is symmetric positive #' semi-definite.} \item{4}{\eqn{Kx=\lambda KGx}{K*x=lambda*KG*x}, \eqn{K} is #' symmetric positive semi-definite, \eqn{KG} is symmetric indefinite.} #' \item{5}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{A} is symmetric, \eqn{M} #' is symmetric positive semi-definite. (Cayley transformed mode.)} } Please #' note that only \code{mode==1} was tested and other values might not work #' properly. #' #' Possible values if the input matrix is not symmetric: \describe{ #' \item{1}{\eqn{Ax=\lambda x}{A*x=lambda*x}.} \item{2}{\eqn{Ax=\lambda #' Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric positive definite.} #' \item{3}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is symmetric #' semi-definite.} \item{4}{\eqn{Ax=\lambda Mx}{A*x=lambda*M*x}, \eqn{M} is #' symmetric semi-definite.} } Please note that only \code{mode==1} was tested #' and other values might not work properly. } \item{start}{Not used #' currently. Later it be used to set a starting vector.} \item{sigma}{Not used #' currently.} \item{sigmai}{Not use currently.} #' #' On output the following additional fields are added: \describe{ #' \item{info}{Error flag of ARPACK. Possible values: \describe{ #' \item{0}{Normal exit.} \item{1}{Maximum number of iterations taken.} #' \item{3}{No shifts could be applied during a cycle of the Implicitly #' restarted Arnoldi iteration. One possibility is to increase the size of #' \code{ncv} relative to \code{nev}.} } #' #' ARPACK can return more error conditions than these, but they are converted #' to regular igraph errors. } \item{iter}{Number of Arnoldi iterations #' taken.} \item{nconv}{Number of \dQuote{converged} Ritz values. This #' represents the number of Ritz values that satisfy the convergence critetion. #' } \item{numop}{Total number of matrix-vector multiplications.} #' \item{numopb}{Not used currently.} \item{numreo}{Total number of steps of #' re-orthogonalization.} } } Please see the ARPACK documentation for #' additional details. #' #' @aliases arpack arpack-options igraph.arpack.default arpack.unpack.complex #' arpack_defaults #' @param func The function to perform the matrix-vector multiplication. ARPACK #' requires to perform these by the user. The function gets the vector \eqn{x} #' as the first argument, and it should return \eqn{Ax}, where \eqn{A} is the #' \dQuote{input matrix}. (The input matrix is never given explicitly.) The #' second argument is \code{extra}. #' @param extra Extra argument to supply to \code{func}. #' @param sym Logical scalar, whether the input matrix is symmetric. Always #' supply \code{TRUE} here if it is, since it can speed up the computation. #' @param options Options to ARPACK, a named list to overwrite some of the #' default option values. See details below. #' @param env The environment in which \code{func} will be evaluated. #' @param complex Whether to convert the eigenvectors returned by ARPACK into R #' complex vectors. By default this is not done for symmetric problems (these #' only have real eigenvectors/values), but only non-symmetric ones. If you #' have a non-symmetric problem, but you're sure that the results will be real, #' then supply \code{FALSE} here. #' @return A named list with the following members: \item{values}{Numeric #' vector, the desired eigenvalues.} \item{vectors}{Numeric matrix, the desired #' eigenvectors as columns. If \code{complex=TRUE} (the default for #' non-symmetric problems), then the matrix is complex.} \item{options}{A named #' list with the supplied \code{options} and some information about the #' performed calculation, including an ARPACK exit code. See the details above. #' } #' @author Rich Lehoucq, Kristi Maschhoff, Danny Sorensen, Chao Yang for #' ARPACK, Gabor Csardi \email{csardi.gabor@@gmail.com} for the R interface. #' @seealso \code{\link{eigen_centrality}}, \code{\link{page_rank}}, #' \code{\link{hub_score}}, \code{\link{cluster_leading_eigen}} are some of the #' functions in igraph which use ARPACK. The ARPACK homepage is at #' \url{http://www.caam.rice.edu/software/ARPACK/}. #' @references D.C. Sorensen, Implicit Application of Polynomial Filters in a #' k-Step Arnoldi Method. \emph{SIAM J. Matr. Anal. Apps.}, 13 (1992), pp #' 357-385. #' #' R.B. Lehoucq, Analysis and Implementation of an Implicitly Restarted Arnoldi #' Iteration. \emph{Rice University Technical Report} TR95-13, Department of #' Computational and Applied Mathematics. #' #' B.N. Parlett & Y. Saad, Complex Shift and Invert Strategies for Real #' Matrices. \emph{Linear Algebra and its Applications}, vol 88/89, pp 575-595, #' (1987). #' @keywords graphs #' @examples #' #' # Identity matrix #' f <- function(x, extra=NULL) x #' arpack(f, options=list(n=10, nev=2, ncv=4), sym=TRUE) #' #' # Graph laplacian of a star graph (undirected), n>=2 #' # Note that this is a linear operation #' f <- function(x, extra=NULL) { #' y <- x #' y[1] <- (length(x)-1)*x[1] - sum(x[-1]) #' for (i in 2:length(x)) { #' y[i] <- x[i] - x[1] #' } #' y #' } #' #' arpack(f, options=list(n=10, nev=1, ncv=3), sym=TRUE) #' #' # double check #' eigen(laplacian_matrix(make_star(10, mode="undirected"))) #' #' ## First three eigenvalues of the adjacency matrix of a graph #' ## We need the 'Matrix' package for this #' if (require(Matrix)) { #' set.seed(42) #' g <- sample_gnp(1000, 5/1000) #' M <- as_adj(g, sparse=TRUE) #' f2 <- function(x, extra=NULL) { cat("."); as.vector(M %*% x) } #' baev <- arpack(f2, sym=TRUE, options=list(n=vcount(g), nev=3, ncv=8, #' which="LM", maxiter=2000)) #' } #' @export arpack <- function(func, extra=NULL, sym=FALSE, options=arpack_defaults, env=parent.frame(), complex=!sym) { if (!is.list(options) || (is.null(names(options)) && length(options) != 0)) { stop("options must be a named list") } if (any(names(options) == "")) { stop("all options must be named") } if (any(! names(options) %in% names(arpack_defaults))) { stop("unkown ARPACK option(s): ", paste(setdiff(names(options), names(arpack_defaults)), collapse=", ")) } options.tmp <- arpack_defaults options.tmp[ names(options) ] <- options options <- options.tmp if (sym && complex) { complex <- FALSE warning("Symmetric matrix, setting `complex' to FALSE") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_arpack, func, extra, options, env, sym) if (complex) { rew <- arpack.unpack.complex(res$vectors, res$values, min(res$options$nev, res$options$nconv)) res$vectors <- rew$vectors res$values <- rew$values res$values <- apply(res$values, 1, function(x) x[1]+x[2]*1i) dim(res$vectors) <- c(nrow(res$vectors)*2, ncol(res$vectors)/2) res$vectors <- apply(res$vectors, 2, function(x) { l <- length(x)/2 x[1:l] + x[(l+1):length(x)]*1i }) } else { if (is.matrix(res$values)) { if (!all(res$values[,2]==0)) { warning("Dropping imaginary parts of eigenvalues") } res$values <- res$values[,1] } res$vectors <- res$vectors[,1:length(res$values)] } res } arpack.unpack.complex <- function(vectors, values, nev) { # Argument checks vectors <- as.matrix(structure(as.double(vectors), dim=dim(vectors))) values <- as.matrix(structure(as.double(values), dim=dim(values))) nev <- as.integer(nev) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_arpack_unpack_complex, vectors, values, nev) res } #' Find subgraph centrality scores of network positions #' #' Subgraph centrality of a vertex measures the number of subgraphs a vertex #' participates in, weighting them according to their size. #' #' The subgraph centrality of a vertex is defined as the number of closed loops #' originating at the vertex, where longer loops are exponentially #' downweighted. #' #' Currently the calculation is performed by explicitly calculating all #' eigenvalues and eigenvectors of the adjacency matrix of the graph. This #' effectively means that the measure can only be calculated for small graphs. #' #' @aliases subgraph.centrality #' @param graph The input graph, it should be undirected, but the #' implementation does not check this currently. #' @param diag Boolean scalar, whether to include the diagonal of the adjacency #' matrix in the analysis. Giving \code{FALSE} here effectively eliminates the #' loops edges from the graph before the calculation. #' @return A numeric vector, the subgraph centrality scores of the vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} based on the Matlab #' code by Ernesto Estrada #' @seealso \code{\link{eigen_centrality}}, \code{\link{page_rank}} #' @references Ernesto Estrada, Juan A. Rodriguez-Velazquez: Subgraph #' centrality in Complex Networks. \emph{Physical Review E} 71, 056103 (2005). #' @export #' @keywords graphs #' @examples #' #' g <- sample_pa(100, m=4, dir=FALSE) #' sc <- subgraph_centrality(g) #' cor(degree(g), sc) #' subgraph_centrality <- function(graph, diag=FALSE) { A <- as_adj(graph) if (!diag) { diag(A) <- 0 } eig <- eigen(A) res <- as.vector(eig$vectors^2 %*% exp(eig$values)) if (igraph_opt("add.vertex.names") && is_named(graph)) { names(res) <- vertex_attr(graph, "name") } res } #' Eigenvalues and eigenvectors of the adjacency matrix of a graph #' #' Calculate selected eigenvalues and eigenvectors of a (supposedly sparse) #' graph. #' #' The \code{which} argument is a list and it specifies which eigenvalues and #' corresponding eigenvectors to calculate: There are eight options: #' \enumerate{ \item Eigenvalues with the largest magnitude. Set \code{pos} to #' \code{LM}, and \code{howmany} to the number of eigenvalues you want. \item #' Eigenvalues with the smallest magnitude. Set \code{pos} to \code{SM} and #' \code{howmany} to the number of eigenvalues you want. \item Largest #' eigenvalues. Set \code{pos} to \code{LA} and \code{howmany} to the number of #' eigenvalues you want. \item Smallest eigenvalues. Set \code{pos} to #' \code{SA} and \code{howmany} to the number of eigenvalues you want. \item #' Eigenvalues from both ends of the spectrum. Set \code{pos} to \code{BE} and #' \code{howmany} to the number of eigenvalues you want. If \code{howmany} is #' odd, then one more eigenvalue is returned from the larger end. \item #' Selected eigenvalues. This is not (yet) implemented currently. \item #' Eigenvalues in an interval. This is not (yet) implemented. \item All #' eigenvalues. This is not implemented yet. The standard \code{eigen} function #' does a better job at this, anyway. } #' #' Note that ARPACK might be unstable for graphs with multiple components, e.g. #' graphs with isolate vertices. #' #' @aliases graph.eigen spectrum igraph.eigen.default #' @param graph The input graph, can be directed or undirected. #' @param algorithm The algorithm to use. Currently only \code{arpack} is #' implemented, which uses the ARPACK solver. See also \code{\link{arpack}}. #' @param which A list to specify which eigenvalues and eigenvectors to #' calculate. By default the leading (i.e. largest magnitude) eigenvalue and #' the corresponding eigenvector is calculated. #' @param options Options for the ARPACK solver. See #' \code{\link{arpack_defaults}}. #' @return Depends on the algorithm used. #' #' For \code{arpack} a list with three entries is returned: \item{options}{See #' the return value for \code{arpack} for a complete description.} #' \item{values}{Numeric vector, the eigenvalues.} \item{vectors}{Numeric #' matrix, with the eigenvectors as columns.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{as_adj}} to create a (sparse) adjacency matrix. #' @keywords graphs #' @examples #' #' ## Small example graph, leading eigenvector by default #' kite <- make_graph("Krackhardt_kite") #' spectrum(kite)[c("values", "vectors")] #' #' ## Double check #' eigen(as_adj(kite, sparse=FALSE))$vectors[,1] #' #' ## Should be the same as 'eigen_centrality' (but rescaled) #' cor(eigen_centrality(kite)$vector, spectrum(kite)$vectors) #' #' ## Smallest eigenvalues #' spectrum(kite, which=list(pos="SM", howmany=2))$values #' #' @export #' @include auto.R spectrum <- spectrum eigen_defaults <- list(pos="LM", howmany=1L, il=-1L, iu=-1L, vl=-Inf, vu=Inf, vestimate=0L, balance="none") #' Find Eigenvector Centrality Scores of Network Positions #' #' \code{eigen_centrality} takes a graph (\code{graph}) and returns the #' eigenvector centralities of positions \code{v} within it #' #' Eigenvector centrality scores correspond to the values of the first #' eigenvector of the graph adjacency matrix; these scores may, in turn, be #' interpreted as arising from a reciprocal process in which the centrality of #' each actor is proportional to the sum of the centralities of those actors to #' whom he or she is connected. In general, vertices with high eigenvector #' centralities are those which are connected to many other vertices which are, #' in turn, connected to many others (and so on). (The perceptive may realize #' that this implies that the largest values will be obtained by individuals in #' large cliques (or high-density substructures). This is also intelligible #' from an algebraic point of view, with the first eigenvector being closely #' related to the best rank-1 approximation of the adjacency matrix (a #' relationship which is easy to see in the special case of a diagonalizable #' symmetric real matrix via the \eqn{SLS^-1}{$S \Lambda S^{-1}$} #' decomposition).) #' #' From igraph version 0.5 this function uses ARPACK for the underlying #' computation, see \code{\link{arpack}} for more about ARPACK in igraph. #' #' @aliases evcent eigen_centrality #' @param graph Graph to be analyzed. #' @param directed Logical scalar, whether to consider direction of the edges #' in directed graphs. It is ignored for undirected graphs. #' @param scale Logical scalar, whether to scale the result to have a maximum #' score of one. If no scaling is used then the result vector has unit length #' in the Euclidean norm. #' @param weights A numerical vector or \code{NULL}. This argument can be used #' to give edge weights for calculating the weighted eigenvector centrality of #' vertices. If this is \code{NULL} and the graph has a \code{weight} edge #' attribute then that is used. If \code{weights} is a numerical vector then it #' used, even if the graph has a \code{weights} edge attribute. If this is #' \code{NA}, then no edge weights are used (even if the graph has a #' \code{weight} edge attribute. Note that if there are negative edge weights #' and the direction of the edges is considered, then the eigenvector might be #' complex. In this case only the real part is reported. #' This function interprets weights as connection strength. Higher #' weights spread the centrality better. #' @param options A named list, to override some ARPACK options. See #' \code{\link{arpack}} for details. #' @return A named list with components: \item{vector}{A vector containing the #' centrality scores.} \item{value}{The eigenvalue corresponding to the #' calculated eigenvector, i.e. the centrality scores.} \item{options}{A named #' list, information about the underlying ARPACK computation. See #' \code{\link{arpack}} for the details. } #' @section WARNING : \code{eigen_centrality} will not symmetrize your data #' before extracting eigenvectors; don't send this routine asymmetric matrices #' unless you really mean to do so. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} and Carter T. Butts #' (\url{http://www.faculty.uci.edu/profile.cfm?faculty_id=5057}) for the #' manual page. #' @references Bonacich, P. (1987). Power and Centrality: A Family of #' Measures. \emph{American Journal of Sociology}, 92, 1170-1182. #' @keywords graphs #' @examples #' #' #Generate some test data #' g <- make_ring(10, directed=FALSE) #' #Compute eigenvector centrality scores #' eigen_centrality(g) #' @export eigen_centrality <- eigen_centrality #' Strength or weighted vertex degree #' #' Summing up the edge weights of the adjacent edges for each vertex. #' #' #' @aliases graph.strength strength #' @param graph The input graph. #' @param vids The vertices for which the strength will be calculated. #' @param mode Character string, \dQuote{out} for out-degree, \dQuote{in} for #' in-degree or \dQuote{all} for the sum of the two. For undirected graphs this #' argument is ignored. #' @param loops Logical; whether the loop edges are also counted. #' @param weights Weight vector. If the graph has a \code{weight} edge #' attribute, then this is used by default. If the graph does not have a #' \code{weight} edge attribute and this argument is \code{NULL}, then a #' warning is given and \code{\link{degree}} is called. #' @return A numeric vector giving the strength of the vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{degree}} for the unweighted version. #' @references Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, #' Alessandro Vespignani: The architecture of complex weighted networks, Proc. #' Natl. Acad. Sci. USA 101, 3747 (2004) #' @keywords graphs #' @examples #' #' g <- make_star(10) #' E(g)$weight <- seq(ecount(g)) #' strength(g) #' strength(g, mode="out") #' strength(g, mode="in") #' #' # No weights, a warning is given #' g <- make_ring(10) #' strength(g) #' @export strength <- strength #' Graph diversity #' #' Calculates a measure of diversity for all vertices. #' #' The diversity of a vertex is defined as the (scaled) Shannon entropy of the #' weights of its incident edges: #' \deqn{D(i)=\frac{H(i)}{\log k_i}}{D(i)=H(i)/log(k[i])} #' and #' \deqn{H(i)=-\sum_{j=1}^{k_i} p_{ij}\log p_{ij},}{H(i) = #' -sum(p[i,j] log(p[i,j]), j=1..k[i]),} where #' \deqn{p_{ij}=\frac{w_{ij}}{\sum_{l=1}^{k_i}}V_{il},}{p[i,j] = w[i,j] / #' sum(w[i,l], l=1..k[i]),} and \eqn{k_i}{k[i]} is the (total) degree of vertex #' \eqn{i}, \eqn{w_{ij}}{w[i,j]} is the weight of the edge(s) between vertices #' \eqn{i} and \eqn{j}. #' #' For vertices with degree less than two the function returns \code{NaN}. #' #' @aliases graph.diversity diversity #' @param graph The input graph. Edge directions are ignored. #' @param weights \code{NULL}, or the vector of edge weights to use for the #' computation. If \code{NULL}, then the \sQuote{weight} attibute is used. Note #' that this measure is not defined for unweighted graphs. #' @param vids The vertex ids for which to calculate the measure. #' @return A numeric vector, its length is the number of vertices. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Nathan Eagle, Michael Macy and Rob Claxton: Network Diversity #' and Economic Development, \emph{Science} \bold{328}, 1029--1031, 2010. #' @keywords graphs #' @examples #' #' g1 <- sample_gnp(20, 2/20) #' g2 <- sample_gnp(20, 2/20) #' g3 <- sample_gnp(20, 5/20) #' E(g1)$weight <- 1 #' E(g2)$weight <- runif(ecount(g2)) #' E(g3)$weight <- runif(ecount(g3)) #' diversity(g1) #' diversity(g2) #' diversity(g3) #' @export diversity <- diversity #' Kleinberg's hub centrality scores. #' #' The hub scores of the vertices are defined as the principal eigenvector #' of \eqn{A A^T}{A*t(A)}, where \eqn{A} is the adjacency matrix of the #' graph. #' #' For undirected matrices the adjacency matrix is symmetric and the hub #' scores are the same as authority scores, see #' \code{\link{authority_score}}. #' #' @aliases hub.score #' @param graph The input graph. #' @param scale Logical scalar, whether to scale the result to have a maximum #' score of one. If no scaling is used then the result vector has unit length #' in the Euclidean norm. #' @param weights Optional positive weight vector for calculating weighted #' scores. If the graph has a \code{weight} edge attribute, then this is used #' by default. #' This function interprets edge weights as connection strengths. In the #' random surfer model, an edge with a larger weight is more likely to be #' selected by the surfer. #' @param options A named list, to override some ARPACK options. See #' \code{\link{arpack}} for details. #' @return A named list with members: #' \item{vector}{The authority/hub scores of the vertices.} #' \item{value}{The corresponding eigenvalue of the calculated #' principal eigenvector.} #' \item{options}{Some information about the ARPACK computation, it has #' the same members as the \code{options} member returned #' by \code{\link{arpack}}, see that for documentation.} #' @seealso \code{\link{authority_score}}, #' \code{\link{eigen_centrality}} for eigenvector centrality, #' \code{\link{page_rank}} for the Page Rank scores. \code{\link{arpack}} for #' the underlining machinery of the computation. #' @references J. Kleinberg. Authoritative sources in a hyperlinked #' environment. \emph{Proc. 9th ACM-SIAM Symposium on Discrete Algorithms}, #' 1998. Extended version in \emph{Journal of the ACM} 46(1999). Also appears #' as IBM Research Report RJ 10076, May 1997. #' @examples #' ## An in-star #' g <- make_star(10) #' hub_score(g)$vector #' #' ## A ring #' g2 <- make_ring(10) #' hub_score(g2)$vector hub_score <- hub_score #' Kleinberg's authority centrality scores. #' #' The authority scores of the vertices are defined as the principal #' eigenvector of \eqn{A^T A}{t(A)*A}, where \eqn{A} is the adjacency #' matrix of the graph. #' #' For undirected matrices the adjacency matrix is symmetric and the #' authority scores are the same as hub scores, see #' \code{\link{hub_score}}. #' #' @aliases authority.score #' @param graph The input graph. #' @param scale Logical scalar, whether to scale the result to have a maximum #' score of one. If no scaling is used then the result vector has unit length #' in the Euclidean norm. #' @param weights Optional positive weight vector for calculating weighted #' scores. If the graph has a \code{weight} edge attribute, then this is used #' by default. #' This function interprets edge weights as connection strengths. In the #' random surfer model, an edge with a larger weight is more likely to be #' selected by the surfer. #' @param options A named list, to override some ARPACK options. See #' \code{\link{arpack}} for details. #' @return A named list with members: #' \item{vector}{The authority/hub scores of the vertices.} #' \item{value}{The corresponding eigenvalue of the calculated #' principal eigenvector.} #' \item{options}{Some information about the ARPACK computation, it has #' the same members as the \code{options} member returned #' by \code{\link{arpack}}, see that for documentation.} #' @seealso \code{\link{hub_score}}, \code{\link{eigen_centrality}} for #' eigenvector centrality, \code{\link{page_rank}} for the Page Rank #' scores. \code{\link{arpack}} for the underlining machinery of the #' computation. #' @references J. Kleinberg. Authoritative sources in a hyperlinked #' environment. \emph{Proc. 9th ACM-SIAM Symposium on Discrete Algorithms}, #' 1998. Extended version in \emph{Journal of the ACM} 46(1999). Also appears #' as IBM Research Report RJ 10076, May 1997. #' @examples #' ## An in-star #' g <- make_star(10) #' hub_score(g)$vector #' authority_score(g)$vector #' #' ## A ring #' g2 <- make_ring(10) #' hub_score(g2)$vector #' authority_score(g2)$vector authority_score <- authority_score #' The Page Rank algorithm #' #' Calculates the Google PageRank for the specified vertices. #' #' For the explanation of the PageRank algorithm, see the following webpage: #' \url{http://infolab.stanford.edu/~backrub/google.html}, or the following #' reference: #' #' Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual Web #' Search Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane, #' Australia, April 1998. #' #' igraph 0.5 (and later) contains two PageRank calculation implementations. #' The \code{page_rank} function uses ARPACK to perform the calculation, see #' also \code{\link{arpack}}. #' #' The \code{page_rank_old} function performs a simple power method, this is #' the implementation that was available under the name \code{page_rank} in pre #' 0.5 igraph versions. Note that \code{page_rank_old} has an argument called #' \code{old}. If this argument is \code{FALSE} (the default), then the proper #' PageRank algorithm is used, i.e. \eqn{(1-d)/n} is added to the weighted #' PageRank of vertices to calculate the next iteration. If this argument is #' \code{TRUE} then \eqn{(1-d)} is added, just like in the PageRank paper; #' \eqn{d} is the damping factor, and \eqn{n} is the total number of vertices. #' A further difference is that the old implementation does not renormalize the #' page rank vector after each iteration. Note that the \code{old=FALSE} #' method is not stable, is does not necessarily converge to a fixed point. It #' should be avoided for new code, it is only included for compatibility with #' old igraph versions. #' #' Please note that the PageRank of a given vertex depends on the PageRank of #' all other vertices, so even if you want to calculate the PageRank for only #' some of the vertices, all of them must be calculated. Requesting the #' PageRank for only some of the vertices does not result in any performance #' increase at all. #' #' Since the calculation is an iterative process, the algorithm is stopped #' after a given count of iterations or if the PageRank value differences #' between iterations are less than a predefined value. #' #' @aliases page.rank page_rank page.rank.old page_rank_old #' @param graph The graph object. #' @param algo Character scalar, which implementation to use to carry out the #' calculation. The default is \code{"prpack"}, which uses the PRPACK library #' (https://github.com/dgleich/prpack). This is a new implementation in igraph #' version 0.7, and the suggested one, as it is the most stable and the fastest #' for all but small graphs. \code{"arpack"} uses the ARPACK library, the #' default implementation from igraph version 0.5 until version 0.7. #' \code{power} uses a simple implementation of the power method, this was the #' default in igraph before version 0.5 and is the same as calling #' \code{page_rank_old}. #' @param vids The vertices of interest. #' @param directed Logical, if true directed paths will be considered for #' directed graphs. It is ignored for undirected graphs. #' @param damping The damping factor (\sQuote{d} in the original paper). #' @param personalized Optional vector giving a probability distribution to #' calculate personalized PageRank. For personalized PageRank, the probability #' of jumping to a node when abandoning the random walk is not uniform, but it #' is given by this vector. The vector should contains an entry for each vertex #' and it will be rescaled to sum up to one. #' @param weights A numerical vector or \code{NULL}. This argument can be used #' to give edge weights for calculating the weighted PageRank of vertices. If #' this is \code{NULL} and the graph has a \code{weight} edge attribute then #' that is used. If \code{weights} is a numerical vector then it used, even if #' the graph has a \code{weights} edge attribute. If this is \code{NA}, then no #' edge weights are used (even if the graph has a \code{weight} edge attribute. #' This function interprets edge weights as connection strengths. In the #' random surfer model, an edge with a larger weight is more likely to be #' selected by the surfer. #' @param options Either a named list, to override some ARPACK options. See #' \code{\link{arpack}} for details; or a named list to override the default #' options for the power method (if \code{algo="power"}). The default options #' for the power method are \code{niter=1000} and \code{eps=0.001}. This #' argument is ignored if the PRPACK implementation is used. #' @param niter The maximum number of iterations to perform. #' @param eps The algorithm will consider the calculation as complete if the #' difference of PageRank values between iterations change less than this value #' for every node. #' @param old A logical scalar, whether the old style (pre igraph 0.5) #' normalization to use. See details below. #' @return For \code{page_rank} a named list with entries: \item{vector}{A #' numeric vector with the PageRank scores.} \item{value}{The eigenvalue #' corresponding to the eigenvector with the page rank scores. It should be #' always exactly one.} \item{options}{Some information about the underlying #' ARPACK calculation. See \code{\link{arpack}} for details. This entry is #' \code{NULL} if not the ARPACK implementation was used.} #' #' For \code{page_rank_old} a numeric vector of Page Rank scores. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} #' @seealso Other centrality scores: \code{\link{closeness}}, #' \code{\link{betweenness}}, \code{\link{degree}} #' @references Sergey Brin and Larry Page: The Anatomy of a Large-Scale #' Hypertextual Web Search Engine. Proceedings of the 7th World-Wide Web #' Conference, Brisbane, Australia, April 1998. #' @keywords graphs #' @examples #' #' g <- sample_gnp(20, 5/20, directed=TRUE) #' page_rank(g)$vector #' #' g2 <- make_star(10) #' page_rank(g2)$vector #' #' # Personalized PageRank #' g3 <- make_ring(10) #' page_rank(g3)$vector #' reset <- seq(vcount(g3)) #' page_rank(g3, personalized=reset)$vector #' @export page_rank <- page_rank #' @export #' @rdname page_rank page_rank_old <- page_rank_old igraph/R/plot.shapes.R0000644000175100001440000010321213240142531014320 0ustar hornikusers # IGraph R package # Copyright (C) 2003-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### ## API design ## ## A vertex shape is defined by two functions: the clipping function and ## the plotting function. ## ## The clipping function is called to determine where to put the ## arrowhead of a potential (incoming) incident edge. Its signature is ## function(coords, el, params, end=c("both", "from", "to")) ## where the arguments are: ## coords A matrix with one row for each edge, and four columns. ## It contains the coordinates of the end points of all ## edges. The first two columns are the coordinates of the ## first end points (sources, if the graph is directed), ## the last two columns are for the other end points ## (targets if the graph is directed). ## el The edge list itself, with vertex ids. ## params A function object to query plotting parameters. ## end Which end points to calculate. "both" means both, ## "from" means the first end point, "to" the second. ## The clipping function must return the new version of "coords", ## modified according to the vertex sizes/shapes, with proper positions ## for the potential arrow heads. The positions are for the tips of the ## arrows. ## ## The plotting function plots the vertex. Its signature is ## function(coords, v=NULL, params) ## where the arguments are ## coords Two column matrix, the coordinates for the vertices to draw. ## v The vertex ids of the vertices to draw. If NULL, then all ## vertices are drawn. ## params A function object to query plotting parameters. ## ## shapes() - lists all vertex shapes ## shapes(shape) - returns the clipping and plotting functions ## for a given vertex shape ## add_shape() - adds a new vertex shape, the clipping and ## plotting functions must be given, and ## optionally the newly introduced plotting ## parameters. This function can also be used ## to overwrite a given vertex shape. ## ## Examples: ## add_shape("image", clip=image.clip, plot=image.plot, ## parameters=list(filename=NA)) ## ## add_shape("triangle", clip=shapes("circle")$clip, ## plot=triangle.plot) ## ## add_shape("polygon", clip=shapes("circle")$clip, ## plot=polygon.plot) ## ################################################################### #' Various vertex shapes when plotting igraph graphs #' #' Starting from version 0.5.1 igraph supports different #' vertex shapes when plotting graphs. #' #' @details #' In igraph a vertex shape is defined by two functions: 1) provides #' information about the size of the shape for clipping the edges and 2) #' plots the shape if requested. These functions are called \dQuote{shape #' functions} in the rest of this manual page. The first one is the #' clipping function and the second is the plotting function. #' #' The clipping function has the following arguments: #' \describe{ #' \item{coords}{A matrix with four columns, it contains the #' coordinates of the vertices for the edge list supplied in the #' \code{el} argument.} #' \item{el}{A matrix with two columns, the edges of which some end #' points will be clipped. It should have the same number of rows as #' \code{coords}.} #' \item{params}{This is a function object that can be called to query #' vertex/edge/plot graphical parameters. The first argument of the #' function is \dQuote{\code{vertex}}, \dQuote{\code{edge}} or #' \dQuote{\code{plot}} to decide the type of the parameter, the #' second is a character string giving the name of the #' parameter. E.g. #' \preformatted{ #' params("vertex", "size") #' } #' } #' \item{end}{Character string, it gives which end points will be #' used. Possible values are \dQuote{\code{both}}, #' \dQuote{\code{from}} and \dQuote{\code{to}}. If #' \dQuote{\code{from}} the function is expected to clip the #' first column in the \code{el} edge list, \dQuote{\code{to}} #' selects the second column, \dQuote{\code{both}} selects both.} #' } #' #' The clipping function should return a matrix #' with the same number of rows as the \code{el} arguments. #' If \code{end} is \code{both} then the matrix must have four #' columns, otherwise two. The matrix contains the modified coordinates, #' with the clipping applied. #' #' The plotting function has the following arguments: #' \describe{ #' \item{coords}{The coordinates of the vertices, a matrix with two #' columns.} #' \item{v}{The ids of the vertices to plot. It should match the number #' of rows in the \code{coords} argument.} #' \item{params}{The same as for the clipping function, see above.} #' } #' #' The return value of the plotting function is not used. #' #' \code{shapes} can be used to list the names of all installed #' vertex shapes, by calling it without arguments, or setting the #' \code{shape} argument to \code{NULL}. If a shape name is given, then #' the clipping and plotting functions of that shape are returned in a #' named list. #' #' \code{add_shape} can be used to add new vertex shapes to #' igraph. For this one must give the clipping and plotting functions of #' the new shape. It is also possible to list the plot/vertex/edge #' parameters, in the \code{parameters} argument, that the clipping #' and/or plotting functions can make use of. An example would be a #' generic regular polygon shape, which can have a parameter for the #' number of sides. #' #' \code{shape_noclip} is a very simple clipping function that the #' user can use in their own shape definitions. It does no clipping, the #' edges will be drawn exactly until the listed vertex position #' coordinates. #' #' \code{shape_noplot} is a very simple (and probably not very #' useful) plotting function, that does not plot anything. #' #' @aliases add.vertex.shape igraph.shape.noclip igraph.shape.noplot #' vertex.shapes igraph.vertex.shapes #' #' @param shape Character scalar, name of a vertex shape. If it is #' \code{NULL} for \code{shapes}, then the names of all defined #' vertex shapes are returned. #' @param clip An R function object, the clipping function. #' @param plot An R function object, the plotting function. #' @param parameters Named list, additional plot/vertex/edge #' parameters. The element named define the new parameters, and the #' elements themselves define their default values. #' Vertex parameters should have a prefix #' \sQuote{\code{vertex.}}, edge parameters a prefix #' \sQuote{\code{edge.}}. Other general plotting parameters should have #' a prefix \sQuote{\code{plot.}}. See Details below. #' @param coords,el,params,end,v See parameters of the clipping/plotting #' functions below. #' @return \code{shapes} returns a character vector if the #' \code{shape} argument is \code{NULL}. It returns a named list with #' entries named \sQuote{clip} and \sQuote{plot}, both of them R #' functions. #' #' \code{add_shape} returns \code{TRUE}, invisibly. #' #' \code{shape_noclip} returns the appropriate columns of its #' \code{coords} argument. #' @export #' #' @examples #' # all vertex shapes, minus "raster", that might not be available #' shapes <- setdiff(shapes(), "") #' g <- make_ring(length(shapes)) #' set.seed(42) #' plot(g, vertex.shape=shapes, vertex.label=shapes, vertex.label.dist=1, #' vertex.size=15, vertex.size2=15, #' vertex.pie=lapply(shapes, function(x) if (x=="pie") 2:6 else 0), #' vertex.pie.color=list(heat.colors(5))) #' #' # add new vertex shape, plot nothing with no clipping #' add_shape("nil") #' plot(g, vertex.shape="nil") #' #' ################################################################# #' # triangle vertex shape #' mytriangle <- function(coords, v=NULL, params) { #' vertex.color <- params("vertex", "color") #' if (length(vertex.color) != 1 && !is.null(v)) { #' vertex.color <- vertex.color[v] #' } #' vertex.size <- 1/200 * params("vertex", "size") #' if (length(vertex.size) != 1 && !is.null(v)) { #' vertex.size <- vertex.size[v] #' } #' #' symbols(x=coords[,1], y=coords[,2], bg=vertex.color, #' stars=cbind(vertex.size, vertex.size, vertex.size), #' add=TRUE, inches=FALSE) #' } #' # clips as a circle #' add_shape("triangle", clip=shapes("circle")$clip, #' plot=mytriangle) #' plot(g, vertex.shape="triangle", vertex.color=rainbow(vcount(g)), #' vertex.size=seq(10,20,length=vcount(g))) #' #' ################################################################# #' # generic star vertex shape, with a parameter for number of rays #' mystar <- function(coords, v=NULL, params) { #' vertex.color <- params("vertex", "color") #' if (length(vertex.color) != 1 && !is.null(v)) { #' vertex.color <- vertex.color[v] #' } #' vertex.size <- 1/200 * params("vertex", "size") #' if (length(vertex.size) != 1 && !is.null(v)) { #' vertex.size <- vertex.size[v] #' } #' norays <- params("vertex", "norays") #' if (length(norays) != 1 && !is.null(v)) { #' norays <- norays[v] #' } #' #' mapply(coords[,1], coords[,2], vertex.color, vertex.size, norays, #' FUN=function(x, y, bg, size, nor) { #' symbols(x=x, y=y, bg=bg, #' stars=matrix(c(size,size/2), nrow=1, ncol=nor*2), #' add=TRUE, inches=FALSE) #' }) #' } #' # no clipping, edges will be below the vertices anyway #' add_shape("star", clip=shape_noclip, #' plot=mystar, parameters=list(vertex.norays=5)) #' plot(g, vertex.shape="star", vertex.color=rainbow(vcount(g)), #' vertex.size=seq(10,20,length=vcount(g))) #' plot(g, vertex.shape="star", vertex.color=rainbow(vcount(g)), #' vertex.size=seq(10,20,length=vcount(g)), #' vertex.norays=rep(4:8, length=vcount(g))) #' #' ################################################################# #' # Pictures as vertices. #' # Similar musicians from last.fm, we start from an artist and #' # will query two levels. We will use the XML, png and jpeg packages #' # for this, so these must be available. Otherwise the example is #' # skipped #' #' loadIfYouCan <- function(pkg) suppressWarnings(do.call(require, list(pkg))) #' #' if (loadIfYouCan("XML") && loadIfYouCan("png") && #' loadIfYouCan("jpeg")) { #' url <- paste(sep="", #' 'http://ws.audioscrobbler.com/', #' '2.0/?method=artist.getinfo&artist=%s', #' '&api_key=1784468ada3f544faf9172ee8b99fca3') #' getartist <- function(artist) { #' cat("Downloading from last.fm. ... ") #' txt <- readLines(sprintf(url, URLencode(artist))) #' xml <- xmlTreeParse(txt, useInternal=TRUE) #' img <- xpathSApply(xml, "/lfm/artist/image[@@size='medium'][1]", #' xmlValue) #' if (img != "") { #' con <- url(img, open="rb") #' bin <- readBin(con, what="raw", n=10^6) #' close(con) #' if (grepl("\\\\.png$", img)) { #' rast <- readPNG(bin, native=TRUE) #' } else if (grepl("\\\\.jpe?g$", img)) { #' rast <- readJPEG(bin, native=TRUE) #' } else { #' rast <- as.raster(matrix()) #' } #' } else { #' rast <- as.raster(numeric()) #' } #' sim <- xpathSApply(xml, "/lfm/artist/similar/artist/name", xmlValue) #' cat("done.\\n") #' list(name=artist, image=rast, similar=sim) #' } #' #' ego <- getartist("Placebo") #' similar <- lapply(ego$similar, getartist) #' #' edges1 <- cbind(ego$name, ego$similar) #' edges2 <- lapply(similar, function(x) cbind(x$name, x$similar)) #' edges3 <- rbind(edges1, do.call(rbind, edges2)) #' edges <- edges3[ edges3[,1] %in% c(ego$name, ego$similar) & #' edges3[,2] %in% c(ego$name, ego$similar), ] #' #' musnet <- simplify(graph_from_data_frame(edges, dir=FALSE, #' vertices=data.frame(name=c(ego$name, ego$similar)))) #' print_all(musnet) #' #' V(musnet)$raster <- c(list(ego$image), lapply(similar, "[[", "image")) #' plot(musnet, layout=layout_as_star, vertex.shape="raster", #' vertex.label=V(musnet)$name, margin=.2, #' vertex.size=50, vertex.size2=50, #' vertex.label.dist=2, vertex.label.degree=0) #' } else { #' message("You need the `XML', `png' and `jpeg' packages to run this") #' } shapes <- function(shape=NULL) { if (is.null(shape)) { ls(.igraph.shapes) } else { ## checkScalarString(shape) .igraph.shapes[[shape]] } } #' @rdname shapes #' @export shape_noclip <- function(coords, el, params, end=c("both", "from", "to")) { end <- igraph.match.arg(end) if (end=="both") { coords } else if (end=="from") { coords[,1:2,drop=FALSE] } else { coords[,3:4,drop=FALSE] } } #' @rdname shapes #' @export shape_noplot <- function(coords, v=NULL, params) { invisible(NULL) } #' @rdname shapes #' @export add_shape <- function(shape, clip=shape_noclip, plot=shape_noplot, parameters=list()) { ## TODO ## checkScalarString(shape) ## checkFunction(clip) ## checkFunction(plot) ## checkList(parameters, named=TRUE) assign(shape, value=list(clip=clip, plot=plot), envir=.igraph.shapes) do.call(igraph.options, parameters) invisible(TRUE) } ## These are the predefined shapes .igraph.shape.circle.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") if (end=="from") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) vsize.from <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } res <- cbind(coords[,1] + vsize.from*cos(phi), coords[,2] + vsize.from*sin(phi) ) } else if (end=="to") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) r <- sqrt( (coords[,3] - coords[,1])^2 + (coords[,4] - coords[,2])^2 ) vsize.to <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- cbind(coords[,1] + (r-vsize.to)*cos(phi), coords[,2] + (r-vsize.to)*sin(phi) ) } else if (end=="both") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) r <- sqrt( (coords[,3] - coords[,1])^2 + (coords[,4] - coords[,2])^2 ) vsize.from <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } vsize.to <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- cbind(coords[,1] + vsize.from*cos(phi), coords[,2] + vsize.from*sin(phi), coords[,1] + (r-vsize.to)*cos(phi), coords[,2] + (r-vsize.to)*sin(phi) ) } res } #' @importFrom graphics symbols .igraph.shape.circle.plot <- function(coords, v=NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.frame.color <- params("vertex", "frame.color") if (length(vertex.frame.color) != 1 && !is.null(v)) { vertex.frame.color <- vertex.frame.color[v] } vertex.size <- 1/200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } vertex.size <- rep(vertex.size, length=nrow(coords)) symbols(x=coords[,1], y=coords[,2], bg=vertex.color, fg=vertex.frame.color, circles=vertex.size, add=TRUE, inches=FALSE) } .igraph.shape.square.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") square.shift <- function(x0, y0, x1, y1, vsize) { m <- (y0-y1)/(x0-x1) l <- cbind(x1-vsize/m , y1-vsize, x1-vsize , y1-vsize*m, x1+vsize/m, y1+vsize, x1+vsize , y1+vsize*m ) v <- cbind(x1-vsize <= l[,1] & l[,1] <= x1+vsize & y1-vsize <= l[,2] & l[,2] <= y1+vsize, x1-vsize <= l[,3] & l[,3] <= x1+vsize & y1-vsize <= l[,4] & l[,4] <= y1+vsize, x1-vsize <= l[,5] & l[,5] <= x1+vsize & y1-vsize <= l[,6] & l[,6] <= y1+vsize, x1-vsize <= l[,7] & l[,7] <= x1+vsize & y1-vsize <= l[,8] & l[,8] <= y1+vsize) d <- cbind((l[,1]-x0)^2 + (l[,2]-y0)^2, (l[,3]-x0)^2 + (l[,4]-y0)^2, (l[,5]-x0)^2 + (l[,6]-y0)^2, (l[,7]-x0)^2 + (l[,8]-y0)^2) t(sapply(seq(length=nrow(l)), function(x) { d[x,][!v[x,]] <- Inf m <- which.min(d[x,]) l[x, c(m*2-1, m*2)] })) } if (end %in% c("from", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } res <- res1 <- square.shift(coords[,3], coords[,4], coords[,1], coords[,2], vsize) } if (end %in% c("to", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- res2 <- square.shift(coords[,1], coords[,2], coords[,3], coords[,4], vsize) } if (end=="both") { res <- cbind(res1, res2) } res } #' @importFrom graphics symbols .igraph.shape.square.plot <- function(coords, v=NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.frame.color <- params("vertex", "frame.color") if (length(vertex.frame.color) != 1 && !is.null(v)) { vertex.frame.color <- vertex.frame.color[v] } vertex.size <- 1/200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } vertex.size <- rep(vertex.size, length=nrow(coords)) symbols(x=coords[,1], y=coords[,2], bg=vertex.color, fg=vertex.frame.color, squares=2*vertex.size, add=TRUE, inches=FALSE) } .igraph.shape.csquare.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") square.shift <- function(x0, y0, x1, y1, vsize) { l <- cbind(x1, y1-vsize, x1-vsize, y1, x1, y1+vsize, x1+vsize, y1) d <- cbind((l[,1]-x0)^2 + (l[,2]-y0)^2, (l[,3]-x0)^2 + (l[,4]-y0)^2, (l[,5]-x0)^2 + (l[,6]-y0)^2, (l[,7]-x0)^2 + (l[,8]-y0)^2) t(sapply(seq(length=nrow(l)), function(x) { m <- which.min(d[x,]) l[x, c(m*2-1, m*2)] })) } if (end %in% c("from", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } res <- res1 <- square.shift(coords[,3], coords[,4], coords[,1], coords[,2], vsize) } if (end %in% c("to", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- res2 <- square.shift(coords[,1], coords[,2], coords[,3], coords[,4], vsize) } if (end=="both") { res <- cbind(res1, res2) } res } .igraph.shape.csquare.plot <- .igraph.shape.square.plot .igraph.shape.rectangle.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") vertex.size2 <- 1/200 * params("vertex", "size2") rec.shift <- function(x0, y0, x1, y1, vsize, vsize2) { m <- (y0-y1)/(x0-x1) l <- cbind(x1-vsize/m, y1-vsize2, x1-vsize, y1-vsize*m, x1+vsize2/m, y1+vsize2, x1+vsize, y1+vsize*m ) v <- cbind(x1-vsize <= l[,1] & l[,1] <= x1+vsize & y1-vsize2 <= l[,2] & l[,2] <= y1+vsize2, x1-vsize <= l[,3] & l[,3] <= x1+vsize & y1-vsize2 <= l[,4] & l[,4] <= y1+vsize2, x1-vsize <= l[,5] & l[,5] <= x1+vsize & y1-vsize2 <= l[,6] & l[,6] <= y1+vsize2, x1-vsize <= l[,7] & l[,7] <= x1+vsize & y1-vsize2 <= l[,8] & l[,8] <= y1+vsize2) d <- cbind((l[,1]-x0)^2 + (l[,2]-y0)^2, (l[,3]-x0)^2 + (l[,4]-y0)^2, (l[,5]-x0)^2 + (l[,6]-y0)^2, (l[,7]-x0)^2 + (l[,8]-y0)^2) t(sapply(seq(length=nrow(l)), function(x) { d[x,][!v[x,]] <- Inf m <- which.min(d[x,]) l[x, c(m*2-1, m*2)] })) } if (end %in% c("from", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,1] ] } res <- res1 <- rec.shift(coords[,3], coords[,4], coords[,1], coords[,2], vsize, vsize2) } if (end %in% c("to", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,2] ] } res <- res2 <- rec.shift(coords[,1], coords[,2], coords[,3], coords[,4], vsize, vsize2) } if (end=="both") { res <- cbind(res1, res2) } res } #' @importFrom graphics symbols .igraph.shape.rectangle.plot <- function(coords, v=NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.frame.color <- params("vertex", "frame.color") if (length(vertex.frame.color) != 1 && !is.null(v)) { vertex.frame.color <- vertex.frame.color[v] } vertex.size <- 1/200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } vertex.size <- rep(vertex.size, length=nrow(coords)) vertex.size2 <- 1/200 * params("vertex", "size2") if (length(vertex.size2) != 1 && !is.null(v)) { vertex.size2 <- vertex.size2[v] } vertex.size <- cbind(vertex.size, vertex.size2) symbols(x=coords[,1], y=coords[,2], bg=vertex.color, fg=vertex.frame.color, rectangles=2*vertex.size, add=TRUE, inches=FALSE) } .igraph.shape.crectangle.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") vertex.size2 <- 1/200 * params("vertex", "size2") rec.shift <- function(x0, y0, x1, y1, vsize, vsize2) { l <- cbind(x1, y1-vsize2, x1-vsize, y1, x1, y1+vsize2, x1+vsize, y1) d <- cbind((l[,1]-x0)^2 + (l[,2]-y0)^2, (l[,3]-x0)^2 + (l[,4]-y0)^2, (l[,5]-x0)^2 + (l[,6]-y0)^2, (l[,7]-x0)^2 + (l[,8]-y0)^2) t(sapply(seq(length=nrow(l)), function(x) { m <- which.min(d[x,]) l[x, c(m*2-1, m*2)] })) } if (end %in% c("from", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,1] ] } res <- res1 <- rec.shift(coords[,3], coords[,4], coords[,1], coords[,2], vsize, vsize2) } if (end %in% c("to", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,2] ] } res <- res2 <- rec.shift(coords[,1], coords[,2], coords[,3], coords[,4], vsize, vsize2) } if (end=="both") { res <- cbind(res1, res2) } res } .igraph.shape.crectangle.plot <- .igraph.shape.rectangle.plot .igraph.shape.vrectangle.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") vertex.size2 <- 1/200 * params("vertex", "size2") rec.shift <- function(x0, y0, x1, y1, vsize, vsize2) { l <- cbind(x1-vsize, y1, x1+vsize, y1) d <- cbind((l[,1]-x0)^2 + (l[,2]-y0)^2, (l[,3]-x0)^2 + (l[,4]-y0)^2) t(sapply(seq(length=nrow(l)), function(x) { m <- which.min(d[x,]) l[x, c(m*2-1, m*2)] })) } if (end %in% c("from", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,1] ] } res <- res1 <- rec.shift(coords[,3], coords[,4], coords[,1], coords[,2], vsize, vsize2) } if (end %in% c("to", "both")) { vsize <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } vsize2 <- if (length(vertex.size2)==1) { vertex.size2 } else { vertex.size2[ el[,2] ] } res <- res2 <- rec.shift(coords[,1], coords[,2], coords[,3], coords[,4], vsize, vsize2) } if (end=="both") { res <- cbind(res1, res2) } res } .igraph.shape.vrectangle.plot <- .igraph.shape.rectangle.plot .igraph.shape.none.clip <- .igraph.shape.circle.clip .igraph.shape.none.plot <- function(coords, v=NULL, params) { ## does not plot anything at all invisible(NULL) } #' @importFrom graphics par polygon mypie <- function(x, y, values, radius, edges=200, col=NULL, angle=45, density=NULL, border=NULL, lty=NULL, init.angle=90, ...) { values <- c(0, cumsum(values)/sum(values)) dx <- diff(values) nx <- length(dx) twopi <- 2 * pi if (is.null(col)) col <- if (is.null(density)) c("white", "lightblue", "mistyrose", "lightcyan", "lavender", "cornsilk") else par("fg") col <- rep(col, length.out = nx) border <- rep(border, length.out = nx) lty <- rep(lty, length.out = nx) angle <- rep(angle, length.out = nx) density <- rep(density, length.out = nx) t2xy <- function(t) { t2p <- twopi * t + init.angle * pi/180 list(x = radius * cos(t2p), y = radius * sin(t2p)) } for (i in 1:nx) { n <- max(2, floor(edges * dx[i])) P <- t2xy(seq.int(values[i], values[i + 1], length.out = n)) polygon(x+c(P$x, 0), y+c(P$y, 0), density = density[i], angle = angle[i], border = border[i], col = col[i], lty = lty[i], ...) } } .igraph.shape.pie.clip <- function(coords, el, params, end=c("both", "from", "to")) { end <- match.arg(end) if (length(coords)==0) { return (coords) } vertex.size <- 1/200 * params("vertex", "size") if (end=="from") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) vsize.from <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } res <- cbind(coords[,1] + vsize.from*cos(phi), coords[,2] + vsize.from*sin(phi) ) } else if (end=="to") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) r <- sqrt( (coords[,3] - coords[,1])^2 + (coords[,4] - coords[,2])^2 ) vsize.to <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- cbind(coords[,1] + (r-vsize.to)*cos(phi), coords[,2] + (r-vsize.to)*sin(phi) ) } else if (end=="both") { phi <- atan2(coords[,4] - coords[,2], coords[,3] - coords[,1]) r <- sqrt( (coords[,3] - coords[,1])^2 + (coords[,4] - coords[,2])^2 ) vsize.from <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,1] ] } vsize.to <- if (length(vertex.size)==1) { vertex.size } else { vertex.size[ el[,2] ] } res <- cbind(coords[,1] + vsize.from*cos(phi), coords[,2] + vsize.from*sin(phi), coords[,1] + (r-vsize.to)*cos(phi), coords[,2] + (r-vsize.to)*sin(phi) ) } res } #' @importFrom stats na.omit .igraph.shape.pie.plot <- function(coords, v=NULL, params) { getparam <- function(pname) { p <- params("vertex", pname) if (length(p) != 1 && !is.null(v)) { p <- p[v] } p } vertex.color <- getparam("color") vertex.frame.color <- getparam("frame.color") vertex.size <- rep(1/200 * getparam("size"), length=nrow(coords)) vertex.pie <- getparam("pie") vertex.pie.color <- getparam("pie.color") vertex.pie.angle <- getparam("pie.angle") vertex.pie.density <- getparam("pie.density") vertex.pie.lty <- getparam("pie.lty") for (i in seq_len(nrow(coords))) { pie <- if(length(vertex.pie)==1) { vertex.pie[[1]] } else { vertex.pie[[i]] } col <- if (length(vertex.pie.color)==1) { vertex.pie.color[[1]] } else { vertex.pie.color[[i]] } mypie(x=coords[i,1], y=coords[i,2], pie, radius=vertex.size[i], edges=200, col=col, angle=na.omit(vertex.pie.angle[c(i,1)])[1], density=na.omit(vertex.pie.density[c(i,1)])[1], border=na.omit(vertex.frame.color[c(i,1)])[1], lty=na.omit(vertex.pie.lty[c(i,1)])[1]) } } .igraph.shape.sphere.clip <- .igraph.shape.circle.clip #' @importFrom graphics rasterImage #' @importFrom grDevices col2rgb as.raster .igraph.shape.sphere.plot <- function(coords, v=NULL, params) { getparam <- function(pname) { p <- params("vertex", pname) if (length(p) != 1 && !is.null(v)) { p <- p[v] } p } vertex.color <- rep(getparam("color"), length=nrow(coords)) vertex.size <- rep(1/200 * getparam("size"), length=nrow(coords)) ## Need to create a separate image for every different vertex color allcols <- unique(vertex.color) images <- lapply(allcols, function(col) { img <- .Call(C_R_igraph_getsphere, pos=c(0.0,0.0,10.0), radius=7.0, color=col2rgb(col)/255, bgcolor=c(0,0,0), lightpos=list(c(-2,2,2)), lightcolor=list(c(1,1,1)), width=100L, height=100L) as.raster(img) }) whichImage <- match(vertex.color, allcols) for (i in seq_len(nrow(coords))) { vsp2 <- vertex.size[i] rasterImage(images[[ whichImage[i] ]], coords[i,1]-vsp2, coords[i,2]-vsp2, coords[i,1]+vsp2, coords[i,2]+vsp2) } } .igraph.shape.raster.clip <- .igraph.shape.rectangle.clip #' @importFrom graphics rasterImage .igraph.shape.raster.plot <- function(coords, v=NULL, params) { getparam <- function(pname) { p <- params("vertex", pname) if (is.list(p) && length(p) != 1 && !is.null(v)) { p <- p[v] } p } size <- rep(1/200 * getparam("size"), length=nrow(coords)) size2 <- rep(1/200 * getparam("size2"), length=nrow(coords)) raster <- getparam("raster") for (i in seq_len(nrow(coords))) { ras <- if (!is.list(raster) || length(raster)==1) raster else raster[[i]] rasterImage(ras, coords[i,1]-size[i], coords[i,2]-size2[i], coords[i,1]+size[i], coords[i,2]+size2[i]) } } .igraph.shapes <- new.env() .igraph.shapes[["circle"]] <- list(clip=.igraph.shape.circle.clip, plot=.igraph.shape.circle.plot) .igraph.shapes[["square"]] <- list(clip=.igraph.shape.square.clip, plot=.igraph.shape.square.plot) .igraph.shapes[["csquare"]] <- list(clip=.igraph.shape.csquare.clip, plot=.igraph.shape.csquare.plot) .igraph.shapes[["rectangle"]] <- list(clip=.igraph.shape.rectangle.clip, plot=.igraph.shape.rectangle.plot) .igraph.shapes[["crectangle"]] <- list(clip=.igraph.shape.crectangle.clip, plot=.igraph.shape.crectangle.plot) .igraph.shapes[["vrectangle"]] <- list(clip=.igraph.shape.vrectangle.clip, plot=.igraph.shape.vrectangle.plot) .igraph.shapes[["none"]] <- list(clip=.igraph.shape.none.clip, plot=.igraph.shape.none.plot) .igraph.shapes[["pie"]] <- list(clip=.igraph.shape.pie.clip, plot=.igraph.shape.pie.plot) .igraph.shapes[["sphere"]] <- list(clip=.igraph.shape.sphere.clip, plot=.igraph.shape.sphere.plot) .igraph.shapes[["raster"]] <- list(clip=.igraph.shape.raster.clip, plot=.igraph.shape.raster.plot) igraph/R/uuid.R0000644000175100001440000000034713177712334013050 0ustar hornikusers generate_uuid <- function(use_time = NA) { .Call(C_UUID_gen, as.logical(use_time)) } get_graph_id <- function(graph) { if (!warn_version(graph)) { .Call(C_R_igraph_get_graph_id, graph) } else { NA_character_ } } igraph/R/hrg.R0000644000175100001440000010013513177712334012656 0ustar hornikusers# IGraph R package # Copyright (C) 2011-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Hierarchical random graphs #' #' Fitting and sampling hierarchical random graph models. #' #' A hierarchical random graph is an ensemble of undirected graphs with \eqn{n} #' vertices. It is defined via a binary tree with \eqn{n} leaf and \eqn{n-1} #' internal vertices, where the internal vertices are labeled with #' probabilities. The probability that two vertices are connected in the #' random graph is given by the probability label at their closest common #' ancestor. #' #' Please see references below for more about hierarchical random graphs. #' #' igraph contains functions for fitting HRG models to a given network #' (\code{fit_hrg}, for generating networks from a given HRG ensemble #' (\code{sample_hrg}), converting an igraph graph to a HRG and back #' (\code{hrg}, \code{hrg_tree}), for calculating a consensus tree from a set #' of sampled HRGs (\code{consensus_tree}) and for predicting missing edges in #' a network based on its HRG models (\code{predict_edges}). #' #' The igraph HRG implementation is heavily based on the code published by #' Aaron Clauset, at his website (not functional any more). #' #' @name hrg-methods #' @family hierarchical random graph functions NULL #' Fit a hierarchical random graph model #' #' \code{fit_hrg} fits a HRG to a given graph. It takes the specified #' \code{steps} number of MCMC steps to perform the fitting, or a convergence #' criteria if the specified number of steps is zero. \code{fit_hrg} can start #' from a given HRG, if this is given in the \code{hrg} argument and the #' \code{start} argument is \code{TRUE}. #' #' @aliases hrg.fit #' @param graph The graph to fit the model to. Edge directions are ignored in #' directed graphs. #' @param hrg A hierarchical random graph model, in the form of an #' \code{igraphHRG} object. \code{fit_hrg} allows this to be \code{NULL}, in #' which case a random starting point is used for the fitting. #' @param start Logical, whether to start the fitting/sampling from the #' supplied \code{igraphHRG} object, or from a random starting point. #' @param steps The number of MCMC steps to make. If this is zero, then the #' MCMC procedure is performed until convergence. #' @return \code{fit_hrg} returns an \code{igraphHRG} object. This is a list #' with the following members: #' \item{left}{Vector that contains the left children of the internal #' tree vertices. The first vertex is always the root vertex, so the #' first element of the vector is the left child of the root #' vertex. Internal vertices are denoted with negative numbers, starting #' from -1 and going down, i.e. the root vertex is -1. Leaf vertices #' are denoted by non-negative number, starting from zero and up.} #' \item{right}{Vector that contains the right children of the vertices, #' with the same encoding as the \code{left} vector.} #' \item{prob}{The connection probabilities attached to the internal #' vertices, the first number belongs to the root vertex (i.e. internal #' vertex -1), the second to internal vertex -2, etc.} #' \item{edges}{The number of edges in the subtree below the given #' internal vertex.} #' \item{vertices}{The number of vertices in the subtree below the #' given internal vertex, including itself.} #' @references A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure #' and the prediction of missing links in networks. \emph{Nature} 453, 98--101 #' (2008); #' #' A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies #' in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, \emph{Lecture #' Notes in Computer Science} 4503, 1--13. Springer-Verlag, Berlin Heidelberg #' (2007). #' @examples #' ## We are not running these examples any more, because they #' ## take a long time (~15 seconds) to run and this is against the CRAN #' ## repository policy. Copy and paste them by hand to your R prompt if #' ## you want to run them. #' #' \dontrun{ #' ## A graph with two dense groups #' g <- sample_gnp(10, p=1/2) + sample_gnp(10, p=1/2) #' hrg <- fit_hrg(g) #' hrg #' #' ## The consensus tree for it #' consensus_tree(g, hrg=hrg, start=TRUE) #' #' ## Prediction of missing edges #' g2 <- make_full_graph(4) + (make_full_graph(4) - path(1,2)) #' predict_edges(g2) #' } #' @export #' @family hierarchical random graph functions fit_hrg <- function(graph, hrg=NULL, start=FALSE, steps=0) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(hrg)) { hrg <- list(left=c(), right=c(), prob=c(), edges=c(), vertices=c()) } hrg <- lapply(hrg[c("left","right","prob","edges","vertices")], as.numeric) start <- as.logical(start) steps <- as.integer(steps) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_fit, graph, hrg, start, steps) if (igraph_opt("add.vertex.names") && is_named(graph)) { res$names <- V(graph)$name } class(res) <- "igraphHRG" res } #' Create a consensus tree from several hierarchical random graph models #' #' \code{consensus_tree} creates a consensus tree from several fitted #' hierarchical random graph models, using phylogeny methods. If the \code{hrg} #' argument is given and \code{start} is set to \code{TRUE}, then it starts #' sampling from the given HRG. Otherwise it optimizes the HRG log-likelihood #' first, and then samples starting from the optimum. #' #' @aliases hrg.consensus #' @param graph The graph the models were fitted to. #' @param hrg A hierarchical random graph model, in the form of an #' \code{igraphHRG} object. \code{consensus_tree} allows this to be #' \code{NULL} as well, then a HRG is fitted to the graph first, from a #' random starting point. #' @param start Logical, whether to start the fitting/sampling from the #' supplied \code{igraphHRG} object, or from a random starting point. #' @param num.samples Number of samples to use for consensus generation or #' missing edge prediction. #' @return \code{consensus_tree} returns a list of two objects. The first #' is an \code{igraphHRGConsensus} object, the second is an #' \code{igraphHRG} object. The \code{igraphHRGConsensus} object has the #' following members: #' \item{parents}{For each vertex, the id of its parent vertex is stored, #' or zero, if the vertex is the root vertex in the tree. The first n #' vertex ids (from 0) refer to the original vertices of the graph, the #' other ids refer to vertex groups.} #' \item{weights}{Numeric vector, counts the number of times a given tree #' split occured in the generated network samples, for each internal #' vertices. The order is the same as in the \code{parents} vector.} #' @include auto.R #' @family hierarchical random graph functions #' @export consensus_tree <- consensus_tree #' Create a hierarchical random graph from an igraph graph #' #' \code{hrg} creates a HRG from an igraph graph. The igraph graph must be #' a directed binary tree, with \eqn{n-1} internal and \eqn{n} leaf #' vertices. The \code{prob} argument contains the HRG probability labels #' for each vertex; these are ignored for leaf vertices. #' #' @aliases hrg.create #' @param graph The igraph graph to create the HRG from. #' @param prob A vector of probabilities, one for each vertex, in the order of #' vertex ids. #' @return \code{hrg} returns an \code{igraphHRG} object. #' #' @family hierarchical random graph functions #' @export hrg <- hrg #' Create an igraph graph from a hierarchical random graph model #' #' \code{hrg_tree} creates the corresponsing igraph tree of a hierarchical #' random graph model. #' #' @param hrg A hierarchical random graph model. #' @return An igraph graph. #' #' @family hierarchical random graph functions #' @export hrg_tree <- hrg_tree #' Sample from a hierarchical random graph model #' #' \code{sample_hrg} samples a graph from a given hierarchical random graph #' model. #' #' @aliases hrg.game #' @param hrg A hierarchical random graph model. #' @return An igraph graph. #' #' @family hierarchical random graph functions #' @export sample_hrg <- sample_hrg #' Predict edges based on a hierarchical random graph model #' #' \code{predict_edges} uses a hierarchical random graph model to predict #' missing edges from a network. This is done by sampling hierarchical models #' around the optimum model, proportionally to their likelihood. The MCMC #' sampling is stated from \code{hrg}, if it is given and the \code{start} #' argument is set to \code{TRUE}. Otherwise a HRG is fitted to the graph #' first. #' #' @aliases hrg.predict #' @param graph The graph to fit the model to. Edge directions are ignored in #' directed graphs. #' @param hrg A hierarchical random graph model, in the form of an #' \code{igraphHRG} object. \code{predict_edges}s allow this to be #' \code{NULL} as well, then a HRG is fitted to the graph first, from a #' random starting point. #' @param start Logical, whether to start the fitting/sampling from the #' supplied \code{igraphHRG} object, or from a random starting point. #' @param num.samples Number of samples to use for consensus generation or #' missing edge prediction. #' @param num.bins Number of bins for the edge probabilities. Give a higher #' number for a more accurate prediction. #' @return A list with entries: #' \item{edges}{The predicted edges, in a two-column matrix of vertex #' ids.} #' \item{prob}{Probabilities of these edges, according to the fitted #' model.} #' \item{hrg}{The (supplied or fitted) hierarchical random graph model.} #' #' @references A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure #' and the prediction of missing links in networks. \emph{Nature} 453, 98--101 #' (2008); #' #' A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies #' in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, \emph{Lecture #' Notes in Computer Science} 4503, 1--13. Springer-Verlag, Berlin Heidelberg #' (2007). #' @examples #' ## We are not running these examples any more, because they #' ## take a long time (~15 seconds) to run and this is against the CRAN #' ## repository policy. Copy and paste them by hand to your R prompt if #' ## you want to run them. #' #' \dontrun{ #' ## A graph with two dense groups #' g <- sample_gnp(10, p=1/2) + sample_gnp(10, p=1/2) #' hrg <- fit_hrg(g) #' hrg #' #' ## The consensus tree for it #' consensus_tree(g, hrg=hrg, start=TRUE) #' #' ## Prediction of missing edges #' g2 <- make_full_graph(4) + (make_full_graph(4) - path(1,2)) #' predict_edges(g2) #' } #' @export #' @family hierarchical random graph functions predict_edges <- function(graph, hrg=NULL, start=FALSE, num.samples=10000, num.bins=25) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(hrg)) { hrg <- list(left=c(), right=c(), prob=c(), edges=c(), vertices=c()) } hrg <- lapply(hrg[c("left","right","prob","edges","vertices")], as.numeric) start <- as.logical(start) num.samples <- as.integer(num.samples) num.bins <- as.integer(num.bins) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_hrg_predict, graph, hrg, start, num.samples, num.bins) res$edges <- matrix(res$edges, ncol=2, byrow=TRUE) class(res$hrg) <- "igraphHRG" res } #' Conversion to igraph #' #' These fucntions convert various objects to igraph graphs. #' #' You can use \code{as.igraph} to convert various objects to igraph graphs. #' Right now the following objects are supported: \itemize{ \item codeigraphHRG #' These objects are created by the \code{\link{fit_hrg}} and #' \code{\link{consensus_tree}} functions. } #' #' @aliases as.igraph as.igraph.igraphHRG #' @param x The object to convert. #' @param \dots Additional arguments. None currently. #' @return All these functions return an igraph graph. #' @export #' @author Gabor Csardi \email{csardi.gabor@@gmail.com}. #' @keywords graphs #' @examples #' #' g <- make_full_graph(5) + make_full_graph(5) #' hrg <- fit_hrg(g) #' as.igraph(hrg) #' as.igraph <- function(x, ...) UseMethod("as.igraph") #' @method as.igraph igraphHRG #' @export as.igraph.igraphHRG <- function(x, ...) { ovc <- length(x$left)+1L ivc <- ovc-1L ll <- ifelse(x$left < 0, -x$left + ovc, x$left + 1) rr <- ifelse(x$right < 0, -x$right + ovc, x$right + 1) edges <- c(rbind(seq_len(ivc)+ovc, ll), rbind(seq_len(ivc)+ovc, rr)) res <- graph(edges) V(res)$name <- c(if (!is.null(x$names)) x$names else as.character(1:ovc), paste0("g", 1:ivc)) V(res)$prob <- c(rep(NA, ovc), x$prob) res$name <- "Fitted HRG" res } buildMerges <- function(object) { ## Build a merge matrix. This is done by a post-order ## traversal of the tree. S <- numeric() vcount <- length(object$left)+1 nMerge <- vcount-1 merges <- matrix(0, nrow=vcount-1, ncol=3) mptr <- 1 S[length(S)+1] <- -1 prev <- NULL while (length(S) != 0) { curr <- S[length(S)] ## coming from parent? going left if possible. if (is.null(prev) || (prev < 0 && object$left[-prev] == curr) || (prev < 0 && object$right[-prev] == curr)) { if (curr < 0) { S <- c(S, object$left[-curr]) } ## coming from left child? going right } else if (curr < 0 && object$left[-curr] == prev) { S <- c(S, object$right[-curr]) ## coming from right child? going up } else { if (curr < 0) { merges[mptr,] <- c(object$left[-curr], object$right[-curr], curr) mptr <- mptr + 1 } S <- S[-length(S)] } prev <- curr } merges } #' @method as.dendrogram igraphHRG as.dendrogram.igraphHRG <- function(object, hang=0.01, ...) { nMerge <- length(object$left) merges <- buildMerges(object) .memberDend <- function(x) { r <- attr(x,"x.member") if(is.null(r)) { r <- attr(x,"members") if(is.null(r)) r <- 1:1 } r } oHgt <- 1:nrow(merges) hMax <- oHgt[length(oHgt)] mynames <- if (is.null(object$names)) 1:(nMerge+1) else object$names z <- list() for (k in 1:nMerge) { x <- merges[k,1:2] if (any(neg <- x >= 0)) { h0 <- if (hang < 0) 0 else max(0, oHgt[k] - hang * hMax) } if (all(neg)) { # two leaves zk <- as.list(x+1) attr(zk, "members") <- 2L attr(zk, "midpoint") <- 1/2 # mean( c(0,1) ) objlabels <- mynames[x+1] attr(zk[[1]], "label") <- objlabels[1] attr(zk[[2]], "label") <- objlabels[2] attr(zk[[1]], "members") <- attr(zk[[2]], "members") <- 1L attr(zk[[1]], "height") <- attr(zk[[2]], "height") <- h0 attr(zk[[1]], "leaf") <- attr(zk[[2]], "leaf") <- TRUE } else if (any(neg)) { # one leaf, one node X <- paste0("g", -x) isL <- x[1] >= 0 zk <- if (isL) list(x[1]+1, z[[X[2]]]) else list(z[[X[1]]], x[2]+1) attr(zk, "members") <- attr(z[[X[1+isL]]], "members") + 1L attr(zk, "midpoint") <- (.memberDend(zk[[1]]) + attr(z[[X[1+isL]]], "midpoint"))/2 attr(zk[[2 - isL]], "members") <- 1L attr(zk[[2 - isL]], "height") <- h0 attr(zk[[2 - isL]], "label") <- mynames[x[2 - isL]+1] attr(zk[[2 - isL]], "leaf") <- TRUE } else { #two nodes X <- paste0("g", -x) zk <- list(z[[X[1]]], z[[X[2]]]) attr(zk, "members") <- attr(z[[X[1]]], "members") + attr(z[[X[2]]], "members") attr(zk, "midpoint") <- (attr(z[[X[1]]], "members") + attr(z[[X[1]]], "midpoint") + attr(z[[X[2]]], "midpoint"))/2 } attr(zk, "height") <- oHgt[k] z[[k <- paste0("g", -merges[k,3])]] <- zk } z <- z[[k]] class(z) <- "dendrogram" z } #' @importFrom stats as.hclust #' @method as.hclust igraphHRG as.hclust.igraphHRG <- function(x, ...) { merge3 <- buildMerges(x) ## We need to rewrite the merge matrix, because hclust assumes ## that group ids are assigned in the order of the merges map <- order(-merge3[,3]) merge <- merge3[,1:2] gs <- which(merge < 0) merge[ gs] <- map[ -merge[gs] ] merge[-gs] <- -merge[-gs]-1 ## To get the ordering, we need to recode the merge matrix again, ## without using group ids. Here the right node is merged _into_ ## the left node. map2 <- numeric(nrow(merge)) mergeInto <- merge for (i in 1:nrow(merge)) { mr <- mergeInto[i,] mr[mr > 0] <- -map2[mr[mr>0]] mergeInto[i,] <- -mr map2[i] <- -mr[1] } n <- nrow(merge)+1 hcass <- .C("igraphhcass2", n=as.integer(n), ia=as.integer(mergeInto[,1]), ib=as.integer(mergeInto[,2]), order=integer(n), iia=integer(n), iib=integer(n)) mynames <- if (is.null(x$names)) 1:n else x$names res <- list(merge=merge, height=1:nrow(merge), order=hcass$order, labels=mynames, method=NA_character_, dist.method=NA_character_) class(res) <- "hclust" res } #' @method as_phylo igraphHRG #' @importFrom stats reorder as_phylo.igraphHRG <- function(x, ...) { ovc <- length(x$left)+1L ivc <- ovc-1L ll <- ifelse(x$left < 0, -x$left + ovc, x$left + 1) rr <- ifelse(x$right < 0, -x$right + ovc, x$right + 1) edge <- matrix(rbind(seq_len(ivc)+ovc, ll, seq_len(ivc)+ovc, rr), ncol=2, byrow=TRUE) edge.length <- rep(0.5, nrow(edge)) labels <- if (is.null(x$names)) 1:ovc else x$names obj <- list(edge=edge, edge.length=edge.length/2, tip.label=labels, Nnode=ivc) class(obj) <- "phylo" reorder(obj) } #' HRG dendrogram plot #' #' Plot a hierarchical random graph as a dendrogram. #' #' \code{plot_dendrogram} supports three different plotting functions, selected via #' the \code{mode} argument. By default the plotting function is taken from the #' \code{dend.plot.type} igraph option, and it has for possible values: #' \itemize{ \item \code{auto} Choose automatically between the plotting #' functions. As \code{plot.phylo} is the most sophisticated, that is choosen, #' whenever the \code{ape} package is available. Otherwise \code{plot.hclust} #' is used. \item \code{phylo} Use \code{plot.phylo} from the \code{ape} #' package. \item \code{hclust} Use \code{plot.hclust} from the \code{stats} #' package. \item \code{dendrogram} Use \code{plot.dendrogram} from the #' \code{stats} package. } #' #' The different plotting functions take different sets of arguments. When #' using \code{plot.phylo} (\code{mode="phylo"}), we have the following syntax: #' \preformatted{ #' plot_dendrogram(x, mode="phylo", colbar = rainbow(11, start=0.7, #' end=0.1), edge.color = NULL, use.edge.length = FALSE, \dots) #' } The extra arguments not documented above: \itemize{ #' \item \code{colbar} Color bar for the edges. #' \item \code{edge.color} Edge colors. If \code{NULL}, then the #' \code{colbar} argument is used. #' \item \code{use.edge.length} Passed to \code{plot.phylo}. #' \item \code{dots} Attitional arguments to pass to \code{plot.phylo}. #' } #' #' The syntax for \code{plot.hclust} (\code{mode="hclust"}): \preformatted{ #' plot_dendrogram(x, mode="hclust", rect = 0, colbar = rainbow(rect), #' hang = 0.01, ann = FALSE, main = "", sub = "", xlab = "", #' ylab = "", \dots) #' } The extra arguments not documented above: \itemize{ #' \item \code{rect} A numeric scalar, the number of groups to mark on #' the dendrogram. The dendrogram is cut into exactly \code{rect} #' groups and they are marked via the \code{rect.hclust} command. Set #' this to zero if you don't want to mark any groups. #' \item \code{colbar} The colors of the rectanges that mark the #' vertex groups via the \code{rect} argument. #' \item \code{hang} Where to put the leaf nodes, this corresponds to the #' \code{hang} argument of \code{plot.hclust}. #' \item \code{ann} Whether to annotate the plot, the \code{ann} argument #' of \code{plot.hclust}. #' \item \code{main} The main title of the plot, the \code{main} argument #' of \code{plot.hclust}. #' \item \code{sub} The sub-title of the plot, the \code{sub} argument of #' \code{plot.hclust}. #' \item \code{xlab} The label on the horizontal axis, passed to #' \code{plot.hclust}. #' \item \code{ylab} The label on the vertical axis, passed to #' \code{plot.hclust}. #' \item \code{dots} Attitional arguments to pass to \code{plot.hclust}. #' } #' #' The syntax for \code{plot.dendrogram} (\code{mode="dendrogram"}): #' \preformatted{ #' plot_dendrogram(x, \dots) #' } The extra arguments are simply passed to \code{as.dendrogram}. #' #' @aliases hrg.dendrogram #' @param x An \code{igraphHRG}, a hierarchical random graph, as returned by #' the \code{\link{fit_hrg}} function. #' @param mode Which dendrogram plotting function to use. See details below. #' @param \dots Additional arguments to supply to the dendrogram plotting #' function. #' @return Returns whatever the return value was from the plotting function, #' \code{plot.phylo}, \code{plot.dendrogram} or \code{plot.hclust}. #' @method plot_dendrogram igraphHRG #' @export #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @examples #' #' g <- make_full_graph(5) + make_full_graph(5) #' hrg <- fit_hrg(g) #' plot_dendrogram(hrg) #' plot_dendrogram.igraphHRG <- function(x, mode=igraph_opt("dend.plot.type"), ...) { if (mode=="auto") { have_ape <- requireNamespace("ape", quietly = TRUE) mode <- if (have_ape) "phylo" else "hclust" } if (mode=="hclust") { hrgPlotHclust(x, ...) } else if (mode=="dendrogram") { hrgPlotDendrogram(x, ...) } else if (mode=="phylo") { hrgPlotPhylo(x, ...) } } #' @importFrom graphics plot #' @importFrom grDevices rainbow #' @importFrom stats rect.hclust hrgPlotHclust <- function(x, rect=0, colbar=rainbow(rect), hang=.01, ann=FALSE, main="", sub="", xlab="", ylab="", ...) { hc <- as.hclust(x) ret <- plot(hc, hang=hang, ann=ann, main=main, sub=sub, xlab=xlab, ylab=ylab, ...) if (rect > 0) { rect.hclust(hc, k=rect, border=colbar) } invisible(ret) } #' @importFrom graphics plot hrgPlotDendrogram <- function(x, ...) { plot(as.dendrogram(x), ...) } #' @importFrom graphics plot #' @importFrom grDevices rainbow hrgPlotPhylo <- function(x, colbar=rainbow(11, start=.7, end=.1), edge.color=NULL, use.edge.length=FALSE, ...) { vc <- length(x$left)+1 phy <- as_phylo(x) br <- seq(0,1,length=length(colbar)) ; br[1] <- -1 cc <- as.integer(cut(x$prob[phy$edge[,1] - vc], breaks=br)) if (is.null(edge.color)) { edge.color <- colbar[cc] } plot(phy, edge.color=edge.color, use.edge.length=use.edge.length, ...) } #' Print a hierarchical random graph model to the screen #' #' \code{igraphHRG} objects can be printed to the screen in two forms: as #' a tree or as a list, depending on the \code{type} argument of the #' print function. By default the \code{auto} type is used, which selects #' \code{tree} for small graphs and \code{simple} (=list) for bigger #' ones. The \code{tree} format looks like #' this: \preformatted{Hierarchical random graph, at level 3: #' g1 p= 0 #' '- g15 p=0.33 1 #' '- g13 p=0.88 6 3 9 4 2 10 7 5 8 #' '- g8 p= 0.5 #' '- g16 p= 0.2 20 14 17 19 11 15 16 13 #' '- g5 p= 0 12 18 } #' This is a graph with 20 vertices, and the #' top three levels of the fitted hierarchical random graph are #' printed. The root node of the HRG is always vertex group #1 #' (\sQuote{\code{g1}} in the the printout). Vertex pairs in the left #' subtree of \code{g1} connect to vertices in the right subtree with #' probability zero, according to the fitted model. \code{g1} has two #' subgroups, \code{g15} and \code{g8}. \code{g15} has a subgroup of a #' single vertex (vertex 1), and another larger subgroup that contains #' vertices 6, 3, etc. on lower levels, etc. #' The \code{plain} printing is simpler and faster to produce, but less #' visual: \preformatted{Hierarchical random graph: #' g1 p=0.0 -> g12 g10 g2 p=1.0 -> 7 10 g3 p=1.0 -> g18 14 #' g4 p=1.0 -> g17 15 g5 p=0.4 -> g15 17 g6 p=0.0 -> 1 4 #' g7 p=1.0 -> 11 16 g8 p=0.1 -> g9 3 g9 p=0.3 -> g11 g16 #' g10 p=0.2 -> g4 g5 g11 p=1.0 -> g6 5 g12 p=0.8 -> g8 8 #' g13 p=0.0 -> g14 9 g14 p=1.0 -> 2 6 g15 p=0.2 -> g19 18 #' g16 p=1.0 -> g13 g2 g17 p=0.5 -> g7 13 g18 p=1.0 -> 12 19 #' g19 p=0.7 -> g3 20} #' It lists the two subgroups of each internal node, in #' as many columns as the screen width allows. #' #' @param x \code{igraphHRG} object to print. #' @param type How to print the dendrogram, see details below. #' @param level The number of top levels to print from the dendrogram. #' @param ... Additional arguments, not used currently. #' @return The hierarchical random graph model itself, invisibly. #' #' @method print igraphHRG #' @export #' @family hierarchical random graph functions print.igraphHRG <- function(x, type=c("auto", "tree", "plain"), level=3, ...) { type <- igraph.match.arg(type) if (type=="auto") { type <- if (length(x$left <= 100)) "tree" else "plain" } if (type=="tree") { return(print1.igraphHRG(x, level=level, ...)) } else { return(print2.igraphHRG(x, ...)) } } print1.igraphHRG <- function(x, level=3, ...) { cat(sep="", "Hierarchical random graph, at level ", level, ":\n") ## Depth of printed top of the dendrogram .depth <- function(b, l) { l[2] <- max(l[2], nchar(format(x$prob[b], digits=2))) if (l[1]==level) { return(l) } if (x$left[b] < 0 && x$right[b] < 0) { l1 <- .depth(-x$left[b], c(l[1]+1, l[2])) l2 <- .depth(-x$right[b], c(l[1]+1, l[2])) return(pmax(l1,l2)) } if (x$left[b] < 0) { return(.depth(-x$left[b], c(l[1]+1, l[2]))) } if (x$right[b] < 0) { return(.depth(-x$right[b], c(l[1]+1, l[2]))) } return(l) } cs <- .depth(1, c(1, 0)) pw <- cs[2] cs <- cs[1] * 3 vw <- nchar(as.character(length(x$left)+1)) sp <- paste(collapse="", rep(" ", cs+pw+2+2)) nn <- if (is.null(x$names)) seq_len(length(x$left)+1) else x$names ## Function to collect all individual vertex children .children <- function(b) { res <- c() if (x$left[b] < 0) { res <- c(res, .children(-x$left[b])) } else { res <- c(x$left[b]+1, res) } if (x$right[b] < 0) { res <- c(res, .children(-x$right[b])) } else { res <- c(x$right[b]+1, res) } return(res) } ## Recursive printing .plot <- function(b, l, ind = "") { if (b != 1) { he <- format(paste(sep="", ind, "'- g", b), width=cs) ind <- paste(" ", ind) } else { he <- format(paste(sep="", ind, "g", b), width=cs) } ## whether to go left and/or right gol <- x$left[b] < 0 && l < level gor <- x$right[b] < 0 && l < level ## the children to print ch1 <- character() if (!gol && x$left[b] < 0) { ch1 <- c(ch1, paste(sep="", "g", -x$left[b])) } if (!gor && x$right[b] < 0) { ch1 <- c(ch1, paste(sep="", "g", -x$right[b])) } ch2 <- numeric() if (!gol) { if (x$left[b] < 0) { ch2 <- c(ch2, .children(-x$left[b])) } if (x$left[b] >= 0) { ch2 <- c(ch2, x$left[b] + 1) } } if (!gor) { if (x$right[b] < 0) { ch2 <- c(ch2, .children(-x$right[b])) } if (x$right[b] >= 0) { ch2 <- c(ch2, x$right[b] + 1) } } ## print this line ch2 <- as.character(nn[ch2]) lf <- gsub(" ", "x", format(ch2, width=vw), fixed=TRUE) lf <- paste(collapse=" ", lf) lf <- strwrap(lf, width=getOption("width") - cs - pw - 3 - 2) lf <- gsub("x", " ", lf, fixed=TRUE) if (length(lf) > 1) { lf <- c(lf[1], paste(sp, lf[-1])) lf <- paste(collapse="\n", lf) } op <- paste(sep="", format(he, width=cs), " p=", format(x$prob[b], digits=2, width=pw, justify="left"), " ", paste(collapse=" ", lf)) cat(op, fill=TRUE) ## recursive call if (x$left[b] < 0 && l < level) .plot(-x$left[b], l+1, ind) if (x$right[b] < 0 && l < level) .plot(-x$right[b], l+1, ind) } ## Do it if (length(x$left) > 0) .plot(b=1, l=1) invisible(x) } print2.igraphHRG <- function(x, ...) { cat("Hierarchical random graph:\n") bw <- ceiling(log10(length(x$left)+1))+1 p <- format(x$prob, digits=1) pw <- 4 + max(nchar(p)) nn <- if (is.null(x$names)) seq_len(length(x$left)+1) else x$names op <- sapply(seq_along(x$left), function(i) { lc <- if (x$left[i] < 0) { paste(sep="", "g", -x$left[i]) } else { nn[x$left[i]+1] } rc <- if (x$right[i] < 0) { paste(sep="", "g", -x$right[i]) } else { nn[x$right[i]+1] } paste(sep="", format(paste(sep="", "g", i), width=bw), format(paste(sep="", " p=", p[i]), width=pw), "-> ", lc, " ", rc) }) op <- format(op, justify="left") cat(op, sep=" ", fill=TRUE) invisible(x) } ## TODO: print as a tree #' Print a hierarchical random graph consensus tree to the screen #' #' Consensus dendrograms (\code{igraphHRGConsensus} objects) are printed #' simply by listing the children of each internal node of the #' dendrogram: \preformatted{HRG consensus tree: #' g1 -> 11 12 13 14 15 16 17 18 19 20 #' g2 -> 1 2 3 4 5 6 7 8 9 10 #' g3 -> g1 g2} #' The root of the dendrogram is \code{g3} (because it has no incoming #' edges), and it has two subgroups, \code{g1} and \code{g2}. #' #' @param x \code{igraphHRGConsensus} object to print. #' @param ... Ignored. #' @return The input object, invisibly, to allow method chaining. #' #' @method print igraphHRGConsensus #' @export #' @family hierarchical random graph functions print.igraphHRGConsensus <- function(x, ...) { cat("HRG consensus tree:\n") n <- length(x$parents) - length(x$weights) mn <- if (is.null(x$names)) seq_len(n) else x$names id <- c(mn, paste(sep="", "g", seq_along(x$weights))) ch <- tapply(id, x$parents, c)[-1] # first is zero bw <- nchar(as.character(length(x$weights))) vw <- max(nchar(id)) op <- sapply(seq_along(x$weights), function(i) { mych <- format(ch[[i]], width=vw) if (length(ch[[i]])*(vw+1) + bw + 4 > getOption("width")) { mych <- gsub(" ", "x", mych, fixed=TRUE) mych <- paste(collapse=" ", mych) pref <- paste(collapse="", rep(" ", bw+5)) mych <- strwrap(mych, width=getOption("width") - bw - 4, initial="", prefix=pref) mych <- gsub("x", " ", mych, fixed=TRUE) mych <- paste(collapse="\n", mych) } else { mych <- paste(collapse=" ", mych) } paste(sep="", "g", format(i, width=bw), " -> ", mych) }) if (max(nchar(op)) < (getOption("width")-4)/2) { op <- format(op, justify="left") cat(op, sep=" ", fill=TRUE) } else { cat(op, sep="\n") } invisible(x) } " ## How to print HRGs? B-1 p=0 '- B-3 p=1 6 '- B-7 p=1 2 '- B-5 p=1 1 5 '- B-6 p=1 7 '- B-2 p=1 4 '- B-4 p=1 3 8 ## The same at levels 1, 2 and 3: B-1 p=0 B-3 B-6 6 2 1 5 7 4 3 8 B-1 p=0 '+ B-3 p=1 B-7 6 2 1 5 '+ B-6 p=1 B-2 7 4 3 8 B-1 p=0 '- B-3 p=1 6 '+ B-7 p=1 B-5 2 1 5 '- B-6 p=1 7 '+ B-2 p=1 B-4 4 3 8 ## This can be tedious if the graph is big, as we always have n-1 ## internal nodes, we can restrict ourselves to (say) level 3 by default. ## Another possibility is to order the lines according to the group ids. B-1 p=0 B-3 B-6 B-2 p=1 B-4 4 B-3 p=1 B-7 6 B-4 p=1 3 8 B-5 p=1 1 5 B-6 p=1 B-2 7 B-7 p=1 B-5 2 " igraph/R/iterators.R0000644000175100001440000014304313177712334014117 0ustar hornikusers # IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Constructors ################################################################### update_es_ref <- update_vs_ref <- function(graph) { env <- get_vs_ref(graph) if (!is.null(env)) assign("me", graph, envir = env) } get_es_ref <- get_vs_ref <- function(graph) { if (is_igraph(graph) && !warn_version(graph)) { .Call(C_R_igraph_mybracket, graph, 10L) } else { NULL } } get_es_graph <- get_vs_graph <- function(seq) { at <- attr(seq, "env") if (class(at) == "weakref") { weak_ref_key(at)$me } else if (class(at) == "environment") { get("graph", envir = at) } else { NULL } } has_es_graph <- has_vs_graph <- function(seq) { !is.null(weak_ref_key(attr(seq, "env"))) } get_es_graph_id <- get_vs_graph_id <- function(seq) { new_g <- attr(seq, "graph") if (!is.null(new_g)) { new_g } else if (!is.null(attr(seq, "env"))) { get("graph", envir = attr(seq, "env")) } else { NULL } } #' Decide if two graphs are identical #' #' This is similar to \code{identical} in the \code{base} package, #' but ignores the mutable piece of igraph objects, that might be #' different, even if the two graphs are identical. #' #' @param g1,g2 The two graphs #' @return Logical scalar #' @export identical_graphs <- function(g1, g2) { stopifnot(is_igraph(g1), is_igraph(g2)) .Call(C_R_igraph_identical_graphs, g1, g2) } add_vses_graph_ref <- function(vses, graph) { ref <- get_vs_ref(graph) if (!is.null(ref)) { attr(vses, "env") <- make_weak_ref(ref, NULL) attr(vses, "graph") <- get_graph_id(graph) } else { ne <- new.env() assign("graph", graph, envir = ne) attr(vses, "env") <- ne } vses } #' Get the id of a graph #' #' Graph ids are used to check that a vertex or edge sequence #' belongs to a graph. If you create a new graph by changing the #' structure of a graph, the new graph will have a new id. #' Changing the attributes will not change the id. #' #' @param x A graph or a vertex sequence or an edge sequence. #' @param ... Not used currently. #' @return The id of the graph, a character scalar. For #' vertex and edge sequences the id of the graph they were created from. #' #' @export #' @examples #' g <- make_ring(10) #' graph_id(g) #' graph_id(V(g)) #' graph_id(E(g)) #' #' g2 <- g + 1 #' graph_id(g2) graph_id <- function(x, ...) UseMethod("graph_id") #' @method graph_id igraph #' @export graph_id.igraph <- function(x, ...) { get_graph_id(x) } #' @method graph_id igraph.vs #' @export graph_id.igraph.vs <- function(x, ...) { get_vs_graph_id(x) %||% NA_character_ } #' @method graph_id igraph.es #' @export graph_id.igraph.es <- function(x, ...) { get_es_graph_id(x) %||% NA_character_ } #' Vertices of a graph #' #' Create a vertex sequence (vs) containing all vertices of a graph. #' #' @details #' A vertex sequence is just what the name says it is: a sequence of #' vertices. Vertex sequences are usually used as igraph function arguments #' that refer to vertices of a graph. #' #' A vertex sequence is tied to the graph it refers to: it really denoted #' the specific vertices of that graph, and cannot be used together with #' another graph. #' #' At the implementation level, a vertex sequence is simply a vector #' containing numeric vertex ids, but it has a special class attribute #' which makes it possible to perform graph specific operations on it, like #' selecting a subset of the vertices based on graph structure, or vertex #' attributes. #' #' A vertex sequence is most often created by the \code{V()} function. The #' result of this includes all vertices in increasing vertex id order. A #' vertex sequence can be indexed by a numeric vector, just like a regular #' R vector. See \code{\link{[.igraph.vs}} and additional links to other #' vertex sequence operations below. #' #' @section Indexing vertex sequences: #' Vertex sequences mostly behave like regular vectors, but there are some #' additional indexing operations that are specific for them; #' e.g. selecting vertices based on graph structure, or based on vertex #' attributes. See \code{\link{[.igraph.vs}} for details. #' #' @section Querying or setting attributes: #' Vertex sequences can be used to query or set attributes for the #' vertices in the sequence. See \code{\link{$.igraph.vs}} for details. #' #' @param graph The graph #' @return A vertex sequence containing all vertices, in the order #' of their numeric vertex ids. #' #' @family vertex and edge sequences #' @export #' @examples #' # Vertex ids of an unnamed graph #' g <- make_ring(10) #' V(g) #' #' # Vertex ids of a named graph #' g2 <- make_ring(10) %>% #' set_vertex_attr("name", value = letters[1:10]) #' V(g2) V <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } update_vs_ref(graph) res <- seq_len(vcount(graph)) if (is_named(graph)) names(res) <- vertex_attr(graph)$name class(res) <- "igraph.vs" add_vses_graph_ref(res, graph) } create_vs <- function(graph, idx, na_ok = FALSE) { if (na_ok) idx <- ifelse(idx < 1 | idx > gorder(graph), NA, idx) res <- simple_vs_index(V(graph), idx, na_ok = na_ok) add_vses_graph_ref(res, graph) } #' Edges of a graph #' #' An edge sequence is a vector containing numeric edge ids, with a special #' class attribute that allows custom operations: selecting subsets of #' edges based on attributes, or graph structure, creating the #' intersection, union of edges, etc. #' #' @details #' Edge sequences are usually used as igraph function arguments that #' refer to edges of a graph. #' #' An edge sequence is tied to the graph it refers to: it really denoted #' the specific edges of that graph, and cannot be used together with #' another graph. #' #' An edge sequence is most often created by the \code{E()} function. The #' result includes edges in increasing edge id order by default (if. none #' of the \code{P} and \code{path} arguments are used). An edge #' sequence can be indexed by a numeric vector, just like a regular R #' vector. See links to other edge sequence operations below. #' #' @section Indexing edge sequences: #' Edge sequences mostly behave like regular vectors, but there are some #' additional indexing operations that are specific for them; #' e.g. selecting edges based on graph structure, or based on edge #' attributes. See \code{\link{[.igraph.es}} for details. #' #' @section Querying or setting attributes: #' Edge sequences can be used to query or set attributes for the #' edges in the sequence. See \code{\link{$.igraph.es}} for details. #' #' @param graph The graph. #' @param P A list of vertices to select edges via pairs of vertices. #' The first and second vertices select the first edge, the third #' and fourth the second, etc. #' @param path A list of vertices, to select edges along a path. #' Note that this only works reliable for simple graphs. If the graph #' has multiple edges, one of them will be chosen arbitrarily to #' be included in the edge sequence. #' @param directed Whether to consider edge directions in the \code{P} #' argument, for directed graphs. #' @return An edge sequence of the graph. #' #' @export #' @family vertex and edge sequences #' @examples #' # Edges of an unnamed graph #' g <- make_ring(10) #' E(g) #' #' # Edges of a named graph #' g2 <- make_ring(10) %>% #' set_vertex_attr("name", value = letters[1:10]) #' E(g2) E <- function(graph, P=NULL, path=NULL, directed=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } update_es_ref(graph) if (!is.null(P) && !is.null(path)) { stop("Cannot give both `P' and `path' at the same time") } if (is.null(P) && is.null(path)) { ec <- ecount(graph) res <- seq_len(ec) } else if (!is.null(P)) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_es_pairs, graph, as.igraph.vs(graph, P)-1, as.logical(directed)) + 1 } else { on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_es_path, graph, as.igraph.vs(graph, path)-1, as.logical(directed)) + 1 } if ("name" %in% edge_attr_names(graph)) { names(res) <- edge_attr(graph)$name[res] } if (is.named(graph)) { el <- ends(graph, es = res) attr(res, "vnames") <- paste(el[,1], el[,2], sep = "|") } class(res) <- "igraph.es" add_vses_graph_ref(res, graph) } create_es <- function(graph, idx, na_ok = FALSE) { if (na_ok) idx <- ifelse(idx < 1 | idx > gsize(graph), NA, idx) simple_es_index(E(graph), idx) } simple_vs_index <- function(x, i, na_ok = FALSE) { res <- unclass(x)[i] if (!na_ok && any(is.na(res))) stop('Unknown vertex selected') class(res) <- "igraph.vs" res } #' Indexing vertex sequences #' #' Vertex sequences can be indexed very much like a plain numeric R vector, #' with some extras. #' #' @details #' Vertex sequences can be indexed using both the single bracket and #' the double bracket operators, and they both work the same way. #' The only difference between them is that the double bracket operator #' marks the result for printing vertex attributes. #' #' @section Multiple indices: #' When using multiple indices within the bracket, all of them #' are evaluated independently, and then the results are concatenated #' using the \code{c()} function (except for the \code{na_ok} argument, #' which is special an must be named. E.g. \code{V(g)[1, 2, .nei(1)]} #' is equivalent to \code{c(V(g)[1], V(g)[2], V(g)[.nei(1)])}. #' #' @section Index types: #' Vertex sequences can be indexed with positive numeric vectors, #' negative numeric vectors, logical vectors, character vectors: #' \itemize{ #' \item When indexed with positive numeric vectors, the vertices at the #' given positions in the sequence are selected. This is the same as #' indexing a regular R atomic vector with positive numeric vectors. #' \item When indexed with negative numeric vectors, the vertices at the #' given positions in the sequence are omitted. Again, this is the same #' as indexing a regular R atomic vector. #' \item When indexed with a logical vector, the lengths of the vertex #' sequence and the index must match, and the vertices for which the #' index is \code{TRUE} are selected. #' \item Named graphs can be indexed with character vectors, #' to select vertices with the given names. #' } #' #' @section Vertex attributes: #' When indexing vertex sequences, vertex attributes can be refered #' to simply by using their names. E.g. if a graph has a \code{name} vertex #' attribute, then \code{V(g)[name == "foo"]} is equivalent to #' \code{V(g)[V(g)$name == "foo"]}. See examples below. #' #' @section Special functions: #' There are some special igraph functions that can be used only #' in expressions indexing vertex sequences: \describe{ #' \item{\code{.nei}}{takes a vertex sequence as its argument #' and selects neighbors of these vertices. An optional \code{mode} #' argument can be used to select successors (\code{mode="out"}), or #' precedessors (\code{mode="in"}) in directed graphs.} #' \item{\code{.inc}}{Takes an edge sequence as an argument, and #' selects vertices that have at least one incident edge in this #' edge sequence.} #' \item{\code{.from}}{Similar to \code{.inc}, but only considers the #' tails of the edges.} #' \item{\code{.to}}{Similar to \code{.inc}, but only considers the #' heads of the edges.} #' \item{\code{.innei}, \code{.outnei}}{\code{.innei(v)} is a shorthand for #' \code{.nei(v, mode = "in")}, and \code{.outnei(v)} is a shorthand for #' \code{.nei(v, mode = "out")}. #' } #' } #' Note that multiple special functions can be used together, or with #' regular indices, and then their results are concatenated. See more #' examples below. #' #' @param x A vertex sequence. #' @param ... Indices, see details below. #' @param na_ok Whether it is OK to have \code{NA}s in the vertex #' sequence. #' @return Another vertex sequence, referring to the same graph. #' #' @method [ igraph.vs #' @name igraph-vs-indexing #' @export #' @family vertex and edge sequences #' @family vertex and edge sequence operations #' #' @examples #' # ----------------------------------------------------------------- #' # Setting attributes for subsets of vertices #' largest_comp <- function(graph) { #' cl <- components(graph) #' V(graph)[which.max(cl$csize) == cl$membership] #' } #' g <- sample_(gnp(100, 2/100), #' with_vertex_(size = 3, label = ""), #' with_graph_(layout = layout_with_fr) #' ) #' giant_v <- largest_comp(g) #' V(g)$color <- "green" #' V(g)[giant_v]$color <- "red" #' plot(g) #' #' # ----------------------------------------------------------------- #' # nei() special function #' g <- graph( c(1,2, 2,3, 2,4, 4,2) ) #' V(g)[ .nei( c(2,4) ) ] #' V(g)[ .nei( c(2,4), "in") ] #' V(g)[ .nei( c(2,4), "out") ] #' #' # ----------------------------------------------------------------- #' # The same with vertex names #' g <- graph(~ A -+ B, B -+ C:D, D -+ B) #' V(g)[ .nei( c('B', 'D') ) ] #' V(g)[ .nei( c('B', 'D'), "in" ) ] #' V(g)[ .nei( c('B', 'D'), "out" ) ] `[.igraph.vs` <- function(x, ..., na_ok = FALSE) { args <- lazy_dots(..., .follow_symbols = FALSE) ## If indexing has no argument at all, then we still get one, ## but it is "empty", a name that is "" ## Special case, no argument (but we might get an artificial ## empty one if (length(args) < 1 || (length(args) == 1 && class(args[[1]]$expr) == "name" && as.character(args[[1]]$expr) == "")) { return(x) } ## Special case: single numeric argument if (length(args) == 1 && class(args[[1]]$expr) == "numeric") { res <- simple_vs_index(x, args[[1]]$expr) return (add_vses_graph_ref(res, get_vs_graph(x))) } ## Special case: single symbol argument, no such attribute if (length(args) == 1 && class(args[[1]]$expr) == "name") { graph <- get_vs_graph(x) if (! (as.character(args[[1]]$expr) %in% vertex_attr_names(graph))) { res <- simple_vs_index(x, lazy_eval(args[[1]])) return (add_vses_graph_ref(res, graph)) } } .nei <- function(v, mode=c("all", "in", "out", "total")) { ## TRUE iff the vertex is a neighbor (any type) ## of at least one vertex in v mode <- igraph.match.arg(mode) mode <- switch(mode, "out"=1, "in"=2, "all"=3, "total"=3) if (is.logical(v)) { v <- which(v) } on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_vs_nei, graph, x, as.igraph.vs(graph, v)-1, as.numeric(mode)) tmp[as.numeric(x)] } nei <- function(...) { .nei(...) } .innei <- function(v, mode=c("in", "all", "out", "total")) { .nei(v, mode = mode[1]) } innei <- function(...) { .innei(...) } .outnei <- function(v, mode=c("out", "all", "in", "total")) { .nei(v, mode = mode[1]) } outnei <- function(...) { .outnei(...) } .inc <- function(e) { ## TRUE iff the vertex (in the vs) is incident ## to at least one edge in e if (is.logical(e)) { e <- which(e) } on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_vs_adj, graph, x, as.igraph.es(graph, e)-1, as.numeric(3)) tmp[as.numeric(x)] } inc <- function(...) { .inc(...) } adj <- function(...) { .inc(...) } .from <- function(e) { ## TRUE iff the vertex is the source of at least one edge in e if (is.logical(e)) { e <- which(e) } on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_vs_adj, graph, x, as.igraph.es(graph, e)-1, as.numeric(1)) tmp[as.numeric(x)] } from <- function(...) { .from(...) } .to <- function(e) { ## TRUE iff the vertex is the target of at least one edge in e if (is.logical(e)) { e <- which(e) } on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_vs_adj, graph, x, as.igraph.es(graph, e)-1, as.numeric(2)) tmp[as.numeric(x)] } to <- function(...) { .to(...) } graph <- get_vs_graph(x) if (is.null(graph)) { res <- lapply(lazy_eval(args), simple_vs_index, x = x, na_ok = na_ok) } else { attrs <- vertex_attr(graph) xvec <- as.vector(x) for (i in seq_along(attrs)) attrs[[i]] <- attrs[[i]][xvec] res <- lazy_eval( args, data = c(attrs, .nei = .nei, nei = nei, .innei = .innei, innei = innei, .outnei = .outnei, outnei = outnei, adj = adj, .inc = .inc, inc = inc, .from = .from, from = from, .to = .to, to = to) ) res <- lapply(res, function(ii) { if (is.null(ii)) return(NULL) ii <- simple_vs_index(x, ii, na_ok) attr(ii, "env") <- attr(x, "env") attr(ii, "graph") <- attr(x, "graph") class(ii) <- class(x) ii }) } res <- drop_null(res) if (length(res)) { do_call(c, res) } else { x[FALSE] } } #' Select vertices and show their metadata #' #' The double bracket operator can be used on vertex sequences, to print #' the meta-data (vertex attributes) of the vertices in the sequence. #' #' @details #' Technically, when used with vertex sequences, the double bracket #' operator does exactly the same as the single bracket operator, #' but the resulting vertex sequence is printed differently: all #' attributes of the vertices in the sequence are printed as well. #' #' See \code{\link{[.igraph.vs}} for more about indexing vertex sequences. #' #' @param x A vertex sequence. #' @param ... Additional arguments, passed to \code{[}. #' @return The double bracket operator returns another vertex sequence, #' with meta-data (attribute) printing turned on. See details below. #' #' @method [[ igraph.vs #' @name igraph-vs-indexing2 #' @family vertex and edge sequences #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("color", value = "red") %>% #' set_vertex_attr("name", value = LETTERS[1:10]) #' V(g) #' V(g)[[]] #' V(g)[1:5] #' V(g)[[1:5]] `[[.igraph.vs` <- function(x, ...) { res <- x[...] attr(res, "single") <- TRUE res } #' Select edges and show their metadata #' #' The double bracket operator can be used on edge sequences, to print #' the meta-data (edge attributes) of the edges in the sequence. #' #' @details #' Technically, when used with edge sequences, the double bracket #' operator does exactly the same as the single bracket operator, #' but the resulting edge sequence is printed differently: all #' attributes of the edges in the sequence are printed as well. #' #' See \code{\link{[.igraph.es}} for more about indexing edge sequences. #' #' @param x An edge sequence. #' @param ... Additional arguments, passed to \code{[}. #' @return Another edge sequence, with metadata printing turned on. #' See details below. #' #' @method [[ igraph.es #' @name igraph-es-indexing2 #' @family vertex and edge sequences #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), #' with_vertex_(name = LETTERS[1:10]), #' with_edge_(weight = 1:10, color = "green")) #' E(g) #' E(g)[[]] #' E(g)[[.inc('A')]] `[[.igraph.es` <- function(x, ...) { res <- x[...] attr(res, "single") <- TRUE res } simple_es_index <- function(x, i) { if (!is.null(attr(x, "vnames"))) { wh1 <- structure(seq_along(x), names = names(x))[i] wh2 <- structure(seq_along(x), names = attr(x, "vnames"))[i] wh <- ifelse(is.na(wh1), wh2, wh1) res <- unclass(x)[wh] names(res) <- names(x)[wh] attr(res, "vnames") <- attr(x, "vnames")[wh] } else { res <- unclass(x)[i] } if (any(is.na(res))) stop('Unknown edge selected') attr(res, "env") <- attr(x, "env") attr(res, "graph") <- attr(x, "graph") class(res) <- "igraph.es" res } #' Indexing edge sequences #' #' Edge sequences can be indexed very much like a plain numeric R vector, #' with some extras. #' #' @section Multiple indices: #' When using multiple indices within the bracket, all of them #' are evaluated independently, and then the results are concatenated #' using the \code{c()} function. E.g. \code{E(g)[1, 2, .inc(1)]} #' is equivalent to \code{c(E(g)[1], E(g)[2], E(g)[.inc(1)])}. #' #' @section Index types: #' Edge sequences can be indexed with positive numeric vectors, #' negative numeric vectors, logical vectors, character vectors: #' \itemize{ #' \item When indexed with positive numeric vectors, the edges at the #' given positions in the sequence are selected. This is the same as #' indexing a regular R atomic vector with positive numeric vectors. #' \item When indexed with negative numeric vectors, the edges at the #' given positions in the sequence are omitted. Again, this is the same #' as indexing a regular R atomic vector. #' \item When indexed with a logical vector, the lengths of the edge #' sequence and the index must match, and the edges for which the #' index is \code{TRUE} are selected. #' \item Named graphs can be indexed with character vectors, #' to select edges with the given names. Note that a graph may #' have edge names and vertex names, and both can be used to select #' edges. Edge names are simply used as names of the numeric #' edge id vector. Vertex names effectively only work in graphs without #' multiple edges, and must be separated with a \code{|} bar character #' to select an edges that incident to the two given vertices. See #' examples below. #' } #' #' @section Edge attributes: #' When indexing edge sequences, edge attributes can be refered #' to simply by using their names. E.g. if a graph has a \code{weight} edge #' attribute, then \code{E(G)[weight > 1]} selects all edges with a larger #' than one weight. See more examples below. #' #' @section Special functions: #' There are some special igraph functions that can be used #' only in expressions indexing edge sequences: \describe{ #' \item{\code{.inc}}{takes a vertex sequence, and selects #' all edges that have at least one incident vertex in the vertex #' sequence.} #' \item{\code{.from}}{similar to \code{.inc()}, but only #' the tails of the edges are considered.} #' \item{\code{.to}}{is similar to \code{.inc()}, but only #' the heads of the edges are considered.} #' \item{\code{\%--\%}}{a special operator that can be #' used to select all edges between two sets of vertices. It ignores #' the edge directions in directed graphs.} #' \item{\code{\%->\%}}{similar to \code{\%--\%}, #' but edges \emph{from} the left hand side argument, pointing #' \emph{to} the right hand side argument, are selected, in directed #' graphs.} #' \item{\code{\%<-\%}}{similar to \code{\%--\%}, #' but edges \emph{to} the left hand side argument, pointing #' \emph{from} the right hand side argument, are selected, in directed #' graphs.} #' } #' Note that multiple special functions can be used together, or with #' regular indices, and then their results are concatenated. See more #' examples below. #' #' @aliases %--% %<-% %->% #' @param x An edge sequence #' @param ... Indices, see details below. #' @return Another edge sequence, referring to the same graph. #' #' @method [ igraph.es #' @name igraph-es-indexing #' #' @export #' @family vertex and edge sequences #' @family vertex and edge sequence operations #' @examples #' # special operators for indexing based on graph structure #' g <- sample_pa(100, power = 0.3) #' E(g) [ 1:3 %--% 2:6 ] #' E(g) [ 1:5 %->% 1:6 ] #' E(g) [ 1:3 %<-% 2:6 ] #' #' # the edges along the diameter #' g <- sample_pa(100, directed = FALSE) #' d <- get_diameter(g) #' E(g, path = d) #' #' # select edges based on attributes #' g <- sample_gnp(20, 3/20) %>% #' set_edge_attr("weight", value = rnorm(gsize(.))) #' E(g)[[ weight < 0 ]] `[.igraph.es` <- function(x, ...) { args <- lazy_dots(..., .follow_symbols = TRUE) ## If indexing has no argument at all, then we still get one, ## but it is "empty", a name that is "" if (length(args) < 1 || (length(args) == 1 && class(args[[1]]$expr) == "name" && as.character(args[[1]]$expr) == "")) { return(x) } .inc <- function(v) { ## TRUE iff the edge is incident to at least one vertex in v on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_es_adj, graph, x, as.igraph.vs(graph, v)-1, as.numeric(3)) tmp[ as.numeric(x) ] } adj <- function(...) { .inc(...) } inc <- function(...) { .inc(...) } .from <- function(v) { ## TRUE iff the edge originates from at least one vertex in v on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_es_adj, graph, x, as.igraph.vs(graph, v)-1, as.numeric(1)) tmp[ as.numeric(x) ] } from <- function(...) { .from(...) } .to <- function(v) { ## TRUE iff the edge points to at least one vertex in v on.exit(.Call(C_R_igraph_finalizer) ) tmp <- .Call(C_R_igraph_es_adj, graph, x, as.igraph.vs(graph, v)-1, as.numeric(2)) tmp[ as.numeric(x) ] } to <- function(...) { .to(...) } graph <- get_es_graph(x) if (is.null(graph)) { res <- lapply(lazy_eval(args), simple_es_index, x = x) } else { attrs <- edge_attr(graph) xvec <- as.vector(x) for (i in seq_along(attrs)) attrs[[i]] <- attrs[[i]][xvec] res <- lazy_eval( args, data = c(attrs, .inc = .inc, inc = inc, adj = adj, .from = .from, from = from, .to = .to, to = to, .igraph.from = list(.Call(C_R_igraph_mybracket, graph, 3L)[ as.numeric(x) ]), .igraph.to = list(.Call(C_R_igraph_mybracket, graph, 4L)[as.numeric(x)]), .igraph.graph = list(graph), `%--%`=`%--%`, `%->%`=`%->%`, `%<-%`=`%<-%`) ) res <- lapply(res, function(ii) { if (is.null(ii)) return(NULL) ii <- simple_es_index(x, ii) attr(ii, "env") <- attr(x, "env") attr(ii, "graph") <- attr(x, "graph") class(ii) <- class(x) ii }) } res <- drop_null(res) if (length(res) == 1) { res[[1]] } else if (length(res)) { do_call(c, res) } else { x[FALSE] } } #' @export `%--%` <- function(f, t) { from <- get(".igraph.from", parent.frame()) to <- get(".igraph.to", parent.frame()) graph <- get(".igraph.graph", parent.frame()) f <- as.igraph.vs(graph, f)-1 t <- as.igraph.vs(graph, t)-1 (from %in% f & to %in% t) | (to %in% f & from %in% t) } #' @export `%->%` <- function(f, t) { from <- get(".igraph.from", parent.frame()) to <- get(".igraph.to", parent.frame()) graph <- get(".igraph.graph", parent.frame()) f <- as.igraph.vs(graph, f)-1 t <- as.igraph.vs(graph, t)-1 if (is_directed(graph)) { from %in% f & to %in% t } else { (from %in% f & to %in% t) | (to %in% f & from %in% t) } } #' @export `%<-%` <- function(t, value) { from <- get(".igraph.from", parent.frame()) to <- get(".igraph.to", parent.frame()) graph <- get(".igraph.graph", parent.frame()) value <- as.igraph.vs(graph, value)-1 t <- as.igraph.vs(graph, t)-1 if (is_directed(graph)) { from %in% value & to %in% t } else { (from %in% value & to %in% t) | (to %in% value & from %in% t) } } #' @param i Index. #' @method [[<- igraph.vs #' @name igraph-vs-attributes #' @export `[[<-.igraph.vs` <- function(x, i, value) { if (! "name" %in% names(attributes(value)) || ! "value" %in% names(attributes(value))) { stop("invalid indexing") } if (is.null(get_vs_graph(x))) stop("Graph is unknown") value } #' @method [<- igraph.vs #' @name igraph-vs-attributes #' @export `[<-.igraph.vs` <- `[[<-.igraph.vs` #' @param i Index. #' @method [[<- igraph.es #' @name igraph-es-attributes #' @export `[[<-.igraph.es` <- function(x, i, value) { if (! "name" %in% names(attributes(value)) || ! "value" %in% names(attributes(value))) { stop("invalid indexing") } if (is.null(get_es_graph(x))) stop("Graph is unknown") value } #' @method [<- igraph.es #' @name igraph-es-attributes #' @export `[<-.igraph.es` <- `[[<-.igraph.es` #' Query or set attributes of the vertices in a vertex sequence #' #' The \code{$} operator is a syntactic sugar to query and set the #' attributes of the vertices in a vertex sequence. #' #' @details #' The query form of \code{$} is a shortcut for #' \code{\link{vertex_attr}}, e.g. \code{V(g)[idx]$attr} is equivalent #' to \code{vertex_attr(g, attr, V(g)[idx])}. #' #' The assignment form of \code{$} is a shortcut for #' \code{\link{set_vertex_attr}}, e.g. \code{V(g)[idx]$attr <- value} is #' equivalent to \code{g <- set_vertex_attr(g, attr, V(g)[idx], value)}. #' #' @param x A vertex sequence. For \code{V<-} it is a graph. #' @param name Name of the vertex attribute to query or set. #' @return A vector or list, containing the values of #' attribute \code{name} for the vertices in the vertex sequence. #' For numeric, character or logical attributes, it is a vector of the #' appropriate type, otherwise it is a list. #' #' @method $ igraph.vs #' @name igraph-vs-attributes #' #' @export #' @family vertex and edge sequences #' @family graph attributes #' @examples #' g <- make_(ring(10), #' with_vertex_( #' name = LETTERS[1:10], #' color = sample(1:2, 10, replace=TRUE) #' ) #' ) #' V(g)$name #' V(g)$color #' V(g)$frame.color <- V(g)$color #' #' # color vertices of the largest component #' largest_comp <- function(graph) { #' cl <- components(graph) #' V(graph)[which.max(cl$csize) == cl$membership] #' } #' g <- sample_(gnp(100, 2/100), #' with_vertex_(size = 3, label = ""), #' with_graph_(layout = layout_with_fr) #' ) #' giant_v <- largest_comp(g) #' V(g)$color <- "blue" #' V(g)[giant_v]$color <- "orange" #' plot(g) `$.igraph.vs` <- function(x, name) { graph <- get_vs_graph(x) if (is.null(graph)) stop("Graph is unknown") res <- vertex_attr(graph, name, x) if ("single" %in% names(attributes(x)) && attr(x, "single")) { res[[1]] } else { res } } #' Query or set attributes of the edges in an edge sequence #' #' The \code{$} operator is a syntactic sugar to query and set #' edge attributes, for edges in an edge sequence. #' #' @details #' The query form of \code{$} is a shortcut for \code{\link{edge_attr}}, #' e.g. \code{E(g)[idx]$attr} is equivalent to \code{edge_attr(g, attr, #' E(g)[idx])}. #' #' The assignment form of \code{$} is a shortcut for #' \code{\link{set_edge_attr}}, e.g. \code{E(g)[idx]$attr <- value} is #' equivalent to \code{g <- set_edge_attr(g, attr, E(g)[idx], value)}. #' #' @param x An edge sequence. For \code{E<-} it is a graph. #' @param name Name of the edge attribute to query or set. #' @return A vector or list, containing the values of the attribute #' \code{name} for the edges in the sequence. For numeric, character or #' logical attributes, it is a vector of the appropriate type, otherwise #' it is a list. #' #' @method $ igraph.es #' @name igraph-es-attributes #' #' @export #' @family vertex and edge sequences #' @examples #' # color edges of the largest component #' largest_comp <- function(graph) { #' cl <- components(graph) #' V(graph)[which.max(cl$csize) == cl$membership] #' } #' g <- sample_(gnp(100, 1/100), #' with_vertex_(size = 3, label = ""), #' with_graph_(layout = layout_with_fr) #' ) #' giant_v <- largest_comp(g) #' E(g)$color <- "orange" #' E(g)[giant_v %--% giant_v]$color <- "blue" #' plot(g) `$.igraph.es` <- function(x, name) { graph <- get_es_graph(x) if (is.null(graph)) stop("Graph is unknown") res <- edge_attr(graph, name, x) if ("single" %in% names(attributes(x)) && attr(x, "single")) { res[[1]] } else { res } } #' @param value New value of the attribute, for the vertices in the #' vertex sequence. #' #' @method $<- igraph.vs #' @name igraph-vs-attributes #' @export `$<-.igraph.vs` <- function(x, name, value) { if (is.null(get_vs_graph(x))) stop("Graph is unknown") attr(x, "name") <- name attr(x, "value") <- value x } #' @param value New value of the attribute, for the edges in the edge #' sequence. #' @method $<- igraph.es #' @name igraph-es-attributes #' @export #' @family vertex and edge sequences `$<-.igraph.es` <- function(x, name, value) { if (is.null(get_es_graph(x))) stop("Graph is unknown") attr(x, "name") <- name attr(x, "value") <- value x } #' @name igraph-vs-attributes #' @export `V<-` <- function(x, value) { if (!is_igraph(x)) { stop("Not a graph object") } if (! "name" %in% names(attributes(value)) || ! "value" %in% names(attributes(value))) { stop("invalid indexing") } i_set_vertex_attr(x, attr(value, "name"), index=value, value=attr(value, "value"), check = FALSE) } #' @param path Select edges along a path, given by a vertex sequence See #' \code{\link{E}}. #' @param P Select edges via pairs of vertices. See \code{\link{E}}. #' @param directed Whether to use edge directions for the \code{path} or #' \code{P} arguments. #' @name igraph-es-attributes #' @export `E<-` <- function(x, path=NULL, P=NULL, directed=NULL, value) { if (!is_igraph(x)) { stop("Not a graph object") } if (! "name" %in% names(attributes(value)) || ! "value" %in% names(attributes(value))) { stop("invalid indexing") } i_set_edge_attr(x, attr(value, "name"), index=value, value=attr(value, "value"), check = FALSE) } #' Show a vertex sequence on the screen #' #' For long vertex sequences, the printing is truncated to fit to the #' screen. Use \code{print} explicitly and the \code{full} argument to #' see the full sequence. #' #' Vertex sequence created with the double bracket operator are #' printed differently, together with all attributes of the vertices #' in the sequence, as a table. #' #' @param x A vertex sequence. #' @param full Whether to show the full sequence, or truncate the output #' to the screen size. #' @param ... These arguments are currently ignored. #' @return The vertex sequence, invisibly. #' #' @method print igraph.vs #' @export #' @family vertex and edge sequences #' @examples #' # Unnamed graphs #' g <- make_ring(10) #' V(g) #' #' # Named graphs #' g2 <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) #' V(g2) #' #' # All vertices in the sequence #' g3 <- make_ring(1000) #' V(g3) #' print(V(g3), full = TRUE) #' #' # Metadata #' g4 <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) %>% #' set_vertex_attr("color", value = "red") #' V(g4)[[]] #' V(g4)[[2:5, 7:8]] print.igraph.vs <- function(x, full = igraph_opt("print.full"), ...) { graph <- get_vs_graph(x) len <- length(x) id <- graph_id(x) title <- "+ " %+% chr(len) %+% "/" %+% (if (is.null(graph)) "?" else chr(vcount(graph))) %+% (if (len == 1) " vertex" else " vertices") %+% (if (!is.null(names(x))) ", named" else "") %+% (if (!is.na(id)) paste(", from", substr(id, 1, 7)) else "") %+% (if (is.null(graph)) " (deleted)" else "") %+% ":\n" cat(title) if (!is.null(attr(x, "single")) && attr(x, "single") && !is.null(graph) && length(vertex_attr_names(graph) > 0)) { ## Double bracket va <- vertex_attr(graph) if (all(sapply(va, is.atomic))) { print(as.data.frame(va, stringsAsFactors = FALSE)[as.vector(x),, drop = FALSE]) } else { print(lapply(va, "[", as.vector(x))) } } else { ## Single bracket x2 <- if (!is.null(names(x))) names(x) else as.vector(x) if (length(x2)) { if (is.logical(full) && full) { print(x2, quote = FALSE) } else { head_print(x2, omitted_footer = "+ ... omitted several vertices\n", quote = FALSE, max_lines = igraph_opt("auto.print.lines")) } } } invisible(x) } #' Print an edge sequence to the screen #' #' For long edge sequences, the printing is truncated to fit to the #' screen. Use \code{print} explicitly and the code{full} argument to #' see the full sequence. #' #' Edge sequences created with the double bracket operator are printed #' differently, together with all attributes of the edges in the sequence, #' as a table. #' #' @param x An edge sequence. #' @param full Whether to show the full sequence, or truncate the output #' to the screen size. #' @param ... Currently ignored. #' @return The edge sequence, invisibly. #' #' @method print igraph.es #' @export #' @family vertex and edge sequences #' @examples #' # Unnamed graphs #' g <- make_ring(10) #' E(g) #' #' # Named graphs #' g2 <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) #' E(g2) #' #' # All edges in a long sequence #' g3 <- make_ring(200) #' E(g3) #' E(g3) %>% print(full = TRUE) #' #' # Metadata #' g4 <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) %>% #' set_edge_attr("weight", value = 1:10) %>% #' set_edge_attr("color", value = "green") #' E(g4) #' E(g4)[[]] #' E(g4)[[1:5]] print.igraph.es <- function(x, full = igraph_opt("print.full"), ...) { graph <- get_es_graph(x) ml <- if (identical(full, TRUE)) NULL else igraph_opt("auto.print.lines") .print.edges.compressed(x = graph, edges = x, max.lines = ml, names = TRUE, num = TRUE) invisible(x) } # these are internal as.igraph.vs <- function(graph, v, na.ok=FALSE) { if (inherits(v, "igraph.vs") && !is.null(graph) && !warn_version(graph)) { if (get_graph_id(graph) != get_vs_graph_id(v)) { stop("Cannot use a vertex sequence from another graph.") } } if (is.character(v) && "name" %in% vertex_attr_names(graph)) { v <- as.numeric(match(v, V(graph)$name)) if (!na.ok && any(is.na(v))) { stop("Invalid vertex names") } v } else { if (is.logical(v)) { res <- as.vector(V(graph))[v] } else if (is.numeric(v) && any(v<0)){ res <- as.vector(V(graph))[v] } else { res <- as.numeric(v) } if (!na.ok && any(is.na(res))) { stop("Invalid vertex name(s)") } res } } as.igraph.es <- function(graph, e) { if (inherits(e, "igraph.es") && !is.null(graph) && !warn_version(graph)) { if (get_graph_id(graph) != get_es_graph_id(e)) { stop("Cannot use an edge sequence from another graph.") } } if (is.character(e)) { Pairs <- grep("|", e, fixed=TRUE) Names <- if (length(Pairs)==0) seq_along(e) else -Pairs res <- numeric(length(e)) ## Based on vertex ids/names if (length(Pairs)!=0) { vv <- strsplit(e[Pairs], "|", fixed=TRUE) vl <- sapply(vv, length) if (any(vl != 2)) { stop("Invalid edge name: ", e[Pairs][vl!=2][1]) } vp <- unlist(vv) if (! "name" %in% vertex_attr_names(graph)) { vp <- as.numeric(vp) } res[Pairs] <- get.edge.ids(graph, vp) } ## Based on edge ids/names if (length(Names) != 0) { if ("name" %in% edge_attr_names(graph)) { res[Names] <- as.numeric(match(e[Names], E(graph)$name)) } else { res[Names] <- as.numeric(e[Names]) } } } else { res <- as.numeric(e) } if (any(is.na(res))) { stop("Invalid edge names") } res } is_igraph_vs <- function(x) { inherits(x, "igraph.vs") } is_igraph_es <- function(x) { inherits(x, "igraph.es") } parse_op_args <- function(..., what, is_fun, as_fun, check_graph = TRUE) { args <- list(...) if (any(! sapply(args, is_fun))) stop("Not ", what, " sequence") ## get the ids of all graphs graph_id <- sapply(args, get_vs_graph_id) %>% unique() if (length(graph_id) != 1) { warning("Combining vertex/edge sequences from different graphs.\n", "This will not work in future igraph versions") } graphs <- args %>% lapply(get_vs_graph) %>% drop_null() addresses <- graphs %>% sapply(function(x) x %&&% address(x)) %>% unique() if (check_graph && length(addresses) >= 2) { warning("Combining vertex/edge sequences from different graphs.\n", "This will not work in future igraph versions") } graph <- if (length(graphs)) graphs[[1]] else NULL args <- lapply(args, unclass) list(graph = graph, args = args, id = graph_id) } parse_vs_op_args <- function(...) { parse_op_args(..., what = "a vertex", is_fun = is_igraph_vs, as_fun = as.igraph.vs) } parse_es_op_args <- function(...) { parse_op_args(..., what = "an edge", is_fun = is_igraph_es, as_fun = as.igraph.es) } create_op_result <- function(parsed, result, class, args) { result <- add_vses_graph_ref(result, parsed$graph) class(result) <- class ## c() drops names for zero length vectors. Why??? if (! length(result) && any(sapply(args, function(x) !is.null(names(x))))) { names(result) <- character() } result } #' Remove duplicate vertices from a vertex sequence #' #' @param x A vertex sequence. #' @param incomparables a vector of values that cannot be compared. #' Passed to base function \code{duplicated}. See details there. #' @param ... Passed to base function \code{duplicated()}. #' @return A vertex sequence with the duplicate vertices removed. #' #' @method unique igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' V(g)[1, 1:5, 1:10, 5:10] #' V(g)[1, 1:5, 1:10, 5:10] %>% unique() unique.igraph.vs <- function(x, incomparables = FALSE, ...) { x[!duplicated(x, incomparables = incomparables, ...)] } #' Remove duplicate edges from an edge sequence #' #' @param x An edge sequence. #' @param incomparables a vector of values that cannot be compared. #' Passed to base function \code{duplicated}. See details there. #' @param ... Passed to base function \code{duplicated()}. #' @return An edge sequence with the duplicate vertices removed. #' #' @method unique igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' E(g)[1, 1:5, 1:10, 5:10] #' E(g)[1, 1:5, 1:10, 5:10] %>% unique() unique.igraph.es <- function(x, incomparables = FALSE, ...) { x[!duplicated(x, incomparables = incomparables, ...)] } #' Concatenate vertex sequences #' #' @param ... The vertex sequences to concatenate. They must #' refer to the same graph. #' @param recursive Ignored, included for S3 compatibility with #' the base \code{c} function. #' @return A vertex sequence, the input sequences concatenated. #' #' @method c igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' c(V(g)[1], V(g)['A'], V(g)[1:4]) c.igraph.vs <- function(..., recursive = FALSE) { parsed <- parse_vs_op_args(...) res <- do_call(c, .args = parsed$args) create_op_result(parsed, res, "igraph.vs", list(...)) } #' Concatenate edge sequences #' #' @param ... The edge sequences to concatenate. They must #' all refer to the same graph. #' @param recursive Ignored, included for S3 compatibility with the #' base \code{c} function. #' @return An edge sequence, the input sequences concatenated. #' #' @method c igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' c(E(g)[1], E(g)['A|B'], E(g)[1:4]) c.igraph.es <- function(..., recursive = FALSE) { parsed <- parse_es_op_args(...) res <- do_call(c, .args = parsed$args) res <- create_op_result(parsed, res, "igraph.es", list(...)) attr(res, "vnames") <- do_call(c, .args = lapply(list(...), attr, "vnames")) res } #' Union of vertex sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of vertices is lost in the #' result. (This is to match the behavior of the based \code{unique} #' function.) #' #' @param ... The vertex sequences to take the union of. #' @return A vertex sequence that contains all vertices in the given #' sequences, exactly once. #' #' @method union igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' union(V(g)[1:6], V(g)[5:10]) union.igraph.vs <- function(...) { unique(c(...)) } #' Union of edge sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of edges is lost in the #' result. (This is to match the behavior of the based \code{unique} #' function.) #' #' @param ... The edge sequences to take the union of. #' @return An edge sequence that contains all edges in the given #' sequences, exactly once. #' #' @method union igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' union(E(g)[1:6], E(g)[5:9], E(g)['A|J']) union.igraph.es <- union.igraph.vs #' Intersection of vertex sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of vertices is lost in the #' result. #' #' @param ... The vertex sequences to take the intersection of. #' @return A vertex sequence that contains vertices that appear in all #' given sequences, each vertex exactly once. #' #' @method intersection igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' intersection(E(g)[1:6], E(g)[5:9]) intersection.igraph.vs <- function(...) { ifun <- function(x, y) { unique(y[match(as.vector(x), y, 0L)]) } Reduce(ifun, list(...)) } #' Intersection of edge sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of edges is lost in the #' result. #' #' @param ... The edge sequences to take the intersection of. #' @return An edge sequence that contains edges that appear in all #' given sequences, each edge exactly once. #' #' @method intersection igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' intersection(E(g)[1:6], E(g)[5:9]) intersection.igraph.es <- intersection.igraph.vs #' Difference of vertex sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of vertices is lost in the #' result. #' #' @param big The \sQuote{big} vertex sequence. #' @param small The \sQuote{small} vertex sequence. #' @param ... Ignored, included for S3 signature compatibility. #' @return A vertex sequence that contains only vertices that are part of #' \code{big}, but not part of \code{small}. #' #' @method difference igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' difference(V(g), V(g)[6:10]) difference.igraph.vs <- function(big, small, ...) { if (!length(big)) { big } else { big[ match(big, small, 0L) == 0L ] } } #' Difference of edge sequences #' #' @details #' They must belong to the same graph. Note that this function has #' \sQuote{set} semantics and the multiplicity of edges is lost in the #' result. #' #' @param big The \sQuote{big} edge sequence. #' @param small The \sQuote{small} edge sequence. #' @param ... Ignored, included for S3 signature compatibility. #' @return An edge sequence that contains only edges that are part of #' \code{big}, but not part of \code{small}. #' #' @method difference igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' difference(V(g), V(g)[6:10]) difference.igraph.es <- difference.igraph.vs #' Reverse the order in a vertex sequence #' #' @param x The vertex sequence to reverse. #' @return The reversed vertex sequence. #' #' @method rev igraph.vs #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' V(g) %>% rev() rev.igraph.vs <- function(x) { x[rev(seq_along(x))] } #' Reverse the order in an edge sequence #' #' @param x The edge sequence to reverse. #' @return The reversed edge sequence. #' #' @method rev igraph.es #' @family vertex and edge sequence operations #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) #' E(g) #' E(g) %>% rev() rev.igraph.es <- rev.igraph.vs #' Convert a vertex or edge sequence to an ordinary vector #' #' @details #' For graphs without names, a numeric vector is returned, containing the #' internal numeric vertex or edge ids. #' #' For graphs with names, and vertex sequences, the vertex names are #' returned in a character vector. #' #' For graphs with names and edge sequences, a character vector is #' returned, with the \sQuote{bar} notation: \code{a|b} means an edge from #' vertex \code{a} to vertex \code{b}. #' #' @param seq The vertex or edge sequence. #' @return A character or numeric vector, see details below. #' #' @export #' @examples #' g <- make_ring(10) #' as_ids(V(g)) #' as_ids(E(g)) #' #' V(g)$name <- letters[1:10] #' as_ids(V(g)) #' as_ids(E(g)) as_ids <- function(seq) UseMethod("as_ids") #' @method as_ids igraph.vs #' @rdname as_ids #' @export as_ids.igraph.vs <- function(seq) { names(seq) %||% as.vector(seq) } #' @method as_ids igraph.es #' @rdname as_ids #' @export as_ids.igraph.es <- function(seq) { attr(seq, "vnames") %||% as.vector(seq) } igraph/R/adjacency.R0000644000175100001440000003600513561247122014016 0ustar hornikusers ## ---------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2005-2019 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------- graph.adjacency.dense <- function(adjmatrix, mode=c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted=NULL, diag=TRUE) { mode <- igraph.match.arg(mode) mode <- switch(mode, "directed"=0, "undirected"=1, "max"=1, "upper"=2, "lower"=3, "min"=4, "plus"=5) mode(adjmatrix) <- "double" if (!is.null(weighted)) { if (is.logical(weighted) && weighted) { weighted <- "weight" } if (!is.character(weighted)) { stop("invalid value supplied for `weighted' argument, please see docs.") } if (nrow(adjmatrix) != ncol(adjmatrix)) { stop("not a square matrix") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_weighted_adjacency, adjmatrix, as.numeric(mode), weighted, diag) } else { adjmatrix <- as.matrix(adjmatrix) attrs <- attributes(adjmatrix) adjmatrix <- as.numeric(adjmatrix) attributes(adjmatrix) <- attrs if (!diag) { diag(adjmatrix) <- 0 } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_graph_adjacency, adjmatrix, as.numeric(mode)) } res } m2triplet <- get0("mat2triplet", asNamespace("Matrix"), inherits=FALSE) if(!is.function(m2triplet)) ## <==> (packageVersion("Matrix") < "1.3") m2triplet <- function(x) { ## a simplified version of new Matrix' mat2triplet() T <- as(x, "TsparseMatrix") if(is(T, "nsparseMatrix")) list(i = T@i + 1L, j = T@j + 1L) else list(i = T@i + 1L, j = T@j + 1L, x = T@x) } mat_summary <- function(x) as.data.frame(m2triplet(x)) if(FALSE) ## should work, too, *faster* : mat_summary <- function(x) do.call(cbind, m2triplet(x)) graph.adjacency.sparse <- function(adjmatrix, mode=c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted=NULL, diag=TRUE) { mode <- igraph.match.arg(mode) if (!is.null(weighted)) { if (is.logical(weighted) && weighted) { weighted <- "weight" } if (!is.character(weighted)) { stop("invalid value supplied for `weighted' argument, please see docs.") } } if (nrow(adjmatrix) != ncol(adjmatrix)) { stop("not a square matrix") } vc <- nrow(adjmatrix) ## to remove non-redundancies that can persist in a dgtMatrix if(inherits(adjmatrix, "dgTMatrix")) { adjmatrix = as(adjmatrix, "CsparseMatrix") } if (is.null(weighted) && mode=="undirected") { mode <- "max" } if (mode == "directed") { ## DIRECTED el <- mat_summary(adjmatrix) if (!diag) { el <- el[ el[,1] != el[,2], ] } } else if (mode == "undirected") { ## UNDIRECTED, must be symmetric if weighted if (!is.null(weighted) && !Matrix::isSymmetric(adjmatrix)) { stop("Please supply a symmetric matrix if you want to create a weighted graph with mode=UNDIRECTED.") } if (diag) { adjmatrix <- Matrix::tril(adjmatrix) } else { adjmatrix <- Matrix::tril(adjmatrix, -1) } el <- mat_summary(adjmatrix) } else if (mode=="max") { ## MAXIMUM el <- mat_summary(adjmatrix) rm(adjmatrix) if (!diag) { el <- el[ el[,1] != el[,2], ] } el <- el[ el[,3] != 0, ] w <- el[,3] el <- el[,1:2] el <- cbind( pmin(el[,1],el[,2]), pmax(el[,1], el[,2]) ) o <- order(el[,1], el[,2]) el <- el[o,,drop=FALSE] w <- w[o] if (nrow(el) > 1) { dd <- el[2:nrow(el),1] == el[1:(nrow(el)-1),1] & el[2:nrow(el),2] == el[1:(nrow(el)-1),2] dd <- which(dd) if (length(dd)>0) { mw <- pmax(w[dd], w[dd+1]) w[dd] <- mw w[dd+1] <- mw el <- el[-dd,,drop=FALSE] w <- w[-dd] } } el <- cbind(el, w) } else if (mode=="upper") { ## UPPER if (diag) { adjmatrix <- Matrix::triu(adjmatrix) } else { adjmatrix <- Matrix::triu(adjmatrix, 1) } el <- mat_summary(adjmatrix) rm(adjmatrix) if (!diag) { el <- el[ el[,1] != el[,2], ] } } else if (mode=="lower") { ## LOWER if (diag) { adjmatrix <- Matrix::tril(adjmatrix) } else { adjmatrix <- Matrix::tril(adjmatrix, -1) } el <- mat_summary(adjmatrix) rm(adjmatrix) if (!diag) { el <- el[ el[,1] != el[,2], ] } } else if (mode=="min") { ## MINIMUM adjmatrix <- sign(adjmatrix) * sign(Matrix::t(adjmatrix)) * adjmatrix el <- mat_summary(adjmatrix) if (!diag) { el <- el[ el[,1] != el[,2], ] } el <- el[ el[,3] != 0, ] w <- el[,3] el <- el[,1:2] el <- cbind( pmin(el[,1],el[,2]), pmax(el[,1], el[,2]) ) o <- order(el[,1], el[,2]) el <- el[o,] w <- w[o] if (nrow(el) > 1) { dd <- el[2:nrow(el),1] == el[1:(nrow(el)-1),1] & el[2:nrow(el),2] == el[1:(nrow(el)-1),2] dd <- which(dd) if (length(dd)>0) { mw <- pmin(w[dd], w[dd+1]) w[dd] <- mw w[dd+1] <- mw el <- el[-dd,] w <- w[-dd] } } el <- cbind(el, w) } else if (mode=="plus") { ## PLUS adjmatrix <- adjmatrix + Matrix::t(adjmatrix) if (diag) { adjmatrix <- Matrix::tril(adjmatrix) } else { adjmatrix <- Matrix::tril(adjmatrix, -1) } el <- mat_summary(adjmatrix) if (diag) { loop <- el[,1] == el[,2] el[loop,3] <- el[loop,3] / 2 } el <- el[ el[,3] != 0, ] rm(adjmatrix) } if (!is.null(weighted)) { res <- make_empty_graph(n=vc, directed=(mode=="directed")) weight <- list(el[,3]) names(weight) <- weighted res <- add_edges(res, edges=t(as.matrix(el[,1:2])), attr=weight) } else { edges <- unlist(apply(el, 1, function(x) rep(unname(x[1:2]), x[3]))) res <- graph(n=vc, edges, directed=(mode=="directed")) } res } #' Create graphs from adjacency matrices #' #' \code{graph_from_adjacency_matrix} is a flexible function for creating \code{igraph} #' graphs from adjacency matrices. #' #' The order of the vertices are preserved, i.e. the vertex corresponding to #' the first row will be vertex 0 in the graph, etc. #' #' \code{graph_from_adjacency_matrix} operates in two main modes, depending on the #' \code{weighted} argument. #' #' If this argument is \code{NULL} then an unweighted graph is created and an #' element of the adjacency matrix gives the number of edges to create between #' the two corresponding vertices. The details depend on the value of the #' \code{mode} argument: \describe{ \item{"directed"}{The graph will be #' directed and a matrix element gives the number of edges between two #' vertices.} \item{"undirected"}{This is exactly the same as \code{max}, #' for convenience. Note that it is \emph{not} checked whether the matrix is #' symmetric.} \item{"max"}{An undirected graph will be created and #' \code{max(A(i,j), A(j,i))} gives the number of edges.} #' \item{"upper"}{An undirected graph will be created, only the upper #' right triangle (including the diagonal) is used for the number of edges.} #' \item{"lower"}{An undirected graph will be created, only the lower #' left triangle (including the diagonal) is used for creating the edges.} #' \item{"min"}{undirected graph will be created with \code{min(A(i,j), #' A(j,i))} edges between vertex \code{i} and \code{j}.} \item{"plus"}{ #' undirected graph will be created with \code{A(i,j)+A(j,i)} edges between #' vertex \code{i} and \code{j}.} } #' #' If the \code{weighted} argument is not \code{NULL} then the elements of the #' matrix give the weights of the edges (if they are not zero). The details #' depend on the value of the \code{mode} argument: \describe{ #' \item{"directed"}{The graph will be directed and a matrix element #' gives the edge weights.} \item{"undirected"}{First we check that the #' matrix is symmetric. It is an error if not. Then only the upper triangle is #' used to create a weighted undirected graph.} \item{"max"}{An #' undirected graph will be created and \code{max(A(i,j), A(j,i))} gives the #' edge weights.} \item{"upper"}{An undirected graph will be created, #' only the upper right triangle (including the diagonal) is used (for the edge #' weights).} \item{"lower"}{An undirected graph will be created, only #' the lower left triangle (including the diagonal) is used for creating the #' edges.} \item{"min"}{An undirected graph will be created, #' \code{min(A(i,j), A(j,i))} gives the edge weights.} \item{"plus"}{An #' undirected graph will be created, \code{A(i,j)+A(j,i)} gives the edge #' weights.} } #' #' @aliases graph.adjacency #' @param adjmatrix A square adjacency matrix. From igraph version 0.5.1 this #' can be a sparse matrix created with the \code{Matrix} package. #' @param mode Character scalar, specifies how igraph should interpret the #' supplied matrix. See also the \code{weighted} argument, the interpretation #' depends on that too. Possible values are: \code{directed}, #' \code{undirected}, \code{upper}, \code{lower}, \code{max}, \code{min}, #' \code{plus}. See details below. #' @param weighted This argument specifies whether to create a weighted graph #' from an adjacency matrix. If it is \code{NULL} then an unweighted graph is #' created and the elements of the adjacency matrix gives the number of edges #' between the vertices. If it is a character constant then for every non-zero #' matrix entry an edge is created and the value of the entry is added as an #' edge attribute named by the \code{weighted} argument. If it is \code{TRUE} #' then a weighted graph is created and the name of the edge attribute will be #' \code{weight}. See also details below. #' @param diag Logical scalar, whether to include the diagonal of the matrix in #' the calculation. If this is \code{FALSE} then the diagonal is zerod out #' first. #' @param add.colnames Character scalar, whether to add the column names as #' vertex attributes. If it is \sQuote{\code{NULL}} (the default) then, if #' present, column names are added as vertex attribute \sQuote{name}. If #' \sQuote{\code{NA}} then they will not be added. If a character constant, #' then it gives the name of the vertex attribute to add. #' @param add.rownames Character scalar, whether to add the row names as vertex #' attributes. Possible values the same as the previous argument. By default #' row names are not added. If \sQuote{\code{add.rownames}} and #' \sQuote{\code{add.colnames}} specify the same vertex attribute, then the #' former is ignored. #' @return An igraph graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \link{graph} and \code{\link{graph_from_literal}} for other ways to #' create graphs. #' @keywords graphs #' @examples #' #' adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.9,0.1)), nc=10) #' g1 <- graph_from_adjacency_matrix( adjm ) #' adjm <- matrix(sample(0:5, 100, replace=TRUE, #' prob=c(0.9,0.02,0.02,0.02,0.02,0.02)), nc=10) #' g2 <- graph_from_adjacency_matrix(adjm, weighted=TRUE) #' E(g2)$weight #' #' ## various modes for weighted graphs, with some tests #' nzs <- function(x) sort(x [x!=0]) #' adjm <- matrix(runif(100), 10) #' adjm[ adjm<0.5 ] <- 0 #' g3 <- graph_from_adjacency_matrix((adjm + t(adjm))/2, weighted=TRUE, #' mode="undirected") #' #' g4 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="max") #' all(nzs(pmax(adjm, t(adjm))[upper.tri(adjm)]) == sort(E(g4)$weight)) #' #' g5 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="min") #' all(nzs(pmin(adjm, t(adjm))[upper.tri(adjm)]) == sort(E(g5)$weight)) #' #' g6 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="upper") #' all(nzs(adjm[upper.tri(adjm)]) == sort(E(g6)$weight)) #' #' g7 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="lower") #' all(nzs(adjm[lower.tri(adjm)]) == sort(E(g7)$weight)) #' #' g8 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="plus") #' d2 <- function(x) { diag(x) <- diag(x)/2; x } #' all(nzs((d2(adjm+t(adjm)))[lower.tri(adjm)]) == sort(E(g8)$weight)) #' #' g9 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, mode="plus", diag=FALSE) #' d0 <- function(x) { diag(x) <- 0 } #' all(nzs((d0(adjm+t(adjm)))[lower.tri(adjm)]) == sort(E(g9)$weight)) #' #' ## row/column names #' rownames(adjm) <- sample(letters, nrow(adjm)) #' colnames(adjm) <- seq(ncol(adjm)) #' g10 <- graph_from_adjacency_matrix(adjm, weighted=TRUE, add.rownames="code") #' summary(g10) #' graph_from_adjacency_matrix <- function(adjmatrix, mode=c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted=NULL, diag=TRUE, add.colnames=NULL, add.rownames=NA) { if (inherits(adjmatrix, "Matrix")) { res <- graph.adjacency.sparse(adjmatrix, mode=mode, weighted=weighted, diag=diag) } else { res <- graph.adjacency.dense(adjmatrix, mode=mode, weighted=weighted, diag=diag) } ## Add columns and row names as attributes if (is.null(add.colnames)) { if (!is.null(colnames(adjmatrix))) { add.colnames <- "name" } else { add.colnames <- NA } } else if (!is.na(add.colnames)) { if (is.null(colnames(adjmatrix))) { warning("No column names to add") add.colnames <- NA } } if (is.null(add.rownames)) { if (!is.null(rownames(adjmatrix))) { add.rownames <- "name" } else { add.colnames <- NA } } else if (!is.na(add.rownames)) { if (is.null(rownames(adjmatrix))) { warning("No row names to add") add.rownames <- NA } } if (!is.na(add.rownames) && !is.na(add.colnames) && add.rownames == add.colnames ) { warning("Same attribute for columns and rows, row names are ignored") add.rownames <- NA } if (!is.na(add.colnames)) { res <- set_vertex_attr(res, add.colnames, value=colnames(adjmatrix)) } if (!is.na(add.rownames)) { res <- set_vertex_attr(res, add.rownames, value=rownames(adjmatrix)) } res } #' @rdname graph_from_adjacency_matrix #' @param ... Passed to \code{graph_from_adjacency_matrix}. #' @export from_adjacency <- function(...) constructor_spec(graph_from_adjacency_matrix, ...) igraph/R/operators.R0000644000175100001440000011515513177712334014124 0ustar hornikusers# IGraph R package # Copyright (C) 2006-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### rename.attr.if.needed <- function(type, graphs, newsize=NULL, maps=NULL, maps2=NULL, ignore=character()) { listfun <- switch(type, "g"=graph_attr_names, "v"=vertex_attr_names, "e"=edge_attr_names, stop("Internal igraph error")) getfun <- switch(type, "g"=graph_attr, "v"=vertex_attr, "e"=edge_attr, stop("Internal igraph error")) alist <- lapply(graphs, listfun) an <- unique(unlist(alist)) an <- setdiff(an, ignore) getval <- function(which, name) { newval <- getfun(graphs[[which]], name) if (!is.null(maps)) { tmpval <- newval[ maps[[which]] >= 0 ] mm <- maps[[which]][ maps[[which]] >= 0 ] + 1 newval <- rep(NA, newsize) newval[mm] <- tmpval } if (!is.null(maps2)) { newval <- newval[ maps2[[which]] + 1 ] } if (!is.null(newsize)) { length(newval) <- newsize } newval } attr <- list() for (name in an) { w <- which(sapply(alist, function(x) name %in% x)) if (length(w)==1) { attr[[name]] <- getval(w, name) } else { for (w2 in w) { nname <- paste(name, sep="_", w2) newval <- getval(w2, name) attr[[nname]] <-newval } } } attr } #' Disjoint union of graphs #' #' The union of two or more graphs are created. The graphs are assumed to have #' disjoint vertex sets. #' #' \code{disjoint_union} creates a union of two or more disjoint graphs. #' Thus first the vertices in the second, third, etc. graphs are relabeled to #' have completely disjoint graphs. Then a simple union is created. This #' function can also be used via the \%du\% operator. #' #' \code{graph.disjont.union} handles graph, vertex and edge attributes. In #' particular, it merges vertex and edge attributes using the basic \code{c()} #' function. For graphs that lack some vertex/edge attribute, the corresponding #' values in the new graph are set to \code{NA}. Graph attributes are simply #' copied to the result. If this would result a name clash, then they are #' renamed by adding suffixes: _1, _2, etc. #' #' Note that if both graphs have vertex names (ie. a \code{name} vertex #' attribute), then the concatenated vertex names might be non-unique in the #' result. A warning is given if this happens. #' #' An error is generated if some input graphs are directed and others are #' undirected. #' #' @aliases graph.disjoint.union %du% #' @param \dots Graph objects or lists of graph objects. #' @param x,y Graph objects. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' ## A star and a ring #' g1 <- make_star(10, mode="undirected") #' V(g1)$name <- letters[1:10] #' g2 <- make_ring(10) #' V(g2)$name <- letters[11:20] #' print_all(g1 %du% g2) #' @export disjoint_union <- function(...) { graphs <- unlist(recursive=FALSE, lapply(list(...), function(l) { if (is_igraph(l)) list(l) else l } )) if (!all(sapply(graphs, is_igraph))) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_disjoint_union, graphs) ## Graph attributes graph.attributes(res) <- rename.attr.if.needed("g", graphs) ## Vertex attributes attr <- list() vc <- sapply(graphs, vcount) cumvc <- c(0, cumsum(vc)) for (i in seq_along(graphs)) { va <- vertex.attributes(graphs[[i]]) exattr <- intersect(names(va), names(attr)) # existing and present noattr <- setdiff(names(attr), names(va)) # existint and missing newattr <- setdiff(names(va), names(attr)) # new for (a in seq_along(exattr)) { attr[[ exattr[a] ]] <- c(attr[[ exattr[a] ]], va[[ exattr[a] ]]) } for (a in seq_along(noattr)) { attr[[ noattr[a] ]] <- c(attr[[ noattr[a] ]], rep(NA, vc[i])) } for (a in seq_along(newattr)) { attr[[ newattr[a] ]] <- c(rep(NA, cumvc[i]), va[[ newattr[a] ]]) } } vertex.attributes(res) <- attr if ("name" %in% names(attr) && any(duplicated(attr$name))) { warning("Duplicate vertex names in disjoint union") } ## Edge attributes attr <- list() ec <- sapply(graphs, ecount) cumec <- c(0, cumsum(ec)) for (i in seq_along(graphs)) { ea <- edge.attributes(graphs[[i]]) exattr <- intersect(names(ea), names(attr)) # existing and present noattr <- setdiff(names(attr), names(ea)) # existint and missing newattr <- setdiff(names(ea), names(attr)) # new for (a in seq_along(exattr)) { attr[[ exattr[a] ]] <- c(attr[[ exattr[a] ]], ea[[ exattr[a] ]]) } for (a in seq_along(noattr)) { attr[[ noattr[a] ]] <- c(attr[[ noattr[a] ]], rep(NA, ec[i])) } for (a in seq_along(newattr)) { attr[[ newattr[a] ]] <- c(rep(NA, cumec[i]), ea[[ newattr[a] ]]) } } edge.attributes(res) <- attr res } #' @export #' @rdname disjoint_union "%du%" <- function(x,y) { disjoint_union(x,y) } .igraph.graph.union.or.intersection <- function(call, ..., byname, keep.all.vertices) { graphs <- unlist(recursive=FALSE, lapply(list(...), function(l) { if (is_igraph(l)) list(l) else l } )) if (!all(sapply(graphs, is_igraph))) { stop("Not a graph object") } if (byname != "auto" && !is.logical(byname)) { stop("`bynam' must be \"auto\", or logical") } nonamed <- sum(sapply(graphs, is_named)) if (byname == "auto") { byname <- all(sapply(graphs, is_named)) if (nonamed != 0 && nonamed != length(graphs)) { warning("Some, but not all graphs are named, not using vertex names") } } else if (byname && nonamed != length(graphs)) { stop("Some graphs are not named") } edgemaps <- length(unlist(lapply(graphs, edge_attr_names))) != 0 if (byname) { allnames <- lapply(graphs, vertex_attr, "name") if (keep.all.vertices) { uninames <- unique(unlist(allnames)) newgraphs <- lapply(graphs, function(g) { g <- g + setdiff(uninames, V(g)$name) permute(g, match(V(g)$name, uninames)) }) } else { uninames <- Reduce(intersect, allnames) newgraphs <- lapply(graphs, function(g) { g <- g - setdiff(V(g)$name, uninames) permute(g, match(V(g)$name, uninames)) }) } on.exit( .Call(C_R_igraph_finalizer) ) if (call == "union") { res <- .Call(C_R_igraph_union, newgraphs, edgemaps) } else { res <- .Call(C_R_igraph_intersection, newgraphs, edgemaps) } maps <- res$edgemaps res <- res$graph ## We might need to rename all attributes graph.attributes(res) <- rename.attr.if.needed("g", newgraphs) vertex.attributes(res) <- rename.attr.if.needed("v", newgraphs, vcount(res), ignore="name") V(res)$name <- uninames ## Edges are a bit more difficult, we need a mapping if (edgemaps) { edge.attributes(res) <- rename.attr.if.needed("e", newgraphs, ecount(res), maps=maps) } } else { if (!keep.all.vertices) { minsize <- min(sapply(graphs, vcount)) graphs <- lapply(graphs, function(g) { vc <- vcount(g) if (vc > minsize) { g <- g - (minsize+1):vc } g }) } on.exit( .Call(C_R_igraph_finalizer) ) if (call == "union") { res <- .Call(C_R_igraph_union, graphs, edgemaps) } else { res <- .Call(C_R_igraph_intersection, graphs, edgemaps) } maps <- res$edgemaps res <- res$graph ## We might need to rename all attributes graph.attributes(res) <- rename.attr.if.needed("g", graphs) vertex.attributes(res) <- rename.attr.if.needed("v", graphs, vcount(res)) ## Edges are a bit more difficult, we need a mapping if (edgemaps) { edge.attributes(res) <- rename.attr.if.needed("e", graphs, ecount(res), maps=maps) } } res } #' Union of two or more sets #' #' This is an S3 generic function. See \code{methods("union")} #' for the actual implementations for various S3 classes. Initially #' it is implemented for igraph graphs and igraph vertex and edge #' sequences. See #' \code{\link{union.igraph}}, and #' \code{\link{union.igraph.vs}}. #' #' @param ... Arguments, their number and interpretation depends on #' the function that implements \code{union}. #' @return Depends on the function that implements this method. #' #' @export union <- function(...) UseMethod("union") #' @method union default #' @export union.default <- function(...) { base::union(...) } #' Union of graphs #' #' The union of two or more graphs are created. The graphs may have identical #' or overlapping vertex sets. #' #' \code{union} creates the union of two or more graphs. Edges which are #' included in at least one graph will be part of the new graph. This function #' can be also used via the \%u\% operator. #' #' If the \code{byname} argument is \code{TRUE} (or \code{auto} and all graphs #' are named), then the operation is performed on symbolic vertex names instead #' of the internal numeric vertex ids. #' #' \code{union} keeps the attributes of all graphs. All graph, vertex and #' edge attributes are copied to the result. If an attribute is present in #' multiple graphs and would result a name clash, then this attribute is #' renamed by adding suffixes: _1, _2, etc. #' #' The \code{name} vertex attribute is treated specially if the operation is #' performed based on symbolic vertex names. In this case \code{name} must be #' present in all graphs, and it is not renamed in the result graph. #' #' An error is generated if some input graphs are directed and others are #' undirected. #' #' @aliases graph.union %u% #' @param \dots Graph objects or lists of graph objects. #' @param byname A logical scalar, or the character scalar \code{auto}. Whether #' to perform the operation based on symbolic vertex names. If it is #' \code{auto}, that means \code{TRUE} if all graphs are named and \code{FALSE} #' otherwise. A warning is generated if \code{auto} and some (but not all) #' graphs are named. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method union igraph #' @export #' @keywords graphs #' @examples #' #' ## Union of two social networks with overlapping sets of actors #' net1 <- graph_from_literal(D-A:B:F:G, A-C-F-A, B-E-G-B, A-B, F-G, #' H-F:G, H-I-J) #' net2 <- graph_from_literal(D-A:F:Y, B-A-X-F-H-Z, F-Y) #' print_all(net1 %u% net2) union.igraph <- function(..., byname="auto") { .igraph.graph.union.or.intersection("union", ..., byname=byname, keep.all.vertices=TRUE) } #' @export "%u%" <- function(x,y) { union(x,y) } #' Intersection of two or more sets #' #' This is an S3 generic function. See \code{methods("intersection")} #' for the actual implementations for various S3 classes. Initially #' it is implemented for igraph graphs and igraph vertex and edge #' sequences. See #' \code{\link{intersection.igraph}}, and #' \code{\link{intersection.igraph.vs}}. #' #' @param ... Arguments, their number and interpretation depends on #' the function that implements \code{intersection}. #' @return Depends on the function that implements this method. #' #' @export intersection <- function(...) UseMethod("intersection") #' Intersection of graphs #' #' The intersection of two or more graphs are created. The graphs may have #' identical or overlapping vertex sets. #' #' \code{intersection} creates the intersection of two or more graphs: #' only edges present in all graphs will be included. The corresponding #' operator is \%s\%. #' #' If the \code{byname} argument is \code{TRUE} (or \code{auto} and all graphs #' are named), then the operation is performed on symbolic vertex names instead #' of the internal numeric vertex ids. #' #' \code{intersection} keeps the attributes of all graphs. All graph, #' vertex and edge attributes are copied to the result. If an attribute is #' present in multiple graphs and would result a name clash, then this #' attribute is renamed by adding suffixes: _1, _2, etc. #' #' The \code{name} vertex attribute is treated specially if the operation is #' performed based on symbolic vertex names. In this case \code{name} must be #' present in all graphs, and it is not renamed in the result graph. #' #' An error is generated if some input graphs are directed and others are #' undirected. #' #' @aliases graph.intersection %s% #' @param \dots Graph objects or lists of graph objects. #' @param byname A logical scalar, or the character scalar \code{auto}. Whether #' to perform the operation based on symbolic vertex names. If it is #' \code{auto}, that means \code{TRUE} if all graphs are named and \code{FALSE} #' otherwise. A warning is generated if \code{auto} and some (but not all) #' graphs are named. #' @param keep.all.vertices Logical scalar, whether to keep vertices that only #' appear in a subset of the input graphs. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method intersection igraph #' @export #' @keywords graphs #' @examples #' #' ## Common part of two social networks #' net1 <- graph_from_literal(D-A:B:F:G, A-C-F-A, B-E-G-B, A-B, F-G, #' H-F:G, H-I-J) #' net2 <- graph_from_literal(D-A:F:Y, B-A-X-F-H-Z, F-Y) #' print_all(net1 %s% net2) intersection.igraph <- function(..., byname="auto", keep.all.vertices=TRUE) { .igraph.graph.union.or.intersection("intersection", ..., byname=byname, keep.all.vertices=keep.all.vertices) } #' @export "%s%" <- function(x,y) { intersection(x,y) } #' Difference of two sets #' #' This is an S3 generic function. See \code{methods("difference")} #' for the actual implementations for various S3 classes. Initially #' it is implemented for igraph graphs (difference of edges in two graphs), #' and igraph vertex and edge sequences. See #' \code{\link{difference.igraph}}, and #' \code{\link{difference.igraph.vs}}. #' #' @param ... Arguments, their number and interpretation depends on #' the function that implements \code{difference}. #' @return Depends on the function that implements this method. #' #' @export difference <- function(...) UseMethod("difference") #' Difference of graphs #' #' The difference of two graphs are created. #' #' \code{difference} creates the difference of two graphs. Only edges #' present in the first graph but not in the second will be be included in the #' new graph. The corresponding operator is \%m\%. #' #' If the \code{byname} argument is \code{TRUE} (or \code{auto} and the graphs #' are all named), then the operation is performed based on symbolic vertex #' names. Otherwise numeric vertex ids are used. #' #' \code{difference} keeps all attributes (graph, vertex and edge) of the #' first graph. #' #' Note that \code{big} and \code{small} must both be directed or both be #' undirected, otherwise an error message is given. #' #' @aliases graph.difference %m% #' @param big The left hand side argument of the minus operator. A directed or #' undirected graph. #' @param small The right hand side argument of the minus operator. A directed #' ot undirected graph. #' @param byname A logical scalar, or the character scalar \code{auto}. Whether #' to perform the operation based on symbolic vertex names. If it is #' \code{auto}, that means \code{TRUE} if both graphs are named and #' \code{FALSE} otherwise. A warning is generated if \code{auto} and one graph, #' but not both graphs are named. #' @param ... Ignored, included for S3 compatibility. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @method difference igraph #' @export #' @keywords graphs #' @examples #' #' ## Create a wheel graph #' wheel <- union(make_ring(10), #' make_star(11, center=11, mode="undirected")) #' V(wheel)$name <- letters[seq_len(vcount(wheel))] #' #' ## Subtract a star graph from it #' sstar <- make_star(6, center=6, mode="undirected") #' V(sstar)$name <- letters[c(1,3,5,7,9,11)] #' G <- wheel %m% sstar #' print_all(G) #' plot(G, layout=layout_nicely(wheel)) difference.igraph <- function(big, small, byname="auto", ...) { if (!is_igraph(big) || !is_igraph(small)) { stop("argument is not a graph") } if (byname != "auto" && !is.logical(byname)) { stop("`bynam' must be \"auto\", or logical") } nonamed <- is_named(big) + is_named(small) if (byname == "auto") { byname <- nonamed == 2 if (nonamed == 1) { warning("One, but not both graphs are named, not using vertex names") } } else if (byname && nonamed != 2) { stop("Some graphs are not named") } if (byname) { bnames <- V(big)$name snames <- V(small)$name if (any(! snames %in% bnames)) { small <- small - setdiff(snames, bnames) snames <- V(small)$name } perm <- match(bnames, snames) if (any(is.na(perm))) { perm[is.na(perm)] <- seq(from=vcount(small)+1, to=vcount(big)) } big <- permute(big, perm) on.exit(.Call(C_R_igraph_finalizer)) res <- .Call(C_R_igraph_difference, big, small) permute(res, match(V(res)$name, bnames)) } else { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_difference, big, small) } } #' @export "%m%" <- function(x,y) { difference(x,y) } #' Complementer of a graph #' #' A complementer graph contains all edges that were not present in the input #' graph. #' #' \code{complementer} creates the complementer of a graph. Only edges #' which are \emph{not} present in the original graph will be included in the #' new graph. #' #' \code{complementer} keeps graph and vertex attriubutes, edge #' attributes are lost. #' #' @aliases graph.complementer #' @param graph The input graph, can be directed or undirected. #' @param loops Logical constant, whether to generate loop edges. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' ## Complementer of a ring #' g <- make_ring(10) #' complementer(g) #' #' ## A graph and its complementer give together the full graph #' g <- make_ring(10) #' gc <- complementer(g) #' gu <- union(g, gc) #' gu #' graph.isomorphic(gu, make_full_graph(vcount(g))) #' complementer <- function(graph, loops=FALSE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_complementer, graph, as.logical(loops)) } #' Compose two graphs as binary relations #' #' Relational composition of two graph. #' #' \code{compose} creates the relational composition of two graphs. The #' new graph will contain an (a,b) edge only if there is a vertex c, such that #' edge (a,c) is included in the first graph and (c,b) is included in the #' second graph. The corresponding operator is \%c\%. #' #' The function gives an error if one of the input graphs is directed and the #' other is undirected. #' #' If the \code{byname} argument is \code{TRUE} (or \code{auto} and the graphs #' are all named), then the operation is performed based on symbolic vertex #' names. Otherwise numeric vertex ids are used. #' #' \code{compose} keeps the attributes of both graphs. All graph, vertex #' and edge attributes are copied to the result. If an attribute is present in #' multiple graphs and would result a name clash, then this attribute is #' renamed by adding suffixes: _1, _2, etc. #' #' The \code{name} vertex attribute is treated specially if the operation is #' performed based on symbolic vertex names. In this case \code{name} must be #' present in both graphs, and it is not renamed in the result graph. #' #' Note that an edge in the result graph corresponds to two edges in the input, #' one in the first graph, one in the second. This mapping is not injective and #' several edges in the result might correspond to the same edge in the first #' (and/or the second) graph. The edge attributes in the result graph are #' updated accordingly. #' #' Also note that the function may generate multigraphs, if there are more than #' one way to find edges (a,b) in g1 and (b,c) in g2 for an edge (a,c) in the #' result. See \code{\link{simplify}} if you want to get rid of the multiple #' edges. #' #' The function may create loop edges, if edges (a,b) and (b,a) are present in #' g1 and g2, respectively, then (a,a) is included in the result. See #' \code{\link{simplify}} if you want to get rid of the self-loops. #' #' @aliases graph.compose %c% #' @param g1 The first input graph. #' @param g2 The second input graph. #' @param byname A logical scalar, or the character scalar \code{auto}. Whether #' to perform the operation based on symbolic vertex names. If it is #' \code{auto}, that means \code{TRUE} if both graphs are named and #' \code{FALSE} otherwise. A warning is generated if \code{auto} and one graph, #' but not both graphs are named. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g1 <- make_ring(10) #' g2 <- make_star(10, mode="undirected") #' gc <- compose(g1, g2) #' print_all(gc) #' print_all(simplify(gc)) #' compose <- function(g1, g2, byname="auto") { if (!is_igraph(g1) || !is_igraph(g2)) { stop("Not a graph object") } if (byname != "auto" && !is.logical(byname)) { stop("`byname' must be \"auto\", or logical") } nonamed <- is_named(g1) + is_named(g2) if (byname == "auto") { byname <- nonamed == 2 if (nonamed == 1) { warning("One, but not both graphs are named, not using vertex names") } } else if (byname && nonamed != 2) { stop("Some graphs are not named") } if (byname) { uninames <- unique(c(V(g1)$name, V(g2)$name)) if (vcount(g1) < length(uninames)) { g1 <- g1 + setdiff(uninames, V(g1)$name) } if (vcount(g2) < length(uninames)) { g2 <- g2 + setdiff(uninames, V(g2)$name) } if (any(uninames != V(g1)$name)) { g1 <- permute(g1, match(V(g1)$name, uninames)) } if (any(uninames != V(g2)$name)) { g2 <- permute(g2, match(V(g2)$name, uninames)) } } edgemaps <- (length(edge_attr_names(g1)) != 0 || length(edge_attr_names(g2)) != 0) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_compose, g1, g2, edgemaps) maps <- list(res$edge_map1, res$edge_map2) res <- res$graph ## We might need to rename all attributes graphs <- list(g1, g2) graph.attributes(res) <- rename.attr.if.needed("g", graphs) if (byname) { vertex.attributes(res) <- rename.attr.if.needed("v", graphs, vcount(res), ignore="name") V(res)$name <- uninames } else { vertex.attributes(res) <- rename.attr.if.needed("v", graphs, vcount(res)) } if (edgemaps) { edge.attributes(res) <- rename.attr.if.needed("e", graphs, ecount(res), maps2=maps) } res } #' @export "%c%" <- function(x,y) { compose(x,y) } #' Helper function for adding and deleting edges #' #' This is a helper function that simplifies adding and deleting #' edges to/from graphs. #' #' \code{edges} is an alias for \code{edge}. #' #' @details #' When adding edges via \code{+}, all unnamed arguments of #' \code{edge} (or \code{edges}) are concatenated, and then passed to #' \code{\link{add_edges}}. They are interpreted as pairs of vertex ids, #' and an edge will added between each pair. Named arguments will be #' used as edge attributes for the new edges. #' #' When deleting edges via \code{-}, all arguments of \code{edge} (or #' \code{edges}) are concatenated via \code{c()} and passed to #' \code{\link{delete_edges}}. #' #' @param ... See details below. #' @return A special object that can be used with together with #' igraph graphs and the plus and minus operators. #' #' @family functions for manipulating graph structure #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_edge_attr("color", value = "red") #' #' g <- g + edge(1, 5, color = "green") + #' edge(2, 6, color = "blue") - #' edge("8|9") #' #' E(g)[[]] #' #' g %>% #' add_layout_(in_circle()) %>% #' plot() #' #' g <- make_ring(10) + edges(1:10) #' plot(g) edge <- function(...) { structure(list(...), class="igraph.edge") } #' @export #' @rdname edge edges <- edge #' Helper function for adding and deleting vertices #' #' This is a helper function that simplifies adding and deleting #' vertices to/from graphs. #' #' \code{vertices} is an alias for \code{vertex}. #' #' @details #' When adding vertices via \code{+}, all unnamed arguments are interpreted #' as vertex names of the new vertices. Named arguments are interpreted as #' vertex attributes for the new vertices. #' #' When deleting vertices via \code{-}, all arguments of \code{vertex} (or #' \code{vertices}) are concatenated via \code{c()} and passed to #' \code{\link{delete_vertices}}. #' #' @param ... See details below. #' @return A special object that can be used with together with #' igraph graphs and the plus and minus operators. #' #' @family functions for manipulating graph structure #' #' @export #' @examples #' g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) + #' vertices('X', 'Y') #' g #' plot(g) vertex <- function(...) { structure(list(...), class="igraph.vertex") } #' @export #' @rdname vertex vertices <- vertex #' Helper function to add or delete edges along a path #' #' This function can be used to add or delete edges that form a path. #' #' @details #' When adding edges via \code{+}, all unnamed arguments are #' concatenated, and each element of a final vector is interpreted #' as a vertex in the graph. For a vector of length \eqn{n+1}, \eqn{n} #' edges are then added, from vertex 1 to vertex 2, from vertex 2 to vertex #' 3, etc. Named arguments will be used as edge attributes for the new #' edges. #' #' When deleting edges, all attributes are concatenated and then passed #' to \code{\link{delete_edges}}. #' #' @param ... See details below. #' @return A special object that can be used together with igraph #' graphs and the plus and minus operators. #' #' @family functions for manipulating graph structure #' #' @export #' @examples #' # Create a (directed) wheel #' g <- make_star(11, center = 1) + path(2:11, 2) #' plot(g) #' #' g <- make_empty_graph(directed = FALSE, n = 10) %>% #' set_vertex_attr("name", value = letters[1:10]) #' #' g2 <- g + path("a", "b", "c", "d") #' plot(g2) #' #' g3 <- g2 + path("e", "f", "g", weight=1:2, color="red") #' E(g3)[[]] #' #' g4 <- g3 + path(c("f", "c", "j", "d"), width=1:3, color="green") #' E(g4)[[]] path <- function(...) { structure(list(...), class="igraph.path") } #' Add vertices, edges or another graph to a graph #' #' @details #' The plus operator can be used to add vertices or edges to graph. #' The actual operation that is performed depends on the type of the #' right hand side argument. #' \itemize{ #' \item If is is another igraph graph object and they are both #' named graphs, then the union of the two graphs are calculated, #' see \code{\link{union}}. #' \item If it is another igraph graph object, but either of the two #' are not named, then the disjoint union of #' the two graphs is calculated, see \code{\link{disjoint_union}}. #' \item If it is a numeric scalar, then the specified number of vertices #' are added to the graph. #' \item If it is a character scalar or vector, then it is interpreted as #' the names of the vertices to add to the graph. #' \item If it is an object created with the \code{\link{vertex}} or #' \code{\link{vertices}} function, then new vertices are added to the #' graph. This form is appropriate when one wants to add some vertex #' attributes as well. The operands of the \code{vertices} function #' specifies the number of vertices to add and their attributes as #' well. #' #' The unnamed arguments of \code{vertices} are concatenated and #' used as the \sQuote{\code{name}} vertex attribute (i.e. vertex #' names), the named arguments will be added as additional vertex #' attributes. Examples: \preformatted{ g <- g + #' vertex(shape="circle", color= "red") #' g <- g + vertex("foo", color="blue") #' g <- g + vertex("bar", "foobar") #' g <- g + vertices("bar2", "foobar2", color=1:2, shape="rectangle")} #' #' \code{vertex} is just an alias to \code{vertices}, and it is #' provided for readability. The user should use it if a single vertex #' is added to the graph. #' #' \item If it is an object created with the \code{\link{edge}} or #' \code{\link{edges}} function, then new edges will be added to the #' graph. The new edges and possibly their attributes can be specified as #' the arguments of the \code{edges} function. #' #' The unnamed arguments of \code{edges} are concatenated and used #' as vertex ids of the end points of the new edges. The named #' arguments will be added as edge attributes. #' #' Examples: \preformatted{ g <- make_empty_graph() + #' vertices(letters[1:10]) + #' vertices("foo", "bar", "bar2", "foobar2") #' g <- g + edge("a", "b") #' g <- g + edges("foo", "bar", "bar2", "foobar2") #' g <- g + edges(c("bar", "foo", "foobar2", "bar2"), color="red", weight=1:2)} #' See more examples below. #' #' \code{edge} is just an alias to \code{edges} and it is provided #' for readability. The user should use it if a single edge is added to #' the graph. #' #' \item If it is an object created with the \code{\link{path}} function, then #' new edges that form a path are added. The edges and possibly their #' attributes are specified as the arguments to the \code{path} #' function. The non-named arguments are concatenated and interpreted #' as the vertex ids along the path. The remaining arguments are added #' as edge attributes. #' #' Examples: \preformatted{ g <- make_empty_graph() + vertices(letters[1:10]) #' g <- g + path("a", "b", "c", "d") #' g <- g + path("e", "f", "g", weight=1:2, color="red") #' g <- g + path(c("f", "c", "j", "d"), width=1:3, color="green")} #' } #' #' It is important to note that, although the plus operator is #' commutative, i.e. is possible to write \preformatted{ graph <- "foo" + make_empty_graph()} #' it is not associative, e.g. \preformatted{ graph <- "foo" + "bar" + make_empty_graph()} #' results a syntax error, unless parentheses are used: \preformatted{ graph <- "foo" + ( "bar" + make_empty_graph() )} #' For clarity, we suggest to always put the graph object on the left #' hand side of the operator: \preformatted{ graph <- make_empty_graph() + "foo" + "bar"} #' #' @param e1 First argument, probably an igraph graph, but see details #' below. #' @param e2 Second argument, see details below. #' #' @family functions for manipulating graph structure #' #' @method + igraph #' @export #' @examples #' # 10 vertices named a,b,c,... and no edges #' g <- make_empty_graph() + vertices(letters[1:10]) #' #' # Add edges to make it a ring #' g <- g + path(letters[1:10], letters[1], color = "grey") #' #' # Add some extra random edges #' g <- g + edges(sample(V(g), 10, replace = TRUE), color = "red") #' g$layout <- layout_in_circle #' plot(g) `+.igraph` <- function(e1, e2) { if (!is_igraph(e1) && is_igraph(e2)) { tmp <- e1 e1 <- e2 e2 <- tmp } if (is_igraph(e2) && is_named(e1) && is_named(e2)) { ## Union of graphs res <- union(e1, e2) } else if (is_igraph(e2)) { ## Disjoint union of graphs res <- disjoint_union(e1,e2) } else if ("igraph.edge" %in% class(e2)) { ## Adding edges, possibly with attributes ## Non-named arguments define the edges if (is.null(names(e2))) { toadd <- unlist(e2, recursive=FALSE) attr <- list() } else { toadd <- unlist(e2[names(e2)==""]) attr <- e2[names(e2)!=""] } res <- add_edges(e1, as.igraph.vs(e1, toadd), attr=attr) } else if ("igraph.vertex" %in% class(e2)) { ## Adding vertices, possibly with attributes ## If there is a single unnamed argument, that contains the vertex names wn <- which(names(e2)=="") if (length(wn)==1) { names(e2)[wn] <- "name" } else if (is.null(names(e2))) { ## No names at all, everything is a vertex name e2 <- list(name=unlist(e2, recursive=FALSE)) } else if (length(wn)==0) { ## If there are no non-named arguments, we are fine } else { ## Otherwise, all unnamed arguments are collected and used as ## vertex names nn <- unlist(e2[wn], recursive=FALSE) e2 <- c(list(name=nn), e2[names(e2)!=""]) } la <- unique(sapply(e2, length)) res <- add_vertices(e1, la, attr=e2) } else if ("igraph.path" %in% class(e2)) { ## Adding edges along a path, possibly with attributes ## Non-named arguments define the edges if (is.null(names(e2))) { toadd <- unlist(e2, recursive=FALSE) attr <- list() } else { toadd <- unlist(e2[names(e2)==""]) attr <- e2[names(e2)!=""] } toadd <- as.igraph.vs(e1, toadd) lt <- length(toadd) if (lt >= 2) { toadd <- c(toadd[1], rep(toadd[2:(lt-1)], each=2), toadd[lt]) res <- add_edges(e1, toadd, attr=attr) } else { res <- e1 } } else if (is.numeric(e2) && length(e2)==1) { ## Adding some isolate vertices res <- add_vertices(e1, e2) } else if (is.character(e2)) { ## Adding named vertices res <- add_vertices(e1, length(e2), name=e2) } else { stop("Cannot add unknown type to igraph graph") } res } #' Delete vertices or edges from a graph #' #' @details #' The minus operator (\sQuote{\code{-}}) can be used to remove vertices #' or edges from the graph. The operation performed is selected based on #' the type of the right hand side argument: #' \itemize{ #' \item If it is an igraph graph object, then the difference of the #' two graphs is calculated, see \code{\link{difference}}. #' \item If it is a numeric or character vector, then it is interpreted #' as a vector of vertex ids and the specified vertices will be #' deleted from the graph. Example: \preformatted{ g <- make_ring(10) #' V(g)$name <- letters[1:10] #' g <- g - c("a", "b")} #' \item If \code{e2} is a vertex sequence (e.g. created by the #' \code{\link{V}} function), then these vertices will be deleted from #' the graph. #' \item If it is an edge sequence (e.g. created by the \code{\link{E}} #' function), then these edges will be deleted from the graph. #' \item If it is an object created with the \code{\link{vertex}} (or the #' \code{\link{vertices}}) function, then all arguments of \code{\link{vertices}} are #' concatenated and the result is interpreted as a vector of vertex #' ids. These vertices will be removed from the graph. #' \item If it is an object created with the \code{\link{edge}} (or the #' \code{\link{edges}}) function, then all arguments of \code{\link{edges}} are #' concatenated and then interpreted as edges to be removed from the #' graph. #' Example: \preformatted{ g <- make_ring(10) #' V(g)$name <- letters[1:10] #' E(g)$name <- LETTERS[1:10] #' g <- g - edge("e|f") #' g <- g - edge("H")} #' \item If it is an object created with the \code{\link{path}} function, #' then all \code{\link{path}} arguments are concatenated and then interpreted #' as a path along which edges will be removed from the graph. #' Example: \preformatted{ g <- make_ring(10) #' V(g)$name <- letters[1:10] #' g <- g - path("a", "b", "c", "d")} #' } #' #' @param e1 Left argument, see details below. #' @param e2 Right argument, see details below. #' @return An igraph graph. #' #' @family functions for manipulating graph structure #' @name igraph-minus #' #' @method - igraph #' @export `-.igraph` <- function(e1, e2) { if (missing(e2)) { stop("Non-numeric argument to negation operator") } if (is_igraph(e2)) { res <- difference(e1, e2) } else if ("igraph.vertex" %in% class(e2)) { res <- delete_vertices(e1, unlist(e2, recursive=FALSE)) } else if ("igraph.edge" %in% class(e2)) { res <- delete_edges(e1, unlist(e2, recursive=FALSE)) } else if ("igraph.path" %in% class(e2)) { todel <- unlist(e2, recursive=FALSE) lt <- length(todel) if (lt >= 2) { todel <- paste(todel[-lt], todel[-1], sep="|") res <- delete_edges(e1, todel) } else { res <- e1 } } else if ("igraph.vs" %in% class(e2)) { res <- delete_vertices(e1, e2) } else if ("igraph.es" %in% class(e2)) { res <- delete_edges(e1, e2) } else if (is.numeric(e2) || is.character(e2)) { res <- delete_vertices(e1, e2) } else { stop("Cannot substract unknown type from igraph graph") } res } #' Replicate a graph multiple times #' #' The new graph will contain the input graph the given number #' of times, as unconnected components. #' #' @param x The input graph. #' @param n Number of times to replicate it. #' @param mark Whether to mark the vertices with a \code{which} attribute, #' an integer number denoting which replication the vertex is coming #' from. #' @param ... Additional arguments to satisfy S3 requirements, #' currently ignored. #' #' @method rep igraph #' @export #' #' @examples #' rings <- make_ring(5) * 5 rep.igraph <- function(x, n, mark = TRUE, ...) { if (n < 0) stop("Number of replications must be positive") res <- do_call(disjoint_union, .args = replicate(n, x, simplify = FALSE)) if (mark) V(res)$which <- rep(seq_len(n), each = gorder(x)) res } #' @rdname rep.igraph #' @method * igraph #' @export `*.igraph` <- function(x, n) { if (!is_igraph(x) && is_igraph(n)) { tmp <- x x <- n n <- tmp } if (is.numeric(n) && length(n) == 1) { rep.igraph(x, n) } else { stop("Cannot multiply igraph graph with this type") } } igraph/R/centralization.R0000644000175100001440000003153313240142531015114 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' @include auto.R NULL #' Centralization of a graph #' #' Centralization is a method for creating a graph level centralization #' measure from the centrality scores of the vertices. #' #' Centralization is a general method for calculating a graph-level #' centrality score based on node-level centrality measure. The formula for #' this is #' \deqn{C(G)=\sum_v (\max_w c_w - c_v),}{ C(G)=sum( max(c(w), w) - c(v),v),} #' where \eqn{c_v}{c(v)} is the centrality of vertex \eqn{v}. #' #' The graph-level centrality score can be normalized by dividing by the #' maximum theoretical score for a graph with the same number of vertices, #' using the same parameters, e.g. directedness, whether we consider loop #' edges, etc. #' #' For degree, closeness and betweenness the most centralized structure is #' some version of the star graph, in-star, out-star or undirected star. #' #' For eigenvector centrality the most centralized structure is the graph #' with a single edge (and potentially many isolates). #' #' \code{centralize} implements general centralization formula to calculate #' a graph-level score from vertex-level scores. #' #' @param scores The vertex level centrality scores. #' @param theoretical.max Real scalar. The graph level centrality score of #' the most centralized graph with the same number of vertices as the graph #' under study. This is only used if the \code{normalized} argument is set #' to \code{TRUE}. #' @param normalized Logical scalar. Whether to normalize the graph level #' centrality score by dividing by the supplied theoretical maximum. #' @return A real scalar, the centralization of the graph from which #' \code{scores} were derived. #' #' @aliases centralization centralize.scores #' @family centralization related #' #' @export #' @references Freeman, L.C. (1979). Centrality in Social Networks I: #' Conceptual Clarification. \emph{Social Networks} 1, 215--239. #' #' Wasserman, S., and Faust, K. (1994). \emph{Social Network Analysis: #' Methods and Applications.} Cambridge University Press. #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m=4) #' centr_degree(g)$centralization #' centr_clo(g, mode="all")$centralization #' centr_eigen(g, directed=FALSE)$centralization #' #' # The most centralized graph according to eigenvector centrality #' g0 <- graph( c(2,1), n=10, dir=FALSE ) #' g1 <- make_star(10, mode="undirected") #' centr_eigen(g0)$centralization #' centr_eigen(g1)$centralization centralize <- centralize #' Centralize a graph according to the degrees of vertices #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. #' @param mode This is the same as the \code{mode} argument of #' \code{degree}. #' @param loops Logical scalar, whether to consider loops edges when #' calculating the degree. #' @param normalized Logical scalar. Whether to normalize the graph level #' centrality score by dividing by the theoretical maximum. #' @return A named list with the following components: #' \item{res}{The node-level centrality scores.} #' \item{centralization}{The graph level centrality index.} #' \item{theoretical_max}{The maximum theoretical graph level #' centralization score for a graph with the given number of vertices, #' using the same parameters. If the \code{normalized} argument was #' \code{TRUE}, then the result was divided by this number.} #' #' @aliases centralization.degree #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_degree(g)$centralization #' centr_clo(g, mode = "all")$centralization #' centr_betw(g, directed = FALSE)$centralization #' centr_eigen(g, directed = FALSE)$centralization centr_degree <- centr_degree #' Theoretical maximum for degree centralization #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. It can also be \code{NULL}, if #' \code{nodes}, \code{mode} and \code{loops} are all given. #' @param nodes The number of vertices. This is ignored if the graph is given. #' @param mode This is the same as the \code{mode} argument of #' \code{degree}. #' @param loops Logical scalar, whether to consider loops edges when #' calculating the degree. #' @return Real scalar, the theoratical maximum (unnormalized) graph degree #' centrality score for graphs with given order and other parameters. #' #' @aliases centralization.degree.tmax #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_degree(g, normalized = FALSE)$centralization %>% #' `/`(centr_degree_tmax(g)) #' centr_degree(g, normalized = TRUE)$centralization centr_degree_tmax <- centr_degree_tmax #' Centralize a graph according to the betweenness of vertices #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. #' @param directed logical scalar, whether to use directed shortest paths for #' calculating betweenness. #' @param nobigint Logical scalar, whether to use big integers for the #' betweenness calculation. This argument is passed to the #' \code{\link{betweenness}} function. #' @param normalized Logical scalar. Whether to normalize the graph level #' centrality score by dividing by the theoretical maximum. #' @return A named list with the following components: #' \item{res}{The node-level centrality scores.} #' \item{centralization}{The graph level centrality index.} #' \item{theoretical_max}{The maximum theoretical graph level #' centralization score for a graph with the given number of vertices, #' using the same parameters. If the \code{normalized} argument was #' \code{TRUE}, then the result was divided by this number.} #' #' @aliases centralization.betweenness #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_degree(g)$centralization #' centr_clo(g, mode = "all")$centralization #' centr_betw(g, directed = FALSE)$centralization #' centr_eigen(g, directed = FALSE)$centralization centr_betw <- centr_betw #' Theoretical maximum for betweenness centralization #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. It can also be \code{NULL}, if #' \code{nodes} is given. #' @param nodes The number of vertices. This is ignored if the graph is #' given. #' @param directed logical scalar, whether to use directed shortest paths #' for calculating betweenness. #' @return Real scalar, the theoratical maximum (unnormalized) graph #' betweenness centrality score for graphs with given order and other #' parameters. #' #' @aliases centralization.betweenness.tmax #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_betw(g, normalized = FALSE)$centralization %>% #' `/`(centr_betw_tmax(g)) #' centr_betw(g, normalized = TRUE)$centralization centr_betw_tmax <- centr_betw_tmax #' Centralize a graph according to the closeness of vertices #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. #' @param mode This is the same as the \code{mode} argument of #' \code{closeness}. #' @param normalized Logical scalar. Whether to normalize the graph level #' centrality score by dividing by the theoretical maximum. #' @return A named list with the following components: #' \item{res}{The node-level centrality scores.} #' \item{centralization}{The graph level centrality index.} #' \item{theoretical_max}{The maximum theoretical graph level #' centralization score for a graph with the given number of vertices, #' using the same parameters. If the \code{normalized} argument was #' \code{TRUE}, then the result was divided by this number.} #' #' @aliases centralization.closeness #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_degree(g)$centralization #' centr_clo(g, mode = "all")$centralization #' centr_betw(g, directed = FALSE)$centralization #' centr_eigen(g, directed = FALSE)$centralization centr_clo <- centr_clo #' Theoretical maximum for closeness centralization #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. It can also be \code{NULL}, if #' \code{nodes} is given. #' @param nodes The number of vertices. This is ignored if the graph is #' given. #' @param mode This is the same as the \code{mode} argument of #' \code{closeness}. #' @return Real scalar, the theoratical maximum (unnormalized) graph #' closeness centrality score for graphs with given order and other #' parameters. #' #' @aliases centralization.closeness.tmax #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_clo(g, normalized = FALSE)$centralization %>% #' `/`(centr_clo_tmax(g)) #' centr_clo(g, normalized = TRUE)$centralization centr_clo_tmax <- centr_clo_tmax #' Centralize a graph according to the eigenvector centrality of vertices #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. #' @param directed logical scalar, whether to use directed shortest paths for #' calculating eigenvector centrality. #' @param scale Whether to rescale the eigenvector centrality scores, such that #' the maximum score is one. #' @param options This is passed to \code{\link{eigen_centrality}}, the options #' for the ARPACK eigensolver. #' @param normalized Logical scalar. Whether to normalize the graph level #' centrality score by dividing by the theoretical maximum. #' @return A named list with the following components: #' \item{vector}{The node-level centrality scores.} #' \item{value}{The corresponding eigenvalue.} #' \item{options}{ARPACK options, see the return value of #' \code{\link{eigen_centrality}} for details.} #' \item{centralization}{The graph level centrality index.} #' \item{theoretical_max}{The same as above, the theoretical maximum #' centralization score for a graph with the same number of vertices.} #' #' @aliases centralization.evcent #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_degree(g)$centralization #' centr_clo(g, mode = "all")$centralization #' centr_betw(g, directed = FALSE)$centralization #' centr_eigen(g, directed = FALSE)$centralization #' #' # The most centralized graph according to eigenvector centrality #' g0 <- make_graph(c(2,1), n = 10, dir = FALSE) #' g1 <- make_star(10, mode = "undirected") #' centr_eigen(g0)$centralization #' centr_eigen(g1)$centralization centr_eigen <- centr_eigen #' Theoretical maximum for betweenness centralization #' #' See \code{\link{centralize}} for a summary of graph centralization. #' #' @param graph The input graph. It can also be \code{NULL}, if #' \code{nodes} is given. #' @param nodes The number of vertices. This is ignored if the graph is #' given. #' @param directed logical scalar, whether to use directed shortest paths #' for calculating betweenness. #' @param scale Whether to rescale the eigenvector centrality scores, #' such that the maximum score is one. #' @return Real scalar, the theoratical maximum (unnormalized) graph #' betweenness centrality score for graphs with given order and other #' parameters. #' #' @aliases centralization.evcent.tmax #' @family centralization related #' #' @export #' #' @examples #' # A BA graph is quite centralized #' g <- sample_pa(1000, m = 4) #' centr_eigen(g, normalized = FALSE)$centralization %>% #' `/`(centr_eigen_tmax(g)) #' centr_eigen(g, normalized = TRUE)$centralization centr_eigen_tmax <- centr_eigen_tmax igraph/R/conversion.R0000644000175100001440000007445013247066747014305 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### get.adjacency.dense <- function(graph, type=c("both", "upper", "lower"), attr=NULL, edges=FALSE, names=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } type <- igraph.match.arg(type) type <- switch(type, "upper"=0, "lower"=1, "both"=2) if (edges || is.null(attr)) { on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_adjacency, graph, as.numeric(type), as.logical(edges)) } else { attr <- as.character(attr) if (! attr %in% edge_attr_names(graph)) { stop("no such edge attribute") } exattr <- edge_attr(graph, attr) if (is.logical(exattr)) { res <- matrix(FALSE, nrow=vcount(graph), ncol=vcount(graph)) } else if (is.character(exattr)) { res <- matrix("", nrow=vcount(graph), ncol=vcount(graph)) } else if (is.numeric(exattr)) { res <- matrix(0, nrow=vcount(graph), ncol=vcount(graph)) } else { stop("Sparse matrices must be either numeric or logical,", "and the edge attribute is not") } if (is_directed(graph)) { for (i in seq(length=ecount(graph))) { e <- ends(graph, i, names = FALSE) res[ e[1], e[2] ] <- edge_attr(graph, attr, i) } } else { if (type==0) { ## upper for (i in seq(length=ecount(graph))) { e <- ends(graph, i, names = FALSE) res[ min(e), max(e) ] <- edge_attr(graph, attr, i) } } else if (type==1) { ## lower for (i in seq(length=ecount(graph))) { e <- ends(graph, i, names = FALSE) res[ max(e), min(e) ] <- edge_attr(graph, attr, i) } } else if (type==2) { ## both for (i in seq(length=ecount(graph))) { e <- ends(graph, i, names = FALSE) res[ e[1], e[2] ] <- edge_attr(graph, attr, i) if (e[1] != e[2]) { res[ e[2], e[1] ] <- edge_attr(graph, attr, i) } } } } } if (names && "name" %in% vertex_attr_names(graph)) { colnames(res) <- rownames(res) <- V(graph)$name } res } get.adjacency.sparse <- function(graph, type=c("both", "upper", "lower"), attr=NULL, edges=FALSE, names=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } type <- igraph.match.arg(type) vc <- vcount(graph) el <- as_edgelist(graph, names=FALSE) if (edges) { value <- seq_len(nrow(el)) } else if (!is.null(attr)) { attr <- as.character(attr) if (!attr %in% edge_attr_names(graph)) { stop("no such edge attribute") } value <- edge_attr(graph, name=attr) if (!is.numeric(value) && !is.logical(value)) { stop("Sparse matrices must be either numeric or logical,", "and the edge attribute is not") } } else { value <- rep(1, nrow(el)) } if (is_directed(graph)) { res <- Matrix::sparseMatrix(dims=c(vc, vc), i=el[,1], j=el[,2], x=value) } else { if (type=="upper") { ## upper res <- Matrix::sparseMatrix(dims=c(vc, vc), i=pmin(el[,1],el[,2]), j=pmax(el[,1],el[,2]), x=value) } else if (type=="lower") { ## lower res <- Matrix::sparseMatrix(dims=c(vc, vc), i=pmax(el[,1],el[,2]), j=pmin(el[,1],el[,2]), x=value) } else if (type=="both") { ## both res <- Matrix::sparseMatrix(dims=c(vc, vc), i=pmin(el[,1],el[,2]), j=pmax(el[,1],el[,2]), x=value, symmetric=TRUE) res <- as(res, "dgCMatrix") } } if (names && "name" %in% vertex_attr_names(graph)) { colnames(res) <- rownames(res) <- V(graph)$name } res } #' Convert a graph to an adjacency matrix #' #' Sometimes it is useful to work with a standard representation of a #' graph, like an adjacency matrix. #' #' \code{as_adjacency_matrix} returns the adjacency matrix of a graph, a #' regular matrix if \code{sparse} is \code{FALSE}, or a sparse matrix, as #' defined in the \sQuote{\code{Matrix}} package, if \code{sparse} if #' \code{TRUE}. #' #' @aliases get.adjacency #' @param graph The graph to convert. #' @param type Gives how to create the adjacency matrix for undirected graphs. #' It is ignored for directed graphs. Possible values: \code{upper}: the upper #' right triangle of the matrix is used, \code{lower}: the lower left triangle #' of the matrix is used. \code{both}: the whole matrix is used, a symmetric #' matrix is returned. #' @param attr Either \code{NULL} or a character string giving an edge #' attribute name. If \code{NULL} a traditional adjacency matrix is returned. #' If not \code{NULL} then the values of the given edge attribute are included #' in the adjacency matrix. If the graph has multiple edges, the edge attribute #' of an arbitrarily chosen edge (for the multiple edges) is included. This #' argument is ignored if \code{edges} is \code{TRUE}. #' #' Note that this works only for certain attribute types. If the \code{sparse} #' argumen is \code{TRUE}, then the attribute must be either logical or #' numeric. If the \code{sparse} argument is \code{FALSE}, then character is #' also allowed. The reason for the difference is that the \code{Matrix} #' package does not support character sparse matrices yet. #' @param edges Logical scalar, whether to return the edge ids in the matrix. #' For non-existant edges zero is returned. #' @param names Logical constant, whether to assign row and column names #' to the matrix. These are only assigned if the \code{name} vertex attribute #' is present in the graph. #' @param sparse Logical scalar, whether to create a sparse matrix. The #' \sQuote{\code{Matrix}} package must be installed for creating sparse #' matrices. #' @return A \code{vcount(graph)} by \code{vcount(graph)} (usually) numeric #' matrix. #' #' @seealso \code{\link{graph_from_adjacency_matrix}}, \code{\link{read_graph}} #' @examples #' #' g <- sample_gnp(10, 2/10) #' as_adjacency_matrix(g) #' V(g)$name <- letters[1:vcount(g)] #' as_adjacency_matrix(g) #' E(g)$weight <- runif(ecount(g)) #' as_adjacency_matrix(g, attr="weight") #' @export as_adjacency_matrix <- function(graph, type=c("both", "upper", "lower"), attr=NULL, edges=FALSE, names=TRUE, sparse=igraph_opt("sparsematrices")) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!sparse) { get.adjacency.dense(graph, type=type, attr=attr, edges=edges, names=names) } else { get.adjacency.sparse(graph, type=type, attr=attr, edges=edges, names=names) } } #' @export #' @rdname as_adjacency_matrix as_adj <- as_adjacency_matrix #' Convert a graph to an edge list #' #' Sometimes it is useful to work with a standard representation of a #' graph, like an edge list. #' #' \code{as_edgelist} returns the list of edges in a graph. #' #' @aliases get.edgelist #' @param graph The graph to convert. #' @param names Whether to return a character matrix containing vertex #' names (ie. the \code{name} vertex attribute) if they exist or numeric #' vertex ids. #' @return A \code{gsize(graph)} by 2 numeric matrix. #' @seealso \code{\link{graph_from_adjacency_matrix}}, \code{\link{read_graph}} #' @keywords graphs #' @examples #' #' g <- sample_gnp(10, 2/10) #' as_edgelist(g) #' #' V(g)$name <- LETTERS[seq_len(gorder(g))] #' as_edgelist(g) #' #' @export as_edgelist <- function(graph, names=TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } on.exit( .Call(C_R_igraph_finalizer) ) res <- matrix(.Call(C_R_igraph_get_edgelist, graph, TRUE), ncol=2) res <- res+1 if (names && "name" %in% vertex_attr_names(graph)) { res <- matrix(V(graph)$name[ res ], ncol=2) } res } #' Convert between directed and undirected graphs #' #' \code{as.directed} converts an undirected graph to directed, #' \code{as.undirected} does the opposite, it converts a directed graph to #' undirected. #' #' Conversion algorithms for \code{as.directed}: \describe{ #' \item{"arbitrary"}{The number of edges in the graph stays the same, an #' arbitrarily directed edge is created for each undirected edge.} #' \item{"mutual"}{Two directed edges are created for each undirected #' edge, one in each direction.} } #' #' Conversion algorithms for \code{as.undirected}: \describe{ #' \item{"each"}{The number of edges remains constant, an undirected edge #' is created for each directed one, this version might create graphs with #' multiple edges.} \item{"collapse"}{One undirected edge will be created #' for each pair of vertices which are connected with at least one directed #' edge, no multiple edges will be created.} \item{"mutual"}{One #' undirected edge will be created for each pair of mutual edges. Non-mutual #' edges are ignored. This mode might create multiple edges if there are more #' than one mutual edge pairs between the same pair of vertices. } } #' #' @aliases as.directed as.undirected #' @param graph The graph to convert. #' @param mode Character constant, defines the conversion algorithm. For #' \code{as.directed} it can be \code{mutual} or \code{arbitrary}. For #' \code{as.undirected} it can be \code{each}, \code{collapse} or #' \code{mutual}. See details below. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{simplify}} for removing multiple and/or loop edges from #' a graph. #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' as.directed(g, "mutual") #' g2 <- make_star(10) #' as.undirected(g) #' #' # Combining edge attributes #' g3 <- make_ring(10, directed=TRUE, mutual=TRUE) #' E(g3)$weight <- seq_len(ecount(g3)) #' ug3 <- as.undirected(g3) #' print(ug3, e=TRUE) #' \dontrun{ #' x11(width=10, height=5) #' layout(rbind(1:2)) #' plot( g3, layout=layout_in_circle, edge.label=E(g3)$weight) #' plot(ug3, layout=layout_in_circle, edge.label=E(ug3)$weight) #' } #' #' g4 <- graph(c(1,2, 3,2,3,4,3,4, 5,4,5,4, #' 6,7, 7,6,7,8,7,8, 8,7,8,9,8,9, #' 9,8,9,8,9,9, 10,10,10,10)) #' E(g4)$weight <- seq_len(ecount(g4)) #' ug4 <- as.undirected(g4, mode="mutual", #' edge.attr.comb=list(weight=length)) #' print(ug4, e=TRUE) #' as.directed <- function(graph, mode=c("mutual", "arbitrary")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- switch(mode, "arbitrary"=0, "mutual"=1) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_to_directed, graph, as.numeric(mode)) } #' @rdname as.directed #' @param edge.attr.comb Specifies what to do with edge attributes, if #' \code{mode="collapse"} or \code{mode="mutual"}. In these cases many edges #' might be mapped to a single one in the new graph, and their attributes are #' combined. Please see \code{\link{attribute.combination}} for details on #' this. #' @export as.undirected <- function(graph, mode=c("collapse", "each", "mutual"), edge.attr.comb=igraph_opt("edge.attr.comb")) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } mode <- switch(igraph.match.arg(mode), "collapse"=1, "each"=0, "mutual"=2) edge.attr.comb <- igraph.i.attribute.combination(edge.attr.comb) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_to_undirected, graph, mode, edge.attr.comb) res } #' Adjacency lists #' #' Create adjacency lists from a graph, either for adjacent edges or for #' neighboring vertices #' #' \code{as_adj_list} returns a list of numeric vectors, which include the ids #' of neighbor vertices (according to the \code{mode} argument) of all #' vertices. #' #' \code{as_adj_edge_list} returns a list of numeric vectors, which include the #' ids of adjacent edgs (according to the \code{mode} argument) of all #' vertices. #' #' @aliases as_adj_list get.adjedgelist #' @param graph The input graph. #' @param mode Character scalar, it gives what kind of adjacent edges/vertices #' to include in the lists. \sQuote{\code{out}} is for outgoing edges/vertices, #' \sQuote{\code{in}} is for incoming edges/vertices, \sQuote{\code{all}} is #' for both. This argument is ignored for undirected graphs. #' @return A list of numeric vectors. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{as_edgelist}}, \code{\link{as_adj}} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' as_adj_list(g) #' as_adj_edge_list(g) #' as_adj_list <- function(graph, mode=c("all", "out", "in", "total")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- as.numeric(switch(mode, "out"=1, "in"=2, "all"=3, "total"=3)) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_adjlist, graph, mode) res <- lapply(res, function(x) V(graph)[x + 1]) if (is_named(graph)) names(res) <- V(graph)$name res } #' @rdname as_adj_list #' @aliases get.adjlist #' @export as_adj_edge_list <- function(graph, mode=c("all", "out", "in", "total")) { if (!is_igraph(graph)) { stop("Not a graph object") } mode <- igraph.match.arg(mode) mode <- as.numeric(switch(mode, "out"=1, "in"=2, "all"=3, "total"=3)) on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_get_adjedgelist, graph, mode) res <- lapply(res, function(x) E(graph)[x + 1]) if (is_named(graph)) names(res) <- V(graph)$name res } #' Convert graphNEL objects from the graph package to igraph #' #' The graphNEL class is defined in the \code{graph} package, it is another #' way to represent graphs. \code{graph_from_graphnel} takes a graphNEL #' graph and converts it to an igraph graph. It handles all #' graph/vertex/edge attributes. If the graphNEL graph has a vertex #' attribute called \sQuote{\code{name}} it will be used as igraph vertex #' attribute \sQuote{\code{name}} and the graphNEL vertex names will be #' ignored. #' #' Because graphNEL graphs poorly support multiple edges, the edge #' attributes of the multiple edges are lost: they are all replaced by the #' attributes of the first of the multiple edges. #' #' @aliases igraph.from.graphNEL #' @param graphNEL The graphNEL graph. #' @param name Logical scalar, whether to add graphNEL vertex names as an #' igraph vertex attribute called \sQuote{\code{name}}. #' @param weight Logical scalar, whether to add graphNEL edge weights as an #' igraph edge attribute called \sQuote{\code{weight}}. (graphNEL graphs are #' always weighted.) #' @param unlist.attrs Logical scalar. graphNEL attribute query functions #' return the values of the attributes in R lists, if this argument is #' \code{TRUE} (the default) these will be converted to atomic vectors, #' whenever possible, before adding them to the igraph graph. #' @return \code{graph_from_graphnel} returns an igraph graph object. #' @seealso \code{\link{as_graphnel}} for the other direction, #' \code{\link{as_adj}}, \code{\link{graph_from_adjacency_matrix}}, #' \code{\link{as_adj_list}} and \code{\link{graph.adjlist}} for other #' graph representations. #' @examples #' \dontrun{ #' ## Undirected #' g <- make_ring(10) #' V(g)$name <- letters[1:10] #' GNEL <- as_graphnel(g) #' g2 <- graph_from_graphnel(GNEL) #' g2 #' #' ## Directed #' g3 <- make_star(10, mode="in") #' V(g3)$name <- letters[1:10] #' GNEL2 <- as_graphnel(g3) #' g4 <- graph_from_graphnel(GNEL2) #' g4 #' } #' @export graph_from_graphnel <- function(graphNEL, name=TRUE, weight=TRUE, unlist.attrs=TRUE) { if (!inherits(graphNEL, "graphNEL")) { stop("Not a graphNEL graph") } al <- lapply(graph::edgeL(graphNEL), "[[", "edges") if (graph::edgemode(graphNEL)=="undirected") { al <- mapply(SIMPLIFY=FALSE, seq_along(al), al, FUN=function(n, l) { c(l, rep(n, sum(l==n))) }) } mode <- if (graph::edgemode(graphNEL)=="directed") "out" else "all" g <- graph_from_adj_list(al, mode=mode, duplicate=TRUE) if (name) { V(g)$name <- graph::nodes(graphNEL) } ## Graph attributes g.n <- names(graphNEL@graphData) g.n <- g.n [ g.n != "edgemode" ] for (n in g.n) { g <- set_graph_attr(g, n, graphNEL@graphData[[n]]) } ## Vertex attributes v.n <- names(graph::nodeDataDefaults(graphNEL)) for (n in v.n) { val <- unname(graph::nodeData(graphNEL, attr=n)) if (unlist.attrs && all(sapply(val, length)==1)) { val <- unlist(val) } g <- set_vertex_attr(g, n, value=val) } ## Edge attributes e.n <- names(graph::edgeDataDefaults(graphNEL)) if (!weight) { e.n <- e.n [ e.n != "weight" ] } if (length(e.n) > 0) { el <- as_edgelist(g) el <- paste(sep="|", el[,1], el[,2]) for (n in e.n) { val <- unname(graph::edgeData(graphNEL, attr=n)[el]) if (unlist.attrs && all(sapply(val, length)==1)) { val <- unlist(val) } g <- set_edge_attr(g, n, value=val) } } g } #' Convert igraph graphs to graphNEL objects from the graph package #' #' The graphNEL class is defined in the \code{graph} package, it is another #' way to represent graphs. These functions are provided to convert between #' the igraph and the graphNEL objects. #' #' \code{as_graphnel} converts an igraph graph to a graphNEL graph. It #' converts all graph/vertex/edge attributes. If the igraph graph has a #' vertex attribute \sQuote{\code{name}}, then it will be used to assign #' vertex names in the graphNEL graph. Otherwise numeric igraph vertex ids #' will be used for this purpose. #' #' @aliases igraph.to.graphNEL #' @param graph An igraph graph object. #' @return \code{as_graphnel} returns a graphNEL graph object. #' @seealso \code{\link{graph_from_graphnel}} for the other direction, #' \code{\link{as_adj}}, \code{\link{graph_from_adjacency_matrix}}, #' \code{\link{as_adj_list}} and \code{\link{graph.adjlist}} for #' other graph representations. #' @examples #' ## Undirected #' \dontrun{ #' g <- make_ring(10) #' V(g)$name <- letters[1:10] #' GNEL <- as_graphnel(g) #' g2 <- graph_from_graphnel(GNEL) #' g2 #' #' ## Directed #' g3 <- make_star(10, mode="in") #' V(g3)$name <- letters[1:10] #' GNEL2 <- as_graphnel(g3) #' g4 <- graph_from_graphnel(GNEL2) #' g4 #' } #' @export as_graphnel <- function(graph) { if (!is_igraph(graph)) { stop("Not an igraph graph") } if ("name" %in% vertex_attr_names(graph) && is.character(V(graph)$name)) { name <- V(graph)$name } else { name <- as.character(seq(vcount(graph))) } edgemode <- if (is_directed(graph)) "directed" else "undirected" if ("weight" %in% edge_attr_names(graph) && is.numeric(E(graph)$weight)) { al <- lapply(as_adj_edge_list(graph, "out"), as.vector) for (i in seq(along=al)) { edges <- ends(graph, al[[i]], names = FALSE) edges <- ifelse( edges[,2]==i, edges[,1], edges[,2]) weights <- E(graph)$weight[al[[i]]] al[[i]] <- list(edges=edges, weights=weights) } } else { al <- as_adj_list(graph, "out") al <- lapply(al, function(x) list(edges=as.vector(x))) } names(al) <- name res <- graph::graphNEL(nodes=name, edgeL=al, edgemode=edgemode) ## Add graph attributes (other than 'directed') ## Are this "officially" supported at all? g.n <- graph_attr_names(graph) if ("directed" %in% g.n) { warning("Cannot add graph attribute `directed'") g.n <- g.n[ g.n != "directed" ] } for (n in g.n) { res@graphData[[n]] <- graph_attr(graph, n) } ## Add vertex attributes (other than 'name', that is already ## added as vertex names) v.n <- vertex_attr_names(graph) v.n <- v.n[ v.n != "name" ] for (n in v.n) { graph::nodeDataDefaults(res, attr=n) <- NA graph::nodeData(res, attr=n) <- vertex_attr(graph, n) } ## Add edge attributes (other than 'weight') e.n <- edge_attr_names(graph) e.n <- e.n[ e.n != "weight" ] if (length(e.n) > 0) { el <- as_edgelist(graph) el <- paste(sep="|", el[,1], el[,2]) for (n in e.n) { graph::edgeDataDefaults(res, attr=n) <- NA res@edgeData@data[el] <- mapply(function(x,y) { xx <- c(x,y); names(xx)[length(xx)] <- n; xx }, res@edgeData@data[el], edge_attr(graph, n), SIMPLIFY=FALSE) } } res } get.incidence.dense <- function(graph, types, names, attr) { if (is.null(attr)) { on.exit( .Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_get_incidence, graph, types) if (names && "name" %in% vertex_attr_names(graph)) { rownames(res$res) <- V(graph)$name[ res$row_ids+1 ] colnames(res$res) <- V(graph)$name[ res$col_ids+1 ] } else { rownames(res$res) <- res$row_ids+1 colnames(res$res) <- res$col_ids+1 } res$res } else { attr <- as.character(attr) if (!attr %in% edge_attr_names(graph)) { stop("no such edge attribute") } vc <- vcount(graph) n1 <- sum(!types) n2 <- vc-n1 res <- matrix(0, n1, n2) recode <- numeric(vc) recode[!types] <- seq_len(n1) recode[types] <- seq_len(n2) for (i in seq(length=ecount(graph))) { eo <- ends(graph, i, names = FALSE) e <- recode[eo] if (!types[eo[1]]) { res[ e[1], e[2] ] <- edge_attr(graph, attr, i) } else{ res[ e[2], e[1] ] <- edge_attr(graph, attr, i) } } if (names && "name" %in% vertex_attr_names(graph)) { rownames(res) <- V(graph)$name[ which(!types) ] colnames(res) <- V(graph)$name[ which( types) ] } else { rownames(res) <- which(!types) colnames(res) <- which(types) } res } } get.incidence.sparse <- function(graph, types, names, attr) { vc <- vcount(graph) if (length(types) != vc) { stop("Invalid types vector") } el <- as_edgelist(graph, names=FALSE) if (any(types[el[,1]] == types[el[,2]])) { stop("Invalid types vector, not a bipartite graph") } n1 <- sum(!types) n2 <- vc-n1 recode <- numeric(vc) recode[!types] <- seq_len(n1) recode[types] <- seq_len(n2) + n1 el[,1] <- recode[el[,1]] el[,2] <- recode[el[,2]] change <- el[,1] > n1 el[change,] <- el[change,2:1] el[,2] <- el[,2]-n1 if (!is.null(attr)) { attr <- as.character(attr) if (!attr %in% edge_attr_names(graph)) { stop("no such edge attribute") } value <- edge_attr(graph, name=attr) } else { value <- rep(1, nrow(el)) } res <- Matrix::spMatrix(n1, n2, i=el[,1], j=el[,2], x=value) if (names && "name" %in% vertex_attr_names(graph)) { rownames(res) <- V(graph)$name[which(!types)] colnames(res) <- V(graph)$name[which(types)] } else { rownames(res) <- which(!types) colnames(res) <- which(types) } res } #' Incidence matrix of a bipartite graph #' #' This function can return a sparse or dense incidence matrix of a bipartite #' network. The incidence matrix is an \eqn{n} times \eqn{m} matrix, \eqn{n} #' and \eqn{m} are the number of vertices of the two kinds. #' #' Bipartite graphs have a \code{type} vertex attribute in igraph, this is #' boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} #' for vertices of the second kind. #' #' @aliases get.incidence #' @param graph The input graph. The direction of the edges is ignored in #' directed graphs. #' @param types An optional vertex type vector to use instead of the #' \code{type} vertex attribute. You must supply this argument if the graph has #' no \code{type} vertex attribute. #' @param attr Either \code{NULL} or a character string giving an edge #' attribute name. If \code{NULL}, then a traditional incidence matrix is #' returned. If not \code{NULL} then the values of the given edge attribute are #' included in the incidence matrix. If the graph has multiple edges, the edge #' attribute of an arbitrarily chosen edge (for the multiple edges) is #' included. #' @param names Logical scalar, if \code{TRUE} and the vertices in the graph #' are named (i.e. the graph has a vertex attribute called \code{name}), then #' vertex names will be added to the result as row and column names. Otherwise #' the ids of the vertices are used as row and column names. #' @param sparse Logical scalar, if it is \code{TRUE} then a sparse matrix is #' created, you will need the \code{Matrix} package for this. #' @return A sparse or dense matrix. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{graph_from_incidence_matrix}} for the opposite operation. #' @export #' @keywords graphs #' @examples #' #' g <- make_bipartite_graph( c(0,1,0,1,0,0), c(1,2,2,3,3,4) ) #' as_incidence_matrix(g) #' as_incidence_matrix <- function(graph, types=NULL, attr=NULL, names=TRUE, sparse=FALSE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { types <- as.logical(types) } else { stop("Not a bipartite graph, supply `types' argument") } names <- as.logical(names) sparse <- as.logical(sparse) if (sparse) { get.incidence.sparse(graph, types=types, names=names, attr=attr) } else { get.incidence.dense(graph, types=types, names=names, attr=attr) } } #' @rdname graph_from_data_frame #' @param x An igraph object. #' @param what Character constant, whether to return info about vertices, #' edges, or both. The default is \sQuote{edges}. #' @export as_data_frame <- function(x, what=c("edges", "vertices", "both")) { if (!is_igraph(x)) { stop("Not a graph object") } what <- igraph.match.arg(what) if (what %in% c("vertices", "both")) { ver <- .Call(C_R_igraph_mybracket2, x, 9L, 3L) class(ver) <- "data.frame" rn <- if (is_named(x)) { V(x)$name } else { seq_len(vcount(x)) } rownames(ver) <- rn } if (what %in% c("edges", "both")) { el <- as_edgelist(x) edg <- c(list(from=el[,1]), list(to=el[,2]), .Call(C_R_igraph_mybracket2, x, 9L, 4L)) class(edg) <- "data.frame" rownames(edg) <- seq_len(ecount(x)) } if (what=="both") { list(vertices=ver, edges=edg) } else if (what=="vertices") { ver } else { edg } } #' Create graphs from adjacency lists #' #' An adjacency list is a list of numeric vectors, containing the neighbor #' vertices for each vertex. This function creates an igraph graph object from #' such a list. #' #' Adjacency lists are handy if you intend to do many (small) modifications to #' a graph. In this case adjacency lists are more efficient than igraph graphs. #' #' The idea is that you convert your graph to an adjacency list by #' \code{\link{as_adj_list}}, do your modifications to the graphs and finally #' create again an igraph graph by calling \code{graph_from_adj_list}. #' #' @aliases graph.adjlist graph_from_adj_list #' @param adjlist The adjacency list. It should be consistent, i.e. the maximum #' throughout all vectors in the list must be less than the number of vectors #' (=the number of vertices in the graph). Note that the list is expected to be #' 0-indexed. #' @param mode Character scalar, it specifies whether the graph to create is #' undirected (\sQuote{all} or \sQuote{total}) or directed; and in the latter #' case, whether it contains the outgoing (\sQuote{out}) or the incoming #' (\sQuote{in}) neighbors of the vertices. #' @param duplicate Logical scalar. For undirected graphs it gives whether #' edges are included in the list twice. E.g. if it is \code{TRUE} then for an #' undirected \code{{A,B}} edge \code{graph_from_adj_list} expects \code{A} #' included in the neighbors of \code{B} and \code{B} to be included in the #' neighbors of \code{A}. #' #' This argument is ignored if \code{mode} is \code{out} or \code{in}. #' @return An igraph graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{as_edgelist}} #' @keywords graphs #' @examples #' #' ## Directed #' g <- make_ring(10, dir=TRUE) #' al <- as_adj_list(g, mode="out") #' g2 <- graph_from_adj_list(al) #' graph.isomorphic(g, g2) #' #' ## Undirected #' g <- make_ring(10) #' al <- as_adj_list(g) #' g2 <- graph_from_adj_list(al, mode="all") #' graph.isomorphic(g, g2) #' ecount(g2) #' g3 <- graph_from_adj_list(al, mode="all", duplicate=FALSE) #' ecount(g3) #' which_multiple(g3) #' @export graph_from_adj_list <- graph_from_adj_list #' Convert a graph to a long data frame #' #' A long data frame contains all metadata about both the vertices #' and edges of the graph. It contains one row for each edge, and #' all metadata about that edge and its incident vertices are included #' in that row. The names of the columns that contain the metadata #' of the incident vertices are prefixed with \code{from_} and \code{to_}. #' The first two columns are always named \code{from} and \code{to} and #' they contain the numeric ids of the incident vertices. The rows are #' listed in the order of numeric vertex ids. #' #' @param graph Input graph #' @return A long data frame. #' #' @export #' @examples #' g <- make_(ring(10), #' with_vertex_(name = letters[1:10], color = "red"), #' with_edge_(weight = 1:10, color = "green") #' ) #' as_long_data_frame(g) as_long_data_frame <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } ver <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) class(ver) <- "data.frame" rn <- if (is_named(graph)) { V(graph)$name } else { seq_len(vcount(graph)) } rownames(ver) <- rn el <- as_edgelist(graph, names = FALSE) edg <- c(list(from=el[,1]), list(to=el[,2]), .Call(C_R_igraph_mybracket2, graph, 9L, 4L)) class(edg) <- "data.frame" rownames(edg) <- seq_len(ecount(graph)) ver2 <- ver names(ver) <- paste0("from_", names(ver)) names(ver2) <- paste0("to_", names(ver2)) edg <- cbind(edg, ver[ el[,1], ], ver2[ el[,2], ]) edg } igraph/R/scan.R0000644000175100001440000003651613177712334013035 0ustar hornikusers## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Compute local scan statistics on graphs #' #' The scan statistic is a summary of the locality statistics that is #' computed from the local neighborhood of each vertex. The #' \code{local_scan} function computes the local statistics for each vertex #' for a given neighborhood size and the statistic function. #' #' See the given reference below for the details on the local scan #' statistics. #' #' \code{local_scan} calculates exact local scan statistics. #' #' If \code{graph.them} is \code{NULL}, then \code{local_scan} computes the #' \sQuote{us} variant of the scan statistics. Otherwise, #' \code{graph.them} should be an igraph object and the \sQuote{them} #' variant is computed using \code{graph.us} to extract the neighborhood #' information, and applying \code{FUN} on these neighborhoods in #' \code{graph.them}. #' #' @param graph.us,graph An igraph object, the graph for which the scan #' statistics will be computed #' @param graph.them An igraph object or \code{NULL}, if not \code{NULL}, #' then the \sQuote{them} statistics is computed, i.e. the neighborhoods #' calculated from \code{graph.us} are evaluated on \code{graph.them}. #' @param k An integer scalar, the size of the local neighborhood for each #' vertex. Should be non-negative. #' @param FUN Character, a function name, or a function object itself, for #' computing the local statistic in each neighborhood. If \code{NULL}(the #' default value), \code{ecount} is used for unweighted graphs (if #' \code{weighted=FALSE}) and a function that computes the sum of edge #' weights is used for weighted graphs (if \code{weighted=TRUE}). This #' argument is ignored if \code{k} is zero. #' @param weighted Logical scalar, TRUE if the edge weights should be used #' for computation of the scan statistic. If TRUE, the graph should be #' weighted. Note that this argument is ignored if \code{FUN} is not #' \code{NULL}, \code{"ecount"} and \code{"sumweights"}. #' @param mode Character scalar, the kind of neighborhoods to use for the #' calculation. One of \sQuote{\code{out}}, \sQuote{\code{in}}, #' \sQuote{\code{all}} or \sQuote{\code{total}}. This argument is ignored #' for undirected graphs. #' @param neighborhoods A list of neighborhoods, one for each vertex, or #' \code{NULL}. If it is not \code{NULL}, then the function is evaluated on #' the induced subgraphs specified by these neighborhoods. #' #' In theory this could be useful if the same \code{graph.us} graph is used #' for multiple \code{graph.them} arguments. Then the neighborhoods can be #' calculated on \code{graph.us} and used with multiple graphs. In #' practice, this is currently slower than simply using \code{graph.them} #' multiple times. #' @param \dots Arguments passed to \code{FUN}, the function that computes #' the local statistics. #' @return For \code{local_scan} typically a numeric vector containing the #' computed local statistics for each vertex. In general a list or vector #' of objects, as returned by \code{FUN}. #' #' @references Priebe, C. E., Conroy, J. M., Marchette, D. J., Park, #' Y. (2005). Scan Statistics on Enron Graphs. \emph{Computational and #' Mathematical Organization Theory}. #' #' @family scan statistics #' @export #' @examples #' pair <- sample_correlated_gnp_pair(n = 10^3, corr = 0.8, p = 0.1) #' local_0_us <- local_scan(graph.us = pair$graph1, k = 0) #' local_1_us <- local_scan(graph.us = pair$graph1, k = 1) #' #' local_0_them <- local_scan(graph.us = pair$graph1, #' graph.them = pair$graph2, k = 0) #' local_1_them <- local_scan(graph.us = pair$graph1, #' graph.them = pair$graph2, k = 1) #' #' Neigh_1 <- neighborhood(pair$graph1, order = 1) #' local_1_them_nhood <- local_scan(graph.us = pair$graph1, #' graph.them = pair$graph2, #' neighborhoods = Neigh_1) local_scan <- function(graph.us, graph.them=NULL, k=1, FUN=NULL, weighted=FALSE, mode=c("out", "in", "all"), neighborhoods=NULL, ...) { ## Must be igraph object stopifnot(is.igraph(graph.us)) ## Must be NULL or igraph object stopifnot(is.null(graph.them) || is.igraph(graph.them)) ## If given, number of vertices must match stopifnot(is.null(graph.them) || vcount(graph.them) == vcount(graph.us)) ## k must be non-negative integer stopifnot(length(k)==1, k >= 0, as.integer(k) == k) ## Must be NULL or a function stopifnot(is.null(FUN) || is.function(FUN) || (is.character(FUN) && length(FUN) == 1)) ## Logical scalar stopifnot(is.logical(weighted), length(weighted )== 1) ## If weighted, then the graph(s) must be weighted stopifnot(!weighted || (is.weighted(graph.us) && (is.null(graph.them) || is.weighted(graph.them)))) ## Check if 'neighborhoods' makes sense if (!is.null(neighborhoods)) { stopifnot(is.list(neighborhoods)) stopifnot(length(neighborhoods) == vcount(graph.us)) } if (!is.null(neighborhoods) && k==0) { warning("`neighborhoods' ignored for k=0") neighborhoods <- NULL } ## Check mode argument mode <- igraph.match.arg(mode) cmode <- switch(mode, out = 1, `in` = 2, all = 3, total = 3) sumweights <- function(g) sum(E(g)$weight) if (is.null(FUN)) { FUN <- if (weighted) "sumweights" else "ecount" } res <- if (is.null(graph.them)) { if (!is.null(neighborhoods)) { if (is.character(FUN) && FUN %in% c("ecount", "sumweights")) { neighborhoods <- lapply(neighborhoods, function(x) { as.integer(x)-1L }) on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_neighborhood_ecount, graph.us, if (weighted) as.numeric(E(graph.us)$weight) else NULL, neighborhoods) } else { sapply(lapply(neighborhoods, induced.subgraph, graph=graph.us), FUN, ...) } } else { ## scan-0 if (k == 0) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_0, graph.us, if (weighted) as.numeric(E(graph.us)$weight) else NULL, cmode) ## scan-1, ecount } else if (k==1 && is.character(FUN) && FUN %in% c("ecount", "sumweights")) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_1_ecount, graph.us, if (weighted) as.numeric(E(graph.us)$weight) else NULL, cmode) ## scan-k, ecount } else if (is.character(FUN) && FUN %in% c("ecount", "sumweights")) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_k_ecount, graph.us, as.integer(k), if (weighted) as.numeric(E(graph.us)$weight) else NULL, cmode) ## General } else { sapply(graph.neighborhood(graph.us, order=k, V(graph.us), mode=mode), FUN, ...) } } } else { if (!is.null(neighborhoods)) { neighborhoods <- lapply(neighborhoods, as.vector) if (is.character(FUN) && FUN %in% c("ecount", "wumweights")) { neighborhoods <- lapply(neighborhoods, function(x) { as.integer(x)-1L }) on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_neighborhood_ecount, graph.them, if (weighted) as.numeric(E(graph.them)$weight) else NULL, neighborhoods) } else { sapply(lapply(neighborhoods, induced.subgraph, graph=graph.them), FUN, ...) } } else { ## scan-0 if (k == 0) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_0_them, graph.us, graph.them, if (weighted) as.numeric(E(graph.them)$weight) else NULL, cmode) ## scan-1, ecount } else if (k==1 && is.character(FUN) && FUN %in% c("ecount", "sumweights")) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_1_ecount_them, graph.us, graph.them, if (weighted) as.numeric(E(graph.them)$weight) else NULL, cmode) ## scan-k, ecount } else if (is.character(FUN) && FUN %in% c("ecount", "sumweights")) { on.exit(.Call(C_R_igraph_finalizer)) .Call(C_R_igraph_local_scan_k_ecount_them, graph.us, graph.them, as.integer(k), if (weighted) as.numeric(E(graph.them)$weight) else NULL, cmode) ## general case } else { sapply(V(graph.us), function(x) { vei <- neighborhood(graph.us, order=k, nodes=x, mode=mode)[[1]] if (!is.function(FUN)) { FUN <- getFunction(FUN, where=environment()) } FUN(induced.subgraph(graph.them, vei), ...) }) } } } res <- as.numeric(res) if (igraph_opt("add.vertex.names") && is_named(graph.us)) { names(res) <- V(graph.us)$name } res } #' Scan statistics on a time series of graphs #' #' Calculate scan statistics on a time series of graphs. #' This is done by calculating the local scan statistics for #' each graph and each vertex, and then normalizing across the #' vertices and across the time steps. #' #' @param graphs A list of igraph graph objects. They must be all directed #' or all undirected and they must have the same number of vertices. #' @param tau The number of previous time steps to consider for the #' time-dependent normalization for individual vertices. In other words, #' the current locality statistics of each vertex will be compared to this #' many previous time steps of the same vertex to decide whether it is #' significantly larger. #' @param ell The number of previous time steps to consider #' for the aggregated scan statistics. This is essentially a smoothing #' parameter. #' @param locality Whether to calculate the \sQuote{us} or \sQuote{them} #' statistics. #' @param ... Extra arguments are passed to \code{\link{local_scan}}. #' @return A list with entries: #' \item{stat}{The scan statistics in each time step. It is \code{NA} #' for the initial \code{tau + ell} time steps.} #' \item{arg_max_v}{The (numeric) vertex ids for the vertex with #' the largest locality statistics, at each time step. It is \code{NA} #' for the initial \code{tau + ell} time steps.} #' #' @family scan statistics #' @export #' @examples #' ## Generate a bunch of SBMs, with the last one being different #' num_t <- 20 #' block_sizes <- c(10, 5, 5) #' p_ij <- list(p = 0.1, h = 0.9, q = 0.9) #' #' P0 <- matrix(p_ij$p, 3, 3) #' P0[2, 2] <- p_ij$h #' PA <- P0 #' PA[3, 3] <- p_ij$q #' num_v <- sum(block_sizes) #' #' tsg <- replicate(num_t - 1, P0, simplify = FALSE) %>% #' append(list(PA)) %>% #' lapply(sample_sbm, n = num_v, block.sizes = block_sizes, directed = TRUE) #' #' scan_stat(graphs = tsg, k = 1, tau = 4, ell = 2) #' scan_stat(graphs = tsg, locality = "them", k = 1, tau = 4, ell = 2) scan_stat <- function(graphs, tau = 1, ell = 0, locality = c("us", "them"), ...) { ## List of igraph graphs, all have same directedness and ## weightedness stopifnot(is.list(graphs), length(graphs) > 0, all(sapply(graphs, is_igraph)), length(unique(sapply(graphs, is_directed))) == 1, length(unique(sapply(graphs, gorder))) == 1) ## tau must the a non-negative integer stopifnot(length(tau) == 1, tau >= 0, as.integer(tau) == tau) ## ell must the a non-negative integer stopifnot(length(ell) == 1, ell >= 0, as.integer(ell) == ell) locality <- igraph.match.arg(locality) ## number of time steps and number of vertices maxTime = length(graphs) nVertex = vcount(graphs[[1]]) if (locality == 'us') { ## Underlying locality stat is us lstatPsi <- matrix(0, nrow = nVertex , ncol = maxTime) for (i in 1:maxTime) { ## locality statistics \Psi over all vertices at t=i lstatPsi[,i] <- local_scan(graphs[[i]], ...) } lstat <- lstatPsi } else if (locality == 'them') { ## Underlying locality stat is \Phi lstatPhi <- array(0, dim = c(nVertex, (tau + 1), maxTime)) for (i in 1:maxTime) { if (i > tau) { ## graph to trace k-th order neighborhood g <- graphs[[i]] for (j in 0:tau) { ## locality statistics \Phi over all vertices with t=i and t'=i-tau+j lstatPhi[, (j + 1), i] <- local_scan( graph.us = graphs[[i]], graph.them= graphs[[i - tau + j]], ... ) } } } lstat <- lstatPhi } ## vertex-dependent and temporal normalization scan_temp_norm( scan_vertex_norm(lstat, tau), tau, ell ) } #' @importFrom stats sd scan_vertex_norm <-function (input_stat, tau) { if (is.matrix(input_stat)) { n <- nrow(input_stat) nbins <- ncol(input_stat) nstat <- matrix(0, n, nbins) for (i in 1:nbins) { if (i > tau) { if (tau == 0) { nstat[,i] <- input_stat[, i] } else { muv <- apply(as.matrix(input_stat[, (i - tau):(i-1)]), 1, mean) sdv <- apply(as.matrix(input_stat[, (i - tau):(i-1)]), 1, sd) sdv[is.na(sdv)] <- 1 nstat[, i] <- (input_stat[, i] - muv) / pmax(sdv, 1) } } } } else { dd <- dim(input_stat) n <- dd[1] nbins <- dd[3] nstat <- matrix(0, n, nbins) for (i in 1:nbins) { if (i > tau) { if (tau == 0) { nstat[, i] <- input_stat[, (tau + 1), i] } else { muv <- apply(as.matrix(input_stat[, (1 : tau), i]), 1, mean) sdv <- apply(as.matrix(input_stat[, (1 : tau), i]), 1, sd) sdv[is.na(sdv)] <- 1 nstat[, i] <- (input_stat[, (tau + 1),i] - muv) / pmax(sdv, 1) } } } } return(nstat) } #' @importFrom stats sd scan_temp_norm <- function (stat, tau, ell) { maxTime <- ncol(stat) Mtilde <- apply(stat, 2, max) argmaxV <- apply(stat, 2, which.max) if (ell == 0) { res <- list(stat = Mtilde, arg_max_v = argmaxV) } else if(ell ==1 ) { res <- list(stat = Mtilde - c(NA, Mtilde[-maxTime]), arg_max_v = argmaxV) } else { muMtilde <- rep(0, maxTime) sdMtilde <- rep(1, maxTime) for (i in (ell + 1):maxTime) { muMtilde[i] <- mean(Mtilde[(i - ell):(i - 1)]) sdMtilde[i] <- sd(Mtilde[(i - ell):(i - 1)]) } sstat <- (Mtilde - muMtilde) / pmax(sdMtilde, 1) res <- list(stat = sstat, arg_max_v = argmaxV) } res$stat[seq_len(tau + ell)] <- NA res$arg_max_v[seq_len(tau + ell)] <- NA res } igraph/R/degseq.R0000644000175100001440000000733313177712334013354 0ustar hornikusers ## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2015 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Check if a degree sequence is valid for a multi-graph #' #' \code{is_degseq} checks whether the given vertex degrees (in- and #' out-degrees for directed graphs) can be realized by a graph. Note that the #' graph does not have to be simple, it may contain loop and multiple edges. #' For undirected graphs, it also checks whether the sum of degrees is even. #' For directed graphs, the function checks whether the lengths of the two #' degree vectors are equal and whether their sums are also equal. These are #' known sufficient and necessary conditions for a degree sequence to be valid. #' #' @aliases is.degree.sequence is_degseq #' @param out.deg Integer vector, the degree sequence for undirected graphs, or #' the out-degree sequence for directed graphs. #' @param in.deg \code{NULL} or an integer vector. For undireted graphs, it #' should be \code{NULL}. For directed graphs it specifies the in-degrees. #' @return A logical scalar. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references Hakimi SL: On the realizability of a set of integers as degrees #' of the vertices of a simple graph. \emph{J SIAM Appl Math} 10:496-506, 1962. #' #' PL Erdos, I Miklos and Z Toroczkai: A simple Havel-Hakimi type algorithm to #' realize graphical degree sequences of directed graphs. \emph{The Electronic #' Journal of Combinatorics} 17(1):R66, 2010. #' @keywords graphs #' #' @family graphical degree sequences #' #' g <- sample_gnp(100, 2/100) #' is_degseq(degree(g)) #' is_graphical(degree(g)) #' @export #' @include auto.R is_degseq <- is_degseq #' Is a degree sequence graphical? #' #' Determine whether the given vertex degrees (in- and out-degrees for #' directed graphs) can be reliazed in a simple graph, i.e. a graph without #' multiple or loop edges. #' #' @aliases is.graphical.degree.sequence #' @param out.deg Integer vector, the degree sequence for undirected graphs, or #' the out-degree sequence for directed graphs. #' @param in.deg \code{NULL} or an integer vector. For undireted graphs, it #' should be \code{NULL}. For directed graphs it specifies the in-degrees. #' @return A logical scalar. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references Hakimi SL: On the realizability of a set of integers as degrees #' of the vertices of a simple graph. \emph{J SIAM Appl Math} 10:496-506, 1962. #' #' PL Erdos, I Miklos and Z Toroczkai: A simple Havel-Hakimi type algorithm to #' realize graphical degree sequences of directed graphs. \emph{The Electronic #' Journal of Combinatorics} 17(1):R66, 2010. #' @keywords graphs #' #' @family graphical degree sequences #' #' g <- sample_gnp(100, 2/100) #' is_degseq(degree(g)) #' is_graphical(degree(g)) #' @export #' @include auto.R is_graphical <- is_graphical igraph/R/igraph-package.R0000644000175100001440000002055713177712334014752 0ustar hornikusers #' @useDynLib igraph, .registration = TRUE, .fixes = "C_" #' @import methods #' @importFrom magrittr %>% #' @export make_bipartite_graph #' @export connect #' @export make_de_bruijn_graph #' @export make_full_bipartite_graph #' @export graph_from_adjacency_matrix #' @export graph_from_data_frame #' @export graph_from_incidence_matrix #' @export make_kautz_graph #' @export make_line_graph #' @export sample_asym_pref NULL #' Magrittr's pipes #' #' igraph re-exports the \code{\%>\%} operator of magrittr, because #' we find it very useful. Please see the documentation in the #' \code{magrittr} package. #' #' @param lhs Left hand side of the pipe. #' @param rhs Right hand side of the pipe. #' @return Result of applying the right hand side to the #' result of the left hand side. #' #' @export #' @name %>% #' @rdname pipe #' @examples #' make_ring(10) %>% #' add_edges(c(1,6)) %>% #' plot() NULL #' The igraph package #' #' igraph is a library and R package for network analysis. #' #' @rdname aaa-igraph-package #' @name igraph-package #' @aliases igraph-package igraph #' @docType package #' #' @section Introduction: #' The main goals of the igraph library is to provide a set of data types #' and functions for 1) pain-free implementation of graph algorithms, 2) #' fast handling of large graphs, with millions of vertices and edges, 3) #' allowing rapid prototyping via high level languages like R. #' #' @section Igraph graphs: #' Igraph graphs have a class \sQuote{\code{igraph}}. They are printed to #' the screen in a special format, here is an example, a ring graph #' created using \code{\link{make_ring}}: \preformatted{ #' IGRAPH U--- 10 10 -- Ring graph #' + attr: name (g/c), mutual (g/x), circular (g/x) } #' \sQuote{\code{IGRAPH}} denotes that this is an igraph graph. Then #' come four bits that denote the kind of the graph: the first is #' \sQuote{\code{U}} for undirected and \sQuote{\code{D}} for directed #' graphs. The second is \sQuote{\code{N}} for named graph (i.e. if the #' graph has the \sQuote{\code{name}} vertex attribute set). The third is #' \sQuote{\code{W}} for weighted graphs (i.e. if the #' \sQuote{\code{weight}} edge attribute is set). The fourth is #' \sQuote{\code{B}} for bipartite graphs (i.e. if the #' \sQuote{\code{type}} vertex attribute is set). #' #' Then come two numbers, the number of vertices and the number of edges #' in the graph, and after a double dash, the name of the graph (the #' \sQuote{\code{name}} graph attribute) is printed if present. The #' second line is optional and it contains all the attributes of the #' graph. This graph has a \sQuote{\code{name}} graph attribute, of type #' character, and two other graph attributes called #' \sQuote{\code{mutual}} and \sQuote{\code{circular}}, of a complex #' type. A complex type is simply anything that is not numeric or #' character. See the documentation of \code{\link{print.igraph}} for #' details. #' #' If you want to see the edges of the graph as well, then use the #' \code{\link{print_all}} function: \preformatted{ > print_all(g) #' IGRAPH badcafe U--- 10 10 -- Ring graph #' + attr: name (g/c), mutual (g/x), circular (g/x) #' + edges: #' [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10 } #' #' @section Creating graphs: #' There are many functions in igraph for creating graphs, both #' deterministic and stochastic; stochastic graph constructors are called #' \sQuote{games}. #' #' To create small graphs with a given structure probably the #' \code{\link{graph_from_literal}} function is easiest. It uses R's formula #' interface, its manual page contains many examples. Another option is #' \code{\link{graph}}, which takes numeric vertex ids directly. #' \code{\link{graph.atlas}} creates graph from the Graph Atlas, #' \code{\link{make_graph}} can create some special graphs. #' #' To create graphs from field data, \code{\link{graph_from_edgelist}}, #' \code{\link{graph_from_data_frame}} and \code{\link{graph_from_adjacency_matrix}} are #' probably the best choices. #' #' The igraph package includes some classic random graphs like the #' Erdos-Renyi GNP and GNM graphs (\code{\link{sample_gnp}}, \code{\link{sample_gnm}}) and #' some recent popular models, like preferential attachment #' (\code{\link{sample_pa}}) and the small-world model #' (\code{\link{sample_smallworld}}). #' #' @section Vertex and edge IDs: #' Vertices and edges have numerical vertex ids in igraph. Vertex ids are #' always consecutive and they start with one. I.e. for a graph with #' \eqn{n} vertices the vertex ids are between \eqn{1} and #' \eqn{n}. If some operation changes the number of vertices in the #' graphs, e.g. a subgraph is created via \code{\link{induced_subgraph}}, then #' the vertices are renumbered to satisfty this criteria. #' #' The same is true for the edges as well, edge ids are always between #' one and \eqn{m}, the total number of edges in the graph. #' #' It is often desirable to follow vertices along a number of graph #' operations, and vertex ids don't allow this because of the #' renumbering. The solution is to assign attributes to the #' vertices. These are kept by all operations, if possible. See more #' about attributes in the next section. #' #' @section Attributes: #' In igraph it is possible to assign attributes to the vertices or edges #' of a graph, or to the graph itself. igraph provides flexible #' constructs for selecting a set of vertices or edges based on their #' attribute values, see \code{\link{vertex_attr}}, #' \code{\link{V}} and \code{\link{E}} for details. #' #' Some vertex/edge/graph attributes are treated specially. One of them #' is the \sQuote{name} attribute. This is used for printing the graph #' instead of the numerical ids, if it exists. Vertex names can also be #' used to specify a vector or set of vertices, in all igraph #' functions. E.g. \code{\link{degree}} has a \code{v} argument #' that gives the vertices for which the degree is calculated. This #' argument can be given as a character vector of vertex names. #' #' Edges can also have a \sQuote{name} attribute, and this is treated #' specially as well. Just like for vertices, edges can also be selected #' based on their names, e.g. in the \code{\link{delete_edges}} and #' other functions. #' #' We note here, that vertex names can also be used to select edges. #' The form \sQuote{\code{from|to}}, where \sQuote{\code{from}} and #' \sQuote{\code{to}} are vertex names, select a single, possibly #' directed, edge going from \sQuote{\code{from}} to #' \sQuote{\code{to}}. The two forms can also be mixed in the same edge #' selector. #' #' Other attributes define visualization parameters, see #' \code{\link{igraph.plotting}} for details. #' #' Attribute values can be set to any R object, but note that storing the #' graph in some file formats might result the loss of complex attribute #' values. All attribute values are preserved if you use #' \code{\link[base]{save}} and \code{\link[base]{load}} to store/retrieve your #' graphs. #' #' @section Visualization: #' igraph provides three different ways for visualization. The first is #' the \code{\link{plot.igraph}} function. (Actually you don't need to #' write \code{plot.igraph}, \code{plot} is enough. This function uses #' regular R graphics and can be used with any R device. #' #' The second function is \code{\link{tkplot}}, which uses a Tk GUI for #' basic interactive graph manipulation. (Tk is quite resource hungry, so #' don't try this for very large graphs.) #' #' The third way requires the \code{rgl} package and uses OpenGL. See the #' \code{\link{rglplot}} function for the details. #' #' Make sure you read \code{\link{igraph.plotting}} before you start #' plotting your graphs. #' #' @section File formats: #' igraph can handle various graph file formats, usually both for reading #' and writing. We suggest that you use the GraphML file format for your #' graphs, except if the graphs are too big. For big graphs a simpler #' format is recommended. See \code{\link{read_graph}} and #' \code{\link{write_graph}} for details. #' #' @section Further information: #' The igraph homepage is at \url{http://igraph.org}. #' See especially the documentation section. Join the igraph-help mailing #' list if you have questions or comments. NULL igraph/R/plot.R0000644000175100001440000010242313247070466013057 0ustar hornikusers# IGraph R package # Copyright (C) 2003-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Plotting of graphs #' #' \code{plot.igraph} is able to plot graphs to any R device. It is the #' non-interactive companion of the \code{tkplot} function. #' #' One convenient way to plot graphs is to plot with \code{\link{tkplot}} #' first, handtune the placement of the vertices, query the coordinates by the #' \code{\link{tk_coords}} function and use them with \code{plot} to #' plot the graph to any R device. #' #' @aliases plot.graph #' @param x The graph to plot. #' @param axes Logical, whether to plot axes, defaults to FALSE. #' @param add Logical scalar, whether to add the plot to the current device, or #' delete the device's current contents first. #' @param xlim The limits for the horizontal axis, it is unlikely that you want #' to modify this. #' @param ylim The limits for the vertical axis, it is unlikely that you want #' to modify this. #' @param mark.groups A list of vertex id vectors. It is interpreted as a set #' of vertex groups. Each vertex group is highlighted, by plotting a colored #' smoothed polygon around and \dQuote{under} it. See the arguments below to #' control the look of the polygons. #' @param mark.shape A numeric scalar or vector. Controls the smoothness of the #' vertex group marking polygons. This is basically the \sQuote{shape} #' parameter of the \code{\link[graphics]{xspline}} function, its possible #' values are between -1 and 1. If it is a vector, then a different value is #' used for the different vertex groups. #' @param mark.col A scalar or vector giving the colors of marking the #' polygons, in any format accepted by \code{\link[graphics]{xspline}}; e.g. #' numeric color ids, symbolic color names, or colors in RGB. #' @param mark.border A scalar or vector giving the colors of the borders of #' the vertex group marking polygons. If it is \code{NA}, then no border is #' drawn. #' @param mark.expand A numeric scalar or vector, the size of the border around #' the marked vertex groups. It is in the same units as the vertex sizes. If a #' vector is given, then different values are used for the different vertex #' groups. #' @param \dots Additional plotting parameters. See \link{igraph.plotting} for #' the complete list. #' @return Returns \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{layout}} for different layouts, #' \code{\link{igraph.plotting}} for the detailed description of the plotting #' parameters and \code{\link{tkplot}} and \code{\link{rglplot}} for other #' graph plotting functions. #' @method plot igraph #' @export #' @export plot.igraph #' @importFrom grDevices rainbow #' @importFrom graphics plot polygon text par #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' plot(g, layout=layout_with_kk, vertex.color="green") #' plot.igraph <- function(x, # SPECIFIC: ##################################### axes=FALSE, add=FALSE, xlim=c(-1,1), ylim=c(-1,1), mark.groups=list(), mark.shape=1/2, mark.col=rainbow(length(mark.groups), alpha=0.3), mark.border=rainbow(length(mark.groups), alpha=1), mark.expand=15, ...) { graph <- x if (!is_igraph(graph)) { stop("Not a graph object") } ################################################################ ## Visual parameters params <- i.parse.plot.params(graph, list(...)) vertex.size <- 1/200 * params("vertex", "size") label.family <- params("vertex", "label.family") label.font <- params("vertex", "label.font") label.cex <- params("vertex", "label.cex") label.degree <- params("vertex", "label.degree") label.color <- params("vertex", "label.color") label.dist <- params("vertex", "label.dist") labels <- params("vertex", "label") shape <- igraph.check.shapes(params("vertex", "shape")) edge.color <- params("edge", "color") edge.width <- params("edge", "width") edge.lty <- params("edge", "lty") arrow.mode <- params("edge", "arrow.mode") edge.labels <- params("edge", "label") loop.angle <- params("edge", "loop.angle") edge.label.font <- params("edge", "label.font") edge.label.family <- params("edge", "label.family") edge.label.cex <- params("edge", "label.cex") edge.label.color <- params("edge", "label.color") elab.x <- params("edge", "label.x") elab.y <- params("edge", "label.y") arrow.size <- params("edge", "arrow.size")[1] arrow.width <- params("edge", "arrow.width")[1] curved <- params("edge", "curved") if (is.function(curved)) { curved <- curved(graph) } layout <- params("plot", "layout") margin <- params("plot", "margin") margin <- rep(margin, length=4) rescale <- params("plot", "rescale") asp <- params("plot", "asp") frame <- params("plot", "frame") main <- params("plot", "main") sub <- params("plot", "sub") xlab <- params("plot", "xlab") ylab <- params("plot", "ylab") palette <- params("plot", "palette") if (!is.null(palette)) { old_palette <- palette(palette) on.exit(palette(old_palette), add = TRUE) } # the new style parameters can't do this yet arrow.mode <- i.get.arrow.mode(graph, arrow.mode) ################################################################ ## create the plot maxv <- max(vertex.size) if (rescale) { # norm layout to (-1, 1) layout <- norm_coords(layout, -1, 1, -1, 1) xlim <- c(xlim[1]-margin[2]-maxv, xlim[2]+margin[4]+maxv) ylim <- c(ylim[1]-margin[1]-maxv, ylim[2]+margin[3]+maxv) } if (!add) { plot(0, 0, type="n", xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, axes=axes, frame=frame, asp=asp, main=main, sub=sub) } ################################################################ ## Mark vertex groups if (!is.list(mark.groups) && is.numeric(mark.groups)) { mark.groups <- list(mark.groups) } mark.shape <- rep(mark.shape, length=length(mark.groups)) mark.border <- rep(mark.border, length=length(mark.groups)) mark.col <- rep(mark.col, length=length(mark.groups)) mark.expand <- rep(mark.expand, length=length(mark.groups)) for (g in seq_along(mark.groups)) { v <- V(graph)[mark.groups[[g]]] if (length(vertex.size)==1) { vs <- vertex.size } else { vs <- rep(vertex.size, length=vcount(graph))[v] } igraph.polygon(layout[v,,drop=FALSE], vertex.size=vs, expand.by=mark.expand[g]/200, shape=mark.shape[g], col=mark.col[g], border=mark.border[g]) } ################################################################ ## calculate position of arrow-heads el <- as_edgelist(graph, names=FALSE) loops.e <- which(el[,1] == el[,2]) nonloops.e <- which(el[,1] != el[,2]) loops.v <- el[,1] [loops.e] loop.labels <- edge.labels[loops.e] loop.labx <- if (is.null(elab.x)) { rep(NA, length(loops.e)) } else { elab.x[loops.e] } loop.laby <- if (is.null(elab.y)) { rep(NA, length(loops.e)) } else { elab.y[loops.e] } edge.labels <- edge.labels[nonloops.e] elab.x <- if (is.null(elab.x)) NULL else elab.x[nonloops.e] elab.y <- if (is.null(elab.y)) NULL else elab.y[nonloops.e] el <- el[nonloops.e,,drop=FALSE] edge.coords <- matrix(0, nrow=nrow(el), ncol=4) edge.coords[,1] <- layout[,1][ el[,1] ] edge.coords[,2] <- layout[,2][ el[,1] ] edge.coords[,3] <- layout[,1][ el[,2] ] edge.coords[,4] <- layout[,2][ el[,2] ] if ( length(unique(shape)) == 1) { ## same vertex shape for all vertices ec <- .igraph.shapes[[ shape[1] ]]$clip(edge.coords, el, params=params, end="both") } else { ## different vertex shapes, do it by "endpoint" shape <- rep(shape, length=vcount(graph)) ec <- edge.coords ec[,1:2] <- t(sapply(seq(length=nrow(el)), function(x) { .igraph.shapes[[ shape[el[x,1]] ]]$clip(edge.coords[x,,drop=FALSE], el[x,,drop=FALSE], params=params, end="from") })) ec[,3:4] <- t(sapply(seq(length=nrow(el)), function(x) { .igraph.shapes[[ shape[el[x,2]] ]]$clip(edge.coords[x,,drop=FALSE], el[x,,drop=FALSE], params=params, end="to") })) } x0 <- ec[,1] ; y0 <- ec[,2] ; x1 <- ec[,3] ; y1 <- ec[,4] ################################################################ ## add the loop edges if (length(loops.e) > 0) { ec <- edge.color if (length(ec)>1) { ec <- ec[loops.e] } point.on.cubic.bezier <- function(cp, t) { c <- 3 * (cp[2,] - cp[1,]) b <- 3 * (cp[3,] - cp[2,]) - c a <- cp[4,] - cp[1,] - c - b t2 <- t*t; t3 <- t*t*t a*t3 + b*t2 + c*t + cp[1,] } compute.bezier <- function(cp, points) { dt <- seq(0, 1, by=1/(points-1)) sapply(dt, function(t) point.on.cubic.bezier(cp, t)) } plot.bezier <- function(cp, points, color, width, arr, lty, arrow.size, arr.w) { p <- compute.bezier( cp, points ) polygon(p[1,], p[2,], border=color, lwd=width, lty=lty) if (arr==1 || arr==3) { igraph.Arrows(p[1,ncol(p)-1], p[2,ncol(p)-1], p[1,ncol(p)], p[2,ncol(p)], sh.col=color, h.col=color, size=arrow.size, sh.lwd=width, h.lwd=width, open=FALSE, code=2, width=arr.w) } if (arr==2 || arr==3) { igraph.Arrows(p[1,2], p[2,2], p[1,1], p[2,1], sh.col=color, h.col=color, size=arrow.size, sh.lwd=width, h.lwd=width, open=FALSE, code=2, width=arr.w) } } loop <- function(x0, y0, cx=x0, cy=y0, color, angle=0, label=NA, width=1, arr=2, lty=1, arrow.size=arrow.size, arr.w=arr.w, lab.x, lab.y) { rad <- angle center <- c(cx,cy) cp <- matrix( c(x0,y0, x0+.4,y0+.2, x0+.4,y0-.2, x0,y0), ncol=2, byrow=TRUE) phi <- atan2(cp[,2]-center[2], cp[,1]-center[1]) r <- sqrt((cp[,1]-center[1])**2 + (cp[,2]-center[2])**2) phi <- phi + rad cp[,1] <- cx+r*cos(phi) cp[,2] <- cy+r*sin(phi) plot.bezier(cp, 50, color, width, arr=arr, lty=lty, arrow.size=arrow.size, arr.w=arr.w) if (is.language(label) || !is.na(label)) { lx <- x0+.3 ly <- y0 phi <- atan2(ly-center[2], lx-center[1]) r <- sqrt((lx-center[1])**2 + (ly-center[2])**2) phi <- phi + rad lx <- cx+r*cos(phi) ly <- cy+r*sin(phi) if (!is.na(lab.x)) { lx <- lab.x } if (!is.na(lab.y)) { ly <- lab.y } text(lx, ly, label, col=edge.label.color, font=edge.label.font, family=edge.label.family, cex=edge.label.cex) } } ec <- edge.color if (length(ec)>1) { ec <- ec[loops.e] } vs <- vertex.size if (length(vertex.size)>1) { vs <- vs[loops.v] } ew <- edge.width if (length(edge.width)>1) { ew <- ew[loops.e] } la <- loop.angle if (length(loop.angle)>1) { la <- la[loops.e] } lty <- edge.lty if (length(edge.lty)>1) { lty <- lty[loops.e] } arr <- arrow.mode if (length(arrow.mode)>1) { arr <- arrow.mode[loops.e] } asize <- arrow.size if (length(arrow.size)>1) { asize <- arrow.size[loops.e] } xx0 <- layout[loops.v,1] + cos(la) * vs yy0 <- layout[loops.v,2] - sin(la) * vs mapply(loop, xx0, yy0, color=ec, angle=-la, label=loop.labels, lty=lty, width=ew, arr=arr, arrow.size=asize, arr.w=arrow.width, lab.x=loop.labx, lab.y=loop.laby) } ################################################################ ## non-loop edges if (length(x0) != 0) { if (length(edge.color)>1) { edge.color <- edge.color[nonloops.e] } if (length(edge.width)>1) { edge.width <- edge.width[nonloops.e] } if (length(edge.lty)>1) { edge.lty <- edge.lty[nonloops.e] } if (length(arrow.mode)>1) { arrow.mode <- arrow.mode[nonloops.e] } if (length(arrow.size)>1) { arrow.size <- arrow.size[nonloops.e] } if (length(curved)>1) { curved <- curved[nonloops.e] } if (length(unique(arrow.mode))==1) { lc <-igraph.Arrows(x0, y0, x1, y1, h.col=edge.color, sh.col=edge.color, sh.lwd=edge.width, h.lwd=1, open=FALSE, code=arrow.mode[1], sh.lty=edge.lty, h.lty=1, size=arrow.size, width=arrow.width, curved=curved) lc.x <- lc$lab.x lc.y <- lc$lab.y } else { ## different kinds of arrows drawn separately as 'arrows' cannot ## handle a vector as the 'code' argument curved <- rep(curved, length=ecount(graph))[nonloops.e] lc.x <- lc.y <- numeric(length(curved)) for (code in 0:3) { valid <- arrow.mode==code if (!any(valid)) { next } ec <- edge.color ; if (length(ec)>1) { ec <- ec[valid] } ew <- edge.width ; if (length(ew)>1) { ew <- ew[valid] } el <- edge.lty ; if (length(el)>1) { el <- el[valid] } lc <- igraph.Arrows(x0[valid], y0[valid], x1[valid], y1[valid], code=code, sh.col=ec, h.col=ec, sh.lwd=ew, h.lwd=1, h.lty=1, sh.lty=el, open=FALSE, size=arrow.size, width=arrow.width, curved=curved[valid]) lc.x[valid] <- lc$lab.x lc.y[valid] <- lc$lab.y } } if (!is.null(elab.x)) { lc.x <- ifelse(is.na(elab.x), lc.x, elab.x) } if (!is.null(elab.y)) { lc.y <- ifelse(is.na(elab.y), lc.y, elab.y) } text(lc.x, lc.y, labels=edge.labels, col=edge.label.color, family=edge.label.family, font=edge.label.font, cex=edge.label.cex) } rm(x0, y0, x1, y1) ################################################################ # add the vertices if (length(unique(shape)) == 1) { .igraph.shapes[[ shape[1] ]]$plot(layout, params=params) } else { sapply(seq(length=vcount(graph)), function(x) { .igraph.shapes[[ shape[x] ]]$plot(layout[x,,drop=FALSE], v=x, params=params) }) } ################################################################ # add the labels par(xpd=TRUE) x <- layout[,1]+label.dist*cos(-label.degree)* (vertex.size+6*8*log10(2))/200 y <- layout[,2]+label.dist*sin(-label.degree)* (vertex.size+6*8*log10(2))/200 if (length(label.family)==1) { text(x, y, labels=labels, col=label.color, family=label.family, font=label.font, cex=label.cex) } else { if1 <- function(vect, idx) if (length(vect)==1) vect else vect[idx] sapply(seq_len(vcount(graph)), function(v) { text(x[v], y[v], labels=if1(labels, v), col=if1(label.color, v), family=if1(label.family, v), font=if1(label.font, v), cex=if1(label.cex, v)) }) } rm(x, y) invisible(NULL) } #' 3D plotting of graphs with OpenGL #' #' Using the \code{rgl} package, \code{rglplot} plots a graph in 3D. The plot #' can be zoomed, rotated, shifted, etc. but the coordinates of the vertices is #' fixed. #' #' Note that \code{rglplot} is considered to be highly experimental. It is not #' very useful either. See \code{\link{igraph.plotting}} for the possible #' arguments. #' #' @aliases rglplot rglplot.igraph #' @param x The graph to plot. #' @param \dots Additional arguments, see \code{\link{igraph.plotting}} for the #' details #' @return \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{igraph.plotting}}, \code{\link{plot.igraph}} for the 2D #' version, \code{\link{tkplot}} for interactive graph drawing in 2D. #' @export #' @keywords graphs #' @export #' @examples #' #' \dontrun{ #' g <- make_lattice( c(5,5,5) ) #' coords <- layout_with_fr(g, dim=3) #' rglplot(g, layout=coords) #' } #' rglplot <- function(x, ...) UseMethod("rglplot", x) #' @method rglplot igraph #' @export rglplot.igraph <- function(x, ...) { graph <- x if (!is_igraph(graph)) { stop("Not a graph object") } create.edge <- function(v1, v2, r1, r2, ec, ew, am, as) { ## these could also be parameters: aw <- 0.005*3*as # arrow width al <- 0.005*4*as # arrow length dist <- sqrt(sum((v2-v1)^2)) # distance of the centers if (am==0) { edge <- rgl::qmesh3d(c(-ew/2,-ew/2,dist,1, ew/2,-ew/2,dist,1, ew/2,ew/2,dist,1, -ew/2,ew/2,dist,1, -ew/2,-ew/2,0,1, ew/2,-ew/2,0,1, ew/2,ew/2,0,1, -ew/2,ew/2,0,1), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 4,1,5,8)) } else if (am==1) { edge <- rgl::qmesh3d(c(-ew/2,-ew/2,dist,1, ew/2,-ew/2,dist,1, ew/2,ew/2,dist,1, -ew/2,ew/2,dist,1, -ew/2,-ew/2,al+r1,1, ew/2,-ew/2,al+r1,1, ew/2,ew/2,al+r1,1, -ew/2,ew/2,al+r1,1, -aw/2,-aw/2,al+r1,1, aw/2,-aw/2,al+r1,1, aw/2,aw/2,al+r1,1, -aw/2,aw/2,al+r1,1, 0,0,r1,1), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 4,1,5,8, 9,10,11,12, 9,12,13,13, 9,10,13,13, 10,11,13,13, 11,12,13,13)) } else if (am==2) { box <- dist-r2-al edge <- rgl::qmesh3d(c(-ew/2,-ew/2,box,1, ew/2,-ew/2,box,1, ew/2,ew/2,box,1, -ew/2,ew/2,box,1, -ew/2,-ew/2,0,1, ew/2,-ew/2,0,1, ew/2,ew/2,0,1, -ew/2,ew/2,0,1, -aw/2,-aw/2,box,1, aw/2,-aw/2,box,1, aw/2,aw/2,box,1, -aw/2,aw/2,box,1, 0,0,box+al,1), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 4,1,5,8, 9,10,11,12, 9,12,13,13, 9,10,13,13, 10,11,13,13, 11,12,13,13)) } else { edge <- rgl::qmesh3d(c(-ew/2,-ew/2,dist-al-r2,1, ew/2,-ew/2,dist-al-r2,1, ew/2,ew/2,dist-al-r2,1, -ew/2,ew/2,dist-al-r2,1, -ew/2,-ew/2,r1+al,1, ew/2,-ew/2,r1+al,1, ew/2,ew/2,r1+al,1, -ew/2,ew/2,r1+al,1, -aw/2,-aw/2,dist-al-r2,1, aw/2,-aw/2,dist-al-r2,1, aw/2,aw/2,dist-al-r2,1, -aw/2,aw/2,dist-al-r2,1, -aw/2,-aw/2,r1+al,1, aw/2,-aw/2,r1+al,1, aw/2,aw/2,r1+al,1, -aw/2,aw/2,r1+al,1, 0,0,dist-r2,1, 0,0,r1,1), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 4,1,5,8, 9,10,11,12, 9,12,17,17, 9,10,17,17, 10,11,17,17, 11,12,17,17, 13,14,15,16, 13,16,18,18, 13,14,18,18, 14,15,18,18, 15,16,18,18)) } ## rotate and shift it to its position phi<- -atan2(v2[2]-v1[2],v1[1]-v2[1])-pi/2 psi<- acos((v2[3]-v1[3])/dist) rot1 <- rbind(c(1,0,0),c(0,cos(psi),sin(psi)), c(0,-sin(psi),cos(psi))) rot2 <- rbind(c(cos(phi),sin(phi),0),c(-sin(phi),cos(phi),0), c(0,0,1)) rot <- rot1 %*% rot2 edge <- rgl::transform3d(edge, rgl::rotationMatrix(matrix=rot)) edge <- rgl::transform3d(edge, rgl::translationMatrix(v1[1], v1[2], v1[3])) ## we are ready rgl::shade3d(edge, col=ec) } create.loop <- function(v, r, ec, ew, am, la, la2, as) { aw <- 0.005*3*as al <- 0.005*4*as wi <- aw*2 # size of the loop wi2 <- wi+aw-ew # size including the arrow heads hi <- al*2+ew*2 gap <- wi-2*ew if (am==0) { edge <- rgl::qmesh3d(c(-wi/2,-ew/2,0,1, -gap/2,-ew/2,0,1, -gap/2,ew/2,0,1, -wi/2,ew/2,0,1, -wi/2,-ew/2,hi-ew+r,1, -gap/2,-ew/2,hi-ew+r,1, -gap/2,ew/2,hi-ew+r,1, -wi/2,ew/2,hi-ew+r,1, wi/2,-ew/2,0,1, gap/2,-ew/2,0,1, gap/2,ew/2,0,1, wi/2,ew/2,0,1, wi/2,-ew/2,hi-ew+r,1, gap/2,-ew/2,hi-ew+r,1, gap/2,ew/2,hi-ew+r,1, wi/2,ew/2,hi-ew+r,1, -wi/2,-ew/2,hi+r,1, -wi/2,ew/2,hi+r,1, wi/2,-ew/2,hi+r,1, wi/2,ew/2,hi+r,1 ), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 1,4,18,17, 9,10,11,12, 13,14,15,16, 9,10,14,13, 10,11,15,14, 11,12,16,15, 9,12,20,19, 5,13,19,17, 17,18,20,19, 8,16,20,18, 6,7,15,14 )) } else if (am==1 || am==2) { edge <- rgl::qmesh3d(c(-wi/2,-ew/2,r+al,1, -gap/2,-ew/2,r+al,1, -gap/2,ew/2,r+al,1, -wi/2,ew/2,r+al,1, -wi/2,-ew/2,hi-ew+r,1, -gap/2,-ew/2,hi-ew+r,1, -gap/2,ew/2,hi-ew+r,1, -wi/2,ew/2,hi-ew+r,1, wi/2,-ew/2,0,1, gap/2,-ew/2,0,1, gap/2,ew/2,0,1, wi/2,ew/2,0,1, wi/2,-ew/2,hi-ew+r,1, gap/2,-ew/2,hi-ew+r,1, gap/2,ew/2,hi-ew+r,1, wi/2,ew/2,hi-ew+r,1, -wi/2,-ew/2,hi+r,1, -wi/2,ew/2,hi+r,1, wi/2,-ew/2,hi+r,1, wi/2,ew/2,hi+r,1, # the arrow -wi2/2,-aw/2,r+al,1, -wi2/2+aw,-aw/2,r+al,1, -wi2/2+aw,aw/2,r+al,1, -wi2/2,aw/2,r+al,1, -wi2/2+aw/2,0,r,1 ), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 1,4,18,17, 9,10,11,12, 13,14,15,16, 9,10,14,13, 10,11,15,14, 11,12,16,15, 9,12,20,19, 5,13,19,17, 17,18,20,19, 8,16,20,18, 6,7,15,14, # the arrow 21,22,23,24, 21,22,25,25, 22,23,25,25, 23,24,25,25, 21,24,25,25 )) } else if (am==3) { edge <- rgl::qmesh3d(c(-wi/2,-ew/2,r+al,1, -gap/2,-ew/2,r+al,1, -gap/2,ew/2,r+al,1, -wi/2,ew/2,r+al,1, -wi/2,-ew/2,hi-ew+r,1, -gap/2,-ew/2,hi-ew+r,1, -gap/2,ew/2,hi-ew+r,1, -wi/2,ew/2,hi-ew+r,1, wi/2,-ew/2,r+al,1, gap/2,-ew/2,r+al,1, gap/2,ew/2,r+al,1, wi/2,ew/2,r+al,1, wi/2,-ew/2,hi-ew+r,1, gap/2,-ew/2,hi-ew+r,1, gap/2,ew/2,hi-ew+r,1, wi/2,ew/2,hi-ew+r,1, -wi/2,-ew/2,hi+r,1, -wi/2,ew/2,hi+r,1, wi/2,-ew/2,hi+r,1, wi/2,ew/2,hi+r,1, # the arrows -wi2/2,-aw/2,r+al,1, -wi2/2+aw,-aw/2,r+al,1, -wi2/2+aw,aw/2,r+al,1, -wi2/2,aw/2,r+al,1, -wi2/2+aw/2,0,r,1, wi2/2,-aw/2,r+al,1, wi2/2-aw,-aw/2,r+al,1, wi2/2-aw,aw/2,r+al,1, wi2/2,aw/2,r+al,1, wi2/2-aw/2,0,r,1 ), c(1,2,3,4, 5,6,7,8, 1,2,6,5, 2,3,7,6, 3,4,8,7, 1,4,18,17, 9,10,11,12, 13,14,15,16, 9,10,14,13, 10,11,15,14, 11,12,16,15, 9,12,20,19, 5,13,19,17, 17,18,20,19, 8,16,20,18, 6,7,15,14, # the arrows 21,22,23,24, 21,22,25,25, 22,23,25,25, 23,24,25,25, 21,24,25,25, 26,27,28,29, 26,27,30,30, 27,28,30,30, 28,29,30,30, 26,29,30,30 )) } # rotate and shift to its position rot1 <- rbind(c(1,0,0),c(0,cos(la2),sin(la2)), c(0,-sin(la2),cos(la2))) rot2 <- rbind(c(cos(la),sin(la),0),c(-sin(la),cos(la),0), c(0,0,1)) rot <- rot1 %*% rot2 edge <- rgl::transform3d(edge, rgl::rotationMatrix(matrix=rot)) edge <- rgl::transform3d(edge, rgl::translationMatrix(v[1], v[2], v[3])) ## we are ready rgl::shade3d(edge, col=ec) } # Visual parameters params <- i.parse.plot.params(graph, list(...)) labels <- params("vertex", "label") label.color <- params("vertex", "label.color") label.font <- params("vertex", "label.font") label.degree <- params("vertex", "label.degree") label.dist <- params("vertex", "label.dist") vertex.color <- params("vertex", "color") vertex.size <- (1/200) * params("vertex", "size") loop.angle <- params("edge", "loop.angle") loop.angle2 <- params("edge", "loop.angle2") edge.color <- params("edge", "color") edge.width <- (1/200) * params("edge", "width") edge.labels <- params("edge","label") arrow.mode <- params("edge","arrow.mode") arrow.size <- params("edge","arrow.size") layout <- params("plot", "layout") rescale <- params("plot", "rescale") # the new style parameters can't do this yet arrow.mode <- i.get.arrow.mode(graph, arrow.mode) # norm layout to (-1, 1) if (ncol(layout)==2) { layout <- cbind(layout, 0) } if (rescale) { layout <- norm_coords(layout, -1, 1, -1, 1, -1, 1) } # add the edges, the loops are handled separately el <- as_edgelist(graph, names=FALSE) # It is faster this way rgl::par3d(skipRedraw=TRUE) # edges first for (i in seq(length=nrow(el))) { from <- el[i,1] to <- el[i,2] v1 <- layout[from,] v2 <- layout[to,] am <- arrow.mode; if (length(am)>1) { am <- am[i] } ew <- edge.width; if (length(ew)>1) { ew <- ew[i] } ec <- edge.color; if (length(ec)>1) { ec <- ec[i] } r1 <- vertex.size; if (length(r1)>1) { r1 <- r1[from] } r2 <- vertex.size; if (length(r2)>1) { r2 <- r2[to] } if (from!=to) { create.edge(v1,v2,r1,r2,ec,ew,am,arrow.size) } else { la <- loop.angle; if (length(la)>1) { la <- la[i] } la2 <- loop.angle2; if (length(la2)>1) { la2 <- la2[i] } create.loop(v1,r1,ec,ew,am,la,la2,arrow.size) } } # add the vertices if (length(vertex.size)==1) { vertex.size <- rep(vertex.size, nrow(layout)) } rgl::rgl.spheres(layout[,1], layout[,2], layout[,3], radius=vertex.size, col=vertex.color) # add the labels, 'l1' is a stupid workaround of a mysterious rgl bug labels[is.na(labels)] <- "" x <- layout[,1]+label.dist*cos(-label.degree)* (vertex.size+6*10*log10(2))/200 y <- layout[,2]+label.dist*sin(-label.degree)* (vertex.size+6*10*log10(2))/200 z <- layout[,3] l1 <- labels[1] labels[1] <- "" rgl::rgl.texts(x,y,z, labels, col=label.color, adj=0) rgl::rgl.texts(c(0,x[1]), c(0,y[1]), c(0,z[1]), c("",l1), col=c(label.color[1],label.color[1]), adj=0) edge.labels[is.na(edge.labels)] <- "" if (any(edge.labels != "")) { x0 <- layout[,1][el[,1]] x1 <- layout[,1][el[,2]] y0 <- layout[,2][el[,1]] y1 <- layout[,2][el[,2]] z0 <- layout[,3][el[,1]] z1 <- layout[,4][el[,2]] rgl::rgl.texts((x0+x1)/2, (y0+y1)/2, (z0+z1)/2, edge.labels, col=label.color) } # draw everything rgl::par3d(skipRedraw=FALSE) invisible(NULL) } # This is taken from the IDPmisc package, # slightly modified: code argument added #' @importFrom graphics par xyinch segments xspline lines polygon igraph.Arrows <- function (x1, y1, x2, y2, code=2, size= 1, width= 1.2/4/cin, open=TRUE, sh.adj=0.1, sh.lwd=1, sh.col=if(is.R()) par("fg") else 1, sh.lty=1, h.col=sh.col, h.col.bo=sh.col, h.lwd=sh.lwd, h.lty=sh.lty, curved=FALSE) ## Author: Andreas Ruckstuhl, refined by Rene Locher ## Version: 2005-10-17 { cin <- size * par("cin")[2] width <- width * (1.2/4/cin) uin <- if (is.R()) 1/xyinch() else par("uin") x <- sqrt(seq(0, cin^2, length = floor(35 * cin) + 2)) delta <- sqrt(h.lwd)*par("cin")[2]*0.005 ## has been 0.05 x.arr <- c(-rev(x), -x) wx2 <- width * x^2 y.arr <- c(-rev(wx2 + delta), wx2 + delta) deg.arr <- c(atan2(y.arr, x.arr), NA) r.arr <- c(sqrt(x.arr^2 + y.arr^2), NA) ## backup bx1 <- x1 ; bx2 <- x2 ; by1 <- y1 ; by2 <- y2 ## shaft lx <- length(x1) r.seg <- rep(cin*sh.adj, lx) theta1 <- atan2((y1 - y2) * uin[2], (x1 - x2) * uin[1]) th.seg1 <- theta1 + rep(atan2(0, -cin), lx) theta2 <- atan2((y2 - y1) * uin[2], (x2 - x1) * uin[1]) th.seg2 <- theta2 + rep(atan2(0, -cin), lx) x1d <- y1d <- x2d <- y2d <- 0 if (code %in% c(1,3)) { x2d <- r.seg*cos(th.seg2)/uin[1] y2d <- r.seg*sin(th.seg2)/uin[2] } if (code %in% c(2,3)) { x1d <- r.seg*cos(th.seg1)/uin[1] y1d <- r.seg*sin(th.seg1)/uin[2] } if (is.logical(curved) && all(!curved) || is.numeric(curved) && all(!curved)) { segments(x1+x1d, y1+y1d, x2+x2d, y2+y2d, lwd=sh.lwd, col=sh.col, lty=sh.lty) phi <- atan2(y1-y2, x1-x2) r <- sqrt( (x1-x2)^2 + (y1-y2)^2 ) lc.x <- x2 + 2/3*r*cos(phi) lc.y <- y2 + 2/3*r*sin(phi) } else { if (is.numeric(curved)) { lambda <- curved } else { lambda <- as.logical(curved) * 0.5 } lambda <- rep(lambda, length.out = length(x1)) c.x1 <- x1+x1d c.y1 <- y1+y1d c.x2 <- x2+x2d c.y2 <- y2+y2d midx <- (x1+x2)/2 midy <- (y1+y2)/2 spx <- midx - lambda * 1/2 * (c.y2-c.y1) spy <- midy + lambda * 1/2 * (c.x2-c.x1) sh.col <- rep(sh.col, length=length(c.x1)) sh.lty <- rep(sh.lty, length=length(c.x1)) sh.lwd <- rep(sh.lwd, length=length(c.x1)) lc.x <- lc.y <- numeric(length(c.x1)) for (i in seq_len(length(c.x1))) { ## Straight line? if (lambda[i] == 0) { segments(c.x1[i], c.y1[i], c.x2[i], c.y2[i], lwd = sh.lwd[i], col = sh.col[i], lty = sh.lty[i]) phi <- atan2(y1[i] - y2[i], x1[i] - x2[i]) r <- sqrt( (x1[i] - x2[i])^2 + (y1[i] - y2[i])^2 ) lc.x[i] <- x2[i] + 2/3*r*cos(phi) lc.y[i] <- y2[i] + 2/3*r*sin(phi) } else { spl <- xspline(x=c(c.x1[i],spx[i],c.x2[i]), y=c(c.y1[i],spy[i],c.y2[i]), shape=1, draw=FALSE) lines(spl, lwd=sh.lwd[i], col=sh.col[i], lty=sh.lty[i]) if (code %in% c(2,3)) { x1[i] <- spl$x[3*length(spl$x)/4] y1[i] <- spl$y[3*length(spl$y)/4] } if (code %in% c(1,3)) { x2[i] <- spl$x[length(spl$x)/4] y2[i] <- spl$y[length(spl$y)/4] } lc.x[i] <- spl$x[2/3 * length(spl$x)] lc.y[i] <- spl$y[2/3 * length(spl$y)] } } } ## forward arrowhead if (code %in% c(2,3)) { theta <- atan2((by2 - y1) * uin[2], (bx2 - x1) * uin[1]) Rep <- rep(length(deg.arr), lx) p.x2 <- rep(bx2, Rep) p.y2 <- rep(by2, Rep) ttheta <- rep(theta, Rep) + rep(deg.arr, lx) r.arr <- rep(r.arr, lx) if(open) lines((p.x2 + r.arr * cos(ttheta)/uin[1]), (p.y2 + r.arr*sin(ttheta)/uin[2]), lwd=h.lwd, col = h.col.bo, lty=h.lty) else polygon(p.x2 + r.arr * cos(ttheta)/uin[1], p.y2 + r.arr*sin(ttheta)/uin[2], col = h.col, lwd=h.lwd, border=h.col.bo, lty=h.lty) } ## backward arrow head if (code %in% c(1,3)) { x1 <- bx1; y1 <- by1 tmp <- x1 ; x1 <- x2 ; x2 <- tmp tmp <- y1 ; y1 <- y2 ; y2 <- tmp theta <- atan2((y2 - y1) * uin[2], (x2 - x1) * uin[1]) lx <- length(x1) Rep <- rep(length(deg.arr), lx) p.x2 <- rep(x2, Rep) p.y2 <- rep(y2, Rep) ttheta <- rep(theta, Rep) + rep(deg.arr, lx) r.arr <- rep(r.arr, lx) if(open) lines((p.x2 + r.arr * cos(ttheta)/uin[1]), (p.y2 + r.arr*sin(ttheta)/uin[2]), lwd=h.lwd, col = h.col.bo, lty=h.lty) else polygon(p.x2 + r.arr * cos(ttheta)/uin[1], p.y2 + r.arr*sin(ttheta)/uin[2], col = h.col, lwd=h.lwd, border=h.col.bo, lty=h.lty) } list(lab.x=lc.x, lab.y=lc.y) } # Arrows #' @importFrom graphics xspline igraph.polygon <- function(points, vertex.size=15/200, expand.by=15/200, shape=1/2, col="#ff000033", border=NA) { by <- expand.by pp <- rbind(points, cbind(points[,1]-vertex.size-by, points[,2]), cbind(points[,1]+vertex.size+by, points[,2]), cbind(points[,1], points[,2]-vertex.size-by), cbind(points[,1], points[,2]+vertex.size+by)) cl <- convex_hull(pp) xspline(cl$rescoords, shape=shape, open=FALSE, col=col, border=border) } igraph/R/scg.R0000644000175100001440000010150413247212322012641 0ustar hornikusers# IGraph R package # Copyright (C) 2010-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Spectral Coarse Graining #' #' Functions to perform the Spectral Coarse Graining (SCG) of matrices and #' graphs. #' #' @name scg-method #' @section Introduction: The SCG functions provide a framework, called #' Spectral Coarse Graining (SCG), for reducing large graphs while preserving #' their \emph{spectral-related features}, that is features closely related #' with the eigenvalues and eigenvectors of a graph matrix (which for now can #' be the adjacency, the stochastic, or the Laplacian matrix). #' #' Common examples of such features comprise the first-passage-time of random #' walkers on Markovian graphs, thermodynamic properties of lattice models in #' statistical physics (e.g. Ising model), and the epidemic threshold of #' epidemic network models (SIR and SIS models). #' #' SCG differs from traditional clustering schemes by producing a #' \emph{coarse-grained graph} (not just a partition of the vertices), #' representative of the original one. As shown in [1], Principal Component #' Analysis can be viewed as a particular SCG, called \emph{exact SCG}, where #' the matrix to be coarse-grained is the covariance matrix of some data set. #' #' SCG should be of interest to practitioners of various fields dealing with #' problems where matrix eigenpairs play an important role, as for instance is #' the case of dynamical processes on networks. #' @author David Morton de Lachapelle, #' \url{http://people.epfl.ch/david.morton}. #' @references D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, #' Shrinking Matrices while Preserving their Eigenpairs with Application to the #' Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on #' Matrix Analysis and Applications}, 2008. #' \url{http://people.epfl.ch/david.morton} #' #' D. Gfeller, and P. De Los Rios, Spectral Coarse Graining and Synchronization #' in Oscillator Networks. \emph{Physical Review Letters}, \bold{100}(17), #' 2008. \url{http://arxiv.org/abs/0708.2055} #' #' D. Gfeller, and P. De Los Rios, Spectral Coarse Graining of Complex #' Networks, \emph{Physical Review Letters}, \bold{99}(3), 2007. #' \url{http://arxiv.org/abs/0706.0812} #' @keywords graphs NULL #' Stochastic matrix of a graph #' #' Retrieves the stochastic matrix of a graph of class \code{igraph}. #' #' Let \eqn{M} be an \eqn{n \times n}{n x n} adjacency matrix with real #' non-negative entries. Let us define \eqn{D = \textrm{diag}(\sum_{i}M_{1i}, #' \dots, \sum_{i}M_{ni})}{D=diag( sum(M[1,i], i), ..., sum(M[n,i], i) )} #' #' The (row) stochastic matrix is defined as \deqn{W = D^{-1}M,}{W = inv(D) M,} #' where it is assumed that \eqn{D} is non-singular. Column stochastic #' matrices are defined in a symmetric way. #' #' @aliases get.stochastic #' @param graph The input graph. Must be of class \code{igraph}. #' @param column.wise If \code{FALSE}, then the rows of the stochastic matrix #' sum up to one; otherwise it is the columns. #' @param sparse Logical scalar, whether to return a sparse matrix. The #' \code{Matrix} package is needed for sparse matrices. #' @return A regular matrix or a matrix of class \code{Matrix} if a #' \code{sparse} argument was \code{TRUE}. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{as_adj}} #' @export #' @keywords graphs #' @examples #' #' library(Matrix) #' ## g is a large sparse graph #' g <- sample_pa(n = 10^5, power = 2, directed = FALSE) #' W <- stochastic_matrix(g, sparse=TRUE) #' #' ## a dense matrix here would probably not fit in the memory #' class(W) #' #' ## may not be exactly 1, due to numerical errors #' max(abs(rowSums(W))-1) #' stochastic_matrix <- function(graph, column.wise=FALSE, sparse=igraph_opt("sparsematrices")) { if (!is_igraph(graph)) { stop("Not a graph object") } column.wise <- as.logical(column.wise) if (length(column.wise) != 1) { stop("`column.wise' must be a logical scalar") } sparse <- as.logical(sparse) if (length(sparse) != 1) { stop("`sparse' must be a logical scalar") } on.exit(.Call(C_R_igraph_finalizer)) if (sparse) { res <- .Call(C_R_igraph_get_stochastic_sparsemat, graph, column.wise) res <- igraph.i.spMatrix(res) } else { res <- .Call(C_R_igraph_get_stochastic, graph, column.wise) } if (igraph_opt("add.vertex.names") && is_named(graph)) { rownames(res) <- colnames(res) <- V(graph)$name } res } #' SCG Problem Solver #' #' This function solves the Spectral Coarse Graining (SCG) problem; either #' exactly, or approximately but faster. #' #' The algorithm \dQuote{optimum} solves exactly the SCG problem for each #' eigenvector in \code{V}. The running time of this algorithm is \eqn{O(\max #' nt \cdot m^2)}{O(max(nt) m^2)} for the symmetric and laplacian matrix #' problems (i.e. when \code{mtype} is \dQuote{symmetric} or #' \dQuote{laplacian}. It is \eqn{O(m^3)} for the stochastic problem. Here #' \eqn{m} is the number of rows in \code{V}. In all three cases, the memory #' usage is \eqn{O(m^2)}. #' #' The algorithms \dQuote{interv} and \dQuote{interv\_km} solve approximately #' the SCG problem by performing a (for now) constant binning of the components #' of the eigenvectors, that is \code{nt[i]} constant-size bins are used to #' partition \code{V[,i]}. When \code{algo} = \dQuote{interv\_km}, the (Lloyd) #' k-means algorithm is run on each partition obtained by \dQuote{interv} to #' improve accuracy. #' #' Once a minimizing partition (either exact or approximate) has been found for #' each eigenvector, the final grouping is worked out as follows: two vertices #' are grouped together in the final partition if they are grouped together in #' each minimizing partition. In general the size of the final partition is not #' known in advance when \code{ncol(V)}>1. #' #' Finally, the algorithm \dQuote{exact\_scg} groups the vertices with equal #' components in each eigenvector. The last three algorithms essentially have #' linear running time and memory load. #' #' @aliases scgGrouping #' @param V A numeric matrix of (eigen)vectors to be preserved by the coarse #' graining (the vectors are to be stored column-wise in \code{V}). #' @param nt A vector of positive integers of length one or equal to #' \code{length(ev)}. When \code{algo} = \dQuote{optimum}, \code{nt} contains #' the number of groups used to partition each eigenvector separately. When #' \code{algo} is equal to \dQuote{interv\_km} or \dQuote{interv}, \code{nt} #' contains the number of intervals used to partition each eigenvector. The #' same partition size or number of intervals is used for each eigenvector if #' \code{nt} is a single integer. When \code{algo} = \dQuote{exact\_cg} this #' parameter is ignored. #' @param mtype The type of semi-projectors used in the SCG. For now #' \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are #' available. #' @param algo The algorithm used to solve the SCG problem. Possible values are #' \dQuote{optimum}, \dQuote{interv\_km}, \dQuote{interv} and #' \dQuote{exact\_scg}. #' @param p A probability vector of length equal to \code{nrow(V)}. \code{p} is #' the stationary probability distribution of a Markov chain when \code{mtype} #' = \dQuote{stochastic}. This parameter is ignored in all other cases. #' @param maxiter A positive integer giving the maximum number of iterations of #' the k-means algorithm when \code{algo} = \dQuote{interv\_km}. This parameter #' is ignored in all other cases. #' @return A vector of \code{nrow(V)} integers giving the group label of each #' object (vertex) in the partition. #' @author David Morton de Lachapelle \email{david.morton@@epfl.ch}, #' \email{david.mortondelachapelle@@swissquote.ch} #' @seealso \link{scg-method} for a detailed introduction. \code{\link{scg}}, #' \code{\link{scg_eps}} #' @references D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, #' Shrinking Matrices while Preserving their Eigenpairs with Application to the #' Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on #' Matrix Analysis and Applications}, 2008. #' \url{http://people.epfl.ch/david.morton} #' @export #' @keywords graphs #' @examples #' #' #' ## We are not running these examples any more, because they #' ## take a long time to run and this is against the CRAN repository #' ## policy. Copy and paste them by hand to your R prompt if #' ## you want to run them. #' #' \dontrun{ #' # eigenvectors of a random symmetric matrix #' M <- matrix(rexp(10^6), 10^3, 10^3) #' M <- (M + t(M))/2 #' V <- eigen(M, symmetric=TRUE)$vectors[,c(1,2)] #' #' # displays size of the groups in the final partition #' gr <- scg_group(V, nt=c(2,3)) #' col <- rainbow(max(gr)) #' plot(table(gr), col=col, main="Group size", xlab="group", ylab="size") #' #' ## comparison with the grouping obtained by kmeans #' ## for a partition of same size #' gr.km <- kmeans(V,centers=max(gr), iter.max=100, nstart=100)$cluster #' op <- par(mfrow=c(1,2)) #' plot(V[,1], V[,2], col=col[gr], #' main = "SCG grouping", #' xlab = "1st eigenvector", #' ylab = "2nd eigenvector") #' plot(V[,1], V[,2], col=col[gr.km], #' main = "K-means grouping", #' xlab = "1st eigenvector", #' ylab = "2nd eigenvector") #' par(op) #' ## kmeans disregards the first eigenvector as it #' ## spreads a much smaller range of values than the second one #' #' ### comparing optimal and k-means solutions #' ### in the one-dimensional case. #' x <- rexp(2000, 2) #' gr.true <- scg_group(cbind(x), 100) #' gr.km <- kmeans(x, 100, 100, 300)$cluster #' scg_eps(cbind(x), gr.true) #' scg_eps(cbind(x), gr.km) #' } #' scg_group <- function(V, nt, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), p=NULL, maxiter=100) { V <- as.matrix(structure(as.double(V), dim=dim(V))) groups <- as.numeric(nt) mtype <- switch(igraph.match.arg(mtype), "symmetric"=1, "laplacian"=2, "stochastic"=3) algo <- switch(igraph.match.arg(algo), "optimum"=1, "interv_km"=2, "interv"=3, "exact_scg"=4) if (!is.null(p)) p <- as.numeric(p) maxiter <- as.integer(maxiter) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_scg_grouping, V, as.integer(nt[1]), if (length(nt)==1) NULL else nt, mtype, algo, p, maxiter) res } #' Semi-Projectors #' #' A function to compute the \eqn{L} and \eqn{R} semi-projectors for a given #' partition of the vertices. #' #' The three types of semi-projectors are defined as follows. Let #' \eqn{\gamma(j)}{gamma(j)} label the group of vertex \eqn{j} in a partition #' of all the vertices. #' #' The symmetric semi-projectors are defined as \deqn{L_{\alpha j}=R_{\alpha #' j}= }{% L[alpha,j] = R[alpha,j] = 1/sqrt(|alpha|) #' delta[alpha,gamma(j)],}\deqn{ #' \frac{1}{\sqrt{|\alpha|}}\delta_{\alpha\gamma(j)},}{% L[alpha,j] = #' R[alpha,j] = 1/sqrt(|alpha|) delta[alpha,gamma(j)],} the (row) Laplacian #' semi-projectors as \deqn{L_{\alpha #' j}=\frac{1}{|\alpha|}\delta_{\alpha\gamma(j)}\,\,\,\, }{% L[alpha,j] = #' 1/|alpha| delta[alpha,gamma(j)] and R[alpha,j] = #' delta[alpha,gamma(j)],}\deqn{ \textrm{and}\,\,\,\, R_{\alpha #' j}=\delta_{\alpha\gamma(j)},}{% L[alpha,j] = 1/|alpha| delta[alpha,gamma(j)] #' and R[alpha,j] = delta[alpha,gamma(j)],} and the (row) stochastic #' semi-projectors as \deqn{L_{\alpha #' j}=\frac{p_{1}(j)}{\sum_{k\in\gamma(j)}p_{1}(k)}\,\,\,\, }{% L[alpha,j] = #' p[1][j] / sum(p[1][k]; k in gamma(j)) delta[alpha,gamma(j)] and R[alpha,j] = #' delta[alpha,gamma(j)],}\deqn{ \textrm{and}\,\,\,\, R_{\alpha #' j}=\delta_{\alpha\gamma(j)\delta_{\alpha\gamma(j)}},}{% L[alpha,j] = p[1][j] #' / sum(p[1][k]; k in gamma(j)) delta[alpha,gamma(j)] and R[alpha,j] = #' delta[alpha,gamma(j)],} where \eqn{p_1}{p[1]} is the (left) eigenvector #' associated with the one-eigenvalue of the stochastic matrix. \eqn{L} and #' \eqn{R} are defined in a symmetric way when \code{norm = col}. All these #' semi-projectors verify various properties described in the reference. #' #' @aliases scgSemiProjectors #' @param groups A vector of \code{nrow(X)} or \code{vcount(X)} integers giving #' the group label of every vertex in the partition. #' @param mtype The type of semi-projectors. For now \dQuote{symmetric}, #' \dQuote{laplacian} and \dQuote{stochastic} are available. #' @param p A probability vector of length \code{length(gr)}. \code{p} is the #' stationary probability distribution of a Markov chain when \code{mtype} = #' \dQuote{stochastic}. This parameter is ignored in all other cases. #' @param norm Either \dQuote{row} or \dQuote{col}. If set to \dQuote{row} the #' rows of the Laplacian matrix sum up to zero and the rows of the stochastic #' sum up to one; otherwise it is the columns. #' @param sparse Logical scalar, whether to return sparse matrices. #' @return \item{L}{The semi-projector \eqn{L}.} \item{R}{The semi-projector #' \eqn{R}.} #' @author David Morton de Lachapelle, #' \url{http://people.epfl.ch/david.morton}. #' @seealso \link{scg-method} for a detailed introduction. \code{\link{scg}}, #' \code{\link{scg_eps}}, \code{\link{scg_group}} #' @references D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, #' Shrinking Matrices while Preserving their Eigenpairs with Application to the #' Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on #' Matrix Analysis and Applications}, 2008. #' \url{http://people.epfl.ch/david.morton} #' @export #' @examples #' #' library(Matrix) #' # compute the semi-projectors and projector for the partition #' # provided by a community detection method #' g <- sample_pa(20, m = 1.5, directed = FALSE) #' eb <- cluster_edge_betweenness(g) #' memb <- membership(eb) #' lr <- scg_semi_proj(memb) #' #In the symmetric case L = R #' tcrossprod(lr$R) # same as lr$R %*% t(lr$R) #' P <- crossprod(lr$R) # same as t(lr$R) %*% lr$R #' #P is an orthogonal projector #' isSymmetric(P) #' sum( (P %*% P-P)^2 ) #' #' ## use L and R to coarse-grain the graph Laplacian #' lr <- scg_semi_proj(memb, mtype="laplacian") #' L <- laplacian_matrix(g) #' Lt <- lr$L %*% L %*% t(lr$R) #' ## or better lr$L %*% tcrossprod(L,lr$R) #' rowSums(Lt) #' scg_semi_proj <- function(groups, mtype=c("symmetric", "laplacian", "stochastic"), p=NULL, norm=c("row", "col"), sparse=igraph_opt("sparsematrices")) { # Argument checks groups <- as.numeric(groups)-1 mtype <- switch(igraph.match.arg(mtype), "symmetric"=1, "laplacian"=2, "stochastic"=3) if (!is.null(p)) p <- as.numeric(p) norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2) sparse <- as.logical(sparse) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_scg_semiprojectors, groups, mtype, p, norm, sparse) if (sparse) { res$L <- igraph.i.spMatrix(res$L) res$R <- igraph.i.spMatrix(res$R) } res } #' All-in-one Function for the SCG of Matrices and Graphs #' #' This function handles all the steps involved in the Spectral Coarse Graining #' (SCG) of some matrices and graphs as described in the reference below. #' #' Please see \link{scg-method} for an introduction. #' #' In the following \eqn{V} is the matrix of eigenvectors for which the SCG is #' solved. \eqn{V} is calculated from \code{X}, if it is not given in the #' \code{evec} argument. #' #' The algorithm \dQuote{optimum} solves exactly the SCG problem for each #' eigenvector in \code{V}. The running time of this algorithm is \eqn{O(\max #' nt \cdot m^2)}{O(max(nt) m^2)} for the symmetric and laplacian matrix #' problems (i.e. when \code{mtype} is \dQuote{symmetric} or #' \dQuote{laplacian}. It is \eqn{O(m^3)} for the stochastic problem. Here #' \eqn{m} is the number of rows in \code{V}. In all three cases, the memory #' usage is \eqn{O(m^2)}. #' #' The algorithms \dQuote{interv} and \dQuote{interv\_km} solve approximately #' the SCG problem by performing a (for now) constant binning of the components #' of the eigenvectors, that is \code{nt[i]} constant-size bins are used to #' partition \code{V[,i]}. When \code{algo} = \dQuote{interv\_km}, the (Lloyd) #' k-means algorithm is run on each partition obtained by \dQuote{interv} to #' improve accuracy. #' #' Once a minimizing partition (either exact or approximate) has been found for #' each eigenvector, the final grouping is worked out as follows: two vertices #' are grouped together in the final partition if they are grouped together in #' each minimizing partition. In general the size of the final partition is not #' known in advance when \code{ncol(V)}>1. #' #' Finally, the algorithm \dQuote{exact\_scg} groups the vertices with equal #' components in each eigenvector. The last three algorithms essentially have #' linear running time and memory load. #' #' @param X The input graph or square matrix. Can be of class \code{igraph}, #' \code{matrix} or \code{Matrix}. #' @param ev A vector of positive integers giving the indexes of the eigenpairs #' to be preserved. For real eigenpairs, 1 designates the eigenvalue with #' largest algebraic value, 2 the one with second largest algebraic value, etc. #' In the complex case, it is the magnitude that matters. #' @param nt A vector of positive integers of length one or equal to #' \code{length(ev)}. When \code{algo} = \dQuote{optimum}, \code{nt} contains #' the number of groups used to partition each eigenvector separately. When #' \code{algo} is equal to \dQuote{interv\_km} or \dQuote{interv}, \code{nt} #' contains the number of intervals used to partition each eigenvector. The #' same partition size or number of intervals is used for each eigenvector if #' \code{nt} is a single integer. When \code{algo} = \dQuote{exact\_cg} this #' parameter is ignored. #' @param groups A vector of \code{nrow(X)} or \code{vcount(X)} integers #' labeling each group vertex in the partition. If this parameter is supplied #' most part of the function is bypassed. #' @param mtype Character scalar. The type of semi-projector to be used for the #' SCG. For now \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} #' are available. #' @param algo Character scalar. The algorithm used to solve the SCG problem. #' Possible values are \dQuote{optimum}, \dQuote{interv\_km}, \dQuote{interv} #' and \dQuote{exact\_scg}. #' @param norm Character scalar. Either \dQuote{row} or \dQuote{col}. If set to #' \dQuote{row} the rows of the Laplacian matrix sum up to zero and the rows of #' the stochastic matrix sum up to one; otherwise it is the columns. #' @param direction Character scalar. When set to \dQuote{right}, resp. #' \dQuote{left}, the parameters \code{ev} and \code{evec} refer to right, #' resp. left eigenvectors. When passed \dQuote{default} it is the SCG #' described in the reference below that is applied (common usage). This #' argument is currently not implemented, and right eigenvectors are always #' used. #' @param evec A numeric matrix of (eigen)vectors to be preserved by the coarse #' graining (the vectors are to be stored column-wise in \code{evec}). If #' supplied, the eigenvectors should correspond to the indexes in \code{ev} as #' no cross-check will be done. #' @param p A probability vector of length \code{nrow(X)} (or #' \code{vcount(X)}). \code{p} is the stationary probability distribution of a #' Markov chain when \code{mtype} = \dQuote{stochastic}. This parameter is #' ignored in all other cases. #' @param use.arpack Logical scalar. When set to \code{TRUE} uses the function #' \code{\link{arpack}} to compute eigenpairs. This parameter should be set to #' \code{TRUE} if one deals with large (over a few thousands) AND sparse graphs #' or matrices. This argument is not implemented currently and LAPACK is used #' for solving the eigenproblems. #' @param maxiter A positive integer giving the maximum number of iterations #' for the k-means algorithm when \code{algo} = \dQuote{interv\_km}. This #' parameter is ignored in all other cases. #' @param sparse Logical scalar. Whether to return sparse matrices in the #' result, if matrices are requested. #' @param output Character scalar. Set this parameter to \dQuote{default} to #' retrieve a coarse-grained object of the same class as \code{X}. #' @param semproj Logical scalar. Set this parameter to \code{TRUE} to retrieve #' the semi-projectors of the SCG. #' @param epairs Logical scalar. Set this to \code{TRUE} to collect the #' eigenpairs computed by \code{scg}. #' @param stat.prob Logical scalar. This is to collect the stationary #' probability \code{p} when dealing with stochastic matrices. #' @return \item{Xt}{The coarse-grained graph, or matrix, possibly a sparse #' matrix.} \item{groups}{A vector of \code{nrow(X)} or \code{vcount(X)} #' integers giving the group label of each object (vertex) in the partition.} #' \item{L}{The semi-projector \eqn{L} if \code{semproj = TRUE}.} \item{R}{The #' semi-projector \eqn{R} if \code{semproj = TRUE}.} \item{values}{The computed #' eigenvalues if \code{epairs = TRUE}.} \item{vectors}{The computed or #' supplied eigenvectors if \code{epairs = TRUE}.} \item{p}{The stationary #' probability vector if \code{mtype = stochastic} and \code{stat.prob = TRUE}. #' For other matrix types this is missing.} #' @author David Morton de Lachapelle, #' \url{http://people.epfl.ch/david.morton}. #' @seealso \link{scg-method} for an introduction. \code{\link{scg_eps}}, #' \code{\link{scg_group}} and \code{\link{scg_semi_proj}}. #' @references D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, #' Shrinking Matrices while Preserving their Eigenpairs with Application to the #' Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on #' Matrix Analysis and Applications}, 2008. #' \url{http://people.epfl.ch/david.morton} #' @export #' @keywords graphs #' @examples #' #' #' ## We are not running these examples any more, because they #' ## take a long time (~20 seconds) to run and this is against the CRAN #' ## repository policy. Copy and paste them by hand to your R prompt if #' ## you want to run them. #' #' \dontrun{ #' # SCG of a toy network #' g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) #' g <- add_edges(g, c(1,6, 1,11, 6, 11)) #' cg <- scg(g, 1, 3, algo="exact_scg") #' #' #plot the result #' layout <- layout_with_kk(g) #' nt <- vcount(cg$Xt) #' col <- rainbow(nt) #' vsize <- table(cg$groups) #' ewidth <- round(E(cg$Xt)$weight,2) #' #' op <- par(mfrow=c(1,2)) #' plot(g, vertex.color = col[cg$groups], vertex.size = 20, #' vertex.label = NA, layout = layout) #' plot(cg$Xt, edge.width = ewidth, edge.label = ewidth, #' vertex.color = col, vertex.size = 20*vsize/max(vsize), #' vertex.label=NA, layout = layout_with_kk) #' par(op) #' #' ## SCG of real-world network #' library(igraphdata) #' data(immuno) #' summary(immuno) #' n <- vcount(immuno) #' interv <- c(100,100,50,25,12,6,3,2,2) #' cg <- scg(immuno, ev= n-(1:9), nt=interv, mtype="laplacian", #' algo="interv", epairs=TRUE) #' #' ## are the eigenvalues well-preserved? #' gt <- cg$Xt #' nt <- vcount(gt) #' Lt <- laplacian_matrix(gt) #' evalt <- eigen(Lt, only.values=TRUE)$values[nt-(1:9)] #' res <- cbind(interv, cg$values, evalt) #' res <- round(res,5) #' colnames(res) <- c("interv","lambda_i","lambda_tilde_i") #' rownames(res) <- c("N-1","N-2","N-3","N-4","N-5","N-6","N-7","N-8","N-9") #' print(res) #' #' ## use SCG to get the communities #' com <- scg(laplacian_matrix(immuno), ev=n-c(1,2), nt=2)$groups #' col <- rainbow(max(com)) #' layout <- layout_nicely(immuno) #' #' plot(immuno, layout=layout, vertex.size=3, vertex.color=col[com], #' vertex.label=NA) #' #' ## display the coarse-grained graph #' gt <- simplify(as.undirected(gt)) #' layout.cg <- layout_with_kk(gt) #' com.cg <- scg(laplacian_matrix(gt), nt-c(1,2), 2)$groups #' vsize <- sqrt(as.vector(table(cg$groups))) #' #' op <- par(mfrow=c(1,2)) #' plot(immuno, layout=layout, vertex.size=3, vertex.color=col[com], #' vertex.label=NA) #' plot(gt, layout=layout.cg, vertex.size=15*vsize/max(vsize), #' vertex.color=col[com.cg],vertex.label=NA) #' par(op) #' #' } #' scg <- function(X, ev, nt, groups=NULL, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), norm=c("row", "col"), direction=c("default", "left", "right"), evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300, sparse=igraph_opt("sparsematrices"), output=c("default", "matrix", "graph"), semproj=FALSE, epairs=FALSE, stat.prob=FALSE) UseMethod("scg") #' @method scg igraph #' @export scg.igraph <- function(X, ev, nt, groups=NULL, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), norm=c("row", "col"), direction=c("default", "left", "right"), evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300, sparse=igraph_opt("sparsematrices"), output=c("default", "matrix", "graph"), semproj=FALSE, epairs=FALSE, stat.prob=FALSE) { myscg(graph=X, matrix=NULL, sparsemat=NULL, ev=ev, nt=nt, groups=groups, mtype=mtype, algo=algo, norm=norm, direction=direction, evec=evec, p=p, use.arpack=use.arpack, maxiter=maxiter, sparse=sparse, output=output, semproj=semproj, epairs=epairs, stat.prob=stat.prob) } #' @method scg matrix #' @export scg.matrix <- function(X, ev, nt, groups=NULL, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), norm=c("row", "col"), direction=c("default", "left", "right"), evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300, sparse=igraph_opt("sparsematrices"), output=c("default", "matrix", "graph"), semproj=FALSE, epairs=FALSE, stat.prob=FALSE) { myscg(graph=NULL, matrix=X, sparsemat=NULL, ev=ev, nt=nt, groups=groups, mtype=mtype, algo=algo, norm=norm, direction=direction, evec=evec, p=p, use.arpack=use.arpack, maxiter=maxiter, sparse=sparse, output=output, semproj=semproj, epairs=epairs, stat.prob=stat.prob) } #' @method scg Matrix #' @export scg.Matrix <- function(X, ev, nt, groups=NULL, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), norm=c("row", "col"), direction=c("default", "left", "right"), evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300, sparse=igraph_opt("sparsematrices"), output=c("default", "matrix", "graph"), semproj=FALSE, epairs=FALSE, stat.prob=FALSE) { myscg(graph=NULL, matrix=NULL, sparsemat=X, ev=ev, nt=nt, groups=groups, mtype=mtype, algo=algo, norm=norm, direction=direction, evec=evec, p=p, use.arpack=use.arpack, maxiter=maxiter, sparse=sparse, output=output, semproj=semproj, epairs=epairs, stat.prob=stat.prob) } myscg <- function(graph, matrix, sparsemat, ev, nt, groups=NULL, mtype=c("symmetric", "laplacian", "stochastic"), algo=c("optimum", "interv_km", "interv", "exact_scg"), norm=c("row", "col"), direction=c("default", "left", "right"), evec=NULL, p=NULL, use.arpack=FALSE, maxiter=300, sparse=igraph_opt("sparsematrices"), output=c("default", "matrix", "graph"), semproj=FALSE, epairs=FALSE, stat.prob=FALSE) { ## Argument checks if (!is.null(graph)) { stopifnot(is_igraph(graph)) } if (!is.null(matrix)) { stopifnot(is.matrix(matrix)) } if (!is.null(sparsemat)) { stopifnot(inherits(sparsemat, "Matrix")) } if (!is.null(sparsemat)) { sparsemat <- as(sparsemat, "dgCMatrix") } ev <- as.numeric(as.integer(ev)) nt <- as.numeric(as.integer(nt)) if (!is.null(groups)) groups <- as.numeric(groups) mtype <- igraph.match.arg(mtype) algo <- switch(igraph.match.arg(algo), "optimum"=1, "interv_km"=2, "interv"=3, "exact_scg"=4) if (!is.null(groups)) { storage.mode(groups) <- "double" } use.arpack <- as.logical(use.arpack) maxiter <- as.integer(maxiter) sparse <- as.logical(sparse) output <- switch(igraph.match.arg(output), "default"=1, "matrix"=2, "graph"=3) semproj <- as.logical(semproj) epairs <- as.logical(epairs) on.exit( .Call(C_R_igraph_finalizer) ) if (mtype=="symmetric") { if (!is.null(evec)) { storage.mode(evec) <- "double" } res <- .Call(C_R_igraph_scg_adjacency, graph, matrix, sparsemat, ev, nt, algo, evec, groups, use.arpack, maxiter, sparse, output, semproj, epairs) } else if (mtype=="laplacian") { norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2) if (!is.null(evec)) { storage.mode(evec) <- "complex" } direction <- switch(igraph.match.arg(direction), "default"=1, "left"=2, "right"=3) res <- .Call(C_R_igraph_scg_laplacian, graph, matrix, sparsemat, ev, nt, algo, norm, direction, evec, groups, use.arpack, maxiter, sparse, output, semproj, epairs) } else if (mtype=="stochastic") { norm <- switch(igraph.match.arg(norm), "row"=1, "col"=2) if (!is.null(evec)) { storage.mode(evec) <- "complex" } if (!is.null(p)) { storage.mode(p) <- "double" } stat.prob <- as.logical(stat.prob) res <- .Call(C_R_igraph_scg_stochastic, graph, matrix, sparsemat, ev, nt, algo, norm, evec, groups, p, use.arpack, maxiter, sparse, output, semproj, epairs, stat.prob) } if (!is.null(res$Xt) && class(res$Xt) == "igraph.tmp.sparse") { res$Xt <- igraph.i.spMatrix(res$Xt) } if (!is.null(res$L) && class(res$L) == "igraph.tmp.sparse") { res$L <- igraph.i.spMatrix(res$L) } if (!is.null(res$R) && class(res$R) == "igraph.tmp.sparse") { res$R <- igraph.i.spMatrix(res$R) } res } #' Error of the spectral coarse graining (SCG) approximation #' #' \code{scg_eps} computes \eqn{\Vert v_i-Pv_i\Vert}{|v[i]-Pv[i]|}, where #' \eqn{v_i}{v[i]} is the \eqn{i}th eigenvector in \code{V} and \eqn{P} is the #' projector corresponding to the \code{mtype} argument. #' #' @aliases scg_eps scgNormEps #' @param V A numeric matrix of (eigen)vectors assumed normalized. The vectors #' are to be stored column-wise in \code{V}). #' @param groups A vector of \code{nrow(V)} integers labeling each group vertex #' in the partition. #' @param mtype The type of semi-projector used for the SCG. For now #' \dQuote{symmetric}, \dQuote{laplacian} and \dQuote{stochastic} are #' available. #' @param p A probability vector of length \code{nrow(V)}. \code{p} is the #' stationary probability distribution of a Markov chain when \code{mtype} = #' \dQuote{stochastic}. This parameter is ignored otherwise. #' @param norm Either \dQuote{row} or \dQuote{col}. If set to \dQuote{row} the #' rows of the Laplacian matrix sum to zero and the rows of the stochastic #' matrix sum to one; otherwise it is the columns. #' @return \code{scg_eps} returns with a numeric vector whose \eqn{i}th #' component is \eqn{\Vert v_i-Pv_i\Vert}{|v[i]-Pv[i]|} (see Details). #' @author David Morton de Lachapelle, #' \url{http://people.epfl.ch/david.morton}. #' @seealso \link{scg-method} and \code{\link{scg}}. #' @references D. Morton de Lachapelle, D. Gfeller, and P. De Los Rios, #' Shrinking Matrices while Preserving their Eigenpairs with Application to the #' Spectral Coarse Graining of Graphs. Submitted to \emph{SIAM Journal on #' Matrix Analysis and Applications}, 2008. #' \url{http://people.epfl.ch/david.morton} #' @examples #' #' v <- rexp(20) #' km <- kmeans(v,5) #' sum(km$withinss) #' scg_eps(cbind(v), km$cluster)^2 scg_eps <- scg_eps igraph/R/demo.R0000644000175100001440000001437613177712334013035 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Run igraph demos, step by step #' #' Run one of the accompanying igraph demos, somewhat interactively, using a Tk #' window. #' #' This function provides a somewhat nicer interface to igraph demos that come #' with the package, than the standard \code{\link{demo}} function. Igraph #' demos are divided into chunks and \code{igraph_demo} runs them chunk by #' chunk, with the possibility of inspecting the workspace between two chunks. #' #' The \code{tcltk} package is needed for \code{igraph_demo}. #' #' @aliases igraphdemo #' @param which If not given, then the names of the available demos are listed. #' Otherwise it should be either a filename or the name of an igraph demo. #' @return Returns \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{demo}} #' @export #' @keywords graphs #' @examples #' #' igraph_demo() #' if (interactive()) { #' igraph_demo("centrality") #' } #' igraph_demo <- function(which) { if (missing(which)) { demodir <- system.file("demo", package="igraph") if (demodir=="") { stop("Could not find igraph demos, broken igraph installation?") } return( sub("\\.R$", "", list.files(demodir)) ) } if (!grepl("\\.R$", which)) { which <- paste(which, sep=".", "R") } if (!file.exists(which) && ! grepl("^/", which)) { which <- system.file( paste("demo", sep="/", which), package="igraph" ) } if (which=="" || !file.exists(which)) { stop("Could not find demo file") } .igraphdemo.next <- function(top, txt) { act <- as.character(tcltk::tktag.nextrange(txt, "active", "0.0")) if (length(act)==0) { return() } options(keep.source=TRUE) text <- tcltk::tclvalue(tcltk::tkget(txt, act[1], act[2])) cat("=======================================================\n"); expr <- parse(text=text) for (i in seq_along(expr)) { co <- as.character(attributes(expr)$srcref[[i]]) co[1] <- paste("> ", sep="", co[1]) if (length(co)>1) { co[-1] <- paste(" +", sep="", co[-1]) } cat(co, sep="\n") res <- withVisible(eval(expr[[i]], envir=.GlobalEnv)) if (res$visible) { print(res$value) } } cat("> -------------------------------------------------------\n"); cat(options()$prompt) tcltk::tktag.remove(txt, "activechunk", act[1], act[2]) tcltk::tktag.remove(txt, "active", act[1], act[2]) nex <- as.character(tcltk::tktag.nextrange(txt, "activechunk", act[1])) if (length(nex)!=0) { tcltk::tktag.add(txt, "active", nex[1], nex[2]) tcltk::tksee(txt, paste(sep="", as.numeric(nex[2]), ".0")) tcltk::tksee(txt, paste(sep="", as.numeric(nex[1]), ".0")) } } .igraphdemo.close <- function(top) { tcltk::tkdestroy(top) } .igraphdemo.reset <- function(top, txt, which) { demolines <- readLines(which) demolines <- demolines[!grepl("^pause\\(\\)$", demolines)] demolines <- paste(" ", sep="", demolines) ch <- grep("^[ ]*###", demolines) ch <- c(ch, length(demolines)+1) if (length(ch)==1) { warning("Demo source file does not contain chunks") } else { demolines <- demolines[ch[1]:length(demolines)] ch <- grep("^[ ]*###", demolines) ch <- c(ch, length(demolines)+1) } tcltk::tkconfigure(txt, state="normal") tcltk::tkdelete(txt, "0.0", "end") tcltk::tkinsert(txt, "insert", paste(demolines, collapse="\n")) tcltk::tkconfigure(txt, state="disabled") for (i in seq_along(ch[-1])) { from <- paste(sep="", ch[i], ".0") to <- paste(sep="", ch[i+1]-1, ".0") tcltk::tktag.add(txt, "chunk", from, to) tcltk::tktag.add(txt, "activechunk", from, to) } tcltk::tktag.configure(txt, "chunk", "-borderwidth", "1") tcltk::tktag.configure(txt, "chunk", "-relief", "sunken") if (length(ch) >= 2) { tcltk::tktag.add(txt, "active", paste(sep="", ch[1], ".0"), paste(sep="", ch[2]-1, ".0")) tcltk::tktag.configure(txt, "active", "-foreground", "red") tcltk::tktag.configure(txt, "active", "-background", "lightgrey") } comm <- grep("^#", demolines) for (i in comm) { tcltk::tktag.add(txt, "comment", paste(sep="", i, ".0"), paste(sep="", i, ".end")) } tcltk::tktag.configure(txt, "comment", "-font", "bold") tcltk::tktag.configure(txt, "comment", "-foreground", "darkolivegreen") } top <- tcltk::tktoplevel(background="lightgrey") tcltk::tktitle(top) <- paste("igraph demo:", which) main.menu <- tcltk::tkmenu(top) tcltk::tkadd(main.menu, "command", label="Close", command=function() .igraphdemo.close(top)) tcltk::tkadd(main.menu, "command", label="Reset", command=function() .igraphdemo.reset(top, txt, which)) tcltk::tkconfigure(top, "-menu", main.menu) scr <- tcltk::tkscrollbar(top, repeatinterval=5, command=function(...) tcltk::tkyview(txt,...)) txt <- tcltk::tktext(top, yscrollcommand=function(...) tcltk::tkset(scr, ...), width=80, height=40) but <- tcltk::tkbutton(top, text="Next", command=function() .igraphdemo.next(top, txt)) tcltk::tkpack(but, side="bottom", fill="x", expand=0) tcltk::tkpack(scr, side="right", fill="y", expand=0) tcltk::tkpack(txt, side="left", fill="both", expand=1) .igraphdemo.reset(top, txt, which) invisible() } igraph/R/foreign.R0000644000175100001440000005021213247067610013525 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Reading foreign file formats ################################################################### read.graph.toraw <- function(filename) { if (is.character(filename)) { filename <- file(filename, open="rb") } if (!isOpen(filename)) { open(filename, open="rb") } tmpbufsize <- 20000 buffer <- tmpbuffer <- readBin(filename, what=raw(0), n=tmpbufsize) while (length(tmpbuffer) == tmpbufsize) { tmpbuffer <- readBin(filename, what=raw(0), n=tmpbufsize) buffer <- c(buffer, tmpbuffer) } close(filename) rm(tmpbuffer) buffer } write.graph.fromraw <- function(buffer, file) { closeit <- FALSE if (is.character(file)) { file <- file(file, open="w+b") closeit <- TRUE } if (!isOpen(file)) { file <- open(file) closeit <- TRUE } writeBin(buffer, file) if (closeit) { close(file) } invisible(NULL) } #' Reading foreign file formats #' #' The \code{read_graph} function is able to read graphs in various #' representations from a file, or from a http connection. Currently some #' simple formats are supported. #' #' The \code{read_graph} function may have additional arguments depending on #' the file format (the \code{format} argument). See the details separately for #' each file format, below. #' #' @aliases read.graph LGL Pajek GraphML GML DL UCINET #' @param file The connection to read from. This can be a local file, or a #' \code{http} or \code{ftp} connection. It can also be a character string with #' the file name or URI. #' @param format Character constant giving the file format. Right now #' \code{as_edgelist}, \code{pajek}, \code{graphml}, \code{gml}, \code{ncol}, #' \code{lgl}, \code{dimacs} and \code{graphdb} are supported, the default is #' \code{edgelist}. As of igraph 0.4 this argument is case insensitive. #' @param \dots Additional arguments, see below. #' @return A graph object. #' @section Edge list format: This format is a simple text file with numeric #' vertex ids defining the edges. There is no need to have newline characters #' between the edges, a simple space will also do. #' #' Additional arguments: \describe{ \item{n}{The number of vertices in the #' graph. If it is smaller than or equal to the largest integer in the file, #' then it is ignored; so it is safe to set it to zero (the default).} #' \item{directed}{Logical scalar, whether to create a directed graph. The #' default value is \code{TRUE}.} } #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{write_graph}} #' @keywords graphs #' @export read_graph <- function(file, format=c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ...) { if (!is.character(file) || length(grep("://", file, fixed=TRUE)) > 0 || length(grep("~", file, fixed=TRUE)) > 0) { buffer <- read.graph.toraw(file) file <- tempfile() write.graph.fromraw(buffer, file) } format <- igraph.match.arg(format) res <- switch(format, "pajek"=read.graph.pajek(file, ...), "ncol"=read.graph.ncol(file, ...), "edgelist"=read.graph.edgelist(file, ...), "lgl"=read.graph.lgl(file, ...), "graphml"=read.graph.graphml(file, ...), "dimacs"=read.graph.dimacs(file, ...), "graphdb"=read.graph.graphdb(file, ...), "gml"=read.graph.gml(file, ...), "dl"=read.graph.dl(file, ...), stop(paste("Unknown file format:",format)) ) res } #' Writing the graph to a file in some format #' #' \code{write_graph} is a general function for exporting graphs to foreign #' file formats, however not many formats are implemented right now. #' #' @aliases write.graph #' @param graph The graph to export. #' @param file A connection or a string giving the file name to write the graph #' to. #' @param format Character string giving the file format. Right now #' \code{pajek}, \code{graphml}, \code{dot}, \code{gml}, \code{edgelist}, #' \code{lgl}, \code{ncol} and \code{dimacs} are implemented. As of igraph 0.4 #' this argument is case insensitive. #' @param \dots Other, format specific arguments, see below. #' @return A NULL, invisibly. #' @section Edge list format: The \code{edgelist} format is a simple text file, #' with one edge in a line, the two vertex ids separated by a space character. #' The file is sorted by the first and the second column. This format has no #' additional arguments. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{read_graph}} #' @references Adai AT, Date SV, Wieland S, Marcotte EM. LGL: creating a map of #' protein function with an algorithm for visualizing very large biological #' networks. \emph{J Mol Biol.} 2004 Jun 25;340(1):179-90. #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' \dontrun{write_graph(g, "/tmp/g.txt", "edgelist")} #' write_graph <- function(graph, file, format=c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ...) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.character(file) || length(grep("://", file, fixed=TRUE)) > 0 || length(grep("~", file, fixed=TRUE)) > 0) { tmpfile <- TRUE origfile <- file file <- tempfile() } else { tmpfile <- FALSE } format <- igraph.match.arg(format) res <- switch(format, "pajek"=write.graph.pajek(graph, file, ...), "edgelist"=write.graph.edgelist(graph, file, ...), "ncol"=write.graph.ncol(graph, file, ...), "lgl"=write.graph.lgl(graph, file, ...), "graphml"=write.graph.graphml(graph, file, ...), "dimacs"=write.graph.dimacs(graph, file, ...), "gml"=write.graph.gml(graph, file, ...), "dot"=write.graph.dot(graph, file, ...), "leda"=write.graph.leda(graph, file, ...), stop(paste("Unknown file format:",format)) ) if (tmpfile) { buffer <- read.graph.toraw(file) write.graph.fromraw(buffer, origfile) } invisible(res) } ################################################################ # Plain edge list format, not sorted ################################################################ read.graph.edgelist <- function(file, n=0, directed=TRUE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (edgelist format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_edgelist, file, as.numeric(n), as.logical(directed)) } write.graph.edgelist <- function(graph, file, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (edgelist format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_edgelist, graph, file) } ################################################################ # NCOL and LGL formats, quite simple ################################################################ read.graph.ncol <- function(file, predef=character(0), names=TRUE, weights=c("auto", "yes", "no"), directed=FALSE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (NCOL format)") } weights <- switch(igraph.match.arg(weights), "no"=0, "yes"=1, "auto"=2) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_ncol, file, as.character(predef), as.logical(names), as.numeric(weights), as.logical(directed)) } write.graph.ncol <- function(graph, file, names="name", weights="weight", ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (NCOL format)") } names <- as.character(names) weights <- as.character(weights) if (length(names)==0 || ! names %in% vertex_attr_names(graph)) { names <- NULL } if (length(weights)==0 || ! weights %in% edge_attr_names(graph)) { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_ncol, graph, file, names, weights) } read.graph.lgl <- function(file, names=TRUE, weights=c("auto", "yes", "no"), directed=FALSE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (LGL format)") } weights <- switch(igraph.match.arg(weights), "no"=0, "yes"=1, "auto"=2) on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_lgl, file, as.logical(names), as.numeric(weights), as.logical(directed)) } write.graph.lgl <- function(graph, file, names="name", weights="weight", isolates=FALSE, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (LGL format)") } names <- as.character(names) weights <- as.character(weights) if (length(names)==0 || ! names %in% vertex_attr_names(graph)) { names <- NULL } if (length(weights)==0 || ! weights %in% edge_attr_names(graph)) { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_lgl, graph, file, names, weights, as.logical(isolates)) } read.graph.pajek <- function(file, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (Pajek format)") } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_read_graph_pajek, file) if ("type" %in% vertex_attr_names(res)) { type <- as.logical(V(res)$type) res <- delete_vertex_attr(res, "type") res <- set_vertex_attr(res, "type", value=type) } res } write.graph.pajek <- function(graph, file, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (Pajek format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_pajek, graph, file) } read.graph.dimacs <- function(file, directed=TRUE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (DIMACS format)") } res <- .Call(C_R_igraph_read_graph_dimacs, file, as.logical(directed)) if (res[[1]][1] == "max") { graph <- res[[2]] graph <- set_graph_attr(graph, "problem", res[[1]]) graph <- set_graph_attr(graph, "source", res[[3]]) graph <- set_graph_attr(graph, "target", res[[4]]) E(graph)$capacity <- res[[5]] graph } else if (res[[1]][1] == "edge") { graph <- res[[2]] graph <- set_graph_attr(graph, "problem", res[[1]]) V(graph)$label <- res[[3]] graph } } write.graph.dimacs <- function(graph, file, source=NULL, target=NULL, capacity=NULL, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (DIMACS format)") } if (is.null(source)) { source <- graph_attr(graph, "source") } if (is.null(target)) { target <- graph_attr(graph, "target") } if (is.null(capacity)) { capacity <- E(graph)$capacity } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_dimacs, graph, file, as.numeric(source), as.numeric(target), as.numeric(capacity)) } ################################################################ # GraphML ################################################################ read.graph.graphml <- function(file, index=0, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (GraphML format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_graphml, file, as.numeric(index)) } write.graph.graphml <- function(graph, file, prefixAttr=TRUE, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (GraphML format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_graphml, graph, file, as.logical(prefixAttr)) } ################################################################ # GML ################################################################ read.graph.gml <- function(file, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (GML format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_gml, file) } write.graph.gml <- function(graph, file, id=NULL, creator=NULL, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (GML format)") } if (!is.null(id)) { id <- as.numeric(id) } if (!is.null(creator)) { creator <- as.character(creator) } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_gml, graph, file, id, creator) } ################################################################ # UCINET DL ################################################################ read.graph.dl <- function(file, directed=TRUE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (DL format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_dl, file, as.logical(directed)) } ################################################################ # Dot ################################################################ write.graph.dot <- function(graph, file, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (DOT format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_dot, graph, file) } ################################################################ # Download a file from the graph database for # isomorphic problems ################################################################ #' Load a graph from the graph database for testing graph isomorphism. #' #' This function downloads a graph from a database created for the evaluation #' of graph isomorphism testing algothitms. #' #' \code{graph_from_graphdb} reads a graph from the graph database from an FTP or #' HTTP server or from a local copy. It has two modes of operation: #' #' If the \code{url} argument is specified then it should the complete path to #' a local or remote graph database file. In this case we simply call #' \code{\link{read_graph}} with the proper arguments to read the file. #' #' If \code{url} is \code{NULL}, and this is the default, then the filename is #' assembled from the \code{base}, \code{prefix}, \code{type}, \code{nodes}, #' \code{pair} and \code{which} arguments. #' #' Unfortunately the original graph database homepage is now defunct, but see #' its old version at #' \url{http://web.archive.org/web/20090215182331/http://amalfi.dis.unina.it/graph/db/doc/graphdbat.html} #' for the actual format of a graph database file and other information. #' #' @aliases graph.graphdb #' @param url If not \code{NULL} it is a complete URL with the file to import. #' @param prefix Gives the prefix. See details below. Possible values: #' \code{iso}, \code{i2}, \code{si4}, \code{si6}, \code{mcs10}, \code{mcs30}, #' \code{mcs50}, \code{mcs70}, \code{mcs90}. #' @param type Gives the graph type identifier. See details below. Possible #' values: \code{r001}, \code{r005}, \code{r01}, \code{r02}, \code{m2D}, #' \code{m2Dr2}, \code{m2Dr4}, \code{m2Dr6} \code{m3D}, \code{m3Dr2}, #' \code{m3Dr4}, \code{m3Dr6}, \code{m4D}, \code{m4Dr2}, \code{m4Dr4}, #' \code{m4Dr6}, \code{b03}, \code{b03m}, \code{b06}, \code{b06m}, \code{b09}, #' \code{b09m}. #' @param nodes The number of vertices in the graph. #' @param pair Specifies which graph of the pair to read. Possible values: #' \code{A} and \code{B}. #' @param which Gives the number of the graph to read. For every graph type #' there are a number of actual graphs in the database. This argument specifies #' which one to read. #' @param base The base address of the database. See details below. #' @param compressed Logical constant, if TRUE than the file is expected to be #' compressed by gzip. If \code{url} is \code{NULL} then a \sQuote{\code{.gz}} #' suffix is added to the filename. #' @param directed Logical constant, whether to create a directed graph. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{read_graph}}, \code{\link{graph.isomorphic.vf2}} #' @references M. De Santo, P. Foggia, C. Sansone, M. Vento: A large database #' of graphs and its use for benchmarking graph isomorphism algorithms, #' \emph{Pattern Recognition Letters}, Volume 24, Issue 8 (May 2003) #' @export #' @keywords graphs #' @section Examples: #' \preformatted{ #' g <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="A", #' which=10, compressed=TRUE) #' g2 <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="B", #' which=10, compressed=TRUE) #' graph.isomorphic.vf2(g, g2) \% should be TRUE #' g3 <- graph_from_graphdb(url=paste(sep="/", #' "http://cneurocvs.rmki.kfki.hu", #' "graphdb/gzip/iso/bvg/b06m", #' "iso_b06m_m200.A09.gz")) #' } graph_from_graphdb <- function(url=NULL, prefix="iso", type="r001", nodes=NULL, pair="A", which=0, base="http://cneurocvs.rmki.kfki.hu/graphdb/gzip", compressed=TRUE, directed=TRUE) { if (is.null(nodes) && is.null(url)) { stop("The `nodes' or the `url' argument must be non-null") } if (is.null(url)) { prefixes <- c("iso", "si6", "mcs10", "mcs30", "mcs50", "mcs70", "mcs90") types <- c("r001", "r005", "r01", "r02", "m2D", "m2Dr2", "m2Dr4", "m2Dr6", "m3D", "m3Dr2", "m3Dr4", "m3Dr6", "m4D", "m4Dr2", "m4Dr4", "m4Dr6", "b03", "b03m", "b06", "b06m", "b09", "b09m") sizecode <- if (nodes<=100) "s" else if (nodes<2000) "m" else "l" # "l" ???? typegroups <- c("rand", "rand", "rand", "rand", "m2D", "m2D", "m2D", "m2D", "m2D", "m3D", "m3D", "m3D", "m4D", "m4D", "m4D", "m4D", "bvg", "bvg", "bvg", "bvg", "bvg", "bvg") typegroup <- typegroups[which(types==type)] if (!prefix %in% prefixes) { stop("Invalid prefix!") } if (!type %in% types) { stop("Invalid graph type!") } suff <- if (compressed) ".gz" else "" filename <- paste(sep="", base, "/", prefix, "/", typegroup, "/", type, "/", prefix, "_", type, "_", sizecode, nodes, ".", pair, formatC(which, width=2, flag="0"), suff) } else { filename <- url } ## ok, we have the filename f <- try(gzcon(file(filename, open="rb"))) if (inherits(f, "try-error")) { stop(paste("Cannot open URL:", filename)); } buffer <- read.graph.toraw(f) f <- tempfile() write.graph.fromraw(buffer, f) .Call(C_R_igraph_read_graph_graphdb, f, as.logical(directed)) } read.graph.graphdb <- function(file, directed=TRUE, ...) { if (length(list(...))>0) { stop("Unknown arguments to read_graph (GraphDB format)") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_read_graph_graphdb, file, as.logical(directed)) } write.graph.leda <- function(graph, file, vertex.attr=NULL, edge.attr=NULL, ...) { if (length(list(...))>0) { stop("Unknown arguments to write_graph (LEDA format)") } if (!is.null(vertex.attr)) { vertex.attr <- as.character(vertex.attr) } if (!is.null(edge.attr)) { edge.attr <- as.character(edge.attr) } on.exit(.Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_write_graph_leda, graph, file, vertex.attr, edge.attr) } igraph/R/package.R0000644000175100001440000000210513177712334013467 0ustar hornikusers # IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### .onAttach <- function(library, pkg) { ## we can't do this in .onLoad unlockBinding(".igraph.pb", asNamespace("igraph")) invisible() } igraph/R/sgm.R0000644000175100001440000001225213177712334012666 0ustar hornikusers solve_LSAP <- function (x, maximum = FALSE) { if (!is.matrix(x) || any(x < 0)) { stop("x must be a matrix with nonnegative entries.") } nr <- nrow(x) nc <- ncol(x) if (nr > nc) stop("x must not have more rows than columns.") if (nc > nr) x <- rbind(x, matrix(2 * sum(x), nc - nr, nc)) if (maximum) x <- max(x) - x storage.mode(x) <- "double" out <- .Call(C_R_igraph_solve_lsap, x, as.integer(nc)) + 1L out[seq_len(nr)] } #' Match Graphs given a seeding of vertex correspondences #' #' Given two adjacency matrices \code{A} and \code{B} of the same size, match #' the two graphs with the help of \code{m} seed vertex pairs which correspond #' to the first \code{m} rows (and columns) of the adjacency matrices. #' #' The approximate graph matching problem is to find a bijection between the #' vertices of two graphs , such that the number of edge disagreements between #' the corresponding vertex pairs is minimized. For seeded graph matching, part #' of the bijection that consist of known correspondences (the seeds) is known #' and the problem task is to complete the bijection by estimating the #' permutation matrix that permutes the rows and columns of the adjacency #' matrix of the second graph. #' #' It is assumed that for the two supplied adjacency matrices \code{A} and #' \code{B}, both of size \eqn{n\times n}{n*n}, the first \eqn{m} rows(and #' columns) of \code{A} and \code{B} correspond to the same vertices in both #' graphs. That is, the \eqn{n \times n}{n*n} permutation matrix that defines #' the bijection is \eqn{I_{m} \bigoplus P} for a \eqn{(n-m)\times #' (n-m)}{(n-m)*(n-m)} permutation matrix \eqn{P} and \eqn{m} times \eqn{m} #' identity matrix \eqn{I_{m}}. The function \code{match_vertices} estimates #' the permutation matrix \eqn{P} via an optimization algorithm based on the #' Frank-Wolfe algorithm. #' #' See references for further details. #' #' @aliases match_vertices seeded.graph.match #' @param A a numeric matrix, the adjacency matrix of the first graph #' @param B a numeric matrix, the adjacency matrix of the second graph #' @param m The number of seeds. The first \code{m} vertices of both graphs are #' matched. #' @param start a numeric matrix, the permutation matrix estimate is #' initialized with \code{start} #' @param iteration The number of iterations for the Frank-Wolfe algorithm #' @return A numeric matrix which is the permutation matrix that determines the #' bijection between the graphs of \code{A} and \code{B} #' @author Vince Lyzinski \url{http://www.ams.jhu.edu/~lyzinski/} #' @seealso #' \code{\link{sample_correlated_gnp}},\code{\link{sample_correlated_gnp_pair}} #' @references Vogelstein, J. T., Conroy, J. M., Podrazik, L. J., Kratzer, S. #' G., Harley, E. T., Fishkind, D. E.,Vogelstein, R. J., Priebe, C. E. (2011). #' Fast Approximate Quadratic Programming for Large (Brain) Graph Matching. #' Online: \url{http://arxiv.org/abs/1112.5507} #' #' Fishkind, D. E., Adali, S., Priebe, C. E. (2012). Seeded Graph Matching #' Online: \url{http://arxiv.org/abs/1209.0367} #' @keywords graphs #' @examples #' #' #require(Matrix) #' g1 <- erdos.renyi.game(10, .1) #' randperm <- c(1:3, 3+sample(7)) #' g2 <- sample_correlated_gnp(g1, corr=1, p=g1$p, perm=randperm) #' A <- as.matrix(get.adjacency(g1)) #' B <- as.matrix(get.adjacency(g2)) #' P <-match_vertices (A, B, m=3, start=diag(rep(1, nrow(A)-3)), 20) #' P #' @export match_vertices <- function(A, B, m, start, iteration) { ## Seeds are assumed to be vertices 1:m in both graphs totv <- ncol(A) n <- totv - m if (m != 0) { A12 <- A[1:m, (m+1):(m+n), drop=FALSE] A21 <- A[(m+1):(m+n), 1:m, drop=FALSE] B12 <- B[1:m, (m+1):(m+n), drop=FALSE] B21 <- B[(m+1):(m+n), 1:m, drop=FALSE] } if ( m==0 ) { A12 <- Matrix::Matrix(0, n, n) A21 <- Matrix::Matrix(0, n, n) B12 <- Matrix::Matrix(0, n, n) B21 <- Matrix::Matrix(0, n, n) } A22 <- A[(m+1):(m+n), (m+1):(m+n)] B22 <- B[(m+1):(m+n), (m+1):(m+n)] patience <- iteration tol <- 1 P <- start toggle <- 1 iter <- 0 while (toggle == 1 & iter < patience) { iter <- iter+1 x <- A21 %*% Matrix::t(B21) y <- Matrix::t(A12) %*% B12 z <- A22 %*% P %*% Matrix::t(B22) w <- Matrix::t(A22) %*% P %*% B22 Grad <- x + y + z + w ind <- unclass(solve_LSAP(as.matrix(Grad), maximum = TRUE)) ind2 <- cbind(1:n, ind) T <- Matrix::Diagonal(n) T <- T[ind, ] wt <- Matrix::t(A22)[,order(ind)] %*% B22 c <- sum(w * P) d <- sum(wt * P) + sum(w [ ind2 ]) e <- sum(wt[ind2]) u <- sum(P * (x + y)) v <- sum((x + y)[ind2]) if ( c-d+e == 0 && d-2*e+u-v == 0) { alpha <- 0 } else { alpha <- -(d-2*e+u-v) / (2*(c-d+e))} f0 <- 0 f1 <- c-e+u-v falpha <- (c-d+e) * alpha^2 + (d-2*e+u-v) * alpha if (alpha < tol && alpha > 0 && falpha > f0 && falpha > f1) { P <- alpha*P + (1-alpha) * T } else if (f0 > f1) { P <- T } else { toggle <- 0 } } D <- P corr <- matrix(solve_LSAP(as.matrix(P), maximum = TRUE)) P = Matrix::diag(n) P = rbind(cbind(Matrix::diag(m), matrix(0, m, n)), cbind(matrix(0, n, m), P[corr, ])) corr <- cbind(matrix((m+1):totv, n), matrix(m+corr, n)) list(corr=corr, P=P, D=D) } igraph/R/epi.R0000644000175100001440000001657213177712334012666 0ustar hornikusers# IGraph R package # Copyright (C) 2014 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' @export time_bins <- function(x, middle=TRUE) UseMethod("time_bins") #' @method time_bins sir #' @rdname sir #' @export #' @importFrom stats IQR time_bins.sir <- function(x, middle=TRUE) { sir <- x if (!inherits(sir, "sir")) { stop("This is not an SIR model output") } big.time <- unlist(sapply(sir, "[[", "times")) medlen <- median(sapply(lapply(sir, "[[", "times"), length)) ## Adhoc use of Freedman-Diaconis binwidth; rescale time accordingly. w <- 2 * IQR(big.time) / (medlen^(1/3)) minbt <- min(big.time) ; maxbt <- max(big.time) res <- seq(minbt, maxbt, length.out=ceiling((maxbt - minbt)/w)) if (middle) { res <- (res[-1] + res[-length(res)]) / 2 } res } #' @importFrom stats median #' @method median sir #' @rdname sir #' @export median.sir <- function(x, na.rm=FALSE, ...) { sir <- x if (!inherits(sir, "sir")) { stop("This is not an SIR model output") } times <- unlist(sapply(sir, "[[", "times")) big.N.NS <- unlist(sapply(sir, "[[", "NS")) big.N.NI <- unlist(sapply(sir, "[[", "NI")) big.N.NR <- unlist(sapply(sir, "[[", "NR")) time.bin <- cut(times, time_bins(sir, middle=FALSE), include.lowest=TRUE) NS <- tapply(big.N.NS, time.bin, median, na.rm=na.rm) NI <- tapply(big.N.NI, time.bin, median, na.rm=na.rm) NR <- tapply(big.N.NR, time.bin, median, na.rm=na.rm) list(NS=NS, NI=NI, NR=NR) } #' @importFrom stats quantile #' @method quantile sir #' @rdname sir #' @export quantile.sir <- function(x, comp=c("NI", "NS", "NR"), prob, ...) { sir <- x if (!inherits(sir, "sir")) { stop("This is not an SIR model output") } comp <- toupper(igraph.match.arg(comp)) times <- unlist(sapply(sir, "[[", "times")) big.N <- unlist(sapply(sir, function(x) { x[[comp]] })) time.bin <- cut(times, time_bins(sir, middle=FALSE), include.lowest=TRUE) res <- lapply(prob, function(pp) { tapply(big.N, time.bin, function(x) { quantile(x, prob=pp) }) }) if (length(res) == 1) { res <- res[[1]] } res } # R function to plot compartment total curves from simul.net.epi . # Inputs: sim.res := list of simulated network SIR processes # comp := compartment (i.e., "NS", "NI", or "NR") # q := vector of lower and upper quantiles, resp # cols := char vector of colors for lines, median, and quantiles, resp. # Outputs: None. Just produces the plot of all compartment curves, # with median and quantiles. #' Plotting the results on multiple SIR model runs #' #' This function can conveniently plot the results of multiple SIR model #' simulations. #' #' The number of susceptible/infected/recovered individuals is plotted over #' time, for multiple simulations. #' #' @param x The output of the SIR simulation, coming from the \code{\link{sir}} #' function. #' @param comp Character scalar, which component to plot. Either \sQuote{NI} #' (infected, default), \sQuote{NS} (susceptible) or \sQuote{NR} (recovered). #' @param median Logical scalar, whether to plot the (binned) median. #' @param quantiles A vector of (binned) quantiles to plot. #' @param color Color of the individual simulation curves. #' @param median_color Color of the median curve. #' @param quantile_color Color(s) of the quantile curves. (It is recycled if #' needed and non-needed entries are ignored if too long.) #' @param lwd.median Line width of the median. #' @param lwd.quantile Line width of the quantile curves. #' @param lty.quantile Line type of the quantile curves. #' @param xlim The x limits, a two-element numeric vector. If \code{NULL}, then #' it is calculated from the data. #' @param ylim The y limits, a two-element numeric vector. If \code{NULL}, then #' it is calculated from the data. #' @param xlab The x label. #' @param ylab The y label. If \code{NULL} then it is automatically added based #' on the \code{comp} argument. #' @param \dots Additional arguments are passed to \code{plot}, that is run #' before any of the curves are added, to create the figure. #' @return Nothing. #' @author Eric Kolaczyk (\url{http://math.bu.edu/people/kolaczyk/}) and Gabor #' Csardi \email{csardi.gabor@@gmail.com}. #' @seealso \code{\link{sir}} for running the actual simulation. #' @references Bailey, Norman T. J. (1975). The mathematical theory of #' infectious diseases and its applications (2nd ed.). London: Griffin. #' @method plot sir #' @export #' @importFrom graphics plot lines #' @keywords graphs #' @examples #' #' g <- sample_gnm(100, 100) #' sm <- sir(g, beta=5, gamma=1) #' plot(sm) #' plot.sir <- function(x, comp=c("NI", "NS", "NR"), median=TRUE, quantiles=c(0.1, 0.9), color=NULL, median_color=NULL, quantile_color=NULL, lwd.median=2, lwd.quantile=2, lty.quantile=3, xlim=NULL, ylim=NULL, xlab="Time", ylab=NULL, ...) { sir <- x if (!inherits(sir, "sir")) { stop("This is not an SIR model output") } comp <- toupper(igraph.match.arg(comp)) if (!all(quantiles >= 0 & quantiles <= 1)) { stop("Quantiles should be in [0,1]") } if (is.null(color)) { color <- c(NI="skyblue", NS="pink", NR="palegoldenrod")[comp] } if (is.null(median_color)) { median_color <- c(NI="blue", NS="red", NR="gold")[comp] } if (is.null(quantile_color)) { quantile_color <- c(NI="blue", NS="red", NR="gold")[comp] } quantile_color <- rep(quantile_color, length.out=length(quantiles)) ns <- length(sir) if (is.null(xlim)) { xlim <- c(0, max(sapply(sir, function(x) max(x$times)))) } if (is.null(ylim)) { ylim <- c(0, max(sapply(sir, function(x) max(x[[comp]])))) } ## Generate the plot, first with individual curves, and then ## adding median and quantile curves. if (is.null(ylab)) { if (comp == "NI") { ylab <- expression(N[I](t)) } if (comp == "NR") { ylab <- expression(N[R](t)) } if (comp == "NS") { ylab <- expression(N[S](t)) } } # Plot the stochastic curves individually. plot(0, 0, type="n", xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, ...) lapply(seq_along(sir), function(i) { lines(sir[[i]]$time, sir[[i]][[comp]], col=color[1]) }) # Plot the median and quantiles. if (median || length(quantiles) > 0) { time.bin <- time_bins(sir, middle=TRUE) } if (median) { lines(time.bin, median(sir)[[comp]], type="l", lwd=lwd.median, col=median_color) } for (i in seq_along(quantiles)) { my.ql <- quantile(sir, comp, quantiles[i]) lines(time.bin, my.ql, type="l", lty=lty.quantile, lwd=lwd.quantile, col=quantile_color[i]) } invisible() } igraph/R/similarity.R0000644000175100001440000000561113177712334014267 0ustar hornikusers#' Similarity measures of two vertices #' #' These functions calculates similarity scores for vertices based on their #' connection patterns. #' #' @details #' The Jaccard similarity coefficient of two vertices is the number of common #' neighbors divided by the number of vertices that are neighbors of at least #' one of the two vertices being considered. The \code{jaccard} method #' calculates the pairwise Jaccard similarities for some (or all) of the #' vertices. #' #' The Dice similarity coefficient of two vertices is twice the number of #' common neighbors divided by the sum of the degrees of the vertices. #' Methof \code{dice} calculates the pairwise Dice similarities for some #' (or all) of the vertices. #' #' The inverse log-weighted similarity of two vertices is the number of their #' common neighbors, weighted by the inverse logarithm of their degrees. It is #' based on the assumption that two vertices should be considered more similar #' if they share a low-degree common neighbor, since high-degree common #' neighbors are more likely to appear even by pure chance. Isolated vertices #' will have zero similarity to any other vertex. Self-similarities are not #' calculated. See the following paper for more details: Lada A. Adamic and #' Eytan Adar: Friends and neighbors on the Web. Social Networks, #' 25(3):211-230, 2003. #' #' @aliases similarity.jaccard similarity.dice similarity.invlogweighted #' @param graph The input graph. #' @param vids The vertex ids for which the similarity is calculated. #' @param mode The type of neighboring vertices to use for the calculation, #' possible values: \sQuote{\code{out}}, \sQuote{\code{in}}, #' \sQuote{\code{all}}. #' @param loops Whether to include vertices themselves in the neighbor #' sets. #' @param method The method to use. #' @return A \code{length(vids)} by \code{length(vids)} numeric matrix #' containing the similarity scores. This argument is ignored by the #' \code{invlogweighted} method. #' @author Tamas Nepusz \email{ntamas@@gmail.com} and Gabor Csardi #' \email{csardi.gabor@@gmail.com} for the manual page. #' @seealso \code{\link{cocitation}} and \code{\link{bibcoupling}} #' @references Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web. #' \emph{Social Networks}, 25(3):211-230, 2003. #' @keywords graphs #' @export #' @examples #' #' g <- make_ring(5) #' similarity(g, method = "dice") #' similarity(g, method = "jaccard") similarity <- function(graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE, method = c("jaccard", "dice", "invlogweighted")) { method <- igraph.match.arg(method) if (method == "jaccard") { similarity.jaccard(graph, vids, mode, loops) } else if (method == "dice") { similarity.dice(graph, vids, mode, loops) } else if (method == "invlogweighted") { similarity.invlogweighted(graph, vids, mode) } } igraph/R/random_walk.R0000644000175100001440000000372013177712334014376 0ustar hornikusers #' Random walk on a graph #' #' Do a random walk. From the given start vertex, take the given number of #' steps, choosing an edge from the actual vertex uniformly randomly. Edge #' directions are observed in directed graphs (see the \code{mode} argument #' as well). Multiple and loop edges are also observed. #' #' @param graph The input graph, might be undirected or directed. #' @param start The start vertex. #' @param steps The number of steps to make. #' @param mode How to follow directed edges. \code{"out"} steps along the #' edge direction, \code{"in"} is opposite to that. \code{"all"} ignores #' edge directions. This argument is ignored for undirected graphs. #' @param stuck What to do if the random walk gets stuck. \code{"return"} #' returns the partial walk, \code{"error"} raises an error. #' @return A vertex sequence containing the vertices along the walk. #' @export #' @examples #' ## Stationary distribution of a Markov chain #' g <- make_ring(10, directed = TRUE) %u% #' make_star(11, center = 11) + edge(11, 1) #' #' ec <- eigen_centrality(g, directed = TRUE)$vector #' pg <- page_rank(g, damping = 0.999)$vector #' w <- random_walk(g, start = 1, steps = 10000) #' #' ## These are similar, but not exactly the same #' cor(table(w), ec) #' #' ## But these are (almost) the same #' cor(table(w), pg) random_walk <- function(graph, start, steps, mode = c("out", "in", "all"), stuck = c("return", "error")) { ## Argument checks if (!is_igraph(graph)) stop("Not a graph object") start <- as.igraph.vs(graph, start) mode <- switch(igraph.match.arg(mode), "out" = 1, "in" = 2, "all" = 3, "total" = 3) steps <- as.integer(steps) stuck <- switch(igraph.match.arg(stuck), "error" = 0L, "return" = 1L) on.exit( .Call(C_R_igraph_finalizer) ) ## Function call res <- .Call(C_R_igraph_random_walk, graph, start - 1, mode, steps, stuck) if (igraph_opt("return.vs.es")) { res <- create_vs(graph, res) } res } igraph/R/palette.R0000644000175100001440000001437513247072116013541 0ustar hornikusers## ----------------------------------------------------------------------- ## ## IGraph R package ## Copyright (C) 2014 Gabor Csardi ## 334 Harvard street, Cambridge, MA 02139 USA ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA ## 02110-1301 USA ## ## ----------------------------------------------------------------------- #' Palette for categories #' #' This is a color blind friendly palette from #' \url{http://jfly.iam.u-tokyo.ac.jp/color}. It has 8 colors. #' #' This is the suggested palette for visualizations where vertex colors #' mark categories, e.g. community membership. #' #' @param n The number of colors in the palette. We simply take the first #' \code{n} colors from the total 8. #' @return A character vector of RGB color codes. #' #' @section Examples: #' \preformatted{ #' library(igraphdata) #' data(karate) #' karate <- karate %>% #' add_layout_(with_fr()) %>% #' set_vertex_attr("size", value = 10) #' #' cl_k <- cluster_optimal(karate) #' #' V(karate)$color <- membership(cl_k) #' karate$palette <- categorical_pal(length(cl_k)) #' plot(karate) #' } #' #' @family palettes #' @export categorical_pal <- function(n) { stopifnot(n > 0) x <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "#999999") if (n > length(x)) warning("Cannot make ", n, " categorical colors") n <- min(n, length(x)) x[seq_len(n)] } #' Sequential palette #' #' This is the \sQuote{OrRd} palette from \url{http://colorbrewer2.org}. #' It has at most nine colors. #' #' Use this palette, if vertex colors mark some ordinal quantity, e.g. some #' centrality measure, or some ordinal vertex covariate, like the age of #' people, or their seniority level. #' #' @param n The number of colors in the palette. The maximum is nine #' currently. #' @return A character vector of RGB color codes. #' #' @family palettes #' @export #' @examples #' \dontrun{ #' library(igraphdata) #' data(karate) #' karate <- karate %>% #' add_layout_(with_kk()) %>% #' set_vertex_attr("size", value = 10) #' #' V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), sequential_pal) #' plot(karate) #' } sequential_pal <- function(n) { stopifnot(n >= 0) x <- list( "#FEE8C8", c("#FEE8C8", "#FDBB84"), c("#FEE8C8", "#FDBB84", "#E34A33"), c("#FEF0D9", "#FDCC8A", "#FC8D59", "#D7301F"), c("#FEF0D9", "#FDCC8A", "#FC8D59", "#E34A33", "#B30000"), c("#FEF0D9", "#FDD49E", "#FDBB84", "#FC8D59", "#E34A33", "#B30000"), c("#FEF0D9", "#FDD49E", "#FDBB84", "#FC8D59", "#EF6548", "#D7301F", "#990000"), c("#FFF7EC", "#FEE8C8", "#FDD49E", "#FDBB84", "#FC8D59", "#EF6548", "#D7301F", "#990000"), c("#FFF7EC", "#FEE8C8", "#FDD49E", "#FDBB84", "#FC8D59", "#EF6548", "#D7301F", "#B30000", "#7F0000") ) if (n > length(x)) warning("Cannot make ", n, " sequential colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] } #' Diverging palette #' #' This is the \sQuote{PuOr} palette from \url{http://colorbrewer2.org}. #' It has at most eleven colors. #' #' This is similar to \code{\link{sequential_pal}}, but it also puts #' emphasis on the mid-range values, plus the the two extreme ends. #' Use this palette, if you have such a quantity to mark with vertex #' colors. #' #' @param n The number of colors in the palette. The maximum is eleven #' currently. #' @return A character vector of RGB color codes. #' #' @family palettes #' @export #' @examples #' \dontrun{ #' library(igraphdata) #' data(foodwebs) #' fw <- foodwebs[[1]] %>% #' induced_subgraph(V(.)[ECO == 1]) %>% #' add_layout_(with_fr()) %>% #' set_vertex_attr("label", value = seq_len(gorder(.))) %>% #' set_vertex_attr("size", value = 10) %>% #' set_edge_attr("arrow.size", value = 0.3) #' #' V(fw)$color <- scales::dscale(V(fw)$Biomass %>% cut(10), diverging_pal) #' plot(fw) #' #' data(karate) #' karate <- karate %>% #' add_layout_(with_kk()) %>% #' set_vertex_attr("size", value = 10) #' #' V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), diverging_pal) #' plot(karate) #' } diverging_pal <- function(n) { stopifnot(n > 0) x <- list( "#F1A340", c("#F1A340", "#F7F7F7"), c("#F1A340", "#F7F7F7", "#998EC3"), c("#E66101", "#FDB863", "#B2ABD2", "#5E3C99"), c("#E66101", "#FDB863", "#F7F7F7", "#B2ABD2", "#5E3C99"), c("#B35806", "#F1A340", "#FEE0B6", "#D8DAEB", "#998EC3", "#542788"), c("#B35806", "#F1A340", "#FEE0B6", "#F7F7F7", "#D8DAEB", "#998EC3", "#542788"), c("#B35806", "#E08214", "#FDB863", "#FEE0B6", "#D8DAEB", "#B2ABD2", "#8073AC", "#542788"), c("#B35806", "#E08214", "#FDB863", "#FEE0B6", "#F7F7F7", "#D8DAEB", "#B2ABD2", "#8073AC", "#542788"), c("#7F3B08", "#B35806", "#E08214", "#FDB863", "#FEE0B6", "#D8DAEB", "#B2ABD2", "#8073AC", "#542788", "#2D004B"), c("#7F3B08", "#B35806", "#E08214", "#FDB863", "#FEE0B6", "#F7F7F7", "#D8DAEB", "#B2ABD2", "#8073AC", "#542788", "#2D004B") ) if (n > length(x)) warning("Cannot make ", n, " divergent colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] } #' The default R palette #' #' This is the default R palette, to be able to reproduce the #' colors of older igraph versions. Its colors are appropriate #' for categories, but they are not very attractive. #' #' @param n The number of colors to use, the maximum is eight. #' @return A character vector of color names. #' #' @family palettes #' @export #' @importFrom grDevices palette r_pal <- function(n) { x <- palette() if (n > length(x)) warning("Cannot make ", n, " divergent colors") n <- min(n, length(x)) if (n == 0) character() else x[[n]] } igraph/R/bipartite.R0000644000175100001440000001671513240142531014056 0ustar hornikusers# IGraph R package # Copyright (C) 2009-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Project a bipartite graph #' #' A bipartite graph is projected into two one-mode networks #' #' Bipartite graphs have a \code{type} vertex attribute in igraph, this is #' boolean and \code{FALSE} for the vertices of the first kind and \code{TRUE} #' for vertices of the second kind. #' #' \code{bipartite_projection_size} calculates the number of vertices and edges #' in the two projections of the bipartite graphs, without calculating the #' projections themselves. This is useful to check how much memory the #' projections would need if you have a large bipartite graph. #' #' \code{bipartite_projection} calculates the actual projections. You can use #' the \code{probe1} argument to specify the order of the projections in the #' result. By default vertex type \code{FALSE} is the first and \code{TRUE} is #' the second. #' #' \code{bipartite_projection} keeps vertex attributes. #' #' @aliases bipartite.projection bipartite.projection.size bipartite_projection_size bipartite_projection #' @param graph The input graph. It can be directed, but edge directions are #' ignored during the computation. #' @param types An optional vertex type vector to use instead of the #' \sQuote{\code{type}} vertex attribute. You must supply this argument if the #' graph has no \sQuote{\code{type}} vertex attribute. #' @param multiplicity If \code{TRUE}, then igraph keeps the multiplicity of #' the edges as an edge attribute called \sQuote{weight}. #' E.g. if there is an A-C-B and also an A-D-B #' triple in the bipartite graph (but no more X, such that A-X-B is also in the #' graph), then the multiplicity of the A-B edge in the projection will be 2. #' @param probe1 This argument can be used to specify the order of the #' projections in the resulting list. If given, then it is considered as a #' vertex id (or a symbolic vertex name); the projection containing this vertex #' will be the first one in the result list. This argument is ignored if only #' one projection is requested in argument \code{which}. #' @param which A character scalar to specify which projection(s) to calculate. #' The default is to calculate both. #' @param remove.type Logical scalar, whether to remove the \code{type} vertex #' attribute from the projections. This makes sense because these graphs are #' not bipartite any more. However if you want to combine them with each other #' (or other bipartite graphs), then it is worth keeping this attribute. By #' default it will be removed. #' @return A list of two undirected graphs. See details above. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' ## Projection of a full bipartite graph is a full graph #' g <- make_full_bipartite_graph(10,5) #' proj <- bipartite_projection(g) #' graph.isomorphic(proj[[1]], make_full_graph(10)) #' graph.isomorphic(proj[[2]], make_full_graph(5)) #' #' ## The projection keeps the vertex attributes #' M <- matrix(0, nr=5, nc=3) #' rownames(M) <- c("Alice", "Bob", "Cecil", "Dan", "Ethel") #' colnames(M) <- c("Party", "Skiing", "Badminton") #' M[] <- sample(0:1, length(M), replace=TRUE) #' M #' g2 <- graph_from_incidence_matrix(M) #' g2$name <- "Event network" #' proj2 <- bipartite_projection(g2) #' print(proj2[[1]], g=TRUE, e=TRUE) #' print(proj2[[2]], g=TRUE, e=TRUE) #' bipartite_projection <- function(graph, types=NULL, multiplicity=TRUE, probe1=NULL, which=c("both", "true", "false"), remove.type=TRUE) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } if (is.null(types) && "type" %in% vertex_attr_names(graph)) { types <- V(graph)$type } if (!is.null(types)) { if (!is.logical(types)) { warning("vertex types converted to logical") } types <- as.logical(types) if (any(is.na(types))) { stop("`NA' is not allowed in vertex types") } } else { stop("Not a bipartite graph, supply `types' argument") } if (!is.null(probe1)) { probe1 <- as.igraph.vs(graph, probe1)-1 } else { probe1 <- -1 } which <- switch(igraph.match.arg(which), "both"=0L, "false"=1L, "true"=2L) if (which != "both" && probe1 != -1) { warning("`probe1' ignored if only one projection is requested") } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_bipartite_projection, graph, types, as.integer(probe1), which) if (remove.type) { if (is_igraph(res[[1]])) { res[[1]] <- delete_vertex_attr(res[[1]], "type") } if (is_igraph(res[[2]])) { res[[2]] <- delete_vertex_attr(res[[2]], "type") } } if (which == 0L) { if (multiplicity) { E(res[[1]])$weight <- res[[3]] E(res[[2]])$weight <- res[[4]] } res[1:2] } else if (which == 1L) { if (multiplicity) { E(res[[1]])$weight <- res[[3]] } res[[1]] } else { if (multiplicity) { E(res[[2]])$weight <- res[[4]] } res[[2]] } } #' Decide whether a graph is bipartite #' #' This function decides whether the vertices of a network can be mapped to two #' vertex types in a way that no vertices of the same type are connected. #' #' A bipartite graph in igraph has a \sQuote{\code{type}} vertex attribute #' giving the two vertex types. #' #' This function simply checks whether a graph \emph{could} be bipartite. It #' tries to find a mapping that gives a possible division of the vertices into #' two classes, such that no two vertices of the same class are connected by an #' edge. #' #' The existence of such a mapping is equivalent of having no circuits of odd #' length in the graph. A graph with loop edges cannot bipartite. #' #' Note that the mapping is not necessarily unique, e.g. if the graph has at #' least two components, then the vertices in the separate components can be #' mapped independently. #' #' @aliases bipartite.mapping bipartite_mapping #' @param graph The input graph. #' @return A named list with two elements: \item{res}{A logical scalar, #' \code{TRUE} if the can be bipartite, \code{FALSE} otherwise.} \item{type}{A #' possibly vertex type mapping, a logical vector. If no such mapping exists, #' then an empty vector.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @examples #' #' ## A ring has just one loop, so it is fine #' g <- make_ring(10) #' bipartite_mapping(g) #' #' ## A star is fine, too #' g2 <- make_star(10) #' bipartite_mapping(g2) #' #' ## A graph containing a triangle is not fine #' g3 <- make_ring(10) #' g3 <- add_edges(g3, c(1,3)) #' bipartite_mapping(g3) #' @export bipartite_mapping <- bipartite_mapping igraph/R/community.R0000644000175100001440000024470413247213310014121 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ################################################################### # Community structure ################################################################### #' Functions to deal with the result of network community detection #' #' igraph community detection functions return their results as an object from #' the \code{communities} class. This manual page describes the operations of #' this class. #' #' Community structure detection algorithms try to find dense subgraphs in #' directed or undirected graphs, by optimizing some criteria, and usually #' using heuristics. #' #' igraph implements a number of community detection methods (see them below), #' all of which return an object of the class \code{communities}. Because the #' community structure detection algorithms are different, \code{communities} #' objects do not always have the same structure. Nevertheless, they have some #' common operations, these are documented here. #' #' The \code{print} generic function is defined for \code{communities}, it #' prints a short summary. #' #' The \code{length} generic function call be called on \code{communities} and #' returns the number of communities. #' #' The \code{sizes} function returns the community sizes, in the order of their #' ids. #' #' \code{membership} gives the division of the vertices, into communities. It #' returns a numeric vector, one value for each vertex, the id of its #' community. Community ids start from one. Note that some algorithms calculate #' the complete (or incomplete) hierarchical structure of the communities, and #' not just a single partitioning. For these algorithms typically the #' membership for the highest modularity value is returned, but see also the #' manual pages of the individual algorithms. #' #' \code{communities} is also the name of a function, that returns a list of #' communities, each identified by their vertices. The vertices will have #' symbolic names if the \code{add.vertex.names} igraph option is set, and the #' graph itself was named. Otherwise numeric vertex ids are used. #' #' \code{modularity} gives the modularity score of the partitioning. (See #' \code{\link{modularity.igraph}} for details. For algorithms that do not #' result a single partitioning, the highest modularity value is returned. #' #' \code{algorithm} gives the name of the algorithm that was used to calculate #' the community structure. #' #' \code{crossing} returns a logical vector, with one value for each edge, #' ordered according to the edge ids. The value is \code{TRUE} iff the edge #' connects two different communities, according to the (best) membership #' vector, as returned by \code{membership()}. #' #' \code{is_hierarchical} checks whether a hierarchical algorithm was used to #' find the community structure. Some functions only make sense for #' hierarchical methods (e.g. \code{merges}, \code{cut_at} and #' \code{as.dendrogram}). #' #' \code{merges} returns the merge matrix for hierarchical methods. An error #' message is given, if a non-hierarchical method was used to find the #' community structure. You can check this by calling \code{is_hierarchical} on #' the \code{communities} object. #' #' \code{cut_at} cuts the merge tree of a hierarchical community finding method, #' at the desired place and returns a membership vector. The desired place can #' be expressed as the desired number of communities or as the number of merge #' steps to make. The function gives an error message, if called with a #' non-hierarchical method. #' #' \code{as.dendrogram} converts a hierarchical community structure to a #' \code{dendrogram} object. It only works for hierarchical methods, and gives #' an error message to others. See \code{\link[stats]{dendrogram}} for details. #' #' \code{as.hclust} is similar to \code{as.dendrogram}, but converts a #' hierarchical community structure to a \code{hclust} object. #' #' \code{as_phylo} converts a hierarchical community structure to a \code{phylo} #' object, you will need the \code{ape} package for this. #' #' \code{show_trace} works (currently) only for communities found by the leading #' eigenvector method (\code{\link{cluster_leading_eigen}}), and #' returns a character vector that gives the steps performed by the algorithm #' while finding the communities. #' #' \code{code_len} is defined for the InfoMAP method #' (\code{\link{cluster_infomap}} and returns the code length of the #' partition. #' #' It is possibly to call the \code{plot} function on \code{communities} #' objects. This will plot the graph (and uses \code{\link{plot.igraph}} #' internally), with the communities shown. By default it colores the vertices #' according to their communities, and also marks the vertex groups #' corresponding to the communities. It passes additional arguments to #' \code{\link{plot.igraph}}, please see that and also #' \code{\link{igraph.plotting}} on how to change the plot. #' #' @rdname communities #' @aliases communities membership algorithm crossing cutat merges sizes cut_at #' is.hierarchical print.communities plot.communities length.communities #' as.dendrogram.communities as.hclust.communities code_len #' asPhylo asPhylo.communities showtrace code.length #' as_phylo as_phylo.communities show_trace is_hierarchical #' @param communities,x,object A \code{communities} object, the result of an #' igraph community detection function. #' @param graph An igraph graph object, corresponding to \code{communities}. #' @param y An igraph graph object, corresponding to the communities in #' \code{x}. #' @param no Integer scalar, the desired number of communities. If too low or #' two high, then an error message is given. Exactly one of \code{no} and #' \code{steps} must be supplied. #' @param steps The number of merge operations to perform to produce the #' communities. Exactly one of \code{no} and \code{steps} must be supplied. #' @param col A vector of colors, in any format that is accepted by the regular #' R plotting methods. This vector gives the colors of the vertices explicitly. #' @param mark.groups A list of numeric vectors. The communities can be #' highlighted using colored polygons. The groups for which the polygons are #' drawn are given here. The default is to use the groups given by the #' communities. Supply \code{NULL} here if you do not want to highlight any #' groups. #' @param edge.color The colors of the edges. By default the edges within #' communities are colored green and other edges are red. #' @param hang Numeric scalar indicating how the height of leaves should be #' computed from the heights of their parents; see \code{\link{plot.hclust}}. #' @param use.modularity Logical scalar, whether to use the modularity values #' to define the height of the branches. #' @param \dots Additional arguments. \code{plot.communities} passes these to #' \code{\link{plot.igraph}}. The other functions silently ignore #' them. #' @param membership Numeric vector, one value for each vertex, the membership #' vector of the community structure. Might also be \code{NULL} if the #' community structure is given in another way, e.g. by a merge matrix. #' @param algorithm If not \code{NULL} (meaning an unknown algorithm), then a #' character scalar, the name of the algorithm that produced the community #' structure. #' @param merges If not \code{NULL}, then the merge matrix of the hierarchical #' community structure. See \code{merges} below for more information on its #' format. #' @param modularity Numeric scalar or vector, the modularity value of the #' community structure. It can also be \code{NULL}, if the modularity of the #' (best) split is not available. #' @return \code{print} returns the \code{communities} object itself, #' invisibly. #' #' \code{length} returns an integer scalar. #' #' \code{sizes} returns a numeric vector. #' #' \code{membership} returns a numeric vector, one number for each vertex in #' the graph that was the input of the community detection. #' #' \code{modularity} returns a numeric scalar. #' #' \code{algorithm} returns a character scalar. #' #' \code{crossing} returns a logical vector. #' #' \code{is_hierarchical} returns a logical scalar. #' #' \code{merges} returns a two-column numeric matrix. #' #' \code{cut_at} returns a numeric vector, the membership vector of the #' vertices. #' #' \code{as.dendrogram} returns a \code{\link[stats]{dendrogram}} object. #' #' \code{show_trace} returns a character vector. #' #' \code{code_len} returns a numeric scalar for communities found with the #' InfoMAP method and \code{NULL} for other methods. #' #' \code{plot} for \code{communities} objects returns \code{NULL}, invisibly. #' #' #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso See \code{\link{plot_dendrogram}} for plotting community structure #' dendrograms. #' #' See \code{\link{compare}} for comparing two community structures #' on the same graph. #' #' The different methods for finding communities, they all return a #' \code{communities} object: \code{\link{cluster_edge_betweenness}}, #' \code{\link{cluster_fast_greedy}}, #' \code{\link{cluster_label_prop}}, #' \code{\link{cluster_leading_eigen}}, #' \code{\link{cluster_louvain}}, \code{\link{cluster_optimal}}, #' \code{\link{cluster_spinglass}}, \code{\link{cluster_walktrap}}. #' @keywords graphs #' @export #' @examples #' #' karate <- make_graph("Zachary") #' wc <- cluster_walktrap(karate) #' modularity(wc) #' membership(wc) #' plot(wc, karate) #' membership <- function(communities) { if (!is.null(communities$membership)) { res <- communities$membership } else if (!is.null(communities$merges) && !is.null(communities$modularity)) { res <- community.to.membership2(communities$merges, communities$vcount, which.max(communities$modularity)) } else { stop("Cannot calculate community membership") } if (igraph_opt("add.vertex.names") && !is.null(communities$names)) { names(res) <- communities$names } class(res) <- "membership" res } #' @method print membership #' @export print.membership <- function(x, ...) print(unclass(x), ...) #' Declare a numeric vector as a membership vector #' #' This is useful if you want to use functions defined on #' membership vectors, but your membership vector does not #' come from an igraph clustering method. #' #' @param x The input vector. #' @return The input vector, with the \code{membership} class added. #' @export #' @examples #' ## Compare to the correct clustering #' g <- (make_full_graph(10) + make_full_graph(10)) %>% #' rewire(each_edge(p = 0.2)) #' correct <- rep(1:2, each = 10) %>% as_membership #' fc <- cluster_fast_greedy(g) #' compare(correct, fc) #' compare(correct, membership(fc)) as_membership <- function(x) add_class(x, "membership") #' @rdname communities #' @method print communities #' @export print.communities <- function(x, ...) { noc <- if (!is.null(x$membership)) max(membership(x)) else NA mod <- if (!is.null(x$modularity)) { modularity(x) %>% format(digits = 2) } else { NA_real_ } alg <- x$algorithm %||% "unknown" cat("IGRAPH clustering ", alg, ", groups: ", noc, ", mod: ", mod, "\n", sep="") if (!is.null(x$membership)) { grp <- groups(x) cat("+ groups:\n") hp <- function(o) { head_print(o, max_lines = igraph_opt("auto.print.lines"), omitted_footer = "+ ... omitted several groups/vertices\n",) } indent_print(grp, .printer = hp, .indent = " ") } else { cat(" + groups not available\n") } invisible(x) } #' Creates a communities object. #' #' This is useful to integrate the results of community finding algorithms #' that are not included in igraph. #' #' @param graph The graph of the community structure. #' @param membership The membership vector of the community structure, a #' numeric vector denoting the id of the community for each vertex. It #' might be \code{NULL} for hierarchical community structures. #' @param algorithm Character string, the algorithm that generated #' the community structure, it can be arbitrary. #' @param merges A merge matrix, for hierarchical community structures (or #' \code{NULL} otherwise. #' @param modularity Modularity value of the community structure. If this #' is \code{TRUE} and the membership vector is available, then it the #' modularity values is calculated automatically. #' @return A \code{communities} object. #' #' @aliases create.communities #' #' @export make_clusters <- function(graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE) { stopifnot(is.null(membership) || is.numeric(membership)) stopifnot(is.null(algorithm) || (is.character(algorithm) && length(algorithm)==1)) stopifnot(is.null(merges) || (is.matrix(merges) && is.numeric(merges) && ncol(merges)==2)) stopifnot(is.null(modularity) || (is.logical(modularity) && length(modularity) == 1) || (is.numeric(modularity) && length(modularity) %in% c(1, length(membership)))) if (is.logical(modularity)) { if (modularity && !is.null(membership)) { modularity <- modularity(graph, membership) } else { modularity <- NULL } } res <- list(membership=membership, algorithm=if (is.null(algorithm)) "unknown" else algorithm, modularity=modularity) if (!is.null(merges)) { res$merges <- merges } if (!is.null(membership)) { res$vcount <- length(membership) } else if (!is.null(merges)) { res$vcount <- nrow(merges) + 1 } class(res) <- "communities" res } #' @export modularity <- function(x, ...) UseMethod("modularity") #' Modularity of a community structure of a graph #' #' This function calculates how modular is a given division of a graph into #' subgraphs. #' #' \code{modularity} calculates the modularity of a graph with respect to the #' given \code{membership} vector. #' #' The modularity of a graph with respect to some division (or vertex types) #' measures how good the division is, or how separated are the different vertex #' types from each other. It defined as \deqn{Q=\frac{1}{2m} \sum_{i,j} #' (A_{ij}-\frac{k_ik_j}{2m})\delta(c_i,c_j),}{Q=1/(2m) * sum( (Aij-ki*kj/(2m) #' ) delta(ci,cj),i,j),} here \eqn{m} is the number of edges, \eqn{A_{ij}}{Aij} #' is the element of the \eqn{A} adjacency matrix in row \eqn{i} and column #' \eqn{j}, \eqn{k_i}{ki} is the degree of \eqn{i}, \eqn{k_j}{kj} is the degree #' of \eqn{j}, \eqn{c_i}{ci} is the type (or component) of \eqn{i}, #' \eqn{c_j}{cj} that of \eqn{j}, the sum goes over all \eqn{i} and \eqn{j} #' pairs of vertices, and \eqn{\delta(x,y)}{delta(x,y)} is 1 if \eqn{x=y} and 0 #' otherwise. #' #' If edge weights are given, then these are considered as the element of the #' \eqn{A} adjacency matrix, and \eqn{k_i}{ki} is the sum of weights of #' adjacent edges for vertex \eqn{i}. #' #' \code{modularity_matrix} calculates the modularity matrix. This is a dense matrix, #' and it is defined as the difference of the adjacency matrix and the #' configuration model null model matrix. In other words element #' \eqn{M_{ij}}{M[i,j]} is given as \eqn{A_{ij}-d_i #' d_j/(2m)}{A[i,j]-d[i]d[j]/(2m)}, where \eqn{A_{ij}}{A[i,j]} is the (possibly #' weighted) adjacency matrix, \eqn{d_i}{d[i]} is the degree of vertex \eqn{i}, #' and \eqn{m} is the number of edges (or the total weights in the graph, if it #' is weighed). #' #' @aliases modularity #' @param x,graph The input graph. #' @param membership Numeric vector, for each vertex it gives its community. #' The communities are numbered from one. #' @param weights If not \code{NULL} then a numeric vector giving edge weights. #' @param \dots Additional arguments, none currently. #' @return For \code{modularity} a numeric scalar, the modularity score of the #' given configuration. #' #' For \code{modularity_matrix} a numeic square matrix, its order is the number of #' vertices in the graph. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{cluster_walktrap}}, #' \code{\link{cluster_edge_betweenness}}, #' \code{\link{cluster_fast_greedy}}, \code{\link{cluster_spinglass}} for #' various community detection methods. #' @references Clauset, A.; Newman, M. E. J. & Moore, C. Finding community #' structure in very large networks, \emph{Phyisical Review E} 2004, 70, 066111 #' @method modularity igraph #' @export #' @keywords graphs #' @examples #' #' g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) #' g <- add_edges(g, c(1,6, 1,11, 6, 11)) #' wtc <- cluster_walktrap(g) #' modularity(wtc) #' modularity(g, membership(wtc)) #' modularity.igraph <- function(x, membership, weights=NULL, ...) { # Argument checks if (!is_igraph(x)) { stop("Not a graph object") } membership <- as.numeric(membership) if (!is.null(weights)) weights <- as.numeric(weights) on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_modularity, x, membership-1, weights) res } #' @rdname communities #' @method modularity communities #' @export modularity.communities <- function(x, ...) { if (!is.null(x$modularity)) { max(x$modularity) } else { stop("Modularity was not calculated") } } #' @rdname modularity.igraph #' @aliases mod.matrix #' @export modularity_matrix <- function(graph, membership, weights=NULL) { # Argument checks if (!is_igraph(graph)) { stop("Not a graph object") } membership <- as.numeric(membership)-1 if (is.null(weights) && "weight" %in% edge_attr_names(graph)) { weights <- E(graph)$weight } if (!is.null(weights) && any(!is.na(weights))) { weights <- as.numeric(weights) } else { weights <- NULL } on.exit( .Call(C_R_igraph_finalizer) ) # Function call res <- .Call(C_R_igraph_modularity_matrix, graph, membership, weights) res } #' @rdname communities #' @method length communities #' @export length.communities <- function(x) { m <- membership(x) max(m) } #' @rdname communities #' @export sizes <- function(communities) { m <- membership(communities) table(`Community sizes`=m) } #' @rdname communities #' @export algorithm <- function(communities) { communities$algorithm } #' @rdname communities #' @export merges <- function(communities) { if (!is.null(communities$merges)) { communities$merges } else { stop("Not a hierarchical community structure") } } #' @rdname communities #' @export crossing <- function(communities, graph) { m <- membership(communities) el <- as_edgelist(graph, names=FALSE) m1 <- m[el[,1]] m2 <- m[el[,2]] res <- m1 != m2 if (!is.null(names(m1))) { names(res) <- paste(names(m1), names(m2), sep="|") } res } #' @rdname communities #' @export code_len <- function(communities) { communities$codelength } #' @rdname communities #' @export is_hierarchical <- function(communities) { ! is.null(communities$merges) } complete.dend <- function(comm, use.modularity) { merges <- comm$merges if (nrow(merges) < comm$vcount-1) { if (use.modularity) { stop(paste("`use.modularity' requires a full dendrogram,", "i.e. a connected graph")) } miss <- seq_len(comm$vcount + nrow(merges))[-as.vector(merges)] miss <- c(miss, seq_len(length(miss)-2) + comm$vcount+nrow(merges)) miss <- matrix(miss, byrow=TRUE, ncol=2) merges <- rbind(merges, miss) } storage.mode(merges) <- "integer" merges } # The following functions were adapted from the stats R package #' @rdname communities #' @importFrom stats as.dendrogram #' @method as.dendrogram communities #' @export as.dendrogram.communities <- function(object, hang=-1, use.modularity=FALSE, ...) { if (!is_hierarchical(object)) { stop("Not a hierarchical community structure") } .memberDend <- function(x) { r <- attr(x,"x.member") if(is.null(r)) { r <- attr(x,"members") if(is.null(r)) r <- 1:1 } r } ## If multiple components, then we merge them in arbitrary order merges <- complete.dend(object, use.modularity) storage.mode(merges) <- "integer" if (is.null(object$names)) { object$names <- 1:(nrow(merges)+1) } z <- list() if (!use.modularity || is.null(object$modularity)) { object$height <- 1:nrow(merges) } else { object$height <- object$modularity[-1] object$height <- cumsum(object$height - min(object$height)) } nMerge <- length(oHgt <- object$height) if (nMerge != nrow(merges)) stop("'merge' and 'height' do not fit!") hMax <- oHgt[nMerge] one <- 1L two <- 2L leafs <- nrow(merges)+1 for (k in 1:nMerge) { x <- merges[k, ]# no sort() anymore! if (any(neg <- x < leafs+1)) h0 <- if (hang < 0) 0 else max(0, oHgt[k] - hang * hMax) if (all(neg)) { # two leaves zk <- as.list(x) attr(zk, "members") <- two attr(zk, "midpoint") <- 0.5 # mean( c(0,1) ) objlabels <- object$names[x] attr(zk[[1]], "label") <- objlabels[1] attr(zk[[2]], "label") <- objlabels[2] attr(zk[[1]], "members") <- attr(zk[[2]], "members") <- one attr(zk[[1]], "height") <- attr(zk[[2]], "height") <- h0 attr(zk[[1]], "leaf") <- attr(zk[[2]], "leaf") <- TRUE } else if (any(neg)) { # one leaf, one node X <- as.character(x) ## Originally had "x <- sort(..) above => leaf always left, x[1]; ## don't want to assume this isL <- x[1] < leafs+1 ## is leaf left? zk <- if(isL) list(x[1], z[[X[2]]]) else list(z[[X[1]]], x[2]) attr(zk, "members") <- attr(z[[X[1 + isL]]], "members") + one attr(zk, "midpoint") <- (.memberDend(zk[[1]]) + attr(z[[X[1 + isL]]], "midpoint"))/2 attr(zk[[2 - isL]], "members") <- one attr(zk[[2 - isL]], "height") <- h0 attr(zk[[2 - isL]], "label") <- object$names[x[2 - isL]] attr(zk[[2 - isL]], "leaf") <- TRUE } else { # two nodes x <- as.character(x) zk <- list(z[[x[1]]], z[[x[2]]]) attr(zk, "members") <- attr(z[[x[1]]], "members") + attr(z[[x[2]]], "members") attr(zk, "midpoint") <- (attr(z[[x[1]]], "members") + attr(z[[x[1]]], "midpoint") + attr(z[[x[2]]], "midpoint"))/2 } attr(zk, "height") <- oHgt[k] z[[k <- as.character(k+leafs)]] <- zk } z <- z[[k]] class(z) <- "dendrogram" z } #' @rdname communities #' @importFrom stats as.hclust #' @method as.hclust communities #' @export as.hclust.communities <- function(x, hang=-1, use.modularity=FALSE, ...) { as.hclust(as.dendrogram(x, hang=hang, use.modularity=use.modularity)) } #' @rdname communities #' @export as_phylo <- function(x, ...) UseMethod("as_phylo") #' @rdname communities #' @method as_phylo communities #' @export as_phylo.communities <- function(x, use.modularity=FALSE, ...) { if (!is_hierarchical(x)) { stop("Not a hierarchical community structure") } ## If multiple components, then we merge them in arbitrary order merges <- complete.dend(x, use.modularity) if (!use.modularity || is.null(x$modularity)) { height <- 1:nrow(merges) } else { height <- x$modularity[-1] height <- cumsum(height - min(height)) } if (is.null(x$names)) { labels <- 1:(nrow(merges)+1) } else { labels <- x$names } N <- nrow(merges) edge <- matrix(0L, 2*N, 2) edge.length <- numeric(2*N) node <- integer(N) node[N] <- N + 2L cur.nod <- N + 3L j <- 1L for (i in N:1) { edge[j:(j+1), 1] <- node[i] for (l in 1:2) { k <- j + l -1L y <- merges[i, l] if (y > N+1) { edge[k, 2] <- node[y-N-1] <- cur.nod cur.nod <- cur.nod + 1L edge.length[k] <- height[i] - height[y-N-1] } else { edge[k, 2] <- y edge.length[k] <- height[i] } } j <- j + 2L } obj <- list(edge=edge, edge.length=edge.length/2, tip.label=labels, Nnode=N) class(obj) <- "phylo" ape::reorder.phylo(obj) } #' @rdname communities #' @export cut_at <- function(communities, no, steps) { if (!inherits(communities, "communities")) { stop("Not a community structure") } if (!is_hierarchical(communities)) { stop("Not a hierarchical communitity structure") } if ((!missing(no) && !missing(steps)) || ( missing(no) && missing(steps))) { stop("Please give either `no' or `steps' (but not both)") } if (!missing(steps)) { mm <- merges(communities) if (steps > nrow(mm)) { warning("Cannot make that many steps") steps <- nrow(mm) } community.to.membership2(mm, communities$vcount, steps) } else { mm <- merges(communities) noc <- communities$vcount - nrow(mm) # final number of communities if (no 0) { rect.hclust(hc, k=rect, border=colbar) } invisible(ret) } #' @importFrom graphics plot dendPlotDendrogram <- function(communities, hang=-1, ..., use.modularity=FALSE) { plot(as.dendrogram(communities, hang=hang, use.modularity=use.modularity), ...) } #' @importFrom grDevices palette #' @importFrom graphics plot dendPlotPhylo <- function(communities, colbar=palette(), col=colbar[membership(communities)], mark.groups=communities(communities), use.modularity=FALSE, edge.color="#AAAAAAFF", edge.lty=c(1,2), ...) { phy <- as_phylo(communities, use.modularity=use.modularity) getedges <- function(tip) { repeat { ee <- which(! phy$edge[,1] %in% tip & phy$edge[,2] %in% tip) if (length(ee)<=1) { break } tip <- c(tip, unique(phy$edge[ee,1])) } ed <- which(phy$edge[,1] %in% tip & phy$edge[,2] %in% tip) eds <- phy$edge[ed, 1] good <- which(phy$edge[ed,1] %in% which(tabulate(eds) != 1)) ed[good] } gredges <- lapply(mark.groups, getedges) if (length(mark.groups) > 0) { ecol <- rep(edge.color, nrow(phy$edge)) for (gr in seq_along(gredges)) { ecol[gredges[[gr]]] <- colbar[gr] } } else { ecol <- edge.color } elty <- rep(edge.lty[2], nrow(phy$edge)) elty[ unlist(gredges) ] <- edge.lty[1] plot(phy, edge.color=ecol, edge.lty=elty, tip.color=col, ...) } #' Compares community structures using various metrics #' #' This function assesses the distance between two community structures. #' #' #' @aliases compare.communities compare.membership compare #' @param comm1 A \code{\link{communities}} object containing a community #' structure; or a numeric vector, the membership vector of the first community #' structure. The membership vector should contain the community id of each #' vertex, the numbering of the communities starts with one. #' @param comm2 A \code{\link{communities}} object containing a community #' structure; or a numeric vector, the membership vector of the second #' community structure, in the same format as for the previous argument. #' @param method Character scalar, the comparison method to use. Possible #' values: \sQuote{vi} is the variation of information (VI) metric of Meila #' (2003), \sQuote{nmi} is the normalized mutual information measure proposed #' by Danon et al. (2005), \sQuote{split.join} is the split-join distance of #' can Dongen (2000), \sQuote{rand} is the Rand index of Rand (1971), #' \sQuote{adjusted.rand} is the adjusted Rand index by Hubert and Arabie #' (1985). #' @return A real number. #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @seealso \code{\link{cluster_walktrap}}, #' \code{\link{cluster_edge_betweenness}}, #' \code{\link{cluster_fast_greedy}}, \code{\link{cluster_spinglass}} for #' various community detection methods. #' @references Meila M: Comparing clusterings by the variation of information. #' In: Scholkopf B, Warmuth MK (eds.). \emph{Learning Theory and Kernel #' Machines: 16th Annual Conference on Computational Learning Theory and 7th #' Kernel Workshop}, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes in #' Computer Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1. #' #' Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community structure #' identification. \emph{J Stat Mech} P09008, 2005. #' #' van Dongen S: Performance criteria for graph clustering and Markov cluster #' experiments. Technical Report INS-R0012, National Research Institute for #' Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000. #' #' Rand WM: Objective criteria for the evaluation of clustering methods. #' \emph{J Am Stat Assoc} 66(336):846-850, 1971. #' #' Hubert L and Arabie P: Comparing partitions. \emph{Journal of #' Classification} 2:193-218, 1985. #' @export #' @keywords graphs #' @examples #' #' g <- make_graph("Zachary") #' sg <- cluster_spinglass(g) #' le <- cluster_leading_eigen(g) #' compare(sg, le, method="rand") #' compare(membership(sg), membership(le)) #' compare <- function(comm1, comm2, method=c("vi", "nmi", "split.join", "rand", "adjusted.rand")) UseMethod("compare") #' @method compare communities #' @export compare.communities <- function(comm1, comm2, method=c("vi", "nmi", "split.join", "rand", "adjusted.rand")) { i_compare(comm1, comm2, method) } #' @method compare membership #' @export compare.membership <- function(comm1, comm2, method=c("vi", "nmi", "split.join", "rand", "adjusted.rand")) { i_compare(comm1, comm2, method) } #' @method compare default #' @export compare.default <- compare.membership i_compare <- function (comm1, comm2, method=c("vi", "nmi", "split.join", "rand", "adjusted.rand")) { comm1 <- if (inherits(comm1, "communities")) { as.numeric(membership(comm1)) } else { as.numeric(comm1) } comm2 <- if (inherits(comm2, "communities")) { as.numeric(membership(comm2)) } else { as.numeric(comm2) } method <- switch(igraph.match.arg(method), vi = 0, nmi = 1, split.join = 2, rand = 3, adjusted.rand = 4) on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_compare_communities, comm1, comm2, method) res } #' Split-join distance of two community structures #' #' The split-join distance between partitions A and B is the sum of the #' projection distance of A from B and the projection distance of B from #' A. The projection distance is an asymmetric measure and it is defined as #' follows: #' #' First, each set in partition A is evaluated against all sets in #' partition B. For each set in partition A, the best matching set in #' partition B is found and the overlap size is calculated. (Matching is #' quantified by the size of the overlap between the two sets). Then, the #' maximal overlap sizes for each set in A are summed together and #' subtracted from the number of elements in A. #' #' The split-join distance will be returned as two numbers, the first is #' the projection distance of the first partition from the #' second, while the second number is the projection distance of the second #' partition from the first. This makes it easier to detect whether a #' partition is a subpartition of the other, since in this case, the #' corresponding distance will be zero. #' #' @param comm1 The first community structure. #' @param comm2 The second community structure. #' @return Two integer numbers, see details below. #' #' @references #' van Dongen S: Performance criteria for graph clustering and Markov #' cluster experiments. Technical Report INS-R0012, National Research #' Institute for Mathematics and Computer Science in the Netherlands, #' Amsterdam, May 2000. #' #' @export split_join_distance <- function(comm1, comm2) { comm1 <- if (inherits(comm1, "communities")) { as.numeric(membership(comm1)) } else { as.numeric(comm1) } comm2 <- if (inherits(comm2, "communities")) { as.numeric(membership(comm2)) } else { as.numeric(comm2) } on.exit(.Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_split_join_distance, comm1, comm2) unlist(res) } #' Groups of a vertex partitioning #' #' Create a list of vertex groups from some graph clustering or community #' structure. #' #' Currently two methods are defined for this function. The default method #' works on the output of \code{\link{components}}. (In fact it works on any #' object that is a list with an entry called \code{membership}.) #' #' The second method works on \code{\link{communities}} objects. #' #' @aliases groups groups.default groups.communities #' @param x Some object that represents a grouping of the vertices. See details #' below. #' @return A named list of numeric or character vectors. The names are just #' numbers that refer to the groups. The vectors themselves are numeric or #' symbolic vertex ids. #' @seealso \code{\link{components}} and the various community finding #' functions. #' @examples #' g <- make_graph("Zachary") #' fgc <- cluster_fast_greedy(g) #' groups(fgc) #' #' g2 <- make_ring(10) + make_full_graph(5) #' groups(components(g2)) #' @export groups <- function(x) UseMethod("groups") #' @method groups default #' @export groups.default <- function(x) { vids <- names(x$membership) if (is.null(vids)) vids <- seq_along(x$membership) tapply(vids, x$membership, simplify=FALSE, function(x) x) } #' @method groups communities #' @export groups.communities <- function(x) { m <- membership(x) groups.default(list(membership = m)) } #' @export communities <- groups.communities #' @method "[" communities #' @export `[.communities` <- function(x, i) { groups(x)[i] } #' @method "[[" communities #' @export `[[.communities` <- function(x, i) { groups(x)[[i]] } #' Contract several vertices into a single one #' #' This function creates a new graph, by merging several vertices into one. The #' vertices in the new graph correspond to sets of vertices in the input graph. #' #' The attributes of the graph are kept. Graph and edge attributes are #' unchanged, vertex attributes are combined, according to the #' \code{vertex.attr.comb} parameter. #' #' @aliases contract.vertices contract #' @param graph The input graph, it can be directed or undirected. #' @param mapping A numeric vector that specifies the mapping. Its elements #' correspond to the vertices, and for each element the id in the new graph is #' given. #' @param vertex.attr.comb Specifies how to combine the vertex attributes in #' the new graph. Please see \code{\link{attribute.combination}} for details. #' @return A new graph object. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' g$name <- "Ring" #' V(g)$name <- letters[1:vcount(g)] #' E(g)$weight <- runif(ecount(g)) #' #' g2 <- contract(g, rep(1:5, each=2), #' vertex.attr.comb=toString) #' #' ## graph and edge attributes are kept, vertex attributes are #' ## combined using the 'toString' function. #' print(g2, g=TRUE, v=TRUE, e=TRUE) #' #' @export contract <- contract igraph/R/attributes.R0000644000175100001440000006445613240142531014266 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### ## ## The brand new attribute interface: ## ## g(graph)$name # get a graph attribute ## g(graph)$name <- "Ring" # set a graph attribute ## ## v(graph)$color <- "red" # set vertex attribute ## v(graph)$color[1:5] <- "blue" ## v(graph)$color[c(5,6,7)] # get vertex attribute ## ## e(graph)$weight <- 1 # set edge attribute ## e(graph)$weight[1:10] # get edge attribute ## #' Graph attributes of a graph #' #' @param graph Input graph. #' @param name The name of attribute to query. If missing, then all #' attributes are returned in a list. #' @return A list of graph attributes, or a single graph attribute. #' #' @aliases get.graph.attribute graph.attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) #' graph_attr(g) #' graph_attr(g, "name") graph_attr <- function(graph, name) { if (!is_igraph(graph)) { stop("Not a graph object") } if (missing(name)) { graph.attributes(graph) } else { .Call(C_R_igraph_mybracket2, graph, 9L, 2L)[[as.character(name)]] } } #' Set all or some graph attributes #' #' @param graph The graph. #' @param name The name of the attribute to set. If missing, then #' \code{value} should be a named list, and all list members #' are set as attributes. #' @param value The value of the attribute to set #' @return The graph, with the attribute(s) added. #' #' @aliases graph.attributes<- #' @family graph attributes #' #' @export #' @examples #' g <- make_graph(~ A - B:C:D) #' graph_attr(g, "name") <- "4-star" #' g #' #' graph_attr(g) <- list(layout = layout_with_fr(g), #' name = "4-star layed out") #' plot(g) `graph_attr<-` <- function(graph, name, value) { if (missing(name)) { `graph.attributes<-`(graph, value) } else { set_graph_attr(graph, name, value) } } #' Set a graph attribute #' #' An existing attribute with the same name is overwritten. #' #' @param graph The graph. #' @param name The name of the attribute to set. #' @param value New value of the attribute. #' @return The graph with the new graph attribute added or set. #' #' @family graph attributes #' @aliases set.graph.attribute #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_graph_attr("layout", layout_with_fr) #' g #' plot(g) set_graph_attr <- function(graph, name, value) { if (!is_igraph(graph)) { stop("Not a graph object") } .Call(C_R_igraph_mybracket3_set, graph, 9L, 2L, name, value) } #' @export graph.attributes <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } .Call(C_R_igraph_mybracket2_copy, graph, 9L, 2L) } #' @export "graph.attributes<-" <- function(graph, value) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.list(value) || (length(value) > 0 && is.null(names(value))) || any(names(value) == "") || any(duplicated(names(value)))) { stop("Value must be a named list with unique names") } .Call(C_R_igraph_mybracket2_set, graph, 9L, 2L, value) } #' Query vertex attributes of a graph #' #' @param graph The graph. #' @param name Name of the attribute to query. If missing, then #' all vertex attributes are returned in a list. #' @param index A vertex sequence, to query the attribute only #' for these vertices. #' @return The value of the vertex attribute, or the list of #' all vertex attributes, if \code{name} is missing. #' #' @aliases get.vertex.attribute vertex.attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("color", value = "red") %>% #' set_vertex_attr("label", value = letters[1:10]) #' vertex_attr(g, "label") #' vertex_attr(g) #' plot(g) vertex_attr <- function(graph, name, index=V(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } if (missing(name)) { if (missing(index)) { vertex.attributes(graph) } else { vertex.attributes(graph, index = index) } } else { myattr <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L)[[as.character(name)]] if (! missing(index)) { index <- as.igraph.vs(graph, index) myattr <- myattr[index] } myattr } } #' Set one or more vertex attributes #' #' @param graph The graph. #' @param name The name of the vertex attribute to set. If missing, #' then \code{value} must be a named list, and its entries are #' set as vertex attributes. #' @param index An optional vertex sequence to set the attributes #' of a subset of vertices. #' @param value The new value of the attribute(s) for all #' (or \code{index}) vertices. #' @return The graph, with the vertex attribute(s) added or set. #' #' @aliases vertex.attributes<- #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) #' vertex_attr(g) <- list(name = LETTERS[1:10], #' color = rep("yellow", gorder(g))) #' vertex_attr(g, "label") <- V(g)$name #' g #' plot(g) `vertex_attr<-` <- function(graph, name, index = V(graph), value) { if (missing(name)) { `vertex.attributes<-`(graph, index = index, value = value) } else { set_vertex_attr(graph, name = name, index = index, value = value) } } #' Set vertex attributes #' #' @param graph The graph. #' @param name The name of the attribute to set. #' @param index An optional vertex sequence to set the attributes #' of a subset of vertices. #' @param value The new value of the attribute for all (or \code{index}) #' vertices. #' @return The graph, with the vertex attribute added or set. #' #' @aliases set.vertex.attribute #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("label", value = LETTERS[1:10]) #' g #' plot(g) set_vertex_attr <- function(graph, name, index = V(graph), value) { i_set_vertex_attr(graph = graph, name = name, index = index, value = value) } i_set_vertex_attr <- function(graph, name, index=V(graph), value, check = TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } single <- "single" %in% names(attributes(index)) && attr(index, "single") if (!missing(index) && check) { index <- as.igraph.vs(graph, index) } name <- as.character(name) vc <- vcount(graph) vattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) if (single) { vattrs[[name]][[index]] <- value } else { vattrs[[name]][index] <- value } length(vattrs[[name]]) <- vc .Call(C_R_igraph_mybracket2_set, graph, 9L, 3L, vattrs) } #' @export vertex.attributes <- function(graph, index = V(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!missing(index)) { index <- as.igraph.vs(graph, index) } res <- .Call(C_R_igraph_mybracket2_copy, graph, 9L, 3L) if (!missing(index) && (length(index) != vcount(graph) || any(index != V(graph)))) { for (i in seq_along(res)) { res[[i]] <- res[[i]][index] } } res } #' @export "vertex.attributes<-" <- function(graph, index = V(graph), value) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.list(value) || (length(value) > 0 && is.null(names(value))) || any(names(value) == "") || any(duplicated(names(value)))) { stop("Value must be a named list with unique names") } if ( any(sapply(value, length) != length(index)) ) { stop("Invalid attribute value length, must match number of vertices") } if (!missing(index)) { index <- as.igraph.vs(graph, index) if (any(duplicated(index)) || any(is.na(index))) { stop("Invalid vertices in index") } } if (!missing(index) && (length(index) != vcount(graph) || any(index != V(graph)))) { vs <- V(graph) for (i in seq_along(value)) { tmp <- value[[i]] length(tmp) <- 0 length(tmp) <- length(vs) tmp[index] <- value[[i]] value[[i]] <- tmp } } .Call(C_R_igraph_mybracket2_set, graph, 9L, 3L, value) } #' Query edge attributes of a graph #' #' @param graph The graph #' @param name The name of the attribute to query. If missing, then #' all edge attributes are returned in a list. #' @param index An optional edge sequence, to query edge attributes #' for a subset of edges. #' @return The value of the edge attribute, or the list of all #' edge attributes if \code{name} is missing. #' #' @aliases get.edge.attribute edge.attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_edge_attr("weight", value = 1:10) %>% #' set_edge_attr("color", value = "red") #' g #' plot(g, edge.width = E(g)$weight) edge_attr <- function(graph, name, index=E(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } if (missing(name)) { edge.attributes(graph, name) } else { name <- as.character(name) index <- as.igraph.es(graph, index) myattr <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L)[[name]] myattr[index] } } #' Set one or more edge attributes #' #' @param graph The graph. #' @param name The name of the edge attribute to set. If missing, #' then \code{value} must be a named list, and its entries are #' set as edge attributes. #' @param index An optional edge sequence to set the attributes #' of a subset of edges. #' @param value The new value of the attribute(s) for all #' (or \code{index}) edges. #' @return The graph, with the edge attribute(s) added or set. #' #' @aliases edge.attributes<- #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) #' edge_attr(g) <- list(name = LETTERS[1:10], #' color = rep("green", gsize(g))) #' edge_attr(g, "label") <- E(g)$name #' g #' plot(g) `edge_attr<-` <- function(graph, name, index = E(graph), value) { if (missing(name)) { `edge.attributes<-`(graph, index = index, value = value) } else { set_edge_attr(graph, name = name, index = index, value = value) } } #' Set edge attributes #' #' @param graph The graph #' @param name The name of the attribute to set. #' @param index An optional edge sequence to set the attributes of #' a subset of edges. #' @param value The new value of the attribute for all (or \code{index}) #' edges. #' @return The graph, with the edge attribute added or set. #' #' @aliases set.edge.attribute #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_edge_attr("label", value = LETTERS[1:10]) #' g #' plot(g) set_edge_attr <- function(graph, name, index = E(graph), value) { i_set_edge_attr(graph = graph, name = name, index = index, value = value) } i_set_edge_attr <- function(graph, name, index=E(graph), value, check = TRUE) { if (!is_igraph(graph)) { stop("Not a graph object") } single <- "single" %in% names(attributes(index)) && attr(index, "single") name <- as.character(name) if (!missing(index) && check) index <- as.igraph.es(graph, index) ec <- ecount(graph) eattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L) if (single) { eattrs[[name]][[index]] <- value } else { eattrs[[name]][index] <- value } length(eattrs[[name]]) <- ec .Call(C_R_igraph_mybracket2_set, graph, 9L, 4L, eattrs) } #' @export edge.attributes <- function(graph, index = E(graph)) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!missing(index)) { index <- as.igraph.es(graph, index) } res <- .Call(C_R_igraph_mybracket2_copy, graph, 9L, 4L) if (!missing(index) && (length(index) != ecount(graph) || any(index != E(graph)))) { for (i in seq_along(res)) { res[[i]] <- res[[i]][index] } } res } #' @export "edge.attributes<-" <- function(graph, index = E(graph), value) { if (!is_igraph(graph)) { stop("Not a graph object") } if (!is.list(value) || (length(value) > 0 && is.null(names(value))) || any(names(value) == "") || any(duplicated(names(value)))) { stop("Value must be a named list with unique names") } if ( any(sapply(value, length) != length(index)) ) { stop("Invalid attribute value length, must match number of edges") } if (!missing(index)) { index <- as.igraph.es(graph, index) if (any(duplicated(index)) || any(is.na(index))) { stop("Invalid edges in index") } } if (!missing(index) && (length(index) != ecount(graph) || any(index != E(graph)))) { es <- E(graph) for (i in seq_along(value)) { tmp <- value[[i]] length(tmp) <- 0 length(tmp) <- length(es) tmp[index] <- value[[i]] value[[i]] <- tmp } } .Call(C_R_igraph_mybracket2_set, graph, 9L, 4L, value) } #' List names of graph attributes #' #' @param graph The graph. #' @return Character vector, the names of the graph attributes. #' #' @aliases list.graph.attributes attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) #' graph_attr_names(g) graph_attr_names <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } res <- .Call(C_R_igraph_mybracket2_names, graph, 9L, 2L) if (is.null(res)) { res <- character() } res } #' List names of vertex attributes #' #' @param graph The graph. #' @return Character vector, the names of the vertex attributes. #' #' @aliases list.vertex.attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) %>% #' set_vertex_attr("color", value = rep("green", 10)) #' vertex_attr_names(g) #' plot(g) vertex_attr_names <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } res <- .Call(C_R_igraph_mybracket2_names, graph, 9L, 3L) if (is.null(res)) { res <- character() } res } #' List names of edge attributes #' #' @param graph The graph. #' @return Character vector, the names of the edge attributes. #' #' @aliases list.edge.attributes #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_edge_attr("label", value = letters[1:10]) #' edge_attr_names(g) #' plot(g) edge_attr_names <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } res <- .Call(C_R_igraph_mybracket2_names, graph, 9L, 4L) if (is.null(res)) { res <- character() } res } #' Delete a graph attribute #' #' @param graph The graph. #' @param name Name of the attribute to delete. #' @return The graph, with the specified attribute removed. #' #' @aliases remove.graph.attribute #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) #' graph_attr_names(g) #' g2 <- delete_graph_attr(g, "name") #' graph_attr_names(g2) delete_graph_attr <- function(graph, name) { if (!is_igraph(graph)) { stop("Not a graph object") } name <- as.character(name) if (!name %in% graph_attr_names(graph)) { stop("No such graph attribute: ", name) } gattr <- .Call(C_R_igraph_mybracket2, graph, 9L, 2L) gattr[[name]] <- NULL .Call(C_R_igraph_mybracket2_set, graph, 9L, 2L, gattr) } #' Delete a vertex attribute #' #' @param graph The graph #' @param name The name of the vertex attribute to delete. #' @return The graph, with the specified vertex attribute removed. #' #' @aliases remove.vertex.attribute #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_vertex_attr("name", value = LETTERS[1:10]) #' vertex_attr_names(g) #' g2 <- delete_vertex_attr(g, "name") #' vertex_attr_names(g2) delete_vertex_attr <- function(graph, name) { if (!is_igraph(graph)) { stop("Not a graph object") } name <- as.character(name) if (!name %in% vertex_attr_names(graph)) { stop("No such vertex attribute: ", name) } vattr <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) vattr[[name]] <- NULL .Call(C_R_igraph_mybracket2_set, graph, 9L, 3L, vattr) } #' Delete an edge attribute #' #' @param graph The graph #' @param name The name of the edge attribute to delete. #' @return The graph, with the specified edge attribute removed. #' #' @aliases remove.edge.attribute #' @family graph attributes #' #' @export #' @examples #' g <- make_ring(10) %>% #' set_edge_attr("name", value = LETTERS[1:10]) #' edge_attr_names(g) #' g2 <- delete_edge_attr(g, "name") #' edge_attr_names(g2) delete_edge_attr <- function(graph, name) { if (!is_igraph(graph)) { stop("Not a graph object") } name <- as.character(name) if (!name %in% edge_attr_names(graph)) { stop("No such edge attribute: ", name) } eattr <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L) eattr[[name]] <- NULL .Call(C_R_igraph_mybracket2_set, graph, 9L, 4L, eattr) } ############# #' Named graphs #' #' An igraph graph is named, if there is a symbolic name associated with its #' vertices. #' #' In igraph vertices can always be identified and specified via their numeric #' vertex ids. This is, however, not always convenient, and in many cases there #' exist symbolic ids that correspond to the vertices. To allow this more #' flexible identification of vertices, one can assign a vertex attribute #' called \sQuote{name} to an igraph graph. After doing this, the symbolic #' vertex names can be used in all igraph functions, instead of the numeric #' ids. #' #' Note that the uniqueness of vertex names are currently not enforced in #' igraph, you have to check that for yourself, when assigning the vertex #' names. #' #' @aliases is.named #' @param graph The input graph. #' @return A logical scalar. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' is_named(g) #' V(g)$name <- letters[1:10] #' is_named(g) #' neighbors(g, "a") #' is_named <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } "name" %in% vertex_attr_names(graph) } #' Weighted graphs #' #' In weighted graphs, a real number is assigned to each (directed or #' undirected) edge. #' #' In igraph edge weights are represented via an edge attribute, called #' \sQuote{weight}. The \code{is_weighted} function only checks that such an #' attribute exists. (It does not even checks that it is a numeric edge #' attribute.) #' #' Edge weights are used for different purposes by the different functions. #' E.g. shortest path functions use it as the cost of the path; community #' finding methods use it as the strength of the relationship between two #' vertices, etc. Check the manual pages of the functions working with weighted #' graphs for details. #' #' @aliases is.weighted #' @param graph The input graph. #' @return A logical scalar. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords graphs #' @examples #' #' g <- make_ring(10) #' shortest_paths(g, 8, 2) #' E(g)$weight <- seq_len(ecount(g)) #' shortest_paths(g, 8, 2) #' is_weighted <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } "weight" %in% edge_attr_names(graph) } #' @rdname make_bipartite_graph #' @export is_bipartite <- function(graph) { if (!is_igraph(graph)) { stop("Not a graph object") } "type" %in% vertex_attr_names(graph) } ############# igraph.i.attribute.combination <- function(comb) { if (is.function(comb)) { comb <- list(comb) } comb <- as.list(comb) if (any(!sapply(comb, function(x) is.function(x) || (is.character(x) && length(x)==1)))) { stop("Attribute combination element must be a function or character scalar") } if (is.null(names(comb))) { names(comb) <- rep("", length(comb)) } if (any(duplicated(names(comb)))) { warning("Some attributes are duplicated") } comb <- lapply(comb, function(x) { if (!is.character(x)) { x } else { known <- data.frame(n=c("ignore", "sum", "prod", "min", "max", "random", "first", "last", "mean", "median", "concat"), i=c(0,3,4,5,6,7,8,9,10,11,12), stringsAsFactors=FALSE) x <- pmatch(tolower(x), known[,1]) if (is.na(x)) { stop("Unknown/unambigous attribute combination specification") } known[,2][x] } }) comb } #' How igraph functions handle attributes when the graph changes #' #' Many times, when the structure of a graph is modified, vertices/edges map of #' the original graph map to vertices/edges in the newly created (modified) #' graph. For example \code{\link{simplify}} maps multiple edges to single #' edges. igraph provides a flexible mechanism to specify what to do with the #' vertex/edge attributes in these cases. #' #' The functions that support the combination of attributes have one or two #' extra arguments called \code{vertex.attr.comb} and/or \code{edge.attr.comb} #' that specify how to perform the mapping of the attributes. E.g. #' \code{\link{contract}} contracts many vertices into a single one, the #' attributes of the vertices can be combined and stores as the vertex #' attributes of the new graph. #' #' The specification of the combination of (vertex or edge) attributes can be #' given as \enumerate{ #' \item a character scalar, #' \item a function object or #' \item a list of character scalars and/or function objects. #' } #' #' If it is a character scalar, then it refers to one of the predefined #' combinations, see their list below. #' #' If it is a function, then the given function is expected to perform the #' combination. It will be called once for each new vertex/edge in the graph, #' with a single argument: the attribute values of the vertices that map to #' that single vertex. #' #' The third option, a list can be used to specify different combination #' methods for different attributes. A named entry of the list corresponds to #' the attribute with the same name. An unnamed entry (i.e. if the name is the #' empty string) of the list specifies the default combination method. I.e. #' \preformatted{list(weight="sum", "ignore")} specifies that the weight of the #' new edge should be sum of the weights of the corresponding edges in the old #' graph; and that the rest of the attributes should be ignored (=dropped). #' #' @name igraph-attribute-combination #' @aliases attribute.combination #' @section Predefined combination functions: The following combination #' behaviors are predefined: \describe{ \item{"ignore"}{The attribute is #' ignored and dropped.} \item{"sum"}{The sum of the attributes is #' calculated. This does not work for character attributes and works for #' complex attributes only if they have a \code{sum} generic defined. (E.g. it #' works for sparse matrices from the \code{Matrix} package, because they have #' a \code{sum} method.)} \item{"prod"}{The product of the attributes is #' calculated. This does not work for character attributes and works for #' complex attributes only if they have a \code{prod} function defined.} #' \item{"min"}{The minimum of the attributes is calculated and returned. #' For character and complex attributes the standard R \code{min} function is #' used.} \item{"max"}{The maximum of the attributes is calculated and #' returned. For character and complex attributes the standard R \code{max} #' function is used.} \item{"random"}{Chooses one of the supplied #' attribute values, uniformly randomly. For character and complex attributes #' this is implemented by calling \code{sample}.} \item{"first"}{Always #' chooses the first attribute value. It is implemented by calling the #' \code{head} function.} \item{"last"}{Always chooses the last attribute #' value. It is implemented by calling the \code{tail} function.} #' \item{"mean"}{The mean of the attributes is calculated and returned. #' For character and complex attributes this simply calls the \code{mean} #' function.} \item{"median"}{The median of the attributes is selected. #' Calls the R \code{median} function for all attribute types.} #' \item{"concat"}{Concatenate the attributes, using the \code{c} #' function. This results almost always a complex attribute.} } #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{graph_attr}}, \code{\link{vertex_attr}}, #' \code{\link{edge_attr}} on how to use graph/vertex/edge attributes in #' general. \code{\link{igraph_options}} on igraph parameters. #' @keywords graphs #' @examples #' #' g <- graph( c(1,2, 1,2, 1,2, 2,3, 3,4) ) #' E(g)$weight <- 1:5 #' #' ## print attribute values with the graph #' igraph_options(print.graph.attributes=TRUE) #' igraph_options(print.vertex.attributes=TRUE) #' igraph_options(print.edge.attributes=TRUE) #' #' ## new attribute is the sum of the old ones #' simplify(g, edge.attr.comb="sum") #' #' ## collect attributes into a string #' simplify(g, edge.attr.comb=toString) #' #' ## concatenate them into a vector, this creates a complex #' ## attribute #' simplify(g, edge.attr.comb="concat") #' #' E(g)$name <- letters[seq_len(ecount(g))] #' #' ## both attributes are collected into strings #' simplify(g, edge.attr.comb=toString) #' #' ## harmonic average of weights, names are dropped #' simplify(g, edge.attr.comb=list(weight=function(x) length(x)/sum(1/x), #' name="ignore")) NULL #' Getting and setting graph attributes, shortcut #' #' The \code{$} operator is a shortcut to get and and set #' graph attributes. It is shorter and just as readable as #' \code{\link{graph_attr}} and \code{\link{set_graph_attr}}. #' #' @param x An igraph graph #' @param name Name of the attribute to get/set. #' #' @method $ igraph #' @name igraph-dollar #' @export #' @family graph attributes #' @examples #' g <- make_ring(10) #' g$name #' g$name <- "10-ring" #' g$name `$.igraph` <- function(x, name) { graph_attr(x, name) } #' @param value New value of the graph attribute. #' #' @method $<- igraph #' @name igraph-dollar #' @export `$<-.igraph` <- function(x, name, value) { set_graph_attr(x, name, value) } igraph/R/motifs.R0000644000175100001440000002112713177712334013402 0ustar hornikusers # IGraph R package # Copyright (C) 2006-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Graph motifs #' #' Graph motifs are small connected subgraphs with a well-defined #' structure. These functions search a graph for various motifs. #' #' \code{motifs} searches a graph for motifs of a given size and returns a #' numeric vector containing the number of different motifs. The order of #' the motifs is defined by their isomorphism class, see #' \code{\link{isomorphism_class}}. #' #' @aliases graph.motifs #' @param graph Graph object, the input graph. #' @param size The size of the motif, currently 3 and 4 are supported only. #' @param cut.prob Numeric vector giving the probabilities that the search #' graph is cut at a certain level. Its length should be the same as the size #' of the motif (the \code{size} argument). By default no cuts are made. #' @return \code{motifs} returns a numeric vector, the number of occurences of #' each motif in the graph. The motifs are ordered by their isomorphism #' classes. Note that for unconnected subgraphs, which are not considered to be #' motifs, the result will be \code{NA}. #' @seealso \code{\link{isomorphism_class}} #' #' @export #' @family graph motifs #' #' @examples #' g <- barabasi.game(100) #' motifs(g, 3) #' count_motifs(g, 3) #' sample_motifs(g, 3) motifs <- function(graph, size=3, cut.prob=rep(0, size)) { if (!is_igraph(graph)) { stop("Not a graph object") } cut.prob <- as.numeric(cut.prob) if (length(cut.prob) != size) { cut.prob <- c(cut.prob[-length(cut.prob)], rep(cut.prob[-length(cut.prob)], length(cut.prob)-1)) } on.exit( .Call(C_R_igraph_finalizer) ) res <- .Call(C_R_igraph_motifs_randesu, graph, as.integer(size), as.numeric(cut.prob)) res[is.nan(res)] <- NA res } #' Graph motifs #' #' Graph motifs are small connected subgraphs with a well-defined #' structure. These functions search a graph for various motifs. #' #' \code{count_motifs} calculates the total number of motifs of a given #' size in graph. #' #' @aliases graph.motifs.no #' @param graph Graph object, the input graph. #' @param size The size of the motif, currently 3 and 4 are supported only. #' @param cut.prob Numeric vector giving the probabilities that the search #' graph is cut at a certain level. Its length should be the same as the size #' of the motif (the \code{size} argument). By default no cuts are made. #' @return \code{count_motifs} returns a numeric scalar. #' @seealso \code{\link{isomorphism_class}} #' #' @export #' @family graph motifs #' #' @examples #' g <- barabasi.game(100) #' motifs(g, 3) #' count_motifs(g, 3) #' sample_motifs(g, 3) count_motifs <- function(graph, size=3, cut.prob=rep(0, size)) { if (!is_igraph(graph)) { stop("Not a graph object") } cut.prob <- as.numeric(cut.prob) if (length(cut.prob) != size) { cut.prob <- c(cut.prob[-length(cut.prob)], rep(cut.prob[-length(cut.prob)], length(cut.prob)-1)) } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_motifs_randesu_no, graph, as.integer(size), as.numeric(cut.prob)) } #' Graph motifs #' #' Graph motifs are small connected subgraphs with a well-defined #' structure. These functions search a graph for various motifs. #' #' \code{sample_motifs} estimates the total number of motifs of a given #' size in a graph based on a sample. #' #' @aliases graph.motifs.est #' @param graph Graph object, the input graph. #' @param size The size of the motif, currently 3 and 4 are supported only. #' @param cut.prob Numeric vector giving the probabilities that the search #' graph is cut at a certain level. Its length should be the same as the size #' of the motif (the \code{size} argument). By default no cuts are made. #' @param sample.size The number of vertices to use as a starting point for #' finding motifs. Only used if the \code{sample} argument is \code{NULL}. #' @param sample If not \code{NULL} then it specifies the vertices to use as a #' starting point for finding motifs. #' @return A numeric scalar, an estimate for the total number of motifs in #' the graph. #' @seealso \code{\link{isomorphism_class}} #' #' @export #' @family graph motifs #' #' @examples #' g <- barabasi.game(100) #' motifs(g, 3) #' count_motifs(g, 3) #' sample_motifs(g, 3) sample_motifs <- function(graph, size=3, cut.prob=rep(0, size), sample.size=vcount(graph)/10, sample=NULL) { if (!is_igraph(graph)) { stop("Not a graph object") } cut.prob <- as.numeric(cut.prob) if (length(cut.prob) != size) { cut.prob <- c(cut.prob[-length(cut.prob)], rep(cut.prob[-length(cut.prob)], length(cut.prob)-1)) } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_motifs_randesu_estimate, graph, as.integer(size), as.numeric(cut.prob), as.integer(sample.size), as.numeric(sample)) } #' Dyad census of a graph #' #' Classify dyads in a directed graphs. The relationship between each pair of #' vertices is measured. It can be in three states: mutual, asymmetric or #' non-existent. #' #' #' @aliases dyad.census dyad_census #' @param graph The input graph. A warning is given if it is not directed. #' @return A named numeric vector with three elements: \item{mut}{The number of #' pairs with mutual connections.} \item{asym}{The number of pairs with #' non-mutual connections.} \item{null}{The number of pairs with no connection #' between them.} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{triad_census}} for the same classification, but with #' triples. #' @references Holland, P.W. and Leinhardt, S. A Method for Detecting Structure #' in Sociometric Data. \emph{American Journal of Sociology}, 76, 492--513. #' 1970. #' #' Wasserman, S., and Faust, K. \emph{Social Network Analysis: Methods and #' Applications.} Cambridge: Cambridge University Press. 1994. #' @keywords graphs #' @examples #' #' g <- sample_pa(100) #' dyad_census(g) #' @export dyad_census <- dyad_census #' Triad census, subgraphs with three vertices #' #' This function counts the different subgraphs of three vertices in a graph. #' #' Triad census was defined by David and Leinhardt (see References below). #' Every triple of vertices (A, B, C) are classified into the 16 possible #' states: \describe{ \item{003}{A,B,C, the empty graph.} \item{012}{A->B, C, #' the graph with a single directed edge.} \item{102}{A<->B, C, the graph with #' a mutual connection between two vertices.} \item{021D}{A<-B->C, the #' out-star.} \item{021U}{A->B<-C, the in-star.} \item{021C}{A->B->C, directed #' line.} \item{111D}{A<->B<-C.} \item{111U}{A<->B->C.} \item{030T}{A->B<-C, #' A->C.} \item{030C}{A<-B<-C, A->C.} \item{201}{A<->B<->C.} #' \item{120D}{A<-B->C, A<->C.} \item{120U}{A->B<-C, A<->C.} #' \item{120C}{A->B->C, A<->C.} \item{210}{A->B<->C, A<->C.} #' \item{300}{A<->B<->C, A<->C, the complete graph.} } #' #' This functions uses the RANDESU motif finder algorithm to find and count the #' subgraphs, see \code{\link{motifs}}. #' #' @aliases triad.census triad_census #' @param graph The input graph, it should be directed. An undirected graph #' results a warning, and undefined results. #' @return A numeric vector, the subgraph counts, in the order given in the #' above description. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{dyad_census}} for classifying binary relationships, #' \code{\link{motifs}} for the underlying implementation. #' @references See also Davis, J.A. and Leinhardt, S. (1972). The Structure #' of Positive Interpersonal Relations in Small Groups. In J. Berger (Ed.), #' Sociological Theories in Progress, Volume 2, 218-251. Boston: Houghton #' Mifflin. #' @keywords graphs #' @examples #' #' g <- sample_gnm(15, 45, directed = TRUE) #' triad_census(g) #' @export triad_census <- triad_census igraph/R/socnet.R0000644000175100001440000027061113177712334013400 0ustar hornikusers# IGraph R package # Copyright (C) 2009-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### # TODO LIST: # * adding edges to a graph # * exporting graphics # * scroll bar for the graph list area == IMPOSSIBLE right now, should be a list # * window title in the error dialog # * keyboard shortcuts # * implement min & max in .tkigraph.dialog .tkigraph.env <- new.env() #' Experimental basic igraph GUI #' #' This functions starts an experimental GUI to some igraph functions. The GUI #' was written in Tcl/Tk, so it is cross platform. #' #' \code{tkigraph} has its own online help system, please see that for the #' details about how to use it. #' #' @return Returns \code{NULL}, invisibly. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @seealso \code{\link{tkplot}} for interactive plotting of graphs. #' @keywords graphs #' @export tkigraph <- function() { requireNamespace("tcltk", quietly = TRUE) || stop("tcl/tk library not available") options(scipen=10000) if (!exists("window", envir=.tkigraph.env, inherits=FALSE)) { assign("window", TRUE, envir=.tkigraph.env) assign("graphs", list(), envir=.tkigraph.env) assign("selected", list(), envir=.tkigraph.env) assign("tklines", list(), envir=.tkigraph.env) } else { stop("tkigraph window is already open!") } # Create top window top <- tcltk::tktoplevel(background="lightgrey", width=700, height=400) tcltk::tktitle(top) <- "iGraph GUI (Social Network Basics)" topframe <- tcltk::tkframe(top, relief="sunken", borderwidth=1) scr <- tcltk::tkscrollbar(top, repeatinterval=5, command=function(...) tcltk::tkyview(topframe)) tcltk::tkplace(topframe, x=0, y=0, relwidth=1.0) # Store myself in the environment if needed if (!exists("top", envir=.tkigraph.env, inherits=FALSE)) { assign("top", top, envir=.tkigraph.env) assign("topframe", topframe, envir=.tkigraph.env) } # kill myself if window was closed tcltk::tkbind(top, "", function() .tkigraph.close()) # pull-down menu main.menu <- tcltk::tkmenu(top) graph.menu <- tcltk::tkmenu(main.menu) create.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(create.menu, "command", label="By hand", command=function() { .tkigraph.by.hand() }) tcltk::tkadd(create.menu, "separator") tcltk::tkadd(create.menu, "command", label="Ring", command=function() { .tkigraph.ring() }) tcltk::tkadd(create.menu, "command", label="Tree", command=function() { .tkigraph.tree() }) tcltk::tkadd(create.menu, "command", label="Lattice", command=function() { .tkigraph.lattice() }) tcltk::tkadd(create.menu, "command", label="Star", command=function() { .tkigraph.star() }) tcltk::tkadd(create.menu, "command", label="Full", command=function() { .tkigraph.full() }) tcltk::tkadd(create.menu, "separator") tcltk::tkadd(create.menu, "command", label="Graph atlas...", command=function() { .tkigraph.atlas() }) tcltk::tkadd(create.menu, "separator") tcltk::tkadd(create.menu, "command", label="Moody-White network", command=function() { g <- graph_from_adjacency_matrix(.tkigraph.net.moody.white, mode="undirected") g <- set_graph_attr(g, "name", "Moody-White network") .tkigraph.add.graph(g) }) tcltk::tkadd(create.menu, "separator") tcltk::tkadd(create.menu, "command", label="Random (Erdos-Renyi G(n,p))", command=function() { .tkigraph.erdos.renyi.game() }) tcltk::tkadd(create.menu, "command", label="Random (Erdos-Renyi G(n,m))", command=function() { .tkigraph.erdos.renyi.gnm.game() }) tcltk::tkadd(create.menu, "command", label="Random (Barabasi-Albert)", command=function() { .tkigraph.barabasi.game() }) tcltk::tkadd(create.menu, "command", label="Random (Configuration model)", command=function() { .tkigraph.degree.sequence.game() }) tcltk::tkadd(create.menu, "command", label="Watts-Strogatz random graph", command=function() { .tkigraph.watts.strogatz() }) tcltk::tkadd(create.menu, "separator") tcltk::tkadd(create.menu, "command", label="Simplify", command=function() { .tkigraph.simplify() }) tcltk::tkadd(graph.menu, "cascade", label="Create", menu=create.menu) tcltk::tkadd(graph.menu, "command", label="Delete", command=function() { .tkigraph.delete() }) tcltk::tkadd(graph.menu, "separator") tcltk::tkadd(graph.menu, "command", label="Show graph", command=function() { .tkigraph.show() }) tcltk::tkadd(graph.menu, "command", label="Basic statistics", command=function() { .tkigraph.stat() }) tcltk::tkadd(graph.menu, "separator") tcltk::tkadd(graph.menu, "command", label="Import session", command=function() { .tkigraph.load() }) # tcltk::tkadd(graph.menu, "command", label="Load from the Web", command=function() { # .tkigraph.load.online() # }) tcltk::tkadd(graph.menu, "command", label="Export session", command=function() { .tkigraph.save() }) tcltk::tkadd(graph.menu, "separator") tcltk::tkadd(graph.menu, "command", label="Import adjacency matrix", command=function() .tkigraph.import.adjacency()) tcltk::tkadd(graph.menu, "command", label="Import edge list", command=function() .tkigraph.import.edgelist()) tcltk::tkadd(graph.menu, "command", label="Import Pajek file", command=function() .tkigraph.import.pajek()) tcltk::tkadd(graph.menu, "command", label="Export adjacency matrix", command=function() .tkigraph.export.adjacency()) tcltk::tkadd(graph.menu, "command", label="Export edge list", command=function() .tkigraph.export.edgelist()) tcltk::tkadd(graph.menu, "command", label="Export Pajek file", command=function() .tkigraph.export.pajek()) tcltk::tkadd(main.menu, "cascade", label="Graph", menu=graph.menu) plot.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(plot.menu, "command", label="Simple", command=function() { .tkigraph.plot(simple=TRUE) }) tcltk::tkadd(plot.menu, "command", label="Advanced", command=function() { .tkigraph.plot(simple=FALSE) }) tcltk::tkadd(main.menu, "cascade", label="Draw", menu=plot.menu) centrality.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(centrality.menu, "command", label="Degree (out)", command=function() { .tkigraph.degree("out") }) tcltk::tkadd(centrality.menu, "command", label="Degree (in)", command=function() { .tkigraph.degree("in") }) tcltk::tkadd(centrality.menu, "command", label="Degree (total)", command=function() { .tkigraph.degree("total") }) tcltk::tkadd(centrality.menu, "command", label="Plot log-log degree distribution", command=function() { .tkigraph.degree.dist(power=FALSE) }) tcltk::tkadd(centrality.menu, "command", label="Fit a power-law to degree distribution", command=function() { .tkigraph.degree.dist(power=TRUE) }) tcltk::tkadd(centrality.menu, "separator") tcltk::tkadd(centrality.menu, "command", label="Closeness", command=function() { .tkigraph.closeness() }) tcltk::tkadd(centrality.menu, "command", label="Betweenness", command=function() { .tkigraph.betweenness() }) tcltk::tkadd(centrality.menu, "command", label="Burt's constraint", command=function() { .tkigraph.constraints() }) tcltk::tkadd(centrality.menu, "command", label="Page rank", command=function() { .tkigraph.page.rank() }) tcltk::tkadd(centrality.menu, "separator") tcltk::tkadd(centrality.menu, "command", label="Edge betweenness", command=function() { .tkigraph.edge.betweenness() }) tcltk::tkadd(main.menu, "cascade", label="Centrality", menu=centrality.menu) distances.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(distances.menu, "command", label="Distance matrix", command=function() { .tkigraph.dist.matrix() }) tcltk::tkadd(distances.menu, "command", label="Distances from/to vertex", command=function() { .tkigraph.distance.tofrom() }) tcltk::tkadd(distances.menu, "command", label="Diameter (undirected)", command=function() { .tkigraph.diameter() }) tcltk::tkadd(distances.menu, "command", label="Draw diameter", command=function() { .tkigraph.plot.diameter(simple=FALSE) }) tcltk::tkadd(distances.menu, "command", label="Average path length (undirected)", command=function() { .tkigraph.diameter(mode="path") }) tcltk::tkadd(main.menu, "cascade", label="Distances", menu=distances.menu) component.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(component.menu, "command", label="Show components", command=function() { .tkigraph.clusters() }) tcltk::tkadd(component.menu, "command", label="Show membership", command=function() { .tkigraph.clusters.membership() }) tcltk::tkadd(component.menu, "command", label="Calculate component sizes", command=function() { .tkigraph.calculate.clusters() }) tcltk::tkadd(component.menu, "command", label="Draw components", command=function() { .tkigraph.plot.comp(simple=FALSE) }) tcltk::tkadd(component.menu, "command", label="Create graph from giant component", command=function() { .tkigraph.create.giantcomp() }) tcltk::tkadd(component.menu, "command", label="Create graph from component of a vertex", command=function() { .tkigraph.create.mycomp() }) tcltk::tkadd(component.menu, "command", label="Create graph from a component", command=function() { .tkigraph.create.comp() }) community.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(community.menu, "command", label="Spinglass algorithm", command=function() { .tkigraph.spinglass() }) tcltk::tkadd(community.menu, "command", label="Spinglass algorithm, single vertex", command=function() { .tkigraph.my.spinglass() }) cohesion.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(cohesion.menu, "command", label="Cohesion of all components", command=function() { .tkigraph.cohesion() }) subgraph.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(subgraph.menu, "cascade", label="Components", menu=component.menu) tcltk::tkadd(subgraph.menu, "cascade", label="Communities", menu=community.menu) tcltk::tkadd(subgraph.menu, "cascade", label="Cohesion", menu=cohesion.menu) tcltk::tkadd(main.menu, "cascade", label="Subgraphs", menu=subgraph.menu) motif.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(motif.menu, "command", label="Draw motifs", command=function() { .tkigraph.motifs.draw() }) tcltk::tkadd(motif.menu, "command", label="Find motifs", command=function() { .tkigraph.motifs.find() }) tcltk::tkadd(main.menu, "cascade", label="Motifs", menu=motif.menu) help.menu <- tcltk::tkmenu(main.menu) tcltk::tkadd(help.menu, "command", label="Contents", command=function() { .tkigraph.help() }) tcltk::tkadd(help.menu, "command", label="In external browser", command=function() { .tkigraph.help.external() }) tcltk::tkadd(help.menu, "separator") tcltk::tkadd(help.menu, "command", label="About", command=function() { .tkigraph.about() }) tcltk::tkadd(main.menu, "cascade", label="Help", menu=help.menu) tcltk::tkadd(main.menu, "command", label="Quit", command=.tkigraph.close) tcltk::tkconfigure(top, "-menu", main.menu) # Set up the main area tcltk::tkgrid(tcltk::tklabel(top, text=""), tcltk::tklabel(top, text="#", justify="center", relief="raised"), tcltk::tklabel(top, text="Name", width=50, relief="raised", justify="left"), tcltk::tklabel(top, text="|V|", width=6, relief="raised", justify="left"), tcltk::tklabel(top, text="|E|", width=6, relief="raised", justify="left"), tcltk::tklabel(top, text="Dir.", width=6, relief="raised", justify="left"), sticky="nsew", "in"=topframe) tcltk::tkgrid.columnconfigure(topframe, 2, weight=1) invisible(NULL) } .tkigraph.close <- function() { message <- "Are you sure?" yesno <- tcltk::tkmessageBox(message=message, icon="question", type="yesno", default="yes") if (as.character(yesno) == "no") { return() } top <- get("top", .tkigraph.env) tcltk::tkbind(top, "", "") tcltk::tkdestroy(top) rm(list=ls(envir=.tkigraph.env), envir=.tkigraph.env) } .tkigraph.get.selected <- function() { gnos <- get("selected", .tkigraph.env) which(as.logical(sapply(gnos, tcltk::tclvalue))) } .tkigraph.error <- function(message) { tcltk::tkmessageBox(message=message, icon="error", type="ok") } .tkigraph.warning <- function(message) { tcltk::tkmessageBox(message=message, icon="warning", type="ok") } .tkigraph.dialogbox <- function(TITLE="Setup parameters", ...) { params <- list(...) answers <- lapply(params, "[[", "default") dialog <- tcltk::tktoplevel() frame <- tcltk::tkframe(dialog) tcltk::tkgrid(frame) tcltk::tktitle(dialog) <- TITLE vars <- lapply(answers, tcltk::tclVar) retval <- list() widgets <- list() OnOK <- function() { retval <<- lapply(vars, tcltk::tclvalue) for (i in seq(along=params)) { if (params[[i]]$type == "listbox") { retval[[i]] <<- as.numeric(tcltk::tclvalue(tcltk::tkcurselection(widgets[[i]]))) } } tcltk::tkdestroy(dialog) } tcltk::tkgrid(tcltk::tklabel(dialog, text=TITLE, font=tcltk::tkfont.create(family="times", size="16", weight="bold")), columnspan=2, sticky="nsew", "in"=frame, padx=10, pady=10) OK.but <- tcltk::tkbutton(dialog, text=" OK ", command=OnOK) for (i in seq(along=params)) { tcltk::tkgrid(tcltk::tklabel(dialog, text=params[[i]]$name), column=0, row=i, sticky="nw", padx=10, "in"=frame) if (params[[i]]$type == "numeric" || params[[i]]$type == "text") { tmp <- tcltk::tkentry(dialog, width="10", textvariable=vars[[i]]) tcltk::tkgrid(tmp, column=1, row=i, sticky="nsew", padx=10, "in"=frame) tcltk::tkbind(tmp, "", OnOK) } else if (params[[i]]$type == "boolean") { b <- tcltk::tkcheckbutton(dialog, onvalue="TRUE", offvalue="FALSE", variable=vars[[i]]) if (params[[i]]$default == "TRUE") { tcltk::tkselect(b) } tcltk::tkgrid(b, column=1, row=i, sticky="w", padx=10, "in"=frame) } else if (params[[i]]$type == "listbox") { f <- tcltk::tkframe(dialog) tcltk::tkgrid(f, "in"=frame, padx=10, sticky="nsew", column=1, row=i) scr <- tcltk::tkscrollbar(f, repeatinterval=5) fun <- eval(eval(substitute(expression(function(...) tcltk::tkset(scr,...)), list(scr=scr)))) lb <- tcltk::tklistbox(f, selectmode="single", exportselection=FALSE, height=3, yscrollcommand=fun) fun <- eval(eval(substitute(expression(function(...) tcltk::tkyview(lb, ...)), list(lb=lb)))) tcltk::tkconfigure(scr, "-command", fun) tcltk::tkselection.set(lb, as.numeric(params[[i]]$default)+1) lapply(params[[i]]$values, function(l) tcltk::tkinsert(lb, "end", l)) tcltk::tkselection.set(lb, as.numeric(params[[i]]$default)) tcltk::tkgrid(lb, scr, sticky="nsew", "in"=f) tcltk::tkgrid.configure(scr, sticky="nsw") tcltk::tkgrid.columnconfigure(f, 0, weight=1) widgets[[i]] <- lb } } tcltk::tkgrid(OK.but, column=0, columnspan=2, sticky="nsew", "in"=frame, pady=10, padx=10) tcltk::tkgrid.columnconfigure(frame, 1, weight=1) tcltk::tkwait.window(dialog) for (i in seq(retval)) { if (params[[i]]$type == "numeric") { retval[[i]] <- eval(parse(text=retval[[i]])) } else if (params[[i]]$type == "text") { retval[[i]] <- eval(retval[[i]]) } else if (params[[i]]$type == "boolean") { if (retval[[i]] == "FALSE") { retval[[i]] <- FALSE } else { retval[[i]] <- TRUE } } else if (params[[i]]$type == "listbox") { ## nothing to do } } names(retval) <- names(params) return (retval) } .tkigraph.add.graph <- function(g) { top <- get("top", .tkigraph.env) topframe <- get("topframe", .tkigraph.env) ## add 'name' attribute if not present if (!"name" %in% vertex_attr_names(g)) { V(g)$name <- as.integer(seq(vcount(g))) } if (!"name" %in% edge_attr_names(g)) { E(g)$name <- as.integer(seq(ecount(g))) } graphs <- get("graphs", .tkigraph.env) selected <- get("selected", .tkigraph.env) assign("graphs", append(graphs, list(g)), .tkigraph.env) no <- length(graphs)+1 selected[[no]] <- tcltk::tclVar("FALSE") assign("selected", selected, .tkigraph.env) name <- graph_attr(g, "name") tmpvar <- tcltk::tclVar(as.character(name)) but <- tcltk::tkcheckbutton(top, onvalue="TRUE", offvalue="FALSE", variable=selected[[no]]) lab <- tcltk::tklabel(top, text=as.character(no), width=2) ent <- tcltk::tkentry(top, width=30, textvariable=tmpvar) lab2 <- tcltk::tklabel(top, text=as.character(vcount(g)), justify="right", padx=2) lab3 <- tcltk::tklabel(top, text=as.character(ecount(g)), justify="right", padx=2) lab4 <- tcltk::tklabel(top, text=if (is_directed(g)) "YES" else "NO") tcltk::tkgrid(but, lab, ent, lab2, lab3, lab4, "in"=topframe, sticky="nsew") tklines <- get("tklines", .tkigraph.env) tklines[[no]] <- list(but, lab, ent, lab2, lab3, lab4) assign("tklines", tklines, .tkigraph.env) } .tkigraph.delete <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) == 0) { return() } if (length(gnos) > 1) { message <- paste("Are you sure to delete", length(gnos), "graphs?") } else { message <- paste("Are you sure to delete graph #", gnos, "?") } yesno <- tcltk::tkmessageBox(message=message, icon="question", type="yesno", default="yes") if (as.character(yesno) == "no") { return() } ## remove from the screen graphs <- get("graphs", .tkigraph.env) topframe <- get("topframe", .tkigraph.env) todel <- get("tklines", .tkigraph.env)[gnos] todel <- unlist(recursive=FALSE, todel) for (i in todel) { tcltk::tkgrid.remove(topframe, i) } ## delete the graphs graphs[gnos] <- NA assign("graphs", graphs, .tkigraph.env) selected <- get("selected", .tkigraph.env) for (i in gnos) { selected[[i]] <- tcltk::tclVar("FALSE") } assign("selected", selected, .tkigraph.env) } .tkigraph.load <- function() { filename <- tcltk::tkgetOpenFile(defaultextension="Rdata", title="Load graphs") env <- new.env() load(paste(as.character(filename), collapse=" "), envir=env) .tkigraph.graphs <- get("graphs", envir=env) for (i in seq(.tkigraph.graphs)) { .tkigraph.add.graph(.tkigraph.graphs[[i]]) } if (".tkigraph.graphs" %in% ls(all.names=TRUE)) { rm(.tkigraph.graphs) } } .tkigraph.load.online <- function() { ## TODO } .tkigraph.save <- function() { graphs <- get("graphs", .tkigraph.env) topframe <- get("topframe", .tkigraph.env) for (i in seq(graphs)) { if (is.na(graphs)[i]) { next } entry <- tcltk::tkgrid.slaves(topframe, row=i, col=2) graphs[[i]] <- set_graph_attr(graphs[[i]], "name", as.character(tcltk::tcl(entry, "get"))) } graphs <- graphs[ !is.na(graphs) ] filename <- tcltk::tkgetSaveFile(initialfile="graphs.Rdata", defaultextension="Rdata", title="Save graphs") save(graphs, file=paste(as.character(filename), collapse=" ")) } #' @importFrom utils read.table .tkigraph.import.adjacency <- function() { filename <- tcltk::tkgetOpenFile(defaultextension="adj", title="Import adjacency matrix") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } tab <- read.table(filename) tab <- as.matrix(tab) if (ncol(tab) != nrow(tab)) { .tkigraph.error("Cannot interpret as adjacency matrix") return() } dir <- if (all(t(tab)==tab)) "undirected" else "directed" if (all(unique(tab) %in% c(0,1))) { weighted <- NULL } else { weighted <- "weight" } g <- .tkigraph.graph.adjacency(tab, mode=dir, weighted=weighted) g <- set_graph_attr(g, "name", "Imported adjacency matrix") .tkigraph.add.graph(g) } .tkigraph.graph.adjacency <- function(adjmatrix, mode, weighted) { if (is.null(weighted)) { g <- graph_from_adjacency_matrix(adjmatrix, mode=mode) } else { ## there is bug in the currect igraph version, this is a workaround if (mode=="undirected") { adjmatrix[ lower.tri(adjmatrix) ] <- 0 } g <- graph_from_adjacency_matrix(adjmatrix, mode=mode, weighted=weighted) } g } #' @importFrom utils read.table .tkigraph.import.edgelist <- function() { filename <- tcltk::tkgetOpenFile(defaultextension="el", title="Import edge list") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } tab <- read.table(filename, colClasses="character") cn <- rep("", ncol(tab)) if (ncol(tab)>=3) { cn[3] <- "weight" } colnames(tab) <- cn read <- .tkigraph.dialogbox(TITLE="Importing an edge list", directed=list(name="Directed", type="boolean", default="FALSE")) g <- graph_from_data_frame(tab, directed=read$directed) g <- set_graph_attr(g, "name", "Imported edge list") .tkigraph.add.graph(g) } .tkigraph.import.pajek <- function() { filename <- tcltk::tkgetOpenFile(defaultextension="net", title="Import Pajek file") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } g <- read_graph(file=filename, format="pajek") color <- NULL # To eliminate a check NOTE if ("color" %in% vertex_attr_names(g)) { V(g)[ color=="" ]$color <- "black" } if ("color" %in% edge_attr_names(g)) { E(g)[ color=="" ]$color <- "black" } g <- set_graph_attr(g, "name", "Imported Pajek fie") .tkigraph.add.graph(g) } #' @importFrom utils write.table .tkigraph.export.adjacency <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] if ("weight" %in% graph_attr_names(graph)) { tab <- as_adj(graph, attr="weight", names=FALSE, sparse=FALSE) } else { tab <- as_adj(graph, names=FALSE, sparse=FALSE) } filename <- tcltk::tkgetSaveFile(initialfile="graph.adj", defaultextension="adj", title="Export adjacency matrix") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } write.table(tab, file=filename, row.names=FALSE, col.names=FALSE) } #' @importFrom utils write.table .tkigraph.export.edgelist <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] el <- as_edgelist(graph) if ("weight" %in% edge_attr_names(graph)) { el <- cbind(el, E(graph)$weight) } filename <- tcltk::tkgetSaveFile(initialfile="graph.el", defaultextension="el", title="Export edge list") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } write.table(el, file=filename, row.names=FALSE, col.names=FALSE) } .tkigraph.export.pajek <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] filename <- tcltk::tkgetSaveFile(initialfile="pajek.net", defaultextension="net", title="Export Pajek file") filename <- paste(as.character(filename), collapse=" ") if (filename=="") { return() } write_graph(graph, file=filename, format="pajek") } .tkigraph.show <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) el <- as_edgelist(graphs[[gnos]]) el <- data.frame(from=el[,1], to=el[,2]) # if (any(V(graphs[[gnos]])$name != seq(length=vcount(graphs[[gnos]])))) { # el2 <- as_edgelist(graphs[[gnos]], names=FALSE) # el <- cbind(el, el2) # } if ("weight" %in% edge_attr_names(graphs[[gnos]])) { el <- cbind(el, value=E(graphs[[gnos]])$weight) } .tkigraph.showData(el, title=paste(sep="", "Graph #", gnos), right=FALSE) } .tkigraph.stat <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) == 0) { .tkigraph.error("Please select some graphs") return() } read <- .tkigraph.dialogbox(TITLE="Choose statistics", vertices=list(name="Vertices", type="boolean", default="FALSE"), edges=list(name="Edges", type="boolean", default="FALSE"), recip=list(name="Reciprocity", type="boolean", default="FALSE"), dens=list(name="Density", type="boolean", default="FALSE"), trans=list(name="Transitivity (global)", type="boolean", default="FALSE"), ltrans=list(name="Mean local transitivity", type="boolean", default="FALSE"), deg=list(name="Average degree", type="boolean", default="FALSE"), maxdeg=list(name="Maximum degree (total)", type="boolean", default="FALSE"), maxindeg=list(name="Maximum degree (in)", type="boolean", default="FALSE"), maxoutdeg=list(name="Maximum degree (out)", type="boolean", default="FALSE"), mindeg=list(name="Minimum degree (total)", type="boolean", default="FALSE"), minindeg=list(name="Minimum degree (in)", type="boolean", default="FALSE"), minoutdeg=list(name="Minimum degree (out)", type="boolean", default="FALSE") ) graphs <- get("graphs", .tkigraph.env)[gnos] v <- e <- recip <- dens <- trans <- ltrans <- deg <- maxdeg <- maxindeg <- maxoutdeg <- mindeg <- minindeg <- minoutdeg <- numeric() for (i in seq(along=gnos)) { if (read$vertices) { v[i] <- vcount( graphs[[ i ]] ) } if (read$edges) { e[i] <- ecount( graphs[[ i ]] ) } if (read$recip) { recip[i] <- reciprocity( graphs[[ i ]] ) } if (read$dens) { dens[i] <- edge_density( graphs[[ i ]] ) } if (read$trans) { trans[i] <- transitivity( graphs[[ i ]], type="global") } if (read$ltrans) { ltrans[i] <- transitivity( graphs[[ i ]], type="localaverage") } if (read$deg) { deg[i] <- mean(degree( graphs[[ i ]], mode="total")) } if (read$maxdeg) { maxdeg[i] <- max(degree( graphs[[ i ]], mode="total")) } if (read$maxindeg) { maxindeg[i] <- max(degree( graphs[[ i ]], mode="in")) } if (read$maxoutdeg) { maxoutdeg[i] <- max(degree( graphs[[ i ]], mode="out")) } if (read$mindeg) { mindeg[i] <- min(degree( graphs[[ i ]], mode="total")) } if (read$minindeg) { minindeg[i] <- min(degree( graphs[[ i ]], mode="in")) } if (read$minoutdeg) { minoutdeg[i] <- min(degree( graphs[[ i ]], mode="out")) } } value <- numeric() cn <- character() if (read$vertices) { value <- cbind(value, v) cn <- c(cn, "Vertices") } if (read$edges) { value <- cbind(value, e) cn <- c(cn, "Edges") } if (read$recip) { value <- cbind(value, recip) cn <- c(cn, "Reciprocity") } if (read$dens) { value <- cbind(value, dens) cn <- c(cn, "Density") } if (read$trans) { value <- cbind(value, trans) cn <- c(cn, "Transitivity") } if (read$ltrans) { value <- cbind(value, ltrans) cn <- c(cn, "Local trans.") } if (read$deg) { value <- cbind(value, deg) cn <- c(cn, "Mean degree") } if (read$maxdeg) { value <- cbind(value, maxdeg) cn <- c(cn, "Max. degree") } if (read$maxindeg) { value <- cbind(value, maxindeg) cn <- c(cn, "Max. in-deg.") } if (read$maxoutdeg) { value <- cbind(value, maxoutdeg) cn <- c(cn, "Max. out-deg.") } if (read$mindeg) { value <- cbind(value, mindeg) cn <- c(cn, "Min. deg.") } if (read$minindeg) { value <- cbind(value, minindeg) cn <- c(cn, "Min. in-deg.") } if (read$minoutdeg) { value <- cbind(value, minoutdeg) cn <- c(cn, "Min. out-deg.") } value <- t(value) rownames(value) <- cn colnames(value) <- gnos .tkigraph.showData(value, title="Graphs properties", sort.button=FALSE) } #' @importFrom grDevices dev.new .tkigraph.plot <- function(simple=TRUE, gnos=NULL, ...) { if (is.null(gnos)) { gnos <- .tkigraph.get.selected() } graphs <- get("graphs", .tkigraph.env) if (length(gnos)==0) { return (.tkigraph.error("Please select one or more graphs to draw.")) } max.vcount <- max(sapply(graphs[gnos], vcount)) if (max.vcount > 5000) { vertex.size <- 1 } else if (max.vcount > 30) { vertex.size <- 3 } else { vertex.size <- 15 } if (!simple) { read <- .tkigraph.dialogbox(TITLE="Drawing graphs", interactive=list(name="Interactive", type="boolean", default="FALSE"), vertex.size=list(name="Vertex size", type="numeric", default=vertex.size), labels=list(name="Vertex labels", type="listbox", default="3", values=c("None", "IDs", "Names", "Labels")), elabels=list(name="Edge labels", type="listbox", default="0", values=c("None", "IDs", "Names", "Values")), layout=list(name="Layout", type="listbox", default="0", values=c("Default", "Force-based (KK)", "Force-based (FR)", "Tree (RT)", "Circle", "Random"))) } else { read <- list(interactive=FALSE, vertex.size=vertex.size, labels=3, # labels elabels=0, # none layout=0) } if (!read$interactive) { fun <- function(...) { dev.new() ; plot.igraph(...) } } else { fun <- tkplot } layout.default <- function(graph, layout.par) { if ("x" %in% vertex_attr_names(graph) && "y" %in% vertex_attr_names(graph)) { cbind( V(graph)$x , V(graph)$y ) } else if ("layout" %in% graph_attr_names(graph)) { l <- graph_attr(graph, "layout") if (is.function(l)) { l(graph) } else { l } } else if (vcount(graph) < 300 && is_connected(graph)) { layout_with_kk(graph) } else if (vcount(graph) < 1000) { layout_with_fr(graph) } else { layout_in_circle(graph) } } layouts <- list(layout.default, layout_with_kk, layout_with_fr, layout_as_tree, layout_in_circle, layout_randomly) if (read$vertex.size < 10) { label.dist <- 0.4 } else { label.dist <- 0 } for (i in gnos) { if (read$labels == "0") { labels <- NA } else if (read$labels == "1") { labels <- seq(vcount(graphs[[i]])) } else if (read$labels == "2") { labels <- V(graphs[[i]])$name } else if (read$labels == "3") { if ("label" %in% vertex_attr_names(graphs[[i]])) { labels <- V(graphs[[i]])$label } else { labels <- V(graphs[[i]])$name } } if (read$elabels == "0") { elabels <- NA } else if (read$labels == "1") { elabels <- seq(ecount(graphs[[i]])) } else if (read$labels == "2") { elabels <- E(graphs[[i]])$name } else if (read$labels == "3") { if ("weight" %in% edge_attr_names(graphs[[i]])) { elabels <- E(graphs[[i]])$weight } else { .tkigraph.warning("No edge weights, not a valued graph"); elabels <- NA } } if (vcount(graphs[[i]]) > 10) { eas <- 0.5 } else { eas <- 1 } g <- graphs[[i]] g <- delete_vertex_attr(g, "name") fun(g, layout=layouts[[ read$layout+1 ]], vertex.size=read$vertex.size, ## vertex.color=read$vertex.color, vertex.label=labels, vertex.label.dist=label.dist, edge.label=elabels, edge.arrow.size=eas, ...) } } #' @importFrom utils edit .tkigraph.by.hand <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) > 1) { .tkigraph.error("Please select zero or one graph") return() } if (length(gnos)==0) { newdf <- edit(data.frame(list(from=character(), to=character()))) if (ncol(newdf) > 2) { colnames(newdf) <- c("from", "to", "weight") } read <- .tkigraph.dialogbox(TITLE="Creating a graph by hand", directed=list(name="Directed", type="boolean", default="FALSE")) g <- graph_from_data_frame(newdf, directed=read$directed) g <- set_graph_attr(g, "name", "New graph") .tkigraph.add.graph(g) } else { graphs <- get("graphs", .tkigraph.env) df <- as_edgelist(graphs[[gnos]]) colnames <- c("from", "to") if ("weight" %in% edge_attr_names(graphs[[gnos]])) { df <- cbind(df, E(g)$weight) colnames <- c("from", "to", "weight") } df <- as.data.frame(df) colnames(df) <- colnames df <- edit(df) if (ncol(df) > 2) { colnames(df) <- c("from", "to", "weight") } graphs[[gnos]] <- graph_from_data_frame(df, directed=is_directed(graphs[[gnos]])) assign("graphs", graphs, .tkigraph.env) } invisible(NULL) } .tkigraph.tree <- function() { read <- .tkigraph.dialogbox(TITLE="Regular tree", n=list(name="Vertices", type="numeric", default=63, min=0), b=list(name="Branches", type="numeric", default=2, min=1), mode=list(name="Mode", type="listbox", values=c("Directed (out)", "Directed (in)", "Undirected"), default="2")) read$mode <- c("out", "in", "undirected")[read$mode+1] g <- make_tree(n=read$n, children=read$b, mode=read$mode) lay <- layout_as_tree(g, root=1, mode="all") g <- set_graph_attr(g, "layout", lay) g <- set_graph_attr(g, "name", "Regular tree") .tkigraph.add.graph(g) } .tkigraph.ring <- function() { read <- .tkigraph.dialogbox(TITLE="Regular ring", n=list(name="Vertices", type="numeric", default=100, min=0)) g <- make_ring(n=read$n) g <- set_graph_attr(g, "layout", layout_in_circle) g <- set_graph_attr(g, "name", "Regular ring") .tkigraph.add.graph(g) } .tkigraph.lattice <- function() { read <- .tkigraph.dialogbox(TITLE="Regular lattice", dim=list(name="Dimensions", type="numeric", default=2, min=1, max=5), s1=list(name="Size 1", type="numeric", default=10, min=1), s2=list(name="Size 2", type="numeric", default=10, min=1), s3=list(name="Size 3", type="numeric", default=10, min=1), s4=list(name="Size 4", type="numeric", default=10, min=1), s5=list(name="Size 5", type="numeric", default=10, min=1)) if (read$dim > 5) { read$dim <- 5 } dimv <- c(read$s1, read$s2, read$s3, read$s4, read$s5)[1:read$dim] g <- make_lattice(dimvector=dimv) g <- set_graph_attr(g, "name", "Regular Lattice") .tkigraph.add.graph(g) } .tkigraph.star <- function() { read <- .tkigraph.dialogbox(TITLE="Star graph", n=list(name="Vertices", type="numeric", default=100, min=0), mode=list(name="Mode", type="listbox", values=c("Directed (out)", "Directed (in)", "Undirected"), default="2")) read$mode <- c("out", "in", "undirected")[read$mode+1] g <- make_star(read$n, mode=read$mode) g <- set_graph_attr(g, "name", "Star graph") .tkigraph.add.graph(g) } .tkigraph.full <- function() { read <- .tkigraph.dialogbox(TITLE="Full graph", n=list(name="Vertices", type="numeric", default=30, min=0), directed=list(name="Directed", type="boolean", default="FALSE"), loops=list(name="Loops", type="boolean", default="FALSE")) g <- make_full_graph(read$n, read$directed, read$loops) g <- set_graph_attr(g, "name", "Full graph") .tkigraph.add.graph(g) } .tkigraph.atlas <- function() { read <- .tkigraph.dialogbox(TITLE="Graph Atlas", n=list(name="Number", type="numeric", default=sample(0:1252, 1), min=0, max=1252)) g <- graph.atlas(read$n) g <- set_graph_attr(g, "name", paste("Graph Atlas #", read$n)) .tkigraph.add.graph(g) } .tkigraph.erdos.renyi.game <- function() { read <- .tkigraph.dialogbox(TITLE="Erdos-Renyi random graph, G(n,p)", n=list(name="Vertices", type="numeric", default=100, min=0), p=list(name="Connection probability", type="numeric", default=0.02, min=0, max=1), directed=list(name="Directed", type="boolean", default="FALSE")) g <- sample_gnp(read$n,read$p,directed=read$directed) g <- set_graph_attr(g, "name", "Random graph (Erdos-Renyi G(n,p))") .tkigraph.add.graph(g) } .tkigraph.erdos.renyi.gnm.game <- function() { read <- .tkigraph.dialogbox(TITLE="Erdos-Renyi random graph, G(n,m)", n=list(name="Vertices", type="numeric", default=100, min=0), m=list(name="Edges", type="numeric", default=200, min=0), directed=list(name="Directed", type="boolean", default="FALSE")) g <- sample_gnm(read$n, read$m, directed=read$directed) g <- set_graph_attr(g, "name", "Random graph (Erdos-Renyi G(n,m))") .tkigraph.add.graph(g) } .tkigraph.barabasi.game <- function() { read <- .tkigraph.dialogbox(TITLE="Scale Free graph", n=list(name="Vertices", type="numeric", default=100, min=0), m=list(name="Edges per time step", type="numeric", default=1, min=0), directed=list(name="Directed", type="boolean", default="TRUE")) g <- barabasi.game(n=read$n, m=read$m, directed=read$directed) g <- set_graph_attr(g, "name", "Scale-free random graph") .tkigraph.add.graph(g) } #' @importFrom graphics hist plot #' @importFrom grDevices dev.new .tkigraph.degree.sequence.game <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) == 0) { .tkigraph.error("Please select at least one graph") return() } graphs <- get("graphs", .tkigraph.env) for (i in gnos) { if (is_directed(graphs[[i]])) { indeg <- degree(graphs[[i]], mode="in") outdeg <- degree(graphs[[i]], mode="out") g <- sample_degseq(out.deg=outdeg, in.deg=indeg) } else { deg <- degree(graphs[[i]]) g <- sample_degseq(deg) } g <- set_graph_attr(g, "name", paste(sep="", "Configuration model (#", i,")")) .tkigraph.add.graph(g) } } .tkigraph.watts.strogatz <- function() { read <- .tkigraph.dialogbox(TITLE="Watts-Strogatz graph", dim=list(name="Dimensions", type="numeric", default=1, min=1), size=list(name="Lattice size", type="numeric", default=1000, min=1), nei=list(name="Neighborhood", type="numeric", default=5, min=1), p=list(name="Rewiring probability", type="numeric", default=0.01, min=0, max=1)) g <- sample_smallworld(dim=read$dim, size=read$size, nei=read$nei, p=read$p) g <- set_graph_attr(g, "name", "Watts-Strogatz small-world graph") if (read$dim == 1) { g <- set_graph_attr(g, "layout", layout_in_circle) } .tkigraph.add.graph(g) } .tkigraph.simplify <- function() { gnos <- .tkigraph.get.selected() graphs <- get("graphs", .tkigraph.env) for (i in gnos) { g <- simplify(graphs[[i]]) g <- set_graph_attr(g, "name", paste(sep="", "Simplification of #", i)) .tkigraph.add.graph(g) } } ##################################################### .tkigraph.degree <- function(mode) { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) deg <- degree(graphs[[gnos]], mode=mode) value <- data.frame(Vertex=V(graphs[[gnos]])$name, deg) colnames(value) <- c("Vertex", paste(sep="","Degree (", mode, ")")) plot.command <- function() { read <- .tkigraph.dialogbox(TITLE="Plot degree distribution", logx=list(name="Logarithmic `X' axis", type="boolean", default="FALSE"), logy=list(name="Logarithmic `Y' axis", type="boolean", default="FALSE"), hist=list(name="Histogram", type="boolean", default="FALSE")) if (!read$hist) { h <- hist(value[,2], -1:max(value[,2]), plot=FALSE)$density log <- "" if (read$logx) { log <- paste(sep="", log, "x") } if (read$logy) { log <- paste(sep="", log, "y") } dev.new() plot(0:max(value[,2]), h, xlab="Degree", ylab="Relative frequency", type="b", main="Degree distribution", log=log) } else { dev.new() hist(value[,2], main="Degree distribution", xlab="Degree") } } value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean degree:", round(mean(deg), 2)) .tkigraph.showData(value, title=paste(sep="", "Degree for graph #", gnos), plot.text="Plot distribution", plot.command=plot.command, showmean=mv) } #' @importFrom grDevices dev.new #' @importFrom graphics plot hist lines legend #' @importFrom stats coef vcov .tkigraph.degree.dist <- function(power=FALSE) { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) read <- .tkigraph.dialogbox(TITLE="Choose degree type", type=list(name="Degree type", type="listbox", default="0", values=c("Out", "In", "Total"))) mode <- c("out", "in", "all")[read$type+1] deg <- degree(graphs[[gnos]], mode=mode) dev.new() h <- hist(deg, -1:max(deg), plot=FALSE)$density plot(0:max(deg), h, xlab="Degree", ylab="Relative frequency", type="b", main="Degree distribution", log="xy") if (power) { if (max(deg)<10) { .tkigraph.error("Degrees are too small for a power-law fit") return() } fit <- fit_power_law(deg, xmin=10) lines(0:max(deg), (0:max(deg))^(-coef(fit)), col="red") legend("topright", c(paste("exponent:", round(coef(fit), 2)), paste("standard error:", round(sqrt(vcov(fit)), 2))), bty="n", cex=1.5) } } .tkigraph.closeness <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) cl <- closeness(graphs[[gnos]], mode="out") value <- data.frame(Vertex=V(graphs[[gnos]])$name, Closeness=cl) value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(cl),2)) .tkigraph.showData(value, title=paste(sep="", "Closeness for graph #", gnos), showmean=mv) } .tkigraph.betweenness <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) btw <- betweenness(graphs[[gnos]]) vc <- vcount(graphs[[gnos]]) m <- (vc-1)*(vc-2) nbtw <- btw/m value <- data.frame(V(graphs[[gnos]])$name, btw, nbtw) colnames(value) <- c("Vertex", "Betweenness", "Normalized Betweenness") value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(btw),2), "&", round(mean(nbtw),5)) .tkigraph.showData(value, title=paste(sep="", "Betweenness for graph #", gnos), showmean=mv) } .tkigraph.constraints <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) const <- constraint(graphs[[gnos]]) value <- data.frame(V(graphs[[gnos]])$name, const) colnames(value) <- c("Vertex", "Constraint") value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(const),2)) .tkigraph.showData(value, title=paste(sep="", "Constraint for graph #", gnos), showmean=mv) } .tkigraph.power.centrality <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) bp <- power_centrality(graphs[[gnos]]) value <- data.frame(V(graphs[[gnos]])$name, bp) colnames(value) <- c("Vertex", "Power centrality") value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(bp),2)) .tkigraph.showData(value, title=paste(sep="", "Power centrality for graph #", gnos), showmean=mv) } .tkigraph.page.rank <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) bp <- page_rank(graphs[[gnos]])$vector value <- data.frame(V(graphs[[gnos]])$name, bp) colnames(value) <- c("Vertex", "Page rank") value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(bp),2)) .tkigraph.showData(value, title=paste(sep="", "Page rank centrality for graph #", gnos), showmean=mv) } .tkigraph.edge.betweenness <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- get("graphs", .tkigraph.env) ebtw <- edge_betweenness(graphs[[gnos]]) el <- as_edgelist(graphs[[gnos]]) value <- data.frame(E(graphs[[gnos]])$name, el[,1], el[,2], ebtw) colnames(value) <- c("Edge", "From", "To", "Betweenness") value <- value[ order(value[,4], decreasing=TRUE), ] mv <- paste("Mean value:", round(mean(ebtw),2)) .tkigraph.showData(value, title=paste(sep="", "Edge betweenness for graph #",gnos), showmean=mv) } ##################################################### .tkigraph.dist.matrix <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] if (vcount(graph) > 100) { .tkigraph.error("Graphs is too large to do this") return() } value <- distances(graph, mode="out") rownames(value) <- colnames(value) <- V(graph)$name .tkigraph.showData(value, sort.button=FALSE, title=paste(sep="", "Distance matrix for graph #", gnos)) } .tkigraph.distance.tofrom <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] read <- .tkigraph.dialogbox(TITLE="Distance from a vertex", v=list(name="Vertex ID", type="numeric", default=1, min=1, max=vcount(graph))) if (read$v < 1 || read$v > vcount(graph)) { .tkigraph.error("Invalid vertex ID") return() } value <- distances(graph, read$v, mode="out") dim(value) <- NULL value <- data.frame( V(graph)$name, value) colnames(value) <- c("Vertex", "Distance") mv <- paste("Mean distance:", round(mean(value[,2]),2)) .tkigraph.showData(value, title=paste("Distance from vertex", read$v, "in graph #", gnos), showmean=mv) } .tkigraph.diameter <- function(mode="dia") { gnos <- .tkigraph.get.selected() if (length(gnos)==0) { .tkigraph.error("Please select one or more graphs") return() } isconn <- logical() dia <- numeric() graphs <- get("graphs", .tkigraph.env) for (i in seq(along=gnos)) { if (mode=="dia") { dia[i] <- diameter(graphs[[ gnos[i] ]], directed=FALSE) } else if (mode=="path") { dia[i] <- mean_distance(graphs[[ gnos[i] ]], directed=FALSE) } isconn[i] <- is_connected(graphs[[ gnos[i] ]]) } value <- data.frame( gnos, isconn, dia) if (mode=="dia") { title <- "Diameter" colnames(value) <- c("Graph #", "Connected", "Diameter") } else if (mode=="path") { title <- "Average path length" colnames(value) <- c("Graph #", "Connected", "Mean path length") } title <- paste(title, "of graph") if (length(gnos) > 1) { title <- paste(sep="", title, "s") } .tkigraph.showData(value, title=title) } .tkigraph.plot.diameter <- function(simple=FALSE) { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] edges <- E(graph, path=get_diameter(graph, directed=FALSE), directed=FALSE) color <- rep("black", ecount(graph)) color[edges] <- "red" width <- rep(1, ecount(graph)) width[edges] <- 2 .tkigraph.plot(gnos=gnos, simple=simple, edge.color=color, edge.width=width) } .tkigraph.clusters <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] comm <- components(graph) members <- sapply(sapply(seq(along=comm$csize), function(i) which(comm$membership==i)), paste, collapse=", ") value <- data.frame("Component"=seq(along=comm$csize), "Members"=members) .tkigraph.showData(value, title=paste("Components of graph #", gnos), right=FALSE) } .tkigraph.clusters.membership <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] comm <- components(graph) value <- data.frame("Vertex"=seq(along=comm$membership), "Component"=comm$membership) .tkigraph.showData(value, title=paste("Components of graph #", gnos)) } #' @importFrom graphics hist plot #' @importFrom grDevices dev.new .tkigraph.calculate.clusters <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] cs <- components(graph)$csize value <- data.frame(seq(along=cs), cs) colnames(value) <- c("Cluster #", "Size") plot.command <- function() { read <- .tkigraph.dialogbox(TITLE="Plot degree distribution", logx=list(name="Logarithmic `X' axis", type="boolean", default="FALSE"), logy=list(name="Logarithmic `Y' axis", type="boolean", default="FALSE"), hist=list(name="Histogram", type="boolean", default="FALSE")) if (!read$hist) { h <- hist(value[,2], 0:max(value[,2]), plot=FALSE)$density log <- "" if (read$logx) { log <- paste(sep="", log, "x") } if (read$logy) { log <- paste(sep="", log, "y") } dev.new() plot(1:max(value[,2]), h, xlab="Component size", ylab="Relative frequency", type="b", main="Component size distribution", log=log) } else { dev.new() hist(value[,2], main="Component size distribution", xlab="Degree") } } value <- value[ order(value[,2], decreasing=TRUE), ] mv <- paste("Mean component size:", round(mean(cs),2)) .tkigraph.showData(value, title=paste(sep="", "Component sizes, graph #", gnos), plot.text="Plot distribution", plot.command=plot.command, showmean=mv) } #' @importFrom grDevices rainbow .tkigraph.plot.comp <- function(simple=FALSE) { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] clu <- components(graph) colbar <- rainbow(length(clu$csize)*2) vertex.color <- colbar[ clu$membership ] .tkigraph.plot(gnos=gnos, simple=simple, vertex.color=vertex.color) } .tkigraph.create.giantcomp <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] clu <- components(graph) v <- which(clu$membership == which.max(clu$csize)) g <- induced_subgraph(graph, v) .tkigraph.add.graph(g) } .tkigraph.create.mycomp <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] read <- .tkigraph.dialogbox(TITLE="Component of a vertex", vertex=list(name="Vertex", type="numeric", default=1, min=1, max=vcount(graph))) if (read$vertex<1 || read$vertex >vcount(graph)) { .tkigraph.error("Invalid vertex id") return() } g <- induced_subgraph(graph, subcomponent(graph, read$vertex)) .tkigraph.add.graph(g) } .tkigraph.create.comp <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] read <- .tkigraph.dialogbox(TITLE="Graph from component", comp=list(name="Component id", type="numeric", default=1, min=1)) clu <- components(graph) if (read$comp<1 || read$comp > length(clu$csize)) { .tkigraph.error("Invalid component id") return() } v <- which(clu$membership==read$comp) g <- induced_subgraph(graph, v) .tkigraph.add.graph(g) } #' @importFrom grDevices dev.new #' @importFrom graphics layout layout.show par plot text .tkigraph.motifs.draw <- function() { read <- .tkigraph.dialogbox(TITLE="Draw all motifs", size=list(name="Size", type="numeric", default=3, min=3, max=4), directed=list(name="Directed", type="boolean", default="FALSE")) if (read$size < 3 || read$size > 4) { .tkigraph.error("Invalid motif size, should be 3 or 4") return() } if (read$size == 3) { co <- matrix( c(1,1, 0,0, 2,0), ncol=2, byrow=TRUE) } else { co <- matrix( c(0,1, 1,1, 0,0, 1,0), ncol=2, byrow=TRUE) } if (read$size == 3 && read$dir) { no <- 16 rows <- cols <- 4 } else if (read$size == 3 && !read$dir) { no <- 4 rows <- cols <- 2 } else if (read$size == 4 && read$dir) { no <- 216 rows <- cols <- 15 } else if (read$size == 4 && !read$dir) { no <- 11 rows <- 4 cols <- 3 } names <- as.character(seq(no)) dev.new() layout( matrix(1:(rows*cols), nrow=rows, byrow=TRUE) ) layout.show(rows*cols) for (i in seq(no)) { g <- graph_from_isomorphism_class(read$size, i-1, directed=read$dir) par(mai=c(0,0,0,0), mar=c(0,0,0,0)) par(cex=2) plot(g, layout=co, vertex.color="red", vertex.label=NA, frame=TRUE, edge.color="black", margin=0.1, edge.arrow.size=.5) text(0,0, names[i], col="blue", cex=.5) } } #' @importFrom grDevices dev.new #' @importFrom graphics barplot layout layout.show par plot text .tkigraph.motifs.find <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } read <- .tkigraph.dialogbox(TITLE="Find motifs", size=list(name="Size", type="numeric", default=3, min=3, max=4)) if (read$size < 3 || read$size > 4) { .tkigraph.error("Invalid motif size, should be 3 or 4") return() } graphs <- get("graphs", .tkigraph.env) motifs <- motifs(graphs[[gnos]], size=read$size) if (read$size == 3) { co <- matrix( c(1,1, 0,0, 2,0), ncol=2, byrow=TRUE) } else { co <- matrix( c(0,1, 1,1, 0,0, 1,0), ncol=2, byrow=TRUE) } if (read$size == 3 && is_directed(graphs[[gnos]])) { no <- 16 rows <- cols <- 4 } else if (read$size == 3 && !is_directed(graphs[[gnos]])) { no <- 4 rows <- cols <- 2 } else if (read$size == 4 && is_directed(graphs[[gnos]])) { no <- 216 rows <- cols <- 15 } else if (read$size == 4 && !is_directed(graphs[[gnos]])) { no <- 11 rows <- 4 cols <- 3 } dev.new() barplot(motifs, names.arg=seq(no)) names <- as.character(seq(no)) dev.new() layout( matrix(1:(rows*cols), nrow=rows, byrow=TRUE) ) layout.show(rows*cols) for (i in seq(no)) { g <- graph_from_isomorphism_class(read$size, i-1, directed=is_directed(graphs[[gnos]])) par(mai=c(0,0,0,0), mar=c(0,0,0,0)) par(cex=2) plot(g, layout=co, vertex.color="red", vertex.label=NA, frame=TRUE, edge.color="black", margin=0.1) text(0,0, motifs[i], col="green") } } .tkigraph.spinglass <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] if (!is_connected(graph)) { .tkigraph.error("Graph is not connected") return() } weights <- if ("weight" %in% edge_attr_names(graph)) "TRUE" else "FALSE" read <- .tkigraph.dialogbox(TITLE="Spinglass community structure", gamma=list(name="Gamma parameter", type="numeric", default=1), weights=list(name="Use edge weights", type="boolean", default=weights), spins=list(name="Number of spins", type="numeric", default=25), parupdate=list(name="Parallel update", type="boolean", default="FALSE"), update.rule=list(name="Update rule", type="listbox", default="1", values=c("Simple", "Configuration model")), start.temp=list(name="Start temperature", type="numeric", default=1), stop.temp=list(name="Stop temperature", type="numeric", default=0.1), cool.fact=list(name="Cooling factor", type="numeric", default=0.99)) read$update.rule <- c("simple", "config")[read$update.rule+1] if (read$weights) { if (!"weight" %in% edge_attr_names(graph)) { .tkigraph.warning("This graphs is not weighted") read$weights <- NULL } else { read$weights <- E(graph)$weight } } else { read$weights <- NULL } comm <- cluster_spinglass(graph, weights=read$weights, spins=read$spins, parupdate=read$parupdate, start.temp=read$start.temp, stop.temp=read$stop.temp, cool.fact=read$cool.fact, update.rule=read$update.rule, gamma=read$gamma) .tkigraph.spinglass.community.dialog(comm, read, gnos) } #' @importFrom grDevices rainbow .tkigraph.spinglass.community.dialog <- function(comm, read, gnos) { dialog <- tcltk::tktoplevel() frame <- tcltk::tkframe(dialog) tcltk::tkgrid(frame) tcltk::tktitle(dialog) <- "Spinglass community structure algorithm results" read$update.rule <- if (read$update.rule=="simple") "Simple" else "Configuration model" tcltk::tkgrid(tcltk::tklabel(dialog, text="Spinglass community structure algorithm results", font=tcltk::tkfont.create(family="times", size=16, weight="bold")), columnspan=3, sticky="nsew", "in"=frame, padx=10, pady=10) tcltk::tkgrid(txt <- tcltk::tktext(dialog), columnspan=1, rowspan=5, sticky="nsew", "in"=frame, padx=10, pady=10) tcltk::tkconfigure(txt, height=15) tcltk::tkinsert(txt, "end", "Parameters were:\n") tcltk::tkinsert(txt, "end", paste(" Gamma=", read$gamma, "\n")) tcltk::tkinsert(txt, "end", if (is.null(read$weights)) " Weights were not used.\n" else " Weights were used.\n") tcltk::tkinsert(txt, "end", paste(" Number of spins=", read$spins, "\n")) tcltk::tkinsert(txt, "end", if (read$parupdate) " Parallel updating.\n" else " Sequential updating.\n") tcltk::tkinsert(txt, "end", paste(" Update rule:", read$update.rule, "\n")) tcltk::tkinsert(txt, "end", paste(" Start temperature was", read$start.temp, "\n")) tcltk::tkinsert(txt, "end", paste(" Stop temperaure was", read$stop.temp, "\n")) tcltk::tkinsert(txt, "end", paste(" Cooling factor was", read$cool.fact, "\n")) tcltk::tkinsert(txt, "end", "\nResults:\n") tcltk::tkinsert(txt, "end", paste(" Number of communities found:", length(comm$csize), "\n")) tcltk::tkinsert(txt, "end", paste(" Modularity of the result:", comm$modularity, "\n")) tcltk::tkinsert(txt, "end", paste(" Stopped at temperature:", comm$temperature, "\n")) tcltk::tkconfigure(txt, state="disabled") show.communities <- function() { members <- sapply(sapply(seq(along=comm$csize), function(i) which(comm$membership==i)), paste, collapse=", ") value <- data.frame("Community"=seq(along=comm$csize), "Members"=members) .tkigraph.showData(value, title=paste("Communities, spinglass algorithm on graph #", gnos), right=FALSE) } show.membership <- function() { value <- data.frame("Vertex"=seq(along=comm$membership), "Community"=comm$membership) .tkigraph.showData(value, title=paste("Communities, spinglass algorithm on graph #", gnos)) } show.csize <- function() { value <- data.frame("Comm. #"=seq(along=comm$csize), "Size"=comm$csize) value <- value[ order(value[,2], decreasing=TRUE), ] .tkigraph.showData(value, title=paste("Communities, spinglass algorithm on graph #", gnos)) } plot.communities <- function(simple=FALSE) { colbar <- rainbow(length(comm$csize)*2) vertex.color=colbar[ comm$membership ] .tkigraph.plot(gnos=gnos, simple=simple, vertex.color=vertex.color) } create.subgraph <- function() { ## TODO } tcltk::tkgrid(tcltk::tkbutton(dialog, text="Show communities", command=show.communities), "in"=frame, sticky="ew", column=1, row=1, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Show membership", command=show.membership), "in"=frame, sticky="ew", column=1, row=2, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Show community sizes", command=show.csize), "in"=frame, sticky="ew", column=1, row=3, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Draw communities", command=function() plot.communities(simple=FALSE)), "in"=frame, sticky="ew", column=1, row=4, padx=10, pady=10) ## tcltk::tkgrid(tcltk::tkbutton(dialog, text="Create subgraph", command=create.subgraph), ## "in"=frame, sticky="nsew", column=1, row=6, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Close", command=function() tcltk::tkdestroy(dialog)), "in"=frame, sticky="nsew", columnspan=2, padx=10, pady=10) } .tkigraph.my.spinglass <- function() { gnos <- .tkigraph.get.selected() if (length(gnos)!=1) { .tkigraph.error("Please select exactly one graph") return() } graph <- get("graphs", .tkigraph.env)[[gnos]] if (!is_connected(graph)) { .tkigraph.error("Graph is not connected") return() } weights <- if ("weight" %in% edge_attr_names(graph)) "TRUE" else "FALSE" read <- .tkigraph.dialogbox(TITLE="Spinglass community of a vertex", vertex=list(name="Vertex", type="numeric", default=1, min=1, max=vcount(graph)), gamma=list(name="Gamma parameter", type="numeric", default=1), weights=list(name="Use edge weights", type="boolean", default=weights), spins=list(name="Number of spins", type="numeric", default=25), update.rule=list(name="Update rule", type="listbox", default="1", values=c("Simple", "Configuration model"))) if (read$vertex<1 || read$vertex > vcount(graph)) { .tkigraph.error("Invalid vertex id") return() } read$update.rule <- c("simple", "config")[read$update.rule+1] if (read$weights) { if (!"weight" %in% edge_attr_names(graph)) { .tkigraph.warning("This graphs is not weighted") read$weights <- NULL } else { read$weights <- E(graph)$weight } } else { read$weights <- NULL } comm <- cluster_spinglass(graph, vertex=read$vertex, weights=read$weights, spins=read$spins, update.rule=read$update.rule, gamma=read$gamma) .tkigraph.spinglass.mycommunity.dialog(comm, read, gnos) } .tkigraph.spinglass.mycommunity.dialog <- function(comm, read, gnos) { dialog <- tcltk::tktoplevel() frame <- tcltk::tkframe(dialog) tcltk::tkgrid(frame) tcltk::tktitle(dialog) <- "Spinglass community of a single vertex" scr <- tcltk::tkscrollbar(dialog, repeatinterval=5, command=function(...) tcltk::tkyview(txt,...)) read$update.rule <- if (read$update.rule=="simple") "Simple" else "Configuration model" tcltk::tkgrid(tcltk::tklabel(dialog, text="Spinglass community of a single vertex", font=tcltk::tkfont.create(family="times", size=16, weight="bold")), columnspan=3, sticky="nsew", "in"=frame, padx=10, pady=10) tcltk::tkgrid(txt <- tcltk::tktext(dialog, yscrollcommand=function(...) tcltk::tkset(scr,...)), columnspan=1, rowspan=3, sticky="nsew", "in"=frame, padx=10, pady=10) tcltk::tkconfigure(txt, height=17) tcltk::tkgrid(scr, row=1, column=1, rowspan=3, sticky="ns", "in"=frame, pady=10) tcltk::tkinsert(txt, "end", "Parameters were:\n") tcltk::tkinsert(txt, "end", paste(" Vertex:", read$vertex, "\n")); tcltk::tkinsert(txt, "end", paste(" Gamma=", read$gamma, "\n")) tcltk::tkinsert(txt, "end", if (is.null(read$weights)) " Weights were not used.\n" else " Weights were used.\n") tcltk::tkinsert(txt, "end", paste(" Number of spins=", read$spins, "\n")) tcltk::tkinsert(txt, "end", paste(" Update rule:", read$update.rule, "\n")) tcltk::tkinsert(txt, "end", "\nResults:\n") tcltk::tkinsert(txt, "end", paste(" Size of the community:", length(comm$community), "\n")) tcltk::tkinsert(txt, "end", paste(" Cohesion:", comm$cohesion, "\n")) tcltk::tkinsert(txt, "end", paste(" Adhesion:", comm$adhesion, "\n")) tcltk::tkinsert(txt, "end", paste(" Inner links:", comm$inner.links, "\n")) tcltk::tkinsert(txt, "end", paste(" Outer links:", comm$outer.links, "\n")) tcltk::tkinsert(txt, "end", "\nThe community:\n") con <- textConnection(NULL, open="w", local=TRUE) cat(sort(comm$community), file=con, fill=TRUE, sep=", ") tcltk::tkinsert(txt, "end", textConnectionValue(con)) close(con) tcltk::tkconfigure(txt, state="disabled") plot.communities <- function(simple=FALSE) { graph <- get("graphs", .tkigraph.env)[[gnos]] color <- rep("skyblue2", vcount(graph)) color[ comm$community ] <- "red" .tkigraph.plot(gnos=gnos, simple=simple, vertex.color=color) } create.graph <- function() { graph <- get("graphs", .tkigraph.env)[[gnos]] g <- induced_subgraph(graph, comm$community) .tkigraph.add.graph(g) } tcltk::tkgrid(tcltk::tkbutton(dialog, text="Draw community", command=function() plot.communities(simple=FALSE)), "in"=frame, sticky="ew", column=2, row=1, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Create graph from community", command=create.graph), "in"=frame, sticky="ew", column=2, row=2, padx=10, pady=10) tcltk::tkgrid(tcltk::tkbutton(dialog, text="Close", command=function() tcltk::tkdestroy(dialog)), "in"=frame, sticky="nsew", columnspan=3, padx=10, pady=10) } .tkigraph.cohesion <- function() { gnos <- .tkigraph.get.selected() if (length(gnos) != 1) { .tkigraph.error("Please select exactly one graph") return() } graphs <- decompose(get("graphs", .tkigraph.env)[[gnos]]) coh <- sapply(graphs, cohesion) value <- data.frame("Component"=seq(length=length(graphs)), "Cohesion"=coh) .tkigraph.showData(value, title=paste("Cohesion of components in graph #", gnos), right=FALSE) } #' @importFrom utils browseURL .tkigraph.help <- function(page="index.html") { dialog <- tcltk::tktoplevel() tcltk::tktitle(dialog) <- "Help (main page)" close <- function() { tcltk::tkdestroy(dialog) } scr <- tcltk::tkscrollbar(dialog, repeatinterval=5, command=function(...) tcltk::tkyview(txt,...)) txt <- tcltk::tktext(dialog, yscrollcommand=function(...) tcltk::tkset(scr, ...), width=80, height=40) main.menu <- tcltk::tkmenu(dialog) tcltk::tkadd(main.menu, "command", label="Back", command=function() { tcltk::tcl("render_back", txt) }) tcltk::tkadd(main.menu, "command", label="Forw", command=function() { tcltk::tcl("render_forw", txt) }) tcltk::tkadd(main.menu, "command", label="Home", command=function() { tcltk::tcl("render", txt, "index.html"); return() }) tcltk::tkadd(main.menu, "command", label="Close", command=function() { tcltk::tkdestroy(dialog); return() }) tcltk::tkconfigure(dialog, "-menu", main.menu) tcltk::tkpack(scr, side="right", fill="y", expand=0) tcltk::tkpack(txt, side="left", fill="both", expand=1) browser.button <- tcltk::tkbutton(dialog, command=function() { browseURL(tcltk::tclvalue("browser_url")) }) tcltk::tcl("global", "tkigraph_help_root", "tkigraph_help_history", "tkigraph_help_history_pos", "browser_button", "browser_url") tcltk::tcl("set", "tkigraph_help_root", system.file("tkigraph_help", package="igraph")) tcltk::tcl("set", "browser_button", browser.button) tcltk::tcl("source", system.file("html_library.tcl", package="igraph")) tcltk::tcl("source", system.file("my_html_library.tcl", package="igraph")) tcltk::tcl("HMinit_win", txt) tcltk::tcl("start_history", txt) tcltk::tcl("render", txt, "index.html") tcltk::tkconfigure(txt, state="disabled") } #' @importFrom utils browseURL .tkigraph.help.external <- function(page="index.html") { f <- system.file("tkigraph_help/index.html", package="igraph") browseURL(f) } #' @importFrom utils packageDescription .tkigraph.about <- function() { dialog <- tcltk::tktoplevel() tcltk::tktitle(dialog) <- "About tkigraph" image <- tcltk::tkimage.create("photo", "img", format="gif", file=system.file("igraph.gif", package="igraph")) logo <- tcltk::tklabel(dialog, relief="flat", padx=10, pady=10, image=image) label <- tcltk::tklabel(dialog, padx=30, pady=10, text=paste(sep="", "tkigraph (c) 2009 Gabor Csardi\n", "igraph (c) 2003-2009 Gabor Csardi and Tamas Nepusz\n\n", "This is igraph version ", packageDescription("igraph")$Version, " and\n", R.version$version.string)) close <- tcltk::tkbutton(dialog, text="Close", command=function() { tcltk::tkdestroy(dialog); return() }) tcltk::tkpack(logo, side="top", anchor="c", expand=0) tcltk::tkpack(label, side="top", anchor="c", expand=0) tcltk::tkpack(close, side="bottom", anchor="c", expand=0) } ##################################################### # This is from the 'relimp' package by David Firth, thanks #' @importFrom utils write.table .tkigraph.showData <- function (dataframe, colname.bgcolor = "grey50", rowname.bgcolor = "grey50", body.bgcolor = "white", colname.textcolor = "white", rowname.textcolor = "white", body.textcolor = "black", font = "Courier 12", maxheight = 30, maxwidth = 80, title = NULL, rowname.bar = "left", colname.bar = "top", rownumbers = FALSE, placement = "-20-40", plot.text="Plot", plot.command=NULL, suppress.X11.warnings = FALSE, right=TRUE, showmean=NULL, sort.button=TRUE, inthis=NULL) { if (suppress.X11.warnings) { ## as in John Fox's Rcmdr package messages.connection <- textConnection(".messages", open = "w", local = TRUE) sink(messages.connection, type = "message") on.exit({ sink(type="message") close(messages.connection) }) } object.name <- deparse(substitute(dataframe)) if (!is.data.frame(dataframe)){ temp <- try(dataframe <- as.data.frame(dataframe), silent = FALSE) if (inherits(temp, "try-error")) { stop(paste(object.name, "cannot be coerced to a data frame")) } object.name <- paste("as.data.frame(", object.name, ")", sep = "") } if (is.numeric(rownumbers) && length(rownumbers) != nrow(dataframe)) stop("rownumbers argument must be TRUE, FALSE or have length nrow(dataframe)") oldwidth <- unlist(options("width")) options(width = 10000) conn <- textConnection(NULL, open="w", local=TRUE) sink(conn) options(max.print=10000000) print(dataframe, right=right) sink() zz <- strsplit(textConnectionValue(conn), "\n", fixed=TRUE) close(conn) if (length(zz) > 1 + nrow(dataframe)) stop( "data frame too wide") options(width = oldwidth) if (is.null(inthis)) { base <- tcltk::tktoplevel() tcltk::tkwm.geometry(base, placement) tcltk::tkwm.title(base, { if (is.null(title)) object.name else title }) } else { base <- inthis } nrows <- length(zz) - 1 if (is.numeric(rownumbers)) rowname.text <- paste(rownumbers, row.names(dataframe)) else if (rownumbers) rowname.text <- paste(1:nrows, row.names(dataframe)) else rowname.text <- row.names(dataframe) namewidth = max(nchar(rowname.text)) yy <- substring(zz, 2 + max(nchar(row.names(dataframe)))) datawidth <- max(nchar(yy)) winwidth <- min(1 + datawidth, maxwidth) hdr <- tcltk::tktext(base, bg = colname.bgcolor, fg = colname.textcolor, font = font, height = 1, width = winwidth, takefocus = TRUE) ftr <- tcltk::tktext(base, bg = colname.bgcolor, fg = colname.textcolor, font = font, height = 1, width = winwidth, takefocus = TRUE) textheight <- min(maxheight, nrows) txt <- tcltk::tktext(base, bg = body.bgcolor, fg = body.textcolor, font = font, height = textheight, width = winwidth, setgrid = 1, takefocus = TRUE) lnames <- tcltk::tktext(base, bg = rowname.bgcolor, fg = rowname.textcolor, font = font, height = textheight, width = namewidth, takefocus = TRUE) rnames <- tcltk::tktext(base, bg = rowname.bgcolor, fg = rowname.textcolor, font = font, height = textheight, width = namewidth, takefocus = TRUE) xscroll <- tcltk::tkscrollbar(base, orient = "horizontal", repeatinterval = 1, command = function(...) { tcltk::tkxview(txt, ...) tcltk::tkxview(hdr, ...) tcltk::tkxview(ftr, ...) }) string.to.vector <- function(string.of.indices) { string.of.indices <- tcltk::tclvalue(string.of.indices) as.numeric(strsplit(string.of.indices, split = " ")[[1]]) } tcltk::tkconfigure(txt, xscrollcommand = function(...) { tcltk::tkset(xscroll, ...) xy <- string.to.vector(tcltk::tkget(xscroll)) tcltk::tkxview.moveto(hdr, xy[1]) tcltk::tkxview.moveto(ftr, xy[1]) }) tcltk::tkconfigure(hdr, xscrollcommand = function(...) { tcltk::tkset(xscroll, ...) xy <- string.to.vector(tcltk::tkget(xscroll)) tcltk::tkxview.moveto(txt, xy[1]) tcltk::tkxview.moveto(ftr, xy[1]) }) tcltk::tkconfigure(ftr, xscrollcommand = function(...) { tcltk::tkset(xscroll, ...) xy <- string.to.vector(tcltk::tkget(xscroll)) tcltk::tkxview.moveto(hdr, xy[1]) tcltk::tkxview.moveto(txt, xy[1]) }) yscroll <- tcltk::tkscrollbar(base, orient = "vertical", repeatinterval = 1, command = function(...) { tcltk::tkyview(txt, ...) tcltk::tkyview(lnames, ...) tcltk::tkyview(rnames, ...) }) tcltk::tkconfigure(txt, yscrollcommand = function(...) { tcltk::tkset(yscroll, ...) xy <- string.to.vector(tcltk::tkget(yscroll)) tcltk::tkyview.moveto(lnames, xy[1]) tcltk::tkyview.moveto(rnames, xy[1]) }) tcltk::tkconfigure(lnames, yscrollcommand = function(...) { tcltk::tkset(yscroll, ...) xy <- string.to.vector(tcltk::tkget(yscroll)) tcltk::tkyview.moveto(txt, xy[1]) tcltk::tkyview.moveto(rnames, xy[1]) }) tcltk::tkconfigure(rnames, yscrollcommand = function(...) { tcltk::tkset(yscroll, ...) xy <- string.to.vector(tcltk::tkget(yscroll)) tcltk::tkyview.moveto(txt, xy[1]) tcltk::tkyview.moveto(lnames, xy[1]) }) tcltk::tkbind(txt, "", function(x, y) { tcltk::tkscan.dragto(txt, x, y) }) ## The next block just enables copying from the text boxes { copyText.hdr <- function(){ tcltk::tcl("event", "generate", tcltk::.Tk.ID(hdr), "<>")} tcltk::tkbind(hdr, "", function() tcltk::tkfocus(hdr)) editPopupMenu.hdr <- tcltk::tkmenu(hdr, tearoff = FALSE) tcltk::tkadd(editPopupMenu.hdr, "command", label = "Copy ", command = copyText.hdr) RightClick.hdr <- function(x,y) # x and y are the mouse coordinates { rootx <- as.integer(tcltk::tkwinfo("rootx", hdr)) rooty <- as.integer(tcltk::tkwinfo("rooty", hdr)) xTxt <- as.integer(x) + rootx yTxt <- as.integer(y) + rooty tcltk::tcl("tk_popup", editPopupMenu.hdr, xTxt, yTxt) } tcltk::tkbind(hdr, "", RightClick.hdr) tcltk::tkbind(hdr, "", copyText.hdr) ## copyText.ftr <- function(){ tcltk::tcl("event", "generate", tcltk::.Tk.ID(ftr), "<>")} tcltk::tkbind(ftr, "", function() tcltk::tkfocus(ftr)) editPopupMenu.ftr <- tcltk::tkmenu(ftr, tearoff = FALSE) tcltk::tkadd(editPopupMenu.ftr, "command", label = "Copy ", command = copyText.ftr) RightClick.ftr <- function(x,y) # x and y are the mouse coordinates { rootx <- as.integer(tcltk::tkwinfo("rootx", ftr)) rooty <- as.integer(tcltk::tkwinfo("rooty", ftr)) xTxt <- as.integer(x) + rootx yTxt <- as.integer(y) + rooty tcltk::tcl("tk_popup", editPopupMenu.ftr, xTxt, yTxt) } tcltk::tkbind(ftr, "", RightClick.ftr) tcltk::tkbind(ftr, "", copyText.ftr) ## copyText.txt <- function(){ tcltk::tcl("event", "generate", tcltk::.Tk.ID(txt), "<>")} tcltk::tkbind(txt, "", function() tcltk::tkfocus(txt)) editPopupMenu.txt <- tcltk::tkmenu(txt, tearoff = FALSE) tcltk::tkadd(editPopupMenu.txt, "command", label = "Copy ", command = copyText.txt) RightClick.txt <- function(x,y) # x and y are the mouse coordinates { rootx <- as.integer(tcltk::tkwinfo("rootx", txt)) rooty <- as.integer(tcltk::tkwinfo("rooty", txt)) xTxt <- as.integer(x) + rootx yTxt <- as.integer(y) + rooty tcltk::tcl("tk_popup", editPopupMenu.txt, xTxt, yTxt) } tcltk::tkbind(txt, "", RightClick.txt) tcltk::tkbind(txt, "", copyText.txt) ## copyText.lnames <- function(){ tcltk::tcl("event", "generate", tcltk::.Tk.ID(lnames), "<>")} tcltk::tkbind(lnames, "", function() tcltk::tkfocus(lnames)) editPopupMenu.lnames <- tcltk::tkmenu(lnames, tearoff = FALSE) tcltk::tkadd(editPopupMenu.lnames, "command", label = "Copy ", command = copyText.lnames) RightClick.lnames <- function(x,y) # x and y are the mouse coordinates { rootx <- as.integer(tcltk::tkwinfo("rootx", lnames)) rooty <- as.integer(tcltk::tkwinfo("rooty", lnames)) xTxt <- as.integer(x) + rootx yTxt <- as.integer(y) + rooty tcltk::tcl("tk_popup", editPopupMenu.lnames, xTxt, yTxt) } tcltk::tkbind(lnames, "", RightClick.lnames) tcltk::tkbind(lnames, "", copyText.lnames) ## copyText.rnames <- function(){ tcltk::tcl("event", "generate", tcltk::.Tk.ID(rnames), "<>")} tcltk::tkbind(rnames, "", function() tcltk::tkfocus(rnames)) editPopupMenu.rnames <- tcltk::tkmenu(rnames, tearoff = FALSE) tcltk::tkadd(editPopupMenu.rnames, "command", label = "Copy ", command = copyText.rnames) RightClick.rnames <- function(x,y) # x and y are the mouse coordinates { rootx <- as.integer(tcltk::tkwinfo("rootx", rnames)) rooty <- as.integer(tcltk::tkwinfo("rooty", rnames)) xTxt <- as.integer(x) + rootx yTxt <- as.integer(y) + rooty tcltk::tcl("tk_popup", editPopupMenu.rnames, xTxt, yTxt) } tcltk::tkbind(rnames, "", RightClick.rnames) tcltk::tkbind(rnames, "", copyText.rnames) } tcltk::tktag.configure(hdr, "notwrapped", wrap = "none") tcltk::tktag.configure(ftr, "notwrapped", wrap = "none") tcltk::tktag.configure(txt, "notwrapped", wrap = "none") tcltk::tktag.configure(lnames, "notwrapped", wrap = "none") tcltk::tktag.configure(rnames, "notwrapped", wrap = "none") tcltk::tkinsert(txt, "end", paste(paste(yy[-1], collapse = "\n"), sep = ""), "notwrapped") tcltk::tkgrid(txt, row = 1, column = 1, sticky = "nsew") if ("top" %in% colname.bar) { tcltk::tkinsert(hdr, "end", paste(yy[1], sep = ""), "notwrapped") tcltk::tkgrid(hdr, row = 0, column = 1, sticky = "ew") } if ("bottom" %in% colname.bar) { tcltk::tkinsert(ftr, "end", paste(yy[1], sep = ""), "notwrapped") tcltk::tkgrid(ftr, row = 2, column = 1, sticky = "ew") } if ("left" %in% rowname.bar) { tcltk::tkinsert(lnames, "end", paste(rowname.text, collapse = "\n"), "notwrapped") tcltk::tkgrid(lnames, row = 1, column = 0, sticky = "ns") } if ("right" %in% rowname.bar) { tcltk::tkinsert(rnames, "end", paste(rowname.text, collapse = "\n"), "notwrapped") tcltk::tkgrid(rnames, row = 1, column = 2, sticky = "ns") } tcltk::tkconfigure(hdr, state = "disabled") tcltk::tkconfigure(ftr, state = "disabled") tcltk::tkconfigure(txt, state = "disabled") tcltk::tkconfigure(lnames, state = "disabled") tcltk::tkconfigure(rnames, state = "disabled") if (maxheight < nrows) { tcltk::tkgrid(yscroll, row = 1, column = 3, sticky = "ns") } if (maxwidth < datawidth) { tcltk::tkgrid(xscroll, row = 3, column = 1, sticky = "ew") } sortColumn <- function(n, decreasing=FALSE) { dataframe <<- dataframe[ order(dataframe[[n]], decreasing=decreasing), ] rownames(dataframe) <- seq(length=nrow(dataframe)) .tkigraph.showData(dataframe, colname.bgcolor = colname.bgcolor, rowname.bgcolor = rowname.bgcolor, body.bgcolor = body.bgcolor, colname.textcolor = colname.textcolor, rowname.textcolor = rowname.textcolor, body.textcolor = body.textcolor, font = font, maxheight = maxheight, maxwidth = maxwidth, title = title, rowname.bar = rowname.bar, colname.bar = colname.bar, rownumbers = rownumbers, placement = placement, plot.text=plot.text, plot.command=plot.command, suppress.X11.warnings = suppress.X11.warnings, right=right, showmean=showmean, sort.button=sort.button, inthis=base) } pf <- tcltk::tkframe(base) if (is.null(inthis)) { tcltk::tkgrid(pf, column=5, row=0, rowspan=10, sticky="new") } if (!is.null(showmean) && is.null(inthis)) { for (i in seq(along=showmean)) { tcltk::tkgrid(tcltk::tklabel(base, text=showmean[1]), sticky="nsew", column=0, padx=1, pady=1, columnspan=4) } } sortBut <- tcltk::tkbutton(base, text="Sort otherwise", command=function() {}) sortPopup <- function() { sortMenu <- tcltk::tkmenu(base, tearoff=FALSE) sapply(seq(along=colnames(dataframe)), function(n) { tcltk::tkadd(sortMenu, "command", label=colnames(dataframe)[n], command=function() sortColumn(colnames(dataframe)[n])) label <- paste(colnames(dataframe)[n], "decreasing", sep=", ") tcltk::tkadd(sortMenu, "command", label=label, command=function() sortColumn(colnames(dataframe)[n], decreasing=TRUE)) }) rootx <- as.integer(tcltk::tkwinfo("rootx", sortBut)) rooty <- as.integer(tcltk::tkwinfo("rooty", sortBut)) tcltk::tkpopup(sortMenu, rootx, rooty) } if (!is.null(plot.command)) { but <- tcltk::tkbutton(base, text=plot.text, command=plot.command) tcltk::tkgrid(but, "in"=pf, sticky="ew", column=10, row=1, padx=1, pady=1) } if (sort.button) { tcltk::tkgrid(sortBut, "in"=pf, sticky="ew", column=10, row=2, padx=1, pady=1) } tcltk::tkconfigure(sortBut, command=sortPopup) savebut <- tcltk::tkbutton(base, text="Export table to file", command=function() { filename <- tcltk::tkgetSaveFile(initialfile="data.txt", defaultextension="txt", title="Export as table") filename <- paste(as.character(filename), collapse=" ") write.table(dataframe, file=filename, row.names=FALSE, col.names=FALSE) }) tcltk::tkgrid(savebut, "in"=pf, sticky="ew", column=10, row=3, padx=1, pady=1) but <- tcltk::tkbutton(base, text="Close", command=function() tcltk::tkdestroy(base)) tcltk::tkgrid(but, "in"=pf, sticky="ew", column=10, row=4, padx=1, pady=1) tcltk::tkgrid.columnconfigure(pf, 0, weight=1) tcltk::tkgrid.rowconfigure(base, 1, weight = 1) tcltk::tkgrid.columnconfigure(base, 1, weight = 1) tcltk::tkwm.maxsize(base, 2 + datawidth, nrows) tcltk::tkwm.minsize(base, 2 + nchar(names(dataframe)[1]), 1) invisible(NULL) } .tkigraph.net.moody.white <- matrix( c(0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, 1,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0, 0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0), nrow=23, ncol=23) igraph/R/other.R0000644000175100001440000001175213177712334013225 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Running mean of a time series #' #' \code{running_mean} calculates the running mean in a vector with the given #' bin width. #' #' The running mean of \code{v} is a \code{w} vector of length #' \code{length(v)-binwidth+1}. The first element of \code{w} id the average of #' the first \code{binwidth} elements of \code{v}, the second element of #' \code{w} is the average of elements \code{2:(binwidth+1)}, etc. #' #' @aliases running.mean #' @param v The numeric vector. #' @param binwidth Numeric constant, the size of the bin, should be meaningful, #' ie. smaller than the length of \code{v}. #' @return A numeric vector of length \code{length(v)-binwidth+1} #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export #' @keywords manip #' @examples #' #' running_mean(1:100, 10) #' running_mean <- function(v, binwidth) { v <- as.numeric(v) binwidth <- as.numeric(binwidth) if (length(v) < binwidth) { stop("Vector too short for this binwidth.") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_running_mean, v, binwidth) } #' Sampling a random integer sequence #' #' This function provides a very efficient way to pull an integer random sample #' sequence from an integer interval. #' #' The algorithm runs in \code{O(length)} expected time, even if #' \code{high-low} is big. It is much faster (but of course less general) than #' the builtin \code{sample} function of R. #' #' @aliases igraph.sample #' @param low The lower limit of the interval (inclusive). #' @param high The higher limit of the interval (inclusive). #' @param length The length of the sample. #' @return An increasing numeric vector containing integers, the sample. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @references Jeffrey Scott Vitter: An Efficient Algorithm for Sequential #' Random Sampling, \emph{ACM Transactions on Mathematical Software}, 13/1, #' 58--67. #' @export #' @keywords datagen #' @examples #' #' rs <- sample_seq(1, 100000000, 10) #' rs #' sample_seq <- function(low, high, length) { if (length>high-low+1) { stop("length too big for this interval") } on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_random_sample, as.numeric(low), as.numeric(high), as.numeric(length)) } igraph.match.arg <- function(arg, choices, several.ok=FALSE) { if (missing(choices)) { formal.args <- formals(sys.function(sys.parent())) choices <- eval(formal.args[[deparse(substitute(arg))]]) } arg <- tolower(arg) choices <- tolower(choices) match.arg(arg=arg, choices=choices, several.ok=several.ok) } igraph.i.spMatrix <- function(M) { if (M$type == "triplet") { Matrix::sparseMatrix(dims=M$dim, i=M$i+1L, j=M$p+1L, x=M$x) } else { new("dgCMatrix", Dim=M$dim, Dimnames=list(NULL, NULL), factors=list(), i=M$i, p=M$p, x=M$x) } } #' Deprecated function, used to set random seed of the C library's RNG #' #' @param seed Ignored. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @export srand <- function(seed) { warning("This function does nothing, as calling srand from R packages\n", "is now not allowed. If you want to reproduce your past\n", "results, use an older version of igraph, e.g. 0.7.1") } #' Convex hull of a set of vertices #' #' Calculate the convex hull of a set of points, i.e. the covering polygon that #' has the smallest area. #' #' #' @aliases convex.hull convex_hull #' @param data The data points, a numeric matrix with two columns. #' @return A named list with components: \item{resverts}{The indices of the #' input vertices that constritute the convex hull.} \item{rescoords}{The #' coordinates of the corners of the convex hull.} #' @author Tamas Nepusz \email{ntamas@@gmail.com} #' @references Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and #' Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and #' McGraw-Hill, 2001. ISBN 0262032937. Pages 949-955 of section 33.3: Finding #' the convex hull. #' @keywords graphs #' @examples #' #' M <- cbind( runif(100), runif(100) ) #' convex_hull(M) #' @export convex_hull <- convex_hull igraph/R/test.R0000644000175100001440000000525713177712334013066 0ustar hornikusers# IGraph R package # Copyright (C) 2005-2013 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### #' Run package tests #' #' Runs all package tests. #' #' The \code{testthat} package is needed to run all tests. The location tests #' themselves can be extracted from the package via \code{system.file("tests", #' package="igraph")}. #' #' This function simply calls the \code{test_dir} function from the #' \code{testthat} package on the test directory. #' #' @aliases igraphtest #' @return Whatever is returned by \code{test_dir} from the \code{testthat} #' package. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export igraph_test <- function() { do.call(require, list("testthat")) tdir <- system.file("tests", package="igraph") do.call("test_dir", list(tdir)) } #' Query igraph's version string #' #' Queries igraph's original version string. See details below. #' #' The igraph version string is the same as the version of the R package for #' all realeased igraph versions. For development versions and nightly builds, #' they might differ however. #' #' The reason for this is, that R package version numbers are not flexible #' enough to cover in-between releases versions, e.g. alpha and beta versions, #' release candidates, etc. #' #' @aliases igraph.version #' @return A character scalar, the igraph version string. #' @author Gabor Csardi \email{csardi.gabor@@gmail.com} #' @keywords graphs #' @export #' @examples #' #' ## Compare to the package version #' packageDescription("igraph")$Version #' igraph_version() igraph_version <- function() { on.exit( .Call(C_R_igraph_finalizer) ) .Call(C_R_igraph_version) } checkpkg <- function(package_file, args=character()) { package_file <- as.character(package_file) args <- as.character(args) do.call(":::", list("tools", ".check_packages"))(c(package_file, args)) } igraph/MD50000644000175100001440000021600413567553110012063 0ustar hornikusersb3ab16f8b0bf774e8b93b26060ae5db3 *DESCRIPTION 229efae9effacda32f9f057513f0c875 *NAMESPACE 09228ba65a900fdabd76aa20c8b4a9d2 *R/adjacency.R ba96cdf262f284a91629bcc81958464a *R/assortativity.R 4e8a737d746fe286c63f20391b85f5d7 *R/attributes.R fefa1c0d053707ca1bceafe8f6be822a *R/auto.R d41d8cd98f00b204e9800998ecf8427e *R/auto.R.in 5664da08a1f8845c2482800ebdd4da41 *R/basic.R 5a57b9f50c12d6192bfce4cf68daf930 *R/bipartite.R 25e22e5363ea555120ed49f181ee8ae1 *R/centrality.R 249b7f6fb9165564b81c3bf5df932290 *R/centralization.R 4d30719473e0269bfed98ed719796f31 *R/cliques.R bbb60a4c74350d8ef25d2662aa49180c *R/cocitation.R 487ba2140d68e06c0f92cfc651533bdb *R/cohesive.blocks.R 233b6ae98cf322383f0d4b40476f7928 *R/community.R fddb54f1475069dfd9a3643d35d26563 *R/components.R 047be7bba9e76d408aaa49e2daf7f96d *R/console.R cdde3a92bcb68b227e9b13d52fbbf109 *R/conversion.R f60154d5c769713e6694ab0c8b287a43 *R/data_frame.R 0ec847f8d499985036fc2c3e28a4dfee *R/decomposition.R d20ec0854628e7d0173998343b9d9271 *R/degseq.R 4206d088dc2e5cad5568d5b0b19cb103 *R/demo.R 9fedff2192567dcaf3febbf3ccef7a56 *R/embedding.R 6908f573f975b61439cf453d9e388bc9 *R/epi.R 7b52a5f78251b7531e5b6ce2f82c77d7 *R/fit.R 8241496e720b3b60aa8cecdfdd7280cf *R/flow.R f0dbe8d0459be2e4c9f949938a916a53 *R/foreign.R e8c095f57a0f7ec495922d3a43d15aec *R/games.R e19b328c2621fe0db27bc9622a1003b1 *R/glet.R f088a71216577c92399af1b7244b4370 *R/hrg.R 15a62d62546d46acda84a5eeddb19f42 *R/igraph-package.R 77186b76f1f2d9bfa48e28556e5b1838 *R/incidence.R ca2b9fd8d97dcc7d95988c33170e4777 *R/indexing.R 94def4d6fa4c5dcde059b083f8a18fe2 *R/interface.R 5eb3da96bcac60a5ae9636fd003de592 *R/iterators.R 9b65f227ebf8c4a8cf42fa9861db62ab *R/layout.R a37fa01f6f25d76f29ee0301e76a07b1 *R/layout_drl.R 95366f1e91f837bd730f943ee8c005b8 *R/lazyeval.R 8f44d588c4f1a49d406b834f67214a0e *R/make.R 90f64fe163faa43dbb168d3f40166e34 *R/minimum.spanning.tree.R fc601ca07614dca0e233bdf88ceaf2cf *R/motifs.R fcf5d996e7130577144025a55ed94655 *R/nexus.R 231c83447ab19e88f3d8f27d5c53ddee *R/operators.R c55a3913b222e44136d8cffd0a6c889e *R/other.R a782d198b54b5384eb109acf7997f606 *R/package.R edf918ea6c34e98283541e54bb138268 *R/palette.R 55a365385f8989892cb1c0ef4d9c337b *R/par.R 4ed201432c7c922ea37b6cf822b9f75e *R/paths.R cbcc95c184d9cc8a32c98f0fd492e4bb *R/plot.R 76fd2a4de3dfbc84122003afeac34ee1 *R/plot.common.R 4c363225538967c067b8cf060c6b7622 *R/plot.shapes.R 013081ac5ad5942c8ddbca625b67b58b *R/pp.R 5c73d1bd8e5d4bdb47e7d98265e2b890 *R/print.R 72537ec66e0406ccaf61069f220f06fd *R/printr.R b4ef25e0fbb795e3ea6f6f4f28be7e37 *R/random_walk.R 42c4f7aa4e3f5d4656ac228e1e001fe5 *R/rewire.R 597c06b2317dffbc41b020c8d3f832c0 *R/scan.R 59ab90bee689894f07c627f312b4767d *R/scg.R 2a0fd5d6d4e07002c39c1ed497687666 *R/sgm.R ba463b11d0c2f3b7cf1781cdeb34d5a3 *R/similarity.R 296a4b11587d8311ab9ed05836b72f01 *R/simple.R db7f41f5186a1dd4561c2464b2acdc07 *R/sir.R a3032214cb7736e816efac0648691339 *R/socnet.R 1ba5d03fdff8d5e714320cc47f332d1d *R/sparsedf.R d7ca4f4f24d5f341a4307e2f7c9db0d1 *R/structural.properties.R 49277a7f60c0d5d93330d3145c3c00b1 *R/structure.info.R e85ebcf2d2bf8f3590517969b1a4cec3 *R/test.R bd62004d680fdd7e689411d441c2c6ea *R/tkplot.R c6ff94955e31c10166da5704574ee664 *R/topology.R 49d841011964ec28930e7e2b861cbf3f *R/triangles.R 4c372b082cbb95708a85f575fe3bb8d1 *R/utils.R 053db0cd8d886ca5929575dc179f05e0 *R/uuid.R dedeede120a8f6b67ac214934ec34b3d *R/versions.R 986ffd9c0f8b6ff1c1144a6710954914 *R/weakref.R 82be9ebc0900c63b2ffff118e8e81f9f *R/zzz-deprecate.R e7a874fe428f9d5ac2393e15625c4ff0 *configure 266f2d042cb2da57fa4f34394c399df8 *configure.ac d41d8cd98f00b204e9800998ecf8427e *configure.win f6d91efbe9a92d9da367b19ae2b77d48 *demo/00Index 594342a01208503fbaac63fa9b1f24fa *demo/centrality.R 66b983548b89ca5c7cf63df0e7a72fe3 *demo/cohesive.R 4ed3fb8087e8c142cdbc5932c44b363a *demo/community.R 54f8ab308700e80de829711f2eeab719 *demo/crashR.R faf3ffd01e590fd13b34efb775f173eb *demo/hrg.R 771ca356197ee2b54c40ceccb4c2419c *demo/smallworld.R 63f74b06a17d02a00dac03fb54a07b54 *inst/AUTHORS 5cc5f3e2c4239fe9a47bfefdbb923dd0 *inst/CITATION 61b5d73c53881e4256ee8b46a82d4984 *inst/NEWS.md 27e30ac7130f81f5207760f3ef59161c *inst/README.md 9318bc2aeb60f4f79eac2357da0d9b84 *inst/benchmarks/correlated.R 4f938e92ca259e3259a5223e87e51bb0 *inst/benchmarks/local.scan.R e089bba153ae6dd3f7bafb2f62dbded0 *inst/benchmarks/time_call.R 5ad213883678196238e964be02ae0585 *inst/benchmarks/time_dirSelect.R edff9359ac1cb8957676283032452e3c *inst/benchmarks/time_fr_layout.R ebf0471b513b73423273265c2fe2a663 *inst/benchmarks/time_kk_layout.R f864ca3d5dcd66af6f75b31fd00223a4 *inst/benchmarks/time_print.R eae286de8f64912cf4b2ac317bc5e67b *inst/benchmarks/time_sgm.R 56cacf3291bedc3596f2af9f2e664fa9 *inst/benchmarks/time_sir.R 9f15757aae0fc33c5e1c8fd7546173a1 *inst/html_library.license.terms 9a1b851f5373287728fa8fbe7b3f67f0 *inst/html_library.tcl 4fb9f93f54eeef966f8259609247a787 *inst/igraph.gif c07ee84ac019e590ef906200e5183ea2 *inst/igraph2.gif 87bc6231efc284995f9d609715ea4d2f *inst/my_html_library.tcl 2521dfd3cdd6457b8947f9bd78094b48 *inst/tkigraph_help/communities.html b836ba1ad253b94013d430cf0ba3e7c2 *inst/tkigraph_help/index.html 11db5e3c8a97b9b22418aecf954b961a *inst/tkigraph_help/style.css 4cbf1010c7a8edb8b8576853eb8898d6 *inst/tkigraph_help/tkigraph-main.gif 9c0e201566c373ee14ef3c900420aef6 *man/E.Rd 5a46421ac8d01c264d897ed773fa42ef *man/V.Rd 6af61ac445af6756b1bc6132dcf7296d *man/aaa-igraph-package.Rd eff3fdf3b4655784c068090eff4d837e *man/add_edges.Rd 3a85d0a9160a615aa42efad7a48eeb5a *man/add_layout_.Rd 76943ffa99111e11872e7903d02d9a77 *man/add_vertices.Rd 0649a020881a76ee1d03342ee1e9c786 *man/adjacent_vertices.Rd f5acc86dd4a83c6a7f92b4ee9165c9f9 *man/all_simple_paths.Rd 50c77638a121cb85ea019a53c747fef9 *man/alpha_centrality.Rd f82d6c099b5a286aefb23ce07acd3f70 *man/are_adjacent.Rd 3cb07edf070c59b11c55a639fd5c96c3 *man/arpack.Rd 5170bf452d4f03a35cd19e2dad51a0ad *man/articulation_points.Rd 58774e32c2bcb029885e92eade97f6f8 *man/as.directed.Rd 4edd0d5ebe349816bdb3ad552f3d4625 *man/as.igraph.Rd d80d7cd3a20deba5218f74fae9b1f343 *man/as_adj_list.Rd aaa079d91a92c832e3366a198544f503 *man/as_adjacency_matrix.Rd b2630685da60c720488fe4adedcbf6df *man/as_edgelist.Rd 8c82f161731c8e5017b40abb3f2e8d7e *man/as_graphnel.Rd 07c73a99ed8373f3d47bcb3428367bf9 *man/as_ids.Rd 794bc47f2113374b92a0e069ee56c6da *man/as_incidence_matrix.Rd a7e8dcb9ee9a687693602dc251c6fcdb *man/as_long_data_frame.Rd af80a2f10fb2325144873031228602f6 *man/as_membership.Rd 5bf70061229f957952ceefec43461c2a *man/assortativity.Rd 34806ff532c38a8998a4e87a03d166ed *man/authority_score.Rd 26cc0de7da666b382bdf8e881f5338e2 *man/automorphisms.Rd 3d9c8583a5cee8efcf5adfabd2349022 *man/betweenness.Rd d4142625f63e0880153e13c26e9760ff *man/bfs.Rd fd8f543453db1ea10a85aac0e809bc82 *man/biconnected_components.Rd 260b8e476f5318771591d0ece02c1fd0 *man/bipartite_mapping.Rd 90f47a4219f564d37a22764c564dd623 *man/bipartite_projection.Rd 264d20b2ab11ea0666e878a4ee1b6a4b *man/c.igraph.es.Rd 0ee13906edc07c445e769b04eb0f1274 *man/c.igraph.vs.Rd 7ae051da0688ce03f3bdc8347cc2f829 *man/canonical_permutation.Rd cb333bf76dc97bf825533c8e03dbbccc *man/categorical_pal.Rd e40cfffaadef8c7822e4d87beb0d7fcf *man/centr_betw.Rd 4e9841ae12c19c487e83742089f516c6 *man/centr_betw_tmax.Rd 7598ceb9588e7f3305b1868d52d88d24 *man/centr_clo.Rd e4db147b2c310418bb9127bce0ff56ee *man/centr_clo_tmax.Rd e276648bb05dbf5ef92dfe1f3d54d3d2 *man/centr_degree.Rd 873fa0624c1710a28a162f04f41eb981 *man/centr_degree_tmax.Rd 73c7affe57a252af200ec10dbe38068e *man/centr_eigen.Rd 03df68c1415f9a5e04f92a392c4796e1 *man/centr_eigen_tmax.Rd 36d5a2524786ed1a753ca329054756ce *man/centralize.Rd 93470f70a2e68c40c2274afd8ffb3743 *man/cliques.Rd c09b5d058784310562bc21f3faba701e *man/closeness.Rd 4dc8cd011b7f39f182be62f200807c44 *man/cluster_edge_betweenness.Rd 3e7224cbcaa7120dc32280d6c6456628 *man/cluster_fast_greedy.Rd b0d1f57cb67cd973ac0cc95a686066f5 *man/cluster_infomap.Rd 4cf5a805a1319bf9fb44dc3e9281ccaf *man/cluster_label_prop.Rd d150661fa8d5120e92b5333ad4a565e0 *man/cluster_leading_eigen.Rd 77fea04aaed7acfcce1a1ac0256cec26 *man/cluster_louvain.Rd 9590b539c0d58c3afabb2b1a850c0616 *man/cluster_optimal.Rd e9d8a1dcbe4789eab9d4156df97b9280 *man/cluster_spinglass.Rd c9c30a30c7e9c628d71ec88b11341ef3 *man/cluster_walktrap.Rd c61a802eaec3e2767db69e88f9a79312 *man/cocitation.Rd d7a342396f73bc6c0c98e48448c25ef9 *man/cohesive_blocks.Rd df9cb855531244d0350934865f81259e *man/communities.Rd 1ed4f374ab70bf7eb9ad1326975b466f *man/compare.Rd e4fef82addf74c0357b57490d414cd1e *man/complementer.Rd f6b2c539d55a0b8f96cb67ac4ab79e54 *man/component_wise.Rd 24c80f2458a066fe0affc073f9aadb85 *man/components.Rd 81b9eb46f1200483059dcb2fe5e29481 *man/compose.Rd f32fd8ad1f76a7044cf3b85b95a92657 *man/consensus_tree.Rd 94129e9f948154a19ccd4eeaf1a80f6d *man/console.Rd 603fd9022b00de72cec29a38789f7344 *man/constraint.Rd e8c1f5ba49be96b9e95d7852c3eb3661 *man/contract.Rd 7b578c13fb22e242e0d69b19bc9c6e19 *man/convex_hull.Rd dea3a87ace7dc4d3b69ad42e0e43c9cf *man/coreness.Rd 520b19a5e74fe8fafc817e867ad04ab7 *man/count_isomorphisms.Rd caaf0c4133436f158ff1fc2497448e79 *man/count_motifs.Rd d3e28f410442eea7b6f4f158e06d102b *man/count_subgraph_isomorphisms.Rd e2c2e6883f13023956f55ecb85931225 *man/count_triangles.Rd fc701221f2a774802982cd096df1ff9d *man/curve_multiple.Rd 454f7e2a59182a56871736f207106af2 *man/decompose.Rd aaa29a9db916ab3230098be1cc410376 *man/degree.Rd e8c2c978fbc971a6e9570b364f3c0e6b *man/delete_edge_attr.Rd b9dbecdb3bd4083688e10358fc7908c4 *man/delete_edges.Rd 881bd41ac7a989f82cf4218ccf6de8de *man/delete_graph_attr.Rd d9f1d8954f8046c142235524915cccc7 *man/delete_vertex_attr.Rd 6f0d0b4b5a3ed6d9064745e1f8fa9955 *man/delete_vertices.Rd ae9c1b79f9f9af972d7d1d73dbc9fd96 *man/dfs.Rd 4dbe6daea6b6c8a4a740edbc8632ec01 *man/diameter.Rd 77ecc13de99b70c7c4bc5b8bb2c24330 *man/difference.Rd 63b6c01e2734c79503f96b701b12f18b *man/difference.igraph.Rd 4e2f34e3a9db92663650a61d9ce1e53b *man/difference.igraph.es.Rd 76e606a447bd12c80e772d05a61bec3e *man/difference.igraph.vs.Rd 99d912bebd15ccfa2a511460eabcdcae *man/dim_select.Rd 2c36443787d119578640980b242bddf5 *man/disjoint_union.Rd a8cb44b7e87f244585264b72518a83d7 *man/distances.Rd a8a80595c84fd18825bf5564afdd1b99 *man/diverging_pal.Rd 2dc8fd335ddeda98f3a6b2009dd395a9 *man/diversity.Rd 1f6ea4d77c5b8264523f8c392bc792c7 *man/dominator_tree.Rd c85b670920070a8d18a0fff686053f45 *man/dyad_census.Rd 8176cd9816de40581f210cd367eb865b *man/each_edge.Rd f47af2f8cc1eb98b1990eb81234a1899 *man/eccentricity.Rd 16126c0680e60230aad410d507b74cec *man/edge.Rd 08bb8f0ff2d8767e672ea5435181c212 *man/edge_attr-set.Rd f75d8a6554cc2921aa5b1ae5edbb1483 *man/edge_attr.Rd 3a11c99f2ea4198907052fc70643a96f *man/edge_attr_names.Rd 7257668ed6406858b1642dff41e9fecb *man/edge_connectivity.Rd 3b1308f67eb6c4c996aec515d6df0022 *man/edge_density.Rd e7030611abad99d7272940229684bd67 *man/ego.Rd e934374ab33ad4eb743fe4ee958500cb *man/eigen_centrality.Rd 6992f1e3c46eb89cdb31e40cee9c1104 *man/embed_adjacency_matrix.Rd 058111480b8b446184c45d840e4ac1f1 *man/embed_laplacian_matrix.Rd 3b9062ec062e32eccb2f3280234f1859 *man/ends.Rd 4e27209153481d05089e7e126eb0382a *man/erdos.renyi.game.Rd 7a8a08bdfaf5c3d1670c0cb9c98f2057 *man/fit_hrg.Rd 259275bd9858c7bed934192e64cc8ef7 *man/fit_power_law.Rd 69fdbda079abb6c8faa0cca928cd1f63 *man/get.edge.ids.Rd 76d3765c8ee6bc86138f51e556e572b7 *man/girth.Rd ed47f34d3563982d9a3a73658ed33dc7 *man/gorder.Rd 542b983f99f4bed35b29d4c7a34c15b5 *man/graph_.Rd 151b2a2fd7331f79c57d52802dc108f1 *man/graph_attr-set.Rd c04b7425950ce690a4b4343d3be5ad18 *man/graph_attr.Rd e716e992abd9a372faa34a493b2764fd *man/graph_attr_names.Rd e68cca620253df2e5958cd5b8c81f32f *man/graph_from_adj_list.Rd b4d9756806c7adb969ea17232b5696c5 *man/graph_from_adjacency_matrix.Rd 7c916a5c37065106a3817c8e8916e91a *man/graph_from_atlas.Rd 5bf5d27ce5dd050eb77a126d164ddb01 *man/graph_from_data_frame.Rd 1d841bb96d5c46b61d24c698c0401eea *man/graph_from_edgelist.Rd 814bb8c8a67d14d9672c997e8ac0b4df *man/graph_from_graphdb.Rd 305d5098a24be7ef3b66d3de32830984 *man/graph_from_graphnel.Rd 89898323f1671911dd5e5d375ded9716 *man/graph_from_incidence_matrix.Rd 416bc302e079ee87898c6dc1a529fa8d *man/graph_from_isomorphism_class.Rd 27424027699f97428365a76280a3dfe9 *man/graph_from_lcf.Rd 2eff516beedfd4da9698b6cb1b82b527 *man/graph_from_literal.Rd 1383a2013dae1066755c8557d3ff4b82 *man/graph_id.Rd 16ae85d5eb499c462fb828cba0f82a57 *man/graph_version.Rd b9757329131b85209678ddebcfd2be69 *man/graphlet_basis.Rd 52bc656657d35726cae1d1058fea79f5 *man/groups.Rd af9b83150e8065d7bc885de116c3140c *man/gsize.Rd 73b224d258ac2ff14e6e592a2176d725 *man/head_of.Rd 52774b9fc73aab5df0139c260205fcdd *man/head_print.Rd 4c04c782cf5782d13655423986339c6b *man/hrg-methods.Rd cbe8b73d03cc818d9d8bd45c2e6d2e29 *man/hrg.Rd 7b1d70591c108024479df266b854310e *man/hrg_tree.Rd 60d728f32c0ff04f79f7a045e8b7599b *man/hub_score.Rd ade97c3019d3e37c4745ab18d5318731 *man/identical_graphs.Rd cd4fd7d6dbd8d3b8bca793f50deae042 *man/igraph-attribute-combination.Rd 214e821d5af0e40c31b1cf66a5ede34e *man/igraph-dollar.Rd 3457e71d4bd3c829cd2daa219c0758fc *man/igraph-es-attributes.Rd 0528b04fc89b2cf6156d99c24d2ae65f *man/igraph-es-indexing.Rd 02af30928504e72a3f40e841be4a56ac *man/igraph-es-indexing2.Rd bfb90018cf8adce0c87113fd736673b5 *man/igraph-minus.Rd 0a601bf740f9ccd520294dce6f114428 *man/igraph-vs-attributes.Rd 8582132077ce55c8039b6a2ec165f074 *man/igraph-vs-indexing.Rd f8de42d7e3d0392f9ebeb35bd8b3033a *man/igraph-vs-indexing2.Rd a3c2199327e088db50794ea9a1eb26fa *man/igraph_demo.Rd 368d63347f05c97225c8462f4134413a *man/igraph_options.Rd f34a914651b695dd86d6b04f1ef63e87 *man/igraph_test.Rd fff50a87d0cb4e8f9e12739d46536407 *man/igraph_version.Rd 4798cdd45405e0102d49a06df3a731aa *man/incident.Rd 072083beb076580767ca4cc3c600ac5e *man/incident_edges.Rd 63abd479f22420c2809ea4de8ff934f4 *man/indent_print.Rd 4d43970f72495ed573ed25801a9e2053 *man/intersection.Rd 7c019a00e9a940b39699a7ebaaeb2918 *man/intersection.igraph.Rd 2fa25f4c583dd67c35e417049fb62251 *man/intersection.igraph.es.Rd e1c81ed8a0533e29a021e4ab5820fcbc *man/intersection.igraph.vs.Rd 1cdfee019ad8edec2d5238161e781be1 *man/is_chordal.Rd 3009676a0b688dcf494b71ae8242473b *man/is_dag.Rd 42588822a95f9e17815100c76f7feb88 *man/is_degseq.Rd 8abe55e96c66513a1c0d14e7400f80c7 *man/is_directed.Rd e20bf2b38332d30d13d4c4e8753375d8 *man/is_graphical.Rd f5247cd679487788f4c77253ecdde99e *man/is_igraph.Rd fe7704430d6b015fdc02bd8b3719f87f *man/is_min_separator.Rd 9da1c2b9378f092b575328a02c26b28e *man/is_named.Rd 5c7d7e4cb435d08659a690eeb7a2f0b3 *man/is_printer_callback.Rd ad0cc429b7f4aad6d37e11eeb871a004 *man/is_separator.Rd d38af4a3937a9a457b10da6790f24e89 *man/is_weighted.Rd a31721d8c52d77976b9b053f80cb37f5 *man/isomorphic.Rd 8210f202a96b7186221f951352fdeeaa *man/isomorphism_class.Rd dbfc2e4abfa73f2fe497fffa7bb64d37 *man/isomorphisms.Rd 83585378bda03b7d1a14020c2f3f577f *man/ivs.Rd 7997d467ddeb39888877674c0d2ddaf2 *man/keeping_degseq.Rd 1f7ab911e02c5cbf789f61eef82e3626 *man/knn.Rd 925c0cf7fda4be8beac88a6177bd21e4 *man/laplacian_matrix.Rd 2fccef26f52b9406e1802569d67cf90a *man/layout.deprecated.Rd 7f5682fdcc175fa55473f08f670a61bf *man/layout.fruchterman.reingold.grid.Rd cd028ca4b9a1b37e97f775886fecc35d *man/layout.spring.Rd 2eaf9386ffca9813865380fa9bd4c3d6 *man/layout.svd.Rd 83409219839995709c32cc3f240ba33e *man/layout_.Rd 4206c4bbf63d0c33fdff1b71697f52d9 *man/layout_as_bipartite.Rd 51303c9c986bb5abe19ae12a1a724be3 *man/layout_as_star.Rd cfd5a7e0b4755650b06eb8c39740fe9a *man/layout_as_tree.Rd 38248dc34c119c117aa8bdce2b455720 *man/layout_in_circle.Rd 029ab9f1ecbe14e0137c0009448fe492 *man/layout_nicely.Rd 493f3eac7449e8a6a75aa66d7d005ead *man/layout_on_grid.Rd 3aa8f77b6aee0d2c4c8a098e01e08d2e *man/layout_on_sphere.Rd 898f75292a7aa0e67638f843e94101d3 *man/layout_randomly.Rd bb635a47d758613a3fd694284deddddc *man/layout_with_dh.Rd b2af598b0374ecb2db5084d82c74e35c *man/layout_with_drl.Rd ec31184431902e2f6a97d3e0783e33a8 *man/layout_with_fr.Rd e06ea19dad9d54daf7eb3a44895cb831 *man/layout_with_gem.Rd dbefa58f276ad6142eb6ddcd85d23d5b *man/layout_with_graphopt.Rd 2259cd9f44e9f5ee17ab7da8da791a91 *man/layout_with_kk.Rd b1d3ce1ea6d7fb552457cfb338712d12 *man/layout_with_lgl.Rd c24da4c97dae45f6d967315ce1af5090 *man/layout_with_mds.Rd 11ab3db7d9c07a640252b9f593538b7b *man/layout_with_sugiyama.Rd 6be414bfda189ea56eafcef8918f1232 *man/local_scan.Rd 34321539479c57648d5841fd73b73efd *man/make_.Rd 9a70ea8559a8432024f3431426c0e852 *man/make_bipartite_graph.Rd f4d051497a1caf3c64474f83968e8d9e *man/make_chordal_ring.Rd 044d9f59b34399c519bc8386b0c9e178 *man/make_clusters.Rd 6be060a9747c123833a1e076b8db13d9 *man/make_de_bruijn_graph.Rd 9e0a0df5202bafba6846ba6e317534d5 *man/make_empty_graph.Rd eff6b831b36d80bdf09c0338c0b732a7 *man/make_full_bipartite_graph.Rd c9c961af9acf218fc8f41709949fe2ed *man/make_full_citation_graph.Rd e2b440184a9d0204ba940b17dc52b47c *man/make_full_graph.Rd 98d6129f98c61429e3fa92cfe1c6337d *man/make_graph.Rd 71dfa4171f2305fbe0e4f8198386abfe *man/make_kautz_graph.Rd 9f778ec9af637ae1d10367b3e9d9d5ed *man/make_lattice.Rd 3f13f1863d99790749e3061af4ccd990 *man/make_line_graph.Rd f66e24f8914cc58af1015018967803da *man/make_ring.Rd fef14f69d4b7f89dec4c72ca81213774 *man/make_star.Rd 77a33fe32fe41ff8c5339ad43b48f95f *man/make_tree.Rd 8d2eb4e0567086188de0b0e86fbda036 *man/match_vertices.Rd 5856fa0ccb0d602f79a2a8aaae15d250 *man/matching.Rd ac8256b00fa1ff2bc3aa93808e31f19a *man/max_cardinality.Rd a97c79a941a42c44436bdd5a15974131 *man/max_flow.Rd a5513457eef6f98a6c789ad5429a945a *man/merge_coords.Rd e4d09d1506d7ab8c255664aead49c877 *man/min_cut.Rd 7e3614e2abbe9234505a0155a313a3eb *man/min_separators.Rd f8b1f6530fdb70322c655bb4408a9048 *man/min_st_separators.Rd 93e72820f27e7c225d8ea8e9a664cd5c *man/modularity.igraph.Rd 8ebf2aa7d296b01cde9b1564b8a0ae32 *man/motifs.Rd 0693778f29920d0560662cac7867b847 *man/mst.Rd e237f25d76360235b5d837429da65794 *man/neighbors.Rd 253aa5729641653959976acaf3609373 *man/nexus.Rd d4128ab8395b579b770f91be48be565b *man/norm_coords.Rd 8de66d7c8103f186ed014198866b2785 *man/normalize.Rd 6cf3890d6ebd960666226c24ec22e124 *man/page_rank.Rd d1b2a82b56f253a7d6708ed478c554cb *man/path.Rd 19a6b9ab9dcf6b17c9326c52ab0b0cf3 *man/permute.Rd af6d2e9f5a6c77b0c3c5385fa1d12f39 *man/pipe.Rd c74527bbb90ac46e47197a4a587435eb *man/plot.common.Rd bf1a0cdf2c1aa100e8c00500d62947ed *man/plot.igraph.Rd 4abd166aa81daddc7367daa00e3d265e *man/plot.sir.Rd 00f5deafcb84029e549d20cc5e859992 *man/plot_dendrogram.communities.Rd d471d57de70a18d2996fe19e6de21f99 *man/plot_dendrogram.igraphHRG.Rd 93daa2c70f473e7bb37fbaaa441d3f14 *man/plus-.igraph.Rd 2f0e54cda6d0395133b1540e3380905e *man/power_centrality.Rd f31e4a9d66761c7ee39138f4d1132666 *man/predict_edges.Rd f11d8ee030b7a397ff6c84ffc9531f93 *man/print.igraph.Rd e69f76ac691ab8888250ad7ac87c936e *man/print.igraph.es.Rd 51eb35a40d40b389f22a1e4f831b4b59 *man/print.igraph.vs.Rd d620f4ba267d4934901aee0da31cb438 *man/print.igraphHRG.Rd eb45a57f58e1186d6454e93775fbfa02 *man/print.igraphHRGConsensus.Rd 11e8e3d5af20daea1c6be2e9dd3c3daa *man/printer_callback.Rd 0ad6fcd5bdf0453546189c4ae11cca14 *man/printr.Rd 1f5f71f8e28fbd907870b1f8c499db43 *man/r_pal.Rd 9823c518e709d06396e241ff48b83f1e *man/radius.Rd 6532cf86666d2638476026bd84c9b316 *man/random_walk.Rd 7137208886b4e57f237867feb815e6d7 *man/read_graph.Rd 5d439c38e0c50b22f5330526f20c9f80 *man/reciprocity.Rd 876551c8cd37422cb94f64ead21a6ff8 *man/rep.igraph.Rd 9f5f54a7b800494b7aca97f6409a9c06 *man/rev.igraph.es.Rd c08097aa15ad02e9be71a472c0677b25 *man/rev.igraph.vs.Rd 53cc24e3ebd92925bfe573eddbf9a597 *man/rewire.Rd 72c8b2d0260fbd80f7b1a1968fdba1ee *man/rglplot.Rd ce204a0fec214014be7be38aa7fe9624 *man/running_mean.Rd b4c849b235316f063fbb6b683c5c4f23 *man/sample_.Rd feaa511024c9467696e454aeb6b06048 *man/sample_bipartite.Rd 24c84c2ca80a349c74a1255cbe5804ab *man/sample_correlated_gnp.Rd 519414ecb86b9297957ab95c7488b36d *man/sample_correlated_gnp_pair.Rd 52adc73bc7db6096f6442ec4f32a3302 *man/sample_degseq.Rd 32b927323c6c6d2620001baae9a3b88f *man/sample_dirichlet.Rd 938234e8469320764b72d6da09ab15a4 *man/sample_dot_product.Rd 2b448354bde94131dcb66eb1997a4070 *man/sample_fitness.Rd 2a127289a701b95374bb4a467649be6b *man/sample_fitness_pl.Rd 5a4be2a3697806d8a3101908410b8a37 *man/sample_forestfire.Rd 9fc39369add1a088e6187148ae4e160a *man/sample_gnm.Rd 5af23dda93426c846642bab3f1b20641 *man/sample_gnp.Rd 1f697a4761b0f0b061ba24cae7ae9fb3 *man/sample_grg.Rd 282ca01c580b32d2b7e5391d47810683 *man/sample_growing.Rd 49997c3408f8fe9bbe40036d3cc534b1 *man/sample_hierarchical_sbm.Rd fd08f774fb8ef70e824ac4f1c0c8d5c7 *man/sample_hrg.Rd d83dc72a06f90ebc68618fdf7a3babd5 *man/sample_islands.Rd 5de1b411f9d9ea0799e2d17effee9266 *man/sample_k_regular.Rd 24d6cc215e0fa88875376460375d734b *man/sample_last_cit.Rd c20badfe6e4c796966cc874f13514807 *man/sample_motifs.Rd b7eda50cf5a1ad69f5e66016ee16c1ce *man/sample_pa.Rd 327735b0e884f2d40403f7c155d19a42 *man/sample_pa_age.Rd 112bb8c4aabe7679d92ed8156bab02e8 *man/sample_pref.Rd 6761a3da1bec5ba2fa7a68afe650a3e4 *man/sample_sbm.Rd dcccb371f2b36f9b5818edf61f18639a *man/sample_seq.Rd baf738b3c956878848725084f4fbc704 *man/sample_smallworld.Rd 586398b5b424a811b2ab1d79ac7ef534 *man/sample_sphere_surface.Rd 9a98c936db8567ca497a4ade2679704f *man/sample_sphere_volume.Rd 528ea932d9ddf9c72ec0268469660448 *man/sample_traits_callaway.Rd f1687cbe0b75385d290b60034b3e3673 *man/scan_stat.Rd 7239118709a8d586a1fdea139a7fa642 *man/scg-method.Rd 6dad55608c591a2d770b668897780472 *man/scg.Rd c5354904efa120f0d76b79b7078d65aa *man/scg_eps.Rd 05f7f4b3b7b2667210cdacca4eab9ba0 *man/scg_group.Rd 5124e031f57b91baf0d0f986cffe0378 *man/scg_semi_proj.Rd 1427a5a2dee76dc87c541c4a4fccd2e0 *man/sequential_pal.Rd 1716f2e6e1f276408745ceca5f02efe1 *man/set_edge_attr.Rd 7377fb2a847117839844bd98cd5cad5f *man/set_graph_attr.Rd 1fb6e23051a7810a7c26cccd1c2cf340 *man/set_vertex_attr.Rd b9d826f62e1017adb28de815321b831b *man/shapes.Rd 92c2c7de3f2918bb0487d41bcaa2dba3 *man/similarity.Rd fce6c34a7c02efd782132c26d46af6f7 *man/simplified.Rd 8b11b1301076d180a7041ef8fcbca536 *man/simplify.Rd cceb74d71c8e7d3430fe28cbc183fb63 *man/sir.Rd ca6218301e2986a1ce3659bed73d6e1c *man/spectrum.Rd 118d3ecbf649398333da1383be11bb99 *man/split_join_distance.Rd 9b6fcfdbedbd1b584c3b4916c8061dde *man/srand.Rd b2564a561b033096f5eeeefd9f0b1be9 *man/st_cuts.Rd bab7581d7c4fbdba352d6d5a68157493 *man/st_min_cuts.Rd 52f29a4fa679e8a3afd154f235869ebe *man/stochastic_matrix.Rd 181c164daa619d19356514fd927c8ea3 *man/strength.Rd 2eb6774596061ec0a34150b12041b01f *man/sub-.igraph.Rd 461effdabd271176be9b0bbb90eb3c1e *man/sub-sub-.igraph.Rd 787d1730c34490e36bddecae6b25567b *man/subcomponent.Rd 4e28b149fddebf51a88caa2a852067cc *man/subgraph.Rd 216aff0af0d5d87970679b5857e20013 *man/subgraph_centrality.Rd baa324999a9245319b57e5c1f9340589 *man/subgraph_isomorphic.Rd 63dde91a9ac06e2e9ae0804250b5e217 *man/subgraph_isomorphisms.Rd 8139d593123188ac4a5114a0efe3ea5a *man/tail_of.Rd bcb1def4cda65610d735cba196500aad *man/tkigraph.Rd 485a2173a59ca2f61dbc7778935e6537 *man/tkplot.Rd d3833f12bb816481ffeba680357e9e5c *man/topo_sort.Rd a8e392328d8aeb8f5077234b0b36ca87 *man/transitivity.Rd b30be370a2e7f1558836fbe0f75462ff *man/triad_census.Rd 7f2ffe354eaf63c4bc4993abbdff6059 *man/unfold_tree.Rd 83dbdd7ba97f4611b276aa89a0e364e4 *man/union.Rd 32dc5293773b97a03b217bb4d080c72a *man/union.igraph.Rd 7a3f5bab88ce6787d68caff5712f0ede *man/union.igraph.es.Rd b884aedfd0498f9b6533d11bf2409ed1 *man/union.igraph.vs.Rd bf752920d01684539d71a3500696c281 *man/unique.igraph.es.Rd bf5f379902c7b079096e394d629b812b *man/unique.igraph.vs.Rd a6ecfd839feb64f11543f306f88dbba9 *man/upgrade_graph.Rd b4bc03b1b09b0cc5d6778210131c9026 *man/vertex.Rd 618a6de0b4fb2cafd10fb8c33a51733c *man/vertex.shape.pie.Rd a77cbc1542c5165d80ed9321bcbeb1fe *man/vertex_attr-set.Rd af8972cbcb3a373741cd55cc3b57c901 *man/vertex_attr.Rd 271d74de866f9ca6c4577599ee7625fa *man/vertex_attr_names.Rd 5ba56fd769f66175cce39bb56efb20a0 *man/vertex_connectivity.Rd 919e92b231b9f54767bdd41d57945d0b *man/which_multiple.Rd 9e4b0689e47f6b673a0eba4e1031aaf2 *man/which_mutual.Rd fc59e5fcd55f19648e2954da970aa3d2 *man/with_edge_.Rd 16ce6ed9135fe12e2156e32a8f3bc40f *man/with_graph_.Rd 50c9672898bf640a9fb0163748aa1540 *man/with_igraph_opt.Rd 616e7f8583885e60337cfbe0ff36971e *man/with_vertex_.Rd 00939e07942973ce66a6ab220356b4d9 *man/without_attr.Rd 50f10388c84c90e1030ca141669763da *man/without_loops.Rd 31b5ad40e34cb98c46bf89802c0dba7b *man/without_multiples.Rd 41e6b433c761d467b87665721cb3f89e *man/write_graph.Rd 752c6c39d6c94efc9d6ab8059c1b7335 *src/AMD/Include/amd.h c1ec3247520fb501520b4fe077d20856 *src/AMD/Include/amd_internal.h b2470d1e2bced70dbd2b7e2f85405a50 *src/AMD/Makefile 7d60c8defc517d361513bac03d04f13b *src/AMD/README.txt 83d3a6479a3b589c4b53dc7a220f0cf4 *src/AMD/Source/amd.f 41ec90eacd97a62c7393f9a66f714662 *src/AMD/Source/amd_1.c fc12596df9e5a12177d1c6e5dba8fce5 *src/AMD/Source/amd_2.c 23003d2ff7e400dc8738a838951a80cb *src/AMD/Source/amd_aat.c 212a9b583543cc25aceb7c7be7d88b04 *src/AMD/Source/amd_control.c c0a3524d4f5ddcb63065eeabe8ae57f8 *src/AMD/Source/amd_defaults.c 896cccbf9ea7f21142964fe1868da79d *src/AMD/Source/amd_dump.c 536469fbc9cd69d9ea1ee4a65c183a47 *src/AMD/Source/amd_global.c 9abf67b12455bb1989b0e9edaa0bec03 *src/AMD/Source/amd_info.c e0391fcc241630fa3a5b9b2c5ee3f0ea *src/AMD/Source/amd_order.c 5f8f83de491e328aefbff08a09c3b467 *src/AMD/Source/amd_post_tree.c d696467688131d58e3acf9e5a627360e *src/AMD/Source/amd_postorder.c 5d46a2442b5d099f6ba9fa6b427d7a1f *src/AMD/Source/amd_preprocess.c 56f64a3203f5752b5a012b806f101d8c *src/AMD/Source/amd_valid.c 0da45b5971ee18817fde1702fe1cdf02 *src/AMD/Source/amdbar.f 57b4f2e5de8a0744eeefbdb59053cee7 *src/CHOLMOD.diff d2d49c52f19cae17de0efe9bbd0e50b0 *src/CHOLMOD/Check/License.txt 0689532ab6ed7c3864c9fafbee1aa1b6 *src/CHOLMOD/Check/cholmod_check.c eff565a1144bd2dba2d0a9757e50b481 *src/CHOLMOD/Check/cholmod_read.c 84444c62831c05f57c0a41336c7a1f3b *src/CHOLMOD/Check/cholmod_write.c a6f89e2100d9b6cdffcea4f398e37343 *src/CHOLMOD/Check/lesser.txt 887d3c7dc221e09fa581c96ce66e76f2 *src/CHOLMOD/Cholesky/License.txt 8a939bb8ed17557aced224bb47854d8f *src/CHOLMOD/Cholesky/cholmod_amd.c 7213ecb3b13826762028047c2341d9e6 *src/CHOLMOD/Cholesky/cholmod_analyze.c 767989bd106e5d9b8da93137c9985dbf *src/CHOLMOD/Cholesky/cholmod_colamd.c 1fc207b3547818bb016492f2d9714d4b *src/CHOLMOD/Cholesky/cholmod_etree.c ed20e10d4965835e49980924b568536c *src/CHOLMOD/Cholesky/cholmod_factorize.c 7f4ddcc6f7a0b9de350c91ede8b6992c *src/CHOLMOD/Cholesky/cholmod_postorder.c 4873c960895bf2eec956006e2014061b *src/CHOLMOD/Cholesky/cholmod_rcond.c be208074ff7a33899ff08a5ab9102fd9 *src/CHOLMOD/Cholesky/cholmod_resymbol.c 914dc4160a428eae28de6c5f085ff129 *src/CHOLMOD/Cholesky/cholmod_rowcolcounts.c 23f6f11fd436f347922790580e2de2fc *src/CHOLMOD/Cholesky/cholmod_rowfac.c 913f2a4136ae76d3874f4ed82488f486 *src/CHOLMOD/Cholesky/cholmod_solve.c 6cfb3b948b5ff28de6f8f7d4d8fa4859 *src/CHOLMOD/Cholesky/cholmod_spsolve.c a6f89e2100d9b6cdffcea4f398e37343 *src/CHOLMOD/Cholesky/lesser.txt 2d3b7ec83d164d8189d29581badd2ab2 *src/CHOLMOD/Cholesky/t_cholmod_lsolve.c caea1d7895120894a93778e44558bf80 *src/CHOLMOD/Cholesky/t_cholmod_ltsolve.c df437e6236532f410f7dec95c530f689 *src/CHOLMOD/Cholesky/t_cholmod_rowfac.c 5bb20e7d6a626be362a29171bd1eea6d *src/CHOLMOD/Cholesky/t_cholmod_solve.c 0b650d81b9287230f7335cb5d6404b97 *src/CHOLMOD/Core/License.txt 8e9fcd70bd9c5a7809519e89df32536d *src/CHOLMOD/Core/cholmod_aat.c d38fc004c4240ce11eccf6214b9fb76e *src/CHOLMOD/Core/cholmod_add.c 212b6834b4f705afd74c1826836074ca *src/CHOLMOD/Core/cholmod_band.c 3363557ed9201c7fdb11e2a0ee50b938 *src/CHOLMOD/Core/cholmod_change_factor.c bd97debc58e4e02b8a02f117aa291ca1 *src/CHOLMOD/Core/cholmod_common.c 60d8d7bb40db79b8e41a41dd879fe01d *src/CHOLMOD/Core/cholmod_complex.c 741aa40db56db6df1c4157aa8b35f299 *src/CHOLMOD/Core/cholmod_copy.c 4ab120fc9bf2143578f57e91f9176115 *src/CHOLMOD/Core/cholmod_dense.c a0a55400242cbad3c11df002a8f82ba9 *src/CHOLMOD/Core/cholmod_error.c 491edb629e50ec8b63e78be48e79fee3 *src/CHOLMOD/Core/cholmod_factor.c d43e39ea2e8764bee2120ca9720c864e *src/CHOLMOD/Core/cholmod_memory.c 353c79883b82016484f8791916d40392 *src/CHOLMOD/Core/cholmod_sparse.c 4d56f96d959dbb044aad2b1e2543a489 *src/CHOLMOD/Core/cholmod_transpose.c 749075b69c8f254b01f4c1e2ac700b9a *src/CHOLMOD/Core/cholmod_triplet.c d3ab4a4b9ce5287a13a696c837e8178b *src/CHOLMOD/Core/cholmod_version.c a6f89e2100d9b6cdffcea4f398e37343 *src/CHOLMOD/Core/lesser.txt 5935895eb635942363de326b69f1f135 *src/CHOLMOD/Core/t_cholmod_change_factor.c 113394eba44b660e8b1f250794d9e315 *src/CHOLMOD/Core/t_cholmod_dense.c 5eba949e29cf3716912d54cbcaa3d691 *src/CHOLMOD/Core/t_cholmod_transpose.c c28402b3ada915779c2e3f6ea105ade0 *src/CHOLMOD/Core/t_cholmod_triplet.c 43dea0a98ff00c4d001efdcf9e1107fe *src/CHOLMOD/Include/License.txt aebdd50c54b3d11988fa4be5fb71d05f *src/CHOLMOD/Include/README.txt 403be4e598bd11adb647b463f7eb4192 *src/CHOLMOD/Include/cholmod.h dc46c6e059283e2f11cb83825732e367 *src/CHOLMOD/Include/cholmod_blas.h 8c1e3f82c00d6a67dd5d9d3139bea5a5 *src/CHOLMOD/Include/cholmod_camd.h bf7a358cf5641e22d1ae78fc9b350c47 *src/CHOLMOD/Include/cholmod_check.h 67ecb03414269c5dda2e161a330fe1f0 *src/CHOLMOD/Include/cholmod_cholesky.h 3adbb76236b883c09b4065c6f80d0e47 *src/CHOLMOD/Include/cholmod_complexity.h 2bc29a401875fbec85ba108089b90333 *src/CHOLMOD/Include/cholmod_config.h e9946fff88271c4aa2125c88e6316fbf *src/CHOLMOD/Include/cholmod_core.h 22e2cffd0d0420e8e2fe3c428759ce1a *src/CHOLMOD/Include/cholmod_internal.h 0fbe5016dc058131ec1b9161271c287d *src/CHOLMOD/Include/cholmod_io64.h ea5a291dcfe7892727e272bb2ac6d752 *src/CHOLMOD/Include/cholmod_matrixops.h e62d8c9cd22547845a55d05b01fd0c50 *src/CHOLMOD/Include/cholmod_modify.h c834620d8dec432569c68147d3d3e886 *src/CHOLMOD/Include/cholmod_partition.h 690f52f536eca0f17bf339abf01d07ef *src/CHOLMOD/Include/cholmod_supernodal.h 0f53c41fc3e65fc75bd8489e34c552d0 *src/CHOLMOD/Include/cholmod_template.h 48a212ecc047cccc04671355413943e2 *src/CHOLMOD/Makefile e60f67b276c37ca2fc0796a45b61c470 *src/CHOLMOD/MatrixOps/License.txt 49cd872b6e8996dcd66d297ba60389ae *src/CHOLMOD/MatrixOps/cholmod_drop.c 061a1e2dfd78e9ae7ba3c5586faa9acb *src/CHOLMOD/MatrixOps/cholmod_horzcat.c df0d737af990b2d73cd268407ba3d6cb *src/CHOLMOD/MatrixOps/cholmod_norm.c a7e865911dc280f1a508c8a7f1ff7975 *src/CHOLMOD/MatrixOps/cholmod_scale.c 469e5a07b5afdbc789ed3229198030df *src/CHOLMOD/MatrixOps/cholmod_sdmult.c a2fc03dbf62f15c8ed356c20c1355b54 *src/CHOLMOD/MatrixOps/cholmod_ssmult.c 7ffeb180ba7ebb9dd887ae2fb4c1876b *src/CHOLMOD/MatrixOps/cholmod_submatrix.c 2136d5f0931b18d308e9aa9fa44296ca *src/CHOLMOD/MatrixOps/cholmod_symmetry.c 3973c30221dd6c3fccc0ff15507ee260 *src/CHOLMOD/MatrixOps/cholmod_vertcat.c eb723b61539feef013de476e68b5c50a *src/CHOLMOD/MatrixOps/gpl.txt 884c14d213c4e66bae0d0afbec2e89aa *src/CHOLMOD/MatrixOps/t_cholmod_sdmult.c e38b4b22e31f8f215bbf4580cf50619c *src/CHOLMOD/Modify/License.txt 4797dfd399ed782013687044ef323f7e *src/CHOLMOD/Modify/cholmod_rowadd.c 11b6fba3ee7f4d4e63dc7dedd394dcf4 *src/CHOLMOD/Modify/cholmod_rowdel.c 7cf6727bf9f9f03cd07e4e93d533b7f8 *src/CHOLMOD/Modify/cholmod_updown.c eb723b61539feef013de476e68b5c50a *src/CHOLMOD/Modify/gpl.txt 728fec932755d9a0aea090b48d0992d4 *src/CHOLMOD/Modify/t_cholmod_updown.c a6f9b195edaa19e04836ca1d7ac2f834 *src/CHOLMOD/Modify/t_cholmod_updown_numkr.c b0cf7a9044494b5ea9481a1728c710e6 *src/CHOLMOD/Partition/License.txt 329fc0f714341b9dbe184b839892d97f *src/CHOLMOD/Partition/cholmod_camd.c 59e37876b64fb63a152cab1d57bec972 *src/CHOLMOD/Partition/cholmod_ccolamd.c 577a877ebb40c87dadadcd953a8d9bdc *src/CHOLMOD/Partition/cholmod_csymamd.c 6b7929df43c72c0a776aa4fe94f741e2 *src/CHOLMOD/Partition/cholmod_metis.c 6d854f59fdaeb40a885b9bb6e93c5263 *src/CHOLMOD/Partition/cholmod_nesdis.c a6f89e2100d9b6cdffcea4f398e37343 *src/CHOLMOD/Partition/lesser.txt e4f8cd28fc8be8ab14106630610b9c5f *src/CHOLMOD/README.txt 08629b176847ad848a0327e6fde2210a *src/CHOLMOD/Supernodal/License.txt adcb277096f9457b71dd51acfc652b2a *src/CHOLMOD/Supernodal/cholmod_super_numeric.c 5023292b43184229686f4026c5251a80 *src/CHOLMOD/Supernodal/cholmod_super_solve.c 4953c632dbe81cf89d68135e4b340840 *src/CHOLMOD/Supernodal/cholmod_super_symbolic.c eb723b61539feef013de476e68b5c50a *src/CHOLMOD/Supernodal/gpl.txt 1ad404233a51f38540a959c36d880bda *src/CHOLMOD/Supernodal/t_cholmod_gpu.c 9a9583dbc7d17143de8c7245d05b845d *src/CHOLMOD/Supernodal/t_cholmod_super_numeric.c c520e30aafdf20b571fd57ac921e8211 *src/CHOLMOD/Supernodal/t_cholmod_super_solve.c e14e53d0b36e1d0647348a326e8b3b54 *src/COLAMD/Include/colamd.h 9c9253b748adfe1c0afbfbac0f01f955 *src/COLAMD/Makefile 0a80fb0db9cefb02e290ffd2f3431e6c *src/COLAMD/README.txt ed584482056a57c97c84f0f2701f76a6 *src/COLAMD/Source/colamd.c d9b27cdbf6cd3a08a921754ba6acbfc0 *src/COLAMD/Source/colamd_global.c c784fda1171706a403d08b06eb5c243e *src/DensityGrid.cpp 11b90b027549d524c4e8af3cbbfcc307 *src/DensityGrid.h 5ed39a98531aa791d2815b4c5e78d255 *src/DensityGrid_3d.cpp 5cfb53cff37ca7d43a52db4f8e44ba94 *src/DensityGrid_3d.h 9861ee6d9df86db6b973b8d8a72d4856 *src/Makevars.in 3e5c857042b7a0f128583c1075674c84 *src/Makevars.win 47ce39714f6f9d6ec3bd7c91624d87f4 *src/NetDataTypes.cpp 69166cb2f393e3ab50bebc72b16d3f7e *src/NetDataTypes.h 19c564585ab9700eb4356ee8eeb32403 *src/NetRoutines.cpp 6d28d398db2ae73d18c6c0448b55b8ba *src/NetRoutines.h fcce9737f5d328cdc516dd48e2075962 *src/SuiteSparse_config/Makefile 29429afaf74eaac98cb1957ddd4e8a38 *src/SuiteSparse_config/README.txt e9b2be5ad0056f588187cf504cf60764 *src/SuiteSparse_config/SuiteSparse_config.c 5be5db8ccb99f88f234639b97d8227c5 *src/SuiteSparse_config/SuiteSparse_config.h 917bb33fe32383364ed1174ebf623868 *src/SuiteSparse_config/SuiteSparse_config.mk 0ea19089dfd660f6a712ec073f2a24dd *src/SuiteSparse_config/SuiteSparse_config_GPU.mk 293d047331651328bfd9a3899c45e915 *src/SuiteSparse_config/SuiteSparse_config_Mac.mk 7cbf14375f63b39c20ac81b319af4279 *src/adjlist.c cd9fc819a7108d5bd6e3df27bc574f8f *src/arpack.c 84d831cf06a12ccddc98d577cf34638f *src/array.c 28757abe7ee47a2a3752132e6521dbe7 *src/array.pmt 267926cfbc6903038bb8c7569fe853ed *src/atlas-edges.h f94137db5d049089a48e8542b40679c8 *src/atlas.c a7bf705fa703ed691200ff83438d6e4f *src/attributes.c 7f8eedd101f3f975de419df961bc789d *src/basic_query.c 8cdb18f2170bd6eb311cb7ac9b12944f *src/bfgs.c e0fb18ecf621c13a45bfd435b1638fce *src/bigint.c 976d10cf54420e8a8f2fc9f6e142d8fa *src/bigint.h ba0b88f5f1576546416246735befd49e *src/bignum.c 4605cbc38e02812c0cec5b31d33f6f21 *src/bignum.h 946d1f6a6f9bc0da1c2f57fd9a9b2800 *src/bipartite.c 3b088ee6a512aaf29884856942c7e7f8 *src/blas.c edcf3afe464ddbeb584a664159dd8e64 *src/bliss.cc 03691a516b0c665c6dc6f9de4bf4a50e *src/bliss/bignum.hh d68ac2b15e73f41afa201255b00180cc *src/bliss/bliss_heap.cc a908d17c67a15f1630dca13d3251548a *src/bliss/defs.cc 909a84d005b4e83406e715606b6fb737 *src/bliss/defs.hh f1905552a7f3b28221a1481e0b300f5e *src/bliss/graph.cc c11809c42634a8bf957f016ceb2078ac *src/bliss/graph.hh 1f71a985781852d2472d3a5cfb17fd53 *src/bliss/heap.hh 7e3eefe8a41743d132c7e1faf9d7d491 *src/bliss/igraph-changes.md cb75c3b12e2091449199f2620618b9d3 *src/bliss/kqueue.hh 95cbe690c079c438da27195a44894528 *src/bliss/kstack.hh 56935dcfed01d24b6c843cc4b4f746d6 *src/bliss/orbit.cc 50697634bcf08172969b6cf844c675da *src/bliss/orbit.hh 2dd0b46018cafcc2c38e90c9d03c06dc *src/bliss/partition.cc 093219f44162aee9547d01a77e0cee0d *src/bliss/partition.hh 1149a90b4858ef576be632eca8e94c0e *src/bliss/uintseqhash.cc 270d32bee429d455348c9722111b2284 *src/bliss/uintseqhash.hh 1dfd7ce22d1ad9ac0a334cd88340c352 *src/bliss/utils.cc 585195404db8ae1959a36fc182500f4c *src/bliss/utils.hh b6fd9917844e2e249f85b28b4738fe06 *src/cattributes.c e4f6a56efb625de906875d7fce41047a *src/centrality.c c7b8351063a81705746396607cc7c350 *src/cliquer/README b42fa37ab354d950216d94923f82ec74 *src/cliquer/cliquer.c 6048cb4559ad045e66933c7be080cf71 *src/cliquer/cliquer.h ef4bff214b7262783a2bf3a1924760f8 *src/cliquer/cliquer_graph.c 113c0673e6102fa0103b1f4e01b1b6d0 *src/cliquer/cliquerconf.h 5944482363f217cf4ec2e25bd0392179 *src/cliquer/graph.h f1ad39d0a3c6331ef95d7d2cb470ad28 *src/cliquer/misc.h eaeba91188cc59c857527b61acc8adce *src/cliquer/reorder.c 164d316a2ead051b7054673bad48277d *src/cliquer/reorder.h f74032c3a8ce9b4672233a7819ead3ae *src/cliquer/set.h 8d31d311c9b0194b7c8a2b87a991f776 *src/cliques.c e29b420a3b78dee545166a0c8a168f1f *src/clustertool.cpp 6ad201a1dcc21ac1abc526ff8fc5ec37 *src/cocitation.c 769ebaa580beb5101d20afde32bf3d84 *src/cohesive_blocks.c 572bc10c86fd8b71489fbc30cc95d70f *src/coloring.c 295ec5dc71ec18d35cf859f93a41903e *src/community.c c878447bf8cd5bd7d6ad60299325589f *src/complex.c 9828657420ac846bfe520574e68ef2c9 *src/components.c da22a174ed5a1435a55a2ea02737d424 *src/config.h.in 378725bae7943f46f2251647fafb7a49 *src/conversion.c 6f20b66f4a09e408f75df47f33b5f04d *src/cores.c 71e3b8f8d5465f43ca1d555d45ea13d7 *src/cs/UFconfig.h aca82a2cdbbcee0810a60c19c2304b0f *src/cs/cs.h 0de41bfeeb074d64f4e66e522c0ff77d *src/cs/cs_add.c 18a7e97b6d7ed3570c9f597ef025e1f1 *src/cs/cs_amd.c 1d71a8f26f6985adde5b866d3ca886cf *src/cs/cs_chol.c 34b2dc25f7038adaeb9fb251dbdc4003 *src/cs/cs_cholsol.c 6a514645c9c04b6434f0467b9294c060 *src/cs/cs_compress.c 5d1d491b83bddb4de7dfe784d979267a *src/cs/cs_counts.c ec39cce522361be6e4a3758ef018387e *src/cs/cs_cumsum.c 24b004cfcbd8cc8fb359db0f6234208a *src/cs/cs_dfs.c c4f02f5755f68aaa170dbc448a6e0d88 *src/cs/cs_dmperm.c 50f7fc58048430e8be2208013a2ca117 *src/cs/cs_droptol.c 569c98d9f0daefdcca1557a9887e12a9 *src/cs/cs_dropzeros.c d7406542b69bed807fe1a3649917cb5f *src/cs/cs_dupl.c 1d83b91ed80fa761c737e28460f142bb *src/cs/cs_entry.c e84dcca7eb019c54a63244705be9de83 *src/cs/cs_ereach.c 56513bbedfdf82fd50257880a7d4110c *src/cs/cs_etree.c 07a5fe24c1504802ea681fbb392fa3ab *src/cs/cs_fkeep.c 9ccfa44ef05265c7cecf2b8c472444c6 *src/cs/cs_gaxpy.c 77d68d1fa7f658c27a7958b1ddb58b2d *src/cs/cs_happly.c 863e2db4f9333a4c57a145b080830aea *src/cs/cs_house.c d91eb5a0ee22f874955dd304d872bc6a *src/cs/cs_ipvec.c 1ae89c82d2e9acefca697be9bb8c46f9 *src/cs/cs_leaf.c 7bc484d09f7b0ec2e90c3dfe71cb0050 *src/cs/cs_load.c 2c8e2c41defd62711d50dbd701b5d24e *src/cs/cs_lsolve.c 8399329c480228cd4aa3333e9ed55fdb *src/cs/cs_ltsolve.c d5ffd82d7f46f233426919c90d2f626c *src/cs/cs_lu.c c8d35a8b5bfc5158055530718355f2ae *src/cs/cs_lusol.c e6d717bcf526d8094e988af7762a4e86 *src/cs/cs_malloc.c 1fa16ad625004c0751972d6167d302a7 *src/cs/cs_maxtrans.c cd7f8fbe8b9f24d39398e521ee2d09b0 *src/cs/cs_multiply.c 3a79c830ce5dd9bb949a9685e1edaeea *src/cs/cs_norm.c 97293626e9f064a409f1714280395e2e *src/cs/cs_permute.c c7f844492120b9225c45a32abeeb455c *src/cs/cs_pinv.c fce1c3d237985737250c206c1fa9b364 *src/cs/cs_post.c c3ccdcb4c0983305fdd38aed6fcaea4a *src/cs/cs_print.c 88bb28f69b30603dd19009a3375b8ac3 *src/cs/cs_pvec.c 84edbe07c9718c6fe177fed84122803e *src/cs/cs_qr.c 97db2405a8b64e9d702aabc7179cdb89 *src/cs/cs_qrsol.c e76b86549fd5c0f4ae030954ea53a070 *src/cs/cs_randperm.c a8d7f11049e9dd9adb65b37055089f24 *src/cs/cs_reach.c df2cd8d777a7ae7124bb3d3af0336c36 *src/cs/cs_scatter.c 5ea459c942ba6699f9d1c103896e8cec *src/cs/cs_scc.c 95fe5e92c37c842cf7f6ffd95bf45a26 *src/cs/cs_schol.c 25433aeb13e81623bea4fce4f4a386b7 *src/cs/cs_spsolve.c ed31244ed5ef4ab0c2caa42b1a92dec0 *src/cs/cs_sqr.c 637e7a1b32636fe1d088b0895d771c3d *src/cs/cs_symperm.c 74e77d67862dcac028568c0a50b60844 *src/cs/cs_tdfs.c 7f9683f97ae6f192c2e4ded4ba51ed71 *src/cs/cs_transpose.c 5ab9c4c7c85630af49f10c1002795c06 *src/cs/cs_updown.c 4c8096ddf1737b69d8f41bc51ab1c96a *src/cs/cs_usolve.c 4ae2ad895b3ad8adcc0927dee0b33b3e *src/cs/cs_util.c 74e3d5634309a7716491939ecd8b993a *src/cs/cs_utsolve.c ae2b99c6930b9d78a067b9f304e4d021 *src/debug.h c36fc0d316783ca73c33594df813b191 *src/decomposition.c 634a82287e116db541c1c954a3cd9bdc *src/dgetv0.f 53aa0b92a01343a9780f33409ff71448 *src/distances.c ae7917a56c25a07b9860819bebf32f40 *src/dlaqrb.f 334cfcb89b71acd8bcf5e8398923f7f5 *src/dmout.f 33affe232f61fa5cab387c8c3e140ad6 *src/dnaitr.f 8661cfa88ca0ffa0f8847dc88ed53bcc *src/dnapps.f dfccde1654a64a6e14709c827311dc6a *src/dnaup2.f cbd4968767585d82b4ea9762ce7a973b *src/dnaupd.f 8285764ecec3f0da1831503affd69067 *src/dnconv.f 7e7766bc466e28155a85211734e36426 *src/dneigh.f 92be5de027d3bf234c3adb3c1df81216 *src/dneupd.f 599f6e77589fa5338379452ab77ec143 *src/dngets.f 375ff494ab18d30adad217d6c5406a6d *src/dotproduct.c 03a845c6af6e800d15575f831ea2f18e *src/dqueue.c e2ddc9e8d520337ca4fafc08d4bab6d1 *src/dqueue.pmt efac25ebd52c48ef108adc8afb018f16 *src/drl_Node.h f1ca9cf6ad08537f57409d9ce04a6345 *src/drl_Node_3d.h ac508e551027fe56c57650557ae848b5 *src/drl_graph.cpp 0c4a475dc83152ac2a64f07bc13fbc60 *src/drl_graph.h 9b685020b218853e6c53e036b52b5f5e *src/drl_graph_3d.cpp 4ee344063b486976c812f82113d3106c *src/drl_graph_3d.h 084b0e967eabe754512016f676c9fb4a *src/drl_layout.cpp 4c1690cd89b50832fb6ba2398d14414b *src/drl_layout.h a77f381105b0246c7a0719c0b669365b *src/drl_layout_3d.cpp 7e4c69a183df51fc7662e2a3f5c6e6be *src/drl_layout_3d.h 4b5e3c6311f4c7a87eac902316f38b95 *src/drl_parse.cpp 14f8e5de9f1b7e850614ccf71c93bff0 *src/drl_parse.h d1e7ea74631a08da9e1166300adc0af4 *src/dsaitr.f f226039f08b329d7a276b9c920c757b0 *src/dsapps.f 26e0e4fd884197eccdf79c211e4bf09e *src/dsaup2.f 221f58799c95c17f73a5043d9edb959f *src/dsaupd.f 573fb11e41307018f2fdb32ce3111be5 *src/dsconv.f f976b4529dead76e497c2f35fe067b00 *src/dseigt.f 0f7c847fa63252f466a7c312a9baa052 *src/dsesrt.f fd78b52dd2795d4db9d6706e5d7bbe26 *src/dseupd.f 604cef634a570edd5e9e1f0e57b85800 *src/dsgets.f d37e30b6becbd695f77bb83e86fc8845 *src/dsortc.f 8baf60e7aaca0c70f8ce165fa60f0eb4 *src/dsortr.f d4ead7e7ae03b16c06bc2eee64bc99fd *src/dstatn.f 40dc3cb9ded24c012fd5810e6175d7f9 *src/dstats.f de4792cfaab6cdda8d557902c2310fcc *src/dstqrb.f 10246dd04cc987d389f1f369f4b1813b *src/dvout.f d971c3cba371000e3ee5232179b380c3 *src/eigen.c 0accc0fa9659dc8f9f4c741decc84b1b *src/embedding.c 7a18f357ae90d62a9be31318d8e4d152 *src/fast_community.c 941a75d37de0179bd167016cb952806b *src/feedback_arc_set.c 4e4d915b4db7cfa6a03ed14677d30a16 *src/flow.c f51da6e3cf3d9e27793f855b469a3663 *src/foreign-dl-header.h 8dcd446f2b29a07cc182a7c43c84bece *src/foreign-dl-lexer.c 3ae0526a19d4d40aa9bd03768dec7e9a *src/foreign-dl-lexer.l efadc465f06e708e9b9aec61c3ef7966 *src/foreign-dl-parser.c 37cb4cd1f199c12541ad5be1a0b13119 *src/foreign-dl-parser.h 02e51863a28d84b9d930e060c36c309a *src/foreign-dl-parser.y 3db22bd8908d6d05a56a0856702ee72a *src/foreign-gml-header.h e1f955e79ad12556bb07e9b73c696188 *src/foreign-gml-lexer.c 4d1c1fe6dcf1cae6356c60874341e941 *src/foreign-gml-lexer.l 16305ab78fb3d40e034a7db32c1d030a *src/foreign-gml-parser.c f514bca999030ee14126c61812f7e3bb *src/foreign-gml-parser.h 073dd721cad6e6e3d9cb0439584c1dd7 *src/foreign-gml-parser.y 4b00beb752917585ee20f6bc869945e9 *src/foreign-graphml.c 6b3d524a6e9a9e187df1dbfbfd0afdbc *src/foreign-lgl-header.h ca64c0f314ce9888c271c8272baed68d *src/foreign-lgl-lexer.c 5474e51f39937c5829e46a1a86be3955 *src/foreign-lgl-lexer.l de1207e85e61fb581790c3e9b244e463 *src/foreign-lgl-parser.c 0c3a5e050c066f4dc28d969cd4b6cbf3 *src/foreign-lgl-parser.h a30dc3104abf4833c5db3e6494873914 *src/foreign-lgl-parser.y ba4af782887b2b97dc03481ee7f435bb *src/foreign-ncol-header.h 94fc55d6ee08348de5e8646a9b2e7134 *src/foreign-ncol-lexer.c eab2a232e7d214c5956425fc5b1586ff *src/foreign-ncol-lexer.l 8dff81859e1a6994394b99c3baa619b7 *src/foreign-ncol-parser.c 6e182fe588ac8186f497cb890216a08f *src/foreign-ncol-parser.h 30b7332b81818f0c30d66d229da044ba *src/foreign-ncol-parser.y 6228545b60873edce3007a3b200efdde *src/foreign-pajek-header.h 4de3843bea9fb0dcdfa24cc2fe3c53c6 *src/foreign-pajek-lexer.c 7682489b55a6702edb45eaa6ba8796f5 *src/foreign-pajek-lexer.l dc03eaae49cbdd5b764abcfd12d5986f *src/foreign-pajek-parser.c 5a6df4a4ce2cd86e29a88ca70335c90f *src/foreign-pajek-parser.h 5f01f1aed186a9205c089cf50e4ddc32 *src/foreign-pajek-parser.y 3f6f5a141efe284f7d67fffb4e275a82 *src/foreign.c 85aa6b11ac217d0125f2a637b2f44780 *src/forestfire.c a13696b3db177831c57b0f4420a35bb1 *src/fortran_intrinsics.c d890a597ebd23b5a4e35ba1ccf1cbf1d *src/games.c 9c4ac6869dba15f8f3726febbaa66170 *src/gengraph_box_list.cpp 884ddf7e6060db285d036f40cdbb5c0f *src/gengraph_box_list.h 2f9813131916ddc631e671e48abcb169 *src/gengraph_definitions.h 669960a45a8d87d695aead1c4ff45263 *src/gengraph_degree_sequence.cpp e91725a3e6fc82814f0838607077462c *src/gengraph_degree_sequence.h aa2548014952552b00703886669949eb *src/gengraph_graph_molloy_hash.cpp 8cd957d8c81c41dfc84b9d3ab52d89a7 *src/gengraph_graph_molloy_hash.h 7adabaf25556eb549602b1fd5452db30 *src/gengraph_graph_molloy_optimized.cpp 1e029605529d2b30e0c51ce3f0118e28 *src/gengraph_graph_molloy_optimized.h 4cd9c442c3d07a86cdd25c4f23532f3a *src/gengraph_hash.h ed698c541b7f649c44e0ad236a1c4889 *src/gengraph_header.h 3cbf1351fcc949438140bd886b550b46 *src/gengraph_mr-connected.cpp dfecde6d15a11f7fe08510ee52505a0d *src/gengraph_powerlaw.cpp 0cde273c55b4df3bbf9d6db3175ed954 *src/gengraph_powerlaw.h 7a57d0b17fc2497fa2fbd8cd4e88bed8 *src/gengraph_qsort.h 74f893284897e15ef1058d9359bcee1c *src/gengraph_random.cpp 0ec1db22781e6e2dfff3c076dc08cc0a *src/gengraph_random.h 7fca2f62df37344887866770376dfe96 *src/gengraph_vertex_cover.h 1f78b9a79ea04c9a441ca29048ea5c73 *src/glet.c 12adbf485e30a3acdd7382052b4bd6b5 *src/glpk_support.c 9e49afee60da929ba8be5d9561949edd *src/gml_tree.c 9cbe127f9ca1413b025474021b3dbbf8 *src/hacks.c 502e94a6e46f91ec49aef1978e388a99 *src/heap.c 9e02248d200bf72c7fcff7d5e50019fd *src/heap.pmt 6e09173c5033b55d9a469c8dd2152847 *src/hrg_dendro.h db1d06d3f6afa649b603447a27db2ba3 *src/hrg_graph.h 2a55b5aa6dd24af3fbed23c777f3356a *src/hrg_graph_simp.h 45a515d92fd7d19d6b58ce9a99790443 *src/hrg_rbtree.h aa24b037d218c2525ba09ead3425f554 *src/hrg_splittree_eq.h d049469367b24df3aaa04a335e19ae1f *src/igraph_arpack_internal.h 0ba0b5c96c3f5ee66e361b402f6ba852 *src/igraph_blas_internal.h 8c23d74aac650a5a31f7aa2c5fd5e4cb *src/igraph_buckets.c 7f4903acbb99fdeb4d2b1a70cc87b1bb *src/igraph_cliquer.c 7fbb4277146260b1854a3533a71886e9 *src/igraph_cliquer.h b19e0c7e19e68ea56da4bc4d4adb9d42 *src/igraph_error.c 89d68f6df7bcbf4d4076ac0b0e49c76d *src/igraph_estack.c 5724366acc9829a7710570238fb8757c *src/igraph_estack.h b820670b0847175947527134ac67632e *src/igraph_f2c.h cb0744105e9a3bec9c23b323122abf18 *src/igraph_fixed_vectorlist.c 47ee6b99a58e0f65a3c5bc3d393c9778 *src/igraph_flow_internal.h ba6345ae75a97b8435b3f1008394d521 *src/igraph_glpk_support.h 7427a7fd438c1e5c394d9dc3b9296d38 *src/igraph_gml_tree.h 6cc5ff7eb59a0e80a55dd276d626058a *src/igraph_grid.c 70dde0752bdfd37e737b8f919f559296 *src/igraph_hacks_internal.h 798db32cb0483138312afbcee380996c *src/igraph_hashtable.c 5fcba758c3db2a7b7e087ddf0ce31b2d *src/igraph_heap.c 8198ef5ed0064e6dfe10044011f6d483 *src/igraph_hrg.cc ec23eb8c9f95ac5333a7c4a955888c90 *src/igraph_hrg_types.cc 491ac34973b02bee0561a49d3c5b75a9 *src/igraph_interrupt_internal.h ea12c293520c96311f5df9e4de3871a0 *src/igraph_lapack_internal.h 1ea6795e5745f48a13b85a5d565ef2db *src/igraph_marked_queue.c 84c6ecb9eadc9a6615dada2a134ed3a4 *src/igraph_marked_queue.h 184fdcb9b26b795a5e09b3ff80736709 *src/igraph_math.h d3872c797d7d9d20338f3988b3bffa1f *src/igraph_psumtree.c ef0a9f0275dd11cd340293b9c350431b *src/igraph_set.c d45e5264e0d3d4938d079599356bc688 *src/igraph_stack.c 276b378aa4479d729baf29fdca1dd84b *src/igraph_strvector.c b5c3cdfed8c984310dae4ee4e3008ee3 *src/igraph_threading.h 78c519533ba34d958b11a20b183c3dfb *src/igraph_trie.c 4aa482a23cfc790fe9de29e1f8867038 *src/igraph_types_internal.h e64695174d95af9bd48fc48220438fcc *src/igraph_version.h 4244465fd1a0df2470e06a0c10df3e9e *src/include/igraph.h 6716e5369613ded97a4199ba1023c05b *src/include/igraph_adjlist.h 2947ecbc2e4cfd62b210777d1769a492 *src/include/igraph_arpack.h 7854959b8ca1605d515dfc0bb749dbf9 *src/include/igraph_array.h 9001525eae9a131c06ec404e2027450e *src/include/igraph_array_pmt.h 956164a937a281c9a9ef44cb1b2ffd2e *src/include/igraph_attributes.h ded7ce911117cb185695afb6a588fc97 *src/include/igraph_bipartite.h faa2b57d3c505aae29ba301ca089d76f *src/include/igraph_blas.h 6e5565f431ef173b7f5ec52367c5ed94 *src/include/igraph_centrality.h f11a5b678aef9889d9332745639ec32e *src/include/igraph_cliques.h 082b594fc181b155990f2d8db1b79bb4 *src/include/igraph_cocitation.h 1914da75cb7d341220431e0ace1c15d7 *src/include/igraph_cohesive_blocks.h 343832834e78fd98dd0d645d5a4efa46 *src/include/igraph_coloring.h c9a459ff27462adf30561f7ee7155115 *src/include/igraph_community.h 8660919371566588f510185e3e21bf3a *src/include/igraph_complex.h 8275aa1fef31df669f6e1993b48c8c21 *src/include/igraph_components.h b544e4e21d17cdbb0a4fd824bc2efbef *src/include/igraph_constants.h 3cd3abdd075d2e83ad9c12fd24b51fa4 *src/include/igraph_constructors.h bf0205c865296fa089dce1a3f6daf923 *src/include/igraph_conversion.h e4486a2829d55bc33af9aebaed854e73 *src/include/igraph_datatype.h 7d750771b04760596f670262e85bc625 *src/include/igraph_decls.h 6b8fbce9eb547d9a3f70960beae5f494 *src/include/igraph_dqueue.h 2dad489dd70513edda99fdc2775d6e76 *src/include/igraph_dqueue_pmt.h 194e5d07a9a623656ebfe7fc53bba74f *src/include/igraph_eigen.h b2cee5042f804f3ed96637f65209f6f3 *src/include/igraph_embedding.h d98ac998006e57d634782a18be1e232c *src/include/igraph_epidemics.h 4657126fe1d8359d88c76a0413d27366 *src/include/igraph_error.h fa609453980084c3b1188e705d1d41b7 *src/include/igraph_flow.h 7f5c2907a852a74197eb6db7b0ba0a36 *src/include/igraph_foreign.h 0d4685499eadf6f58eac24efa221ee08 *src/include/igraph_games.h 6c12467abd243ddd24e805ec303ae7fb *src/include/igraph_graphlets.h 07e8998bcdaf2b9b02a4f361829146fb *src/include/igraph_heap.h 3e82c52e24b7b05c5641d25ad96519f0 *src/include/igraph_heap_pmt.h d9f977bbc91d976c84510b520564e3cf *src/include/igraph_hrg.h 36fc610a83a89ef4ee4e19834c199ffe *src/include/igraph_interface.h ac0a83d2845c3dd265ba6004fee7cddc *src/include/igraph_interrupt.h b1673f54b1fcfd69ba0f09c02041df13 *src/include/igraph_iterators.h ff2d40874fa7a6e84eef8a98dfb6ea08 *src/include/igraph_lapack.h 4af6de21f70c59f3dbcb01cb2a342a8f *src/include/igraph_layout.h 4183af0a346c6f9c9d23174c0712122c *src/include/igraph_lsap.h ad6c57810e93d79ddf745811da8c46d9 *src/include/igraph_matching.h 12702fb73ccc61a0dc3e1c0b38cccf5a *src/include/igraph_matrix.h 2c844be8edca8fc72ec6a9c5bb27b5e4 *src/include/igraph_matrix_pmt.h dee5f5c00fed24f26d8163a4bc56dfd4 *src/include/igraph_memory.h 477a9f9cf3b49fbe347c02eb12cbf37f *src/include/igraph_microscopic_update.h f78e9fb0e8746215373afcb07b27f7a6 *src/include/igraph_mixing.h 180e8d4c013442dc9d199230b8ff1bf7 *src/include/igraph_motifs.h 84f7f0e433e4bebea6b2c47d30d75140 *src/include/igraph_neighborhood.h e6bdd82b265ee153792ea3d111ffcc44 *src/include/igraph_nongraph.h ce7ea8a3cf2b52540203c8c63e7ad797 *src/include/igraph_operators.h 4be2fced71fa78da28c50e96e65db7ce *src/include/igraph_paths.h e78b1f96059bbfaeafdb0477067edf51 *src/include/igraph_pmt.h c7e18522a9ed70278190d35aad0c2788 *src/include/igraph_pmt_off.h 3b2537a5dd66fb92e83a48e96b946f61 *src/include/igraph_progress.h 5e1010f0e8a7f1a6b21b3b29e168ab90 *src/include/igraph_psumtree.h 10469921eafe6c9feac553762d2c31e3 *src/include/igraph_qsort.h 41f7d71d2d94e60305c40f7e86d41014 *src/include/igraph_random.h 4e29c5978f5d5e8c3cc51002caeaecde *src/include/igraph_scan.h 320603e1a9f5f6b5d9564f933fc70282 *src/include/igraph_scg.h f0dff906f7eefb0e05c6fb787192ca7b *src/include/igraph_separators.h 77af613883e73a35e659d57940a0ad08 *src/include/igraph_sparsemat.h 518fa1cce77c5716c3eede6bfb85c4db *src/include/igraph_spmatrix.h d7670fedfb54c946d0b5c3b49de6f29e *src/include/igraph_stack.h 0ec8e445a707456786fe923cf713e0ee *src/include/igraph_stack_pmt.h ec210a55193a8dbebbc8b696388dd66e *src/include/igraph_statusbar.h 0db0faaf2b5b27f3f1acd455406f994d *src/include/igraph_structural.h 9ff3e263ef874fcb86b2e64f8fb314f7 *src/include/igraph_strvector.h 3ddb62acc79793027a3a080dce9e4944 *src/include/igraph_threading.h.in 1df04917c52097285d7582d0d777f2e2 *src/include/igraph_topology.h 828fb14f89518cd2c7c67f83c3932a38 *src/include/igraph_transitivity.h 3bad9fef1bb4e076a789e6232b0ffed4 *src/include/igraph_types.h 44d28cae8836814959c5432513815a33 *src/include/igraph_vector.h f464447fca1d661198aca82dc375c854 *src/include/igraph_vector_pmt.h d7714d256605e29a7e1d26004ad01559 *src/include/igraph_vector_ptr.h 58c8dccae0eda3cbda698d40a73c5deb *src/include/igraph_vector_type.h d6b0b1202056041712190dee1e95902b *src/include/igraph_version.h.in fb7795744937901c3130cd8a5d4222b5 *src/include/igraph_visitor.h 0ceee7df894ce42f555f5effe0240702 *src/infomap.cc d7095b8ca721c2507d81152d722308e8 *src/infomap_FlowGraph.cc bbf84d35c2016510d97be2b41be84017 *src/infomap_FlowGraph.h 793969346850d33fd683d087a8e4b52f *src/infomap_Greedy.cc 75a431e98e5b7b785bc372f211d432d0 *src/infomap_Greedy.h 7edc0e07208e9487e1fb8656d6493ec5 *src/infomap_Node.cc 9df7c5839a5cf0aa081a637ea9389446 *src/infomap_Node.h 1eb40fbf0a581bddadec6d0faf8c685f *src/init.c 14be091d75db4df0c8261c571a3c235f *src/interrupt.c 491b61dbc3c8a265485f6b29eb5b84aa *src/iterators.c e9e8f2dac33c5cc7bfe1da70a95cc05f *src/ivout.f a21872db43ab0ab40a4660117c02cf94 *src/lad.c f95ab29a3f1862dc2133f145ef2b8387 *src/lapack.c a7df6e16bbf2c8daee0f5392b3d04dc1 *src/layout.c a4d2a269bb68cd053e9346dddf368584 *src/layout_dh.c 1e43eb788e8bafae353dd0f127609418 *src/layout_fr.c 13624439921d6e2b5a0c72731f0cec17 *src/layout_gem.c 9fa436dd96c8eaccf4f2a3a6f219b5e2 *src/layout_kk.c ef9170b9e7c2d1bedf611cedcc79fd20 *src/lazyeval.c 201a9c70e7ebac764daf2578e9753397 *src/lsap.c 14545fd5a7696734b84b8c7277347ff3 *src/matching.c 2237e2aefeecfa2a00061eb8d8dfd8fd *src/math.c 57dbb4060ac063511e83d2c23c04c1e0 *src/matrix.c 2113da793c25725e5c1ff487a9777723 *src/matrix.pmt 6f99b8e27ee426917236833013db4ce5 *src/maximal_cliques.c 09c8159e923bc5d13cb081d6f8c4657a *src/maximal_cliques_template.h d276cc56bd81d89acb004d9f1ac56236 *src/memory.c 04734207be0d430e327d5eaa09127465 *src/microscopic_update.c 8a97bea8b83111ca8fb2f2886db91fc1 *src/mixing.c 2fbaa3b96fe70f50291706b827a55a1b *src/motifs.c 8abad248bfc770d94c3496b6426a531e *src/operators.c 13711e38459b1fc13a31384f665405d7 *src/optimal_modularity.c 7f4dba9bcfbe0db2a808ba15ab2f9329 *src/other.c 3715e9fefcdddbce4e9be24490cbd077 *src/paths.c a6595cc90c64e0aab7a336856a219e53 *src/plfit/arithmetic_ansi.h 098651533f8c80ffeef3d3e43bf39783 *src/plfit/arithmetic_sse_double.h 896685565ace49c58c8587e52c9fdfcb *src/plfit/arithmetic_sse_float.h a132926fc62c5122a0e5db6e7decb1f9 *src/plfit/error.c 9351bcba0c90fce3ad1dc3abdfbad525 *src/plfit/error.h 3325bc090cc6c9f8dfac22689e534a28 *src/plfit/gss.c 24b12def90aee37671bc29d1c267997a *src/plfit/gss.h 04b05118dedd5d894b7451a3077a2abf *src/plfit/kolmogorov.c 1af9acf6c110147ab7392148cf24c0ce *src/plfit/kolmogorov.h a3f7a0497381c0fecd2c2634913c48e3 *src/plfit/lbfgs.c f3601e97b1249e5888d73fd10e8126d9 *src/plfit/lbfgs.h 52f301d8733c4362b51ab461fd41b376 *src/plfit/options.c 2af6a5ba8d50aaa2493f188475fbab8d *src/plfit/platform.h a68a32d67b810ad2271da3d932506179 *src/plfit/plfit.c ec39eb232b03766144d5ce70434cd470 *src/plfit/plfit.h e7ea89c52ae68ed4acd40cee7848cc98 *src/plfit/plfit.inc 23aa3f72d6724222f7563bb22fa011df *src/plfit/zeta.c 2cb90ff85be06e53110d04f2ee7574e3 *src/plfit/zeta.h cbdfab62d68296ad1ac2197dc1a7f567 *src/pottsmodel_2.cpp b39bce59a0e9fdfe1b028aca69f040d3 *src/pottsmodel_2.h 3b4575360f029b448db3946a22672a8d *src/progress.c bf3a89b33370546ff924815b517926b5 *src/prpack.cpp f239c9f27078f7fc0ade177796514f7a *src/prpack.h 9cdd08531c091877493dc38d6d9a76a6 *src/prpack/prpack.h d270166efd776ce2b037b5e33c9e65c9 *src/prpack/prpack.inc 0bd04ba0eae9e7e3c81786f64d64f5d7 *src/prpack/prpack_base_graph.cpp 9204c4b68e204d547368fe45215f1933 *src/prpack/prpack_base_graph.h 981c6153aaed917674373a7f848d33af *src/prpack/prpack_csc.h 6dd85cebd13f0a8636f2410131e7a096 *src/prpack/prpack_csr.h 16f1218cac357f6853a1ef4a56a97a1e *src/prpack/prpack_edge_list.h 8c1c34c537ac91600dd9bb6dde40e298 *src/prpack/prpack_igraph_graph.cpp f4725104dcd769f5b8c536e1e7e7a629 *src/prpack/prpack_igraph_graph.h 4d3341314d147c7713eabf7bf2b28808 *src/prpack/prpack_preprocessed_ge_graph.cpp 23b18b1935c305ff6f8ea72ace07fcb0 *src/prpack/prpack_preprocessed_ge_graph.h f3f1eb733b38a2686c5443728bae2090 *src/prpack/prpack_preprocessed_graph.h 71f33cc3adc3806482f0154329cc996e *src/prpack/prpack_preprocessed_gs_graph.cpp 4bce367b866843fa89ec64a448a209cb *src/prpack/prpack_preprocessed_gs_graph.h d38e02fad914bac940da4a32ac39afea *src/prpack/prpack_preprocessed_scc_graph.cpp b1c479ed32faf5a58f406615ce6f48bd *src/prpack/prpack_preprocessed_scc_graph.h 86aa47464bc6d84a6ebd0912dc66ea66 *src/prpack/prpack_preprocessed_schur_graph.cpp f705b565d4dc23052d5ec58dc2f63d33 *src/prpack/prpack_preprocessed_schur_graph.h 7dbb50744056002b707ae5232924d448 *src/prpack/prpack_result.cpp 9a2d350363928141ef4785e6f0e2cfd5 *src/prpack/prpack_result.h d3bbd80d26189bd89221be9eae9685f8 *src/prpack/prpack_solver.cpp aa69309ad88c68bd3aef2d3b9f78d8ac *src/prpack/prpack_solver.h 3108bd08055e25c22b24cd7aee26f8c5 *src/prpack/prpack_utils.cpp d8e4562102dd19aa2b0ebb8b9ffc761a *src/prpack/prpack_utils.h 051b93697a782d5ee7443e6d14273f95 *src/pstdint.h 1f3978bd0a1d8de7a7f827097ce92c68 *src/qsort.c f9a82bcf4a3a750ab39528bc8d304053 *src/qsort_r.c 20fe91e8c46a4b2471a02b3446712ff2 *src/random.c 84c0c4371f2bcc046dc328374260c71c *src/random_walk.c cb60dc5bcb6213bb7b0e94167d5301d8 *src/rinterface.c 55c344dc2daf18e33b5e11a248013759 *src/rinterface.h 9bd640fc620ccde39a84b4f481c9a267 *src/rinterface_extra.c 9ff59160d545d276ac2419396cd07b77 *src/sbm.c 57c6afe96c89270e09ba578385afcca1 *src/scan.c aea038197b2d7bf291ffae04eb916e1e *src/scg.c 0c45c2990b0c5da3975c486a76988a88 *src/scg_approximate_methods.c 57172adf7c8ab509ba78ca5249e491dc *src/scg_exact_scg.c f02cb493011fc03a7afd0f73429e7444 *src/scg_headers.h 026c19e5e315a61afa720d1a1a02b2b2 *src/scg_kmeans.c 689526007c1e806566487866a1507dfd *src/scg_optimal_method.c bd4eee538520a213640c06c511215412 *src/scg_utils.c 86e001901ddbd58540c49d9e1440358e *src/second.f 525dd7ca0c9d60cb909e6a50bb5cdfe6 *src/separators.c af447f07a45af2b4f7edaee5d0a877a7 *src/simpleraytracer/Color.cpp be39147aa9a658a401d5d8e304bfbb68 *src/simpleraytracer/Color.h 605d507fd74ae304c92e9a08d23443fa *src/simpleraytracer/Light.cpp a06dcdf977661620d9a30542d0708979 *src/simpleraytracer/Light.h b9106690e86aab37621da51d42ba6673 *src/simpleraytracer/Point.cpp a62fbead2d3a236d5303cc9085c8b2eb *src/simpleraytracer/Point.h 1dd5be0de737299119ccbcde22702bb7 *src/simpleraytracer/RIgraphRay.cpp a799c64d3087459d00e419f3fe8d6570 *src/simpleraytracer/Ray.cpp 2e3885be19867ed6a3562aeadf9e5271 *src/simpleraytracer/Ray.h 1feae5499e54a7b2015c14e67dbf25e7 *src/simpleraytracer/RayTracer.cpp 79ce54bb866d3c8341d6ca072b034bb3 *src/simpleraytracer/RayTracer.h c5e9fe64aa620a4c2578d84ce4eb3a69 *src/simpleraytracer/RayVector.cpp 61172ce5b49dfa8b864abcfb8808d5bc *src/simpleraytracer/RayVector.h bd7cf3fc7d493820b559dc1a65b6736a *src/simpleraytracer/Shape.cpp e8afe23482477c8dc53db328272ccd7e *src/simpleraytracer/Shape.h 5c198eab1fe06123c45405eaa1a09200 *src/simpleraytracer/Sphere.cpp a4e697cdced0ed1c4d1caf55e7dba557 *src/simpleraytracer/Sphere.h dc312c8337bad1b31afdf169f3e9e194 *src/simpleraytracer/Triangle.cpp c422300a2a528aa3da4ec98ed2dd1c8f *src/simpleraytracer/Triangle.h fc6fc5c9aa5a5187e6a2b1643f72ed4a *src/simpleraytracer/unit_limiter.cpp 10c5f89c9426685c966b72e159221f1a *src/simpleraytracer/unit_limiter.h 2afac75f121c2b327f3a2310c2d2cfb8 *src/sir.c eee880ddc507c1a7add8ffa2a86ffc78 *src/spanning_trees.c 5650b3b4026735368885edeb7a2a9b20 *src/sparsemat.c 1f47f981eab357a0dbcc76df4a38926f *src/spectral_properties.c c09d0e9140d619f214444c71395afbe6 *src/spmatrix.c eca023c1e47dc08d757a306ce363251c *src/st-cuts.c 6900ecd75c77fa349fd21b96ac3948cf *src/stack.pmt b5163c86a9a4ff980ad7a02f9303d2b7 *src/stat.h 0a0892716e6bfe89fa6cccb8d9685b2f *src/statusbar.c 7a321a48e99f2d4686a70e427961f296 *src/structural_properties.c 84d5e7407dedd69d87c1f12113017e2f *src/structural_properties_internal.h ea3146ba4b98871a9fc147e45fb85fcd *src/structure_generators.c 8fa4711e4da6193579f9dda3dda2b5d6 *src/sugiyama.c f97445842b82e98c855b014788b70de5 *src/topology.c 8637a769b8bfd68002637252da0ea70e *src/triangles.c 5b20a3297338f3156a70a9ad255eb74d *src/triangles_template.h 7f3088b31e11c80c0de807760fa173ce *src/triangles_template1.h 2475f0aeb10d27edef133c0533a11d63 *src/type_indexededgelist.c 79ff3df7bfa26151b9893cffeba4d002 *src/types.c cfb66084ea2bfc7648ab47ed1018e8a4 *src/uuid/COPYING c733862ac29e8bbd01a49b5ac7d4a780 *src/uuid/Makevars.in 81a759562546aeea16d466fece227601 *src/uuid/Makevars.win 3eb0f4eb28341a52ddd7790ad4c043ae *src/uuid/R.c 137be172372dd9bfeb50ed7aa2869b3e *src/uuid/clear.c d2b39a0b3d72632db235a9c6d36ef344 *src/uuid/compare.c 76087d772af7d37cab53b1a56cf72ade *src/uuid/config.h.in d0026e30bb2f3feb7ac1db9827dd4820 *src/uuid/copy.c 0bf618d5e3f7bbff90c60455fa89b697 *src/uuid/gen_uuid.c 7374a713629b202c4fb82d650e510acb *src/uuid/isnull.c b671656493c2119636a4e981e9aad857 *src/uuid/pack.c dcc91eb622c08bf2fca11680c71b92cc *src/uuid/parse.c bededb71c0c869f06c3275a79781ed17 *src/uuid/unpack.c e51bd355555086e18222fbe3dff9d59f *src/uuid/unparse.c 35a97c82d22737936a4ba8fb6924bcd4 *src/uuid/uuid.h 84c21b1a1c769a488f5ff52e91be798a *src/uuid/uuidP.h aad9fd83e8f3cc7eb80e2ab0b2c4f84c *src/uuid/uuidd.h 9e16418d043b96a6061ffb43150c5abd *src/uuid/win32/config.h b345cf8deb9563717b23547730686212 *src/vector.c f6c884fce6c20ec8c4e2e3da53624868 *src/vector.pmt 6911588db261b2ab842d009b28d8d902 *src/vector_ptr.c 86dd274efc3061285ec0d3930f21fc2f *src/version.c e593dc778e53754657c788127e1a1ab0 *src/visitors.c 3e539674df5de90da12ae880863af9c6 *src/walktrap.cpp 15455e530da0bd2c8f68cef84a7a6870 *src/walktrap_communities.cpp d4677977768e0f15fb39a1d42bb4a7e7 *src/walktrap_communities.h 9ad1bb10814df4f9aa098fc1da0a4d3b *src/walktrap_graph.cpp 5b6742755090692a9f8f7bec3ac4531f *src/walktrap_graph.h 4708174b9d0a7ad332731d356b1f51fd *src/walktrap_heap.cpp 50c30f2b5e618bc971622ee539994586 *src/walktrap_heap.h 5125d305fe99bd9f8a0f550eb758a30f *src/zeroin.c 3ac491440c081055587468834ef456e0 *tests/testthat.R 3a5ec4e3cc8d87587b31237c5541f86e *tests/testthat/celegansneural.gml.gz 28cd0567bf26075c39c14d11c4c829aa *tests/testthat/dyad.census.R 34d03342fd57be47bdcf3079baea1efa *tests/testthat/football.gml.gz e95bd4dcfd5c9cfc68c4e8262d14965a *tests/testthat/helper.R 157659d4b0f46abf1b2893b2e52a9fc1 *tests/testthat/power.gml.gz d44acbb3efd8c507e3dbb2004a4dc52f *tests/testthat/test-constructor-modifiers.R 222570e74d422f0698d5b13a9ab876e1 *tests/testthat/test-graph-ids.R 1a0309528fa3062366defba21221c741 *tests/testthat/test-index-es.R 4788e269746f1dab1c81dd3c451e25ba *tests/testthat/test-isomorphism.R 72eaaa03dc1634f01b6627dc4b579331 *tests/testthat/test-make.R 69b30e1a71abb8ba4183e53802995c5a *tests/testthat/test-make_graph.R 22c63ccc32ad7bcc1ca5858e1f7682f1 *tests/testthat/test-new-layout-api.R 3c946c65dbee1987ac5fd0991ab4cbdd *tests/testthat/test-notable.R 7687fdcb891047a342172e1feab863b5 *tests/testthat/test-old-data-type.R f4383004c3666fcdda76b140c9be5f91 *tests/testthat/test-random_walk.R 9611d2c9cb947b58c40443fe2368bbc3 *tests/testthat/test-version.R ec4d2c7247fdbb3cb6e5f8299d51925d *tests/testthat/test-versions.R 9f5cff46fd4d9d30ce1849ced84a6c9d *tests/testthat/test-vs-es-printing.R 89c1da084e2516de1600992f2c91adbc *tests/testthat/test-vs-es-quirks.R ec51b0fd41e6535ff41a81d3855e0b45 *tests/testthat/test-vs-es.R b0783b265ed1ce213fc45bfc8ef0abf6 *tests/testthat/test-vs-operators.R 4c1ba73219c8dfd973fc878c0e2ed3b7 *tests/testthat/test-weakref.R 85ec5222dcf11a56e1c119cefcd8c9d1 *tests/testthat/test_add.edges.R 9d640d7ac3411dad252fa61e191968fd *tests/testthat/test_add.vertices.R 13cae003d2c04d379736320d7dac41f9 *tests/testthat/test_adjacency.spectral.embedding.R b93a3944e3c6b752dac2e225ce10d2ea *tests/testthat/test_all.st.cuts.R 542a9710d4d20713093a35d9b5000c7a *tests/testthat/test_alpha.centrality.R 505493c56ee9fd269286cf68a3701fd7 *tests/testthat/test_are.connected.R 1186c6125dd7536cc593a14912cacb2a *tests/testthat/test_arpack.R e282694af0f688cb034709e529f70ea2 *tests/testthat/test_articulation.points.R 8979b7079adec68a4eebc1fdcfec25b8 *tests/testthat/test_as.directed.R e48a4e35ddf3d28d072f439de1eb0499 *tests/testthat/test_as.undirected.R 3d24bf6e4a3f12e23306a6075f786b84 *tests/testthat/test_assortativity.R 795eb9d342b6953248fd9578ad6f4868 *tests/testthat/test_attributes.R 271f5a8b1b7ae28c5bae6dfcdd46f4d9 *tests/testthat/test_authority.score.R 3809cd4a3febab2fe0a453bc8cabc030 *tests/testthat/test_average.path.length.R 6b49e3650ff1719aa1f44db76b47ba4d *tests/testthat/test_ba.game.R 0a5a3daca2a7c84fcebfbe44f771f794 *tests/testthat/test_betweenness.R 4f381a3bdebfbf215316ec09037f3c02 *tests/testthat/test_biconnected.components.R 5082b11e39d7b485770e6400656841e7 *tests/testthat/test_bipartite.projection.R 6a8d5c5cba60d5c0bcc9087023ec8cad *tests/testthat/test_bipartite.random.game.R 8582a01c00fe03d6cc8336be5ea1555d *tests/testthat/test_bonpow.R 3a8a8485e09a9be56b8aa61943d1b2cf *tests/testthat/test_bug-1019624.R a0f71df068480720e927de8b86f061d9 *tests/testthat/test_bug-1032819.R 6de97cc0e6c5f0eccb17bcebed244070 *tests/testthat/test_bug-1033045.R 254a3cf2d08007ad5803d244a99abdfb *tests/testthat/test_bug-1073705-indexing.R 8eb54ffc45a7662db609689ab1da7ee2 *tests/testthat/test_bug-1073800-clique.R 2c96af4031e6a3b8b018a8ce8735eb07 *tests/testthat/test_canonical.permutation.R f254ac34fc9203ce26ad62ed19d30976 *tests/testthat/test_cliques.R ac1d66133bea5969e51bd75e13c354d8 *tests/testthat/test_closeness.R c45762e40c0ee3cb70d305d06db47f0d *tests/testthat/test_clusters.R 94471673c91e7ce3cd7a13a0b56bc741 *tests/testthat/test_communities.R 4a2a8e80da2d290077446c5cccca7998 *tests/testthat/test_constraint.R 2786c19359b36de1d6c2d90c305fde9e *tests/testthat/test_contract.vertices.R a4762ac8213e2d36626defccac985e1a *tests/testthat/test_correlated.R df25b65676954132724105f0c45d76fc *tests/testthat/test_count.multiple.R 401b5276d52c308093b1d9ebf252ec66 *tests/testthat/test_decompose.graph.R 3bce5671201a06ebd58d90ad350a01a8 *tests/testthat/test_degree.R 5512dce75135fa587c083313a70c6b19 *tests/testthat/test_degree.sequence.game.R 8ceeede3d4b00fd625b2f111a1ce60af *tests/testthat/test_delete.edges.R a2667985a9407d55df61cd8b56c58b5d *tests/testthat/test_delete.vertices.R 6fef9d7dba6ac8269458d0d5764e0052 *tests/testthat/test_diameter.R c5526915b4f853835809c7fb5898822f *tests/testthat/test_dimSelect.R 94f8ad23a61bb3dc9d46ff310b712611 *tests/testthat/test_dominator.tree.R 541d7ff02723427f2026be1a0eb7a737 *tests/testthat/test_dot.product.game.R 5d9a8a58619b8bb5c7645e2a4dbbc309 *tests/testthat/test_dyad.census.R faf67f6d469e7e3ccf0e78ea4096d660 *tests/testthat/test_edge.betweenness.R 82fe00c577b8f8ec3430f7848f2c2fd8 *tests/testthat/test_edge.betweenness.community.R 078a1606ee3392ef9d8408b2b146ab60 *tests/testthat/test_edge.connectivity.R fecffc869c851602342b441a3a418b77 *tests/testthat/test_edgenames.R 4781c4417c2f526009605d601b832ba6 *tests/testthat/test_evcent.R 85edbfa6a1db6972776e62292a19dc8b *tests/testthat/test_fartherst.nodes.R 80cf1f5676bd09a700e490ed4b439cfb *tests/testthat/test_fastgreedy.community.R 542aafbf6ff22a659f339ea8ffff8276 *tests/testthat/test_forestfire.R 36eccc1dd3d999a3941e7d034d1e6d17 *tests/testthat/test_get.adjacency.R 50bebe4a8abd9402f1e335bcc2d7aefc *tests/testthat/test_get.adjlist.R 51873b120dd3fd8fba64430e3a5daec8 *tests/testthat/test_get.all.shortest.paths.R 849cff0f46c9170797641ba66cba5595 *tests/testthat/test_get.diameter.R c4ba0a587f9530519bf13ea2acb58843 *tests/testthat/test_get.edge.R f9249efa32145fc1c8c12a36f945cbdf *tests/testthat/test_get.edgelist.R ded360a0009f7c4f67dc2b0352a0fb8a *tests/testthat/test_get.incidence.R 713863c8a73e169cd24293f85d08fc74 *tests/testthat/test_get.shortest.paths.R 03b481f55a65183b3b0e8ad203897960 *tests/testthat/test_girth.R f2214f9cf209e9878e4da3c57232f17f *tests/testthat/test_graph.adhesion.R d8a4ae5fc8b23235a3fed1249f21c2be *tests/testthat/test_graph.adjacency.R f7f7d009ae1a05610d9410b8bcc9d3a5 *tests/testthat/test_graph.adjlist.R 9ba1d7ad6342b0bef83bf1aaa52aae50 *tests/testthat/test_graph.atlas.R cf3ba37d89177cbbdc45c3c175355921 *tests/testthat/test_graph.bfs.R 499b455adea86ee71817783a4a65f577 *tests/testthat/test_graph.bipartite.R 879c434fba2bfd905c539be92ebe91fa *tests/testthat/test_graph.complementer.R c13bf09188f949377f0eac6d68a84042 *tests/testthat/test_graph.compose.R 2aa42f162d1bcb6b9582281130432efb *tests/testthat/test_graph.coreness.R 5f4e9c1eb0d4699236654074358b5115 *tests/testthat/test_graph.data.frame.R 68161b1dacafdfeef13eccd9efd7ae5f *tests/testthat/test_graph.de.bruijn.R 8723a905ccf9bd8987926a579d0442a5 *tests/testthat/test_graph.density.R de6d23c1d3d6e7b16d3159f56185e434 *tests/testthat/test_graph.edgelist.R df43bbc9223f5d6496e5715f1881abd6 *tests/testthat/test_graph.eigen.R f894160c868e9392d2727cf9a6dc5af6 *tests/testthat/test_graph.formula.R e2efb24c4db5b274ac18017ed480d2d9 *tests/testthat/test_graph.isoclass.R 6f3d4507996dbcc43920adce657a738f *tests/testthat/test_graph.kautz.R 0a80082ebc39ec4cdca090a3e1c11c67 *tests/testthat/test_graph.knn.R 9d869da1cc161a645c293d10dc341590 *tests/testthat/test_graph.maxflow.R 1159c879ec2285bbaa08209a1d2c5add *tests/testthat/test_graph.mincut.R 530fba9e8d790c38aca699b1a568de00 *tests/testthat/test_graph.subisomorphic.lad.R eb55c1cd65d26a7530d9460ec396dfb2 *tests/testthat/test_graph.subisomorphic.vf2.R eba8e06baddc6b0a8ddfbe7e48cebac2 *tests/testthat/test_graphNEL.R 7ade84c2f969fe28375fd8d0cb662cc8 *tests/testthat/test_graphlets.R 3e58a33bfda76293340465d7aac08c86 *tests/testthat/test_hrg.R a570ca5f125efa4d98d030585f2004d2 *tests/testthat/test_hsbm.R 753560560670d5f5d28c7029ef745fd8 *tests/testthat/test_igraph.options.R 026f3752506a2ec286066504e9d37a85 *tests/testthat/test_independent.vertex.sets.R e466a39d382b5505b953292b62c50366 *tests/testthat/test_indexing.R ff070d086e04573751eb22de047f4b7c *tests/testthat/test_indexing2.R c78a920d52351d67639476e2aac25a8d *tests/testthat/test_indexing3.R 7748209eb0003b8d2c5d4ee90606878e *tests/testthat/test_is.bipartite.R d501b567e3e573c4d999ac1ace4bb665 *tests/testthat/test_is.chordal.R 52138bea453eda91c667da3742007912 *tests/testthat/test_iterators.R 764d5cb76819f0a268562b2f6f59f82b *tests/testthat/test_label.propagation.community.R c8c475e2e86016609574169e78c716ea *tests/testthat/test_laplacian.spectral.embedding.R 418d9fcc91a880b0fb839eb0fe002a41 *tests/testthat/test_largest.cliques.R fce5463a31d7da19e21761e1d3bfbe9d *tests/testthat/test_largest.independent.vertex.sets.R 76c4bcfe67ae3b21a0aef80ef6db25be *tests/testthat/test_layout.fr.R 60985a23558525cd15acaffb0b95b742 *tests/testthat/test_layout.kk.R 6a2aed874635751a944a0f28f08f2c9a *tests/testthat/test_layout.mds.R 7e921347ce3b1b198f167e574067d1db *tests/testthat/test_layout.merge.R dea0f7483ea375c42c7a00e6217a09eb *tests/testthat/test_leading.eigenvector.community.R b373b6fd97fabb47114c76e104fa86bb *tests/testthat/test_maximal_cliques.R 751e142d0005412034ca097b97c9a153 *tests/testthat/test_minimal.st.separators.R e376dbc01376d61de29507390ea4a4a0 *tests/testthat/test_minimum.size.separators.R 27b029baf39ed4c32ba0d69d5f7ed5a0 *tests/testthat/test_modularity_matrix.R 76e7ce19e8352b279c775ebed2f69153 *tests/testthat/test_motifs.R 993e177c45db6a718a6784b34330c659 *tests/testthat/test_multilevel.community.R 46d54173d41a303f3390ca543721ccb5 *tests/testthat/test_neighborhood.R 9f34f2b64e709ee9d3d3069464f88c15 *tests/testthat/test_neighbors.R 24cbc821daf29547b37847071891286a *tests/testthat/test_operators.R 46c39f7c2bed29cc43dc7ce9cfefa10b *tests/testthat/test_operators3.R b45cd48a81d66aec4e4c28a9bd9da016 *tests/testthat/test_operators4.R 8521df17b3085adcee4874ae9118e266 *tests/testthat/test_optimal.community.R 560990b6b9e50c3585297bbea2a8313b *tests/testthat/test_pajek.R 89b900f0d5dd8a0d46c1d9010d9c93f2 *tests/testthat/test_print.R acfd49645b89a10f93eab7ea814815eb *tests/testthat/test_psumtree.R c16adef7ce46505194e165e819a6ee7f *tests/testthat/test_sample.R 071bf3fb054279e535ccb9936ecb1944 *tests/testthat/test_sbm.game.R 5996191f90b8e86be20a5840a2089aa1 *tests/testthat/test_scan.R 9274bc5af61b2058a08fe4d377aedab0 *tests/testthat/test_sdf.R 307c4bdb58bd0229816f4363a5b12186 *tests/testthat/test_sgm.R 5ececc4dc384fa67819917344078e366 *tests/testthat/test_sir.R 802bc718931dca81b4750a5e028fc945 *tests/testthat/test_sphere.R f7f321f4b3ae913bf5ff88ee468b21af *tests/testthat/test_transitivity.R 59b470781b4cbb8184b85b2f292cc9a0 *tests/testthat/test_triangles.R 7f8ca4c58a09baf998e26774fc6a6290 *tests/testthat/test_unfold.tree.R 2426bc82153054e1f00534d6c81e47b9 *tests/testthat/test_walktrap.community.R d8d7a03abfc121b96fad591afb9fbca7 *tests/testthat/test_watts.strogatz.game.R igraph/inst/0000755000175100001440000000000013430770106012520 5ustar hornikusersigraph/inst/benchmarks/0000755000175100001440000000000013177712334014644 5ustar hornikusersigraph/inst/benchmarks/time_fr_layout.R0000644000175100001440000000070313177712334020011 0ustar hornikusers time_group("Fruchterman-Reingold layout") time_that("FR layout is fast, connected", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_pa(400) }, { layout_with_fr(g, niter=500) }) time_that("FR layout is fast, unconnected", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_gnm(400, 400) }, { layout_with_fr(g, niter=500) }) igraph/inst/benchmarks/time_dirSelect.R0000644000175100001440000000035113177712334017722 0ustar hornikusers time_group("dimensionality selection") time_that("dimensionaility selection is fast", replications=10, init = { library(igraph) }, reinit = { sv <- c(rnorm(2000), rnorm(2000)/5) }, { dim_select(sv) }) igraph/inst/benchmarks/time_call.R0000644000175100001440000000075713177712334016731 0ustar hornikusers time_group(".Call from R") time_that("Redefining .Call does not have much overhead #1", replications=10, init = { library(igraph) ; g <- graph.ring(100) }, { for (i in 1:20000) { .Call(C_R_igraph_vcount, g) } }) time_that("Redefining .Call does not have much overhead #1", replications=10, init = { library(igraph) ; g <- graph.ring(100) }, { for (i in 1:20000) { igraph:::.Call(C_R_igraph_vcount, g) } }) igraph/inst/benchmarks/time_kk_layout.R0000644000175100001440000000122013177712334020002 0ustar hornikusers time_group("Kamada-Kawai layout") time_that("KK layout is fast, connected", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_pa(400) }, { layout_with_kk(g, maxiter=500) }) time_that("KK layout is fast, unconnected", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_gnm(400, 400) }, { layout_with_kk(g, maxiter=500) }) time_that("KK layout is fast for large graphs", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_pa(3000) }, { layout_with_kk(g, maxiter=500) }) igraph/inst/benchmarks/time_sgm.R0000644000175100001440000000075513177712334016602 0ustar hornikusers time_group("Seeded graph matching") time_that("SGM is fast(er)", replications=10, init = { library(igraph); set.seed(42); vc <- 200; nos=10 }, reinit = { g1 <- erdos.renyi.game(vc, .01); perm <- c(1:nos, sample(vc-nos)+nos) g2 <- sample_correlated_gnp(g1, corr=.7, p=g1$p, perm=perm) }, { match_vertices(g1[], g2[], m=nos, start=matrix(1/(vc-nos), vc-nos, vc-nos), iteration = 20) }) igraph/inst/benchmarks/time_print.R0000644000175100001440000000447313177712334017151 0ustar hornikusers time_group("Printing graphs to the screen") time_that("Print large graphs without attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)) }, { print(g) }) time_that("Summarize large graphs without attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)) }, { summary(g) }) time_that("Print large graphs with large graph attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_graph_attr(g, "foo", 1:1000000) }, { print(g) }) time_that("Summarize large graphs with large graph attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_graph_attr(g, "foo", 1:1000000) }, { summary(g) }) time_that("Print large graphs with vertex attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_vertex_attr(g, 'foo', value = as.character(seq_len(gorder(g)))) }, { print(g) }) time_that("Summarize large graphs with vertex attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_vertex_attr(g, 'foo', value = as.character(seq_len(gorder(g)))) }, { print(g) }) time_that("Print large graphs with edge attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_edge_attr(g, 'foo', value = as.character(seq_len(gsize(g)))) }, { print(g) }) time_that("Summarize large graphs with edge attributes", replications = 10, init = { library(igraph); set.seed(42) }, reinit = { g <- make_lattice(c(1000, 1000)); g <- set_edge_attr(g, 'foo', value = as.character(seq_len(gsize(g)))) }, { print(g) }) igraph/inst/benchmarks/correlated.R0000644000175100001440000000031513177712334017112 0ustar hornikusers time_group("correlated E-R graphs, v1") time_that("sample_correlated_gnp is fast", replications=10, init={ library(igraph) }, { sample_correlated_gnp_pair(100, corr=.8, p=5/100) }) igraph/inst/benchmarks/local.scan.R0000644000175100001440000000362213177712334017007 0ustar hornikusers time_group("local scan v1") init <- expression({library(igraph); set.seed(42) }) reinit <- expression({g <- random.graph.game(1000, p=.1) E(g)$weight <- sample(ecount(g)) gp <- random.graph.game(1000, p=.1) E(gp)$weight <- sample(ecount(gp)) }) time_that("us, scan-0, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=0) }) time_that("us, scan-0, weighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=0, weighted=TRUE) }) time_that("us, scan-1, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=1) }) time_that("us, scan-1, weighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=1, weighted=TRUE) }) time_that("us, scan-2, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=2) }) time_that("us, scan-2, weighted", replications=10, init=init, reinit=reinit, { local_scan(g, k=2, weighted=TRUE) }) time_that("them, scan-0, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=0) }) time_that("them, scan-0, weighted", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=0, weighted=TRUE) }) time_that("them, scan-1, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=1)} ) time_that("them, scan-1, weighted", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=1, weighted=TRUE) }) time_that("them, scan-2, unweighted", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=2) }) time_that("them, scan-2, weigthed", replications=10, init=init, reinit=reinit, { local_scan(g, gp, k=2, weighted=TRUE) }) igraph/inst/benchmarks/time_sir.R0000644000175100001440000000036213177712334016603 0ustar hornikusers time_group("SIR epidemics models on networks") time_that("SIR is fast", replications=10, init = { library(igraph); set.seed(42) }, reinit = { g <- sample_gnm(40, 40) }, { sir(g, beta=5, gamma=1, no.sim=100) }) igraph/inst/README.md0000644000175100001440000000115513177712334014010 0ustar hornikusers # R/igraph R/igraph is an R package of the igraph network analysis library. ## Installation You can install the stable version of R/igraph from CRAN: ```r install.packages("igraph") ``` For the development version, you can use Github, with the `devtools` package: ```r devtools::install_github("gaborcsardi/pkgconfig") devtools::install_github("igraph/rigraph") ``` ## Documentation See the [igraph homepage](http://igraph.org/r) for the complete manual. ## Contributions Please read our [contribution guide](https://github.com/igraph/rigraph/blob/dev/CONTRIBUTING.md). ## License GNU GPL version 2 or later igraph/inst/CITATION0000644000175100001440000000120413177712334013661 0ustar hornikuserscitHeader("To cite 'igraph' in publications use:") citEntry(entry="article", title="The igraph software package for complex network research", author=personList(as.person("Gabor Csardi"), as.person("Tamas Nepusz")), journal="InterJournal", volume="Complex Systems", pages="1695", year="2006", url="http://igraph.org", textVersion=paste("Csardi G, Nepusz T: The igraph software package for ", "complex network research, InterJournal, ", "Complex Systems 1695. 2006. ", "http://igraph.org", sep="")) igraph/inst/igraph2.gif0000644000175100001440000000312713177712334014555 0ustar hornikusersGIF89a@@÷ï î õõóóôòñ íëçåâäÞ%%Ý('Ú+*Ü)(Ø.-Ï<;Ó43Ô65Ð:9á!!¾UU¹[[­nnµcc²gg°ii±ii§wv«rqªsr¤{{£||¢ÊBAÉFEÈGFÆJIÅJJÀQQÀRRÀSSëÞìßëÞýîýîûíúìûíüíõç õæ÷é ùëùë øé øê ÿðÿðïáîáïâíáóæòäðãßÓ-ÝÒ/×Í7ÙÎ5ÒÇ>ÔÊ;×Í8ÓÉ<ÓÉ=ÛÐ1ÛÐ2ã×'çÛ!æÚ"äØ&èÛ âÖ(â×(àÔ*áÕ*àÔ+¿·X¾¶Yº³^»´]¼´\¼µ\¼´]¿¸X£ž¤Ÿ~¶¯d±«k²«j³­h³¬i³­i´­h±«l¹²aº³`¬§r¬§sª¤u«¦t©¤w¦¡z¦¢z¤ }Ç¿MƽNƾNúRûSļQºTÀ¸WÎÅCÌÂFÌÃFÎÄDËÁHÊÁIËÂHÑÈ@Ÿƒƒž„„—›ˆˆ™ŒŒ™šŒŒ˜ŽŽŸ›„Ÿš…Ÿ›…™‡—•›—Šš–‹˜•™•™–Œš–Œ˜”Ž˜•Žœ˜ˆœ™ˆ”‘‘•‘‘––‘‘•’‘–“–’‘–“‘”’’•’’•“’”““•““–’’–“’–““¡€€¡¢€¢ž€¡œ‚!ù´,@@þi H° Áƒ*\Ȱ¡Ã‡#JœH±¢Å‹3jܨѕLJ]rÅq¡+E"S. ‰’<–H–48²&¥ŸdtE&‡ŸEbÎ$èñT'&/faÒIä'„®üœJHçPrpøˆ1õÆW”vž*2õ'‘Ci¤4ä'W·/nZxJŒ²>’Ìåèñ Þ²a>tõæíV9§ÒÒ9èïÔ%‚ Šô$Œ3hÓŽtâøg’‘PCž­ø”¢1cô‰Ls­â"!ùăÆ,°IodMp¤+/[ËÆðjâŽ5y ëê Y®E0+_¾·¢G.T^jð“wžgÈþ¤<~P÷E†‚û 2}tQ‘æ“¿xJWÃiæK‰RfH«ÓQ䊭ÆÐhîÕÄß»]bØOiT·J#1R|Ém41¼%…+O)Ÿ"Xà #€•Ón”xq†Üt“~™æÊàã>Á)ßm”ƒ‹å¤È~®d€Púø"Z´—oD)²A”\ ðÀ'ñ)¦ÒH‹Ð%—CVYÒ§Xp&—”æk"1‚â›Qf€Òkƒ¹ž\V &l¾IèHåü‰¨`HaM4ŠFÉÈh aHÆexäÝD©P)¨X¦B$Rþ£þø€o8ªåŠ%d©C§†fz "±úˆBrŠ˜–%!þtħ¥´@°|”\J)¥ú—rItÒ–£NЪ­"{Ê´ÕFɋ͎fB¥ rSh#1Q. s6ä# J'õ*R4çC„‘JzÒ o:BM+ydoÑàGqòwþ ŠäTkŸ®Lâ \q¤uÖ¤e(p §S½îW(X/æ"ˆ4 &Z¿Ó‚úŸ„;ƒÈ–DaHqZ!A’K˜q#u1óI—"iäÐa‡GÄÔ_ÍRÃæÊ,<üå’];HgždV¶B#eÑÙõ®£"Pt6‡±rûÚG7²>Ð` ×y¯õmE-7ˆH1Dç-¢wu¼qF';î(›†[¾\åšwîùç ‡.úè¤Ó;igraph/inst/AUTHORS0000644000175100001440000001137613177712334013607 0ustar hornikusers igraph authors, in alphabetical order: -------------------------------------- Patrick R. Amestoy AMD library Adelchi Azzalini igraph.options based on the sm package Tamas Badics GLPK Gregory Benison Minimum cut calculation Adrian Bowman igraph.options based on the sm package Walter Böhm LSAP Keith Briggs Parts from the Very Nauty Graph Library Geometric random graphs Girth Various patches and bug fixes Jeroen Bruggeman spinglass community detection Burt's constraints Juergen Buchmueller Big number math implementation Carter T. Butts Some layout algorithms from the SNA R package bonpow function in the SNA R package Some R manual pages, from the SNA R package Aaron Clauset Hierarchical random graphs J.T. Conklin logbl function Topher Cooper GSL random number generators (not used in R) Gabor Csardi Most of igraph Trevor Croft simpleraytracer Peter DalGaard zeroin root finder Timothy A Davis CXSPARSE: a Concise Sparse Matrix package - Extended AMD library Sparse matrix column ordering Laurent Deniau Bits of the error handling system Ulrich Drepper logbl function Iain S. Duff AMD library GLPK S.I. Feldman f2c David Firth Display data frame in Tk, from relimp package P. Foggia VF2 graph isomorphism algorithm John Fox R: suppressing X11 warnings Alan George GLPK John Gilbert Sparse matrix column ordering D.Goldfarb GLPK Brian Gough GSL random number generators (not used in R) Tom Gregorovic Multilevel community detection M.Grigoriadis GLPK Oscar Gustafsson GLPK Kurt Hornik LSAP Paul Hsieh pstdint.h Ross Ihaka Some random number generators (not used in R) Tommi Junttila BLISS graph isomorphism library Petteri Kaski BLISS graph isomorphism library Oleg Keselyov zeroin root finder Darwin Klingman GLPK Donald E. Knuth GLPK Stefan I. Larimore Sparse matrix column ordering Yusin Lee GLPK Richard Lehoucq ARPACK Rene Locher R arrow drawing function, from IDPmisc package J.C. Nash BFGS optimizer Joseph W-H Liu GLPK Makoto Matsumoto GSL random number generators (not used in R) Vincent Matossian Graph laplacian igraph_neighborhood_graphs Line graphs Peter McMahan Cohesive blocking Andrew Makhorin GLPK David Morton de Lachapelle Spectral coarse graining Laurence Muller Fixes for compilation on MS Visual Studio Fionn Murtagh Order a hierarchical clustering Emmanuel Navarro infomap community detection Various fixes and patches Tamas Nepusz Most of igraph Esmond Ng Sparse matrix column ordering Kevin O'Neill Maximal independent vertex sets Takuji Nishimura GSL random number generators (not used in R) Jim Orlin GLPK Patric Ostergard GLPK Elliot Paquette psumtree data type Pascal Pons walktrap community detection Joerg Reichardt spinglass community detection Marc Rieffel GSL random number generators (not used in R) B.D. Ripley igraph.options based on the sm package BFGS optimizer Various bug fixes Martin Rosvall infomap community detection Andreas Ruckstuhl R arrow drawing function, from IDPmisc package Heinrich Schuchardt GLPK J.K. Reid GLPK C. Sansone VF2 graph isomorphism algorithm Michael Schmuhl The graphopt layout generator Christine Solnon LAD graph isomorphism library Danny Sorensen ARPACK James Theiler GSL random number generators (not used in R) Samuel Thiriot Interconnected islands graph generator Vincent A. Traag spinglass community detection Magnus Torfason R operators that work by name Theodore Y. Ts'o libuuid Minh Van Nguyen Microscopic update rules Various test cases Many documentation and other fixes M. Vento VF2 graph isomorphism algorithm Fabien Viger gengraph graph generator Phuong Vu ARPACK P.J. Weinberger f2c Hadley Wickham lazyeval Garrett A. Wollman qsort B.N. Wylie DrL layout generator Chao Yang ARPACK Institutional copyright owners: ------------------------------- Free Software Foundation, Inc Code generated by bison Sandia Corporation DrL layout generator The R Development Core Team Some random number generators (not used in R) R: as.dendrogram from stats package The Regents of the University of California qsort Xerox PARC Sparse matrix column ordering R Studio lazyeval Other contributors ------------------ Neal Becker Patches to compile with gcc 4.4 Richard Bowman R patches Alex Chen Patch to compile on Intel compilers Daniel Cordeiro Patches Tom Gregorovic Bug fixes Mayank Lahiri Forest fire game fix John Lapeyre Patches Christopher Lu Various fixes and patches André Panisson R patches Bob Pap Bug fixes Keith Ponting R package bug fixes Martin J Reed Bug fixes Elena Tea Russo Bug fixes KennyTM Bug fixes Jordi Torrents Patches Matthew Walker Various patches Kai Willadsen Arrow size support in Python igraph/inst/html_library.tcl0000644000175100001440000011751013177712334015730 0ustar hornikusers# Simple HTML display library by Stephen Uhler (stephen.uhler@sun.com) # Copyright (c) 1995 by Sun Microsystems # Version 0.3 Fri Sep 1 10:47:17 PDT 1995 # # See the file "license.terms" for information on usage and redistribution # of this file, and for a DISCLAIMER OF ALL WARRANTIES. # # To use this package, create a text widget (say, .text) # and set a variable full of html, (say $html), and issue: # HMinit_win .text # HMparse_html $html "HMrender .text" # You also need to supply the routine: # proc HMlink_callback {win href} { ...} # win: The name of the text widget # href The name of the link # which will be called anytime the user "clicks" on a link. # The supplied version just prints the link to stdout. # In addition, if you wish to use embedded images, you will need to write # proc HMset_image {handle src} # handle an arbitrary handle (not really) # src The name of the image # Which calls # HMgot_image $handle $image # with the TK image. # # To return a "used" text widget to its initialized state, call: # HMreset_win .text # See "sample.tcl" for sample usage ################################################################## ############################################ # mapping of html tags to text tag properties # properties beginning with "T" map directly to text tags # These are Defined in HTML 2.0 array set HMtag_map { b {weight bold} blockquote {style i indent 1 Trindent rindent} bq {style i indent 1 Trindent rindent} cite {style i} code {family courier} dfn {style i} dir {indent 1} dl {indent 1} em {style i} h1 {size 24 weight bold} h2 {size 22} h3 {size 20} h4 {size 18} h5 {size 16} h6 {style i} i {style i} kbd {family courier weight bold} menu {indent 1} ol {indent 1} pre {fill 0 family courier Tnowrap nowrap} samp {family courier} strong {weight bold} tt {family courier} u {Tunderline underline} ul {indent 1} var {style i} } # These are in common(?) use, but not defined in html2.0 array set HMtag_map { center {Tcenter center} strike {Tstrike strike} u {Tunderline underline} } # initial values set HMtag_map(hmstart) { family times weight medium style r size 14 Tcenter "" Tlink "" Tnowrap "" Tunderline "" list list fill 1 indent "" counter 0 adjust 0 } # html tags that insert white space array set HMinsert_map { blockquote "\n\n" /blockquote "\n" br "\n" dd "\n" /dd "\n" dl "\n" /dl "\n" dt "\n" form "\n" /form "\n" h1 "\n\n" /h1 "\n" h2 "\n\n" /h2 "\n" h3 "\n\n" /h3 "\n" h4 "\n" /h4 "\n" h5 "\n" /h5 "\n" h6 "\n" /h6 "\n" li "\n" /dir "\n" /ul "\n" /ol "\n" /menu "\n" p "\n\n" pre "\n" /pre "\n" } # tags that are list elements, that support "compact" rendering array set HMlist_elements { ol 1 ul 1 menu 1 dl 1 dir 1 } ############################################ # initialize the window and stack state proc HMinit_win {win} { upvar #0 HM$win var HMinit_state $win $win tag configure underline -underline 1 $win tag configure center -justify center $win tag configure nowrap -wrap none $win tag configure rindent -rmargin $var(S_tab)c $win tag configure strike -overstrike 1 $win tag configure mark -foreground red ;# list markers $win tag configure list -spacing1 3p -spacing3 3p ;# regular lists $win tag configure compact -spacing1 0p ;# compact lists $win tag configure link -borderwidth 2 -foreground blue ;# hypertext links HMset_indent $win $var(S_tab) $win configure -wrap word # configure the text insertion point $win mark set $var(S_insert) 1.0 # for horizontal rules $win tag configure thin -font [HMx_font times 2 medium r] $win tag configure hr -relief sunken -borderwidth 2 -wrap none \ -tabs [winfo width $win] bind $win { %W tag configure hr -tabs %w %W tag configure last -spacing3 %h } # generic link enter callback $win tag bind link <1> "HMlink_hit $win %x %y" } # set the indent spacing (in cm) for lists # TK uses a "weird" tabbing model that causes \t to insert a single # space if the current line position is past the tab setting proc HMset_indent {win cm} { set tabs [expr $cm / 2.0] $win configure -tabs ${tabs}c foreach i {1 2 3 4 5 6 7 8 9} { set tab [expr $i * $cm] $win tag configure indent$i -lmargin1 ${tab}c -lmargin2 ${tab}c \ -tabs "[expr $tab + $tabs]c [expr $tab + 2*$tabs]c" } } # reset the state of window - get ready for the next page # remove all but the font tags, and remove all form state proc HMreset_win {win} { upvar #0 HM$win var regsub -all { +[^L ][^ ]*} " [$win tag names] " {} tags catch "$win tag delete $tags" eval $win mark unset [$win mark names] $win delete 0.0 end $win tag configure hr -tabs [winfo width $win] # configure the text insertion point $win mark set $var(S_insert) 1.0 # remove form state. If any check/radio buttons still exists, # their variables will be magically re-created, and never get # cleaned up. catch unset [info globals HM$win.form*] HMinit_state $win return HM$win } # initialize the window's state array # Parameters beginning with S_ are NOT reset # adjust_size: global font size adjuster # unknown: character to use for unknown entities # tab: tab stop (in cm) # stop: enabled to stop processing # update: how many tags between update calls # tags: number of tags processed so far # symbols: Symbols to use on un-ordered lists proc HMinit_state {win} { upvar #0 HM$win var array set tmp [array get var S_*] catch {unset var} array set var { stop 0 tags 0 fill 0 list list S_adjust_size 0 S_tab 1.0 S_unknown \xb7 S_update 10 S_symbols O*=+-o\xd7\xb0>:\xb7 S_insert Insert } array set var [array get tmp] } # alter the parameters of the text state # this allows an application to over-ride the default settings # it is called as: HMset_state -param value -param value ... array set HMparam_map { -update S_update -tab S_tab -unknown S_unknown -stop S_stop -size S_adjust_size -symbols S_symbols -insert S_insert } proc HMset_state {win args} { upvar #0 HM$win var global HMparam_map set bad 0 if {[catch {array set params $args}]} {return 0} foreach i [array names params] { incr bad [catch {set var($HMparam_map($i)) $params($i)}] } return [expr $bad == 0] } ############################################ # manage the display of html # HMrender gets called for every html tag # win: The name of the text widget to render into # tag: The html tag (in arbitrary case) # not: a "/" or the empty string # param: The un-interpreted parameter list # text: The plain text until the next html tag proc HMrender {win tag not param text} { upvar #0 HM$win var if {$var(stop)} return global HMtag_map HMinsert_map HMlist_elements set tag [string tolower $tag] set text [HMmap_esc $text] # manage compact rendering of lists if {[info exists HMlist_elements($tag)]} { set list "list [expr {[HMextract_param $param compact] ? "compact" : "list"}]" } else { set list "" } # Allow text to be diverted to a different window (for tables) # this is not currently used if {[info exists var(divert)]} { set win $var(divert) upvar #0 HM$win var } # adjust (push or pop) tag state catch {HMstack $win $not "$HMtag_map($tag) $list"} # insert white space (with current font) # adding white space can get a bit tricky. This isn't quite right set bad [catch {$win insert $var(S_insert) $HMinsert_map($not$tag) "space $var(font)"}] if {!$bad && [lindex $var(fill) end]} { set text [string trimleft $text] } # to fill or not to fill if {[lindex $var(fill) end]} { set text [HMzap_white $text] } # generic mark hook catch {HMmark $not$tag $win $param text} err # do any special tag processing catch {HMtag_$not$tag $win $param text} msg # add the text with proper tags set tags [HMcurrent_tags $win] $win insert $var(S_insert) $text $tags # We need to do an update every so often to insure interactive response. # This can cause us to re-enter the event loop, and cause recursive # invocations of HMrender, so we need to be careful. if {!([incr var(tags)] % $var(S_update))} { update } } # html tags requiring special processing # Procs of the form HMtag_ or HMtag_ get called just before # the text for this tag is displayed. These procs are called inside a # "catch" so it is OK to fail. # win: The name of the text widget to render into # param: The un-interpreted parameter list # text: A pass-by-reference name of the plain text until the next html tag # Tag commands may change this to affect what text will be inserted # next. # A pair of pseudo tags are added automatically as the 1st and last html # tags in the document. The default is and . # Append enough blank space at the end of the text widget while # rendering so HMgoto can place the target near the top of the page, # then remove the extra space when done rendering. proc HMtag_hmstart {win param text} { upvar #0 HM$win var $win mark gravity $var(S_insert) left $win insert end "\n " last $win mark gravity $var(S_insert) right } proc HMtag_/hmstart {win param text} { $win delete last.first end } # put the document title in the window banner, and remove the title text # from the document proc HMtag_title {win param text} { upvar $text data wm title [winfo toplevel $win] $data set data "" } proc HMtag_hr {win param text} { upvar #0 HM$win var $win insert $var(S_insert) "\n" space "\n" thin "\t" "thin hr" "\n" thin } # list element tags proc HMtag_ol {win param text} { upvar #0 HM$win var set var(count$var(level)) 0 } proc HMtag_ul {win param text} { upvar #0 HM$win var catch {unset var(count$var(level))} } proc HMtag_menu {win param text} { upvar #0 HM$win var set var(menu) -> set var(compact) 1 } proc HMtag_/menu {win param text} { upvar #0 HM$win var catch {unset var(menu)} catch {unset var(compact)} } proc HMtag_dt {win param text} { upvar #0 HM$win var upvar $text data set level $var(level) incr level -1 $win insert $var(S_insert) "$data" \ "hi [lindex $var(list) end] indent$level $var(font)" set data {} } proc HMtag_li {win param text} { upvar #0 HM$win var set level $var(level) incr level -1 set x [string index $var(S_symbols)+-+-+-+-" $level] catch {set x [incr var(count$level)]} catch {set x $var(menu)} $win insert $var(S_insert) \t$x\t "mark [lindex $var(list) end] indent$level $var(font)" } # Manage hypertext "anchor" links. A link can be either a source (href) # a destination (name) or both. If its a source, register it via a callback, # and set its default behavior. If its a destination, check to see if we need # to go there now, as a result of a previous HMgoto request. If so, schedule # it to happen with the closing tag, so we can highlight the text up to # the . proc HMtag_a {win param text} { upvar #0 HM$win var # a source if {[HMextract_param $param href]} { set var(Tref) [list L:$href] HMstack $win "" "Tlink link" HMlink_setup $win $href } # a destination if {[HMextract_param $param name]} { set var(Tname) [list N:$name] HMstack $win "" "Tanchor anchor" $win mark set N:$name "$var(S_insert) - 1 chars" $win mark gravity N:$name left if {[info exists var(goto)] && $var(goto) == $name} { unset var(goto) set var(going) $name } } } # The application should call here with the fragment name # to cause the display to go to this spot. # If the target exists, go there (and do the callback), # otherwise schedule the goto to happen when we see the reference. proc HMgoto {win where {callback HMwent_to}} { upvar #0 HM$win var if {[regexp N:$where [$win mark names]]} { $win see N:$where update eval $callback $win [list $where] return 1 } else { set var(goto) $where return 0 } } # We actually got to the spot, so highlight it! # This should/could be replaced by the application # We'll flash it orange a couple of times. proc HMwent_to {win where {count 0} {color orange}} { upvar #0 HM$win var if {$count > 5} return catch {$win tag configure N:$where -foreground $color} update after 200 [list HMwent_to $win $where [incr count] \ [expr {$color=="orange" ? "" : "orange"}]] } proc HMtag_/a {win param text} { upvar #0 HM$win var if {[info exists var(Tref)]} { unset var(Tref) HMstack $win / "Tlink link" } # goto this link, then invoke the call-back. if {[info exists var(going)]} { $win yview N:$var(going) update HMwent_to $win $var(going) unset var(going) } if {[info exists var(Tname)]} { unset var(Tname) HMstack $win / "Tanchor anchor" } } # Inline Images # This interface is subject to change # Most of the work is getting around a limitation of TK that prevents # setting the size of a label to a widthxheight in pixels # # Images have the following parameters: # align: top,middle,bottom # alt: alternate text # ismap: A clickable image map # src: The URL link # Netscape supports (and so do we) # width: A width hint (in pixels) # height: A height hint (in pixels) # border: The size of the window border proc HMtag_img {win param text} { upvar #0 HM$win var # get alignment array set align_map {top top middle center bottom bottom} set align bottom ;# The spec isn't clear what the default should be HMextract_param $param align catch {set align $align_map([string tolower $align])} # get alternate text set alt "" HMextract_param $param alt set alt [HMmap_esc $alt] # get the border width set border 1 HMextract_param $param border # see if we have an image size hint # If so, make a frame the "hint" size to put the label in # otherwise just make the label set item $win.$var(tags) # catch {destroy $item} if {[HMextract_param $param width] && [HMextract_param $param height]} { frame $item -width $width -height $height pack propagate $item 0 set label $item.label label $label pack $label -expand 1 -fill both } else { set label $item label $label } $label configure -relief ridge -fg orange -text $alt catch {$label configure -bd $border} $win window create $var(S_insert) -align $align -window $item -pady 2 -padx 2 # add in all the current tags (this is overkill) set tags [HMcurrent_tags $win] foreach tag $tags { $win tag add $tag $item } # set imagemap callbacks if {[HMextract_param $param ismap]} { # regsub -all {[^L]*L:([^ ]*).*} $tags {\1} link set link [lindex $tags [lsearch -glob $tags L:*]] regsub L: $link {} link global HMevents regsub -all {%} $link {%%} link2 foreach i [array names HMevents] { bind $label <$i> "catch \{%W configure $HMevents($i)\}" } bind $label <1> "+HMlink_callback $win $link2?%x,%y" } # now callback to the application set src "" HMextract_param $param src HMset_image $win $label $src return $label ;# used by the forms package for input_image types } # The app needs to supply one of these proc HMset_image {win handle src} { HMgot_image $handle "can't get\n$src" } # When the image is available, the application should call back here. # If we have the image, put it in the label, otherwise display the error # message. If we don't get a callback, the "alt" text remains. # if we have a clickable image, arrange for a callback proc HMgot_image {win image_error} { # if we're in a frame turn on geometry propogation if {[winfo name $win] == "label"} { pack propagate [winfo parent $win] 1 } if {[catch {$win configure -image $image_error}]} { $win configure -image {} $win configure -text $image_error } } # Sample hypertext link callback routine - should be replaced by app # This proc is called once for each tag. # Applications can overwrite this procedure, as required, or # replace the HMevents array # win: The name of the text widget to render into # href: The HREF link for this tag. array set HMevents { Enter {-borderwidth 2 -relief raised } Leave {-borderwidth 2 -relief flat } 1 {-borderwidth 2 -relief sunken} ButtonRelease-1 {-borderwidth 2 -relief raised} } # We need to escape any %'s in the href tag name so the bind command # doesn't try to substitute them. proc HMlink_setup {win href} { global HMevents regsub -all {%} $href {%%} href2 foreach i [array names HMevents] { eval {$win tag bind L:$href <$i>} \ \{$win tag configure \{L:$href2\} $HMevents($i)\} } } # generic link-hit callback # This gets called upon button hits on hypertext links # Applications are expected to supply ther own HMlink_callback routine # win: The name of the text widget to render into # x,y: The cursor position at the "click" proc HMlink_hit {win x y} { set tags [$win tag names @$x,$y] set link [lindex $tags [lsearch -glob $tags L:*]] # regsub -all {[^L]*L:([^ ]*).*} $tags {\1} link regsub L: $link {} link HMlink_callback $win $link } # replace this! # win: The name of the text widget to render into # href: The HREF link for this tag. proc HMlink_callback {win href} { puts "Got hit on $win, link $href" } # extract a value from parameter list (this needs a re-do) # returns "1" if the keyword is found, "0" otherwise # param: A parameter list. It should alredy have been processed to # remove any entity references # key: The parameter name # val: The variable to put the value into (use key as default) proc HMextract_param {param key {val ""}} { if {$val == ""} { upvar $key result } else { upvar $val result } set ws " \n\r" # look for name=value combinations. Either (') or (") are valid delimeters if { [regsub -nocase [format {.*%s[%s]*=[%s]*"([^"]*).*} $key $ws $ws] $param {\1} value] || [regsub -nocase [format {.*%s[%s]*=[%s]*'([^']*).*} $key $ws $ws] $param {\1} value] || [regsub -nocase [format {.*%s[%s]*=[%s]*([^%s]+).*} $key $ws $ws $ws] $param {\1} value] } { set result $value return 1 } # now look for valueless names # I should strip out name=value pairs, so we don't end up with "name" # inside the "value" part of some other key word - some day set bad \[^a-zA-Z\]+ if {[regexp -nocase "$bad$key$bad" -$param-]} { return 1 } else { return 0 } } # These next two routines manage the display state of the page. # Push or pop tags to/from stack. # Each orthogonal text property has its own stack, stored as a list. # The current (most recent) tag is the last item on the list. # Push is {} for pushing and {/} for popping proc HMstack {win push list} { upvar #0 HM$win var array set tags $list if {$push == ""} { foreach tag [array names tags] { lappend var($tag) $tags($tag) } } else { foreach tag [array names tags] { # set cnt [regsub { *[^ ]+$} $var($tag) {} var($tag)] set var($tag) [lreplace $var($tag) end end] } } } # extract set of current text tags # tags starting with T map directly to text tags, all others are # handled specially. There is an application callback, HMset_font # to allow the application to do font error handling proc HMcurrent_tags {win} { upvar #0 HM$win var set font font foreach i {family size weight style} { set $i [lindex $var($i) end] append font :[set $i] } set xfont [HMx_font $family $size $weight $style $var(S_adjust_size)] HMset_font $win $font $xfont set indent [llength $var(indent)] incr indent -1 lappend tags $font indent$indent foreach tag [array names var T*] { lappend tags [lindex $var($tag) end] ;# test } set var(font) $font set var(xfont) [$win tag cget $font -font] set var(level) $indent return $tags } # allow the application to do do better font management # by overriding this procedure proc HMset_font {win tag font} { catch {$win tag configure $tag -font $font} msg } # generate an X font name proc HMx_font {family size weight style {adjust_size 0}} { catch {incr size $adjust_size} return "-*-$family-$weight-$style-normal-*-*-${size}0-*-*-*-*-*-*" } # Optimize HMrender (hee hee) # This is experimental proc HMoptimize {} { regsub -all "\n\[ \]*#\[^\n\]*" [info body HMrender] {} body regsub -all ";\[ \]*#\[^\n]*" $body {} body regsub -all "\n\n+" $body \n body proc HMrender {win tag not param text} $body } ############################################ # Turn HTML into TCL commands # html A string containing an html document # cmd A command to run for each html tag found # start The name of the dummy html start/stop tags proc HMparse_html {html {cmd HMtest_parse} {start hmstart}} { regsub -all \{ $html {\&ob;} html regsub -all \} $html {\&cb;} html set w " \t\r\n" ;# white space proc HMcl x {return "\[$x\]"} set exp <(/?)([HMcl ^$w>]+)[HMcl $w]*([HMcl ^>]*)> set sub "\}\n$cmd {\\2} {\\1} {\\3} \{" regsub -all $exp $html $sub html eval "$cmd {$start} {} {} \{ $html \}" eval "$cmd {$start} / {} {}" } proc HMtest_parse {command tag slash text_after_tag} { puts "==> $command $tag $slash $text_after_tag" } # Convert multiple white space into a single space proc HMzap_white {data} { regsub -all "\[ \t\r\n\]+" $data " " data return $data } # find HTML escape characters of the form &xxx; proc HMmap_esc {text} { if {![regexp & $text]} {return $text} regsub -all {([][$\\])} $text {\\\1} new regsub -all {&#([0-9][0-9]?[0-9]?);?} \ $new {[format %c [scan \1 %d tmp;set tmp]]} new regsub -all {&([a-zA-Z]+);?} $new {[HMdo_map \1]} new return [subst $new] } # convert an HTML escape sequence into character proc HMdo_map {text {unknown ?}} { global HMesc_map set result $unknown catch {set result $HMesc_map($text)} return $result } # table of escape characters (ISO latin-1 esc's are in a different table) array set HMesc_map { lt < gt > amp & quot \" copy \xa9 reg \xae ob \x7b cb \x7d nbsp \xa0 } ############################################################# # ISO Latin-1 escape codes array set HMesc_map { nbsp \xa0 iexcl \xa1 cent \xa2 pound \xa3 curren \xa4 yen \xa5 brvbar \xa6 sect \xa7 uml \xa8 copy \xa9 ordf \xaa laquo \xab not \xac shy \xad reg \xae hibar \xaf deg \xb0 plusmn \xb1 sup2 \xb2 sup3 \xb3 acute \xb4 micro \xb5 para \xb6 middot \xb7 cedil \xb8 sup1 \xb9 ordm \xba raquo \xbb frac14 \xbc frac12 \xbd frac34 \xbe iquest \xbf Agrave \xc0 Aacute \xc1 Acirc \xc2 Atilde \xc3 Auml \xc4 Aring \xc5 AElig \xc6 Ccedil \xc7 Egrave \xc8 Eacute \xc9 Ecirc \xca Euml \xcb Igrave \xcc Iacute \xcd Icirc \xce Iuml \xcf ETH \xd0 Ntilde \xd1 Ograve \xd2 Oacute \xd3 Ocirc \xd4 Otilde \xd5 Ouml \xd6 times \xd7 Oslash \xd8 Ugrave \xd9 Uacute \xda Ucirc \xdb Uuml \xdc Yacute \xdd THORN \xde szlig \xdf agrave \xe0 aacute \xe1 acirc \xe2 atilde \xe3 auml \xe4 aring \xe5 aelig \xe6 ccedil \xe7 egrave \xe8 eacute \xe9 ecirc \xea euml \xeb igrave \xec iacute \xed icirc \xee iuml \xef eth \xf0 ntilde \xf1 ograve \xf2 oacute \xf3 ocirc \xf4 otilde \xf5 ouml \xf6 divide \xf7 oslash \xf8 ugrave \xf9 uacute \xfa ucirc \xfb uuml \xfc yacute \xfd thorn \xfe yuml \xff } ########################################################## # html forms management commands # As each form element is located, it is created and rendered. Additional # state is stored in a form specific global variable to be processed at # the end of the form, including the "reset" and "submit" options. # Remember, there can be multiple forms existing on multiple pages. When # HTML tables are added, a single form could be spread out over multiple # text widgets, which makes it impractical to hang the form state off the # HM$win structure. We don't need to check for the existance of required # parameters, we just "fail" and get caught in HMrender # This causes line breaks to be preserved in the inital values # of text areas array set HMtag_map { textarea {fill 0} } ########################################################## # html isindex tag. Although not strictly forms, they're close enough # to be in this file # is-index forms # make a frame with a label, entry, and submit button proc HMtag_isindex {win param text} { upvar #0 HM$win var set item $win.$var(tags) if {[winfo exists $item]} { destroy $item } frame $item -relief ridge -bd 3 set prompt "Enter search keywords here" HMextract_param $param prompt label $item.label -text [HMmap_esc $prompt] -font $var(xfont) entry $item.entry bind $item.entry "$item.submit invoke" button $item.submit -text search -font $var(xfont) -command \ [format {HMsubmit_index %s {%s} [HMmap_reply [%s get]]} \ $win $param $item.entry] pack $item.label -side top pack $item.entry $item.submit -side left # insert window into text widget $win insert $var(S_insert) \n isindex HMwin_install $win $item $win insert $var(S_insert) \n isindex bind $item {focus %W.entry} } # This is called when the isindex form is submitted. # The default version calls HMlink_callback. Isindex tags should either # be deprecated, or fully supported (e.g. they need an href parameter) proc HMsubmit_index {win param text} { HMlink_callback $win ?$text } # initialize form state. All of the state for this form is kept # in a global array whose name is stored in the form_id field of # the main window array. # Parameters: ACTION, METHOD, ENCTYPE proc HMtag_form {win param text} { upvar #0 HM$win var # create a global array for the form set id HM$win.form$var(tags) upvar #0 $id form # missing /form tag, simulate it if {[info exists var(form_id)]} { puts "Missing end-form tag !!!! $var(form_id)" HMtag_/form $win {} {} } catch {unset form} set var(form_id) $id set form(param) $param ;# form initial parameter list set form(reset) "" ;# command to reset the form set form(reset_button) "" ;# list of all reset buttons set form(submit) "" ;# command to submit the form set form(submit_button) "" ;# list of all submit buttons } # Where we're done try to get all of the state into the widgets so # we can free up the form structure here. Unfortunately, we can't! proc HMtag_/form {win param text} { upvar #0 HM$win var upvar #0 $var(form_id) form # make submit button entries for all radio buttons foreach name [array names form radio_*] { regsub radio_ $name {} name lappend form(submit) [list $name \$form(radio_$name)] } # process the reset button(s) foreach item $form(reset_button) { $item configure -command $form(reset) } # no submit button - add one if {$form(submit_button) == ""} { HMinput_submit $win {} } # process the "submit" command(s) # each submit button could have its own name,value pair foreach item $form(submit_button) { set submit $form(submit) catch {lappend submit $form(submit_$item)} $item configure -command \ [list HMsubmit_button $win $var(form_id) $form(param) \ $submit] } # unset all unused fields here unset form(reset) form(submit) form(reset_button) form(submit_button) unset var(form_id) } ################################################################### # handle form input items # each item type is handled in a separate procedure # Each "type" procedure needs to: # - create the window # - initialize it # - add the "submit" and "reset" commands onto the proper Q's # "submit" is subst'd # "reset" is eval'd proc HMtag_input {win param text} { upvar #0 HM$win var set type text ;# the default HMextract_param $param type set type [string tolower $type] if {[catch {HMinput_$type $win $param} err]} { puts stderr $err } } # input type=text # parameters NAME (reqd), MAXLENGTH, SIZE, VALUE proc HMinput_text {win param {show {}}} { upvar #0 HM$win var upvar #0 $var(form_id) form # make the entry HMextract_param $param name ;# required set item $win.input_text,$var(tags) set size 20; HMextract_param $param size set maxlength 0; HMextract_param $param maxlength entry $item -width $size -show $show # set the initial value set value ""; HMextract_param $param value $item insert 0 $value # insert the entry HMwin_install $win $item # set the "reset" and "submit" commands append form(reset) ";$item delete 0 end;$item insert 0 [list $value]" lappend form(submit) [list $name "\[$item get]"] # handle the maximum length (broken - no way to cleanup bindtags state) if {$maxlength} { bindtags $item "[bindtags $item] max$maxlength" bind max$maxlength "%W delete $maxlength end" } } # password fields - same as text, only don't show data # parameters NAME (reqd), MAXLENGTH, SIZE, VALUE proc HMinput_password {win param} { HMinput_text $win $param * } # checkbuttons are missing a "get" option, so we must use a global # variable to store the value. # Parameters NAME, VALUE, (reqd), CHECKED proc HMinput_checkbox {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name HMextract_param $param value # Set the global variable, don't use the "form" alias as it is not # defined in the global scope of the button set variable $var(form_id)(check_$var(tags)) set item $win.input_checkbutton,$var(tags) checkbutton $item -variable $variable -off {} -on $value -text " " if {[HMextract_param $param checked]} { $item select append form(reset) ";$item select" } else { append form(reset) ";$item deselect" } HMwin_install $win $item lappend form(submit) [list $name \$form(check_$var(tags))] } # radio buttons. These are like check buttons, but only one can be selected proc HMinput_radio {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name HMextract_param $param value set first [expr ![info exists form(radio_$name)]] set variable $var(form_id)(radio_$name) set variable $var(form_id)(radio_$name) set item $win.input_radiobutton,$var(tags) radiobutton $item -variable $variable -value $value -text " " HMwin_install $win $item if {$first || [HMextract_param $param checked]} { $item select append form(reset) ";$item select" } else { append form(reset) ";$item deselect" } # do the "submit" actions in /form so we only end up with 1 per button grouping # contributing to the submission } # hidden fields, just append to the "submit" data # params: NAME, VALUE (reqd) proc HMinput_hidden {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name HMextract_param $param value lappend form(submit) [list $name $value] } # handle input images. The spec isn't very clear on these, so I'm not # sure its quite right # Use std image tag, only set up our own callbacks # (e.g. make sure ismap isn't set) # params: NAME, SRC (reqd) ALIGN proc HMinput_image {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name set name ;# barf if no name is specified set item [HMtag_img $win $param {}] $item configure -relief raised -bd 2 -bg blue # make a dummy "submit" button, and invoke it to send the form. # We have to get the %x,%y in the value somehow, so calculate it during # binding, and save it in the form array for later processing set submit $win.dummy_submit,$var(tags) if {[winfo exists $submit]} { destroy $submit } button $submit -takefocus 0;# this never gets mapped! lappend form(submit_button) $submit set form(submit_$submit) [list $name $name.\$form(X).\$form(Y)] $item configure -takefocus 1 bind $item "catch \{$win see $item\}" bind $item <1> "$item configure -relief sunken" bind $item " set $var(form_id)(X) 0 set $var(form_id)(Y) 0 $submit invoke " bind $item " set $var(form_id)(X) %x set $var(form_id)(Y) %y $item configure -relief raised $submit invoke " } # Set up the reset button. Wait for the /form to attach # the -command option. There could be more that 1 reset button # params VALUE proc HMinput_reset {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form set value reset HMextract_param $param value set item $win.input_reset,$var(tags) button $item -text [HMmap_esc $value] HMwin_install $win $item lappend form(reset_button) $item } # Set up the submit button. Wait for the /form to attach # the -command option. There could be more that 1 submit button # params: NAME, VALUE proc HMinput_submit {win param} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name set value submit HMextract_param $param value set item $win.input_submit,$var(tags) button $item -text [HMmap_esc $value] -fg blue HMwin_install $win $item lappend form(submit_button) $item # need to tie the "name=value" to this button # save the pair and do it when we finish the submit button catch {set form(submit_$item) [list $name $value]} } ######################################################################### # selection items # They all go into a list box. We don't what to do with the listbox until # we know how many items end up in it. Gather up the data for the "options" # and finish up in the /select tag # params: NAME (reqd), MULTIPLE, SIZE proc HMtag_select {win param text} { upvar #0 HM$win var upvar #0 $var(form_id) form HMextract_param $param name set size 5; HMextract_param $param size set form(select_size) $size set form(select_name) $name set form(select_values) "" ;# list of values to submit if {[HMextract_param $param multiple]} { set mode multiple } else { set mode single } set item $win.select,$var(tags) frame $item set form(select_frame) $item listbox $item.list -selectmode $mode -width 0 -exportselection 0 HMwin_install $win $item } # select options # The values returned in the query may be different from those # displayed in the listbox, so we need to keep a separate list of # query values. # form(select_default) - contains the default query value # form(select_frame) - name of the listbox's containing frame # form(select_values) - list of query values # params: VALUE, SELECTED proc HMtag_option {win param text} { upvar #0 HM$win var upvar #0 $var(form_id) form upvar $text data set frame $form(select_frame) # set default option (or options) if {[HMextract_param $param selected]} { lappend form(select_default) [$form(select_frame).list size] } set value [string trimright $data " \n"] $frame.list insert end $value HMextract_param $param value lappend form(select_values) $value set data "" } # do most of the work here! # if SIZE>1, make the listbox. Otherwise make a "drop-down" # listbox with a label in it # If the # of items > size, add a scroll bar # This should probably be broken up into callbacks to make it # easier to override the "look". proc HMtag_/select {win param text} { upvar #0 HM$win var upvar #0 $var(form_id) form set frame $form(select_frame) set size $form(select_size) set items [$frame.list size] # set the defaults and reset button append form(reset) ";$frame.list selection clear 0 $items" if {[info exists form(select_default)]} { foreach i $form(select_default) { $frame.list selection set $i append form(reset) ";$frame.list selection set $i" } } else { $frame.list selection set 0 append form(reset) ";$frame.list selection set 0" } # set up the submit button. This is the general case. For single # selections we could be smarter for {set i 0} {$i < $size} {incr i} { set value [format {[expr {[%s selection includes %s] ? {%s} : {}}]} \ $frame.list $i [lindex $form(select_values) $i]] lappend form(submit) [list $form(select_name) $value] } # show the listbox - no scroll bar if {$size > 1 && $items <= $size} { $frame.list configure -height $items pack $frame.list # Listbox with scrollbar } elseif {$size > 1} { scrollbar $frame.scroll -command "$frame.list yview" \ -orient v -takefocus 0 $frame.list configure -height $size \ -yscrollcommand "$frame.scroll set" pack $frame.list $frame.scroll -side right -fill y # This is a joke! } else { scrollbar $frame.scroll -command "$frame.list yview" \ -orient h -takefocus 0 $frame.list configure -height 1 \ -yscrollcommand "$frame.scroll set" pack $frame.list $frame.scroll -side top -fill x } # cleanup foreach i [array names form select_*] { unset form($i) } } # do a text area (multi-line text) # params: COLS, NAME, ROWS (all reqd, but default rows and cols anyway) proc HMtag_textarea {win param text} { upvar #0 HM$win var upvar #0 $var(form_id) form upvar $text data set rows 5; HMextract_param $param rows set cols 30; HMextract_param $param cols HMextract_param $param name set item $win.textarea,$var(tags) frame $item text $item.text -width $cols -height $rows -wrap none \ -yscrollcommand "$item.scroll set" -padx 3 -pady 3 scrollbar $item.scroll -command "$item.text yview" -orient v $item.text insert 1.0 $data HMwin_install $win $item pack $item.text $item.scroll -side right -fill y lappend form(submit) [list $name "\[$item.text get 0.0 end]"] append form(reset) ";$item.text delete 1.0 end; \ $item.text insert 1.0 [list $data]" set data "" } # procedure to install windows into the text widget # - win: name of the text widget # - item: name of widget to install proc HMwin_install {win item} { upvar #0 HM$win var $win window create $var(S_insert) -window $item -align bottom $win tag add indent$var(level) $item set focus [expr {[winfo class $item] != "Frame"}] $item configure -takefocus $focus bind $item "$win see $item" } ##################################################################### # Assemble and submit the query # each list element in "stuff" is a name/value pair # - The names are the NAME parameters of the various fields # - The values get run through "subst" to extract the values # - We do the user callback with the list of name value pairs proc HMsubmit_button {win form_id param stuff} { upvar #0 HM$win var upvar #0 $form_id form set query "" foreach pair $stuff { set value [subst [lindex $pair 1]] if {$value != ""} { set item [lindex $pair 0] lappend query $item $value } } # this is the user callback. HMsubmit_form $win $param $query } # sample user callback for form submission # should be replaced by the application # Sample version generates a string suitable for http proc HMsubmit_form {win param query} { set result "" set sep "" foreach i $query { append result $sep [HMmap_reply $i] if {$sep != "="} {set sep =} {set sep &} } puts $result } # do x-www-urlencoded character mapping # The spec says: "non-alphanumeric characters are replaced by '%HH'" set HMalphanumeric a-zA-Z0-9 ;# definition of alphanumeric character class for {set i 1} {$i <= 256} {incr i} { set c [format %c $i] if {![string match \[$HMalphanumeric\] $c]} { set HMform_map($c) %[format %.2x $i] } } # These are handled specially array set HMform_map { " " + \n %0d%0a } # 1 leave alphanumerics characters alone # 2 Convert every other character to an array lookup # 3 Escape constructs that are "special" to the tcl parser # 4 "subst" the result, doing all the array substitutions proc HMmap_reply {string} { global HMform_map HMalphanumeric regsub -all \[^$HMalphanumeric\] $string {$HMform_map(&)} string regsub -all \n $string {\\n} string regsub -all \t $string {\\t} string regsub -all {[][{})\\]\)} $string {\\&} string return [subst $string] } # convert a x-www-urlencoded string int a a list of name/value pairs # 1 convert a=b&c=d... to {a} {b} {c} {d}... # 2, convert + to " " # 3, convert %xx to char equiv proc HMcgiDecode {data} { set data [split $data "&="] foreach i $data { lappend result [cgiMap $i] } return $result } proc HMcgiMap {data} { regsub -all {\+} $data " " data if {[regexp % $data]} { regsub -all {([][$\\])} $data {\\\1} data regsub -all {%([0-9a-fA-F][0-9a-fA-F])} $data {[format %c 0x\1]} data return [subst $data] } else { return $data } } # There is a bug in the tcl library focus routines that prevents focus # from every reaching an un-viewable window. Use our *own* # version of the library routine, until the bug is fixed, make sure we # over-ride the library version, and not the otherway around auto_load tkFocusOK proc tkFocusOK w { set code [catch {$w cget -takefocus} value] if {($code == 0) && ($value != "")} { if {$value == 0} { return 0 } elseif {$value == 1} { return 1 } else { set value [uplevel #0 $value $w] if {$value != ""} { return $value } } } set code [catch {$w cget -state} value] if {($code == 0) && ($value == "disabled")} { return 0 } regexp Key|Focus "[bind $w] [bind [winfo class $w]]" } igraph/inst/igraph.gif0000644000175100001440000000376113177712334014477 0ustar hornikusersGIF89a––öî õòð çéçäÞ&%Ý('Ú,+×0/Î=<Ó65Ð:9à!!Ì@?¿TT·__»ZZ­nn¶bb°ii­po§wv¨ut£}|ÊDCÅKKÀQQêÝüîõçöè øê ÿðîáíàòåÞÓ.×Í7ÙÎ4ÒÇ>ÔÊ;ÜÑ0ã×&åÙ#èÛ áÖ)¼µ[¿¸X£Ÿ~¯©oµ¯f²«k·°d¹²a¬¦s®¨p¦¡z¨£xǾMÈ¿LºTÎÄDÊÁIÐÇ@ž……—š‹‹žš†—”™–Œœ™ˆ•’’¡€€¡œ!ùM,––þ€M‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌJÏÐÍÁÐÔÔÒ•ÕÕœÙÜJ×ÝÜ™Ü;4IÙߌáë—Ô3'"#ò$?ÚéˆëùØÐ?òÿò\0±v¯P¾ƒÞ"Q«°á §ȉ-Rü˜Ná³$ 6ìñ^·&DŽp¡C¸g=TQ2]6&dþâÒ4:ÿíˆV0ÛŽAå±è¹ˆZʤ1ˆš¤†„DR€BÐ5¢f5é ©ß²­¸ÚІ½­ÏP\ø¬(µþþÈþƒx¶é³IAÔ”VM…܆-÷â{v¤DP‚—eCúWÏƨåˆ+r)ØkÕ˜4H÷²"j:ºüäˆg¾’7ÿ3¡í3$=`ˆøPEŽºa©ÙP-&îÏÜ0µù–÷¿Õ”8‘Zã0’+ïÆ|P¶¼ëAND½ºAjx7`{Ún[!a,EkŸåÑ7É&£±òç_æO¶==´±d}PÃ{ðíW ;Bs„ZI}•tÀ8 BÎdóC<2‘p®%t`6 Ç]6Fñg2t§Ÿ‡ÄT³Ã | ‚ @œßwÝðPƒ 1Ø€„²8!4=P¶šY7þ‚‚’ô· 5~É„¤„#.é¤Ç@CCP&„(¤yVîCå/ÔäTI²dzÓ} ŒzFª]šþ¹¦’têMWù6f“Vv4_ž¹@³[ƒWv(“*ñ\R/$Úæ¢‚ãTRYýéBDÜ™å]A}À‘¦ r£A ½Tðè¬ ˜F´ç$ª‘ èÄÝÄ¥:ƒ rÉFéœ'=•ƒöÈSŸ+R0D »Bc¢¸G„ÖéDrÁCOùÕL©¡}œf6£ÈŒZ‚FP ¥8Ñjh/(Á¨GÙ,¹ˆàœ*])랃Ƭ %­†=“b|ÆT¦Õ09“rÑfÊ´Ž58)@sЕfƒfI úTÓ£šQ A ¨<>Ÿ’ô¨Ý8‚ dЃÜÀ«_µê-­º b²u˜º|k.…)×¶¦µ®xÍ«^÷Ê×¾úõ¯€ ¬`KØÂö°ˆM¬bËØÆ:V¦;igraph/inst/tkigraph_help/0000755000175100001440000000000013177712334015350 5ustar hornikusersigraph/inst/tkigraph_help/style.css0000644000175100001440000002111313177712334017220 0ustar hornikusers body { font: medium/150% "Lucida Grande", sans-serif; margin: 0; padding: 0 0 10px; color: #333; background: #fff; } a img { border: 0; } h1 { color: #fff; margin: 0; height: 40px; line-height: 40px; text-shadow: 0px 1px 2px #000; background: #1872ce url(images/header_blue.png) repeat-x; border-top: 1px solid #1872ce; border-bottom: 1px solid #1c477f; font-size: large; padding-left: 10px; } h2 { font-size: 1.5em; text-indent: -40px; } h2.th { font-size: 1.5em; text-indent: 0px; } h3 { font-size: 1em; text-indent: -20px; } h4 { font-size: 0.8em; } body.error h1 { background: #d70000; border-bottom: 1px solid #7f0000; } hr { color: #888; background-color: #888; height: 1px; width: 100%; border: 0; } code { font-size: 1.2em; } img.float_right { float: right } img.float_left { float: left } pre.condensed { font-size: 0.8em; line-height: 1.5em; } .igraphlogo { float: right; padding-left: 40px; padding-right: 40px; padding-top:30px; } div.main { max-width:900px; padding-left: 50px; padding-bottom: 50px; margin-right: 0; } .more { text-align: right; margin-top: -1em; } .back { text-align: left; } ul.no-bullet { list-style-type: none; padding: 0; margin: 0; } ul.no-bullet li { padding: 0; margin: 0; } li.download { line-height: 1em; padding-bottom: 10px !important; } li.download .name { font-weight: bold; padding-left: 20px; } li.download span.comment { font-size: 0.8em; color: #888; } li.download div.comment { font-size: 0.8em; padding: 4px 0px 0px 20px; } p.comment { font-size: 0.8em; color: #888; } div.image_caption { font-size: 0.8em; color: #888; text-align: center; } li.download-c { background: url(images/icon_c.png) no-repeat 0px 0px; } li.download-sf { background: url(images/icon_sf.png) no-repeat 0px 0px; } li.download-r { background: url(images/icon_r.png) no-repeat 0px 0px; } li.download-python { background: url(images/icon_python.png) no-repeat 0px 0px; } li.download-ruby { background: url(images/icon_ruby.png) no-repeat 0px 0px; } li.download-doc { background: url(images/icon_documentation.png) no-repeat 0px 0px; } li.download-wiki { background: url(images/icon_wiki.png) no-repeat 0px 0px; } ul.download-links { list-style-type: none; padding: 2px 0 0 20px; margin: 0; font-size: 0.8em; } ul.download-links li { padding: 0px 10px 0px 0px; margin: 0; padding-bottom: 5px !important; } ul.download-links li.download-source { background: url(images/icon_source.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-sf { background: url(images/icon_sf.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-windows { background: url(images/icon_windows.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-debian { background: url(images/icon_debian.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-osx { background: url(images/icon_osx.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-html { background: url(images/icon_html.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-external { background: url(images/icon_links.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-wiki { background: url(images/icon_wiki.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-pdf { background: url(images/icon_pdf.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-html { background: url(images/icon_html.png) no-repeat 0px 0px; padding-left: 18px; } ul.download-links li.download-info { background: url(images/icon_info.png) no-repeat 0px 0px; padding-left: 18px; } a { color: #00f; text-decoration: none } a:visited { color: #00c } a:hover { color: #00f; text-decoration: underline } h1 a, h1 a:visited, h1 a:hover { color: #fff; text-decoration: none } h2 a, h2 a:visited, h2 a:hover { color: #000; text-decoration: none } h3 a, h3 a:visited, h3 a:hover { color: #000; text-decoration: none } #sourceforge_logo { float: right; padding: 3px 15px 0px 0px; } /* Menu items */ ul.menu { list-style-type: none; padding: 0; margin: 0; } ul.menu-upper { list-style-type: none; padding: 0px 0px 0px 15px; margin: 0; margin-top: 10px; width: 95%; border-bottom: 1px solid; text-align: left; } ul.menu li { padding: 0px 10px 10px 20px; margin: 0px; } ul.menu-upper li { padding: 8px 10px 4px 25px; font-size: 0.8em; border: solid; border-width: 1px 1px 1px 1px; margin: 0px 0px 0px 0px; display: inline; } ul.menu-upper li:hover { border-top: solid 2px #0000ff; border-left: solid 2px #0000ff; border-right: solid 2px #0000ff; } ul li.item-introduction { background: #dadaff url(images/icon_info.png) no-repeat 5px 6px; } ul li.item-download { background: #dadaff url(images/icon_download.png) no-repeat 5px 6px; } ul li.item-news { background: #dadaff url(images/icon_news.png) no-repeat 5px 6px; } ul li.item-documentation { background: #dadaff url(images/icon_documentation.png) no-repeat 5px 6px; } ul li.item-wiki { background: #dadaff url(images/icon_wiki.png) no-repeat 5px 6px; } ul li.item-screenshots { background: #dadaff url(images/icon_screenshots.png) no-repeat 5px 6px; } ul li.item-community { background: #dadaff url(images/icon_community.png) no-repeat 5px 6px; } ul li.item-bug { background: #dadaff url(images/icon_bug.png) no-repeat 5px 6px; } ul li.item-links { background: #dadaff url(images/icon_links.png) no-repeat 5px 6px; } ul li.item-license { background: #dadaff url(images/icon_license.png) no-repeat 5px 6px; } body#index li#n-index { background: #ffffff url(images/icon_info.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#news li#n-news { background: #ffffff url(images/icon_news.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#download li#n-download{ background: #ffffff url(images/icon_download.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#documentation li#n-documentation{ background: #ffffff url(images/icon_documentation.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#screenshots li#n-screenshots{ background: #ffffff url(images/icon_screenshots.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#support li#n-support{ background: #ffffff url(images/icon_community.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#bugs li#n-bugs{ background: #ffffff url(images/icon_bug.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } body#license li#n-license { background: #ffffff url(images/icon_license.png) no-repeat 5px 6px; border-bottom: 1px solid #ffffff; } /* Forms */ label { display: block; float: left; width: 130px; font-weight: bold; } label.normal { color: #444; } div.explanation { border-left: 130px solid white; font-size: 0.8em; color: #888; } .programlisting { background: #eeeeff; border: solid 1px #4444ff; padding: 0.5em; } p.news { padding: 0px 40px 0px; } h4.news { padding: 0px 40px 0px; } ul.newslist { padding: 0px 60px 0px; } table.intro td { vertical-align: top; width: 33.3%; padding: 20px; } div.feed { width: 100%; padding: 20px; } div.feedburnerFeedBlock p.feedTitle { font-size: 1em; } div.feedburnerFeedBlock a { color: black; } div.feedburnerFeedBlock ul a { color: #00f; text-decoration: none } div.feedburnerFeedBlock { font-size: 1em; } div.feedburnerFeedBlock ul { list-style-type: none; } div.feedburnerFeedBlock ul li { margin-top: 10px; } div.feedburnerFeedBlock p.date { font-style: italic; font-size: 0.8em; margin: 5px; } div.feedburnerFeedBlock p.date:before { content: "("; } div.feedburnerFeedBlock p.date:after { content: ")"; } div.feedburnerFeedBlock span, span+p {display:inline} div.feed span.headline { font-size: 1.25em; } #creditfooter { float: right; } div.feedburnerFeedBlock table { table-layout: fixed; width: 100%; } div.quick-menu { position:fixed; bottom:0; width: 100%; } div.quick-menu ul.menu-bottom { padding: 5px; border-top: 1px solid #0000a0; text-align: center; background: #dadaff; } ul.menu-bottom { list-style-type: none; padding: 0px 0px 0px 15px; margin: 0; } ul.menu-bottom li { padding: 8px 10px 10px 25px; font-size: 0.8em; margin: 0px; display: inline; } div.copyright { border-top: 1px solid #8e8e8e; text-align: center; color: #8e8e8e; padding-top: 10px; padding-bottom: 50px; }igraph/inst/tkigraph_help/tkigraph-main.gif0000644000175100001440000003451313177712334020600 0ustar hornikusersGIF89a*çÿ      "#%"'(&*,)-.,0205748:7=>cÅ d„jI ,¨°r¸õëØ³kßν»wÅÂþK0€`y®oæÒ§oæ©Ã¾ËŸO¿¾ýûøG‡WCÂTàŽzëUrÁŸie„à¶5øànRt° I!dÎ×amR ü°à‰¡ƒŒ©Hdµ!£Œœ"L',Ѐ «4Sˆ P0F)‚0ãŒVŒ°Á#Xqä“PF)å”TVie”e¼ðN=BˆÑ4ˆÐÁ˜2°q%•YnÙ%•`ŠI&ʨaœ3±+þD3Ã4Œi¡™g¶‘&—^B9èšr†ð§ Še£^y¨£G6èg&l© Zj%3,ã.?ljꩨJ©ä.¤*å’þ°ÆºA”cŒÉTȸ„­#Œ!%AolÖÛÌ).40€cœ˳E ¬.<¸ ƒ´Üvëí·à†+î¸Ý ç ´ ã?ì8Óä‚k®¼èªË®3;t*œ¡/¼Á–Q„<÷hñEÈôã?à¼ïó–ûoÀZúã aL,±š?nÄÒ¦¹îÂט±…Ç ‡KÆòÄsÅÉÇ,óÌàîºîKÐüí#÷ìÏÞ.‘‰?Ú¨@*hãO&9{ ¬´Ä+µ'ôc6(¡.wÉË^5ò[WѨàKòLVÇ!0ýñoÌÏ !`˜Àb-ÐØÌæ#È®}­8þ€ŠIÎrö’jjÁ8 æ:(ÊsôÇ1vP7ÜB%þ¸>˜!ƒŠõ"²U?ßá^Ô@zéxW&c°N-´ós„:¹ô/Ò!å(˜ê}PøAž€§”TO€\5 pƒZLvöħ>ùYQ; Ó¡ÈÇ&ôÕ<#x‚…v·†Æã¶ôÇNß‘ô´ Uí:Ïäm) ã°ä…,ÊJèIÏ3ÈCLó¹Ï0Ôr%xÛxªR–ºthUkÖ˜ó®x á¬A4aúÃ#È«’Y@Â~iÎd¦ÑDH=8Ö±Ô¬æ5³‰Í>VÝô‡Æ ¢prಠ ­hGKÚÒšö´ ¨ôOŠfÑ¡z˜þ¶§¥vAKûËŠ[ƒý˱ªmíj9¦Úßêá¦ûÂÂ#ÆÈCX0Á Ãn{Àµ¥a sp¿f;¦ÚÞ–cÀee¤á %¤Óºo96‡ð"‘¼7˜†y𺓮<ÖËNtòü¸¤‹Îžéc]Ðw;P[Äà÷àÄJ`‚ˆ ¡ºú¸nvá ›€ ¯jGLâ›ø±#P†5T°.XC#8ñh9àÏ>–Æ6-kûé”¶±—-@)ªiÉRÖ²­–?š¡4Cƒ.±”§lbÕª³¿úÒ—ôP†XÎðZ²ÇÖЩïrÉÂ[ÖCþŠe(rɉYn"p9 [0”  ­P£mÃ<æ2‡Y[Vm¼üG0Ëù¸¬ d>REŸÕÃÐoV°-SQ]°¢¡¨¢P(f2wRËöÇQ·pÙ‰zuz8è²)g($ër‡&V E{Zvx«c­ /Ä®< ²°‡MÚZ€Æ5A¯HËf;»ÙÌ®ñeq<Úâ(­™Dûi Ò‡nw[ÈØ·¸œMDÀÛ}P‘:z¦ŽÍ¢ûÝðŽ·¼çMïzÛûݪU¡úˆP\5áÁgÅ ŠÅüN—µ¬º=‡#ª‚ß §óÈ@W3+¼Û‡À)Ñ?äÀ VhËþâ„+kA¿ Åpº]}©ÓrwóÅû Z,ÃøàRuï‘?}À ø9ÔQE>äƒu­~O~pßôÓë¼Ü2¿\à?3 Và…Wàc½:·.ˇ­wýë=ƒ-qyï¶»ýíp‡7²9`od÷ŒîòÆñ³qo;¸À™ß¸ à]ðyDˆG<¸ÅnrcsH<â© kaKT¼æ7ÏùÎ{þó ýæýð0 š AäáZ.íàåЇ"NP×Bõ¤2Hx¾‡ÄÇáô÷Hý깄„€öb´(ïÈI. ÏÅ„hØ€¤·@þ¹Ò–¾T•}ò[/„Þ ‚ôj C}ýACÈÍ3qWàp<°‡Cô }G­Ø4n ‡;e_LÀ{è÷húT 8@ˆ7€§v1á7{µ'QP rõvBPCþÐ}.%8 ¥o'z"8‚$X‚›7ÍÐ #zv72ày-xwœgžÀL.ÀYçž`G…ðƒ?h‘` Œ‡ „ Hˆ„±`„@ø: lÛâ„TX…Vx…X˜…Z¸…V8€åGQà ÌÅÁà¼W`ðjÄj~´0>¤Z»§&{à„`(†ëB†d7´0†t†?˜W07€ öGPPþzØH³`„pN0 jÄFújØ3ä7‡…à…„@9ì'„ðˆj„J’0X°k®Çkg§T]P‡ˆddªõz G¢Ðº‚‰@äÝn†køGBðŒ°jB´ijò‰¸F¦°Ǩ0B¤[ò`F€\˜Ú¸ÜX…m lm°…—r)X8Žãh…~ç *0?8.à .`WHˆPõ( z  ãæI¸ TðpöXy™ ¹ ÙY~ôW~@<¦ó„‘Y`°=t‡6&‰¹$)‘&ié&0’‡€,9þ’%Y‡àÑHà&%’’‡ð¥Ó’„P/ù“]@(‰y)ô7“ö8“5Ù9”dÒŠhøN)Ép¸ÐöØ“?)“Gy’ôw`ÐDPM —bnÀ‘ •sX}‚)oé”X@”…@—câ–9 *º–9˜„Y˜†y˜ˆéz`zP‹Ù˜ IŽ0™“¹c€ Pà ÍpM™ °`”Yš¦yš¨™šª¹š¬Ùš®ùš°Yš˜{›¶éš‡€•D@·Ù›¾ù›ÀœÂyšOI‹0œÈ™œÊ¹œ¶I‘ðœÐùœ…°p ` Ùþ©…Þùàžâ9žäYžæyžè)ž‰ ^†žîùžðŸò9ŸôYŸöyŸø™Ÿú¹ŸéI•🠕P*  o   º  Ú ú ¡:¡Z ‘†P¡º¡Ú¡ú¡ ¢":¢$Z¢&z¢ÿ韖°¢,Ú¢.ú¢0£2:£4Z£6z£8š£:º£<Ú£>ú£@¤B:¤DZ¤Fz¤HZ£•àƒ™Ð¤Nú¤P¥R:¥TZ¥Vz¥Xš¥Zº¥\Ú¥^ú¥`¦b:¦dZ¦fz¦hš¦jz¥…ÐX‚P MÚ r:§tZ§vz§xš§zº§|Ú§~ú§€¨‚:¨þ„Z¨†z¨ˆš¨Šº¨ŒÚ¨Žú¨tÚ¤• zÐX†q©˜š©šº©œÚ©žú©bQ© r?¦zª¨šªªºª¬Úª®úª°«²:«´Z«¶z«¸š«ºº«¼Ú«¾*«"ª¤ªEdÆz¬Èš¬Êº¬ÌÚ¬Îú¬Ð­Ò:­ÔZ­Öz­Øš­Úº­ÜÚ­Þú¬j¬UªßZ®æz®èš®êº®ìÚ®îú®ðš@áªÂJ®ñz¯øš¯úº¯üÚ¯þú¯Å2¯éQ¯Ä °{°›° »° Û­k›ÅÚ°[±{±›±æú°k«± ²";²$«°;®[²*»²,Ûþ².›­';ªöú²4[³6{³%³Ã*±éj±€³ÏЍ` B{®EK²>k®I{¯E‹ 0c`´C«®Gk±:;³Dæ àV@ Ôº´ÐÊð_«®‹ðžð¬0µÌZ´z Ö·ÖJ¶f‹¶`k uk¬x»¯¥ð{û¶È*¶ÞЏÔJ¶¹ 5«p¬ë·v˰¸} 5…°ÈZµÓ*  v‹¬;¹ {µ)Kdg@u« ¥`¿@Ðð¬ŠÛ¬  Ð • PMµë°ÐÂ@ ˆ°p+·R¼D湨+­¹»»½û»Éú¼ñþª °Ê  €@‡û³ÏʼÌz»Ð»:P,¸€+¹Ê[,𘫹œ{¬ž­gP“Ð ¸`Ð Ëj½ «ºl ¹pÃÅbÃ8|¾€µÅ]̬®œ@0»ÖÐ.–ÁV°pÁþÅ‚ @{UÄ'ŒÄ),ÁlÁ¬Á¼ZÌÅ틬  óë*‘ 0`?Ä`,´ €¶0Éq̬ ,¿k|Ã9L´%ÜȀ̬\RÓ  ÖpÇÅ¢ÇKìŤLÄ©+®2»º T tŒÀ¼‹`·z0þk@ Ô <Âð ÊUœ@ @üÌÅÍ~K͸0Ô° pÖ€ зÊÊÌu\,ÔÐ(¸ €|Øüà<¹`ÎÖ€ÎÓì¿L<´» @ Ö PÉÇúÊR3δ| `·»° w+·MÍÿТL ÐÍþ ”ÏûÜÏÍÑ-ÃÙ ¥[,ÀœÇ{l@ Ä. µ§0‡\ÐÐ,Í"mÍØ¬ÍÌÍÞ,Ê/m »ˆàC«¶ÀÉЀ:@ ¨0C6¹EKðÕSíÊ4¼¹ÖÀÒÍÀÏþ\´JÍ{¼¬öœ@ð»7-Ì´üÑ+Àk¬‘@R3`l†[M PÂP,žl¸#p¹á,5àbˆm¬‹}·«Pð¶°ÂÍ: ‚]M_Ý·VpçbNæTý QËÉˆÐæÅÅý=ÖðëèuŽ»VÐÑ»0œûæJÎäp­è-Nä^,w½ç8=Ìý}Ìôв\MÍ0º\Þ"¾±@¶ÐÂ(> Åb Íè1¾Û"LÂiþëÁn ð¶m@ ° –põ‹¬|ÀËÞ ´´Nоì¾×.·Ìâ+ãW¼×Å" p¹ëìåîÈ›Üô\dÞ^MðNÙÏêP,°îÓl Þ­ïRc…¾âäíÃ^ìÇnï ÔïTm  v{ßù],û½éCûßRcñÊnþ j ÞÍ[ÂÄn ÆÞ¬¹¼Ëµ_,/ë~°~¬c@ÄÛ ¨€¿i~ à¿€è:ÍÓÐðjžì˽Â` ×éâÅ"ôDè¶0 ðbÀÎÎÚº‚ÀÓ‹°&­þk %üâ1Þ»ôCo E_åX<´jŸ@ÀzŽ»ºûôQO˱€ ÔÐ Àßso TïöFökÍ(¨Ò‰OöÖ`ö}ÿ÷Ϭ¸°¸ ¸ P,¿¹P9½ÓÊ{ÔBMÔROømÿö¼Ó=­ôOù€Ïß®ìϸ0µZKàÕ`m ƒïßð+û“_òj=öe÷­ô‡Ì¬cP•þ ¿ÀþÛùf ú²þû´>°¶þ×ÇŠ[ÛµVP»bË À(ÞÇüȈ»e{¶áŸúS\þço¸“^,0Њlë¶Rm1`€ƒLÖ Ä²fMdž„‚ hcaB "p`àÉT;:„˜°; MžD™X–#*)³2bÅ‹%&\˜ׄ2$ÜeA Aš6q¦L) Ã,ìJˆjƒ T$4`eÁ Ͳ2 @!Ãן-bÔvlY°ƒ6p*TˆPXeÍ„Þ4|‘£5 ‡ñêÝ‹’A“… U:°àb¹dÍFþNÙ§ËOµrõ*ócbЭ]¿†mR9ÚæôT¨ §¶9±aô\øpâÅ]ç ÌøræÍ‹[°ò{¢sêÕƒ7.ˆ€-ë݋Ϯ};÷îÞÕ±{GŸ¾ùˆ£êÝ¿Oy §§¸¤ÃÇßü|qAzòÿ·<ÚÄÓ­¶ò¨Û@ÕSfì[0BæÔ0€‰-A 7éàf(%!bp…m„ƒ›™²²_m2“l #Ζp€áŠÆwoã’µc ¥úž&]tÉÉ€ÅG^'=0Ë€ ˆÁ…lQ‚%¬¡¦ ÙeEœÿ½yœÙÒ ½3xŸöØbOIl×ȶÆv“ ‚G bµáí\^qþ¢Uä‚~ƒc_p°\ ‹;‰:b0†-VÀ€5P1€»Yá\—û\gR`ψΠ¦Â™  7 aF:ÿ%D_áLÛ—7Q!Í$ÂHK €ÄP6*dß­¡ ,n~@â2‘ Îc¨Û"°2" (œa ¦€Bà‰Ó¡Û`g6+ìÂŽ›Óß¶x(»„4 :œ™Žï…@‹UFÖ¨€™‡Æ­9:ØX,¶“l1!]L­qŠ0²}j4‰ &à‚›Õ/… ìM’GÐð¯‡nÔÝ™B"m_)Á6B ¨ðR´þ°1Nš¥Zl &¿X7j0@f±EG<¹?,8€_L™Æ9ªmjÛæßF bX‚nªi‹5ÞPÖ²bFDZUS%5ÀYÙ¯±Ägw¤IR6Cw&8*¼gAEŠŸNt¢ötèÂÚÖP¬u´riLATÒ•–®¦z<¨ÌnÚJ(zx„„§8e:Ôr©°ŠLÉQí¥F¦©Ü —?\T˜Õªÿ )z²êÓžvç§× üá)²–Õ¬gEëÆŠÖµžµ­f•êÁzUºÖ5‚qä\%dþ ¾öÕ¯l`;XÂÖ°‡Elb»XÆ6Ö±…ldkWêàubz%‚µYÎvÖ³Ÿmheõ ÊŽjª{mjU»ZÖ¶–µ¤-í¾N›Y×ÖÖ¶·ÅmnSÛØo¶O³SW¡¢YݦêÍ(nr•»ÜYñ¶·ýíW+Œ†!‘!î."€¼ä‚T †mË\ò–×¼þp®kª €ë&DÀ¼h÷Æw¾è‰€B˜$¿ûíoz( =‘à4cI)Kñà©‹eöNŽM÷5‹¨Ú;\¨ƒzP‡:pñ‹ï†×UôŠc5Þó¶ØÅ¶Mok0¬áþ“h`ÊXêbcë=Ð@€  qŠ ÈB&ò,«³ ¤® (ÉÙÒÖŒ˜4h ÊPF'Ná ¥† 6œÍ6*.• °YIXh€-Hu;DÀ§"† pPaÎu¾³›á,g@ hà1gK4@@ó‹%=éÍÆØ5b6 4°eklà(šæ´§Ó³ |ækÖ µ©Á–;( #˜€JT)08]j…UåLc×ð8ÀpÁ›R·T¨à'°èd Òþ á_ ÀÏ…v6©íe3;۰œ-`Žp4 ”FwºyeéÖþôÚnüŒ ðîR7kÞèAE½­a ˆPßüvÏ(@€\È%Í0À:1´G·Y¬âõ˜QB\lŒ`6ÓF‰SµaÚ»§ÚJ•kàã§âx¡qA*\,`Χ‚ Ô=sš7W8î&µIỜ7Äw?>€ ¨ [AzÑÕsM'Öä†È!.4 H à —«Þ¾¼ëظ›Ã¦ ‡& qRUâ úÊYl*TD T:(9rË~ö´ZîÐÀœåÞÔÜïW»AãnxÛ›Þñ¾7zVïe Ö¨f<ÿž‘u¼#J~1¿a=¯Zï%Ä».ñ“þ×T«(Ù¡QjêAvGUÈGwR­¾õþxý\AªX¸öþà;à…/|ÁGÆÝš–&>-€ä;-à9<É ŸžÊólÖ(q¸ìð‰Þ5ÔhÆ4ÐŒ»‘ÙÚ°6è X€T@©„€E»Qír7U´§]mÚûcþõµ›sP è¿à¾¤¹âK ð?òKˆ  €f$“@ l2õ@…_†%0Óà@d8ô¨>oš²˜À…%ÀhÀ è7Ï»,ÐÓµT 5«ªá0sØ€,* øR)… €LðX p¸¿T=»€·ß+Â#LBµ+þ„šP4½#TÀ.¤4D d ¬/˜¯2¼/ïPã‘îHˆ5Ì7t숢©  «À œ0²†V©ÓÛ¬ XXY;/DD¿Ãç \ìÄ^Þ¨ l0DüKÄLT·EdĽpD¤-`±„(€(…ÃDMTEIãÄNL‰O,"ÔZÅY¤Å^iEW< X´¥Ìú†^ôÅ_Æ`Æa$Æb4ÆcDÆdTÆedÆftÆg„Æh”FfÄEáÐE «ÆlÔF#¹F?ÜÆoGéF‘¬r4ÇsDÇtTÇudÇv¬plqÜH¬Åz´GX¹Ål”GY¼Ç~ôÇÀþƒÇFä¾ü Ç4È{ÌÇjÜÇ ®@–%¸¶\9DRQ#¯‰<ÈKH\\Hæ³Öت0€(¿‰#€Œ#• e¨ˆt;p?×›IÜ;),O06_éI‰LÅŒ<¯„  Š°NI’üäx¼ ¡: ‚©š‘ɉЀ|Ž”.®sRÀb8(‰¯ë7 lP€pIZÉVù@±oP€¨KøAŒ,6‹ä•Ÿ´ãK¡$¯T†pax˜±$K³ü €€§,„ðbh ©$´¢¨„fÈ p€…‚ ¯|¸| þaP€JØ âr5hR+Hh 87ÛÄMÝ$ex€=ë3Ѓ (¹R¡¯Sè€íñ‡Sð½h´GS±ŠT³`3m¸0 T¡3 XH#îôNµÌÎJê„ p=ãäI—¼ÍÜÜM:³3Ø›?B#ÌÂdð“PMÖÄH €%xÊÀÿ0Ä™khHÊf@oôDîsÔ (ŸÖ@¤Ž‚ômu â:-›eÄÔ%HÏZ‚µã?æ,<~.=Æ8Þxˆ´äE¶Å€Œ B†CfäIŽ_GžÐ@ÝEHœÆMæäNöäOåPåQFK† H6åTVeï@åUvåWV ,dw¤åZ¶å[Æå\vGXneõdJfÜäÞêåôøå`FæÖæØ*fô8æd†fÑZæÒJ]µrÈ\¹ØVÁ €i«­¸Ô­ÁŒæÑâå ^]¨pJ_CÖí€î’•lfXÜçÜçqþÆGßX¯ «/ù2‰~>]ëø/þò/ý"h#020³‘`0ƒ°Ò4g°| É|Jóó012…x^• aåÄ•g‹•zÞ,’f•{ÆgW¹ÅÛ0Ë1ƒióŽ#²"3º »i%£&s2(ëŸo¢2ú€+Ë2N“hLÆF¤èÖÐ.æ03#iî´!?´8{UóüNSé€ËUk Ï;Ójµ<¿îÜj%´6{3¬.4;OòôàÎk‹Oß,´H¨‰%І   cX£c>аlô¾”8÷9´¼ë;‰ì;õärUG•×þð_`E?õc¿™t€%¨mû?°?ÝîëííuüëÞƒ/xïbù£?ßó ¦á%ÞꆲßåÝß{öƒMtðæ¿‰ ø?€,À”ôn_•[tÀñ»› ¬ÀœÀ˜·ïüÀ¬°y¯:”2pJÁlAþ–àÓÞºUÖ6IäA,Ï ¨êæ¥B%$ø!îáÎp'.ª/â®züÄs#DB©çóß=á¦kÜ$aŽ?ôD÷?'„¯z+ÄÂE3ö”WùÝò 12„/3üç¾èê€Ã64‰Á—Cõày;´<¬Š«x÷>ôD ^Žg†_B¼Ä»Ç•i¦¬föþÊÏÏIø°ÄWQiÌgÍ·+ÎïÏ'ÌQ,ÅS¼|Ó¯Ô¯+Õ·Ö—ýÜ?Ú§+ÛDRþàþá'þâ'år&zXVþåçYfþç‡~”ðý7Öåê·þëÇþìgGäGõ¥VÜ×ýðçý«š~çÿðÏýñ·ªòoŽóGÓW¢ªæ†|ch¾XÆæ5é_)}DŒÿ¡æšÓS¡‚‚æÔXkè°¡'R|hÑ"\thÉŸ ˆ”ÈàEŠˆM\™ò¥Ä] ˆK¢K˜:w¦ÌÉó'Љ X j´(Å%TŒ2My YÓ¨R§R¥ø­£E+ lxþ¨ì‚€c~ ;¶aY±X×^̸‘,Xµhãžµ–¶.Û¼ Ö°‡‚0 Á¯^‹ D¨aLj;[£Ð¦æµ çž¿ø¦Ó§ÏêèQ§×/œ,Sz®ê/µm E‘æöÌ[¢Ò¨µ>Ímü¸í«yUÂÐÕ¡† ÊV (Õ0úôê×¥S·N¹£eÌÍ s×n {÷íÙ½×Ë€Àˆ¿­)P©Y. Æ·_<°qBAv‘d:QFz}D,ÒÁ. ‘ Ѐ-þ¨À x²a‡žøC…, EÍ0œD zèÏvDà€?ÍH0€þHDŒ\0ÂRþTxa†.z²ÊIÖ”‰&¢x@$|-¡ÍP …b(Ñn³IÔÉ&e€“25Þ˜£D1ÎèOQÊ<à#/ñgjÒ8ä–0ª1AÀ“¦%  ‹ÈzhJÊéÅÁsÖ@#À) m£JJ飑Z3i{m%øP¦—Vª)§¡nJi§y1 Ã¿X˜5ÍPˆCÍ 0 eþtP€áúP0x€d¢™Dâ X±¬ H„Š9þxBÀŸ¨Íö‹áø£iÁsÀ¸TÛ’—dà= ¼á0­Òƒ€#þü2@ÔZ‹ím^J¤N•PÄ­þ·àÂh9Ø 5êL Ç´Õ^ûg—aCÀg àÂþ´ûn¼±©[ÛPí.›‹AN4o½÷Ö¹nÄûþ9²?X‘&Âá4 #¢=÷¬h^Œ:„ ü©5D´Ò!ªCklCM[stÒE;õÒP³ÅÀ"pðj`¥hítª+€aìK”uâ .T€ Vù3ƘXcKß"¦tb¿èJÔŒ¸*6#,ÚÈ6Ñ7ù³‹©àÂ.K”ÊŽ#¤„¸â”ã"7ûSÈ/^±JÊœ2BÔt‚Á噷茖³IÌ.L„Aè—{^sÂSDþø«ûƒË„ÁKDð>kÐl ÝÐ*Æ€5á_¾ø B¾×ÖÌ]÷ÝèŸo¾úäÓoÍúíc6.äk$`D`m i›€ÞÆ“TQ >Ñ. `ã©ãæ€äüQ‰ @X¶&b  @ᨄF&@‘pX@……KTü LÄ@E&¢ƒ m°ƒ|¡DÆ?¥d„%ôVqü¡zipLä W×%@…„ J±„Jt@2¤¡Dl£‡:Lž%²CN¤‡Q£D 16ú£ *ØsÓ½µ|k[³Öù4ý5¤~¼ÓÎHEþ’Ûy4+³ñ§!i3 cxå¶È,°SpàEôˆÑ°ƒç Qj˜„^Â90=˜¬¢“£#æ4ǹåΪd¥?àʉ¸âá‚I,—Ä%J¤cúe+‡'MŠdÐF,6P”\þŽ\"ž&²äun"½ô&4ƒ¹º¸B"±¨^í˜ÇyNeXéã£ðf `Júäg¥þ‰*G~2 –ì§@ ºÏ:²!D™#+Z5ÄVxI Û4™@NNF/Í@Ä/ˆ¡°Ç"z󇀉¸€\þD´Õ=©iQD Ìò[vÀ=°a’à”þŽí²ƒ?ˆA€]°Ì^ø‚WL§÷âZû€ 4tÊSo2³‰P•éi7k `Bê(ÀØ¥¤*õªI=‹o yMua ÖuNÀê@b(OzÖ(ö´5š± 4ƒ Éš x²’¥ìc#;Ù’vê£!ie5‹YkXv³™½,g É}`>c°~,ЀJæê€õ•;še ²®€2ùãK@8`u¥82áçFW0à­‰˜c@4.êJ÷­6@¤ ¯] ®sr™ë\èf¢ @~y7ëbW»þ\e¢3“»ÜæJó7i’–)Kb&ôª÷­E!$pq¾Dìu/™_ |ñ[Øïä°ÙFàÀ² .,v1XZ¬?ÞÀ·À‹dŒcÛ%Æmèj!€ùào+Èbúc[Çlô"?i¨GHŒ¨ ,BÊVf •‰CÆ+s™'&†2˜Ã,æ1c%£LÆ-™¿sÒ.GEÕê6Ø,gx½yqÊ[ç¬ç/§¹Ï~þ3F—Ü«…:/kÖ3P,q€, ˆî²¢íh-?zÏ…¾4¦3í3úWš¶Æ¡+-êQ“ºÔ@áó§S­jLþç¶„^5¨¿!ëYÓºÖ¶þ¾5®s­ë]óº×¾þ5°ƒ-ìa»ØÆ>v°a­ìe+9“g~5³£-íiS»ÚÖ¾6¶¡ÆéǘºÛÞþ6¸Ã-îq#ÓÙƒºÓ­îu³»Ýî~7¼ã-ïyÓ»Þö¾7¾ó­ï}ó»ßþþ7À.ð¯[Ð !8®ð…3¼á8Ä#.ñ‰«Ûà¡8Æ3®ñs¼ãÿ8ÈÓmñ„¼ä&?9ÊS®ò•|äæ`9Ìc.ó™Ó¼æ w¹Ís®óó¼ç1ǹσ.ô¡½èºÑ“®ô¥3]èHo:Ô£.õ©{üéT¿:Ö³®u[}ë^ÿ:ØÃÞõ°“½ìfWúØÏ®öµ³}æioþ;Üã.wŽ¿}îv¿;Þ^÷¼ó½ï~§÷Þÿ.øÁ>ð„?<âçnøÄ3¾ñe_¼ã#/ù«C~ò–¿|Ò+ùÍs~çšï<èCÏòÏ‹¾ô¦ÿ8éO¯úÕK<õ¬=ìõnîƒÇ¾ö¶oýì/~ûÝó>á®ï=ðƒ/òÜ“\øÆ?>à‰ÿrä3¿ùW¾ó£ýßK¿ú¡§¾õ³yìk¿û‘ç¾÷Ãxð‹¿ü'¿ùÓwô«¿ýqg¿ûã¯vøË¿þb‡¾ýó?~üë¿ÿçç¿ÿàú àû &àü! 6àýµÚ³9 >N Rý] Â\n ¢\~ ‚\þŽ  n\ ž  N\ ®  :\ ¾  ú^Π ‚` Þ ’`î ¢`þ ²`¡Â`¡Ò žÛ>aÄÅ Na3H!>¡^¡f¡!v¡~!ú Ž¡–¡Ú ¦¡ ®!º ¾¡ Æ¡š Ö¡Þ!z î¡ö¡Z ¢"!6 !b&¢" #6b>"$öŸ$NbþU¢%Ö&fbüm"'¶Ÿ'~bú…¢(–)–bø"*vŸ*®böµ¢+V,Æâô%!-þà,Þ"óå¢./ö¢ðý"0Ÿ0#ï£1Þ2&cí-#þ3ž3>#ëE£4ª5V£é]#6Šž6n#èu£7r8†ãöÙ"9ò¡9žã¦£: ";¶c!¾#<"¢<Îã"Ö£=:">æc$î#?R¢?þã%¤@j"Ad'$B‚¢B.ä(6¤Cš"DFd*N$E²¢E^ä+*ŸBt¤G~$H†¤HŽ$I–¤Iž$J¦¤J®$K¶¤K¾$LƤLÎ$MÖ¤MÞ¤I"Nî$Oö¤Oþ$P¥P%Q¥Q’¤N¥R.%S6¥S>%TF¥TŠdcœÁT^%Vf¥Vn%Wv¥PžÁAl@èY–¥Yž%Z¦¥Z®%[¶¥[¾%\Æ¥\Î%]Ö¥]ÞI%^æ¥^î%_ö¥_þ%`&[¶ÁTÀ?b&¦b.&c6¦c>&dF¦dN&eV¦e^&ff¦fn&gv¦g~&h†¦hŽ&iRæ?;igraph/inst/tkigraph_help/index.html0000644000175100001440000001333413177712334017351 0ustar hornikusers tkigraph online help

The tkigraph manual

tkigraph is a basic Graphical User Interface (GUI) to some igraph functions.

What is tkigraph?

tkigraph is a simple Graphical User Interface to the igraph R package. R is a general purpose programming language and environment, used mostly but not exclusively for statistical analysis. igraph is an extension package to R. tkigraph lets you use some basic features of igraph via a GUI, instead of typing in R commands.

Installing and starting tkigraph

Well, if you are reading these lines, then you probably already know how to install and start tkigraph. If not, here is how to do it.

First, install the GNU R software package. It can be downloaded from the R website, but first check your system, because it might be already installed. You can also ask your system administrator to install it for you.

Second, you need to install the igraph extension package. First, start R by clicking on its icon in Windows, or by typing "R" into a terminal and pressing ENTER on Linux. Now type in

	install.package("igraph")
      
and press ENTER. After choosing an appropriate mirror site, R downloads and installs the igraph package.

Third, you need to load the igraph package and start tkigraph. This can be done by typing

	library(igraph)
	tkigraph()
      
(in two separate lines, pressing ENTER after each line) into your R session. You should see a new windows appear, it looks like the one on the picture below.

The tkigraph window

The main window of tkigraph look like this:

Main tkigraph window

Almost all the window is occupied by the list of graphs in the workspace. Unlike on the picture for you this is initially empty. Every graph has a number, in the # column, a name that is not necessarily unique, you can change the name of the graph to whatever you like. In the last three columns you can see the number of vertices and edges in the graph, and whether it is directed or not.

In the leftmost column there is a checkbox for every graph, you can select one or more graphs using this and then perform operations on them. Some operations require exactly one graph to be selected, others work happily on many graphs as well. You will always get an error message if not the appropriate number of graphs were selected for an operation.

The tkigraph menus

Creating new graphs or performing operations on them can be done by selecting entries from the main menu. Let us discuss briefly what the various menus are good for.

Graph menu

The Graph menu lets you create and delete graphs, show them in an edge list format, calculate some basic properties for them. Moreover all file-related operations are here a well.

Draw menu

In this menu you can draw your graphs using various layouts, possibly also interactively. There are two entries in the menu. The first one (Simple) tries to do the plotting automatically; first it chooses an appropriate layout for the graph and then tries to guess the graphical parameters to make the plot look good. Finally it creates a non-interactive plot.

The advanced plotting lets you choose various graphical parameters, and you also have the possibility to create an interactive plot.

Centrality menu

Lets you calculate various degree centrality measures, plus edge betweenness. The results are always shown in a table that can be sorted according to all of its columns and the data can also be exported into a text file.

Distances menu

Various measures related to path lengths in the network are included in this menu.

Subgraphs menu

This menu contains three slightly related entries. Components are maximal connected subgraphs of a graph. Communities are natural modules in the graph, a module is a subgraph that has more edges within the module than between the module and the rest of the graph. (Loosely speaking.) In the 'Communities' menu you can run the Spinglass algorithm by J Reichardt and S Bornholdt. Cohesion measures how difficult it is to disconnect a graph by removing vertices from it. The last menu entry calculates cohesion for all components in the selected graph.

Motifs menu

Motifs are small subgraphs with a given structure. The first menu entry in this menu just plots all possible motifs of a given size in a directed or directed graphs. The second menu entry finds all the different motifs in the selected graph and plots all the different motifs annotated with the number of motifs of that kind found in the graph. It also plots a histogram for the various motifs.

Help menu

This is what you are reading right now.

Quit

Not really a menu, just a button. Lets you quit from tkigraph.

igraph/inst/tkigraph_help/communities.html0000644000175100001440000000013613177712334020572 0ustar hornikusers Community structure detection

Bla-bla-bla

igraph/inst/html_library.license.terms0000644000175100001440000000314513177712334017717 0ustar hornikusersSun Microsystems, Inc. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. The authors hereby grant permission to use, copy, modify, distribute, and license this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. No written agreement, license, or royalty fee is required for any of the authorized uses. Modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated on the first page of each file where they apply. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. RESTRICTED RIGHTS: Use, duplication or disclosure by the government is subject to the restrictions as set forth in subparagraph (c) (1) (ii) of the Rights in Technical Data and Computer Software Clause as DFARS 252.227-7013 and FAR 52.227-19. igraph/inst/my_html_library.tcl0000644000175100001440000000622713177712334016437 0ustar hornikusers # IGraph R package # Copyright (C) 2009-2012 Gabor Csardi # 334 Harvard street, Cambridge, MA 02139 USA # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA # ################################################################### proc render_real {win href} { global tkigraph_help_root set Url $tkigraph_help_root/$href $win configure -state normal HMreset_win $win HMparse_html [get_html $Url] "HMrender $win" $win tag add indented 1.0 insert $win tag configure indented -lmargin1 20 -lmargin2 20 $win configure -state disabled update } proc render {win href} { global tkigraph_help_history tkigraph_help_history_pos global browser_button browser_url if { [ regexp ^http:// "$href" ] } { set browser_url $href $browser_button invoke return } lappend tkigraph_help_history($win) $href incr tkigraph_help_history_pos($win) render_real $win $href } proc start_history {win} { global tkigraph_help_history tkigraph_help_history_pos set tkigraph_help_history($win) [ list ] set tkigraph_help_history_pos($win) -1 } proc render_back {win} { global tkigraph_help_history tkigraph_help_history_pos if { $tkigraph_help_history_pos($win) > 0 } { set pos [ incr tkigraph_help_history_pos($win) -1 ] render_real $win [ lindex $tkigraph_help_history($win) $pos ] } } proc render_forw {win} { global tkigraph_help_history tkigraph_help_history_pos if { [ expr $tkigraph_help_history_pos($win) + 1 ] < [ llength $tkigraph_help_history($win) ] } { set pos [ incr tkigraph_help_history_pos($win) ] render_real $win [ lindex $tkigraph_help_history($win) $pos ] } } proc HMlink_callback {win href} { render $win $href } proc get_html {file} { global tkigraph_help_root if {[catch {set fd [open $file]} msg]} { return " Bad file $file

Error reading $file

$msg


Go home " } set result [read $fd] close $fd return $result } proc HMset_image {win handle src} { global tkigraph_help_root set image $tkigraph_help_root/$src update if {[string first " $image " " [image names] "] >= 0} { HMgot_image $handle $image } else { set type photo if {[file extension $image] == ".bmp"} {set type bitmap} catch {image create $type $image -file $image} image HMgot_image $handle $image } } igraph/inst/NEWS.md0000644000175100001440000013367213430770106013632 0ustar hornikusers # igraph 1.2.4 Feb 13, 2019 No user visible changes. # igraph 1.2.3 Jan 27, 2019 No user visible changes. # igraph 1.2.2 Jul 27, 2018 No user visible changes. # igraph 1.2.1 - The GLPK library is optional, if it is not available, then the `cluster_optimal()` function does not work. Unfortunately we cannot bundle the GLPK library into igraph on CRAN any more, because CRAN maintainers forbid the pragmas in its source code. - Removed the NMF package dependency, and related functions. - Fix compilation without libxml2 # igraph 1.1.2 Jul 20, 2017 - Fix compilation on Solaris # igraph 1.1.1 Jul 13, 2017 - Graph id is printed in the header, and a `graph_id` function was added - Fix `edge_attr` for some index values - Fix a `bfs()` bug, `restricted` argument was zero-based - `match_vertices` is exported now - `%>%` is re-exported in a better way, to avoid interference with other packages - `ego_` functions default to `order = 1` now - New function `igraph_with_opt` to run code with temporary igraph options settings - Fix broken `sample_asym_pref` function - Fix `curve_multiple` to avoid warnings for graphs with self-loops. - The `NMF` package is only suggested now, it is not a hard dependency - Fix gen_uid.c _SVID_SOURCE issues - Avoid drawing straight lines as Bezier curves - Use the `pkgconfig` package for options. This allows setting options on a per-package basis. E.g. a package using igraph can set `return.vs.es` to `FALSE` in its `.onLoad()` function, and then igraph will return plain numeric vectors instead of vertex/edge sequences *if called from this package*. - `igraph_options()` returns the *old* values of the updated options, this is actually useful, returning the new values was not. - `with_igraph_opt()` function to temporarily change values of igraph options. - `get.edge()` is deprecated, use `ends()` instead. (This was already the case for igraph 1.0.0, but we forgot to add a NEWS point for it.) - Do not redefine `.Call()`, to make native calls faster. - Speed up special cases of indexing vertex sequences. - Removed an `anyNA()` call, to be compatible with older R versions. - Fixed a fast-greedy community finding bug, https://github.com/igraph/igraph/issues/836 - Fixed `head_of()` and `tail_of()`, they were mixed up. - Plot: make `label.dist` independent of label lengths, fixes #63. - Plot: no error for unknown graphical parameters. - Import functions from base packages, to eliminate `R CMD check` `NOTE`s. - Readd support for edge weights in Fruchterman-Reingold layout - Check membershiph vector in `modularity()`. - Rename `str.igraph()` to `print_all()`. - Use the igraph version in exported graphs, instread of @VERSION@ #75. - Functions that can be used inside a `V()` or `E()` indexing now begin with a dot. Old names are deprecated. New names: `.nei()`, `.innei()`, `.outnei()`, `.inc()`, `.from()`, `.to()`. #22 - Fix packages that convert graphs to graph::graphNEL: they don't need to attach 'graph' manually any more. - Fix a bugs in `layout_with_dh`, `layout_with_gem` and `layout_with_sugiyama`. They crashed in some cases. # igraph 1.0.1 June 26, 2015 Some minor updates: - Documentation fixes. - Do not require a C++-11 compiler any more. - Fedora, Solaris and Windows compilation fixes. # igraph 1.0.0 June 21, 2015 ## Release notes This is a new major version of igraph, and then why not call it 1.0.0. This does not mean that it is ready, it'll never be ready. The biggest changes in the release are - the new function names. Most functions were renamed to make them more consistent and readable. (Relax, old names can still be used, no need to update any code.) - Better operations for vertex and edge sequences. Most functions return proper vertex/edge sequences instead of numeric ids. - The versatile `make_()` and `make_graph()` functions to create graphs. ## Major changes - Many functions were renamed. Old names are not documented, but can still be used. - A generic `make_graph()` function to create graphs. - A generic `layout_()` (not the underscore!) function to create graph layouts, see also `add_layout_()`. - The igraph data type has changed. You need to call `upgrade_graph()` on graphs created with previous igraph versions. - Vertex and edge sequence operations: union, intersection, etc. - Vertex and edge sequences can only be used with the graphs they belong to. This is now strictly checked. - Most functions that return a (sub)set of vertices or edges return vertex or edge sequences instead. - Vertex and edge sequences have a `[[` operator now, for easy viewing of vertex/edge metadata. - Vertex and edge sequences are implemented as weak references. See also the `as_ids()` function to convert them to simple ids. - Vertex order can be specified for the circle layout now. - Davidson-Harel layout algorithm `layout_with_dh()`. - GEM layout algorithm `layout_with_gem()`. - Neighborhood functions have a `mindist` parameter for the smallest distance to consider. - `all_simple_paths()` function to list all simple paths in a graph. - `triangles()` lists all triangles in a graph. - Fruchterman-Reingold and Kamada-Kawai layout algorithms rewritten from scratch. They are much faster and follow the original publications closely. - Nicer printing of graphs, vertex and edge sequences. - `local_scan()` function calculates scan statistics. - Embeddings: `embed_adjacency_matrix()` and `embed_laplacian_matrix()`. - Product operator: `*`, the same graph multiple times. Can be also used as `rep()`. - Better default colors, color palettes for vertices. - Random walk on a graph: `random_walk()` - `adjacenct_vertices()` and `incident_edges()` functions, they are vectorized, as opposed to `neighhors()` and `incident()`. - Convert a graph to a _long_ data frame with `as_long_data_frame()`. ## Bug fixes Too many to list. Please try if your issue was fixed and (re-)report it if not. Thanks! # igraph 0.7.1 April 21, 2014 ## Release Notes Some bug fixes, to make sure that the code included in 'Statistical Analysis of Network Data with R' works. See https://github.com/kolaczyk/sand ## Detailed changes: - Graph drawing: fix labels of curved edges, issue #181. - Graph drawing: allow fixing edge labels at given positions, issue #181. - Drop the 'type' vertex attribute after bipartite projection, the projections are not bipartite any more, issue #255. - Print logical attributes in header properly (i.e. encoded by `l`, not `x`, which is for complex attributes. Issue #578. - Add a constructor for `communities` objects, see `create.communities()`. Issue #547. - Better error handling in the GraphML parser. - GraphML reader is a bit more lenient now; makes it possible to read GraphML files saved from yWorks apps. - Fixed a bug in `constaint()`, issue #580. - Bipartite projection now detects invalid edges instead of giving a cryptic error, issue #543. - Fixed the `simplify` argument of `graph.formula()`, which was broken, issue #586. - The function `crossing()` adds better names to the result, fixes issue #587. - The `sir()` function gives an error if the input graph is not simple, fixes issue #582. - Calling igraph functions from igraph callbacks is not allowed now, fixes issue #571. # igraph 0.7.0 February 4, 2014 ## Release Notes There are a bunch of new features in the library itself, and other important changes in the life of the project. Thanks everyone for sending code and reporting bugs! ### igraph @ github igraph's development has moved from Launchpad to github. This has actually happened several month ago, but never announced officially. The place for reporting bugs is at https://github.com/igraph/igraph/issues. ### New homepage igraph's homepage is now hosted at http://igraph.org, and it is brand new. We wanted to make it easier to use and modern. ### Better nightly downloads You can download nightly builds from igraph at http://igraph.org/nightly. Source and binary R packages (for windows and OSX), are all built. ## New features and bug fixes - Added a demo for hierarchical random graphs, invoke it via `demo(hrg)`. - Make attribute prefixes optional when writing a GraphML file. - Added function `mod.matrix()`. - Support edge weights in leading eigenvector community detection. - Added the LAD library for checking (sub)graph isomorphism, version 1. - Logical attributes. - Added `layout.bipartite()` function, a simple two-column layout for bipartite graphs. - Support incidence matrices in bipartite Pajek files. - Pajek files in matrix format are now directed by default, unless they are bipartite. - Support weighted (and signed) networks in Pajek when file is in matrix format. - Fixed a bug in `barabasi.game()`, algorithm psumtree-multiple just froze. - Function `layout.mds()` by default returns a layout matrix now. - Added support for Boolean attributes in the GraphML and GML readers and writer. - Change MDS layout coordinates, first dim is according to first eigenvalue, etc. - `plot.communities()` (`plot.igraph()`, really) draws a border around the marked groups by default. - printing graphs now converts the `name` graph attribute to character - Convenience functions to query and set all attributes at once: `vertex.attriubutes()`, `graph.attributes()` and `edge.attributes()`. - Function `graph.disjoint.union()` handles attributes now. - Rewrite `graph.union()` to handle attributes properly. - `rewire()`: now supports the generation and destruction of loops. - Erdos-Renyi type bipartite random graphs: `bipartite.random.game()`. - Support the new options (predecessors and inbound_edges) of `get_shortest_paths()`, reorganized the output of `get.shortest.paths()` completely. - Added `graphlets()` and related functions. - Fix modularity values of multilevel community if there are no merges at all. - Fixed bug when deleting edges with FALSE in the matrix notation. - Fix `bonpow()` and `alpha.centrality()` and make sure that the sparse solver is called. - `tkplot()` news: enable setting coordinates from the command line via `tkplot.setcoords()` and access to the canvas via `tkplot.canvas()`. - Fixed a potential crash in `igraph_edge_connectivity()`, because of an un-initialized variable in the C code. - Avoiding overflow in `closeness()` and related functions. - Check for NAs after converting 'type' to logical in `bipartite.projection()`. - `graphNEL` conversion functions only load the 'graph' package if it was not loaded before and they load it at the end of the search path, to minimize conflicts. - Fixed a bug when creating graphs from adjacency matrices, we now convert them to double, in case they are integers. - Fixed an invalid memory read (and a potential crash) in the infomap community detection. - Fixed a memory leak in the functions with attribute combinations. - Removed some memory leaks from the SCG functions. - Fixed some memory leaks in the ray tracer. - Fixed memory leak in `graph.bfs()` and `graph.dfs()`. - Fix a bug in triad census that set the first element of the result to NaN. - Fixed a crash in `is.chordal()`. - Fixed a bug in weighted mudularity calculation, sum of the weights was truncated to an integer. - Fixed a bug in weighted multilevel communtiies, the maximum weight was rounded to an integer. - Fixed a bug in `centralization.closeness.tmax()`. - Reimplement push-relabel maximum flow with gap heuristics. - Maximum flow functions now return some statistics about the push relabel algorithm steps. - Function `arpack()` now gives error message if unknown options are given. - Fixed missing whitespace in Pajek writer when the ID attribute was numeric. - Fixed a bug that caused the GML reader to crash when the ID attribute was non-numeric. - Fixed issue #500, potential segfault if the two graphs in BLISS differ in the number of vertices or edges. - Added `igraphtest()` function. - Fix dyad census instability, sometimes incorrect results were reported. - Dyad census detects integer overflow now and gives a warning. - Function `add.edges()` does not allow now zeros in the vertex set. - Added a function to count the number of adjacent triangles: `adjacenct.triangles()`. - Added `graph.eigen()` function, eigenproblems on adjacency matrices. - Added some workarounds for functions that create a lot of graphs, `decompose.graph()` and `graph.neighborhood()` use it. Fixes issue #508. - Added weights support for `optimal.community()`, closes #511. - Faster maximal clique finding. - Added a function to count maximum cliques. - Set operations: union, intersection, disjoint, union, difference, compose now work based on vertex names (if they are present) and keep attributes, closes #20. - Removed functions `graph.intersection.by.name()`, `graph.union.by.name()`, `graph.difference.by.name()`. - The `+` operator on graphs now calls `graph.union()` if both argument graphs are named, and calls `graph.disjoint.union()` otherwise. - Added function `igraph.version()`. - Generate graphs from a stochastic block model: `sbm.game()`. - Do not suggest the stats, XML, jpeg and png packages any more. - Fixed a `set.vertex/edge.attribute` bug that changed both graph objects, after copying (#533) - Fixed a bug in `barabasi.game` that caused crashes. - We use PRPACK to calculate PageRank scores see https://github.com/dgleich/prpack - Added`'which` argument to `bipartite.projection` (#307). - Add `normalized` argument to closeness functions, fixes issue #3. - R: better handling of complex attributes, `[[` on vertex/edge sets, fixes #231. - Implement the `start` argument in `hrg.fit` (#225). - Set root vertex in Reingold-Tilford layout, solves #473. - Fix betweenness normalization for directed graphs. - Fixed a bug in `graph.density` that resulted in incorrect values for undirected graphs with loops - Fixed a bug when many graphs were created in one C call (e.g. by `graph.decompose`), causing #550. - Fixed sparse `graph.adjacency` bugs for graphs with one edge, and graphs with zero edges. - Fixed a bug that made Bellman-Ford shortest paths calculations fail. - Fixed a `graph.adjacency` bug for undirected, weighted graphs and sparse matrices. - `main`, `sub`, `xlab` and `ylab` are proper graphics parameters now (#555). - `graph.data.frame` coerces arguments to data frame (#557). - Fixed a minimum cut bug for weighted undirected graphs (#564). - Functions for simulating epidemics (SIR model) on networks, see the `sir` function. - Fixed argument ordering in `graph.mincut` and related functions. - Avoid copying attributes in query functions and print (#573), these functions are much faster now for graphs with many vertices/edges and attributes. - Speed up writing GML and GraphML files, if some attributes are integer. It was really-really slow. - Fix multiple root vertices in `graph.bfs` (#575). # igraph 0.6.6 Released Oct 28, 2013 Some bugs fixed: - Fixed a potential crash in the infomap.community() function. - Various fixed for the operators that work on vertex names (#136). - Fixed an example in the arpack() manual page. - arpack() now gives error message if unknown options are supplied (#492). - Better arpack() error messages. - Fixed missing whitespace in Pajek writer when ID attribute was numeric. - Fixed dyad census instability, sometimes incorrect results were reported (#496). - Fixed a bug that caused the GML reader to crash when the ID attribute was non-numeric - Fixed a potential segfault if the two graphs in BLISS differ in the number of vertices or edges (#500). - Added the igraphtest() function to run tests from R (#485). - Dyad census detects integer overflow now and gives a warning (#497). - R: add.edges() does not allow now zeros in the vertex set (#503). - Add C++ namespace to the files that didn't have one. Fixes some incompatibility with other packages (e.g. rgl) and mysterious crashes (#523). - Fixed a bug that caused a side effect in set.vertex.attributes(), set.edge.attributes() and set.graph.attributes() (#533). - Fixed a bug in degree.distribution() and cluster.distribution() (#257). # igraph 0.6.5-2 Released May 16, 2013 Worked two CRAN check problems, and a gfortran bug (string bound checking does not work if code is called from C and without string length arguments at the "right" place). Otherwise identical to 0.6.5-1. # igraph 0.6.5-1 Released February 27, 2013 Fixing an annoying bug, that broke two other packages on CRAN: - Setting graph attributes failed sometimes, if the attributes were lists or other complex objects. # igraph 0.6.5 Released February 24, 2013 This is a minor release, to fix some very annoying bugs in 0.6.4: - igraph should now work well with older R versions. - Eliminate gap between vertex and edge when plotting an edge without an arrow. Fixes #1118448. - Fixed an out-of-bounds array indexing error in the DrL layout, that potentially caused crashes. - Fixed a crash in weighted betweenness calculation. - Plotting: fixed a bug that caused misplaced arrows at rectangle vertex shapes. # igraph 0.6.4 Released February 2, 2013 The version number is not a mistake, we jump to 0.6.4 from 0.6, for technical reasons. This version was actually never really released, but some R packages of this version were uplodaded to CRAN, so we include this version in this NEW file. # New features and bug fixes - Added a vertex shape API for defining new vertex shapes, and also a couple of new vertex shapes. - Added the get.data.frame() function, opposite of graph.data.frame(). - Added bipartite support to the Pajek reader and writer, closes bug #1042298. - degree.sequence.game() has a new method now: "simple_no_multiple". - Added the is.degree.sequence() and is.graphical.degree.sequence() functions. - rewire() has a new method: "loops", that can create loop edges. - Walktrap community detection now handles isolates. - layout.mds() returns a layout matrix now. - layout.mds() uses LAPACK instead of ARPACK. - Handle the '~' character in write.graph and read.graph. Bug #1066986. - Added k.regular.game(). - Use vertex names to plot if no labels are specified in the function call or as vetex attributes. Fixes issue #1085431. - power.law.fit() can now use a C implementation. - Fixed a bug in barabasi.game() when out.seq was an empty vector. - Fixed a bug that made functions with a progress bar fail if called from another package. - Fixed a bug when creating graphs from a weighted integer adjacency matrix via graph.adjacency(). Bug #1019624. - Fixed overflow issues in centralization calculations. - Fixed a minimal.st.separators() bug, some vertex sets were incorrectly reported as separators. Bug #1033045. - Fixed a bug that mishandled vertex colors in VF2 isomorphism functions. Bug #1032819. - Pajek exporter now always quotes strings, thanks to Elena Tea Russo. - Fixed a bug with handling small edge weights in shortest paths calculation in shortest.paths() (Dijkstra's algorithm.) Thanks to Martin J Reed. - Weighted transitivity uses V(graph) as 'vids' if it is NULL. - Fixed a bug when 'pie' vertices were drawn together with other vertex shapes. - Speed up printing graphs. - Speed up attribute queries and other basic operations, by avoiding copying of the graph. Bug #1043616. - Fixed a bug in the NCV setting for ARPACK functions. It cannot be bigger than the matrix size. - layout.merge()'s DLA mode has better defaults now. - Fixed a bug in layout.mds() that resulted vertices on top of each other. - Fixed a bug in layout.spring(), it was not working properly. - Fixed layout.svd(), which was completely defunct. - Fixed a bug in layout.graphopt() that caused warnings and on some platforms crashes. - Fixed community.to.membership(). Bug #1022850. - Fixed a graph.incidence() crash if it was called with a non-matrix argument. - Fixed a get.shortest.paths bug, when output was set to "both". - Motif finding functions return NA for isomorphism classes that are not motifs (i.e. not connected). Fixes bug #1050859. - Fixed get.adjacency() when attr is given, and the attribute has some complex type. Bug #1025799. - Fixed attribute name in graph.adjacency() for dense matrices. Bug #1066952. - Fixed erratic behavior of alpha.centrality(). - Fixed igraph indexing, when attr is given. Bug #1073705. - Fixed a bug when calculating the largest cliques of a directed graph. Bug #1073800. - Fixed a bug in the maximal clique search, closes #1074402. - Warn for negative weights when calculating PageRank. - Fixed dense, unweighted graph.adjacency when diag=FALSE. Closes issue #1077425. - Fixed a bug in eccentricity() and radius(), the results were often simply wrong. - Fixed a bug in get.all.shortest.paths() when some edges had zero weight. - graph.data.frame() is more careful when vertex names are numbers, to avoid their scientific notation. Fixes issue #1082221. - Better check for NAs in vertex names. Fixes issue #1087215 - Fixed a potential crash in the DrL layout generator. - Fixed a bug in the Reingold-Tilford layout when the graph is directed and mode != ALL. # igraph 0.6 Released June 11, 2012 See also the release notes at http://igraph.sf.net/relnotes-0.6.html # R: Major new features - Vertices and edges are numbered from 1 instead of 0. Note that this makes most of the old R igraph code incompatible with igraph 0.6. If you want to use your old code, please use the igraph0 package. See more at http://igraph.sf.net/relnotes-0.6.html. - The '[' and '[[' operators can now be used on igraph graphs, for '[' the graph behaves as an adjacency matrix, for '[[' is is treated as an adjacency list. It is also much simpler to manipulate the graph structure, i.e. add/remove edges and vertices, with some new operators. See more at ?graph.structure. - In all functions that take a vector or list of vertices or edges, vertex/edge names can be given instead of the numeric ids. - New package 'igraphdata', contains a number of data sets that can be used directly in igraph. - Igraph now supports loading graphs from the Nexus online data repository, see nexus.get(), nexus.info(), nexus.list() and nexus.search(). - All the community structure finding algorithm return a 'communities' object now, which has a bunch of useful operations, see ?communities for details. - Vertex and edge attributes are handled much better now. They are kept whenever possible, and can be combined via a flexible API. See ?attribute.combination. - R now prints igraph graphs to the screen in a more structured and informative way. The output of summary() was also updated accordingly. # R: Other new features - It is possible to mark vertex groups on plots, via shading. Communities and cohesive blocks are plotted using this by default. - Some igraph demos are now available, see a list via 'demo(package="igraph")'. - igraph now tries to select the optimal layout algorithm, when plotting a graph. - Added a simple console, using Tcl/Tk. It contains a text area for status messages and also a status bar. See igraph.console(). - Reimplemented igraph options support, see igraph.options() and getIgraphOpt(). - Igraph functions can now print status messages. # R: New or updated functions ## Community detection - The multi-level modularity optimization community structure detection algorithm by Blondel et al. was added, see multilevel.community(). - Distance between two community structures: compare.communities(). - Community structure via exact modularity optimization, optimal.community(). - Hierarchical random graphs and community finding, porting the code from Aaron Clauset. See hrg.game(), hrg.fit(), etc. - Added the InfoMAP community finding method, thanks to Emmanuel Navarro for the code. See infomap.community(). ## Shortest paths - Eccentricity (eccentricity()), and radius (radius()) calculations. - Shortest path calculations with get.shortest.paths() can now return the edges along the shortest paths. - get.all.shortest.paths() now supports edge weights. ## Centrality - Centralization scores for degree, closeness, betweenness and eigenvector centrality. See centralization.scores(). - Personalized Page-Rank scores, see page.rank(). - Subgraph centrality, subgraph.centrality(). - Authority (authority.score()) and hub (hub.score()) scores support edge weights now. - Support edge weights in betweenness and closeness calculations. - bonpow(), Bonacich's power centrality and alpha.centrality(), Alpha centrality calculations now use sparse matrices by default. - Eigenvector centrality calculation, evcent() now works for directed graphs. - Betweenness calculation can now use arbitrarily large integers, this is required for some lattice-like graphs to avoid overflow. ## Input/output and file formats - Support the DL file format in graph.read(). See http://www.analytictech.com/networks/dataentry.htm. - Support writing the LEDA file format in write.graph(). ## Plotting and layouts - Star layout: layout.star(). - Layout based on multidimensional scaling, layout.mds(). - New layouts layout.grid() and layout.grid.3d(). - Sugiyama layout algorithm for layered directed acyclic graphs, layout.sugiyama(). ## Graph generators - New graph generators: static.fitness.game(), static.power.law.game(). - barabasi.game() was rewritten and it supports three algorithms now, the default algorithm does not generate multiple or loop edges. The graph generation process can now start from a supplied graph. - The Watts-Strogatz graph generator, igraph_watts_strogatz() can now create graphs without loop edges. ## Others - Added the Spectral Coarse Graining algorithm, see scg(). - The cohesive.blocks() function was rewritten in C, it is much faster now. It has a nicer API, too. See demo("cohesive"). - Added generic breadth-first and depth-first search implementations with many callbacks, graph.bfs() and graph_dfs(). - Support vertex and edge coloring in the VF2 (sub)graph isomorphism functions (graph.isomorphic.vf2(), graph.count.isomorphisms.vf2(), graph.get.isomorphisms.vf2(), graph.subisomorphic.vf2(), graph.count.subisomorphisms.vf2(), graph.get.subisomorphisms.vf2()). - Assortativity coefficient, assortativity(), assortativity.nominal() and assortativity.degree(). - Vertex operators that work by vertex names: graph.intersection.by.name(), graph.union.by.name(), graph.difference.by.name(). Thanks to Magnus Torfason for contributing his code! - Function to calculate a non-induced subraph: subgraph.edges(). - More comprehensive maximum flow and minimum cut calculation, see functions graph.maxflow(), graph.mincut(), stCuts(), stMincuts(). - Check whether a directed graph is a DAG, is.dag(). - has.multiple() to decide whether a graph has multiple edges. - Added a function to calculate a diversity score for the vertices, graph.diversity(). - Graph Laplacian calculation (graph.laplacian()) supports edge weights now. - Biconnected component calculation, biconnected.components() now returns the components themselves. - bipartite.projection() calculates multiplicity of edges. - Maximum cardinality search: maximum.cardinality.search() and chordality test: is.chordal() - Convex hull computation, convex.hull(). - Contract vertices, contract.vertices(). # igraph 0.5.3 Released November 22, 2009 ## Bugs corrected in the R interface - Some small changes to make 'R CMD check' clean - Fixed a bug in graph.incidence, the 'directed' and 'mode' arguments were not handled correctly - Betweenness and edge betweenness functions work for graphs with many shortest paths now (up to the limit of long long int) - When compiling the package, the configure script fails if there is no C compiler available - igraph.from.graphNEL creates the right number of loop edges now - Fixed a bug in bipartite.projection() that caused occasional crashes on some systems # igraph 0.5.2 Released April 10, 2009 See also the release notes at http://igraph.sf.net/relnotes-0.5.2.html ## New in the R interface - Added progress bar support to beweenness() and betweenness.estimate(), layout.drl() - Speeded up betweenness estimation - Speeded up are.connected() - Johnson's shortest paths algorithm added - shortest.paths() has now an 'algorithm' argument to choose from the various implementations manually - Always quote symbolic vertex names when printing graphs or edges - Average nearest neighbor degree calculation, graph.knn() - Weighted degree (also called strength) calculation, graph.strength() - Some new functions to support bipartite graphs: graph.bipartite(), is.bipartite(), get.indicence(), graph.incidence(), bipartite.projection(), bipartite.projection.size() - Support for plotting curved edges with plot.igraph() and tkplot() - Added support for weighted graphs in alpha.centrality() - Added the label propagation community detection algorithm by Raghavan et al., label.propagation.community() - cohesive.blocks() now has a 'cutsetHeuristic' argument to choose between two cutset algorithms - Added a function to "unfold" a tree, unfold.tree() - New tkplot() arguments to change the drawing area - Added a minimal GUI, invoke it with tkigraph() - The DrL layout generator, layout.drl() has a three dimensional mode now. ## Bugs corrected in the R interface - Fixed a bug in VF2 graph isomorphism functions - Fixed a bug when a sparse adjacency matrix was requested in get.adjacency() and the graph was named - VL graph generator in degree.sequence.game() checks now that the sum of the degrees is even - Many fixes for supporting various compilers, e.g. GCC 4.4 and Sun's C compiler - Fixed memory leaks in graph.automorphisms(), Bellman-Ford shortest.paths(), independent.vertex.sets() - Fix a bug when a graph was imported from LGL and exported to NCOL format (#289596) - cohesive.blocks() creates its temporary file in the session temporary directory - write.graph() and read.graph() now give error messages when unknown arguments are given - The GraphML reader checks the name of the attributes to avoid adding a duplicate 'id' attribute - It is possible to change the 'ncv' ARPACK parameter for leading.eigenvector.community() - Fixed a bug in path.length.hist(), 'unconnected' was wrong for unconnected and undirected graphs - Better handling of attribute assingment via iterators, this is now also clarified in the manual - Better error messages for unknown vertex shapes - Make R package unload cleanly if unloadNamespace() is used - Fixed a bug in plotting square shaped vertices (#325244) - Fixed a bug in graph.adjacency() when the matrix is a sparse matrix of class "dgTMatrix" # igraph 0.5.1 Released July 14, 2008 See also the release notes at http://igraph.sf.net/relnotes-0.5.1.html ## New in the R interface - A new layout generator called DrL. - Uniform sampling of random connected undirected graphs with a given degree sequence. - Edge labels are plotted at 1/3 of the edge, this is better if the graph has mutual edges. - Initial and experimental vertex shape support in 'plot'. - New function, 'graph.adjlist' creates igraph graphs from adjacency lists. - Conversion to/from graphNEL graphs, from the 'graph' R package. - Fastgreedy community detection can utilize edge weights now, this was missing from the R interface. - The 'arrow.width' graphical parameter was added. - graph.data.frame has a new argument 'vertices'. - graph.adjacency and get.adjacency support sparse matrices, the 'Matrix' package is required to use this functionality. - graph.adjacency adds column/row names as 'name' attribute. - Weighted shortest paths using Dijkstra's or the Belmann-Ford algorithm. - Shortest path functions return 'Inf' for unreachable vertices. - New function 'is.mutual' to find mutual edges in a directed graph. - Added inverse log-weighted similarity measure (a.k.a. Adamic/Adar similarity). - preference.game and asymmetric.preference.game were rewritten, they are O(|V|+|E|) now, instead of O(|V|^2). - Edge weight support in function 'get.shortest.paths', it uses Dijkstra's algorithm. ## Bugs corrected in the R interface - A bug was corrected in write.pajek.bgraph. - Several bugs were corrected in graph.adjacency. - Pajek reader bug corrected, used to segfault if '*Vertices' was missing. - Directedness is handled correctly when writing GML files. (But note that 'correct' conflicts the standard here.) - Corrected a bug when calculating weighted, directed PageRank on an undirected graph. (Which does not make sense anyway.) - Several bugs were fixed in the Reingold-Tilford layout to avoid edge crossings. - A bug was fixed in the GraphML reader, when the value of a graph attribute was not specified. - Fixed a bug in the graph isomorphism routine for small (3-4 vertices) graphs. - Corrected the random sampling implementation (igraph_random_sample), now it always generates unique numbers. This affects the Gnm Erdos-Renyi generator, it always generates simple graphs now. - The basic igraph constructor (igraph_empty_attrs, all functions are expected to call this internally) now checks whether the number of vertices is finite. - The LGL, NCOL and Pajek graph readers handle errors properly now. - The non-symmetric ARPACK solver returns results in a consistent form now. - The fast greedy community detection routine now checks that the graph is simple. - The LGL and NCOL parsers were corrected to work with all kinds of end-of-line encodings. - Hub & authority score calculations initialize ARPACK parameters now. - Fixed a bug in the Walktrap community detection routine, when applied to unconnected graphs. - Several small memory leaks were removed, and a big one from the Spinglass community structure detection function # igraph 0.5 Released February 14, 2008 See also the release notes at http://igraph.sf.net/relnotes-0.5.html ## New in the R interface - The 'rescale', 'asp' and 'frame' graphical parameters were added - Create graphs from a formula notation (graph.formula) - Handle graph attributes properly - Calculate the actual minimum cut for undirected graphs - Adjacency lists, get.adjlist and get.adjedgelist added - Eigenvector centrality computation is much faster now - Proper R warnings, instead of writing the warning to the terminal - R checks graphical parameters now, the unknown ones are not just ignored, but an error message is given - plot.igraph has an 'add' argument now to compose plots with multiple graphs - plot.igraph supports the 'main' and 'sub' arguments - layout.norm is public now, it can normalize a layout - It is possible to supply startup positions to layout generators - Always free memory when CTRL+C/ESC is pressed, in all operating systems - plot.igraph can plot square vertices now, see the 'shape' parameter - graph.adjacency rewritten when creating weighted graphs - We use match.arg whenever possible. This means that character scalar options can be abbreviated and they are always case insensitive - VF2 graph isomorphism routines can check subgraph isomorphism now, and they are able to return matching(s) - The BLISS graph isomorphism algorithm is included in igraph now. See canonical.permutation, graph.isomorphic.bliss - We use ARPACK for eigenvalue/eigenvector calculation. This means that the following functions were rewritten: page.rank, leading.eigenvector.community.*, evcent. New functions based on ARPACK: hub.score, authority.score, arpack. - Edge weights for Fruchterman-Reingold layout (layout.fruchterman.reingold). - Line graph calculation (line.graph) - Kautz and de Bruijn graph generators (graph.kautz, graph.de.bruijn) - Support for writing graphs in DOT format - Jaccard and Dice similarity coefficients added (similarity.jaccard, similarity.dice) - Counting the multiplicity of edges (count.multiple) - The graphopt layout algorithm was added, layout.graphopt - Generation of "famous" graphs (graph.famous). - Create graphs from LCF notation (graph.cf). - Dyad census and triad cencus functions (dyad.census, triad.census) - Cheking for simple graphs (is.simple) - Create full citation networks (graph.full.citation) - Create a histogram of path lengths (path.length.hist) - Forest fire model added (forest.fire.game) - DIMACS reader can handle different file types now - Biconnected components and articulation points (biconnected.components, articulation.points) - Kleinberg's hub and authority scores (hub.score, authority.score) - as.undirected handles attributes now - Geometric random graph generator (grg.game) can return the coordinates of the vertices - Function added to convert leading eigenvector community structure result to a membership vector (community.le.to.membership) - Weighted fast greedy community detection - Weighted page rank calculation - Functions for estimating closeness, betweenness, edge betweenness by introducing a cutoff for path lengths (closeness.estimate, betweenness.estimate, edge.betweenness.estimate) - Weighted modularity calculation - Function for permuting vertices (permute.vertices) - Betweenness and closeness calculations are speeded up - read.graph can handle all possible line terminators now (\r, \n, \r\n, \n\r) - Error handling was rewritten for walktrap community detection, the calculation can be interrupted now - The maxflow/mincut functions allow to supply NULL pointer for edge capacities, implying unit capacities for all edges ## Bugs corrected in the R interface - Fixed a bug in cohesive.blocks, cohesive blocks were sometimes not calculated correctly # igraph 0.4.5 Released January 1, 2008 New: - Cohesive block finding in the R interface, thanks to Peter McMahan for contributing his code. See James Moody and Douglas R. White, 2003, in Structural Cohesion and Embeddedness: A Hierarchical Conception of Social Groups American Sociological Review 68(1):1-25 - Biconnected components and articulation points. - R interface: better printing of attributes. - R interface: graph attributes can be used via '$'. Bug fixed: - Erdos-Renyi random graph generators rewritten. # igraph 0.4.4 Released October 3, 2007 This release should work seemlessly with the new R 2.6.0 version. Some other bugs were also fixed: - A bug was fixed in the Erdos-Renyi graph generator, which sometimes added an extra vertex. # igraph 0.4.3 Released August 13, 2007 The next one in the sequence of bugfix releases. Thanks to many people sending bug reports. Here are the changes: - Some memory leaks removed when using attributes from R or Python. - GraphML parser: entities and character data in multiple chunks are now handled correctly. - A bug corrected in edge betweenness community structure detection, it failed if called many times from the same program/session. - Edge betweeness community structure: handle unconnected graphs properly. - Fixed bug related to fast greedy community detection in unconnected graphs. - Use a different kind of parser (Push) for reading GraphML files. This is almost invisible for users but fixed a nondeterministic bug when reading in GraphML files. - R interface: plot now handles properly if called with a vector as the edge.width argument for directed graphs. - R interface: bug (typo) corrected for walktrap.community and weighted graphs. # igraph 0.4.2 Released June 7, 2007 This is another bugfix release, as there was a serious bug in the R package of the previous version: it could not read and write graphs to files in any format under MS Windows. Some other bits added: - circular Reingold-Tilford layout generator for trees - corrected a bug, Pajek files are written properly under MS Windows now. - arrow.size graphical edge parameter added in the R interface. # igraph 0.4.1 Released May 23, 2007 This is a minor release, it corrects a number of bugs, mostly in the R package. # igraph 0.4 Released May 21, 2007 The major new additions in this release is a bunch of community detection algorithms and support for the GML file format. Here is the complete list of changes: ## New in the R interface - as the internal representation changed, graphs stored with 'save' with an older igraph version cannot be read back with the new version reliably. - neighbors returns ordered lists - is.loop and is.multiple were added - topological sorting - VF2 isomorphism algorithm - support for reading graphs from the Graph Database for isomorphism - graph.mincut can calculate the actual minimum cut - girth calculation added, thanks to Keith Briggs - support for reading and writing GML files - Walktrap community detection algorithm added, thanks to Matthieu Latapy and Pascal Pons - edge betweenness based community detection algorithm added - fast greedy algorithm for community detection by Clauset et al. added thanks to Aaron Clauset for sharing his code - leading eigenvector community detection algorithm by Mark Newman added - functions for creating dendrograms from the output of the community detection algorithms added - community.membership supporting function added, creates a membership vector from a community structure merge tree - modularity calculation added - graphics parameter handling is completely rewritten, uniform handling of colors and fonts, make sure you read ?igraph.plotting - new plotting parameter for edges: arrow.mode - a bug corrected when playing a nonlinear barabasi.game - better looking plotting in 3d using rglplot: edges are 3d too - rglplot layout is allowed to be two dimensional now - rglplot suspends updates while drawing, this makes it faster - loop edges are correctly plotted by all three plotting functions - better printing of attributes when printing graphs - summary of a graph prints attribute names - is.igraph rewritten to make it possible to inherit from the 'igraph' class - somewhat better looking progress meter for functions which support it ## Others - many functions benefit from the new internal representation and are faster now: transitivity, reciprocity, graph operator functions like intersection and union, etc. ## Bugs corrected - corrected a bug when reading Pajek files: directed graphs were read as undirected # igraph 0.3.2 Released Dec 19, 2006 This is a new major release, it contains many new things: ## Changes in the R interface - bonpow function ported from SNA to calculate Bonacich power centrality - get.adjacency supports attributes now, this means that it sets the colnames and rownames attributes and can return attribute values in the matrix instead of 0/1 - grg.game, geometric random graphs - graph.density, graph density calculation - edge and vertex attributes can be added easily now when added new edges with add.edges or new vertices with add.vertices - graph.data.frame creates graph from data frames, this can be used to create graphs with edge attributes easily - plot.igraph and tkplot can plot self-loop edges now - graph.edgelist to create a graph from an edge list, can also handle edge lists with symbolic names - get.edgelist has now a 'names' argument and can return symbolic vertex names instead of vertex ids, by default id uses the 'name' vertex attribute is returned - printing graphs on screen also prints symbolic symbolic names (the 'name' attribute if present) - maximum flow and minimum cut functions: graph.maxflow, graph.mincut - vertex and edge connectivity: edge.connectivity, vertex.connectivity - edge and vertex disjoint paths: edge.disjoint.paths, vertex.disjoint.paths - White's cohesion and adhesion measure: graph.adhesion, graph.cohesion - dimacs file format added - as.directed handles attributes now - constraint corrected, it handles weighted graphs as well now - weighted attribute to graph.adjacency - spinglass-based community structure detection, the Joerg Reichardt -- Stefan Bornholdt algorithm added: spinglass.community - graph.extended.chordal.ring, extended chordal ring generation - no.clusters calculates the number of clusters without calculating the clusters themselves - minimum spanning tree functions updated to keep attributes - transitivity can calculate local transitivity as well - neighborhood related functions added: neighborhood, neighborhood.size, graph.neighborhood - new graph generators based on vertex types: preference.game and asymmetric.preference.game ## Bugs corrected - attribute handling bug when deleting edges corrected - GraphML escaping and NaN handling corrected - bug corrected to make it possible compile the R package without the libxml2 library - a bug in Erdos-Renyi graph generation corrected: it had problems with generating large directed graphs - bug in constraint calculation corrected, it works well now - fixed memory leaks in the GraphML reader - error handling bug corrected in the GraphML reader - bug corrected in R version of graph.laplacian when normalized Laplacian is requested - memory leak corrected in get.all.shortest.paths in the R package # igraph 0.2.1 Released Aug 23, 2006 This is a bug-fix release. Bugs fixed: - reciprocity corrected to avoid segfaults - some docs updates - various R package updates to make it conform to the CRAN rules # igraph 0.2 Released Aug 18, 2006 Release time at last! There are many new things in igraph 0.2, the most important ones: - reading writing Pajek and GraphML formats with attributes (not all Pajek and GraphML files are supported, see documentation for details) - the RANDEDU fast motif search algorithm is implemented - many new graph generators, both games and regular graphs - many new structural properties: transitivity, reciprocity, etc. - graph operators: union, intersection, difference, structural holes, etc. - conversion between directed and undirected graphs - new layout algorithms for trees and large graphs, 3D layouts and many more. New things specifically in the R package: - support for CTRL+C - new functions: Graph Laplacian, Burt's constraint, etc. - vertex/edge sequences totally rewritten, smart indexing (see manual) - new R manual and tutorial: `Network Analysis with igraph', still under development but useful - very basic 3D plotting using OpenGL Although this release was somewhat tested on Linux, MS Windows, Mac OSX, Solaris 8 and FreeBSD, no heavy testing was done, so it might contain bugs, and we kindly ask you to send bug reports to make igraph better. # igraph 0.1 Released Jan 30, 2006 After about a year of development this is the first "official" release of the igraph library. This release should be considered as beta software, but it should be useful in general. Please send your questions and comments. igraph/configure0000755000175100001440000052214213562737552013476 0ustar hornikusers#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for igraph 1.2.4. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org and $0: csardi.gabor@gmail.com about your system, including any $0: error possibly output before this message. Then install $0: a modern shell, or manually run the script under such a $0: shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='igraph' PACKAGE_TARNAME='igraph' PACKAGE_VERSION='1.2.4' PACKAGE_STRING='igraph 1.2.4' PACKAGE_BUGREPORT='csardi.gabor@gmail.com' PACKAGE_URL='' ac_unique_file="src/rinterface.c" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS HAVE_GLPK GLPK_LIBS GMP_LIBS HAVE_GMP HAVE_LIBXML XML2_CFLAGS XML2_LIBS XML2CONFIG EGREP GREP CPP CXXCPP ac_ct_CXX CXXFLAGS CXX ac_ct_FC FCFLAGS FC OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_graphml enable_gmp enable_glpk ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS FC FCFLAGS CXX CXXFLAGS CCC CXXCPP CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures igraph 1.2.4 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/igraph] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of igraph 1.2.4:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-graphml Disable support for GraphML format --disable-gmp Compile without the GMP library --enable-glpk Enable support for GLPK Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory FC Fortran compiler command FCFLAGS Fortran compiler flags CXX C++ compiler command CXXFLAGS C++ compiler flags CXXCPP C++ preprocessor CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF igraph configure 1.2.4 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_fc_try_compile LINENO # --------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_fc_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_fc_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_fc_try_compile # ac_fn_cxx_try_compile LINENO # ---------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile # ac_fn_cxx_try_cpp LINENO # ------------------------ # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES # --------------------------------------------- # Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR # accordingly. ac_fn_c_check_decl () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack as_decl_name=`echo $2|sed 's/ *(.*//'` as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 $as_echo_n "checking whether $as_decl_name is declared... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { #ifndef $as_decl_name #ifdef __cplusplus (void) $as_decl_use; #else (void) $as_decl_name; #endif #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_decl # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ------------------------------------- ## ## Report this to csardi.gabor@gmail.com ## ## ------------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES # ---------------------------------------------------- # Tries to find if the field MEMBER exists in type AGGR, after including # INCLUDES, setting cache variable VAR accordingly. ac_fn_c_check_member () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 $as_echo_n "checking for $2.$3... " >&6; } if eval \${$4+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $5 int main () { static $2 ac_aggr; if (sizeof ac_aggr.$3) return 0; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$4=yes" else eval "$4=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$4 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_member # ac_fn_cxx_try_link LINENO # ------------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_link # ac_fn_cxx_check_header_mongrel LINENO HEADER VAR INCLUDES # --------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_cxx_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_cxx_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ------------------------------------- ## ## Report this to csardi.gabor@gmail.com ## ## ------------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_header_mongrel cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by igraph $as_me 1.2.4, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers src/config.h" : ${R_HOME=`R RHOME`} if test -z "${R_HOME}"; then echo "could not determine R_HOME" exit 1 fi CC=`"${R_HOME}/bin/R" CMD config CC` CXX=`"${R_HOME}/bin/R" CMD config CXX` FC=`"${R_HOME}/bin/R" CMD config FC` CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS` CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS` CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS` FCFLAGS=`"${R_HOME}/bin/R" CMD config FCFLAGS` FLIBS=`"${R_HOME}/bin/R" CMD config FLIBS` ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Fortran compiler, we need to check if it is the GNU compiler ac_ext=${ac_fc_srcext-f} ac_compile='$FC -c $FCFLAGS $ac_fcflags_srcext conftest.$ac_ext >&5' ac_link='$FC -o conftest$ac_exeext $FCFLAGS $LDFLAGS $ac_fcflags_srcext conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_fc_compiler_gnu if test -n "$ac_tool_prefix"; then for ac_prog in gfortran g95 xlf95 f95 fort ifort ifc efc pgfortran pgf95 lf95 ftn nagfor xlf90 f90 pgf90 pghpf epcf90 g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_FC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$FC"; then ac_cv_prog_FC="$FC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_FC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi FC=$ac_cv_prog_FC if test -n "$FC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $FC" >&5 $as_echo "$FC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$FC" && break done fi if test -z "$FC"; then ac_ct_FC=$FC for ac_prog in gfortran g95 xlf95 f95 fort ifort ifc efc pgfortran pgf95 lf95 ftn nagfor xlf90 f90 pgf90 pghpf epcf90 g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_FC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_FC"; then ac_cv_prog_ac_ct_FC="$ac_ct_FC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_FC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_FC=$ac_cv_prog_ac_ct_FC if test -n "$ac_ct_FC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_FC" >&5 $as_echo "$ac_ct_FC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_FC" && break done if test "x$ac_ct_FC" = x; then FC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac FC=$ac_ct_FC fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for Fortran compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done rm -f a.out # If we don't use `.F' as extension, the preprocessor is not run on the # input file. (Note that this only needs to work for GNU compilers.) ac_save_ext=$ac_ext ac_ext=F { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU Fortran compiler" >&5 $as_echo_n "checking whether we are using the GNU Fortran compiler... " >&6; } if ${ac_cv_fc_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat > conftest.$ac_ext <<_ACEOF program main #ifndef __GNUC__ choke me #endif end _ACEOF if ac_fn_fc_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_fc_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_fc_compiler_gnu" >&5 $as_echo "$ac_cv_fc_compiler_gnu" >&6; } ac_ext=$ac_save_ext ac_test_FCFLAGS=${FCFLAGS+set} ac_save_FCFLAGS=$FCFLAGS FCFLAGS= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $FC accepts -g" >&5 $as_echo_n "checking whether $FC accepts -g... " >&6; } if ${ac_cv_prog_fc_g+:} false; then : $as_echo_n "(cached) " >&6 else FCFLAGS=-g cat > conftest.$ac_ext <<_ACEOF program main end _ACEOF if ac_fn_fc_try_compile "$LINENO"; then : ac_cv_prog_fc_g=yes else ac_cv_prog_fc_g=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_fc_g" >&5 $as_echo "$ac_cv_prog_fc_g" >&6; } if test "$ac_test_FCFLAGS" = set; then FCFLAGS=$ac_save_FCFLAGS elif test $ac_cv_prog_fc_g = yes; then if test "x$ac_cv_fc_compiler_gnu" = xyes; then FCFLAGS="-g -O2" else FCFLAGS="-g" fi else if test "x$ac_cv_fc_compiler_gnu" = xyes; then FCFLAGS="-O2" else FCFLAGS= fi fi if test $ac_compiler_gnu = yes; then GFC=yes else GFC= fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "x$ac_cv_fc_compiler_gnu" == xyes; then $as_echo "#define HAVE_GFORTRAN 1" >>confdefs.h fi # Tricky check for C++ compiler, because Autoconf has a weird bug: # http://lists.gnu.org/archive/html/autoconf/2006-03/msg00067.html ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if ${ac_cv_cxx_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if ${ac_cv_prog_cxx_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include const char hw[] = "Hello, World\n"; int main () { std::cout << hw; ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then if ${ac_cv_prog_CXXCPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded for CXXCPP in "$CXX -E" "/lib/cpp" do ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CXXCPP=$CXXCPP fi CXXCPP=$ac_cv_prog_CXXCPP else ac_cv_prog_CXXCPP=$CXXCPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 $as_echo "$CXXCPP" >&6; } ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cxx_error=no else as_fn_error $? "no C++ compiler found or it cannot create executables" "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu LIBS_SAVE=$LIBS LIBS="$LIBS -lm" for ac_func in rintf finite expm1 rint log2 logbl snprintf log1p round fmin stpcpy do : as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" if eval test \"x\$"$as_ac_var"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_c_check_decl "$LINENO" "stpcpy" "ac_cv_have_decl_stpcpy" "$ac_includes_default" if test "x$ac_cv_have_decl_stpcpy" = xyes; then : $as_echo "#define HAVE_STPCPY_SIGNATURE 1" >>confdefs.h fi LIBS=$LIBS_SAVE ac_fn_c_check_header_mongrel "$LINENO" "sys/times.h" "ac_cv_header_sys_times_h" "$ac_includes_default" if test "x$ac_cv_header_sys_times_h" = xyes; then : $as_echo "#define HAVE_TIMES_H 1" >>confdefs.h fi for ac_header in \ net/if.h \ netinet/in.h \ net/if_dl.h \ sys/sockio.h \ sys/un.h \ sys/socket.h \ sys/ioctl.h \ sys/time.h \ sys/file.h \ do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done ac_fn_c_check_member "$LINENO" "struct sockaddr" "sa_len" "ac_cv_member_struct_sockaddr_sa_len" "#include #include " if test "x$ac_cv_member_struct_sockaddr_sa_len" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SA_LEN 1 _ACEOF fi graphml_support=yes # Check whether --enable-graphml was given. if test "${enable_graphml+set}" = set; then : enableval=$enable_graphml; graphml_support=$enableval else graphml_support=yes fi HAVE_LIBXML=0 if test $graphml_support = yes; then # Extract the first word of "xml2-config", so it can be a program name with args. set dummy xml2-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_XML2CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $XML2CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_XML2CONFIG="$XML2CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_XML2CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS test -z "$ac_cv_path_XML2CONFIG" && ac_cv_path_XML2CONFIG="none" ;; esac fi XML2CONFIG=$ac_cv_path_XML2CONFIG if test -n "$XML2CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $XML2CONFIG" >&5 $as_echo "$XML2CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "$XML2CONFIG" = "none"; then graphml_support=no else XML2_LIBS=`$XML2CONFIG --libs` XML2_CFLAGS=`$XML2CONFIG --cflags` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for xmlSAXUserParseFile in -lxml2" >&5 $as_echo_n "checking for xmlSAXUserParseFile in -lxml2... " >&6; } if ${ac_cv_lib_xml2_xmlSAXUserParseFile+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lxml2 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char xmlSAXUserParseFile (); int main () { return xmlSAXUserParseFile (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_xml2_xmlSAXUserParseFile=yes else ac_cv_lib_xml2_xmlSAXUserParseFile=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_xml2_xmlSAXUserParseFile" >&5 $as_echo "$ac_cv_lib_xml2_xmlSAXUserParseFile" >&6; } if test "x$ac_cv_lib_xml2_xmlSAXUserParseFile" = xyes; then : OLDCFLAGS=${CFLAGS} OLDCPPFLAGS=${CPPFLAGS} CFLAGS=${XML2_CFLAGS} CPPFLAGS=${XML2_CFLAGS} ac_fn_c_check_header_mongrel "$LINENO" "libxml/parser.h" "ac_cv_header_libxml_parser_h" "$ac_includes_default" if test "x$ac_cv_header_libxml_parser_h" = xyes; then : HAVE_LIBXML=1 $as_echo "#define HAVE_LIBXML 1" >>confdefs.h CFLAGS="${OLDCFLAGS} ${XML2_CFLAGS}" CPPFLAGS="${OLDCFLAGS} ${XML2_CFLAGS}" else graphml_support=no CFLAGS=${OLDCFLAGS} CPPFLAGS=${OLDCPPFLAGS} fi else graphml_support=no fi fi fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu HAVE_GMP=0 GMP_LIBS="" gmp_support=no # Check whether --enable-gmp was given. if test "${enable_gmp+set}" = set; then : enableval=$enable_gmp; fi if test "x$enable_gmp" != "xno"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __gmpz_add in -lgmp" >&5 $as_echo_n "checking for __gmpz_add in -lgmp... " >&6; } if ${ac_cv_lib_gmp___gmpz_add+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lgmp $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char __gmpz_add (); int main () { return __gmpz_add (); ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : ac_cv_lib_gmp___gmpz_add=yes else ac_cv_lib_gmp___gmpz_add=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gmp___gmpz_add" >&5 $as_echo "$ac_cv_lib_gmp___gmpz_add" >&6; } if test "x$ac_cv_lib_gmp___gmpz_add" = xyes; then : ac_fn_cxx_check_header_mongrel "$LINENO" "gmp.h" "ac_cv_header_gmp_h" "$ac_includes_default" if test "x$ac_cv_header_gmp_h" = xyes; then : HAVE_GMP=1 $as_echo "#define HAVE_GMP 1" >>confdefs.h gmp_support=yes GMP_LIBS="-lgmp" fi fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu glpk_support=no # Check whether --enable-glpk was given. if test "${enable_glpk+set}" = set; then : enableval=$enable_glpk; glpk_support=$enableval else glpk_support=yes fi HAVE_GLPK=0 if test $glpk_support = yes; then glpk_support=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for glp_read_mps in -lglpk" >&5 $as_echo_n "checking for glp_read_mps in -lglpk... " >&6; } if ${ac_cv_lib_glpk_glp_read_mps+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lglpk $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char glp_read_mps (); int main () { return glp_read_mps (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_glpk_glp_read_mps=yes else ac_cv_lib_glpk_glp_read_mps=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_glpk_glp_read_mps" >&5 $as_echo "$ac_cv_lib_glpk_glp_read_mps" >&6; } if test "x$ac_cv_lib_glpk_glp_read_mps" = xyes; then : ac_fn_c_check_header_mongrel "$LINENO" "glpk.h" "ac_cv_header_glpk_h" "$ac_includes_default" if test "x$ac_cv_header_glpk_h" = xyes; then : cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #if GLP_MAJOR_VERSION > 4 || (GLP_MAJOR_VERSION == 4 && GLP_MINOR_VERSION >= 38) yes #endif _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "yes" >/dev/null 2>&1; then : $as_echo "#define HAVE_GLPK 1" >>confdefs.h HAVE_GLPK=1 glpk_support=yes GLPK_LIBS="-lglpk" fi rm -f conftest* fi fi fi $as_echo "#define IGRAPH_THREAD_LOCAL /**/" >>confdefs.h ac_config_files="$ac_config_files src/Makevars.tmp:src/Makevars.in" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by igraph $as_me 1.2.4, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ igraph config.status 1.2.4 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;; "src/Makevars.tmp") CONFIG_FILES="$CONFIG_FILES src/Makevars.tmp:src/Makevars.in" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi ;; esac case $ac_file$ac_mode in "src/Makevars.tmp":F) if test -f src/Makevars && cmp -s src/Makevars.tmp src/Makevars; then { $as_echo "$as_me:${as_lineno-$LINENO}: creating src/Makevars" >&5 $as_echo "$as_me: creating src/Makevars" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: src/Makevars is unchanged" >&5 $as_echo "$as_me: src/Makevars is unchanged" >&6;} rm src/Makevars.tmp else { $as_echo "$as_me:${as_lineno-$LINENO}: creating src/Makevars" >&5 $as_echo "$as_me: creating src/Makevars" >&6;} mv src/Makevars.tmp src/Makevars fi ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi